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

@@ -4,11 +4,11 @@
*/
package net.minecraftforge.common.loot;
/*
import com.google.common.collect.ImmutableSet;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParam;
@@ -22,46 +22,30 @@ import java.util.Set;
/**
* This LootItemCondition "forge:can_tool_perform_action" can be used to check if a tool can perform a given ToolAction.
* /
public class CanToolPerformAction implements LootItemCondition {
*/
public record CanToolPerformAction(ToolAction action) implements LootItemCondition {
public static final Codec<CanToolPerformAction> CODEC = RecordCodecBuilder.create(b -> b.group(
ToolAction.CODEC.fieldOf("action").forGetter(CanToolPerformAction::action)
).apply(b, CanToolPerformAction::new));
public static final LootItemConditionType TYPE = new LootItemConditionType(CODEC);
public static final LootItemConditionType LOOT_CONDITION_TYPE = new LootItemConditionType(new CanToolPerformAction.Serializer());
final ToolAction action;
public CanToolPerformAction(ToolAction action) {
this.action = action;
@Override
public @NotNull LootItemConditionType getType() {
return TYPE;
}
@NotNull
public LootItemConditionType getType() {
return LOOT_CONDITION_TYPE;
}
@NotNull
public Set<LootContextParam<?>> getReferencedContextParams() {
@Override
public @NotNull Set<LootContextParam<?>> getReferencedContextParams() {
return ImmutableSet.of(LootContextParams.TOOL);
}
public boolean test(LootContext lootContext) {
ItemStack itemstack = lootContext.getParamOrNull(LootContextParams.TOOL);
@Override
public boolean test(LootContext ctx) {
ItemStack itemstack = ctx.getParamOrNull(LootContextParams.TOOL);
return itemstack != null && itemstack.canPerformAction(this.action);
}
public static LootItemCondition.Builder canToolPerformAction(ToolAction action) {
return () -> new CanToolPerformAction(action);
}
public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer<CanToolPerformAction> {
public void serialize(JsonObject json, CanToolPerformAction itemCondition, @NotNull JsonSerializationContext context) {
json.addProperty("action", itemCondition.action.name());
}
@NotNull
public CanToolPerformAction deserialize(JsonObject json, @NotNull JsonDeserializationContext context) {
return new CanToolPerformAction(ToolAction.get(json.get("action").getAsString()));
}
}
}
*/
}
@@ -4,11 +4,9 @@
*/
package net.minecraftforge.common.loot;
/*
import com.google.gson.JsonElement;
import com.google.gson.JsonSyntaxException;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.JsonOps;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -16,9 +14,11 @@ import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditions;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.Function;
/**
@@ -26,46 +26,19 @@ import java.util.function.Function;
* {@link LootModifier} Supplies base functionality; most modders should only need to extend that.<br/>
* Requires a {@link Codec} to be registered: {@link ForgeRegistries#GLOBAL_LOOT_MODIFIER_SERIALIZERS}, and returned in {@link #codec()}
* Individual instances of modifiers must be registered via json, see forge:loot_modifiers/global_loot_modifiers
* /
*/
public interface IGlobalLootModifier {
Codec<IGlobalLootModifier> DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.GLOBAL_LOOT_MODIFIER_SERIALIZERS.get().getCodec())
.dispatch(IGlobalLootModifier::codec, Function.identity());
Codec<LootItemCondition[]> LOOT_CONDITIONS_CODEC = Codec.PASSTHROUGH.flatXmap(
d ->
{
try
{
LootItemCondition[] conditions = LootModifierManager.GSON_INSTANCE.fromJson(getJson(d), LootItemCondition[].class);
return DataResult.success(conditions);
}
catch (JsonSyntaxException e)
{
LootModifierManager.LOGGER.warn("Unable to decode loot conditions", e);
return DataResult.error(e::getMessage);
}
},
conditions ->
{
try
{
JsonElement element = LootModifierManager.GSON_INSTANCE.toJsonTree(conditions);
return DataResult.success(new Dynamic<>(JsonOps.INSTANCE, element));
}
catch (JsonSyntaxException e)
{
LootModifierManager.LOGGER.warn("Unable to encode loot conditions", e);
return DataResult.error(e::getMessage);
}
}
);
Codec<LootItemCondition[]> LOOT_CONDITIONS_CODEC = LootItemConditions.CODEC.listOf().xmap(list -> list.toArray(LootItemCondition[]::new), List::of);
@SuppressWarnings("unchecked")
static <U> JsonElement getJson(Dynamic<?> dynamic) {
Dynamic<U> typed = (Dynamic<U>) dynamic;
return typed.getValue() instanceof JsonElement ?
(JsonElement) typed.getValue() :
typed.getOps().convertTo(JsonOps.INSTANCE, typed.getValue());
return typed.getValue() instanceof JsonElement element ?
element :
typed.getOps().convertTo(JsonOps.INSTANCE, typed.getValue());
}
/**
@@ -74,13 +47,12 @@ public interface IGlobalLootModifier {
* @param generatedLoot the list of ItemStacks that will be dropped, generated by loot tables
* @param context the LootContext, identical to what is passed to loot tables
* @return modified loot drops
* /
*/
@NotNull
ObjectArrayList<ItemStack> apply(ObjectArrayList<ItemStack> generatedLoot, LootContext context);
/**
* Returns the registered codec for this modifier
* /
*/
Codec<? extends IGlobalLootModifier> codec();
}
*/
@@ -4,7 +4,8 @@
*/
package net.minecraftforge.common.loot;
/*
import java.util.Arrays;
import java.util.function.Predicate;
import com.mojang.datafixers.Products;
@@ -20,9 +21,8 @@ import org.jetbrains.annotations.NotNull;
/**
* A base implementation of a Global Loot Modifier for modders to extend.
* Takes care of ILootCondition matching and comes with the base codec to extend.
* /
public abstract class LootModifier implements IGlobalLootModifier
{
*/
public abstract class LootModifier implements IGlobalLootModifier {
protected final LootItemCondition[] conditions;
private final Predicate<LootContext> combinedConditions;
@@ -35,26 +35,23 @@ public abstract class LootModifier implements IGlobalLootModifier
* </p>
* Otherwise can follow this with #and() to add more fields.
* Examples: Forge Test Subclasses or {@link BendingTrunkPlacer#CODEC}
* /
protected static <T extends LootModifier> Products.P1<RecordCodecBuilder.Mu<T>, LootItemCondition[]> codecStart(RecordCodecBuilder.Instance<T> instance)
{
*/
protected static <T extends LootModifier> Products.P1<RecordCodecBuilder.Mu<T>, LootItemCondition[]> codecStart(RecordCodecBuilder.Instance<T> instance) {
return instance.group(LOOT_CONDITIONS_CODEC.fieldOf("conditions").forGetter(lm -> lm.conditions));
}
/**
* Constructs a LootModifier.
* @param conditionsIn the ILootConditions that need to be matched before the loot is modified.
* /
protected LootModifier(LootItemCondition[] conditionsIn)
{
*/
protected LootModifier(LootItemCondition[] conditionsIn) {
this.conditions = conditionsIn;
this.combinedConditions = LootItemConditions.andConditions(conditionsIn);
this.combinedConditions = LootItemConditions.andConditions(Arrays.asList(conditionsIn));
}
@NotNull
@Override
public final ObjectArrayList<ItemStack> apply(ObjectArrayList<ItemStack> generatedLoot, LootContext context)
{
public final ObjectArrayList<ItemStack> apply(ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
return this.combinedConditions.test(context) ? this.doApply(generatedLoot, context) : generatedLoot;
}
@@ -64,8 +61,7 @@ public abstract class LootModifier implements IGlobalLootModifier
* @param generatedLoot the list of ItemStacks that will be dropped, generated by loot tables
* @param context the LootContext, identical to what is passed to loot tables
* @return modified loot drops
* /
*/
@NotNull
protected abstract ObjectArrayList<ItemStack> doApply(ObjectArrayList<ItemStack> generatedLoot, LootContext context);
}
*/
@@ -4,17 +4,10 @@
*/
package net.minecraftforge.common.loot;
/*
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -22,74 +15,73 @@ import org.apache.logging.log4j.Logger;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;
public class LootModifierManager extends SimpleJsonResourceReloadListener {
public static final Logger LOGGER = LogManager.getLogger();
public static final Gson GSON_INSTANCE = Deserializers.createFunctionSerializer().create();
private static final Logger LOGGER = LogManager.getLogger();
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private static final String FOLDER = "loot_modifiers";
private Map<ResourceLocation, IGlobalLootModifier> registeredLootModifiers = ImmutableMap.of();
private static final String folder = "loot_modifiers";
private Map<ResourceLocation, IGlobalLootModifier> modifiers = ImmutableMap.of();
public LootModifierManager() {
super(GSON_INSTANCE, folder);
super(GSON, FOLDER);
}
@Override
protected void apply(Map<ResourceLocation, JsonElement> resourceList, ResourceManager resourceManagerIn, ProfilerFiller profilerIn) {
Builder<ResourceLocation, IGlobalLootModifier> builder = ImmutableMap.builder();
List<ResourceLocation> finalLocations = new ArrayList<>();
ResourceLocation resourcelocation = new ResourceLocation("forge","loot_modifiers/global_loot_modifiers.json");
//read in all data files from forge:loot_modifiers/global_loot_modifiers in order to do layering
for(Resource iresource : resourceManagerIn.getResourceStack(resourcelocation)) {
try ( InputStream inputstream = iresource.open();
Reader reader = new BufferedReader(new InputStreamReader(inputstream, StandardCharsets.UTF_8));
) {
JsonObject jsonobject = GsonHelper.fromJson(GSON_INSTANCE, reader, JsonObject.class);
boolean replace = jsonobject.get("replace").getAsBoolean();
if (replace)
finalLocations.clear();
JsonArray entryList = jsonobject.get("entries").getAsJsonArray();
for(JsonElement entry : entryList) {
ResourceLocation loc = new ResourceLocation(entry.getAsString());
finalLocations.remove(loc); //remove and re-add if needed, to update the ordering.
finalLocations.add(loc);
}
}
protected Map<ResourceLocation, JsonElement> prepare(ResourceManager resources, ProfilerFiller profilerFiller) {
var path = new ResourceLocation("forge", FOLDER + "/global_loot_modifiers.json");
catch (RuntimeException | IOException ioexception) {
LOGGER.error("Couldn't read global loot modifier list {} in data pack {}", resourcelocation, iresource.sourcePackId(), ioexception);
List<ResourceLocation> toLoad = new ArrayList<>();
//read in all data files from forge:loot_modifiers/global_loot_modifiers in order to do layering
for (var resource : resources.getResourceStack(path)) {
try (var reader = resource.openAsReader()) {
var json = GsonHelper.fromJson(GSON, reader, JsonObject.class);
if (GsonHelper.getAsBoolean(json, "replace", false))
toLoad.clear();
for(var entry : GsonHelper.getAsJsonArray(json, "entries")) {
ResourceLocation loc = new ResourceLocation(entry.getAsString());
toLoad.remove(loc); //remove and re-add if needed, to update the ordering.
toLoad.add(loc);
}
} catch (RuntimeException | IOException ioexception) {
LOGGER.error("Couldn't read global loot modifier list {} in data pack {}", path, resource.sourcePackId(), ioexception);
}
}
//use layered config to fetch modifier data files (modifiers missing from config are disabled)
for (ResourceLocation location : finalLocations)
{
JsonElement json = resourceList.get(location);
var ret = super.prepare(resources, profilerFiller);
ret.keySet().removeIf(k -> !toLoad.contains(k));
return ret;
}
@Override
protected void apply(Map<ResourceLocation, JsonElement> resources, ResourceManager resourceManagerIn, ProfilerFiller profilerIn) {
Builder<ResourceLocation, IGlobalLootModifier> builder = ImmutableMap.builder();
resources.forEach((location, json) -> {
IGlobalLootModifier.DIRECT_CODEC.parse(JsonOps.INSTANCE, json)
// log error if parse fails
.resultOrPartial(errorMsg -> LOGGER.warn("Could not decode GlobalLootModifier with json id {} - error: {}", location, errorMsg))
// add loot modifier if parse succeeds
.ifPresent(modifier -> builder.put(location, modifier));
}
this.registeredLootModifiers = builder.build();
});
this.modifiers = builder.build();
}
/**
* An immutable collection of the registered loot modifiers in layered order.
* /
*/
public Collection<IGlobalLootModifier> getAllLootMods() {
return registeredLootModifiers.values();
return modifiers.values();
}
}
*/
}
@@ -4,77 +4,51 @@
*/
package net.minecraftforge.common.loot;
/*
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.world.level.storage.loot.Serializer;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import net.minecraft.util.GsonHelper;
import net.minecraft.resources.ResourceLocation;
public class LootTableIdCondition implements LootItemCondition
{
public record LootTableIdCondition(ResourceLocation id) implements LootItemCondition {
public static final Codec<LootTableIdCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
ResourceLocation.CODEC.fieldOf("loot_table_id").forGetter(LootTableIdCondition::id)
).apply(b, LootTableIdCondition::new));
// TODO Forge Registry at some point?
public static final LootItemConditionType LOOT_TABLE_ID = new LootItemConditionType(new LootTableIdCondition.Serializer());
public static final LootItemConditionType TYPE = new LootItemConditionType(CODEC);
public static final ResourceLocation UNKNOWN_LOOT_TABLE = new ResourceLocation("forge", "unknown_loot_table");
private final ResourceLocation targetLootTableId;
private LootTableIdCondition(final ResourceLocation targetLootTableId)
{
this.targetLootTableId = targetLootTableId;
@Override
public LootItemConditionType getType() {
return TYPE;
}
@Override
public LootItemConditionType getType()
{
return LOOT_TABLE_ID;
public boolean test(LootContext ctx) {
return ctx.getQueriedLootTableId().equals(this.id());
}
@Override
public boolean test(LootContext lootContext)
{
return lootContext.getQueriedLootTableId().equals(this.targetLootTableId);
}
public static Builder builder(final ResourceLocation targetLootTableId)
{
public static Builder builder(final ResourceLocation targetLootTableId) {
return new Builder(targetLootTableId);
}
public static class Builder implements LootItemCondition.Builder
{
private final ResourceLocation targetLootTableId;
public static class Builder implements LootItemCondition.Builder {
private final ResourceLocation id;
public Builder(ResourceLocation targetLootTableId)
{
if (targetLootTableId == null) throw new IllegalArgumentException("Target loot table must not be null");
this.targetLootTableId = targetLootTableId;
public Builder(ResourceLocation id) {
if (id == null)
throw new IllegalArgumentException("Target loot table must not be null");
this.id = id;
}
@Override
public LootItemCondition build()
{
return new LootTableIdCondition(this.targetLootTableId);
}
}
public static class Serializer implements net.minecraft.world.level.storage.loot.Serializer<LootTableIdCondition>
{
@Override
public void serialize(JsonObject object, LootTableIdCondition instance, JsonSerializationContext ctx)
{
object.addProperty("loot_table_id", instance.targetLootTableId.toString());
}
@Override
public LootTableIdCondition deserialize(JsonObject object, JsonDeserializationContext ctx)
{
return new LootTableIdCondition(new ResourceLocation(GsonHelper.getAsString(object, "loot_table_id")));
public LootItemCondition build() {
return new LootTableIdCondition(this.id);
}
}
}
*/