mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-16 18:45:09 +00:00
Global Loot Modifiers
This commit is contained in:
63 files changed
+1058
-1502
No files matched your search
@@ -22,9 +22,15 @@ import java.util.stream.Stream;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Multimap;
|
||||
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.Dynamic;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
@@ -76,6 +82,8 @@ import net.minecraft.world.level.gameevent.GameEvent;
|
||||
import net.minecraft.world.level.material.Fluids;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.storage.WorldData;
|
||||
import net.minecraft.world.level.storage.loot.LootContext;
|
||||
import net.minecraft.world.level.storage.loot.LootPool;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
@@ -121,7 +129,6 @@ import net.minecraftforge.event.RegisterStructureConversionsEvent;
|
||||
import net.minecraftforge.event.VanillaGameEvent;
|
||||
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
|
||||
import net.minecraftforge.event.entity.EntityAttributeModificationEvent;
|
||||
import net.minecraftforge.event.entity.EntityEvent;
|
||||
import net.minecraftforge.event.entity.item.ItemTossEvent;
|
||||
import net.minecraftforge.event.entity.living.EnderManAngerEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingAttackEvent;
|
||||
@@ -139,10 +146,8 @@ import net.minecraftforge.event.entity.living.LivingFallEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingHurtEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingKnockBackEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingMakeBrainEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingSwapItemsEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingUseTotemEvent;
|
||||
import net.minecraftforge.event.entity.living.LootingLevelEvent;
|
||||
import net.minecraftforge.event.entity.living.ShieldBlockEvent;
|
||||
import net.minecraftforge.event.entity.player.AnvilRepairEvent;
|
||||
import net.minecraftforge.event.entity.player.AttackEntityEvent;
|
||||
import net.minecraftforge.event.entity.player.CriticalHitEvent;
|
||||
@@ -188,6 +193,8 @@ import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
|
||||
@ApiStatus.Internal
|
||||
public class ForgeHooks {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
@SuppressWarnings("unused")
|
||||
@@ -648,14 +655,6 @@ public class ForgeHooks {
|
||||
return evt.isCanceled() ? evt.getCancellationResult() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use {@link #onLeftClickBlock(Player, BlockPos, Direction, ServerboundPlayerActionPacket.Action)} instead
|
||||
*/
|
||||
@Deprecated(since = "1.20.1", forRemoval = true)
|
||||
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face) {
|
||||
return onLeftClickBlock(player, pos, face, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK);
|
||||
}
|
||||
|
||||
public static PlayerInteractEvent.LeftClickBlock onLeftClickBlock(Player player, BlockPos pos, Direction face, ServerboundPlayerActionPacket.Action action) {
|
||||
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.convert(action));
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
@@ -693,85 +692,23 @@ public class ForgeHooks {
|
||||
return evt.getNewGameMode();
|
||||
}
|
||||
|
||||
/* TODO: GLM
|
||||
private static final ThreadLocal<Deque<LootTableContext>> lootContext = new ThreadLocal<>();
|
||||
private static LootTableContext getLootTableContext() {
|
||||
LootTableContext ctx = lootContext.get().peek();
|
||||
public static <E extends LootPool> Codec<List<E>> createLootTablePoolCodec(Codec<E> vanilla) {
|
||||
var list = vanilla.listOf();
|
||||
Decoder<List<E>> decoder = new Decoder<>() {
|
||||
@Override
|
||||
public <T> DataResult<Pair<List<E>, T>> decode(DynamicOps<T> ops, T input) {
|
||||
return list.decode(ops, input).map(p -> {
|
||||
var decoded = p.getFirst();
|
||||
for (int x = 0; x < decoded.size(); x++)
|
||||
decoded.get(x);
|
||||
|
||||
if (ctx == null)
|
||||
throw new JsonParseException("Invalid call stack, could not grab json context!"); // Should I throw this? Do we care about custom deserializers outside the manager?
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
public static TriFunction<ResourceLocation, JsonElement, ResourceManager, Optional<LootTable>> getLootTableDeserializer(Gson gson, String directory) {
|
||||
return (location, data, resourceManager) -> {
|
||||
try {
|
||||
Resource resource = resourceManager.getResource(location.withPath(directory + "/" + location.getPath() + ".json")).orElse(null);
|
||||
boolean custom = resource == null || !resource.isBuiltin();
|
||||
return Optional.ofNullable(loadLootTable(gson, location, data, custom));
|
||||
} catch (Exception exception) {
|
||||
LOGGER.error("Couldn't parse element {}:{}", directory, location, exception);
|
||||
return Optional.empty();
|
||||
return p;
|
||||
});
|
||||
}
|
||||
};
|
||||
return Codec.of(list, decoder);
|
||||
}
|
||||
|
||||
public static LootTable loadLootTable(Gson gson, ResourceLocation name, JsonElement data, boolean custom) {
|
||||
Deque<LootTableContext> que = lootContext.get();
|
||||
if (que == null) {
|
||||
que = Queues.newArrayDeque();
|
||||
lootContext.set(que);
|
||||
}
|
||||
|
||||
LootTable ret;
|
||||
try {
|
||||
que.push(new LootTableContext(name, custom));
|
||||
ret = gson.fromJson(data, LootTable.class);
|
||||
ret.setLootTableId(name);
|
||||
} catch (JsonParseException e) {
|
||||
throw e;
|
||||
} finally {
|
||||
que.pop();
|
||||
}
|
||||
|
||||
if (!custom)
|
||||
ret = ForgeEventFactory.loadLootTable(name, ret);
|
||||
|
||||
if (ret != null)
|
||||
ret.freeze();
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
private static class LootTableContext {
|
||||
public final ResourceLocation name;
|
||||
public final boolean vanilla;
|
||||
public final boolean custom;
|
||||
public int poolCount = 0;
|
||||
|
||||
private LootTableContext(ResourceLocation name, boolean custom) {
|
||||
this.name = name;
|
||||
this.custom = custom;
|
||||
this.vanilla = "minecraft".equals(this.name.getNamespace());
|
||||
}
|
||||
}
|
||||
|
||||
public static String readPoolName(JsonObject json) {
|
||||
LootTableContext ctx = getLootTableContext();
|
||||
|
||||
if (json.has("name"))
|
||||
return GsonHelper.getAsString(json, "name");
|
||||
|
||||
if (ctx.custom)
|
||||
return "custom#" + json.hashCode(); //We don't care about custom ones modders shouldn't be editing them!
|
||||
|
||||
ctx.poolCount++;
|
||||
|
||||
return ctx.poolCount == 1 ? "main" : "pool" + (ctx.poolCount - 1);
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns a vanilla fluid type for the given fluid.
|
||||
*
|
||||
@@ -953,7 +890,6 @@ public class ForgeHooks {
|
||||
FurnaceBlockEntity.getFuel().entrySet().forEach(e -> VANILLA_BURNS.put(ForgeRegistries.ITEMS.getDelegateOrThrow(e.getKey()), e.getValue()));
|
||||
}
|
||||
|
||||
// TODO: GLM
|
||||
/**
|
||||
* Handles the modification of loot table drops via the registered Global Loot Modifiers,
|
||||
* so that custom effects can be processed.
|
||||
@@ -967,16 +903,13 @@ public class ForgeHooks {
|
||||
*
|
||||
* @apiNote The given context will be modified by this method to also store the ID of the
|
||||
* loot table being queried.
|
||||
* /
|
||||
*/
|
||||
public static ObjectArrayList<ItemStack> modifyLoot(ResourceLocation lootTableId, ObjectArrayList<ItemStack> generatedLoot, LootContext context) {
|
||||
context.setQueriedLootTableId(lootTableId); // In case the ID was set via copy constructor, this will be ignored: intended
|
||||
LootModifierManager man = ForgeInternalHandler.getLootModifierManager();
|
||||
for (IGlobalLootModifier mod : man.getAllLootMods()) {
|
||||
for (var mod : ForgeInternalHandler.getLootModifierManager().getAllLootMods())
|
||||
generatedLoot = mod.apply(generatedLoot, context);
|
||||
}
|
||||
return generatedLoot;
|
||||
}
|
||||
*/
|
||||
|
||||
public static List<String> getModPacks() {
|
||||
List<String> modpacks = ResourcePackLoader.getPackNames();
|
||||
@@ -992,13 +925,11 @@ public class ForgeHooks {
|
||||
}
|
||||
|
||||
private static final Map<EntityType<? extends LivingEntity>, AttributeSupplier> FORGE_ATTRIBUTES = new HashMap<>();
|
||||
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
|
||||
@Deprecated
|
||||
public static Map<EntityType<? extends LivingEntity>, AttributeSupplier> getAttributesView() {
|
||||
return Collections.unmodifiableMap(FORGE_ATTRIBUTES);
|
||||
}
|
||||
|
||||
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
|
||||
@Deprecated
|
||||
public static void modifyAttributes() {
|
||||
ModLoader.get().postEvent(new EntityAttributeCreationEvent(FORGE_ATTRIBUTES));
|
||||
@@ -1013,22 +944,6 @@ public class ForgeHooks {
|
||||
});
|
||||
}
|
||||
|
||||
public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) {
|
||||
MinecraftForge.EVENT_BUS.post(new EntityEvent.EnteringSection(entity, packedOldPos, packedNewPos));
|
||||
}
|
||||
|
||||
public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) {
|
||||
ShieldBlockEvent e = new ShieldBlockEvent(blocker, source, blocked);
|
||||
MinecraftForge.EVENT_BUS.post(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
public static LivingSwapItemsEvent.Hands onLivingSwapHandItems(LivingEntity livingEntity) {
|
||||
LivingSwapItemsEvent.Hands event = new LivingSwapItemsEvent.Hands(livingEntity);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
public static void writeAdditionalLevelSaveData(WorldData worldData, CompoundTag levelTag) {
|
||||
CompoundTag fmlData = new CompoundTag();
|
||||
ListTag modList = new ListTag();
|
||||
|
||||
@@ -12,6 +12,7 @@ import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.server.TickTask;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraftforge.common.loot.LootModifierManager;
|
||||
import net.minecraftforge.common.util.FakePlayerFactory;
|
||||
import net.minecraftforge.event.AddReloadListenerEvent;
|
||||
import net.minecraftforge.event.RegisterCommandsEvent;
|
||||
@@ -101,7 +102,6 @@ public class ForgeInternalHandler {
|
||||
ConfigCommand.register(event.getDispatcher());
|
||||
}
|
||||
|
||||
/*
|
||||
private static LootModifierManager INSTANCE;
|
||||
|
||||
@SubscribeEvent
|
||||
@@ -111,11 +111,10 @@ public class ForgeInternalHandler {
|
||||
}
|
||||
|
||||
static LootModifierManager getLootModifierManager() {
|
||||
if(INSTANCE == null)
|
||||
if (INSTANCE == null)
|
||||
throw new IllegalStateException("Can not retrieve LootModifierManager until resources have loaded once.");
|
||||
return INSTANCE;
|
||||
}
|
||||
*/
|
||||
|
||||
@SubscribeEvent
|
||||
public void resourceReloadListeners(AddReloadListenerEvent event) {
|
||||
|
||||
@@ -41,6 +41,7 @@ import net.minecraft.util.ExtraCodecs;
|
||||
import net.minecraft.core.RegistryCodecs;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.pathfinder.BlockPathTypes;
|
||||
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions;
|
||||
import net.minecraftforge.common.data.ExistingFileHelper;
|
||||
@@ -50,6 +51,8 @@ import net.minecraftforge.common.data.ForgeSpriteSourceProvider;
|
||||
import net.minecraftforge.common.data.VanillaSoundDefinitionsProvider;
|
||||
import net.minecraftforge.common.extensions.IForgeEntity;
|
||||
import net.minecraftforge.common.extensions.IForgePlayer;
|
||||
import net.minecraftforge.common.loot.CanToolPerformAction;
|
||||
import net.minecraftforge.common.loot.LootTableIdCondition;
|
||||
import net.minecraftforge.common.world.BiomeModifier;
|
||||
import net.minecraftforge.common.world.ForgeBiomeModifiers.AddFeaturesBiomeModifier;
|
||||
import net.minecraftforge.common.world.ForgeBiomeModifiers.AddSpawnsBiomeModifier;
|
||||
@@ -89,9 +92,9 @@ import org.apache.logging.log4j.Logger;
|
||||
|
||||
import net.minecraft.data.DataGenerator;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.common.crafting.CraftingHelper;
|
||||
import net.minecraftforge.common.crafting.conditions.AndCondition;
|
||||
import net.minecraftforge.common.crafting.conditions.FalseCondition;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.common.crafting.conditions.ItemExistsCondition;
|
||||
import net.minecraftforge.common.crafting.conditions.ModLoadedCondition;
|
||||
import net.minecraftforge.common.crafting.conditions.NotCondition;
|
||||
@@ -129,9 +132,10 @@ public class ForgeMod {
|
||||
private static final DeferredRegister<Codec<? extends StructureModifier>> STRUCTURE_MODIFIER_SERIALIZERS = DeferredRegister.create(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS, "forge");
|
||||
private static final DeferredRegister<HolderSetType> HOLDER_SET_TYPES = DeferredRegister.create(ForgeRegistries.Keys.HOLDER_SET_TYPES, "forge");
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
|
||||
private static final RegistryObject<EnumArgument.Info> ENUM_COMMAND_ARGUMENT_TYPE = COMMAND_ARGUMENT_TYPES.register("enum", () ->
|
||||
ArgumentTypeInfos.registerByClass(EnumArgument.class, new EnumArgument.Info()));
|
||||
@SuppressWarnings("unused")
|
||||
private static final RegistryObject<SingletonArgumentInfo<ModIdArgument>> MODID_COMMAND_ARGUMENT_TYPE = COMMAND_ARGUMENT_TYPES.register("modid", () ->
|
||||
ArgumentTypeInfos.registerByClass(ModIdArgument.class,
|
||||
SingletonArgumentInfo.contextFree(ModIdArgument::modIdArgument)));
|
||||
@@ -367,6 +371,25 @@ public class ForgeMod {
|
||||
}
|
||||
});
|
||||
|
||||
private static final DeferredRegister<LootItemConditionType> LOOT_CONDITION_TYPES = DeferredRegister.create(Registries.LOOT_CONDITION_TYPE, "forge");
|
||||
static {
|
||||
LOOT_CONDITION_TYPES.register("loot_table_id", () -> LootTableIdCondition.TYPE);
|
||||
LOOT_CONDITION_TYPES.register("can_tool_perform_action", () -> CanToolPerformAction.TYPE);
|
||||
}
|
||||
|
||||
private static final DeferredRegister<Codec<? extends ICondition>> CONDITION_SERIALIZERS = DeferredRegister.create(ForgeRegistries.Keys.CONDITION_SERIALIZERS, "forge");
|
||||
static {
|
||||
CONDITION_SERIALIZERS.register("and", () -> AndCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("false", () -> FalseCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("item_exists", () -> ItemExistsCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("mod_loaded", () -> ModLoadedCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("not", () -> NotCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("or", () -> OrCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("true", () -> TrueCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("tag_empty", () -> TagEmptyCondition.CODEC);
|
||||
}
|
||||
|
||||
|
||||
private static boolean enableMilkFluid = false;
|
||||
public static final RegistryObject<SoundEvent> BUCKET_EMPTY_MILK = RegistryObject.create(new ResourceLocation("item.bucket.empty_milk"), ForgeRegistries.SOUND_EVENTS);
|
||||
public static final RegistryObject<SoundEvent> BUCKET_FILL_MILK = RegistryObject.create(new ResourceLocation("item.bucket.fill_milk"), ForgeRegistries.SOUND_EVENTS);
|
||||
@@ -414,7 +437,6 @@ public class ForgeMod {
|
||||
modEventBus.addListener(this::registerFluids);
|
||||
modEventBus.addListener(this::registerVanillaDisplayContexts);
|
||||
modEventBus.addListener(this::registerRecipeSerializers);
|
||||
modEventBus.addListener(this::registerLootData);
|
||||
modEventBus.register(this);
|
||||
ATTRIBUTES.register(modEventBus);
|
||||
COMMAND_ARGUMENT_TYPES.register(modEventBus);
|
||||
@@ -422,6 +444,8 @@ public class ForgeMod {
|
||||
STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
|
||||
HOLDER_SET_TYPES.register(modEventBus);
|
||||
VANILLA_FLUID_TYPES.register(modEventBus);
|
||||
LOOT_CONDITION_TYPES.register(modEventBus);
|
||||
CONDITION_SERIALIZERS.register(modEventBus);
|
||||
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
|
||||
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
|
||||
ModLoadingContext.get().registerConfig(ModConfig.Type.SERVER, ForgeConfig.serverSpec);
|
||||
@@ -546,14 +570,6 @@ public class ForgeMod {
|
||||
|
||||
public void registerRecipeSerializers(RegisterEvent event) {
|
||||
if (event.getRegistryKey().equals(ForgeRegistries.Keys.RECIPE_SERIALIZERS)) {
|
||||
CraftingHelper.register(AndCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(FalseCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(ItemExistsCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(ModLoadedCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(NotCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(OrCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(TrueCondition.Serializer.INSTANCE);
|
||||
CraftingHelper.register(TagEmptyCondition.Serializer.INSTANCE);
|
||||
|
||||
/*
|
||||
CraftingHelper.register(new ResourceLocation("forge", "compound"), CompoundIngredient.Serializer.INSTANCE);
|
||||
@@ -568,14 +584,6 @@ public class ForgeMod {
|
||||
}
|
||||
}
|
||||
|
||||
public void registerLootData(RegisterEvent event) {
|
||||
if (!event.getRegistryKey().equals(Registries.LOOT_CONDITION_TYPE))
|
||||
return;
|
||||
|
||||
//event.register(Registries.LOOT_CONDITION_TYPE, new ResourceLocation("forge:loot_table_id"), () -> LootTableIdCondition.LOOT_TABLE_ID);
|
||||
//event.register(Registries.LOOT_CONDITION_TYPE, new ResourceLocation("forge:can_tool_perform_action"), () -> CanToolPerformAction.LOOT_CONDITION_TYPE);
|
||||
}
|
||||
|
||||
public static final PermissionNode<Boolean> USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
|
||||
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS));
|
||||
|
||||
|
||||
@@ -10,9 +10,10 @@ import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@SuppressWarnings("ClassCanBeRecord")
|
||||
public final class ToolAction
|
||||
{
|
||||
import com.mojang.serialization.Codec;
|
||||
|
||||
public final class ToolAction {
|
||||
public static final Codec<ToolAction> CODEC = Codec.STRING.xmap(ToolAction::get, ToolAction::name).stable();
|
||||
private static final Map<String, ToolAction> actions = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
@@ -20,30 +21,26 @@ public final class ToolAction
|
||||
* This collection can be kept around, and will update itself in response to changes to the map.
|
||||
* See {@link ConcurrentHashMap#values()} for details.
|
||||
*/
|
||||
public static Collection<ToolAction> getActions()
|
||||
{
|
||||
public static Collection<ToolAction> getActions() {
|
||||
return Collections.unmodifiableCollection(actions.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates a new ToolAction for the given name.
|
||||
*/
|
||||
public static ToolAction get(String name)
|
||||
{
|
||||
public static ToolAction get(String name) {
|
||||
return actions.computeIfAbsent(name, ToolAction::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this tool action
|
||||
*/
|
||||
public String name()
|
||||
{
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
public String toString() {
|
||||
return "ToolAction[" + name + "]";
|
||||
}
|
||||
|
||||
@@ -52,8 +49,7 @@ public final class ToolAction
|
||||
/**
|
||||
* Use {@link #get(String)} to get or create a ToolAction
|
||||
*/
|
||||
private ToolAction(String name)
|
||||
{
|
||||
private ToolAction(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
+16
-22
@@ -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;
|
||||
}
|
||||
}
|
||||
+11
-52
@@ -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;
|
||||
}
|
||||
}
|
||||
+12
-43
@@ -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;
|
||||
}
|
||||
}
|
||||
+11
-52
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.data;
|
||||
/*
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
@@ -31,7 +31,7 @@ import java.util.stream.Collectors;
|
||||
* Provider for forge's GlobalLootModifier system. See {@link LootModifier}
|
||||
*
|
||||
* This provider only requires implementing {@link #start()} and calling {@link #add} from it.
|
||||
* /
|
||||
*/
|
||||
public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
{
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
@@ -48,7 +48,7 @@ public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
|
||||
/**
|
||||
* Sets the "replace" key in global_loot_modifiers to true.
|
||||
* /
|
||||
*/
|
||||
protected void replacing()
|
||||
{
|
||||
this.replace = true;
|
||||
@@ -56,7 +56,7 @@ public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
|
||||
/**
|
||||
* Call {@link #add} here, which will pass in the necessary information to write the jsons.
|
||||
* /
|
||||
*/
|
||||
protected abstract void start();
|
||||
|
||||
@Override
|
||||
@@ -91,7 +91,7 @@ public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
*
|
||||
* @param modifier The name of the modifier, which will be the file name.
|
||||
* @param instance The instance to serialize
|
||||
* /
|
||||
*/
|
||||
public <T extends IGlobalLootModifier> void add(String modifier, T instance)
|
||||
{
|
||||
JsonElement json = IGlobalLootModifier.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, instance).getOrThrow(false, s -> {});
|
||||
@@ -104,4 +104,3 @@ public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
return "Global Loot Modifiers : " + modid;
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -15,8 +15,6 @@ import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.PlayerChatMessage;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.common.ServerboundClientInformationPacket;
|
||||
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundAcceptTeleportationPacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundBlockEntityTagQuery;
|
||||
import net.minecraft.network.protocol.game.ServerboundChangeDifficultyPacket;
|
||||
@@ -76,7 +74,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
/**
|
||||
* A basic fake server player implementation that can be used to simulate player actions.
|
||||
*/
|
||||
@Deprecated // TODO: Re-write this whole system to be less hacky. Use until we get a good replacement.
|
||||
// TODO: Re-write this whole system to be less hacky. Use until we get a good replacement.
|
||||
public class FakePlayer extends ServerPlayer {
|
||||
protected FakePlayer(ServerLevel level, GameProfile name, ClientInformation info) {
|
||||
super(level.getServer(), level, name, info);
|
||||
|
||||
@@ -14,17 +14,14 @@ import com.mojang.authlib.GameProfile;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
|
||||
|
||||
@Deprecated // TODO: Re-write this whole system to be less hacky. Use until we get a good replacement.
|
||||
public class FakePlayerFactory
|
||||
{
|
||||
// TODO: Re-write this whole system to be less hacky. Use until we get a good replacement.
|
||||
public class FakePlayerFactory {
|
||||
private static final GameProfile MINECRAFT = new GameProfile(UUID.fromString("41C82C87-7AfB-4024-BA57-13D2C99CAE77"), "[Minecraft]");
|
||||
// Map of all active fake player usernames to their entities
|
||||
private static final Map<FakePlayerKey, FakePlayer> fakePlayers = Maps.newHashMap();
|
||||
private record FakePlayerKey(ServerLevel level, GameProfile username) { }
|
||||
|
||||
public static FakePlayer getMinecraft(ServerLevel level)
|
||||
{
|
||||
public static FakePlayer getMinecraft(ServerLevel level) {
|
||||
return get(level, MINECRAFT);
|
||||
}
|
||||
|
||||
@@ -34,14 +31,12 @@ public class FakePlayerFactory
|
||||
* WorldEvent.Unload and kill all references to prevent worlds staying in memory,
|
||||
* or call this function every time and let Forge take care of the cleanup.
|
||||
*/
|
||||
public static FakePlayer get(ServerLevel level, GameProfile username)
|
||||
{
|
||||
public static FakePlayer get(ServerLevel level, GameProfile username) {
|
||||
FakePlayerKey key = new FakePlayerKey(level, username);
|
||||
return fakePlayers.computeIfAbsent(key, FakePlayerFactory::create);
|
||||
}
|
||||
|
||||
public static void unloadLevel(ServerLevel level)
|
||||
{
|
||||
public static void unloadLevel(ServerLevel level) {
|
||||
fakePlayers.entrySet().removeIf(entry -> entry.getValue().level() == level);
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ import net.minecraft.world.level.storage.loot.LootTable;
|
||||
import net.minecraft.server.packs.resources.PreparableReloadListener;
|
||||
import net.minecraft.world.level.BaseSpawner;
|
||||
import net.minecraft.world.InteractionResultHolder;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
@@ -110,7 +111,9 @@ import net.minecraftforge.event.entity.living.LivingEntityUseItemEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingExperienceDropEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingHealEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingPackSizeEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingSwapItemsEvent;
|
||||
import net.minecraftforge.event.entity.living.MobSpawnEvent;
|
||||
import net.minecraftforge.event.entity.living.ShieldBlockEvent;
|
||||
import net.minecraftforge.event.entity.living.MobSpawnEvent.AllowDespawn;
|
||||
import net.minecraftforge.event.entity.living.MobSpawnEvent.PositionCheck;
|
||||
import net.minecraftforge.event.entity.living.MobSpawnEvent.SpawnPlacementCheck;
|
||||
@@ -572,11 +575,9 @@ public class ForgeEventFactory {
|
||||
return onProjectileImpactResult(projectile, ray) != ProjectileImpactEvent.ImpactResult.DEFAULT;
|
||||
}
|
||||
|
||||
public static LootTable loadLootTable(ResourceLocation name, LootTable table) {
|
||||
public static @Nullable LootTable onLoadLootTable(ResourceLocation name, LootTable table) {
|
||||
var event = new LootTableLoadEvent(name, table);
|
||||
if (post(event))
|
||||
return LootTable.EMPTY;
|
||||
return event.getTable();
|
||||
return post(event) ? null : event.getTable();
|
||||
}
|
||||
|
||||
public static boolean canCreateFluidSource(Level level, BlockPos pos, BlockState state, boolean def) {
|
||||
@@ -811,4 +812,16 @@ public class ForgeEventFactory {
|
||||
public static void onChannelRegistrationChange(Connection connection, ChannelRegistrationChangeEvent.Type changeType, HashSet<ResourceLocation> changed) {
|
||||
post(new ChannelRegistrationChangeEvent(connection, changeType, changed));
|
||||
}
|
||||
|
||||
public static LivingSwapItemsEvent.Hands onLivingSwapHandItems(LivingEntity entity) {
|
||||
return fire(new LivingSwapItemsEvent.Hands(entity));
|
||||
}
|
||||
|
||||
public static ShieldBlockEvent onShieldBlock(LivingEntity blocker, DamageSource source, float blocked) {
|
||||
return fire(new ShieldBlockEvent(blocker, source, blocked));
|
||||
}
|
||||
|
||||
public static void onEntityEnterSection(Entity entity, long packedOldPos, long packedNewPos) {
|
||||
post(new EntityEvent.EnteringSection(entity, packedOldPos, packedNewPos));
|
||||
}
|
||||
}
|
||||
@@ -25,11 +25,12 @@ public class ForgeDeferredRegistriesSetup
|
||||
}
|
||||
|
||||
ForgeRegistries.DEFERRED_ENTITY_DATA_SERIALIZERS.register(modEventBus);
|
||||
//ForgeRegistries.DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_BIOME_MODIFIER_SERIALIZERS.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_FLUID_TYPES.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_HOLDER_SET_TYPES.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_DISPLAY_CONTEXTS.register(modEventBus);
|
||||
ForgeRegistries.DEFERRED_CONDITION_CODECS.register(modEventBus);
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ import net.minecraft.world.level.levelgen.feature.Feature;
|
||||
import net.minecraft.world.level.levelgen.feature.foliageplacers.FoliagePlacerType;
|
||||
import net.minecraft.world.level.levelgen.feature.treedecorators.TreeDecoratorType;
|
||||
import net.minecraftforge.common.Tags;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.common.loot.IGlobalLootModifier;
|
||||
import net.minecraftforge.common.world.BiomeModifier;
|
||||
import net.minecraftforge.fluids.FluidType;
|
||||
import net.minecraftforge.registries.holdersets.HolderSetType;
|
||||
@@ -104,12 +106,12 @@ public class ForgeRegistries
|
||||
* Use {@link Keys#ENTITY_DATA_SERIALIZERS} to create a {@link DeferredRegister}.
|
||||
*/
|
||||
public static final Supplier<IForgeRegistry<EntityDataSerializer<?>>> ENTITY_DATA_SERIALIZERS = DEFERRED_ENTITY_DATA_SERIALIZERS.makeRegistry(GameData::getDataSerializersRegistryBuilder);
|
||||
//static final DeferredRegister<Codec<? extends IGlobalLootModifier>> DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS = DeferredRegister.create(Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS.location().getNamespace());
|
||||
static final DeferredRegister<Codec<? extends IGlobalLootModifier>> DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS = DeferredRegister.create(Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS, Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS.location().getNamespace());
|
||||
/**
|
||||
* Calling {@link Supplier#get()} before {@link NewRegistryEvent} is fired will result in a null registry returned.
|
||||
* Use {@link Keys#GLOBAL_LOOT_MODIFIER_SERIALIZERS} to create a {@link DeferredRegister}.
|
||||
*/
|
||||
//public static final Supplier<IForgeRegistry<Codec<? extends IGlobalLootModifier>>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS.makeRegistry(GameData::getGLMSerializersRegistryBuilder);
|
||||
public static final Supplier<IForgeRegistry<Codec<? extends IGlobalLootModifier>>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = DEFERRED_GLOBAL_LOOT_MODIFIER_SERIALIZERS.makeRegistry(GameData::getGLMSerializersRegistryBuilder);
|
||||
static final DeferredRegister<Codec<? extends BiomeModifier>> DEFERRED_BIOME_MODIFIER_SERIALIZERS = DeferredRegister.create(Keys.BIOME_MODIFIER_SERIALIZERS, Keys.BIOME_MODIFIER_SERIALIZERS.location().getNamespace());
|
||||
/**
|
||||
* Calling {@link Supplier#get()} before {@link NewRegistryEvent} is fired will result in a null registry returned.
|
||||
@@ -142,6 +144,13 @@ public class ForgeRegistries
|
||||
*/
|
||||
public static final Supplier<IForgeRegistry<ItemDisplayContext>> DISPLAY_CONTEXTS = DEFERRED_DISPLAY_CONTEXTS.makeRegistry(GameData::getItemDisplayContextRegistryBuilder);
|
||||
|
||||
static final DeferredRegister<Codec<? extends ICondition>> DEFERRED_CONDITION_CODECS = DeferredRegister.create(Keys.CONDITION_SERIALIZERS, Keys.CONDITION_SERIALIZERS.location().getNamespace());
|
||||
/**
|
||||
* Calling {@link Supplier#get()} before {@link NewRegistryEvent} is fired will result in a null registry returned.
|
||||
* Use {@link Keys#CONDITION_SERIALIZERS} to create a {@link DeferredRegister}.
|
||||
*/
|
||||
public static final Supplier<IForgeRegistry<Codec<? extends ICondition>>> CONDITION_SERIALIZERS = DEFERRED_CONDITION_CODECS.makeRegistry(GameData::getConditionCodecRegistryBuilder);
|
||||
|
||||
public static final class Keys {
|
||||
//Vanilla
|
||||
public static final ResourceKey<Registry<Block>> BLOCKS = key("block");
|
||||
@@ -179,12 +188,13 @@ public class ForgeRegistries
|
||||
|
||||
// Forge
|
||||
public static final ResourceKey<Registry<EntityDataSerializer<?>>> ENTITY_DATA_SERIALIZERS = key("forge:entity_data_serializers");
|
||||
//public static final ResourceKey<Registry<Codec<? extends IGlobalLootModifier>>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = key("forge:global_loot_modifier_serializers");
|
||||
public static final ResourceKey<Registry<Codec<? extends IGlobalLootModifier>>> GLOBAL_LOOT_MODIFIER_SERIALIZERS = key("forge:global_loot_modifier_serializers");
|
||||
public static final ResourceKey<Registry<Codec<? extends BiomeModifier>>> BIOME_MODIFIER_SERIALIZERS = key("forge:biome_modifier_serializers");
|
||||
public static final ResourceKey<Registry<Codec<? extends StructureModifier>>> STRUCTURE_MODIFIER_SERIALIZERS = key("forge:structure_modifier_serializers");
|
||||
public static final ResourceKey<Registry<FluidType>> FLUID_TYPES = key("forge:fluid_type");
|
||||
public static final ResourceKey<Registry<HolderSetType>> HOLDER_SET_TYPES = key("forge:holder_set_type");
|
||||
public static final ResourceKey<Registry<ItemDisplayContext>> DISPLAY_CONTEXTS = key("forge:display_contexts");
|
||||
public static final ResourceKey<Registry<Codec<? extends ICondition>>> CONDITION_SERIALIZERS = key("forge:condition_codecs");
|
||||
|
||||
// Forge Dynamic
|
||||
public static final ResourceKey<Registry<BiomeModifier>> BIOME_MODIFIERS = key("forge:biome_modifier");
|
||||
@@ -207,4 +217,4 @@ public class ForgeRegistries
|
||||
Bootstrap.bootStrap();
|
||||
Tags.init();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ import net.minecraft.world.level.material.Fluid;
|
||||
import net.minecraftforge.common.CreativeModeTabRegistry;
|
||||
import net.minecraftforge.common.ForgeHooks;
|
||||
import net.minecraftforge.common.MinecraftForge;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.common.loot.IGlobalLootModifier;
|
||||
import net.minecraftforge.common.util.LogMessageAdapter;
|
||||
import net.minecraftforge.common.world.BiomeModifier;
|
||||
import net.minecraftforge.common.world.StructureModifier;
|
||||
@@ -91,6 +93,7 @@ public class GameData
|
||||
init();
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void init()
|
||||
{
|
||||
if (DISABLE_VANILLA_REGISTRIES)
|
||||
@@ -146,12 +149,10 @@ public class GameData
|
||||
return makeRegistry(Keys.ENTITY_DATA_SERIALIZERS, 256 /*vanilla space*/, MAX_VARINT).disableSaving().disableOverrides();
|
||||
}
|
||||
|
||||
/*
|
||||
static RegistryBuilder<Codec<? extends IGlobalLootModifier>> getGLMSerializersRegistryBuilder()
|
||||
{
|
||||
return makeRegistry(Keys.GLOBAL_LOOT_MODIFIER_SERIALIZERS).disableSaving().disableSync();
|
||||
}
|
||||
*/
|
||||
|
||||
static RegistryBuilder<Codec<? extends BiomeModifier>> getBiomeModifierSerializersRegistryBuilder()
|
||||
{
|
||||
@@ -173,6 +174,11 @@ public class GameData
|
||||
return new RegistryBuilder<HolderSetType>().disableSaving().disableSync();
|
||||
}
|
||||
|
||||
static RegistryBuilder<Codec<? extends ICondition>> getConditionCodecRegistryBuilder()
|
||||
{
|
||||
return new RegistryBuilder<Codec<? extends ICondition>>().disableSaving().disableSync();
|
||||
}
|
||||
|
||||
static RegistryBuilder<ItemDisplayContext> getItemDisplayContextRegistryBuilder()
|
||||
{
|
||||
return new RegistryBuilder<ItemDisplayContext>()
|
||||
@@ -232,7 +238,6 @@ public class GameData
|
||||
return RegistryManager.ACTIVE.getRegistry(Keys.POI_TYPES).getSlaveMap(BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE, Map.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static void vanillaSnapshot()
|
||||
{
|
||||
LOGGER.debug(REGISTRIES, "Creating vanilla freeze snapshot");
|
||||
@@ -250,13 +255,13 @@ public class GameData
|
||||
LOGGER.debug(REGISTRIES, "Vanilla freeze snapshot created");
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public static void unfreezeData()
|
||||
{
|
||||
LOGGER.debug(REGISTRIES, "Unfreezing vanilla registries");
|
||||
BuiltInRegistries.REGISTRY.stream().filter(r -> r instanceof MappedRegistry).forEach(r -> ((MappedRegistry<?>)r).unfreeze());
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public static void freezeData()
|
||||
{
|
||||
LOGGER.debug(REGISTRIES, "Freezing registries");
|
||||
@@ -286,7 +291,7 @@ public class GameData
|
||||
public static void revertToFrozen() {
|
||||
revertTo(RegistryManager.FROZEN, true);
|
||||
}
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
|
||||
public static void revertTo(final RegistryManager target, boolean fireEvents)
|
||||
{
|
||||
if (target.registries.isEmpty())
|
||||
@@ -312,7 +317,6 @@ public class GameData
|
||||
LOGGER.debug(REGISTRIES, "{} state restored.", target.getName());
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
public static void revert(RegistryManager state, ResourceLocation registry, boolean lock)
|
||||
{
|
||||
LOGGER.debug(REGISTRIES, "Reverting {} to {}", registry, state.getName());
|
||||
@@ -381,8 +385,10 @@ public class GameData
|
||||
this.nextId = 0;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
void remove(I key)
|
||||
{
|
||||
@SuppressWarnings("deprecation")
|
||||
Integer prev = this.tToId.remove(key);
|
||||
if (prev != null)
|
||||
{
|
||||
@@ -437,6 +443,7 @@ public class GameData
|
||||
{
|
||||
final ClearableObjectIntIdentityMap<BlockState> idMap = new ClearableObjectIntIdentityMap<BlockState>()
|
||||
{
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override
|
||||
public int getId(BlockState key)
|
||||
{
|
||||
@@ -527,6 +534,7 @@ public class GameData
|
||||
@Override
|
||||
public void onAdd(IForgeRegistryInternal<PoiType> owner, RegistryManager stage, int id, ResourceKey<PoiType> key, PoiType obj, @Nullable PoiType oldObj)
|
||||
{
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<BlockState, PoiType> map = owner.getSlaveMap(BLOCKSTATE_TO_POINT_OF_INTEREST_TYPE, Map.class);
|
||||
if (oldObj != null)
|
||||
{
|
||||
@@ -595,7 +603,6 @@ public class GameData
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static Multimap<ResourceLocation, ResourceLocation> injectSnapshot(Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot, boolean injectFrozenData, boolean isLocalWorld)
|
||||
{
|
||||
LOGGER.info(REGISTRIES, "Injecting existing registry data into this {} instance", EffectiveSide.get());
|
||||
@@ -756,7 +763,6 @@ public class GameData
|
||||
}
|
||||
|
||||
//Another bouncer for generic reasons
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> void processMissing(ResourceLocation name, RegistryManager STAGING, MissingMappingsEvent e, Map<ResourceLocation, Integer> missing, Map<ResourceLocation, IdMappingEvent.IdRemapping> remaps, Collection<ResourceLocation> defaulted, Collection<ResourceLocation> failed, boolean injectNetworkDummies)
|
||||
{
|
||||
List<MissingMappingsEvent.Mapping<T>> mappings = e.getAllMappings(ResourceKey.createRegistryKey(name));
|
||||
|
||||
Reference in new issue
Block a user