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:
committed 2024-04-30 11:42:52 -07:00
1 parent e1fa61080a
commit 7b782e5b05
1114 files changed
+24245 -28536

No files matched your search

@@ -8,28 +8,28 @@ package net.minecraftforge.client;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.world.item.component.FireworkExplosion;
import org.jetbrains.annotations.Nullable;
import net.minecraft.client.particle.FireworkParticles;
import net.minecraft.world.item.FireworkRocketItem;
/**
* Keeps track of custom firework shape types, because Particle is client side only this can't be on the Shape itself.
* So sometime during your client initalization call register.
*/
public class FireworkShapeFactoryRegistry {
private static final Map<FireworkRocketItem.Shape, Factory> factories = new HashMap<>();
private static final Map<FireworkExplosion.Shape, Factory> factories = new HashMap<>();
public static interface Factory {
public interface Factory {
void build(FireworkParticles.Starter starter, boolean trail, boolean flicker, int[] colors, int[] fadecolors);
}
public static void register(FireworkRocketItem.Shape shape, Factory factory) {
public static void register(FireworkExplosion.Shape shape, Factory factory) {
factories.put(shape, factory);
}
@Nullable
public static Factory get(FireworkRocketItem.Shape shape) {
public static Factory get(FireworkExplosion.Shape shape) {
return factories.get(shape);
}
}
@@ -6,6 +6,7 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.shaders.FogShape;
@@ -70,6 +71,8 @@ import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.locale.Language;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.ChatType;
@@ -112,12 +115,12 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ClientChatEvent;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.client.event.ClientPauseChangeEvent;
import net.minecraftforge.client.event.ClientPauseEvent;
import net.minecraftforge.client.event.ClientPlayerChangeGameTypeEvent;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.client.event.ComputeFovModifierEvent;
import net.minecraftforge.client.event.CustomizeGuiOverlayEvent;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.client.event.ForgeEventFactoryClient;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.client.event.MovementInputUpdateEvent;
@@ -144,7 +147,6 @@ import net.minecraftforge.client.extensions.common.IClientItemExtensions;
import net.minecraftforge.client.extensions.common.IClientMobEffectExtensions;
import net.minecraftforge.client.gui.ClientTooltipComponentManager;
import net.minecraftforge.client.gui.ModMismatchDisconnectedScreen;
import net.minecraftforge.client.gui.overlay.GuiOverlayManager;
import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.textures.ForgeTextureMetadata;
import net.minecraftforge.client.textures.TextureAtlasSpriteLoaderManager;
@@ -256,7 +258,6 @@ public class ForgeHooksClient {
public static void onClientPauseChangePost(boolean pause) {
MinecraftForge.EVENT_BUS.post(new ClientPauseChangeEvent.Post(pause));
MinecraftForge.EVENT_BUS.post(new ClientPauseEvent(pause));
}
public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EquipmentSlot slot, String type) {
@@ -264,7 +265,9 @@ public class ForgeHooksClient {
return result != null ? result : _default;
}
public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, PoseStack poseStack, MultiBufferSource bufferSource) {
public static boolean onDrawHighlight(LevelRenderer context, Camera camera, HitResult target, float partialTick, Matrix4f ctxPos, MultiBufferSource bufferSource) {
var poseStack = new PoseStack();
poseStack.mulPose(ctxPos);
switch (target.getType()) {
case BLOCK:
if (!(target instanceof BlockHitResult blockTarget)) return false;
@@ -277,7 +280,7 @@ public class ForgeHooksClient {
}
}
public static void dispatchRenderStage(RenderType renderType, LevelRenderer levelRenderer, PoseStack poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) {
public static void dispatchRenderStage(RenderType renderType, LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) {
RenderLevelStageEvent.Stage stage = RenderLevelStageEvent.Stage.fromRenderType(renderType);
if (stage != null)
stage.dispatch(levelRenderer, poseStack, projectionMatrix, renderTick, camera, frustum);
@@ -287,10 +290,6 @@ public class ForgeHooksClient {
return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(hand, poseStack, bufferSource, packedLight, partialTick, interpPitch, swingProgress, equipProgress, stack));
}
public static boolean renderSpecificFirstPersonArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
return MinecraftForge.EVENT_BUS.post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm));
}
public static void onTextureStitchedPost(TextureAtlas map) {
ModLoader.get().postEvent(new TextureStitchEvent.Post(map));
}
@@ -342,12 +341,6 @@ public class ForgeHooksClient {
return fovModifierEvent.getNewFovModifier();
}
public static double getFieldOfView(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) {
ViewportEvent.ComputeFov event = new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov);
MinecraftForge.EVENT_BUS.post(event);
return event.getFOV();
}
/**
* Initialization of Forge Renderers.
*/
@@ -429,12 +422,6 @@ public class ForgeHooksClient {
}
}
public static ViewportEvent.ComputeCameraAngles onCameraSetup(GameRenderer renderer, Camera camera, float partial) {
ViewportEvent.ComputeCameraAngles event = new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static void onModifyBakingResult(Map<ResourceLocation, BakedModel> models, ModelBakery modelBakery) {
ModLoader.get().postEvent(new ModelEvent.ModifyBakingResult(models, modelBakery));
}
@@ -443,11 +430,6 @@ public class ForgeHooksClient {
ModLoader.get().postEvent(new ModelEvent.BakingCompleted(modelManager, Collections.unmodifiableMap(models), modelBakery));
}
public static BakedModel handleCameraTransforms(PoseStack poseStack, BakedModel model, ItemDisplayContext cameraTransformType, boolean applyLeftHandTransform) {
model = model.applyTransform(cameraTransformType, poseStack, applyLeftHandTransform);
return model;
}
@SuppressWarnings("deprecation")
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) {
IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn);
@@ -548,12 +530,6 @@ public class ForgeHooksClient {
return evt;
}
public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) {
ScreenshotEvent event = new ScreenshotEvent(image, screenshotFile);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) {
if (currentGameMode != newGameMode) {
ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode);
@@ -565,34 +541,22 @@ public class ForgeHooksClient {
MinecraftForge.EVENT_BUS.post(new MovementInputUpdateEvent(player, movementInput));
}
public static boolean onScreenKeyPressedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyPressed.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
public static void onScreenKeyPressed(boolean[] state, Screen screen, int keyCode, int scanCode, int modifiers) {
state[0] = ForgeEventFactoryClient.onScreenKeyPressedPre(screen, keyCode, scanCode, modifiers)
|| screen.keyPressed(keyCode, scanCode, modifiers)
|| ForgeEventFactoryClient.onScreenKeyPressedPost(screen, keyCode, scanCode, modifiers);
}
public static boolean onScreenKeyPressedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyPressed.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
public static void onScreenKeyReleased(boolean[] state, Screen screen, int keyCode, int scanCode, int modifiers) {
state[0] = ForgeEventFactoryClient.onScreenKeyReleasedPre(screen, keyCode, scanCode, modifiers)
|| screen.keyReleased(keyCode, scanCode, modifiers)
|| ForgeEventFactoryClient.onScreenKeyReleasedPost(screen, keyCode, scanCode, modifiers);
}
public static boolean onScreenKeyReleasedPre(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyReleased.Pre(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onScreenKeyReleasedPost(Screen guiScreen, int keyCode, int scanCode, int modifiers) {
Event event = new ScreenEvent.KeyReleased.Post(guiScreen, keyCode, scanCode, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static boolean onScreenCharTypedPre(Screen guiScreen, char codePoint, int modifiers) {
Event event = new ScreenEvent.CharacterTyped.Pre(guiScreen, codePoint, modifiers);
return MinecraftForge.EVENT_BUS.post(event);
}
public static void onScreenCharTypedPost(Screen guiScreen, char codePoint, int modifiers) {
Event event = new ScreenEvent.CharacterTyped.Post(guiScreen, codePoint, modifiers);
MinecraftForge.EVENT_BUS.post(event);
public static boolean onScreenCharTyped(Screen screen, char codePoint, int modifiers) {
return ForgeEventFactoryClient.onScreenCharTypedPre(screen, codePoint, modifiers)
|| screen.charTyped(codePoint, modifiers)
|| ForgeEventFactoryClient.onScreenCharTypedPost(screen, codePoint, modifiers);
}
public static void onRecipesUpdated(RecipeManager mgr) {
@@ -604,15 +568,9 @@ public class ForgeHooksClient {
MinecraftForge.EVENT_BUS.post(new InputEvent.Key(key, scanCode, action, modifiers));
}
public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) {
InputEvent.InteractionKeyMappingTriggered event = new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand);
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static boolean isNameplateInRenderDistance(Entity entity, double squareDistance) {
if (entity instanceof LivingEntity) {
final AttributeInstance attribute = ((LivingEntity) entity).getAttribute(ForgeMod.NAMETAG_DISTANCE.get());
if (entity instanceof LivingEntity living) {
var attribute = living.getAttribute(ForgeMod.NAMETAG_DISTANCE.getHolder().get());
if (attribute != null) {
return !(squareDistance > (attribute.getValue() * attribute.getValue()));
}
@@ -620,14 +578,6 @@ public class ForgeHooksClient {
return !(squareDistance > 4096.0f);
}
public static void renderPistonMovedBlocks(BlockPos pos, BlockState state, PoseStack stack, MultiBufferSource bufferSource, Level level, boolean checkSides, int packedOverlay, BlockRenderDispatcher blockRenderer) {
var model = blockRenderer.getBlockModel(state);
for (var renderType : model.getRenderTypes(state, RandomSource.create(state.getSeed(pos)), ModelData.EMPTY)) {
VertexConsumer vertexConsumer = bufferSource.getBuffer(RenderTypeHelper.getMovingBlockRenderType(renderType));
blockRenderer.getModelRenderer().tesselateBlock(level, model, state, pos, stack, vertexConsumer, checkSides, RandomSource.create(), state.getSeed(pos), packedOverlay, ModelData.EMPTY, renderType);
}
}
public static boolean shouldRenderEffect(MobEffectInstance effectInstance) {
return IClientMobEffectExtensions.of(effectInstance).isVisibleInInventory(effectInstance);
}
@@ -757,7 +707,8 @@ public class ForgeHooksClient {
if(relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26) {
//this is not the most proper way to do it,
//but works best here and has the least maintenance overhead
gui.setToolTip(Arrays.stream(tooltip.split("\n")).map(Component::literal).collect(Collectors.toList()));
var lines = Arrays.stream(tooltip.split("\n")).map(Component::literal).toList();
gui.setTooltipForNextRenderPass(Lists.transform(lines, Component::getVisualOrderText));
}
}
@@ -772,18 +723,6 @@ public class ForgeHooksClient {
GameData.revertToFrozen();
}
public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) {
MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.LoggingIn(pc, player, networkManager));
}
public static void firePlayerLogout(@Nullable MultiPlayerGameMode pc, @Nullable LocalPlayer player) {
MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.LoggingOut(pc, player, player != null ? player.connection != null ? player.connection.getConnection() : null : null));
}
public static void firePlayerRespawn(MultiPlayerGameMode pc, LocalPlayer oldPlayer, LocalPlayer newPlayer, Connection networkManager) {
MinecraftForge.EVENT_BUS.post(new ClientPlayerNetworkEvent.Clone(pc, oldPlayer, newPlayer, networkManager));
}
public static void onRegisterParticleProviders(ParticleEngine particleEngine) {
ModLoader.get().postEvent(new RegisterParticleProvidersEvent(particleEngine));
}
@@ -808,14 +747,14 @@ public class ForgeHooksClient {
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
}
private static final ChatTypeDecoration SYSTEM_CHAT_TYPE_DECORATION = new ChatTypeDecoration("forge.chatType.system", List.of(ChatTypeDecoration.Parameter.CONTENT), Style.EMPTY);
private static final ChatType SYSTEM_CHAT_TYPE = new ChatType(SYSTEM_CHAT_TYPE_DECORATION, SYSTEM_CHAT_TYPE_DECORATION);
private static final ChatType.Bound SYSTEM_CHAT_TYPE_BOUND = SYSTEM_CHAT_TYPE.bind(Component.literal("System"));
@Nullable
public static Component onClientSystemChat(Component message, boolean overlay) {
ClientChatReceivedEvent.System event = new ClientChatReceivedEvent.System(SYSTEM_CHAT_TYPE_BOUND, message, overlay);
public static Component onClientSystemChat(Component message, boolean overlay, RegistryAccess registry) {
return message;
/*
var bound = ChatType.bind(ForgeMod.SYSTEM_CHAT_TYPE.getKey(), registry, Component.literal("System"));
var event = new ClientChatReceivedEvent.System(bound, message, overlay);
return MinecraftForge.EVENT_BUS.post(event) ? null : event.getMessage();
*/
}
@NotNull
@@ -1050,7 +989,7 @@ public class ForgeHooksClient {
EntitySpectatorShaderManager.init();
ForgeHooksClient.onRegisterKeyMappings(mc.options);
RecipeBookManager.init();
GuiOverlayManager.init();
//GuiOverlayManager.init();
DimensionSpecialEffectsManager.init();
NamedRenderTypeManager.init();
ColorResolverManager.init();
@@ -1065,4 +1004,12 @@ public class ForgeHooksClient {
mc.setScreen(new ModMismatchDisconnectedScreen(parent, CommonComponents.CONNECT_FAILED, message, mismatch));
return true;
}
public static void onScreenMouseDrag(Screen screen, double mouseX, double mouseY, int mouseButton, double dragX, double dragY) {
if (ForgeEventFactoryClient.onScreenMouseDragPre(screen, mouseX, mouseY, mouseButton, dragX, dragY))
return;
if (screen.mouseDragged(mouseX, mouseY, mouseButton, dragX, dragY))
return;
ForgeEventFactoryClient.onScreenMouseDragPost(screen, mouseX, mouseY, mouseButton, dragX, dragY);
}
}
@@ -28,8 +28,7 @@ import java.util.function.Function;
* <p>
* Provides a recipe category lookup.
*/
public final class RecipeBookManager
{
public final class RecipeBookManager {
// Not using ConcurrentHashMap here because it's slower for lookups, so we only use it during init
private static final Map<RecipeBookCategories, List<RecipeBookCategories>> AGGREGATE_CATEGORIES = new HashMap<>();
private static final Map<RecipeBookType, List<RecipeBookCategories>> TYPE_CATEGORIES = new HashMap<>();
@@ -40,27 +39,23 @@ public final class RecipeBookManager
* Finds the category the specified recipe should display in, or null if none.
*/
@Nullable
public static <T extends Recipe<?>> RecipeBookCategories findCategories(RecipeType<T> type, RecipeHolder<T> recipe)
{
public static <T extends Recipe<?>> RecipeBookCategories findCategories(RecipeType<T> type, RecipeHolder<T> recipe) {
var lookup = RECIPE_CATEGORY_LOOKUPS.get(type);
return lookup != null ? lookup.apply(recipe.value()) : null;
}
@ApiStatus.Internal
public static Map<RecipeBookCategories, List<RecipeBookCategories>> getAggregateCategories()
{
public static Map<RecipeBookCategories, List<RecipeBookCategories>> getAggregateCategories(Map<RecipeBookCategories, List<RecipeBookCategories>> vanilla) {
return AGGREGATE_CATEGORIES_VIEW;
}
@ApiStatus.Internal
public static List<RecipeBookCategories> getCustomCategoriesOrEmpty(RecipeBookType recipeBookType)
{
public static List<RecipeBookCategories> getCustomCategoriesOrEmpty(RecipeBookType recipeBookType) {
return TYPE_CATEGORIES.getOrDefault(recipeBookType, List.of());
}
@ApiStatus.Internal
public static void init()
{
public static void init() {
// The ImmutableMap is the patched out value of AGGREGATE_CATEGORIES
var aggregateCategories = new HashMap<>(ImmutableMap.of(
RecipeBookCategories.CRAFTING_SEARCH, ImmutableList.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE),
@@ -13,26 +13,22 @@ import net.minecraft.client.renderer.RenderType;
* {@code entityFabulous} may support custom render targets and other aspects of the fabulous pipeline, or can otherwise
* be the same as {@code entity}.
*/
public record RenderTypeGroup(RenderType block, RenderType entity, RenderType entityFabulous)
{
public record RenderTypeGroup(RenderType block, RenderType entity, RenderType entityFabulous) {
public static RenderTypeGroup EMPTY = new RenderTypeGroup(null, null, null);
public RenderTypeGroup
{
public RenderTypeGroup {
if ((block == null) != (entity == null) || (block == null) != (entityFabulous == null))
throw new IllegalArgumentException("The render types in a group must either be all null, or all non-null.");
}
public RenderTypeGroup(RenderType block, RenderType entity)
{
public RenderTypeGroup(RenderType block, RenderType entity) {
this(block, entity, entity);
}
/**
* {@return true if this group has render types or not. It either has all, or none}
*/
public boolean isEmpty()
{
public boolean isEmpty() {
// We throw an exception in the constructor if nullability doesn't match, so checking this is enough
return block == null;
}
@@ -21,8 +21,7 @@ import org.jetbrains.annotations.NotNull;
/**
* Provides helper functions replacing those in {@link ItemBlockRenderTypes}.
*/
public final class RenderTypeHelper
{
public final class RenderTypeHelper {
/**
* Provides a {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for the given {@link DefaultVertexFormat#BLOCK} format.
* This should be called for each {@link RenderType} returned by {@link BakedModel#getRenderTypes(BlockState, RandomSource, ModelData)}.
@@ -30,8 +29,7 @@ public final class RenderTypeHelper
* Mimics the behavior of vanilla's {@link ItemBlockRenderTypes#getRenderType(BlockState, boolean)}.
*/
@NotNull
public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull)
{
public static RenderType getEntityRenderType(RenderType chunkRenderType, boolean cull) {
if (chunkRenderType != RenderType.translucent())
return Sheets.cutoutBlockSheet();
return cull || !Minecraft.useShaderTransparency() ? Sheets.translucentCullBlockSheet() : Sheets.translucentItemSheet();
@@ -44,8 +42,7 @@ public final class RenderTypeHelper
* Mimics the behavior of vanilla's {@link ItemBlockRenderTypes#getMovingBlockRenderType(BlockState)}.
*/
@NotNull
public static RenderType getMovingBlockRenderType(RenderType renderType)
{
public static RenderType getMovingBlockRenderType(RenderType renderType) {
if (renderType == RenderType.translucent())
return RenderType.translucentMovingBlock();
return renderType;
@@ -58,10 +55,8 @@ public final class RenderTypeHelper
* but removes the need to query the model again if the item is a {@link BlockItem}.
*/
@NotNull
public static RenderType getFallbackItemRenderType(ItemStack stack, BakedModel model, boolean cull)
{
if (stack.getItem() instanceof BlockItem blockItem)
{
public static RenderType getFallbackItemRenderType(ItemStack stack, BakedModel model, boolean cull) {
if (stack.getItem() instanceof BlockItem blockItem) {
var renderTypes = model.getRenderTypes(blockItem.getBlock().defaultBlockState(), RandomSource.create(42), ModelData.EMPTY);
if (renderTypes.contains(RenderType.translucent()))
return getEntityRenderType(RenderType.translucent(), cull);
@@ -70,7 +65,5 @@ public final class RenderTypeHelper
return cull ? Sheets.translucentCullBlockSheet() : Sheets.translucentItemSheet();
}
private RenderTypeHelper()
{
}
private RenderTypeHelper() {}
}
@@ -1,45 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.event;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.LogicalSide;
/**
* Fired when {@linkplain Minecraft#pause Minecraft.pause} value got updated by
* the {@linkplain Minecraft#runTick(boolean) Minecraft.runTick(...)} on a single-player world
*
* <p>This event is not {@linkplain Cancelable cancellable}, and does not {@linkplain HasResult have a result}.</p>
*
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* @deprecated use {@linkplain ClientPauseChangeEvent.Post ClientPauseChangeEvent.Post} instead
* @see ClientPauseChangeEvent.Pre
* @see ClientPauseChangeEvent.Post
*/
@Deprecated(forRemoval = true, since="1.20.4")
public class ClientPauseEvent extends Event
{
private final boolean paused;
public ClientPauseEvent(boolean isPaused)
{
this.paused = isPaused;
}
/**
* {@return game is paused}
*/
public boolean isPaused()
{
return paused;
}
}
@@ -26,15 +26,13 @@ import org.jetbrains.annotations.Nullable;
* @see LoggingOut
* @see Clone
**/
public abstract class ClientPlayerNetworkEvent extends Event
{
public abstract class ClientPlayerNetworkEvent extends Event {
private final MultiPlayerGameMode multiPlayerGameMode;
private final LocalPlayer player;
private final Connection connection;
@ApiStatus.Internal
protected ClientPlayerNetworkEvent(final MultiPlayerGameMode multiPlayerGameMode, final LocalPlayer player, final Connection connection)
{
protected ClientPlayerNetworkEvent(final MultiPlayerGameMode multiPlayerGameMode, final LocalPlayer player, final Connection connection) {
this.multiPlayerGameMode = multiPlayerGameMode;
this.player = player;
this.connection = connection;
@@ -43,24 +41,21 @@ public abstract class ClientPlayerNetworkEvent extends Event
/**
* {@return the multiplayer game mode controller for the player}
*/
public MultiPlayerGameMode getMultiPlayerGameMode()
{
public MultiPlayerGameMode getMultiPlayerGameMode() {
return multiPlayerGameMode;
}
/**
* {@return the player instance}
*/
public LocalPlayer getPlayer()
{
public LocalPlayer getPlayer() {
return player;
}
/**
* {@return the network connection for the player}
*/
public Connection getConnection()
{
public Connection getConnection() {
return connection;
}
@@ -72,11 +67,9 @@ public abstract class ClientPlayerNetworkEvent extends Event
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class LoggingIn extends ClientPlayerNetworkEvent
{
public static class LoggingIn extends ClientPlayerNetworkEvent {
@ApiStatus.Internal
public LoggingIn(final MultiPlayerGameMode controller, final LocalPlayer player, final Connection networkManager)
{
public LoggingIn(final MultiPlayerGameMode controller, final LocalPlayer player, final Connection networkManager) {
super(controller, player, networkManager);
}
}
@@ -91,11 +84,9 @@ public abstract class ClientPlayerNetworkEvent extends Event
*/
@SuppressWarnings("NullableProblems")
// Shush IntelliJ, we override non-nullables as nullables in this specific event; see later comment
public static class LoggingOut extends ClientPlayerNetworkEvent
{
public static class LoggingOut extends ClientPlayerNetworkEvent {
@ApiStatus.Internal
public LoggingOut(@Nullable final MultiPlayerGameMode controller, @Nullable final LocalPlayer player, @Nullable final Connection networkManager)
{
public LoggingOut(@Nullable final MultiPlayerGameMode controller, @Nullable final LocalPlayer player, @Nullable final Connection networkManager) {
//noinspection ConstantConditions we know these are nullable, but we don't want to annotate the super as nullable since this is the only event with nullables
super(controller, player, networkManager);
}
@@ -107,8 +98,7 @@ public abstract class ClientPlayerNetworkEvent extends Event
*/
@Nullable
@Override
public MultiPlayerGameMode getMultiPlayerGameMode()
{
public MultiPlayerGameMode getMultiPlayerGameMode() {
return super.getMultiPlayerGameMode();
}
@@ -119,8 +109,7 @@ public abstract class ClientPlayerNetworkEvent extends Event
*/
@Nullable
@Override
public LocalPlayer getPlayer()
{
public LocalPlayer getPlayer() {
return super.getPlayer();
}
@@ -131,8 +120,7 @@ public abstract class ClientPlayerNetworkEvent extends Event
*/
@Nullable
@Override
public Connection getConnection()
{
public Connection getConnection() {
return super.getConnection();
}
}
@@ -145,13 +133,11 @@ public abstract class ClientPlayerNetworkEvent extends Event
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class Clone extends ClientPlayerNetworkEvent
{
public static class Clone extends ClientPlayerNetworkEvent {
private final LocalPlayer oldPlayer;
@ApiStatus.Internal
public Clone(final MultiPlayerGameMode pc, final LocalPlayer oldPlayer, final LocalPlayer newPlayer, final Connection networkManager)
{
public Clone(final MultiPlayerGameMode pc, final LocalPlayer oldPlayer, final LocalPlayer newPlayer, final Connection networkManager) {
super(pc, newPlayer, networkManager);
this.oldPlayer = oldPlayer;
}
@@ -159,16 +145,14 @@ public abstract class ClientPlayerNetworkEvent extends Event
/**
* {@return the previous player instance}
*/
public LocalPlayer getOldPlayer()
{
public LocalPlayer getOldPlayer() {
return oldPlayer;
}
/**
* {@return the newly created player instance}
*/
public LocalPlayer getNewPlayer()
{
public LocalPlayer getNewPlayer() {
return super.getPlayer();
}
@@ -178,8 +162,7 @@ public abstract class ClientPlayerNetworkEvent extends Event
* @see #getNewPlayer()
*/
@Override
public LocalPlayer getPlayer()
{
public LocalPlayer getPlayer() {
return super.getPlayer();
}
}
@@ -23,21 +23,18 @@ import org.jetbrains.annotations.ApiStatus;
* @see Render.Foreground
* @see Render.Background
*/
public abstract class ContainerScreenEvent extends Event
{
public abstract class ContainerScreenEvent extends Event {
private final AbstractContainerScreen<?> containerScreen;
@ApiStatus.Internal
protected ContainerScreenEvent(AbstractContainerScreen<?> containerScreen)
{
protected ContainerScreenEvent(AbstractContainerScreen<?> containerScreen) {
this.containerScreen = containerScreen;
}
/**
* {@return the container screen}
*/
public AbstractContainerScreen<?> getContainerScreen()
{
public AbstractContainerScreen<?> getContainerScreen() {
return containerScreen;
}
@@ -51,15 +48,13 @@ public abstract class ContainerScreenEvent extends Event
* @see Foreground
* @see Background
*/
public static abstract class Render extends ContainerScreenEvent
{
public static abstract class Render extends ContainerScreenEvent {
private final GuiGraphics guiGraphics;
private final int mouseX;
private final int mouseY;
@ApiStatus.Internal
protected Render(AbstractContainerScreen<?> guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY)
{
protected Render(AbstractContainerScreen<?> guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) {
super(guiContainer);
this.guiGraphics = guiGraphics;
this.mouseX = mouseX;
@@ -69,24 +64,21 @@ public abstract class ContainerScreenEvent extends Event
/**
* {@return the gui graphics used for rendering}
*/
public GuiGraphics getGuiGraphics()
{
public GuiGraphics getGuiGraphics() {
return guiGraphics;
}
/**
* {@return the X coordinate of the mouse pointer}
*/
public int getMouseX()
{
public int getMouseX() {
return mouseX;
}
/**
* {@return the Y coordinate of the mouse pointer}
*/
public int getMouseY()
{
public int getMouseY() {
return mouseY;
}
@@ -102,11 +94,9 @@ public abstract class ContainerScreenEvent extends Event
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class Foreground extends Render
{
public static class Foreground extends Render {
@ApiStatus.Internal
public Foreground(AbstractContainerScreen<?> guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY)
{
public Foreground(AbstractContainerScreen<?> guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) {
super(guiContainer, guiGraphics, mouseX, mouseY);
}
}
@@ -120,11 +110,9 @@ public abstract class ContainerScreenEvent extends Event
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class Background extends Render
{
public static class Background extends Render {
@ApiStatus.Internal
public Background(AbstractContainerScreen<?> guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY)
{
public Background(AbstractContainerScreen<?> guiContainer, GuiGraphics guiGraphics, int mouseX, int mouseY) {
super(guiContainer, guiGraphics, mouseX, mouseY);
}
}
@@ -5,28 +5,59 @@
package net.minecraftforge.client.event;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.jetbrains.annotations.Nullable;
import com.mojang.blaze3d.audio.Channel;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.datafixers.util.Pair;
import net.minecraft.client.Camera;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.MouseHandler;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.model.EntityModel;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererProvider.Context;
import net.minecraft.client.renderer.entity.ItemFrameRenderer;
import net.minecraft.client.renderer.entity.LivingEntityRenderer;
import net.minecraft.client.renderer.entity.player.PlayerRenderer;
import net.minecraft.client.resources.PlayerSkin.Model;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.HumanoidArm;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.client.event.sound.PlaySoundSourceEvent;
import net.minecraftforge.client.event.sound.PlayStreamingSourceEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.ModLoader;
public class ForgeEventFactoryClient {
public final class ForgeEventFactoryClient {
private ForgeEventFactoryClient() {}
private static boolean post(Event e) {
return MinecraftForge.EVENT_BUS.post(e);
}
@@ -36,27 +67,33 @@ public class ForgeEventFactoryClient {
return e;
}
public static void gatherLayers(Map<EntityType<?>, EntityRenderer<?>> renderers, Map<Model, EntityRenderer<? extends Player>> playerRenderers, Context context) {
public static void onGatherLayers(Map<EntityType<?>, EntityRenderer<?>> renderers, Map<Model, EntityRenderer<? extends Player>> playerRenderers, Context context) {
// TODO: Why is this a ModLoader event...
ModLoader.get().postEvent(new EntityRenderersEvent.AddLayers(renderers, playerRenderers, context));
}
public static boolean onScreenMouseReleasedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
return post(new ScreenEvent.MouseButtonReleased.Pre(guiScreen, mouseX, mouseY, button));
public static void onRegisterShaders(ResourceProvider resourceProvider, List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList) {
// TODO: Why i this a ModLoader event...
ModLoader.get().postEvent(new RegisterShadersEvent(resourceProvider, shaderList));
}
public static boolean onScreenMouseReleasedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
var result = fire(new ScreenEvent.MouseButtonReleased.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
public static void onScreenMouseReleased(boolean[] state, Screen screen, double mouseX, double mouseY, int button) {
state[0] = post(new ScreenEvent.MouseButtonReleased.Pre(screen, mouseX, mouseY, button));
if (!state[0]) {
state[0] = screen.mouseReleased(mouseX, mouseY, button);
var result = fire(new ScreenEvent.MouseButtonReleased.Post(screen, mouseX, mouseY, button, state[0])).getResult();
state[0] = result == Event.Result.DEFAULT ? state[0] : result == Event.Result.ALLOW;
}
}
public static boolean onScreenMouseClickedPre(Screen guiScreen, double mouseX, double mouseY, int button) {
return post(new ScreenEvent.MouseButtonPressed.Pre(guiScreen, mouseX, mouseY, button));
}
public static void onScreenMouseClicked(boolean[] state, Screen screen, double mouseX, double mouseY, int button) {
state[0] = post(new ScreenEvent.MouseButtonPressed.Pre(screen, mouseX, mouseY, button));
if (!state[0]) {
state[0] = screen.mouseClicked(mouseX, mouseY, button);
}
public static boolean onScreenMouseClickedPost(Screen guiScreen, double mouseX, double mouseY, int button, boolean handled) {
var result = fire(new ScreenEvent.MouseButtonPressed.Post(guiScreen, mouseX, mouseY, button, handled)).getResult();
return result == Event.Result.DEFAULT ? handled : result == Event.Result.ALLOW;
var result = fire(new ScreenEvent.MouseButtonPressed.Post(screen, mouseX, mouseY, button, state[0])).getResult();
state[0] = result == Event.Result.DEFAULT ? state[0] : result == Event.Result.ALLOW;
}
public static boolean onMouseButtonPre(int button, int action, int mods) {
@@ -105,4 +142,96 @@ public class ForgeEventFactoryClient {
public static void onPlayStreamingSource(SoundEngine engine, SoundInstance sound, Channel channel) {
post(new PlayStreamingSourceEvent(engine, sound, channel));
}
public static ScreenshotEvent onScreenshot(NativeImage image, File screenshotFile) {
return fire(new ScreenshotEvent(image, screenshotFile));
}
public static boolean onScreenKeyPressedPre(Screen screen, int keyCode, int scanCode, int modifiers) {
return post(new ScreenEvent.KeyPressed.Pre(screen, keyCode, scanCode, modifiers));
}
public static boolean onScreenKeyPressedPost(Screen screen, int keyCode, int scanCode, int modifiers) {
return post(new ScreenEvent.KeyPressed.Post(screen, keyCode, scanCode, modifiers));
}
public static boolean onScreenKeyReleasedPre(Screen screen, int keyCode, int scanCode, int modifiers) {
return post(new ScreenEvent.KeyReleased.Pre(screen, keyCode, scanCode, modifiers));
}
public static boolean onScreenKeyReleasedPost(Screen screen, int keyCode, int scanCode, int modifiers) {
return post(new ScreenEvent.KeyReleased.Post(screen, keyCode, scanCode, modifiers));
}
public static boolean onScreenCharTypedPre(Screen screen, char codePoint, int modifiers) {
return post(new ScreenEvent.CharacterTyped.Pre(screen, codePoint, modifiers));
}
public static boolean onScreenCharTypedPost(Screen screen, char codePoint, int modifiers) {
return post(new ScreenEvent.CharacterTyped.Post(screen, codePoint, modifiers));
}
public static InputEvent.InteractionKeyMappingTriggered onClickInput(int button, KeyMapping keyBinding, InteractionHand hand) {
return fire(new InputEvent.InteractionKeyMappingTriggered(button, keyBinding, hand));
}
public static void onContainerRenderBackground(AbstractContainerScreen<?> screen, GuiGraphics graphics, int mouseX, int mouseY) {
post(new ContainerScreenEvent.Render.Background(screen, graphics, mouseX, mouseY));
}
public static void onContainerRenderForeground(AbstractContainerScreen<?> screen, GuiGraphics graphics, int mouseX, int mouseY) {
post(new ContainerScreenEvent.Render.Foreground(screen, graphics, mouseX, mouseY));
}
public static void firePlayerLogin(MultiPlayerGameMode pc, LocalPlayer player, Connection networkManager) {
post(new ClientPlayerNetworkEvent.LoggingIn(pc, player, networkManager));
}
public static void firePlayerLogout(@Nullable MultiPlayerGameMode pc, @Nullable LocalPlayer player) {
post(new ClientPlayerNetworkEvent.LoggingOut(pc, player, player != null ? player.connection != null ? player.connection.getConnection() : null : null));
}
public static void firePlayerRespawn(MultiPlayerGameMode pc, LocalPlayer oldPlayer, LocalPlayer newPlayer, Connection networkManager) {
post(new ClientPlayerNetworkEvent.Clone(pc, oldPlayer, newPlayer, networkManager));
}
public static ViewportEvent.ComputeFov fireComputeFov(GameRenderer renderer, Camera camera, double partialTick, double fov, boolean usedConfiguredFov) {
return fire(new ViewportEvent.ComputeFov(renderer, camera, partialTick, fov, usedConfiguredFov));
}
public static ViewportEvent.ComputeCameraAngles fireComputeCameraAngles(GameRenderer renderer, Camera camera, float partial) {
return fire(new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0));
}
public static <T extends LivingEntity, M extends EntityModel<T>> boolean onRenderLivingPre(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
return post(new RenderLivingEvent.Pre<T, M>(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight));
}
public static <T extends LivingEntity, M extends EntityModel<T>> boolean onRenderLivingPost(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
return post(new RenderLivingEvent.Post<T, M>(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight));
}
public static boolean onRenderPlayerPre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
return post(new RenderPlayerEvent.Pre(player, renderer, partialTick, poseStack, multiBufferSource, packedLight));
}
public static boolean onRenderPlayerPost(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
return post(new RenderPlayerEvent.Post(player, renderer, partialTick, poseStack, multiBufferSource, packedLight));
}
public static boolean onRenderArm(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
return post(new RenderArmEvent(poseStack, multiBufferSource, packedLight, player, arm));
}
public static boolean onRenderItemInFrame(ItemFrame itemFrame, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
return post(new RenderItemInFrameEvent(itemFrame, renderItemFrame, poseStack, multiBufferSource, packedLight));
}
public static RenderNameTagEvent fireRenderNameTagEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) {
return fire(new RenderNameTagEvent(entity, content, entityRenderer, poseStack, multiBufferSource, packedLight, partialTick));
}
public static void onRenderScreenBackground(Screen screen, GuiGraphics guiGraphics) {
fire(new ScreenEvent.BackgroundRendered(screen, guiGraphics));
}
}
@@ -295,6 +295,7 @@ public abstract class InputEvent extends Event {
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
// TODO: Change the 'button' to sub events. - Lex 0422202
@Cancelable
public static class InteractionKeyMappingTriggered extends InputEvent {
private final int button;
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.event;
import com.google.common.base.Preconditions;
@@ -29,7 +30,7 @@ import java.util.Map;
*
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
* /
public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
{
private final Map<ResourceLocation, IGuiOverlay> overlays;
@@ -47,7 +48,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
*
* @param id A unique resource id for this overlay
* @param overlay The overlay
*/
* /
public void registerBelowAll(@NotNull String id, @NotNull IGuiOverlay overlay)
{
register(Ordering.BEFORE, null, id, overlay);
@@ -60,7 +61,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
* {@link VanillaGuiOverlay vanilla overlay}. Do not use other mods' overlays.
* @param id A unique resource id for this overlay
* @param overlay The overlay
*/
* /
public void registerBelow(@NotNull ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay)
{
register(Ordering.BEFORE, other, id, overlay);
@@ -73,7 +74,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
* {@link VanillaGuiOverlay vanilla overlay}. Do not use other mods' overlays.
* @param id A unique resource id for this overlay
* @param overlay The overlay
*/
* /
public void registerAbove(@NotNull ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay)
{
register(Ordering.AFTER, other, id, overlay);
@@ -84,7 +85,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
*
* @param id A unique resource id for this overlay
* @param overlay The overlay
*/
* /
public void registerAboveAll(@NotNull String id, @NotNull IGuiOverlay overlay)
{
register(Ordering.AFTER, null, id, overlay);
@@ -116,3 +117,4 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
BEFORE, AFTER
}
}
*/
@@ -7,7 +7,6 @@ package net.minecraftforge.client.event;
import com.mojang.datafixers.util.Pair;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceProvider;
import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
@@ -28,14 +27,12 @@ import java.util.function.Consumer;
* <p>This event is fired on the {@linkplain FMLJavaModLoadingContext#getModEventBus() mod-specific event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public class RegisterShadersEvent extends Event implements IModBusEvent
{
public class RegisterShadersEvent extends Event implements IModBusEvent {
private final ResourceProvider resourceProvider;
private final List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList;
@ApiStatus.Internal
public RegisterShadersEvent(ResourceProvider resourceProvider, List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList)
{
public RegisterShadersEvent(ResourceProvider resourceProvider, List<Pair<ShaderInstance, Consumer<ShaderInstance>>> shaderList) {
this.resourceProvider = resourceProvider;
this.shaderList = shaderList;
}
@@ -43,8 +40,7 @@ public class RegisterShadersEvent extends Event implements IModBusEvent
/**
* {@return the client-side resource provider}
*/
public ResourceProvider getResourceProvider()
{
public ResourceProvider getResourceProvider() {
return resourceProvider;
}
@@ -60,8 +56,7 @@ public class RegisterShadersEvent extends Event implements IModBusEvent
* @param shaderInstance a shader
* @param onLoaded a callback for when the shader is loaded
*/
public void registerShader(ShaderInstance shaderInstance, Consumer<ShaderInstance> onLoaded)
{
public void registerShader(ShaderInstance shaderInstance, Consumer<ShaderInstance> onLoaded) {
shaderList.add(Pair.of(shaderInstance, onLoaded));
}
}
@@ -28,8 +28,7 @@ import org.jetbrains.annotations.ApiStatus;
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
@Cancelable
public class RenderArmEvent extends Event
{
public class RenderArmEvent extends Event {
private final PoseStack poseStack;
private final MultiBufferSource multiBufferSource;
private final int packedLight;
@@ -37,8 +36,7 @@ public class RenderArmEvent extends Event
private final HumanoidArm arm;
@ApiStatus.Internal
public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm)
{
public RenderArmEvent(PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, AbstractClientPlayer player, HumanoidArm arm) {
this.poseStack = poseStack;
this.multiBufferSource = multiBufferSource;
this.packedLight = packedLight;
@@ -49,24 +47,21 @@ public class RenderArmEvent extends Event
/**
* {@return the arm being rendered}
*/
public HumanoidArm getArm()
{
public HumanoidArm getArm() {
return arm;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack()
{
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource()
{
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
@@ -75,8 +70,7 @@ public class RenderArmEvent extends Event
*
* @see LightTexture
*/
public int getPackedLight()
{
public int getPackedLight() {
return packedLight;
}
@@ -84,8 +78,7 @@ public class RenderArmEvent extends Event
* {@return the client player that is having their arm rendered} In general, this will be the same as
* {@link net.minecraft.client.Minecraft#player}.
*/
public AbstractClientPlayer getPlayer()
{
public AbstractClientPlayer getPlayer() {
return player;
}
}
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.event;
import com.mojang.blaze3d.platform.Window;
@@ -12,14 +13,13 @@ import net.minecraftforge.eventbus.api.Cancelable;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.LogicalSide;
import org.jetbrains.annotations.ApiStatus;
/**
* Fired when the HUD is rendered to the screen.
* See the two subclasses for listening to the two possible phases.
*
* @see Pre
* @see Post
*/
* /
public abstract class RenderGuiEvent extends Event
{
private final Window window;
@@ -60,7 +60,7 @@ public abstract class RenderGuiEvent extends Event
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* @see Post
*/
* /
@Cancelable
public static class Pre extends RenderGuiEvent
{
@@ -78,7 +78,7 @@ public abstract class RenderGuiEvent extends Event
*
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
* /
public static class Post extends RenderGuiEvent
{
@ApiStatus.Internal
@@ -88,3 +88,4 @@ public abstract class RenderGuiEvent extends Event
}
}
}
*/
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.event;
import com.mojang.blaze3d.platform.Window;
@@ -22,7 +23,7 @@ import org.jetbrains.annotations.ApiStatus;
*
* @see Pre
* @see Post
*/
* /
public abstract class RenderGuiOverlayEvent extends Event
{
private final Window window;
@@ -70,7 +71,7 @@ public abstract class RenderGuiOverlayEvent extends Event
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*
* @see Post
*/
* /
@Cancelable
public static class Pre extends RenderGuiOverlayEvent
{
@@ -88,7 +89,7 @@ public abstract class RenderGuiOverlayEvent extends Event
*
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
* /
public static class Post extends RenderGuiOverlayEvent
{
@ApiStatus.Internal
@@ -98,3 +99,4 @@ public abstract class RenderGuiOverlayEvent extends Event
}
}
}
*/
@@ -30,8 +30,7 @@ import org.jetbrains.annotations.ApiStatus;
* @see ItemFrameRenderer
*/
@Cancelable
public class RenderItemInFrameEvent extends Event
{
public class RenderItemInFrameEvent extends Event {
private final ItemStack itemStack;
private final ItemFrame itemFrameEntity;
private final ItemFrameRenderer<?> renderer;
@@ -40,9 +39,7 @@ public class RenderItemInFrameEvent extends Event
private final int packedLight;
@ApiStatus.Internal
public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack,
MultiBufferSource multiBufferSource, int packedLight)
{
public RenderItemInFrameEvent(ItemFrame itemFrame, ItemFrameRenderer<?> renderItemFrame, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
itemStack = itemFrame.getItem();
itemFrameEntity = itemFrame;
renderer = renderItemFrame;
@@ -54,40 +51,35 @@ public class RenderItemInFrameEvent extends Event
/**
* {@return the item stack being rendered}
*/
public ItemStack getItemStack()
{
public ItemStack getItemStack() {
return itemStack;
}
/**
* {@return the item frame entity}
*/
public ItemFrame getItemFrameEntity()
{
public ItemFrame getItemFrameEntity() {
return itemFrameEntity;
}
/**
* {@return the renderer for the item frame entity}
*/
public ItemFrameRenderer<?> getRenderer()
{
public ItemFrameRenderer<?> getRenderer() {
return renderer;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack()
{
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource()
{
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
@@ -96,8 +88,7 @@ public class RenderItemInFrameEvent extends Event
*
* @see LightTexture
*/
public int getPackedLight()
{
public int getPackedLight() {
return packedLight;
}
}
@@ -43,14 +43,14 @@ import org.joml.Matrix4f;
public class RenderLevelStageEvent extends Event {
private final Stage stage;
private final LevelRenderer levelRenderer;
private final PoseStack poseStack;
private final Matrix4f poseStack;
private final Matrix4f projectionMatrix;
private final int renderTick;
private final float partialTick;
private final Camera camera;
private final Frustum frustum;
public RenderLevelStageEvent(Stage stage, LevelRenderer levelRenderer, PoseStack poseStack, Matrix4f projectionMatrix, int renderTick, float partialTick, Camera camera, Frustum frustum) {
public RenderLevelStageEvent(Stage stage, LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, float partialTick, Camera camera, Frustum frustum) {
this.stage = stage;
this.levelRenderer = levelRenderer;
this.poseStack = poseStack;
@@ -79,7 +79,7 @@ public class RenderLevelStageEvent extends Event {
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack() {
public Matrix4f getPoseStack() {
return poseStack;
}
@@ -235,7 +235,7 @@ public class RenderLevelStageEvent extends Event {
/** Internal just to make our patch smaller, it just fires the event. If you have good reason for this to be external, ask. */
@ApiStatus.Internal
public void dispatch(LevelRenderer levelRenderer, PoseStack poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) {
public void dispatch(LevelRenderer levelRenderer, Matrix4f poseStack, Matrix4f projectionMatrix, int renderTick, Camera camera, Frustum frustum) {
var mc = Minecraft.getInstance();
var profiler = mc.getProfiler();
profiler.push(this.toString());
@@ -31,8 +31,7 @@ import org.jetbrains.annotations.ApiStatus;
* @see RenderPlayerEvent
* @see LivingEntityRenderer
*/
public abstract class RenderLivingEvent<T extends LivingEntity, M extends EntityModel<T>> extends Event
{
public abstract class RenderLivingEvent<T extends LivingEntity, M extends EntityModel<T>> extends Event {
private final LivingEntity entity;
private final LivingEntityRenderer<T, M> renderer;
private final float partialTick;
@@ -41,9 +40,7 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
private final int packedLight;
@ApiStatus.Internal
protected RenderLivingEvent(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack,
MultiBufferSource multiBufferSource, int packedLight)
{
protected RenderLivingEvent(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
this.entity = entity;
this.renderer = renderer;
this.partialTick = partialTick;
@@ -55,40 +52,35 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
/**
* @return the living entity being rendered
*/
public LivingEntity getEntity()
{
public LivingEntity getEntity() {
return entity;
}
/**
* @return the renderer for the living entity
*/
public LivingEntityRenderer<T, M> getRenderer()
{
public LivingEntityRenderer<T, M> getRenderer() {
return renderer;
}
/**
* {@return the partial tick}
*/
public float getPartialTick()
{
public float getPartialTick() {
return partialTick;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack()
{
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource()
{
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
@@ -97,8 +89,7 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
*
* @see LightTexture
*/
public int getPackedLight()
{
public int getPackedLight() {
return packedLight;
}
@@ -117,11 +108,9 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
* @param <M> the model for the living entity
*/
@Cancelable
public static class Pre<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M>
{
public static class Pre<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M> {
@ApiStatus.Internal
public Pre(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight)
{
public Pre(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
super(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight);
}
}
@@ -137,11 +126,9 @@ public abstract class RenderLivingEvent<T extends LivingEntity, M extends Entity
* @param <T> the living entity that was rendered
* @param <M> the model for the living entity
*/
public static class Post<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M>
{
public static class Post<T extends LivingEntity, M extends EntityModel<T>> extends RenderLivingEvent<T, M> {
@ApiStatus.Internal
public Post(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight)
{
public Post(LivingEntity entity, LivingEntityRenderer<T, M> renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
super(entity, renderer, partialTick, poseStack, multiBufferSource, packedLight);
}
}
@@ -33,8 +33,7 @@ import org.jetbrains.annotations.ApiStatus;
* @see EntityRenderer
*/
@Event.HasResult
public class RenderNameTagEvent extends EntityEvent
{
public class RenderNameTagEvent extends EntityEvent {
private Component nameplateContent;
private final Component originalContent;
private final EntityRenderer<?> entityRenderer;
@@ -44,8 +43,7 @@ public class RenderNameTagEvent extends EntityEvent
private final float partialTick;
@ApiStatus.Internal
public RenderNameTagEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick)
{
public RenderNameTagEvent(Entity entity, Component content, EntityRenderer<?> entityRenderer, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight, float partialTick) {
super(entity);
this.originalContent = content;
this.setContent(this.originalContent);
@@ -61,48 +59,42 @@ public class RenderNameTagEvent extends EntityEvent
*
* @param contents the new text
*/
public void setContent(Component contents)
{
public void setContent(Component contents) {
this.nameplateContent = contents;
}
/**
* {@return the text on the nameplate that will be rendered, if the event is not {@link Result#DENY DENIED}}
*/
public Component getContent()
{
public Component getContent() {
return this.nameplateContent;
}
/**
* {@return the original text on the nameplate}
*/
public Component getOriginalContent()
{
public Component getOriginalContent() {
return this.originalContent;
}
/**
* {@return the entity renderer rendering the nameplate}
*/
public EntityRenderer<?> getEntityRenderer()
{
public EntityRenderer<?> getEntityRenderer() {
return this.entityRenderer;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack()
{
public PoseStack getPoseStack() {
return this.poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource()
{
public MultiBufferSource getMultiBufferSource() {
return this.multiBufferSource;
}
@@ -111,16 +103,14 @@ public class RenderNameTagEvent extends EntityEvent
*
* @see net.minecraft.client.renderer.LightTexture
*/
public int getPackedLight()
{
public int getPackedLight() {
return this.packedLight;
}
/**
* {@return the partial tick}
*/
public float getPartialTick()
{
public float getPartialTick() {
return this.partialTick;
}
}
@@ -24,8 +24,7 @@ import org.jetbrains.annotations.ApiStatus;
* @see RenderPlayerEvent.Post
* @see PlayerRenderer
*/
public abstract class RenderPlayerEvent extends PlayerEvent
{
public abstract class RenderPlayerEvent extends PlayerEvent {
private final PlayerRenderer renderer;
private final float partialTick;
private final PoseStack poseStack;
@@ -33,8 +32,7 @@ public abstract class RenderPlayerEvent extends PlayerEvent
private final int packedLight;
@ApiStatus.Internal
protected RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight)
{
protected RenderPlayerEvent(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
super(player);
this.renderer = renderer;
this.partialTick = partialTick;
@@ -46,32 +44,28 @@ public abstract class RenderPlayerEvent extends PlayerEvent
/**
* {@return the player entity renderer}
*/
public PlayerRenderer getRenderer()
{
public PlayerRenderer getRenderer() {
return renderer;
}
/**
* {@return the partial tick}
*/
public float getPartialTick()
{
public float getPartialTick() {
return partialTick;
}
/**
* {@return the pose stack used for rendering}
*/
public PoseStack getPoseStack()
{
public PoseStack getPoseStack() {
return poseStack;
}
/**
* {@return the source of rendering buffers}
*/
public MultiBufferSource getMultiBufferSource()
{
public MultiBufferSource getMultiBufferSource() {
return multiBufferSource;
}
@@ -80,8 +74,7 @@ public abstract class RenderPlayerEvent extends PlayerEvent
*
* @see LightTexture
*/
public int getPackedLight()
{
public int getPackedLight() {
return packedLight;
}
@@ -97,11 +90,9 @@ public abstract class RenderPlayerEvent extends PlayerEvent
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
@Cancelable
public static class Pre extends RenderPlayerEvent
{
public static class Pre extends RenderPlayerEvent {
@ApiStatus.Internal
public Pre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight)
{
public Pre(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
super(player, renderer, partialTick, poseStack, multiBufferSource, packedLight);
}
}
@@ -114,11 +105,9 @@ public abstract class RenderPlayerEvent extends PlayerEvent
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class Post extends RenderPlayerEvent
{
public static class Post extends RenderPlayerEvent {
@ApiStatus.Internal
public Post(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight)
{
public Post(Player player, PlayerRenderer renderer, float partialTick, PoseStack poseStack, MultiBufferSource multiBufferSource, int packedLight) {
super(player, renderer, partialTick, poseStack, multiBufferSource, packedLight);
}
}
@@ -30,15 +30,13 @@ import org.jetbrains.annotations.ApiStatus;
* @see ComputeCameraAngles
* @see ComputeFov
*/
public abstract class ViewportEvent extends Event
{
public abstract class ViewportEvent extends Event {
private final GameRenderer renderer;
private final Camera camera;
private final double partialTick;
@ApiStatus.Internal
public ViewportEvent(GameRenderer renderer, Camera camera, double partialTick)
{
public ViewportEvent(GameRenderer renderer, Camera camera, double partialTick) {
this.renderer = renderer;
this.camera = camera;
this.partialTick = partialTick;
@@ -47,24 +45,21 @@ public abstract class ViewportEvent extends Event
/**
* {@return the game renderer}
*/
public GameRenderer getRenderer()
{
public GameRenderer getRenderer() {
return renderer;
}
/**
* {@return the camera information}
*/
public Camera getCamera()
{
public Camera getCamera() {
return camera;
}
/**
* {@return the partial tick}
*/
public double getPartialTick()
{
public double getPartialTick() {
return partialTick;
}
@@ -78,8 +73,7 @@ public abstract class ViewportEvent extends Event
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
@Cancelable
public static class RenderFog extends ViewportEvent
{
public static class RenderFog extends ViewportEvent {
private final FogMode mode;
private final FogType type;
private float farPlaneDistance;
@@ -87,8 +81,7 @@ public abstract class ViewportEvent extends Event
private FogShape fogShape;
@ApiStatus.Internal
public RenderFog(FogMode mode, FogType type, Camera camera, float partialTicks, float nearPlaneDistance, float farPlaneDistance, FogShape fogShape)
{
public RenderFog(FogMode mode, FogType type, Camera camera, float partialTicks, float nearPlaneDistance, float farPlaneDistance, FogShape fogShape) {
super(Minecraft.getInstance().gameRenderer, camera, partialTicks);
this.mode = mode;
this.type = type;
@@ -100,40 +93,35 @@ public abstract class ViewportEvent extends Event
/**
* {@return the mode of fog being rendered}
*/
public FogMode getMode()
{
public FogMode getMode() {
return mode;
}
/**
* {@return the type of fog being rendered}
*/
public FogType getType()
{
public FogType getType() {
return type;
}
/**
* {@return the distance to the far plane where the fog ends}
*/
public float getFarPlaneDistance()
{
public float getFarPlaneDistance() {
return farPlaneDistance;
}
/**
* {@return the distance to the near plane where the fog starts}
*/
public float getNearPlaneDistance()
{
public float getNearPlaneDistance() {
return nearPlaneDistance;
}
/**
* {@return the shape of the fog being rendered}
*/
public FogShape getFogShape()
{
public FogShape getFogShape() {
return fogShape;
}
@@ -143,8 +131,7 @@ public abstract class ViewportEvent extends Event
* @param distance the new distance to the far place
* @see #scaleFarPlaneDistance(float)
*/
public void setFarPlaneDistance(float distance)
{
public void setFarPlaneDistance(float distance) {
farPlaneDistance = distance;
}
@@ -154,8 +141,7 @@ public abstract class ViewportEvent extends Event
* @param distance the new distance to the near plane
* @see #scaleNearPlaneDistance(float)
*/
public void setNearPlaneDistance(float distance)
{
public void setNearPlaneDistance(float distance) {
nearPlaneDistance = distance;
}
@@ -164,8 +150,7 @@ public abstract class ViewportEvent extends Event
*
* @param shape the new shape of the fog
*/
public void setFogShape(FogShape shape)
{
public void setFogShape(FogShape shape) {
fogShape = shape;
}
@@ -174,8 +159,7 @@ public abstract class ViewportEvent extends Event
*
* @param factor the factor to scale the far plane distance by
*/
public void scaleFarPlaneDistance(float factor)
{
public void scaleFarPlaneDistance(float factor) {
farPlaneDistance *= factor;
}
@@ -184,8 +168,7 @@ public abstract class ViewportEvent extends Event
*
* @param factor the factor to scale the near plane distance by
*/
public void scaleNearPlaneDistance(float factor)
{
public void scaleNearPlaneDistance(float factor) {
nearPlaneDistance *= factor;
}
}
@@ -198,15 +181,13 @@ public abstract class ViewportEvent extends Event
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class ComputeFogColor extends ViewportEvent
{
public static class ComputeFogColor extends ViewportEvent {
private float red;
private float green;
private float blue;
@ApiStatus.Internal
public ComputeFogColor(Camera camera, float partialTicks, float red, float green, float blue)
{
public ComputeFogColor(Camera camera, float partialTicks, float red, float green, float blue) {
super(Minecraft.getInstance().gameRenderer, camera, partialTicks);
this.setRed(red);
this.setGreen(green);
@@ -216,8 +197,7 @@ public abstract class ViewportEvent extends Event
/**
* {@return the red color value of the fog}
*/
public float getRed()
{
public float getRed() {
return red;
}
@@ -226,16 +206,14 @@ public abstract class ViewportEvent extends Event
*
* @param red the new red color value
*/
public void setRed(float red)
{
public void setRed(float red) {
this.red = red;
}
/**
* {@return the green color value of the fog}
*/
public float getGreen()
{
public float getGreen() {
return green;
}
@@ -244,16 +222,14 @@ public abstract class ViewportEvent extends Event
*
* @param green the new blue color value
*/
public void setGreen(float green)
{
public void setGreen(float green) {
this.green = green;
}
/**
* {@return the blue color value of the fog}
*/
public float getBlue()
{
public float getBlue() {
return blue;
}
@@ -262,8 +238,7 @@ public abstract class ViewportEvent extends Event
*
* @param blue the new blue color value
*/
public void setBlue(float blue)
{
public void setBlue(float blue) {
this.blue = blue;
}
}
@@ -277,15 +252,13 @@ public abstract class ViewportEvent extends Event
* <p>This event is fired on the {@linkplain MinecraftForge#EVENT_BUS main Forge event bus},
* only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
public static class ComputeCameraAngles extends ViewportEvent
{
public static class ComputeCameraAngles extends ViewportEvent {
private float yaw;
private float pitch;
private float roll;
@ApiStatus.Internal
public ComputeCameraAngles(GameRenderer renderer, Camera camera, double renderPartialTicks, float yaw, float pitch, float roll)
{
public ComputeCameraAngles(GameRenderer renderer, Camera camera, double renderPartialTicks, float yaw, float pitch, float roll) {
super(renderer, camera, renderPartialTicks);
this.setYaw(yaw);
this.setPitch(pitch);
@@ -295,8 +268,7 @@ public abstract class ViewportEvent extends Event
/**
* {@return the yaw of the player's camera}
*/
public float getYaw()
{
public float getYaw() {
return yaw;
}
@@ -305,16 +277,14 @@ public abstract class ViewportEvent extends Event
*
* @param yaw the new yaw
*/
public void setYaw(float yaw)
{
public void setYaw(float yaw) {
this.yaw = yaw;
}
/**
* {@return the pitch of the player's camera}
*/
public float getPitch()
{
public float getPitch() {
return pitch;
}
@@ -323,16 +293,14 @@ public abstract class ViewportEvent extends Event
*
* @param pitch the new pitch
*/
public void setPitch(float pitch)
{
public void setPitch(float pitch) {
this.pitch = pitch;
}
/**
* {@return the roll of the player's camera}
*/
public float getRoll()
{
public float getRoll() {
return roll;
}
@@ -341,8 +309,7 @@ public abstract class ViewportEvent extends Event
*
* @param roll the new roll
*/
public void setRoll(float roll)
{
public void setRoll(float roll) {
this.roll = roll;
}
}
@@ -358,14 +325,12 @@ public abstract class ViewportEvent extends Event
*
* @see ComputeFovModifierEvent
*/
public static class ComputeFov extends ViewportEvent
{
public static class ComputeFov extends ViewportEvent {
private final boolean usedConfiguredFov;
private double fov;
@ApiStatus.Internal
public ComputeFov(GameRenderer renderer, Camera camera, double renderPartialTicks, double fov, boolean usedConfiguredFov)
{
public ComputeFov(GameRenderer renderer, Camera camera, double renderPartialTicks, double fov, boolean usedConfiguredFov) {
super(renderer, camera, renderPartialTicks);
this.usedConfiguredFov = usedConfiguredFov;
this.setFOV(fov);
@@ -374,8 +339,7 @@ public abstract class ViewportEvent extends Event
/**
* {@return the raw field of view value}
*/
public double getFOV()
{
public double getFOV() {
return fov;
}
@@ -384,16 +348,14 @@ public abstract class ViewportEvent extends Event
*
* @param fov the new FOV value
*/
public void setFOV(double fov)
{
public void setFOV(double fov) {
this.fov = fov;
}
/**
* {@return whether the base fov value started with a constant or was sourced from the fov set in the options}
*/
public boolean usedConfiguredFov()
{
public boolean usedConfiguredFov() {
return usedConfiguredFov;
}
}
@@ -30,29 +30,24 @@ import java.util.List;
/**
* Extension interface for {@link IForgeBakedModel}.
*/
public interface IForgeBakedModel
{
private BakedModel self()
{
return (BakedModel) this;
public interface IForgeBakedModel {
private BakedModel self() {
return (BakedModel)this;
}
/**
* A null {@link RenderType} is used for the breaking overlay as well as non-standard rendering, so models should return all their quads.
*/
@NotNull
default List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType)
{
default List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand, @NotNull ModelData data, @Nullable RenderType renderType) {
return self().getQuads(state, side, rand);
}
default boolean useAmbientOcclusion(BlockState state)
{
default boolean useAmbientOcclusion(BlockState state) {
return self().useAmbientOcclusion();
}
default boolean useAmbientOcclusion(BlockState state, RenderType renderType)
{
default boolean useAmbientOcclusion(BlockState state, RenderType renderType) {
return self().useAmbientOcclusion(state);
}
@@ -60,19 +55,16 @@ public interface IForgeBakedModel
* Applies a transform for the given {@link ItemTransforms.TransformType} and {@code applyLeftHandTransform}, and
* returns the model to be rendered.
*/
default BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, boolean applyLeftHandTransform)
{
default BakedModel applyTransform(ItemDisplayContext transformType, PoseStack poseStack, boolean applyLeftHandTransform) {
self().getTransforms().getTransform(transformType).apply(applyLeftHandTransform, poseStack);
return self();
}
default @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData)
{
default @NotNull ModelData getModelData(@NotNull BlockAndTintGetter level, @NotNull BlockPos pos, @NotNull BlockState state, @NotNull ModelData modelData) {
return modelData;
}
default TextureAtlasSprite getParticleIcon(@NotNull ModelData data)
{
default TextureAtlasSprite getParticleIcon(@NotNull ModelData data) {
return self().getParticleIcon();
}
@@ -82,8 +74,7 @@ public interface IForgeBakedModel
* <p>
* By default, defers query to {@link ItemBlockRenderTypes}.
*/
default ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data)
{
default ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) {
return ItemBlockRenderTypes.getRenderLayers(state);
}
@@ -97,8 +88,7 @@ public interface IForgeBakedModel
*
* @see #getRenderPasses(ItemStack, boolean)
*/
default List<RenderType> getRenderTypes(ItemStack itemStack, boolean fabulous)
{
default List<RenderType> getRenderTypes(ItemStack itemStack, boolean fabulous) {
return List.of(RenderTypeHelper.getFallbackItemRenderType(itemStack, self(), fabulous));
}
@@ -110,8 +100,7 @@ public interface IForgeBakedModel
*
* @see #getRenderTypes(ItemStack, boolean)
*/
default List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous)
{
default List<BakedModel> getRenderPasses(ItemStack itemStack, boolean fabulous) {
return List.of(self());
}
}
@@ -16,11 +16,9 @@ import org.joml.Vector3f;
/**
* Extension interface for {@link DimensionSpecialEffects}.
*/
public interface IForgeDimensionSpecialEffects
{
private DimensionSpecialEffects self()
{
return (DimensionSpecialEffects) this;
public interface IForgeDimensionSpecialEffects {
private DimensionSpecialEffects self() {
return (DimensionSpecialEffects)this;
}
/**
@@ -28,8 +26,7 @@ public interface IForgeDimensionSpecialEffects
*
* @return true to prevent vanilla cloud rendering
*/
default boolean renderClouds(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, double camX, double camY, double camZ, Matrix4f projectionMatrix)
{
default boolean renderClouds(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, double camX, double camY, double camZ, Matrix4f projectionMatrix) {
return false;
}
@@ -38,8 +35,7 @@ public interface IForgeDimensionSpecialEffects
*
* @return true to prevent vanilla sky rendering
*/
default boolean renderSky(ClientLevel level, int ticks, float partialTick, PoseStack poseStack, Camera camera, Matrix4f projectionMatrix, boolean isFoggy, Runnable setupFog)
{
default boolean renderSky(ClientLevel level, int ticks, float partialTick, Camera camera, Matrix4f projectionMatrix, boolean isFoggy, Runnable setupFog) {
return false;
}
@@ -48,8 +44,7 @@ public interface IForgeDimensionSpecialEffects
*
* @return true to prevent vanilla snow and rain rendering
*/
default boolean renderSnowAndRain(ClientLevel level, int ticks, float partialTick, LightTexture lightTexture, double camX, double camY, double camZ)
{
default boolean renderSnowAndRain(ClientLevel level, int ticks, float partialTick, LightTexture lightTexture, double camX, double camY, double camZ) {
return false;
}
@@ -58,8 +53,7 @@ public interface IForgeDimensionSpecialEffects
*
* @return true to prevent vanilla rain ticking
*/
default boolean tickRain(ClientLevel level, int ticks, Camera camera)
{
default boolean tickRain(ClientLevel level, int ticks, Camera camera) {
return false;
}
@@ -13,8 +13,7 @@ import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.Nullable;
import java.util.function.Function;
public interface IForgeModelBaker
{
public interface IForgeModelBaker {
@Nullable
BakedModel bake(ResourceLocation location, ModelState state, Function<Material, TextureAtlasSprite> sprites);
@@ -12,11 +12,9 @@ import org.joml.Vector3f;
/**
* Extension interface for {@link com.mojang.blaze3d.vertex.PoseStack}.
*/
public interface IForgePoseStack
{
private PoseStack self()
{
return (PoseStack) this;
public interface IForgePoseStack {
private PoseStack self() {
return (PoseStack)this;
}
/**
@@ -25,8 +23,7 @@ public interface IForgePoseStack
*
* @param transformation the transformation to push
*/
default void pushTransformation(Transformation transformation)
{
default void pushTransformation(Transformation transformation) {
final PoseStack self = self();
self.pushPose();
@@ -18,11 +18,9 @@ import java.nio.ByteBuffer;
/**
* Extension interface for {@link VertexConsumer}.
*/
public interface IForgeVertexConsumer
{
private VertexConsumer self()
{
return (VertexConsumer) this;
public interface IForgeVertexConsumer {
private VertexConsumer self() {
return (VertexConsumer)this;
}
/**
@@ -30,21 +28,18 @@ public interface IForgeVertexConsumer
* <p>
* If the consumer needs to store the data for later use, it must copy it. There are no guarantees on immutability.
*/
default VertexConsumer misc(VertexFormatElement element, int... rawData)
{
default VertexConsumer misc(VertexFormatElement element, int... rawData) {
return self();
}
/**
* Variant with no per-vertex shading.
*/
default void putBulkData(PoseStack.Pose pose, BakedQuad bakedQuad, float red, float green, float blue, float alpha, int packedLight, int packedOverlay, boolean readExistingColor)
{
default void putBulkData(PoseStack.Pose pose, BakedQuad bakedQuad, float red, float green, float blue, float alpha, int packedLight, int packedOverlay, boolean readExistingColor) {
self().putBulkData(pose, bakedQuad, new float[] { 1.0F, 1.0F, 1.0F, 1.0F }, red, green, blue, alpha, new int[] { packedLight, packedLight, packedLight, packedLight }, packedOverlay, readExistingColor);
}
default int applyBakedLighting(int packedLight, ByteBuffer data)
{
default int applyBakedLighting(int packedLight, ByteBuffer data) {
int bl = packedLight & 0xFFFF;
int sl = (packedLight >> 16) & 0xFFFF;
int offset = IQuadTransformer.UV2 * 4; // int offset for vertex 0 * 4 bytes per int
@@ -55,13 +50,11 @@ public interface IForgeVertexConsumer
return bl | (sl << 16);
}
default void applyBakedNormals(Vector3f generated, ByteBuffer data, Matrix3f normalTransform)
{
default void applyBakedNormals(Vector3f generated, ByteBuffer data, Matrix3f normalTransform) {
byte nx = data.get(28);
byte ny = data.get(29);
byte nz = data.get(30);
if (nx != 0 || ny != 0 || nz != 0)
{
if (nx != 0 || ny != 0 || nz != 0) {
generated.set(nx / 127f, ny / 127f, nz / 127f);
generated.mul(normalTransform);
}
@@ -30,23 +30,20 @@ import java.util.function.Consumer;
*
* @see Block#initializeClient(Consumer)
*/
public interface IClientBlockExtensions
{
public interface IClientBlockExtensions {
IClientBlockExtensions DEFAULT = new IClientBlockExtensions() { };
static IClientBlockExtensions of(BlockState state)
{
static IClientBlockExtensions of(BlockState state) {
return of(state.getBlock());
}
static IClientBlockExtensions of(Block block)
{
static IClientBlockExtensions of(Block block) {
return block.getRenderPropertiesInternal() instanceof IClientBlockExtensions e ? e : DEFAULT;
}
/**
* Spawn a digging particle effect in the level, this is a wrapper
* around EffectRenderer.addBlockHitEffects to allow the block more
* around EffectRenderer.crack to allow the block more
* control over the particles. Useful when you have entirely different
* texture sheets for different sides/locations in the level.
*
@@ -56,8 +53,7 @@ public interface IClientBlockExtensions
* @param manager A reference to the current particle manager.
* @return True to prevent vanilla digging particles form spawning.
*/
default boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager)
{
default boolean addHitEffects(BlockState state, Level level, HitResult target, ParticleEngine manager) {
return false;
}
@@ -72,8 +68,7 @@ public interface IClientBlockExtensions
* @param manager A reference to the current particle manager.
* @return True to prevent vanilla break particles from spawning.
*/
default boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager)
{
default boolean addDestroyEffects(BlockState state, Level Level, BlockPos pos, ParticleEngine manager) {
return !state.shouldSpawnTerrainParticles();
}
@@ -90,27 +85,20 @@ public interface IClientBlockExtensions
* @param originalColor The current fog color, You are not expected to use this, Return as the default if applicable.
* @return The new fog color.
*/
default Vector3d getFogColor(BlockState state, LevelReader level, BlockPos pos, Entity entity, Vector3d originalColor, float partialTick)
{
default Vector3d getFogColor(BlockState state, LevelReader level, BlockPos pos, Entity entity, Vector3d originalColor, float partialTick) {
FluidState fluidState = level.getFluidState(pos);
if (fluidState.is(FluidTags.WATER))
{
if (fluidState.is(FluidTags.WATER)) {
float f12 = 0.0F;
if (entity instanceof LivingEntity)
{
LivingEntity ent = (LivingEntity) entity;
if (entity instanceof LivingEntity ent) {
f12 = (float) EnchantmentHelper.getRespiration(ent) * 0.2F;
if (ent.hasEffect(MobEffects.WATER_BREATHING))
{
if (ent.hasEffect(MobEffects.WATER_BREATHING)) {
f12 = f12 * 0.3F + 0.6F;
}
}
return new Vector3d(0.02F + f12, 0.02F + f12, 0.2F + f12);
}
else if (fluidState.is(FluidTags.LAVA))
{
} else if (fluidState.is(FluidTags.LAVA)) {
return new Vector3d(0.6F, 0.1F, 0.0F);
}
return originalColor;
@@ -124,8 +112,7 @@ public interface IClientBlockExtensions
* @param pos The position of the block
* @return {@code true} if the particles should be tinted.
*/
default boolean areBreakingParticlesTinted(BlockState state, ClientLevel level, BlockPos pos)
{
default boolean areBreakingParticlesTinted(BlockState state, ClientLevel level, BlockPos pos) {
return !state.is(Blocks.GRASS_BLOCK);
}
}
@@ -19,17 +19,14 @@ import java.util.function.Consumer;
*
* @see MobEffect#initializeClient(Consumer)
*/
public interface IClientMobEffectExtensions
{
public interface IClientMobEffectExtensions {
IClientMobEffectExtensions DEFAULT = new IClientMobEffectExtensions() { };
static IClientMobEffectExtensions of(MobEffectInstance instance)
{
return of(instance.getEffect());
static IClientMobEffectExtensions of(MobEffectInstance instance) {
return of(instance.getEffect().value());
}
static IClientMobEffectExtensions of(MobEffect effect)
{
static IClientMobEffectExtensions of(MobEffect effect) {
return effect.getEffectRendererInternal() instanceof IClientMobEffectExtensions r ? r : DEFAULT;
}
@@ -38,8 +35,7 @@ public interface IClientMobEffectExtensions
* <p>
* By default, this returns {@code true}.
*/
default boolean isVisibleInInventory(MobEffectInstance instance)
{
default boolean isVisibleInInventory(MobEffectInstance instance) {
return true;
}
@@ -48,8 +44,7 @@ public interface IClientMobEffectExtensions
* <p>
* By default, this returns {@code true}.
*/
default boolean isVisibleInGui(MobEffectInstance instance)
{
default boolean isVisibleInGui(MobEffectInstance instance) {
return true;
}
@@ -65,8 +60,7 @@ public interface IClientMobEffectExtensions
* @param blitOffset The blit offset
* @return true to prevent default rendering, false otherwise
*/
default boolean renderInventoryIcon(MobEffectInstance instance, EffectRenderingInventoryScreen<?> screen, GuiGraphics guiGraphics, int x, int y, int blitOffset)
{
default boolean renderInventoryIcon(MobEffectInstance instance, EffectRenderingInventoryScreen<?> screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
return false;
}
@@ -81,8 +75,7 @@ public interface IClientMobEffectExtensions
* @param blitOffset The blit offset
* @return true to prevent default rendering, false otherwise
*/
default boolean renderInventoryText(MobEffectInstance instance, EffectRenderingInventoryScreen<?> screen, GuiGraphics guiGraphics, int x, int y, int blitOffset)
{
default boolean renderInventoryText(MobEffectInstance instance, EffectRenderingInventoryScreen<?> screen, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
return false;
}
@@ -99,8 +92,7 @@ public interface IClientMobEffectExtensions
* @param alpha The alpha value. Blinks when the effect is about to run out
* @return true to prevent default rendering, false otherwise
*/
default boolean renderGuiIcon(MobEffectInstance instance, Gui gui, GuiGraphics guiGraphics, int x, int y, float z, float alpha)
{
default boolean renderGuiIcon(MobEffectInstance instance, Gui gui, GuiGraphics guiGraphics, int x, int y, float z, float alpha) {
return false;
}
}
@@ -66,7 +66,7 @@ public class TitleScreenModUpdateIndicator extends Screen
public static TitleScreenModUpdateIndicator init(TitleScreen guiMainMenu, Button modButton)
{
TitleScreenModUpdateIndicator titleScreenModUpdateIndicator = new TitleScreenModUpdateIndicator(modButton);
titleScreenModUpdateIndicator.resize(guiMainMenu.getMinecraft(), guiMainMenu.width, guiMainMenu.height);
//titleScreenModUpdateIndicator.resize(guiMainMenu.getMinecraft(), guiMainMenu.width, guiMainMenu.height);
titleScreenModUpdateIndicator.init();
return titleScreenModUpdateIndicator;
}
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.gui.overlay;
import com.mojang.blaze3d.platform.Window;
@@ -47,7 +48,7 @@ import java.util.List;
/**
* Forge wrapper around {@link Gui} to be able to render {@link IGuiOverlay HUD overlays}.
*/
* /
public class ForgeGui extends Gui {
private static final Logger LOGGER = LogManager.getLogger();
@@ -55,14 +56,14 @@ public class ForgeGui extends Gui {
/*
* If the Euclidean distance to the moused-over block in meters is less than this value, the "Looking at" text will appear on the debug overlay.
*/
* /
public static double rayTraceDistance = 20.0D;
public int leftHeight = 39;
public int rightHeight = 39;
public ForgeGui(Minecraft mc) {
super(mc, mc.getItemRenderer());
super(mc);
this.debugOverlay = new OverlayAccess(mc);
}
@@ -457,7 +458,7 @@ public class ForgeGui extends Gui {
guiGraphics.pose().translate(event.getPosX(), (event.getPosY() - height + 40) / chat.getScale(), 0.0D);
int mouseX = Mth.floor(minecraft.mouseHandler.xpos() * window.getGuiScaledWidth() / window.getScreenWidth());
int mouseY = Mth.floor(minecraft.mouseHandler.ypos() * window.getGuiScaledHeight() / window.getScreenHeight());
chat.render(guiGraphics, tickCount, mouseX, mouseY);
chat.render(guiGraphics, tickCount, mouseX, mouseY, false);
guiGraphics.pose().popPose();
minecraft.getProfiler().pop();
@@ -533,3 +534,4 @@ public class ForgeGui extends Gui {
@Override protected void renderLines(GuiGraphics gfx, List<String> lines, boolean leftAlign) { super.renderLines(gfx, lines, leftAlign); }
}
}
*/
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.gui.overlay;
import com.google.common.collect.ImmutableList;
@@ -21,7 +22,7 @@ import java.util.function.Function;
* Manager for {@linkplain IGuiOverlay HUD overlays}.
* <p>
* Provides a lookup by ID, as well as all registered {@link IGuiOverlay overlays}.
*/
* /
public final class GuiOverlayManager
{
private static ImmutableList<NamedGuiOverlay> OVERLAYS;
@@ -29,7 +30,7 @@ public final class GuiOverlayManager
/**
* Retrieves an ordered list of all registered overlays.
*/
* /
public static ImmutableList<NamedGuiOverlay> getOverlays()
{
return OVERLAYS;
@@ -38,7 +39,7 @@ public final class GuiOverlayManager
/**
* Finds the overlay corresponding to a given ID.
* Do not call this before {@link RegisterGuiOverlaysEvent} has finished firing.
*/
* /
@Nullable
public static NamedGuiOverlay findOverlay(ResourceLocation id)
{
@@ -63,7 +64,7 @@ public final class GuiOverlayManager
/**
* Pre-registers vanilla overlays so they are available for ordering.
*/
* /
private static void preRegisterVanillaOverlays(HashMap<ResourceLocation, IGuiOverlay> overlays, ArrayList<ResourceLocation> orderedOverlays)
{
for (var entry : VanillaGuiOverlay.values())
@@ -83,3 +84,4 @@ public final class GuiOverlayManager
{
}
}
*/
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.gui.overlay;
import net.minecraft.client.gui.GuiGraphics;
@@ -12,8 +13,9 @@ import net.minecraftforge.client.event.RegisterGuiOverlaysEvent;
* A HUD overlay.
*
* @see RegisterGuiOverlaysEvent
*/
* /
@FunctionalInterface
public interface IGuiOverlay {
void render(ForgeGui gui, GuiGraphics guiGraphics, float partialTick, int screenWidth, int screenHeight);
}
*/
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.gui.overlay;
import net.minecraft.resources.ResourceLocation;
@@ -14,7 +15,7 @@ import org.jetbrains.annotations.ApiStatus;
* Useful to identify overlays in {@link net.minecraftforge.client.event.RenderGuiOverlayEvent}.
* <p>
* Users should not be instantiating this themselves. Retrieve from {@link GuiOverlayManager}.
*/
* /
public record NamedGuiOverlay(ResourceLocation id, IGuiOverlay overlay)
{
@ApiStatus.Internal
@@ -22,3 +23,4 @@ public record NamedGuiOverlay(ResourceLocation id, IGuiOverlay overlay)
{
}
}
*/
@@ -3,6 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.gui.overlay;
import com.mojang.blaze3d.systems.RenderSystem;
@@ -22,7 +23,7 @@ import org.lwjgl.opengl.GL11;
/**
* All the vanilla {@linkplain IGuiOverlay HUD overlays} in the order that they render.
*/
* /
@SuppressWarnings("resource")
public enum VanillaGuiOverlay {
VIGNETTE("vignette", (gui, guiGraphics, partialTick, screenWidth, screenHeight) -> {
@@ -233,3 +234,4 @@ public enum VanillaGuiOverlay {
return type;
}
}
*/
@@ -155,7 +155,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
if (this.client.level != null) {
this.drawGradientRect(guiGraphics, this.left, this.top, this.right, this.bottom, bgColorFrom, bgColorTo);
} else { // Draw dark dirt background
} /* else { // Draw dark dirt background
RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
RenderSystem.setShaderTexture(0, Screen.BACKGROUND_LOCATION);
final float texScale = 32.0F;
@@ -166,6 +166,7 @@ public abstract class ScrollPanel extends AbstractContainerEventHandler implemen
worldr.vertex(this.left, this.top, 0.0D).uv(this.left / texScale, (this.top + (int)this.scrollDistance) / texScale).color(0x20, 0x20, 0x20, 0xFF).endVertex();
tess.end();
}
*/
}
/**
@@ -39,7 +39,7 @@ public record ForgeFaceData(int color, int blockLight, int skyLight, boolean amb
public static final ForgeFaceData DEFAULT = new ForgeFaceData(0xFFFFFFFF, 0, 0, true, false);
public static final Codec<Integer> COLOR = ExtraCodecs.either(Codec.INT, Codec.STRING).xmap(
public static final Codec<Integer> COLOR = Codec.either(Codec.INT, Codec.STRING).xmap(
either -> either.map(Function.identity(), str -> (int) Long.parseLong(str, 16)),
color -> Either.right(Integer.toHexString(color)));
@@ -65,6 +65,6 @@ public record ForgeFaceData(int color, int blockLight, int skyLight, boolean amb
{
return fallback;
}
return CODEC.parse(JsonOps.INSTANCE, obj).getOrThrow(false, JsonParseException::new);
return CODEC.parse(JsonOps.INSTANCE, obj).getOrThrow(JsonParseException::new);
}
}
@@ -23,43 +23,36 @@ import java.util.Map;
/**
* Wrapper around {@link ItemModelShaper} that cleans up the internal maps to respect ID remapping.
*/
public class ForgeItemModelShaper extends ItemModelShaper
{
public class ForgeItemModelShaper extends ItemModelShaper {
private final Map<Holder.Reference<Item>, ModelResourceLocation> locations = Maps.newHashMap();
private final Map<Holder.Reference<Item>, BakedModel> models = Maps.newHashMap();
public ForgeItemModelShaper(ModelManager manager)
{
public ForgeItemModelShaper(ModelManager manager) {
super(manager);
}
@Override
@Nullable
public BakedModel getItemModel(Item item)
{
public BakedModel getItemModel(Item item) {
return models.get(ForgeRegistries.ITEMS.getDelegateOrThrow(item));
}
@Override
public void register(Item item, ModelResourceLocation location)
{
public void register(Item item, ModelResourceLocation location) {
Holder.Reference<Item> key = ForgeRegistries.ITEMS.getDelegateOrThrow(item);
locations.put(key, location);
models.put(key, getModelManager().getModel(location));
}
@Override
public void rebuildCache()
{
public void rebuildCache() {
final ModelManager manager = this.getModelManager();
for (Map.Entry<Holder.Reference<Item>, ModelResourceLocation> e : locations.entrySet())
{
for (Map.Entry<Holder.Reference<Item>, ModelResourceLocation> e : locations.entrySet()) {
models.put(e.getKey(), manager.getModel(e.getValue()));
}
}
public ModelResourceLocation getLocation(@NotNull ItemStack stack)
{
public ModelResourceLocation getLocation(@NotNull ItemStack stack) {
ModelResourceLocation location = locations.get(ForgeRegistries.ITEMS.getDelegateOrThrow(stack.getItem()));
return location == null ? ModelBakery.MISSING_MODEL_LOCATION : location;
}
@@ -21,11 +21,9 @@ import java.util.List;
/**
* Convenience interface with default implementation of {@link IForgeBakedModel#getQuads(BlockState, Direction, RandomSource, ModelData, RenderType)}.
*/
public interface IDynamicBakedModel extends BakedModel
{
public interface IDynamicBakedModel extends BakedModel {
@Override
default @NotNull List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand)
{
default @NotNull List<BakedQuad> getQuads(@Nullable BlockState state, @Nullable Direction side, @NotNull RandomSource rand) {
return getQuads(state, side, rand, ModelData.EMPTY, null);
}
@@ -80,7 +80,7 @@ public interface IModelBuilder<T extends IModelBuilder<T>>
@Override
public BakedModel build()
{
return builder.build(renderTypes);
return builder.renderTypes(renderTypes).build();
}
}
@@ -154,7 +154,9 @@ public class ItemLayerModelBuilder<T extends ModelBuilder<T>> extends CustomLoad
for(Int2ObjectMap.Entry<ForgeFaceData> entry : this.faceData.int2ObjectEntrySet())
{
layerObj.add(String.valueOf(entry.getIntKey()), ForgeFaceData.CODEC.encodeStart(JsonOps.INSTANCE, entry.getValue()).getOrThrow(false, s -> {}));
layerObj.add(String.valueOf(entry.getIntKey()), ForgeFaceData.CODEC.encodeStart(JsonOps.INSTANCE, entry.getValue()).getOrThrow(s -> {
return new RuntimeException(); // Perhaps not the best way to deal with this? - MangoRage
}));
}
forgeData.add("layers", layerObj);
@@ -131,7 +131,7 @@ public abstract class QuadLighter
}
var color = quad.isTinted() ? getColorFast(quad.getTintIndex()) : WHITE;
consumer.putBulkData(pose, quad, brightness, color[0], color[1], color[2], lightmap, overlay, true);
consumer.putBulkData(pose, quad, brightness, color[0], color[1], color[2], 1.0f, lightmap, overlay, true);
}
private float[] getColorFast(int tintIndex)
@@ -6,13 +6,13 @@
package net.minecraftforge.client.model.obj;
import com.google.common.collect.Maps;
import joptsimple.internal.Strings;
import org.joml.Vector4f;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
/**
* An OBJ material library (MTL), composed of named {@link Material materials}.
@@ -37,7 +37,7 @@ public class ObjMaterialLibrary
{
case "newmtl":
{
String name = Strings.join(Arrays.copyOfRange(line, 1, line.length), " ");
String name = Arrays.asList(Arrays.copyOfRange(line, 1, line.length)).stream().collect(Collectors.joining(" "));
currentMaterial = new Material(name);
materials.put(name, currentMaterial);
break;
@@ -9,7 +9,6 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.mojang.math.Transformation;
import joptsimple.internal.Strings;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
@@ -145,7 +144,8 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel>
case "usemtl": // Sets the current material (starts new mesh)
{
String mat = Strings.join(Arrays.copyOfRange(line, 1, line.length), " ");
String mat = Arrays.asList(Arrays.copyOfRange(line, 1, line.length)).stream().collect(Collectors.joining(" "));
ObjMaterialLibrary.Material newMat = mtllib.getMaterial(mat);
if (!Objects.equals(newMat, currentMat))
{
@@ -201,7 +201,7 @@ public class ObjModel extends SimpleUnbakedGeometry<ObjModel>
{
String vertexData = line[i + 1];
String[] vertexParts = vertexData.split("/");
int[] vertex = Arrays.stream(vertexParts).mapToInt(num -> Strings.isNullOrEmpty(num) ? 0 : Integer.parseInt(num)).toArray();
int[] vertex = Arrays.stream(vertexParts).mapToInt(num -> num == null || num.isEmpty() ? 0 : Integer.parseInt(num)).toArray();
if (vertex[0] < 0) vertex[0] = model.positions.size() + vertex[0];
else vertex[0]--;
if (vertex.length > 1)
@@ -60,7 +60,7 @@ public class CompositeRenderable implements IRenderable<CompositeRenderable.Tran
if (matrix != null)
{
poseStack.pushPose();
poseStack.mulPoseMatrix(matrix);
poseStack.mulPose(matrix);
}
for (var part : children)
@@ -23,32 +23,6 @@ public class KeyMappingLookup {
map.put(modifier, new HashMap<>());
}
/** Replaced by {@link #getAll(InputConstants.Key) getAll} */
@Deprecated(forRemoval = true, since = "1.20.1")
@Nullable
public KeyMapping get(InputConstants.Key keyCode) {
var activeModifier = KeyModifier.getActiveModifier();
if (!activeModifier.matches(keyCode)) {
var binding = get(keyCode, activeModifier);
if (binding != null)
return binding;
}
return get(keyCode, KeyModifier.NONE);
}
@Nullable
@Deprecated(forRemoval = true, since = "1.20.1")
private KeyMapping get(InputConstants.Key keyCode, KeyModifier keyModifier) {
var bindings = map.get(keyModifier).get(keyCode);
if (bindings != null) {
for (var binding : bindings) {
if (binding.isActiveAndMatches(keyCode))
return binding;
}
}
return null;
}
/**
* Returns all active keys associated with the given key code and the active
* modifiers and conflict context.
@@ -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 */
@@ -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()");
}
}
@@ -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);
}
};
@@ -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);
}
};
}
@@ -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());
}
};
}
@@ -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));
}
};
}
@@ -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);
}
};
@@ -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);
}
}
Loaded 100 of 1114 files, more files were not shown because too many files have changed in this diff. Show more