Global Loot Modifiers

This commit is contained in:
LexManos committed 2023-09-20 15:24:46 -07:00
1 parent dd139115ed
commit af6e848227
63 files changed
+1058 -1502

No files matched your search

@@ -1,94 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
import com.google.gson.JsonElement;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import org.jetbrains.annotations.Nullable;
import java.util.stream.Stream;
/**
* Extension of {@link Ingredient} which makes most methods custom ingredients need to implement abstract, and removes the static constructors
* Mods are encouraged to extend this class for their custom ingredients
* /
public abstract class AbstractIngredient extends Ingredient {
/** Empty constructor, for the sake of dynamic ingredients * /
protected AbstractIngredient() {
super(Stream.of());
}
/** Value constructor, for ingredients that have some vanilla representation * /
protected AbstractIngredient(Stream<? extends Value> values) {
super(values);
}
@Override
public abstract boolean isSimple();
@Override
public abstract IIngredientSerializer<? extends Ingredient> getSerializer();
@Override
public abstract JsonElement toJson(boolean allowEmpty);
/* Hide vanilla ingredient static constructors to reduce errors with constructing custom ingredients * /
/** @deprecated use {@link Ingredient#fromValues(Stream)} * /
@Deprecated
public static Ingredient fromValues(Stream<? extends Ingredient.Value> values) {
throw new UnsupportedOperationException("Use Ingredient.fromValues()");
}
/** @deprecated use {@link Ingredient#of()} * /
@Deprecated
public static Ingredient of() {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(ItemLike...)} (Stream)} * /
@Deprecated
public static Ingredient of(ItemLike... items) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(ItemStack...)} (Stream)} * /
@Deprecated
public static Ingredient of(ItemStack... stacks) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(Stream)} (Stream)} * /
@Deprecated
public static Ingredient of(Stream<ItemStack> stacks) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#of(TagKey)} (Stream)} * /
@Deprecated
public static Ingredient of(TagKey<Item> tag) {
throw new UnsupportedOperationException("Use Ingredient.of()");
}
/** @deprecated use {@link Ingredient#fromNetwork(FriendlyByteBuf)} * /
@Deprecated
public static Ingredient fromNetwork(FriendlyByteBuf buffer) {
throw new UnsupportedOperationException("Use Ingredient.fromNetwork()");
}
/** @deprecated use {@link Ingredient#fromJson(JsonElement)} (Stream)} * /
@Deprecated
public static Ingredient fromJson(@Nullable JsonElement json) {
throw new UnsupportedOperationException("Use Ingredient.fromJson()");
}
}
*/
@@ -27,9 +27,9 @@ import net.minecraft.network.FriendlyByteBuf;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/** Ingredient that matches if any of the child ingredients match * /
public class CompoundIngredient extends AbstractIngredient
{
/** Ingredient that matches if any of the child ingredients match */
/*
public class CompoundIngredient extends Ingredient {
private List<Ingredient> children;
private ItemStack[] stacks;
private IntList itemIds;
@@ -41,7 +41,8 @@ public class CompoundIngredient extends AbstractIngredient
this.isSimple = children.stream().allMatch(Ingredient::isSimple);
}
/** Creates a compound ingredient from the given list of ingredients * /
/** Creates a compound ingredient from the given list of ingredients */
/*
public static Ingredient of(Ingredient... children)
{
// if 0 or 1 ingredient, can save effort
@@ -68,10 +69,8 @@ public class CompoundIngredient extends AbstractIngredient
@Override
@NotNull
public ItemStack[] getItems()
{
if (stacks == null)
{
public ItemStack[] getItems() {
if (stacks == null) {
List<ItemStack> tmp = Lists.newArrayList();
for (Ingredient child : children)
Collections.addAll(tmp, child.getItems());
@@ -83,15 +82,11 @@ public class CompoundIngredient extends AbstractIngredient
@Override
@NotNull
public IntList getStackingIds()
{
public IntList getStackingIds() {
boolean childrenNeedInvalidation = false;
for (Ingredient child : children)
{
childrenNeedInvalidation |= child.checkInvalidation();
}
if (childrenNeedInvalidation || this.itemIds == null || checkInvalidation())
{
if (childrenNeedInvalidation || this.itemIds == null || checkInvalidation()) {
this.markValid();
this.itemIds = new IntArrayList();
for (Ingredient child : children)
@@ -103,8 +98,7 @@ public class CompoundIngredient extends AbstractIngredient
}
@Override
public boolean test(@Nullable ItemStack target)
{
public boolean test(@Nullable ItemStack target) {
if (target == null)
return false;
@@ -112,74 +106,18 @@ public class CompoundIngredient extends AbstractIngredient
}
@Override
protected void invalidate()
{
this.itemIds = null;
this.stacks = null;
}
@Override
public boolean isSimple()
{
public boolean isSimple() {
return isSimple;
}
@Override
public IIngredientSerializer<? extends Ingredient> getSerializer()
{
return Serializer.INSTANCE;
}
@NotNull
public Collection<Ingredient> getChildren()
{
public Collection<Ingredient> getChildren() {
return this.children;
}
@Override
public JsonElement toJson()
{
if (this.children.size() == 1)
{
return this.children.get(0).toJson();
}
else
{
JsonArray json = new JsonArray();
this.children.stream().forEach(e -> json.add(e.toJson()));
return json;
}
}
@Override
public boolean isEmpty()
{
public boolean isEmpty() {
return children.stream().allMatch(Ingredient::isEmpty);
}
public static class Serializer implements IIngredientSerializer<CompoundIngredient>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public CompoundIngredient parse(FriendlyByteBuf buffer)
{
return new CompoundIngredient(Stream.generate(() -> Ingredient.fromNetwork(buffer)).limit(buffer.readVarInt()).collect(Collectors.toList()));
}
@Override
public CompoundIngredient parse(JsonObject json)
{
throw new JsonSyntaxException("CompoundIngredient should not be directly referenced in json, just use an array of ingredients.");
}
@Override
public void write(FriendlyByteBuf buffer, CompoundIngredient ingredient)
{
buffer.writeVarInt(ingredient.children.size());
ingredient.children.forEach(c -> c.toNetwork(buffer));
}
}
}
*/
@@ -16,12 +16,12 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.serialization.Codec;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraftforge.common.crafting.conditions.ICondition;
import net.minecraftforge.common.crafting.conditions.IConditionSerializer;
import net.minecraft.nbt.TagParser;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.GsonHelper;
@@ -173,13 +173,11 @@ public class CraftingHelper {
}
// CONDITIONS
private static final Map<ResourceLocation, IConditionSerializer<?>> conditions = new HashMap<>();
public static IConditionSerializer<?> register(IConditionSerializer<?> serializer) {
ResourceLocation key = serializer.getID();
private static final Map<ResourceLocation, Codec<? extends ICondition>> conditions = new HashMap<>();
public static void register(ResourceLocation key, Codec<? extends ICondition> codec) {
if (conditions.containsKey(key))
throw new IllegalStateException("Duplicate recipe condition serializer: " + key);
conditions.put(key, serializer);
return serializer;
conditions.put(key, codec);
}
public static boolean processConditions(JsonObject json, String memberName, ICondition.IContext context) {
@@ -187,38 +185,16 @@ public class CraftingHelper {
}
public static boolean processConditions(JsonArray conditions, ICondition.IContext context) {
for (int x = 0; x < conditions.size(); x++)
{
for (int x = 0; x < conditions.size(); x++) {
if (!conditions.get(x).isJsonObject())
throw new JsonSyntaxException("Conditions must be an array of JsonObjects");
JsonObject json = conditions.get(x).getAsJsonObject();
/*
if (!CraftingHelper.getCondition(json).test(context))
return false;
*/
}
return true;
}
public static ICondition getCondition(JsonObject json) {
ResourceLocation type = new ResourceLocation(GsonHelper.getAsString(json, "type"));
IConditionSerializer<?> serializer = conditions.get(type);
if (serializer == null)
throw new JsonSyntaxException("Unknown condition type: " + type.toString());
return serializer.read(json);
}
public static <T extends ICondition> JsonObject serialize(T condition) {
@SuppressWarnings("unchecked")
IConditionSerializer<T> serializer = (IConditionSerializer<T>)conditions.get(condition.getID());
if (serializer == null)
throw new JsonSyntaxException("Unknown condition type: " + condition.getID().toString());
return serializer.getJson(condition);
}
public static JsonArray serialize(ICondition... conditions) {
JsonArray arr = new JsonArray();
for(ICondition iCond : conditions)
arr.add(serialize(iCond));
return arr;
}
}
@@ -1,22 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
// TODO: Ingredient Serializers
/*
import com.google.gson.JsonObject;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public interface IIngredientSerializer<T extends Ingredient> {
T parse(FriendlyByteBuf buffer);
T parse(JsonObject json);
void write(FriendlyByteBuf buffer, T ingredient);
}
*/
@@ -1,57 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
import java.util.Collection;
import java.util.Collections;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient.Value;
import net.minecraftforge.registries.ForgeRegistries;
public class MultiItemValue implements Value
{
private Collection<ItemStack> items;
public MultiItemValue(Collection<ItemStack> items)
{
this.items = Collections.unmodifiableCollection(items);
}
@Override
public Collection<ItemStack> getItems()
{
return items;
}
@Override
public JsonObject serialize()
{
if (items.size() == 1)
return toJson(items.iterator().next());
JsonObject ret = new JsonObject();
JsonArray array = new JsonArray();
items.forEach(stack -> array.add(toJson(stack)));
ret.add("items", array);
return ret;
}
private JsonObject toJson(ItemStack stack)
{
JsonObject ret = new JsonObject();
ret.addProperty("item", ForgeRegistries.ITEMS.getKey(stack.getItem()).toString());
if (stack.getCount() != 1)
ret.addProperty("count", stack.getCount());
if (stack.getTag() != null)
ret.addProperty("nbt", stack.getTag().toString()); //TODO: Better serialization?
return ret;
}
}
*/
@@ -4,37 +4,35 @@
*/
package net.minecraftforge.common.crafting;
/*
import java.util.stream.Stream;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.stream.Stream;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.Nullable;
/** Ingredient that matches the given stack, performing an exact NBT match. Use {@link PartialNBTIngredient} if you need partial match. * /
public class StrictNBTIngredient extends AbstractIngredient
{
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
/** Ingredient that matches the given stack, performing an exact NBT match. Use {@link PartialNBTIngredient} if you need partial match. */
public class StrictNBTIngredient extends Ingredient {
public static final Codec<StrictNBTIngredient> CODEC = RecordCodecBuilder.create(b -> b.group(
ItemStack.CODEC.fieldOf("stack").forGetter(i -> i.stack)
).apply(b, StrictNBTIngredient::new));
private final ItemStack stack;
protected StrictNBTIngredient(ItemStack stack)
{
protected StrictNBTIngredient(ItemStack stack) {
super(Stream.of(new Ingredient.ItemValue(stack)));
this.stack = stack;
}
/** Creates a new ingredient matching the given stack and tag * /
public static StrictNBTIngredient of(ItemStack stack)
{
/** Creates a new ingredient matching the given stack and tag */
public static StrictNBTIngredient of(ItemStack stack) {
return new StrictNBTIngredient(stack);
}
@Override
public boolean test(@Nullable ItemStack input)
{
public boolean test(@Nullable ItemStack input) {
if (input == null)
return false;
//Can't use areItemStacksEqualUsingNBTShareTag because it compares stack size as well
@@ -42,47 +40,7 @@ public class StrictNBTIngredient extends AbstractIngredient
}
@Override
public boolean isSimple()
{
public boolean isSimple() {
return false;
}
@Override
public IIngredientSerializer<? extends Ingredient> getSerializer()
{
return Serializer.INSTANCE;
}
@Override
public JsonElement toJson()
{
JsonObject json = new JsonObject();
json.addProperty("type", CraftingHelper.getID(Serializer.INSTANCE).toString());
json.addProperty("item", ForgeRegistries.ITEMS.getKey(stack.getItem()).toString());
json.addProperty("count", stack.getCount());
if (stack.hasTag())
json.addProperty("nbt", stack.getTag().toString());
return json;
}
public static class Serializer implements IIngredientSerializer<StrictNBTIngredient>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public StrictNBTIngredient parse(FriendlyByteBuf buffer) {
return new StrictNBTIngredient(buffer.readItem());
}
@Override
public StrictNBTIngredient parse(JsonObject json) {
return new StrictNBTIngredient(CraftingHelper.getItemStack(json, true));
}
@Override
public void write(FriendlyByteBuf buffer, StrictNBTIngredient ingredient) {
buffer.writeItem(ingredient.stack);
}
}
}
*/
@@ -1,39 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting;
/*
import java.util.stream.Stream;
import com.google.gson.JsonObject;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.network.FriendlyByteBuf;
public class VanillaIngredientSerializer implements IIngredientSerializer<Ingredient>
{
public static final VanillaIngredientSerializer INSTANCE = new VanillaIngredientSerializer();
public Ingredient parse(FriendlyByteBuf buffer)
{
return Ingredient.fromValues(Stream.generate(() -> new Ingredient.ItemValue(buffer.readItem())).limit(buffer.readVarInt()));
}
public Ingredient parse(JsonObject json)
{
return Ingredient.fromValues(Stream.of(Ingredient.valueFromJson(json)));
}
public void write(FriendlyByteBuf buffer, Ingredient ingredient)
{
ItemStack[] items = ingredient.getItems();
buffer.writeVarInt(items.length);
for (ItemStack stack : items)
buffer.writeItem(stack);
}
}
*/
@@ -5,49 +5,20 @@
package net.minecraftforge.common.crafting.conditions;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
public class AndCondition implements ICondition
{
private static final ResourceLocation NAME = new ResourceLocation("forge", "and");
private final ICondition[] children;
public AndCondition(ICondition... values)
{
if (values == null || values.length == 0)
throw new IllegalArgumentException("Values must not be empty");
for (ICondition child : values)
{
if (child == null)
throw new IllegalArgumentException("Value must not be null");
}
this.children = values;
}
public record AndCondition(List<ICondition> children) implements ICondition {
public static final Codec<AndCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
ICondition.CODEC.listOf().fieldOf("values").forGetter(AndCondition::children)
).apply(b, AndCondition::new));
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext context)
{
for (ICondition child : children)
{
public boolean test(IContext context) {
for (ICondition child : children) {
if (!child.test(context))
return false;
}
@@ -55,41 +26,12 @@ public class AndCondition implements ICondition
}
@Override
public String toString()
{
public String toString() {
return Joiner.on(" && ").join(children);
}
public static class Serializer implements IConditionSerializer<AndCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, AndCondition value)
{
JsonArray values = new JsonArray();
for (ICondition child : value.children)
values.add(CraftingHelper.serialize(child));
json.add("values", values);
}
@Override
public AndCondition read(JsonObject json)
{
List<ICondition> children = new ArrayList<>();
for (JsonElement j : GsonHelper.getAsJsonArray(json, "values"))
{
if (!j.isJsonObject())
throw new JsonSyntaxException("And condition values must be an array of JsonObjects");
children.add(CraftingHelper.getCondition(j.getAsJsonObject()));
}
return new AndCondition(children.toArray(new ICondition[children.size()]));
}
@Override
public ResourceLocation getID()
{
return AndCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -0,0 +1,66 @@
package net.minecraftforge.common.crafting.conditions;
import java.util.Optional;
import java.util.function.Supplier;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.Decoder;
import com.mojang.serialization.DynamicOps;
import net.minecraft.resources.DelegatingOps;
import net.minecraftforge.common.crafting.conditions.ICondition.IContext;
public class ConditionCodec {
public static <T> Codec<T> checkingDecode(Codec<T> normal, Supplier<T> _default) {
return checkingDecode(normal, _default, ICondition.DEFAULT_FIELD);
}
public static <T> Codec<T> checkingDecode(Codec<T> normal, Supplier<T> _default, String key) {
return Codec.of(normal, new UnwrapDecoder<>(wrap(normal, key), _default));
}
public static <T> Decoder<Optional<T>> wrap(Decoder<T> normal) {
return wrap(normal, ICondition.DEFAULT_FIELD);
}
public static <T> Decoder<Optional<T>> wrap(Decoder<T> normal, String key) {
return new OptionalConditionalDecoder<>(normal, key);
}
public static <T> IContext getContext(DynamicOps<T> ops) {
IContext ret = null;
if (ops instanceof DelegatingOps<?> dele)
ret = dele.getContext(ICondition.IContext.KEY);
return ret == null ? IContext.EMPTY : ret;
}
private static record UnwrapDecoder<A>(Decoder<Optional<A>> normal, Supplier<A> _default) implements Decoder<A> {
@Override
public <T> DataResult<Pair<A, T>> decode(DynamicOps<T> ops, T input) {
var ret = normal.decode(ops, input);
if (!ret.result().isPresent() || !ret.result().get().getFirst().isPresent())
return ret.map(p -> p.mapFirst(e -> _default.get()));
return ret.map(p -> p.mapFirst(Optional::get));
}
}
private static record OptionalConditionalDecoder<A>(Decoder<A> normal, String key) implements Decoder<Optional<A>> {
@Override
public <T> DataResult<Pair<Optional<A>, T>> decode(DynamicOps<T> ops, T input) {
var conditionRaw = ops.get(input, key);
if (conditionRaw.error().isPresent() || !conditionRaw.result().isPresent())
return normal.decode(ops, input).map(p -> p.mapFirst(Optional::of));
var conditionDecoded = ICondition.CODEC.parse(ops, conditionRaw.result().get());
if (conditionDecoded.error().isPresent())
return DataResult.error(() -> conditionDecoded.error().get().message());
var condition = conditionDecoded.result().get();
if (condition.test(getContext(ops)))
return DataResult.success(Pair.of(Optional.empty(), null));
return normal.decode(ops, input).map(p -> p.mapFirst(Optional::of));
}
}
}
@@ -6,7 +6,6 @@
package net.minecraftforge.common.crafting.conditions;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
@@ -17,32 +16,27 @@ import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Map;
public class ConditionContext implements ICondition.IContext
{
private final TagManager tagManager;
private Map<ResourceKey<?>, Map<ResourceLocation, Collection<Holder<?>>>> loadedTags = null;
public class ConditionContext implements ICondition.IContext {
private final TagManager tagManager;
private Map<ResourceKey<?>, Map<ResourceLocation, Collection<Holder<?>>>> loadedTags = null;
public ConditionContext(TagManager tagManager)
{
this.tagManager = tagManager;
}
public ConditionContext(TagManager tagManager) {
this.tagManager = tagManager;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry)
{
if (loadedTags == null)
{
var tags = tagManager.getResult();
if (tags.isEmpty()) throw new IllegalStateException("Tags have not been loaded yet.");
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
if (loadedTags == null) {
var tags = tagManager.getResult();
if (tags.isEmpty()) throw new IllegalStateException("Tags have not been loaded yet.");
loadedTags = new IdentityHashMap<>();
for (var loadResult : tags)
{
Map<ResourceLocation, Collection<? extends Holder<?>>> map = Collections.unmodifiableMap(loadResult.tags());
loadedTags.put(loadResult.key(), (Map) map);
}
}
return (Map) loadedTags.getOrDefault(registry, Collections.emptyMap());
}
loadedTags = new IdentityHashMap<>();
for (var loadResult : tags) {
var map = Collections.unmodifiableMap(loadResult.tags());
loadedTags.put(loadResult.key(), (Map)map);
}
}
return (Map)loadedTags.getOrDefault(registry, Collections.emptyMap());
}
}
@@ -5,51 +5,26 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import com.mojang.serialization.Codec;
public final class FalseCondition implements ICondition
{
public final class FalseCondition implements ICondition {
public static final FalseCondition INSTANCE = new FalseCondition();
private static final ResourceLocation NAME = new ResourceLocation("forge", "false");
public static final Codec<FalseCondition> CODEC = Codec.unit(INSTANCE).stable();
private FalseCondition() {}
private FalseCondition() { }
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext condition)
{
public boolean test(IContext condition) {
return false;
}
@Override
public String toString()
{
public String toString() {
return "false";
}
public static class Serializer implements IConditionSerializer<FalseCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, FalseCondition value) { }
@Override
public FalseCondition read(JsonObject json)
{
return FalseCondition.INSTANCE;
}
@Override
public ResourceLocation getID()
{
return FalseCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -5,50 +5,46 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraft.util.ExtraCodecs;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
public interface ICondition
{
static boolean shouldRegisterEntry(JsonElement json)
{
if (!(json instanceof JsonObject obj) || !obj.has("forge:conditions"))
return true;
return CraftingHelper.processConditions(obj, "forge:conditions", IContext.TAGS_INVALID);
}
ResourceLocation getID();
public interface ICondition {
Codec<ICondition> CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.CONDITION_SERIALIZERS.get().getCodec().dispatch(ICondition::codec, Function.identity()));
String DEFAULT_FIELD = "forge:condition";
MapCodec<Optional<ICondition>> OPTIONAL_FEILD_CODEC = CODEC.optionalFieldOf(DEFAULT_FIELD);
boolean test(IContext context);
interface IContext
{
IContext EMPTY = new IContext()
{
Codec<? extends ICondition> codec();
interface IContext {
public static ResourceLocation KEY = new ResourceLocation("forge", "condition_context");
IContext EMPTY = new IContext() {
@Override
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry)
{
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
return Collections.emptyMap();
}
};
IContext TAGS_INVALID = new IContext()
{
IContext TAGS_INVALID = new IContext() {
@Override
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry)
{
public <T> Map<ResourceLocation, Collection<Holder<T>>> getAllTags(ResourceKey<? extends Registry<T>> registry) {
throw new UnsupportedOperationException("Usage of tag-based conditions is not permitted in this context!");
}
};
@@ -56,8 +52,7 @@ public interface ICondition
/**
* Return the requested tag if available, or an empty tag otherwise.
*/
default <T> Collection<Holder<T>> getTag(TagKey<T> key)
{
default <T> Collection<Holder<T>> getTag(TagKey<T> key) {
return getAllTags(key.registry()).getOrDefault(key.location(), Set.of());
}
@@ -5,48 +5,42 @@
package net.minecraftforge.common.crafting.conditions;
import java.util.List;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
public interface IConditionBuilder
{
default ICondition and(ICondition... values)
{
return new AndCondition(values);
public interface IConditionBuilder {
default ICondition and(ICondition... values) {
return new AndCondition(List.of(values));
}
default ICondition FALSE()
{
default ICondition FALSE() {
return FalseCondition.INSTANCE;
}
default ICondition TRUE()
{
default ICondition TRUE() {
return TrueCondition.INSTANCE;
}
default ICondition not(ICondition value)
{
default ICondition not(ICondition value) {
return new NotCondition(value);
}
default ICondition or(ICondition... values)
{
return new OrCondition(values);
default ICondition or(ICondition... values) {
return new OrCondition(List.of(values));
}
default ICondition itemExists(String namespace, String path)
{
return new ItemExistsCondition(namespace, path);
default ICondition itemExists(String namespace, String path) {
return new ItemExistsCondition(new ResourceLocation(namespace, path));
}
default ICondition modLoaded(String modid)
{
default ICondition modLoaded(String modid) {
return new ModLoadedCondition(modid);
}
default ICondition tagEmpty(TagKey<Item> tag)
{
return new TagEmptyCondition(tag.location());
default ICondition tagEmpty(TagKey<Item> tag) {
return new TagEmptyCondition(tag);
}
}
@@ -1,27 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
public interface IConditionSerializer<T extends ICondition>
{
void write(JsonObject json, T value);
T read(JsonObject json);
ResourceLocation getID();
default JsonObject getJson(T value)
{
JsonObject json = new JsonObject();
this.write(json, value);
json.addProperty("type", value.getID().toString());
return json;
}
}
@@ -5,70 +5,29 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
public class ItemExistsCondition implements ICondition
{
private static final ResourceLocation NAME = new ResourceLocation("forge", "item_exists");
private final ResourceLocation item;
public ItemExistsCondition(String location)
{
this(new ResourceLocation(location));
}
public ItemExistsCondition(String namespace, String path)
{
this(new ResourceLocation(namespace, path));
}
public ItemExistsCondition(ResourceLocation item)
{
this.item = item;
}
public record ItemExistsCondition(ResourceLocation item) implements ICondition {
public static Codec<ItemExistsCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
ResourceLocation.CODEC.fieldOf("item").forGetter(ItemExistsCondition::item)
).apply(b, ItemExistsCondition::new));
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext context)
{
public boolean test(IContext context) {
return ForgeRegistries.ITEMS.containsKey(item);
}
@Override
public String toString()
{
public String toString() {
return "item_exists(\"" + item + "\")";
}
public static class Serializer implements IConditionSerializer<ItemExistsCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, ItemExistsCondition value)
{
json.addProperty("item", value.item.toString());
}
@Override
public ItemExistsCondition read(JsonObject json)
{
return new ItemExistsCondition(new ResourceLocation(GsonHelper.getAsString(json, "item")));
}
@Override
public ResourceLocation getID()
{
return ItemExistsCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -5,60 +5,29 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.ModList;
public class ModLoadedCondition implements ICondition
{
private static final ResourceLocation NAME = new ResourceLocation("forge", "mod_loaded");
private final String modid;
public ModLoadedCondition(String modid)
{
this.modid = modid;
}
public record ModLoadedCondition(String modid) implements ICondition {
public static final Codec<ModLoadedCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
Codec.STRING.fieldOf("modid").forGetter(ModLoadedCondition::modid)
).apply(b, ModLoadedCondition::new));
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext context)
{
public boolean test(IContext context) {
return ModList.get().isLoaded(modid);
}
@Override
public String toString()
{
public String toString() {
return "mod_loaded(\"" + modid + "\")";
}
public static class Serializer implements IConditionSerializer<ModLoadedCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, ModLoadedCondition value)
{
json.addProperty("modid", value.modid);
}
@Override
public ModLoadedCondition read(JsonObject json)
{
return new ModLoadedCondition(GsonHelper.getAsString(json, "modid"));
}
@Override
public ResourceLocation getID()
{
return ModLoadedCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -5,59 +5,26 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
public class NotCondition implements ICondition
{
private static final ResourceLocation NAME = new ResourceLocation("forge", "not");
private final ICondition child;
public NotCondition(ICondition child)
{
this.child = child;
}
public record NotCondition(ICondition child) implements ICondition {
public static Codec<NotCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
ICondition.CODEC.fieldOf("value").forGetter(NotCondition::child)
).apply(b, NotCondition::new));
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext context)
{
public boolean test(IContext context) {
return !child.test(context);
}
@Override
public String toString()
{
public String toString() {
return "!" + child;
}
public static class Serializer implements IConditionSerializer<NotCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, NotCondition value)
{
json.add("value", CraftingHelper.serialize(value.child));
}
@Override
public NotCondition read(JsonObject json)
{
return new NotCondition(CraftingHelper.getCondition(GsonHelper.getAsJsonObject(json, "value")));
}
@Override
public ResourceLocation getID()
{
return NotCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -5,49 +5,21 @@
package net.minecraftforge.common.crafting.conditions;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.crafting.CraftingHelper;
public record OrCondition(List<ICondition> children) implements ICondition {
public static final Codec<AndCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
ICondition.CODEC.listOf().fieldOf("values").forGetter(AndCondition::children)
).apply(b, AndCondition::new));
public class OrCondition implements ICondition
{
private static final ResourceLocation NAME = new ResourceLocation("forge", "or");
private final ICondition[] children;
public OrCondition(ICondition... values)
{
if (values == null || values.length == 0)
throw new IllegalArgumentException("Values must not be empty");
for (ICondition child : values)
{
if (child == null)
throw new IllegalArgumentException("Value must not be null");
}
this.children = values;
}
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext context)
{
for (ICondition child : children)
{
public boolean test(IContext context) {
for (ICondition child : children) {
if (child.test(context))
return true;
}
@@ -56,41 +28,12 @@ public class OrCondition implements ICondition
}
@Override
public String toString()
{
public String toString() {
return Joiner.on(" || ").join(children);
}
public static class Serializer implements IConditionSerializer<OrCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, OrCondition value)
{
JsonArray values = new JsonArray();
for (ICondition child : value.children)
values.add(CraftingHelper.serialize(child));
json.add("values", values);
}
@Override
public OrCondition read(JsonObject json)
{
List<ICondition> children = new ArrayList<>();
for (JsonElement j : GsonHelper.getAsJsonArray(json, "values"))
{
if (!j.isJsonObject())
throw new JsonSyntaxException("Or condition values must be an array of JsonObjects");
children.add(CraftingHelper.getCondition(j.getAsJsonObject()));
}
return new OrCondition(children.toArray(new ICondition[children.size()]));
}
@Override
public ResourceLocation getID()
{
return OrCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -5,73 +5,32 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
public class TagEmptyCondition implements ICondition
{
private static final ResourceLocation NAME = new ResourceLocation("forge", "tag_empty");
private final TagKey<Item> tag;
public record TagEmptyCondition(TagKey<Item> tag) implements ICondition {
public static final Codec<TagEmptyCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
ResourceLocation.CODEC.xmap(loc -> TagKey.create(Registries.ITEM, loc), TagKey::location).fieldOf("tag").forGetter(TagEmptyCondition::tag)
).apply(b, TagEmptyCondition::new));
public TagEmptyCondition(String location)
{
this(new ResourceLocation(location));
}
public TagEmptyCondition(String namespace, String path)
{
this(new ResourceLocation(namespace, path));
}
public TagEmptyCondition(ResourceLocation tag)
{
this.tag = TagKey.create(Registries.ITEM, tag);
}
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(ICondition.IContext context)
{
public boolean test(ICondition.IContext context) {
return context.getTag(tag).isEmpty();
}
@Override
public String toString()
{
public String toString() {
return "tag_empty(\"" + tag.location() + "\")";
}
public static class Serializer implements IConditionSerializer<TagEmptyCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, TagEmptyCondition value)
{
json.addProperty("tag", value.tag.location().toString());
}
@Override
public TagEmptyCondition read(JsonObject json)
{
return new TagEmptyCondition(new ResourceLocation(GsonHelper.getAsString(json, "tag")));
}
@Override
public ResourceLocation getID()
{
return TagEmptyCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}
@@ -5,52 +5,26 @@
package net.minecraftforge.common.crafting.conditions;
import com.google.gson.JsonObject;
import com.mojang.serialization.Codec;
import net.minecraft.resources.ResourceLocation;
public final class TrueCondition implements ICondition
{
public final class TrueCondition implements ICondition {
public static final TrueCondition INSTANCE = new TrueCondition();
private static final ResourceLocation NAME = new ResourceLocation("forge", "true");
public static Codec<TrueCondition> CODEC = Codec.unit(INSTANCE).stable();
private TrueCondition() {}
@Override
public ResourceLocation getID()
{
return NAME;
}
@Override
public boolean test(IContext context)
{
public boolean test(IContext context) {
return true;
}
@Override
public String toString()
{
public String toString() {
return "true";
}
public static class Serializer implements IConditionSerializer<TrueCondition>
{
public static final Serializer INSTANCE = new Serializer();
@Override
public void write(JsonObject json, TrueCondition value) { }
@Override
public TrueCondition read(JsonObject json)
{
return TrueCondition.INSTANCE;
}
@Override
public ResourceLocation getID()
{
return TrueCondition.NAME;
}
@Override
public Codec<? extends ICondition> codec() {
return CODEC;
}
}