mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-22 13:09:59 +00:00
1.20.6 Initial Update
New Decompiler Runtime Official mappings ItemStacks arnt Capability providers anymore, use Vanilla's system. Co-authored-by: RealMangoRage <[email protected]> Co-authored-by: Paint_Ninja <[email protected]>
This commit is contained in:
1114 files changed
+24245
-28536
No files matched your search
@@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.npc.VillagerTrades.ItemListing;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.trading.MerchantOffer;
|
||||
|
||||
/**
|
||||
* A default, exposed implementation of ITrade. All of the other implementations of ITrade (in VillagerTrades) are not public.
|
||||
* This class contains everything needed to make a MerchantOffer, the actual "trade" object shown in trading guis.
|
||||
*/
|
||||
public class BasicItemListing implements ItemListing
|
||||
{
|
||||
|
||||
protected final ItemStack price;
|
||||
protected final ItemStack price2;
|
||||
protected final ItemStack forSale;
|
||||
protected final int maxTrades;
|
||||
protected final int xp;
|
||||
protected final float priceMult;
|
||||
|
||||
public BasicItemListing(ItemStack price, ItemStack price2, ItemStack forSale, int maxTrades, int xp, float priceMult)
|
||||
{
|
||||
this.price = price;
|
||||
this.price2 = price2;
|
||||
this.forSale = forSale;
|
||||
this.maxTrades = maxTrades;
|
||||
this.xp = xp;
|
||||
this.priceMult = priceMult;
|
||||
}
|
||||
|
||||
public BasicItemListing(ItemStack price, ItemStack forSale, int maxTrades, int xp, float priceMult)
|
||||
{
|
||||
this(price, ItemStack.EMPTY, forSale, maxTrades, xp, priceMult);
|
||||
}
|
||||
|
||||
public BasicItemListing(int emeralds, ItemStack forSale, int maxTrades, int xp, float mult)
|
||||
{
|
||||
this(new ItemStack(Items.EMERALD, emeralds), forSale, maxTrades, xp, mult);
|
||||
}
|
||||
|
||||
public BasicItemListing(int emeralds, ItemStack forSale, int maxTrades, int xp)
|
||||
{
|
||||
this(new ItemStack(Items.EMERALD, emeralds), forSale, maxTrades, xp, 1);
|
||||
}
|
||||
|
||||
@org.jetbrains.annotations.Nullable
|
||||
@Override
|
||||
public MerchantOffer getOffer(Entity p_219693_, RandomSource p_219694_) {
|
||||
return new MerchantOffer(price, price2, forSale, maxTrades, xp, priceMult);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ package net.minecraftforge.common;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
@@ -23,6 +24,7 @@ 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.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
@@ -46,24 +48,24 @@ import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.NonNullList;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.particles.ParticleTypes;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.chat.ClickEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.MutableComponent;
|
||||
import net.minecraft.network.chat.TextColor;
|
||||
import net.minecraft.network.chat.contents.PlainTextContents.LiteralContents;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap;
|
||||
import net.minecraft.util.ExtraCodecs;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraft.util.Mth;
|
||||
import net.minecraft.util.datafix.fixes.StructuresBecomeConfiguredFix;
|
||||
import net.minecraft.world.Difficulty;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.effect.MobEffectUtil;
|
||||
@@ -73,22 +75,15 @@ import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.entity.ExperienceOrb;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.ai.Brain;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
|
||||
import net.minecraft.world.entity.ai.attributes.DefaultAttributes;
|
||||
import net.minecraft.world.entity.monster.EnderMan;
|
||||
import net.minecraft.world.entity.SlotAccess;
|
||||
import net.minecraft.world.inventory.ClickAction;
|
||||
import net.minecraft.world.inventory.ContainerLevelAccess;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.item.enchantment.Enchantments;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
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;
|
||||
@@ -108,20 +103,16 @@ import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.syncher.EntityDataSerializer;
|
||||
import net.minecraft.network.protocol.game.ClientGamePacketListener;
|
||||
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
|
||||
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
|
||||
import net.minecraft.world.item.alchemy.Potion;
|
||||
import net.minecraft.world.item.alchemy.PotionUtils;
|
||||
import net.minecraft.stats.Stats;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraft.world.level.block.entity.FurnaceBlockEntity;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import net.minecraft.world.level.biome.BiomeGenerationSettings;
|
||||
import net.minecraft.world.level.biome.MobSpawnSettings;
|
||||
import net.minecraftforge.common.crafting.conditions.ConditionCodec;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition.IContext;
|
||||
import net.minecraftforge.common.crafting.ingredients.IIngredientSerializer;
|
||||
@@ -133,22 +124,17 @@ import net.minecraftforge.common.util.MutableHashedLinkedMap;
|
||||
import net.minecraftforge.entity.IEntityAdditionalSpawnData;
|
||||
import net.minecraftforge.event.AnvilUpdateEvent;
|
||||
import net.minecraftforge.event.BuildCreativeModeTabContentsEvent;
|
||||
import net.minecraftforge.event.DifficultyChangeEvent;
|
||||
import net.minecraftforge.event.ForgeEventFactory;
|
||||
import net.minecraftforge.event.GrindstoneEvent;
|
||||
import net.minecraftforge.event.ItemAttributeModifierEvent;
|
||||
import net.minecraftforge.event.ItemStackedOnOtherEvent;
|
||||
import net.minecraftforge.event.ModMismatchEvent;
|
||||
import net.minecraftforge.event.ServerChatEvent;
|
||||
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.item.ItemTossEvent;
|
||||
import net.minecraftforge.event.entity.living.EnderManAngerEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingAttackEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingBreatheEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingChangeTargetEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingDamageEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingDeathEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingDropsEvent;
|
||||
@@ -156,18 +142,14 @@ import net.minecraftforge.event.entity.living.LivingDrownEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingEvent.LivingJumpEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingEvent.LivingTickEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingChangeTargetEvent.ILivingTargetType;
|
||||
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.LivingUseTotemEvent;
|
||||
import net.minecraftforge.event.entity.living.LootingLevelEvent;
|
||||
import net.minecraftforge.event.entity.player.AnvilRepairEvent;
|
||||
import net.minecraftforge.event.entity.player.AttackEntityEvent;
|
||||
import net.minecraftforge.event.entity.player.CriticalHitEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingGetProjectileEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.minecraftforge.event.level.BlockEvent;
|
||||
import net.minecraftforge.event.level.NoteBlockEvent;
|
||||
import net.minecraftforge.event.network.CustomPayloadEvent;
|
||||
@@ -197,7 +179,7 @@ import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
@@ -213,15 +195,18 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/** FOR INTERNAL USE ONLY, DO NOT CALL DIRECTLY */
|
||||
@ApiStatus.Internal
|
||||
public class ForgeHooks {
|
||||
public final class ForgeHooks {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
@SuppressWarnings("unused")
|
||||
private static final Marker FORGEHOOKS = MarkerManager.getMarker("FORGEHOOKS");
|
||||
private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP");
|
||||
|
||||
private ForgeHooks() {}
|
||||
|
||||
public static boolean canContinueUsing(@NotNull ItemStack from, @NotNull ItemStack to) {
|
||||
if (!from.isEmpty() && !to.isEmpty())
|
||||
if (!from.isEmpty() && !to.isEmpty()) {
|
||||
return from.getItem().canContinueUsing(from, to);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -232,21 +217,6 @@ public class ForgeHooks {
|
||||
return player.hasCorrectToolForDrops(state);
|
||||
}
|
||||
|
||||
public static boolean onItemStackedOn(ItemStack carriedItem, ItemStack stackedOnItem, Slot slot, ClickAction action, Player player, SlotAccess carriedSlotAccess) {
|
||||
return MinecraftForge.EVENT_BUS.post(new ItemStackedOnOtherEvent(carriedItem, stackedOnItem, slot, action, player, carriedSlotAccess));
|
||||
}
|
||||
|
||||
public static void onDifficultyChange(Difficulty difficulty, Difficulty oldDifficulty) {
|
||||
MinecraftForge.EVENT_BUS.post(new DifficultyChangeEvent(difficulty, oldDifficulty));
|
||||
}
|
||||
|
||||
public static LivingChangeTargetEvent onLivingChangeTarget(LivingEntity entity, LivingEntity originalTarget, ILivingTargetType targetType) {
|
||||
LivingChangeTargetEvent event = new LivingChangeTargetEvent(entity, originalTarget, targetType);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
public static Brain<?> onLivingMakeBrain(LivingEntity entity, Brain<?> originalBrain, Dynamic<?> dynamic) {
|
||||
BrainBuilder<?> brainBuilder = originalBrain.createBuilder();
|
||||
LivingMakeBrainEvent event = new LivingMakeBrainEvent(entity, brainBuilder);
|
||||
@@ -266,12 +236,6 @@ public class ForgeHooks {
|
||||
return !MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
|
||||
}
|
||||
|
||||
public static LivingKnockBackEvent onLivingKnockBack(LivingEntity target, float strength, double ratioX, double ratioZ) {
|
||||
LivingKnockBackEvent event = new LivingKnockBackEvent(target, strength, ratioX, ratioZ);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
public static boolean onLivingUseTotem(LivingEntity entity, DamageSource damageSource, ItemStack totem, InteractionHand hand) {
|
||||
return !MinecraftForge.EVENT_BUS.post(new LivingUseTotemEvent(entity, damageSource, totem, hand));
|
||||
}
|
||||
@@ -362,10 +326,6 @@ public class ForgeHooks {
|
||||
return event.getEntity();
|
||||
}
|
||||
|
||||
public static boolean onVanillaGameEvent(Level level, GameEvent vanillaEvent, Vec3 pos, GameEvent.Context context) {
|
||||
return !MinecraftForge.EVENT_BUS.post(new VanillaGameEvent(level, vanillaEvent, pos, context));
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static Component onServerChatSubmittedEvent(ServerPlayer player, Component message) {
|
||||
var plain = message.getContents() instanceof LiteralContents literalContents ? literalContents.text() : "";
|
||||
@@ -395,7 +355,7 @@ public class ForgeHooks {
|
||||
|
||||
// Append the previous left overs.
|
||||
String part = string.substring(lastEnd, start);
|
||||
if (part.length() > 0) {
|
||||
if (!part.isEmpty()) {
|
||||
if (ichat == null)
|
||||
ichat = Component.literal(part);
|
||||
else
|
||||
@@ -436,13 +396,13 @@ public class ForgeHooks {
|
||||
String end = string.substring(lastEnd);
|
||||
if (ichat == null)
|
||||
ichat = Component.literal(end);
|
||||
else if (end.length() > 0)
|
||||
else if (!end.isEmpty())
|
||||
ichat.append(Component.literal(string.substring(lastEnd)));
|
||||
return ichat;
|
||||
}
|
||||
|
||||
public static void dropXpForBlock(BlockState state, ServerLevel level, BlockPos pos, ItemStack stack) {
|
||||
int fortuneLevel = stack.getEnchantmentLevel(Enchantments.BLOCK_FORTUNE);
|
||||
int fortuneLevel = stack.getEnchantmentLevel(Enchantments.FORTUNE);
|
||||
int silkTouchLevel = stack.getEnchantmentLevel(Enchantments.SILK_TOUCH);
|
||||
int exp = state.getExpDrop(level, level.random, pos, fortuneLevel, silkTouchLevel);
|
||||
if (exp > 0)
|
||||
@@ -453,26 +413,23 @@ public class ForgeHooks {
|
||||
// Logic from tryHarvestBlock for pre-canceling the event
|
||||
boolean preCancelEvent = false;
|
||||
ItemStack itemstack = entityPlayer.getMainHandItem();
|
||||
if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer))
|
||||
if (!itemstack.isEmpty() && !itemstack.getItem().canAttackBlock(level.getBlockState(pos), level, pos, entityPlayer)) {
|
||||
preCancelEvent = true;
|
||||
|
||||
if (gameType.isBlockPlacingRestricted()) {
|
||||
if (gameType == GameType.SPECTATOR)
|
||||
preCancelEvent = true;
|
||||
|
||||
if (!entityPlayer.mayBuild()) {
|
||||
if (itemstack.isEmpty() || !itemstack.hasAdventureModeBreakTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, pos, false)))
|
||||
preCancelEvent = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Tell client the block is gone immediately then process events
|
||||
if (level.getBlockEntity(pos) == null)
|
||||
entityPlayer.connection.send(new ClientboundBlockUpdatePacket(pos, level.getFluidState(pos).createLegacyBlock()));
|
||||
if (entityPlayer.blockActionRestricted(level, pos, gameType)) {
|
||||
preCancelEvent = true;
|
||||
}
|
||||
|
||||
// Post the block break event
|
||||
BlockState state = level.getBlockState(pos);
|
||||
BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(level, pos, state, entityPlayer);
|
||||
|
||||
// Tell client the block is gone immediately then process events
|
||||
if (level.getBlockEntity(pos) == null) {
|
||||
level.sendBlockUpdated(pos, state, state, 3);
|
||||
}
|
||||
|
||||
var event = new BlockEvent.BreakEvent(level, pos, state, entityPlayer);
|
||||
event.setCanceled(preCancelEvent);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
|
||||
@@ -497,39 +454,29 @@ public class ForgeHooks {
|
||||
Level level = context.getLevel();
|
||||
|
||||
Player player = context.getPlayer();
|
||||
if (player != null && !player.getAbilities().mayBuild && !itemstack.hasAdventureModePlaceTagForBlock(level.registryAccess().registryOrThrow(Registries.BLOCK), new BlockInWorld(level, context.getClickedPos(), false)))
|
||||
if (player != null && !player.getAbilities().mayBuild && !itemstack.canPlaceOnBlockInAdventureMode(new BlockInWorld(level, context.getClickedPos(), false))) {
|
||||
return InteractionResult.PASS;
|
||||
}
|
||||
|
||||
// handle all placement events here
|
||||
Item item = itemstack.getItem();
|
||||
int size = itemstack.getCount();
|
||||
CompoundTag nbt = null;
|
||||
if (itemstack.getTag() != null)
|
||||
nbt = itemstack.getTag().copy();
|
||||
|
||||
if (!(itemstack.getItem() instanceof BucketItem)) // if not bucket
|
||||
level.captureBlockSnapshots = true;
|
||||
|
||||
ItemStack copy = itemstack.copy();
|
||||
ItemStack preUse = itemstack.copy();
|
||||
InteractionResult ret = itemstack.getItem().useOn(context);
|
||||
if (itemstack.isEmpty())
|
||||
ForgeEventFactory.onPlayerDestroyItem(player, copy, context.getHand());
|
||||
ForgeEventFactory.onPlayerDestroyItem(player, preUse, context.getHand());
|
||||
|
||||
level.captureBlockSnapshots = false;
|
||||
|
||||
if (ret.consumesAction()) {
|
||||
// save new item data
|
||||
int newSize = itemstack.getCount();
|
||||
CompoundTag newNBT = null;
|
||||
if (itemstack.getTag() != null)
|
||||
newNBT = itemstack.getTag().copy();
|
||||
@SuppressWarnings("unchecked")
|
||||
List<BlockSnapshot> blockSnapshots = (List<BlockSnapshot>)level.capturedBlockSnapshots.clone();
|
||||
var postUse = itemstack.copy();
|
||||
|
||||
var blockSnapshots = new ArrayList<>(level.capturedBlockSnapshots);
|
||||
level.capturedBlockSnapshots.clear();
|
||||
|
||||
// make sure to set pre-placement item data for event
|
||||
itemstack.setCount(size);
|
||||
itemstack.setTag(nbt);
|
||||
player.setItemInHand(context.getHand(), preUse);
|
||||
|
||||
Direction side = context.getClickedFace();
|
||||
|
||||
@@ -549,8 +496,8 @@ public class ForgeHooks {
|
||||
}
|
||||
} else {
|
||||
// Change the stack to its new content
|
||||
itemstack.setCount(newSize);
|
||||
itemstack.setTag(newNBT);
|
||||
if (!player.isCreative())
|
||||
player.setItemInHand(context.getHand(), postUse);
|
||||
|
||||
for (BlockSnapshot snap : blockSnapshots) {
|
||||
int updateFlag = snap.getFlag();
|
||||
@@ -561,7 +508,7 @@ public class ForgeHooks {
|
||||
level.markAndNotifyBlock(snap.getPos(), level.getChunkAt(snap.getPos()), oldBlock, newBlock, updateFlag, 512);
|
||||
}
|
||||
if (player != null)
|
||||
player.awardStat(Stats.ITEM_USED.get(item));
|
||||
player.awardStat(Stats.ITEM_USED.get(preUse.getItem()));
|
||||
}
|
||||
}
|
||||
level.capturedBlockSnapshots.clear();
|
||||
@@ -569,35 +516,17 @@ public class ForgeHooks {
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, int baseCost, Player player) {
|
||||
public static boolean onAnvilChange(AnvilMenu container, @NotNull ItemStack left, @NotNull ItemStack right, Container outputSlot, String name, long baseCost, Player player) {
|
||||
AnvilUpdateEvent e = new AnvilUpdateEvent(left, right, name, baseCost, player);
|
||||
if (MinecraftForge.EVENT_BUS.post(e)) return false;
|
||||
if (e.getOutput().isEmpty()) return true;
|
||||
|
||||
outputSlot.setItem(0, e.getOutput());
|
||||
container.setMaximumCost(e.getCost());
|
||||
container.setMaximumCost((int)e.getCost());
|
||||
container.repairItemCountCost = e.getMaterialCost();
|
||||
return false;
|
||||
}
|
||||
|
||||
public static float onAnvilRepair(Player player, @NotNull ItemStack output, @NotNull ItemStack left, @NotNull ItemStack right) {
|
||||
AnvilRepairEvent e = new AnvilRepairEvent(player, left, right, output);
|
||||
MinecraftForge.EVENT_BUS.post(e);
|
||||
return e.getBreakChance();
|
||||
}
|
||||
|
||||
public static int onGrindstoneChange(@NotNull ItemStack top, @NotNull ItemStack bottom, Container outputSlot, int xp) {
|
||||
GrindstoneEvent.OnPlaceItem e = new GrindstoneEvent.OnPlaceItem(top, bottom, xp);
|
||||
if (MinecraftForge.EVENT_BUS.post(e)) {
|
||||
outputSlot.setItem(0, ItemStack.EMPTY);
|
||||
return -1;
|
||||
}
|
||||
if (e.getOutput().isEmpty()) return Integer.MIN_VALUE;
|
||||
|
||||
outputSlot.setItem(0, e.getOutput());
|
||||
return e.getXp();
|
||||
}
|
||||
|
||||
public static boolean onGrindstoneTake(Container inputSlots, ContainerLevelAccess access, Function<Level, Integer> xpFunction) {
|
||||
access.execute((l,p) -> {
|
||||
int xp = xpFunction.apply(l);
|
||||
@@ -616,13 +545,13 @@ public class ForgeHooks {
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ThreadLocal<Player> craftingPlayer = new ThreadLocal<Player>();
|
||||
private static final ThreadLocal<Player> CRAFTING_PLAYER = new ThreadLocal<>();
|
||||
public static void setCraftingPlayer(Player player) {
|
||||
craftingPlayer.set(player);
|
||||
CRAFTING_PLAYER.set(player);
|
||||
}
|
||||
|
||||
public static Player getCraftingPlayer() {
|
||||
return craftingPlayer.get();
|
||||
return CRAFTING_PLAYER.get();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@@ -630,7 +559,7 @@ public class ForgeHooks {
|
||||
if (stack.getItem().hasCraftingRemainingItem(stack)) {
|
||||
stack = stack.getItem().getCraftingRemainingItem(stack);
|
||||
if (!stack.isEmpty() && stack.isDamageableItem() && stack.getDamageValue() > stack.getMaxDamage()) {
|
||||
ForgeEventFactory.onPlayerDestroyItem(craftingPlayer.get(), stack, null);
|
||||
ForgeEventFactory.onPlayerDestroyItem(CRAFTING_PLAYER.get(), stack, (EquipmentSlot)null);
|
||||
return ItemStack.EMPTY;
|
||||
}
|
||||
return stack;
|
||||
@@ -644,55 +573,11 @@ public class ForgeHooks {
|
||||
return stack.isEmpty() || !stack.getItem().onLeftClickEntity(stack, player, target);
|
||||
}
|
||||
|
||||
public static InteractionResult onInteractEntityAt(Player player, Entity entity, HitResult ray, InteractionHand hand) {
|
||||
Vec3 vec3d = ray.getLocation().subtract(entity.position());
|
||||
return onInteractEntityAt(player, entity, vec3d, hand);
|
||||
}
|
||||
|
||||
public static InteractionResult onInteractEntityAt(Player player, Entity entity, Vec3 vec3d, InteractionHand hand) {
|
||||
PlayerInteractEvent.EntityInteractSpecific evt = new PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3d);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
return evt.isCanceled() ? evt.getCancellationResult() : null;
|
||||
}
|
||||
|
||||
public static InteractionResult onInteractEntity(Player player, Entity entity, InteractionHand hand) {
|
||||
PlayerInteractEvent.EntityInteract evt = new PlayerInteractEvent.EntityInteract(player, hand, entity);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
return evt.isCanceled() ? evt.getCancellationResult() : null;
|
||||
}
|
||||
|
||||
public static InteractionResult onItemRightClick(Player player, InteractionHand hand) {
|
||||
PlayerInteractEvent.RightClickItem evt = new PlayerInteractEvent.RightClickItem(player, hand);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
var evt = ForgeEventFactory.onRightClickItem(player, hand);
|
||||
return evt.isCanceled() ? evt.getCancellationResult() : null;
|
||||
}
|
||||
|
||||
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);
|
||||
return evt;
|
||||
}
|
||||
|
||||
public static PlayerInteractEvent.LeftClickBlock onClientMineHold(Player player, BlockPos pos, Direction face) {
|
||||
PlayerInteractEvent.LeftClickBlock evt = new PlayerInteractEvent.LeftClickBlock(player, pos, face, PlayerInteractEvent.LeftClickBlock.Action.CLIENT_HOLD);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
return evt;
|
||||
}
|
||||
|
||||
public static PlayerInteractEvent.RightClickBlock onRightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) {
|
||||
PlayerInteractEvent.RightClickBlock evt = new PlayerInteractEvent.RightClickBlock(player, hand, pos, hitVec);
|
||||
MinecraftForge.EVENT_BUS.post(evt);
|
||||
return evt;
|
||||
}
|
||||
|
||||
public static void onEmptyClick(Player player, InteractionHand hand) {
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.RightClickEmpty(player, hand));
|
||||
}
|
||||
|
||||
public static void onEmptyLeftClick(Player player) {
|
||||
MinecraftForge.EVENT_BUS.post(new PlayerInteractEvent.LeftClickEmpty(player));
|
||||
}
|
||||
|
||||
public static GameType onChangeGameType(Player player, GameType currentGameType, GameType newGameType) {
|
||||
if (currentGameType == newGameType)
|
||||
return currentGameType;
|
||||
@@ -740,6 +625,7 @@ public class ForgeHooks {
|
||||
throw new RuntimeException("Mod fluids must override getFluidType.");
|
||||
}
|
||||
|
||||
/*
|
||||
public static TagKey<Block> getTagFromVanillaTier(Tiers tier) {
|
||||
return switch(tier) {
|
||||
case WOOD -> Tags.Blocks.NEEDS_WOOD_TOOL;
|
||||
@@ -750,6 +636,7 @@ public class ForgeHooks {
|
||||
case NETHERITE -> Tags.Blocks.NEEDS_NETHERITE_TOOL;
|
||||
};
|
||||
}
|
||||
*/
|
||||
|
||||
@FunctionalInterface
|
||||
public interface BiomeCallbackFunction {
|
||||
@@ -775,15 +662,6 @@ public class ForgeHooks {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fire {@link ItemAttributeModifierEvent}. Modders should use {@link ItemStack#getAttributeModifiers(EquipmentSlot)} instead.
|
||||
*/
|
||||
public static Multimap<Attribute,AttributeModifier> getAttributeModifiers(ItemStack stack, EquipmentSlot equipmentSlot, Multimap<Attribute,AttributeModifier> attributes) {
|
||||
ItemAttributeModifierEvent event = new ItemAttributeModifierEvent(stack, equipmentSlot, attributes);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
return event.getModifiers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fire {@link LivingGetProjectileEvent}. Returns the ammo to be used.
|
||||
*/
|
||||
@@ -803,20 +681,19 @@ public class ForgeHooks {
|
||||
String modId = registryName == null ? null : registryName.getNamespace();
|
||||
if ("minecraft".equals(modId)) {
|
||||
if (item instanceof EnchantedBookItem) {
|
||||
ListTag enchantmentsNbt = EnchantedBookItem.getEnchantments(itemStack);
|
||||
if (enchantmentsNbt.size() == 1) {
|
||||
CompoundTag nbttagcompound = enchantmentsNbt.getCompound(0);
|
||||
ResourceLocation resourceLocation = ResourceLocation.tryParse(nbttagcompound.getString("id"));
|
||||
if (resourceLocation != null && ForgeRegistries.ENCHANTMENTS.containsKey(resourceLocation))
|
||||
return resourceLocation.getNamespace();
|
||||
var enchants = EnchantmentHelper.getEnchantmentsForCrafting(itemStack);
|
||||
if (enchants.size() == 1) {
|
||||
var enchant = enchants.keySet().iterator().next();
|
||||
var name = enchant.unwrapKey();
|
||||
if (name.isPresent())
|
||||
return name.get().location().getNamespace();
|
||||
}
|
||||
} else if (item instanceof PotionItem || item instanceof TippedArrowItem) {
|
||||
Potion potionType = PotionUtils.getPotion(itemStack);
|
||||
ResourceLocation resourceLocation = ForgeRegistries.POTIONS.getKey(potionType);
|
||||
if (resourceLocation != null)
|
||||
return resourceLocation.getNamespace();
|
||||
} else if (itemStack.has(DataComponents.POTION_CONTENTS)) {
|
||||
var potion = itemStack.get(DataComponents.POTION_CONTENTS).potion().orElse(null);
|
||||
if (potion != null && potion.unwrapKey().isPresent())
|
||||
return potion.unwrapKey().get().location().getNamespace();
|
||||
} else if (item instanceof SpawnEggItem egg) {
|
||||
ResourceLocation resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(egg.getType(null));
|
||||
var resourceLocation = ForgeRegistries.ENTITY_TYPES.getKey(egg.getType(null));
|
||||
if (resourceLocation != null)
|
||||
return resourceLocation.getNamespace();
|
||||
}
|
||||
@@ -1167,7 +1044,7 @@ public class ForgeHooks {
|
||||
@ApiStatus.Internal
|
||||
public static <T> HolderLookup.RegistryLookup<T> wrapRegistryLookup(final HolderLookup.RegistryLookup<T> lookup) {
|
||||
return new HolderLookup.RegistryLookup.Delegate<>() {
|
||||
@Override protected RegistryLookup<T> parent() { return lookup; }
|
||||
@Override public RegistryLookup<T> parent() { return lookup; }
|
||||
@Override public Stream<HolderSet.Named<T>> listTags() { return Stream.empty(); }
|
||||
@SuppressWarnings("deprecation")
|
||||
@Override public Optional<HolderSet.Named<T>> get(TagKey<T> key) { return Optional.of(HolderSet.emptyNamed(lookup, key)); }
|
||||
@@ -1188,18 +1065,18 @@ public class ForgeHooks {
|
||||
// Check things that vanilla considers to be air - these will cause the air supply to be increased.
|
||||
boolean isAir = entity.getEyeInFluidType().isAir() || entity.level().getBlockState(BlockPos.containing(entity.getX(), entity.getEyeY(), entity.getZ())).is(Blocks.BUBBLE_COLUMN);
|
||||
// The following effects cause the entity to not drown, but do not cause the air supply to be increased.
|
||||
boolean canBreathe = !entity.canDrownInFluidType(entity.getEyeInFluidType()) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player && ((Player) entity).getAbilities().invulnerable);
|
||||
LivingBreatheEvent breatheEvent = new LivingBreatheEvent(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir);
|
||||
MinecraftForge.EVENT_BUS.post(breatheEvent);
|
||||
boolean canBreathe = !entity.canDrownInFluidType(entity.getEyeInFluidType()) || MobEffectUtil.hasWaterBreathing(entity) || (entity instanceof Player player && player.getAbilities().invulnerable);
|
||||
var breatheEvent = ForgeEventFactory.onLivingBreathe(entity, isAir || canBreathe, consumeAirAmount, refillAirAmount, isAir);
|
||||
if (breatheEvent.canBreathe()) {
|
||||
if (breatheEvent.canRefillAir())
|
||||
if (breatheEvent.canRefillAir()) {
|
||||
entity.setAirSupply(Math.min(entity.getAirSupply() + breatheEvent.getRefillAirAmount(), entity.getMaxAirSupply()));
|
||||
}
|
||||
} else
|
||||
entity.setAirSupply(entity.getAirSupply() - breatheEvent.getConsumeAirAmount());
|
||||
|
||||
if (entity.getAirSupply() <= 0) {
|
||||
LivingDrownEvent drownEvent = new LivingDrownEvent(entity, entity.getAirSupply() <= -20, 2.0F, 8);
|
||||
if (!MinecraftForge.EVENT_BUS.post(drownEvent) && drownEvent.isDrowning()) {
|
||||
if (entity.getAirSupply() <= -20) {
|
||||
var drownEvent = ForgeEventFactory.onLivingDrown(entity, entity.getAirSupply() <= -20, 2.0F, 8);
|
||||
if (!drownEvent.isCanceled() && drownEvent.isDrowning()) {
|
||||
entity.setAirSupply(0);
|
||||
Vec3 vec3 = entity.getDeltaMovement();
|
||||
|
||||
@@ -1210,12 +1087,15 @@ public class ForgeHooks {
|
||||
entity.level().addParticle(ParticleTypes.BUBBLE, entity.getX() + d2, entity.getY() + d3, entity.getZ() + d4, vec3.x, vec3.y, vec3.z);
|
||||
}
|
||||
|
||||
if (drownEvent.getDamageAmount() > 0) entity.hurt(entity.damageSources().drown(), drownEvent.getDamageAmount());
|
||||
if (drownEvent.getDamageAmount() > 0) {
|
||||
entity.hurt(entity.damageSources().drown(), drownEvent.getDamageAmount());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAir && !entity.level().isClientSide && entity.isPassenger() && entity.getVehicle() != null && !entity.getVehicle().canBeRiddenUnderFluidType(entity.getEyeInFluidType(), entity))
|
||||
if (!isAir && !entity.level().isClientSide && entity.isPassenger() && entity.getVehicle() != null && !entity.getVehicle().canBeRiddenUnderFluidType(entity.getEyeInFluidType(), entity)) {
|
||||
entity.stopRiding();
|
||||
}
|
||||
}
|
||||
|
||||
public static void onCreativeModeTabBuildContents(CreativeModeTab tab, ResourceKey<CreativeModeTab> tabKey, CreativeModeTab.DisplayItemsGenerator originalGenerator, CreativeModeTab.ItemDisplayParameters params, CreativeModeTab.Output output) {
|
||||
@@ -1289,30 +1169,27 @@ public class ForgeHooks {
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static boolean readAndTestCondition(@Nullable ICondition.IContext context, JsonObject json) {
|
||||
if (context == null)
|
||||
context = IContext.EMPTY;
|
||||
|
||||
public static boolean readAndTestCondition(RegistryOps<JsonElement> ops, JsonObject json) {
|
||||
if (!json.has(ICondition.DEFAULT_FIELD))
|
||||
return true;
|
||||
|
||||
var condition = Util.getOrThrow(ICondition.SAFE_CODEC.parse(JsonOps.INSTANCE, json.getAsJsonObject(ICondition.DEFAULT_FIELD)), JsonParseException::new);
|
||||
return condition.test(context);
|
||||
var condition = ICondition.SAFE_CODEC.parse(ops, json.getAsJsonObject(ICondition.DEFAULT_FIELD))
|
||||
.getOrThrow(JsonParseException::new);
|
||||
|
||||
return condition.test(ConditionCodec.getContext(ops), ops);
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static void writeCondition(ICondition condition, JsonObject out) {
|
||||
if (condition == null)
|
||||
return;
|
||||
var data = ICondition.CODEC.encode(condition, JsonOps.INSTANCE, JsonOps.INSTANCE.empty()).getOrThrow(false, JsonSyntaxException::new);
|
||||
var data = ICondition.CODEC.encode(condition, JsonOps.INSTANCE, JsonOps.INSTANCE.empty()).getOrThrow(JsonSyntaxException::new);
|
||||
out.add(ICondition.DEFAULT_FIELD, data);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@ApiStatus.Internal
|
||||
public static JsonObject readConditionalAdvancement(@Nullable ICondition.IContext context, JsonObject json) {
|
||||
if (context == null)
|
||||
context = IContext.EMPTY;
|
||||
public static JsonObject readConditionalAdvancement(RegistryOps<JsonElement> context, JsonObject json) {
|
||||
var entries = GsonHelper.getAsJsonArray(json, "advancements", null);
|
||||
if (entries == null)
|
||||
return readAndTestCondition(context, json) ? json : null;
|
||||
@@ -1333,8 +1210,8 @@ public class ForgeHooks {
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static Codec<Ingredient> enhanceIngredientCodec(Codec<Ingredient> vanilla) {
|
||||
return ExtraCodecs.lazyInitializedCodec(() ->
|
||||
ExtraCodecs.<Ingredient, Ingredient>either(
|
||||
return Codec.lazyInitialized(() ->
|
||||
Codec.<Ingredient, Ingredient>either(
|
||||
ForgeRegistries.INGREDIENT_SERIALIZERS.get().getCodec().dispatch(Ingredient::serializer, IIngredientSerializer::codec),
|
||||
vanilla
|
||||
)
|
||||
@@ -1345,29 +1222,43 @@ public class ForgeHooks {
|
||||
);
|
||||
}
|
||||
|
||||
@ApiStatus.Internal
|
||||
public static <T extends Ingredient> boolean ingredientToNetwork(FriendlyByteBuf buffer, T ingredient) {
|
||||
if (ingredient.isVanilla())
|
||||
return true;
|
||||
public static StreamCodec<RegistryFriendlyByteBuf, Ingredient> ingredientStreamCodec() {
|
||||
return StreamCodec.<RegistryFriendlyByteBuf, Ingredient>of(
|
||||
(buf, value) -> {
|
||||
if (value.isVanilla()) {
|
||||
var items = value.getItems();
|
||||
ByteBufCodecs.writeCount(buf, items.length, Integer.MAX_VALUE);
|
||||
for (var item : items) {
|
||||
ItemStack.STREAM_CODEC.encode(buf, item);
|
||||
}
|
||||
} else {
|
||||
@SuppressWarnings("unchecked")
|
||||
var serializer = (IIngredientSerializer<Ingredient>)value.serializer();
|
||||
var key = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getKey(serializer);
|
||||
if (key == null)
|
||||
throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + value);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
var serializer = (IIngredientSerializer<T>)ingredient.serializer();
|
||||
var key = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getKey(ingredient.serializer());
|
||||
if (key == null)
|
||||
throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + ingredient);
|
||||
|
||||
buffer.writeVarInt(-1); // Our Marker
|
||||
buffer.writeResourceLocation(key);
|
||||
serializer.write(buffer, ingredient);
|
||||
return false;
|
||||
}
|
||||
|
||||
public static Ingredient ingredientFromNetwork(FriendlyByteBuf buffer) {
|
||||
// We have already read our marker
|
||||
var key = buffer.readResourceLocation();
|
||||
var serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
|
||||
if (serializer == null)
|
||||
throw new DecoderException("Could not read ingredient of type: " + key);
|
||||
return serializer.read(buffer);
|
||||
buf.writeVarInt(-1); // Our Marker
|
||||
buf.writeResourceLocation(key);
|
||||
serializer.write(buf, value);
|
||||
}
|
||||
},
|
||||
(buf) -> {
|
||||
var size = ByteBufCodecs.readCount(buf, Integer.MAX_VALUE);
|
||||
if (size != -1) {
|
||||
var ret = NonNullList.<ItemStack>createWithCapacity(size);
|
||||
for (int x = 0; x < size; x++) {
|
||||
ret.add(ItemStack.STREAM_CODEC.decode(buf));
|
||||
}
|
||||
return Ingredient.fromValues(ret.stream().map(Ingredient.ItemValue::new));
|
||||
} else {
|
||||
var key = buf.readResourceLocation();
|
||||
var serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
|
||||
if (serializer == null)
|
||||
throw new DecoderException("Could not read ingredient of type: " + key);
|
||||
return serializer.read(buf);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,6 @@ public class ForgeInternalHandler {
|
||||
|
||||
@SubscribeEvent
|
||||
public void resourceReloadListeners(AddReloadListenerEvent event) {
|
||||
event.addListener(TierSortingRegistry.getReloadListener());
|
||||
event.addListener(CreativeModeTabRegistry.getReloadListener());
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,10 @@ import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.metadata.PackMetadataGenerator;
|
||||
import net.minecraft.network.chat.ChatType;
|
||||
import net.minecraft.network.chat.ChatTypeDecoration;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.chat.Style;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.metadata.pack.PackMetadataSection;
|
||||
import net.minecraft.sounds.SoundEvents;
|
||||
@@ -36,7 +39,7 @@ import net.minecraft.world.level.material.Fluid;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.pathfinder.BlockPathTypes;
|
||||
import net.minecraft.world.level.pathfinder.PathType;
|
||||
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions;
|
||||
@@ -46,8 +49,6 @@ import net.minecraftforge.common.data.ForgeFluidTagsProvider;
|
||||
import net.minecraftforge.common.data.ForgeLootTableProvider;
|
||||
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;
|
||||
@@ -116,6 +117,8 @@ import org.apache.logging.log4j.Marker;
|
||||
import org.apache.logging.log4j.MarkerManager;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
@@ -150,32 +153,8 @@ public class ForgeMod {
|
||||
private static final DeferredRegister<Attribute> ATTRIBUTES = deferred(ForgeRegistries.Keys.ATTRIBUTES);
|
||||
public static final RegistryObject<Attribute> SWIM_SPEED = ATTRIBUTES.register("swim_speed", () -> new RangedAttribute("forge.swim_speed", 1.0D, 0.0D, 1024.0D).setSyncable(true));
|
||||
public static final RegistryObject<Attribute> NAMETAG_DISTANCE = ATTRIBUTES.register("nametag_distance", () -> new RangedAttribute("forge.name_tag_distance", 64.0D, 0.0D, 64.0).setSyncable(true));
|
||||
public static final RegistryObject<Attribute> ENTITY_GRAVITY = ATTRIBUTES.register("entity_gravity", () -> new RangedAttribute("forge.entity_gravity", 0.08D, -8.0D, 8.0D).setSyncable(true));
|
||||
|
||||
/**
|
||||
* Reach Distance represents the distance at which a player may interact with the world. The default is 4.5 blocks. Players in creative mode have an additional 0.5 blocks of block reach.
|
||||
* @see IForgePlayer#getBlockReach()
|
||||
* @see IForgePlayer#canReach(BlockPos, double)
|
||||
*/
|
||||
public static final RegistryObject<Attribute> BLOCK_REACH = ATTRIBUTES.register("block_reach", () -> new RangedAttribute("forge.block_reach", 4.5D, 0.0D, 1024.0D).setSyncable(true));
|
||||
|
||||
/**
|
||||
* Attack Range represents the distance at which a player may attack an entity. The default is 3 blocks. Players in creative mode have an additional 3 blocks of entity reach.
|
||||
* The default of 3.0 is technically considered a bug by Mojang - see MC-172289 and MC-92484. However, updating this value would allow for longer-range attacks on vanilla servers, which makes some people mad.
|
||||
* @see IForgePlayer#getEntityReach()
|
||||
* @see IForgePlayer#canReach(Entity, double)
|
||||
* @see IForgePlayer#canReach(Vec3, double)
|
||||
*/
|
||||
public static final RegistryObject<Attribute> ENTITY_REACH = ATTRIBUTES.register("entity_reach", () -> new RangedAttribute("forge.entity_reach", 3.0D, 0.0D, 1024.0D).setSyncable(true));
|
||||
|
||||
/**
|
||||
* Step Height Addition modifies the amount of blocks an entity may walk up without jumping.
|
||||
* @see IForgeEntity#getStepHeight()
|
||||
*/
|
||||
public static final RegistryObject<Attribute> STEP_HEIGHT_ADDITION = ATTRIBUTES.register("step_height_addition", () -> new RangedAttribute("forge.step_height", 0.0D, -512.0D, 512.0D).setSyncable(true));
|
||||
|
||||
|
||||
private static final DeferredRegister<Codec<? extends BiomeModifier>> BIOME_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS);
|
||||
private static final DeferredRegister<MapCodec<? extends BiomeModifier>> BIOME_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS);
|
||||
static {
|
||||
BIOME_MODIFIER_SERIALIZERS.register("none", () -> NoneBiomeModifier.CODEC);
|
||||
BIOME_MODIFIER_SERIALIZERS.register("add_features", () -> AddFeaturesBiomeModifier.CODEC);
|
||||
@@ -184,7 +163,7 @@ public class ForgeMod {
|
||||
BIOME_MODIFIER_SERIALIZERS.register("remove_spawns", () -> RemoveSpawnsBiomeModifier.CODEC);
|
||||
}
|
||||
|
||||
private static final DeferredRegister<Codec<? extends StructureModifier>> STRUCTURE_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS);
|
||||
private static final DeferredRegister<MapCodec<? extends StructureModifier>> STRUCTURE_MODIFIER_SERIALIZERS = deferred(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS);
|
||||
static {
|
||||
STRUCTURE_MODIFIER_SERIALIZERS.register("none", () -> NoneStructureModifier.CODEC);
|
||||
}
|
||||
@@ -247,7 +226,7 @@ public class ForgeMod {
|
||||
.canHydrate(true))
|
||||
{
|
||||
@Override
|
||||
public @Nullable BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
|
||||
public @Nullable PathType getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
|
||||
return canFluidLog ? super.getBlockPathType(state, level, pos, mob, true) : null;
|
||||
}
|
||||
|
||||
@@ -298,7 +277,7 @@ public class ForgeMod {
|
||||
.descriptionId("block.minecraft.lava")
|
||||
.canSwim(false)
|
||||
.canDrown(false)
|
||||
.pathType(BlockPathTypes.LAVA)
|
||||
.pathType(PathType.LAVA)
|
||||
.adjacentPathType(null)
|
||||
.sound(SoundActions.BUCKET_FILL, SoundEvents.BUCKET_FILL_LAVA)
|
||||
.sound(SoundActions.BUCKET_EMPTY, SoundEvents.BUCKET_EMPTY_LAVA)
|
||||
@@ -343,7 +322,7 @@ public class ForgeMod {
|
||||
LOOT_CONDITION_TYPES.register("can_tool_perform_action", () -> CanToolPerformAction.TYPE);
|
||||
}
|
||||
|
||||
private static final DeferredRegister<Codec<? extends ICondition>> CONDITION_SERIALIZERS = deferred(ForgeRegistries.Keys.CONDITION_SERIALIZERS);
|
||||
private static final DeferredRegister<MapCodec<? extends ICondition>> CONDITION_SERIALIZERS = deferred(ForgeRegistries.Keys.CONDITION_SERIALIZERS);
|
||||
static {
|
||||
CONDITION_SERIALIZERS.register("and", () -> AndCondition.CODEC);
|
||||
CONDITION_SERIALIZERS.register("false", () -> FalseCondition.CODEC);
|
||||
@@ -377,6 +356,12 @@ public class ForgeMod {
|
||||
public static final RegistryObject<Fluid> MILK = RegistryObject.create(new ResourceLocation("milk"), ForgeRegistries.FLUIDS);
|
||||
public static final RegistryObject<Fluid> FLOWING_MILK = RegistryObject.create(new ResourceLocation("flowing_milk"), ForgeRegistries.FLUIDS);
|
||||
|
||||
/*
|
||||
private static final ChatTypeDecoration SYSTEM_CHAT_TYPE_DECORATION = new ChatTypeDecoration("forge.chatType.system", List.of(ChatTypeDecoration.Parameter.CONTENT), Style.EMPTY);
|
||||
private static final DeferredRegister<ChatType> CHAT_TYPES = deferred(Registries.CHAT_TYPE);
|
||||
public static final RegistryObject<ChatType> SYSTEM_CHAT_TYPE = CHAT_TYPES.register("syste_chat", () -> new ChatType(SYSTEM_CHAT_TYPE_DECORATION, SYSTEM_CHAT_TYPE_DECORATION));
|
||||
*/
|
||||
|
||||
private static ForgeMod INSTANCE;
|
||||
public static ForgeMod getInstance() {
|
||||
return INSTANCE;
|
||||
@@ -482,8 +467,8 @@ public class ForgeMod {
|
||||
gen.addProvider(event.includeServer(), new ForgeItemTagsProvider(packOutput, lookupProvider, blockTags.contentsGetter(), existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeEntityTypeTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeFluidTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput));
|
||||
gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput));
|
||||
gen.addProvider(event.includeServer(), new ForgeRecipeProvider(packOutput, lookupProvider));
|
||||
gen.addProvider(event.includeServer(), new ForgeLootTableProvider(packOutput, lookupProvider));
|
||||
gen.addProvider(event.includeServer(), new ForgeBiomeTagsProvider(packOutput, lookupProvider, existingFileHelper));
|
||||
|
||||
gen.addProvider(event.includeClient(), new ForgeSpriteSourceProvider(packOutput, existingFileHelper));
|
||||
|
||||
@@ -7,7 +7,6 @@ package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.dispenser.DispenseItemBehavior;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.MobSpawnType;
|
||||
@@ -42,12 +41,6 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
|
||||
MOD_EGGS.add(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EntityType<?> getType(@Nullable CompoundTag tag) {
|
||||
EntityType<?> type = super.getType(tag);
|
||||
return type != null ? type : typeSupplier.get();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
protected DispenseItemBehavior createDispenseBehavior() {
|
||||
return DEFAULT_DISPENSE_BEHAVIOR;
|
||||
@@ -66,7 +59,7 @@ public class ForgeSpawnEggItem extends SpawnEggItem {
|
||||
|
||||
private static final DispenseItemBehavior DEFAULT_DISPENSE_BEHAVIOR = (source, stack) -> {
|
||||
Direction face = source.state().getValue(DispenserBlock.FACING);
|
||||
EntityType<?> type = ((SpawnEggItem)stack.getItem()).getType(stack.getTag());
|
||||
EntityType<?> type = ((SpawnEggItem)stack.getItem()).getType(stack);
|
||||
|
||||
try {
|
||||
type.spawn(source.level(), stack, null, source.pos().relative(face), MobSpawnType.DISPENSER, face != Direction.UP, false);
|
||||
|
||||
@@ -17,9 +17,7 @@ import java.util.function.Supplier;
|
||||
* Helper class to define a custom tier
|
||||
*/
|
||||
@SuppressWarnings("ClassCanBeRecord") // can't make it a record because the method names will be obfuscated
|
||||
public final class ForgeTier implements Tier
|
||||
{
|
||||
private final int level;
|
||||
public final class ForgeTier implements Tier {
|
||||
private final int uses;
|
||||
private final float speed;
|
||||
private final float attackDamageBonus;
|
||||
@@ -28,72 +26,66 @@ public final class ForgeTier implements Tier
|
||||
private final TagKey<Block> tag;
|
||||
@NotNull
|
||||
private final Supplier<Ingredient> repairIngredient;
|
||||
@NotNull
|
||||
public final TagKey<Block> incorrectBlocks;
|
||||
|
||||
public ForgeTier(int level, int uses, float speed, float attackDamageBonus, int enchantmentValue,
|
||||
@NotNull TagKey<Block> tag, @NotNull Supplier<Ingredient> repairIngredient)
|
||||
{
|
||||
this.level = level;
|
||||
public ForgeTier(int uses, float speed, float attackDamageBonus, int enchantmentValue,
|
||||
@NotNull TagKey<Block> tag, @NotNull Supplier<Ingredient> repairIngredient,
|
||||
@NotNull TagKey<Block> incorrectBlocks) {
|
||||
this.uses = uses;
|
||||
this.speed = speed;
|
||||
this.attackDamageBonus = attackDamageBonus;
|
||||
this.enchantmentValue = enchantmentValue;
|
||||
this.tag = tag;
|
||||
this.repairIngredient = repairIngredient;
|
||||
this.incorrectBlocks = incorrectBlocks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getUses()
|
||||
{
|
||||
public int getUses() {
|
||||
return this.uses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getSpeed()
|
||||
{
|
||||
public float getSpeed() {
|
||||
return this.speed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getAttackDamageBonus()
|
||||
{
|
||||
public float getAttackDamageBonus() {
|
||||
return this.attackDamageBonus;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLevel()
|
||||
{
|
||||
return this.level;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEnchantmentValue()
|
||||
{
|
||||
public int getEnchantmentValue() {
|
||||
return this.enchantmentValue;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public TagKey<Block> getTag()
|
||||
{
|
||||
public TagKey<Block> getTag() {
|
||||
return this.tag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TagKey<Block> getIncorrectBlocksForDrops() {
|
||||
return this.incorrectBlocks;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
public Ingredient getRepairIngredient()
|
||||
{
|
||||
public Ingredient getRepairIngredient() {
|
||||
return this.repairIngredient.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
public String toString() {
|
||||
return "ForgeTier[" +
|
||||
"level=" + level + ", " +
|
||||
"uses=" + uses + ", " +
|
||||
"speed=" + speed + ", " +
|
||||
"attackDamageBonus=" + attackDamageBonus + ", " +
|
||||
"enchantmentValue=" + enchantmentValue + ", " +
|
||||
"tag=" + tag + ", " +
|
||||
"incorrect=" + incorrectBlocks+ ", " +
|
||||
"repairIngredient=" + repairIngredient + ']';
|
||||
}
|
||||
}
|
||||
@@ -47,14 +47,14 @@ public interface IExtensibleEnum {
|
||||
static <E extends Enum<E> & StringRepresentable> Codec<E> createCodecForExtensibleEnum(Supplier<E[]> valuesSupplier, Function<? super String, ? extends E> enumValueFromNameFunction) {
|
||||
return Codec.either(Codec.STRING, Codec.INT).comapFlatMap(
|
||||
either -> either.map(
|
||||
str -> {
|
||||
var val = enumValueFromNameFunction.apply(str);
|
||||
return val != null ? DataResult.success(val) : DataResult.error(() -> "Unknown enum value name: " + str);
|
||||
},
|
||||
num -> {
|
||||
var values = valuesSupplier.get();
|
||||
return num >= 0 && num < values.length ? DataResult.success(values[num]) : DataResult.error(() -> "Unknown enum id: " + num);
|
||||
}
|
||||
str -> {
|
||||
var val = enumValueFromNameFunction.apply(str);
|
||||
return val != null ? DataResult.success(val) : DataResult.error(() -> "Unknown enum value name: " + str);
|
||||
},
|
||||
num -> {
|
||||
var values = valuesSupplier.get();
|
||||
return num >= 0 && num < values.length ? DataResult.success(values[num]) : DataResult.error(() -> "Unknown enum id: " + num);
|
||||
}
|
||||
),
|
||||
value -> Either.left(value.getSerializedName())
|
||||
);
|
||||
|
||||
@@ -52,7 +52,6 @@ public class MinecraftForge
|
||||
LOGGER.info(FORGE,"MinecraftForge v{} Initialized", ForgeVersion.getVersion());
|
||||
|
||||
UsernameCache.load();
|
||||
TierSortingRegistry.init();
|
||||
if (FMLEnvironment.dist == Dist.CLIENT) ClientCommandHandler.init();
|
||||
DualStackUtils.initialise();
|
||||
}
|
||||
|
||||
@@ -1,353 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import com.google.common.collect.*;
|
||||
import com.google.common.graph.ElementOrder;
|
||||
import com.google.common.graph.GraphBuilder;
|
||||
import com.google.common.graph.MutableGraph;
|
||||
import com.google.gson.*;
|
||||
import it.unimi.dsi.fastutil.booleans.BooleanConsumer;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.packs.resources.PreparableReloadListener;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.server.packs.resources.SimplePreparableReloadListener;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraft.util.profiling.ProfilerFiller;
|
||||
import net.minecraft.world.item.DiggerItem;
|
||||
import net.minecraft.world.item.Tier;
|
||||
import net.minecraft.world.item.Tiers;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraftforge.api.distmarker.Dist;
|
||||
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerEvent;
|
||||
import net.minecraftforge.event.network.CustomPayloadEvent;
|
||||
import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import net.minecraftforge.fml.loading.toposort.TopologicalSort;
|
||||
import net.minecraftforge.network.ChannelBuilder;
|
||||
import net.minecraftforge.network.NetworkDirection;
|
||||
import net.minecraftforge.network.PacketDistributor;
|
||||
import net.minecraftforge.network.SimpleChannel;
|
||||
import net.minecraftforge.server.ServerLifecycleHooks;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TierSortingRegistry {
|
||||
private static final Logger LOGGER = LogManager.getLogger();
|
||||
private static final ResourceLocation ITEM_TIER_ORDERING_JSON = new ResourceLocation("forge", "item_tier_ordering.json");
|
||||
|
||||
/**
|
||||
* Registers a tier into the tier sorting registry.
|
||||
* @param tier The tier to register
|
||||
* @param name The name to use internally for dependency resolution
|
||||
* @param after List of tiers to place this tier after (the tiers in the list will be considered lesser tiers)
|
||||
* @param before List of tiers to place this tier before (the tiers in the list will be considered better tiers)
|
||||
*/
|
||||
public static synchronized Tier registerTier(Tier tier, ResourceLocation name, List<Object> after, List<Object> before) {
|
||||
if (tier == null)
|
||||
throw new NullPointerException("Registering a new Tier requires a nonnull tier! ResourceLocation name: " + name);
|
||||
if (tiers.containsKey(name))
|
||||
throw new IllegalStateException("Duplicate tier name " + name);
|
||||
|
||||
processTier(tier, name, after, before);
|
||||
|
||||
hasCustomTiers = true;
|
||||
return tier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of tiers in the order defined by the dependencies.
|
||||
* This list will remain valid
|
||||
* @return An unmodifiable list of tiers ordered lesser to greater
|
||||
*/
|
||||
public static List<Tier> getSortedTiers() {
|
||||
return sortedTiersUnmodifiable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the tier associated with a name, if registered into the sorting system.
|
||||
* @param name The name to look up
|
||||
* @return The tier, or null if not registered
|
||||
*/
|
||||
@Nullable
|
||||
public static Tier byName(ResourceLocation name) {
|
||||
return tiers.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name associated with a tier, if the tier is registered into the sorting system.
|
||||
* @param tier The tier to look up
|
||||
* @return The name for the tier, or null if not registered
|
||||
*/
|
||||
@Nullable
|
||||
public static ResourceLocation getName(Tier tier) {
|
||||
return tiers.inverse().get(tier);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries if a tier should be evaluated using the sorting system, by calling isCorrectTierForDrops
|
||||
* @param tier The tier to query
|
||||
* @return True if isCorrectTierForDrops should be called for the tier
|
||||
*/
|
||||
public static boolean isTierSorted(Tier tier) {
|
||||
return getName(tier) != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries if a tier is high enough to be able to get drops for the given blockstate.
|
||||
* @param tier The tier to look up
|
||||
* @param state The state to test against
|
||||
* @return True if the tier is good enough
|
||||
*/
|
||||
public static boolean isCorrectTierForDrops(Tier tier, BlockState state) {
|
||||
if (!isTierSorted(tier))
|
||||
return isCorrectTierVanilla(tier, state);
|
||||
|
||||
for (int x = sortedTiers.indexOf(tier) + 1; x < sortedTiers.size(); x++) {
|
||||
TagKey<Block> tag = sortedTiers.get(x).getTag();
|
||||
if (tag != null && state.is(tag))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to query all tiers that are lower than the given tier
|
||||
* @param tier The tier
|
||||
* @return All the lower tiers
|
||||
*/
|
||||
public static List<Tier> getTiersLowerThan(Tier tier) {
|
||||
if (!isTierSorted(tier)) return List.of();
|
||||
return sortedTiers.stream().takeWhile(t -> t != tier).toList();
|
||||
}
|
||||
|
||||
// ===================== PRIVATE INTERNAL STUFFS BELOW THIS LINE =====================
|
||||
|
||||
/**
|
||||
* Fallback for when a tier isn't in the registry, copy of the logic in {@link DiggerItem#isCorrectToolForDrops}
|
||||
*/
|
||||
private static boolean isCorrectTierVanilla(Tier tier, BlockState state) {
|
||||
@SuppressWarnings("deprecation")
|
||||
int i = tier.getLevel();
|
||||
if (i < 3 && state.is(BlockTags.NEEDS_DIAMOND_TOOL))
|
||||
return false;
|
||||
else if (i < 2 && state.is(BlockTags.NEEDS_IRON_TOOL))
|
||||
return false;
|
||||
else if (i < 1 && state.is(BlockTags.NEEDS_STONE_TOOL))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void processTier(Tier tier, ResourceLocation name, List<Object> afters, List<Object> befores) {
|
||||
tiers.put(name, tier);
|
||||
for(Object after : afters)
|
||||
edges.put(getTierName(after), name);
|
||||
for(Object before : befores)
|
||||
edges.put(name, getTierName(before));
|
||||
}
|
||||
|
||||
private static ResourceLocation getTierName(Object entry) {
|
||||
if (entry instanceof String s)
|
||||
return new ResourceLocation(s);
|
||||
if (entry instanceof ResourceLocation rl)
|
||||
return rl;
|
||||
if (entry instanceof Tier t)
|
||||
return Objects.requireNonNull(getName(t), "Can't have sorting dependencies for tiers not registered in the TierSortingRegistry");
|
||||
throw new IllegalStateException("Invalid object type passed into the tier dependencies " + entry.getClass());
|
||||
}
|
||||
|
||||
private static boolean hasCustomTiers = false;
|
||||
private static final BiMap<ResourceLocation, Tier> tiers = HashBiMap.create();
|
||||
private static final Multimap<ResourceLocation, ResourceLocation> edges = HashMultimap.create();
|
||||
private static final Multimap<ResourceLocation, ResourceLocation> vanillaEdges = HashMultimap.create();
|
||||
|
||||
static {
|
||||
var wood = new ResourceLocation("wood");
|
||||
var stone = new ResourceLocation("stone");
|
||||
var iron = new ResourceLocation("iron");
|
||||
var diamond = new ResourceLocation("diamond");
|
||||
var netherite = new ResourceLocation("netherite");
|
||||
var gold = new ResourceLocation("gold");
|
||||
processTier(Tiers.WOOD, wood, List.of(), List.of());
|
||||
processTier(Tiers.GOLD, gold, List.of(wood), List.of(stone));
|
||||
processTier(Tiers.STONE, stone, List.of(wood), List.of(iron));
|
||||
processTier(Tiers.IRON, iron, List.of(stone), List.of(diamond));
|
||||
processTier(Tiers.DIAMOND, diamond, List.of(iron), List.of(netherite));
|
||||
processTier(Tiers.NETHERITE, netherite, List.of(diamond), List.of());
|
||||
vanillaEdges.putAll(edges);
|
||||
}
|
||||
|
||||
private static final List<Tier> sortedTiers = new ArrayList<>();
|
||||
private static final List<Tier> sortedTiersUnmodifiable = Collections.unmodifiableList(sortedTiers);
|
||||
|
||||
private static final ResourceLocation CHANNEL_NAME = new ResourceLocation("forge:tier_sorting");
|
||||
private static final SimpleChannel SYNC_CHANNEL = ChannelBuilder
|
||||
.named(CHANNEL_NAME)
|
||||
.networkProtocolVersion(1)
|
||||
.acceptedVersions((s, v) -> v == 1 || allowVanilla()) // Accepts vanilla unless we've got custom tiers
|
||||
.simpleChannel()
|
||||
.messageBuilder(SyncPacket.class, NetworkDirection.PLAY_TO_CLIENT)
|
||||
.encoder(SyncPacket::encode)
|
||||
.decoder(TierSortingRegistry::receive)
|
||||
.consumerNetworkThread(TierSortingRegistry::handle)
|
||||
.add();
|
||||
|
||||
static boolean allowVanilla() {
|
||||
return !hasCustomTiers;
|
||||
}
|
||||
|
||||
/*package private*/
|
||||
static void init() {
|
||||
MinecraftForge.EVENT_BUS.addListener(TierSortingRegistry::playerLoggedIn);
|
||||
if (FMLEnvironment.dist == Dist.CLIENT)
|
||||
ClientEvents.init();
|
||||
}
|
||||
|
||||
/*package private*/
|
||||
static PreparableReloadListener getReloadListener() {
|
||||
return new SimplePreparableReloadListener<JsonObject>() {
|
||||
final Gson gson = (new GsonBuilder()).create();
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
protected JsonObject prepare(@NotNull ResourceManager resourceManager, ProfilerFiller p) {
|
||||
Optional<Resource> res = resourceManager.getResource(ITEM_TIER_ORDERING_JSON);
|
||||
if (res.isEmpty())
|
||||
return new JsonObject();
|
||||
|
||||
try (var reader = res.get().openAsReader()) {
|
||||
return gson.fromJson(reader, JsonObject.class);
|
||||
} catch (IOException e) {
|
||||
LOGGER.error("Could not read Tier sorting file " + ITEM_TIER_ORDERING_JSON, e);
|
||||
return new JsonObject();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void apply(@NotNull JsonObject data, @NotNull ResourceManager resourceManager, ProfilerFiller p) {
|
||||
try {
|
||||
if (data.size() > 0) {
|
||||
JsonArray order = GsonHelper.getAsJsonArray(data, "order");
|
||||
List<Tier> customOrder = new ArrayList<>();
|
||||
for (JsonElement entry : order) {
|
||||
ResourceLocation id = new ResourceLocation(entry.getAsString());
|
||||
Tier tier = byName(id);
|
||||
if (tier == null) throw new IllegalStateException("Tier not found with name " + id);
|
||||
customOrder.add(tier);
|
||||
}
|
||||
|
||||
List<Tier> missingTiers = tiers.values().stream().filter(tier -> !customOrder.contains(tier)).toList();
|
||||
if (missingTiers.size() > 0)
|
||||
throw new IllegalStateException("Tiers missing from the ordered list: " + missingTiers.stream().map(tier -> Objects.toString(TierSortingRegistry.getName(tier))).collect(Collectors.joining(", ")));
|
||||
|
||||
setTierOrder(customOrder);
|
||||
return;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
LOGGER.error("Error parsing Tier sorting file " + ITEM_TIER_ORDERING_JSON, e);
|
||||
}
|
||||
|
||||
recalculateItemTiers();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static void recalculateItemTiers() {
|
||||
final MutableGraph<Tier> graph = GraphBuilder.directed().nodeOrder(ElementOrder.<Tier>insertion()).build();
|
||||
|
||||
for(Tier tier : tiers.values())
|
||||
graph.addNode(tier);
|
||||
|
||||
edges.forEach((key, value) -> {
|
||||
if (tiers.containsKey(key) && tiers.containsKey(value))
|
||||
graph.putEdge(tiers.get(key), tiers.get(value));
|
||||
});
|
||||
List<Tier> tierList = TopologicalSort.topologicalSort(graph, null);
|
||||
|
||||
setTierOrder(tierList);
|
||||
}
|
||||
|
||||
private static void setTierOrder(List<Tier> tierList) {
|
||||
runInServerThreadIfPossible(hasServer -> {
|
||||
sortedTiers.clear();
|
||||
sortedTiers.addAll(tierList);
|
||||
if (hasServer)
|
||||
syncToAll();
|
||||
});
|
||||
}
|
||||
|
||||
private static void runInServerThreadIfPossible(BooleanConsumer runnable) {
|
||||
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
|
||||
if (server != null)
|
||||
server.execute(() -> runnable.accept(true));
|
||||
else
|
||||
runnable.accept(false);
|
||||
}
|
||||
|
||||
private static void syncToAll() {
|
||||
for (ServerPlayer serverPlayer : ServerLifecycleHooks.getCurrentServer().getPlayerList().getPlayers())
|
||||
syncToPlayer(serverPlayer);
|
||||
}
|
||||
|
||||
private static void playerLoggedIn(PlayerEvent.PlayerLoggedInEvent event) {
|
||||
if (event.getEntity() instanceof ServerPlayer serverPlayer)
|
||||
syncToPlayer(serverPlayer);
|
||||
}
|
||||
|
||||
private static void syncToPlayer(ServerPlayer serverPlayer) {
|
||||
if (SYNC_CHANNEL.isRemotePresent(serverPlayer.connection.getConnection()) && !serverPlayer.connection.getConnection().isMemoryConnection())
|
||||
SYNC_CHANNEL.send(new SyncPacket(sortedTiers.stream().map(TierSortingRegistry::getName).toList()), PacketDistributor.PLAYER.with(serverPlayer));
|
||||
}
|
||||
|
||||
private static SyncPacket receive(FriendlyByteBuf buffer) {
|
||||
int count = buffer.readVarInt();
|
||||
List<ResourceLocation> list = new ArrayList<>();
|
||||
for(int i = 0; i < count; i++)
|
||||
list.add(buffer.readResourceLocation());
|
||||
return new SyncPacket(list);
|
||||
}
|
||||
|
||||
private static void handle(SyncPacket packet, CustomPayloadEvent.Context context) {
|
||||
setTierOrder(packet.tiers.stream().map(TierSortingRegistry::byName).toList());
|
||||
context.setPacketHandled(true);
|
||||
}
|
||||
|
||||
private record SyncPacket(List<ResourceLocation> tiers) {
|
||||
private void encode(FriendlyByteBuf buffer) {
|
||||
buffer.writeVarInt(tiers.size());
|
||||
for(ResourceLocation loc : tiers)
|
||||
buffer.writeResourceLocation(loc);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ClientEvents {
|
||||
public static void init() {
|
||||
MinecraftForge.EVENT_BUS.addListener(ClientEvents::clientLogInToServer);
|
||||
}
|
||||
|
||||
private static void clientLogInToServer(ClientPlayerNetworkEvent.LoggingIn event) {
|
||||
if (event.getConnection() == null || !event.getConnection().isMemoryConnection())
|
||||
recalculateItemTiers();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,11 @@ import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
public final class ToolAction {
|
||||
public record ToolAction(String name) {
|
||||
public static final Codec<ToolAction> CODEC = Codec.STRING.xmap(ToolAction::get, ToolAction::name).stable();
|
||||
private static final Map<String, ToolAction> actions = new ConcurrentHashMap<>();
|
||||
private static final Map<String, ToolAction> ACTIONS = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Returns all registered actions.
|
||||
@@ -22,14 +23,14 @@ public final class ToolAction {
|
||||
* See {@link ConcurrentHashMap#values()} for details.
|
||||
*/
|
||||
public static Collection<ToolAction> getActions() {
|
||||
return Collections.unmodifiableCollection(actions.values());
|
||||
return Collections.unmodifiableCollection(ACTIONS.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates a new ToolAction for the given name.
|
||||
*/
|
||||
public static ToolAction get(String name) {
|
||||
return actions.computeIfAbsent(name, ToolAction::new);
|
||||
return ACTIONS.computeIfAbsent(name, ToolAction::new);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,17 +40,7 @@ public final class ToolAction {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ToolAction[" + name + "]";
|
||||
}
|
||||
|
||||
private final String name;
|
||||
|
||||
/**
|
||||
* Use {@link #get(String)} to get or create a ToolAction
|
||||
*/
|
||||
private ToolAction(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
/** Use {@link #get(String)} to get or create a ToolAction */
|
||||
@ApiStatus.Internal
|
||||
public ToolAction {}
|
||||
}
|
||||
@@ -9,49 +9,41 @@ import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class BrewingRecipe implements IBrewingRecipe
|
||||
{
|
||||
public class BrewingRecipe implements IBrewingRecipe {
|
||||
@NotNull private final Ingredient input;
|
||||
@NotNull private final Ingredient ingredient;
|
||||
@NotNull private final ItemStack output;
|
||||
|
||||
public BrewingRecipe(Ingredient input, Ingredient ingredient, ItemStack output)
|
||||
{
|
||||
public BrewingRecipe(Ingredient input, Ingredient ingredient, ItemStack output) {
|
||||
this.input = input;
|
||||
this.ingredient = ingredient;
|
||||
this.output = output;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInput(@NotNull ItemStack stack)
|
||||
{
|
||||
public boolean isInput(@NotNull ItemStack stack) {
|
||||
return this.input.test(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getOutput(ItemStack input, ItemStack ingredient)
|
||||
{
|
||||
public ItemStack getOutput(ItemStack input, ItemStack ingredient) {
|
||||
return isInput(input) && isIngredient(ingredient) ? getOutput().copy() : ItemStack.EMPTY;
|
||||
}
|
||||
|
||||
public Ingredient getInput()
|
||||
{
|
||||
public Ingredient getInput() {
|
||||
return input;
|
||||
}
|
||||
|
||||
public Ingredient getIngredient()
|
||||
{
|
||||
public Ingredient getIngredient() {
|
||||
return ingredient;
|
||||
}
|
||||
|
||||
public ItemStack getOutput()
|
||||
{
|
||||
public ItemStack getOutput() {
|
||||
return output;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isIngredient(ItemStack ingredient)
|
||||
{
|
||||
public boolean isIngredient(ItemStack ingredient) {
|
||||
return this.ingredient.test(ingredient);
|
||||
}
|
||||
}
|
||||
@@ -12,57 +12,20 @@ import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.core.NonNullList;
|
||||
|
||||
/*
|
||||
public class BrewingRecipeRegistry {
|
||||
|
||||
private static List<IBrewingRecipe> recipes = new ArrayList<IBrewingRecipe>();
|
||||
|
||||
static
|
||||
{
|
||||
addRecipe(new VanillaBrewingRecipe());
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a recipe to the registry. Due to the nature of the brewing stand
|
||||
* inputs that stack (a.k.a max stack size > 1) are not allowed.
|
||||
*
|
||||
* @param input
|
||||
* The Ingredient that goes in same slots as the water bottles
|
||||
* would.
|
||||
* @param ingredient
|
||||
* The Ingredient that goes in the same slot as nether wart would.
|
||||
* @param output
|
||||
* The ItemStack that will replace the input once the brewing is
|
||||
* done.
|
||||
* @return true if the recipe was added.
|
||||
*/
|
||||
public static boolean addRecipe(Ingredient input, Ingredient ingredient, ItemStack output)
|
||||
{
|
||||
return addRecipe(new BrewingRecipe(input, ingredient, output));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a recipe to the registry. Due to the nature of the brewing stand
|
||||
* inputs that stack (a.k.a max stack size > 1) are not allowed.
|
||||
*/
|
||||
public static boolean addRecipe(IBrewingRecipe recipe)
|
||||
{
|
||||
return recipes.add(recipe);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output ItemStack obtained by brewing the passed input and
|
||||
* ingredient.
|
||||
*/
|
||||
public static ItemStack getOutput(ItemStack input, ItemStack ingredient)
|
||||
{
|
||||
* /
|
||||
public static ItemStack getOutput(ItemStack input, ItemStack ingredient) {
|
||||
if (input.isEmpty() || input.getCount() != 1) return ItemStack.EMPTY;
|
||||
if (ingredient.isEmpty()) return ItemStack.EMPTY;
|
||||
|
||||
for (IBrewingRecipe recipe : recipes)
|
||||
{
|
||||
for (IBrewingRecipe recipe : recipes) {
|
||||
ItemStack output = recipe.getOutput(input, ingredient);
|
||||
if (!output.isEmpty())
|
||||
{
|
||||
if (!output.isEmpty()) {
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -71,9 +34,8 @@ public class BrewingRecipeRegistry {
|
||||
|
||||
/**
|
||||
* Returns true if the passed input and ingredient have an output
|
||||
*/
|
||||
public static boolean hasOutput(ItemStack input, ItemStack ingredient)
|
||||
{
|
||||
* /
|
||||
public static boolean hasOutput(ItemStack input, ItemStack ingredient) {
|
||||
return !getOutput(input, ingredient).isEmpty();
|
||||
}
|
||||
|
||||
@@ -81,15 +43,12 @@ public class BrewingRecipeRegistry {
|
||||
* Used by the brewing stand to determine if its contents can be brewed.
|
||||
* Extra parameters exist to allow modders to create bigger brewing stands
|
||||
* without much hassle
|
||||
*/
|
||||
public static boolean canBrew(NonNullList<ItemStack> inputs, ItemStack ingredient, int[] inputIndexes)
|
||||
{
|
||||
* /
|
||||
public static boolean canBrew(NonNullList<ItemStack> inputs, ItemStack ingredient, int[] inputIndexes) {
|
||||
if (ingredient.isEmpty()) return false;
|
||||
|
||||
for (int i : inputIndexes)
|
||||
{
|
||||
if (hasOutput(inputs.get(i), ingredient))
|
||||
{
|
||||
for (int i : inputIndexes) {
|
||||
if (hasOutput(inputs.get(i), ingredient)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -100,58 +59,14 @@ public class BrewingRecipeRegistry {
|
||||
/**
|
||||
* Used by the brewing stand to brew its inventory Extra parameters exist to
|
||||
* allow modders to create bigger brewing stands without much hassle
|
||||
*/
|
||||
public static void brewPotions(NonNullList<ItemStack> inputs, ItemStack ingredient, int[] inputIndexes)
|
||||
{
|
||||
for (int i : inputIndexes)
|
||||
{
|
||||
* /
|
||||
public static void brewPotions(NonNullList<ItemStack> inputs, ItemStack ingredient, int[] inputIndexes) {
|
||||
for (int i : inputIndexes) {
|
||||
ItemStack output = getOutput(inputs.get(i), ingredient);
|
||||
if (!output.isEmpty())
|
||||
{
|
||||
if (!output.isEmpty()) {
|
||||
inputs.set(i, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the passed ItemStack is a valid ingredient for any of the
|
||||
* recipes in the registry.
|
||||
*/
|
||||
public static boolean isValidIngredient(ItemStack stack)
|
||||
{
|
||||
if (stack.isEmpty()) return false;
|
||||
|
||||
for (IBrewingRecipe recipe : recipes)
|
||||
{
|
||||
if (recipe.isIngredient(stack))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the passed ItemStack is a valid input for any of the
|
||||
* recipes in the registry.
|
||||
*/
|
||||
public static boolean isValidInput(ItemStack stack)
|
||||
{
|
||||
for (IBrewingRecipe recipe : recipes)
|
||||
{
|
||||
if (recipe.isInput(stack))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an unmodifiable list containing all the recipes in the registry
|
||||
*/
|
||||
public static List<IBrewingRecipe> getRecipes()
|
||||
{
|
||||
return Collections.unmodifiableList(recipes);
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -5,8 +5,9 @@
|
||||
|
||||
package net.minecraftforge.common.brewing;
|
||||
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.world.item.Item;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
import net.minecraft.world.inventory.BrewingStandMenu;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.alchemy.PotionBrewing;
|
||||
|
||||
@@ -16,24 +17,28 @@ import net.minecraft.world.item.alchemy.PotionBrewing;
|
||||
* Most of the code was simply adapted from net.minecraft.tileentity.TileEntityBrewingStand
|
||||
*/
|
||||
public class VanillaBrewingRecipe implements IBrewingRecipe {
|
||||
private final PotionBrewing vanilla;
|
||||
private final BiFunction<ItemStack, ItemStack, ItemStack> vanillaMix;
|
||||
|
||||
/**
|
||||
* Code adapted from TileEntityBrewingStand.isItemValidForSlot(int index, ItemStack stack)
|
||||
*/
|
||||
@Override
|
||||
public boolean isInput(ItemStack stack)
|
||||
{
|
||||
Item item = stack.getItem();
|
||||
return item == Items.POTION || item == Items.SPLASH_POTION || item == Items.LINGERING_POTION || item == Items.GLASS_BOTTLE;
|
||||
public VanillaBrewingRecipe(PotionBrewing vanilla, BiFunction<ItemStack, ItemStack, ItemStack> vanillaMix) {
|
||||
this.vanilla = vanilla;
|
||||
this.vanillaMix = vanillaMix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Code adapted from TileEntityBrewingStand.isItemValidForSlot(int index, ItemStack stack)
|
||||
*/
|
||||
@Override
|
||||
public boolean isIngredient(ItemStack stack)
|
||||
{
|
||||
return PotionBrewing.isIngredient(stack);
|
||||
public boolean isInput(ItemStack stack) {
|
||||
return BrewingStandMenu.PotionSlot.mayPlaceItem(stack);
|
||||
}
|
||||
|
||||
/**
|
||||
* Code adapted from TileEntityBrewingStand.isItemValidForSlot(int index, ItemStack stack)
|
||||
*/
|
||||
@Override
|
||||
public boolean isIngredient(ItemStack stack) {
|
||||
return vanilla.isContainerIngredient(stack) || vanilla.isPotionIngredient(stack);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,13 +47,10 @@ public class VanillaBrewingRecipe implements IBrewingRecipe {
|
||||
* or if the new potion is a splash potion when the old one wasn't.
|
||||
*/
|
||||
@Override
|
||||
public ItemStack getOutput(ItemStack input, ItemStack ingredient)
|
||||
{
|
||||
if (!input.isEmpty() && !ingredient.isEmpty() && isIngredient(ingredient))
|
||||
{
|
||||
ItemStack result = PotionBrewing.mix(ingredient, input);
|
||||
if (result != input)
|
||||
{
|
||||
public ItemStack getOutput(ItemStack input, ItemStack ingredient) {
|
||||
if (!input.isEmpty() && !ingredient.isEmpty() && isIngredient(ingredient)) {
|
||||
ItemStack result = vanillaMix.apply(ingredient, input);
|
||||
if (result != input) {
|
||||
return result;
|
||||
}
|
||||
return ItemStack.EMPTY;
|
||||
|
||||
@@ -9,12 +9,14 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.common.ForgeHooks;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
@@ -37,7 +39,7 @@ public class ConditionalAdvancement {
|
||||
public static class Builder {
|
||||
private static final ResourceLocation DOESNT_MATTER = new ResourceLocation("doesnt", "matter");
|
||||
|
||||
private List<Pair> advancements = new ArrayList<>();
|
||||
private List<Adv> advancements = new ArrayList<>();
|
||||
private ICondition condition;
|
||||
|
||||
public Builder condition(ICondition value) {
|
||||
@@ -58,26 +60,41 @@ public class ConditionalAdvancement {
|
||||
return advancement(holder.value());
|
||||
}
|
||||
|
||||
public Builder advancement(JsonObject value) {
|
||||
return advancement(null, value);
|
||||
}
|
||||
|
||||
private Builder advancement(Advancement value) {
|
||||
return advancement(value, null);
|
||||
}
|
||||
|
||||
private Builder advancement(Advancement value, JsonObject json) {
|
||||
if (condition == null)
|
||||
throw new IllegalStateException("Can not add a advancement with no conditions.");
|
||||
|
||||
if (value == null)
|
||||
throw new IllegalStateException("Can not add a null advancement");
|
||||
|
||||
this.advancements.add(new Pair(this.condition, value));
|
||||
this.advancements.add(new Adv(this.condition, value, json));
|
||||
this.condition = null;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public JsonObject build() {
|
||||
public JsonObject build(HolderLookup.Provider lookup) {
|
||||
var json = new JsonObject();
|
||||
var array = new JsonArray();
|
||||
json.add("advancements", array);
|
||||
|
||||
var ops = lookup.createSerializationContext(JsonOps.INSTANCE);
|
||||
|
||||
for (var pair : advancements) {
|
||||
JsonObject holder = (JsonObject)Util.getOrThrow(Advancement.CODEC.encodeStart(JsonOps.INSTANCE, pair.adv()), IllegalStateException::new);
|
||||
JsonObject holder = null;
|
||||
if (pair.json != null)
|
||||
holder = pair.json;
|
||||
else
|
||||
holder = (JsonObject)Advancement.CODEC.encodeStart(ops, pair.adv()).getOrThrow(IllegalStateException::new);
|
||||
|
||||
if (holder.has(ICondition.DEFAULT_FIELD))
|
||||
throw new IllegalStateException("Recipe already serialized conditions!");
|
||||
ForgeHooks.writeCondition(pair.condition(), holder);
|
||||
@@ -88,5 +105,5 @@ public class ConditionalAdvancement {
|
||||
}
|
||||
}
|
||||
|
||||
private record Pair(ICondition condition, Advancement adv) {}
|
||||
private record Adv(ICondition condition, Advancement adv, JsonObject json) {}
|
||||
}
|
||||
@@ -13,20 +13,20 @@ import java.util.stream.Stream;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DataResult;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.MapDecoder;
|
||||
import com.mojang.serialization.MapEncoder;
|
||||
import com.mojang.serialization.MapLike;
|
||||
import com.mojang.serialization.RecordBuilder;
|
||||
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.advancements.Advancement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderLookup.Provider;
|
||||
import net.minecraft.data.recipes.RecipeBuilder;
|
||||
import net.minecraft.data.recipes.RecipeOutput;
|
||||
import net.minecraft.world.Container;
|
||||
@@ -35,12 +35,12 @@ import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeSerializer;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraftforge.common.crafting.conditions.ConditionCodec;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
import net.minecraftforge.common.crafting.conditions.ICondition.IContext;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
@@ -79,11 +79,16 @@ public class ConditionalRecipe {
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
AdvancementHolder holder = null;
|
||||
if (advancement != null) {
|
||||
Advancement adv = Util.getOrThrow(Advancement.CODEC.parse(JsonOps.INSTANCE, advancement), JsonParseException::new);
|
||||
Advancement adv = Advancement.CODEC.parse(JsonOps.INSTANCE, advancement).getOrThrow(JsonParseException::new);
|
||||
holder = new AdvancementHolder(advancementId, adv);
|
||||
}
|
||||
accept(id, recipe, holder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider registry() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
@Nullable
|
||||
@@ -118,7 +123,7 @@ public class ConditionalRecipe {
|
||||
throw new IllegalStateException("Can not add a recipe with no conditions.");
|
||||
recipes.add(new InnerRecipe(this.condition, recipe));
|
||||
if (advancement != null)
|
||||
advancements.add(new InnerAdvancement(this.condition, advancement));
|
||||
advancements.add(new InnerAdvancement(this.condition, advancement, null));
|
||||
condition = null;
|
||||
return this;
|
||||
}
|
||||
@@ -143,12 +148,15 @@ public class ConditionalRecipe {
|
||||
if (!advancements.isEmpty()) {
|
||||
var adv = ConditionalAdvancement.builder();
|
||||
for (var data : advancements) {
|
||||
adv.condition(data.condition())
|
||||
.advancement(data.advancement());
|
||||
adv.condition(data.condition());
|
||||
if (data.json != null)
|
||||
adv.advancement(data.json());
|
||||
else
|
||||
adv.advancement(data.advancement());
|
||||
}
|
||||
if (advancementId == null)
|
||||
advancementId = id.withPrefix("recipes/");
|
||||
advancement = adv.build();
|
||||
advancement = adv.build(out.registry());
|
||||
} else {
|
||||
advancementId = null;
|
||||
}
|
||||
@@ -158,13 +166,13 @@ public class ConditionalRecipe {
|
||||
}
|
||||
|
||||
private record InnerRecipe(ICondition condition, Recipe<?> recipe) {}
|
||||
private record InnerAdvancement(ICondition condition, AdvancementHolder advancement) {}
|
||||
private record InnerAdvancement(ICondition condition, AdvancementHolder advancement, JsonObject json) {}
|
||||
|
||||
private static class Wrapper implements Recipe<Container> {
|
||||
@Override public boolean matches(Container inv, Level level) { return false; }
|
||||
@Override public ItemStack assemble(Container inv, RegistryAccess reg) { return null; }
|
||||
@Override public ItemStack assemble(Container inv, HolderLookup.Provider reg) { return null; }
|
||||
@Override public boolean canCraftInDimensions(int width, int height) { return false; }
|
||||
@Override public ItemStack getResultItem(RegistryAccess reg) { return null; }
|
||||
@Override public ItemStack getResultItem(HolderLookup.Provider reg) { return null; }
|
||||
@Override public RecipeSerializer<?> getSerializer() { return ConditionalRecipe.SERIALZIER; }
|
||||
@Override public RecipeType<?> getType() { throw new UnsupportedOperationException(); }
|
||||
|
||||
@@ -176,7 +184,7 @@ public class ConditionalRecipe {
|
||||
}
|
||||
|
||||
}
|
||||
private static final Codec<Recipe<?>> CODEC = Codec.of(new MapEncoder.Implementation<>() {
|
||||
private static final MapCodec<Recipe<?>> CODEC = Codec.of(new MapEncoder.Implementation<>() {
|
||||
@Override
|
||||
public <T> RecordBuilder<T> encode(Recipe<?> input, DynamicOps<T> ops, RecordBuilder<T> prefix) {
|
||||
if (!(input instanceof Wrapper))
|
||||
@@ -188,14 +196,15 @@ public class ConditionalRecipe {
|
||||
else if (wrapper.recipes.size() == 1)
|
||||
prefix.add(ICondition.DEFAULT_FIELD, ICondition.CODEC.encodeStart(ops, wrapper.recipes.get(0).condition()));
|
||||
|
||||
var recipes = new ArrayList<T>();
|
||||
var recipes = ops.listBuilder();
|
||||
for (var recipe : wrapper.recipes) {
|
||||
var json = (JsonObject)json(Recipe.CODEC, recipe.recipe());
|
||||
if (wrapper.recipes.size() > 1)
|
||||
json.add(ICondition.DEFAULT_FIELD, json(ICondition.CODEC, recipe.condition()));
|
||||
recipes.add(JsonOps.INSTANCE.convertTo(ops, json));
|
||||
var map = ops.mapBuilder();
|
||||
if (wrapper.main != null || wrapper.recipes.size() != 1)
|
||||
map.add(ICondition.DEFAULT_FIELD, recipe.condition(), ICondition.CODEC);
|
||||
map.add("recipe", recipe.recipe(), Recipe.CODEC);
|
||||
recipes.add(map.build(ops.emptyMap()));
|
||||
}
|
||||
prefix.add("recipes", ops.createList(recipes.stream()));
|
||||
prefix.add("recipes", recipes.build(ops.emptyList()));
|
||||
return prefix;
|
||||
}
|
||||
|
||||
@@ -203,65 +212,67 @@ public class ConditionalRecipe {
|
||||
public <T> Stream<T> keys(DynamicOps<T> ops) {
|
||||
return Stream.of(ops.createString(ICondition.DEFAULT_FIELD), ops.createString("recipes"));
|
||||
}
|
||||
|
||||
|
||||
private static <T> JsonElement json(Codec<T> codec, T object) {
|
||||
return Util.getOrThrow(codec.encodeStart(JsonOps.INSTANCE, object), IllegalStateException::new);
|
||||
}
|
||||
}, new MapDecoder.Implementation<Recipe<?>>() {
|
||||
@Override
|
||||
public <T> DataResult<Recipe<?>> decode(DynamicOps<T> ops, MapLike<T> input) {
|
||||
var context = ConditionCodec.getContext(ops);
|
||||
var json = ops.convertTo(JsonOps.INSTANCE, input.get("recipes"));
|
||||
try {
|
||||
var recipes = GsonHelper.convertToJsonArray(json, "recipes");
|
||||
int idx = 0;
|
||||
for (var entry : recipes) {
|
||||
var object = GsonHelper.convertToJsonObject(entry, "recipe[" + idx++ + "]");
|
||||
if (object.has(ICondition.DEFAULT_FIELD)) {
|
||||
var conditionjson = GsonHelper.getAsJsonObject(object, ICondition.DEFAULT_FIELD);
|
||||
var condition = Util.getOrThrow(ICondition.SAFE_CODEC.parse(JsonOps.INSTANCE, conditionjson), JsonSyntaxException::new);
|
||||
if (!condition.test(context))
|
||||
continue;
|
||||
}
|
||||
var type = new ResourceLocation(GsonHelper.getAsString(object, "type"));
|
||||
var serializer = ForgeRegistries.RECIPE_SERIALIZERS.getValue(type);
|
||||
if (serializer == null)
|
||||
return DataResult.error(() -> "Invalid or unsupported recipe type '" + type + "' Conditions were successful, but unknown type");
|
||||
var parsed = serializer.codec().parse(JsonOps.INSTANCE, object);
|
||||
if (parsed.error().isPresent())
|
||||
return DataResult.error(parsed.error().get()::message);
|
||||
else if (!parsed.result().isPresent())
|
||||
return DataResult.error(() -> "Recipe passed all conditions but did not parse a valid return");
|
||||
else
|
||||
return DataResult.success(parsed.result().get());
|
||||
}
|
||||
return ops.getStream(input.get("recipes")).flatMap(stream -> {
|
||||
var count = new Holder<Integer>();
|
||||
count.value = -1;
|
||||
var ret = stream.map(entry -> accept(context, ops, count, entry))
|
||||
.filter(entry -> entry != null)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (ret != null)
|
||||
return ret;
|
||||
|
||||
return DataResult.error(() -> "No recipe passed conditions, if this is the case, you should have an outer condition.");
|
||||
} catch (JsonSyntaxException e) {
|
||||
return DataResult.error(() -> e.getMessage());
|
||||
});
|
||||
}
|
||||
|
||||
private <T> DataResult<Recipe<?>> accept(IContext context, DynamicOps<T> ops, Holder<Integer> count, T entry) {
|
||||
count.value = count.value + 1;
|
||||
var map = ops.getMap(entry).result().orElse(null);
|
||||
if (map == null)
|
||||
return DataResult.error(() -> "Entry " + count.value + " was not MapLike " + entry.getClass());
|
||||
|
||||
if (map.get(ICondition.DEFAULT_FIELD) != null) {
|
||||
var parsed = ICondition.SAFE_CODEC.parse(ops, (T)map.get(ICondition.DEFAULT_FIELD));
|
||||
if (parsed.result().isPresent()) {
|
||||
var condition = parsed.result().get();
|
||||
if (!condition.test(context, ops))
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var recipe = map.get("recipe");
|
||||
if (recipe == null)
|
||||
return DataResult.error(() -> "Missing `recipe` entry " + count.value);
|
||||
|
||||
var ret = Recipe.CODEC.parse(ops, (T)recipe);
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Stream<T> keys(DynamicOps<T> ops) {
|
||||
return Stream.of(ops.createString(ICondition.DEFAULT_FIELD), ops.createString("recipes"));
|
||||
}
|
||||
}).codec();
|
||||
});
|
||||
|
||||
public static final RecipeSerializer<Recipe<?>> SERIALZIER = new RecipeSerializer<Recipe<?>>() {
|
||||
@Override
|
||||
public Codec<Recipe<?>> codec() {
|
||||
public MapCodec<Recipe<?>> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Recipe<?> fromNetwork(FriendlyByteBuf buffer) {
|
||||
throw new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support decoding from network");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void toNetwork(FriendlyByteBuf buffer, Recipe<?> recipe) {
|
||||
public StreamCodec<RegistryFriendlyByteBuf, Recipe<?>> streamCodec() {
|
||||
throw new UnsupportedOperationException("ConditionaRecipe.SERIALIZER does not support encoding to network");
|
||||
}
|
||||
};
|
||||
|
||||
private static class Holder<T> {
|
||||
private T value;
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.crafting;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.util.GsonHelper;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
public class CraftingHelper {
|
||||
private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
|
||||
public static ItemStack getItemStack(JsonObject json, boolean readNBT) {
|
||||
return getItemStack(json, readNBT, false);
|
||||
}
|
||||
|
||||
public static Item getItem(String itemName, boolean disallowsAirInRecipe) {
|
||||
ResourceLocation itemKey = new ResourceLocation(itemName);
|
||||
if (!ForgeRegistries.ITEMS.containsKey(itemKey))
|
||||
throw new JsonSyntaxException("Unknown item '" + itemName + "'");
|
||||
|
||||
Item item = ForgeRegistries.ITEMS.getValue(itemKey);
|
||||
if (disallowsAirInRecipe && item == Items.AIR)
|
||||
throw new JsonSyntaxException("Invalid item: " + itemName);
|
||||
return Objects.requireNonNull(item);
|
||||
}
|
||||
|
||||
public static CompoundTag getNBT(JsonElement element) {
|
||||
try {
|
||||
if (element.isJsonObject())
|
||||
return TagParser.parseTag(GSON.toJson(element));
|
||||
else
|
||||
return TagParser.parseTag(GsonHelper.convertToString(element, "nbt"));
|
||||
} catch (CommandSyntaxException e) {
|
||||
throw new JsonSyntaxException("Invalid NBT Entry: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
public static ItemStack getItemStack(JsonObject json, boolean readNBT, boolean disallowsAirInRecipe) {
|
||||
String itemName = GsonHelper.getAsString(json, "item");
|
||||
Item item = getItem(itemName, disallowsAirInRecipe);
|
||||
if (readNBT && json.has("nbt")) {
|
||||
CompoundTag nbt = getNBT(json.get("nbt"));
|
||||
CompoundTag tmp = new CompoundTag();
|
||||
if (nbt.contains("ForgeCaps")) {
|
||||
tmp.put("ForgeCaps", nbt.get("ForgeCaps"));
|
||||
nbt.remove("ForgeCaps");
|
||||
}
|
||||
|
||||
tmp.put("tag", nbt);
|
||||
tmp.putString("id", itemName);
|
||||
tmp.putInt("Count", GsonHelper.getAsInt(json, "count", 1));
|
||||
|
||||
return ItemStack.of(tmp);
|
||||
}
|
||||
|
||||
return new ItemStack(item, GsonHelper.getAsInt(json, "count", 1));
|
||||
}
|
||||
}
|
||||
@@ -8,18 +8,19 @@ package net.minecraftforge.common.crafting.conditions;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
public record AndCondition(List<ICondition> children) implements ICondition {
|
||||
public static final Codec<AndCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<AndCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ICondition.CODEC.listOf().fieldOf("values").forGetter(AndCondition::children)
|
||||
).apply(b, AndCondition::new));
|
||||
|
||||
@Override
|
||||
public boolean test(IContext context) {
|
||||
public boolean test(IContext context, DynamicOps<?> ops) {
|
||||
for (ICondition child : children) {
|
||||
if (!child.test(context))
|
||||
if (!child.test(context, ops))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -31,7 +32,7 @@ public record AndCondition(List<ICondition> children) implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -62,7 +62,7 @@ public class ConditionCodec {
|
||||
return DataResult.error(() -> conditionDecoded.error().get().message());
|
||||
|
||||
var condition = conditionDecoded.result().get();
|
||||
if (!condition.test(getContext(ops)))
|
||||
if (!condition.test(getContext(ops), ops))
|
||||
return DataResult.success(Pair.of(Optional.empty(), ops.empty()));
|
||||
|
||||
return normal.decode(ops, input).map(p -> p.mapFirst(Optional::of));
|
||||
|
||||
@@ -5,16 +5,17 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
public final class FalseCondition implements ICondition {
|
||||
public static final FalseCondition INSTANCE = new FalseCondition();
|
||||
public static final Codec<FalseCondition> CODEC = Codec.unit(INSTANCE).stable();
|
||||
public static final MapCodec<FalseCondition> CODEC = MapCodec.unit(INSTANCE).stable();
|
||||
|
||||
private FalseCondition() { }
|
||||
|
||||
@Override
|
||||
public boolean test(IContext condition) {
|
||||
public boolean test(IContext condition, DynamicOps<?> ops) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -24,7 +25,7 @@ public final class FalseCondition implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
@@ -13,7 +14,6 @@ import net.minecraft.core.Registry;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.util.ExtraCodecs;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
import java.util.Collection;
|
||||
@@ -26,14 +26,14 @@ import java.util.function.Function;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
public interface ICondition {
|
||||
Codec<ICondition> CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.CONDITION_SERIALIZERS.get().getCodec().dispatch(ICondition::codec, Function.identity()));
|
||||
Codec<ICondition> CODEC = Codec.lazyInitialized(() -> 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);
|
||||
Codec<ICondition> SAFE_CODEC = CODEC.orElse(FalseCondition.INSTANCE);
|
||||
|
||||
boolean test(IContext context);
|
||||
boolean test(IContext context, DynamicOps<?> ops);
|
||||
|
||||
Codec<? extends ICondition> codec();
|
||||
MapCodec<? extends ICondition> codec();
|
||||
|
||||
interface IContext {
|
||||
/* Key used to attach this context option to a DynamicOps instance */
|
||||
|
||||
+21
-4
@@ -5,19 +5,36 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.core.HolderGetter;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
|
||||
public record ItemExistsCondition(ResourceLocation item) implements ICondition {
|
||||
public static final Codec<ItemExistsCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<ItemExistsCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ResourceLocation.CODEC.fieldOf("item").forGetter(ItemExistsCondition::item)
|
||||
).apply(b, ItemExistsCondition::new));
|
||||
|
||||
@Override
|
||||
public boolean test(IContext context) {
|
||||
public boolean test(IContext context, DynamicOps<?> ops) {
|
||||
// Check the actual deserialization context if possible
|
||||
if (ops instanceof RegistryOps<?> reg) {
|
||||
Optional<HolderGetter<Item>> items = reg.getter(Registries.ITEM);
|
||||
if (items.isPresent()) {
|
||||
var key = ResourceKey.create(Registries.ITEM, this.item);
|
||||
return items.get().get(key).isPresent();
|
||||
}
|
||||
}
|
||||
// Default to the active registry if its missing
|
||||
return ForgeRegistries.ITEMS.containsKey(item);
|
||||
}
|
||||
|
||||
@@ -27,7 +44,7 @@ public record ItemExistsCondition(ResourceLocation item) implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -6,17 +6,19 @@
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraftforge.fml.ModList;
|
||||
|
||||
public record ModLoadedCondition(String modid) implements ICondition {
|
||||
public static final Codec<ModLoadedCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<ModLoadedCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
Codec.STRING.fieldOf("modid").forGetter(ModLoadedCondition::modid)
|
||||
).apply(b, ModLoadedCondition::new));
|
||||
|
||||
@Override
|
||||
public boolean test(IContext context) {
|
||||
public boolean test(IContext context, DynamicOps<?> ops) {
|
||||
return ModList.get().isLoaded(modid);
|
||||
}
|
||||
|
||||
@@ -26,7 +28,7 @@ public record ModLoadedCondition(String modid) implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,17 +5,18 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
public record NotCondition(ICondition child) implements ICondition {
|
||||
public static final Codec<NotCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<NotCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ICondition.CODEC.fieldOf("value").forGetter(NotCondition::child)
|
||||
).apply(b, NotCondition::new));
|
||||
|
||||
@Override
|
||||
public boolean test(IContext context) {
|
||||
return !child.test(context);
|
||||
public boolean test(IContext context, DynamicOps<?> ops) {
|
||||
return !child.test(context, ops);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -24,7 +25,7 @@ public record NotCondition(ICondition child) implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -8,19 +8,20 @@ package net.minecraftforge.common.crafting.conditions;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.base.Joiner;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
public record OrCondition(List<ICondition> children) implements ICondition {
|
||||
public static final Codec<OrCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<OrCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ICondition.CODEC.listOf().fieldOf("values").forGetter(OrCondition::children)
|
||||
).apply(b, OrCondition::new));
|
||||
|
||||
|
||||
@Override
|
||||
public boolean test(IContext context) {
|
||||
public boolean test(IContext context, DynamicOps<?> ops) {
|
||||
for (ICondition child : children) {
|
||||
if (child.test(context))
|
||||
if (child.test(context, ops))
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -33,7 +34,7 @@ public record OrCondition(List<ICondition> children) implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,36 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.core.HolderGetter;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
public record TagEmptyCondition(TagKey<Item> tag) implements ICondition {
|
||||
public static final Codec<TagEmptyCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<TagEmptyCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ResourceLocation.CODEC.xmap(loc -> TagKey.create(Registries.ITEM, loc), TagKey::location).fieldOf("tag").forGetter(TagEmptyCondition::tag)
|
||||
).apply(b, TagEmptyCondition::new));
|
||||
|
||||
|
||||
@Override
|
||||
public boolean test(ICondition.IContext context) {
|
||||
public boolean test(ICondition.IContext context, DynamicOps<?> ops) {
|
||||
// Check the actual deserialization context if possible
|
||||
if (ops instanceof RegistryOps<?> reg) {
|
||||
Optional<HolderGetter<Item>> items = reg.getter(Registries.ITEM);
|
||||
if (items.isPresent()) {
|
||||
var optional = items.get().get(this.tag);
|
||||
return optional.isPresent();
|
||||
}
|
||||
}
|
||||
return context.getTag(tag).isEmpty();
|
||||
}
|
||||
|
||||
@@ -30,7 +44,7 @@ public record TagEmptyCondition(TagKey<Item> tag) implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,17 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.conditions;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DynamicOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
public final class TrueCondition implements ICondition {
|
||||
public static final TrueCondition INSTANCE = new TrueCondition();
|
||||
public static final Codec<TrueCondition> CODEC = Codec.unit(INSTANCE).stable();
|
||||
public static final MapCodec<TrueCondition> CODEC = MapCodec.unit(INSTANCE).stable();
|
||||
|
||||
private TrueCondition() {}
|
||||
|
||||
@Override
|
||||
public boolean test(IContext context) {
|
||||
public boolean test(IContext context, DynamicOps<?> ops) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -24,7 +25,7 @@ public final class TrueCondition implements ICondition {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends ICondition> codec() {
|
||||
public MapCodec<? extends ICondition> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
@@ -72,10 +71,4 @@ public abstract class AbstractIngredient extends Ingredient {
|
||||
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()");
|
||||
}
|
||||
}
|
||||
+9
-13
@@ -10,7 +10,7 @@ import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
@@ -18,7 +18,8 @@ import it.unimi.dsi.fastutil.ints.IntComparators;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@@ -97,7 +98,7 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
return SERIALIZER;
|
||||
}
|
||||
|
||||
public static final Codec<CompoundIngredient> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<CompoundIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Ingredient.CODEC_NONEMPTY.listOf().fieldOf("children").forGetter(i -> i.children)
|
||||
).apply(builder, CompoundIngredient::new)
|
||||
@@ -105,23 +106,18 @@ public class CompoundIngredient extends AbstractIngredient {
|
||||
|
||||
public static final IIngredientSerializer<CompoundIngredient> SERIALIZER = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public Codec<CompoundIngredient> codec() {
|
||||
public MapCodec<CompoundIngredient> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(FriendlyByteBuf buffer, CompoundIngredient value) {
|
||||
buffer.writeVarInt(value.children.size());
|
||||
for (var child : value.children)
|
||||
child.toNetwork(buffer);
|
||||
public void write(RegistryFriendlyByteBuf buffer, CompoundIngredient value) {
|
||||
buffer.writeCollection(value.children, (buf, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundIngredient read(FriendlyByteBuf buffer) {
|
||||
int size = buffer.readVarInt();
|
||||
var children = new ArrayList<Ingredient>(size);
|
||||
for (int x = 0; x < size; x++)
|
||||
children.add(Ingredient.fromNetwork(buffer));
|
||||
public CompoundIngredient read(RegistryFriendlyByteBuf buffer) {
|
||||
var children = buffer.readCollection(ArrayList::new, buf -> Ingredient.CONTENTS_STREAM_CODEC.decode(buffer));
|
||||
return new CompoundIngredient(children);
|
||||
}
|
||||
};
|
||||
|
||||
+10
-10
@@ -5,13 +5,13 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntComparators;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.entity.player.StackedContents;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
@@ -93,7 +93,7 @@ public class DifferenceIngredient extends AbstractIngredient {
|
||||
return SERIALIZER;
|
||||
}
|
||||
|
||||
public static final Codec<DifferenceIngredient> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<DifferenceIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Ingredient.CODEC.fieldOf("base").forGetter(i -> i.base),
|
||||
Ingredient.CODEC.fieldOf("subtracted").forGetter(i -> i.subtracted)
|
||||
@@ -102,21 +102,21 @@ public class DifferenceIngredient extends AbstractIngredient {
|
||||
|
||||
public static final IIngredientSerializer<DifferenceIngredient> SERIALIZER = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public Codec<? extends DifferenceIngredient> codec() {
|
||||
public MapCodec<? extends DifferenceIngredient> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DifferenceIngredient read(FriendlyByteBuf buffer) {
|
||||
Ingredient base = Ingredient.fromNetwork(buffer);
|
||||
Ingredient without = Ingredient.fromNetwork(buffer);
|
||||
public DifferenceIngredient read(RegistryFriendlyByteBuf buffer) {
|
||||
Ingredient base = Ingredient.CONTENTS_STREAM_CODEC.decode(buffer);
|
||||
Ingredient without = Ingredient.CONTENTS_STREAM_CODEC.decode(buffer);
|
||||
return new DifferenceIngredient(base, without);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(FriendlyByteBuf buffer, DifferenceIngredient ingredient) {
|
||||
ingredient.base.toNetwork(buffer);
|
||||
ingredient.subtracted.toNetwork(buffer);
|
||||
public void write(RegistryFriendlyByteBuf buffer, DifferenceIngredient ingredient) {
|
||||
Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, ingredient.base);
|
||||
Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, ingredient.subtracted);
|
||||
}
|
||||
};
|
||||
}
|
||||
+16
-11
@@ -5,30 +5,35 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import java.util.Arrays;
|
||||
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
|
||||
public interface IIngredientSerializer<T extends Ingredient> {
|
||||
Codec<? extends T> codec();
|
||||
void write(FriendlyByteBuf buffer, T value);
|
||||
T read(FriendlyByteBuf buffer);
|
||||
MapCodec<? extends T> codec();
|
||||
|
||||
void write(RegistryFriendlyByteBuf buffer, T value);
|
||||
T read(RegistryFriendlyByteBuf buffer);
|
||||
|
||||
|
||||
IIngredientSerializer<Ingredient> VANILLA = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public Codec<? extends Ingredient> codec() {
|
||||
return Ingredient.VANILLA_CODEC;
|
||||
public MapCodec<? extends Ingredient> codec() {
|
||||
return Ingredient.VANILLA_MAP_CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(FriendlyByteBuf buffer, Ingredient value) {
|
||||
value.toNetwork(buffer);
|
||||
public void write(RegistryFriendlyByteBuf buffer, Ingredient value) {
|
||||
ItemStack.LIST_STREAM_CODEC.encode(buffer, Arrays.asList(value.getItems()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Ingredient read(FriendlyByteBuf buffer) {
|
||||
return Ingredient.fromNetwork(buffer);
|
||||
public Ingredient read(RegistryFriendlyByteBuf buffer) {
|
||||
return Ingredient.of(ItemStack.LIST_STREAM_CODEC.decode(buffer).stream());
|
||||
}
|
||||
};
|
||||
}
|
||||
+10
-8
@@ -5,18 +5,19 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntArrayList;
|
||||
import it.unimi.dsi.fastutil.ints.IntComparators;
|
||||
import it.unimi.dsi.fastutil.ints.IntList;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.entity.player.StackedContents;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -113,7 +114,7 @@ public class IntersectionIngredient extends AbstractIngredient {
|
||||
return SERIALIZER;
|
||||
}
|
||||
|
||||
public static final Codec<IntersectionIngredient> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<IntersectionIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Ingredient.CODEC.listOf().fieldOf("children").forGetter(i -> i.children)
|
||||
)
|
||||
@@ -122,18 +123,19 @@ public class IntersectionIngredient extends AbstractIngredient {
|
||||
|
||||
public static final IIngredientSerializer<IntersectionIngredient> SERIALIZER = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public Codec<? extends IntersectionIngredient> codec() {
|
||||
public MapCodec<? extends IntersectionIngredient> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IntersectionIngredient read(FriendlyByteBuf buffer) {
|
||||
return new IntersectionIngredient(buffer.readList(Ingredient::fromNetwork));
|
||||
public IntersectionIngredient read(RegistryFriendlyByteBuf buffer) {
|
||||
var children = buffer.readCollection(ArrayList::new, buf -> Ingredient.CONTENTS_STREAM_CODEC.decode(buffer));
|
||||
return new IntersectionIngredient(children);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(FriendlyByteBuf buffer, IntersectionIngredient value) {
|
||||
buffer.writeCollection(value.children, (b, i) -> i.toNetwork(b));
|
||||
public void write(RegistryFriendlyByteBuf buffer, IntersectionIngredient value) {
|
||||
buffer.writeCollection(value.children, (b, child) -> Ingredient.CONTENTS_STREAM_CODEC.encode(buffer, child));
|
||||
}
|
||||
};
|
||||
}
|
||||
+13
-10
@@ -5,15 +5,17 @@
|
||||
|
||||
package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.advancements.critereon.NbtPredicate;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.TagParser;
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.component.CustomData;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import net.minecraft.world.level.ItemLike;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
@@ -39,7 +41,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
super(items.stream().map(item -> {
|
||||
var stack = new ItemStack(item);
|
||||
// copy NBT to prevent the stack from modifying the original, as capabilities or vanilla item durability will modify the tag
|
||||
stack.setTag(nbt.copy());
|
||||
stack.set(DataComponents.CUSTOM_DATA, CustomData.of(nbt.copy()));
|
||||
return new Ingredient.ItemValue(stack);
|
||||
}));
|
||||
|
||||
@@ -65,7 +67,8 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
public boolean test(@Nullable ItemStack input) {
|
||||
if (input == null)
|
||||
return false;
|
||||
return items.contains(input.getItem()) && predicate.matches(input.getShareTag());
|
||||
var nbt = input.get(DataComponents.CUSTOM_DATA);
|
||||
return nbt != null && items.contains(input.getItem()) && predicate.matches(nbt.copyTag());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -78,7 +81,7 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
return SERIALIZER;
|
||||
}
|
||||
|
||||
public static final Codec<PartialNBTIngredient> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<PartialNBTIngredient> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
ForgeRegistries.ITEMS.getCodec().listOf().fieldOf("items").forGetter(i -> i.items),
|
||||
TagParser.AS_CODEC.fieldOf("nbt").forGetter(i -> i.nbt)
|
||||
@@ -87,20 +90,20 @@ public class PartialNBTIngredient extends AbstractIngredient {
|
||||
|
||||
public static final IIngredientSerializer<PartialNBTIngredient> SERIALIZER = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public Codec<? extends PartialNBTIngredient> codec() {
|
||||
public MapCodec<? extends PartialNBTIngredient> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PartialNBTIngredient read(FriendlyByteBuf buffer) {
|
||||
var items = buffer.readList(b -> b.readRegistryIdUnsafe(ForgeRegistries.ITEMS));
|
||||
public PartialNBTIngredient read(RegistryFriendlyByteBuf buffer) {
|
||||
var items = buffer.readList(b -> Item.STREAM_CODEC.decode(buffer).get());
|
||||
var nbt = buffer.readNbt();
|
||||
return new PartialNBTIngredient(items, Objects.requireNonNull(nbt));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(FriendlyByteBuf buffer, PartialNBTIngredient value) {
|
||||
buffer.writeCollection(value.items, (b, item) -> b.writeRegistryIdUnsafe(ForgeRegistries.ITEMS, item));
|
||||
public void write(RegistryFriendlyByteBuf buffer, PartialNBTIngredient value) {
|
||||
buffer.writeCollection(value.items, (b, item) -> Item.STREAM_CODEC.encode(buffer, item.builtInRegistryHolder()));
|
||||
buffer.writeNbt(value.nbt);
|
||||
}
|
||||
};
|
||||
|
||||
+16
-9
@@ -7,12 +7,13 @@ package net.minecraftforge.common.crafting.ingredients;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import net.minecraft.network.FriendlyByteBuf;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.Ingredient;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
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. */
|
||||
@@ -32,7 +33,12 @@ public class StrictNBTIngredient extends AbstractIngredient {
|
||||
if (input == null)
|
||||
return false;
|
||||
//Can't use areItemStacksEqualUsingNBTShareTag because it compares stack size as well
|
||||
return this.stack.getItem() == input.getItem() && this.stack.getDamageValue() == input.getDamageValue() && this.stack.areShareTagsEqual(input);
|
||||
var inbt = input.get(DataComponents.CUSTOM_DATA);
|
||||
var tnbt = this.stack.get(DataComponents.CUSTOM_DATA);
|
||||
if(inbt == null || tnbt == null)
|
||||
return false;
|
||||
|
||||
return this.stack.getItem() == input.getItem() && tnbt.matchedBy(inbt.copyTag());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -45,24 +51,25 @@ public class StrictNBTIngredient extends AbstractIngredient {
|
||||
return SERIALIZER;
|
||||
}
|
||||
|
||||
public static final Codec<StrictNBTIngredient> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<StrictNBTIngredient> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ItemStack.CODEC.fieldOf("stack").forGetter(i -> i.stack)
|
||||
).apply(b, StrictNBTIngredient::new));
|
||||
|
||||
public static final IIngredientSerializer<StrictNBTIngredient> SERIALIZER = new IIngredientSerializer<>() {
|
||||
@Override
|
||||
public Codec<? extends StrictNBTIngredient> codec() {
|
||||
public MapCodec<? extends StrictNBTIngredient> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(FriendlyByteBuf buffer, StrictNBTIngredient value) {
|
||||
buffer.writeItem(value.stack);
|
||||
public void write(RegistryFriendlyByteBuf buffer, StrictNBTIngredient value) {
|
||||
ItemStack.STREAM_CODEC.encode(buffer, value.stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StrictNBTIngredient read(FriendlyByteBuf buffer) {
|
||||
return new StrictNBTIngredient(buffer.readItem());
|
||||
public StrictNBTIngredient read(RegistryFriendlyByteBuf buffer) {
|
||||
var stack = ItemStack.STREAM_CODEC.decode(buffer);
|
||||
return new StrictNBTIngredient(stack);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -7,10 +7,12 @@ package net.minecraftforge.common.data;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.common.collect.HashMultimap;
|
||||
@@ -19,15 +21,22 @@ import com.google.common.collect.Multimap;
|
||||
import net.minecraft.client.resources.ClientPackSource;
|
||||
import net.minecraft.client.resources.IndexedAssetSource;
|
||||
import net.minecraft.data.DataProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.packs.FilePackResources;
|
||||
import net.minecraft.server.packs.PackLocationInfo;
|
||||
import net.minecraft.server.packs.FilePackResources.FileResourcesSupplier;
|
||||
import net.minecraft.server.packs.PathPackResources;
|
||||
import net.minecraft.server.packs.repository.FolderRepositorySource;
|
||||
import net.minecraft.server.packs.repository.PackSource;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.world.level.validation.DirectoryValidator;
|
||||
import net.minecraft.world.level.validation.ForbiddenSymlinkInfo;
|
||||
import net.minecraft.server.packs.PackResources;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.PathPackResources.PathResourcesSupplier;
|
||||
import net.minecraft.server.packs.VanillaPackResources;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraftforge.client.model.generators.ModelBuilder;
|
||||
@@ -102,16 +111,29 @@ public class ExistingFileHelper {
|
||||
candidateClientResources.add(ClientPackSource.createVanillaPackSource(IndexedAssetSource.createIndexFs(assetsDir.toPath(), assetIndex)));
|
||||
}
|
||||
candidateServerResources.add(ServerPacksSource.createVanillaPackSource());
|
||||
|
||||
var symlinks = new ArrayList<ForbiddenSymlinkInfo>();
|
||||
var folder = new FolderRepositorySource.FolderPackDetector(new DirectoryValidator(p -> true));
|
||||
|
||||
for (Path existing : existingPacks) {
|
||||
File file = existing.toFile();
|
||||
PackResources pack = file.isDirectory() ? new PathPackResources(file.getName(), file.toPath(), false) : new FileResourcesSupplier(file, false).openPrimary(file.getName()); // FilePackResources(file.getName(), file, false, "");
|
||||
candidateClientResources.add(pack);
|
||||
candidateServerResources.add(pack);
|
||||
try {
|
||||
var info = new PackLocationInfo(existing.getFileName().toString(), Component.literal("data_gen"), PackSource.DEFAULT, Optional.empty());
|
||||
var supplier = folder.detectPackResources(existing, symlinks, false);
|
||||
PackResources pack = supplier.openPrimary(info);
|
||||
candidateClientResources.add(pack);
|
||||
candidateServerResources.add(pack);
|
||||
}catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
for (String existingMod : existingMods) {
|
||||
IModFileInfo modFileInfo = ModList.get().getModFileById(existingMod);
|
||||
if (modFileInfo != null) {
|
||||
PackResources pack = ResourcePackLoader.createPackForMod(modFileInfo);
|
||||
var root = modFileInfo.getFile().findResource("/");
|
||||
var supplier = new PathResourcesSupplier(root);
|
||||
var info = new PackLocationInfo("mod:" + existingMod, Component.literal("data_gen:" + existingMod), PackSource.DEFAULT, Optional.empty());
|
||||
var pack = supplier.openPrimary(info);
|
||||
candidateClientResources.add(pack);
|
||||
candidateServerResources.add(pack);
|
||||
}
|
||||
|
||||
@@ -6,13 +6,15 @@
|
||||
package net.minecraftforge.common.data;
|
||||
|
||||
import net.minecraft.advancements.critereon.ItemPredicate;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.loot.LootTableProvider;
|
||||
import net.minecraft.data.loot.LootTableSubProvider;
|
||||
import net.minecraft.data.loot.packs.VanillaLootTableProvider;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.Items;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.util.ProblemReporter;
|
||||
import net.minecraft.world.level.storage.loot.predicates.CompositeLootItemCondition;
|
||||
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
||||
import net.minecraft.world.level.storage.loot.predicates.InvertedLootItemCondition;
|
||||
@@ -24,8 +26,8 @@ import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
@@ -47,12 +49,12 @@ public final class ForgeLootTableProvider extends LootTableProvider {
|
||||
private static final String ENTRY_CONDITION = "f_7963" + "6_"; // LootPoolEntryContainer.conditions
|
||||
private static final String TERMS = "f_28560" + "9_"; // CompositeLootItemCondition.terms
|
||||
|
||||
public ForgeLootTableProvider(PackOutput packOutput) {
|
||||
super(packOutput, Set.of(), VanillaLootTableProvider.create(packOutput).getTables());
|
||||
public ForgeLootTableProvider(PackOutput pack, CompletableFuture<HolderLookup.Provider> lookup) {
|
||||
super(pack, Set.of(), VanillaLootTableProvider.create(pack, lookup).getTables(), lookup);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void validate(Map<ResourceLocation, LootTable> map, ValidationContext validationcontext) {
|
||||
protected void validate(Registry<LootTable> map, ValidationContext validationcontext, ProblemReporter report) {
|
||||
// Do not validate against all registered loot tables
|
||||
}
|
||||
|
||||
@@ -65,7 +67,7 @@ public final class ForgeLootTableProvider extends LootTableProvider {
|
||||
}
|
||||
|
||||
private LootTableSubProvider replaceAndFilterChangesOnly(LootTableSubProvider subProvider) {
|
||||
return newConsumer -> subProvider.generate((resourceLocation, builder) -> {
|
||||
return (provider, newConsumer) -> subProvider.generate(provider, (resourceLocation, builder) -> {
|
||||
if (findAndReplaceInLootTableBuilder(builder, Items.SHEARS, ToolActions.SHEARS_DIG)) {
|
||||
newConsumer.accept(resourceLocation, builder);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ package net.minecraftforge.common.data;
|
||||
import com.google.gson.JsonElement;
|
||||
import net.minecraft.advancements.AdvancementHolder;
|
||||
import net.minecraft.advancements.Advancement.Builder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderLookup.Provider;
|
||||
import net.minecraft.data.CachedOutput;
|
||||
import net.minecraft.data.PackOutput;
|
||||
import net.minecraft.data.recipes.RecipeOutput;
|
||||
@@ -44,8 +46,8 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
private final Map<Item, TagKey<Item>> replacements = new HashMap<>();
|
||||
private final Set<ResourceLocation> excludes = new HashSet<>();
|
||||
|
||||
public ForgeRecipeProvider(PackOutput packOutput) {
|
||||
super(packOutput);
|
||||
public ForgeRecipeProvider(PackOutput packOutput, CompletableFuture<HolderLookup.Provider> lookup) {
|
||||
super(packOutput, lookup);
|
||||
}
|
||||
|
||||
private void exclude(ItemLike item) {
|
||||
@@ -110,6 +112,11 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
@Override
|
||||
public void accept(ResourceLocation id, Recipe<?> recipe, ResourceLocation advancementId, JsonElement advancement) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Provider registry() {
|
||||
return consumer.registry();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,7 +151,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CompletableFuture<?> buildAdvancement(CachedOutput p_253674_, AdvancementHolder p_297687_) {
|
||||
protected CompletableFuture<?> buildAdvancement(CachedOutput p_253674_, HolderLookup.Provider p_335995_, AdvancementHolder p_297687_) {
|
||||
// NOOP - We don't replace any of the advancement things yet...
|
||||
return CompletableFuture.allOf();
|
||||
}
|
||||
@@ -172,7 +179,7 @@ public final class ForgeRecipeProvider extends VanillaRecipeProvider {
|
||||
|
||||
boolean modified = false;
|
||||
List<Value> items = new ArrayList<>();
|
||||
Value[] vanillaItems = getField(Ingredient.class, vanilla, 2); //This will probably crash between versions, if null fix index
|
||||
Value[] vanillaItems = getField(Ingredient.class, vanilla, 3); //This will probably crash between versions, if null fix index
|
||||
for (Value entry : vanillaItems) {
|
||||
if (entry instanceof ItemValue) {
|
||||
ItemStack stack = entry.getItems().stream().findFirst().orElse(ItemStack.EMPTY);
|
||||
|
||||
@@ -8,10 +8,10 @@ package net.minecraftforge.common.data;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.data.CachedOutput;
|
||||
import net.minecraft.data.DataProvider;
|
||||
import net.minecraft.data.PackOutput;
|
||||
@@ -32,25 +32,24 @@ import java.util.stream.Collectors;
|
||||
*
|
||||
* This provider only requires implementing {@link #start()} and calling {@link #add} from it.
|
||||
*/
|
||||
public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
{
|
||||
public abstract class GlobalLootModifierProvider implements DataProvider {
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
private final PackOutput output;
|
||||
private final String modid;
|
||||
private final Map<String, JsonElement> toSerialize = new HashMap<>();
|
||||
private final CompletableFuture<HolderLookup.Provider> registries;
|
||||
private final Map<String, IGlobalLootModifier> toSerialize = new HashMap<>();
|
||||
private boolean replace = false;
|
||||
|
||||
public GlobalLootModifierProvider(PackOutput output, String modid)
|
||||
{
|
||||
public GlobalLootModifierProvider(PackOutput output, String modid, CompletableFuture<HolderLookup.Provider> registries) {
|
||||
this.output = output;
|
||||
this.modid = modid;
|
||||
this.registries = registries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the "replace" key in global_loot_modifiers to true.
|
||||
*/
|
||||
protected void replacing()
|
||||
{
|
||||
protected void replacing() {
|
||||
this.replace = true;
|
||||
}
|
||||
|
||||
@@ -60,18 +59,25 @@ public abstract class GlobalLootModifierProvider implements DataProvider
|
||||
protected abstract void start();
|
||||
|
||||
@Override
|
||||
public CompletableFuture<?> run(CachedOutput cache)
|
||||
{
|
||||
public CompletableFuture<?> run(CachedOutput cache) {
|
||||
return this.registries.thenCompose(p -> this.run(cache, p));
|
||||
}
|
||||
|
||||
private CompletableFuture<?> run(CachedOutput cache, HolderLookup.Provider registries) {
|
||||
start();
|
||||
|
||||
Path forgePath = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("forge").resolve("loot_modifiers").resolve("global_loot_modifiers.json");
|
||||
Path forgePath = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("forge/loot_modifiers/global_loot_modifiers.json");
|
||||
Path modifierFolderPath = this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(this.modid).resolve("loot_modifiers");
|
||||
List<ResourceLocation> entries = new ArrayList<>();
|
||||
|
||||
ImmutableList.Builder<CompletableFuture<?>> futuresBuilder = new ImmutableList.Builder<>();
|
||||
|
||||
toSerialize.forEach(LamdbaExceptionUtils.rethrowBiConsumer((name, json) ->
|
||||
{
|
||||
|
||||
var ops = registries.createSerializationContext(JsonOps.INSTANCE);
|
||||
var codec = IGlobalLootModifier.DIRECT_CODEC;
|
||||
|
||||
toSerialize.forEach(LamdbaExceptionUtils.rethrowBiConsumer((name, instance) -> {
|
||||
var json = codec.encodeStart(ops, instance).getOrThrow();
|
||||
entries.add(new ResourceLocation(modid, name));
|
||||
Path modifierPath = modifierFolderPath.resolve(name + ".json");
|
||||
futuresBuilder.add(DataProvider.saveStable(cache, json, modifierPath));
|
||||
@@ -92,15 +98,12 @@ 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 -> {});
|
||||
this.toSerialize.put(modifier, json);
|
||||
public <T extends IGlobalLootModifier> void add(String modifier, T instance) {
|
||||
this.toSerialize.put(modifier, instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
public String getName() {
|
||||
return "Global Loot Modifiers : " + modid;
|
||||
}
|
||||
}
|
||||
@@ -87,7 +87,7 @@ public class JsonCodecProvider<T> implements DataProvider
|
||||
gather(LamdbaExceptionUtils.rethrowBiConsumer((id, value) -> {
|
||||
final Path path = outputFolder.resolve(id.getNamespace()).resolve(this.directory).resolve(id.getPath() + ".json");
|
||||
JsonElement encoded = this.codec.encodeStart(this.dynamicOps, value)
|
||||
.getOrThrow(false, msg -> LOGGER.error("Failed to encode {}: {}", path, msg));
|
||||
.getOrThrow( msg -> new IllegalStateException(String.format("Failed to encode {}: {}", path, msg)));
|
||||
/* TODO: Conditional JSONS
|
||||
ICondition[] conditions = this.conditions.get(id);
|
||||
if (conditions != null && conditions.length > 0)
|
||||
|
||||
@@ -12,8 +12,8 @@ import net.minecraft.client.Camera;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.SpawnPlacementType;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.SpawnPlacements;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
|
||||
import net.minecraft.world.entity.boss.wither.WitherBoss;
|
||||
@@ -31,7 +31,7 @@ import net.minecraft.world.level.levelgen.feature.configurations.TreeConfigurati
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.material.MapColor;
|
||||
import net.minecraft.world.level.material.PushReaction;
|
||||
import net.minecraft.world.level.pathfinder.BlockPathTypes;
|
||||
import net.minecraft.world.level.pathfinder.PathType;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.BlockPos;
|
||||
@@ -58,11 +58,9 @@ import net.minecraftforge.fml.loading.FMLEnvironment;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
public interface IForgeBlock
|
||||
{
|
||||
private Block self()
|
||||
{
|
||||
return (Block) this;
|
||||
public interface IForgeBlock {
|
||||
private Block self() {
|
||||
return (Block)this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,8 +78,7 @@ public interface IForgeBlock
|
||||
* @param entity the entity in question
|
||||
* @return the factor by which the entity's motion should be multiplied
|
||||
*/
|
||||
default float getFriction(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity)
|
||||
{
|
||||
default float getFriction(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity) {
|
||||
return self().getFriction();
|
||||
}
|
||||
|
||||
@@ -110,8 +107,7 @@ public interface IForgeBlock
|
||||
* </li>
|
||||
* </ul>
|
||||
*/
|
||||
default int getLightEmission(BlockState state, BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default int getLightEmission(BlockState state, BlockGetter level, BlockPos pos) {
|
||||
return state.getLightEmission();
|
||||
}
|
||||
|
||||
@@ -124,8 +120,7 @@ public interface IForgeBlock
|
||||
* @param entity The entity trying to use the ladder, CAN be null.
|
||||
* @return True if the block should act like a ladder
|
||||
*/
|
||||
default boolean isLadder(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity)
|
||||
{
|
||||
default boolean isLadder(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) {
|
||||
return state.is(BlockTags.CLIMBABLE);
|
||||
}
|
||||
|
||||
@@ -138,8 +133,7 @@ public interface IForgeBlock
|
||||
* @param trapdoorState The current state of the open trapdoor above
|
||||
* @return True if the block should act like a ladder
|
||||
*/
|
||||
default boolean makesOpenTrapdoorAboveClimbable(BlockState state, LevelReader level, BlockPos pos, BlockState trapdoorState)
|
||||
{
|
||||
default boolean makesOpenTrapdoorAboveClimbable(BlockState state, LevelReader level, BlockPos pos, BlockState trapdoorState) {
|
||||
return state.getBlock() instanceof LadderBlock && state.getValue(LadderBlock.FACING) == trapdoorState.getValue(TrapDoorBlock.FACING);
|
||||
}
|
||||
|
||||
@@ -151,8 +145,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return True if the block should deal damage
|
||||
*/
|
||||
default boolean isBurning(BlockState state, BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default boolean isBurning(BlockState state, BlockGetter level, BlockPos pos) {
|
||||
return this == Blocks.FIRE || this == Blocks.LAVA;
|
||||
}
|
||||
|
||||
@@ -164,8 +157,7 @@ public interface IForgeBlock
|
||||
* @param player The player damaging the block
|
||||
* @return True to spawn the drops
|
||||
*/
|
||||
default public boolean canHarvestBlock(BlockState state, BlockGetter level, BlockPos pos, Player player)
|
||||
{
|
||||
default public boolean canHarvestBlock(BlockState state, BlockGetter level, BlockPos pos, Player player) {
|
||||
return ForgeHooks.isCorrectToolForDrops(state, player);
|
||||
}
|
||||
|
||||
@@ -189,8 +181,7 @@ public interface IForgeBlock
|
||||
* @param fluid The current fluid state at current position
|
||||
* @return True if the block is actually destroyed.
|
||||
*/
|
||||
default boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
|
||||
{
|
||||
default boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) {
|
||||
self().playerWillDestroy(level, pos, state, player);
|
||||
return level.setBlock(pos, fluid.createLegacyBlock(), level.isClientSide ? 11 : 3);
|
||||
}
|
||||
@@ -206,8 +197,7 @@ public interface IForgeBlock
|
||||
* @param player The player or camera entity, null in some cases.
|
||||
* @return True to treat this as a bed
|
||||
*/
|
||||
default boolean isBed(BlockState state, BlockGetter level, BlockPos pos, @Nullable Entity player)
|
||||
{
|
||||
default boolean isBed(BlockState state, BlockGetter level, BlockPos pos, @Nullable Entity player) {
|
||||
return self() instanceof BedBlock; //TODO: Forge: Keep isBed function?
|
||||
}
|
||||
|
||||
@@ -223,10 +213,8 @@ public interface IForgeBlock
|
||||
* @param entity The entity respawning, often null
|
||||
* @return The spawn position or the empty optional if respawning here is not possible
|
||||
*/
|
||||
default Optional<Vec3> getRespawnPosition(BlockState state, EntityType<?> type, LevelReader levelReader, BlockPos pos, float orientation, @Nullable LivingEntity entity)
|
||||
{
|
||||
if (isBed(state, levelReader, pos, entity) && levelReader instanceof Level level && BedBlock.canSetSpawn(level))
|
||||
{
|
||||
default Optional<Vec3> getRespawnPosition(BlockState state, EntityType<?> type, LevelReader levelReader, BlockPos pos, float orientation, @Nullable LivingEntity entity) {
|
||||
if (isBed(state, levelReader, pos, entity) && levelReader instanceof Level level && BedBlock.canSetSpawn(level)) {
|
||||
return BedBlock.findStandUpPosition(type, levelReader, pos, state.getValue(BedBlock.FACING), orientation);
|
||||
}
|
||||
return Optional.empty();
|
||||
@@ -242,8 +230,7 @@ public interface IForgeBlock
|
||||
* @param type The Mob Category Type
|
||||
* @return True to allow a mob of the specified category to spawn, false to prevent it.
|
||||
*/
|
||||
default boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacements.Type type, EntityType<?> entityType)
|
||||
{
|
||||
default boolean isValidSpawn(BlockState state, BlockGetter level, BlockPos pos, SpawnPlacementType type, EntityType<?> entityType) {
|
||||
return state.isValidSpawn(level, pos, entityType);
|
||||
}
|
||||
|
||||
@@ -255,8 +242,7 @@ public interface IForgeBlock
|
||||
* @param sleeper The sleeper or camera entity, null in some cases.
|
||||
* @param occupied True if we are occupying the bed, or false if they are stopping use of the bed
|
||||
*/
|
||||
default void setBedOccupied(BlockState state, Level level, BlockPos pos, LivingEntity sleeper, boolean occupied)
|
||||
{
|
||||
default void setBedOccupied(BlockState state, Level level, BlockPos pos, LivingEntity sleeper, boolean occupied) {
|
||||
level.setBlock(pos, state.setValue(BedBlock.OCCUPIED, occupied), 3);
|
||||
}
|
||||
|
||||
@@ -269,8 +255,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return Bed direction
|
||||
*/
|
||||
default Direction getBedDirection(BlockState state, LevelReader level, BlockPos pos)
|
||||
{
|
||||
default Direction getBedDirection(BlockState state, LevelReader level, BlockPos pos) {
|
||||
return state.getValue(HorizontalDirectionalBlock.FACING);
|
||||
}
|
||||
|
||||
@@ -282,8 +267,7 @@ public interface IForgeBlock
|
||||
* @param explosion The explosion
|
||||
* @return The amount of the explosion absorbed.
|
||||
*/
|
||||
default float getExplosionResistance(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion)
|
||||
{
|
||||
default float getExplosionResistance(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) {
|
||||
return self().getExplosionResistance();
|
||||
}
|
||||
|
||||
@@ -294,8 +278,7 @@ public interface IForgeBlock
|
||||
* @param target The full target the player is looking at
|
||||
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
|
||||
*/
|
||||
default ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player)
|
||||
{
|
||||
default ItemStack getCloneItemStack(BlockState state, HitResult target, LevelReader level, BlockPos pos, Player player) {
|
||||
return self().getCloneItemStack(level, pos, state);
|
||||
}
|
||||
|
||||
@@ -311,8 +294,7 @@ public interface IForgeBlock
|
||||
* @param numberOfParticles That vanilla level have spawned
|
||||
* @return True to prevent vanilla landing particles from spawning
|
||||
*/
|
||||
default boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
|
||||
{
|
||||
default boolean addLandingEffects(BlockState state1, ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -328,8 +310,7 @@ public interface IForgeBlock
|
||||
* @param entity The entity running on the block.
|
||||
* @return True to prevent vanilla running particles from spawning.
|
||||
*/
|
||||
default boolean addRunningEffects(BlockState state, Level level, BlockPos pos, Entity entity)
|
||||
{
|
||||
default boolean addRunningEffects(BlockState state, Level level, BlockPos pos, Entity entity) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -372,8 +353,7 @@ public interface IForgeBlock
|
||||
* @param config Configuration of the trunk placer. Consider azalea trees, which should place rooted dirt instead of regular dirt.
|
||||
* @return True to ignore vanilla behaviour
|
||||
*/
|
||||
default boolean onTreeGrow(BlockState state, LevelReader level, BiConsumer<BlockPos, BlockState> placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config)
|
||||
{
|
||||
default boolean onTreeGrow(BlockState state, LevelReader level, BiConsumer<BlockPos, BlockState> placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -386,8 +366,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return True if the soil should be considered fertile.
|
||||
*/
|
||||
default boolean isFertile(BlockState state, BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default boolean isFertile(BlockState state, BlockGetter level, BlockPos pos) {
|
||||
if (state.is(Blocks.FARMLAND))
|
||||
return state.getValue(FarmBlock.MOISTURE) > 0;
|
||||
|
||||
@@ -402,8 +381,7 @@ public interface IForgeBlock
|
||||
* @param conduit Conduit position in level
|
||||
* @return True, to support the conduit, and make it active with this block.
|
||||
*/
|
||||
default boolean isConduitFrame(BlockState state, LevelReader level, BlockPos pos, BlockPos conduit)
|
||||
{
|
||||
default boolean isConduitFrame(BlockState state, LevelReader level, BlockPos pos, BlockPos conduit) {
|
||||
return state.getBlock() == Blocks.PRISMARINE ||
|
||||
state.getBlock() == Blocks.PRISMARINE_BRICKS ||
|
||||
state.getBlock() == Blocks.SEA_LANTERN ||
|
||||
@@ -418,8 +396,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return True, to support being part of a nether portal frame, false otherwise.
|
||||
*/
|
||||
default boolean isPortalFrame(BlockState state, BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default boolean isPortalFrame(BlockState state, BlockGetter level, BlockPos pos) {
|
||||
return state.is(Blocks.OBSIDIAN);
|
||||
}
|
||||
|
||||
@@ -434,13 +411,11 @@ public interface IForgeBlock
|
||||
* @param silkTouchLevel silk touch enchantment level of tool being used
|
||||
* @return Amount of XP from breaking this block.
|
||||
*/
|
||||
default int getExpDrop(BlockState state, LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel)
|
||||
{
|
||||
default int getExpDrop(BlockState state, LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
default BlockState rotate(BlockState state, LevelAccessor level, BlockPos pos, Rotation direction)
|
||||
{
|
||||
default BlockState rotate(BlockState state, LevelAccessor level, BlockPos pos, Rotation direction) {
|
||||
return state.rotate(direction);
|
||||
}
|
||||
|
||||
@@ -450,8 +425,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return The amount of enchanting power this block produces.
|
||||
*/
|
||||
default float getEnchantPowerBonus(BlockState state, LevelReader level, BlockPos pos)
|
||||
{
|
||||
default float getEnchantPowerBonus(BlockState state, LevelReader level, BlockPos pos) {
|
||||
return state.is(BlockTags.ENCHANTMENT_POWER_PROVIDER) ? 1: 0;
|
||||
}
|
||||
|
||||
@@ -470,8 +444,7 @@ public interface IForgeBlock
|
||||
* @param side The INPUT side of the block to be powered - ie the opposite of this block's output side
|
||||
* @return Whether Block#isProvidingWeakPower should be called when determining indirect power
|
||||
*/
|
||||
default boolean shouldCheckWeakPower(BlockState state, SignalGetter level, BlockPos pos, Direction side)
|
||||
{
|
||||
default boolean shouldCheckWeakPower(BlockState state, SignalGetter level, BlockPos pos, Direction side) {
|
||||
return state.isRedstoneConductor(level, pos);
|
||||
}
|
||||
|
||||
@@ -484,8 +457,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return true To be notified of changes
|
||||
*/
|
||||
default boolean getWeakChanges(BlockState state, LevelReader level, BlockPos pos)
|
||||
{
|
||||
default boolean getWeakChanges(BlockState state, LevelReader level, BlockPos pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -497,10 +469,7 @@ public interface IForgeBlock
|
||||
* @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context
|
||||
* @return A SoundType to use
|
||||
*/
|
||||
default SoundType getSoundType(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity)
|
||||
{
|
||||
return self().getSoundType(state);
|
||||
}
|
||||
SoundType getSoundType(BlockState state, LevelReader level, BlockPos pos, @Nullable Entity entity);
|
||||
|
||||
/**
|
||||
* @param state The state
|
||||
@@ -510,10 +479,9 @@ public interface IForgeBlock
|
||||
* @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam
|
||||
*/
|
||||
@Nullable
|
||||
default float[] getBeaconColorMultiplier(BlockState state, LevelReader level, BlockPos pos, BlockPos beaconPos)
|
||||
{
|
||||
if (self() instanceof BeaconBeamBlock)
|
||||
return ((BeaconBeamBlock) self()).getColor().getTextureDiffuseColors();
|
||||
default float[] getBeaconColorMultiplier(BlockState state, LevelReader level, BlockPos pos, BlockPos beaconPos) {
|
||||
if (self() instanceof BeaconBeamBlock beam)
|
||||
return beam.getColor().getTextureDiffuseColors();
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -528,8 +496,7 @@ public interface IForgeBlock
|
||||
* @param viewpoint the viewpoint
|
||||
* @return the block state that should be 'seen'
|
||||
*/
|
||||
default BlockState getStateAtViewpoint(BlockState state, BlockGetter level, BlockPos pos, Vec3 viewpoint)
|
||||
{
|
||||
default BlockState getStateAtViewpoint(BlockState state, BlockGetter level, BlockPos pos, Vec3 viewpoint) {
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -544,9 +511,8 @@ public interface IForgeBlock
|
||||
* @return the path type of this block
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob)
|
||||
{
|
||||
return state.getBlock() == Blocks.LAVA ? BlockPathTypes.LAVA : state.isBurning(level, pos) ? BlockPathTypes.DAMAGE_FIRE : null;
|
||||
default PathType getBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob) {
|
||||
return state.getBlock() == Blocks.LAVA ? PathType.LAVA : state.isBurning(level, pos) ? PathType.DAMAGE_FIRE : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -563,10 +529,9 @@ public interface IForgeBlock
|
||||
* @return the path type of this block
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getAdjacentBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType)
|
||||
{
|
||||
if (state.is(Blocks.SWEET_BERRY_BUSH)) return BlockPathTypes.DANGER_OTHER;
|
||||
else if (WalkNodeEvaluator.isBurningBlock(state)) return BlockPathTypes.DANGER_FIRE;
|
||||
default PathType getAdjacentBlockPathType(BlockState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) {
|
||||
if (state.is(Blocks.SWEET_BERRY_BUSH)) return PathType.DANGER_OTHER;
|
||||
else if (WalkNodeEvaluator.isBurningBlock(state)) return PathType.DANGER_FIRE;
|
||||
else return null;
|
||||
}
|
||||
|
||||
@@ -574,8 +539,7 @@ public interface IForgeBlock
|
||||
* @param state The state
|
||||
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
|
||||
*/
|
||||
default boolean isSlimeBlock(BlockState state)
|
||||
{
|
||||
default boolean isSlimeBlock(BlockState state) {
|
||||
return state.getBlock() == Blocks.SLIME_BLOCK;
|
||||
}
|
||||
|
||||
@@ -583,8 +547,7 @@ public interface IForgeBlock
|
||||
* @param state The state
|
||||
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
|
||||
*/
|
||||
default boolean isStickyBlock(BlockState state)
|
||||
{
|
||||
default boolean isStickyBlock(BlockState state) {
|
||||
return state.getBlock() == Blocks.SLIME_BLOCK || state.getBlock() == Blocks.HONEY_BLOCK;
|
||||
}
|
||||
|
||||
@@ -594,8 +557,7 @@ public interface IForgeBlock
|
||||
* @param other Other block
|
||||
* @return True to link blocks
|
||||
*/
|
||||
default boolean canStickTo(BlockState state, BlockState other)
|
||||
{
|
||||
default boolean canStickTo(BlockState state, BlockState other) {
|
||||
if (state.getBlock() == Blocks.HONEY_BLOCK && other.getBlock() == Blocks.SLIME_BLOCK) return false;
|
||||
if (state.getBlock() == Blocks.SLIME_BLOCK && other.getBlock() == Blocks.HONEY_BLOCK) return false;
|
||||
return state.isStickyBlock() || other.isStickyBlock();
|
||||
@@ -611,8 +573,7 @@ public interface IForgeBlock
|
||||
* @param direction The direction that the fire is coming from
|
||||
* @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire
|
||||
*/
|
||||
default int getFlammability(BlockState state, BlockGetter level, BlockPos pos, Direction direction)
|
||||
{
|
||||
default int getFlammability(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
|
||||
return ((FireBlock)Blocks.FIRE).getBurnOdds(state);
|
||||
}
|
||||
|
||||
@@ -626,8 +587,7 @@ public interface IForgeBlock
|
||||
* @param direction The direction that the fire is coming from
|
||||
* @return True if the face can be on fire, false otherwise.
|
||||
*/
|
||||
default boolean isFlammable(BlockState state, BlockGetter level, BlockPos pos, Direction direction)
|
||||
{
|
||||
default boolean isFlammable(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
|
||||
return state.getFlammability(level, pos, direction) > 0;
|
||||
}
|
||||
|
||||
@@ -652,8 +612,7 @@ public interface IForgeBlock
|
||||
* @param direction The direction that the fire is coming from
|
||||
* @return A number that is used to determine the speed of fire growth around the block
|
||||
*/
|
||||
default int getFireSpreadSpeed(BlockState state, BlockGetter level, BlockPos pos, Direction direction)
|
||||
{
|
||||
default int getFireSpreadSpeed(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
|
||||
return ((FireBlock)Blocks.FIRE).getIgniteOdds(state);
|
||||
}
|
||||
|
||||
@@ -668,8 +627,7 @@ public interface IForgeBlock
|
||||
* @param direction The direction that the fire is coming from
|
||||
* @return True if this block sustains fire, meaning it will never go out.
|
||||
*/
|
||||
default boolean isFireSource(BlockState state, LevelReader level, BlockPos pos, Direction direction)
|
||||
{
|
||||
default boolean isFireSource(BlockState state, LevelReader level, BlockPos pos, Direction direction) {
|
||||
return state.is(level.dimensionType().infiniburn());
|
||||
}
|
||||
|
||||
@@ -681,15 +639,11 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @return True to allow the ender dragon to destroy this block
|
||||
*/
|
||||
default boolean canEntityDestroy(BlockState state, BlockGetter level, BlockPos pos, Entity entity)
|
||||
{
|
||||
if (entity instanceof EnderDragon)
|
||||
{
|
||||
default boolean canEntityDestroy(BlockState state, BlockGetter level, BlockPos pos, Entity entity) {
|
||||
if (entity instanceof EnderDragon) {
|
||||
return !this.self().defaultBlockState().is(BlockTags.DRAGON_IMMUNE);
|
||||
}
|
||||
else if ((entity instanceof WitherBoss) ||
|
||||
(entity instanceof WitherSkull))
|
||||
{
|
||||
} else if ((entity instanceof WitherBoss) ||
|
||||
(entity instanceof WitherSkull)) {
|
||||
return state.isAir() || WitherBoss.canDestroy(state);
|
||||
}
|
||||
|
||||
@@ -699,8 +653,7 @@ public interface IForgeBlock
|
||||
/**
|
||||
* Determines if this block should drop loot when exploded.
|
||||
*/
|
||||
default boolean canDropFromExplosion(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion)
|
||||
{
|
||||
default boolean canDropFromExplosion(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) {
|
||||
return state.getBlock().dropFromExplosion(explosion);
|
||||
}
|
||||
|
||||
@@ -713,8 +666,7 @@ public interface IForgeBlock
|
||||
* @param pos Block position in level
|
||||
* @param explosion The explosion instance affecting the block
|
||||
*/
|
||||
default void onBlockExploded(BlockState state, Level level, BlockPos pos, Explosion explosion)
|
||||
{
|
||||
default void onBlockExploded(BlockState state, Level level, BlockPos pos, Explosion explosion) {
|
||||
level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3);
|
||||
self().wasExploded(level, pos, explosion);
|
||||
}
|
||||
@@ -723,8 +675,7 @@ public interface IForgeBlock
|
||||
* Determines if this block's collision box should be treated as though it can extend above its block space.
|
||||
* Use this to replicate fence and wall behavior.
|
||||
*/
|
||||
default boolean collisionExtendsVertically(BlockState state, BlockGetter level, BlockPos pos, Entity collidingEntity)
|
||||
{
|
||||
default boolean collisionExtendsVertically(BlockState state, BlockGetter level, BlockPos pos, Entity collidingEntity) {
|
||||
return state.is(BlockTags.FENCES) || state.is(BlockTags.WALLS) || self() instanceof FenceGateBlock;
|
||||
}
|
||||
|
||||
@@ -737,8 +688,7 @@ public interface IForgeBlock
|
||||
* @param fluidState The state of the fluid
|
||||
* @return Whether the fluid overlay texture should be used
|
||||
*/
|
||||
default boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter level, BlockPos pos, FluidState fluidState)
|
||||
{
|
||||
default boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter level, BlockPos pos, FluidState fluidState) {
|
||||
return state.getBlock() instanceof HalfTransparentBlock || state.getBlock() instanceof LeavesBlock;
|
||||
}
|
||||
|
||||
@@ -755,38 +705,29 @@ public interface IForgeBlock
|
||||
* @return The resulting state after the action has been performed
|
||||
*/
|
||||
@Nullable
|
||||
default BlockState getToolModifiedState(BlockState state, UseOnContext context, ToolAction toolAction, boolean simulate)
|
||||
{
|
||||
default BlockState getToolModifiedState(BlockState state, UseOnContext context, ToolAction toolAction, boolean simulate) {
|
||||
ItemStack itemStack = context.getItemInHand();
|
||||
if (!itemStack.canPerformAction(toolAction))
|
||||
return null;
|
||||
|
||||
if (ToolActions.AXE_STRIP == toolAction)
|
||||
{
|
||||
if (ToolActions.AXE_STRIP == toolAction) {
|
||||
return AxeItem.getAxeStrippingState(state);
|
||||
} else if (ToolActions.AXE_SCRAPE == toolAction)
|
||||
{
|
||||
} else if (ToolActions.AXE_SCRAPE == toolAction) {
|
||||
return WeatheringCopper.getPrevious(state).orElse(null);
|
||||
} else if (ToolActions.AXE_WAX_OFF == toolAction)
|
||||
{
|
||||
} else if (ToolActions.AXE_WAX_OFF == toolAction) {
|
||||
return Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(state.getBlock())).map(block -> block.withPropertiesOf(state)).orElse(null);
|
||||
} else if (ToolActions.SHOVEL_FLATTEN == toolAction)
|
||||
{
|
||||
} else if (ToolActions.SHOVEL_FLATTEN == toolAction) {
|
||||
return ShovelItem.getShovelPathingState(state);
|
||||
} else if (ToolActions.HOE_TILL == toolAction)
|
||||
{
|
||||
} else if (ToolActions.HOE_TILL == toolAction) {
|
||||
// Logic copied from HoeItem#TILLABLES; needs to be kept in sync during updating
|
||||
Block block = state.getBlock();
|
||||
if (block == Blocks.ROOTED_DIRT)
|
||||
{
|
||||
if (!simulate && !context.getLevel().isClientSide)
|
||||
{
|
||||
if (block == Blocks.ROOTED_DIRT) {
|
||||
if (!simulate && !context.getLevel().isClientSide) {
|
||||
Block.popResourceFromFace(context.getLevel(), context.getClickedPos(), context.getClickedFace(), new ItemStack(Items.HANGING_ROOTS));
|
||||
}
|
||||
return Blocks.DIRT.defaultBlockState();
|
||||
} else if ((block == Blocks.GRASS_BLOCK || block == Blocks.DIRT_PATH || block == Blocks.DIRT || block == Blocks.COARSE_DIRT) &&
|
||||
context.getLevel().getBlockState(context.getClickedPos().above()).isAir())
|
||||
{
|
||||
context.getLevel().getBlockState(context.getClickedPos().above()).isAir()) {
|
||||
return block == Blocks.COARSE_DIRT ? Blocks.DIRT.defaultBlockState() : Blocks.FARMLAND.defaultBlockState();
|
||||
}
|
||||
}
|
||||
@@ -803,8 +744,7 @@ public interface IForgeBlock
|
||||
* @param entity The entity on the scaffolding
|
||||
* @return True if the block should act like scaffolding
|
||||
*/
|
||||
default boolean isScaffolding(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity)
|
||||
{
|
||||
default boolean isScaffolding(BlockState state, LevelReader level, BlockPos pos, LivingEntity entity) {
|
||||
return state.is(Blocks.SCAFFOLDING);
|
||||
}
|
||||
|
||||
@@ -837,23 +777,15 @@ public interface IForgeBlock
|
||||
* 2. {@code neighborState.updateShape(fromDirection, stateOfYourBlock, level, neighborBlockPos, yourBlockPos)},
|
||||
* where {@code fromDirection} is defined from the neighbor block's point of view.
|
||||
*/
|
||||
default boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction)
|
||||
{
|
||||
if (state.is(Blocks.REDSTONE_WIRE))
|
||||
{
|
||||
default boolean canConnectRedstone(BlockState state, BlockGetter level, BlockPos pos, @Nullable Direction direction) {
|
||||
if (state.is(Blocks.REDSTONE_WIRE)) {
|
||||
return true;
|
||||
}
|
||||
else if (state.is(Blocks.REPEATER))
|
||||
{
|
||||
} else if (state.is(Blocks.REPEATER)) {
|
||||
Direction facing = state.getValue(RepeaterBlock.FACING);
|
||||
return facing == direction || facing.getOpposite() == direction;
|
||||
}
|
||||
else if (state.is(Blocks.OBSERVER))
|
||||
{
|
||||
} else if (state.is(Blocks.OBSERVER)) {
|
||||
return direction == state.getValue(ObserverBlock.FACING);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
return state.isSignalSource() && direction != null;
|
||||
}
|
||||
}
|
||||
@@ -878,8 +810,7 @@ public interface IForgeBlock
|
||||
* @param neighborState The neighboring blocks {@link BlockState}
|
||||
* @param dir The direction towards the neighboring block
|
||||
*/
|
||||
default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState state, BlockState neighborState, Direction dir)
|
||||
{
|
||||
default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState state, BlockState neighborState, Direction dir) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -888,10 +819,8 @@ public interface IForgeBlock
|
||||
* If this returns true, {@link IForgeBlockState#hidesNeighborFace(BlockGetter, BlockPos, BlockState, Direction)}
|
||||
* will be called on the neighboring block.
|
||||
*/
|
||||
default boolean supportsExternalFaceHiding(BlockState state)
|
||||
{
|
||||
if (FMLEnvironment.dist.isClient())
|
||||
{
|
||||
default boolean supportsExternalFaceHiding(BlockState state) {
|
||||
if (FMLEnvironment.dist.isClient()) {
|
||||
return !ForgeHooksClient.isBlockInSolidLayer(state);
|
||||
}
|
||||
return true;
|
||||
@@ -927,8 +856,7 @@ public interface IForgeBlock
|
||||
* @param fluidPos the position of the fluid
|
||||
* @return {@code true} if the block can be hydrated, {@code false} otherwise
|
||||
*/
|
||||
default boolean canBeHydrated(BlockState state, BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos)
|
||||
{
|
||||
default boolean canBeHydrated(BlockState state, BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos) {
|
||||
return fluid.canHydrate(getter, fluidPos, state, pos);
|
||||
}
|
||||
|
||||
@@ -940,8 +868,7 @@ public interface IForgeBlock
|
||||
* @param pos The blocks position in the level
|
||||
* @param defaultColor The {@code MapColor} configured for the given {@code BlockState} in the {@link BlockBehaviour.Properties}
|
||||
*/
|
||||
default MapColor getMapColor(BlockState state, BlockGetter level, BlockPos pos, MapColor defaultColor)
|
||||
{
|
||||
default MapColor getMapColor(BlockState state, BlockGetter level, BlockPos pos, MapColor defaultColor) {
|
||||
return defaultColor;
|
||||
}
|
||||
|
||||
@@ -968,8 +895,7 @@ public interface IForgeBlock
|
||||
* @return The appearance of this block on the given side. By default, the current state
|
||||
* @see IForgeBlockState#getAppearance(BlockAndTintGetter, BlockPos, Direction, BlockState, BlockPos)
|
||||
*/
|
||||
default BlockState getAppearance(BlockState state, BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos)
|
||||
{
|
||||
default BlockState getAppearance(BlockState state, BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos) {
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -988,8 +914,7 @@ public interface IForgeBlock
|
||||
* @return the PushReaction of this state or {@code null} if the one passed into the block properties should be used
|
||||
*/
|
||||
@Nullable
|
||||
default PushReaction getPistonPushReaction(BlockState state)
|
||||
{
|
||||
default PushReaction getPistonPushReaction(BlockState state) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -19,26 +19,16 @@ import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.world.phys.shapes.VoxelShape;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.client.model.data.ModelData;
|
||||
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
|
||||
import net.minecraftforge.common.capabilities.ICapabilityProvider;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
{
|
||||
private BlockEntity self() { return (BlockEntity) this; }
|
||||
|
||||
@Override
|
||||
default void deserializeNBT(CompoundTag nbt)
|
||||
{
|
||||
self().load(nbt);
|
||||
}
|
||||
|
||||
@Override
|
||||
default CompoundTag serializeNBT()
|
||||
{
|
||||
return self().saveWithFullMetadata();
|
||||
public interface IForgeBlockEntity extends ICapabilityProvider {
|
||||
private BlockEntity self() {
|
||||
return (BlockEntity)this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,34 +40,24 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
* @param net The NetworkManager the packet originated from
|
||||
* @param pkt The data packet
|
||||
*/
|
||||
default void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt)
|
||||
{
|
||||
default void onDataPacket(Connection connection, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider lookup) {
|
||||
CompoundTag compoundtag = pkt.getTag();
|
||||
if (compoundtag != null) {
|
||||
self().load(compoundtag);
|
||||
self().loadWithComponents(compoundtag, lookup);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the chunk's TE update tag, gotten from {@link BlockEntity#getUpdateTag()}, is received on the client.
|
||||
* <p>
|
||||
* Used to handle this tag in a special way. By default this simply calls {@link BlockEntity#load(CompoundTag)}.
|
||||
* Used to handle this tag in a special way. By default this simply calls {@link BlockEntity#loadWithComponents(CompoundTag, HolderLookup.Provider)}.
|
||||
*
|
||||
* @param tag The {@link CompoundTag} sent from {@link BlockEntity#getUpdateTag()}
|
||||
*/
|
||||
default void handleUpdateTag(CompoundTag tag)
|
||||
{
|
||||
self().load(tag);
|
||||
default void handleUpdateTag(CompoundTag tag, HolderLookup.Provider holders) {
|
||||
self().loadWithComponents(tag, holders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a {@link CompoundTag} that can be used to store custom data for this block entity.
|
||||
* It will be written, and read from disc, so it persists over world saves.
|
||||
*
|
||||
* @return A compound tag for custom persistent data
|
||||
*/
|
||||
CompoundTag getPersistentData();
|
||||
|
||||
default void onChunkUnloaded(){}
|
||||
|
||||
/**
|
||||
@@ -85,8 +65,7 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
* or right before the first tick when the chunk is generated or loaded from disk.
|
||||
* Override instead of adding {@code if (firstTick)} stuff in update.
|
||||
*/
|
||||
default void onLoad()
|
||||
{
|
||||
default void onLoad() {
|
||||
requestModelDataUpdate();
|
||||
}
|
||||
|
||||
@@ -137,15 +116,12 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
* Requests a refresh for the model data of your TE
|
||||
* Call this every time your {@link #getModelData()} changes
|
||||
*/
|
||||
default void requestModelDataUpdate()
|
||||
{
|
||||
default void requestModelDataUpdate() {
|
||||
BlockEntity te = self();
|
||||
Level level = te.getLevel();
|
||||
if (level != null && level.isClientSide)
|
||||
{
|
||||
if (level != null && level.isClientSide) {
|
||||
var modelDataManager = level.getModelDataManager();
|
||||
if (modelDataManager != null)
|
||||
{
|
||||
if (modelDataManager != null) {
|
||||
modelDataManager.requestRefresh(te);
|
||||
}
|
||||
}
|
||||
@@ -158,8 +134,7 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
* <b>Note that this method may be called on a chunk render thread instead of the main client thread</b>
|
||||
* @return Your model data
|
||||
*/
|
||||
default @NotNull ModelData getModelData()
|
||||
{
|
||||
default @NotNull ModelData getModelData() {
|
||||
return ModelData.EMPTY;
|
||||
}
|
||||
|
||||
@@ -169,8 +144,7 @@ public interface IForgeBlockEntity extends ICapabilitySerializable<CompoundTag>
|
||||
* @param player the local player currently viewing this {@code BlockEntity}
|
||||
* @return {@code true} to enable outline processing
|
||||
*/
|
||||
default boolean hasCustomOutlineRendering(Player player)
|
||||
{
|
||||
default boolean hasCustomOutlineRendering(Player player) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.SpawnPlacements.Type;
|
||||
import net.minecraft.world.entity.SpawnPlacementType;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
@@ -23,7 +23,7 @@ import net.minecraft.world.level.SignalGetter;
|
||||
import net.minecraft.world.level.levelgen.feature.configurations.TreeConfiguration;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.pathfinder.BlockPathTypes;
|
||||
import net.minecraft.world.level.pathfinder.PathType;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
@@ -45,10 +45,8 @@ import net.minecraftforge.common.ToolActions;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public interface IForgeBlockState
|
||||
{
|
||||
private BlockState self()
|
||||
{
|
||||
public interface IForgeBlockState {
|
||||
private BlockState self() {
|
||||
return (BlockState)this;
|
||||
}
|
||||
|
||||
@@ -66,16 +64,14 @@ public interface IForgeBlockState
|
||||
* @param entity the entity in question
|
||||
* @return the factor by which the entity's motion should be multiplied
|
||||
*/
|
||||
default float getFriction(LevelReader level, BlockPos pos, @Nullable Entity entity)
|
||||
{
|
||||
default float getFriction(LevelReader level, BlockPos pos, @Nullable Entity entity) {
|
||||
return self().getBlock().getFriction(self(), level, pos, entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a light value for this block, taking into account the given state and coordinates, normal ranges are between 0 and 15
|
||||
*/
|
||||
default int getLightEmission(BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default int getLightEmission(BlockGetter level, BlockPos pos) {
|
||||
return self().getBlock().getLightEmission(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -87,8 +83,7 @@ public interface IForgeBlockState
|
||||
* @param entity The entity trying to use the ladder, CAN be null.
|
||||
* @return True if the block should act like a ladder
|
||||
*/
|
||||
default boolean isLadder(LevelReader level, BlockPos pos, LivingEntity entity)
|
||||
{
|
||||
default boolean isLadder(LevelReader level, BlockPos pos, LivingEntity entity) {
|
||||
return self().getBlock().isLadder(self(), level, pos, entity);
|
||||
}
|
||||
|
||||
@@ -100,8 +95,7 @@ public interface IForgeBlockState
|
||||
* @param player The player damaging the block
|
||||
* @return True to spawn the drops
|
||||
*/
|
||||
default boolean canHarvestBlock(BlockGetter level, BlockPos pos, Player player)
|
||||
{
|
||||
default boolean canHarvestBlock(BlockGetter level, BlockPos pos, Player player) {
|
||||
return self().getBlock().canHarvestBlock(self(), level, pos, player);
|
||||
}
|
||||
|
||||
@@ -124,8 +118,7 @@ public interface IForgeBlockState
|
||||
* @param fluid The current fluid and block state for the position in the level.
|
||||
* @return True if the block is actually destroyed.
|
||||
*/
|
||||
default boolean onDestroyedByPlayer(Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid)
|
||||
{
|
||||
default boolean onDestroyedByPlayer(Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) {
|
||||
return self().getBlock().onDestroyedByPlayer(self(), level, pos, player, willHarvest, fluid);
|
||||
}
|
||||
|
||||
@@ -139,8 +132,7 @@ public interface IForgeBlockState
|
||||
* @param sleeper The sleeper or camera entity, null in some cases.
|
||||
* @return True to treat this as a bed
|
||||
*/
|
||||
default boolean isBed(BlockGetter level, BlockPos pos, @Nullable LivingEntity sleeper)
|
||||
{
|
||||
default boolean isBed(BlockGetter level, BlockPos pos, @Nullable LivingEntity sleeper) {
|
||||
return self().getBlock().isBed(self(), level, pos, sleeper);
|
||||
}
|
||||
|
||||
@@ -153,8 +145,7 @@ public interface IForgeBlockState
|
||||
* @param type The Mob Category Type
|
||||
* @return True to allow a mob of the specified category to spawn, false to prevent it.
|
||||
*/
|
||||
default boolean isValidSpawn(LevelReader level, BlockPos pos, Type type, EntityType<?> entityType)
|
||||
{
|
||||
default boolean isValidSpawn(LevelReader level, BlockPos pos, SpawnPlacementType type, EntityType<?> entityType) {
|
||||
return self().getBlock().isValidSpawn(self(), level, pos, type, entityType);
|
||||
}
|
||||
|
||||
@@ -169,8 +160,7 @@ public interface IForgeBlockState
|
||||
* @param entity The entity respawning, often null
|
||||
* @return The spawn position or the empty optional if respawning here is not possible
|
||||
*/
|
||||
default Optional<Vec3> getRespawnPosition(EntityType<?> type, LevelReader level, BlockPos pos, float orientation, @Nullable LivingEntity entity)
|
||||
{
|
||||
default Optional<Vec3> getRespawnPosition(EntityType<?> type, LevelReader level, BlockPos pos, float orientation, @Nullable LivingEntity entity) {
|
||||
return self().getBlock().getRespawnPosition(self(), type, level, pos, orientation, entity);
|
||||
}
|
||||
|
||||
@@ -182,8 +172,7 @@ public interface IForgeBlockState
|
||||
* @param sleeper The sleeper or camera entity, null in some cases.
|
||||
* @param occupied True if we are occupying the bed, or false if they are stopping use of the bed
|
||||
*/
|
||||
default void setBedOccupied(Level level, BlockPos pos, LivingEntity sleeper, boolean occupied)
|
||||
{
|
||||
default void setBedOccupied(Level level, BlockPos pos, LivingEntity sleeper, boolean occupied) {
|
||||
self().getBlock().setBedOccupied(self(), level, pos, sleeper, occupied);
|
||||
}
|
||||
|
||||
@@ -195,8 +184,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return Bed direction
|
||||
*/
|
||||
default Direction getBedDirection(LevelReader level, BlockPos pos)
|
||||
{
|
||||
default Direction getBedDirection(LevelReader level, BlockPos pos) {
|
||||
return self().getBlock().getBedDirection(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -208,8 +196,7 @@ public interface IForgeBlockState
|
||||
* @param explosion The explosion
|
||||
* @return The amount of the explosion absorbed.
|
||||
*/
|
||||
default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion)
|
||||
{
|
||||
default float getExplosionResistance(BlockGetter level, BlockPos pos, Explosion explosion) {
|
||||
return self().getBlock().getExplosionResistance(self(), level, pos, explosion);
|
||||
}
|
||||
|
||||
@@ -220,8 +207,7 @@ public interface IForgeBlockState
|
||||
* @param target The full target the player is looking at
|
||||
* @return A ItemStack to add to the player's inventory, empty itemstack if nothing should be added.
|
||||
*/
|
||||
default ItemStack getCloneItemStack(HitResult target, LevelReader level, BlockPos pos, Player player)
|
||||
{
|
||||
default ItemStack getCloneItemStack(HitResult target, LevelReader level, BlockPos pos, Player player) {
|
||||
return self().getBlock().getCloneItemStack(self(), target, level, pos, player);
|
||||
}
|
||||
|
||||
@@ -237,10 +223,10 @@ public interface IForgeBlockState
|
||||
* @param numberOfParticles That vanilla world have spawned
|
||||
* @return True to prevent vanilla landing particles from spawning
|
||||
*/
|
||||
default boolean addLandingEffects(ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles)
|
||||
{
|
||||
default boolean addLandingEffects(ServerLevel level, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) {
|
||||
return self().getBlock().addLandingEffects(self(), level, pos, state2, entity, numberOfParticles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows a block to override the standard vanilla running particles.
|
||||
* This is called from {@code Entity#spawnSprintParticle()} and is called both,
|
||||
@@ -252,8 +238,7 @@ public interface IForgeBlockState
|
||||
* @param entity The entity running on the block.
|
||||
* @return True to prevent vanilla running particles from spawning.
|
||||
*/
|
||||
default boolean addRunningEffects(Level level, BlockPos pos, Entity entity)
|
||||
{
|
||||
default boolean addRunningEffects(Level level, BlockPos pos, Entity entity) {
|
||||
return self().getBlock().addRunningEffects(self(), level, pos, entity);
|
||||
}
|
||||
|
||||
@@ -273,8 +258,7 @@ public interface IForgeBlockState
|
||||
* @param plantable The plant that wants to check
|
||||
* @return True to allow the plant to be planted/stay.
|
||||
*/
|
||||
default boolean canSustainPlant(BlockGetter level, BlockPos pos, Direction facing, IPlantable plantable)
|
||||
{
|
||||
default boolean canSustainPlant(BlockGetter level, BlockPos pos, Direction facing, IPlantable plantable) {
|
||||
return self().getBlock().canSustainPlant(self(), level, pos, facing, plantable);
|
||||
}
|
||||
|
||||
@@ -296,8 +280,7 @@ public interface IForgeBlockState
|
||||
* @param config Configuration of the trunk placer. Consider azalea trees, which should place rooted dirt instead of regular dirt.
|
||||
* @return True to ignore vanilla behaviour
|
||||
*/
|
||||
default boolean onTreeGrow(LevelReader level, BiConsumer<BlockPos, BlockState> placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config)
|
||||
{
|
||||
default boolean onTreeGrow(LevelReader level, BiConsumer<BlockPos, BlockState> placeFunction, RandomSource randomSource, BlockPos pos, TreeConfiguration config) {
|
||||
return self().getBlock().onTreeGrow(self(), level, placeFunction, randomSource, pos, config);
|
||||
}
|
||||
|
||||
@@ -310,8 +293,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return True if the soil should be considered fertile.
|
||||
*/
|
||||
default boolean isFertile(BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default boolean isFertile(BlockGetter level, BlockPos pos) {
|
||||
return self().getBlock().isFertile(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -323,8 +305,7 @@ public interface IForgeBlockState
|
||||
* @param conduit Conduit position in level
|
||||
* @return True, to support the conduit, and make it active with this block.
|
||||
*/
|
||||
default boolean isConduitFrame(LevelReader level, BlockPos pos, BlockPos conduit)
|
||||
{
|
||||
default boolean isConduitFrame(LevelReader level, BlockPos pos, BlockPos conduit) {
|
||||
return self().getBlock().isConduitFrame(self(), level, pos, conduit);
|
||||
}
|
||||
|
||||
@@ -335,8 +316,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return True, to support being part of a nether portal frame, false otherwise.
|
||||
*/
|
||||
default boolean isPortalFrame(BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default boolean isPortalFrame(BlockGetter level, BlockPos pos) {
|
||||
return self().getBlock().isPortalFrame(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -350,13 +330,11 @@ public interface IForgeBlockState
|
||||
* @param silkTouchLevel silk touch enchantment level of tool being used
|
||||
* @return Amount of XP from breaking this block.
|
||||
*/
|
||||
default int getExpDrop(LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel)
|
||||
{
|
||||
default int getExpDrop(LevelReader level, RandomSource randomSource, BlockPos pos, int fortuneLevel, int silkTouchLevel) {
|
||||
return self().getBlock().getExpDrop(self(), level, randomSource, pos, fortuneLevel, silkTouchLevel);
|
||||
}
|
||||
|
||||
default BlockState rotate(LevelAccessor level, BlockPos pos, Rotation direction)
|
||||
{
|
||||
default BlockState rotate(LevelAccessor level, BlockPos pos, Rotation direction) {
|
||||
return self().getBlock().rotate(self(), level, pos, direction);
|
||||
}
|
||||
|
||||
@@ -366,8 +344,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return The amount of enchanting power this block produces.
|
||||
*/
|
||||
default float getEnchantPowerBonus(LevelReader level, BlockPos pos)
|
||||
{
|
||||
default float getEnchantPowerBonus(LevelReader level, BlockPos pos) {
|
||||
return self().getBlock().getEnchantPowerBonus(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -377,8 +354,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @param neighbor Block position of neighbor
|
||||
*/
|
||||
default void onNeighborChange(LevelReader level, BlockPos pos, BlockPos neighbor)
|
||||
{
|
||||
default void onNeighborChange(LevelReader level, BlockPos pos, BlockPos neighbor) {
|
||||
self().getBlock().onNeighborChange(self(), level, pos, neighbor);
|
||||
}
|
||||
|
||||
@@ -389,8 +365,7 @@ public interface IForgeBlockState
|
||||
* @param side The INPUT side of the block to be powered - ie the opposite of this block's output side
|
||||
* @return Whether Block#isProvidingWeakPower should be called when determining indirect power
|
||||
*/
|
||||
default boolean shouldCheckWeakPower(SignalGetter level, BlockPos pos, Direction side)
|
||||
{
|
||||
default boolean shouldCheckWeakPower(SignalGetter level, BlockPos pos, Direction side) {
|
||||
return self().getBlock().shouldCheckWeakPower(self(), level, pos, side);
|
||||
}
|
||||
|
||||
@@ -403,8 +378,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return true To be notified of changes
|
||||
*/
|
||||
default boolean getWeakChanges(LevelReader level, BlockPos pos)
|
||||
{
|
||||
default boolean getWeakChanges(LevelReader level, BlockPos pos) {
|
||||
return self().getBlock().getWeakChanges(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -415,8 +389,7 @@ public interface IForgeBlockState
|
||||
* @param entity The entity that is breaking/stepping on/placing/hitting/falling on this block, or null if no entity is in this context
|
||||
* @return A SoundType to use
|
||||
*/
|
||||
default SoundType getSoundType(LevelReader level, BlockPos pos, @Nullable Entity entity)
|
||||
{
|
||||
default SoundType getSoundType(LevelReader level, BlockPos pos, @Nullable Entity entity) {
|
||||
return self().getBlock().getSoundType(self(), level, pos, entity);
|
||||
}
|
||||
|
||||
@@ -427,8 +400,7 @@ public interface IForgeBlockState
|
||||
* @return A float RGB [0.0, 1.0] array to be averaged with a beacon's existing beam color, or null to do nothing to the beam
|
||||
*/
|
||||
@Nullable
|
||||
default float[] getBeaconColorMultiplier(LevelReader level, BlockPos pos, BlockPos beacon)
|
||||
{
|
||||
default float[] getBeaconColorMultiplier(LevelReader level, BlockPos pos, BlockPos beacon) {
|
||||
return self().getBlock().getBeaconColorMultiplier(self(), level, pos, beacon);
|
||||
}
|
||||
|
||||
@@ -442,24 +414,21 @@ public interface IForgeBlockState
|
||||
* @param viewpoint the viewpoint
|
||||
* @return the block state that should be 'seen'
|
||||
*/
|
||||
default BlockState getStateAtViewpoint(BlockGetter level, BlockPos pos, Vec3 viewpoint)
|
||||
{
|
||||
default BlockState getStateAtViewpoint(BlockGetter level, BlockPos pos, Vec3 viewpoint) {
|
||||
return self().getBlock().getStateAtViewpoint(self(), level, pos, viewpoint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
|
||||
*/
|
||||
default boolean isSlimeBlock()
|
||||
{
|
||||
default boolean isSlimeBlock() {
|
||||
return self().getBlock().isSlimeBlock(self());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if the block is sticky block which used for pull or push adjacent blocks (use by piston)
|
||||
*/
|
||||
default boolean isStickyBlock()
|
||||
{
|
||||
default boolean isStickyBlock() {
|
||||
return self().getBlock().isStickyBlock(self());
|
||||
}
|
||||
|
||||
@@ -468,8 +437,7 @@ public interface IForgeBlockState
|
||||
* @param other Other block
|
||||
* @return True to link blocks
|
||||
*/
|
||||
default boolean canStickTo(@NotNull BlockState other)
|
||||
{
|
||||
default boolean canStickTo(@NotNull BlockState other) {
|
||||
return self().getBlock().canStickTo(self(), other);
|
||||
}
|
||||
|
||||
@@ -482,8 +450,7 @@ public interface IForgeBlockState
|
||||
* @param face The face that the fire is coming from
|
||||
* @return A number ranging from 0 to 300 relating used to determine if the block will be consumed by fire
|
||||
*/
|
||||
default int getFlammability(BlockGetter level, BlockPos pos, Direction face)
|
||||
{
|
||||
default int getFlammability(BlockGetter level, BlockPos pos, Direction face) {
|
||||
return self().getBlock().getFlammability(self(), level, pos, face);
|
||||
}
|
||||
|
||||
@@ -495,8 +462,7 @@ public interface IForgeBlockState
|
||||
* @param face The face that the fire is coming from
|
||||
* @return True if the face can be on fire, false otherwise.
|
||||
*/
|
||||
default boolean isFlammable(BlockGetter level, BlockPos pos, Direction face)
|
||||
{
|
||||
default boolean isFlammable(BlockGetter level, BlockPos pos, Direction face) {
|
||||
return self().getBlock().isFlammable(self(), level, pos, face);
|
||||
}
|
||||
|
||||
@@ -508,8 +474,7 @@ public interface IForgeBlockState
|
||||
* @param face The face that the fire is coming from
|
||||
* @param igniter The entity that lit the fire
|
||||
*/
|
||||
default void onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter)
|
||||
{
|
||||
default void onCaughtFire(Level level, BlockPos pos, @Nullable Direction face, @Nullable LivingEntity igniter) {
|
||||
self().getBlock().onCaughtFire(self(), level, pos, face, igniter);
|
||||
}
|
||||
|
||||
@@ -522,8 +487,7 @@ public interface IForgeBlockState
|
||||
* @param face The face that the fire is coming from
|
||||
* @return A number that is used to determine the speed of fire growth around the block
|
||||
*/
|
||||
default int getFireSpreadSpeed(BlockGetter level, BlockPos pos, Direction face)
|
||||
{
|
||||
default int getFireSpreadSpeed(BlockGetter level, BlockPos pos, Direction face) {
|
||||
return self().getBlock().getFireSpreadSpeed(self(), level, pos, face);
|
||||
}
|
||||
|
||||
@@ -537,8 +501,7 @@ public interface IForgeBlockState
|
||||
* @param side The face that the fire is coming from
|
||||
* @return True if this block sustains fire, meaning it will never go out.
|
||||
*/
|
||||
default boolean isFireSource(LevelReader level, BlockPos pos, Direction side)
|
||||
{
|
||||
default boolean isFireSource(LevelReader level, BlockPos pos, Direction side) {
|
||||
return self().getBlock().isFireSource(self(), level, pos, side);
|
||||
}
|
||||
|
||||
@@ -549,8 +512,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return True to allow the ender dragon to destroy this block
|
||||
*/
|
||||
default boolean canEntityDestroy(BlockGetter level, BlockPos pos, Entity entity)
|
||||
{
|
||||
default boolean canEntityDestroy(BlockGetter level, BlockPos pos, Entity entity) {
|
||||
return self().getBlock().canEntityDestroy(self(), level, pos, entity);
|
||||
}
|
||||
|
||||
@@ -562,8 +524,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @return True if the block should deal damage
|
||||
*/
|
||||
default boolean isBurning(BlockGetter level, BlockPos pos)
|
||||
{
|
||||
default boolean isBurning(BlockGetter level, BlockPos pos) {
|
||||
return self().getBlock().isBurning(self(), level, pos);
|
||||
}
|
||||
|
||||
@@ -577,8 +538,7 @@ public interface IForgeBlockState
|
||||
* @return the path type of this block
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob)
|
||||
{
|
||||
default PathType getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob) {
|
||||
return self().getBlock().getBlockPathType(self(), level, pos, mob);
|
||||
}
|
||||
|
||||
@@ -595,16 +555,14 @@ public interface IForgeBlockState
|
||||
* @return the path type of this block
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType)
|
||||
{
|
||||
default PathType getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) {
|
||||
return self().getBlock().getAdjacentBlockPathType(self(), level, pos, mob, originalType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if this block should drop loot when exploded.
|
||||
*/
|
||||
default boolean canDropFromExplosion(BlockGetter level, BlockPos pos, Explosion explosion)
|
||||
{
|
||||
default boolean canDropFromExplosion(BlockGetter level, BlockPos pos, Explosion explosion) {
|
||||
return self().getBlock().canDropFromExplosion(self(), level, pos, explosion);
|
||||
}
|
||||
|
||||
@@ -617,8 +575,7 @@ public interface IForgeBlockState
|
||||
* @param pos Block position in level
|
||||
* @param explosion The explosion instance affecting the block
|
||||
*/
|
||||
default void onBlockExploded(Level level, BlockPos pos, Explosion explosion)
|
||||
{
|
||||
default void onBlockExploded(Level level, BlockPos pos, Explosion explosion) {
|
||||
self().getBlock().onBlockExploded(self(), level, pos, explosion);
|
||||
}
|
||||
|
||||
@@ -626,8 +583,7 @@ public interface IForgeBlockState
|
||||
* Determines if this block's collision box should be treated as though it can extend above its block space.
|
||||
* This can be used to replicate fence and wall behavior.
|
||||
*/
|
||||
default boolean collisionExtendsVertically(BlockGetter level, BlockPos pos, Entity collidingEntity)
|
||||
{
|
||||
default boolean collisionExtendsVertically(BlockGetter level, BlockPos pos, Entity collidingEntity) {
|
||||
return self().getBlock().collisionExtendsVertically(self(), level, pos, collidingEntity);
|
||||
}
|
||||
|
||||
@@ -639,8 +595,7 @@ public interface IForgeBlockState
|
||||
* @param fluidState The state of the fluid
|
||||
* @return Whether the fluid overlay texture should be used
|
||||
*/
|
||||
default boolean shouldDisplayFluidOverlay(BlockAndTintGetter level, BlockPos pos, FluidState fluidState)
|
||||
{
|
||||
default boolean shouldDisplayFluidOverlay(BlockAndTintGetter level, BlockPos pos, FluidState fluidState) {
|
||||
return self().getBlock().shouldDisplayFluidOverlay(self(), level, pos, fluidState);
|
||||
}
|
||||
|
||||
@@ -656,8 +611,7 @@ public interface IForgeBlockState
|
||||
* @return The resulting state after the action has been performed
|
||||
*/
|
||||
@Nullable
|
||||
default BlockState getToolModifiedState(UseOnContext context, ToolAction toolAction, boolean simulate)
|
||||
{
|
||||
default BlockState getToolModifiedState(UseOnContext context, ToolAction toolAction, boolean simulate) {
|
||||
BlockState eventState = net.minecraftforge.event.ForgeEventFactory.onToolUse(self(), context, toolAction, simulate);
|
||||
return eventState != self() ? eventState : self().getBlock().getToolModifiedState(self(), context, toolAction, simulate);
|
||||
}
|
||||
@@ -668,8 +622,7 @@ public interface IForgeBlockState
|
||||
* @param entity The entity on the scaffolding
|
||||
* @return True if the block should act like scaffolding
|
||||
*/
|
||||
default boolean isScaffolding(LivingEntity entity)
|
||||
{
|
||||
default boolean isScaffolding(LivingEntity entity) {
|
||||
return self().getBlock().isScaffolding(self(), entity.level(), entity.blockPosition(), entity);
|
||||
}
|
||||
|
||||
@@ -683,8 +636,7 @@ public interface IForgeBlockState
|
||||
* @param direction The coming direction of the redstone dust connection (with respect to the block at pos)
|
||||
* @return True if redstone dust should visually connect on the side passed
|
||||
*/
|
||||
default boolean canRedstoneConnectTo(BlockGetter level, BlockPos pos, @Nullable Direction direction)
|
||||
{
|
||||
default boolean canRedstoneConnectTo(BlockGetter level, BlockPos pos, @Nullable Direction direction) {
|
||||
return self().getBlock().canConnectRedstone(self(), level, pos, direction);
|
||||
}
|
||||
|
||||
@@ -700,8 +652,7 @@ public interface IForgeBlockState
|
||||
* @param neighborState The neighboring blocks {@link BlockState}
|
||||
* @param dir The direction towards the neighboring block
|
||||
*/
|
||||
default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState neighborState, Direction dir)
|
||||
{
|
||||
default boolean hidesNeighborFace(BlockGetter level, BlockPos pos, BlockState neighborState, Direction dir) {
|
||||
return self().getBlock().hidesNeighborFace(level, pos, self(), neighborState, dir);
|
||||
}
|
||||
|
||||
@@ -710,8 +661,7 @@ public interface IForgeBlockState
|
||||
* If this returns true, {@link IForgeBlockState#hidesNeighborFace(BlockGetter, BlockPos, BlockState, Direction)}
|
||||
* will be called on the neighboring block.
|
||||
*/
|
||||
default boolean supportsExternalFaceHiding()
|
||||
{
|
||||
default boolean supportsExternalFaceHiding() {
|
||||
return self().getBlock().supportsExternalFaceHiding(self());
|
||||
}
|
||||
|
||||
@@ -725,8 +675,7 @@ public interface IForgeBlockState
|
||||
* @param pos The blocks position in the level
|
||||
* @param oldState The previous state of the block at the given position, may be a different block than this one
|
||||
*/
|
||||
default void onBlockStateChange(LevelReader level, BlockPos pos, BlockState oldState)
|
||||
{
|
||||
default void onBlockStateChange(LevelReader level, BlockPos pos, BlockState oldState) {
|
||||
self().getBlock().onBlockStateChange(level, pos, oldState, self());
|
||||
}
|
||||
|
||||
@@ -746,8 +695,7 @@ public interface IForgeBlockState
|
||||
* @param fluidPos the position of the fluid
|
||||
* @return {@code true} if the block can be hydrated, {@code false} otherwise
|
||||
*/
|
||||
default boolean canBeHydrated(BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos)
|
||||
{
|
||||
default boolean canBeHydrated(BlockGetter getter, BlockPos pos, FluidState fluid, BlockPos fluidPos) {
|
||||
return self().getBlock().canBeHydrated(self(), getter, pos, fluid, fluidPos);
|
||||
}
|
||||
|
||||
@@ -762,8 +710,7 @@ public interface IForgeBlockState
|
||||
* @return The appearance of this block from the given side
|
||||
* @see IForgeBlock#getAppearance(BlockState, BlockAndTintGetter, BlockPos, Direction, BlockState, BlockPos)
|
||||
*/
|
||||
default BlockState getAppearance(BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos)
|
||||
{
|
||||
default BlockState getAppearance(BlockAndTintGetter level, BlockPos pos, Direction side, @Nullable BlockState queryState, @Nullable BlockPos queryPos) {
|
||||
return self().getBlock().getAppearance(self(), level, pos, side, queryState, queryPos);
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,10 @@
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.world.entity.MobType;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.enchantment.Enchantment;
|
||||
import net.minecraft.world.item.enchantment.EnchantmentCategory;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public interface IForgeEnchantment {
|
||||
private Enchantment self() {
|
||||
@@ -25,18 +23,23 @@ public interface IForgeEnchantment {
|
||||
* @return the damage bonus
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
default float getDamageBonus(int level, MobType mobType, ItemStack enchantedItem) {
|
||||
default float getDamageBonus(int level, @Nullable EntityType<?> mobType, ItemStack enchantedItem) {
|
||||
return self().getDamageBonus(level, mobType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether item variants of this enchantment can be added to a given creative tab with the allowed categories.
|
||||
*
|
||||
* @param book the item being added to the creative tab
|
||||
* @param allowedCategories the enchantment categories allowed in the creative tab
|
||||
* @return whether item variants of this enchantment can be added to a given creative tab with the allowed categories
|
||||
* Is this enchantment allowed to be enchanted on books via Enchantment Table
|
||||
* @return false to disable the vanilla feature
|
||||
*/
|
||||
default boolean allowedInCreativeTab(Item book, Set<EnchantmentCategory> allowedCategories) {
|
||||
return self().isAllowedOnBooks() && allowedCategories.contains(self().category);
|
||||
default boolean isAllowedOnBooks() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* This applies specifically to applying at the enchanting table. The other method {@link #canEnchant(ItemStack)}
|
||||
* applies for <i>all possible</i> enchantments.
|
||||
*/
|
||||
default boolean canApplyAtEnchatingTable(ItemStack stack) {
|
||||
return stack.canApplyAtEnchantingTable(null);
|
||||
}
|
||||
}
|
||||
@@ -9,24 +9,19 @@ import java.util.Collection;
|
||||
import java.util.function.BiPredicate;
|
||||
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
|
||||
import net.minecraft.world.entity.boss.enderdragon.EnderDragon;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.entity.vehicle.Boat;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityDimensions;
|
||||
import net.minecraft.world.entity.MobCategory;
|
||||
import net.minecraft.world.entity.Pose;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraftforge.common.ForgeMod;
|
||||
import net.minecraftforge.common.ForgeSpawnEggItem;
|
||||
import net.minecraftforge.common.SoundAction;
|
||||
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
|
||||
@@ -189,23 +184,6 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Return the height in blocks the Entity can step up without needing to jump
|
||||
* This is the sum of vanilla's {@link Entity#maxUpStep()} method and the current value
|
||||
* of the {@link net.minecraftforge.common.ForgeMod#STEP_HEIGHT_ADDITION} attribute
|
||||
* (if this Entity is a {@link LivingEntity} and has the attribute), clamped at 0.
|
||||
*/
|
||||
default float getStepHeight() {
|
||||
@SuppressWarnings("deprecation")
|
||||
float vanillaStep = self().maxUpStep();
|
||||
if (self() instanceof LivingEntity living) {
|
||||
AttributeInstance stepHeightAttribute = living.getAttribute(ForgeMod.STEP_HEIGHT_ADDITION.get());
|
||||
if (stepHeightAttribute != null)
|
||||
return (float) Math.max(0, vanillaStep + stepHeightAttribute.getValue());
|
||||
}
|
||||
return vanillaStep;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the height of the fluid type in relation to the bounding box of
|
||||
* the entity. If the entity is not in the fluid type, then {@code 0}
|
||||
@@ -398,11 +376,6 @@ public interface IForgeEntity extends ICapabilitySerializable<CompoundTag> {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Deprecated(forRemoval = true, since = "1.20.1") // Remove Entity Eye/Size hooks, as they need to be redesigned
|
||||
default float getEyeHeightForge(Pose pose, EntityDimensions size) {
|
||||
return self().getEyeHeightAccess(pose, size);
|
||||
}
|
||||
|
||||
/**
|
||||
* When {@code false}, the fluid will no longer update its height value while
|
||||
* within a boat while it is not within a fluid ({@link Boat#isUnderWater()}.
|
||||
|
||||
@@ -15,7 +15,7 @@ import net.minecraft.world.level.Explosion;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.pathfinder.BlockPathTypes;
|
||||
import net.minecraft.world.level.pathfinder.PathType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.fluids.FluidType;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -109,7 +109,7 @@ public interface IForgeFluid {
|
||||
* @return the path type of this fluid
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
|
||||
default PathType getBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
|
||||
return getFluidType().getBlockPathType(state, level, pos, mob, canFluidLog);
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ public interface IForgeFluid {
|
||||
* @return the path type of this fluid
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) {
|
||||
default PathType getAdjacentBlockPathType(FluidState state, BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) {
|
||||
return getFluidType().getAdjacentBlockPathType(state, level, pos, mob, originalType);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import net.minecraft.world.level.Explosion;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import net.minecraft.world.level.pathfinder.BlockPathTypes;
|
||||
import net.minecraft.world.level.pathfinder.PathType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.fluids.FluidType;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -105,7 +105,7 @@ public interface IForgeFluidState {
|
||||
* @return the path type of this fluid
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
|
||||
default PathType getBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, boolean canFluidLog) {
|
||||
return self().getType().getBlockPathType(self(), level, pos, mob, canFluidLog);
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ public interface IForgeFluidState {
|
||||
* @return the path type of this fluid
|
||||
*/
|
||||
@Nullable
|
||||
default BlockPathTypes getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, BlockPathTypes originalType) {
|
||||
default PathType getAdjacentBlockPathType(BlockGetter level, BlockPos pos, @Nullable Mob mob, PathType originalType) {
|
||||
return self().getType().getAdjacentBlockPathType(self(), level, pos, mob, originalType);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Extension-Interface providing methods for writing registry-id's instead of their registry-names.
|
||||
*/
|
||||
* /
|
||||
public interface IForgeFriendlyByteBuf {
|
||||
private FriendlyByteBuf self() {
|
||||
return (FriendlyByteBuf)this;
|
||||
@@ -30,7 +30,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* @param registry The registry containing the given entry
|
||||
* @param entry The entry who's registryName is to be written
|
||||
* @param <T> The type of the entry.
|
||||
*/
|
||||
* /
|
||||
default <T> void writeRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry, @NotNull T entry) {
|
||||
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
|
||||
int id = forgeRegistry.getID(entry);
|
||||
@@ -42,7 +42,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* in the given registry. Therefore no safety checks can be performed whilst reading it and if the entry is not in the registry a default value will be written.
|
||||
* @param registry The registry containing the entry represented by this key
|
||||
* @param entryKey The registry-name of an entry in this {@link IForgeRegistry}
|
||||
*/
|
||||
* /
|
||||
default void writeRegistryIdUnsafe(@NotNull IForgeRegistry<?> registry, @NotNull ResourceLocation entryKey) {
|
||||
ForgeRegistry<?> forgeRegistry = (ForgeRegistry<?>) registry;
|
||||
int id = forgeRegistry.getID(entryKey);
|
||||
@@ -53,7 +53,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* Reads an integer value from the buffer, which will be interpreted as an registry-id in the given registry. Notice that if there is no value in the specified registry for the
|
||||
* read id, that the registry's default value will be returned.
|
||||
* @param registry The registry containing the entry
|
||||
*/
|
||||
* /
|
||||
default <T> T readRegistryIdUnsafe(@NotNull IForgeRegistry<T> registry) {
|
||||
ForgeRegistry<T> forgeRegistry = (ForgeRegistry<T>) registry;
|
||||
int id = self().readVarInt();
|
||||
@@ -71,7 +71,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* @param <T> The type of the registry-entry
|
||||
* @throws NullPointerException if the registry or entry was null
|
||||
* @throws IllegalArgumentException if the registry does not contain the specified value
|
||||
*/
|
||||
* /
|
||||
default <T> void writeRegistryId(@NotNull IForgeRegistry<T> registry, @NotNull T entry) {
|
||||
Objects.requireNonNull(registry, "Cannot write a null registry key!");
|
||||
Objects.requireNonNull(entry,"Cannot write a null registry entry!");
|
||||
@@ -87,7 +87,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* - see {@link #readRegistryIdSafe(Class)} for an safe version.
|
||||
* @param <T> The type of the registry-entry. Notice that this should match the actual type written to the buffer.
|
||||
* @throws NullPointerException if the registry could not be found.
|
||||
*/
|
||||
* /
|
||||
default <T> T readRegistryId() {
|
||||
ResourceLocation location = self().readResourceLocation(); //TODO change to reading a varInt once registries use id's
|
||||
ForgeRegistry<T> registry = RegistryManager.ACTIVE.getRegistry(location);
|
||||
@@ -99,7 +99,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* @param <T> The type of the registry-entry.
|
||||
* @throws IllegalArgumentException if the retrieved entries registryType doesn't match the one passed in.
|
||||
* @throws NullPointerException if the registry could not be found.
|
||||
*/
|
||||
* /
|
||||
default <T> T readRegistryIdSafe(Class<? super T> registrySuperType) {
|
||||
T value = readRegistryId();
|
||||
if (!registrySuperType.isAssignableFrom(value.getClass()))
|
||||
@@ -112,7 +112,7 @@ public interface IForgeFriendlyByteBuf {
|
||||
* This behavior provides parity with the ItemStack method in PacketBuffer.
|
||||
*
|
||||
* @param stack FluidStack to be written to the packet buffer.
|
||||
*/
|
||||
* /
|
||||
default void writeFluidStack(FluidStack stack) {
|
||||
if (stack.isEmpty())
|
||||
self().writeBoolean(false);
|
||||
@@ -124,8 +124,9 @@ public interface IForgeFriendlyByteBuf {
|
||||
|
||||
/**
|
||||
* Reads a FluidStack from this buffer.
|
||||
*/
|
||||
* /
|
||||
default FluidStack readFluidStack() {
|
||||
return !self().readBoolean() ? FluidStack.EMPTY : FluidStack.readFromPacket(self());
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -15,7 +15,9 @@ import net.minecraft.gametest.framework.GameTestAssertException;
|
||||
import net.minecraft.gametest.framework.GameTestHelper;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.ConnectionProtocol;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.protocol.PacketFlow;
|
||||
import net.minecraft.network.protocol.game.GameProtocols;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.CommonListenerCookie;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
@@ -37,7 +39,7 @@ public interface IForgeGameTestHelper {
|
||||
|
||||
default ServerPlayer makeMockServerPlayer() {
|
||||
var level = self().getLevel();
|
||||
var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player"));
|
||||
var cookie = CommonListenerCookie.createInitial(new GameProfile(UUID.randomUUID(), "test-mock-player"), false);
|
||||
var player = new ServerPlayer(level.getServer(), level, cookie.gameProfile(), cookie.clientInformation()) {
|
||||
public boolean isSpectator() {
|
||||
return false;
|
||||
@@ -49,9 +51,11 @@ public interface IForgeGameTestHelper {
|
||||
};
|
||||
var connection = new Connection(PacketFlow.SERVERBOUND);
|
||||
var channel = new EmbeddedChannel(connection);
|
||||
channel.attr(Connection.ATTRIBUTE_SERVERBOUND_PROTOCOL).set(ConnectionProtocol.PLAY.codec(PacketFlow.SERVERBOUND));
|
||||
// This sets the connection/listener in the player
|
||||
new ServerGamePacketListenerImpl(level.getServer(), connection, player, cookie);
|
||||
var server = level.getServer();
|
||||
|
||||
var listener = new ServerGamePacketListenerImpl(server, connection, player, cookie);
|
||||
var info = GameProtocols.SERVERBOUND.bind(RegistryFriendlyByteBuf.decorator(server.registryAccess()));
|
||||
connection.setupInboundProtocol(info, listener);
|
||||
return player;
|
||||
}
|
||||
}
|
||||
@@ -7,37 +7,34 @@ package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.core.HolderSet.ListBacked;
|
||||
|
||||
public interface IForgeHolderSet<T>
|
||||
{
|
||||
public interface IForgeHolderSet<T> {
|
||||
/**
|
||||
* <p>Adds a callback to run when this holderset's contents invalidate (i.e. because tags were rebound).</p>
|
||||
*
|
||||
*
|
||||
* <p>The intended usage and use case is with composite holdersets that need to cache sets/list based on other
|
||||
* holdersets, which may be mutable (because they are tag-based or themselves composite holdersets).
|
||||
* Composite holdersets should use this to add callbacks to each of their component holdersets when constructed.</p>
|
||||
*
|
||||
*
|
||||
* @param runnable Runnable to invoke when this component holderset's contents are no longer valid.
|
||||
* This runnable should only clear caches and allow them to be lazily reevaluated later,
|
||||
* as not all tag holdersets may have been rebound when this is called.
|
||||
* This runnable should also invalidate all of the caller's listeners.
|
||||
*/
|
||||
default public void addInvalidationListener(Runnable runnable)
|
||||
{
|
||||
default public void addInvalidationListener(Runnable runnable) {
|
||||
// noop by default, mutable/composite holdersets must override
|
||||
}
|
||||
|
||||
/**
|
||||
* What format this holderset serializes to in json/nbt/etc
|
||||
*/
|
||||
default public SerializationType serializationType()
|
||||
{
|
||||
default public SerializationType serializationType() {
|
||||
// handle vanilla holderset types
|
||||
return this instanceof ListBacked<T> listBacked
|
||||
? listBacked.unwrap().map(
|
||||
// serializes as tag name if this holderset is named
|
||||
tag -> SerializationType.STRING,
|
||||
// serializes as tag name if this holderset is named
|
||||
tag -> SerializationType.STRING,
|
||||
list -> list.size() == 1
|
||||
// if list has exactly one element then we have to check what kind, otherwise it's a list
|
||||
// if list has exactly one element then we have to check what kind, otherwise it's a list
|
||||
? list.get(0).unwrap().map(
|
||||
// if holder has a key bound then it's serialized as that string, otherwise it's inlined as an object
|
||||
key -> key == null ? SerializationType.OBJECT : SerializationType.STRING,
|
||||
@@ -45,12 +42,11 @@ public interface IForgeHolderSet<T>
|
||||
: SerializationType.LIST)
|
||||
: SerializationType.UNKNOWN; // unsupported holderset impl, could be anything
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* What format a holderset serializes to in json/nbt/etc
|
||||
*/
|
||||
public static enum SerializationType
|
||||
{
|
||||
public static enum SerializationType {
|
||||
/** Unhandled/unsupported holderset implementation, could serialize as potentially anything **/
|
||||
UNKNOWN,
|
||||
STRING,
|
||||
|
||||
@@ -5,28 +5,19 @@
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.google.common.collect.Multimap;
|
||||
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.food.FoodProperties;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.component.ItemAttributeModifiers;
|
||||
import net.minecraft.world.item.enchantment.Enchantment;
|
||||
import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.Mob;
|
||||
import net.minecraft.world.entity.LivingEntity;
|
||||
import net.minecraft.world.entity.ai.attributes.Attribute;
|
||||
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
|
||||
import net.minecraft.world.entity.item.ItemEntity;
|
||||
import net.minecraft.world.entity.monster.EnderMan;
|
||||
import net.minecraft.world.entity.monster.piglin.PiglinAi;
|
||||
@@ -34,7 +25,6 @@ import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.item.context.UseOnContext;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
@@ -42,8 +32,6 @@ import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.common.ForgeHooks;
|
||||
import net.minecraftforge.common.ToolAction;
|
||||
import net.minecraftforge.common.ToolActions;
|
||||
import net.minecraftforge.common.capabilities.ICapabilityProvider;
|
||||
import net.minecraftforge.items.wrapper.ShulkerItemStackInvWrapper;
|
||||
import net.minecraftforge.registries.IForgeRegistry;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -58,8 +46,8 @@ public interface IForgeItem {
|
||||
* ItemStack sensitive version of getItemAttributeModifiers
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
default Multimap<Attribute, AttributeModifier> getAttributeModifiers(EquipmentSlot slot, ItemStack stack) {
|
||||
return self().getDefaultAttributeModifiers(slot);
|
||||
default ItemAttributeModifiers getAttributeModifiers(EquipmentSlot slot, ItemStack stack) {
|
||||
return self().getDefaultAttributeModifiers();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,13 +105,6 @@ public interface IForgeItem {
|
||||
return stack.getItem() instanceof ArmorItem && ((ArmorItem) stack.getItem()).getMaterial() == ArmorMaterials.GOLD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by CraftingManager to determine if an item is reparable.
|
||||
*
|
||||
* @return True if reparable
|
||||
*/
|
||||
boolean isRepairable(ItemStack stack);
|
||||
|
||||
/**
|
||||
* Determines the amount of durability the mending enchantment
|
||||
* will repair, on average, per point of experience.
|
||||
@@ -132,38 +113,6 @@ public interface IForgeItem {
|
||||
return 2f;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override this method to change the NBT data being sent to the client. You
|
||||
* should ONLY override this when you have no other choice, as this might change
|
||||
* behavior client side!
|
||||
*
|
||||
* Note that this will sometimes be applied multiple times, the following MUST
|
||||
* be supported:
|
||||
* Item item = stack.getItem();
|
||||
* NBTTagCompound nbtShare1 = item.getNBTShareTag(stack);
|
||||
* stack.setTagCompound(nbtShare1);
|
||||
* NBTTagCompound nbtShare2 = item.getNBTShareTag(stack);
|
||||
* assert nbtShare1.equals(nbtShare2);
|
||||
*
|
||||
* @param stack The stack to send the NBT tag for
|
||||
* @return The NBT tag
|
||||
*/
|
||||
@Nullable
|
||||
default CompoundTag getShareTag(ItemStack stack) {
|
||||
return stack.getTag();
|
||||
}
|
||||
|
||||
/**
|
||||
* Override this method to decide what to do with the NBT data received from
|
||||
* getNBTShareTag().
|
||||
*
|
||||
* @param stack The stack that received NBT
|
||||
* @param nbt Received NBT, can be null
|
||||
*/
|
||||
default void readShareTag(ItemStack stack, @Nullable CompoundTag nbt) {
|
||||
stack.setTag(nbt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called before a block is broken. Return true to prevent default block
|
||||
* harvesting.
|
||||
@@ -395,51 +344,6 @@ public interface IForgeItem {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the itemDamage represented by this ItemStack. Defaults to the Damage
|
||||
* entry in the stack NBT, but can be overridden here for other sources.
|
||||
*
|
||||
* @param stack The itemstack that is damaged
|
||||
* @return the damage value
|
||||
*/
|
||||
default int getDamage(ItemStack stack) {
|
||||
return !stack.hasTag() ? 0 : stack.getTag().getInt("Damage");
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the maxDamage for this ItemStack. Defaults to the maxDamage field in
|
||||
* this item, but can be overridden here for other sources such as NBT.
|
||||
*
|
||||
* @param stack The itemstack that is damaged
|
||||
* @return the damage value
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
default int getMaxDamage(ItemStack stack) {
|
||||
return self().getMaxDamage();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return if this itemstack is damaged. Note only called if
|
||||
* {@link ItemStack#isDamageableItem()} is true.
|
||||
*
|
||||
* @param stack the stack
|
||||
* @return if the stack is damaged
|
||||
*/
|
||||
default boolean isDamaged(ItemStack stack) {
|
||||
return stack.getDamageValue() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the damage for this itemstack. Note, this method is responsible for zero
|
||||
* checking.
|
||||
*
|
||||
* @param stack the stack
|
||||
* @param damage the new damage value
|
||||
*/
|
||||
default void setDamage(ItemStack stack, int damage) {
|
||||
stack.getOrCreateTag().putInt(ItemStack.TAG_DAMAGE, Math.max(0, damage));
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries if an item can perform the given action.
|
||||
* See {@link ToolActions} for a description of each stock action
|
||||
@@ -451,29 +355,6 @@ public interface IForgeItem {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* ItemStack sensitive version of {@link Item#isCorrectToolForDrops(BlockState)}
|
||||
*
|
||||
* @param stack The itemstack used to harvest the block
|
||||
* @param state The block trying to harvest
|
||||
* @return true if the stack can harvest the block
|
||||
*/
|
||||
default boolean isCorrectToolForDrops(ItemStack stack, BlockState state) {
|
||||
return self().isCorrectToolForDrops(state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the maximum number of items that this stack should be able to hold. This
|
||||
* is a ItemStack (and thus NBT) sensitive version of {@link Item#getMaxStackSize()}.
|
||||
*
|
||||
* @param stack The ItemStack
|
||||
* @return The maximum size this item can be stacked to
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
default int getMaxStackSize(ItemStack stack) {
|
||||
return self().getMaxStackSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* ItemStack sensitive version of {@link Item#getEnchantmentValue()}.
|
||||
*
|
||||
@@ -499,7 +380,7 @@ public interface IForgeItem {
|
||||
* @return true if the enchantment can be applied to this item
|
||||
*/
|
||||
default boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
|
||||
return enchantment.category.canEnchant(stack.getItem());
|
||||
return self().builtInRegistryHolder().is(enchantment.getSupportedItems()) && enchantment.isPrimaryItem(stack);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -513,20 +394,7 @@ public interface IForgeItem {
|
||||
* @see #getAllEnchantments(ItemStack)
|
||||
*/
|
||||
default int getEnchantmentLevel(ItemStack stack, Enchantment enchantment) {
|
||||
return EnchantmentHelper.getTagEnchantmentLevel(enchantment, stack);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a map of all enchantments present on the stack. By default, returns the enchantments present in NBT.
|
||||
* Used in several places in code including armor enchantment hooks.
|
||||
* For consistency, any enchantments in the returned map should include the same level in {@link #getEnchantmentLevel(ItemStack, Enchantment)}
|
||||
*
|
||||
* @param stack the item stack being checked
|
||||
* @return Map of all enchantments on the stack, empty if no enchantments are present
|
||||
* @see #getEnchantmentLevel(ItemStack, Enchantment)
|
||||
*/
|
||||
default Map<Enchantment, Integer> getAllEnchantments(ItemStack stack) {
|
||||
return EnchantmentHelper.deserializeEnchantments(stack.getEnchantmentTags());
|
||||
return EnchantmentHelper.getEnchantmentsForCrafting(stack).getLevel(enchantment);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -553,31 +421,12 @@ public interface IForgeItem {
|
||||
* @return True to reset block break progress
|
||||
*/
|
||||
default boolean shouldCauseBlockBreakReset(ItemStack oldStack, ItemStack newStack) {
|
||||
// Fix MC-176559 mending resets mining progress / breaking animation
|
||||
if (!newStack.is(oldStack.getItem()))
|
||||
return true;
|
||||
|
||||
if (!newStack.isDamageableItem() || !oldStack.isDamageableItem())
|
||||
return !ItemStack.isSameItemSameTags(newStack, oldStack);
|
||||
// TODO: Fix MC-176559 mending resets mining progress / breaking animation by removing damange component
|
||||
|
||||
CompoundTag newTag = newStack.getTag();
|
||||
CompoundTag oldTag = oldStack.getTag();
|
||||
|
||||
if (newTag == null || oldTag == null)
|
||||
return !(newTag == null && oldTag == null);
|
||||
|
||||
Set<String> newKeys = new HashSet<>(newTag.getAllKeys());
|
||||
Set<String> oldKeys = new HashSet<>(oldTag.getAllKeys());
|
||||
|
||||
newKeys.remove(ItemStack.TAG_DAMAGE);
|
||||
oldKeys.remove(ItemStack.TAG_DAMAGE);
|
||||
|
||||
if (!newKeys.equals(oldKeys))
|
||||
return true;
|
||||
|
||||
return !newKeys.stream().allMatch(key -> Objects.equals(newTag.get(key), oldTag.get(key)));
|
||||
// return !(newStack.is(oldStack.getItem()) && ItemStack.tagMatches(newStack, oldStack)
|
||||
// && (newStack.isDamageableItem() || newStack.getDamageValue() == oldStack.getDamageValue()));
|
||||
return !ItemStack.isSameItemSameComponents(oldStack, newStack);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -628,11 +477,15 @@ public interface IForgeItem {
|
||||
* @param nbt NBT of this item serialized, or null.
|
||||
* @return A holder instance associated with this ItemStack where you can hold
|
||||
* capabilities for the life of this item.
|
||||
*/
|
||||
*
|
||||
*
|
||||
* Forge: TODO: Forge ItemStack capabilities - Lex 042724
|
||||
* /
|
||||
@Nullable
|
||||
default ICapabilityProvider initCapabilities(ItemStack stack, @Nullable CompoundTag nbt) {
|
||||
return ShulkerItemStackInvWrapper.createDefaultProvider(stack);
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Can this Item disable a shield
|
||||
@@ -666,20 +519,6 @@ public interface IForgeItem {
|
||||
*/
|
||||
default void onHorseArmorTick(ItemStack stack, Level level, Mob horse) { }
|
||||
|
||||
/**
|
||||
* Reduce the durability of this item by the amount given.
|
||||
* This can be used to e.g. consume power from NBT before durability.
|
||||
*
|
||||
* @param stack The itemstack to damage
|
||||
* @param amount The amount to damage
|
||||
* @param entity The entity damaging the item
|
||||
* @param onBroken The on-broken callback from vanilla
|
||||
* @return The amount of damage to pass to the vanilla logic
|
||||
*/
|
||||
default <T extends LivingEntity> int damageItem(ItemStack stack, int amount, T entity, Consumer<T> onBroken) {
|
||||
return amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when an item entity for this stack is destroyed. Note: The {@link ItemStack} can be retrieved from the item entity.
|
||||
*
|
||||
@@ -744,16 +583,6 @@ public interface IForgeItem {
|
||||
return stack.is(Items.LEATHER_BOOTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to test if this item can be damaged, but with the ItemStack in question.
|
||||
* Please note that in some cases no ItemStack is available, so the stack-less method will be used.
|
||||
*
|
||||
* @param stack ItemStack in the Chest slot of the entity.
|
||||
*/
|
||||
default boolean isDamageable(ItemStack stack) {
|
||||
return self().canBeDepleted();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a bounding box ({@link AABB}) of a sweep attack.
|
||||
*
|
||||
@@ -777,23 +606,6 @@ public interface IForgeItem {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the food properties for this item.
|
||||
* Use this instead of the {@link Item#getFoodProperties()} method, for ItemStack sensitivity.
|
||||
*
|
||||
* The @Nullable annotation was only added, due to the default method, also being @Nullable.
|
||||
* Use this with a grain of salt, as if you return null here and true at {@link Item#isEdible()}, NPEs will occur!
|
||||
*
|
||||
* @param stack The ItemStack the entity wants to eat.
|
||||
* @param entity The entity which wants to eat the food. Be aware that this can be null!
|
||||
* @return The current FoodProperties for the item.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
@Nullable // read javadoc to find a potential problem
|
||||
default FoodProperties getFoodProperties(ItemStack stack, @Nullable LivingEntity entity) {
|
||||
return self().getFoodProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the given ItemStack should be excluded (if possible) when selecting the target hotbar slot of a "pick" action.
|
||||
* By default, this returns true for enchanted stacks.
|
||||
|
||||
@@ -5,14 +5,10 @@
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.world.damagesource.DamageSource;
|
||||
import net.minecraft.world.entity.monster.EnderMan;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.food.FoodProperties;
|
||||
import net.minecraft.world.item.crafting.RecipeType;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.pattern.BlockInWorld;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.item.enchantment.Enchantment;
|
||||
@@ -25,7 +21,6 @@ import net.minecraft.world.entity.EquipmentSlot;
|
||||
import net.minecraft.world.item.Item;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.context.UseOnContext;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.stats.Stats;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.core.BlockPos;
|
||||
@@ -33,21 +28,15 @@ import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.common.ToolAction;
|
||||
import net.minecraftforge.common.ToolActions;
|
||||
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/*
|
||||
* Extension added to ItemStack that bounces to ItemSack sensitive Item methods. Typically this is just for convince.
|
||||
*/
|
||||
public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
{
|
||||
public interface IForgeItemStack {
|
||||
// Helpers for accessing Item data
|
||||
private ItemStack self()
|
||||
{
|
||||
private ItemStack self() {
|
||||
return (ItemStack)this;
|
||||
}
|
||||
|
||||
@@ -57,8 +46,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
*
|
||||
* @return The resulting ItemStack
|
||||
*/
|
||||
default ItemStack getCraftingRemainingItem()
|
||||
{
|
||||
default ItemStack getCraftingRemainingItem() {
|
||||
return self().getItem().getCraftingRemainingItem(self());
|
||||
}
|
||||
|
||||
@@ -67,8 +55,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
*
|
||||
* @return True if this item has a crafting remaining item
|
||||
*/
|
||||
default boolean hasCraftingRemainingItem()
|
||||
{
|
||||
default boolean hasCraftingRemainingItem() {
|
||||
return self().getItem().hasCraftingRemainingItem(self());
|
||||
}
|
||||
|
||||
@@ -77,18 +64,16 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* it not act as a fuel. Return -1 to let the default vanilla logic
|
||||
* decide.
|
||||
*/
|
||||
default int getBurnTime(@Nullable RecipeType<?> recipeType)
|
||||
{
|
||||
default int getBurnTime(@Nullable RecipeType<?> recipeType) {
|
||||
return self().getItem().getBurnTime(self(), recipeType);
|
||||
}
|
||||
|
||||
default InteractionResult onItemUseFirst(UseOnContext context)
|
||||
{
|
||||
default InteractionResult onItemUseFirst(UseOnContext context) {
|
||||
Player entityplayer = context.getPlayer();
|
||||
BlockPos blockpos = context.getClickedPos();
|
||||
BlockInWorld blockworldstate = new BlockInWorld(context.getLevel(), blockpos, false);
|
||||
Registry<Block> registry = entityplayer.level().registryAccess().registryOrThrow(Registries.BLOCK);
|
||||
if (entityplayer != null && !entityplayer.getAbilities().mayBuild && !self().hasAdventureModePlaceTagForBlock(registry, blockworldstate)) {
|
||||
var adventure = (self().canBreakBlockInAdventureMode(blockworldstate) || self().canPlaceOnBlockInAdventureMode(blockworldstate));
|
||||
if (entityplayer != null && !entityplayer.getAbilities().mayBuild && !adventure) {
|
||||
return InteractionResult.PASS;
|
||||
} else {
|
||||
Item item = self().getItem();
|
||||
@@ -101,21 +86,13 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
}
|
||||
}
|
||||
|
||||
default CompoundTag serializeNBT()
|
||||
{
|
||||
CompoundTag ret = new CompoundTag();
|
||||
self().save(ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries if an item can perform the given action.
|
||||
* See {@link ToolActions} for a description of each stock action
|
||||
* @param toolAction The action being queried
|
||||
* @return True if the stack can perform the action
|
||||
*/
|
||||
default boolean canPerformAction(ToolAction toolAction)
|
||||
{
|
||||
default boolean canPerformAction(ToolAction toolAction) {
|
||||
return self().getItem().canPerformAction(self(), toolAction);
|
||||
}
|
||||
|
||||
@@ -129,8 +106,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param player The Player that is wielding the item
|
||||
* @return True to prevent harvesting, false to continue as normal
|
||||
*/
|
||||
default boolean onBlockStartBreak(BlockPos pos, Player player)
|
||||
{
|
||||
default boolean onBlockStartBreak(BlockPos pos, Player player) {
|
||||
return !self().isEmpty() && self().getItem().onBlockStartBreak(self(), pos, player);
|
||||
}
|
||||
|
||||
@@ -141,8 +117,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param newStack The new stack
|
||||
* @return True to reset block break progress
|
||||
*/
|
||||
default boolean shouldCauseBlockBreakReset(ItemStack newStack)
|
||||
{
|
||||
default boolean shouldCauseBlockBreakReset(ItemStack newStack) {
|
||||
return self().getItem().shouldCauseBlockBreakReset(self(), newStack);
|
||||
}
|
||||
|
||||
@@ -158,8 +133,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param enchantment the enchantment to be applied
|
||||
* @return true if the enchantment can be applied to this item
|
||||
*/
|
||||
default boolean canApplyAtEnchantingTable(Enchantment enchantment)
|
||||
{
|
||||
default boolean canApplyAtEnchantingTable(Enchantment enchantment) {
|
||||
return self().getItem().canApplyAtEnchantingTable(self(), enchantment);
|
||||
}
|
||||
|
||||
@@ -175,33 +149,16 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @see #getAllEnchantments()
|
||||
* @see net.minecraft.world.item.enchantment.EnchantmentHelper#getTagEnchantmentLevel(Enchantment, ItemStack)
|
||||
*/
|
||||
default int getEnchantmentLevel(Enchantment enchantment)
|
||||
{
|
||||
default int getEnchantmentLevel(Enchantment enchantment) {
|
||||
return self().getItem().getEnchantmentLevel(self(), enchantment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a map of all enchantments present on the stack. By default, returns the enchantments present in NBT, ignoring book enchantments.
|
||||
*
|
||||
* Use in place of {@link net.minecraft.world.item.enchantment.EnchantmentHelper#getEnchantments(ItemStack)} for checking presence of an enchantment in logic implementing the enchantment behavior.
|
||||
* Use {@link net.minecraft.world.item.enchantment.EnchantmentHelper#getEnchantments(ItemStack)} instead when modifying an item's enchantments.
|
||||
*
|
||||
* @return Map of all enchantments on the stack, empty if no enchantments are present
|
||||
* @see #getEnchantmentLevel(Enchantment)
|
||||
* @see net.minecraft.world.item.enchantment.EnchantmentHelper#getEnchantments(ItemStack)
|
||||
*/
|
||||
default Map<Enchantment, Integer> getAllEnchantments()
|
||||
{
|
||||
return self().getItem().getAllEnchantments(self());
|
||||
}
|
||||
|
||||
/**
|
||||
* ItemStack sensitive version of {@link Item#getEnchantmentValue()}.
|
||||
*
|
||||
* @return the enchantment value of this ItemStack
|
||||
*/
|
||||
default int getEnchantmentValue()
|
||||
{
|
||||
default int getEnchantmentValue() {
|
||||
return self().getItem().getEnchantmentValue(self());
|
||||
}
|
||||
|
||||
@@ -215,8 +172,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* decide
|
||||
*/
|
||||
@Nullable
|
||||
default EquipmentSlot getEquipmentSlot()
|
||||
{
|
||||
default EquipmentSlot getEquipmentSlot() {
|
||||
return self().getItem().getEquipmentSlot(self());
|
||||
}
|
||||
|
||||
@@ -228,8 +184,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param attacker The LivingEntity holding the ItemStack
|
||||
* @return True if this ItemStack can disable the shield in question.
|
||||
*/
|
||||
default boolean canDisableShield(ItemStack shield, LivingEntity entity, LivingEntity attacker)
|
||||
{
|
||||
default boolean canDisableShield(ItemStack shield, LivingEntity entity, LivingEntity attacker) {
|
||||
return self().getItem().canDisableShield(self(), shield, entity, attacker);
|
||||
}
|
||||
|
||||
@@ -239,8 +194,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param entity The entity swinging the item.
|
||||
* @return True to cancel any further processing by EntityLiving
|
||||
*/
|
||||
default boolean onEntitySwing(LivingEntity entity)
|
||||
{
|
||||
default boolean onEntitySwing(LivingEntity entity) {
|
||||
return self().getItem().onEntitySwing(self(), entity);
|
||||
}
|
||||
|
||||
@@ -250,8 +204,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param entity The entity using the item, typically a player
|
||||
* @param count The amount of time in tick the item has been used for continuously
|
||||
*/
|
||||
default void onStopUsing(LivingEntity entity, int count)
|
||||
{
|
||||
default void onStopUsing(LivingEntity entity, int count) {
|
||||
self().getItem().onStopUsing(self(), entity, count);
|
||||
}
|
||||
|
||||
@@ -262,8 +215,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param level The level the entity is in
|
||||
* @return The normal lifespan in ticks.
|
||||
*/
|
||||
default int getEntityLifespan(Level level)
|
||||
{
|
||||
default int getEntityLifespan(Level level) {
|
||||
return self().getItem().getEntityLifespan(self(), level);
|
||||
}
|
||||
|
||||
@@ -275,8 +227,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param entity The entity Item
|
||||
* @return Return true to skip any further update code.
|
||||
*/
|
||||
default boolean onEntityItemUpdate(ItemEntity entity)
|
||||
{
|
||||
default boolean onEntityItemUpdate(ItemEntity entity) {
|
||||
return self().getItem().onEntityItemUpdate(self(), entity);
|
||||
}
|
||||
|
||||
@@ -284,26 +235,15 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* Determines the amount of durability the mending enchantment
|
||||
* will repair, on average, per point of experience.
|
||||
*/
|
||||
default float getXpRepairRatio()
|
||||
{
|
||||
default float getXpRepairRatio() {
|
||||
return self().getItem().getXpRepairRatio(self());
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to tick armor in the armor slot. Override to do something
|
||||
*/
|
||||
@Deprecated(forRemoval = true, since = "1.20.1") // Use onInventoryTick
|
||||
default void onArmorTick(Level level, Player player)
|
||||
{
|
||||
self().getItem().onArmorTick(self(), level, player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called to tick this items in a players inventory, the indexes are the global slot index.
|
||||
*/
|
||||
default void onInventoryTick(Level level, Player player, int slotIndex, int selectedIndex)
|
||||
{
|
||||
self().getItem().onInventoryTick(self(), level, player, slotIndex, selectedIndex);
|
||||
default void onInventoryTick(Level level, Player player, int slotIndex, int selectedIndex) {
|
||||
self().getItem().onInventoryTick(self(), level, player, slotIndex, selectedIndex);
|
||||
}
|
||||
|
||||
|
||||
@@ -314,8 +254,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param level the level the horse is in
|
||||
* @param horse the horse wearing this armor
|
||||
*/
|
||||
default void onHorseArmorTick(Level level, Mob horse)
|
||||
{
|
||||
default void onHorseArmorTick(Level level, Mob horse) {
|
||||
self().getItem().onHorseArmorTick(self(), level, horse);
|
||||
}
|
||||
|
||||
@@ -327,8 +266,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param entity The entity trying to equip the armor
|
||||
* @return True if the given ItemStack can be inserted in the slot
|
||||
*/
|
||||
default boolean canEquip(EquipmentSlot armorType, Entity entity)
|
||||
{
|
||||
default boolean canEquip(EquipmentSlot armorType, Entity entity) {
|
||||
return self().getItem().canEquip(self(), armorType, entity);
|
||||
}
|
||||
|
||||
@@ -338,8 +276,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param book The book
|
||||
* @return if the enchantment is allowed
|
||||
*/
|
||||
default boolean isBookEnchantable(ItemStack book)
|
||||
{
|
||||
default boolean isBookEnchantable(ItemStack book) {
|
||||
return self().getItem().isBookEnchantable(self(), book);
|
||||
}
|
||||
|
||||
@@ -351,8 +288,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
*
|
||||
* @param player The player that dropped the item
|
||||
*/
|
||||
default boolean onDroppedByPlayer(Player player)
|
||||
{
|
||||
default boolean onDroppedByPlayer(Player player) {
|
||||
return self().getItem().onDroppedByPlayer(self(), player);
|
||||
}
|
||||
|
||||
@@ -364,41 +300,10 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param displayName the name that will be displayed unless it is changed in
|
||||
* this method.
|
||||
*/
|
||||
default Component getHighlightTip(Component displayName)
|
||||
{
|
||||
default Component getHighlightTip(Component displayName) {
|
||||
return self().getItem().getHighlightTip(self(), displayName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the NBT data to be sent to the client. The Item can control what data is kept in the tag.
|
||||
*
|
||||
* Note that this will sometimes be applied multiple times, the following MUST
|
||||
* be supported:
|
||||
* Item item = stack.getItem();
|
||||
* NBTTagCompound nbtShare1 = item.getNBTShareTag(stack);
|
||||
* stack.setTagCompound(nbtShare1);
|
||||
* NBTTagCompound nbtShare2 = item.getNBTShareTag(stack);
|
||||
* assert nbtShare1.equals(nbtShare2);
|
||||
*
|
||||
* @return The NBT tag
|
||||
*/
|
||||
@Nullable
|
||||
default CompoundTag getShareTag()
|
||||
{
|
||||
return self().getItem().getShareTag(self());
|
||||
}
|
||||
|
||||
/**
|
||||
* Override this method to decide what to do with the NBT data received from
|
||||
* getNBTShareTag().
|
||||
*
|
||||
* @param nbt Received NBT, can be null
|
||||
*/
|
||||
default void readShareTag(@Nullable CompoundTag nbt)
|
||||
{
|
||||
self().getItem().readShareTag(self(), nbt);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Should this item, when held, allow sneak-clicks to pass through to the underlying block?
|
||||
@@ -407,59 +312,16 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param pos Block position in level
|
||||
* @param player The Player that is wielding the item
|
||||
*/
|
||||
default boolean doesSneakBypassUse(net.minecraft.world.level.LevelReader level, BlockPos pos, Player player)
|
||||
{
|
||||
default boolean doesSneakBypassUse(net.minecraft.world.level.LevelReader level, BlockPos pos, Player player) {
|
||||
return self().isEmpty() || self().getItem().doesSneakBypassUse(self(), level, pos, player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Modeled after ItemStack.areItemStackTagsEqual
|
||||
* Uses Item.getNBTShareTag for comparison instead of NBT and capabilities.
|
||||
* Only used for comparing itemStacks that were transferred from server to client using Item.getNBTShareTag.
|
||||
*/
|
||||
default boolean areShareTagsEqual(ItemStack other)
|
||||
{
|
||||
CompoundTag shareTagA = self().getShareTag();
|
||||
CompoundTag shareTagB = other.getShareTag();
|
||||
if (shareTagA == null)
|
||||
return shareTagB == null;
|
||||
else
|
||||
return shareTagB != null && shareTagA.equals(shareTagB);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the ItemStack is equal to the other item stack, including Item, Count, and NBT.
|
||||
*
|
||||
* @param other The other stack
|
||||
* @param limitTags True to use shareTag False to use full NBT tag
|
||||
* @return true if equals
|
||||
*/
|
||||
default boolean equals(ItemStack other, boolean limitTags)
|
||||
{
|
||||
if (self().isEmpty())
|
||||
return other.isEmpty();
|
||||
else
|
||||
return !other.isEmpty() && self().getCount() == other.getCount() && self().getItem() == other.getItem() &&
|
||||
(limitTags ? self().areShareTagsEqual(other) : Objects.equals(self().getTag(), other.getTag()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a item is reparable, used by Repair recipes and Grindstone.
|
||||
*
|
||||
* @return True if reparable
|
||||
*/
|
||||
default boolean isRepairable()
|
||||
{
|
||||
return self().getItem().isRepairable(self());
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by Piglins when checking to see if they will give an item or something in exchange for this item.
|
||||
*
|
||||
* @return True if this item can be used as "currency" by piglins
|
||||
*/
|
||||
default boolean isPiglinCurrency()
|
||||
{
|
||||
default boolean isPiglinCurrency() {
|
||||
return self().getItem().isPiglinCurrency(self());
|
||||
}
|
||||
|
||||
@@ -471,8 +333,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
*
|
||||
* @return True if piglins are neutral to players wearing this item in an armor slot
|
||||
*/
|
||||
default boolean makesPiglinsNeutral(LivingEntity wearer)
|
||||
{
|
||||
default boolean makesPiglinsNeutral(LivingEntity wearer) {
|
||||
return self().getItem().makesPiglinsNeutral(self(), wearer);
|
||||
}
|
||||
|
||||
@@ -483,8 +344,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param endermanEntity The enderman that the player look
|
||||
* @return true if this Item can be used.
|
||||
*/
|
||||
default boolean isEnderMask(Player player, EnderMan endermanEntity)
|
||||
{
|
||||
default boolean isEnderMask(Player player, EnderMan endermanEntity) {
|
||||
return self().getItem().isEnderMask(self(), player, endermanEntity);
|
||||
}
|
||||
|
||||
@@ -495,8 +355,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param entity The entity trying to fly.
|
||||
* @return True if the entity can use Elytra flight.
|
||||
*/
|
||||
default boolean canElytraFly(LivingEntity entity)
|
||||
{
|
||||
default boolean canElytraFly(LivingEntity entity) {
|
||||
return self().getItem().canElytraFly(self(), entity);
|
||||
}
|
||||
|
||||
@@ -511,8 +370,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param flightTicks The number of ticks the entity has been Elytra flying for.
|
||||
* @return True if the entity should continue Elytra flight or False to stop.
|
||||
*/
|
||||
default boolean elytraFlightTick(LivingEntity entity, int flightTicks)
|
||||
{
|
||||
default boolean elytraFlightTick(LivingEntity entity, int flightTicks) {
|
||||
return self().getItem().elytraFlightTick(self(), entity, flightTicks);
|
||||
}
|
||||
|
||||
@@ -524,8 +382,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
*
|
||||
* @return True if the entity can walk on powdered snow
|
||||
*/
|
||||
default boolean canWalkOnPowderedSnow(LivingEntity wearer)
|
||||
{
|
||||
default boolean canWalkOnPowderedSnow(LivingEntity wearer) {
|
||||
return self().getItem().canWalkOnPowderedSnow(self(), wearer);
|
||||
}
|
||||
|
||||
@@ -537,8 +394,7 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @return the bounding box.
|
||||
*/
|
||||
@NotNull
|
||||
default AABB getSweepHitBox(@NotNull Player player, @NotNull Entity target)
|
||||
{
|
||||
default AABB getSweepHitBox(@NotNull Player player, @NotNull Entity target) {
|
||||
return self().getItem().getSweepHitBox(self(), player, target);
|
||||
}
|
||||
|
||||
@@ -548,27 +404,10 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param itemEntity The item entity that was destroyed.
|
||||
* @param damageSource Damage source that caused the item entity to "die".
|
||||
*/
|
||||
default void onDestroyed(ItemEntity itemEntity, DamageSource damageSource)
|
||||
{
|
||||
default void onDestroyed(ItemEntity itemEntity, DamageSource damageSource) {
|
||||
self().getItem().onDestroyed(itemEntity, damageSource);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the food properties for this item.
|
||||
* This is a bouncer for easier use of {@link IForgeItem#getFoodProperties(ItemStack, LivingEntity)}
|
||||
*
|
||||
* The @Nullable annotation was only added, due to the default method, also being @Nullable.
|
||||
* Use this with a grain of salt, as if you return null here and true at {@link Item#isEdible()}, NPEs will occur!
|
||||
*
|
||||
* @param entity The entity which wants to eat the food. Be aware that this can be null!
|
||||
* @return The current FoodProperties for the item.
|
||||
*/
|
||||
@Nullable // read javadoc to find a potential problem
|
||||
default FoodProperties getFoodProperties(@Nullable LivingEntity entity)
|
||||
{
|
||||
return self().getItem().getFoodProperties(self(), entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this stack should be excluded (if possible) when selecting the target hotbar slot of a "pick" action.
|
||||
* By default, this returns true for enchanted stacks.
|
||||
@@ -578,16 +417,14 @@ public interface IForgeItemStack extends ICapabilitySerializable<CompoundTag>
|
||||
* @param inventorySlot the inventory slot of the item being up for replacement
|
||||
* @return true to leave this stack in the hotbar if possible
|
||||
*/
|
||||
default boolean isNotReplaceableByPickAction(Player player, int inventorySlot)
|
||||
{
|
||||
default boolean isNotReplaceableByPickAction(Player player, int inventorySlot) {
|
||||
return self().getItem().isNotReplaceableByPickAction(self(), player, inventorySlot);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@return true if the given ItemStack can be put into a grindstone to be repaired and/or stripped of its enchantments}
|
||||
*/
|
||||
default boolean canGrindstoneRepair()
|
||||
{
|
||||
default boolean canGrindstoneRepair() {
|
||||
return self().getItem().canGrindstoneRepair(self());
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public interface IForgeLivingEntity extends IForgeEntity {
|
||||
* @param type the type of the fluid
|
||||
*/
|
||||
default void jumpInFluid(FluidType type) {
|
||||
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D));
|
||||
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.getHolder().get()), 0.0D));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -39,7 +39,7 @@ public interface IForgeLivingEntity extends IForgeEntity {
|
||||
* @param type the type of the fluid
|
||||
*/
|
||||
default void sinkInFluid(FluidType type) {
|
||||
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)-0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.get()), 0.0D));
|
||||
self().setDeltaMovement(self().getDeltaMovement().add(0.0D, (double)-0.04F * self().getAttributeValue(ForgeMod.SWIM_SPEED.getHolder().get()), 0.0D));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
|
||||
public interface IForgeMobEffectInstance {
|
||||
/***
|
||||
* Returns a list of curative items for the potion effect
|
||||
* By default, this list is initialized using {@link MobEffect#getCurativeItems()}
|
||||
*
|
||||
* @return The list (ItemStack) of curative items for the potion effect
|
||||
*/
|
||||
List<ItemStack> getCurativeItems();
|
||||
|
||||
/***
|
||||
* Checks the given ItemStack to see if it is in the list of curative items for the potion effect
|
||||
* @param stack The ItemStack being checked against the list of curative items for this PotionEffect
|
||||
* @return true if the given ItemStack is in the list of curative items for this PotionEffect, false otherwise
|
||||
*/
|
||||
default boolean isCurativeItem(ItemStack stack) {
|
||||
return this.getCurativeItems().stream().anyMatch(e -> ItemStack.isSameItem(e, stack));
|
||||
}
|
||||
|
||||
/***
|
||||
* Sets the list of curative items for this potion effect, overwriting any already present
|
||||
* @param curativeItems The list of ItemStacks being set to the potion effect
|
||||
*/
|
||||
void setCurativeItems(List<ItemStack> curativeItems);
|
||||
|
||||
/***
|
||||
* Adds the given stack to the list of curative items for this PotionEffect
|
||||
* @param stack The ItemStack being added to the curative item list
|
||||
*/
|
||||
default void addCurativeItem(ItemStack stack) {
|
||||
if (!this.isCurativeItem(stack))
|
||||
this.getCurativeItems().add(stack);
|
||||
}
|
||||
|
||||
default void writeCurativeItems(CompoundTag nbt) {
|
||||
ListTag list = new ListTag();
|
||||
getCurativeItems().forEach(s -> list.add(s.save(new CompoundTag())));
|
||||
nbt.put("CurativeItems", list);
|
||||
}
|
||||
}
|
||||
@@ -5,73 +5,16 @@
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.minecraftforge.common.ForgeMod;
|
||||
|
||||
public interface IForgePlayer {
|
||||
private Player self() {
|
||||
return (Player)this;
|
||||
}
|
||||
|
||||
/**
|
||||
* The entity reach is increased by 3 for creative players, unless it is currently zero, which disables attacks and entity interactions.
|
||||
* @return The entity reach of this player.
|
||||
*/
|
||||
default double getEntityReach() {
|
||||
double range = self().getAttributeValue(ForgeMod.ENTITY_REACH.get());
|
||||
return range == 0 ? 0 : range + (self().isCreative() ? 3 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reach distance is increased by 0.5 for creative players, unless it is currently zero, which disables interactions.
|
||||
* @return The reach distance of this player.
|
||||
*/
|
||||
default double getBlockReach() {
|
||||
double reach = self().getAttributeValue(ForgeMod.BLOCK_REACH.get());
|
||||
return reach == 0 ? 0 : reach + (self().isCreative() ? 0.5 : 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player can reach an entity by targeting the passed vector.<br>
|
||||
* On the server, additional padding is added to account for movement/lag.
|
||||
* @param entityHitVec The vector being range-checked.
|
||||
* @param padding Extra validation distance.
|
||||
* @return If the player can attack the entity.
|
||||
* @apiNote Do not use for block checks, as this method uses {@link #getEntityReach()}
|
||||
*/
|
||||
default boolean canReach(Vec3 entityHitVec, double padding) {
|
||||
return self().getEyePosition().closerThan(entityHitVec, getEntityReach() + padding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player can reach an entity.<br>
|
||||
* On the server, additional padding is added to account for movement/lag.
|
||||
* @param entity The entity being range-checked.
|
||||
* @param padding Extra validation distance.
|
||||
* @return If the player can attack the passed entity.
|
||||
* @apiNote Prefer using {@link #canReach(Vec3, double)} if you have a {@link HitResult} available.
|
||||
*/
|
||||
default boolean canReach(Entity entity, double padding) {
|
||||
return isCloseEnough(entity, getEntityReach() + padding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player can reach a block.<br>
|
||||
* On the server, additional padding is added to account for movement/lag.
|
||||
* @param pos The position being range-checked.
|
||||
* @param padding Extra validation distance.
|
||||
* @return If the player can interact with this location.
|
||||
*/
|
||||
default boolean canReach(BlockPos pos, double padding) {
|
||||
double reach = this.getBlockReach() + padding;
|
||||
return self().getEyePosition().distanceToSqr(Vec3.atCenterOf(pos)) < reach * reach;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility check to see if the player is close enough to a target entity. Uses "eye-to-closest-corner" checks.
|
||||
* @param entity The entity being checked against
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) Forge Development LLC and contributors
|
||||
* SPDX-License-Identifier: LGPL-2.1-only
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.extensions;
|
||||
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.alchemy.PotionUtils;
|
||||
|
||||
public interface IForgePotion {
|
||||
/**
|
||||
* Determines whether the potion bottle item should be enchanted.
|
||||
* Not called for tipped arrows or if the item is already enchanted.
|
||||
* @param stack The potion bottle
|
||||
* @return whether the item should appear enchanted.
|
||||
*/
|
||||
default boolean isFoil(ItemStack stack) {
|
||||
return !PotionUtils.getMobEffects(stack).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import net.minecraft.tags.TagEntry;
|
||||
|
||||
public interface IForgeRawTagBuilder {
|
||||
default TagBuilder getRawBuilder() {
|
||||
return (TagBuilder)this;
|
||||
return (TagBuilder) this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -51,4 +51,11 @@ public interface IForgeRawTagBuilder {
|
||||
default TagBuilder removeTag(final ResourceLocation tagID, final String source) {
|
||||
return this.remove(TagEntry.tag(tagID), source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shorthand version of {@code replace(true)}
|
||||
*/
|
||||
default TagBuilder replace() {
|
||||
return this.getRawBuilder().replace(true);
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,9 @@ import org.joml.Vector4f;
|
||||
/**
|
||||
* Extension interface for {@link Transformation}.
|
||||
*/
|
||||
public interface IForgeTransformation
|
||||
{
|
||||
private Transformation self()
|
||||
{
|
||||
return (Transformation) this;
|
||||
public interface IForgeTransformation {
|
||||
private Transformation self() {
|
||||
return (Transformation)this;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -27,8 +25,7 @@ public interface IForgeTransformation
|
||||
*
|
||||
* @see Transformation#identity()
|
||||
*/
|
||||
default boolean isIdentity()
|
||||
{
|
||||
default boolean isIdentity() {
|
||||
return self().equals(Transformation.identity());
|
||||
}
|
||||
|
||||
@@ -37,8 +34,7 @@ public interface IForgeTransformation
|
||||
*
|
||||
* @param position the position to transform
|
||||
*/
|
||||
default void transformPosition(Vector4f position)
|
||||
{
|
||||
default void transformPosition(Vector4f position) {
|
||||
position.mul(self().getMatrix());
|
||||
}
|
||||
|
||||
@@ -47,8 +43,7 @@ public interface IForgeTransformation
|
||||
*
|
||||
* @param normal the normal to transform
|
||||
*/
|
||||
default void transformNormal(Vector3f normal)
|
||||
{
|
||||
default void transformNormal(Vector3f normal) {
|
||||
normal.mul(self().getNormalMatrix());
|
||||
normal.normalize();
|
||||
}
|
||||
@@ -61,8 +56,7 @@ public interface IForgeTransformation
|
||||
* @return the {@code Direction} value nearest to the resulting transformed direction
|
||||
* @see Direction#rotate(Matrix4f, Direction)
|
||||
*/
|
||||
default Direction rotateTransform(Direction facing)
|
||||
{
|
||||
default Direction rotateTransform(Direction facing) {
|
||||
return Direction.rotate(self().getMatrix(), facing);
|
||||
}
|
||||
|
||||
@@ -72,8 +66,7 @@ public interface IForgeTransformation
|
||||
*
|
||||
* @return a new transformation using the opposing-corner-block system
|
||||
*/
|
||||
default Transformation blockCenterToCorner()
|
||||
{
|
||||
default Transformation blockCenterToCorner() {
|
||||
return applyOrigin(new Vector3f(.5f, .5f, .5f));
|
||||
}
|
||||
|
||||
@@ -83,8 +76,7 @@ public interface IForgeTransformation
|
||||
*
|
||||
* @return a new transformation using the center-block system
|
||||
*/
|
||||
default Transformation blockCornerToCenter()
|
||||
{
|
||||
default Transformation blockCornerToCenter() {
|
||||
return applyOrigin(new Vector3f(-.5f, -.5f, -.5f));
|
||||
}
|
||||
|
||||
@@ -95,8 +87,7 @@ public interface IForgeTransformation
|
||||
* @param origin the new origin as relative to the current origin
|
||||
* @return a new transformation with a changed origin
|
||||
*/
|
||||
default Transformation applyOrigin(Vector3f origin)
|
||||
{
|
||||
default Transformation applyOrigin(Vector3f origin) {
|
||||
Transformation transform = self();
|
||||
if (transform.isIdentity()) return Transformation.identity();
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
package net.minecraftforge.common.loot;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
@@ -24,7 +24,7 @@ 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 record CanToolPerformAction(ToolAction action) implements LootItemCondition {
|
||||
public static final Codec<CanToolPerformAction> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<CanToolPerformAction> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ToolAction.CODEC.fieldOf("action").forGetter(CanToolPerformAction::action)
|
||||
).apply(b, CanToolPerformAction::new));
|
||||
public static final LootItemConditionType TYPE = new LootItemConditionType(CODEC);
|
||||
|
||||
@@ -9,8 +9,9 @@ import com.google.gson.JsonElement;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.Dynamic;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
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;
|
||||
@@ -28,10 +29,9 @@ import java.util.function.Function;
|
||||
* 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<IGlobalLootModifier> DIRECT_CODEC = Codec.lazyInitialized(() -> ForgeRegistries.GLOBAL_LOOT_MODIFIER_SERIALIZERS.get().getCodec().dispatch(IGlobalLootModifier::codec, Function.identity()));
|
||||
|
||||
Codec<LootItemCondition[]> LOOT_CONDITIONS_CODEC = LootItemConditions.CODEC.listOf().xmap(list -> list.toArray(LootItemCondition[]::new), List::of);
|
||||
Codec<LootItemCondition[]> LOOT_CONDITIONS_CODEC = LootItemConditions.DIRECT_CODEC.listOf().xmap(list -> list.toArray(LootItemCondition[]::new), List::of);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static <U> JsonElement getJson(Dynamic<?> dynamic) {
|
||||
@@ -54,5 +54,5 @@ public interface IGlobalLootModifier {
|
||||
/**
|
||||
* Returns the registered codec for this modifier
|
||||
*/
|
||||
Codec<? extends IGlobalLootModifier> codec();
|
||||
MapCodec<? extends IGlobalLootModifier> codec();
|
||||
}
|
||||
@@ -11,11 +11,11 @@ import java.util.function.Predicate;
|
||||
import com.mojang.datafixers.Products;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
|
||||
import net.minecraft.Util;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.levelgen.feature.trunkplacers.BendingTrunkPlacer;
|
||||
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 org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
@@ -46,7 +46,7 @@ public abstract class LootModifier implements IGlobalLootModifier {
|
||||
*/
|
||||
protected LootModifier(LootItemCondition[] conditionsIn) {
|
||||
this.conditions = conditionsIn;
|
||||
this.combinedConditions = LootItemConditions.andConditions(Arrays.asList(conditionsIn));
|
||||
this.combinedConditions = Util.allOf(Arrays.asList(conditionsIn));
|
||||
}
|
||||
|
||||
@NotNull
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
package net.minecraftforge.common.loot;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.world.level.storage.loot.predicates.LootItemConditionType;
|
||||
@@ -14,7 +14,7 @@ import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
|
||||
public record LootTableIdCondition(ResourceLocation id) implements LootItemCondition {
|
||||
public static final Codec<LootTableIdCondition> CODEC = RecordCodecBuilder.create(b -> b.group(
|
||||
public static final MapCodec<LootTableIdCondition> CODEC = RecordCodecBuilder.mapCodec(b -> b.group(
|
||||
ResourceLocation.CODEC.fieldOf("loot_table_id").forGetter(LootTableIdCondition::id)
|
||||
).apply(b, LootTableIdCondition::new));
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.world.level.LevelAccessor;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraftforge.server.ServerLifecycleHooks;
|
||||
@@ -27,8 +28,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
* Unlike Block, which only one object can exist per coordinate, BlockSnapshot
|
||||
* can exist multiple times for any given Block.
|
||||
*/
|
||||
public class BlockSnapshot
|
||||
{
|
||||
public class BlockSnapshot {
|
||||
private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("forge.debugBlockSnapshot", "false"));
|
||||
|
||||
private final ResourceKey<Level> dim;
|
||||
@@ -42,8 +42,7 @@ public class BlockSnapshot
|
||||
private WeakReference<LevelAccessor> level;
|
||||
private String toString = null;
|
||||
|
||||
private BlockSnapshot(ResourceKey<Level> dim, LevelAccessor level, BlockPos pos, BlockState state, @Nullable CompoundTag nbt, int flags)
|
||||
{
|
||||
private BlockSnapshot(ResourceKey<Level> dim, LevelAccessor level, BlockPos pos, BlockState state, @Nullable CompoundTag nbt, int flags) {
|
||||
this.dim = dim;
|
||||
this.pos = pos.immutable();
|
||||
this.block = state;
|
||||
@@ -56,75 +55,64 @@ public class BlockSnapshot
|
||||
System.out.println("Created " + this.toString());
|
||||
}
|
||||
|
||||
public static BlockSnapshot create(ResourceKey<Level> dim, LevelAccessor world, BlockPos pos)
|
||||
{
|
||||
public static BlockSnapshot create(ResourceKey<Level> dim, LevelAccessor world, BlockPos pos) {
|
||||
return create(dim, world, pos, 3);
|
||||
}
|
||||
|
||||
public static BlockSnapshot create(ResourceKey<Level> dim, LevelAccessor world, BlockPos pos, int flag)
|
||||
{
|
||||
return new BlockSnapshot(dim, world, pos, world.getBlockState(pos), getBlockEntityTag(world.getBlockEntity(pos)), flag);
|
||||
public static BlockSnapshot create(ResourceKey<Level> dim, LevelAccessor world, BlockPos pos, int flag) {
|
||||
return new BlockSnapshot(dim, world, pos, world.getBlockState(pos), getBlockEntityTag(world.getBlockEntity(pos), world.registryAccess()), flag);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private static CompoundTag getBlockEntityTag(@Nullable BlockEntity te)
|
||||
{
|
||||
return te == null ? null : te.saveWithFullMetadata();
|
||||
private static CompoundTag getBlockEntityTag(@Nullable BlockEntity te, HolderLookup.Provider lookup) {
|
||||
return te == null ? null : te.saveCustomAndMetadata(lookup);
|
||||
}
|
||||
|
||||
public BlockState getCurrentBlock()
|
||||
{
|
||||
public BlockState getCurrentBlock() {
|
||||
LevelAccessor world = getLevel();
|
||||
return world == null ? Blocks.AIR.defaultBlockState() : world.getBlockState(this.pos);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public LevelAccessor getLevel()
|
||||
{
|
||||
public LevelAccessor getLevel() {
|
||||
LevelAccessor world = this.level != null ? this.level.get() : null;
|
||||
if (world == null)
|
||||
{
|
||||
if (world == null) {
|
||||
world = ServerLifecycleHooks.getCurrentServer().getLevel(this.dim);
|
||||
this.level = new WeakReference<LevelAccessor>(world);
|
||||
}
|
||||
return world;
|
||||
}
|
||||
|
||||
public BlockState getReplacedBlock()
|
||||
{
|
||||
public BlockState getReplacedBlock() {
|
||||
return this.block;
|
||||
}
|
||||
|
||||
/*
|
||||
@Nullable
|
||||
public BlockEntity getBlockEntity()
|
||||
{
|
||||
public BlockEntity getBlockEntity() {
|
||||
return getTag() != null ? BlockEntity.loadStatic(getPos(), getReplacedBlock(), getTag()) : null;
|
||||
}
|
||||
*/
|
||||
|
||||
public boolean restore()
|
||||
{
|
||||
public boolean restore() {
|
||||
return restore(false);
|
||||
}
|
||||
|
||||
public boolean restore(boolean force)
|
||||
{
|
||||
public boolean restore(boolean force) {
|
||||
return restore(force, true);
|
||||
}
|
||||
|
||||
public boolean restore(boolean force, boolean notifyNeighbors)
|
||||
{
|
||||
public boolean restore(boolean force, boolean notifyNeighbors) {
|
||||
return restoreToLocation(getLevel(), getPos(), force, notifyNeighbors);
|
||||
}
|
||||
|
||||
public boolean restoreToLocation(LevelAccessor world, BlockPos pos, boolean force, boolean notifyNeighbors)
|
||||
{
|
||||
public boolean restoreToLocation(LevelAccessor world, BlockPos pos, boolean force, boolean notifyNeighbors) {
|
||||
BlockState current = getCurrentBlock();
|
||||
BlockState replaced = getReplacedBlock();
|
||||
|
||||
int flags = notifyNeighbors ? Block.UPDATE_ALL : Block.UPDATE_CLIENTS;
|
||||
|
||||
if (current != replaced)
|
||||
{
|
||||
if (current != replaced) {
|
||||
if (force)
|
||||
world.setBlock(pos, replaced, flags);
|
||||
else
|
||||
@@ -136,12 +124,10 @@ public class BlockSnapshot
|
||||
((Level)world).sendBlockUpdated(pos, current, replaced, flags);
|
||||
|
||||
BlockEntity te = null;
|
||||
if (getTag() != null)
|
||||
{
|
||||
if (getTag() != null) {
|
||||
te = world.getBlockEntity(pos);
|
||||
if (te != null)
|
||||
{
|
||||
te.load(getTag());
|
||||
if (te != null) {
|
||||
te.loadWithComponents(nbt, world.registryAccess());
|
||||
te.setChanged();
|
||||
}
|
||||
}
|
||||
@@ -152,8 +138,7 @@ public class BlockSnapshot
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == this)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
@@ -168,8 +153,7 @@ public class BlockSnapshot
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode()
|
||||
{
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 73 * hash + this.dim.hashCode();
|
||||
hash = 73 * hash + this.pos.hashCode();
|
||||
@@ -180,10 +164,8 @@ public class BlockSnapshot
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
if (toString == null)
|
||||
{
|
||||
public String toString() {
|
||||
if (toString == null) {
|
||||
this.toString =
|
||||
"BlockSnapshot[" +
|
||||
"World:" + this.dim.location() + ',' +
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
package net.minecraftforge.common.util;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
|
||||
@@ -15,8 +16,7 @@ public class DummySavedData extends SavedData {
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag save(final CompoundTag compound) {
|
||||
// NOOP
|
||||
public CompoundTag save(final CompoundTag compound, HolderLookup.Provider lookup) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,22 @@
|
||||
|
||||
package net.minecraftforge.common.util;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.Tag;
|
||||
|
||||
/**
|
||||
* An interface designed to unify various things in the Minecraft
|
||||
* code base that can be serialized to and from a NBT tag.
|
||||
*
|
||||
* @deprecated // Mojang has switched most things to Codecs and registry context, probably worth deleting this.
|
||||
*/
|
||||
public interface INBTSerializable<T extends Tag>
|
||||
{
|
||||
T serializeNBT();
|
||||
void deserializeNBT(T nbt);
|
||||
public interface INBTSerializable<T extends Tag> {
|
||||
default T serializeNBT() { return null; }
|
||||
default T serializeNBT(HolderLookup.Provider registryAccess) {
|
||||
return serializeNBT();
|
||||
}
|
||||
default void deserializeNBT(T nbt) { }
|
||||
default void deserializeNBT(HolderLookup.Provider registryAccess, T nbt) {
|
||||
deserializeNBT(nbt);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
package net.minecraftforge.common.util;
|
||||
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderLookup.Provider;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
import net.minecraft.world.level.storage.DimensionDataStorage;
|
||||
@@ -30,7 +32,7 @@ public class LevelCapabilityData extends SavedData {
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag save(CompoundTag nbt) {
|
||||
public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) {
|
||||
if (serializable != null)
|
||||
nbt = serializable.serializeNBT();
|
||||
return nbt;
|
||||
@@ -52,7 +54,7 @@ public class LevelCapabilityData extends SavedData {
|
||||
public static LevelCapabilityData compute(DimensionDataStorage data, @Nullable INBTSerializable<CompoundTag> caps) {
|
||||
var factory = new Factory<>(
|
||||
() -> new LevelCapabilityData(caps),
|
||||
(tag) -> {
|
||||
(tag, lookup) -> {
|
||||
var ret = new LevelCapabilityData(caps);
|
||||
ret.read(tag);
|
||||
return ret;
|
||||
|
||||
@@ -47,11 +47,8 @@ public class PacketLogger {
|
||||
if (packet instanceof ClientboundFinishConfigurationPacket)
|
||||
enabled = false;
|
||||
|
||||
if (packet instanceof ICustomPacket) {
|
||||
var data = new FriendlyByteBuf(Unpooled.buffer());
|
||||
|
||||
packet.write(data);
|
||||
LOGGER.info(MARKER, "{} {} {}\n{}", side(side), dir(flow), packet.getClass().getName(), HexDumper.dump(data));
|
||||
if (packet instanceof ICustomPacket custom && custom.getInternalData() != null) {
|
||||
LOGGER.info(MARKER, "{} {} {}\n{}", side(side), dir(flow), packet.getClass().getName(), HexDumper.dump(custom.getInternalData()));
|
||||
} else {
|
||||
LOGGER.info(MARKER, "{} {} {}", side(side), dir(flow), packet.getClass().getName());
|
||||
}
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
package net.minecraftforge.common.world;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.RegistryCodecs;
|
||||
import net.minecraft.resources.RegistryFileCodec;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.util.ExtraCodecs;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
@@ -31,14 +32,12 @@ import java.util.function.Function;
|
||||
* <p>
|
||||
* Datapacks can also disable a biome modifier by overriding the json and using {@code "type": "forge:none"}.</p>
|
||||
*/
|
||||
public interface BiomeModifier
|
||||
{
|
||||
public interface BiomeModifier {
|
||||
/**
|
||||
* Codec for (de)serializing biome modifiers inline.
|
||||
* Mods can use this for data generation.
|
||||
*/
|
||||
Codec<BiomeModifier> DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.BIOME_MODIFIER_SERIALIZERS.get().getCodec())
|
||||
.dispatch(BiomeModifier::codec, Function.identity());
|
||||
Codec<BiomeModifier> DIRECT_CODEC = Codec.lazyInitialized(() -> ForgeRegistries.BIOME_MODIFIER_SERIALIZERS.get().getCodec().dispatch(BiomeModifier::codec, Function.identity()));
|
||||
|
||||
/**
|
||||
* Codec for referring to biome modifiers by id in other datapack registry files.
|
||||
@@ -66,10 +65,9 @@ public interface BiomeModifier
|
||||
/**
|
||||
* @return the codec which serializes and deserializes this biome modifier
|
||||
*/
|
||||
Codec<? extends BiomeModifier> codec();
|
||||
MapCodec<? extends BiomeModifier> codec();
|
||||
|
||||
enum Phase
|
||||
{
|
||||
enum Phase {
|
||||
/**
|
||||
* Catch-all for anything that needs to run before standard phases.
|
||||
*/
|
||||
|
||||
@@ -12,12 +12,12 @@ import java.util.function.Function;
|
||||
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import com.mojang.serialization.codecs.RecordCodecBuilder;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.RegistryCodecs;
|
||||
import net.minecraft.util.ExtraCodecs;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.MobCategory;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
@@ -47,7 +47,7 @@ public final class ForgeBiomeModifiers {
|
||||
* @param step Decoration step to run features in.
|
||||
*/
|
||||
public static record AddFeaturesBiomeModifier(HolderSet<Biome> biomes, HolderSet<PlacedFeature> features, Decoration step) implements BiomeModifier {
|
||||
public static final Codec<AddFeaturesBiomeModifier> CODEC = RecordCodecBuilder.create(builder -> builder.group(
|
||||
public static final MapCodec<AddFeaturesBiomeModifier> CODEC = RecordCodecBuilder.mapCodec(builder -> builder.group(
|
||||
Biome.LIST_CODEC.fieldOf("biomes").forGetter(AddFeaturesBiomeModifier::biomes),
|
||||
PlacedFeature.LIST_CODEC.fieldOf("features").forGetter(AddFeaturesBiomeModifier::features),
|
||||
Decoration.CODEC.fieldOf("step").forGetter(AddFeaturesBiomeModifier::step)
|
||||
@@ -62,7 +62,7 @@ public final class ForgeBiomeModifiers {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends BiomeModifier> codec() {
|
||||
public MapCodec<? extends BiomeModifier> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -83,11 +83,11 @@ public final class ForgeBiomeModifiers {
|
||||
* @param steps Decoration steps to remove features from.
|
||||
*/
|
||||
public static record RemoveFeaturesBiomeModifier(HolderSet<Biome> biomes, HolderSet<PlacedFeature> features, Set<Decoration> steps) implements BiomeModifier {
|
||||
public static final Codec<RemoveFeaturesBiomeModifier> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<RemoveFeaturesBiomeModifier> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Biome.LIST_CODEC.fieldOf("biomes").forGetter(RemoveFeaturesBiomeModifier::biomes),
|
||||
PlacedFeature.LIST_CODEC.fieldOf("features").forGetter(RemoveFeaturesBiomeModifier::features),
|
||||
ExtraCodecs.either(Decoration.CODEC.listOf(), Decoration.CODEC).<Set<Decoration>>xmap(
|
||||
Codec.either(Decoration.CODEC.listOf(), Decoration.CODEC).<Set<Decoration>>xmap(
|
||||
either -> either.map(Set::copyOf, Set::of), // convert list/singleton to set when decoding
|
||||
set -> set.size() == 1 ? Either.right(set.toArray(Decoration[]::new)[0]) : Either.left(List.copyOf(set))
|
||||
).optionalFieldOf("steps", EnumSet.allOf(Decoration.class)).forGetter(RemoveFeaturesBiomeModifier::steps)
|
||||
@@ -112,7 +112,7 @@ public final class ForgeBiomeModifiers {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends BiomeModifier> codec() {
|
||||
public MapCodec<? extends BiomeModifier> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -156,11 +156,11 @@ public final class ForgeBiomeModifiers {
|
||||
* @param spawners List of SpawnerDatas specifying EntityType, weight, and pack size.
|
||||
*/
|
||||
public record AddSpawnsBiomeModifier(HolderSet<Biome> biomes, List<SpawnerData> spawners) implements BiomeModifier {
|
||||
public static final Codec<AddSpawnsBiomeModifier> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<AddSpawnsBiomeModifier> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Biome.LIST_CODEC.fieldOf("biomes").forGetter(AddSpawnsBiomeModifier::biomes),
|
||||
// Allow either a list or single spawner, attempting to decode the list format first.
|
||||
ExtraCodecs.either(SpawnerData.CODEC.listOf(), SpawnerData.CODEC).xmap(
|
||||
Codec.either(SpawnerData.CODEC.listOf(), SpawnerData.CODEC).xmap(
|
||||
either -> either.map(Function.identity(), List::of), // convert list/singleton to list when decoding
|
||||
list -> list.size() == 1 ? Either.right(list.get(0)) : Either.left(list) // convert list to singleton/list when encoding
|
||||
).fieldOf("spawners").forGetter(AddSpawnsBiomeModifier::spawners)
|
||||
@@ -186,7 +186,7 @@ public final class ForgeBiomeModifiers {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends BiomeModifier> codec() {
|
||||
public MapCodec<? extends BiomeModifier> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -205,7 +205,7 @@ public final class ForgeBiomeModifiers {
|
||||
* @param entityTypes EntityTypes to remove from spawn lists.
|
||||
*/
|
||||
public record RemoveSpawnsBiomeModifier(HolderSet<Biome> biomes, HolderSet<EntityType<?>> entityTypes) implements BiomeModifier {
|
||||
public static final Codec<RemoveSpawnsBiomeModifier> CODEC = RecordCodecBuilder.create(builder ->
|
||||
public static final MapCodec<RemoveSpawnsBiomeModifier> CODEC = RecordCodecBuilder.mapCodec(builder ->
|
||||
builder.group(
|
||||
Biome.LIST_CODEC.fieldOf("biomes").forGetter(RemoveSpawnsBiomeModifier::biomes),
|
||||
RegistryCodecs.homogeneousList(ForgeRegistries.Keys.ENTITY_TYPES).fieldOf("entity_types").forGetter(RemoveSpawnsBiomeModifier::entityTypes)
|
||||
@@ -221,7 +221,7 @@ public final class ForgeBiomeModifiers {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends BiomeModifier> codec() {
|
||||
public MapCodec<? extends BiomeModifier> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
@@ -324,10 +325,12 @@ public class ForgeChunkManager
|
||||
*/
|
||||
private static void readBlockForcedChunks(String modId, long chunkPos, CompoundTag modEntry, String key, Map<TicketOwner<BlockPos>, LongSet> blockForcedChunks)
|
||||
{
|
||||
ListTag forcedBlocks = modEntry.getList(key, Tag.TAG_COMPOUND);
|
||||
ListTag forcedBlocks = modEntry.getList(key, Tag.TAG_INT_ARRAY);
|
||||
for (int k = 0; k < forcedBlocks.size(); k++)
|
||||
{
|
||||
blockForcedChunks.computeIfAbsent(new TicketOwner<>(modId, NbtUtils.readBlockPos(forcedBlocks.getCompound(k))), owner -> new LongOpenHashSet()).add(chunkPos);
|
||||
var aint = forcedBlocks.getIntArray(k);
|
||||
var pos = aint.length == 3 ? new BlockPos(aint[0], aint[1], aint[2]) : BlockPos.ZERO;
|
||||
blockForcedChunks.computeIfAbsent(new TicketOwner<>(modId, pos), owner -> new LongOpenHashSet()).add(chunkPos);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
package net.minecraftforge.common.world;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo.Builder;
|
||||
@@ -15,14 +16,14 @@ import net.minecraftforge.common.world.ModifiableBiomeInfo.BiomeInfo.Builder;
|
||||
*/
|
||||
public class NoneBiomeModifier implements BiomeModifier {
|
||||
public static final NoneBiomeModifier INSTANCE = new NoneBiomeModifier();
|
||||
public static final Codec<NoneBiomeModifier> CODEC = Codec.unit(NoneBiomeModifier.INSTANCE);
|
||||
public static final MapCodec<NoneBiomeModifier> CODEC = MapCodec.unit(NoneBiomeModifier.INSTANCE);
|
||||
|
||||
@Override
|
||||
public void modify(Holder<Biome> biome, Phase phase, Builder builder) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Codec<? extends BiomeModifier> codec() {
|
||||
public MapCodec<? extends BiomeModifier> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
package net.minecraftforge.common.world;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo.Builder;
|
||||
@@ -16,13 +17,13 @@ import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo.Bui
|
||||
*/
|
||||
public class NoneStructureModifier implements StructureModifier {
|
||||
public static final NoneStructureModifier INSTANCE = new NoneStructureModifier();
|
||||
public static final Codec<NoneStructureModifier> CODEC = Codec.unit(NoneStructureModifier.INSTANCE);
|
||||
public static final MapCodec<NoneStructureModifier> CODEC = MapCodec.unit(NoneStructureModifier.INSTANCE);
|
||||
|
||||
@Override
|
||||
public void modify(Holder<Structure> structure, Phase phase, Builder builder) {}
|
||||
|
||||
@Override
|
||||
public Codec<? extends StructureModifier> codec() {
|
||||
public MapCodec<? extends StructureModifier> codec() {
|
||||
return CODEC;
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,14 @@
|
||||
package net.minecraftforge.common.world;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
|
||||
import java.util.function.Function;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.RegistryCodecs;
|
||||
import net.minecraft.resources.RegistryFileCodec;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.util.ExtraCodecs;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo;
|
||||
import net.minecraftforge.registries.ForgeRegistries;
|
||||
@@ -31,14 +32,12 @@ import net.minecraftforge.registries.ForgeRegistries;
|
||||
* <p>
|
||||
* Datapacks can also disable a structure modifier by overriding the json and using {@code "type": "forge:none"}.</p>
|
||||
*/
|
||||
public interface StructureModifier
|
||||
{
|
||||
public interface StructureModifier {
|
||||
/**
|
||||
* Codec for (de)serializing structure modifiers inline.
|
||||
* Mods can use this for data generation.
|
||||
*/
|
||||
Codec<StructureModifier> DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.STRUCTURE_MODIFIER_SERIALIZERS.get().getCodec())
|
||||
.dispatch(StructureModifier::codec, Function.identity());
|
||||
Codec<StructureModifier> DIRECT_CODEC = Codec.lazyInitialized(() -> ForgeRegistries.STRUCTURE_MODIFIER_SERIALIZERS.get().getCodec().dispatch(StructureModifier::codec, Function.identity()));
|
||||
|
||||
/**
|
||||
* Codec for referring to structure modifiers by id in other datapack registry files.
|
||||
@@ -66,10 +65,9 @@ public interface StructureModifier
|
||||
/**
|
||||
* @return the codec which serializes and deserializes this structure modifier
|
||||
*/
|
||||
Codec<? extends StructureModifier> codec();
|
||||
MapCodec<? extends StructureModifier> codec();
|
||||
|
||||
enum Phase
|
||||
{
|
||||
enum Phase {
|
||||
/**
|
||||
* Catch-all for anything that needs to run before standard phases.
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user