diff --git a/gradle.properties b/gradle.properties index 7ef188b37a..379dd17110 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,7 +7,7 @@ org.gradle.parallel=true JAVA_VERSION=25 MC_VERSION=26.1 MC_NEXT_VERSION=26.2 -MCP_VERSION=20260324.123823 +MCP_VERSION=20260326.105027 MAPPING_CHANNEL=official MAPPING_VERSION=26.1 diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch index a284b9ecd6..9dcd24218d 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlDebug.java.patch @@ -18,14 +18,14 @@ @@ -103,6 +_,8 @@ } - LOGGER.info("OpenGL debug message: {}", gldebug$logentry); + LOGGER.info("OpenGL debug message: {}", entry); + // TODO: [VEN] Trim the stack trace + if (PRINT_STACKTRACE_ON_ERROR) LOGGER.info("Trace: ", new Throwable("GlDebug")); } public List getLastOpenGlDebugMessages() { @@ -126,7 +_,7 @@ - GlDebug gldebug1 = new GlDebug(); + GlDebug debug = new GlDebug(); enabledExtensions.add("GL_KHR_debug"); GL11.glEnable(37600); - if (debugSynchronousGlLogs) { @@ -34,8 +34,8 @@ } @@ -140,7 +_,7 @@ - } else if (glcapabilities.GL_ARB_debug_output && GlDevice.USE_GL_ARB_debug_output) { - GlDebug gldebug = new GlDebug(); + } else if (caps.GL_ARB_debug_output && GlDevice.USE_GL_ARB_debug_output) { + GlDebug debug = new GlDebug(); enabledExtensions.add("GL_ARB_debug_output"); - if (debugSynchronousGlLogs) { + if (debugSynchronousGlLogs | PRINT_STACKTRACE_ON_ERROR) { diff --git a/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch b/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch index 9882980d67..ddcc82b13f 100644 --- a/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/opengl/GlDevice.java.patch @@ -24,31 +24,39 @@ + @Override + public GpuTexture createTexture(@Nullable String label, @GpuTexture.Usage final int usage, final TextureFormat format, final int width, final int height, final int depthOrLayers, final int mipLevels, boolean stencil) { GlStateManager.clearGlErrors(); - int i = GlStateManager._genTexture(); + int id = GlStateManager._genTexture(); if (label == null) { -@@ -169,14 +_,14 @@ - for (int k : GlConst.CUBEMAP_TARGETS) { - for (int l = 0; l < mipLevels; l++) { +@@ -171,12 +_,12 @@ GlStateManager._texImage2D( -- k, l, GlConst.toGlInternalId(format), width >> l, height >> l, 0, GlConst.toGlExternalId(format), GlConst.toGlType(format), null -+ k, l, GlConst.toGlInternalId(format, stencil), width >> l, height >> l, 0, GlConst.toGlExternalId(format, stencil), GlConst.toGlType(format, stencil), null + cubeTarget, + i, +- GlConst.toGlInternalId(format), ++ GlConst.toGlInternalId(format, stencil), + width >> i, + height >> i, + 0, +- GlConst.toGlExternalId(format), +- GlConst.toGlType(format), ++ GlConst.toGlExternalId(format, stencil), ++ GlConst.toGlType(format, stencil), + null ); } - } +@@ -184,7 +_,7 @@ } else { - for (int i1 = 0; i1 < mipLevels; i1++) { + for (int i = 0; i < mipLevels; i++) { GlStateManager._texImage2D( -- j, i1, GlConst.toGlInternalId(format), width >> i1, height >> i1, 0, GlConst.toGlExternalId(format), GlConst.toGlType(format), null -+ j, i1, GlConst.toGlInternalId(format, stencil), width >> i1, height >> i1, 0, GlConst.toGlExternalId(format, stencil), GlConst.toGlType(format, stencil), null +- target, i, GlConst.toGlInternalId(format), width >> i, height >> i, 0, GlConst.toGlExternalId(format), GlConst.toGlType(format), null ++ target, i, GlConst.toGlInternalId(format, stencil), width >> i, height >> i, 0, GlConst.toGlExternalId(format, stencil), GlConst.toGlType(format, stencil), null ); } } -@@ -187,7 +_,7 @@ - } else if (j1 != 0) { - throw new IllegalStateException("OpenGL error " + j1); +@@ -195,7 +_,7 @@ + } else if (error != 0) { + throw new IllegalStateException("OpenGL error " + error); } else { -- GlTexture gltexture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, i); -+ GlTexture gltexture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, i, stencil); - this.debugLabels.applyLabel(gltexture); - return gltexture; +- GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id); ++ GlTexture texture = new GlTexture(usage, label, format, width, height, depthOrLayers, mipLevels, id, stencil); + this.debugLabels.applyLabel(texture); + return texture; } diff --git a/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch b/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch index 09e7a71e25..1821e02f6e 100644 --- a/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/pipeline/RenderTarget.java.patch @@ -4,9 +4,9 @@ this.width = width; this.height = height; if (this.useDepth) { -- this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, width, height, 1, 1); -+ this.depthTexture = gpudevice.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, width, height, 1, 1, this.stencilEnabled); - this.depthTextureView = gpudevice.createTextureView(this.depthTexture); +- this.depthTexture = device.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, width, height, 1, 1); ++ this.depthTexture = device.createTexture(() -> this.label + " / Depth", 15, TextureFormat.DEPTH32, width, height, 1, 1, this.stencilEnabled); + this.depthTextureView = device.createTextureView(this.depthTexture); } @@ -124,5 +_,26 @@ diff --git a/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch b/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch index 3625ee9afb..1da5502ab9 100644 --- a/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/platform/Window.java.patch @@ -1,28 +1,28 @@ --- a/com/mojang/blaze3d/platform/Window.java +++ b/com/mojang/blaze3d/platform/Window.java @@ -97,8 +_,9 @@ - Monitor monitor = this.screenManager.getMonitor(GLFW.glfwGetPrimaryMonitor()); + Monitor initialMonitor = this.screenManager.getMonitor(GLFW.glfwGetPrimaryMonitor()); this.windowedWidth = this.width = allowedWindowMinSize(displayData.width()); this.windowedHeight = this.height = allowedWindowMinSize(displayData.height()); -- this.handle = this.createWindow(backend, this.width, this.height, title, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L); -+ this.handle = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(this.width, this.height, title, this.fullscreen && monitor != null ? monitor.getMonitor() : 0L, () -> backend); +- this.handle = this.createWindow(backend, this.width, this.height, title, this.fullscreen && initialMonitor != null ? initialMonitor.getMonitor() : 0L); ++ this.handle = net.minecraftforge.fml.loading.ImmediateWindowHandler.setupMinecraftWindow(this.width, this.height, title, this.fullscreen && initialMonitor != null ? initialMonitor.getMonitor() : 0L, () -> backend); this.backend = backend; -+ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(monitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) { - if (monitor != null) { - VideoMode videomode = monitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty()); - this.windowedX = this.x = monitor.getX() + videomode.getWidth() / 2 - this.width / 2; ++ if (!net.minecraftforge.fml.loading.ImmediateWindowHandler.positionWindow(Optional.ofNullable(initialMonitor), w->this.width = this.windowedWidth = w, h->this.height = this.windowedHeight = h, x->this.x = this.windowedX = x, y->this.y = this.windowedY = y)) { + if (initialMonitor != null) { + VideoMode mode = initialMonitor.getPreferredVidMode(this.fullscreen ? this.preferredFullscreenVideoMode : Optional.empty()); + this.windowedX = this.x = initialMonitor.getX() + mode.getWidth() / 2 - this.width / 2; @@ -110,6 +_,7 @@ - this.windowedX = this.x = aint1[0]; - this.windowedY = this.y = aint[0]; + this.windowedX = this.x = actualX[0]; + this.windowedY = this.y = actualY[0]; } + } this.setMode(); this.refreshFramebufferSize(); @@ -300,6 +_,9 @@ - GLFW.glfwGetFramebufferSize(this.handle, aint, aint1); - this.framebufferWidth = aint[0] > 0 ? aint[0] : 1; - this.framebufferHeight = aint1[0] > 0 ? aint1[0] : 1; + GLFW.glfwGetFramebufferSize(this.handle, outWidth, outHeight); + this.framebufferWidth = outWidth[0] > 0 ? outWidth[0] : 1; + this.framebufferHeight = outHeight[0] > 0 ? outHeight[0] : 1; + if (this.framebufferHeight == 0 || this.framebufferWidth == 0) { + net.minecraftforge.fml.loading.ImmediateWindowHandler.updateFBSize(w -> this.framebufferWidth = w, h -> this.framebufferHeight = h); + } diff --git a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch index 6b8eaa1d7c..71a66ec7e9 100644 --- a/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch +++ b/patches/minecraft/com/mojang/blaze3d/vertex/VertexFormat.java.patch @@ -9,8 +9,8 @@ private VertexFormat(final List elements, final List names, final IntList offsets, final int vertexSize) { this.elements = elements; @@ -41,6 +_,11 @@ - int j = vertexformatelement != null ? elements.indexOf(vertexformatelement) : -1; - this.offsetsByElement[i] = j != -1 ? offsets.getInt(j) : -1; + int index = element != null ? elements.indexOf(element) : -1; + this.offsetsByElement[id] = index != -1 ? offsets.getInt(index) : -1; } + + ImmutableMap.Builder elementMapping = ImmutableMap.builder(); diff --git a/patches/minecraft/com/mojang/math/Transformation.java.patch b/patches/minecraft/com/mojang/math/Transformation.java.patch index 537bbf1349..dbb6774e63 100644 --- a/patches/minecraft/com/mojang/math/Transformation.java.patch +++ b/patches/minecraft/com/mojang/math/Transformation.java.patch @@ -1,6 +1,6 @@ --- a/com/mojang/math/Transformation.java +++ b/com/mojang/math/Transformation.java -@@ -17,7 +_,7 @@ +@@ -16,7 +_,7 @@ import org.joml.Vector3fc; import org.jspecify.annotations.Nullable; @@ -9,7 +9,7 @@ private static final Vector3fc ZERO_TRANSLATION = new Vector3f(); private static final Vector3fc UNIT_SCALE = new Vector3f(1.0F, 1.0F, 1.0F); private static final Quaternionfc ZERO_ROTATION = new Quaternionf(); -@@ -172,6 +_,20 @@ +@@ -171,6 +_,20 @@ this.scale().lerp(that.scale(), progress, new Vector3f()), this.rightRotation().slerp(that.rightRotation(), progress, new Quaternionf()) ); diff --git a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch index fea9804e7c..84348ff3a8 100644 --- a/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch +++ b/patches/minecraft/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java.patch @@ -1,11 +1,11 @@ --- a/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java +++ b/com/mojang/realmsclient/gui/screens/RealmsResetWorldScreen.java -@@ -303,7 +_,7 @@ - int k = this.getY(); - graphics.blit(RenderPipelines.GUI_TEXTURED, this.image, j + 2, k + 2, 0.0F, 0.0F, 56, 56, 56, 56, 56, 56, i); - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_FRAME_SPRITE, j, k, 60, 60, i); -- int l = flag ? -6250336 : -1; -+ int l = getFGColor(); - graphics.centeredText(RealmsResetWorldScreen.this.font, this.getMessage(), j + 28, k - 14, l); +@@ -302,7 +_,7 @@ + int y = this.getY(); + graphics.blit(RenderPipelines.GUI_TEXTURED, this.image, x + 2, y + 2, 0.0F, 0.0F, 56, 56, 56, 56, 56, 56, color); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, SLOT_FRAME_SPRITE, x, y, 60, 60, color); +- int textColor = hoveredOrFocused ? -6250336 : -1; ++ int textColor = getFGColor(); + graphics.centeredText(RealmsResetWorldScreen.this.font, this.getMessage(), x + 28, y - 14, textColor); } } diff --git a/patches/minecraft/net/minecraft/CrashReport.java.patch b/patches/minecraft/net/minecraft/CrashReport.java.patch index 1bc62134c6..7315552858 100644 --- a/patches/minecraft/net/minecraft/CrashReport.java.patch +++ b/patches/minecraft/net/minecraft/CrashReport.java.patch @@ -6,8 +6,8 @@ builder.append("Thread: ").append(Thread.currentThread().getName()).append("\n"); - builder.append("Stacktrace:\n"); - -- for (StackTraceElement stacktraceelement : this.uncategorizedStackTrace) { -- builder.append("\t").append("at ").append(stacktraceelement); +- for (StackTraceElement element : this.uncategorizedStackTrace) { +- builder.append("\t").append("at ").append(element); - builder.append("\n"); - } - @@ -17,7 +17,7 @@ + builder.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.uncategorizedStackTrace)); } - for (CrashReportCategory crashreportcategory : this.details) { + for (CrashReportCategory entry : this.details) { @@ -73,6 +_,7 @@ builder.append("\n\n"); } @@ -27,22 +27,22 @@ } @@ -92,18 +_,7 @@ - throwable.setStackTrace(this.exception.getStackTrace()); + exception.setStackTrace(this.exception.getStackTrace()); } -- String s; +- String var4; - try { -- stringwriter = new StringWriter(); -- printwriter = new PrintWriter(stringwriter); -- throwable.printStackTrace(printwriter); -- s = stringwriter.toString(); +- writer = new StringWriter(); +- printWriter = new PrintWriter(writer); +- exception.printStackTrace(printWriter); +- var4 = writer.toString(); - } finally { -- IOUtils.closeQuietly((Writer)stringwriter); -- IOUtils.closeQuietly((Writer)printwriter); +- IOUtils.closeQuietly((Writer)writer); +- IOUtils.closeQuietly((Writer)printWriter); - } - -- return s; -+ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(throwable); +- return var4; ++ return net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(exception); } public String getFriendlyReport(final ReportType reportType, final List extraComments) { diff --git a/patches/minecraft/net/minecraft/CrashReportCategory.java.patch b/patches/minecraft/net/minecraft/CrashReportCategory.java.patch index 1ce817c8dc..1adddf7dcd 100644 --- a/patches/minecraft/net/minecraft/CrashReportCategory.java.patch +++ b/patches/minecraft/net/minecraft/CrashReportCategory.java.patch @@ -1,26 +1,26 @@ --- a/net/minecraft/CrashReportCategory.java +++ b/net/minecraft/CrashReportCategory.java -@@ -114,8 +_,10 @@ - if (astacktraceelement.length <= 0) { +@@ -140,8 +_,10 @@ + if (full.length <= 0) { return 0; } else { -- this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - nestedOffset]; -- System.arraycopy(astacktraceelement, 3 + nestedOffset, this.stackTrace, 0, this.stackTrace.length); -+ int len = astacktraceelement.length - 3 - nestedOffset; -+ if (len <= 0) len = astacktraceelement.length; +- this.stackTrace = new StackTraceElement[full.length - 3 - nestedOffset]; +- System.arraycopy(full, 3 + nestedOffset, this.stackTrace, 0, this.stackTrace.length); ++ int len = full.length - 3 - nestedOffset; ++ if (len <= 0) len = full.length; + this.stackTrace = new StackTraceElement[len]; -+ System.arraycopy(astacktraceelement, astacktraceelement.length - len, this.stackTrace, 0, this.stackTrace.length); ++ System.arraycopy(full, full.length - len, this.stackTrace, 0, this.stackTrace.length); return this.stackTrace.length; } } -@@ -162,16 +_,16 @@ +@@ -188,16 +_,16 @@ if (this.stackTrace != null && this.stackTrace.length > 0) { builder.append("\nStacktrace:"); - -- for (StackTraceElement stacktraceelement : this.stackTrace) { +- for (StackTraceElement element : this.stackTrace) { - builder.append("\n\tat "); -- builder.append(stacktraceelement); +- builder.append(element); - } + builder.append(net.minecraftforge.logging.CrashReportExtender.generateEnhancedStackTrace(this.stackTrace)); } diff --git a/patches/minecraft/net/minecraft/advancements/Advancement.java.patch b/patches/minecraft/net/minecraft/advancements/Advancement.java.patch index 6d5670fd12..4c5e4fafa5 100644 --- a/patches/minecraft/net/minecraft/advancements/Advancement.java.patch +++ b/patches/minecraft/net/minecraft/advancements/Advancement.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/advancements/Advancement.java +++ b/net/minecraft/advancements/Advancement.java -@@ -227,7 +_,11 @@ +@@ -219,7 +_,11 @@ } public AdvancementHolder save(final Consumer output, final String name) { -- AdvancementHolder advancementholder = this.build(Identifier.parse(name)); +- AdvancementHolder advancement = this.build(Identifier.parse(name)); + return save(output, Identifier.parse(name)); + } + + public AdvancementHolder save(Consumer output, Identifier id) { -+ AdvancementHolder advancementholder = this.build(id); - output.accept(advancementholder); - return advancementholder; ++ AdvancementHolder advancement = this.build(id); + output.accept(advancement); + return advancement; } diff --git a/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch b/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch index f626d79953..24a7b0abf3 100644 --- a/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch +++ b/patches/minecraft/net/minecraft/advancements/AdvancementRewards.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/advancements/AdvancementRewards.java +++ b/net/minecraft/advancements/AdvancementRewards.java -@@ -44,6 +_,7 @@ - LootParams lootparams = new LootParams.Builder(serverlevel) +@@ -43,6 +_,7 @@ + LootParams params = new LootParams.Builder(level) .withParameter(LootContextParams.THIS_ENTITY, player) .withParameter(LootContextParams.ORIGIN, player.position()) + .withLuck(player.getLuck()) .create(LootContextParamSets.ADVANCEMENT_REWARD); - boolean flag = false; + boolean changes = false; diff --git a/patches/minecraft/net/minecraft/client/Camera.java.patch b/patches/minecraft/net/minecraft/client/Camera.java.patch index b32b0b843c..47f39b96a9 100644 --- a/patches/minecraft/net/minecraft/client/Camera.java.patch +++ b/patches/minecraft/net/minecraft/client/Camera.java.patch @@ -3,9 +3,9 @@ @@ -217,12 +_,14 @@ return 90.0F; } else { - float f = this.minecraft.options.fov().get().intValue() * Mth.lerp(partialTicks, this.oldFovModifier, this.fovModifier); -- return this.modifyFovBasedOnDeathOrFluid(partialTicks, f); -+ var ret = this.modifyFovBasedOnDeathOrFluid(partialTicks, f); + float fov = this.minecraft.options.fov().get().intValue() * Mth.lerp(partialTicks, this.oldFovModifier, this.fovModifier); +- return this.modifyFovBasedOnDeathOrFluid(partialTicks, fov); ++ var ret = this.modifyFovBasedOnDeathOrFluid(partialTicks, fov); + return net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeFov(this.minecraft.gameRenderer, this, partialTicks, ret, true).getFOV(); } } diff --git a/patches/minecraft/net/minecraft/client/KeyMapping.java.patch b/patches/minecraft/net/minecraft/client/KeyMapping.java.patch index 9a4b06e8b9..345782f4c3 100644 --- a/patches/minecraft/net/minecraft/client/KeyMapping.java.patch +++ b/patches/minecraft/net/minecraft/client/KeyMapping.java.patch @@ -16,11 +16,11 @@ } private static void forAllKeyMappings(final InputConstants.Key key, final Consumer operation) { -- List list = MAP.get(key); -+ List list = MAP.getAll(key); - if (list != null && !list.isEmpty()) { - for (KeyMapping keymapping : list) { - operation.accept(keymapping); +- List keyMappings = MAP.get(key); ++ List keyMappings = MAP.getAll(key); + if (keyMappings != null && !keyMappings.isEmpty()) { + for (KeyMapping keyMapping : keyMappings) { + operation.accept(keyMapping); @@ -106,7 +_,7 @@ } diff --git a/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch b/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch index 71c954bdb0..d25a7a62fc 100644 --- a/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/KeyboardHandler.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/KeyboardHandler.java +++ b/net/minecraft/client/KeyboardHandler.java -@@ -516,7 +_,7 @@ +@@ -514,7 +_,7 @@ if (screen != null) { try { if (action != 1 && action != 2) { @@ -9,16 +9,16 @@ if (options.keyDebugModifier.matches(event)) { this.usedDebugKeyAsModifier = false; } -@@ -525,7 +_,7 @@ +@@ -523,7 +_,7 @@ } } else { screen.afterKeyboardAction(); - if (screen.keyPressed(event)) { + if (net.minecraftforge.client.ForgeHooksClient.onScreenKeyPressed(screen, event)) { if (this.minecraft.screen == null) { - InputConstants.Key inputconstants$key = InputConstants.getKey(event); - KeyMapping.set(inputconstants$key, false); -@@ -597,6 +_,7 @@ + InputConstants.Key key = InputConstants.getKey(event); + KeyMapping.set(key, false); +@@ -595,6 +_,7 @@ } } } @@ -26,12 +26,12 @@ } } -@@ -605,7 +_,7 @@ +@@ -603,7 +_,7 @@ Screen screen = this.minecraft.screen; if (screen != null && this.minecraft.getOverlay() == null) { try { - screen.charTyped(event); + net.minecraftforge.client.ForgeHooksClient.onScreenCharTyped(screen, event); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.forThrowable(throwable, "charTyped event handler"); - screen.fillCrashDetails(crashreport); + } catch (Throwable var8) { + CrashReport report = CrashReport.forThrowable(var8, "charTyped event handler"); + screen.fillCrashDetails(report); diff --git a/patches/minecraft/net/minecraft/client/Minecraft.java.patch b/patches/minecraft/net/minecraft/client/Minecraft.java.patch index 2901bd6cee..7ae0e21049 100644 --- a/patches/minecraft/net/minecraft/client/Minecraft.java.patch +++ b/patches/minecraft/net/minecraft/client/Minecraft.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/Minecraft.java +++ b/net/minecraft/client/Minecraft.java -@@ -272,7 +_,7 @@ +@@ -268,7 +_,7 @@ import org.slf4j.Logger; @OnlyIn(Dist.CLIENT) @@ -9,7 +9,7 @@ private static Minecraft instance; private static final Logger LOGGER = LogUtils.getLogger(); private static final int MAX_TICKS_PER_UPDATE = 10; -@@ -436,7 +_,6 @@ +@@ -432,7 +_,6 @@ } }, Util.nonCriticalIoPool()); LOGGER.info("Setting user: {}", this.user.getName()); @@ -17,8 +17,8 @@ this.demo = gameConfig.game.demo; this.allowsMultiplayer = !gameConfig.game.disableMultiplayer; this.allowsChat = !gameConfig.game.disableChat; -@@ -522,14 +_,14 @@ - LOGGER.error("Couldn't set icon", (Throwable)ioexception); +@@ -518,14 +_,14 @@ + LOGGER.error("Couldn't set icon", (Throwable)var23); } + // FORGE: Move mouse and keyboard handler setup further below @@ -34,7 +34,7 @@ this.resourcePackRepository.reload(); this.options.loadSelectedResourcePacks(this.resourcePackRepository); this.languageManager = new LanguageManager(this.options.languageCode, languageData -> { -@@ -617,6 +_,7 @@ +@@ -613,6 +_,7 @@ this.particleResources = new ParticleResources(); this.resourceManager.registerReloadListener(this.particleResources); this.particleEngine = new ParticleEngine(this.level, this.particleResources); @@ -42,17 +42,17 @@ this.particleResources.onReload(this.particleEngine::clearParticles); this.waypointStyles = new WaypointStyleManager(); this.resourceManager.registerReloadListener(this.waypointStyles); -@@ -638,6 +_,9 @@ +@@ -634,6 +_,9 @@ this.resourceManager.registerReloadListener(this.gpuWarnlistManager); this.resourceManager.registerReloadListener(this.regionalCompliancies); this.gui = new Gui(this); + // FORGE: Moved keyboard and mouse handler setup below ingame gui creation to prevent NPEs in them. + this.mouseHandler.setup(this.window); + this.keyboardHandler.setup(this.window); - RealmsClient realmsclient = RealmsClient.getOrCreate(this); - this.realmsDataFetcher = new RealmsDataFetcher(realmsclient); + RealmsClient realmsClient = RealmsClient.getOrCreate(this); + this.realmsDataFetcher = new RealmsDataFetcher(realmsClient); RenderSystem.setErrorCallback(this::onFullscreenError); -@@ -669,6 +_,7 @@ +@@ -665,6 +_,7 @@ } } @@ -60,34 +60,33 @@ this.window.updateVsync(this.options.enableVsync().get()); this.window.updateRawMouseInput(this.options.rawMouseInput().get()); this.window.setAllowCursorChanges(this.options.allowCursorChanges().get()); -@@ -695,14 +_,16 @@ +@@ -690,14 +_,15 @@ + .createReload(Util.backgroundExecutor().forName("resourceLoad"), this, RESOURCE_RELOAD_INITIAL_TASK, packs); GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS); - Minecraft.GameLoadCookie minecraft$gameloadcookie = new Minecraft.GameLoadCookie(realmsclient, gameConfig.quickPlay); - this.setOverlay( -- new LoadingOverlay(this, reloadinstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, minecraft$gameloadcookie), () -> { -+ net.minecraftforge.fml.loading.ImmediateWindowHandler.loadingOverlay( -+ () -> this, () -> reloadinstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, minecraft$gameloadcookie), () -> { - if (SharedConstants.IS_RUNNING_IN_IDE) { - this.selfTest(); - } + Minecraft.GameLoadCookie loadCookie = new Minecraft.GameLoadCookie(realmsClient, gameConfig.quickPlay); +- this.setOverlay(new LoadingOverlay(this, reloadInstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, loadCookie), () -> { ++ this.setOverlay(net.minecraftforge.fml.loading.ImmediateWindowHandler.loadingOverlay(() -> this, () ->reloadInstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, loadCookie), () -> { + if (SharedConstants.IS_RUNNING_IN_IDE) { + this.selfTest(); + } - this.reloadStateTracker.finishReload(); - this.onResourceLoadFinished(minecraft$gameloadcookie); -- }), false) -+ net.minecraftforge.client.loading.ClientModLoader.completeModLoading(); -+ }), false).get() - ); + this.reloadStateTracker.finishReload(); + this.onResourceLoadFinished(loadCookie); +- }), false)); ++ net.minecraftforge.client.loading.ClientModLoader.completeModLoading(); ++ }), false).get()); this.quickPlayLog = QuickPlayLog.of(gameConfig.quickPlay.logPath()); this.framerateLimitTracker = new FramerateLimitTracker(this.options, this); -@@ -822,6 +_,7 @@ - StringBuilder stringbuilder = new StringBuilder("Minecraft"); + this.fpsPieProfiler = new ContinuousProfiler(Util.timeSource, () -> this.fpsPieRenderTicks, this.framerateLimitTracker::isHeavilyThrottled); +@@ -816,6 +_,7 @@ + StringBuilder builder = new StringBuilder("Minecraft"); if (checkModStatus().shouldReportAsModified()) { - stringbuilder.append("*"); -+ stringbuilder.append(" Forge"); + builder.append("*"); ++ builder.append(" Forge"); } - stringbuilder.append(" "); -@@ -845,6 +_,8 @@ + builder.append(" "); +@@ -839,6 +_,8 @@ } private UserApiService createUserApiService(final YggdrasilAuthenticationService authService, final GameConfig config) { @@ -96,7 +95,7 @@ return config.game.offlineDeveloperMode ? UserApiService.OFFLINE : authService.createUserApiService(config.user.user.getAccessToken()); } -@@ -857,7 +_,7 @@ +@@ -851,7 +_,7 @@ } private void rollbackResourcePacks(final Throwable t, final Minecraft.@Nullable GameLoadCookie loadCookie) { @@ -105,7 +104,7 @@ this.clearResourcePacksOnError(t, null, loadCookie); } else { Util.throwAsRuntime(t); -@@ -1134,12 +_,6 @@ +@@ -1128,12 +_,6 @@ LOGGER.error("setScreen called from non-game thread"); } @@ -118,7 +117,7 @@ if (screen == null) { if (this.clientLevelTeardownInProgress) { throw new IllegalStateException("Trying to return to in-game GUI during disconnection"); -@@ -1158,6 +_,23 @@ +@@ -1152,6 +_,23 @@ } } @@ -142,33 +141,33 @@ this.screen = screen; if (this.screen != null) { this.screen.added(); -@@ -1241,6 +_,7 @@ +@@ -1235,6 +_,7 @@ Util.shutdownExecutors(); RenderSystem.getSamplerCache().close(); RenderSystem.getDevice().close(); + net.minecraftforge.fml.config.ConfigTracker.forceUnload(); - } catch (Throwable throwable) { - LOGGER.error("Shutdown failure!", throwable); - throw throwable; -@@ -1352,7 +_,9 @@ - profilerfiller.popPush("gpuAsync"); + } catch (Throwable var5) { + LOGGER.error("Shutdown failure!", var5); + throw var5; +@@ -1346,7 +_,9 @@ + profiler.popPush("gpuAsync"); RenderSystem.executePendingTasks(); - profilerfiller.pop(); + profiler.pop(); + net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickStart(this.deltaTracker); this.gameRenderer.render(this.deltaTracker, advanceGameTime); + net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderTickEnd(this.deltaTracker); - profilerfiller.push("present"); + profiler.push("present"); if (!this.gameRenderer.getGameRenderState().windowRenderState.isMinimized) { this.mainRenderTarget.blitToScreen(); -@@ -1456,6 +_,7 @@ - this.window.setGuiScale(i); +@@ -1450,6 +_,7 @@ + this.window.setGuiScale(guiScale); if (this.screen != null) { this.screen.resize(this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); + net.minecraftforge.client.ForgeHooksClient.resizeGuiLayers(this, this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight()); } this.mouseHandler.setIgnoreFirstMove(); -@@ -1600,6 +_,7 @@ +@@ -1601,6 +_,7 @@ } public void stop() { @@ -176,29 +175,29 @@ this.running = false; } -@@ -1629,10 +_,18 @@ +@@ -1630,10 +_,18 @@ if (down && this.hitResult != null && this.hitResult.getType() == HitResult.Type.BLOCK) { - BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; - BlockPos blockpos = blockhitresult.getBlockPos(); -- if (!this.level.getBlockState(blockpos).isAir()) { -+ if (!this.level.isEmptyBlock(blockpos)) { + BlockHitResult blockHit = (BlockHitResult)this.hitResult; + BlockPos pos = blockHit.getBlockPos(); +- if (!this.level.getBlockState(pos).isAir()) { ++ if (!this.level.isEmptyBlock(pos)) { + var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(0, this.options.keyAttack, InteractionHand.MAIN_HAND); + if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) { + if (inputEvent.shouldSwingHand()) { -+ this.level.addBreakingBlockEffect(blockpos, blockhitresult); ++ this.level.addBreakingBlockEffect(pos, blockHit); + this.player.swing(InteractionHand.MAIN_HAND); + } + return; + } - Direction direction = blockhitresult.getDirection(); -- if (this.gameMode.continueDestroyBlock(blockpos, direction)) { -- this.level.addBreakingBlockEffect(blockpos, direction); -+ if (this.gameMode.continueDestroyBlock(blockpos, direction) && inputEvent.shouldSwingHand()) { -+ this.level.addBreakingBlockEffect(blockpos, blockhitresult); + Direction direction = blockHit.getDirection(); +- if (this.gameMode.continueDestroyBlock(pos, direction)) { +- this.level.addBreakingBlockEffect(pos, direction); ++ if (this.gameMode.continueDestroyBlock(pos, direction) && inputEvent.shouldSwingHand()) { ++ this.level.addBreakingBlockEffect(pos, blockHit); this.player.swing(InteractionHand.MAIN_HAND); } } -@@ -1675,6 +_,8 @@ +@@ -1676,6 +_,8 @@ this.player.swing(InteractionHand.MAIN_HAND); return true; } else { @@ -206,17 +205,17 @@ + if (!net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) switch (this.hitResult.getType()) { case ENTITY: - AttackRange attackrange = itemstack.get(DataComponents.ATTACK_RANGE); -@@ -1685,7 +_,7 @@ + AttackRange customItemRange = heldItem.get(DataComponents.ATTACK_RANGE); +@@ -1686,7 +_,7 @@ case BLOCK: - BlockHitResult blockhitresult = (BlockHitResult)this.hitResult; - BlockPos blockpos = blockhitresult.getBlockPos(); -- if (!this.level.getBlockState(blockpos).isAir()) { -+ if (!this.level.isEmptyBlock(blockpos)) { - this.gameMode.startDestroyBlock(blockpos, blockhitresult.getDirection()); - if (this.level.getBlockState(blockpos).isAir()) { - flag = true; -@@ -1698,8 +_,10 @@ + BlockHitResult blockHit = (BlockHitResult)this.hitResult; + BlockPos pos = blockHit.getBlockPos(); +- if (!this.level.getBlockState(pos).isAir()) { ++ if (!this.level.isEmptyBlock(pos)) { + this.gameMode.startDestroyBlock(pos, blockHit.getDirection()); + if (this.level.getBlockState(pos).isAir()) { + endAttack = true; +@@ -1699,8 +_,10 @@ } this.player.resetAttackStrengthTicker(); @@ -225,83 +224,83 @@ + if (inputEvent.shouldSwingHand()) this.player.swing(InteractionHand.MAIN_HAND); - return flag; + return endAttack; } -@@ -1716,6 +_,12 @@ +@@ -1717,6 +_,12 @@ } - for (InteractionHand interactionhand : InteractionHand.values()) { -+ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(1, this.options.keyUse, interactionhand); + for (InteractionHand hand : InteractionHand.values()) { ++ var inputEvent = new net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered(1, this.options.keyUse, hand); + if (net.minecraftforge.client.event.InputEvent.InteractionKeyMappingTriggered.BUS.post(inputEvent)) { -+ if (inputEvent.shouldSwingHand()) this.player.swing(interactionhand); ++ if (inputEvent.shouldSwingHand()) this.player.swing(hand); + return; + } + - ItemStack itemstack = this.player.getItemInHand(interactionhand); - if (!itemstack.isItemEnabled(this.level.enabledFeatures())) { + ItemStack heldItem = this.player.getItemInHand(hand); + if (!heldItem.isItemEnabled(this.level.enabledFeatures())) { return; -@@ -1734,7 +_,7 @@ - && this.gameMode.interact(this.player, entity, entityhitresult, interactionhand) instanceof InteractionResult.Success interactionresult$success2 - ) - { -- if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT) { -+ if (interactionresult$success2.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { - this.player.swing(interactionhand); +@@ -1733,7 +_,7 @@ + + if (this.player.isWithinEntityInteractionRange(entity, 0.0) + && this.gameMode.interact(this.player, entity, entityHit, hand) instanceof InteractionResult.Success success) { +- if (success.swingSource() == InteractionResult.SwingSource.CLIENT) { ++ if (success.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { + this.player.swing(hand); } -@@ -1746,7 +_,7 @@ - int i = itemstack.getCount(); - InteractionResult interactionresult = this.gameMode.useItemOn(this.player, interactionhand, blockhitresult); - if (interactionresult instanceof InteractionResult.Success interactionresult$success) { -- if (interactionresult$success.swingSource() == InteractionResult.SwingSource.CLIENT) { -+ if (interactionresult$success.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { - this.player.swing(interactionhand); - if (!itemstack.isEmpty() && (itemstack.getCount() != i || this.player.hasInfiniteMaterials())) { - this.gameRenderer.itemInHandRenderer.itemUsed(interactionhand); -@@ -1762,6 +_,9 @@ +@@ -1745,7 +_,7 @@ + int oldCount = heldItem.getCount(); + InteractionResult useResult = this.gameMode.useItemOn(this.player, hand, blockHit); + if (useResult instanceof InteractionResult.Success success) { +- if (success.swingSource() == InteractionResult.SwingSource.CLIENT) { ++ if (success.swingSource() == InteractionResult.SwingSource.CLIENT && inputEvent.shouldSwingHand()) { + this.player.swing(hand); + if (!heldItem.isEmpty() && (heldItem.getCount() != oldCount || this.player.hasInfiniteMaterials())) { + this.gameRenderer.itemInHandRenderer.itemUsed(hand); +@@ -1761,6 +_,9 @@ } } -+ if (itemstack.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS)) -+ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, interactionhand); ++ if (heldItem.isEmpty() && (this.hitResult == null || this.hitResult.getType() == HitResult.Type.MISS)) ++ net.minecraftforge.event.ForgeEventFactory.onRightClickEmpty(this.player, hand); + - if (!itemstack.isEmpty() - && this.gameMode.useItem(this.player, interactionhand) instanceof InteractionResult.Success interactionresult$success1) { - if (interactionresult$success1.swingSource() == InteractionResult.SwingSource.CLIENT) { -@@ -1791,6 +_,8 @@ + if (!heldItem.isEmpty() && this.gameMode.useItem(this.player, hand) instanceof InteractionResult.Success success) { + if (success.swingSource() == InteractionResult.SwingSource.CLIENT) { + this.player.swing(hand); +@@ -1789,6 +_,8 @@ } - ProfilerFiller profilerfiller = Profiler.get(); + ProfilerFiller profiler = Profiler.get(); + net.minecraftforge.event.ForgeEventFactory.onPreClientTick(); + - profilerfiller.push("gui"); + profiler.push("gui"); this.textInputManager.tick(); this.chatListener.tick(); -@@ -1873,6 +_,7 @@ +@@ -1871,6 +_,7 @@ this.tutorial.tick(); + net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(this.level, () -> true); try { this.level.tick(() -> true); - } catch (Throwable throwable1) { -@@ -1886,6 +_,7 @@ + } catch (Throwable var6) { +@@ -1884,6 +_,7 @@ - throw new ReportedException(crashreport1); + throw new ReportedException(report); } + net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(this.level, () -> true); } - profilerfiller.popPush("animateTick"); -@@ -1910,6 +_,7 @@ - profilerfiller.popPush("keyboard"); + profiler.popPush("animateTick"); +@@ -1908,6 +_,7 @@ + profiler.popPush("keyboard"); this.keyboardHandler.tick(); - profilerfiller.pop(); + profiler.pop(); + net.minecraftforge.event.ForgeEventFactory.onPostClientTick(); } private boolean isLevelRunningNormally() { -@@ -2140,6 +_,7 @@ +@@ -2138,6 +_,7 @@ } public void setLevel(final ClientLevel level) { @@ -309,15 +308,15 @@ this.level = level; this.updateLevelInEngines(level); } -@@ -2201,6 +_,7 @@ - IntegratedServer integratedserver = this.singleplayerServer; +@@ -2199,6 +_,7 @@ + IntegratedServer server = this.singleplayerServer; this.singleplayerServer = null; this.gameRenderer.resetData(); + net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerLogout(this.gameMode, this.player); this.gameMode = null; this.narrator.clear(); this.clientLevelTeardownInProgress = true; -@@ -2208,6 +_,7 @@ +@@ -2206,6 +_,7 @@ try { if (this.level != null) { this.gui.onDisconnected(); @@ -325,19 +324,19 @@ } this.level = null; -@@ -2222,6 +_,7 @@ +@@ -2220,6 +_,7 @@ } - profilerfiller.pop(); + profiler.pop(); + net.minecraftforge.client.ForgeHooksClient.handleClientLevelClosing(this.level); } this.setScreenAndShow(screen); -@@ -2374,6 +_,7 @@ +@@ -2372,6 +_,7 @@ private void pickBlockOrEntity() { if (this.hitResult != null && this.hitResult.getType() != HitResult.Type.MISS) { + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onClickInputPickBlock(this.options.keyPickItem)) return; - boolean flag = this.hasControlDown(); + boolean includeData = this.hasControlDown(); switch (this.hitResult) { - case BlockHitResult blockhitresult: + case BlockHitResult blockHitResult: diff --git a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch index d684bf2620..bcbd48a913 100644 --- a/patches/minecraft/net/minecraft/client/MouseHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/MouseHandler.java.patch @@ -4,65 +4,65 @@ this.activeButton = null; } -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(mousebuttoninfo, action)) return; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPre(buttonInfo, action)) return; if (this.minecraft.getOverlay() == null) { if (this.minecraft.screen == null) { - if (!this.mouseGrabbed && flag) { + if (!this.mouseGrabbed && pressed) { @@ -106,7 +_,7 @@ - && i - this.lastClick.time() < 250L + && currentTime - this.lastClick.time() < 250L && this.lastClick.screen() == screen - && this.lastClickButton == mousebuttonevent.button(); -- if (screen.mouseClicked(mousebuttonevent, flag1)) { -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, d0, d1, mousebuttonevent, flag1)) { - this.lastClick = new MouseHandler.LastClick(i, screen); - this.lastClickButton = mousebuttoninfo.button(); + && this.lastClickButton == event.button(); +- if (screen.mouseClicked(event, doubleClick)) { ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseClicked(screen, xm, ym, event, doubleClick)) { + this.lastClick = new MouseHandler.LastClick(currentTime, screen); + this.lastClickButton = buttonInfo.button(); return; @@ -121,7 +_,7 @@ } } else { try { -- if (screen.mouseReleased(mousebuttonevent)) { -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, d0, d1, mousebuttonevent)) { +- if (screen.mouseReleased(event)) { ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseReleased(screen, xm, ym, event)) { return; } - } catch (Throwable throwable) { + } catch (Throwable var17) { @@ -151,6 +_,7 @@ - KeyMapping.click(inputconstants$key); + KeyMapping.click(mouseKey); } } -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(mousebuttoninfo, action); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseButtonPost(buttonInfo, action); } } @@ -202,7 +_,9 @@ if (this.minecraft.screen != null) { - double d3 = this.getScaledXPos(this.minecraft.getWindow()); - double d4 = this.getScaledYPos(this.minecraft.getWindow()); -- this.minecraft.screen.mouseScrolled(d3, d4, d1, d2); -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, d3, d4, d1, d2)) return; -+ if (this.minecraft.screen.mouseScrolled(d3, d4, d1, d2)) return; -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, d3, d4, d1, d2); + double xm = this.getScaledXPos(this.minecraft.getWindow()); + double ym = this.getScaledYPos(this.minecraft.getWindow()); +- this.minecraft.screen.mouseScrolled(xm, ym, scaledXOffset, scaledYOffset); ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPre(this.minecraft.screen, xm, ym, scaledXOffset, scaledYOffset)) return; ++ if (this.minecraft.screen.mouseScrolled(xm, ym, scaledXOffset, scaledYOffset)) return; ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenMouseScrollPost(this.minecraft.screen, xm, ym, scaledXOffset, scaledYOffset); this.minecraft.screen.afterMouseAction(); } else if (this.minecraft.player != null) { - Vector2i vector2i = this.scrollWheelHandler.onMouseScroll(d1, d2); + Vector2i wheelXY = this.scrollWheelHandler.onMouseScroll(scaledXOffset, scaledYOffset); @@ -211,6 +_,7 @@ } - int i = vector2i.y == 0 ? -vector2i.x : vector2i.y; -+ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, d1, d2)) return; + int wheel = wheelXY.y == 0 ? -wheelXY.x : wheelXY.y; ++ if (net.minecraftforge.client.event.ForgeEventFactoryClient.onMouseScroll(this, scaledXOffset, scaledYOffset)) return; if (this.minecraft.player.isSpectator()) { if (this.minecraft.gui.getSpectatorGui().isMenuActive()) { - this.minecraft.gui.getSpectatorGui().onMouseScrolled(-i); -@@ -315,7 +_,7 @@ - double d5 = getScaledYPos(window, this.accumulatedDY); + this.minecraft.gui.getSpectatorGui().onMouseScrolled(-wheel); +@@ -317,7 +_,7 @@ + double dy = getScaledYPos(window, this.accumulatedDY); try { -- screen.mouseDragged(new MouseButtonEvent(d2, d3, this.activeButton), d4, d5); -+ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, new MouseButtonEvent(d2, d3, this.activeButton), d4, d5); - } catch (Throwable throwable) { - CrashReport crashreport1 = CrashReport.forThrowable(throwable, "mouseDragged event handler"); - screen.fillCrashDetails(crashreport1); -@@ -400,6 +_,14 @@ +- screen.mouseDragged(new MouseButtonEvent(xm, ym, this.activeButton), dx, dy); ++ net.minecraftforge.client.ForgeHooksClient.onScreenMouseDrag(screen, new MouseButtonEvent(xm, ym, this.activeButton), dx, dy); + } catch (Throwable var19) { + CrashReport report = CrashReport.forThrowable(var19, "mouseDragged event handler"); + screen.fillCrashDetails(report); +@@ -402,6 +_,14 @@ public double ypos() { return this.ypos; diff --git a/patches/minecraft/net/minecraft/client/Options.java.patch b/patches/minecraft/net/minecraft/client/Options.java.patch index 69156039ac..c06d1f0058 100644 --- a/patches/minecraft/net/minecraft/client/Options.java.patch +++ b/patches/minecraft/net/minecraft/client/Options.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/Options.java +++ b/net/minecraft/client/Options.java -@@ -921,6 +_,7 @@ +@@ -929,6 +_,7 @@ ); public boolean syncWrites; public boolean startedCleanly = true; @@ -8,15 +8,15 @@ public static boolean isSoundDeviceDefault(final String deviceName) { return deviceName.equals(""); -@@ -1396,6 +_,7 @@ +@@ -1404,6 +_,7 @@ } public Options(final Minecraft minecraft, final File workingDirectory) { + setForgeKeybindProperties(); this.minecraft = minecraft; this.optionsFile = new File(workingDirectory, "options.txt"); - boolean flag = Runtime.getRuntime().maxMemory() >= 1000000000L; -@@ -1548,15 +_,28 @@ + boolean largeDistances = Runtime.getRuntime().maxMemory() >= 1000000000L; +@@ -1556,15 +_,28 @@ this.startedCleanly = access.process("startedCleanly", this.startedCleanly); access.process("musicToast", this.musicToast); access.process("musicFrequency", this.musicFrequency); @@ -26,27 +26,27 @@ + // FORGE: split off to allow reloading keys after mod loading is done + private void processOptionsKeysOnly(Options.FieldAccess access) { - for (KeyMapping keymapping : this.keyMappings) { -- String s = keymapping.saveString(); -+ String s = keymapping.saveString() + (keymapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keymapping.getKeyModifier() : ""); - String s1 = access.process("key_" + keymapping.getName(), s); - if (!s.equals(s1)) { - keymapping.setKey(InputConstants.getKey(s1)); -+ if (s1.indexOf(':') != -1) { -+ String[] pts = s1.split(":"); -+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0])); + for (KeyMapping keyMapping : this.keyMappings) { +- String currentValue = keyMapping.saveString(); ++ String currentValue = keyMapping.saveString() + (keyMapping.getKeyModifier() != net.minecraftforge.client.settings.KeyModifier.NONE ? ":" + keyMapping.getKeyModifier() : ""); + String newValue = access.process("key_" + keyMapping.getName(), currentValue); + if (!currentValue.equals(newValue)) { + keyMapping.setKey(InputConstants.getKey(newValue)); ++ if (newValue.indexOf(':') != -1) { ++ String[] pts = newValue.split(":"); ++ keyMapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.valueFromString(pts[1]), InputConstants.getKey(pts[0])); + } else { -+ keymapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(s1)); ++ keyMapping.setKeyModifierAndCode(net.minecraftforge.client.settings.KeyModifier.NONE, InputConstants.getKey(newValue)); + } } } + } + private void processOptionsEnd(Options.FieldAccess access) { - for (SoundSource soundsource : SoundSource.values()) { - access.process("soundCategory_" + soundsource.getName(), this.soundSourceVolumes.get(soundsource)); + for (SoundSource source : SoundSource.values()) { + access.process("soundCategory_" + source.getName(), this.soundSourceVolumes.get(source)); } -@@ -1571,6 +_,10 @@ +@@ -1579,6 +_,10 @@ } public void load() { @@ -57,64 +57,64 @@ try { if (!this.optionsFile.exists()) { return; -@@ -1590,7 +_,8 @@ +@@ -1598,7 +_,8 @@ } - final CompoundTag compoundtag1 = this.dataFix(compoundtag); + final CompoundTag options = this.dataFix(rawOptions); - this.processOptions( + java.util.function.Consumer processor = limited ? this::processOptionsKeysOnly : this::processOptions; + processor.accept( new Options.FieldAccess() { { Objects.requireNonNull(Options.this); -@@ -1672,6 +_,17 @@ +@@ -1680,6 +_,17 @@ ); - compoundtag1.getString("fullscreenResolution").ifPresent(fullscreenResolution -> this.fullscreenVideoModeString = fullscreenResolution); + options.getString("fullscreenResolution").ifPresent(fullscreenResolution -> this.fullscreenVideoModeString = fullscreenResolution); KeyMapping.resetMapping(); + + if (limited) { + this.unknownKeys.clear(); + } else { + var knownKeys = Arrays.stream(this.keyMappings).map(k -> "key_" + k.getName()).collect(Collectors.toSet()); -+ for (var entry : compoundtag1.entrySet()) { ++ for (var entry : options.entrySet()) { + if (entry.getKey().startsWith("key_") && entry.getValue().asString().isPresent() && !knownKeys.contains(entry.getKey())) + this.unknownKeys.put(entry.getKey(), entry.getValue().asString().get()); + } + } + - } catch (Exception exception) { - LOGGER.error("Failed to load options", (Throwable)exception); + } catch (Exception var7) { + LOGGER.error("Failed to load options", (Throwable)var7); } -@@ -1699,6 +_,7 @@ +@@ -1707,6 +_,7 @@ public void save() { - try (final PrintWriter printwriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) { - printwriter.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version()); + try (final PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.optionsFile), StandardCharsets.UTF_8))) { + writer.println("version:" + SharedConstants.getCurrentVersion().dataVersion().version()); + var seen = new java.util.HashSet(); this.processOptions( new Options.FieldAccess() { { -@@ -1706,6 +_,7 @@ +@@ -1714,6 +_,7 @@ } public void writePrefix(final String name) { + seen.add(name); - printwriter.print(name); - printwriter.print(':'); + writer.print(name); + writer.print(':'); } -@@ -1761,6 +_,12 @@ - if (s != null) { - printwriter.println("fullscreenResolution:" + s); +@@ -1769,6 +_,12 @@ + if (fullscreenVideoModeString != null) { + writer.println("fullscreenResolution:" + fullscreenVideoModeString); } + // Forge add any unknown keys so that Mods can add keybindings between vanilla loading/saving its config. + for (var entry : this.unknownKeys.entrySet()) { + if (!seen.contains(entry.getKey())) -+ printwriter.println(entry.getKey() + ":" + entry.getValue()); ++ writer.println(entry.getKey() + ":" + entry.getValue()); + } + - } catch (Exception exception) { - LOGGER.error("Failed to save options", (Throwable)exception); + } catch (Exception var6) { + LOGGER.error("Failed to save options", (Throwable)var6); } -@@ -1798,6 +_,7 @@ +@@ -1806,6 +_,7 @@ } public void broadcastOptions() { @@ -122,7 +122,7 @@ if (this.minecraft.player != null) { this.minecraft.player.connection.broadcastClientInformation(this.buildPlayerInformation()); } -@@ -1915,6 +_,23 @@ +@@ -1923,6 +_,23 @@ public static Component genericValueLabel(final Component caption, final int value) { return genericValueLabel(caption, Component.literal(Integer.toString(value))); diff --git a/patches/minecraft/net/minecraft/client/Screenshot.java.patch b/patches/minecraft/net/minecraft/client/Screenshot.java.patch index 4a51109d7f..cce47db65c 100644 --- a/patches/minecraft/net/minecraft/client/Screenshot.java.patch +++ b/patches/minecraft/net/minecraft/client/Screenshot.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/Screenshot.java +++ b/net/minecraft/client/Screenshot.java -@@ -45,6 +_,13 @@ - file2 = new File(file1, forceName); +@@ -44,6 +_,13 @@ + file = new File(picDir, forceName); } -+ var event = new net.minecraftforge.client.event.ScreenshotEvent(image, file2); ++ var event = new net.minecraftforge.client.event.ScreenshotEvent(image, file); + if (net.minecraftforge.client.event.ScreenshotEvent.BUS.post(event)) { + callback.accept(event.getCancelMessage()); + return; @@ -14,19 +14,19 @@ Util.ioPool() .execute( () -> { -@@ -52,10 +_,13 @@ - NativeImage nativeimage = image; +@@ -51,10 +_,13 @@ + NativeImage twrVar0$ = image; try { -- image.writeToFile(file2); -- Component component = Component.literal(file2.getName()) +- image.writeToFile(file); +- Component component = Component.literal(file.getName()) + image.writeToFile(outputFile); + Component component = Component.literal(outputFile.getName()) .withStyle(ChatFormatting.UNDERLINE) - .withStyle(s -> s.withClickEvent(new ClickEvent.OpenFile(file2.getAbsoluteFile()))); + .withStyle(s -> s.withClickEvent(new ClickEvent.OpenFile(file.getAbsoluteFile()))); + if (event.getResultMessage() != null) + callback.accept(event.getResultMessage()); + else callback.accept(Component.translatable("screenshot.success", component)); - } catch (Throwable throwable1) { + } catch (Throwable var7) { if (image != null) { diff --git a/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch b/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch index 196aa01623..7f5ef9ee48 100644 --- a/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch +++ b/patches/minecraft/net/minecraft/client/color/block/BlockColors.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/client/color/block/BlockColors.java +++ b/net/minecraft/client/color/block/BlockColors.java @@ -45,6 +_,7 @@ - blockcolors.register(List.of(BlockTintSources.constant(-2046180)), Blocks.ATTACHED_MELON_STEM, Blocks.ATTACHED_PUMPKIN_STEM); - blockcolors.register(List.of(BlockTintSources.stem()), Blocks.MELON_STEM, Blocks.PUMPKIN_STEM); - blockcolors.register(List.of(BlockTintSources.constant(-9321636, -14647248)), Blocks.LILY_PAD); -+ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(blockcolors); - return blockcolors; + colors.register(List.of(BlockTintSources.constant(-2046180)), Blocks.ATTACHED_MELON_STEM, Blocks.ATTACHED_PUMPKIN_STEM); + colors.register(List.of(BlockTintSources.stem()), Blocks.MELON_STEM, Blocks.PUMPKIN_STEM); + colors.register(List.of(BlockTintSources.constant(-9321636, -14647248)), Blocks.LILY_PAD); ++ net.minecraftforge.client.ForgeHooksClient.onBlockColorsInit(colors); + return colors; } @@ -57,6 +_,8 @@ - return layer >= list.size() ? null : list.get(layer); + return layer >= layers.size() ? null : layers.get(layer); } + /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterColorHandlersEvent.Block} */ diff --git a/patches/minecraft/net/minecraft/client/data/Main.java.patch b/patches/minecraft/net/minecraft/client/data/Main.java.patch index 78a59e26e1..e270fa81b4 100644 --- a/patches/minecraft/net/minecraft/client/data/Main.java.patch +++ b/patches/minecraft/net/minecraft/client/data/Main.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/client/data/Main.java +++ b/net/minecraft/client/data/Main.java @@ -28,13 +_,18 @@ - OptionSpec optionspec1 = optionparser.accepts("client", "Include client generators"); - OptionSpec optionspec2 = optionparser.accepts("all", "Include all generators"); - OptionSpec optionspec3 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); -+ OptionSpec inputSpec = optionparser.accepts("input", "Input folder").withRequiredArg(); -+ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(optionparser, true); - OptionSet optionset = optionparser.parse(args); -- if (!optionset.has(optionspec) && optionset.hasOptions()) { -+ if (!optionset.has(optionspec) && optionset.hasOptions() && loader.hasArgs(optionset)) { -+ var input = optionset.valuesOf(inputSpec).stream().map(Paths::get).toList(); - Path path = Paths.get(optionspec3.value(optionset)); - boolean flag = optionset.has(optionspec2); - boolean flag1 = flag || optionset.has(optionspec1); + OptionSpec clientOption = parser.accepts("client", "Include client generators"); + OptionSpec allOption = parser.accepts("all", "Include all generators"); + OptionSpec outputOption = parser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); ++ OptionSpec inputSpec = parser.accepts("input", "Input folder").withRequiredArg(); ++ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(parser, true); + OptionSet optionSet = parser.parse(args); +- if (!optionSet.has(helpOption) && optionSet.hasOptions()) { ++ if (!optionSet.has(helpOption) && optionSet.hasOptions() && loader.hasArgs(optionSet)) { ++ var input = optionSet.valuesOf(inputSpec).stream().map(Paths::get).toList(); + Path output = Paths.get(outputOption.value(optionSet)); + boolean allOptions = optionSet.has(allOption); + boolean client = allOptions || optionSet.has(clientOption); Bootstrap.bootStrap(); ClientBootstrap.bootstrap(); -+ if (!loader.run(optionset, path, input, flag, flag1, flag, flag)) ++ if (!loader.run(optionSet, output, input, allOptions, client, allOptions, allOptions)) + return; - DataGenerator datagenerator = new DataGenerator.Cached(path, SharedConstants.getCurrentVersion(), true); - addClientProviders(datagenerator, flag1); - datagenerator.run(); + DataGenerator generator = new DataGenerator.Cached(output, SharedConstants.getCurrentVersion(), true); + addClientProviders(generator, client); + generator.run(); diff --git a/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch b/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch index a69c0a5c8c..3d412eead5 100644 --- a/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch +++ b/patches/minecraft/net/minecraft/client/data/models/ItemModelGenerators.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/data/models/ItemModelGenerators.java +++ b/net/minecraft/client/data/models/ItemModelGenerators.java -@@ -922,6 +_,9 @@ +@@ -909,6 +_,9 @@ this.declareCustomModelItem(Items.COD); this.declareCustomModelItem(Items.FEATHER); this.declareCustomModelItem(Items.LEAD); diff --git a/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch b/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch index 381d3e129f..e0dd6d0676 100644 --- a/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch +++ b/patches/minecraft/net/minecraft/client/data/models/ModelProvider.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/client/data/models/ModelProvider.java +++ b/net/minecraft/client/data/models/ModelProvider.java -@@ -44,11 +_,11 @@ +@@ -43,11 +_,11 @@ @Override public CompletableFuture run(final CachedOutput cache) { -- ModelProvider.ItemInfoCollector modelprovider$iteminfocollector = new ModelProvider.ItemInfoCollector(); -- ModelProvider.BlockStateGeneratorCollector modelprovider$blockstategeneratorcollector = new ModelProvider.BlockStateGeneratorCollector(); -+ ModelProvider.ItemInfoCollector modelprovider$iteminfocollector = new ModelProvider.ItemInfoCollector(this::getKnownItems); -+ ModelProvider.BlockStateGeneratorCollector modelprovider$blockstategeneratorcollector = new ModelProvider.BlockStateGeneratorCollector(this::getKnownBlocks); - ModelProvider.SimpleModelCollector modelprovider$simplemodelcollector = new ModelProvider.SimpleModelCollector(); -- new BlockModelGenerators(modelprovider$blockstategeneratorcollector, modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); -- new ItemModelGenerators(modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); -+ getBlockModelGenerators(modelprovider$blockstategeneratorcollector, modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); -+ getItemModelGenerators(modelprovider$iteminfocollector, modelprovider$simplemodelcollector).run(); - modelprovider$blockstategeneratorcollector.validate(); - modelprovider$iteminfocollector.finalizeAndValidate(); +- ModelProvider.ItemInfoCollector itemModels = new ModelProvider.ItemInfoCollector(); +- ModelProvider.BlockStateGeneratorCollector blockStateGenerators = new ModelProvider.BlockStateGeneratorCollector(); ++ ModelProvider.ItemInfoCollector itemModels = new ModelProvider.ItemInfoCollector(this::getKnownItems); ++ ModelProvider.BlockStateGeneratorCollector blockStateGenerators = new ModelProvider.BlockStateGeneratorCollector(this::getKnownBlocks); + ModelProvider.SimpleModelCollector simpleModels = new ModelProvider.SimpleModelCollector(); +- new BlockModelGenerators(blockStateGenerators, itemModels, simpleModels).run(); +- new ItemModelGenerators(itemModels, simpleModels).run(); ++ getBlockModelGenerators(blockStateGenerators, itemModels, simpleModels).run(); ++ getItemModelGenerators(itemModels, simpleModels).run(); + blockStateGenerators.validate(); + itemModels.finalizeAndValidate(); return CompletableFuture.allOf( -@@ -58,6 +_,22 @@ +@@ -57,6 +_,22 @@ ); } @@ -39,7 +39,7 @@ @Override public final String getName() { return "Model Definitions"; -@@ -66,6 +_,15 @@ +@@ -65,6 +_,15 @@ @OnlyIn(Dist.CLIENT) public static class BlockStateGeneratorCollector implements Consumer { private final Map generators = new HashMap<>(); @@ -55,17 +55,17 @@ public void accept(final BlockModelDefinitionGenerator generator) { Block block = generator.block(); -@@ -76,8 +_,7 @@ +@@ -75,8 +_,7 @@ } public void validate() { -- List list = BuiltInRegistries.BLOCK +- List missingDefinitions = BuiltInRegistries.BLOCK - .listElements() -+ List list = known.get().map(Block::builtInRegistryHolder) ++ List missingDefinitions = known.get().map(Block::builtInRegistryHolder) .filter(e -> !this.generators.containsKey(e.value())) .map(e -> e.key().identifier()) .toList(); -@@ -97,6 +_,15 @@ +@@ -96,6 +_,15 @@ public static class ItemInfoCollector implements ItemModelOutput { private final Map itemInfos = new HashMap<>(); private final Map copies = new HashMap<>(); @@ -81,7 +81,7 @@ @Override public void accept(final Item item, final ItemModel.Unbaked model, final ClientItem.Properties properties) { -@@ -115,7 +_,7 @@ +@@ -114,7 +_,7 @@ this.copies.put(acceptor, donor); } @@ -89,23 +89,23 @@ + public void generateDefaultBlockModels() { BuiltInRegistries.ITEM.forEach(item -> { if (!this.copies.containsKey(item)) { - if (item instanceof BlockItem blockitem && !this.itemInfos.containsKey(blockitem)) { -@@ -124,6 +_,8 @@ + if (item instanceof BlockItem blockItem && !this.itemInfos.containsKey(blockItem)) { +@@ -123,6 +_,8 @@ } } }); + } + public void finalizeAndValidate() { this.copies.forEach((acceptor, donor) -> { - ClientItem clientitem = this.itemInfos.get(donor); - if (clientitem == null) { -@@ -132,8 +_,8 @@ - this.register(acceptor, clientitem); + ClientItem donorInfo = this.itemInfos.get(donor); + if (donorInfo == null) { +@@ -131,8 +_,8 @@ + this.register(acceptor, donorInfo); } }); -- List list = BuiltInRegistries.ITEM +- List missingDefinitions = BuiltInRegistries.ITEM - .listElements() -+ List list = known.get() ++ List missingDefinitions = known.get() + .map(item -> item.builtInRegistryHolder()) .filter(e -> !this.itemInfos.containsKey(e.value())) .map(e -> e.key().identifier()) diff --git a/patches/minecraft/net/minecraft/client/gui/Gui.java.patch b/patches/minecraft/net/minecraft/client/gui/Gui.java.patch index 0515b1e903..fb02ee442c 100644 --- a/patches/minecraft/net/minecraft/client/gui/Gui.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/Gui.java.patch @@ -29,32 +29,32 @@ this.extractCameraOverlays(graphics, deltaTracker); this.extractCrosshair(graphics, deltaTracker); @@ -385,7 +_,7 @@ - int i = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window)); - int j = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window)); + int mouseX = Mth.floor(this.minecraft.mouseHandler.getScaledXPos(window)); + int mouseY = Mth.floor(this.minecraft.mouseHandler.getScaledYPos(window)); graphics.nextStratum(); -- this.chat.extractRenderState(graphics, this.getFont(), this.tickCount, i, j, ChatComponent.DisplayMode.BACKGROUND, false); -+ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(graphics, this.chat, window, i, j, this.tickCount, this.getFont()); +- this.chat.extractRenderState(graphics, this.getFont(), this.tickCount, mouseX, mouseY, ChatComponent.DisplayMode.BACKGROUND, false); ++ net.minecraftforge.client.ForgeHooksClient.onCustomizeChatEvent(graphics, this.chat, window, mouseX, mouseY, this.tickCount, this.getFont()); } } -@@ -475,6 +_,8 @@ +@@ -478,6 +_,8 @@ - for (MobEffectInstance mobeffectinstance : Ordering.natural().reverse().sortedCopy(collection)) { - Holder holder = mobeffectinstance.getEffect(); -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); -+ if (!renderer.isVisibleInGui(mobeffectinstance)) continue; - if (mobeffectinstance.showIcon()) { - int k = graphics.guiWidth(); - int l = 1; -@@ -505,6 +_,7 @@ + for (MobEffectInstance instance : Ordering.natural().reverse().sortedCopy(activeEffects)) { + Holder effect = instance.getEffect(); ++ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(instance); ++ if (!renderer.isVisibleInGui(instance)) continue; + if (instance.showIcon()) { + int x = graphics.guiWidth(); + int y = 1; +@@ -508,6 +_,7 @@ } } -+ if (renderer.extractGuiIcon(mobeffectinstance, this, graphics, k, l, 0, f)) continue; - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(holder), k + 3, l + 3, 18, 18, ARGB.white(f)); ++ if (renderer.extractGuiIcon(instance, this, graphics, x, y, 0, alpha)) continue; + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, getMobEffectSprite(effect), x + 3, y + 3, 18, 18, ARGB.white(alpha)); } } -@@ -605,6 +_,10 @@ +@@ -610,15 +_,23 @@ } public void extractSelectedItemName(final GuiGraphicsExtractor graphics) { @@ -63,40 +63,39 @@ + + public void renderSelectedItemName(final GuiGraphicsExtractor graphics, int yShift) { if (this.toolHighlightTimer > 0 && !this.lastToolHighlight.isEmpty()) { - MutableComponent mutablecomponent = Component.empty() - .append(this.lastToolHighlight.getHoverName()) -@@ -613,9 +_,13 @@ - mutablecomponent.withStyle(ChatFormatting.ITALIC); + MutableComponent str = Component.empty().append(this.lastToolHighlight.getHoverName()).withStyle(this.lastToolHighlight.getRarity().color()); + if (this.lastToolHighlight.has(DataComponents.CUSTOM_NAME)) { + str.withStyle(ChatFormatting.ITALIC); } -- int i = this.getFont().width(mutablecomponent); -+ Component highlightTip = this.lastToolHighlight.getHighlightTip(mutablecomponent); +- int strWidth = this.getFont().width(str); ++ Component highlightTip = this.lastToolHighlight.getHighlightTip(str); + Font font = net.minecraftforge.client.extensions.common.IClientItemExtensions.of(lastToolHighlight).getFont(lastToolHighlight, net.minecraftforge.client.extensions.common.IClientItemExtensions.FontContext.SELECTED_ITEM_NAME); + if (font == null) + font = this.getFont(); -+ int i = font.width(highlightTip); - int j = (graphics.guiWidth() - i) / 2; -- int k = graphics.guiHeight() - 59; -+ int k = graphics.guiHeight() - Math.max(yShift, 59); ++ int strWidth = font.width(highlightTip); + int x = (graphics.guiWidth() - strWidth) / 2; +- int y = graphics.guiHeight() - 59; ++ int y = graphics.guiHeight() - Math.max(yShift, 59); if (!this.minecraft.gameMode.canHurtPlayer()) { - k += 14; + y += 14; } -@@ -626,7 +_,7 @@ +@@ -629,7 +_,7 @@ } - if (l > 0) { -- graphics.textWithBackdrop(this.getFont(), mutablecomponent, j, k, i, ARGB.white(l)); -+ graphics.textWithBackdrop(font, highlightTip, j, k, i, ARGB.white(l)); + if (alpha > 0) { +- graphics.textWithBackdrop(this.getFont(), str, x, y, strWidth, ARGB.white(alpha)); ++ graphics.textWithBackdrop(font, highlightTip, x, y, strWidth, ARGB.white(alpha)); } } } -@@ -1165,7 +_,9 @@ +@@ -1195,7 +_,9 @@ this.toolHighlightTimer = 0; } else if (this.lastToolHighlight.isEmpty() - || !itemstack.is(this.lastToolHighlight.getItem()) -- || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName())) { -+ || !itemstack.getHoverName().equals(this.lastToolHighlight.getHoverName()) -+ || !itemstack.getHighlightTip(itemstack.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName())) + || !selected.is(this.lastToolHighlight.getItem()) +- || !selected.getHoverName().equals(this.lastToolHighlight.getHoverName())) { ++ || !selected.getHoverName().equals(this.lastToolHighlight.getHoverName()) ++ || !selected.getHighlightTip(selected.getHoverName()).equals(lastToolHighlight.getHighlightTip(lastToolHighlight.getHoverName())) + ) { this.toolHighlightTimer = (int)(40.0 * this.minecraft.options.notificationDisplayTime().get()); } else if (this.toolHighlightTimer > 0) { diff --git a/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch b/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch index 3022b44b22..4d5898a6c8 100644 --- a/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/GuiGraphicsExtractor.java.patch @@ -9,15 +9,15 @@ private static final int EXTRA_SPACE_AFTER_FIRST_TOOLTIP_LINE = 2; private final Minecraft minecraft; private final Matrix3x2fStack pose; -@@ -867,6 +_,7 @@ - CrashReport crashreport = CrashReport.forThrowable(throwable, "Rendering item"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Item being rendered"); - crashreportcategory.setDetail("Item Type", () -> String.valueOf(itemStack.getItem())); -+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); - crashreportcategory.setDetail("Item Components", () -> String.valueOf(itemStack.getComponents())); - crashreportcategory.setDetail("Item Foil", () -> String.valueOf(itemStack.hasFoil())); - throw new ReportedException(crashreport); -@@ -893,6 +_,7 @@ +@@ -914,6 +_,7 @@ + CrashReport report = CrashReport.forThrowable(var11, "Rendering item"); + CrashReportCategory category = report.addCategory("Item being rendered"); + category.setDetail("Item Type", () -> String.valueOf(itemStack.getItem())); ++ category.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); + category.setDetail("Item Components", () -> String.valueOf(itemStack.getComponents())); + category.setDetail("Item Foil", () -> String.valueOf(itemStack.hasFoil())); + throw new ReportedException(report); +@@ -940,6 +_,7 @@ this.itemCooldown(itemStack, x, y); this.itemCount(font, itemStack, x, y, countText); this.pose.popMatrix(); @@ -25,7 +25,7 @@ } } -@@ -1069,16 +_,25 @@ +@@ -1112,16 +_,25 @@ this.setTooltipForNextFrame(this.minecraft.font, formattedCharSequences, DefaultTooltipPositioner.INSTANCE, x, y, false); } @@ -51,17 +51,20 @@ public void setTooltipForNextFrame( final Font font, final List texts, -@@ -1087,8 +_,7 @@ +@@ -1130,11 +_,7 @@ final int yo, final @Nullable Identifier style ) { -- List list = texts.stream().map(Component::getVisualOrderText).map(ClientTooltipComponent::create).collect(Util.toMutableList()); -- optionalImage.ifPresent(image -> list.add(list.isEmpty() ? 0 : 1, ClientTooltipComponent.create(image))); -+ List list = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, texts, optionalImage, xo, guiWidth(), guiHeight(), font); - this.setTooltipForNextFrameInternal(font, list, xo, yo, DefaultTooltipPositioner.INSTANCE, style, false); +- List components = texts.stream() +- .map(Component::getVisualOrderText) +- .map(ClientTooltipComponent::create) +- .collect(Util.toMutableList()); +- optionalImage.ifPresent(image -> components.add(components.isEmpty() ? 0 : 1, ClientTooltipComponent.create(image))); ++ List components = net.minecraftforge.client.ForgeHooksClient.gatherTooltipComponents(this.tooltipStack, texts, optionalImage, xo, guiWidth(), guiHeight(), font); + this.setTooltipForNextFrameInternal(font, components, xo, yo, DefaultTooltipPositioner.INSTANCE, style, false); } -@@ -1116,7 +_,22 @@ +@@ -1162,7 +_,22 @@ } public void setComponentTooltipForNextFrame(final Font font, final List lines, final int xo, final int yo) { @@ -85,7 +88,7 @@ } public void setComponentTooltipForNextFrame(final Font font, final List lines, final int xo, final int yo, final @Nullable Identifier style) { -@@ -1167,10 +_,16 @@ +@@ -1213,10 +_,16 @@ ) { if (!lines.isEmpty()) { if (this.deferredTooltip == null || replaceExisting) { @@ -103,7 +106,7 @@ public void tooltip( final Font font, -@@ -1178,13 +_,16 @@ +@@ -1224,13 +_,16 @@ final int xo, final int yo, final ClientTooltipPositioner positioner, @@ -113,48 +116,48 @@ ) { + var preEvent = net.minecraftforge.client.ForgeHooksClient.onRenderTooltipPre(itemstack, this, xo, yo, guiWidth(), guiHeight(), lines, font, positioner, style); + if (preEvent == null) return; - int i = 0; - int j = lines.size() == 1 ? -2 : 0; + int textWidth = 0; + int tempHeight = lines.size() == 1 ? -2 : 0; - for (ClientTooltipComponent clienttooltipcomponent : lines) { -- int k = clienttooltipcomponent.getWidth(font); -+ int k = clienttooltipcomponent.getWidth(preEvent.getFont()); - if (k > i) { - i = k; + for (ClientTooltipComponent line : lines) { +- int lineWidth = line.getWidth(font); ++ int lineWidth = line.getWidth(preEvent.getFont()); + if (lineWidth > textWidth) { + textWidth = lineWidth; } -@@ -1194,25 +_,25 @@ +@@ -1240,25 +_,25 @@ - int l1 = i; - int i2 = j; -- Vector2ic vector2ic = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), xo, yo, i, j); -+ Vector2ic vector2ic = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), i, j); - int l = vector2ic.x(); - int i1 = vector2ic.y(); + int w = textWidth; + int h = tempHeight; +- Vector2ic positionedTooltip = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), xo, yo, textWidth, tempHeight); ++ Vector2ic positionedTooltip = positioner.positionTooltip(this.guiWidth(), this.guiHeight(), preEvent.getX(), preEvent.getY(), textWidth, tempHeight); + int x = positionedTooltip.x(); + int y = positionedTooltip.y(); this.pose.pushMatrix(); -- TooltipRenderUtil.extractTooltipBackground(this, l, i1, i, j, style); -+ TooltipRenderUtil.extractTooltipBackground(this, l, i1, i, j, preEvent.getBackground()); - int j1 = i1; +- TooltipRenderUtil.extractTooltipBackground(this, x, y, textWidth, tempHeight, style); ++ TooltipRenderUtil.extractTooltipBackground(this, x, y, textWidth, tempHeight, preEvent.getBackground()); + int localY = y; - for (int k1 = 0; k1 < lines.size(); k1++) { - ClientTooltipComponent clienttooltipcomponent1 = lines.get(k1); -- clienttooltipcomponent1.extractText(this, font, l, j1); -- j1 += clienttooltipcomponent1.getHeight(font) + (k1 == 0 ? 2 : 0); -+ clienttooltipcomponent1.extractText(this, preEvent.getFont(), l, j1); -+ j1 += clienttooltipcomponent1.getHeight(preEvent.getFont()) + (k1 == 0 ? 2 : 0); + for (int i = 0; i < lines.size(); i++) { + ClientTooltipComponent line = lines.get(i); +- line.extractText(this, font, x, localY); +- localY += line.getHeight(font) + (i == 0 ? 2 : 0); ++ line.extractText(this, preEvent.getFont(), x, localY); ++ localY += line.getHeight(preEvent.getFont()) + (i == 0 ? 2 : 0); } - j1 = i1; + localY = y; - for (int j2 = 0; j2 < lines.size(); j2++) { - ClientTooltipComponent clienttooltipcomponent2 = lines.get(j2); -- clienttooltipcomponent2.extractImage(font, l, j1, l1, i2, this); -- j1 += clienttooltipcomponent2.getHeight(font) + (j2 == 0 ? 2 : 0); -+ clienttooltipcomponent2.extractImage(preEvent.getFont(), l, j1, l1, i2, this); -+ j1 += clienttooltipcomponent2.getHeight(preEvent.getFont()) + (j2 == 0 ? 2 : 0); + for (int i = 0; i < lines.size(); i++) { + ClientTooltipComponent line = lines.get(i); +- line.extractImage(font, x, localY, w, h, this); +- localY += line.getHeight(font) + (i == 0 ? 2 : 0); ++ line.extractImage(preEvent.getFont(), x, localY, w, h, this); ++ localY += line.getHeight(preEvent.getFont()) + (i == 0 ? 2 : 0); } this.pose.popMatrix(); -@@ -1287,6 +_,14 @@ +@@ -1333,6 +_,14 @@ private ActiveTextCollector.Parameters createDefaultTextParameters(final float opacity) { return new ActiveTextCollector.Parameters(new Matrix3x2f(this.pose), opacity, this.scissorStack.peek()); diff --git a/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch b/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch index bdd5333e13..aa89778180 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/BossHealthOverlay.java.patch @@ -2,19 +2,19 @@ +++ b/net/minecraft/client/gui/components/BossHealthOverlay.java @@ -68,13 +_,16 @@ - for (LerpingBossEvent lerpingbossevent : this.events.values()) { - int k = i / 2 - 91; -+ var event = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(graphics, this.minecraft.getWindow(), lerpingbossevent, k, j, 10 + this.minecraft.font.lineHeight); -+ if (event != null) { - this.extractBar(graphics, k, j, lerpingbossevent); - Component component = lerpingbossevent.getName(); - int l = this.minecraft.font.width(component); - int i1 = i / 2 - l / 2; - int j1 = j - 9; - graphics.text(this.minecraft.font, component, i1, j1, -1); -- j += 10 + 9; + for (LerpingBossEvent event : this.events.values()) { + int xLeft = screenWidth / 2 - 91; ++ var progressEvent = net.minecraftforge.client.ForgeHooksClient.onCustomizeBossEventProgress(graphics, this.minecraft.getWindow(), event, xLeft, yOffset, 10 + this.minecraft.font.lineHeight); ++ if (progressEvent != null) { + this.extractBar(graphics, xLeft, yOffset, event); + Component msg = event.getName(); + int width = this.minecraft.font.width(msg); + int x = screenWidth / 2 - width / 2; + int y = yOffset - 9; + graphics.text(this.minecraft.font, msg, x, y, -1); +- yOffset += 10 + 9; + } -+ j += event.getIncrement(); - if (j >= graphics.guiHeight() / 3) { ++ yOffset += progressEvent.getIncrement(); + if (yOffset >= graphics.guiHeight() / 3) { break; } diff --git a/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch b/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch index 4021699366..f4e973747c 100644 --- a/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java.patch @@ -2,9 +2,9 @@ +++ b/net/minecraft/client/gui/components/debug/DebugEntryLookingAtEntity.java @@ -29,6 +_,7 @@ if (entity != null) { - list.add(ChatFormatting.UNDERLINE + "Targeted Entity"); - list.add(entity.typeHolder().getRegisteredName()); -+ entity.getType().builtInRegistryHolder().tags().forEach(t -> list.add("#" + t.location())); + result.add(ChatFormatting.UNDERLINE + "Targeted Entity"); + result.add(entity.typeHolder().getRegisteredName()); ++ entity.getType().builtInRegistryHolder().tags().forEach(t -> result.add("#" + t.location())); } - displayer.addToGroup(GROUP, list); + displayer.addToGroup(GROUP, result); diff --git a/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch b/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch index 9437099d7e..17ad64af07 100644 --- a/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/render/GuiRenderer.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/client/gui/render/GuiRenderer.java +++ b/net/minecraft/client/gui/render/GuiRenderer.java -@@ -131,6 +_,7 @@ - builder.put((Class)pictureinpicturerenderer.getRenderStateClass(), pictureinpicturerenderer); +@@ -130,6 +_,7 @@ + builder.put((Class)pictureInPictureRenderer.getRenderStateClass(), pictureInPictureRenderer); } + net.minecraftforge.client.ForgeHooksClient.onRegisterPictureInPictureRenderers(pictureInPictureRenderers, bufferSource, builder); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch index 3e3207b92d..06989a69b4 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/ConnectScreen.java.patch @@ -3,7 +3,7 @@ @@ -114,6 +_,8 @@ } - if (optional.isEmpty()) { + if (resolvedAddress.isEmpty()) { + ConnectScreen.LOGGER.error("Couldn't connect to server: Unknown host \"{}\"", hostAndPort.getHost()); + net.minecraftforge.network.DualStackUtils.logInitialPreferences(); minecraft.execute( diff --git a/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch index e8ad174ffb..7ee979b614 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/LoadingOverlay.java.patch @@ -8,24 +8,24 @@ + @Override public void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a) { - int i = graphics.guiWidth(); + int width = graphics.guiWidth(); @@ -103,6 +_,7 @@ - f2 = 1.0F; + logoAlpha = 1.0F; } -+ if (extractContentRenderState(graphics, f2)) { - int k2 = (int)(graphics.guiWidth() * 0.5); - int i1 = (int)(graphics.guiHeight() * 0.5); - double d0 = Math.min(graphics.guiWidth() * 0.75, (double)graphics.guiHeight()) * 0.25; -@@ -118,6 +_,7 @@ - if (f < 1.0F) { - this.extractProgressBar(graphics, i / 2 - k1, i2 - 5, i / 2 + k1, i2 + 5, 1.0F - Mth.clamp(f, 0.0F, 1.0F)); ++ if (extractContentRenderState(graphics, logoAlpha)) { + int contentX = (int)(graphics.guiWidth() * 0.5); + int logoY = (int)(graphics.guiHeight() * 0.5); + double logoHeight = Math.min(graphics.guiWidth() * 0.75, (double)graphics.guiHeight()) * 0.25; +@@ -148,6 +_,7 @@ + graphics, width / 2 - logoWidthHalf, barY - 5, width / 2 + logoWidthHalf, barY + 5, 1.0F - Mth.clamp(fadeOutAnim, 0.0F, 1.0F) + ); } + } - if (f >= 2.0F) { + if (fadeOutAnim >= 2.0F) { this.minecraft.setOverlay(null); -@@ -127,6 +_,7 @@ +@@ -157,6 +_,7 @@ @Override public void tick() { if (this.fadeOutStart == -1L && this.reload.isDone() && this.isReadyToFadeOut()) { @@ -33,8 +33,8 @@ try { this.reload.checkExceptions(); this.onFinish.accept(Optional.empty()); -@@ -134,7 +_,6 @@ - this.onFinish.accept(Optional.of(throwable)); +@@ -164,7 +_,6 @@ + this.onFinish.accept(Optional.of(var2)); } - this.fadeOutStart = Util.getMillis(); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch index 0c0ff84c91..b68e34708a 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/MenuScreens.java.patch @@ -8,13 +8,13 @@ + } + + public static java.util.Optional> getScreenFactory(@Nullable MenuType type, Minecraft minecraft, int containerId, Component title) { - MenuScreens.ScreenConstructor screenconstructor = getConstructor(type); - if (screenconstructor == null) { + MenuScreens.ScreenConstructor constructor = getConstructor(type); + if (constructor == null) { LOGGER.warn("Failed to create screen for menu type: {}", BuiltInRegistries.MENU.getKey(type)); + return java.util.Optional.empty(); } else { -- screenconstructor.fromPacket(title, type, minecraft, containerId); -+ return java.util.Optional.of(screenconstructor); +- constructor.fromPacket(title, type, minecraft, containerId); ++ return java.util.Optional.of(constructor); } } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch index 358831c2fc..d78d0a9314 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/PauseScreen.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/gui/screens/PauseScreen.java +++ b/net/minecraft/client/gui/screens/PauseScreen.java -@@ -104,6 +_,7 @@ +@@ -102,6 +_,7 @@ } else { - gridlayout$rowhelper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this))); + helper.addChild(this.openScreenButton(PLAYER_REPORTING, () -> new SocialInteractionsScreen(this))); } -+ gridlayout$rowhelper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2); ++ helper.addChild(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))).width(BUTTON_WIDTH_FULL).build(), 2); - this.disconnectButton = gridlayout$rowhelper.addChild( + this.disconnectButton = helper.addChild( Button.builder( diff --git a/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch index d6a50d3fc9..6bea4f3d44 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/TitleScreen.java.patch @@ -9,47 +9,47 @@ public TitleScreen() { this(false); @@ -105,11 +_,15 @@ - int j = this.width - i - 2; - int k = 24; - int l = this.height / 4 + 48; + int copyrightX = this.width - copyrightWidth - 2; + int spacing = 24; + int topPos = this.height / 4 + 48; + Button modButton = null; if (this.minecraft.isDemo()) { - l = this.createDemoMenuOptions(l, 24); + topPos = this.createDemoMenuOptions(topPos, 24); } else { - l = this.createNormalMenuOptions(l, 24); + topPos = this.createNormalMenuOptions(topPos, 24); + modButton = this.addRenderableWidget(Button.builder(Component.translatable("fml.menu.mods"), button -> this.minecraft.setScreen(new net.minecraftforge.client.gui.ModListScreen(this))) -+ .pos(this.width / 2 - 100, l).size(98, 20).build()); ++ .pos(this.width / 2 - 100, topPos).size(98, 20).build()); } + modUpdateNotification = net.minecraftforge.client.gui.TitleScreenModUpdateIndicator.init(this, modButton); - l = this.createTestWorldButton(l, 24); - SpriteIconButton spriteiconbutton = this.addRenderableWidget( -@@ -176,7 +_,7 @@ - }).bounds(this.width / 2 - 100, i = topPos + spacing, 200, 20).tooltip(tooltip).build()).active = flag; + topPos = this.createTestWorldButton(topPos, 24); + SpriteIconButton language = this.addRenderableWidget( +@@ -182,7 +_,7 @@ + }).bounds(this.width / 2 - 100, var6 = topPos + spacing, 200, 20).tooltip(tooltip).build()).active = multiplayerAllowed; this.addRenderableWidget( Button.builder(Component.translatable("menu.online"), button -> this.minecraft.setScreen(new RealmsMainScreen(this))) -- .bounds(this.width / 2 - 100, topPos = i + spacing, 200, 20) -+ .bounds(this.width / 2 + 2, topPos = i + spacing, 98, 20) +- .bounds(this.width / 2 - 100, topPos = var6 + spacing, 200, 20) ++ .bounds(this.width / 2 + 2, topPos = var6 + spacing, 98, 20) .tooltip(tooltip) .build() ) -@@ -304,9 +_,18 @@ - s = s + I18n.get("menu.modded"); +@@ -310,9 +_,18 @@ + versionString = versionString + I18n.get("menu.modded"); } -- graphics.text(this.font, s, 2, this.height - 10, ARGB.white(f)); -+ final float f_f = f; +- graphics.text(this.font, versionString, 2, this.height - 10, ARGB.white(widgetFade)); ++ final float widgetFade_f = widgetFade; + net.minecraftforge.internal.BrandingControl.forEachLine(true, true, (brd, brdline) -> -+ graphics.text(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), ARGB.color(f_f, -1)) ++ graphics.text(this.font, brd, 2, this.height - ( 10 + brdline * (this.font.lineHeight + 1)), ARGB.color(widgetFade_f, -1)) + ); + + net.minecraftforge.internal.BrandingControl.forEachAboveCopyrightLine((brd, brdline) -> -+ graphics.text(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), ARGB.color(f_f, -1)) ++ graphics.text(this.font, brd, this.width - font.width(brd), this.height - (10 + (brdline + 1) * ( this.font.lineHeight + 1)), ARGB.color(widgetFade_f, -1)) + ); + - if (this.realmsNotificationsEnabled() && f >= 1.0F) { + if (this.realmsNotificationsEnabled() && widgetFade >= 1.0F) { this.realmsNotificationsScreen.extractRenderState(graphics, mouseX, mouseY, a); -+ if (f >= 1.0f) this.modUpdateNotification.extractRenderState(graphics, mouseX, mouseY, a); ++ if (widgetFade >= 1.0f) this.modUpdateNotification.extractRenderState(graphics, mouseX, mouseY, a); } } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch index 63f7d1273d..8522fc3e7f 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementTab.java.patch @@ -27,11 +27,11 @@ @@ -155,8 +_,8 @@ return null; } else { - for (AdvancementTabType advancementtabtype : AdvancementTabType.values()) { -- if (index < advancementtabtype.getMax()) { -- return new AdvancementTab(minecraft, screen, advancementtabtype, index, root, optional.get()); -+ if ((index % AdvancementTabType.MAX_TABS) < advancementtabtype.getMax()) { -+ return new AdvancementTab(minecraft, screen, advancementtabtype, index % AdvancementTabType.MAX_TABS, index / AdvancementTabType.MAX_TABS, root, optional.get()); + for (AdvancementTabType type : AdvancementTabType.values()) { +- if (index < type.getMax()) { +- return new AdvancementTab(minecraft, screen, type, index, root, display.get()); ++ if ((index % AdvancementTabType.MAX_TABS) < type.getMax()) { ++ return new AdvancementTab(minecraft, screen, type, index % AdvancementTabType.MAX_TABS, index / AdvancementTabType.MAX_TABS, root, display.get()); } - index -= advancementtabtype.getMax(); + index -= type.getMax(); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch index 43a5f3f861..9516a4603f 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java +++ b/net/minecraft/client/gui/screens/advancements/AdvancementsScreen.java -@@ -51,6 +_,7 @@ +@@ -50,6 +_,7 @@ private final Map tabs = Maps.newLinkedHashMap(); private @Nullable AdvancementTab selectedTab; private boolean isScrolling; @@ -8,7 +8,7 @@ public AdvancementsScreen(final ClientAdvancements advancements) { this(advancements, null); -@@ -64,6 +_,19 @@ +@@ -63,6 +_,19 @@ @Override protected void init() { @@ -28,33 +28,33 @@ this.layout.addTitleHeader(TITLE, this.font); this.tabs.clear(); this.selectedTab = null; -@@ -106,7 +_,7 @@ - int j = (this.height - 140) / 2; +@@ -105,7 +_,7 @@ + int yo = (this.height - 140) / 2; - for (AdvancementTab advancementtab : this.tabs.values()) { -- if (advancementtab.isMouseOver(i, j, event.x(), event.y())) { -+ if (advancementtab.getPage() == tabPage && advancementtab.isMouseOver(i, j, event.x(), event.y())) { - this.advancements.setSelectedTab(advancementtab.getRootNode().holder(), true); + for (AdvancementTab tab : this.tabs.values()) { +- if (tab.isMouseOver(xo, yo, event.x(), event.y())) { ++ if (tab.getPage() == tabPage && tab.isMouseOver(xo, yo, event.x(), event.y())) { + this.advancements.setSelectedTab(tab.getRootNode().holder(), true); break; } -@@ -197,10 +_,12 @@ +@@ -196,10 +_,12 @@ graphics.blit(RenderPipelines.GUI_TEXTURED, WINDOW_LOCATION, xo, yo, 0.0F, 0.0F, 252, 140, 256, 256); if (this.tabs.size() > 1) { - for (AdvancementTab advancementtab : this.tabs.values()) { -+ if (advancementtab.getPage() == tabPage) - advancementtab.extractTab(graphics, xo, yo, mouseX, mouseY, advancementtab == this.selectedTab); + for (AdvancementTab tab : this.tabs.values()) { ++ if (tab.getPage() == tabPage) + tab.extractTab(graphics, xo, yo, mouseX, mouseY, tab == this.selectedTab); } - for (AdvancementTab advancementtab1 : this.tabs.values()) { -+ if (advancementtab1.getPage() == tabPage) - advancementtab1.extractIcon(graphics, xo, yo); + for (AdvancementTab tab : this.tabs.values()) { ++ if (tab.getPage() == tabPage) + tab.extractIcon(graphics, xo, yo); } } -@@ -219,6 +_,7 @@ +@@ -218,6 +_,7 @@ if (this.tabs.size() > 1) { - for (AdvancementTab advancementtab : this.tabs.values()) { -+ if (advancementtab.getPage() == tabPage) - if (advancementtab.isMouseOver(xo, yo, mouseX, mouseY)) { - graphics.setTooltipForNextFrame(this.font, advancementtab.getTitle(), mouseX, mouseY); + for (AdvancementTab tab : this.tabs.values()) { ++ if (tab.getPage() == tabPage) + if (tab.isMouseOver(xo, yo, mouseX, mouseY)) { + graphics.setTooltipForNextFrame(this.font, tab.getTitle(), mouseX, mouseY); } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch index 6e2473bea1..67832b00f1 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java.patch @@ -1,34 +1,31 @@ --- a/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java +++ b/net/minecraft/client/gui/screens/inventory/AbstractContainerScreen.java @@ -111,6 +_,7 @@ - int i = this.leftPos; - int j = this.topPos; + int xo = this.leftPos; + int yo = this.topPos; super.extractRenderState(graphics, mouseX, mouseY, a); + net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderBackground(this, graphics, mouseX, mouseY); graphics.pose().pushMatrix(); - graphics.pose().translate(i, j); + graphics.pose().translate(xo, yo); this.extractLabels(graphics, mouseX, mouseY); @@ -122,6 +_,7 @@ - if (slot != null && slot != this.hoveredSlot) { - this.onStopHovering(slot); + if (previouslyHoveredSlot != null && previouslyHoveredSlot != this.hoveredSlot) { + this.onStopHovering(previouslyHoveredSlot); } + net.minecraftforge.client.event.ForgeEventFactoryClient.onContainerRenderForeground(this, graphics, mouseX, mouseY); graphics.pose().popMatrix(); } -@@ -203,9 +_,9 @@ - this.font, - this.getTooltipFromContainerItem(itemstack), - itemstack.getTooltipImage(), -+ itemstack, - mouseX, -- mouseY, -- itemstack.get(DataComponents.TOOLTIP_STYLE) -+ mouseY +@@ -200,7 +_,7 @@ + ItemStack item = this.hoveredSlot.getItem(); + if (this.menu.getCarried().isEmpty() || this.showTooltipWithItemInHand(item)) { + graphics.setTooltipForNextFrame( +- this.font, this.getTooltipFromContainerItem(item), item.getTooltipImage(), mouseX, mouseY, item.get(DataComponents.TOOLTIP_STYLE) ++ this.font, this.getTooltipFromContainerItem(item), item.getTooltipImage(), item, mouseX, mouseY ); } } -@@ -221,7 +_,8 @@ +@@ -216,7 +_,8 @@ private void extractFloatingItem(final GuiGraphicsExtractor graphics, final ItemStack carried, final int x, final int y, final @Nullable String itemCount) { graphics.item(carried, x, y); @@ -38,75 +35,75 @@ } protected void extractLabels(final GuiGraphicsExtractor graphics, final int xm, final int ym) { -@@ -319,7 +_,8 @@ +@@ -316,7 +_,8 @@ if (super.mouseClicked(event, doubleClick)) { return true; } else { -- boolean flag = this.minecraft.options.keyPickItem.matchesMouse(event) && this.minecraft.player.hasInfiniteMaterials(); +- boolean cloning = this.minecraft.options.keyPickItem.matchesMouse(event) && this.minecraft.player.hasInfiniteMaterials(); + var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(event.button()); -+ boolean flag = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey) && this.minecraft.player.hasInfiniteMaterials(); ++ boolean cloning = this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey) && this.minecraft.player.hasInfiniteMaterials(); Slot slot = this.getHoveredSlot(event.x(), event.y()); this.doubleclick = this.lastClickSlot == slot && doubleClick; this.skipNextRelease = false; -@@ -329,6 +_,7 @@ - int i = this.leftPos; - int j = this.topPos; - boolean flag1 = this.hasClickedOutside(event.x(), event.y(), i, j); -+ if (slot != null) flag1 = false; // Forge, prevent dropping of items through slots outside of GUI boundaries - int k = -1; +@@ -326,6 +_,7 @@ + int xo = this.leftPos; + int yo = this.topPos; + boolean clickedOutside = this.hasClickedOutside(event.x(), event.y(), xo, yo); ++ if (slot != null) clickedOutside = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + int slotId = -1; if (slot != null) { - k = slot.index; -@@ -354,7 +_,7 @@ + slotId = slot.index; +@@ -351,7 +_,7 @@ } } else if (!this.isQuickCrafting) { if (this.menu.getCarried().isEmpty()) { -- if (flag) { +- if (cloning) { + if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(slot, k, event.button(), ContainerInput.CLONE); + this.slotClicked(slot, slotId, event.button(), ContainerInput.CLONE); } else { - boolean flag2 = k != -999 && event.hasShiftDown(); -@@ -378,7 +_,7 @@ + boolean quickKey = slotId != -999 && event.hasShiftDown(); +@@ -375,7 +_,7 @@ this.quickCraftingType = 0; } else if (event.button() == 1) { this.quickCraftingType = 1; -- } else if (flag) { +- } else if (cloning) { + } else if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { this.quickCraftingType = 2; } } -@@ -448,10 +_,13 @@ +@@ -445,10 +_,13 @@ @Override public boolean mouseReleased(final MouseButtonEvent event) { + super.mouseReleased(event); //Forge, Call parent to release buttons Slot slot = this.getHoveredSlot(event.x(), event.y()); - int i = this.leftPos; - int j = this.topPos; - boolean flag = this.hasClickedOutside(event.x(), event.y(), i, j); -+ if (slot != null) flag = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + int xo = this.leftPos; + int yo = this.topPos; + boolean clickedOutside = this.hasClickedOutside(event.x(), event.y(), xo, yo); ++ if (slot != null) clickedOutside = false; // Forge, prevent dropping of items through slots outside of GUI boundaries + var mouseKey = com.mojang.blaze3d.platform.InputConstants.Type.MOUSE.getOrCreate(event.button()); - int k = -1; + int slotId = -1; if (slot != null) { - k = slot.index; -@@ -468,7 +_,7 @@ - if (slot1 != null - && slot1.mayPickup(this.minecraft.player) - && slot1.hasItem() -- && slot1.container == slot.container -+ && slot1.isSameInventory(slot) - && AbstractContainerMenu.canItemQuickReplace(slot1, this.lastQuickMoved, true)) { - this.slotClicked(slot1, slot1.index, event.button(), ContainerInput.QUICK_MOVE); + slotId = slot.index; +@@ -465,7 +_,7 @@ + if (target != null + && target.mayPickup(this.minecraft.player) + && target.hasItem() +- && target.container == slot.container ++ && target.isSameInventory(slot) + && AbstractContainerMenu.canItemQuickReplace(target, this.lastQuickMoved, true)) { + this.slotClicked(target, target.index, event.button(), ContainerInput.QUICK_MOVE); } -@@ -527,7 +_,7 @@ +@@ -524,7 +_,7 @@ } else if (this.isQuickCrafting && !this.quickCraftSlots.isEmpty()) { this.quickCraftToSlots(); } else if (!this.menu.getCarried().isEmpty()) { - if (this.minecraft.options.keyPickItem.matchesMouse(event)) { + if (this.minecraft.options.keyPickItem.isActiveAndMatches(mouseKey)) { - this.slotClicked(slot, k, event.button(), ContainerInput.CLONE); + this.slotClicked(slot, slotId, event.button(), ContainerInput.CLONE); } else { - boolean flag1 = k != -999 && event.hasShiftDown(); -@@ -598,7 +_,7 @@ + boolean quickKey = slotId != -999 && event.hasShiftDown(); +@@ -595,7 +_,7 @@ public boolean keyPressed(final KeyEvent event) { if (super.keyPressed(event)) { return true; @@ -115,7 +112,7 @@ this.onClose(); return true; } else { -@@ -696,6 +_,13 @@ +@@ -693,6 +_,13 @@ super.onClose(); } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch index dd485d7950..b9d7663b0d 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/CreativeModeInventoryScreen.java.patch @@ -11,7 +11,7 @@ super(new CreativeModeInventoryScreen.ItemPickerMenu(player), player.getInventory(), CommonComponents.EMPTY, 195, 136); @@ -164,7 +_,7 @@ private void refreshCurrentTabContents(final Collection displayList) { - int i = this.menu.getRowIndexForScroll(this.scrollOffs); + int oldRowIndex = this.menu.getRowIndexForScroll(this.scrollOffs); this.menu.items.clear(); - if (selectedTab.getType() == CreativeModeTab.Type.SEARCH) { + if (selectedTab.hasSearchBar()) { @@ -63,7 +63,7 @@ + } else if (!selectedTab.hasSearchBar()) { return false; } else { - String s = this.searchBox.getValue(); + String oldContents = this.searchBox.getValue(); @@ -405,7 +_,7 @@ @Override public boolean keyPressed(final KeyEvent event) { @@ -80,20 +80,20 @@ + if (!selectedTab.hasSearchBar()) return; this.menu.items.clear(); this.visibleTags.clear(); - String s = this.searchBox.getValue(); + String searchTerm = this.searchBox.getValue(); @@ -453,10 +_,10 @@ - SearchTree searchtree; - if (s.startsWith("#")) { - s = s.substring(1); -- searchtree = sessionsearchtrees.creativeTagSearch(); -+ searchtree = sessionsearchtrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab)); - this.updateVisibleTags(s); + SearchTree tree; + if (searchTerm.startsWith("#")) { + searchTerm = searchTerm.substring(1); +- tree = searchTrees.creativeTagSearch(); ++ tree = searchTrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getTagSearchKey(selectedTab)); + this.updateVisibleTags(searchTerm); } else { -- searchtree = sessionsearchtrees.creativeNameSearch(); -+ searchtree = sessionsearchtrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab)); +- tree = searchTrees.creativeNameSearch(); ++ tree = searchTrees.getSearchTree(net.minecraftforge.client.CreativeModeTabSearchRegistry.getNameSearchKey(selectedTab)); } - this.menu.items.addAll(searchtree.search(s.toLowerCase(Locale.ROOT))); + this.menu.items.addAll(tree.search(searchTerm.toLowerCase(Locale.ROOT))); @@ -484,7 +_,7 @@ @Override protected void extractLabels(final GuiGraphicsExtractor graphics, final int xm, final int ym) { @@ -104,22 +104,22 @@ } @@ -494,7 +_,7 @@ - double d0 = event.x() - this.leftPos; - double d1 = event.y() - this.topPos; + double xm = event.x() - this.leftPos; + double ym = event.y() - this.topPos; -- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (this.checkTabClicked(creativemodetab, d0, d1)) { +- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { + if (this.checkTabClicked(tab, xm, ym)) { return true; } @@ -516,7 +_,7 @@ - double d1 = event.y() - this.topPos; + double ym = event.y() - this.topPos; this.scrolling = false; -- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (this.checkTabClicked(creativemodetab, d0, d1)) { - this.selectTab(creativemodetab); +- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { + if (this.checkTabClicked(tab, xm, ym)) { + this.selectTab(tab); return true; @@ -610,13 +_,15 @@ this.originalSlots = null; @@ -130,7 +130,7 @@ this.searchBox.setVisible(true); this.searchBox.setCanLoseFocus(false); this.searchBox.setFocused(true); - if (creativemodetab != tab) { + if (oldTab != tab) { this.searchBox.setValue(""); } + this.searchBox.setWidth(selectedTab.getSearchBarWidth()); @@ -142,7 +142,7 @@ this.effects.extractRenderState(graphics, mouseX, mouseY); super.extractRenderState(graphics, mouseX, mouseY, a); -- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { +- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { + if (this.pages.size() != 1) { + Component page = Component.literal(String.format("%d / %d", this.pages.indexOf(this.currentPage) + 1, this.pages.size())); + graphics.pose().pushMatrix(); @@ -150,39 +150,39 @@ + graphics.pose().popMatrix(); + } + -+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (this.checkTabHovering(graphics, creativemodetab, mouseX, mouseY)) { ++ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { + if (this.checkTabHovering(graphics, tab, mouseX, mouseY)) { break; } @@ -701,7 +_,7 @@ public List getTooltipFromContainerItem(final ItemStack itemStack) { - boolean flag = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot; - boolean flag1 = selectedTab.getType() == CreativeModeTab.Type.CATEGORY; -- boolean flag2 = selectedTab.getType() == CreativeModeTab.Type.SEARCH; -+ boolean flag2 = selectedTab.hasSearchBar(); - TooltipFlag.Default tooltipflag$default = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL; - TooltipFlag tooltipflag = flag ? tooltipflag$default.asCreative() : tooltipflag$default; - List list = itemStack.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipflag); + boolean isCreativeSlot = this.hoveredSlot != null && this.hoveredSlot instanceof CreativeModeInventoryScreen.CustomCreativeSlot; + boolean isSingleCategoryTab = selectedTab.getType() == CreativeModeTab.Type.CATEGORY; +- boolean isSearchTab = selectedTab.getType() == CreativeModeTab.Type.SEARCH; ++ boolean isSearchTab = selectedTab.hasSearchBar(); + TooltipFlag.Default originalTooltipStyle = this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL; + TooltipFlag tooltipStyle = isCreativeSlot ? originalTooltipStyle.asCreative() : originalTooltipStyle; + List originalLines = itemStack.getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, tooltipStyle); @@ -722,7 +_,7 @@ int i = 1; - for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -- if (creativemodetab.getType() != CreativeModeTab.Type.SEARCH && creativemodetab.contains(itemStack)) { -+ if (!creativemodetab.hasSearchBar() && creativemodetab.contains(itemStack)) { - list1.add(i++, creativemodetab.getDisplayName().copy().withStyle(ChatFormatting.BLUE)); + for (CreativeModeTab tab : CreativeModeTabs.tabs()) { +- if (tab.getType() != CreativeModeTab.Type.SEARCH && tab.contains(itemStack)) { ++ if (!tab.hasSearchBar() && tab.contains(itemStack)) { + linesToDisplay.add(i++, tab.getDisplayName().copy().withStyle(ChatFormatting.BLUE)); } } @@ -735,7 +_,7 @@ public void extractBackground(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a) { super.extractBackground(graphics, mouseX, mouseY, a); -- for (CreativeModeTab creativemodetab : CreativeModeTabs.tabs()) { -+ for (CreativeModeTab creativemodetab : currentPage.getVisibleTabs()) { - if (creativemodetab != selectedTab) { - this.extractTabButton(graphics, mouseX, mouseY, creativemodetab); +- for (CreativeModeTab tab : CreativeModeTabs.tabs()) { ++ for (CreativeModeTab tab : currentPage.getVisibleTabs()) { + if (tab != selectedTab) { + this.extractTabButton(graphics, mouseX, mouseY, tab); } @@ -770,6 +_,7 @@ - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, identifier, j, k + (int)((i - k - 17) * this.scrollOffs), 12, 15); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, sprite, xscr, yscr + (int)((yscr2 - yscr - 17) * this.scrollOffs), 12, 15); } + if (currentPage.getVisibleTabs().contains(selectedTab)) //Forge: only display tab selection when the selected tab is on the current page @@ -193,39 +193,39 @@ } private int getTabX(final CreativeModeTab tab) { -- int i = tab.column(); -+ int i = currentPage.getColumn(tab); - int j = 27; - int k = 27 * i; +- int pos = tab.column(); ++ int pos = currentPage.getColumn(tab); + int spacing = 27; + int x = 27 * pos; if (tab.isAlignedRight()) { @@ -791,7 +_,7 @@ private int getTabY(final CreativeModeTab tab) { - int i = 0; + int y = 0; - if (tab.row() == CreativeModeTab.Row.TOP) { + if (currentPage.isTop(tab)) { - i -= 32; + y -= 32; } else { - i += this.imageHeight; + y += this.imageHeight; @@ -819,8 +_,8 @@ protected void extractTabButton(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final CreativeModeTab tab) { - boolean flag = tab == selectedTab; -- boolean flag1 = tab.row() == CreativeModeTab.Row.TOP; -- int i = tab.column(); -+ boolean flag1 = currentPage.isTop(tab); -+ int i = currentPage.getColumn(tab); - int j = this.leftPos + this.getTabX(tab); - int k = this.topPos - (flag1 ? 28 : -(this.imageHeight - 4)); - Identifier[] aidentifier; + boolean selected = tab == selectedTab; +- boolean isTop = tab.row() == CreativeModeTab.Row.TOP; +- int pos = tab.column(); ++ boolean isTop = currentPage.isTop(tab); ++ int pos = currentPage.getColumn(tab); + int x = this.leftPos + this.getTabX(tab); + int y = this.topPos - (isTop ? 28 : -(this.imageHeight - 4)); + Identifier[] sprites; @@ -834,6 +_,7 @@ graphics.requestCursor(CursorTypes.POINTING_HAND); } + com.mojang.blaze3d.opengl.GlStateManager._enableBlend(); //Forge: Make sure blend is enabled else tabs show a white border. - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, aidentifier[Mth.clamp(i, 0, aidentifier.length)], j, k, 26, 32); - int l = j + 13 - 8; - int i1 = k + 16 - 8 + (flag1 ? 1 : -1); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, sprites[Mth.clamp(pos, 0, sprites.length)], x, y, 26, 32); + int iconX = x + 13 - 8; + int iconY = y + 16 - 8 + (isTop ? 1 : -1); @@ -870,6 +_,14 @@ } } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch index 515c9a4b75..38a927f73f 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java.patch @@ -1,39 +1,39 @@ --- a/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java +++ b/net/minecraft/client/gui/screens/inventory/EffectsInInventory.java @@ -47,12 +_,16 @@ - int j = this.screen.width - i; - Collection collection = this.minecraft.player.getActiveEffects(); - if (!collection.isEmpty() && j >= 32) { -- int k = j >= 120 ? j - 7 : 32; -+ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenEffectSize(this.screen, j, j < 120, i); + int availableWidth = this.screen.width - xo; + Collection activeEffects = this.minecraft.player.getActiveEffects(); + if (!activeEffects.isEmpty() && availableWidth >= 32) { +- int maxWidth = availableWidth >= 120 ? availableWidth - 7 : 32; ++ var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onScreenEffectSize(this.screen, availableWidth, availableWidth < 120, xo); + if (event == null) return; -+ int k = !event.isCompact() ? j - 7 : 32; -+ i = event.getHorizontalOffset(); - int l = 33; - if (collection.size() > 5) { - l = 132 / (collection.size() - 1); ++ int maxWidth = !event.isCompact() ? availableWidth - 7 : 32; ++ xo = event.getHorizontalOffset(); + int yStep = 33; + if (activeEffects.size() > 5) { + yStep = 132 / (activeEffects.size() - 1); } -+ Iterable iterable = collection.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().toList(); - this.extractEffects(graphics, collection, i, l, mouseX, mouseY, k); ++ Iterable iterable = activeEffects.stream().filter(net.minecraftforge.client.ForgeHooksClient::shouldRenderEffect).sorted().toList(); + this.extractEffects(graphics, activeEffects, xo, yStep, mouseX, mouseY, maxWidth); } } @@ -72,6 +_,11 @@ - for (MobEffectInstance mobeffectinstance : iterable) { - boolean flag = mobeffectinstance.isAmbient(); -+ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(mobeffectinstance); -+ if (renderer.extractInventory(mobeffectinstance, this, graphics, x0, i, 0)) { -+ i += yStep; + for (MobEffectInstance effect : sortedEffects) { + boolean isAmbient = effect.isAmbient(); ++ var renderer = net.minecraftforge.client.extensions.common.IClientMobEffectExtensions.of(effect); ++ if (renderer.extractInventory(effect, this, graphics, x0, y0, 0)) { ++ y0 += yStep; + continue; + } - Component component = this.getEffectName(mobeffectinstance); - Component component1 = MobEffectUtil.formatDuration(mobeffectinstance, 1.0F, this.minecraft.level.tickRateManager().tickrate()); - int j = this.extractBackground(graphics, font, component, component1, x0, i, flag, maxWidth); + Component effectText = this.getEffectName(effect); + Component duration = MobEffectUtil.formatDuration(effect, 1.0F, this.minecraft.level.tickRateManager().tickrate()); + int textureWidth = this.extractBackground(graphics, font, effectText, duration, x0, y0, isAmbient, maxWidth); @@ -136,5 +_,9 @@ } - return mutablecomponent; + return name; + } + + public AbstractContainerScreen getScreen() { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch index f58ce6e108..d32f83cb84 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java.patch @@ -1,32 +1,33 @@ --- a/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java +++ b/net/minecraft/client/gui/screens/inventory/EnchantmentScreen.java @@ -111,7 +_,7 @@ - int l1 = 86 - this.font.width(s); - FormattedText formattedtext = EnchantmentNames.getInstance().getRandomName(this.font, l1); - int i2 = -9937334; -- if ((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.hasInfiniteMaterials()) { -+ if (((k < l + 1 || this.minecraft.player.experienceLevel < k1) && !this.minecraft.player.hasInfiniteMaterials()) || this.menu.enchantClue[l] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels{ - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, ENCHANTMENT_SLOT_DISABLED_SPRITE, i1, j + 14 + 19 * l, 108, 19); - graphics.blitSprite(RenderPipelines.GUI_TEXTURED, DISABLED_LEVEL_SPRITES[l], i1 + 1, j + 15 + 19 * l, 16, 16); - graphics.textWithWordWrap(this.font, formattedtext, j1, j + 16 + 19 * l, l1, ARGB.opaque((i2 & 16711422) >> 1), false); -@@ -162,13 +_,16 @@ + int textWidth = 86 - this.font.width(costText); + FormattedText message = EnchantmentNames.getInstance().getRandomName(this.font, textWidth); + int col = -9937334; +- if ((goldCount < i + 1 || this.minecraft.player.experienceLevel < cost) && !this.minecraft.player.hasInfiniteMaterials()) { ++ if (((goldCount < i + 1 || this.minecraft.player.experienceLevel < cost) && !this.minecraft.player.hasInfiniteMaterials()) || this.menu.enchantClue[i] == -1) { // Forge: render buttons as disabled when enchantable but enchantability not met on lower levels{ + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, ENCHANTMENT_SLOT_DISABLED_SPRITE, leftPos, yo + 14 + 19 * i, 108, 19); + graphics.blitSprite(RenderPipelines.GUI_TEXTURED, DISABLED_LEVEL_SPRITES[i], leftPos + 1, yo + 15 + 19 * i, 16, 16); + graphics.textWithWordWrap(this.font, message, leftPosText, yo + 16 + 19 * i, textWidth, ARGB.opaque((col & 16711422) >> 1), false); +@@ -162,14 +_,18 @@ .registryAccess() .lookupOrThrow(Registries.ENCHANTMENT) - .get(this.menu.enchantClue[j]); -- if (!optional.isEmpty()) { + .get(this.menu.enchantClue[i]); +- if (!enchant.isEmpty()) { + { - int l = this.menu.levelClue[j]; - int i1 = j + 1; -- if (this.isHovering(60, 14 + 19 * j, 108, 17, mouseX, mouseY) && k > 0 && l >= 0) { -+ if (this.isHovering(60, 14 + 19 * j, 108, 17, (double)mouseX, (double)mouseY) && l >= 0) { - List list = Lists.newArrayList(); -- list.add(Component.translatable("container.enchant.clue", Enchantment.getFullname(optional.get(), l)).withStyle(ChatFormatting.WHITE)); -- if (!flag) { -+ list.add(Component.translatable("container.enchant.clue", optional.isEmpty() ? "" : Enchantment.getFullname(optional.get(), l)).withStyle(ChatFormatting.WHITE)); -+ if (optional.isEmpty()) { -+ list.add(Component.literal("")); -+ list.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED)); -+ } else if (!flag) { - list.add(CommonComponents.EMPTY); - if (this.minecraft.player.experienceLevel < k) { - list.add(Component.translatable("container.enchant.level.requirement", this.menu.costs[j]).withStyle(ChatFormatting.RED)); + int enchantLevel = this.menu.levelClue[i]; + int cost = i + 1; +- if (this.isHovering(60, 14 + 19 * i, 108, 17, mouseX, mouseY) && minLevel > 0 && enchantLevel >= 0) { ++ if (this.isHovering(60, 14 + 19 * i, 108, 17, (double)mouseX, (double)mouseY) && enchantLevel >= 0) { + List texts = Lists.newArrayList(); + texts.add( +- Component.translatable("container.enchant.clue", Enchantment.getFullname(enchant.get(), enchantLevel)).withStyle(ChatFormatting.WHITE) ++ Component.translatable("container.enchant.clue", enchant.isEmpty() ? "" : Enchantment.getFullname(enchant.get(), enchantLevel)).withStyle(ChatFormatting.WHITE) + ); ++ if (enchant.isEmpty()) { ++ texts.add(Component.literal("")); ++ texts.add(Component.translatable("forge.container.enchant.limitedEnchantability").withStyle(ChatFormatting.RED)); ++ } else + if (!infiniteMaterials) { + texts.add(CommonComponents.EMPTY); + if (this.minecraft.player.experienceLevel < minLevel) { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch index 246c28c0af..5823f8029f 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java +++ b/net/minecraft/client/gui/screens/inventory/tooltip/ClientTooltipComponent.java -@@ -20,7 +_,7 @@ - case ClientActivePlayersTooltip.ActivePlayersTooltip clientactiveplayerstooltip$activeplayerstooltip -> new ClientActivePlayersTooltip( - clientactiveplayerstooltip$activeplayerstooltip - ); +@@ -18,7 +_,7 @@ + return (ClientTooltipComponent)(switch (component) { + case BundleTooltip bundleTooltip -> new ClientBundleTooltip(bundleTooltip.contents()); + case ClientActivePlayersTooltip.ActivePlayersTooltip activePlayersTooltip -> new ClientActivePlayersTooltip(activePlayersTooltip); - default -> throw new IllegalArgumentException("Unknown TooltipComponent"); + default -> net.minecraftforge.client.gui.ClientTooltipComponentManager.createClientTooltipComponent(component); }); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch index f7efecb938..906daafefb 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java +++ b/net/minecraft/client/gui/screens/multiplayer/ServerSelectionList.java -@@ -371,6 +_,8 @@ +@@ -372,6 +_,8 @@ graphics.setTooltipForNextFrame(Lists.transform(this.onlinePlayersTooltip, Component::getVisualOrderText), mouseX, mouseY); } @@ -8,4 +8,4 @@ + if (this.minecraft.options.touchscreen().get() || hovered) { graphics.fill(this.getContentX(), this.getContentY(), this.getContentX() + 32, this.getContentY() + 32, -1601138544); - int i1 = mouseX - this.getContentX(); + int relX = mouseX - this.getContentX(); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch index 774ce5641d..54adfe62fe 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java +++ b/net/minecraft/client/gui/screens/options/controls/KeyBindsList.java -@@ -123,9 +_,10 @@ +@@ -122,9 +_,10 @@ this.name = name; this.changeButton = Button.builder(name, button -> { KeyBindsList.this.keyBindsScreen.selectedKey = key; @@ -12,7 +12,7 @@ .createNarration( defaultNarrationSupplier -> key.isUnbound() ? Component.translatable("narrator.controls.unbound", name) -@@ -133,7 +_,7 @@ +@@ -132,7 +_,7 @@ ) .build(); this.resetButton = Button.builder(RESET_BUTTON_TITLE, button -> { @@ -21,13 +21,13 @@ KeyBindsList.this.resetMappingAndUpdateButtons(); }).bounds(0, 0, 50, 20).createNarration(defaultNarrationSupplier -> Component.translatable("narrator.controls.reset", name)).build(); this.refreshEntry(); -@@ -174,7 +_,8 @@ - MutableComponent mutablecomponent = Component.empty(); +@@ -173,7 +_,8 @@ + MutableComponent tooltip = Component.empty(); if (!this.key.isUnbound()) { - for (KeyMapping keymapping : KeyBindsList.this.minecraft.options.keyMappings) { -- if (keymapping != this.key && this.key.same(keymapping) && (!keymapping.isDefault() || !this.key.isDefault())) { -+ var vanillConflict = keymapping != this.key && this.key.same(keymapping) && (!keymapping.isDefault() || !this.key.isDefault()); -+ if (vanillConflict || keymapping.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G + for (KeyMapping otherKey : KeyBindsList.this.minecraft.options.keyMappings) { +- if (otherKey != this.key && this.key.same(otherKey) && (!otherKey.isDefault() || !this.key.isDefault())) { ++ var vanillConflict = otherKey != this.key && this.key.same(otherKey) && (!otherKey.isDefault() || !this.key.isDefault()); ++ if (vanillConflict || otherKey.hasKeyModifierConflict(this.key)) { // FORGE: gracefully handle conflicts like SHIFT vs SHIFT+G if (this.hasCollision) { - mutablecomponent.append(", "); + tooltip.append(", "); } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch index 5a179d9cc6..8558529b3e 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/options/controls/KeyBindsScreen.java.patch @@ -3,9 +3,9 @@ @@ -42,7 +_,7 @@ protected void addFooter() { this.resetButton = Button.builder(Component.translatable("controls.resetAll"), button -> { - for (KeyMapping keymapping : this.options.keyMappings) { -- keymapping.setKey(keymapping.getDefaultKey()); -+ keymapping.setToDefault(); + for (KeyMapping key : this.options.keyMappings) { +- key.setKey(key.getDefaultKey()); ++ key.setToDefault(); } this.keyBindsList.resetMappingAndUpdateButtons(); @@ -27,7 +27,7 @@ @@ -101,5 +_,18 @@ } - this.resetButton.active = flag; + this.resetButton.active = canReset; + } + + @Override diff --git a/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch index 70dc308202..e5867e8ce1 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java +++ b/net/minecraft/client/gui/screens/packs/TransferableSelectionList.java @@ -66,7 +_,7 @@ - Component component = Component.empty().append(this.title).withStyle(ChatFormatting.UNDERLINE, ChatFormatting.BOLD); - this.addEntry(new TransferableSelectionList.HeaderEntry(this.minecraft.font, component), (int)(9.0F * 1.5F)); + Component header = Component.empty().append(this.title).withStyle(ChatFormatting.UNDERLINE, ChatFormatting.BOLD); + this.addEntry(new TransferableSelectionList.HeaderEntry(this.minecraft.font, header), (int)(9.0F * 1.5F)); this.setSelected(null); - entries.forEach(e -> { + entries.filter(PackSelectionModel.Entry::notHidden).forEach(e -> { - TransferableSelectionList.PackEntry transferableselectionlist$packentry = new TransferableSelectionList.PackEntry(this.minecraft, this, e); - this.addEntry(transferableselectionlist$packentry); + TransferableSelectionList.PackEntry entry = new TransferableSelectionList.PackEntry(this.minecraft, this, e); + this.addEntry(entry); if (transferredEntry != null && transferredEntry.getId().equals(e.getId())) { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch index 950bf2b1b9..ebcd6eea9c 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java +++ b/net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java -@@ -177,6 +_,7 @@ - WorldDataConfiguration worlddataconfiguration = SharedConstants.IS_RUNNING_IN_IDE +@@ -174,6 +_,7 @@ + WorldDataConfiguration dataConfig = SharedConstants.IS_RUNNING_IN_IDE ? new WorldDataConfiguration(new DataPackConfig(List.of("vanilla", "tests"), List.of()), FeatureFlags.DEFAULT_FLAGS) : WorldDataConfiguration.DEFAULT; -+ net.minecraftforge.event.ForgeEventFactory.addPackFindersServer(packrepository::addPackFinder); - WorldLoader.InitConfig worldloader$initconfig = createDefaultLoadConfig(packrepository, worlddataconfiguration); - CompletableFuture completablefuture = WorldLoader.load( - worldloader$initconfig, -@@ -520,7 +_,7 @@ ++ net.minecraftforge.event.ForgeEventFactory.addPackFindersServer(vanillaOnlyPackRepository::addPackFinder); + WorldLoader.InitConfig loadConfig = createDefaultLoadConfig(vanillaOnlyPackRepository, dataConfig); + CompletableFuture loadResult = WorldLoader.load( + loadConfig, +@@ -509,7 +_,7 @@ if (retry) { onAbort.accept(this.uiState.getSettings().dataConfiguration()); } else { @@ -17,10 +17,10 @@ } }, Component.translatable("dataPack.validation.failed"), -@@ -634,6 +_,7 @@ - if (path != null) { +@@ -623,6 +_,7 @@ + if (dataPackDir != null) { if (this.tempDataPackRepository == null) { - this.tempDataPackRepository = ServerPacksSource.createPackRepository(path, this.packValidator); + this.tempDataPackRepository = ServerPacksSource.createPackRepository(dataPackDir, this.packValidator); + net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(this.tempDataPackRepository, false); this.tempDataPackRepository.reload(); } diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch index aa503f068e..2deeb0af17 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/PresetEditor.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/gui/screens/worldselection/PresetEditor.java +++ b/net/minecraft/client/gui/screens/worldselection/PresetEditor.java -@@ -29,6 +_,10 @@ +@@ -28,6 +_,10 @@ @OnlyIn(Dist.CLIENT) public interface PresetEditor { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch index 4d2bbafbde..7550bad00c 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldCreationUiState.java -@@ -234,7 +_,7 @@ +@@ -229,7 +_,7 @@ public @Nullable PresetEditor getPresetEditor() { - Holder holder = this.getWorldType().preset(); -- return holder != null ? PresetEditor.EDITORS.get(holder.unwrapKey()) : null; -+ return holder != null ? holder.unwrapKey().map(net.minecraftforge.client.PresetEditorManager::get).orElse(null) : null; // FORGE: redirect lookup to expanded map + Holder preset = this.getWorldType().preset(); +- return preset != null ? PresetEditor.EDITORS.get(preset.unwrapKey()) : null; ++ return preset != null ? preset.unwrapKey().map(net.minecraftforge.client.PresetEditorManager::get).orElse(null) : null; // FORGE: redirect lookup to expanded map } public List getNormalPresetList() { diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch index 212b5cbe84..b1d6617da2 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java +++ b/net/minecraft/client/gui/screens/worldselection/WorldOpenFlows.java -@@ -507,6 +_,8 @@ +@@ -489,6 +_,8 @@ this.minecraft.setScreenAndShow(new GenericMessageScreen(Component.translatable("selectWorld.resource_load"))); - PackRepository packrepository = ServerPacksSource.createPackRepository(worldAccess); + PackRepository packRepository = ServerPacksSource.createPackRepository(worldAccess); + net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(worldAccess, worldAccess.getLevelDirectory()); + - WorldStem worldstem; + WorldStem worldStem; try { - worldstem = this.loadWorldStem(worldAccess, levelDataTag, safeMode, packrepository); + worldStem = this.loadWorldStem(worldAccess, levelDataTag, safeMode, packRepository); diff --git a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch index 0a0325f977..57a716822a 100644 --- a/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch +++ b/patches/minecraft/net/minecraft/client/gui/screens/worldselection/WorldSelectionList.java.patch @@ -8,7 +8,7 @@ private static final Component FROM_NEWER_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.fromNewerVersion1").withStyle(ChatFormatting.RED); private static final Component FROM_NEWER_TOOLTIP_2 = Component.translatable("selectWorld.tooltip.fromNewerVersion2").withStyle(ChatFormatting.RED); private static final Component SNAPSHOT_TOOLTIP_1 = Component.translatable("selectWorld.tooltip.snapshot1").withStyle(ChatFormatting.GOLD); -@@ -493,6 +_,19 @@ +@@ -486,6 +_,19 @@ } } @@ -27,12 +27,12 @@ + @Override public Component getNarration() { - Component component = Component.translatable( -@@ -522,6 +_,7 @@ - this.infoText.setPosition(i, this.getContentY() + 9 + 9 + 3); + Component entryNarration = Component.translatable( +@@ -515,6 +_,7 @@ + this.infoText.setPosition(textX, this.getContentY() + 9 + 9 + 3); this.infoText.extractRenderState(graphics, mouseX, mouseY, a); graphics.blit(RenderPipelines.GUI_TEXTURED, this.icon.textureLocation(), this.getContentX(), this.getContentY(), 0.0F, 0.0F, 32, 32, 32, 32); + renderExperimentalWarning(graphics, mouseX, mouseY, this.getContentY(), this.getContentX()); if (this.list.entryType == WorldSelectionList.EntryType.SINGLEPLAYER && (this.minecraft.options.touchscreen().get() || hovered)) { graphics.fill(this.getContentX(), this.getContentY(), this.getContentX() + 32, this.getContentY() + 32, -1601138544); - int j = mouseX - this.getContentX(); + int relX = mouseX - this.getContentX(); diff --git a/patches/minecraft/net/minecraft/client/main/Main.java.patch b/patches/minecraft/net/minecraft/client/main/Main.java.patch index 476c04ce08..70984f135e 100644 --- a/patches/minecraft/net/minecraft/client/main/Main.java.patch +++ b/patches/minecraft/net/minecraft/client/main/Main.java.patch @@ -3,11 +3,11 @@ @@ -114,8 +_,8 @@ CrashReport.preload(); logger = LogUtils.getLogger(); - s1 = "Bootstrap"; + stage = "Bootstrap"; - Bootstrap.bootStrap(); - ClientBootstrap.bootstrap(); + net.minecraftforge.fml.loading.BackgroundWaiter.runAndTick(Bootstrap::bootStrap, net.minecraftforge.fml.loading.FMLLoader.progressWindowTick); + net.minecraftforge.fml.loading.BackgroundWaiter.runAndTick(ClientBootstrap::bootstrap, net.minecraftforge.fml.loading.FMLLoader.progressWindowTick); GameLoadTimesEvent.INSTANCE.setBootstrapTime(Bootstrap.bootstrapDuration.get()); Bootstrap.validate(); - s1 = "Argument parsing"; + stage = "Argument parsing"; diff --git a/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch b/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch index 805bd4cdf4..d931e128dc 100644 --- a/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch +++ b/patches/minecraft/net/minecraft/client/model/HumanoidModel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/model/HumanoidModel.java +++ b/net/minecraft/client/model/HumanoidModel.java -@@ -387,6 +_,8 @@ +@@ -391,6 +_,8 @@ break; case SPEAR: SpearAnimations.thirdPersonHandUse(this.rightArm, this.head, true, state.getUseItemStackForArm(HumanoidArm.RIGHT), state); @@ -9,7 +9,7 @@ } } -@@ -432,6 +_,8 @@ +@@ -436,6 +_,8 @@ break; case SPEAR: SpearAnimations.thirdPersonHandUse(this.leftArm, this.head, false, state.getUseItemStackForArm(HumanoidArm.LEFT), state); @@ -18,7 +18,7 @@ } } -@@ -493,7 +_,7 @@ +@@ -497,7 +_,7 @@ } @OnlyIn(Dist.CLIENT) @@ -27,7 +27,7 @@ EMPTY(false, false), ITEM(false, false), BLOCK(false, false), -@@ -519,10 +_,29 @@ +@@ -523,10 +_,29 @@ private ArmPose(final boolean twoHanded, final boolean affectsOffhandPose) { this.twoHanded = twoHanded; this.affectsOffhandPose = affectsOffhandPose; diff --git a/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch b/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch index 35e82948e2..b2257ffa10 100644 --- a/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch +++ b/patches/minecraft/net/minecraft/client/model/geom/LayerDefinitions.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/model/geom/LayerDefinitions.java +++ b/net/minecraft/client/model/geom/LayerDefinitions.java -@@ -572,6 +_,7 @@ - builder.put(ModelLayers.createHangingSignModelName(woodType, hangingsignblock$attachment), layerdefinition70); +@@ -569,6 +_,7 @@ + result.put(ModelLayers.createHangingSignModelName(woodType, attachmentType), hangingSignModel); } }); -+ net.minecraftforge.client.ForgeHooksClient.loadLayerDefinitions(builder); - ImmutableMap immutablemap = builder.build(); - List list = ModelLayers.getKnownLocations().filter(l -> !immutablemap.containsKey(l)).toList(); - if (!list.isEmpty()) { ++ net.minecraftforge.client.ForgeHooksClient.loadLayerDefinitions(result); + ImmutableMap definitions = result.build(); + List missingDefinitions = ModelLayers.getKnownLocations().filter(l -> !definitions.containsKey(l)).toList(); + if (!missingDefinitions.isEmpty()) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch index a21d92e760..6767c1b645 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java +++ b/net/minecraft/client/multiplayer/AccountProfileKeyPairManager.java -@@ -76,6 +_,8 @@ - this.writeProfileKeyPair(profilekeypair); - return Optional.ofNullable(profilekeypair); - } catch (CryptException | MinecraftClientException | IOException ioexception) { +@@ -75,6 +_,8 @@ + this.writeProfileKeyPair(fetchedKeyPair); + return Optional.ofNullable(fetchedKeyPair); + } catch (CryptException | MinecraftClientException | IOException var3) { + // Forge: The offline user api service always returns a null profile key pair, so let's hide this useless exception if in dev + if (net.minecraftforge.fml.loading.FMLLoader.isProduction() || this.userApiService != UserApiService.OFFLINE) - LOGGER.error("Failed to retrieve profile key pair", (Throwable)ioexception); + LOGGER.error("Failed to retrieve profile key pair", (Throwable)var3); this.writeProfileKeyPair(null); return cachedKeyPair; diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch index a4fce51e58..714ac6ac1f 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientChunkCache.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/client/multiplayer/ClientChunkCache.java +++ b/net/minecraft/client/multiplayer/ClientChunkCache.java @@ -65,6 +_,7 @@ - int i = this.storage.getIndex(pos.x(), pos.z()); - LevelChunk levelchunk = this.storage.getChunk(i); - if (isValidChunk(levelchunk, pos.x(), pos.z())) { -+ net.minecraftforge.event.level.ChunkEvent.Unload.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Unload(levelchunk)); - this.storage.drop(i, levelchunk); + int index = this.storage.getIndex(pos.x(), pos.z()); + LevelChunk currentChunk = this.storage.getChunk(index); + if (isValidChunk(currentChunk, pos.x(), pos.z())) { ++ net.minecraftforge.event.level.ChunkEvent.Unload.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Unload(currentChunk)); + this.storage.drop(index, currentChunk); } } @@ -124,6 +_,7 @@ } - this.level.onChunkLoaded(chunkpos); -+ net.minecraftforge.event.level.ChunkEvent.Load.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Load(levelchunk, false)); - return levelchunk; + this.level.onChunkLoaded(pos); ++ net.minecraftforge.event.level.ChunkEvent.Load.BUS.post(new net.minecraftforge.event.level.ChunkEvent.Load(chunk, false)); + return chunk; } } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch index 1038902575..7502d7fa93 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientCommonPacketListenerImpl.java.patch @@ -5,6 +5,6 @@ @Override public void handleCustomPayload(final ClientboundCustomPayloadPacket packet) { + if (net.minecraftforge.common.ForgeHooks.onCustomPayload(packet.payload(), this.connection)) return; - CustomPacketPayload custompacketpayload = packet.payload(); - if (!(custompacketpayload instanceof DiscardedPayload)) { + CustomPacketPayload payload = packet.payload(); + if (!(payload instanceof DiscardedPayload)) { PacketUtils.ensureRunningOnSameThread(packet, this, this.minecraft.packetProcessor()); diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch index 137f604874..183b9f99df 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java +++ b/net/minecraft/client/multiplayer/ClientHandshakePacketListenerImpl.java @@ -209,6 +_,7 @@ - Component component = this.wasTransferredTo ? CommonComponents.TRANSFER_CONNECT_FAILED : CommonComponents.CONNECT_FAILED; + Component title = this.wasTransferredTo ? CommonComponents.TRANSFER_CONNECT_FAILED : CommonComponents.CONNECT_FAILED; if (this.serverData != null && this.serverData.isRealm()) { - this.minecraft.setScreen(new DisconnectedScreen(this.parent, component, details.reason(), CommonComponents.GUI_BACK)); + this.minecraft.setScreen(new DisconnectedScreen(this.parent, title, details.reason(), CommonComponents.GUI_BACK)); + } else if (net.minecraftforge.client.ForgeHooksClient.onClientDisconnect(this.connection, this.minecraft, this.parent, details.reason())) { } else { - this.minecraft.setScreen(new DisconnectedScreen(this.parent, component, details)); + this.minecraft.setScreen(new DisconnectedScreen(this.parent, title, details)); } @@ -233,6 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch index d7f671294c..05675df8bf 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientLevel.java.patch @@ -19,7 +19,7 @@ if (SharedConstants.DEBUG_BLOCK_BREAK) { @@ -273,6 +_,8 @@ - runnable.run(); + update.run(); } + this.gatherCapabilities(); + net.minecraftforge.event.ForgeEventFactory.onLevelLoad(this); @@ -45,7 +45,7 @@ } public void removeEntity(final int id, final Entity.RemovalReason reason) { -@@ -579,8 +_,10 @@ +@@ -576,8 +_,10 @@ final float pitch, final long seed ) { @@ -57,7 +57,7 @@ } } -@@ -594,8 +_,10 @@ +@@ -591,8 +_,10 @@ final float pitch, final long seed ) { @@ -69,24 +69,24 @@ } } -@@ -951,7 +_,7 @@ +@@ -946,7 +_,7 @@ @Override public void addDestroyBlockEffect(final BlockPos pos, final BlockState blockState) { - if (!blockState.isAir() && blockState.shouldSpawnTerrainParticles()) { + if (!blockState.isAir() && !net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(blockState).addDestroyEffects(blockState, this, pos, this.minecraft.particleEngine)) { - VoxelShape voxelshape = blockState.getShape(this, pos); - double d0 = 0.25; - voxelshape.forAllBoxes( -@@ -978,6 +_,7 @@ + VoxelShape shape = blockState.getShape(this, pos); + double density = 0.25; + shape.forAllBoxes( +@@ -973,6 +_,7 @@ new TerrainParticle( - this, pos.getX() + d7, pos.getY() + d8, pos.getZ() + d9, d4 - 0.5, d5 - 0.5, d6 - 0.5, blockState, pos + this, pos.getX() + x, pos.getY() + y, pos.getZ() + z, relX - 0.5, relY - 0.5, relZ - 0.5, blockState, pos ) + .updateSprite(blockState, pos) ); } } -@@ -987,6 +_,13 @@ +@@ -982,6 +_,13 @@ } } @@ -98,18 +98,18 @@ + + /** @deprecated Forge - Use crack(BlockPos, BlockHitResult) as it has more context and gives more control to modders */ public void addBreakingBlockEffect(final BlockPos pos, final Direction direction) { - BlockState blockstate = this.getBlockState(pos); - if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.shouldSpawnTerrainParticles()) { -@@ -1022,7 +_,7 @@ - d0 = i + aabb.maxX + 0.1F; + BlockState blockState = this.getBlockState(pos); + if (blockState.getRenderShape() != RenderShape.INVISIBLE && blockState.shouldSpawnTerrainParticles()) { +@@ -1017,7 +_,7 @@ + xp = x + shape.maxX + 0.1F; } -- this.minecraft.particleEngine.add(new TerrainParticle(this, d0, d1, d2, 0.0, 0.0, 0.0, blockstate, pos).setPower(0.2F).scale(0.6F)); -+ this.minecraft.particleEngine.add(new TerrainParticle(this, d0, d1, d2, 0.0, 0.0, 0.0, blockstate, pos).updateSprite(blockstate, pos).setPower(0.2F).scale(0.6F)); +- this.minecraft.particleEngine.add(new TerrainParticle(this, xp, yp, zp, 0.0, 0.0, 0.0, blockState, pos).setPower(0.2F).scale(0.6F)); ++ this.minecraft.particleEngine.add(new TerrainParticle(this, xp, yp, zp, 0.0, 0.0, 0.0, blockState, pos).updateSprite(blockState, pos).setPower(0.2F).scale(0.6F)); } } -@@ -1088,6 +_,16 @@ +@@ -1083,6 +_,16 @@ this.explosionTracker.track(center, radius, blockCount, blockParticles); } @@ -126,7 +126,7 @@ @OnlyIn(Dist.CLIENT) public static class ClientLevelData implements WritableLevelData { private final boolean hardcore; -@@ -1143,6 +_,7 @@ +@@ -1138,6 +_,7 @@ } public void setDifficulty(final Difficulty difficulty) { @@ -134,7 +134,7 @@ this.difficulty = difficulty; } -@@ -1190,6 +_,12 @@ +@@ -1185,6 +_,12 @@ break; default: } @@ -147,8 +147,8 @@ } public void onTrackingEnd(final Entity entity) { -@@ -1202,6 +_,15 @@ - ClientLevel.this.dragonParts.removeAll(Arrays.asList(enderdragon.getSubEntities())); +@@ -1197,6 +_,15 @@ + ClientLevel.this.dragonParts.removeAll(Arrays.asList(dragon.getSubEntities())); break; default: + } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch index 475f0c06fe..5471634931 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ClientPacketListener.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/multiplayer/ClientPacketListener.java +++ b/net/minecraft/client/multiplayer/ClientPacketListener.java -@@ -536,6 +_,7 @@ +@@ -531,6 +_,7 @@ this.debugSubscriber.clear(); this.minecraft.levelRenderer.debugRenderer.refreshRendererList(); this.minecraft.player.resetPos(); @@ -8,25 +8,25 @@ this.minecraft.player.setId(packet.playerId()); this.level.addEntity(this.minecraft.player); this.minecraft.player.input = new KeyboardInput(this.minecraft.options); -@@ -1345,6 +_,8 @@ - localplayer1.getAttributes().assignBaseValues(localplayer.getAttributes()); +@@ -1325,6 +_,8 @@ + newPlayer.getAttributes().assignBaseValues(oldPlayer.getAttributes()); } -+ localplayer1.updateSyncFields(localplayer); // Forge: fix MC-10657 -+ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerRespawn(this.minecraft.gameMode, localplayer, localplayer1, localplayer1.connection.connection); - this.level.addEntity(localplayer1); - localplayer1.input = new KeyboardInput(this.minecraft.options); - this.minecraft.gameMode.adjustPlayer(localplayer1); -@@ -1504,7 +_,7 @@ - ProblemReporter.ScopedCollector problemreporter$scopedcollector = new ProblemReporter.ScopedCollector(blockEntity.problemPath(), LOGGER); ++ newPlayer.updateSyncFields(oldPlayer); // Forge: fix MC-10657 ++ net.minecraftforge.client.event.ForgeEventFactoryClient.firePlayerRespawn(this.minecraft.gameMode, oldPlayer, newPlayer, newPlayer.connection.connection); + this.level.addEntity(newPlayer); + newPlayer.input = new KeyboardInput(this.minecraft.options); + this.minecraft.gameMode.adjustPlayer(newPlayer); +@@ -1480,7 +_,7 @@ + ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(blockEntity.problemPath(), LOGGER); try { -- blockEntity.loadWithComponents(TagValueInput.create(problemreporter$scopedcollector, this.registryAccess, packet.getTag())); -+ blockEntity.onDataPacket(connection, TagValueInput.create(problemreporter$scopedcollector, this.registryAccess, packet.getTag()), this.registryAccess); - } catch (Throwable throwable1) { +- blockEntity.loadWithComponents(TagValueInput.create(reporter, this.registryAccess, packet.getTag())); ++ blockEntity.onDataPacket(connection, TagValueInput.create(reporter, this.registryAccess, packet.getTag()), this.registryAccess); + } catch (Throwable var7) { try { - problemreporter$scopedcollector.close(); -@@ -1727,7 +_,9 @@ + reporter.close(); +@@ -1687,7 +_,9 @@ @Override public void handleCommands(final ClientboundCommandsPacket packet) { PacketUtils.ensureRunningOnSameThread(packet, this, this.minecraft.packetProcessor()); @@ -37,24 +37,24 @@ } @Override -@@ -1828,6 +_,7 @@ - if (this.minecraft.screen instanceof RecipeUpdateListener recipeupdatelistener) { - recipeupdatelistener.recipesUpdated(); +@@ -1788,6 +_,7 @@ + if (this.minecraft.screen instanceof RecipeUpdateListener updateListener) { + updateListener.recipesUpdated(); } + net.minecraftforge.client.event.ForgeEventFactoryClient.onRecipesUpdated(recipeBook); } @Override -@@ -1872,6 +_,8 @@ +@@ -1832,6 +_,8 @@ this.fuelValues = FuelValues.vanillaBurnTimes(this.registryAccess, this.enabledFeatures); - List list1 = List.copyOf(CreativeModeTabs.searchTab().getDisplayItems()); - this.searchTrees.updateCreativeTags(list1); + List searchItems = List.copyOf(CreativeModeTabs.searchTab().getDisplayItems()); + this.searchTrees.updateCreativeTags(searchItems); + + net.minecraftforge.event.ForgeEventFactory.onTagsUpdated(this.registryAccess, true, this.connection.isMemoryConnection()); } @Override -@@ -2688,7 +_,9 @@ +@@ -2650,7 +_,9 @@ } } @@ -62,18 +62,18 @@ + public void sendChat(String content) { + content = net.minecraftforge.client.ForgeHooksClient.onClientSendMessage(content); + if (content.isEmpty()) return; - Instant instant = Instant.now(); - long i = Crypt.SaltSupplier.getLong(); - LastSeenMessagesTracker.Update lastseenmessagestracker$update = this.lastSeenMessages.generateAndApplyUpdate(); -@@ -2698,6 +_,7 @@ + Instant timeStamp = Instant.now(); + long salt = Crypt.SaltSupplier.getLong(); + LastSeenMessagesTracker.Update lastSeenUpdate = this.lastSeenMessages.generateAndApplyUpdate(); +@@ -2659,6 +_,7 @@ } public void sendCommand(final String command) { + if (net.minecraftforge.client.ClientCommandHandler.runCommand(command)) return; - SignableCommand signablecommand = SignableCommand.of(this.commands.parse(command, this.suggestionsProvider)); - if (signablecommand.arguments().isEmpty()) { + SignableCommand signableCommand = SignableCommand.of(this.commands.parse(command, this.suggestionsProvider)); + if (signableCommand.arguments().isEmpty()) { this.send(new ServerboundChatCommandPacket(command)); -@@ -2714,6 +_,7 @@ +@@ -2675,6 +_,7 @@ } public void sendUnattendedCommand(final String command, final @Nullable Screen screenAfterCommand) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch index 5b6a49eda1..65d02b1331 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/MultiPlayerGameMode.java.patch @@ -9,15 +9,15 @@ return false; } else { @@ -128,9 +_,8 @@ - } else if (blockstate.isAir()) { + } else if (oldState.isAir()) { return false; } else { -- block.playerWillDestroy(level, pos, blockstate, this.minecraft.player); - FluidState fluidstate = level.getFluidState(pos); -- boolean flag = level.setBlock(pos, fluidstate.createLegacyBlock(), 11); -+ boolean flag = blockstate.onDestroyedByPlayer(level, pos, minecraft.player, false, fluidstate); - if (flag) { - block.destroy(level, pos, blockstate); +- oldBlock.playerWillDestroy(level, pos, oldState, this.minecraft.player); + FluidState fluidState = level.getFluidState(pos); +- boolean changed = level.setBlock(pos, fluidState.createLegacyBlock(), 11); ++ boolean changed = oldState.onDestroyedByPlayer(level, pos, minecraft.player, false, fluidState); + if (changed) { + oldBlock.destroy(level, pos, oldState); } @@ -159,6 +_,7 @@ } @@ -33,18 +33,18 @@ } + var event = net.minecraftforge.event.ForgeEventFactory.onLeftClickBlock(this.minecraft.player, pos, direction, ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK); - BlockState blockstate1 = this.minecraft.level.getBlockState(pos); - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, blockstate1, 0.0F); + BlockState state = this.minecraft.level.getBlockState(pos); + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, state, 0.0F); @@ -182,9 +_,11 @@ this.startPrediction(this.minecraft.level, sequence -> { - boolean flag = !blockstate1.isAir(); - if (flag && this.destroyProgress == 0.0F) { + boolean notAir = !state.isAir(); + if (notAir && this.destroyProgress == 0.0F) { + if (event != null && !event.getUseBlock().isDenied()) - blockstate1.attack(this.minecraft.level, pos, this.minecraft.player); + state.attack(this.minecraft.level, pos, this.minecraft.player); } + if (event != null && !event.getUseItem().isDenied()) { - if (flag && blockstate1.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos) >= 1.0F) { + if (notAir && state.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos) >= 1.0F) { this.destroyBlock(pos); } else { @@ -195,6 +_,7 @@ @@ -65,17 +65,17 @@ }); @@ -247,7 +_,7 @@ } else { - this.destroyProgress = this.destroyProgress + blockstate.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos); + this.destroyProgress = this.destroyProgress + state.getDestroyProgress(this.minecraft.player, this.minecraft.player.level(), pos); if (this.destroyTicks % 4.0F == 0.0F) { -- SoundType soundtype = blockstate.getSoundType(); -+ SoundType soundtype = blockstate.getSoundType(this.minecraft.level, pos, this.minecraft.player); +- SoundType soundType = state.getSoundType(); ++ SoundType soundType = state.getSoundType(this.minecraft.level, pos, this.minecraft.player); this.minecraft .getSoundManager() .play( @@ -264,6 +_,7 @@ this.destroyTicks++; - this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, blockstate, Mth.clamp(this.destroyProgress, 0.0F, 1.0F)); + this.minecraft.getTutorial().onDestroyBlock(this.minecraft.level, pos, state, Mth.clamp(this.destroyProgress, 0.0F, 1.0F)); + if (net.minecraftforge.event.ForgeEventFactory.onLeftClickBlockHold(this.minecraft.player, pos, direction).getUseItem().isDenied()) return true; if (this.destroyProgress >= 1.0F) { this.isDestroying = false; @@ -83,81 +83,81 @@ @@ -306,7 +_,7 @@ private boolean sameDestroyTarget(final BlockPos pos) { - ItemStack itemstack = this.minecraft.player.getMainHandItem(); -- return pos.equals(this.destroyBlockPos) && ItemStack.isSameItemSameComponents(itemstack, this.destroyingItem); -+ return pos.equals(this.destroyBlockPos) && !destroyingItem.shouldCauseBlockBreakReset(itemstack); + ItemStack selected = this.minecraft.player.getMainHandItem(); +- return pos.equals(this.destroyBlockPos) && ItemStack.isSameItemSameComponents(selected, this.destroyingItem); ++ return pos.equals(this.destroyBlockPos) && !destroyingItem.shouldCauseBlockBreakReset(selected); } private void ensureHasSentCarriedItem() { @@ -334,12 +_,23 @@ private InteractionResult performUseItemOn(final LocalPlayer player, final InteractionHand hand, final BlockHitResult blockHit) { - BlockPos blockpos = blockHit.getBlockPos(); - ItemStack itemstack = player.getItemInHand(hand); -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, blockpos, blockHit); + BlockPos pos = blockHit.getBlockPos(); + ItemStack itemStack = player.getItemInHand(hand); ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, pos, blockHit); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock.BUS.post(event)) { + return event.getCancellationResult(); + } if (this.localPlayerMode == GameType.SPECTATOR) { return InteractionResult.CONSUME; } else { -- boolean flag = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); -+ UseOnContext useoncontext = new UseOnContext(player, hand, blockHit); +- boolean haveSomethingInOurHands = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); ++ UseOnContext context = new UseOnContext(player, hand, blockHit); + if (!event.getUseItem().isDenied()) { -+ InteractionResult result = itemstack.onItemUseFirst(useoncontext); ++ InteractionResult result = itemStack.onItemUseFirst(context); + if (result != InteractionResult.PASS) { + return result; + } + } -+ boolean flag = !player.getMainHandItem().doesSneakBypassUse(player.level(), blockpos, player) || !player.getOffhandItem().doesSneakBypassUse(player.level(), blockpos, player); - boolean flag1 = player.isSecondaryUseActive() && flag; -- if (!flag1) { -+ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !flag1)) { - BlockState blockstate = this.minecraft.level.getBlockState(blockpos); - if (!this.connection.isFeatureEnabled(blockstate.getBlock().requiredFeatures())) { ++ boolean haveSomethingInOurHands = !player.getMainHandItem().doesSneakBypassUse(player.level(), pos, player) || !player.getOffhandItem().doesSneakBypassUse(player.level(), pos, player); + boolean suppressUsingBlock = player.isSecondaryUseActive() && haveSomethingInOurHands; +- if (!suppressUsingBlock) { ++ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !suppressUsingBlock)) { + BlockState blockState = this.minecraft.level.getBlockState(pos); + if (!this.connection.isFeatureEnabled(blockState.getBlock().requiredFeatures())) { return InteractionResult.FAIL; @@ -358,8 +_,10 @@ } } -- if (!itemstack.isEmpty() && !player.getCooldowns().isOnCooldown(itemstack)) { -- UseOnContext useoncontext = new UseOnContext(player, hand, blockHit); +- if (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack)) { +- UseOnContext context = new UseOnContext(player, hand, blockHit); + if (event.getUseItem().isDenied()) { + return InteractionResult.PASS; + } -+ if (event.getUseItem().isAllowed() || (!itemstack.isEmpty() && !player.getCooldowns().isOnCooldown(itemstack))) { - InteractionResult interactionresult2; ++ if (event.getUseItem().isAllowed() || (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack))) { + InteractionResult success; if (player.hasInfiniteMaterials()) { - int i = itemstack.getCount(); + int count = itemStack.getCount(); @@ -389,6 +_,11 @@ - mutableobject.setValue(InteractionResult.PASS); - return serverbounduseitempacket; + interactionResult.setValue(InteractionResult.PASS); + return packet; } else { + var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickItem(player, hand); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickItem.BUS.post(event)) { -+ mutableobject.setValue(event.getCancellationResult()); -+ return serverbounduseitempacket; ++ interactionResult.setValue(event.getCancellationResult()); ++ return packet; + } - InteractionResult interactionresult = itemstack.use(this.minecraft.level, player, hand); - ItemStack itemstack1; - if (interactionresult instanceof InteractionResult.Success interactionresult$success) { + InteractionResult resultHolder = itemStack.use(this.minecraft.level, player, hand); + ItemStack result; + if (resultHolder instanceof InteractionResult.Success success) { @@ -399,6 +_,9 @@ - if (itemstack1 != itemstack) { - player.setItemInHand(hand, itemstack1); -+ if (itemstack1.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, itemstack, hand); + if (result != itemStack) { + player.setItemInHand(hand, result); ++ if (result.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, itemStack, hand); + } } - mutableobject.setValue(interactionresult); + interactionResult.setValue(resultHolder); @@ -434,6 +_,10 @@ this.ensureHasSentCarriedItem(); - Vec3 vec3 = hitResult.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ()); - this.connection.send(new ServerboundInteractPacket(entity.getId(), hand, vec3, player.isShiftKeyDown())); + Vec3 location = hitResult.getLocation().subtract(entity.getX(), entity.getY(), entity.getZ()); + this.connection.send(new ServerboundInteractPacket(entity.getId(), hand, location, player.isShiftKeyDown())); + if (this.localPlayerMode != GameType.SPECTATOR) { -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, vec3); ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific(player, hand, entity, location); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific.BUS.post(event)) return event.getCancellationResult(); + } - return (InteractionResult)(this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : player.interactOn(entity, hand, vec3)); + return (InteractionResult)(this.localPlayerMode == GameType.SPECTATOR ? InteractionResult.PASS : player.interactOn(entity, hand, location)); } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch index b0e87ba8f2..d588e61db7 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/ServerStatusPinger.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/multiplayer/ServerStatusPinger.java +++ b/net/minecraft/client/multiplayer/ServerStatusPinger.java -@@ -124,6 +_,7 @@ +@@ -123,6 +_,7 @@ onPersistentDataChange.run(); } }); -+ net.minecraftforge.client.ForgeHooksClient.processForgeListPingData(serverstatus, data); ++ net.minecraftforge.client.ForgeHooksClient.processForgeListPingData(status, data); this.pingStart = Util.getMillis(); connection.send(new ServerboundPingRequestPacket(this.pingStart)); this.success = true; -@@ -180,7 +_,7 @@ +@@ -179,7 +_,7 @@ private void pingLegacyServer( final InetSocketAddress resolvedAddress, final ServerAddress rawAddress, final ServerData data, final EventLoopGroupHolder eventLoopGroupHolder ) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch index 5cd36219b3..fd72487550 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/SessionSearchTrees.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/multiplayer/SessionSearchTrees.java +++ b/net/minecraft/client/multiplayer/SessionSearchTrees.java -@@ -34,8 +_,8 @@ +@@ -33,8 +_,8 @@ private static final SessionSearchTrees.Key RECIPE_COLLECTIONS = new SessionSearchTrees.Key(); public static final SessionSearchTrees.Key CREATIVE_NAMES = new SessionSearchTrees.Key(); public static final SessionSearchTrees.Key CREATIVE_TAGS = new SessionSearchTrees.Key(); @@ -11,7 +11,7 @@ private CompletableFuture> recipeSearch = CompletableFuture.completedFuture(SearchTree.empty()); private final Map reloaders = new IdentityHashMap<>(); -@@ -90,44 +_,52 @@ +@@ -89,44 +_,52 @@ } public void updateCreativeTags(final List items) { @@ -20,16 +20,16 @@ - CREATIVE_TAGS, + entry.getValue(), () -> { -- CompletableFuture completablefuture = this.creativeByTagSearch; +- CompletableFuture previous = this.creativeByTagSearch; - this.creativeByTagSearch = CompletableFuture.supplyAsync( - () -> new IdSearchTree<>(itemStack -> itemStack.tags().map(TagKey::location), items), Util.backgroundExecutor() - ); + var tabItems = entry.getKey() == net.minecraft.world.item.CreativeModeTabs.searchTab() ? items : List.copyOf(entry.getKey().getDisplayItems()); -+ CompletableFuture completablefuture = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); ++ CompletableFuture previous = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); + this.creativeSearch.put(entry.getValue(), CompletableFuture.supplyAsync( + () -> new IdSearchTree<>(itemStack -> itemStack.tags().map(TagKey::location), tabItems), Util.backgroundExecutor() + )); - completablefuture.cancel(true); + previous.cancel(true); } ); } @@ -46,14 +46,14 @@ + entry.getValue(), () -> { + var items = entry.getKey() == net.minecraft.world.item.CreativeModeTabs.searchTab() ? itemStacks : List.copyOf(entry.getKey().getDisplayItems()); - Item.TooltipContext item$tooltipcontext = Item.TooltipContext.of(registries); - TooltipFlag tooltipflag = TooltipFlag.Default.NORMAL.asCreative(); -- CompletableFuture completablefuture = this.creativeByNameSearch; + Item.TooltipContext tooltipContext = Item.TooltipContext.of(registries); + TooltipFlag tooltipFlag = TooltipFlag.Default.NORMAL.asCreative(); +- CompletableFuture previous = this.creativeByNameSearch; - this.creativeByNameSearch = CompletableFuture.supplyAsync( -+ CompletableFuture completablefuture = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); ++ CompletableFuture previous = this.creativeSearch.getOrDefault(entry.getValue(), EMPTY); + this.creativeSearch.put(entry.getValue(), CompletableFuture.supplyAsync( () -> new FullTextSearchTree<>( - itemStack -> getTooltipLines(Stream.of(itemStack), item$tooltipcontext, tooltipflag), + itemStack -> getTooltipLines(Stream.of(itemStack), tooltipContext, tooltipFlag), itemStack -> itemStack.typeHolder().unwrapKey().map(ResourceKey::identifier).stream(), - itemStacks + items @@ -61,7 +61,7 @@ Util.backgroundExecutor() - ); + )); - completablefuture.cancel(true); + previous.cancel(true); } ); } diff --git a/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch index 85168444ee..4a31f4895a 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/chat/ChatListener.java.patch @@ -1,42 +1,42 @@ --- a/net/minecraft/client/multiplayer/chat/ChatListener.java +++ b/net/minecraft/client/multiplayer/chat/ChatListener.java @@ -140,6 +_,8 @@ - LocalPlayer localplayer = this.minecraft.player; - if (localplayer != null && localplayer.chatAbilities().canReceivePlayerMessages()) { - Component component = boundChatType.decorate(message); -+ component = net.minecraftforge.client.ForgeHooksClient.onClientChat(boundChatType, component, Util.NIL_UUID); -+ if (component == null) return false; - this.minecraft.gui.getChat().addPlayerMessage(component, null, GuiMessageTag.system()); + LocalPlayer receiver = this.minecraft.player; + if (receiver != null && receiver.chatAbilities().canReceivePlayerMessages()) { + Component decoratedMessage = boundChatType.decorate(message); ++ decoratedMessage = net.minecraftforge.client.ForgeHooksClient.onClientChat(boundChatType, decoratedMessage, Util.NIL_UUID); ++ if (decoratedMessage == null) return false; + this.minecraft.gui.getChat().addPlayerMessage(decoratedMessage, null, GuiMessageTag.system()); this.narrateChatMessage(boundChatType, message); - this.logSystemMessage(component, instant); + this.logSystemMessage(decoratedMessage, received); @@ -169,12 +_,16 @@ - MessageSignature messagesignature = message.signature(); - FilterMask filtermask = message.filterMask(); - if (filtermask.isEmpty()) { -- this.minecraft.gui.getChat().addPlayerMessage(decoratedMessage, messagesignature, guimessagetag); + MessageSignature signature = message.signature(); + FilterMask filterMask = message.filterMask(); + if (filterMask.isEmpty()) { +- this.minecraft.gui.getChat().addPlayerMessage(decoratedMessage, signature, tag); + Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(boundChatType, decoratedMessage, message, message.sender()); + if (forgeComponent == null) return false; -+ this.minecraft.gui.getChat().addPlayerMessage(forgeComponent, messagesignature, guimessagetag); ++ this.minecraft.gui.getChat().addPlayerMessage(forgeComponent, signature, tag); this.narrateChatMessage(boundChatType, message.decoratedContent()); } else { - Component component = filtermask.applyWithFormatting(message.signedContent()); - if (component != null) { -- this.minecraft.gui.getChat().addPlayerMessage(boundChatType.decorate(component), messagesignature, guimessagetag); -+ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(boundChatType, boundChatType.decorate(component), message, message.sender()); + Component filteredContent = filterMask.applyWithFormatting(message.signedContent()); + if (filteredContent != null) { +- this.minecraft.gui.getChat().addPlayerMessage(boundChatType.decorate(filteredContent), signature, tag); ++ Component forgeComponent = net.minecraftforge.client.ForgeHooksClient.onClientPlayerChat(boundChatType, boundChatType.decorate(filteredContent), message, message.sender()); + if (forgeComponent == null) return false; -+ this.minecraft.gui.getChat().addPlayerMessage(forgeComponent, messagesignature, guimessagetag); - this.narrateChatMessage(boundChatType, component); ++ this.minecraft.gui.getChat().addPlayerMessage(forgeComponent, signature, tag); + this.narrateChatMessage(boundChatType, filteredContent); } } @@ -208,10 +_,12 @@ - chatlog.push(LoggedChatMessage.system(message, timeStamp)); + chatLog.push(LoggedChatMessage.system(message, timeStamp)); } - public void handleSystemMessage(final Component message, final boolean remote) { + public void handleSystemMessage(Component message, final boolean remote) { if (!this.minecraft.options.hideMatchedNames().get() || !this.minecraft.isBlocked(this.guessChatUUID(message))) { - LocalPlayer localplayer = this.minecraft.player; - if (localplayer != null && localplayer.chatAbilities().canReceiveSystemMessages()) { + LocalPlayer receiver = this.minecraft.player; + if (receiver != null && receiver.chatAbilities().canReceiveSystemMessages()) { + message = net.minecraftforge.client.ForgeHooksClient.onClientSystemMessage(message, remote); + if (message == null) return; if (remote) { diff --git a/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch b/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch index 8c79125e4f..c7a72f7f4e 100644 --- a/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch +++ b/patches/minecraft/net/minecraft/client/multiplayer/resolver/AddressCheck.java.patch @@ -4,8 +4,8 @@ boolean isAllowed(ServerAddress address); static AddressCheck createFromService() { -- final ImmutableList> immutablelist = Streams.stream(ServiceLoader.load(BlockListSupplier.class)) -+ final ImmutableList> immutablelist = Streams.stream(ServiceLoader.load(BlockListSupplier.class, net.minecraftforge.fml.loading.FMLLoader.class.getClassLoader())) +- final ImmutableList> blockLists = Streams.stream(ServiceLoader.load(BlockListSupplier.class)) ++ final ImmutableList> blockLists = Streams.stream(ServiceLoader.load(BlockListSupplier.class, net.minecraftforge.fml.loading.FMLLoader.class.getClassLoader())) .map(BlockListSupplier::createBlockList) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); diff --git a/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch b/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch index 2b192da3fc..e1b2a6936a 100644 --- a/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/FireworkParticles.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/particle/FireworkParticles.java +++ b/net/minecraft/client/particle/FireworkParticles.java @@ -256,6 +_,10 @@ - intlist = IntList.of(DyeColor.BLACK.getFireworkColor()); + colors = IntList.of(DyeColor.BLACK.getFireworkColor()); } -+ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(fireworkexplosion1.shape()); ++ var factory = net.minecraftforge.client.FireworkShapeFactoryRegistry.get(explosionx.shape()); + if (factory != null) -+ factory.build(this, flag3, flag4, intlist.toIntArray(), intlist1.toIntArray()); ++ factory.build(this, trail, twinkle, colors.toIntArray(), colors.toIntArray()); + else - switch (fireworkexplosion1.shape()) { + switch (explosionx.shape()) { case SMALL_BALL: - this.createParticleBall(0.25, 2, intlist, intlist1, flag3, flag4); + this.createParticleBall(0.25, 2, colors, fadeColors, trail, twinkle); diff --git a/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch index 1ce295bf48..b8cbb0e086 100644 --- a/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/FlyTowardsPositionParticle.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/particle/FlyTowardsPositionParticle.java +++ b/net/minecraft/client/particle/FlyTowardsPositionParticle.java @@ -107,6 +_,7 @@ - this.x = this.xStart + this.xd * f; - this.y = this.yStart + this.yd * f - f1 * 1.2F; - this.z = this.zStart + this.zd * f; + this.x = this.xStart + this.xd * pos; + this.y = this.yStart + this.yd * pos - pp * 1.2F; + this.z = this.zStart + this.zd * pos; + this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box } } diff --git a/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch b/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch index 8300437bbb..7be893aaa4 100644 --- a/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ParticleEngine.java.patch @@ -1,16 +1,15 @@ --- a/net/minecraft/client/particle/ParticleEngine.java +++ b/net/minecraft/client/particle/ParticleEngine.java -@@ -64,8 +_,7 @@ +@@ -63,7 +_,7 @@ + private @Nullable Particle makeParticle( final T options, final double x, final double y, final double z, final double xa, final double ya, final double za ) { - ParticleProvider particleprovider = (ParticleProvider)this.resourceManager -- .getProviders() -- .get(BuiltInRegistries.PARTICLE_TYPE.getId(options.getType())); -+ .getProvider(options.getType()); - return particleprovider == null ? null : particleprovider.createParticle(options, this.level, x, y, z, xa, ya, za, this.random); +- ParticleProvider provider = (ParticleProvider)this.resourceManager.getProviders().get(BuiltInRegistries.PARTICLE_TYPE.getId(options.getType())); ++ ParticleProvider provider = (ParticleProvider)this.resourceManager.getProvider(options.getType()); + return provider == null ? null : provider.createParticle(options, this.level, x, y, z, xa, ya, za, this.random); } -@@ -113,6 +_,8 @@ +@@ -111,6 +_,8 @@ return new ItemPickupParticleGroup(this); } else if (type == ParticleRenderType.ELDER_GUARDIANS) { return new ElderGuardianParticleGroup(this); @@ -19,7 +18,7 @@ } else { return (ParticleGroup)(type == ParticleRenderType.NO_RENDER ? new NoRenderParticleGroup(this) : new QuadParticleGroup(this, type)); } -@@ -122,8 +_,20 @@ +@@ -120,8 +_,20 @@ this.trackedParticleCounts.addTo(limit, change); } @@ -36,8 +35,8 @@ + } + public void extract(final ParticlesRenderState particlesRenderState, final Frustum frustum, final Camera camera, final float partialTickTime) { -- for (ParticleRenderType particlerendertype : RENDER_ORDER) { -+ for (ParticleRenderType particlerendertype : particleRenderOrder) { // Forge: allow custom ParticleRenderType's - ParticleGroup particlegroup = this.particles.get(particlerendertype); - if (particlegroup != null && !particlegroup.isEmpty()) { - particlesRenderState.add(particlegroup.extractRenderState(frustum, camera, partialTickTime)); +- for (ParticleRenderType particleType : RENDER_ORDER) { ++ for (ParticleRenderType particleType : particleRenderOrder) { // Forge: allow custom ParticleRenderType's + ParticleGroup particles = this.particles.get(particleType); + if (particles != null && !particles.isEmpty()) { + particlesRenderState.add(particles.extractRenderState(frustum, camera, partialTickTime)); diff --git a/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch b/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch index 01848d5f0a..49cb37f093 100644 --- a/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ParticleResources.java.patch @@ -20,10 +20,10 @@ + /** @deprecated Register via {@link net.minecraftforge.client.event.RegisterParticleProvidersEvent} */ public void register(final ParticleType type, final ParticleResources.SpriteParticleRegistration provider) { - ParticleResources.MutableSpriteSet particleresources$mutablespriteset = new ParticleResources.MutableSpriteSet(); - this.spriteSets.put(BuiltInRegistries.PARTICLE_TYPE.getKey(type), particleresources$mutablespriteset); -- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(type), provider.create(particleresources$mutablespriteset)); -+ register(type, provider.create(particleresources$mutablespriteset)); + ParticleResources.MutableSpriteSet spriteSet = new ParticleResources.MutableSpriteSet(); + this.spriteSets.put(BuiltInRegistries.PARTICLE_TYPE.getKey(type), spriteSet); +- this.providers.put(BuiltInRegistries.PARTICLE_TYPE.getId(type), provider.create(spriteSet)); ++ register(type, provider.create(spriteSet)); } @Override diff --git a/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch index 6e013dc2fe..d0498f2dd0 100644 --- a/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/PortalParticle.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/particle/PortalParticle.java +++ b/net/minecraft/client/particle/PortalParticle.java @@ -84,6 +_,7 @@ - this.x = this.xStart + this.xd * f2; - this.y = this.yStart + this.yd * f2 + (1.0F - f); - this.z = this.zStart + this.zd * f2; + this.x = this.xStart + this.xd * var4; + this.y = this.yStart + this.yd * var4 + (1.0F - pos); + this.z = this.zStart + this.zd * var4; + this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box } } diff --git a/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch index bd115b3485..9e4ae118c2 100644 --- a/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/ReversePortalParticle.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/client/particle/ReversePortalParticle.java +++ b/net/minecraft/client/particle/ReversePortalParticle.java @@ -42,6 +_,7 @@ - this.x = this.x + this.xd * f; - this.y = this.y + this.yd * f; - this.z = this.z + this.zd * f; + this.x = this.x + this.xd * speedMultiplier; + this.y = this.y + this.yd * speedMultiplier; + this.z = this.z + this.zd * speedMultiplier; + this.setPos(this.x, this.y, this.z); // FORGE: update the particle's bounding box } } diff --git a/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch index b3314754fe..b72b1f8e6a 100644 --- a/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/TerrainParticle.java.patch @@ -3,18 +3,18 @@ @@ -43,7 +_,7 @@ this.gCol = 0.6F; this.bCol = 0.6F; - BlockTintSource blocktintsource = Minecraft.getInstance().getBlockColors().getTintSource(blockState, 0); -- if (blocktintsource != null) { -+ if (blocktintsource != null && net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(blockState).areBreakingParticlesTinted(blockState, level, pos)) { - int i = blocktintsource.colorAsTerrainParticle(blockState, level, pos); - this.rCol *= (i >> 16 & 0xFF) / 255.0F; - this.gCol *= (i >> 8 & 0xFF) / 255.0F; + BlockTintSource tintSource = Minecraft.getInstance().getBlockColors().getTintSource(blockState, 0); +- if (tintSource != null) { ++ if (tintSource != null && net.minecraftforge.client.extensions.common.IClientBlockExtensions.of(blockState).areBreakingParticlesTinted(blockState, level, pos)) { + int col = tintSource.colorAsTerrainParticle(blockState, level, pos); + this.rCol *= (col >> 16 & 0xFF) / 255.0F; + this.gCol *= (col >> 8 & 0xFF) / 255.0F; @@ -93,8 +_,14 @@ ) { - BlockState blockstate = options.getState(); - return !blockstate.isAir() && !blockstate.is(Blocks.MOVING_PISTON) && blockstate.shouldSpawnTerrainParticles() -- ? new TerrainParticle(level, x, y, z, xAux, yAux, zAux, blockstate) -+ ? (TerrainParticle)new TerrainParticle(level, x, y, z, xAux, yAux, zAux, blockstate).updateSprite(blockstate, options.getPos()) + BlockState state = options.getState(); + return !state.isAir() && !state.is(Blocks.MOVING_PISTON) && state.shouldSpawnTerrainParticles() +- ? new TerrainParticle(level, x, y, z, xAux, yAux, zAux, state) ++ ? (TerrainParticle)new TerrainParticle(level, x, y, z, xAux, yAux, zAux, state).updateSprite(state, options.getPos()) : null; + } + diff --git a/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch b/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch index 61cfafc590..1233dedf45 100644 --- a/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch +++ b/patches/minecraft/net/minecraft/client/particle/VibrationSignalParticle.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/client/particle/VibrationSignalParticle.java +++ b/net/minecraft/client/particle/VibrationSignalParticle.java @@ -87,6 +_,7 @@ - this.x = Mth.lerp(d0, this.x, vec3.x()); - this.y = Mth.lerp(d0, this.y, vec3.y()); - this.z = Mth.lerp(d0, this.z, vec3.z()); + this.x = Mth.lerp(alpha, this.x, destination.x()); + this.y = Mth.lerp(alpha, this.y, destination.y()); + this.z = Mth.lerp(alpha, this.z, destination.z()); + this.setPos(this.x, this.y, this.z); // FORGE: Update the particle's bounding box - double d1 = this.x - vec3.x(); - double d2 = this.y - vec3.y(); - double d3 = this.z - vec3.z(); + double dx = this.x - destination.x(); + double dy = this.y - destination.y(); + double dz = this.z - destination.z(); diff --git a/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch b/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch index c4db09489e..c0cd60352a 100644 --- a/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/AbstractClientPlayer.java.patch @@ -4,8 +4,8 @@ } } -- return Mth.lerp(effectScale, 1.0F, f); -+ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireFovModifierEvent(this, f, effectScale).getNewFovModifier(); +- return Mth.lerp(effectScale, 1.0F, modifier); ++ return net.minecraftforge.client.event.ForgeEventFactoryClient.fireFovModifierEvent(this, modifier, effectScale).getNewFovModifier(); } @Override diff --git a/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch b/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch index 500c4d65e5..8d84db9304 100644 --- a/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch +++ b/patches/minecraft/net/minecraft/client/player/LocalPlayer.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/player/LocalPlayer.java +++ b/net/minecraft/client/player/LocalPlayer.java -@@ -324,6 +_,7 @@ - ServerboundPlayerActionPacket.Action serverboundplayeractionpacket$action = all +@@ -318,6 +_,7 @@ + ServerboundPlayerActionPacket.Action action = all ? ServerboundPlayerActionPacket.Action.DROP_ALL_ITEMS : ServerboundPlayerActionPacket.Action.DROP_ITEM; + if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (all || getUseItem().getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the clientside - ItemStack itemstack = this.getInventory().removeFromSelected(all); - this.connection.send(new ServerboundPlayerActionPacket(serverboundplayeractionpacket$action, BlockPos.ZERO, Direction.DOWN)); - return !itemstack.isEmpty(); -@@ -551,7 +_,10 @@ + ItemStack prediction = this.getInventory().removeFromSelected(all); + this.connection.send(new ServerboundPlayerActionPacket(action, BlockPos.ZERO, Direction.DOWN)); + return !prediction.isEmpty(); +@@ -545,7 +_,10 @@ @Override public void playSound(final SoundEvent sound, final float volume, final float pitch) { @@ -20,15 +20,15 @@ } @Override -@@ -793,6 +_,7 @@ +@@ -787,6 +_,7 @@ && this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.CROUCHING) && (this.isShiftKeyDown() || !this.isSleeping() && !this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.STANDING)); this.input.tick(); + net.minecraftforge.client.ForgeHooksClient.onMovementInputUpdate(this, this.input); this.minecraft.getTutorial().onInput(this.input); - boolean flag3 = false; + boolean wasAutoJump = false; if (this.autoJumpTime > 0) { -@@ -865,8 +_,9 @@ +@@ -859,8 +_,9 @@ } this.wasFallFlying = this.isFallFlying(); @@ -40,7 +40,7 @@ } if (this.isEyeInFluid(FluidTags.WATER)) { -@@ -934,7 +_,7 @@ +@@ -928,7 +_,7 @@ } private boolean shouldStopSwimSprinting() { @@ -49,16 +49,16 @@ } public Portal.Transition getActivePortalLocalTransition() { -@@ -979,6 +_,8 @@ +@@ -973,6 +_,8 @@ @Override public void rideTick() { super.rideTick(); + if (this.wantsToStopRiding() && this.isPassenger()) + this.input.keyPresses = this.input.keyPresses.jump(false); this.handsBusy = false; - if (this.getControlledVehicle() instanceof AbstractBoat abstractboat) { - abstractboat.setInput( -@@ -1154,7 +_,7 @@ + if (this.getControlledVehicle() instanceof AbstractBoat boat) { + boat.setInput(this.input.keyPresses.left(), this.input.keyPresses.right(), this.input.keyPresses.forward(), this.input.keyPresses.backward()); +@@ -1146,7 +_,7 @@ && this.isSprintingPossible(this.getAbilities().flying) && !this.isSlowDueToUsingItem() && (!this.isFallFlying() || this.isUnderWater()) @@ -67,7 +67,7 @@ } private boolean vehicleCanSprint(final Entity vehicle) { -@@ -1230,6 +_,17 @@ +@@ -1222,6 +_,17 @@ @Override public float getVisualRotationYInDegrees() { return this.getYRot(); diff --git a/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch index d0058d90b1..dbab5fd128 100644 --- a/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/GameRenderer.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/GameRenderer.java +++ b/net/minecraft/client/renderer/GameRenderer.java -@@ -235,6 +_,9 @@ +@@ -233,6 +_,9 @@ case null: default: this.clearPostEffect(); @@ -10,47 +10,47 @@ } } -@@ -246,7 +_,13 @@ +@@ -244,7 +_,13 @@ public void processBlurEffect() { - PostChain postchain = this.minecraft.getShaderManager().getPostChain(BLUR_POST_CHAIN_ID, LevelTargetBundle.MAIN_TARGETS); - if (postchain != null) { + PostChain postChain = this.minecraft.getShaderManager().getPostChain(BLUR_POST_CHAIN_ID, LevelTargetBundle.MAIN_TARGETS); + if (postChain != null) { + // TODO: [Forge][Rendering] Check if this blend management is needed anymnore with the new render pipeline changes + boolean wasBlendEnabled = com.mojang.blaze3d.opengl.GlStateManager._isBlendEnabled(); + if (wasBlendEnabled) + com.mojang.blaze3d.opengl.GlStateManager._disableBlend(); - postchain.process(this.minecraft.getMainRenderTarget(), this.resourcePool); + postChain.process(this.minecraft.getMainRenderTarget(), this.resourcePool); + if (wasBlendEnabled) + com.mojang.blaze3d.opengl.GlStateManager._enableBlend(); } } -@@ -507,7 +_,7 @@ - profilerfiller.push("screen"); +@@ -509,7 +_,7 @@ + profiler.push("screen"); try { -- this.minecraft.screen.extractRenderStateWithTooltipAndSubtitles(guigraphicsextractor, i, j, deltaTracker.getGameTimeDeltaTicks()); -+ net.minecraftforge.client.ForgeHooksClient.drawScreen(this.minecraft.screen, guigraphicsextractor, i, j, deltaTracker.getRealtimeDeltaTicks()); - } catch (Throwable throwable) { - CrashReport crashreport1 = CrashReport.forThrowable(throwable, "Rendering screen"); - CrashReportCategory crashreportcategory1 = crashreport1.addCategory("Screen render details"); -@@ -672,6 +_,10 @@ - Registry registry = this.minecraft.level.registryAccess().lookupOrThrow(Registries.BLOCK); - flag = !itemstack.isEmpty() - && (itemstack.canBreakBlockInAdventureMode(blockinworld) || itemstack.canPlaceOnBlockInAdventureMode(blockinworld)); -+ if (!flag && blockstate.hasBlockEntity()) { -+ var blockEntity = this.minecraft.level.getBlockEntity(blockpos); -+ flag = blockEntity != null && blockEntity.hasCustomOutlineRendering(); +- this.minecraft.screen.extractRenderStateWithTooltipAndSubtitles(graphics, xMouse, yMouse, deltaTracker.getGameTimeDeltaTicks()); ++ net.minecraftforge.client.ForgeHooksClient.drawScreen(this.minecraft.screen, graphics, xMouse, yMouse, deltaTracker.getRealtimeDeltaTicks()); + } catch (Throwable var12) { + CrashReport report = CrashReport.forThrowable(var12, "Rendering screen"); + CrashReportCategory category = report.addCategory("Screen render details"); +@@ -674,6 +_,10 @@ + Registry blockRegistry = this.minecraft.level.registryAccess().lookupOrThrow(Registries.BLOCK); + renderOutline = !itemStack.isEmpty() + && (itemStack.canBreakBlockInAdventureMode(blockInWorld) || itemStack.canPlaceOnBlockInAdventureMode(blockInWorld)); ++ if (!renderOutline && blockState.hasBlockEntity()) { ++ var blockEntity = this.minecraft.level.getBlockEntity(pos); ++ renderOutline = blockEntity != null && blockEntity.hasCustomOutlineRendering(); + } } } } -@@ -696,6 +_,9 @@ - if (optionsrenderstate.bobView) { - this.bobView(camerarenderstate, posestack); +@@ -698,6 +_,9 @@ + if (optionsState.bobView) { + this.bobView(cameraState, bobStack); } + -+ var cameraSetup = net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeCameraAngles(this, this.mainCamera, f); ++ var cameraSetup = net.minecraftforge.client.event.ForgeEventFactoryClient.fireComputeCameraAngles(this, this.mainCamera, worldPartialTicks); + this.mainCamera.setRotation(cameraSetup.getYaw(), cameraSetup.getPitch(), cameraSetup.getRoll()); - matrix4f.mul(posestack.last().pose()); - float f2 = optionsrenderstate.screenEffectScale; + projectionMatrix.mul(bobStack.last().pose()); + float screenEffectScale = optionsState.screenEffectScale; diff --git a/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch index 7253bbc9cf..0741f21e3d 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ItemInHandRenderer.java.patch @@ -1,55 +1,57 @@ --- a/net/minecraft/client/renderer/ItemInHandRenderer.java +++ b/net/minecraft/client/renderer/ItemInHandRenderer.java -@@ -366,12 +_,14 @@ - if (iteminhandrenderer$handrenderselection.renderMainHand) { - float f4 = interactionhand == InteractionHand.MAIN_HAND ? f : 0.0F; - float f5 = this.itemModelResolver.swapAnimationScale(this.mainHandItem) * (1.0F - Mth.lerp(frameInterp, this.oMainHandHeight, this.mainHandHeight)); -+ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, f1, f4, f5, this.mainHandItem)) - this.renderArmWithItem(player, frameInterp, f1, InteractionHand.MAIN_HAND, f4, this.mainHandItem, f5, poseStack, submitNodeCollector, lightCoords); - } - - if (iteminhandrenderer$handrenderselection.renderOffHand) { - float f6 = interactionhand == InteractionHand.OFF_HAND ? f : 0.0F; - float f7 = this.itemModelResolver.swapAnimationScale(this.offHandItem) * (1.0F - Mth.lerp(frameInterp, this.oOffHandHeight, this.offHandHeight)); -+ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.OFF_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, f1, f6, f7, this.offHandItem)) - this.renderArmWithItem(player, frameInterp, f1, InteractionHand.OFF_HAND, f6, this.offHandItem, f7, poseStack, submitNodeCollector, lightCoords); - } - -@@ -438,7 +_,7 @@ +@@ -362,6 +_,7 @@ + float mainHandAttack = attackHand == InteractionHand.MAIN_HAND ? attackValue : 0.0F; + float mainhandInverseArmHeight = this.itemModelResolver.swapAnimationScale(this.mainHandItem) + * (1.0F - Mth.lerp(frameInterp, this.oMainHandHeight, this.mainHandHeight)); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.MAIN_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, xRot, mainHandAttack, mainhandInverseArmHeight, this.mainHandItem)) + this.renderArmWithItem( + player, + frameInterp, +@@ -380,6 +_,8 @@ + float offHandAttack = attackHand == InteractionHand.OFF_HAND ? attackValue : 0.0F; + float offhandInverseArmHeight = this.itemModelResolver.swapAnimationScale(this.offHandItem) + * (1.0F - Mth.lerp(frameInterp, this.oOffHandHeight, this.offHandHeight)); ++ ++ if (!net.minecraftforge.client.ForgeHooksClient.renderSpecificFirstPersonHand(InteractionHand.OFF_HAND, poseStack, submitNodeCollector, lightCoords, frameInterp, xRot, offHandAttack, offhandInverseArmHeight, this.offHandItem)) + this.renderArmWithItem( + player, + frameInterp, +@@ -457,7 +_,7 @@ } else { - this.renderOneHandedMap(poseStack, submitNodeCollector, lightCoords, inverseArmHeight, humanoidarm, attack, itemStack); + this.renderOneHandedMap(poseStack, submitNodeCollector, lightCoords, inverseArmHeight, arm, attack, itemStack); } - } else if (itemStack.is(Items.CROSSBOW)) { + } else if (itemStack.getItem() instanceof CrossbowItem) { - this.applyItemArmTransform(poseStack, humanoidarm, inverseArmHeight); - boolean flag1 = CrossbowItem.isCharged(itemStack); - boolean flag2 = humanoidarm == HumanoidArm.RIGHT; -@@ -483,6 +_,7 @@ + this.applyItemArmTransform(poseStack, arm, inverseArmHeight); + boolean charged = CrossbowItem.isCharged(itemStack); + boolean isRightArm = arm == HumanoidArm.RIGHT; +@@ -502,6 +_,7 @@ } else { - boolean flag3 = humanoidarm == HumanoidArm.RIGHT; - int j = flag3 ? 1 : -1; -+ if (!net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemStack).applyForgeHandTransform(poseStack, minecraft.player, humanoidarm, itemStack, frameInterp, inverseArmHeight, attack)) // FORGE: Allow items to define custom arm animation + boolean isRightArm = arm == HumanoidArm.RIGHT; + int invert = isRightArm ? 1 : -1; ++ if (!net.minecraftforge.client.extensions.common.IClientItemExtensions.of(itemStack).applyForgeHandTransform(poseStack, minecraft.player, arm, itemStack, frameInterp, inverseArmHeight, attack)) // FORGE: Allow items to define custom arm animation if (player.isUsingItem() && player.getUseItemRemainingTicks() > 0 && player.getUsedItemHand() == hand) { - ItemUseAnimation itemuseanimation = itemStack.getUseAnimation(); - if (!itemuseanimation.hasCustomArmTransform()) { -@@ -628,8 +_,18 @@ + ItemUseAnimation useAnimation = itemStack.getUseAnimation(); + if (!useAnimation.hasCustomArmTransform()) { +@@ -647,8 +_,18 @@ this.offHandHeight = Mth.clamp(this.offHandHeight - 0.4F, 0.0F, 1.0F); } else { - float f = localplayer.getItemSwapScale(1.0F); -- float f1 = this.mainHandItem != itemstack ? 0.0F : f * f * f; -- float f2 = this.offHandItem != itemstack1 ? 0.0F : 1.0F; + float attackAnim = player.getItemSwapScale(1.0F); +- float mainHandTargetHeight = this.mainHandItem != nextMainHand ? 0.0F : attackAnim * attackAnim * attackAnim; +- float offHandTargetHeight = this.offHandItem != nextOffHand ? 0.0F : 1.0F; + -+ boolean requipM = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.mainHandItem, itemstack, localplayer.getInventory().getSelectedSlot()); -+ boolean requipO = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.offHandItem, itemstack1, -1); ++ boolean requipM = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.mainHandItem, nextMainHand, player.getInventory().getSelectedSlot()); ++ boolean requipO = net.minecraftforge.client.ForgeHooksClient.shouldCauseReequipAnimation(this.offHandItem, nextOffHand, -1); + -+ if (!requipM && this.mainHandItem != itemstack) -+ this.mainHandItem = itemstack; -+ if (!requipO && this.offHandItem != itemstack1) -+ this.offHandItem = itemstack1; ++ if (!requipM && this.mainHandItem != nextMainHand) ++ this.mainHandItem = nextMainHand; ++ if (!requipO && this.offHandItem != nextOffHand) ++ this.offHandItem = nextOffHand; + -+ float f1 = requipM ? 0.0F : f * f * f; -+ float f2 = requipO ? 0.0F : 1.0F; ++ float mainHandTargetHeight = requipM ? 0.0F : attackAnim * attackAnim * attackAnim; ++ float offHandTargetHeight = requipO ? 0.0F : 1.0F; + - this.mainHandHeight = this.mainHandHeight + Mth.clamp(f1 - this.mainHandHeight, -0.4F, 0.4F); - this.offHandHeight = this.offHandHeight + Mth.clamp(f2 - this.offHandHeight, -0.4F, 0.4F); + this.mainHandHeight = this.mainHandHeight + Mth.clamp(mainHandTargetHeight - this.mainHandHeight, -0.4F, 0.4F); + this.offHandHeight = this.offHandHeight + Mth.clamp(offHandTargetHeight - this.offHandHeight, -0.4F, 0.4F); } diff --git a/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch b/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch index 786f314f5d..2e20aee1cb 100644 --- a/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/LevelEventHandler.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/LevelEventHandler.java +++ b/net/minecraft/client/renderer/LevelEventHandler.java -@@ -384,7 +_,7 @@ +@@ -302,7 +_,7 @@ case 2001: - BlockState blockstate1 = Block.stateById(data); - if (!blockstate1.isAir()) { -- SoundType soundtype = blockstate1.getSoundType(); -+ SoundType soundtype = blockstate1.getSoundType(this.level, pos, null); + BlockState blockState = Block.stateById(data); + if (!blockState.isAir()) { +- SoundType soundType = blockState.getSoundType(); ++ SoundType soundType = blockState.getSoundType(this.level, pos, null); this.level .playLocalSound( - pos, soundtype.getBreakSound(), SoundSource.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F, false + pos, soundType.getBreakSound(), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F, false diff --git a/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch index ac4e502fcf..ea79aef0e9 100644 --- a/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/LevelRenderer.java.patch @@ -8,69 +8,68 @@ } @Override -@@ -515,8 +_,9 @@ - this.addSkyPass(framegraphbuilder, cameraState, terrainFog); +@@ -518,7 +_,8 @@ + this.addSkyPass(frame, cameraState, terrainFog); } +- this.addMainPass(frame, cullFrustum, modelViewMatrix, terrainFog, renderOutline, this.levelRenderState, deltaTracker, profiler, chunkSectionsToRender); + var hasCustomOutline = this.levelRenderState.blockOutlineRenderState != null && this.levelRenderState.blockOutlineRenderState.customRenderer() != null; - this.addMainPass( -- framegraphbuilder, frustum, modelViewMatrix, terrainFog, renderOutline, this.levelRenderState, deltaTracker, profilerfiller, chunkSectionsToRender -+ framegraphbuilder, frustum, modelViewMatrix, terrainFog, renderOutline | hasCustomOutline, this.levelRenderState, deltaTracker, profilerfiller, chunkSectionsToRender - ); - PostChain postchain1 = this.minecraft.getShaderManager().getPostChain(ENTITY_OUTLINE_POST_CHAIN_ID, LevelTargetBundle.OUTLINE_TARGETS); - if (this.levelRenderState.haveGlowingEntities && postchain1 != null) { -@@ -543,6 +_,7 @@ ++ this.addMainPass(frame, cullFrustum, modelViewMatrix, terrainFog, renderOutline | hasCustomOutline, this.levelRenderState, deltaTracker, profiler, chunkSectionsToRender); + PostChain entityOutlineChain = this.minecraft.getShaderManager().getPostChain(ENTITY_OUTLINE_POST_CHAIN_ID, LevelTargetBundle.OUTLINE_TARGETS); + if (this.levelRenderState.haveGlowingEntities && entityOutlineChain != null) { + entityOutlineChain.addToFrame(frame, screenWidth, screenHeight, this.targets); +@@ -544,6 +_,7 @@ } - this.addLateDebugPass(framegraphbuilder, this.levelRenderState.cameraRenderState, terrainFog, modelViewMatrix); -+ net.minecraftforge.client.FramePassManager.insertForgePasses(framegraphbuilder, targets, this.levelRenderState); // Forge: Modded passes are inserted here. - profilerfiller.popPush("executeFrameGraph"); - framegraphbuilder.execute(resourceAllocator, new FrameGraphBuilder.Inspector() { + this.addLateDebugPass(frame, this.levelRenderState.cameraRenderState, terrainFog, modelViewMatrix); ++ net.minecraftforge.client.FramePassManager.insertForgePasses(frame, targets, this.levelRenderState); // Forge: Modded passes are inserted here. + profiler.popPush("executeFrameGraph"); + frame.execute(resourceAllocator, new FrameGraphBuilder.Inspector() { { -@@ -580,7 +_,7 @@ - profilerfiller.popPush("entities"); - this.extractVisibleEntities(camera, frustum, deltaTracker, this.levelRenderState); - profilerfiller.popPush("blockEntities"); +@@ -581,7 +_,7 @@ + profiler.popPush("entities"); + this.extractVisibleEntities(camera, cullFrustum, deltaTracker, this.levelRenderState); + profiler.popPush("blockEntities"); - this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState); -+ this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState, frustum); - profilerfiller.popPush("blockOutline"); ++ this.extractVisibleBlockEntities(camera, deltaPartialTick, this.levelRenderState, cullFrustum); + profiler.popPush("blockOutline"); this.extractBlockOutline(camera, this.levelRenderState); - profilerfiller.popPush("blockBreaking"); -@@ -863,7 +_,7 @@ + profiler.popPush("blockBreaking"); +@@ -857,7 +_,7 @@ } } - private void extractVisibleBlockEntities(final Camera camera, final float deltaPartialTick, final LevelRenderState levelRenderState) { + private void extractVisibleBlockEntities(final Camera camera, final float deltaPartialTick, final LevelRenderState levelRenderState, final Frustum frustum) { - Vec3 vec3 = camera.position(); - double d0 = vec3.x(); - double d1 = vec3.y(); -@@ -874,6 +_,7 @@ - List list = sectionrenderdispatcher$rendersection.getSectionMesh().getRenderableBlockEntities(); - if (!list.isEmpty() && !(sectionrenderdispatcher$rendersection.getVisibility(Util.getMillis()) < 0.3F)) { - for (BlockEntity blockentity : list) { -+ if (!frustum.isVisible(blockentity.getRenderBoundingBox())) continue; - BlockPos blockpos = blockentity.getBlockPos(); - SortedSet sortedset = this.destructionProgress.get(blockpos.asLong()); - ModelFeatureRenderer.CrumblingOverlay modelfeaturerenderer$crumblingoverlay; -@@ -902,6 +_,7 @@ - if (blockentity1.isRemoved()) { + Vec3 cameraPos = camera.position(); + double camX = cameraPos.x(); + double camY = cameraPos.y(); +@@ -868,6 +_,7 @@ + List renderableBlockEntities = section.getSectionMesh().getRenderableBlockEntities(); + if (!renderableBlockEntities.isEmpty() && !(section.getVisibility(Util.getMillis()) < 0.3F)) { + for (BlockEntity blockEntity : renderableBlockEntities) { ++ if (!frustum.isVisible(blockEntity.getRenderBoundingBox())) continue; + BlockPos blockPos = blockEntity.getBlockPos(); + SortedSet progresses = this.destructionProgress.get(blockPos.asLong()); + ModelFeatureRenderer.CrumblingOverlay breakProgress; +@@ -895,6 +_,7 @@ + if (blockEntity.isRemoved()) { iterator.remove(); } else { -+ if (!frustum.isVisible(blockentity1.getRenderBoundingBox())) continue; - BlockEntityRenderState blockentityrenderstate1 = this.blockEntityRenderDispatcher.tryExtractRenderState(blockentity1, deltaPartialTick, null); - if (blockentityrenderstate1 != null) { - levelRenderState.blockEntityRenderStates.add(blockentityrenderstate1); -@@ -938,7 +_,7 @@ - SortedSet sortedset = entry.getValue(); - if (sortedset != null && !sortedset.isEmpty()) { - int i = sortedset.last().getProgress(); -- levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(blockpos, this.level.getBlockState(blockpos), i)); -+ levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(blockpos, this.level.getBlockState(blockpos), i, this.level.getModelDataManager().getAtOrEmpty(blockpos))); ++ if (!frustum.isVisible(blockEntity.getRenderBoundingBox())) continue; + BlockEntityRenderState state = this.blockEntityRenderDispatcher.tryExtractRenderState(blockEntity, deltaPartialTick, null); + if (state != null) { + levelRenderState.blockEntityRenderStates.add(state); +@@ -931,7 +_,7 @@ + SortedSet progresses = entry.getValue(); + if (progresses != null && !progresses.isEmpty()) { + int progress = progresses.last().getProgress(); +- levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(pos, this.level.getBlockState(pos), progress)); ++ levelRenderState.blockBreakingRenderStates.add(new BlockBreakingRenderState(pos, this.level.getBlockState(pos), progress, this.level.getModelDataManager().getAtOrEmpty(pos))); } } } -@@ -966,6 +_,12 @@ +@@ -957,6 +_,12 @@ private void extractBlockOutline(final Camera camera, final LevelRenderState levelRenderState) { levelRenderState.blockOutlineRenderState = null; @@ -80,30 +79,30 @@ + return; + } + - if (this.minecraft.hitResult instanceof BlockHitResult blockhitresult) { - if (blockhitresult.getType() != HitResult.Type.MISS) { - BlockPos blockpos = blockhitresult.getBlockPos(); -@@ -999,6 +_,10 @@ + if (this.minecraft.hitResult instanceof BlockHitResult blockHitResult) { + if (blockHitResult.getType() != HitResult.Type.MISS) { + BlockPos pos = blockHitResult.getBlockPos(); +@@ -990,6 +_,10 @@ ) { - BlockOutlineRenderState blockoutlinerenderstate = levelRenderState.blockOutlineRenderState; - if (blockoutlinerenderstate != null) { -+ if (blockoutlinerenderstate.customRenderer() != null) { -+ blockoutlinerenderstate.customRenderer().render(bufferSource, poseStack, onlyTranslucentBlocks, levelRenderState); + BlockOutlineRenderState state = levelRenderState.blockOutlineRenderState; + if (state != null) { ++ if (state.customRenderer() != null) { ++ state.customRenderer().render(bufferSource, poseStack, onlyTranslucentBlocks, levelRenderState); + return; + } - if (blockoutlinerenderstate.isTranslucent() == onlyTranslucentBlocks) { - Vec3 vec3 = levelRenderState.cameraRenderState.pos; - if (blockoutlinerenderstate.highContrast()) { -@@ -1491,7 +_,7 @@ + if (state.isTranslucent() == onlyTranslucentBlocks) { + Vec3 cameraPos = levelRenderState.cameraRenderState.pos; + if (state.highContrast()) { +@@ -1458,7 +_,7 @@ } else { - int i = brightnessGetter.packedBrightness(level, pos); - int j = LightCoordsUtil.block(i); -- int k = state.getLightEmission(); -+ int k = state.getLightEmission(level, pos); - return j < k ? LightCoordsUtil.withBlock(i, k) : i; + int packedBrightness = brightnessGetter.packedBrightness(level, pos); + int block = LightCoordsUtil.block(packedBrightness); +- int blockSelfEmission = state.getLightEmission(); ++ int blockSelfEmission = state.getLightEmission(level, pos); + return block < blockSelfEmission ? LightCoordsUtil.withBlock(packedBrightness, blockSelfEmission) : packedBrightness; } } -@@ -1539,6 +_,18 @@ +@@ -1506,6 +_,18 @@ public CloudRenderer getCloudRenderer() { return this.cloudRenderer; diff --git a/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch index 1ce73125ff..1d22bf1826 100644 --- a/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/ScreenEffectRenderer.java.patch @@ -4,30 +4,30 @@ Player player = this.minecraft.player; if (isFirstPerson && !isSleeping) { if (!player.noPhysics) { -- BlockState blockstate = getViewBlockingState(player); +- BlockState blockState = getViewBlockingState(player); + var overlay = getOverlayBlock(player); -+ BlockState blockstate = overlay == null ? null : overlay.getLeft(); - if (blockstate != null) { -+ if (!net.minecraftforge.client.ForgeHooksClient.renderBlockOverlay(player, posestack, net.minecraftforge.client.event.RenderBlockScreenEffectEvent.OverlayType.BLOCK, overlay.getLeft(), overlay.getRight())) - renderTex(this.minecraft.getModelManager().getBlockStateModelSet().getParticleMaterial(blockstate).sprite(), posestack, this.bufferSource); ++ BlockState blockState = overlay == null ? null : overlay.getLeft(); + if (blockState != null) { ++ if (!net.minecraftforge.client.ForgeHooksClient.renderBlockOverlay(player, poseStack, net.minecraftforge.client.event.RenderBlockScreenEffectEvent.OverlayType.BLOCK, overlay.getLeft(), overlay.getRight())) + renderTex(this.minecraft.getModelManager().getBlockStateModelSet().getParticleMaterial(blockState).sprite(), poseStack, this.bufferSource); } } if (!this.minecraft.player.isSpectator()) { if (this.minecraft.player.isEyeInFluid(FluidTags.WATER)) { -+ if (!net.minecraftforge.client.ForgeHooksClient.renderWaterOverlay(player, posestack)) - renderWater(this.minecraft, posestack, this.bufferSource); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderWaterOverlay(player, poseStack)) + renderWater(this.minecraft, poseStack, this.bufferSource); + } else if (!player.getEyeInFluidType().isAir()) { -+ net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(player.getEyeInFluidType()).renderOverlay(this.minecraft, posestack, this.bufferSource); ++ net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(player.getEyeInFluidType()).renderOverlay(this.minecraft, poseStack, this.bufferSource); } if (this.minecraft.player.isOnFire()) { - TextureAtlasSprite textureatlassprite = this.sprites.get(ModelBakery.FIRE_1); -+ if (!net.minecraftforge.client.ForgeHooksClient.renderFireOverlay(player, posestack)) - renderFire(posestack, this.bufferSource, textureatlassprite); + TextureAtlasSprite fireSprite = this.sprites.get(ModelBakery.FIRE_1); ++ if (!net.minecraftforge.client.ForgeHooksClient.renderFireOverlay(player, poseStack)) + renderFire(poseStack, this.bufferSource, fireSprite); } } -@@ -126,6 +_,11 @@ +@@ -124,6 +_,11 @@ } private static @Nullable BlockState getViewBlockingState(final Player player) { @@ -36,19 +36,19 @@ + } + + private static org.apache.commons.lang3.tuple.@Nullable Pair getOverlayBlock(Player player) { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + BlockPos.MutableBlockPos testPos = new BlockPos.MutableBlockPos(); for (int i = 0; i < 8; i++) { -@@ -135,7 +_,7 @@ - blockpos$mutableblockpos.set(d0, d1, d2); - BlockState blockstate = player.level().getBlockState(blockpos$mutableblockpos); - if (blockstate.getRenderShape() != RenderShape.INVISIBLE && blockstate.isViewBlocking(player.level(), blockpos$mutableblockpos)) { -- return blockstate; -+ return org.apache.commons.lang3.tuple.Pair.of(blockstate, blockpos$mutableblockpos.immutable()); +@@ -133,7 +_,7 @@ + testPos.set(xo, yo, zo); + BlockState blockState = player.level().getBlockState(testPos); + if (blockState.getRenderShape() != RenderShape.INVISIBLE && blockState.isViewBlocking(player.level(), testPos)) { +- return blockState; ++ return org.apache.commons.lang3.tuple.Pair.of(blockState, testPos.immutable()); } } -@@ -163,6 +_,10 @@ +@@ -161,6 +_,10 @@ } private static void renderWater(final Minecraft minecraft, final PoseStack poseStack, final MultiBufferSource bufferSource) { @@ -56,15 +56,15 @@ + } + + public static void renderFluid(Minecraft minecraft, PoseStack poseStack, MultiBufferSource bufferSource, Identifier texture) { - BlockPos blockpos = BlockPos.containing(minecraft.player.getX(), minecraft.player.getEyeY(), minecraft.player.getZ()); - float f = Lightmap.getBrightness(minecraft.player.level().dimensionType(), minecraft.player.level().getMaxLocalRawBrightness(blockpos)); - int i = ARGB.colorFromFloat(0.1F, f, f, f); -@@ -175,7 +_,7 @@ - float f7 = -minecraft.player.getYRot() / 64.0F; - float f8 = minecraft.player.getXRot() / 64.0F; - Matrix4f matrix4f = poseStack.last().pose(); -- VertexConsumer vertexconsumer = bufferSource.getBuffer(RenderTypes.blockScreenEffect(UNDERWATER_LOCATION)); -+ VertexConsumer vertexconsumer = bufferSource.getBuffer(RenderTypes.blockScreenEffect(texture)); - vertexconsumer.addVertex(matrix4f, -1.0F, -1.0F, -0.5F).setUv(4.0F + f7, 4.0F + f8).setColor(i); - vertexconsumer.addVertex(matrix4f, 1.0F, -1.0F, -0.5F).setUv(0.0F + f7, 4.0F + f8).setColor(i); - vertexconsumer.addVertex(matrix4f, 1.0F, 1.0F, -0.5F).setUv(0.0F + f7, 0.0F + f8).setColor(i); + BlockPos pos = BlockPos.containing(minecraft.player.getX(), minecraft.player.getEyeY(), minecraft.player.getZ()); + float br = Lightmap.getBrightness(minecraft.player.level().dimensionType(), minecraft.player.level().getMaxLocalRawBrightness(pos)); + int color = ARGB.colorFromFloat(0.1F, br, br, br); +@@ -173,7 +_,7 @@ + float uo = -minecraft.player.getYRot() / 64.0F; + float vo = minecraft.player.getXRot() / 64.0F; + Matrix4f pose = poseStack.last().pose(); +- VertexConsumer builder = bufferSource.getBuffer(RenderTypes.blockScreenEffect(UNDERWATER_LOCATION)); ++ VertexConsumer builder = bufferSource.getBuffer(RenderTypes.blockScreenEffect(texture)); + builder.addVertex(pose, -1.0F, -1.0F, -0.5F).setUv(4.0F + uo, 4.0F + vo).setColor(color); + builder.addVertex(pose, 1.0F, -1.0F, -0.5F).setUv(0.0F + uo, 4.0F + vo).setColor(color); + builder.addVertex(pose, 1.0F, 1.0F, -0.5F).setUv(0.0F + uo, 0.0F + vo).setColor(color); diff --git a/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch index 7923bbe67d..4a67c8ed23 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/FluidRenderer.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/client/renderer/block/FluidRenderer.java +++ b/net/minecraft/client/renderer/block/FluidRenderer.java @@ -87,8 +_,10 @@ - boolean flag5 = shouldRenderFace(fluidState, blockState, Direction.EAST, fluidstate5); - if (flag || flag1 || flag5 || flag4 || flag2 || flag3) { - FluidModel fluidmodel = this.fluidModels.get(fluidState); + boolean renderEast = shouldRenderFace(fluidState, blockState, Direction.EAST, fluidStateEast); + if (renderUp || renderDown || renderEast || renderWest || renderNorth || renderSouth) { + FluidModel model = this.fluidModels.get(fluidState); + var fluidExt = net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions.of(fluidState); -+ fluidmodel = fluidExt.getModel(fluidState, level, pos, fluidmodel); - VertexConsumer vertexconsumer = output.getBuilder(fluidmodel.layer()); -- int i = fluidmodel.tintSource() != null ? fluidmodel.tintSource().colorInWorld(blockState, level, pos) : -1; -+ int i = fluidmodel.tintSource() != null ? fluidmodel.tintSource().colorInWorld(blockState, level, pos) : fluidExt.getTintColor(); - CardinalLighting cardinallighting = level.cardinalLighting(); - Fluid fluid = fluidState.getType(); - float f4 = this.getHeight(level, fluid, pos, blockState, fluidState); -@@ -284,7 +_,7 @@ - boolean flag7 = false; - if (fluidmodel.overlayMaterial() != null) { - Block block = blockstate6.getBlock(); -- if (block instanceof HalfTransparentBlock || block instanceof LeavesBlock) { -+ if (blockstate6.shouldDisplayFluidOverlay(level, pos.relative(direction), fluidState)) { - textureatlassprite3 = fluidmodel.overlayMaterial().sprite(); - flag7 = true; ++ model = fluidExt.getModel(fluidState, level, pos, model); + VertexConsumer builder = output.getBuilder(model.layer()); +- int tintColor = model.tintSource() != null ? model.tintSource().colorInWorld(blockState, level, pos) : -1; ++ int tintColor = model.tintSource() != null ? model.tintSource().colorInWorld(blockState, level, pos) : fluidExt.getTintColor(); + CardinalLighting cardinalLighting = level.cardinalLighting(); + Fluid type = fluidState.getType(); + float heightSelf = this.getHeight(level, type, pos, blockState, fluidState); +@@ -295,7 +_,7 @@ + boolean isOverlay = false; + if (model.overlayMaterial() != null) { + Block relativeBlock = faceState.getBlock(); +- if (relativeBlock instanceof HalfTransparentBlock || relativeBlock instanceof LeavesBlock) { ++ if (faceState.shouldDisplayFluidOverlay(level, pos.relative(faceDir), fluidState)) { + sprite = model.overlayMaterial().sprite(); + isOverlay = true; } diff --git a/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch index 676b261c60..6607f98f7e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/ModelBlockRenderer.java.patch @@ -26,9 +26,9 @@ + model.collectParts(this.random, this.parts, modelData); if (!this.parts.isEmpty()) { try { - Vec3 vec3 = blockState.getOffset(pos); + Vec3 offset = blockState.getOffset(pos); - if (this.ambientOcclusion && blockState.getLightEmission() == 0 && this.parts.getFirst().useAmbientOcclusion()) { + if (this.ambientOcclusion && blockState.getLightEmission(level, pos) == 0 && this.parts.getFirst().useAmbientOcclusion()) { - this.tesselateAmbientOcclusion(output, x + (float)vec3.x, y + (float)vec3.y, z + (float)vec3.z, this.parts, level, blockState, pos); + this.tesselateAmbientOcclusion(output, x + (float)offset.x, y + (float)offset.y, z + (float)offset.z, this.parts, level, blockState, pos); } else { - this.tesselateFlat(output, x + (float)vec3.x, y + (float)vec3.y, z + (float)vec3.z, this.parts, level, blockState, pos); + this.tesselateFlat(output, x + (float)offset.x, y + (float)offset.y, z + (float)offset.z, this.parts, level, blockState, pos); diff --git a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch index 35eb5a4d6e..9cf6048610 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java +++ b/net/minecraft/client/renderer/block/dispatch/BlockStateModel.java -@@ -22,9 +_,11 @@ +@@ -21,9 +_,11 @@ import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) diff --git a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch index 0b9c85bb8d..17002e9c96 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/WeightedVariants.java.patch @@ -8,9 +8,9 @@ public WeightedVariants(final WeightedList list) { this.list = list; - BlockStateModel blockstatemodel = list.unwrap().getFirst().value(); - this.particleMaterial = blockstatemodel.particleMaterial(); -+ this.first = blockstatemodel; + BlockStateModel firstModel = list.unwrap().getFirst().value(); + this.particleMaterial = firstModel.particleMaterial(); ++ this.first = firstModel; this.materialFlags = computeMaterialFlags(list); } diff --git a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch index d221d7c5b3..0cd8f69738 100644 --- a/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/block/dispatch/multipart/MultiPartModel.java.patch @@ -28,10 +28,10 @@ } @@ -54,7 +_,7 @@ - for (BlockStateModel blockstatemodel : this.models) { - random.setSeed(i); -- blockstatemodel.collectParts(random, output); -+ blockstatemodel.collectParts(random, output, data); + for (BlockStateModel model : this.models) { + random.setSeed(seed); +- model.collectParts(random, output); ++ model.collectParts(random, output, data); } } diff --git a/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch index 499a66c7a0..6c34bb4d4b 100644 --- a/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java +++ b/net/minecraft/client/renderer/blockentity/SkullBlockRenderer.java -@@ -44,6 +_,7 @@ +@@ -43,6 +_,7 @@ public static final WallAndGroundTransformations TRANSFORMATIONS = new WallAndGroundTransformations<>( SkullBlockRenderer::createWallTransformation, SkullBlockRenderer::createGroundTransformation, 16 ); @@ -8,7 +8,7 @@ private final Function modelByType; public static final Map SKIN_BY_TYPE = Util.make(Maps.newHashMap(), map -> { map.put(SkullBlock.Types.SKELETON, Identifier.withDefaultNamespace("textures/entity/skeleton/skeleton.png")); -@@ -68,7 +_,9 @@ +@@ -67,7 +_,9 @@ case PIGLIN -> new PiglinHeadModel(modelSet.bakeLayer(ModelLayers.PIGLIN_HEAD)); }); } else { diff --git a/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch b/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch index 48c6a97f1c..647b9c78fd 100644 --- a/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/chunk/SectionCompiler.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/client/renderer/chunk/SectionCompiler.java +++ b/net/minecraft/client/renderer/chunk/SectionCompiler.java -@@ -63,6 +_,7 @@ +@@ -61,6 +_,7 @@ public SectionCompiler.Results compile( final SectionPos sectionPos, final RenderSectionRegion region, final VertexSorting vertexSorting, final SectionBufferBuilderPack builders ) { + var modelDataMap = net.minecraft.client.Minecraft.getInstance().level.getModelDataManager().getAt(sectionPos); - SectionCompiler.Results sectioncompiler$results = new SectionCompiler.Results(); - BlockPos blockpos = sectionPos.origin(); - BlockPos blockpos1 = blockpos.offset(15, 15, 15); -@@ -111,7 +_,8 @@ - blockpos2, - blockstate, - this.blockModelSet.get(blockstate), -- blockstate.getSeed(blockpos2) -+ blockstate.getSeed(blockpos2), -+ modelDataMap.getOrDefault(blockpos2, net.minecraftforge.client.model.data.ModelData.EMPTY) + SectionCompiler.Results results = new SectionCompiler.Results(); + BlockPos minPos = sectionPos.origin(); + BlockPos maxPos = minPos.offset(15, 15, 15); +@@ -109,7 +_,8 @@ + pos, + blockState, + this.blockModelSet.get(blockState), +- blockState.getSeed(pos) ++ blockState.getSeed(pos), ++ modelDataMap.getOrDefault(pos, net.minecraftforge.client.model.data.ModelData.EMPTY) ); } - } catch (Throwable throwable) { + } catch (Throwable var21) { diff --git a/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch b/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch index 4112c208bd..f84ccf0f15 100644 --- a/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/culling/Frustum.java.patch @@ -6,6 +6,6 @@ public boolean isVisible(final AABB bb) { + // Forge: exit early for infinite bounds, these would otherwise fail in the intersection test at certain camera angles (GH-9321) + if (bb.equals(net.minecraftforge.common.extensions.IForgeBlockEntity.INFINITE_EXTENT_AABB)) return true; - int i = this.cubeInFrustum(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); - return i == -2 || i == -1; + int intersectionResult = this.cubeInFrustum(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ); + return intersectionResult == -2 || intersectionResult == -1; } diff --git a/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch index 84d27d0637..454a39430f 100644 --- a/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java +++ b/net/minecraft/client/renderer/debug/EntityHitboxDebugRenderer.java -@@ -93,8 +_,8 @@ +@@ -98,8 +_,8 @@ ); } -- if (entity instanceof EnderDragon enderdragon) { -- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { +- if (entity instanceof EnderDragon dragon) { +- for (EnderDragonPart subEntity : dragon.getSubEntities()) { + if (entity.isMultipartEntity()) { -+ for (var enderdragonpart : entity.getParts()) { - Vec3 vec34 = enderdragonpart.position(); - Vec3 vec35 = enderdragonpart.getPosition(partialTicks); - Vec3 vec36 = vec35.subtract(vec34); ++ for (var subEntity : entity.getParts()) { + Vec3 latestSubPosition = subEntity.position(); + Vec3 currentSubPosition = subEntity.getPosition(partialTicks); + Vec3 subOffset = currentSubPosition.subtract(latestSubPosition); diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch index 022b06d41b..a04ce8151e 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java +++ b/net/minecraft/client/renderer/entity/EntityRenderDispatcher.java -@@ -209,6 +_,14 @@ +@@ -207,6 +_,14 @@ return this.itemInHandRenderer; } @@ -14,11 +14,11 @@ + @Override public void onResourceManagerReload(final ResourceManager resourceManager) { - EntityRendererProvider.Context entityrendererprovider$context = new EntityRendererProvider.Context( -@@ -226,5 +_,6 @@ - this.renderers = EntityRenderers.createEntityRenderers(entityrendererprovider$context); - this.playerRenderers = EntityRenderers.createAvatarRenderers(entityrendererprovider$context); - this.mannequinRenderers = EntityRenderers.createAvatarRenderers(entityrendererprovider$context); -+ net.minecraftforge.client.event.ForgeEventFactoryClient.onGatherLayers(renderers, playerRenderers, mannequinRenderers, entityrendererprovider$context); + EntityRendererProvider.Context context = new EntityRendererProvider.Context( +@@ -224,5 +_,6 @@ + this.renderers = EntityRenderers.createEntityRenderers(context); + this.playerRenderers = EntityRenderers.createAvatarRenderers(context); + this.mannequinRenderers = EntityRenderers.createAvatarRenderers(context); ++ net.minecraftforge.client.event.ForgeEventFactoryClient.onGatherLayers(renderers, playerRenderers, mannequinRenderers, context); } } diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch index 444d0bfebb..24854d9d4c 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/EntityRenderer.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/renderer/entity/EntityRenderer.java +++ b/net/minecraft/client/renderer/entity/EntityRenderer.java -@@ -126,16 +_,17 @@ +@@ -128,16 +_,17 @@ final S state, final PoseStack poseStack, final SubmitNodeCollector submitNodeCollector, final CameraRenderState camera, final int offset ) { poseStack.pushPose(); @@ -22,12 +22,12 @@ ); } -@@ -187,7 +_,7 @@ +@@ -189,7 +_,7 @@ if (this.entityRenderDispatcher.camera != null) { state.distanceToCameraSq = this.entityRenderDispatcher.distanceToSqr(entity); -- boolean flag1 = state.distanceToCameraSq < 4096.0 && this.shouldShowName(entity, state.distanceToCameraSq); -+ boolean flag1 = net.minecraftforge.client.ForgeHooksClient.isNameplateInRenderDistance(entity, state.distanceToCameraSq) && this.shouldShowName(entity, state.distanceToCameraSq); - if (flag1) { +- boolean shouldShowName = state.distanceToCameraSq < 4096.0 && this.shouldShowName(entity, state.distanceToCameraSq); ++ boolean shouldShowName = net.minecraftforge.client.ForgeHooksClient.isNameplateInRenderDistance(entity, state.distanceToCameraSq) && this.shouldShowName(entity, state.distanceToCameraSq); + if (shouldShowName) { state.nameTag = this.getNameTag(entity); state.nameTagAttachment = entity.getAttachments().getNullable(EntityAttachment.NAME_TAG, 0, entity.getYRot(partialTicks)); diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch index 3e7cdc88f0..3cc42ac3d9 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/ItemFrameRenderer.java.patch @@ -2,17 +2,17 @@ +++ b/net/minecraft/client/renderer/entity/ItemFrameRenderer.java @@ -82,6 +_,7 @@ if (state.mapId != null) { - int i = state.rotation % 4 * 2; - poseStack.mulPose(Axis.ZP.rotationDegrees(i * 360.0F / 8.0F)); + int rotation = state.rotation % 4 * 2; + poseStack.mulPose(Axis.ZP.rotationDegrees(rotation * 360.0F / 8.0F)); + if (!net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderItemInFrame(state, this, poseStack, submitNodeCollector, state.lightCoords)) { poseStack.mulPose(Axis.ZP.rotationDegrees(180.0F)); - float f2 = 0.0078125F; + float s = 0.0078125F; poseStack.scale(0.0078125F, 0.0078125F, 0.0078125F); @@ -89,6 +_,7 @@ poseStack.translate(0.0F, 0.0F, -1.0F); - int j = this.getLightCoords(state.isGlowFrame, 15728850, state.lightCoords); - this.mapRenderer.render(state.mapRenderState, poseStack, submitNodeCollector, true, j); + int lightCoords = this.getLightCoords(state.isGlowFrame, 15728850, state.lightCoords); + this.mapRenderer.render(state.mapRenderState, poseStack, submitNodeCollector, true, lightCoords); + } } else if (!state.item.isEmpty()) { poseStack.mulPose(Axis.ZP.rotationDegrees(state.rotation * 360.0F / 8.0F)); - int k = this.getLightCoords(state.isGlowFrame, 15728880, state.lightCoords); + int lightVal = this.getLightCoords(state.isGlowFrame, 15728880, state.lightCoords); diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch index 357e2023ec..d4694ecaba 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/LivingEntityRenderer.java.patch @@ -7,8 +7,8 @@ + if (net.minecraftforge.client.event.ForgeEventFactoryClient.onRenderLivingPre(state, this, poseStack, submitNodeCollector, camera)) return; poseStack.pushPose(); if (state.hasPose(Pose.SLEEPING)) { - Direction direction = state.bedOrientation; -@@ -107,6 +_,7 @@ + Direction bedOrientation = state.bedOrientation; +@@ -109,6 +_,7 @@ poseStack.popPose(); super.submit(state, poseStack, submitNodeCollector, camera); @@ -16,7 +16,7 @@ } protected boolean shouldRenderLayers(final S state) { -@@ -283,7 +_,7 @@ +@@ -285,7 +_,7 @@ state.isFullyFrozen = entity.isFullyFrozen(); state.isBaby = entity.isBaby(); diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch index db416febd6..909399e425 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java.patch @@ -1,23 +1,21 @@ --- a/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java +++ b/net/minecraft/client/renderer/entity/layers/HumanoidArmorLayer.java -@@ -66,6 +_,7 @@ +@@ -66,12 +_,13 @@ Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE); if (equippable != null && shouldRender(equippable, slot)) { - A a = this.getArmorModel(state, slot); -+ var model = this.getArmorModel(state, slot, itemStack, a); - EquipmentClientInfo.LayerType equipmentclientinfo$layertype = state.isBaby && state.entityType != EntityType.ARMOR_STAND + A model = this.getArmorModel(state, slot); ++ var newModel = this.getArmorModel(state, slot, itemStack, model); + EquipmentClientInfo.LayerType layerType = state.isBaby && state.entityType != EntityType.ARMOR_STAND ? EquipmentClientInfo.LayerType.HUMANOID_BABY : (this.usesInnerModel(slot) ? EquipmentClientInfo.LayerType.HUMANOID_LEGGINGS : EquipmentClientInfo.LayerType.HUMANOID); -@@ -73,7 +_,7 @@ + this.equipmentRenderer .renderLayers( - equipmentclientinfo$layertype, - equippable.assetId().orElseThrow(), -- a, -+ model, - state, - itemStack, - poseStack, -@@ -90,5 +_,12 @@ +- layerType, equippable.assetId().orElseThrow(), model, state, itemStack, poseStack, submitNodeCollector, lightCoords, state.outlineColor ++ layerType, equippable.assetId().orElseThrow(), newModel, state, itemStack, poseStack, submitNodeCollector, lightCoords, state.outlineColor + ); + } + } +@@ -82,5 +_,12 @@ private boolean usesInnerModel(final EquipmentSlot slot) { return slot == EquipmentSlot.LEGS; diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch index 36e65971d9..67cdb05fa5 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/layers/WingsLayer.java.patch @@ -6,6 +6,6 @@ - protected static @Nullable Identifier getPlayerElytraTexture(final HumanoidRenderState state) { + protected @Nullable Identifier getPlayerElytraTexture(final HumanoidRenderState state) { - if (state instanceof AvatarRenderState avatarrenderstate) { - PlayerSkin playerskin = avatarrenderstate.skin; - if (playerskin.elytra() != null) { + if (state instanceof AvatarRenderState playerState) { + PlayerSkin skin = playerState.skin; + if (skin.elytra() != null) { diff --git a/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch index 7fb5516fd1..ed46262468 100644 --- a/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/entity/player/AvatarRenderer.java.patch @@ -10,7 +10,7 @@ } else { if (avatar.getUsedItemHand() == hand && avatar.getUseItemRemainingTicks() > 0) { @@ -138,7 +_,9 @@ - if (swinganimation != null && swinganimation.type() == SwingAnimationType.STAB && avatar.swinging) { + if (attack != null && attack.type() == SwingAnimationType.STAB && avatar.swinging) { return HumanoidModel.ArmPose.SPEAR; } else { - return itemInHand.is(ItemTags.SPEARS) ? HumanoidModel.ArmPose.SPEAR : HumanoidModel.ArmPose.ITEM; diff --git a/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch index 9b2cc91f11..bd1f2f3a48 100644 --- a/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java +++ b/net/minecraft/client/renderer/feature/BlockFeatureRenderer.java -@@ -164,7 +_,7 @@ - this.random.setSeed(submitnodestorage$breakingblockmodelsubmit.seed()); +@@ -153,7 +_,7 @@ + this.random.setSeed(submit.seed()); try { -- submitnodestorage$breakingblockmodelsubmit.model().collectParts(this.random, this.parts); -+ submitnodestorage$breakingblockmodelsubmit.model().collectParts(this.random, this.parts, submitnodestorage$breakingblockmodelsubmit.data()); +- submit.model().collectParts(this.random, this.parts); ++ submit.model().collectParts(this.random, this.parts, submit.data()); - for (BlockStateModelPart blockstatemodelpart : this.parts) { - putPartQuads(blockstatemodelpart, submitnodestorage$breakingblockmodelsubmit.pose(), this.quadInstance, NO_TINT, vertexconsumer, null); + for (BlockStateModelPart part : this.parts) { + putPartQuads(part, submit.pose(), this.quadInstance, NO_TINT, buffer, null); diff --git a/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch b/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch index 688160ecff..bcf3d046c2 100644 --- a/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/fog/FogRenderer.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/client/renderer/fog/FogRenderer.java +++ b/net/minecraft/client/renderer/fog/FogRenderer.java @@ -153,6 +_,12 @@ - f2 = Mth.lerp(f6, f2, f2 * f7); + fogBlue = Mth.lerp(brightenFactor, fogBlue, fogBlue * targetScale); } -+ var fogColor = net.minecraftforge.client.ForgeHooksClient.getFogColor(camera, partialTicks, level, renderDistance, darkenWorldAmount, f5, f1, f2); ++ var fogColor = net.minecraftforge.client.ForgeHooksClient.getFogColor(camera, partialTicks, level, renderDistance, darkenWorldAmount, fogRed, fogGreen, fogBlue); + -+ f5 = fogColor.x(); -+ f1 = fogColor.y(); -+ f2 = fogColor.z(); ++ fogRed = fogColor.x(); ++ fogGreen = fogColor.y(); ++ fogBlue = fogColor.z(); + - dest.set(f5, f1, f2, 1.0F); + dest.set(fogRed, fogGreen, fogBlue, 1.0F); } } @@ -181,6 +_,7 @@ - float f2 = Mth.clamp(f1 / 10.0F, 4.0F, 64.0F); - fogdata.renderDistanceStart = f1 - f2; - fogdata.renderDistanceEnd = f1; -+ fogdata.color = net.minecraftforge.client.ForgeHooksClient.setupFog(fogtype, camera, deltaTracker, fogdata, fogdata.color); - return fogdata; + float renderDistanceFogSpan = Mth.clamp(renderDistanceInBlocks / 10.0F, 4.0F, 64.0F); + fog.renderDistanceStart = renderDistanceInBlocks - renderDistanceFogSpan; + fog.renderDistanceEnd = renderDistanceInBlocks; ++ fog.color = net.minecraftforge.client.ForgeHooksClient.setupFog(fogType, camera, deltaTracker, fog, fog.color); + return fog; } diff --git a/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch b/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch index b8a7a9c88e..c53b513c7b 100644 --- a/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/rendertype/RenderSetup.java.patch @@ -30,9 +30,9 @@ ); } -+ map.putAll(this.texturesWithSamplers); ++ result.putAll(this.texturesWithSamplers); + - return map; + return result; } } @@ -150,6 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch index 3239ef2fb1..591ad8c712 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/MipmapGenerator.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/client/renderer/texture/MipmapGenerator.java +++ b/net/minecraft/client/renderer/texture/MipmapGenerator.java @@ -122,12 +_,16 @@ - float f = mipmapStrategy == MipmapStrategy.STRICT_CUTOUT ? 0.3F : 0.5F; - float f1 = flag ? alphaTestCoverage(currentMips[0], f, 1.0F) : 0.0F; + float cutoutRef = mipmapStrategy == MipmapStrategy.STRICT_CUTOUT ? 0.3F : 0.5F; + float originalCoverage = isCutoutMip ? alphaTestCoverage(currentMips[0], cutoutRef, 1.0F) : 0.0F; -+ int maxMipmapLevel = net.minecraftforge.client.ForgeHooksClient.getMaxMipmapLevel(anativeimage[0].getWidth(), anativeimage[0].getHeight()); - for (int i = 1; i <= newMipLevel; i++) { - if (i < currentMips.length) { - anativeimage[i] = currentMips[i]; ++ int maxMipmapLevel = net.minecraftforge.client.ForgeHooksClient.getMaxMipmapLevel(result[0].getWidth(), result[0].getHeight()); + for (int level = 1; level <= newMipLevel; level++) { + if (level < currentMips.length) { + result[level] = currentMips[level]; } else { - NativeImage nativeimage = anativeimage[i - 1]; -- NativeImage nativeimage1 = new NativeImage(nativeimage.getWidth() >> 1, nativeimage.getHeight() >> 1, false); + NativeImage lastData = result[level - 1]; +- NativeImage data = new NativeImage(lastData.getWidth() >> 1, lastData.getHeight() >> 1, false); + // Forge: Guard against invalid texture size, because we allow generating mipmaps regardless of texture sizes -+ NativeImage nativeimage1 = new NativeImage(Math.max(1, nativeimage.getWidth() >> 1), Math.max(1, nativeimage.getHeight() >> 1), false); -+ if (i <= maxMipmapLevel) { ++ NativeImage data = new NativeImage(Math.max(1, lastData.getWidth() >> 1), Math.max(1, lastData.getHeight() >> 1), false); ++ if (level <= maxMipmapLevel) { + - int j = nativeimage1.getWidth(); - int k = nativeimage1.getHeight(); + int width = data.getWidth(); + int height = data.getHeight(); @@ -146,6 +_,7 @@ - nativeimage1.setPixel(l, i1, j2); + data.setPixel(x, y, color); } + } } - anativeimage[i] = nativeimage1; + result[level] = data; diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch index c8a1dd5a2a..adf953788d 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/SpriteLoader.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/client/renderer/texture/SpriteLoader.java +++ b/net/minecraft/client/renderer/texture/SpriteLoader.java @@ -72,7 +_,7 @@ - int j1 = Math.min(j, k); - int k1 = Mth.log2(j1); - int l1; -- if (k1 < maxMipmapLevels) { -+ if (k1 < maxMipmapLevels && net.minecraftforge.common.ForgeConfig.CLIENT.allowMipmapLowering()) { // Forge: Do not lower the mipmap level - LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, maxMipmapLevels, k1, j1); - l1 = k1; + int minSize = Math.min(minTexelSize, lowestOneBit); + int minPowerOfTwo = Mth.log2(minSize); + int mipLevel; +- if (minPowerOfTwo < maxMipmapLevels) { ++ if (minPowerOfTwo < maxMipmapLevels && net.minecraftforge.common.ForgeConfig.CLIENT.allowMipmapLowering()) { // Forge: Do not lower the mipmap level + LOGGER.warn("{}: dropping miplevel from {} to {}, because of minimum power of two: {}", this.location, maxMipmapLevels, minPowerOfTwo, minSize); + mipLevel = minPowerOfTwo; } else { -@@ -130,7 +_,8 @@ +@@ -132,7 +_,8 @@ final Executor taskExecutor, final Set> additionalMetadata ) { -- SpriteResourceLoader spriteresourceloader = SpriteResourceLoader.create(additionalMetadata); +- SpriteResourceLoader spriteResourceLoader = SpriteResourceLoader.create(additionalMetadata); + var sections = net.minecraftforge.client.ForgeHooksClient.getAtlastMetadataSections(atlasInfoLocation, additionalMetadata); -+ SpriteResourceLoader spriteresourceloader = SpriteResourceLoader.create(sections); ++ SpriteResourceLoader spriteResourceLoader = SpriteResourceLoader.create(sections); return CompletableFuture.>supplyAsync(() -> SpriteSourceList.load(manager, atlasInfoLocation).list(manager), taskExecutor) - .thenCompose(sprites -> runSpriteSuppliers(spriteresourceloader, (List)sprites, taskExecutor)) + .thenCompose(sprites -> runSpriteSuppliers(spriteResourceLoader, (List)sprites, taskExecutor)) .thenApply(resources -> this.stitch((List)resources, maxMipmapLevels, taskExecutor)); -@@ -139,7 +_,7 @@ +@@ -141,7 +_,7 @@ private Map getStitchedSprites(final Stitcher stitcher, final int atlasWidth, final int atlasHeight) { - Map map = new HashMap<>(); + Map result = new HashMap<>(); stitcher.gatherSprites( -- (contents, x, y, padding) -> map.put(contents.name(), new TextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) -+ (contents, x, y, padding) -> map.put(contents.name(), net.minecraftforge.client.ForgeHooksClient.loadTextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) +- (contents, x, y, padding) -> result.put(contents.name(), new TextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) ++ (contents, x, y, padding) -> result.put(contents.name(), net.minecraftforge.client.ForgeHooksClient.loadTextureAtlasSprite(this.location, contents, atlasWidth, atlasHeight, x, y, padding)) ); - return map; + return result; } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch index bd353204e2..185a35cc17 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/Stitcher.java.patch @@ -10,25 +10,25 @@ .thenComparing(h -> h.entry.name()); @@ -54,6 +_,14 @@ - for (Stitcher.Holder holder : list) { + for (Stitcher.Holder holder : holders) { if (!this.addToStorage(holder)) { + if (LOGGER.isInfoEnabled()) { + StringBuilder sb = new StringBuilder(); + sb.append("Unable to fit: ").append(holder.entry().name()); + sb.append(" - size: ").append(holder.entry.width()).append("x").append(holder.entry.height()); + sb.append(" - Maybe try a lower resolution resourcepack?\n"); -+ list.forEach(h -> sb.append("\t").append(h).append("\n")); ++ holders.forEach(h -> sb.append("\t").append(h).append("\n")); + LOGGER.info(sb.toString()); + } - throw new StitcherException(holder.entry, list.stream().map(h -> h.entry).collect(ImmutableList.toImmutableList())); + throw new StitcherException(holder.entry, holders.stream().map(h -> h.entry).collect(ImmutableList.toImmutableList())); } } @@ -93,7 +_,7 @@ - boolean flag4 = flag2 && j != l; - boolean flag; - if (flag3 ^ flag4) { -- flag = flag3; -+ flag = !flag3 && flag1; // Forge: Fix stitcher not expanding entire height before growing width, and (potentially) growing larger then the max size. + boolean yWillGrow = yCanGrow && yCurrentSize != yNewSize; + boolean growOnX; + if (xWillGrow ^ yWillGrow) { +- growOnX = xWillGrow; ++ growOnX = !xWillGrow && xCanGrow; // Forge: Fix stitcher not expanding entire height before growing width, and (potentially) growing larger then the max size. } else { - flag = flag1 && i <= j; + growOnX = xCanGrow && xCurrentSize <= yCurrentSize; } diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch index dc7f995bb9..65bf550361 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/TextureAtlas.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/client/renderer/texture/TextureAtlas.java +++ b/net/minecraft/client/renderer/texture/TextureAtlas.java -@@ -119,6 +_,7 @@ - this.sprites = list; - this.animatedTexturesStates = List.copyOf(list1); +@@ -123,6 +_,7 @@ + this.sprites = sprites; + this.animatedTexturesStates = List.copyOf(animationStates); this.uploadInitialContents(); + net.minecraftforge.client.ForgeHooksClient.onTextureStitchedPost(this); if (SharedConstants.DEBUG_DUMP_TEXTURE_ATLAS) { - Path path = TextureUtil.getDebugTexturePath(); + Path dumpDir = TextureUtil.getDebugTexturePath(); -@@ -304,5 +_,10 @@ +@@ -302,5 +_,10 @@ int getHeight() { return this.height; diff --git a/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch b/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch index dec5805bd8..3fadacbcc9 100644 --- a/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch +++ b/patches/minecraft/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java +++ b/net/minecraft/client/renderer/texture/atlas/SpriteResourceLoader.java @@ -68,6 +_,9 @@ - framesize = new FrameSize(nativeimage.getWidth(), nativeimage.getHeight()); + frameSize = new FrameSize(image.getWidth(), image.getHeight()); } -+ SpriteContents contents = net.minecraftforge.client.ForgeHooksClient.loadSpriteContents(spriteLocation, resource, framesize, nativeimage, list); ++ SpriteContents contents = net.minecraftforge.client.ForgeHooksClient.loadSpriteContents(spriteLocation, resource, frameSize, image, additionalMetadata); + if (contents != null) return contents; + - return new SpriteContents(spriteLocation, framesize, nativeimage, optional, list, optional1); + return new SpriteContents(spriteLocation, frameSize, image, animationInfo, additionalMetadata, textureInfo); }; } diff --git a/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch b/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch index e951131a98..6247c80ac9 100644 --- a/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/language/LanguageManager.java.patch @@ -11,7 +11,7 @@ private static Map extractLanguages(final Stream resourcePacks) { @@ -68,8 +_,12 @@ - this.reloadCallback.accept(clientlanguage); + this.reloadCallback.accept(locale); } + private java.util.Locale javaLocale; // Forge: add locale information for modders diff --git a/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch b/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch index c156208aa6..b2143eb706 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/BlockStateDefinitions.java.patch @@ -3,9 +3,9 @@ @@ -33,6 +_,8 @@ static Function> definitionLocationToBlockStateMapper() { - Map> map = new HashMap<>(STATIC_DEFINITIONS); + Map> result = new HashMap<>(STATIC_DEFINITIONS); + var event = net.minecraftforge.client.event.ForgeEventFactoryClient.onRegisterModeStateDefinitions(); -+ map.putAll(event.getStates()); ++ result.putAll(event.getStates()); for (Block block : BuiltInRegistries.BLOCK) { - map.put(block.builtInRegistryHolder().key().identifier(), block.getStateDefinition()); + result.put(block.builtInRegistryHolder().key().identifier(), block.getStateDefinition()); diff --git a/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch index 371b6f96db..4ac9113c82 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelDiscovery.java.patch @@ -15,20 +15,20 @@ @Override public String debugName() { return this.id.toString(); -@@ -233,14 +_,14 @@ - QuadCollection quadcollection = this.getSlot(KEY_DEFAULT_GEOMETRY); - return quadcollection != null - ? quadcollection -- : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this)); -+ : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this, getContext())); +@@ -229,14 +_,14 @@ + + private QuadCollection bakeDefaultState(final TextureSlots textureSlots, final ModelBaker baker, final ModelState state) { + QuadCollection result = this.getSlot(KEY_DEFAULT_GEOMETRY); +- return result != null ? result : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this)); ++ return result != null ? result : this.updateSlot(KEY_DEFAULT_GEOMETRY, this.getTopGeometry().bake(textureSlots, baker, state, this, getContext())); } @Override public QuadCollection bakeTopGeometry(final TextureSlots textureSlots, final ModelBaker baker, final ModelState state) { return state == BlockModelRotation.IDENTITY ? this.bakeDefaultState(textureSlots, baker, state) : this.modelBakeCache.computeIfAbsent(state, s -> { - UnbakedGeometry unbakedgeometry = this.getTopGeometry(); -- return unbakedgeometry.bake(textureSlots, baker, s, this); -+ return unbakedgeometry.bake(textureSlots, baker, s, this, getContext()); + UnbakedGeometry topGeometry = this.getTopGeometry(); +- return topGeometry.bake(textureSlots, baker, s, this); ++ return topGeometry.bake(textureSlots, baker, s, this, getContext()); }); } } diff --git a/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch b/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch index 94851681bf..fb2918adae 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/ModelManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/resources/model/ModelManager.java +++ b/net/minecraft/client/resources/model/ModelManager.java -@@ -68,6 +_,7 @@ +@@ -67,6 +_,7 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final FileToIdConverter MODEL_LISTER = FileToIdConverter.json("models"); private Map bakedItemStackModels = Map.of(); @@ -8,7 +8,7 @@ private Map itemProperties = Map.of(); private final AtlasManager atlasManager; private final PlayerSkinRenderCache playerSkinRenderCache; -@@ -78,6 +_,7 @@ +@@ -77,6 +_,7 @@ private @Nullable BlockModelSet blockModelSet; private @Nullable FluidStateModelSet fluidStateModelSet; private Object2IntMap modelGroups = Object2IntMaps.emptyMap(); @@ -16,7 +16,7 @@ public ModelManager(final BlockColors blockColors, final AtlasManager atlasManager, final PlayerSkinRenderCache playerSkinRenderCache) { this.blockColors = blockColors; -@@ -89,6 +_,18 @@ +@@ -88,6 +_,18 @@ return this.bakedItemStackModels.getOrDefault(id, this.missingModels.item()); } @@ -35,49 +35,49 @@ public ClientItem.Properties getItemProperties(final Identifier id) { return this.itemProperties.getOrDefault(id, ClientItem.Properties.DEFAULT); } -@@ -112,6 +_,7 @@ +@@ -111,6 +_,7 @@ final PreparableReloadListener.PreparationBarrier preparationBarrier, final Executor reloadExecutor ) { + net.minecraftforge.client.model.geometry.GeometryLoaderManager.init(); - ResourceManager resourcemanager = currentReload.resourceManager(); - CompletableFuture completablefuture = CompletableFuture.supplyAsync(EntityModelSet::vanilla, taskExecutor); - CompletableFuture> completablefuture1 = loadBlockModels(resourcemanager, taskExecutor); -@@ -275,6 +_,8 @@ - completablefuture1, + ResourceManager manager = currentReload.resourceManager(); + CompletableFuture entityModelSet = CompletableFuture.supplyAsync(EntityModelSet::vanilla, taskExecutor); + CompletableFuture> modelCache = loadBlockModels(manager, taskExecutor); +@@ -269,6 +_,8 @@ + bakedModelsFuture, (bakingResult, bakedModels) -> { - Map map = FluidStateModelSet.bake(materialbaker); -+ map = net.minecraftforge.client.ForgeHooksClient.onFluidModelBake(bakery, materialbaker, map); + Map fluidModels = FluidStateModelSet.bake(materialBaker); ++ fluidModels = net.minecraftforge.client.ForgeHooksClient.onFluidModelBake(bakery, materialBaker, fluidModels); + net.minecraftforge.client.ForgeHooksClient.onModifyBakingResult(bakery, bakingResult); - multimap.asMap() + missingSprites.asMap() .forEach( (location, sprites) -> LOGGER.warn( -@@ -292,7 +_,7 @@ - ) - ); - Map map1 = createBlockStateToModelDispatch(bakingResult.blockStateModels(), bakingResult.missingModels().block()); -- return new ModelManager.ReloadState(bakingResult, modelGroups, map1, (Map)bakedModels, map, entityModelSet); -+ return new ModelManager.ReloadState(bakingResult, modelGroups, map1, (Map)bakedModels, map, entityModelSet, bakery); +@@ -289,7 +_,7 @@ + bakingResult.blockStateModels(), bakingResult.missingModels().block() + ); + return new ModelManager.ReloadState( +- bakingResult, modelGroups, modelByStateCache, (Map)bakedModels, fluidModels, entityModelSet ++ bakingResult, modelGroups, modelByStateCache, (Map)bakedModels, fluidModels, entityModelSet, bakery + ); } ); - } -@@ -329,10 +_,15 @@ +@@ -327,10 +_,15 @@ private void apply(final ModelManager.ReloadState preparations) { - ModelBakery.BakingResult modelbakery$bakingresult = preparations.bakedModels; + ModelBakery.BakingResult bakedModels = preparations.bakedModels; + // TODO [BlockState Models] fix + //this.bakedBlockStateModelsView = java.util.Collections.unmodifiableMap(this.bakedBlockStateModels); - this.bakedItemStackModels = modelbakery$bakingresult.itemStackModels(); + this.bakedItemStackModels = bakedModels.itemStackModels(); + this.bakedItemStackModelsView = java.util.Collections.unmodifiableMap(this.bakedItemStackModels); - this.itemProperties = modelbakery$bakingresult.itemProperties(); + this.itemProperties = bakedModels.itemProperties(); this.modelGroups = preparations.modelGroups; - this.missingModels = modelbakery$bakingresult.missingModels(); + this.missingModels = bakedModels.missingModels(); + this.modelBakery = preparations.modelBakery(); + net.minecraftforge.client.ForgeHooksClient.onModelBake(this, this.modelBakery); this.blockStateModelSet = new BlockStateModelSet(preparations.blockStateModels, this.missingModels.block()); this.blockModelSet = new BlockModelSet(this.blockStateModelSet, preparations.blockModels, this.blockColors); this.fluidStateModelSet = new FluidStateModelSet(preparations.fluidModels, this.missingModels.fluid()); -@@ -368,7 +_,8 @@ +@@ -366,7 +_,8 @@ Map blockStateModels, Map blockModels, Map fluidModels, diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch index 509bff2402..0623fc6b7a 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidFace.java.patch @@ -21,11 +21,11 @@ return uvs.getVertexU(rotation.rotateVertexIndex(vertex)) / 16.0F; } @@ -38,7 +_,7 @@ - String s = getTexture(jsonobject); - CuboidFace.UVs cuboidface$uvs = getUVs(jsonobject); - Quadrant quadrant = getRotation(jsonobject); -- return new CuboidFace(direction, i, s, cuboidface$uvs, quadrant); -+ return new CuboidFace(direction, i, s, cuboidface$uvs, quadrant, net.minecraftforge.client.model.ForgeFaceData.read(jsonobject.get("forge_data"), null)); + String texture = getTexture(object); + CuboidFace.UVs uvs = getUVs(object); + Quadrant rotation = getRotation(object); +- return new CuboidFace(cullDirection, tintIndex, texture, uvs, rotation); ++ return new CuboidFace(cullDirection, tintIndex, texture, uvs, rotation, net.minecraftforge.client.model.ForgeFaceData.read(object.get("forge_data"), null)); } private static int getTintIndex(final JsonObject object) { diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch index 9f52c81911..bb44fc2b9f 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/CuboidModel.java.patch @@ -23,13 +23,13 @@ static final Gson GSON = new GsonBuilder() .registerTypeAdapter(CuboidModel.class, new CuboidModel.Deserializer()) @@ -62,8 +_,9 @@ - unbakedmodel$guilight = UnbakedModel.GuiLight.getByName(GsonHelper.getAsString(jsonobject, "gui_light")); + guiLight = UnbakedModel.GuiLight.getByName(GsonHelper.getAsString(object, "gui_light")); } -+ var forgeData = net.minecraftforge.client.ForgeHooksClient.deserializeBlockModel(jsonobject, context); - Identifier identifier = s.isEmpty() ? null : Identifier.parse(s); -- return new CuboidModel(unbakedgeometry, unbakedmodel$guilight, obool, itemtransforms, textureslots$data, identifier); -+ return new CuboidModel(unbakedgeometry, unbakedmodel$guilight, obool, itemtransforms, textureslots$data, identifier, forgeData); ++ var forgeData = net.minecraftforge.client.ForgeHooksClient.deserializeBlockModel(object, context); + Identifier parentLocation = parentName.isEmpty() ? null : Identifier.parse(parentName); +- return new CuboidModel(elements, guiLight, hasAmbientOcclusion, transforms, textureMap, parentLocation); ++ return new CuboidModel(elements, guiLight, hasAmbientOcclusion, transforms, textureMap, parentLocation, forgeData); } private TextureSlots.Data getTextureMap(final JsonObject object) { diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch index f9d2f52a10..ec4c207a07 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java +++ b/net/minecraft/client/resources/model/cuboid/ItemModelGenerator.java @@ -52,8 +_,10 @@ - QuadCollection quadcollection = null; - QuadCollection.Builder quadcollection$builder = null; + QuadCollection singleResult = null; + QuadCollection.Builder builder = null; -- for (int i = 0; i < LAYERS.size(); i++) { -- String s = LAYERS.get(i); +- for (int layerIndex = 0; layerIndex < LAYERS.size(); layerIndex++) { +- String textureReference = LAYERS.get(layerIndex); + // Forge: Allow for more layers -+ int i = 0; ++ int layerIndex = 0; + while (true) { -+ String s = String.format(java.util.Locale.ROOT, "layer%d", i++); - Material material = textureSlots.getMaterial(s); ++ String textureReference = String.format(java.util.Locale.ROOT, "layer%d", layerIndex++); + Material material = textureSlots.getMaterial(textureReference); if (material == null) { break; -@@ -83,6 +_,12 @@ +@@ -83,17 +_,29 @@ public static void bakeExtrudedSprite( final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo ) { @@ -23,13 +23,10 @@ + public static void bakeExtrudedSprite( + final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo, final BakedQuad.MaterialInfo template + ) { - Vector3f vector3f = new Vector3f(0.0F, 0.0F, 7.5F); - Vector3f vector3f1 = new Vector3f(16.0F, 16.0F, 8.5F); - builder.addUnculledFace( -@@ -91,13 +_,19 @@ - builder.addUnculledFace( - FaceBakery.bakeQuad(interner, vector3f, vector3f1, NORTH_FACE_UVS, Quadrant.R0, materialInfo, Direction.NORTH, modelState, null) - ); + Vector3f from = new Vector3f(0.0F, 0.0F, 7.5F); + Vector3f to = new Vector3f(16.0F, 16.0F, 8.5F); + builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, SOUTH_FACE_UVS, Quadrant.R0, materialInfo, Direction.SOUTH, modelState, null)); + builder.addUnculledFace(FaceBakery.bakeQuad(interner, from, to, NORTH_FACE_UVS, Quadrant.R0, materialInfo, Direction.NORTH, modelState, null)); - bakeSideFaces(builder, interner, modelState, materialInfo); + bakeSideFaces(builder, interner, modelState, materialInfo, template); } @@ -37,14 +34,14 @@ public static void bakeSideFaces( final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo ) { -- SpriteContents spritecontents = materialInfo.sprite().contents(); +- SpriteContents sprite = materialInfo.sprite().contents(); + bakeSideFaces(builder, interner, modelState, materialInfo, materialInfo); + } + + public static void bakeSideFaces( + final QuadCollection.Builder builder, final ModelBaker.Interner interner, final ModelState modelState, final BakedQuad.MaterialInfo materialInfo, final BakedQuad.MaterialInfo template + ) { -+ SpriteContents spritecontents = template.sprite().contents(); - float f = 16.0F / spritecontents.width(); - float f1 = 16.0F / spritecontents.height(); - Vector3f vector3f = new Vector3f(); ++ SpriteContents sprite = template.sprite().contents(); + float xScale = 16.0F / sprite.width(); + float yScale = 16.0F / sprite.height(); + Vector3f from = new Vector3f(); diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch index f7a3af2860..2f7dbffa78 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransform.java.patch @@ -12,12 +12,12 @@ public static final ItemTransform NO_TRANSFORM = new ItemTransform(new Vector3f(), new Vector3f(), new Vector3f(1.0F, 1.0F, 1.0F)); public void apply(final boolean applyLeftHandFix, final PoseStack.Pose pose) { -@@ -62,7 +_,7 @@ - vector3f1.set(Mth.clamp(vector3f1.x, -5.0F, 5.0F), Mth.clamp(vector3f1.y, -5.0F, 5.0F), Mth.clamp(vector3f1.z, -5.0F, 5.0F)); - Vector3f vector3f2 = this.getVector3f(jsonobject, "scale", DEFAULT_SCALE); - vector3f2.set(Mth.clamp(vector3f2.x, -4.0F, 4.0F), Mth.clamp(vector3f2.y, -4.0F, 4.0F), Mth.clamp(vector3f2.z, -4.0F, 4.0F)); -- return new ItemTransform(vector3f, vector3f1, vector3f2); -+ return new ItemTransform(vector3f, vector3f1, vector3f2, this.getVector3f(jsonobject, "right_rotation", DEFAULT_ROTATION)); +@@ -63,7 +_,7 @@ + translation.set(Mth.clamp(translation.x, -5.0F, 5.0F), Mth.clamp(translation.y, -5.0F, 5.0F), Mth.clamp(translation.z, -5.0F, 5.0F)); + Vector3f scale = this.getVector3f(object, "scale", DEFAULT_SCALE); + scale.set(Mth.clamp(scale.x, -4.0F, 4.0F), Mth.clamp(scale.y, -4.0F, 4.0F), Mth.clamp(scale.z, -4.0F, 4.0F)); +- return new ItemTransform(rotation, translation, scale); ++ return new ItemTransform(rotation, translation, scale, this.getVector3f(object, "right_rotation", DEFAULT_ROTATION)); } private Vector3f getVector3f(final JsonObject object, final String key, final Vector3f def) { diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch index c8cff8dd0b..6a93fdb22f 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/ItemTransforms.java.patch @@ -26,22 +26,22 @@ } @@ -70,6 +_,19 @@ - ItemTransform itemtransform6 = this.getTransform(context, jsonobject, ItemDisplayContext.GROUND); - ItemTransform itemtransform7 = this.getTransform(context, jsonobject, ItemDisplayContext.FIXED); - ItemTransform itemtransform8 = this.getTransform(context, jsonobject, ItemDisplayContext.ON_SHELF); + ItemTransform ground = this.getTransform(context, object, ItemDisplayContext.GROUND); + ItemTransform fixed = this.getTransform(context, object, ItemDisplayContext.FIXED); + ItemTransform fixedFromBottom = this.getTransform(context, object, ItemDisplayContext.ON_SHELF); + var builder = com.google.common.collect.ImmutableMap.builder(); + for (ItemDisplayContext type : ItemDisplayContext.values()) { + if (type.isModded()) { -+ var transform = this.getTransform(context, jsonobject, type); ++ var transform = this.getTransform(context, object, type); + var fallbackType = type; + while (transform == ItemTransform.NO_TRANSFORM && fallbackType.fallback() != null) { + fallbackType = fallbackType.fallback(); -+ transform = this.getTransform(context, jsonobject, fallbackType); ++ transform = this.getTransform(context, object, fallbackType); + } + if (transform != ItemTransform.NO_TRANSFORM) + builder.put(type, transform); + } + } return new ItemTransforms( - itemtransform1, itemtransform, itemtransform3, itemtransform2, itemtransform4, itemtransform5, itemtransform6, itemtransform7, itemtransform8 + thirdPersonLeftHand, thirdPersonRightHand, firstPersonLeftHand, firstPersonRightHand, head, gui, ground, fixed, fixedFromBottom ); diff --git a/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch b/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch index 4cbca8b569..5377339e00 100644 --- a/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch +++ b/patches/minecraft/net/minecraft/client/resources/model/cuboid/UnbakedCuboidGeometry.java.patch @@ -4,7 +4,7 @@ final ModelState modelState, final ModelDebugName name ) { -- QuadCollection.Builder quadcollection$builder = new QuadCollection.Builder(); +- QuadCollection.Builder builder = new QuadCollection.Builder(); + var builder = new QuadCollection.Builder(); + bake(builder, elements, textures, modelBaker, modelState, name, id -> modelBaker.materials().resolveSlot(textures, id, name)); + return builder.build(); @@ -19,35 +19,23 @@ + final ModelDebugName name, + final java.util.function.Function materialMapper //Forge: Allow overwriting textures + ) { - for (CuboidModelElement cuboidmodelelement : elements) { - boolean flag = true; - boolean flag1 = true; + for (CuboidModelElement element : elements) { + boolean drawXFaces = true; + boolean drawYFaces = true; @@ -63,7 +_,7 @@ - case Z -> flag2; + case Z -> drawZFaces; }; - if (flag3) { -- Material.Baked material$baked = modelBaker.materials().resolveSlot(textures, cuboidface.texture(), name); -+ Material.Baked material$baked = materialMapper.apply(cuboidface.texture()); - BakedQuad bakedquad = FaceBakery.bakeQuad( - modelBaker, - vector3fc, -@@ -77,9 +_,9 @@ - cuboidmodelelement.lightEmission() + if (shouldDrawFace) { +- Material.Baked material = modelBaker.materials().resolveSlot(textures, face.texture(), name); ++ Material.Baked material = materialMapper.apply(face.texture()); + BakedQuad quad = FaceBakery.bakeQuad( + modelBaker, from, to, face, material, facing, modelState, element.rotation(), element.shade(), element.lightEmission() ); - if (cuboidface.cullForDirection() == null) { -- quadcollection$builder.addUnculledFace(bakedquad); -+ builder.addUnculledFace(bakedquad); - } else { -- quadcollection$builder.addCulledFace( -+ builder.addCulledFace( - Direction.rotate(modelState.transformation().getMatrix(), cuboidface.cullForDirection()), bakedquad - ); - } -@@ -87,7 +_,5 @@ +@@ -76,7 +_,5 @@ } } } - -- return quadcollection$builder.build(); +- return builder.build(); } } diff --git a/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch b/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch index 4a4b1b2840..125d0efffc 100644 --- a/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch +++ b/patches/minecraft/net/minecraft/client/server/IntegratedServer.java.patch @@ -6,9 +6,9 @@ this.initializeKeyPair(); + if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; this.loadLevel(); - GameProfile gameprofile = this.getSingleplayerProfile(); - String s = this.getWorldData().getLevelName(); - this.setMotd(gameprofile != null ? gameprofile.name() + " - " + s : s); + GameProfile host = this.getSingleplayerProfile(); + String levelName = this.getWorldData().getLevelName(); + this.setMotd(host != null ? host.name() + " - " + levelName : levelName); this.saveEverything(false, true, true); - return true; + return net.minecraftforge.server.ServerLifecycleHooks.handleServerStarting(this); @@ -21,5 +21,5 @@ public void halt(final boolean wait) { + if (isRunning()) this.executeBlocking(() -> { - for (ServerPlayer serverplayer : Lists.newArrayList(this.getPlayerList().getPlayers())) { - if (!serverplayer.getUUID().equals(this.uuid)) { + for (ServerPlayer player : Lists.newArrayList(this.getPlayerList().getPlayers())) { + if (!player.getUUID().equals(this.uuid)) { diff --git a/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch b/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch index 195146481f..fdc3c5c619 100644 --- a/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch +++ b/patches/minecraft/net/minecraft/client/server/LanServerDetection.java.patch @@ -10,15 +10,15 @@ this.socket.joinGroup(this.pingGroup); } @@ -87,7 +_,11 @@ - String s = LanServerPinger.parseMotd(pingData); - String s1 = LanServerPinger.parseAddress(pingData); - if (s1 != null) { -- s1 = socketAddress.getHostAddress() + ":" + s1; + String motd = LanServerPinger.parseMotd(pingData); + String address = LanServerPinger.parseAddress(pingData); + if (address != null) { +- address = socketAddress.getHostAddress() + ":" + address; + if (net.minecraftforge.network.DualStackUtils.checkIPv6(socketAddress)) { -+ s1 = "[" + com.google.common.net.InetAddresses.toAddrString(socketAddress) + "]:" + s1; ++ address = "[" + com.google.common.net.InetAddresses.toAddrString(socketAddress) + "]:" + address; + } else { -+ s1 = socketAddress.getHostAddress() + ":" + s1; ++ address = socketAddress.getHostAddress() + ":" + address; + } - boolean flag = false; + boolean found = false; - for (LanServer lanserver : this.servers) { + for (LanServer server : this.servers) { diff --git a/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch b/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch index 43f23fa2e3..02cd7abe32 100644 --- a/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch +++ b/patches/minecraft/net/minecraft/client/server/LanServerPinger.java.patch @@ -13,8 +13,8 @@ while (!this.isInterrupted() && this.isRunning) { try { -- InetAddress inetaddress = InetAddress.getByName("224.0.2.60"); -+ InetAddress inetaddress = InetAddress.getByName(MULTICAST_GROUP); - DatagramPacket datagrampacket = new DatagramPacket(abyte, abyte.length, inetaddress, 4445); - this.socket.send(datagrampacket); - } catch (IOException ioexception) { +- InetAddress group = InetAddress.getByName("224.0.2.60"); ++ InetAddress group = InetAddress.getByName(MULTICAST_GROUP); + DatagramPacket packet = new DatagramPacket(ping, ping.length, group, 4445); + this.socket.send(packet); + } catch (IOException var6) { diff --git a/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch b/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch index d7c50023ae..e51afe28f3 100644 --- a/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch +++ b/patches/minecraft/net/minecraft/client/sounds/SoundEngine.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/client/sounds/SoundEngine.java +++ b/net/minecraft/client/sounds/SoundEngine.java -@@ -84,6 +_,7 @@ +@@ -82,6 +_,7 @@ this.options = options; this.soundBuffers = new SoundBufferLibrary(resourceProvider); this.lastSeenDevices = this.deviceTracker.currentDevices(); @@ -8,7 +8,7 @@ } public void reload() { -@@ -101,6 +_,7 @@ +@@ -99,6 +_,7 @@ this.destroy(); this.loadLibrary(); @@ -16,7 +16,7 @@ } private synchronized void loadLibrary() { -@@ -342,12 +_,15 @@ +@@ -340,12 +_,15 @@ } } @@ -30,22 +30,22 @@ + instance = net.minecraftforge.client.ForgeHooksClient.playSound(this, instance); + if (instance == null || !instance.canPlaySound()) + return SoundEngine.PlayResult.NOT_STARTED; - WeighedSoundEvents weighedsoundevents = instance.resolve(this.soundManager); - Identifier identifier = instance.getIdentifier(); - if (weighedsoundevents == null) { -@@ -427,15 +_,18 @@ - channel.setSelfPosition(vec3); - channel.setRelative(flag); + WeighedSoundEvents soundEvent = instance.resolve(this.soundManager); + Identifier eventLocation = instance.getIdentifier(); + if (soundEvent == null) { +@@ -425,15 +_,18 @@ + channel.setSelfPosition(position); + channel.setRelative(isRelative); }); + SoundInstance soundinstance = instance; - if (!flag1) { - this.soundBuffers.getCompleteBuffer(sound.getPath()).thenAccept(soundBuffer -> channelaccess$channelhandle.execute(channel -> { + if (!isStreaming) { + this.soundBuffers.getCompleteBuffer(sound.getPath()).thenAccept(soundBuffer -> handle.execute(channel -> { channel.attachStaticBuffer(soundBuffer); channel.play(); + net.minecraftforge.client.event.ForgeEventFactoryClient.onPlaySoundSource(this, soundinstance, channel); })); } else { - this.soundBuffers.getStream(sound.getPath(), flag3).thenAccept(stream -> channelaccess$channelhandle.execute(channel -> { + this.soundBuffers.getStream(sound.getPath(), isLooping).thenAccept(stream -> handle.execute(channel -> { channel.attachBufferStream(stream); channel.play(); + net.minecraftforge.client.event.ForgeEventFactoryClient.onPlayStreamingSource(this, soundinstance, channel); diff --git a/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch b/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch index d0471f04cd..33b4390d27 100644 --- a/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch +++ b/patches/minecraft/net/minecraft/commands/CommandSourceStack.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/commands/CommandSourceStack.java +++ b/net/minecraft/commands/CommandSourceStack.java -@@ -49,7 +_,7 @@ +@@ -48,7 +_,7 @@ import net.minecraft.world.phys.Vec3; import org.jspecify.annotations.Nullable; diff --git a/patches/minecraft/net/minecraft/commands/Commands.java.patch b/patches/minecraft/net/minecraft/commands/Commands.java.patch index 4abd7ee2b8..b69d1d9b87 100644 --- a/patches/minecraft/net/minecraft/commands/Commands.java.patch +++ b/patches/minecraft/net/minecraft/commands/Commands.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/commands/Commands.java +++ b/net/minecraft/commands/Commands.java -@@ -267,7 +_,7 @@ +@@ -265,7 +_,7 @@ ChaseCommand.register(this.dispatcher); } @@ -9,7 +9,7 @@ RaidCommand.register(this.dispatcher, context); DebugPathCommand.register(this.dispatcher); DebugMobSpawningCommand.register(this.dispatcher); -@@ -300,6 +_,7 @@ +@@ -298,6 +_,7 @@ if (commandSelection.includeIntegrated) { PublishCommand.register(this.dispatcher); } @@ -17,11 +17,11 @@ this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer()); } -@@ -322,9 +_,18 @@ +@@ -320,9 +_,18 @@ public void performCommand(final ParseResults command, final String commandString) { - CommandSourceStack commandsourcestack = command.getContext().getSource(); + CommandSourceStack sender = command.getContext().getSource(); Profiler.get().push(() -> "/" + commandString); -- ContextChain contextchain = finishParsing(command, commandString, commandsourcestack); +- ContextChain commandChain = finishParsing(command, commandString, sender); try { + var event = new net.minecraftforge.event.CommandEvent(command); @@ -33,19 +33,19 @@ + } + return; + } -+ ContextChain contextchain = finishParsing(event.getParseResults(), commandString, commandsourcestack); - if (contextchain != null) { ++ ContextChain commandChain = finishParsing(event.getParseResults(), commandString, sender); + if (commandChain != null) { executeCommandInContext( - commandsourcestack, -@@ -416,7 +_,10 @@ - Map, CommandNode> map = new HashMap<>(); - RootCommandNode rootcommandnode = new RootCommandNode<>(); - map.put(this.dispatcher.getRoot(), rootcommandnode); -- fillUsableCommands(this.dispatcher.getRoot(), rootcommandnode, player.createCommandSourceStack(), map); + sender, +@@ -413,7 +_,10 @@ + Map, CommandNode> playerCommands = new HashMap<>(); + RootCommandNode root = new RootCommandNode<>(); + playerCommands.put(this.dispatcher.getRoot(), root); +- fillUsableCommands(this.dispatcher.getRoot(), root, player.createCommandSourceStack(), playerCommands); + // FORGE: Use our own command node merging method to handle redirect nodes properly, see issue #7551 -+ net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), rootcommandnode, map, player.createCommandSourceStack(), ctx -> 0, suggest -> suggest); ++ net.minecraftforge.server.command.CommandHelper.mergeCommandNode(this.dispatcher.getRoot(), root, playerCommands, player.createCommandSourceStack(), ctx -> 0, suggest -> suggest); + // FORGE: Clean any modded command content if the client is vanilla -+ rootcommandnode = net.minecraftforge.server.command.CommandHelper.filterCommandList(player.connection.getConnection(), rootcommandnode); - player.connection.send(new ClientboundCommandsPacket(rootcommandnode, COMMAND_NODE_INSPECTOR)); ++ root = net.minecraftforge.server.command.CommandHelper.filterCommandList(player.connection.getConnection(), root); + player.connection.send(new ClientboundCommandsPacket(root, COMMAND_NODE_INSPECTOR)); } diff --git a/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch index 8d6474fe18..7eae079a0b 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/EntityArgument.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/commands/arguments/EntityArgument.java +++ b/net/minecraft/commands/arguments/EntityArgument.java -@@ -130,7 +_,7 @@ - StringReader stringreader = new StringReader(builder.getInput()); - stringreader.setCursor(builder.getStart()); - EntitySelectorParser entityselectorparser = new EntitySelectorParser( -- stringreader, sharedsuggestionprovider.permissions().hasPermission(Permissions.COMMANDS_ENTITY_SELECTORS) -+ stringreader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(sharedsuggestionprovider) - ); +@@ -129,7 +_,7 @@ + if (contextBuilder.getSource() instanceof SharedSuggestionProvider source) { + StringReader reader = new StringReader(builder.getInput()); + reader.setCursor(builder.getStart()); +- EntitySelectorParser parser = new EntitySelectorParser(reader, source.permissions().hasPermission(Permissions.COMMANDS_ENTITY_SELECTORS)); ++ EntitySelectorParser parser = new EntitySelectorParser(reader, net.minecraftforge.common.ForgeHooks.canUseEntitySelectors(source)); try { + parser.parse(); diff --git a/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch index a9fcd71425..0f583f2c97 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/ObjectiveArgument.java.patch @@ -3,18 +3,18 @@ @@ -31,7 +_,7 @@ public static Objective getObjective(final CommandContext context, final String name) throws CommandSyntaxException { - String s = context.getArgument(name, String.class); + String id = context.getArgument(name, String.class); - Scoreboard scoreboard = context.getSource().getServer().getScoreboard(); + Scoreboard scoreboard = context.getSource().getScoreboard(); - Objective objective = scoreboard.getObjective(s); + Objective objective = scoreboard.getObjective(id); if (objective == null) { - throw ERROR_OBJECTIVE_NOT_FOUND.create(s); + throw ERROR_OBJECTIVE_NOT_FOUND.create(id); @@ -57,7 +_,7 @@ public CompletableFuture listSuggestions(final CommandContext context, final SuggestionsBuilder builder) { - S s = context.getSource(); - if (s instanceof CommandSourceStack commandsourcestack) { -- return SharedSuggestionProvider.suggest(commandsourcestack.getServer().getScoreboard().getObjectiveNames(), builder); -+ return SharedSuggestionProvider.suggest(commandsourcestack.getScoreboard().getObjectiveNames(), builder); + S rawSource = context.getSource(); + if (rawSource instanceof CommandSourceStack source) { +- return SharedSuggestionProvider.suggest(source.getServer().getScoreboard().getObjectiveNames(), builder); ++ return SharedSuggestionProvider.suggest(source.getScoreboard().getObjectiveNames(), builder); } else { - return s instanceof SharedSuggestionProvider sharedsuggestionprovider ? sharedsuggestionprovider.customSuggestion(context) : Suggestions.empty(); + return rawSource instanceof SharedSuggestionProvider source ? source.customSuggestion(context) : Suggestions.empty(); } diff --git a/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch b/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch index 40bf69e0c8..257d518e49 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/TeamArgument.java.patch @@ -3,9 +3,9 @@ @@ -28,7 +_,7 @@ public static PlayerTeam getTeam(final CommandContext context, final String name) throws CommandSyntaxException { - String s = context.getArgument(name, String.class); + String id = context.getArgument(name, String.class); - Scoreboard scoreboard = context.getSource().getServer().getScoreboard(); + Scoreboard scoreboard = context.getSource().getScoreboard(); - PlayerTeam playerteam = scoreboard.getPlayerTeam(s); - if (playerteam == null) { - throw ERROR_TEAM_NOT_FOUND.create(s); + PlayerTeam team = scoreboard.getPlayerTeam(id); + if (team == null) { + throw ERROR_TEAM_NOT_FOUND.create(id); diff --git a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch index 553740988c..51f2fe36c1 100644 --- a/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch +++ b/patches/minecraft/net/minecraft/commands/arguments/selector/EntitySelectorParser.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/commands/arguments/selector/EntitySelectorParser.java +++ b/net/minecraft/commands/arguments/selector/EntitySelectorParser.java -@@ -466,6 +_,11 @@ +@@ -465,6 +_,11 @@ } this.reader.skip(); @@ -12,7 +12,7 @@ this.parseSelector(); } else { this.parseNameOrUUID(); -@@ -482,6 +_,7 @@ +@@ -481,6 +_,7 @@ builder.suggest("@s", Component.translatable("argument.entity.selector.self")); builder.suggest("@e", Component.translatable("argument.entity.selector.allEntities")); builder.suggest("@n", Component.translatable("argument.entity.selector.nearestEntity")); diff --git a/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch b/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch index e12c2068f4..5eff8c0326 100644 --- a/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch +++ b/patches/minecraft/net/minecraft/core/MappedRegistry.java.patch @@ -18,23 +18,23 @@ Objects.requireNonNull(key); Objects.requireNonNull(value); @@ -104,6 +_,8 @@ - reference.bindKey(key); + holder.bindKey(key); } else { - reference = this.byKey.computeIfAbsent(key, k -> Holder.Reference.createStandAlone(this, (ResourceKey)k)); + holder = this.byKey.computeIfAbsent(key, k -> Holder.Reference.createStandAlone(this, (ResourceKey)k)); + // Forge: Bind the value immediately so it can be queried while the registry is not frozen -+ reference.bindValue(value); ++ holder.bindValue(value); } - this.byKey.put(key, reference); + this.byKey.put(key, holder); @@ -275,7 +_,6 @@ return this; } else { this.frozen = true; - this.byValue.forEach((value, holder) -> holder.bindValue((T)value)); - List list = this.byKey.entrySet().stream().filter(e -> !e.getValue().isBound()).map(e -> e.getKey().identifier()).sorted().toList(); - if (!list.isEmpty()) { - throw new IllegalStateException("Unbound values in registry " + this.key() + ": " + list); -@@ -285,7 +_,8 @@ + List unboundEntries = this.byKey + .entrySet() + .stream() +@@ -291,7 +_,8 @@ throw new IllegalStateException("Some intrusive holders were not registered: " + this.unregisteredIntrusiveHolders.values()); } @@ -44,19 +44,19 @@ } if (this.allTags.isBound()) { -@@ -299,8 +_,9 @@ +@@ -305,8 +_,9 @@ .sorted() .toList(); - if (!list1.isEmpty()) { -- throw new IllegalStateException("Unbound tags in registry " + this.key() + ": " + list1); + if (!unboundTags.isEmpty()) { +- throw new IllegalStateException("Unbound tags in registry " + this.key() + ": " + unboundTags); - } else { -+ LOGGER.debug(MARKER, "Unbound tags in registry " + this.key() + ": " + list1); ++ LOGGER.debug(MARKER, "Unbound tags in registry " + this.key() + ": " + unboundTags); + bindAllUnboundTagsToEmpty(); + } /* else */ { this.componentLookup = new DataComponentLookup<>(this.byId); this.allTags = MappedRegistry.TagSet.fromMap(this.frozenTags); this.refreshTagsInHolders(); -@@ -311,6 +_,13 @@ +@@ -317,6 +_,13 @@ } } @@ -70,7 +70,7 @@ @Override public Holder.Reference createIntrusiveHolder(final T value) { if (this.unregisteredIntrusiveHolders == null) { -@@ -389,6 +_,31 @@ +@@ -395,6 +_,31 @@ }; } @@ -102,15 +102,15 @@ @Override public Registry.PendingTags prepareTagReload(final TagLoader.LoadResult tags) { if (!this.frozen) { -@@ -444,6 +_,11 @@ +@@ -450,6 +_,11 @@ @Override public HolderLookup.RegistryLookup lookup() { - return registrylookup; + return patchedHolder; + } + + @Override + public List> getPending(TagKey key) { -+ return map.getOrDefault(key, List.of()); ++ return pendingContents.getOrDefault(key, List.of()); } @Override diff --git a/patches/minecraft/net/minecraft/core/Registry.java.patch b/patches/minecraft/net/minecraft/core/Registry.java.patch index acfad02147..2ca4381be8 100644 --- a/patches/minecraft/net/minecraft/core/Registry.java.patch +++ b/patches/minecraft/net/minecraft/core/Registry.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/core/Registry.java +++ b/net/minecraft/core/Registry.java -@@ -178,5 +_,7 @@ +@@ -180,5 +_,7 @@ void apply(); int size(); diff --git a/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch b/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch index ec117b8d3b..da7821729f 100644 --- a/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch +++ b/patches/minecraft/net/minecraft/core/RegistrySetBuilder.java.patch @@ -53,38 +53,38 @@ + } + private RegistrySetBuilder.BuildState createState(final RegistryAccess context) { - RegistrySetBuilder.BuildState registrysetbuilder$buildstate = RegistrySetBuilder.BuildState.create( - context, this.entries.stream().map(RegistrySetBuilder.RegistryStub::key) -@@ -183,14 +_,16 @@ + RegistrySetBuilder.BuildState state = RegistrySetBuilder.BuildState.create(context, this.entries.stream().map(RegistrySetBuilder.RegistryStub::key)); + this.entries.forEach(e -> e.apply(state)); +@@ -181,14 +_,16 @@ throw new NullPointerException("No cloner for " + registryKey.identifier()); } else { - Map, Holder.Reference> map = new HashMap<>(); -- HolderLookup.RegistryLookup registrylookup = patchProvider.lookupOrThrow(registryKey); -+ HolderLookup.RegistryLookup registrylookup = patchProvider.lookup(registryKey).orElse(null); - registrylookup.listElements().forEach(elementHolder -> { - ResourceKey resourcekey = elementHolder.key(); - RegistrySetBuilder.LazyHolder lazyholder = new RegistrySetBuilder.LazyHolder<>(owner, resourcekey); - lazyholder.supplier = () -> cloner.clone((T)elementHolder.value(), patchProvider, targetProvider.get()); - map.put(resourcekey, lazyholder); + Map, Holder.Reference> entries = new HashMap<>(); +- HolderLookup.RegistryLookup patchContents = patchProvider.lookupOrThrow(registryKey); ++ HolderLookup.RegistryLookup patchContents = patchProvider.lookup(registryKey).orElse(null); + patchContents.listElements().forEach(elementHolder -> { + ResourceKey elementKey = elementHolder.key(); + RegistrySetBuilder.LazyHolder holder = new RegistrySetBuilder.LazyHolder<>(owner, elementKey); + holder.supplier = () -> cloner.clone((T)elementHolder.value(), patchProvider, targetProvider.get()); + entries.put(elementKey, holder); }); -- HolderLookup.RegistryLookup registrylookup1 = fallbackProvider.lookupOrThrow(registryKey); -+ HolderLookup.RegistryLookup registrylookup1 = fallbackProvider.lookup(registryKey).orElse(null); -+ Lifecycle lifecycle = registrylookup.registryLifecycle(); -+ if (registrylookup1 != null) { - registrylookup1.listElements().forEach(elementHolder -> { - ResourceKey resourcekey = elementHolder.key(); - map.computeIfAbsent(resourcekey, key -> { -@@ -199,7 +_,8 @@ - return lazyholder; +- HolderLookup.RegistryLookup fallbackContents = fallbackProvider.lookupOrThrow(registryKey); ++ HolderLookup.RegistryLookup fallbackContents = fallbackProvider.lookup(registryKey).orElse(null); ++ Lifecycle lifecycle = patchContents.registryLifecycle(); ++ if (fallbackContents != null) { + fallbackContents.listElements().forEach(elementHolder -> { + ResourceKey elementKey = elementHolder.key(); + entries.computeIfAbsent(elementKey, key -> { +@@ -197,7 +_,8 @@ + return holder; }); }); -- Lifecycle lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); -+ lifecycle = registrylookup.registryLifecycle().add(registrylookup1.registryLifecycle()); +- Lifecycle lifecycle = patchContents.registryLifecycle().add(fallbackContents.registryLifecycle()); ++ lifecycle = patchContents.registryLifecycle().add(fallbackContents.registryLifecycle()); + } - return lookupFromMap(registryKey, lifecycle, owner, map); + return lookupFromMap(registryKey, lifecycle, owner, entries); } } -@@ -275,6 +_,11 @@ +@@ -271,6 +_,11 @@ @Override public HolderGetter lookup(final ResourceKey> key) { return (HolderGetter)BuildState.this.registries.getOrDefault(key.identifier(), BuildState.this.lookup); diff --git a/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch index 5ee5127611..ff9bc9d0ef 100644 --- a/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch +++ b/patches/minecraft/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java +++ b/net/minecraft/core/dispenser/BoatDispenseItemBehavior.java @@ -29,18 +_,22 @@ - double d2 = vec3.y() + direction.getStepY() * 1.125F; - double d3 = vec3.z() + direction.getStepZ() * d0; - BlockPos blockpos = source.pos().relative(direction); -+ AbstractBoat abstractboat = this.type.create(serverlevel, EntitySpawnReason.DISPENSER); -+ if (abstractboat == null) { + double spawnY = center.y() + direction.getStepY() * 1.125F; + double spawnZ = center.z() + direction.getStepZ() * justOutsideDispenser; + BlockPos frontPos = source.pos().relative(direction); ++ AbstractBoat boat = this.type.create(level, EntitySpawnReason.DISPENSER); ++ if (boat == null) { + return this.defaultDispenseItemBehavior.dispense(source, dispensed); + } -+ abstractboat.setYRot(direction.toYRot()); - double d4; -- if (serverlevel.getFluidState(blockpos).is(FluidTags.WATER)) { -+ if (abstractboat.canBoatInFluid(serverlevel.getFluidState(blockpos))) { - d4 = 1.0; ++ boat.setYRot(direction.toYRot()); + double yOffset; +- if (level.getFluidState(frontPos).is(FluidTags.WATER)) { ++ if (boat.canBoatInFluid(level.getFluidState(frontPos))) { + yOffset = 1.0; } else { -- if (!serverlevel.getBlockState(blockpos).isAir() || !serverlevel.getFluidState(blockpos.below()).is(FluidTags.WATER)) { -+ if (!serverlevel.getBlockState(blockpos).isAir() || !abstractboat.canBoatInFluid(serverlevel.getFluidState(blockpos.below()))) { +- if (!level.getBlockState(frontPos).isAir() || !level.getFluidState(frontPos.below()).is(FluidTags.WATER)) { ++ if (!level.getBlockState(frontPos).isAir() || !boat.canBoatInFluid(level.getFluidState(frontPos.below()))) { return this.defaultDispenseItemBehavior.dispense(source, dispensed); } - d4 = 0.0; + yOffset = 0.0; } -- AbstractBoat abstractboat = this.type.create(serverlevel, EntitySpawnReason.DISPENSER); - if (abstractboat != null) { - abstractboat.setInitialPos(d1, d2 + d4, d3); - EntityType.createDefaultStackConfig(serverlevel, dispensed, null).accept(abstractboat); +- AbstractBoat boat = this.type.create(level, EntitySpawnReason.DISPENSER); + if (boat != null) { + boat.setInitialPos(spawnX, spawnY + yOffset, spawnZ); + EntityType.createDefaultStackConfig(level, dispensed, null).accept(boat); diff --git a/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch b/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch index eac5f4ca9a..fa2c8bdf84 100644 --- a/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch +++ b/patches/minecraft/net/minecraft/core/dispenser/DispenseItemBehavior.java.patch @@ -1,23 +1,23 @@ --- a/net/minecraft/core/dispenser/DispenseItemBehavior.java +++ b/net/minecraft/core/dispenser/DispenseItemBehavior.java -@@ -148,7 +_,7 @@ - DispensibleContainerItem dispensiblecontaineritem = (DispensibleContainerItem)dispensed.getItem(); - BlockPos blockpos = source.pos().relative(source.state().getValue(DispenserBlock.FACING)); +@@ -147,7 +_,7 @@ + DispensibleContainerItem bucket = (DispensibleContainerItem)dispensed.getItem(); + BlockPos target = source.pos().relative(source.state().getValue(DispenserBlock.FACING)); Level level = source.level(); -- if (dispensiblecontaineritem.emptyContents(null, level, blockpos, null)) { -+ if (dispensiblecontaineritem.emptyContents(null, level, blockpos, null, dispensed)) { - dispensiblecontaineritem.checkExtraContent(null, level, dispensed, blockpos); +- if (bucket.emptyContents(null, level, target, null)) { ++ if (bucket.emptyContents(null, level, target, null, dispensed)) { + bucket.checkExtraContent(null, level, dispensed, target); return this.consumeWithRemainder(source, dispensed, new ItemStack(Items.BUCKET)); } else { -@@ -199,8 +_,9 @@ - } else if (CampfireBlock.canLight(blockstate) || CandleBlock.canLight(blockstate) || CandleCakeBlock.canLight(blockstate)) { - serverlevel.setBlockAndUpdate(blockpos, blockstate.setValue(BlockStateProperties.LIT, true)); - serverlevel.gameEvent(null, GameEvent.BLOCK_CHANGE, blockpos); -- } else if (blockstate.getBlock() instanceof TntBlock) { -- if (TntBlock.prime(serverlevel, blockpos)) { -+ } else if (blockstate.isFlammable(serverlevel, blockpos, source.state().getValue(DispenserBlock.FACING).getOpposite())) { -+ if (blockstate.onCaughtFire(serverlevel, blockpos, source.state().getValue(DispenserBlock.FACING).getOpposite(), null)) { -+ if (blockstate.getBlock() instanceof TntBlock) - serverlevel.removeBlock(blockpos, false); +@@ -198,8 +_,9 @@ + } else if (CampfireBlock.canLight(target) || CandleBlock.canLight(target) || CandleCakeBlock.canLight(target)) { + level.setBlockAndUpdate(targetPos, target.setValue(BlockStateProperties.LIT, true)); + level.gameEvent(null, GameEvent.BLOCK_CHANGE, targetPos); +- } else if (target.getBlock() instanceof TntBlock) { +- if (TntBlock.prime(level, targetPos)) { ++ } else if (target.isFlammable(level, targetPos, source.state().getValue(DispenserBlock.FACING).getOpposite())) { ++ if (target.onCaughtFire(level, targetPos, source.state().getValue(DispenserBlock.FACING).getOpposite(), null)) { ++ if (target.getBlock() instanceof TntBlock) + level.removeBlock(targetPos, false); } else { this.setSuccess(false); diff --git a/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch b/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch index b763fd20a7..9db6fd0f5d 100644 --- a/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch +++ b/patches/minecraft/net/minecraft/core/registries/BuiltInRegistries.java.patch @@ -8,20 +8,20 @@ + final ResourceKey> name, R registry, final BuiltInRegistries.RegistryBootstrap loader ) { Bootstrap.checkBootstrapCalled(() -> "registry " + name.identifier()); - Identifier identifier = name.identifier(); -- LOADERS.put(identifier, () -> loader.run(registry)); + Identifier key = name.identifier(); +- LOADERS.put(key, () -> loader.run(registry)); + var maybeWrapped = net.minecraftforge.registries.GameData.getWrapper(name, registry); + registry = maybeWrapped; -+ LOADERS.put(identifier, () -> loader.run(maybeWrapped)); ++ LOADERS.put(key, () -> loader.run(maybeWrapped)); WRITABLE_REGISTRY.register((ResourceKey)name, registry, RegistrationInfo.BUILT_IN); return registry; } @@ -425,7 +_,7 @@ if (r instanceof DefaultedRegistry) { - Identifier identifier = ((DefaultedRegistry)r).getDefaultKey(); -- Objects.requireNonNull(r.getValue(identifier), "Missing default of DefaultedMappedRegistry: " + identifier); -+ Objects.requireNonNull(r.getValue(identifier), "Missing default of DefaultedMappedRegistry: " + r.key() + " - " + identifier); + Identifier key = ((DefaultedRegistry)r).getDefaultKey(); +- Objects.requireNonNull(r.getValue(key), "Missing default of DefaultedMappedRegistry: " + key); ++ Objects.requireNonNull(r.getValue(key), "Missing default of DefaultedMappedRegistry: " + r.key() + " - " + key); } }); } diff --git a/patches/minecraft/net/minecraft/data/DataGenerator.java.patch b/patches/minecraft/net/minecraft/data/DataGenerator.java.patch index 8ef665c9d2..4ce67a2fa3 100644 --- a/patches/minecraft/net/minecraft/data/DataGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/DataGenerator.java.patch @@ -9,8 +9,8 @@ public DataGenerator(final Path output) { this.vanillaPackOutput = new PackOutput(output); @@ -34,6 +_,35 @@ - Path path = this.vanillaPackOutput.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("minecraft").resolve("datapacks").resolve(packId); - return new DataGenerator.PackGenerator(toRun, packId, new PackOutput(path)); + Path packOutputDir = this.vanillaPackOutput.getOutputFolder(PackOutput.Target.DATA_PACK).resolve("minecraft").resolve("datapacks").resolve(packId); + return new DataGenerator.PackGenerator(toRun, packId, new PackOutput(packOutputDir)); } + public Map getProvidersView() { + return this.providersView; @@ -49,14 +49,14 @@ } else { DataGenerator.LOGGER.info("Starting provider: {}", providerId); + net.minecraftforge.fml.StartupMessageManager.addModMessage("Generating: " + providerId); - stopwatch1.start(); - hashcache.applyUpdate(hashcache.generateUpdate(providerId, provider::run).join()); - stopwatch1.stop(); + stopwatch.start(); + cache.applyUpdate(cache.generateUpdate(providerId, provider::run).join()); + stopwatch.stop(); @@ -112,6 +_,7 @@ - Stopwatch stopwatch1 = Stopwatch.createUnstarted(); + Stopwatch stopwatch = Stopwatch.createUnstarted(); this.providersToRun.forEach((providerId, provider) -> { DataGenerator.LOGGER.info("Starting uncached provider: {}", providerId); + net.minecraftforge.fml.StartupMessageManager.addModMessage("Generating: " + providerId); - stopwatch1.start(); + stopwatch.start(); provider.run(CachedOutput.NO_CACHE).join(); - stopwatch1.stop(); + stopwatch.stop(); diff --git a/patches/minecraft/net/minecraft/data/HashCache.java.patch b/patches/minecraft/net/minecraft/data/HashCache.java.patch index 5efdd9058e..81ecf0ff66 100644 --- a/patches/minecraft/net/minecraft/data/HashCache.java.patch +++ b/patches/minecraft/net/minecraft/data/HashCache.java.patch @@ -11,31 +11,31 @@ @@ -65,6 +_,7 @@ } - this.caches = map; + this.caches = loadedCaches; + this.originalCaches = Map.copyOf(this.caches); - this.initialCount = i; + this.initialCount = initialCount; } @@ -106,6 +_,8 @@ this.caches.forEach((providerId, cache) -> { if (this.cachesToWrite.contains(providerId)) { - Path path = this.getProviderCachePath(providerId); + Path cachePath = this.getProviderCachePath(providerId); + // Forge: Only rewrite the cache file if it changed or is missing -+ if (!cache.equals(this.originalCaches.get(providerId)) || !Files.exists(path)) - cache.save(this.rootDir, path, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime.now()) + "\t" + providerId); ++ if (!cache.equals(this.originalCaches.get(providerId)) || !Files.exists(cachePath)) + cache.save(this.rootDir, cachePath, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime.now()) + "\t" + providerId); } @@ -224,10 +_,11 @@ - bufferedwriter.write(extraHeaderInfo); - bufferedwriter.newLine(); + output.write(extraHeaderInfo); + output.newLine(); -- for (Entry entry : this.data.entrySet()) { +- for (Entry e : this.data.entrySet()) { + // Forge: Standardize order of entries -+ for (Entry entry : this.data.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { - bufferedwriter.write(entry.getValue().toString()); - bufferedwriter.write(32); -- bufferedwriter.write(rootDir.relativize(entry.getKey()).toString()); -+ bufferedwriter.write(rootDir.relativize(entry.getKey()).toString().replace("\\", "/")); // Forge: Standardize file paths. - bufferedwriter.newLine(); ++ for (Entry e : this.data.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { + output.write(e.getValue().toString()); + output.write(32); +- output.write(rootDir.relativize(e.getKey()).toString()); ++ output.write(rootDir.relativize(e.getKey()).toString().replace("\\", "/")); // Forge: Standardize file paths. + output.newLine(); } - } catch (IOException ioexception) { + } catch (IOException var9) { diff --git a/patches/minecraft/net/minecraft/data/Main.java.patch b/patches/minecraft/net/minecraft/data/Main.java.patch index 2329f4aa1c..5bb968547a 100644 --- a/patches/minecraft/net/minecraft/data/Main.java.patch +++ b/patches/minecraft/net/minecraft/data/Main.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/data/Main.java +++ b/net/minecraft/data/Main.java @@ -78,14 +_,17 @@ - OptionSpec optionspec4 = optionparser.accepts("all", "Include all generators"); - OptionSpec optionspec5 = optionparser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); - OptionSpec optionspec6 = optionparser.accepts("input", "Input folder").withRequiredArg(); -+ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(optionparser, false); - OptionSet optionset = optionparser.parse(args); -- if (!optionset.has(optionspec) && optionset.hasOptions()) { -+ if (!optionset.has(optionspec) && optionset.hasOptions() && loader.hasArgs(optionset)) { - Path path = Paths.get(optionspec5.value(optionset)); - boolean flag = optionset.has(optionspec4); - boolean flag1 = flag || optionset.has(optionspec1); - boolean flag2 = flag || optionset.has(optionspec2); - boolean flag3 = flag || optionset.has(optionspec3); - Collection collection = optionset.valuesOf(optionspec6).stream().map(x$0 -> Paths.get(x$0)).toList(); -+ if (!loader.run(optionset, path, collection, flag1, flag, flag2, flag3)) + OptionSpec allOption = parser.accepts("all", "Include all generators"); + OptionSpec outputOption = parser.accepts("output", "Output folder").withRequiredArg().defaultsTo("generated"); + OptionSpec inputOption = parser.accepts("input", "Input folder").withRequiredArg(); ++ var loader = net.minecraftforge.data.loading.DatagenModLoader.setup(parser, false); + OptionSet optionSet = parser.parse(args); +- if (!optionSet.has(helpOption) && optionSet.hasOptions()) { ++ if (!optionSet.has(helpOption) && optionSet.hasOptions() && loader.hasArgs(optionSet)) { + Path output = Paths.get(outputOption.value(optionSet)); + boolean allOptions = optionSet.has(allOption); + boolean server = allOptions || optionSet.has(serverOption); + boolean dev = allOptions || optionSet.has(devOption); + boolean reports = allOptions || optionSet.has(reportsOption); + Collection input = optionSet.valuesOf(inputOption).stream().map(x$0 -> Paths.get(x$0)).toList(); ++ if (!loader.run(optionSet, output, input, server, allOptions, dev, reports)) + return; - DataGenerator datagenerator = new DataGenerator.Cached(path, SharedConstants.getCurrentVersion(), true); - addServerDefinitionProviders(datagenerator, flag1, flag3); - addServerConverters(datagenerator, collection, flag1, flag2); + DataGenerator generator = new DataGenerator.Cached(output, SharedConstants.getCurrentVersion(), true); + addServerDefinitionProviders(generator, server, reports); + addServerConverters(generator, input, server, dev); diff --git a/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch index 80f7c557df..a26aec6715 100644 --- a/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/BlockLootSubProvider.java.patch @@ -11,7 +11,7 @@ @Override public void generate(final BiConsumer, LootTable.Builder> output) { this.generate(); - Set> set = new HashSet<>(); + Set> seen = new HashSet<>(); - for (Block block : BuiltInRegistries.BLOCK) { + for (Block block : getKnownBlocks()) { diff --git a/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch index 143b382b8e..7e9b2796ac 100644 --- a/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/EntityLootSubProvider.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/loot/EntityLootSubProvider.java +++ b/net/minecraft/data/loot/EntityLootSubProvider.java -@@ -119,12 +_,16 @@ +@@ -120,12 +_,16 @@ public abstract void generate(); @@ -11,11 +11,11 @@ @Override public void generate(final BiConsumer, LootTable.Builder> output) { this.generate(); - Set> set = new HashSet<>(); + Set> seen = new HashSet<>(); - BuiltInRegistries.ENTITY_TYPE - .listElements() + this.getKnownEntityTypes() + .map(EntityType::builtInRegistryHolder) .forEach( holder -> { - EntityType entitytype = holder.value(); + EntityType type = holder.value(); diff --git a/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch b/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch index 5debbdb428..ac401dd8aa 100644 --- a/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/loot/LootTableProvider.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/data/loot/LootTableProvider.java +++ b/net/minecraft/data/loot/LootTableProvider.java -@@ -60,7 +_,7 @@ +@@ -59,7 +_,7 @@ private CompletableFuture run(final CachedOutput cache, final HolderLookup.Provider registries) { - WritableRegistry writableregistry = new MappedRegistry<>(Registries.LOOT_TABLE, Lifecycle.experimental()); - Map map = new Object2ObjectOpenHashMap<>(); + WritableRegistry tables = new MappedRegistry<>(Registries.LOOT_TABLE, Lifecycle.experimental()); + Map randomSequenceSeeds = new Object2ObjectOpenHashMap<>(); - this.subProviders.forEach(subProvider -> subProvider.provider().apply(registries).generate((id, lootTable) -> { + this.getTables().forEach(subProvider -> subProvider.provider().apply(registries).generate((id, lootTable) -> { - Identifier identifier = sequenceIdForLootTable(id); - Identifier identifier1 = map.put(RandomSequence.seedForKey(identifier), identifier); - if (identifier1 != null) { -@@ -76,11 +_,8 @@ - HolderGetter.Provider holdergetter$provider = new RegistryAccess.ImmutableRegistryAccess(List.of(writableregistry)).freeze(); - ValidationContextSource validationcontextsource = new ValidationContextSource(problemreporter$collector, holdergetter$provider); + Identifier sequenceId = sequenceIdForLootTable(id); + Identifier previous = randomSequenceSeeds.put(RandomSequence.seedForKey(sequenceId), sequenceId); + if (previous != null) { +@@ -75,11 +_,8 @@ + HolderGetter.Provider validationProvider = new RegistryAccess.ImmutableRegistryAccess(List.of(tables)).freeze(); + ValidationContextSource validationContext = new ValidationContextSource(problems, validationProvider); -- for (ResourceKey resourcekey : Sets.difference(this.requiredTables, writableregistry.registryKeySet())) { -- problemreporter$collector.report(new LootTableProvider.MissingTableProblem(resourcekey)); +- for (ResourceKey missingTable : Sets.difference(this.requiredTables, tables.registryKeySet())) { +- problems.report(new LootTableProvider.MissingTableProblem(missingTable)); - } -+ validate(writableregistry, validationcontextsource, problemreporter$collector); ++ validate(tables, validationContext, problems); -- LootDataType.TABLE.runValidation(validationcontextsource, writableregistry); - if (!problemreporter$collector.isEmpty()) { - problemreporter$collector.forEach((id, problem) -> LOGGER.warn("Found validation problem in {}: {}", id, problem.description())); +- LootDataType.TABLE.runValidation(validationContext, tables); + if (!problems.isEmpty()) { + problems.forEach((id, problem) -> LOGGER.warn("Found validation problem in {}: {}", id, problem.description())); throw new IllegalStateException("Failed to validate loot tables, see logs"); -@@ -101,6 +_,18 @@ +@@ -100,6 +_,18 @@ @Override public final String getName() { return "Loot Tables"; diff --git a/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch b/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch index 9c93b96500..08cccec02f 100644 --- a/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/recipes/RecipeProvider.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/data/recipes/RecipeProvider.java +++ b/net/minecraft/data/recipes/RecipeProvider.java -@@ -892,13 +_,13 @@ +@@ -891,13 +_,13 @@ } @Override - public void accept(final ResourceKey> id, final Recipe recipe, final @Nullable AdvancementHolder advancementHolder) { + public void accept(final ResourceKey> id, final Recipe recipe, net.minecraft.resources.@Nullable Identifier advancementId, com.google.gson.@Nullable JsonElement advancement) { - if (!set.add(id)) { + if (!allRecipes.add(id)) { throw new IllegalStateException("Duplicate recipe " + id.identifier()); } else { this.saveRecipe(id, recipe); @@ -17,26 +17,26 @@ } } } -@@ -913,19 +_,26 @@ - AdvancementHolder advancementholder = Advancement.Builder.recipeAdvancement() +@@ -912,19 +_,26 @@ + AdvancementHolder root = Advancement.Builder.recipeAdvancement() .addCriterion("impossible", CriteriaTriggers.IMPOSSIBLE.createCriterion(new ImpossibleTrigger.TriggerInstance())) .build(RecipeBuilder.ROOT_RECIPE_ADVANCEMENT); -- this.saveAdvancement(advancementholder); +- this.saveAdvancement(root); + var ops = registry().createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE); -+ var json = Advancement.CODEC.encodeStart(ops, advancementholder.value()).getOrThrow(IllegalStateException::new); -+ this.saveAdvancement(advancementholder.id(), json); ++ var json = Advancement.CODEC.encodeStart(ops, root.value()).getOrThrow(IllegalStateException::new); ++ this.saveAdvancement(root.id(), json); } private void saveRecipe(final ResourceKey> id, final Recipe recipe) { - list.add(DataProvider.saveStable(cache, registries, Recipe.CODEC, recipe, packoutput$pathprovider.json(id.identifier()))); + tasks.add(DataProvider.saveStable(cache, registries, Recipe.CODEC, recipe, recipePathProvider.json(id.identifier()))); } - private void saveAdvancement(final AdvancementHolder advancementHolder) { + private void saveAdvancement(net.minecraft.resources.Identifier id, com.google.gson.JsonElement advancement) { - list.add( + tasks.add( DataProvider.saveStable( -- cache, registries, Advancement.CODEC, advancementHolder.value(), packoutput$pathprovider1.json(advancementHolder.id()) -+ cache, advancement, packoutput$pathprovider1.json(id) +- cache, registries, Advancement.CODEC, advancementHolder.value(), advancementPathProvider.json(advancementHolder.id()) ++ cache, advancement, advancementPathProvider.json(id) ) ); + } @@ -46,4 +46,4 @@ + return registries; } }; - this.createRecipeProvider(registries, recipeoutput).buildRecipes(); + this.createRecipeProvider(registries, recipeOutput).buildRecipes(); diff --git a/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch b/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch index ceec6566ec..a73e9cad16 100644 --- a/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/RegistriesDatapackGenerator.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/registries/RegistriesDatapackGenerator.java +++ b/net/minecraft/data/registries/RegistriesDatapackGenerator.java -@@ -20,10 +_,21 @@ +@@ -18,10 +_,21 @@ public class RegistriesDatapackGenerator implements DataProvider { private final PackOutput output; private final CompletableFuture registries; @@ -22,22 +22,22 @@ } @Override -@@ -33,8 +_,7 @@ +@@ -31,8 +_,7 @@ access -> { - DynamicOps dynamicops = access.createSerializationContext(JsonOps.INSTANCE); + DynamicOps registryOps = access.createSerializationContext(JsonOps.INSTANCE); return CompletableFuture.allOf( - RegistryDataLoader.WORLDGEN_REGISTRIES - .stream() + RegistryDataLoader.getWorldGenAndDimensionStream() - .flatMap(v -> this.dumpRegistryCap(cache, access, dynamicops, (RegistryDataLoader.RegistryData)v).stream()) + .flatMap(v -> this.dumpRegistryCap(cache, access, registryOps, (RegistryDataLoader.RegistryData)v).stream()) .toArray(CompletableFuture[]::new) ); -@@ -52,11 +_,16 @@ - PackOutput.PathProvider packoutput$pathprovider = this.output.createRegistryElementsPathProvider(resourcekey); +@@ -50,11 +_,16 @@ + PackOutput.PathProvider pathProvider = this.output.createRegistryElementsPathProvider(registryKey); return CompletableFuture.allOf( registry.listElements() + .filter(holder -> shouldDump(holder.key())) - .>map(e -> dumpValue(packoutput$pathprovider.json(e.key().identifier()), cache, writeOps, v.elementCodec(), e.value())) + .>map(e -> dumpValue(pathProvider.json(e.key().identifier()), cache, writeOps, v.elementCodec(), e.value())) .toArray(CompletableFuture[]::new) ); } diff --git a/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch b/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch index 9adc5a4240..091d98a9ab 100644 --- a/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/RegistryPatchGenerator.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/data/registries/RegistryPatchGenerator.java @@ -21,7 +_,7 @@ parent -> { - RegistryAccess.Frozen registryaccess$frozen = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); - Cloner.Factory cloner$factory = new Cloner.Factory(); -- RegistryDataLoader.WORLDGEN_REGISTRIES.forEach(registryData -> registryData.runWithArguments(cloner$factory::addCodec)); -+ RegistryDataLoader.getWorldGenAndDimensionStream().forEach(registryData -> registryData.runWithArguments(cloner$factory::addCodec)); - RegistrySetBuilder.PatchedRegistries registrysetbuilder$patchedregistries = packBuilder.buildPatch( - registryaccess$frozen, parent, cloner$factory - ); + RegistryAccess.Frozen staticRegistries = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY); + Cloner.Factory cloner = new Cloner.Factory(); +- RegistryDataLoader.WORLDGEN_REGISTRIES.forEach(registryData -> registryData.runWithArguments(cloner::addCodec)); ++ RegistryDataLoader.getWorldGenAndDimensionStream().forEach(registryData -> registryData.runWithArguments(cloner::addCodec)); + RegistrySetBuilder.PatchedRegistries newRegistries = packBuilder.buildPatch(staticRegistries, parent, cloner); + HolderLookup.Provider fullPatchedRegistry = newRegistries.full(); + Optional> biomes = fullPatchedRegistry.lookup(Registries.BIOME); diff --git a/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch b/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch index 3aac66dc71..dbe1bb8181 100644 --- a/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch +++ b/patches/minecraft/net/minecraft/data/registries/VanillaRegistries.java.patch @@ -9,9 +9,9 @@ private static void validateThatAllBiomeFeaturesHaveBiomeFilter(final HolderLookup.Provider provider) { validateThatAllBiomeFeaturesHaveBiomeFilter(provider.lookupOrThrow(Registries.PLACED_FEATURE), provider.lookupOrThrow(Registries.BIOME)); @@ -139,5 +_,9 @@ - HolderLookup.Provider holderlookup$provider = BUILDER.build(registryaccess$frozen); - validateThatAllBiomeFeaturesHaveBiomeFilter(holderlookup$provider); - return holderlookup$provider; + HolderLookup.Provider newRegistries = BUILDER.build(staticRegistries); + validateThatAllBiomeFeaturesHaveBiomeFilter(newRegistries); + return newRegistries; + } + + public static RegistrySetBuilder builder() { diff --git a/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch index a3082f668a..54a860a62e 100644 --- a/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/IntrinsicHolderTagsProvider.java.patch @@ -37,8 +37,8 @@ + } + protected TagAppender tag(final TagKey tag) { - TagBuilder tagbuilder = this.getOrCreateRawBuilder(tag); -- return TagAppender.forBuilder(tagbuilder).map(this.keyExtractor); -+ return TagAppender.forBuilder(tagbuilder, this.modId).map(this.keyExtractor); + TagBuilder builder = this.getOrCreateRawBuilder(tag); +- return TagAppender.forBuilder(builder).map(this.keyExtractor); ++ return TagAppender.forBuilder(builder, this.modId).map(this.keyExtractor); } } diff --git a/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch index 37dd14b965..d8f7ac66d3 100644 --- a/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/KeyTagProvider.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/data/tags/KeyTagProvider.java +++ b/net/minecraft/data/tags/KeyTagProvider.java @@ -20,9 +_,13 @@ - return TagAppender.forBuilder(tagbuilder); + return TagAppender.forBuilder(builder); } + protected KeyTagProvider(final PackOutput output, final ResourceKey> registryKey, final CompletableFuture lookupProvider, String modId, @org.jetbrains.annotations.Nullable net.minecraftforge.common.data.ExistingFileHelper existingFileHelper) { @@ -9,9 +9,9 @@ + } + protected TagAppender, T> tag(final TagKey tag, final boolean replace) { - TagBuilder tagbuilder = this.getOrCreateRawBuilder(tag); - tagbuilder.setReplace(replace); -- return TagAppender.forBuilder(tagbuilder); -+ return TagAppender.forBuilder(tagbuilder, this.modId); + TagBuilder builder = this.getOrCreateRawBuilder(tag); + builder.setReplace(replace); +- return TagAppender.forBuilder(builder); ++ return TagAppender.forBuilder(builder, this.modId); } } diff --git a/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch b/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch index d1714f2feb..149eb6002d 100644 --- a/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/TagAppender.java.patch @@ -45,23 +45,23 @@ @@ -86,6 +_,22 @@ @Override public TagAppender addOptionalTag(final TagKey tag) { - tagappender.addOptionalTag(tag); + original.addOptionalTag(tag); + return this; + } + + @Override + public TagBuilder getInternalBuilder() { -+ return tagappender.getInternalBuilder(); ++ return original.getInternalBuilder(); + } + + @Override + public String getSourceName() { -+ return tagappender.getSourceName(); ++ return original.getSourceName(); + } + + @Override + public TagAppender remove(U value) { -+ tagappender.remove(converter.apply(value)); ++ original.remove(converter.apply(value)); return this; } }; diff --git a/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch b/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch index c98380cbd9..3836edd899 100644 --- a/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch +++ b/patches/minecraft/net/minecraft/data/tags/TagsProvider.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/data/tags/TagsProvider.java +++ b/net/minecraft/data/tags/TagsProvider.java -@@ -32,28 +_,53 @@ +@@ -31,28 +_,53 @@ private final CompletableFuture> parentProvider; protected final ResourceKey> registryKey; protected final Map builders = Maps.newLinkedHashMap(); @@ -57,45 +57,45 @@ } protected abstract void addTags(HolderLookup.Provider registries); -@@ -71,7 +_,13 @@ +@@ -70,7 +_,13 @@ .thenCombineAsync(this.parentProvider, (x$0, x$1) -> new CombinedData<>(x$0, (TagsProvider.TagLookup)x$1), Util.backgroundExecutor()) .thenCompose( c -> { -- HolderLookup.RegistryLookup registrylookup = c.contents.lookupOrThrow(this.registryKey); -+ HolderLookup.RegistryLookup registrylookup = c.contents.lookup(this.registryKey).orElseThrow(() -> { +- HolderLookup.RegistryLookup lookup = c.contents.lookupOrThrow(this.registryKey); ++ HolderLookup.RegistryLookup lookup = c.contents.lookup(this.registryKey).orElseThrow(() -> { + // FORGE: Throw a more descriptive error message if this is a Forge registry without tags enabled + if (net.minecraftforge.registries.RegistryManager.ACTIVE.getRegistry(this.registryKey) != null) { + return new IllegalStateException("Forge registry " + this.registryKey.identifier() + " does not have support for tags"); + } + return new IllegalStateException("Registry " + this.registryKey.identifier() + " not found"); + }); - Predicate predicate = id -> registrylookup.get(ResourceKey.create(this.registryKey, id)).isPresent(); - Predicate predicate1 = id -> this.builders.containsKey(id) || c.parent.contains(TagKey.create(this.registryKey, id)); + Predicate elementCheck = id -> lookup.get(ResourceKey.create(this.registryKey, id)).isPresent(); + Predicate tagCheck = id -> this.builders.containsKey(id) || c.parent.contains(TagKey.create(this.registryKey, id)); return CompletableFuture.allOf( -@@ -83,7 +_,7 @@ - Identifier identifier = entry.getKey(); - TagBuilder tagbuilder = entry.getValue(); - List list = tagbuilder.build(); -- List list1 = list.stream().filter(e -> !e.verifyIfPresent(predicate, predicate1)).toList(); -+ List list1 = java.util.stream.Stream.concat(list.stream(), tagbuilder.getRemoveEntries()).filter(e -> !e.verifyIfPresent(predicate, predicate1)).filter(this::missing).toList(); - if (!list1.isEmpty()) { +@@ -82,7 +_,7 @@ + Identifier id = entry.getKey(); + TagBuilder builder = entry.getValue(); + List entries = builder.build(); +- List unresolvedEntries = entries.stream().filter(e -> !e.verifyIfPresent(elementCheck, tagCheck)).toList(); ++ List unresolvedEntries = java.util.stream.Stream.concat(entries.stream(), builder.getRemoveEntries()).filter(e -> !e.verifyIfPresent(elementCheck, tagCheck)).filter(this::missing).toList(); + if (!unresolvedEntries.isEmpty()) { throw new IllegalArgumentException( String.format( -@@ -94,8 +_,11 @@ +@@ -93,8 +_,11 @@ ) ); } else { -- Path path = this.pathProvider.json(identifier); -- return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(list, tagbuilder.shouldReplace()), path); -+ Path path = this.getPath(identifier); +- Path path = this.pathProvider.json(id); +- return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(entries, builder.shouldReplace()), path); ++ Path path = this.getPath(id); + if (path == null) { + return CompletableFuture.completedFuture(null); // Forge: Allow running this data provider without writing it. Recipe provider needs valid tags. + } -+ return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(list, tagbuilder.shouldReplace(), tagbuilder.getRemoveEntries().toList()), path); ++ return DataProvider.saveStable(cache, c.contents, TagFile.CODEC, new TagFile(entries, builder.shouldReplace(), builder.getRemoveEntries().toList()), path); } } ) -@@ -106,7 +_,12 @@ +@@ -105,7 +_,12 @@ } protected TagBuilder getOrCreateRawBuilder(final TagKey tag) { @@ -109,7 +109,7 @@ } public CompletableFuture> contentsGetter() { -@@ -119,6 +_,15 @@ +@@ -118,6 +_,15 @@ this.addTags(registries); return (HolderLookup.Provider)registries; }); diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch index ddb4454f87..d11eb8800a 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestHelper.java.patch @@ -23,7 +23,7 @@ return this.testInfo.getStructureBounds(); } @@ -1122,6 +_,26 @@ - if (either.right().isPresent()) { + if (result.right().isPresent()) { throw this.assertionException("test.error.set_biome"); } + } diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch index 53c1b805be..e8a168dfc6 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestMainUtil.java.patch @@ -5,6 +5,6 @@ Bootstrap.bootStrap(); Util.startTimerHackThread(); + net.minecraftforge.server.loading.ServerModLoader.load(); - String s = optionset.valueOf(universe); - createOrResetDir(s); - onUniverseCreated.accept(s); + String universePath = options.valueOf(universe); + createOrResetDir(universePath); + onUniverseCreated.accept(universePath); diff --git a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch index d4f0561e18..08f4ca665b 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/GameTestServer.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/gametest/framework/GameTestServer.java +++ b/net/minecraft/gametest/framework/GameTestServer.java -@@ -102,7 +_,7 @@ +@@ -101,7 +_,7 @@ final int repeatCount ) { packRepository.reload(); -- ArrayList arraylist = new ArrayList<>(packRepository.getAvailableIds()); -+ ArrayList arraylist = new ArrayList<>(packRepository.getSelectedIds()); // Forge: Use the selected datapacks as this takes sorting into account. - arraylist.remove("vanilla"); - arraylist.addFirst("vanilla"); - WorldDataConfiguration worlddataconfiguration = new WorldDataConfiguration(new DataPackConfig(arraylist, List.of()), ENABLED_FEATURES); -@@ -178,6 +_,7 @@ +- ArrayList enabledPacks = new ArrayList<>(packRepository.getAvailableIds()); ++ ArrayList enabledPacks = new ArrayList<>(packRepository.getSelectedIds()); // Forge: Use the selected datapacks as this takes sorting into account. + enabledPacks.remove("vanilla"); + enabledPacks.addFirst("vanilla"); + WorldDataConfiguration defaultTestConfig = new WorldDataConfiguration(new DataPackConfig(enabledPacks, List.of()), ENABLED_FEATURES); +@@ -173,6 +_,7 @@ @Override protected boolean initServer() { diff --git a/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch b/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch index 34211c42ae..5dae5ebe99 100644 --- a/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch +++ b/patches/minecraft/net/minecraft/gametest/framework/TestCommand.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/gametest/framework/TestCommand.java +++ b/net/minecraft/gametest/framework/TestCommand.java -@@ -477,7 +_,12 @@ +@@ -481,7 +_,12 @@ return Optional.empty(); } else { - Holder.Reference reference = optional.get(); -- GameTestInfo gametestinfo = new GameTestInfo(reference, testinstanceblockentity.getRotation(), serverlevel, retryOptions); + Holder.Reference test = maybeTest.get(); +- GameTestInfo testInfo = new GameTestInfo(test, blockEntity.getRotation(), level, retryOptions); + // Forge: The rotation is stored in the structure block, and added in the GameTestInfo constructor. + // So reverse it to find the manually specified rotation so the test runs the same every time. -+ var rotation = testinstanceblockentity.test().flatMap(testinstanceblockentity.getLevel().registryAccess()::get).map(Holder::value).map(GameTestInstance::rotation).orElse(Rotation.NONE); -+ var steps = StructureUtils.getRotationStepsForRotation(testinstanceblockentity.getRotation()) - StructureUtils.getRotationStepsForRotation(rotation); ++ var rotation = blockEntity.test().flatMap(blockEntity.getLevel().registryAccess()::get).map(Holder::value).map(GameTestInstance::rotation).orElse(Rotation.NONE); ++ var steps = StructureUtils.getRotationStepsForRotation(blockEntity.getRotation()) - StructureUtils.getRotationStepsForRotation(rotation); + if (steps < 0) steps += 4; -+ GameTestInfo gametestinfo = new GameTestInfo(reference, StructureUtils.getRotationForRotationSteps(steps), serverlevel, retryOptions); - gametestinfo.setTestBlockPos(testBlockPos); - return !verifyStructureExists(source, gametestinfo.getStructure()) ? Optional.empty() : Optional.of(gametestinfo); ++ GameTestInfo testInfo = new GameTestInfo(test, StructureUtils.getRotationForRotationSteps(steps), level, retryOptions); + testInfo.setTestBlockPos(testBlockPos); + return !verifyStructureExists(source, testInfo.getStructure()) ? Optional.empty() : Optional.of(testInfo); } diff --git a/patches/minecraft/net/minecraft/locale/Language.java.patch b/patches/minecraft/net/minecraft/locale/Language.java.patch index 38f6e9c842..bf914e4b7d 100644 --- a/patches/minecraft/net/minecraft/locale/Language.java.patch +++ b/patches/minecraft/net/minecraft/locale/Language.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/locale/Language.java +++ b/net/minecraft/locale/Language.java -@@ -38,7 +_,8 @@ - BiConsumer biconsumer = map::put; - parseTranslations(biconsumer, "/assets/minecraft/lang/en_us.json"); - deprecatedtranslationsinfo.applyToMap(map); -- final Map map1 = Map.copyOf(map); -+ net.minecraftforge.server.LanguageHook.captureLanguageMap(map); -+ final Map map1 = map; +@@ -37,7 +_,8 @@ + BiConsumer output = loadedData::put; + parseTranslations(output, "/assets/minecraft/lang/en_us.json"); + deprecatedInfo.applyToMap(loadedData); +- final Map storage = Map.copyOf(loadedData); ++ net.minecraftforge.server.LanguageHook.captureLanguageMap(loadedData); ++ final Map storage = loadedData; return new Language() { @Override public String getOrDefault(final String elementId, final String defaultValue) { -@@ -63,6 +_,11 @@ +@@ -62,6 +_,11 @@ ) .isPresent(); } + + @Override + public Map getLanguageData() { -+ return map; ++ return loadedData; + } }; } -@@ -90,6 +_,8 @@ +@@ -89,6 +_,8 @@ public static void inject(final Language language) { instance = language; } diff --git a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch index 4dbbc31641..98e18d9c7f 100644 --- a/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch +++ b/patches/minecraft/net/minecraft/network/CompressionEncoder.java.patch @@ -13,12 +13,12 @@ VarInt.write(out, 0); out.writeBytes(uncompressed); } else { -+ if (!DISABLE_PACKET_DEBUG && i > net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH) { ++ if (!DISABLE_PACKET_DEBUG && uncompressedLength > net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH) { + uncompressed.markReaderIndex(); -+ LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", i, net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH, ++ LOGGER.error("Attempted to send packet over maximum protocol size: {} > {}\nData:\n{}", uncompressedLength, net.minecraft.network.CompressionDecoder.MAXIMUM_UNCOMPRESSED_LENGTH, + net.minecraftforge.common.util.HexDumper.dump(uncompressed)); + uncompressed.resetReaderIndex(); + } - byte[] abyte = new byte[i]; - uncompressed.readBytes(abyte); - VarInt.write(out, abyte.length); + byte[] input = new byte[uncompressedLength]; + uncompressed.readBytes(input); + VarInt.write(out, input.length); diff --git a/patches/minecraft/net/minecraft/network/Connection.java.patch b/patches/minecraft/net/minecraft/network/Connection.java.patch index e48de671dc..f5e92ecd28 100644 --- a/patches/minecraft/net/minecraft/network/Connection.java.patch +++ b/patches/minecraft/net/minecraft/network/Connection.java.patch @@ -28,12 +28,12 @@ } @@ -151,6 +_,7 @@ } else { - if (packetlistener.shouldHandleMessage(packet)) { + if (packetListener.shouldHandleMessage(packet)) { try { + packetLogger.recv(packet); - genericsFtw(packet, packetlistener); - } catch (RunningOnDifferentThreadException runningondifferentthreadexception) { - } catch (RejectedExecutionException rejectedexecutionexception) { + genericsFtw(packet, packetListener); + } catch (RunningOnDifferentThreadException var5) { + } catch (RejectedExecutionException var6) { @@ -200,6 +_,7 @@ if (protocol.flow() != this.getReceiving()) { throw new IllegalStateException("Invalid inbound protocol: " + protocol.id()); @@ -41,17 +41,17 @@ + this.inboundProtocol = protocol; this.packetListener = packetListener; this.disconnectListener = null; - UnconfiguredPipelineHandler.InboundConfigurationTask unconfiguredpipelinehandler$inboundconfigurationtask = UnconfiguredPipelineHandler.setupInboundProtocol( -@@ -223,6 +_,8 @@ + UnconfiguredPipelineHandler.InboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupInboundProtocol(protocol); +@@ -217,7 +_,7 @@ + if (protocol.flow() != this.getSending()) { + throw new IllegalStateException("Invalid outbound protocol: " + protocol.id()); } else { - UnconfiguredPipelineHandler.OutboundConfigurationTask unconfiguredpipelinehandler$outboundconfigurationtask = UnconfiguredPipelineHandler.setupOutboundProtocol( - protocol -+ ).andThen( -+ f -> this.outboundProtocol = protocol - ); - BundlerInfo bundlerinfo = protocol.bundlerInfo(); - if (bundlerinfo != null) { -@@ -274,7 +_,8 @@ +- UnconfiguredPipelineHandler.OutboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupOutboundProtocol(protocol); ++ UnconfiguredPipelineHandler.OutboundConfigurationTask configMessage = UnconfiguredPipelineHandler.setupOutboundProtocol(protocol).andThen(_ -> this.outboundProtocol = protocol); + BundlerInfo bundlerInfo = protocol.bundlerInfo(); + if (bundlerInfo != null) { + PacketBundleUnpacker newUnbundler = new PacketBundleUnpacker(bundlerInfo); +@@ -264,7 +_,8 @@ this.disconnectListener = listener; this.runOnceConnected(connection -> { this.setupInboundProtocol(inbound, listener); @@ -61,11 +61,11 @@ this.setupOutboundProtocol(outbound); }); } -@@ -319,10 +_,13 @@ +@@ -309,10 +_,13 @@ if (listener != null) { - ChannelFuture channelfuture = flush ? this.channel.writeAndFlush(packet) : this.channel.write(packet); - channelfuture.addListener(listener); -+ channelfuture.addListener(f -> packetLogger.send(packet)); + ChannelFuture future = flush ? this.channel.writeAndFlush(packet) : this.channel.write(packet); + future.addListener(listener); ++ future.addListener(f -> packetLogger.send(packet)); } else if (flush) { this.channel.writeAndFlush(packet, this.channel.voidPromise()); + packetLogger.send(packet); @@ -75,7 +75,7 @@ } } -@@ -391,7 +_,7 @@ +@@ -381,7 +_,7 @@ if (this.address == null) { return "local"; } else { @@ -84,7 +84,7 @@ } } -@@ -436,7 +_,9 @@ +@@ -426,7 +_,9 @@ } public static ChannelFuture connect(final InetSocketAddress address, final EventLoopGroupHolder eventLoopGroupHolder, final Connection connection) { @@ -95,7 +95,7 @@ @Override protected void initChannel(final Channel channel) { try { -@@ -503,7 +_,8 @@ +@@ -499,7 +_,8 @@ public static Connection connectToLocalServer(final SocketAddress address) { final Connection connection = new Connection(PacketFlow.CLIENTBOUND); @@ -104,8 +104,8 @@ + new Bootstrap().group(EventLoopGroupHolder.local().eventLoopGroup(true)).handler(new ChannelInitializer() { @Override protected void initChannel(final Channel channel) { - ChannelPipeline channelpipeline = channel.pipeline(); -@@ -594,6 +_,22 @@ + ChannelPipeline pipeline = channel.pipeline(); +@@ -590,6 +_,22 @@ public float getAverageSentPackets() { return this.averageSentPackets; diff --git a/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch b/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch index d208f6ce37..8b24670454 100644 --- a/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch +++ b/patches/minecraft/net/minecraft/network/chat/contents/TranslatableContents.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/network/chat/contents/TranslatableContents.java +++ b/net/minecraft/network/chat/contents/TranslatableContents.java -@@ -136,6 +_,11 @@ - j = l; +@@ -135,6 +_,11 @@ + current = end; } -+ if (j == 0) { ++ if (current == 0) { + // Forge has some special formatting handlers defined in ForgeI18n, use those if no %s replacements present. -+ j = net.minecraftforge.internal.TextComponentMessageFormatHandler.handle(this, decomposedParts, this.args, template); ++ current = net.minecraftforge.internal.TextComponentMessageFormatHandler.handle(this, decomposedParts, this.args, template); + } + - if (j < template.length()) { - String s3 = template.substring(j); - if (s3.indexOf(37) != -1) { + if (current < template.length()) { + String tail = template.substring(current); + if (tail.indexOf(37) != -1) { diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch index 6d4ce39733..25d2a2403d 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ClientboundCustomPayloadPacket.java -@@ -17,12 +_,12 @@ +@@ -15,12 +_,12 @@ public record ClientboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet { private static final int MAX_PAYLOAD_SIZE = 1048576; public static final StreamCodec GAMEPLAY_STREAM_CODEC = CustomPacketPayload.codec( diff --git a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch index 0ff99ea96d..2fe3bc9c45 100644 --- a/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java +++ b/net/minecraft/network/protocol/common/ServerboundCustomPayloadPacket.java -@@ -15,7 +_,7 @@ +@@ -13,7 +_,7 @@ public record ServerboundCustomPayloadPacket(CustomPacketPayload payload) implements Packet { private static final int MAX_PAYLOAD_SIZE = 32767; public static final StreamCodec STREAM_CODEC = CustomPacketPayload.codec( diff --git a/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch b/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch index 0d250cc8f1..2188327f6b 100644 --- a/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch +++ b/patches/minecraft/net/minecraft/network/protocol/status/ServerStatus.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/network/protocol/status/ServerStatus.java +++ b/net/minecraft/network/protocol/status/ServerStatus.java -@@ -20,7 +_,8 @@ +@@ -19,7 +_,8 @@ Optional players, Optional version, Optional favicon, @@ -10,7 +10,7 @@ ) { public static final Codec CODEC = RecordCodecBuilder.create( i -> i.group( -@@ -28,7 +_,8 @@ +@@ -27,7 +_,8 @@ ServerStatus.Players.CODEC.lenientOptionalFieldOf("players").forGetter(ServerStatus::players), ServerStatus.Version.CODEC.lenientOptionalFieldOf("version").forGetter(ServerStatus::version), ServerStatus.Favicon.CODEC.lenientOptionalFieldOf("favicon").forGetter(ServerStatus::favicon), diff --git a/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch b/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch index cd32bbfe62..92651f5bda 100644 --- a/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch +++ b/patches/minecraft/net/minecraft/network/syncher/SynchedEntityData.java.patch @@ -7,12 +7,12 @@ - if (LOGGER.isDebugEnabled()) { + if (true) { // Forge: This is very useful for mods that register keys on classes that are not their own try { - Class oclass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); - if (!oclass.equals(clazz)) { -- LOGGER.debug("defineId called for: {} from {}", clazz, oclass, new RuntimeException()); + Class aClass = Class.forName(Thread.currentThread().getStackTrace()[2].getClassName()); + if (!aClass.equals(clazz)) { +- LOGGER.debug("defineId called for: {} from {}", clazz, aClass, new RuntimeException()); + // Forge: log at warn, mods should not add to classes that they don't own, and only add stacktrace when in debug is enabled as it is mostly not needed and consumes time -+ if (LOGGER.isDebugEnabled()) LOGGER.warn("defineId called for: {} from {}", clazz, oclass, new RuntimeException()); -+ else LOGGER.warn("defineId called for: {} from {}", clazz, oclass); ++ if (LOGGER.isDebugEnabled()) LOGGER.warn("defineId called for: {} from {}", clazz, aClass, new RuntimeException()); ++ else LOGGER.warn("defineId called for: {} from {}", clazz, aClass); } - } catch (ClassNotFoundException classnotfoundexception) { + } catch (ClassNotFoundException var3) { } diff --git a/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch b/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch index 23003264b6..6ddfba8610 100644 --- a/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch +++ b/patches/minecraft/net/minecraft/resources/HolderSetCodec.java.patch @@ -8,7 +8,7 @@ + private final Codec, Either, List>>>> combinedCodec; private static Codec>> homogenousList(final Codec> elementCodec, final boolean alwaysUseList) { - Codec>> codec = elementCodec.listOf().validate(ExtraCodecs.ensureHomogenous(Holder::kind)); + Codec>> listCodec = elementCodec.listOf().validate(ExtraCodecs.ensureHomogenous(Holder::kind)); @@ -38,6 +_,10 @@ this.elementCodec = elementCodec; this.homogenousListCodec = homogenousList(elementCodec, alwaysUseList); @@ -21,23 +21,23 @@ @Override @@ -46,14 +_,17 @@ - Optional> optional = registryops.getter(this.registryKey); - if (optional.isPresent()) { - HolderGetter holdergetter = optional.get(); + Optional> registryOptional = registryOps.getter(this.registryKey); + if (registryOptional.isPresent()) { + HolderGetter registry = registryOptional.get(); - return this.registryAwareCodec + return this.combinedCodec .decode(ops, input) .flatMap( p -> { - DataResult> dataresult = p.getFirst() + DataResult> result = p.getFirst() + .map(custom -> DataResult.success(custom), + tagOrList -> tagOrList .map( - tag -> lookupTag(holdergetter, (TagKey)tag), + tag -> lookupTag(registry, (TagKey)tag), values -> DataResult.success(HolderSet.direct((List>)values)) + ) ); - return dataresult.map(holders -> Pair.of((HolderSet)holders, (T)p.getSecond())); + return result.map(holders -> Pair.of((HolderSet)holders, (T)p.getSecond())); } @@ -86,7 +_,7 @@ } @@ -45,7 +45,7 @@ private DataResult, T>> decodeWithoutRegistry(final DynamicOps ops, final T input) { - return this.elementCodec.listOf().decode(ops, input).flatMap(p -> { + return this.homogenousListCodec.decode(ops, input).flatMap(p -> { // Forge: Match encodeWithoutRegistry's use of the homogenousListCodec - List> list = new ArrayList<>(); + List> directHolders = new ArrayList<>(); for (Holder holder : p.getFirst()) { @@ -102,6 +_,9 @@ diff --git a/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch b/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch index 3eaaa3317e..9ba97434c8 100644 --- a/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch +++ b/patches/minecraft/net/minecraft/resources/RegistryOps.java.patch @@ -21,5 +21,5 @@ + } + public static RecordCodecBuilder> retrieveElement(final ResourceKey key) { - ResourceKey> resourcekey = ResourceKey.createRegistryKey(key.registry()); + ResourceKey> registryKey = ResourceKey.createRegistryKey(key.registry()); return ExtraCodecs.retrieveContext( diff --git a/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch b/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch index edef63a6ec..9db7969690 100644 --- a/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch +++ b/patches/minecraft/net/minecraft/resources/ResourceManagerRegistryLoadTask.java.patch @@ -11,28 +11,28 @@ @@ -40,6 +_,7 @@ @Override public CompletableFuture load(final RegistryOps.RegistryInfoLookup context, final Executor executor) { - FileToIdConverter filetoidconverter = FileToIdConverter.registry(this.registryKey()); + FileToIdConverter lister = FileToIdConverter.registry(this.registryKey()); + var optionalCodec = net.minecraftforge.common.crafting.conditions.ConditionCodec.wrap(this.data.elementCodec()); - return CompletableFuture.>supplyAsync(() -> filetoidconverter.listMatchingResources(this.resourceManager), executor) + return CompletableFuture.>supplyAsync(() -> lister.listMatchingResources(this.resourceManager), executor) .thenCompose( registryResources -> { @@ -49,9 +_,18 @@ (resourceId, thunk) -> { - ResourceKey resourcekey = ResourceKey.create(this.registryKey(), filetoidconverter.fileToId(resourceId)); - RegistrationInfo registrationinfo = REGISTRATION_INFO_CACHE.apply(thunk.knownPackInfo()); + ResourceKey elementKey = ResourceKey.create(this.registryKey(), lister.fileToId(resourceId)); + RegistrationInfo registrationInfo = REGISTRATION_INFO_CACHE.apply(thunk.knownPackInfo()); + // braking types here for smaller patch, its just used for error messages so its fine -+ var result = RegistryLoadTask.PendingRegistration.loadFromResource(optionalCodec, registryops, (ResourceKey>)resourcekey, thunk); ++ var result = RegistryLoadTask.PendingRegistration.loadFromResource(optionalCodec, ops, (ResourceKey>)elementKey, thunk); + if (!result.right().isPresent()) { // Wasn't an error so check if present + var value = result.left().get(); + if (value.isEmpty()) { -+ LOGGER.debug("Skipping {} conditions not met", resourcekey); ++ LOGGER.debug("Skipping {} conditions not met", elementKey); + return null; + } + } return new RegistryLoadTask.PendingRegistration<>( - resourcekey, -- RegistryLoadTask.PendingRegistration.loadFromResource(this.data.elementCodec(), registryops, resourcekey, thunk), + elementKey, +- RegistryLoadTask.PendingRegistration.loadFromResource(this.data.elementCodec(), ops, elementKey, thunk), + result.mapLeft(Optional::get), - registrationinfo + registrationInfo ); }, diff --git a/patches/minecraft/net/minecraft/server/Bootstrap.java.patch b/patches/minecraft/net/minecraft/server/Bootstrap.java.patch index f103f90d70..12ae3a7053 100644 --- a/patches/minecraft/net/minecraft/server/Bootstrap.java.patch +++ b/patches/minecraft/net/minecraft/server/Bootstrap.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/server/Bootstrap.java +++ b/net/minecraft/server/Bootstrap.java -@@ -57,6 +_,8 @@ +@@ -56,6 +_,8 @@ CauldronInteractions.bootStrap(); BuiltInRegistries.bootStrap(); CreativeModeTabs.validate(); + net.minecraftforge.registries.GameData.vanillaSnapshot(); + if (false) // skip redirectOutputToLog, Forge already redirects stdout and stderr output to log so that they print with more context wrapStreams(); - bootstrapDuration.set(Duration.between(instant, Instant.now()).toMillis()); + bootstrapDuration.set(Duration.between(start, Instant.now()).toMillis()); } -@@ -123,7 +_,6 @@ +@@ -122,7 +_,6 @@ Commands.validate(); } diff --git a/patches/minecraft/net/minecraft/server/Main.java.patch b/patches/minecraft/net/minecraft/server/Main.java.patch index 016ca66cd9..5b9d1beade 100644 --- a/patches/minecraft/net/minecraft/server/Main.java.patch +++ b/patches/minecraft/net/minecraft/server/Main.java.patch @@ -1,53 +1,53 @@ --- a/net/minecraft/server/Main.java +++ b/net/minecraft/server/Main.java -@@ -83,6 +_,17 @@ - OptionSpec optionspec13 = optionparser.accepts("jfrProfile"); - OptionSpec optionspec14 = optionparser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter()); - OptionSpec optionspec15 = optionparser.nonOptions(); -+ optionparser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed -+ optionparser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side. +@@ -82,6 +_,17 @@ + OptionSpec jfrProfilingOption = parser.accepts("jfrProfile"); + OptionSpec pidFile = parser.accepts("pidFile").withRequiredArg().withValuesConvertedBy(new PathConverter()); + OptionSpec nonOptions = parser.nonOptions(); ++ parser.accepts("allowUpdates").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE); // Forge: allow mod updates to proceed ++ parser.accepts("gameDir").withRequiredArg().ofType(File.class).defaultsTo(new File(".")); //Forge: Consume this argument, we use it in the launcher, and the client side. + final OptionSpec spawnPosOpt; + OptionSpec uniqueWorld = null; + boolean gametestEnabled = Boolean.getBoolean("forge.gameTestServer"); + if (gametestEnabled) { -+ spawnPosOpt = optionparser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); -+ uniqueWorld = optionparser.accepts("uniqueWorld"); ++ spawnPosOpt = parser.accepts("spawnPos").withRequiredArg().withValuesConvertedBy(new net.minecraftforge.gametest.BlockPosValueConverter()).defaultsTo(new net.minecraft.core.BlockPos(0, 60, 0)); ++ uniqueWorld = parser.accepts("uniqueWorld"); + } else { + spawnPosOpt = null; + } try { - OptionSet optionset = optionparser.parse(args); -@@ -91,6 +_,14 @@ + OptionSet options = parser.parse(args); +@@ -90,6 +_,14 @@ return; } -+ Path path2 = Paths.get("eula.txt"); -+ Eula eula = new Eula(path2); ++ Path eulaFile = Paths.get("eula.txt"); ++ Eula eula = new Eula(eulaFile); + + if (!eula.hasAgreedToEULA()) { + LOGGER.info("You need to agree to the EULA in order to run the server. Go to eula.txt for more info."); + return; + } + - Path path = optionset.valueOf(optionspec14); - if (path != null) { - writePidFile(path); -@@ -105,24 +_,28 @@ + Path pidFilePath = options.valueOf(pidFile); + if (pidFilePath != null) { + writePidFile(pidFilePath); +@@ -104,24 +_,28 @@ Bootstrap.validate(); Util.startTimerHackThread(); - Path path1 = Paths.get("server.properties"); -+ if (!optionset.has(optionspec1)) { + Path settingsFile = Paths.get("server.properties"); ++ if (!options.has(initSettings)) { + // Load mods before we load almost anything else anymore. Single spot now. Only loads if they haven't passed the initserver param + net.minecraftforge.server.loading.ServerModLoader.load(); + } - DedicatedServerSettings dedicatedserversettings = new DedicatedServerSettings(path1); - dedicatedserversettings.forceSave(); - RegionFileVersion.configure(dedicatedserversettings.getProperties().regionFileComression); -- Path path2 = Paths.get("eula.txt"); -- Eula eula = new Eula(path2); - if (optionset.has(optionspec1)) { - LOGGER.info("Initialized '{}' and '{}'", path1.toAbsolutePath(), path2.toAbsolutePath()); + DedicatedServerSettings settings = new DedicatedServerSettings(settingsFile); + settings.forceSave(); + RegionFileVersion.configure(settings.getProperties().regionFileComression); +- Path eulaFile = Paths.get("eula.txt"); +- Eula eula = new Eula(eulaFile); + if (options.has(initSettings)) { + LOGGER.info("Initialized '{}' and '{}'", settingsFile.toAbsolutePath(), eulaFile.toAbsolutePath()); return; } @@ -56,52 +56,52 @@ - return; - } - - File file1 = new File(optionset.valueOf(optionspec9)); - Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), file1); - String s = Optional.ofNullable(optionset.valueOf(optionspec10)).orElse(dedicatedserversettings.getProperties().levelName); + File universePath = new File(options.valueOf(universe)); + Services services = Services.create(new YggdrasilAuthenticationService(Proxy.NO_PROXY), universePath); + String levelName = Optional.ofNullable(options.valueOf(worldName)).orElse(settings.getProperties().levelName); + // Forge: make each gametest use a timestamped world name -+ if (uniqueWorld != null && optionset.has(uniqueWorld)) -+ s = "gametest_world\\" + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss.SSS").format(java.time.LocalDateTime.now()); -+ if (s == null || s.isEmpty() || new File(file1, s).getAbsolutePath().equals(new File(s).getAbsolutePath())) { -+ LOGGER.error("Invalid world directory specified, must not be null, empty or the same directory as your universe! " + s); ++ if (uniqueWorld != null && options.has(uniqueWorld)) ++ levelName = "gametest_world\\" + java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss.SSS").format(java.time.LocalDateTime.now()); ++ if (levelName == null || levelName.isEmpty() || new File(universePath, levelName).getAbsolutePath().equals(new File(levelName).getAbsolutePath())) { ++ LOGGER.error("Invalid world directory specified, must not be null, empty or the same directory as your universe! " + levelName); + return; + } - LevelStorageSource levelstoragesource = LevelStorageSource.createDefault(file1.toPath()); - LevelStorageSource.LevelStorageAccess levelstoragesource$levelstorageaccess = levelstoragesource.validateAndCreateAccess(s); - Dynamic dynamic; -@@ -158,6 +_,10 @@ + LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(universePath.toPath()); + LevelStorageSource.LevelStorageAccess access = levelStorageSource.validateAndCreateAccess(levelName); + Dynamic levelDataTag; +@@ -157,6 +_,10 @@ - PackRepository packrepository = ServerPacksSource.createPackRepository(levelstoragesource$levelstorageaccess); + PackRepository packRepository = ServerPacksSource.createPackRepository(access); -+ if (dynamic != null) { -+ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(levelstoragesource$levelstorageaccess, levelstoragesource$levelstorageaccess.getLevelDirectory()); ++ if (levelDataTag != null) { ++ net.minecraftforge.common.ForgeHooks.readAdditionalLevelSaveData(access, access.getLevelDirectory()); + } + - WorldStem worldstem; + WorldStem worldStem; try { - WorldLoader.InitConfig worldloader$initconfig = loadOrCreateConfig(dedicatedserversettings.getProperties(), dynamic, flag1, packrepository); -@@ -231,6 +_,7 @@ + WorldLoader.InitConfig worldLoadConfig = loadOrCreateConfig(settings.getProperties(), levelDataTag, safeModeEnabled, packRepository); +@@ -219,6 +_,7 @@ @Override public void run() { - dedicatedserver.halt(true); + dedicatedServer.halt(true); + org.apache.logging.log4j.LogManager.shutdown(); // we're manually managing the logging shutdown on the server. Make sure we do it here at the end. } }; - thread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)); -@@ -266,6 +_,16 @@ - worldoptions = bonusChest ? dedicatedserverproperties.worldOptions.withBonusChest(true) : dedicatedserverproperties.worldOptions; - worlddimensions = dedicatedserverproperties.createDimensions(context.datapackWorldgen()); + shutdownThread.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER)); +@@ -254,6 +_,16 @@ + worldOptions = bonusChest ? properties.worldOptions.withBonusChest(true) : properties.worldOptions; + dimensions = properties.createDimensions(context.datapackWorldgen()); } + + //Forge: Do a write-read-cycle to inject modded dimensions on first start of a dedicated server into its generated world dimensions list. + var dynamicops = net.minecraft.resources.RegistryOps.create(net.minecraft.nbt.NbtOps.INSTANCE, context.datapackWorldgen()); -+ worlddimensions = WorldDimensions.CODEC.encoder() -+ .encodeStart(dynamicops, worlddimensions) ++ dimensions = WorldDimensions.CODEC.encoder() ++ .encodeStart(dynamicops, dimensions) + .flatMap((writtenPayloadWithModdedDimensions) -> + WorldDimensions.CODEC.decoder().parse(dynamicops, writtenPayloadWithModdedDimensions) + ) + .resultOrPartial(LOGGER::error) -+ .orElse(worlddimensions); ++ .orElse(dimensions); - WorldDimensions.Complete worlddimensions$complete = worlddimensions.bake(datapackDimensions); - Lifecycle lifecycle = worlddimensions$complete.lifecycle().add(context.datapackWorldgen().allRegistriesLifecycle()); + WorldDimensions.Complete finalDimensions = dimensions.bake(datapackDimensions); + Lifecycle lifecycle = finalDimensions.lifecycle().add(context.datapackWorldgen().allRegistriesLifecycle()); diff --git a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch index e95d01147d..f9a9dfaf3a 100644 --- a/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch +++ b/patches/minecraft/net/minecraft/server/MinecraftServer.java.patch @@ -1,47 +1,47 @@ --- a/net/minecraft/server/MinecraftServer.java +++ b/net/minecraft/server/MinecraftServer.java -@@ -298,7 +_,7 @@ +@@ -297,7 +_,7 @@ public static S spin(final Function factory) { - AtomicReference atomicreference = new AtomicReference<>(); -- Thread thread = new Thread(() -> atomicreference.get().runServer(), "Server thread"); -+ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, () -> atomicreference.get().runServer(), "Server thread"); + AtomicReference serverReference = new AtomicReference<>(); +- Thread thread = new Thread(() -> serverReference.get().runServer(), "Server thread"); ++ Thread thread = new Thread(net.minecraftforge.fml.util.thread.SidedThreadGroups.SERVER, () -> serverReference.get().runServer(), "Server thread"); thread.setUncaughtExceptionHandler((t, e) -> LOGGER.error("Uncaught exception in server thread", e)); if (Runtime.getRuntime().availableProcessors() > 4) { thread.setPriority(8); -@@ -442,6 +_,7 @@ +@@ -443,6 +_,7 @@ this.scoreboard.load(this.savedDataStorage.computeIfAbsent(ScoreboardSaveData.TYPE).getData()); this.commandStorage = new CommandStorage(this.savedDataStorage); this.stopwatches = this.savedDataStorage.computeIfAbsent(Stopwatches.TYPE); + net.minecraftforge.event.ForgeEventFactory.onLevelLoad(levels.get(Level.OVERWORLD)); - if (!serverleveldata.isInitialized()) { + if (!levelData.isInitialized()) { try { - setInitialSpawn(serverlevel, serverleveldata, worldoptions.generateBonusChest(), flag, this.levelLoadListener); -@@ -476,6 +_,7 @@ - this, this.executor, this.storageSource, derivedleveldata, resourcekey1, entry.getValue(), flag, j, ImmutableList.of(), false + setInitialSpawn(overworld, levelData, worldOptions.generateBonusChest(), isDebug, this.levelLoadListener); +@@ -477,6 +_,7 @@ + this, this.executor, this.storageSource, derivedLevelData, dimension, entry.getValue(), isDebug, biomeZoomSeed, ImmutableList.of(), false ); - this.levels.put(resourcekey1, serverlevel1); -+ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(serverlevel1); + this.levels.put(dimension, level); ++ net.minecraftforge.event.ForgeEventFactory.onLevelLoad(level); } else { - serverlevel1 = serverlevel; + level = overworld; } -@@ -498,6 +_,7 @@ +@@ -499,6 +_,7 @@ levelData.setSpawn(LevelData.RespawnData.of(level.dimension(), BlockPos.ZERO.above(80), 0.0F, 0.0F)); } else { - ServerChunkCache serverchunkcache = level.getChunkSource(); + ServerChunkCache chunkSource = level.getChunkSource(); + if (net.minecraftforge.event.ForgeEventFactory.onCreateWorldSpawn(level, levelData)) return; - ChunkPos chunkpos = ChunkPos.containing(serverchunkcache.randomState().sampler().findSpawnPosition()); + ChunkPos spawnChunk = ChunkPos.containing(chunkSource.randomState().sampler().findSpawnPosition()); levelLoadListener.start(LevelLoadListener.Stage.PREPARE_GLOBAL_SPAWN, 0); - levelLoadListener.updateFocus(level.dimension(), chunkpos); -@@ -687,6 +_,7 @@ - for (ServerLevel serverlevel2 : this.getAllLevels()) { - if (serverlevel2 != null) { + levelLoadListener.updateFocus(level.dimension(), spawnChunk); +@@ -688,6 +_,7 @@ + for (ServerLevel levelx : this.getAllLevels()) { + if (levelx != null) { try { -+ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(serverlevel2); - serverlevel2.close(); - } catch (IOException ioexception1) { - LOGGER.error("Exception closing the level", (Throwable)ioexception1); -@@ -734,9 +_,11 @@ ++ net.minecraftforge.event.ForgeEventFactory.onLevelUnload(levelx); + levelx.close(); + } catch (IOException var5) { + LOGGER.error("Exception closing the level", (Throwable)var5); +@@ -735,9 +_,11 @@ throw new IllegalStateException("Failed to initialize server"); } @@ -52,33 +52,33 @@ + resetStatusCache(status); while (this.running) { - long i; -@@ -786,6 +_,8 @@ + long thisTickNanos; +@@ -791,6 +_,8 @@ this.isReady = true; JvmProfiler.INSTANCE.onServerTick(this.smoothedTickTimeMillis); } + net.minecraftforge.server.ServerLifecycleHooks.handleServerStopping(this); + net.minecraftforge.server.ServerLifecycleHooks.expectServerStopped(); // Forge: Has to come before MinecraftServer#onServerCrash to avoid race conditions - } catch (Throwable throwable2) { - LOGGER.error("Encountered an unexpected exception", throwable2); - CrashReport crashreport = constructOrExtractCrashReport(throwable2); -@@ -797,6 +_,7 @@ + } catch (Throwable var69) { + LOGGER.error("Encountered an unexpected exception", var69); + CrashReport report = constructOrExtractCrashReport(var69); +@@ -802,6 +_,7 @@ LOGGER.error("We were unable to save this crash report to disk."); } + net.minecraftforge.server.ServerLifecycleHooks.expectServerStopped(); // Forge: Has to come before MinecraftServer#onServerCrash to avoid race conditions - this.onServerCrash(crashreport); + this.onServerCrash(report); } finally { try { -@@ -805,6 +_,7 @@ - } catch (Throwable throwable) { - LOGGER.error("Exception stopping the server", throwable); +@@ -810,6 +_,7 @@ + } catch (Throwable var64) { + LOGGER.error("Exception stopping the server", var64); } finally { + net.minecraftforge.server.ServerLifecycleHooks.handleServerStopped(this); this.onServerExit(); } } -@@ -985,12 +_,14 @@ +@@ -990,12 +_,14 @@ } } @@ -86,23 +86,23 @@ this.tickCount++; this.tickRateManager.tick(); this.tickChildren(haveTime); - if (i - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { - this.lastServerStatus = i; + if (nano - this.lastServerStatus >= STATUS_EXPIRE_TIME_NANOS) { + this.lastServerStatus = nano; this.status = this.buildServerStatus(); + resetStatusCache(status); } this.ticksUntilAutosave--; -@@ -1008,6 +_,7 @@ - this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)k / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F; - this.logTickMethodTime(i); - profilerfiller.pop(); +@@ -1013,6 +_,7 @@ + this.smoothedTickTimeMillis = this.smoothedTickTimeMillis * 0.8F + (float)tickTime / (float)TimeUtil.NANOSECONDS_PER_MILLISECOND * 0.19999999F; + this.logTickMethodTime(nano); + profiler.pop(); + net.minecraftforge.event.ForgeEventFactory.onPostServerTick(haveTime, this); } protected void processPacketsAndTick(final boolean sprinting) { -@@ -1069,7 +_,8 @@ - Optional.of(serverstatus$players), +@@ -1074,7 +_,8 @@ + Optional.of(players), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), - this.enforceSecureProfile() @@ -111,41 +111,41 @@ ); } -@@ -1114,9 +_,11 @@ - profilerfiller.push("levels"); +@@ -1119,9 +_,11 @@ + profiler.push("levels"); this.updateEffectiveRespawnData(); -- for (ServerLevel serverlevel : this.getAllLevels()) { -+ for (ServerLevel serverlevel : this.getWorldArray()) { +- for (ServerLevel level : this.getAllLevels()) { ++ for (ServerLevel level : this.getWorldArray()) { + long tickStart = Util.getNanos(); - profilerfiller.push(() -> serverlevel + " " + serverlevel.dimension().identifier()); - profilerfiller.push("tick"); -+ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(serverlevel, haveTime); + profiler.push(() -> level + " " + level.dimension().identifier()); + profiler.push("tick"); ++ net.minecraftforge.event.ForgeEventFactory.onPreLevelTick(level, haveTime); try { - serverlevel.tick(haveTime); -@@ -1125,9 +_,11 @@ - serverlevel.fillReportDetails(crashreport); - throw new ReportedException(crashreport); + level.tick(haveTime); +@@ -1130,9 +_,11 @@ + level.fillReportDetails(report); + throw new ReportedException(report); } -+ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(serverlevel, haveTime); ++ net.minecraftforge.event.ForgeEventFactory.onPostLevelTick(level, haveTime); - profilerfiller.pop(); - profilerfiller.pop(); -+ perWorldTickTimes.computeIfAbsent(serverlevel.dimension(), k -> new long[100])[this.tickCount % 100] = Util.getNanos() - tickStart; + profiler.pop(); + profiler.pop(); ++ perWorldTickTimes.computeIfAbsent(level.dimension(), k -> new long[100])[this.tickCount % 100] = Util.getNanos() - tickStart; } - profilerfiller.popPush("connection"); -@@ -1136,7 +_,7 @@ + profiler.popPush("connection"); +@@ -1141,7 +_,7 @@ this.playerList.tick(); - profilerfiller.popPush("debugSubscribers"); + profiler.popPush("debugSubscribers"); this.debugSubscribers.tick(); - if (this.tickRateManager.runsNormally()) { + if (net.minecraftforge.gametest.ForgeGameTestHooks.isGametestEnabled() && this.tickRateManager.runsNormally()) { - profilerfiller.popPush("gameTests"); + profiler.popPush("gameTests"); GameTestTicker.SINGLETON.tick(); } -@@ -1222,7 +_,7 @@ +@@ -1227,7 +_,7 @@ } public String getServerModName() { @@ -154,32 +154,32 @@ } public ServerClockManager clockManager() { -@@ -1561,6 +_,7 @@ - this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); - this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); - this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures()); -+ this.getPlayerList().getPlayers().forEach(this.getPlayerList()::sendPlayerPermissionLevel); //Forge: Fix newly added/modified commands not being sent to the client when commands reload. - }, - this - ); +@@ -1563,6 +_,7 @@ + this.functionManager.replaceLibrary(this.resources.managers.getFunctionLibrary()); + this.structureTemplateManager.onResourceManagerReload(this.resources.resourceManager); + this.fuelValues = FuelValues.vanillaBurnTimes(this.registries.compositeAccess(), this.worldData.enabledFeatures()); ++ this.getPlayerList().getPlayers().forEach(this.getPlayerList()::sendPlayerPermissionLevel); //Forge: Fix newly added/modified commands not being sent to the client when commands reload. + }, this); + if (this.isSameThread()) { + this.managedBlock(result::isDone); @@ -1574,12 +_,15 @@ public static WorldDataConfiguration configurePackRepository( final PackRepository packRepository, final WorldDataConfiguration initialDataConfig, final boolean initMode, final boolean safeMode ) { + net.minecraftforge.resource.ResourcePackLoader.loadResourcePacks(packRepository, false); - DataPackConfig datapackconfig = initialDataConfig.dataPacks(); - FeatureFlagSet featureflagset = initMode ? FeatureFlagSet.of() : initialDataConfig.enabledFeatures(); - FeatureFlagSet featureflagset1 = initMode ? FeatureFlags.REGISTRY.allFlags() : initialDataConfig.enabledFeatures(); + DataPackConfig dataPackConfig = initialDataConfig.dataPacks(); + FeatureFlagSet forcedFeatures = initMode ? FeatureFlagSet.of() : initialDataConfig.enabledFeatures(); + FeatureFlagSet allowedFeatures = initMode ? FeatureFlags.REGISTRY.allFlags() : initialDataConfig.enabledFeatures(); packRepository.reload(); + DataPackConfig.DEFAULT.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); -+ datapackconfig.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); ++ dataPackConfig.addModPacks(net.minecraftforge.common.ForgeHooks.getModPacks()); if (safeMode) { -- return configureRepositoryWithSelection(packRepository, List.of("vanilla"), featureflagset, false); -+ return configureRepositoryWithSelection(packRepository, net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla(), featureflagset, false); +- return configureRepositoryWithSelection(packRepository, List.of("vanilla"), forcedFeatures, false); ++ return configureRepositoryWithSelection(packRepository, net.minecraftforge.common.ForgeHooks.getModPacksWithVanilla(), forcedFeatures, false); } else { - Set set = Sets.newLinkedHashSet(); + Set selected = Sets.newLinkedHashSet(); -@@ -2235,6 +_,48 @@ +@@ -2233,6 +_,48 @@ public ServerLinks serverLinks() { return ServerLinks.EMPTY; diff --git a/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch b/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch index de5ada8ca9..e99ae1a416 100644 --- a/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch +++ b/patches/minecraft/net/minecraft/server/PlayerAdvancements.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/server/PlayerAdvancements.java +++ b/net/minecraft/server/PlayerAdvancements.java -@@ -173,6 +_,7 @@ +@@ -172,6 +_,7 @@ this.unregisterListeners(holder); this.progressChanged.add(holder); - flag = true; -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementGrant(this.player, holder, advancementprogress, criterion); - if (!flag1 && advancementprogress.isDone()) { + result = true; ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementGrant(this.player, holder, progress, criterion); + if (!wasDone && progress.isDone()) { holder.value().rewards().grant(this.player); holder.value().display().ifPresent(display -> { -@@ -180,6 +_,7 @@ +@@ -179,6 +_,7 @@ this.playerList.broadcastSystemMessage(display.getType().createAnnouncement(holder, this.player), false); } }); @@ -16,11 +16,11 @@ } } -@@ -198,6 +_,7 @@ +@@ -197,6 +_,7 @@ this.registerListeners(advancement); this.progressChanged.add(advancement); - flag = true; -+ net.minecraftforge.event.ForgeEventFactory.onAdvancementRevoke(this.player, advancement, advancementprogress, criterion); + result = true; ++ net.minecraftforge.event.ForgeEventFactory.onAdvancementRevoke(this.player, advancement, progress, criterion); } - if (flag1 && !advancementprogress.isDone()) { + if (wasDone && !progress.isDone()) { diff --git a/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch b/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch index 2b83c4c672..5715cce8ce 100644 --- a/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch +++ b/patches/minecraft/net/minecraft/server/ReloadableServerResources.java.patch @@ -26,8 +26,8 @@ ); return SimpleReloadInstance.create( resourceManager, -- reloadableserverresources.listeners(), -+ net.minecraftforge.event.ForgeEventFactory.onResourceReload(reloadableserverresources, fullRegistries.lookupWithUpdatedTags(), reloadableserverresources.listeners()), +- result.listeners(), ++ net.minecraftforge.event.ForgeEventFactory.onResourceReload(result, fullRegistries.lookupWithUpdatedTags(), result.listeners()), backgroundExecutor, mainThreadExecutor, DATA_RELOAD_INITIAL_TASK, diff --git a/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch b/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch index 12964180ba..cc24e84257 100644 --- a/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch +++ b/patches/minecraft/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java +++ b/net/minecraft/server/advancements/AdvancementVisibilityEvaluator.java @@ -71,6 +_,16 @@ - evaluateVisibility(advancementnode, stack, isDone, output); + evaluateVisibility(root, visibilityStack, isDone, output); } + public static boolean isVisible(AdvancementNode advancement, Predicate test) { diff --git a/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch b/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch index bdd30a179a..c32d931e5c 100644 --- a/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch +++ b/patches/minecraft/net/minecraft/server/commands/SpreadPlayersCommand.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/server/commands/SpreadPlayersCommand.java +++ b/net/minecraft/server/commands/SpreadPlayersCommand.java -@@ -259,11 +_,17 @@ - spreadplayerscommand$position = positions[i++]; +@@ -256,11 +_,17 @@ + position = positions[positionIndex++]; } + var event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportSpreadPlayersCommand(entity, -+ (double)Mth.floor(spreadplayerscommand$position.x) + 0.5D, -+ (double)spreadplayerscommand$position.getSpawnY(level, maxHeight), -+ (double)Mth.floor(spreadplayerscommand$position.z) + 0.5D ++ (double)Mth.floor(position.x) + 0.5D, ++ (double)position.getSpawnY(level, maxHeight), ++ (double)Mth.floor(position.z) + 0.5D + ); + if (event != null) entity.teleportTo( level, -- Mth.floor(spreadplayerscommand$position.x) + 0.5, -- spreadplayerscommand$position.getSpawnY(level, maxHeight), -- Mth.floor(spreadplayerscommand$position.z) + 0.5, +- Mth.floor(position.x) + 0.5, +- position.getSpawnY(level, maxHeight), +- Mth.floor(position.z) + 0.5, + event.getTargetX(), + event.getTargetY(), + event.getTargetZ(), diff --git a/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch b/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch index ce03e555fe..11f9610d5d 100644 --- a/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch +++ b/patches/minecraft/net/minecraft/server/commands/TeleportCommand.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/commands/TeleportCommand.java +++ b/net/minecraft/server/commands/TeleportCommand.java -@@ -237,14 +_,17 @@ +@@ -236,14 +_,17 @@ final CommandSourceStack source, final Entity victim, final ServerLevel level, @@ -18,6 +18,6 @@ + var event = net.minecraftforge.event.ForgeEventFactory.onEntityTeleportCommand(victim, x, y, z); + if (event == null) return; + x = event.getTargetX(); y = event.getTargetY(); z = event.getTargetZ(); - BlockPos blockpos = BlockPos.containing(x, y, z); - if (!Level.isInSpawnableBounds(blockpos)) { + BlockPos blockPos = BlockPos.containing(x, y, z); + if (!Level.isInSpawnableBounds(blockPos)) { throw INVALID_POSITION.create(); diff --git a/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch b/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch index 3edd705b17..5cf33b4b10 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/DedicatedServer.java.patch @@ -13,22 +13,22 @@ @Override public void run() { + if (net.minecraftforge.server.console.TerminalHandler.handleCommands(DedicatedServer.this)) return; - BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); - String s4; + String line; @@ -284,11 +_,13 @@ this.tickTimeLogger = new RemoteSampleLogger(TpsDebugDimensions.values().length, this.debugSubscribers(), RemoteDebugSampleType.TICK_TIME); - long j = Util.getNanos(); + long levelNanoTime = Util.getNanos(); this.services.nameToIdCache().resolveOfflineUsers(!this.usesAuthentication()); + if (!net.minecraftforge.server.ServerLifecycleHooks.handleServerAboutToStart(this)) return false; LOGGER.info("Preparing level \"{}\"", this.getLevelIdName()); this.loadLevel(); - long k = Util.getNanos() - j; - String s3 = String.format(Locale.ROOT, "%.3fs", k / 1.0E9); - LOGGER.info("Done ({})! For help, type \"help\"", s3); + long elapsed = Util.getNanos() - levelNanoTime; + String time = String.format(Locale.ROOT, "%.3fs", elapsed / 1.0E9); + LOGGER.info("Done ({})! For help, type \"help\"", time); + this.nextTickTimeNanos = Util.getNanos(); //Forge: Update server time to prevent watchdog/spaming during long load. - if (dedicatedserverproperties.announcePlayerAchievements != null) { - this.getGameRules().set(GameRules.SHOW_ADVANCEMENT_MESSAGES, dedicatedserverproperties.announcePlayerAchievements, this); + if (properties.announcePlayerAchievements != null) { + this.getGameRules().set(GameRules.SHOW_ADVANCEMENT_MESSAGES, properties.announcePlayerAchievements, this); } @@ -318,7 +_,12 @@ @@ -45,7 +45,7 @@ } @@ -470,6 +_,13 @@ - LOGGER.error("Interrupted while stopping the management server", (Throwable)interruptedexception); + LOGGER.error("Interrupted while stopping the management server", (Throwable)var2); } } + diff --git a/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch b/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch index 65f8c6b9e7..c539d68dc4 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/ServerWatchdog.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/server/dedicated/ServerWatchdog.java +++ b/net/minecraft/server/dedicated/ServerWatchdog.java -@@ -79,7 +_,7 @@ - ThreadMXBean threadmxbean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] athreadinfo = threadmxbean.dumpAllThreads(true, true); - StringBuilder stringbuilder = new StringBuilder(); -- Error error = new Error("Watchdog"); -+ Error error = new Error(String.format(java.util.Locale.ENGLISH, "ServerHangWatchdog detected that a single server tick took too long")); // Forge: don't just make a crash report with a seemingly-inexplicable Error +@@ -78,7 +_,7 @@ + ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); + ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(true, true); + StringBuilder builder = new StringBuilder(); +- Error exception = new Error("Watchdog"); ++ Error exception = new Error(String.format(java.util.Locale.ENGLISH, "ServerHangWatchdog detected that a single server tick took too long")); // Forge: don't just make a crash report with a seemingly-inexplicable Error - for (ThreadInfo threadinfo : athreadinfo) { - if (threadinfo.getThreadId() == mainThreadId) { + for (ThreadInfo threadInfo : threadInfos) { + if (threadInfo.getThreadId() == mainThreadId) { diff --git a/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch b/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch index 649f6c8dde..26cb9685f4 100644 --- a/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch +++ b/patches/minecraft/net/minecraft/server/dedicated/Settings.java.patch @@ -3,9 +3,9 @@ @@ -66,7 +_,7 @@ public void store(final Path output) { - try (Writer writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) { -- this.properties.store(writer, "Minecraft server properties"); -+ net.minecraftforge.common.util.SortedProperties.store(this.properties, writer, "Minecraft server properties"); - } catch (IOException ioexception) { + try (Writer os = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) { +- this.properties.store(os, "Minecraft server properties"); ++ net.minecraftforge.common.util.SortedProperties.store(this.properties, os, "Minecraft server properties"); + } catch (IOException var7) { LOGGER.error("Failed to store properties to file: {}", output); } diff --git a/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch b/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch index a9d82bd6ab..44192e7b79 100644 --- a/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch +++ b/patches/minecraft/net/minecraft/server/gui/MinecraftServerGui.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/server/gui/MinecraftServerGui.java +++ b/net/minecraft/server/gui/MinecraftServerGui.java -@@ -142,8 +_,10 @@ - return jpanel; +@@ -141,8 +_,10 @@ + return panel; } + private final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); @@ -11,7 +11,7 @@ } public void close() { -@@ -157,6 +_,9 @@ +@@ -156,6 +_,9 @@ } public void print(final JTextArea console, final JScrollPane scrollPane, final String line) { diff --git a/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch b/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch index 5b7d1ce644..207194d26e 100644 --- a/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ChunkMap.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ChunkMap.java +++ b/net/minecraft/server/level/ChunkMap.java -@@ -402,6 +_,7 @@ +@@ -391,6 +_,7 @@ this.modified = true; } @@ -8,28 +8,28 @@ return chunk; } } -@@ -533,6 +_,7 @@ - if (this.pendingUnloads.remove(pos, chunkHolder) && chunkaccess != null) { - if (chunkaccess instanceof LevelChunk levelchunk) { - levelchunk.setLoaded(false); -+ net.minecraftforge.event.ForgeEventFactory.onChunkUnload(chunkaccess); +@@ -522,6 +_,7 @@ + if (this.pendingUnloads.remove(pos, chunkHolder) && chunk != null) { + if (chunk instanceof LevelChunk levelChunk) { + levelChunk.setLoaded(false); ++ net.minecraftforge.event.ForgeEventFactory.onChunkUnload(chunk); } - this.save(chunkaccess); -@@ -775,6 +_,7 @@ + this.save(chunk); +@@ -764,6 +_,7 @@ this.activeChunkWrites.incrementAndGet(); - SerializableChunkData serializablechunkdata = SerializableChunkData.copyOf(this.level, chunk); - CompletableFuture completablefuture = CompletableFuture.supplyAsync(serializablechunkdata::write, Util.backgroundExecutor()); -+ net.minecraftforge.event.ForgeEventFactory.onChunkDataSave(chunk, chunk.getWorldForge() != null ? chunk.getWorldForge() : this.level, serializablechunkdata); - this.write(chunkpos, completablefuture::join).handle((ignored, throwable) -> { + SerializableChunkData data = SerializableChunkData.copyOf(this.level, chunk); + CompletableFuture encodedData = CompletableFuture.supplyAsync(data::write, Util.backgroundExecutor()); ++ net.minecraftforge.event.ForgeEventFactory.onChunkDataSave(chunk, chunk.getWorldForge() != null ? chunk.getWorldForge() : this.level, data); + this.write(pos, encodedData::join).handle((ignored, throwable) -> { if (throwable != null) { - this.level.getServer().reportChunkSaveFailure(throwable, this.storageInfo(), chunkpos); -@@ -1153,7 +_,7 @@ + this.level.getServer().reportChunkSaveFailure(throwable, this.storageInfo(), pos); +@@ -1136,7 +_,7 @@ } protected void addEntity(final Entity entity) { - if (!(entity instanceof EnderDragonPart)) { + if (!(entity instanceof net.minecraftforge.entity.PartEntity)) { - EntityType entitytype = entity.getType(); - int i = entitytype.clientTrackingRange() * 16; - if (i != 0) { + EntityType type = entity.getType(); + int range = type.clientTrackingRange() * 16; + if (range != 0) { diff --git a/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch b/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch index 9bb577024b..f62f30b1af 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerChunkCache.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/server/level/ServerChunkCache.java +++ b/net/minecraft/server/level/ServerChunkCache.java @@ -193,6 +_,10 @@ - if (chunkholder == null) { + if (chunkHolder == null) { return null; } else { + // Forge: If the requested chunk is loading, bypass the future chain to prevent a deadlock. -+ if (chunkholder.currentlyLoading != null) { -+ return chunkholder.currentlyLoading; ++ if (chunkHolder.currentlyLoading != null) { ++ return chunkHolder.currentlyLoading; + } - ChunkAccess chunkaccess1 = chunkholder.getChunkIfPresent(ChunkStatus.FULL); - if (chunkaccess1 != null) { - this.storeInCache(i, chunkaccess1, ChunkStatus.FULL); + ChunkAccess chunk = chunkHolder.getChunkIfPresent(ChunkStatus.FULL); + if (chunk != null) { + this.storeInCache(pos, chunk, ChunkStatus.FULL); diff --git a/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch b/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch index 9e1502d711..40dfb42506 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerEntity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ServerEntity.java +++ b/net/minecraft/server/level/ServerEntity.java -@@ -258,6 +_,7 @@ +@@ -257,6 +_,7 @@ public void removePairing(final ServerPlayer player) { this.entity.stopSeenByPlayer(player); player.connection.send(new ClientboundRemoveEntitiesPacket(this.entity.getId())); @@ -8,9 +8,9 @@ } public void addPairing(final ServerPlayer player) { -@@ -265,6 +_,7 @@ - this.sendPairingData(player, list::add); - player.connection.send(new ClientboundBundlePacket(list)); +@@ -264,6 +_,7 @@ + this.sendPairingData(player, packets::add); + player.connection.send(new ClientboundBundlePacket(packets)); this.entity.startSeenByPlayer(player); + net.minecraftforge.event.ForgeEventFactory.onStartEntityTracking(this.entity, player); } diff --git a/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch b/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch index 73c8cd7385..06fa862fa8 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerLevel.java.patch @@ -33,13 +33,13 @@ @Deprecated @@ -354,7 +_,9 @@ - if (this.sleepStatus.areEnoughSleeping(i) && this.sleepStatus.areEnoughDeepSleeping(i, this.players)) { - Optional> optional = this.dimensionType().defaultClock(); - if (this.getGameRules().get(GameRules.ADVANCE_TIME) && optional.isPresent()) { -- this.server.clockManager().moveToTimeMarker(optional.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); -+ long minTime = this.server.clockManager().getTotalTicks(optional.get()); -+ long newTime = this.server.clockManager().getTimeMarker(optional.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); -+ this.server.clockManager().setTotalTicks(optional.get(), net.minecraftforge.event.ForgeEventFactory.onSleepFinished(this, newTime, minTime)); + if (this.sleepStatus.areEnoughSleeping(percentage) && this.sleepStatus.areEnoughDeepSleeping(percentage, this.players)) { + Optional> defaultClock = this.dimensionType().defaultClock(); + if (this.getGameRules().get(GameRules.ADVANCE_TIME) && defaultClock.isPresent()) { +- this.server.clockManager().moveToTimeMarker(defaultClock.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); ++ long minTime = this.server.clockManager().getTotalTicks(defaultClock.get()); ++ long newTime = this.server.clockManager().getTimeMarker(defaultClock.get(), ClockTimeMarkers.WAKE_UP_FROM_SLEEP); ++ this.server.clockManager().setTotalTicks(defaultClock.get(), net.minecraftforge.event.ForgeEventFactory.onSleepFinished(this, newTime, minTime)); } this.wakeUpAllPlayers(); @@ -48,16 +48,16 @@ } + if (entity.isRemoved() || entity instanceof net.minecraftforge.entity.PartEntity) return; - profilerfiller.push("tick"); + profiler.push("tick"); this.guardEntityTick(this::tickNonPassenger, entity); - profilerfiller.pop(); + profiler.pop(); @@ -569,6 +_,7 @@ - BlockPos blockpos = this.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, pos); - BlockPos blockpos1 = blockpos.below(); - Biome biome = this.getBiome(blockpos).value(); -+ if (this.isAreaLoaded(blockpos1, 1)) // Forge: check area to avoid loading neighbors in unloaded chunks - if (biome.shouldFreeze(this, blockpos1)) { - this.setBlockAndUpdate(blockpos1, Blocks.ICE.defaultBlockState()); + BlockPos topPos = this.getHeightmapPos(Heightmap.Types.MOTION_BLOCKING, pos); + BlockPos belowPos = topPos.below(); + Biome biome = this.getBiome(topPos).value(); ++ if (this.isAreaLoaded(belowPos, 1)) // Forge: check area to avoid loading neighbors in unloaded chunks + if (biome.shouldFreeze(this, belowPos)) { + this.setBlockAndUpdate(belowPos, Blocks.ICE.defaultBlockState()); } @@ -778,8 +_,8 @@ this.server.getPlayerList().broadcastAll(new ClientboundGameEventPacket(ClientboundGameEventPacket.START_RAINING, 0.0F)); @@ -72,19 +72,19 @@ @@ -817,6 +_,7 @@ entity.tickCount++; - profilerfiller.push(entity.typeHolder()::getRegisteredName); - profilerfiller.incrementCounter("tickNonPassenger"); + profiler.push(entity.typeHolder()::getRegisteredName); + profiler.incrementCounter("tickNonPassenger"); + if (entity.canUpdate()) entity.tick(); - profilerfiller.pop(); + profiler.pop(); @@ -834,6 +_,7 @@ - ProfilerFiller profilerfiller = Profiler.get(); - profilerfiller.push(entity.typeHolder()::getRegisteredName); - profilerfiller.incrementCounter("tickPassenger"); + ProfilerFiller profiler = Profiler.get(); + profiler.push(entity.typeHolder()::getRegisteredName); + profiler.incrementCounter("tickPassenger"); + if (entity.canUpdate()) entity.rideTick(); - profilerfiller.pop(); + profiler.pop(); @@ -880,6 +_,7 @@ } else { @@ -99,11 +99,11 @@ private void addPlayer(final ServerPlayer player) { + if (net.minecraftforge.event.ForgeEventFactory.onEntityJoinLevel(player, this)) return; - Entity entity = this.getEntity(player.getUUID()); - if (entity != null) { + Entity existing = this.getEntity(player.getUUID()); + if (existing != null) { LOGGER.warn("Force-added player with duplicate UUID {}", player.getUUID()); @@ -978,7 +_,8 @@ - this.removePlayerImmediately((ServerPlayer)entity, Entity.RemovalReason.DISCARDED); + this.removePlayerImmediately((ServerPlayer)existing, Entity.RemovalReason.DISCARDED); } - this.entityManager.addNewEntity(player); @@ -201,7 +201,7 @@ } @@ -1214,7 +_,7 @@ - Explosion.BlockInteraction explosion$blockinteraction = switch (interactionType) { + Explosion.BlockInteraction blockInteraction = switch (interactionType) { case NONE -> Explosion.BlockInteraction.KEEP; case BLOCK -> this.getDestroyType(GameRules.BLOCK_EXPLOSION_DROP_DECAY); - case MOB -> this.getGameRules().get(GameRules.MOB_GRIEFING) @@ -211,12 +211,12 @@ case TNT -> this.getDestroyType(GameRules.TNT_EXPLOSION_DROP_DECAY); @@ -1222,6 +_,8 @@ }; - Vec3 vec3 = new Vec3(x, y, z); - ServerExplosion serverexplosion = new ServerExplosion(this, source, damageSource, damageCalculator, vec3, r, fire, explosion$blockinteraction); -+ if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, serverexplosion)) + Vec3 center = new Vec3(x, y, z); + ServerExplosion explosion = new ServerExplosion(this, source, damageSource, damageCalculator, center, r, fire, blockInteraction); ++ if (net.minecraftforge.event.ForgeEventFactory.onExplosionStart(this, explosion)) + return; - int i = serverexplosion.explode(); - ParticleOptions particleoptions = serverexplosion.isSmall() ? smallExplosionParticles : largeExplosionParticles; + int blockCount = explosion.explode(); + ParticleOptions explosionParticle = explosion.isSmall() ? smallExplosionParticles : largeExplosionParticles; @@ -1888,6 +_,11 @@ return this.getGameRules().get(GameRules.SPAWNER_BLOCKS_WORK); diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch index cc94492ca6..2ee95df9d8 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayer.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ServerPlayer.java +++ b/net/minecraft/server/level/ServerPlayer.java -@@ -205,7 +_,8 @@ +@@ -202,7 +_,8 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -10,15 +10,15 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_XZ = 32; private static final int NEUTRAL_MOB_DEATH_NOTIFICATION_RADII_Y = 10; -@@ -885,6 +_,7 @@ +@@ -880,6 +_,7 @@ @Override public void die(final DamageSource source) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, source)) return; this.gameEvent(GameEvent.ENTITY_DIE); - boolean flag = this.level().getGameRules().get(GameRules.SHOW_DEATH_MESSAGES); - if (flag) { -@@ -1098,6 +_,7 @@ + boolean showDeathMessage = this.level().getGameRules().get(GameRules.SHOW_DEATH_MESSAGES); + if (showDeathMessage) { +@@ -1088,6 +_,7 @@ } public @Nullable ServerPlayer teleport(final TeleportTransition transition) { @@ -26,24 +26,24 @@ if (this.isRemoved()) { return null; } else { -@@ -1125,7 +_,7 @@ - PlayerList playerlist = this.server.getPlayerList(); - playerlist.sendPlayerPermissionLevel(this); - serverlevel1.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); +@@ -1115,7 +_,7 @@ + PlayerList playerList = this.server.getPlayerList(); + playerList.sendPlayerPermissionLevel(this); + oldLevel.removePlayerImmediately(this, Entity.RemovalReason.CHANGED_DIMENSION); - this.unsetRemoved(); + this.revive(); - ProfilerFiller profilerfiller = Profiler.get(); - profilerfiller.push("moving"); - if (resourcekey == Level.OVERWORLD && serverlevel.dimension() == Level.NETHER) { -@@ -1150,6 +_,7 @@ + ProfilerFiller profiler = Profiler.get(); + profiler.push("moving"); + if (lastDimension == Level.OVERWORLD && newLevel.dimension() == Level.NETHER) { +@@ -1140,6 +_,7 @@ this.lastSentHealth = -1.0F; this.lastSentFood = -1; - this.teleportSpectators(transition, serverlevel1); -+ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, resourcekey, transition.newLevel().dimension()); + this.teleportSpectators(transition, oldLevel); ++ net.minecraftforge.event.ForgeEventFactory.onPlayerChangedDimension(this, lastDimension, transition.newLevel().dimension()); return this; } } -@@ -1191,10 +_,13 @@ +@@ -1181,10 +_,13 @@ @Override public Either startSleepInBed(final BlockPos pos) { @@ -52,13 +52,13 @@ + if (ret != null) return Either.left(ret); Direction direction = this.level().getBlockState(pos).getValue(HorizontalDirectionalBlock.FACING); if (!this.isSleeping() && this.isAlive()) { - BedRule bedrule = this.level().environmentAttributes().getValue(EnvironmentAttributes.BED_RULE, pos); -- boolean flag = bedrule.canSleep(this.level()); -+ boolean flag = net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, optAt, bedrule); - boolean flag1 = bedrule.canSetSpawn(this.level()); - if (!flag1 && !flag) { - return Either.left(bedrule.asProblem()); -@@ -1251,6 +_,7 @@ + BedRule rule = this.level().environmentAttributes().getValue(EnvironmentAttributes.BED_RULE, pos); +- boolean canSleep = rule.canSleep(this.level()); ++ boolean canSleep = net.minecraftforge.event.ForgeEventFactory.onSleepingTimeCheck(this, optAt, rule); + boolean canSetSpawn = rule.canSetSpawn(this.level()); + if (!canSetSpawn && !canSleep) { + return Either.left(rule.asProblem()); +@@ -1248,6 +_,7 @@ } private boolean bedInRange(final BlockPos pos, final Direction direction) { @@ -66,15 +66,15 @@ return this.isReachableBedBlock(pos) || this.isReachableBedBlock(pos.relative(direction.getOpposite())); } -@@ -1351,6 +_,7 @@ - .send(new ClientboundOpenScreenPacket(abstractcontainermenu.containerId, abstractcontainermenu.getType(), provider.getDisplayName())); - this.initMenu(abstractcontainermenu); - this.containerMenu = abstractcontainermenu; +@@ -1350,6 +_,7 @@ + this.connection.send(new ClientboundOpenScreenPacket(menu.containerId, menu.getType(), provider.getDisplayName())); + this.initMenu(menu); + this.containerMenu = menu; + net.minecraftforge.event.ForgeEventFactory.onPlayerOpenContainer(this, this.containerMenu); return OptionalInt.of(this.containerCounter); } } -@@ -1420,6 +_,7 @@ +@@ -1419,6 +_,7 @@ public void doCloseContainer() { this.containerMenu.removed(this); this.inventoryMenu.transferState(this.containerMenu); @@ -82,7 +82,7 @@ this.containerMenu = this.inventoryMenu; } -@@ -1637,6 +_,15 @@ +@@ -1636,6 +_,15 @@ this.setShoulderEntityRight(oldPlayer.getShoulderEntityRight()); this.setLastDeathLocation(oldPlayer.getLastDeathLocation()); this.waypointIcon().copyFrom(oldPlayer.waypointIcon()); @@ -98,28 +98,28 @@ } private void transferInventoryXpAndScore(final Player oldPlayer) { -@@ -1746,8 +_,9 @@ +@@ -1745,8 +_,9 @@ return (ServerLevel)super.level(); } - public boolean setGameMode(final GameType mode) { + public boolean setGameMode(GameType mode) { - boolean flag = this.isSpectator(); + boolean wasSpectator = this.isSpectator(); + mode = net.minecraftforge.common.ForgeHooks.onChangeGameType(this, this.gameMode.getGameModeForPlayer(), mode); if (!this.gameMode.changeGameModeForPlayer(mode)) { return false; } else { -@@ -1931,6 +_,9 @@ +@@ -1930,6 +_,9 @@ public void setCamera(final @Nullable Entity newCamera) { - Entity entity = this.getCamera(); + Entity oldCamera = this.getCamera(); this.camera = (Entity)(newCamera == null ? this : newCamera); + while (this.camera instanceof net.minecraftforge.entity.PartEntity partEntity) { + this.camera = partEntity.getParent(); // FORGE: fix MC-46486 + } - if (entity != this.camera) { - if (this.camera.level() instanceof ServerLevel serverlevel) { - this.teleportTo(serverlevel, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false); -@@ -1957,7 +_,11 @@ + if (oldCamera != this.camera) { + if (this.camera.level() instanceof ServerLevel level) { + this.teleportTo(level, this.camera.getX(), this.camera.getY(), this.camera.getZ(), Set.of(), this.getYRot(), this.getXRot(), false); +@@ -1956,7 +_,11 @@ } public @Nullable Component getTabListDisplayName() { @@ -132,7 +132,7 @@ } public int getTabListOrder() { -@@ -1991,6 +_,7 @@ +@@ -1990,6 +_,7 @@ } public void setRespawnPosition(final ServerPlayer.@Nullable RespawnConfig respawnConfig, final boolean showMessage) { @@ -140,26 +140,26 @@ if (showMessage && respawnConfig != null && !respawnConfig.isSamePosition(this.respawnConfig)) { this.sendSystemMessage(SPAWN_SET_MESSAGE); } -@@ -2078,6 +_,9 @@ +@@ -2077,6 +_,9 @@ public void drop(final boolean all) { Inventory inventory = this.getInventory(); + ItemStack selected = inventory.getSelectedItem(); + if (selected.isEmpty() || !selected.onDroppedByPlayer(this)) return; + if (isUsingItem() && getUsedItemHand() == InteractionHand.MAIN_HAND && (all || selected.getCount() == 1)) stopUsingItem(); // Forge: fix MC-231097 on the serverside - ItemStack itemstack = inventory.removeFromSelected(all); + ItemStack removed = inventory.removeFromSelected(all); this.containerMenu .findSlot(inventory, inventory.getSelectedSlot()) -@@ -2086,7 +_,7 @@ +@@ -2085,7 +_,7 @@ this.stopUsingItem(); } -- this.drop(itemstack, false, true); -+ net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, itemstack, true); +- this.drop(removed, false, true); ++ net.minecraftforge.common.ForgeHooks.onPlayerTossEvent(this, removed, true); } @Override -@@ -2188,6 +_,75 @@ +@@ -2187,6 +_,75 @@ public @Nullable BlockPos getRaidOmenPosition() { return this.raidOmenPosition; diff --git a/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch b/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch index f8e2ac3e2f..b84852104c 100644 --- a/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ServerPlayerGameMode.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/level/ServerPlayerGameMode.java +++ b/net/minecraft/server/level/ServerPlayerGameMode.java -@@ -151,6 +_,10 @@ +@@ -150,6 +_,10 @@ public void handleBlockBreakAction( final BlockPos pos, final ServerboundPlayerActionPacket.Action action, final Direction direction, final int maxY, final int sequence ) { @@ -11,73 +11,73 @@ if (!this.player.isWithinBlockInteractionRange(pos, 1.0)) { this.debugLogging(pos, false, sequence, "too far"); } else if (pos.getY() > maxY) { -@@ -185,6 +_,7 @@ - float f = 1.0F; - BlockState blockstate = this.level.getBlockState(pos); - if (!blockstate.isAir()) { +@@ -184,6 +_,7 @@ + float progress = 1.0F; + BlockState blockState = this.level.getBlockState(pos); + if (!blockState.isAir()) { + if (!event.getUseBlock().isDenied()) { EnchantmentHelper.onHitBlock( this.level, this.player.getMainHandItem(), -@@ -196,6 +_,7 @@ +@@ -195,6 +_,7 @@ item -> this.player.onEquippedItemBroken(item, EquipmentSlot.MAINHAND) ); - blockstate.attack(this.level, pos, this.player); + blockState.attack(this.level, pos, this.player); + } - f = blockstate.getDestroyProgress(this.player, this.player.level(), pos); + progress = blockState.getDestroyProgress(this.player, this.player.level(), pos); } -@@ -262,7 +_,8 @@ +@@ -261,7 +_,8 @@ public boolean destroyBlock(final BlockPos pos) { - BlockState blockstate1 = this.level.getBlockState(pos); -- if (!this.player.getMainHandItem().canDestroyBlock(blockstate1, this.level, pos, this.player)) { + BlockState state = this.level.getBlockState(pos); +- if (!this.player.getMainHandItem().canDestroyBlock(state, this.level, pos, this.player)) { + int exp = net.minecraftforge.common.ForgeHooks.onBlockBreakEvent(level, gameModeForPlayer, player, pos); + if (exp == -1) { return false; } else { - BlockEntity blockentity = this.level.getBlockEntity(pos); -@@ -270,34 +_,50 @@ + BlockEntity blockEntity = this.level.getBlockEntity(pos); +@@ -269,34 +_,50 @@ if (block instanceof GameMasterBlock && !this.player.canUseGameMasterBlocks()) { - this.level.sendBlockUpdated(pos, blockstate1, blockstate1, 3); + this.level.sendBlockUpdated(pos, state, state, 3); return false; + } else if (player.getMainHandItem().onBlockStartBreak(pos, player)) { + return false; } else if (this.player.blockActionRestricted(this.level, pos, this.gameModeForPlayer)) { return false; } else { -- BlockState blockstate = block.playerWillDestroy(this.level, pos, blockstate1, this.player); -- boolean flag1 = this.level.removeBlock(pos, false); +- BlockState adjustedState = block.playerWillDestroy(this.level, pos, state, this.player); +- boolean changed = this.level.removeBlock(pos, false); - if (SharedConstants.DEBUG_BLOCK_BREAK) { -- LOGGER.info("server broke {} {} -> {}", pos, blockstate, this.level.getBlockState(pos)); +- LOGGER.info("server broke {} {} -> {}", pos, adjustedState, this.level.getBlockState(pos)); - } - -- if (flag1) { -- block.destroy(this.level, pos, blockstate); +- if (changed) { +- block.destroy(this.level, pos, adjustedState); - } - -+ BlockState blockstate = blockstate1; ++ BlockState adjustedState = state; if (this.player.preventsBlockDrops()) { + removeBlock(pos, false); return true; } else { - ItemStack itemstack = this.player.getMainHandItem(); - ItemStack itemstack1 = itemstack.copy(); -- boolean flag = this.player.hasCorrectToolForDrops(blockstate); -+ boolean flag = blockstate.canHarvestBlock(this.level, pos, this.player); // previously player.hasCorrectToolForDrops(blockstate) - itemstack.mineBlock(this.level, blockstate, pos, this.player); + ItemStack itemStack = this.player.getMainHandItem(); + ItemStack destroyedWith = itemStack.copy(); +- boolean canDestroy = this.player.hasCorrectToolForDrops(adjustedState); ++ boolean canDestroy = adjustedState.canHarvestBlock(this.level, pos, this.player); // previously player.hasCorrectToolForDrops(blockstate) + itemStack.mineBlock(this.level, adjustedState, pos, this.player); + -+ if (itemstack.isEmpty() && !itemstack1.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this.player, itemstack1, InteractionHand.MAIN_HAND); ++ if (itemStack.isEmpty() && !destroyedWith.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this.player, destroyedWith, InteractionHand.MAIN_HAND); + } -+ boolean flag1 = removeBlock(pos, flag); ++ boolean changed = removeBlock(pos, canDestroy); + - if (flag1 && flag) { - block.playerDestroy(this.level, this.player, pos, blockstate, blockentity, itemstack1); + if (changed && canDestroy) { + block.playerDestroy(this.level, this.player, pos, adjustedState, blockEntity, destroyedWith); } -+ if (flag && exp > 0) { -+ blockstate1.getBlock().popExperience(level, pos, exp); ++ if (canDestroy && exp > 0) { ++ state.getBlock().popExperience(level, pos, exp); + } + return true; @@ -99,53 +99,53 @@ } public InteractionResult useItem(final ServerPlayer player, final Level level, final ItemStack itemStack, final InteractionHand hand) { -@@ -306,6 +_,8 @@ +@@ -305,6 +_,8 @@ } else if (player.getCooldowns().isOnCooldown(itemStack)) { return InteractionResult.PASS; } else { + InteractionResult cancelResult = net.minecraftforge.common.ForgeHooks.onItemRightClick(player, hand); + if (cancelResult != null) return cancelResult; - int i = itemStack.getCount(); - int j = itemStack.getDamageValue(); - InteractionResult interactionresult = itemStack.use(level, player, hand); -@@ -346,6 +_,11 @@ - if (!blockstate.getBlock().isEnabled(level.enabledFeatures())) { + int oldCount = itemStack.getCount(); + int oldDamage = itemStack.getDamageValue(); + InteractionResult result = itemStack.use(level, player, hand); +@@ -348,6 +_,11 @@ + if (!state.getBlock().isEnabled(level.enabledFeatures())) { return InteractionResult.FAIL; } else if (this.gameModeForPlayer == GameType.SPECTATOR) { + } + -+ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, blockpos, hitResult); ++ var event = new net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock(player, hand, pos, hitResult); + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.RightClickBlock.BUS.post(event)) return event.getCancellationResult(); + if (this.gameModeForPlayer == GameType.SPECTATOR) { - MenuProvider menuprovider = blockstate.getMenuProvider(level, blockpos); - if (menuprovider != null) { - player.openMenu(menuprovider); -@@ -354,10 +_,16 @@ + MenuProvider menuProvider = state.getMenuProvider(level, pos); + if (menuProvider != null) { + player.openMenu(menuProvider); +@@ -356,10 +_,16 @@ return InteractionResult.PASS; } } else { -+ UseOnContext useoncontext = new UseOnContext(player, hand, hitResult); ++ UseOnContext context = new UseOnContext(player, hand, hitResult); + if (!event.getUseItem().isDenied()) { -+ InteractionResult result = itemStack.onItemUseFirst(useoncontext); ++ InteractionResult result = itemStack.onItemUseFirst(context); + if (result != InteractionResult.PASS) return result; + } - boolean flag = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); - boolean flag1 = player.isSecondaryUseActive() && flag; -+ flag1 &= !(player.getMainHandItem().doesSneakBypassUse(level, blockpos, player) && player.getOffhandItem().doesSneakBypassUse(level, blockpos, player)); - ItemStack itemstack = itemStack.copy(); -- if (!flag1) { -+ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !flag1)) { - InteractionResult interactionresult = blockstate.useItemOn(player.getItemInHand(hand), level, player, hand, hitResult); - if (interactionresult.consumesAction()) { - CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(player, blockpos, itemstack); -@@ -373,8 +_,8 @@ + boolean haveSomethingInOurHands = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); + boolean suppressUsingBlock = player.isSecondaryUseActive() && haveSomethingInOurHands; ++ suppressUsingBlock &= !(player.getMainHandItem().doesSneakBypassUse(level, pos, player) && player.getOffhandItem().doesSneakBypassUse(level, pos, player)); + ItemStack usedItemStack = itemStack.copy(); +- if (!suppressUsingBlock) { ++ if (event.getUseBlock().isAllowed() || (!event.getUseBlock().isDenied() && !suppressUsingBlock)) { + InteractionResult itemUse = state.useItemOn(player.getItemInHand(hand), level, player, hand, hitResult); + if (itemUse.consumesAction()) { + CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(player, pos, usedItemStack); +@@ -375,8 +_,8 @@ } } - if (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack)) { -- UseOnContext useoncontext = new UseOnContext(player, hand, hitResult); +- UseOnContext context = new UseOnContext(player, hand, hitResult); + if (event.getUseItem().isAllowed() || (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack))) { + if (event.getUseItem().isDenied()) return InteractionResult.PASS; - InteractionResult interactionresult2; + InteractionResult success; if (player.hasInfiniteMaterials()) { - int i = itemStack.getCount(); + int count = itemStack.getCount(); diff --git a/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch b/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch index 7565a63561..f78bae86a7 100644 --- a/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch +++ b/patches/minecraft/net/minecraft/server/level/ThreadedLevelLightEngine.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/level/ThreadedLevelLightEngine.java +++ b/net/minecraft/server/level/ThreadedLevelLightEngine.java @@ -175,6 +_,7 @@ - }, () -> "lightChunk " + chunkpos + " " + lighted)); + }, () -> "lightChunk " + pos + " " + lighted)); return CompletableFuture.supplyAsync(() -> { centerChunk.setLightCorrect(true); + net.minecraftforge.common.ForgeHooks.fireLightingCalculatedEvent(centerChunk); return centerChunk; - }, r -> this.addTask(chunkpos.x(), chunkpos.z(), ThreadedLevelLightEngine.TaskType.POST_UPDATE, r)); + }, r -> this.addTask(pos.x(), pos.z(), ThreadedLevelLightEngine.TaskType.POST_UPDATE, r)); } diff --git a/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch b/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch index bed5d7c261..13cc4b0557 100644 --- a/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch +++ b/patches/minecraft/net/minecraft/server/level/WorldGenRegion.java.patch @@ -5,6 +5,6 @@ @Override public boolean addFreshEntity(final Entity entity) { + if (entity instanceof net.minecraft.world.entity.Mob mob && mob.isSpawnCancelled()) return false; - int i = SectionPos.blockToSectionCoord(entity.getBlockX()); - int j = SectionPos.blockToSectionCoord(entity.getBlockZ()); - this.getChunk(i, j).addEntity(entity); + int xc = SectionPos.blockToSectionCoord(entity.getBlockX()); + int zc = SectionPos.blockToSectionCoord(entity.getBlockZ()); + this.getChunk(xc, zc).addEntity(entity); diff --git a/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch b/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch index 42fcd20a34..d6585479fe 100644 --- a/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch +++ b/patches/minecraft/net/minecraft/server/network/EventLoopGroupHolder.java.patch @@ -27,24 +27,24 @@ } public EventLoopGroup eventLoopGroup() { -- EventLoopGroup eventloopgroup = this.group; +- EventLoopGroup result = this.group; + return eventLoopGroup(false); + } + + public EventLoopGroup eventLoopGroup(boolean client) { -+ EventLoopGroup eventloopgroup = client ? this.groupClient : this.group; - if (eventloopgroup == null) { ++ EventLoopGroup result = client ? this.groupClient : this.group; + if (result == null) { synchronized (this) { -- eventloopgroup = this.group; -+ eventloopgroup = client ? this.groupClient : this.group; - if (eventloopgroup == null) { -- eventloopgroup = this.createEventLoopGroup(); -- this.group = eventloopgroup; -+ eventloopgroup = this.createEventLoopGroup(client); +- result = this.group; ++ result = client ? this.groupClient : this.group; + if (result == null) { +- result = this.createEventLoopGroup(); +- this.group = result; ++ result = this.createEventLoopGroup(client); + if (client) -+ this.groupClient = eventloopgroup; ++ this.groupClient = result; + else -+ this.group = eventloopgroup; ++ this.group = result; } } } diff --git a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch index 58410340ef..bef37c5114 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java -@@ -47,17 +_,20 @@ +@@ -46,17 +_,20 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final Component DISCONNECT_REASON_INVALID_DATA = Component.translatable("multiplayer.disconnect.invalid_player_data"); private static final Component DISCONNECT_REASON_CONFIGURATION_ERROR = Component.translatable("multiplayer.disconnect.configuration_error"); @@ -21,16 +21,16 @@ } @Override -@@ -81,22 +_,27 @@ +@@ -80,22 +_,27 @@ return this.connection.isConnected(); } - public void startConfiguration() { + public void vanillaStart() { this.send(new ClientboundCustomPayloadPacket(new BrandPayload(this.server.getServerModName()))); - ServerLinks serverlinks = this.server.serverLinks(); - if (!serverlinks.isEmpty()) { - this.send(new ClientboundServerLinksPacket(serverlinks.untrust())); + ServerLinks serverLinks = this.server.serverLinks(); + if (!serverLinks.isEmpty()) { + this.send(new ClientboundServerLinksPacket(serverLinks.untrust())); } + this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); @@ -38,25 +38,25 @@ + + public void startConfiguration() { + net.minecraftforge.event.ForgeEventFactory.gatherLoginConfigTasks(this.connection, this.configurationTasks::add); - LayeredRegistryAccess layeredregistryaccess = this.server.registries(); - List list = this.server + LayeredRegistryAccess registries = this.server.registries(); + List knownPacks = this.server .getResourceManager() .listPacks() .flatMap(packResources -> packResources.location().knownPackInfo().stream()) .toList(); - this.send(new ClientboundUpdateEnabledFeaturesPacket(FeatureFlags.REGISTRY.toNames(this.server.getWorldData().enabledFeatures()))); - this.synchronizeRegistriesTask = new SynchronizeRegistriesTask(list, layeredregistryaccess); + this.synchronizeRegistriesTask = new SynchronizeRegistriesTask(knownPacks, registries); this.configurationTasks.add(this.synchronizeRegistriesTask); + this.configurationTasks.add(new net.minecraftforge.network.config.SimpleConfigurationTask(VANILLA_START, this::vanillaStart)); this.addOptionalTasks(); this.returnToWorld(); } -@@ -212,7 +_,7 @@ - this.currentTask = configurationtask; +@@ -211,7 +_,7 @@ + this.currentTask = task; try { -- configurationtask.start(this::send); -+ configurationtask.start(this.taskContext); - } catch (Exception exception) { - LOGGER.error("Failed to start configuration task {}", configurationtask.type(), exception); +- task.start(this::send); ++ task.start(this.taskContext); + } catch (Exception var3) { + LOGGER.error("Failed to start configuration task {}", task.type(), var3); this.disconnect(DISCONNECT_REASON_CONFIGURATION_ERROR); diff --git a/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch b/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch index fb088035e7..eafdf76953 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerConnectionListener.java.patch @@ -15,23 +15,23 @@ + var fixedAddress = address != null ? address : new java.net.InetSocketAddress(port).getAddress(); + net.minecraftforge.network.DualStackUtils.checkIPv6(fixedAddress); synchronized (this.channels) { - EventLoopGroupHolder eventloopgroupholder = EventLoopGroupHolder.remote(this.server.useNativeTransport()); - this.channels.add(new ServerBootstrap().channel(eventloopgroupholder.serverChannelCls()).childHandler(new ChannelInitializer() { -@@ -64,7 +_,7 @@ - } catch (ChannelException channelexception) { - } - -- ChannelPipeline channelpipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30)); -+ ChannelPipeline channelpipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(READ_TIMEOUT)); - if (ServerConnectionListener.this.server.repliesToStatus()) { - channelpipeline.addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); - } -@@ -76,7 +_,7 @@ - connection.configurePacketHandler(channelpipeline); - connection.setListenerForServerboundHandshake(new ServerHandshakePacketListenerImpl(ServerConnectionListener.this.server, connection)); - } -- }).group(eventloopgroupholder.eventLoopGroup()).localAddress(address, port).bind().syncUninterruptibly()); -+ }).group(eventloopgroupholder.eventLoopGroup()).localAddress(fixedAddress, port).bind().syncUninterruptibly()); - } - } + EventLoopGroupHolder eventLoopGroupHolder = EventLoopGroupHolder.remote(this.server.useNativeTransport()); + this.channels +@@ -69,7 +_,7 @@ + } catch (ChannelException var5) { + } +- ChannelPipeline pipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(30)); ++ ChannelPipeline pipeline = channel.pipeline().addLast("timeout", new ReadTimeoutHandler(READ_TIMEOUT)); + if (ServerConnectionListener.this.server.repliesToStatus()) { + pipeline.addLast("legacy_query", new LegacyQueryHandler(ServerConnectionListener.this.getServer())); + } +@@ -88,7 +_,7 @@ + } + ) + .group(eventLoopGroupHolder.eventLoopGroup()) +- .localAddress(address, port) ++ .localAddress(fixedAddress, port) + .bind() + .syncUninterruptibly() + ); diff --git a/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch index 433ba9e7a4..6815b8aa2b 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerGamePacketListenerImpl.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/server/network/ServerGamePacketListenerImpl.java +++ b/net/minecraft/server/network/ServerGamePacketListenerImpl.java -@@ -1279,9 +_,10 @@ +@@ -1286,9 +_,10 @@ } case SWAP_ITEM_WITH_OFFHAND: if (!this.player.isSpectator()) { -- ItemStack itemstack1 = this.player.getItemInHand(InteractionHand.OFF_HAND); +- ItemStack swap = this.player.getItemInHand(InteractionHand.OFF_HAND); - this.player.setItemInHand(InteractionHand.OFF_HAND, this.player.getItemInHand(InteractionHand.MAIN_HAND)); -- this.player.setItemInHand(InteractionHand.MAIN_HAND, itemstack1); +- this.player.setItemInHand(InteractionHand.MAIN_HAND, swap); + var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this.player); + if (event == null) return; + this.player.setItemInHand(InteractionHand.OFF_HAND, event.getItemSwappedToOffHand()); @@ -14,18 +14,18 @@ this.player.stopUsingItem(); } -@@ -1503,8 +_,9 @@ +@@ -1504,8 +_,9 @@ } - CompletableFuture completablefuture = this.filterTextPacket(playerchatmessage.signedContent()); -- Component component = this.server.getChatDecorator().decorate(this.player, playerchatmessage.decoratedContent()); -+ Component component = net.minecraftforge.common.ForgeHooks.onServerChatSubmittedEvent(this.player, playerchatmessage.decoratedContent()); - this.chatMessageChain.append(completablefuture, filtered -> { -+ if (component == null) return; - PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(component).filter(filtered.mask()); - this.broadcastChatMessage(playerchatmessage1); + CompletableFuture filteredFuture = this.filterTextPacket(signedMessage.signedContent()); +- Component decorated = this.server.getChatDecorator().decorate(this.player, signedMessage.decoratedContent()); ++ Component decorated = net.minecraftforge.common.ForgeHooks.onServerChatSubmittedEvent(this.player, signedMessage.decoratedContent()); + this.chatMessageChain.append(filteredFuture, filtered -> { ++ if (decorated == null) return; + PlayerChatMessage filteredMessage = signedMessage.withUnsignedContent(decorated).filter(filtered.mask()); + this.broadcastChatMessage(filteredMessage); }); -@@ -2186,6 +_,7 @@ +@@ -2175,6 +_,7 @@ @Override public void handleCustomPayload(final ServerboundCustomPayloadPacket packet) { diff --git a/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch index e86aef9472..fc5b14c68f 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerHandshakePacketListenerImpl.java.patch @@ -9,11 +9,11 @@ case LOGIN: this.beginLogin(packet, false); @@ -32,7 +_,7 @@ - ServerStatus serverstatus = this.server.getStatus(); + ServerStatus status = this.server.getStatus(); this.connection.setupOutboundProtocol(StatusProtocols.CLIENTBOUND); - if (this.server.repliesToStatus() && serverstatus != null) { -- this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(serverstatus, this.connection)); -+ this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(serverstatus, this.connection, this.server.getStatusJson())); + if (this.server.repliesToStatus() && status != null) { +- this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(status, this.connection)); ++ this.connection.setupInboundProtocol(StatusProtocols.SERVERBOUND, new ServerStatusPacketListenerImpl(status, this.connection, this.server.getStatusJson())); } else { this.connection.disconnect(IGNORE_STATUS_REASON); } diff --git a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch index 1ae4dbad0f..a789944c91 100644 --- a/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch +++ b/patches/minecraft/net/minecraft/server/network/ServerLoginPacketListenerImpl.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/server/network/ServerLoginPacketListenerImpl.java +++ b/net/minecraft/server/network/ServerLoginPacketListenerImpl.java @@ -186,7 +_,7 @@ - throw new IllegalStateException("Protocol error", cryptexception); + throw new IllegalStateException("Protocol error", var7); } - Thread thread = new Thread("User Authenticator #" + UNIQUE_THREAD_ID.incrementAndGet()) { @@ -17,7 +17,7 @@ this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY); } -@@ -260,6 +_,11 @@ +@@ -258,6 +_,11 @@ @Override public void handleCookieResponse(final ServerboundCookieResponsePacket packet) { this.disconnect(ServerCommonPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY); diff --git a/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch b/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch index 9257f4abc3..3df7bd84ce 100644 --- a/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch +++ b/patches/minecraft/net/minecraft/server/network/config/PrepareSpawnTask.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/server/network/config/PrepareSpawnTask.java +++ b/net/minecraft/server/network/config/PrepareSpawnTask.java -@@ -192,6 +_,7 @@ +@@ -187,6 +_,7 @@ .loadPlayerData(PrepareSpawnTask.this.nameAndId) - .map(tag -> TagValueInput.create(problemreporter$scopedcollector, PrepareSpawnTask.this.server.registryAccess(), tag)); - optional.ifPresent(serverplayer::load); -+ optional.ifPresent(v -> net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(serverplayer, PrepareSpawnTask.this.server.getPlayerList().getPlayerIo().getPlayerDataFolder(), PrepareSpawnTask.this.nameAndId.id().toString())); - serverplayer.snapTo(this.spawnPosition, this.spawnAngle.x, this.spawnAngle.y); - PrepareSpawnTask.this.server.getPlayerList().placeNewPlayer(connection, serverplayer, cookie); - optional.ifPresent(tag -> { + .map(tag -> TagValueInput.create(reporter, PrepareSpawnTask.this.server.registryAccess(), tag)); + input.ifPresent(player::load); ++ input.ifPresent(v -> net.minecraftforge.event.ForgeEventFactory.firePlayerLoadingEvent(player, PrepareSpawnTask.this.server.getPlayerList().getPlayerIo().getPlayerDataFolder(), PrepareSpawnTask.this.nameAndId.id().toString())); + player.snapTo(this.spawnPosition, this.spawnAngle.x, this.spawnAngle.y); + PrepareSpawnTask.this.server.getPlayerList().placeNewPlayer(connection, player, cookie); + input.ifPresent(tag -> { diff --git a/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch b/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch index da6e2cb239..6b77a59f69 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/Pack.java.patch @@ -17,14 +17,14 @@ public static Pack.@Nullable Metadata readPackMetadata( @@ -66,7 +_,7 @@ - PackCompatibility packcompatibility = PackCompatibility.forVersion(packmetadatasection.supportedFormats(), currentPackVersion); - OverlayMetadataSection overlaymetadatasection = packresources.getMetadataSection(OverlayMetadataSection.forPackType(type)); - List list = overlaymetadatasection != null ? overlaymetadatasection.overlaysForVersion(currentPackVersion) : List.of(); -- pack$metadata = new Pack.Metadata(packmetadatasection.description(), packcompatibility, featureflagset, list); -+ pack$metadata = new Pack.Metadata(packmetadatasection.description(), packcompatibility, featureflagset, list, packresources.isHidden()); + PackCompatibility packCompatibility = PackCompatibility.forVersion(meta.supportedFormats(), currentPackVersion); + OverlayMetadataSection overlays = pack.getMetadataSection(OverlayMetadataSection.forPackType(type)); + List overlaySet = overlays != null ? overlays.overlaysForVersion(currentPackVersion) : List.of(); +- var11 = new Pack.Metadata(meta.description(), packCompatibility, requiredFlags, overlaySet); ++ var11 = new Pack.Metadata(meta.description(), packCompatibility, requiredFlags, overlaySet, pack.isHidden()); } - return pack$metadata; + return var11; @@ -128,6 +_,10 @@ return this.location.source(); } diff --git a/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch b/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch index 6b9c8166a6..5f54eb5932 100644 --- a/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/repository/PackDetector.java.patch @@ -8,20 +8,20 @@ + } + @Nullable + public T detectPackResources(Path content, List issues, boolean requireMeta) throws IOException { - Path path = content; + Path targetContext = content; - BasicFileAttributes basicfileattributes; + BasicFileAttributes attributes; @@ -43,10 +_,11 @@ if (!issues.isEmpty()) { return null; } else { -- return !Files.isRegularFile(path.resolve("pack.mcmeta")) ? null : this.createDirectoryPack(path); -+ return !Files.isRegularFile(path.resolve("pack.mcmeta")) && requireMeta ? null : this.createDirectoryPack(path); +- return !Files.isRegularFile(targetContext.resolve("pack.mcmeta")) ? null : this.createDirectoryPack(targetContext); ++ return !Files.isRegularFile(targetContext.resolve("pack.mcmeta")) && requireMeta ? null : this.createDirectoryPack(targetContext); } } else { -- return basicfileattributes.isRegularFile() && path.getFileName().toString().endsWith(".zip") ? this.createZipPack(path) : null; -+ var name = path.getFileName().toString(); -+ return basicfileattributes.isRegularFile() && (name.endsWith(".zip") || name.endsWith(".jar")) ? this.createZipPack(path) : null; +- return attributes.isRegularFile() && targetContext.getFileName().toString().endsWith(".zip") ? this.createZipPack(targetContext) : null; ++ var name = targetContext.getFileName().toString(); ++ return attributes.isRegularFile() && (name.endsWith(".zip") || name.endsWith(".jar")) ? this.createZipPack(targetContext) : null; } } diff --git a/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch b/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch index 14fa10c6d6..a807929241 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/FallbackResourceManager.java.patch @@ -3,21 +3,21 @@ @@ -103,8 +_,11 @@ for (int i = this.fallbacks.size() - 1; i >= 0; i--) { - FallbackResourceManager.PackEntry fallbackresourcemanager$packentry = this.fallbacks.get(i); -- PackResources packresources = fallbackresourcemanager$packentry.resources; -- if (packresources != null) { -+ PackResources pack = fallbackresourcemanager$packentry.resources; + FallbackResourceManager.PackEntry entry = this.fallbacks.get(i); +- PackResources fileSource = entry.resources; +- if (fileSource != null) { ++ PackResources pack = entry.resources; + if (pack != null) { + var children = pack.getChildren(); + var packs = children == null ? List.of(pack) : children; -+ for (final PackResources packresources : packs) { - IoSupplier iosupplier = packresources.getResource(this.type, location); - if (iosupplier != null) { - IoSupplier iosupplier1; ++ for (final PackResources fileSource : packs) { + IoSupplier resource = fileSource.getResource(this.type, location); + if (resource != null) { + IoSupplier metadataGetter; @@ -118,6 +_,7 @@ } - list.add(new Resource(packresources, iosupplier, iosupplier1)); + result.add(new Resource(fileSource, resource, metadataGetter)); + } } } diff --git a/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch b/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch index 4454378c2a..89c04a4f80 100644 --- a/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch +++ b/patches/minecraft/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java +++ b/net/minecraft/server/packs/resources/SimpleJsonResourceReloadListener.java -@@ -33,6 +_,10 @@ +@@ -32,6 +_,10 @@ this(registries.createSerializationContext(JsonOps.INSTANCE), codec, FileToIdConverter.registry(registryKey)); } @@ -11,20 +11,20 @@ protected SimpleJsonResourceReloadListener(final Codec codec, final FileToIdConverter lister) { this(JsonOps.INSTANCE, codec, lister); } -@@ -67,7 +_,15 @@ - Identifier identifier1 = lister.fileToId(identifier); +@@ -66,7 +_,15 @@ + Identifier id = lister.fileToId(location); try (Reader reader = entry.getValue().openAsReader()) { - codec.parse(ops, StrictJsonParser.parse(reader)).ifSuccess(parsed -> { + var json = StrictJsonParser.parse(reader); + json = net.minecraftforge.common.ForgeHooks.readConditional(ops, json); + if (json == null) { -+ LOGGER.debug("Skipping loading {} as its conditions were not met", identifier); ++ LOGGER.debug("Skipping loading {} as its conditions were not met", location); + continue; + } + codec.parse(ops, json).ifSuccess(parsed -> { -+ parsed = net.minecraftforge.common.ForgeHooks.onJsonDataParsed(codec, identifier1, parsed); ++ parsed = net.minecraftforge.common.ForgeHooks.onJsonDataParsed(codec, location, parsed); + if (parsed == null) return; - if (result.putIfAbsent(identifier1, (T)parsed) != null) { - throw new IllegalStateException("Duplicate data file ignored with ID " + identifier1); + if (result.putIfAbsent(id, (T)parsed) != null) { + throw new IllegalStateException("Duplicate data file ignored with ID " + id); } diff --git a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch index 22610a76a5..b205cfe28f 100644 --- a/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch +++ b/patches/minecraft/net/minecraft/server/players/PlayerList.java.patch @@ -8,46 +8,46 @@ public PlayerList( final MinecraftServer server, -@@ -184,6 +_,7 @@ - servergamepacketlistenerimpl.send(new ClientboundPlayerAbilitiesPacket(player.getAbilities())); - servergamepacketlistenerimpl.send(new ClientboundSetHeldSlotPacket(player.getInventory().getSelectedSlot())); - RecipeManager recipemanager = this.server.getRecipeManager(); +@@ -189,6 +_,7 @@ + playerConnection.send(new ClientboundPlayerAbilitiesPacket(player.getAbilities())); + playerConnection.send(new ClientboundSetHeldSlotPacket(player.getInventory().getSelectedSlot())); + RecipeManager recipeManager = this.server.getRecipeManager(); + net.minecraftforge.event.OnDatapackSyncEvent.BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, player)); - servergamepacketlistenerimpl.send( - new ClientboundUpdateRecipesPacket(recipemanager.getSynchronizedItemProperties(), recipemanager.getSynchronizedStonecutterRecipes()) + playerConnection.send( + new ClientboundUpdateRecipesPacket(recipeManager.getSynchronizedItemProperties(), recipeManager.getSynchronizedStonecutterRecipes()) ); -@@ -217,6 +_,7 @@ +@@ -222,6 +_,7 @@ player.initInventoryMenu(); this.server.notificationManager().playerJoined(player); - servergamepacketlistenerimpl.resumeFlushing(); + playerConnection.resumeFlushing(); + net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedIn(player); } protected void updateEntireScoreboard(final ServerScoreboard scoreboard, final ServerPlayer player) { -@@ -290,6 +_,7 @@ +@@ -295,6 +_,7 @@ } protected void save(final ServerPlayer player) { + if (player.connection == null) return; // Not sure if still needed -Paint_Ninja this.playerIo.save(player); - ServerStatsCounter serverstatscounter = this.stats.get(player.getUUID()); - if (serverstatscounter != null) { -@@ -303,6 +_,7 @@ + ServerStatsCounter stats = this.stats.get(player.getUUID()); + if (stats != null) { +@@ -308,6 +_,7 @@ } public void remove(final ServerPlayer player) { + net.minecraftforge.event.ForgeEventFactory.firePlayerLoggedOut(player); - ServerLevel serverlevel = player.level(); + ServerLevel level = player.level(); player.awardStat(Stats.LEAVE_GAME); this.save(player); @@ -429,6 +_,7 @@ - this.playersByUUID.put(serverplayer.getUUID(), serverplayer); - serverplayer.initInventoryMenu(); - serverplayer.setHealth(serverplayer.getHealth()); -+ net.minecraftforge.event.ForgeEventFactory.firePlayerRespawnEvent(serverplayer, keepAllPlayerData); - ServerPlayer.RespawnConfig serverplayer$respawnconfig = serverplayer.getRespawnConfig(); - if (!keepAllPlayerData && serverplayer$respawnconfig != null) { - LevelData.RespawnData leveldata$respawndata = serverplayer$respawnconfig.respawnData(); + this.playersByUUID.put(player.getUUID(), player); + player.initInventoryMenu(); + player.setHealth(player.getHealth()); ++ net.minecraftforge.event.ForgeEventFactory.firePlayerRespawnEvent(player, keepAllPlayerData); + ServerPlayer.RespawnConfig respawnConfig = player.getRespawnConfig(); + if (!keepAllPlayerData && respawnConfig != null) { + LevelData.RespawnData respawnData = respawnConfig.respawnData(); @@ -542,6 +_,7 @@ } @@ -62,8 +62,8 @@ public void deop(final NameAndId nameAndId) { + if (net.minecraftforge.event.ForgeEventFactory.onPermissionChanged(nameAndId, null, this)) return; if (this.ops.remove(nameAndId)) { - ServerPlayer serverplayer = this.getPlayer(nameAndId.id()); - if (serverplayer != null) { + ServerPlayer player = this.getPlayer(nameAndId.id()); + if (player != null) { @@ -824,7 +_,7 @@ } @@ -74,13 +74,13 @@ public @Nullable ServerPlayer getPlayer(final UUID uuid) { @@ -850,6 +_,7 @@ - playeradvancements.reload(this.server.getAdvancements()); + advancements.reload(this.server.getAdvancements()); } + net.minecraftforge.event.OnDatapackSyncEvent.BUS.post(new net.minecraftforge.event.OnDatapackSyncEvent(this, null)); this.broadcastAll(new ClientboundUpdateTagsPacket(TagNetworkSerialization.serializeTagsToNetwork(this.registries))); - RecipeManager recipemanager = this.server.getRecipeManager(); - ClientboundUpdateRecipesPacket clientboundupdaterecipespacket = new ClientboundUpdateRecipesPacket( + RecipeManager recipeManager = this.server.getRecipeManager(); + ClientboundUpdateRecipesPacket recipes = new ClientboundUpdateRecipesPacket( @@ -864,5 +_,9 @@ public boolean isAllowCommandsForAllPlayers() { diff --git a/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch b/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch index f71c9d0feb..04cc437302 100644 --- a/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch +++ b/patches/minecraft/net/minecraft/server/rcon/thread/RconClient.java.patch @@ -4,14 +4,14 @@ } private void sendCmdResponse(final int requestid, String response) throws IOException { -- int i = response.length(); +- int len = response.length(); - - do { -- int j = 4096 <= i ? 4096 : i; -- this.send(requestid, 0, response.substring(0, j)); -- response = response.substring(j); -- i = response.length(); -- } while (0 != i); +- int dataLen = 4096 <= len ? 4096 : len; +- this.send(requestid, 0, response.substring(0, dataLen)); +- response = response.substring(dataLen); +- len = response.length(); +- } while (0 != len); + // Forge: Actually convert to UTF8 and process bytes accordingly. Why do we do this? UTF8 should be single byte per character + byte[] data = response.getBytes(StandardCharsets.UTF_8); + for (int x = 0; x < data.length; x += 4096) { diff --git a/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch b/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch index f77d3f93c9..47a0e6e6d6 100644 --- a/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch +++ b/patches/minecraft/net/minecraft/stats/RecipeBookSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/stats/RecipeBookSettings.java +++ b/net/minecraft/stats/RecipeBookSettings.java -@@ -12,6 +_,7 @@ +@@ -11,6 +_,7 @@ import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.inventory.RecipeBookType; @@ -8,7 +8,7 @@ public final class RecipeBookSettings { public static final StreamCodec STREAM_CODEC = StreamCodec.composite( RecipeBookSettings.TypeSettings.STREAM_CODEC, -@@ -150,5 +_,13 @@ +@@ -149,5 +_,13 @@ .apply(i, RecipeBookSettings.TypeSettings::new) ); } diff --git a/patches/minecraft/net/minecraft/tags/TagEntry.java.patch b/patches/minecraft/net/minecraft/tags/TagEntry.java.patch index e99dec29b2..a329bd19e0 100644 --- a/patches/minecraft/net/minecraft/tags/TagEntry.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagEntry.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/tags/TagEntry.java +++ b/net/minecraft/tags/TagEntry.java -@@ -108,6 +_,18 @@ - return stringbuilder.toString(); +@@ -107,6 +_,18 @@ + return result.toString(); } + public Identifier getId() { diff --git a/patches/minecraft/net/minecraft/tags/TagFile.java.patch b/patches/minecraft/net/minecraft/tags/TagFile.java.patch index c433a0085c..1e7f9fbbd6 100644 --- a/patches/minecraft/net/minecraft/tags/TagFile.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagFile.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/tags/TagFile.java +++ b/net/minecraft/tags/TagFile.java -@@ -5,11 +_,16 @@ - import com.mojang.serialization.codecs.RecordCodecBuilder.Instance; +@@ -4,11 +_,16 @@ + import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.List; -public record TagFile(List entries, boolean replace) { diff --git a/patches/minecraft/net/minecraft/tags/TagLoader.java.patch b/patches/minecraft/net/minecraft/tags/TagLoader.java.patch index 1335999ca2..ff4b7cb312 100644 --- a/patches/minecraft/net/minecraft/tags/TagLoader.java.patch +++ b/patches/minecraft/net/minecraft/tags/TagLoader.java.patch @@ -2,30 +2,30 @@ +++ b/net/minecraft/tags/TagLoader.java @@ -64,6 +_,7 @@ - String s = resource.sourcePackId(); - tagfile.entries().forEach(ex -> list.add(new TagLoader.EntryWithSource(ex, s))); -+ tagfile.remove().forEach(e -> list.add(new TagLoader.EntryWithSource(e, s, true))); - } catch (Exception exception) { - LOGGER.error("Couldn't read tag list {} from {} in data pack {}", identifier1, identifier, resource.sourcePackId(), exception); + String sourceId = resource.sourcePackId(); + parsedContents.entries().forEach(ex -> tagContents.add(new TagLoader.EntryWithSource(ex, sourceId))); ++ parsedContents.remove().forEach(e -> tagContents.add(new TagLoader.EntryWithSource(e, sourceId, true))); + } catch (Exception var17) { + LOGGER.error("Couldn't read tag list {} from {} in data pack {}", id, location, resource.sourcePackId(), var17); } @@ -74,16 +_,17 @@ } private Either, List> tryBuildTag(final TagEntry.Lookup lookup, final List entries) { -- SequencedSet sequencedset = new LinkedHashSet<>(); +- SequencedSet values = new LinkedHashSet<>(); + var builder = new java.util.LinkedHashSet(); // Order is important, as ImmutableSet is ordered and some people rely on that. https://github.com/MinecraftForge/MinecraftForge/issues/9774 - List list = new ArrayList<>(); + List missingElements = new ArrayList<>(); - for (TagLoader.EntryWithSource tagloader$entrywithsource : entries) { -- if (!tagloader$entrywithsource.entry().build(lookup, sequencedset::add)) { -+ if (!tagloader$entrywithsource.entry().build(lookup, tagloader$entrywithsource.remove() ? builder::remove : builder::add)) { -+ if (!tagloader$entrywithsource.remove()) // Treat all removals as optional at runtime. If it was missing, then it could of never been added. - list.add(tagloader$entrywithsource); + for (TagLoader.EntryWithSource entry : entries) { +- if (!entry.entry().build(lookup, values::add)) { ++ if (!entry.entry().build(lookup, entry.remove() ? builder::remove : builder::add)) { ++ if (!entry.remove()) // Treat all removals as optional at runtime. If it was missing, then it could of never been added. + missingElements.add(entry); } } -- return list.isEmpty() ? Either.right(List.copyOf(sequencedset)) : Either.left(list); -+ return list.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(list); +- return missingElements.isEmpty() ? Either.right(List.copyOf(values)) : Either.left(missingElements); ++ return missingElements.isEmpty() ? Either.right(List.copyOf(builder)) : Either.left(missingElements); } public Map> build(final Map> builders) { @@ -37,7 +37,7 @@ + missing.stream().map(Objects::toString).collect(Collectors.joining(", \n\t")) ) ) - .ifRight(tag -> map.put(id, (List)tag)) + .ifRight(tag -> newTags.put(id, (List)tag)) @@ -192,7 +_,11 @@ } } diff --git a/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch b/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch index cd4174cc55..f55901cfa1 100644 --- a/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch +++ b/patches/minecraft/net/minecraft/util/SpawnUtil.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/util/SpawnUtil.java +++ b/net/minecraft/util/SpawnUtil.java -@@ -46,7 +_,7 @@ - )) { - T t = (T)entityType.create(level, null, blockpos$mutableblockpos, spawnReason, false, false); - if (t != null) { -- if (t.checkSpawnRules(level, spawnReason) && t.checkSpawnObstruction(level)) { -+ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(t, level, spawnReason)) { - level.addFreshEntityWithPassengers(t); - t.playAmbientSound(); - return Optional.of(t); +@@ -39,7 +_,7 @@ + && (!checkCollisions || level.noCollision(entityType.getSpawnAABB(searchPos.getX() + 0.5, searchPos.getY(), searchPos.getZ() + 0.5)))) { + T mob = (T)entityType.create(level, null, searchPos, spawnReason, false, false); + if (mob != null) { +- if (mob.checkSpawnRules(level, spawnReason) && mob.checkSpawnObstruction(level)) { ++ if (net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(mob, level, spawnReason)) { + level.addFreshEntityWithPassengers(mob); + mob.playAmbientSound(); + return Optional.of(mob); diff --git a/patches/minecraft/net/minecraft/util/Util.java.patch b/patches/minecraft/net/minecraft/util/Util.java.patch index 4c71772978..f177964579 100644 --- a/patches/minecraft/net/minecraft/util/Util.java.patch +++ b/patches/minecraft/net/minecraft/util/Util.java.patch @@ -3,9 +3,9 @@ @@ -272,7 +_,7 @@ .getSchema(DataFixUtils.makeKey(SharedConstants.getCurrentVersion().dataVersion().version())) .getChoiceType(reference, name); - } catch (IllegalArgumentException illegalargumentexception) { + } catch (IllegalArgumentException var4) { - LOGGER.error("No data fixer registered for {}", name); + LOGGER.debug("No data fixer registered for {}", name); if (SharedConstants.IS_RUNNING_IN_IDE) { - throw illegalargumentexception; + throw var4; } diff --git a/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch index fef9c41c15..1f0b8b3c00 100644 --- a/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch +++ b/patches/minecraft/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java +++ b/net/minecraft/util/datafix/fixes/StructuresBecomeConfiguredFix.java @@ -178,7 +_,16 @@ - String s = dynamicKey.asString("UNKNOWN").toLowerCase(Locale.ROOT); - StructuresBecomeConfiguredFix.Conversion structuresbecomeconfiguredfix$conversion = CONVERSION_MAP.get(s); - if (structuresbecomeconfiguredfix$conversion == null) { + String key = dynamicKey.asString("UNKNOWN").toLowerCase(Locale.ROOT); + StructuresBecomeConfiguredFix.Conversion conversion = CONVERSION_MAP.get(key); + if (conversion == null) { - return null; + // Forge: hook for mods to register conversions through RegisterStructureConversionsEvent -+ structuresbecomeconfiguredfix$conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(s); ++ conversion = net.minecraftforge.common.ForgeHooks.getStructureConversion(key); + } -+ if (structuresbecomeconfiguredfix$conversion == null) { -+ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(s)) { ++ if (conversion == null) { ++ if (net.minecraftforge.common.ForgeHooks.checkStructureNamespace(key)) { + // Forge: pass-through structure IDs which have a non-"minecraft" namespace -+ return chunk.createString(s); ++ return chunk.createString(key); + } + // Forge: Pass-through with "unknown." prefix, so deserializer logs and ignores rather than fixer throwing an exception and dropping chunk data -+ return chunk.createString("unknown." + s); ++ return chunk.createString("unknown." + key); } else { - String s1 = structuresbecomeconfiguredfix$conversion.fallback; - if (!structuresbecomeconfiguredfix$conversion.biomeMapping().isEmpty()) { + String resultingId = conversion.fallback; + if (!conversion.biomeMapping().isEmpty()) { diff --git a/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch b/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch index a5b6de6ba7..e9bfd02c48 100644 --- a/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch +++ b/patches/minecraft/net/minecraft/util/random/WeightedList.java.patch @@ -9,8 +9,8 @@ private static final int FLAT_THRESHOLD = 64; private final int totalWeight; private final List> items; -@@ -145,7 +_,7 @@ - return 31 * i + this.items.hashCode(); +@@ -143,7 +_,7 @@ + return 31 * result + this.items.hashCode(); } - public static class Builder { diff --git a/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch b/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch index ecf700f126..1295489d46 100644 --- a/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch +++ b/patches/minecraft/net/minecraft/world/clock/ServerClockManager.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/clock/ServerClockManager.java +++ b/net/minecraft/world/clock/ServerClockManager.java @@ -97,6 +_,12 @@ - return mutableboolean.booleanValue(); + return set.booleanValue(); } + public long getTimeMarker(final Holder clock, final ResourceKey timeMarkerId) { diff --git a/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch b/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch index c1d201134c..44c3932444 100644 --- a/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch +++ b/patches/minecraft/net/minecraft/world/effect/MobEffect.java.patch @@ -11,8 +11,8 @@ public static final StreamCodec> STREAM_CODEC = ByteBufCodecs.holderRegistry(Registries.MOB_EFFECT); private static final int AMBIENT_ALPHA = Mth.floor(38.25F); @@ -58,12 +_,14 @@ - int i = effectInstance.isAmbient() ? AMBIENT_ALPHA : 255; - return ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ARGB.color(i, color)); + int alpha = effectInstance.isAmbient() ? AMBIENT_ALPHA : 255; + return ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ARGB.color(alpha, color)); }; + initClient(); } diff --git a/patches/minecraft/net/minecraft/world/entity/Entity.java.patch b/patches/minecraft/net/minecraft/world/entity/Entity.java.patch index 1fdc617ab7..469814262e 100644 --- a/patches/minecraft/net/minecraft/world/entity/Entity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Entity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/Entity.java +++ b/net/minecraft/world/entity/Entity.java -@@ -160,7 +_,9 @@ +@@ -159,7 +_,9 @@ import org.slf4j.Logger; public abstract class Entity @@ -10,7 +10,7 @@ EntityAccess, ScoreHolder, SyncedDataHolder, -@@ -206,6 +_,7 @@ +@@ -205,6 +_,7 @@ private static final int MAX_BLOCK_ITERATIONS_ALONG_TRAVEL_PER_TICK = 16; private static final double MAX_MOVEMENT_RESETTING_TRACE_DISTANCE = 8.0; private static double viewScale = 1.0; @@ -18,8 +18,8 @@ private final EntityType type; private boolean requiresPrecisePosition; private int id = ENTITY_COUNTER.incrementAndGet(); -@@ -321,6 +_,8 @@ - this.entityData = synchedentitydata$builder.build(); +@@ -320,6 +_,8 @@ + this.entityData = entityDataBuilder.build(); this.setPos(0.0, 0.0, 0.0); this.eyeHeight = this.dimensions.eyeHeight(); + net.minecraftforge.event.ForgeEventFactory.onEntityConstructing(this); @@ -27,7 +27,7 @@ } public boolean isColliding(final BlockPos pos, final BlockState state) { -@@ -424,6 +_,7 @@ +@@ -423,6 +_,7 @@ public void remove(final Entity.RemovalReason reason) { this.setRemoved(reason); @@ -35,7 +35,7 @@ } public void onClientRemoval() { -@@ -543,7 +_,7 @@ +@@ -542,7 +_,7 @@ } if (this.isInLava()) { @@ -44,44 +44,44 @@ } this.checkBelowWorld(); -@@ -999,9 +_,7 @@ - return blockpos; +@@ -1000,9 +_,7 @@ + return getOnPos; } else { - BlockState blockstate = this.level().getBlockState(blockpos); -- return (!(offset <= 0.5) || !blockstate.is(BlockTags.FENCES)) -- && !blockstate.is(BlockTags.WALLS) -- && !(blockstate.getBlock() instanceof FenceGateBlock) -+ return (!((double)offset <= 0.5) || !blockstate.collisionExtendsVertically(this.level(), blockpos, this)) - ? blockpos.atY(Mth.floor(this.position.y - offset)) - : blockpos; + BlockState belowState = this.level().getBlockState(getOnPos); +- return (!(offset <= 0.5) || !belowState.is(BlockTags.FENCES)) +- && !belowState.is(BlockTags.WALLS) +- && !(belowState.getBlock() instanceof FenceGateBlock) ++ return (!((double)offset <= 0.5) || !belowState.collisionExtendsVertically(this.level(), getOnPos, this)) + ? getOnPos.atY(Mth.floor(this.position.y - offset)) + : getOnPos; } -@@ -1356,19 +_,19 @@ - return !blockstate.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? affectingPos : blockpos; +@@ -1363,19 +_,19 @@ + return !aboveState.is(BlockTags.INSIDE_STEP_SOUND_BLOCKS) && !aboveState.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS) ? affectingPos : abovePos; } - protected void playCombinationStepSounds(final BlockState primaryStepSound, final BlockState secondaryStepSound) { -- SoundType soundtype = primaryStepSound.getSoundType(); +- SoundType primaryStepSoundType = primaryStepSound.getSoundType(); + protected void playCombinationStepSounds(final BlockState primaryStepSound, final BlockState secondaryStepSound, final BlockPos primaryPos, final BlockPos secondaryPos) { -+ SoundType soundtype = primaryStepSound.getSoundType(this.level(), primaryPos, this); - this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); ++ SoundType primaryStepSoundType = primaryStepSound.getSoundType(this.level(), primaryPos, this); + this.playSound(primaryStepSoundType.getStepSound(), primaryStepSoundType.getVolume() * 0.15F, primaryStepSoundType.getPitch()); - this.playMuffledStepSound(secondaryStepSound); + this.playMuffledStepSound(secondaryStepSound, secondaryPos); } - protected void playMuffledStepSound(final BlockState blockState) { -- SoundType soundtype = blockState.getSoundType(); +- SoundType secondaryStepSoundType = blockState.getSoundType(); + protected void playMuffledStepSound(final BlockState blockState, final BlockPos pos) { -+ SoundType soundtype = blockState.getSoundType(this.level(), pos, this); - this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.05F, soundtype.getPitch() * 0.8F); ++ SoundType secondaryStepSoundType = blockState.getSoundType(this.level(), pos, this); + this.playSound(secondaryStepSoundType.getStepSound(), secondaryStepSoundType.getVolume() * 0.05F, secondaryStepSoundType.getPitch() * 0.8F); } protected void playStepSound(final BlockPos pos, final BlockState blockState) { -- SoundType soundtype = blockState.getSoundType(); -+ SoundType soundtype = blockState.getSoundType(this.level(), pos, this); - this.playSound(soundtype.getStepSound(), soundtype.getVolume() * 0.15F, soundtype.getPitch()); +- SoundType soundType = blockState.getSoundType(); ++ SoundType soundType = blockState.getSoundType(this.level(), pos, this); + this.playSound(soundType.getStepSound(), soundType.getVolume() * 0.15F, soundType.getPitch()); } -@@ -1503,6 +_,10 @@ +@@ -1510,6 +_,10 @@ return this.wasTouchingWater; } @@ -90,9 +90,9 @@ + } + boolean isInRain() { - BlockPos blockpos = this.blockPosition(); - return this.level().isRainingAt(blockpos) -@@ -1541,10 +_,10 @@ + BlockPos pos = this.blockPosition(); + return this.level().isRainingAt(pos) || this.level().isRainingAt(BlockPos.containing(pos.getX(), this.getBoundingBox().maxY, pos.getZ())); +@@ -1547,10 +_,10 @@ public void updateSwimming() { if (this.isSwimming()) { @@ -105,25 +105,25 @@ ); } } -@@ -1561,16 +_,7 @@ +@@ -1567,16 +_,7 @@ } - this.wasTouchingWater = flag; + this.wasTouchingWater = inWater; - if (this.isPushedByFluid()) { -- if (flag) { +- if (inWater) { - this.fluidInteraction.applyCurrentTo(FluidTags.WATER, this, 0.014); - } - -- if (flag1) { -- double d0 = this.level.environmentAttributes().getDimensionValue(EnvironmentAttributes.FAST_LAVA) ? 0.007 : 0.0023333333333333335; -- this.fluidInteraction.applyCurrentTo(FluidTags.LAVA, this, d0); +- if (inLava) { +- double lavaFlowScale = this.level.environmentAttributes().getDimensionValue(EnvironmentAttributes.FAST_LAVA) ? 0.007 : 0.0023333333333333335; +- this.fluidInteraction.applyCurrentTo(FluidTags.LAVA, this, lavaFlowScale); - } - } + this.fluidInteraction.applyCurrentTo(this); - return flag || flag1; + return inWater || inLava; } -@@ -1614,12 +_,13 @@ +@@ -1624,12 +_,13 @@ } public boolean canSpawnSprintParticle() { @@ -132,22 +132,22 @@ } protected void spawnSprintParticle() { - BlockPos blockpos = this.getOnPosLegacy(); - BlockState blockstate = this.level().getBlockState(blockpos); -+ if (!blockstate.addRunningEffects(level, blockpos, this)) - if (blockstate.getRenderShape() != RenderShape.INVISIBLE) { - Vec3 vec3 = this.getDeltaMovement(); - BlockPos blockpos1 = this.blockPosition(); -@@ -1633,7 +_,7 @@ - d1 = Mth.clamp(d1, (double)blockpos.getZ(), blockpos.getZ() + 1.0); + BlockPos pos = this.getOnPosLegacy(); + BlockState blockState = this.level().getBlockState(pos); ++ if (!blockState.addRunningEffects(level, pos, this)) + if (blockState.getRenderShape() != RenderShape.INVISIBLE) { + Vec3 movement = this.getDeltaMovement(); + BlockPos entityPosition = this.blockPosition(); +@@ -1644,7 +_,7 @@ } -- this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate), d0, this.getY() + 0.1, d1, vec3.x * -4.0, 1.5, vec3.z * -4.0); -+ this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate).setPos(blockpos), d0, this.getY() + 0.1, d1, vec3.x * -4.0, 1.5, vec3.z * -4.0); + this.level() +- .addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockState), x, this.getY() + 0.1, z, movement.x * -4.0, 1.5, movement.z * -4.0); ++ .addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockState).setPos(pos), x, this.getY() + 0.1, z, movement.x * -4.0, 1.5, movement.z * -4.0); } } -@@ -2010,6 +_,10 @@ +@@ -2021,6 +_,10 @@ output.putBoolean("HasVisualFire", this.hasVisualFire); } @@ -158,7 +158,7 @@ if (!this.tags.isEmpty()) { output.store("Tags", TAG_LIST_CODEC, List.copyOf(this.tags)); } -@@ -2077,6 +_,9 @@ +@@ -2090,6 +_,9 @@ this.setGlowingTag(input.getBooleanOr("Glowing", false)); this.setTicksFrozen(input.getIntOr("TicksFrozen", 0)); this.hasVisualFire = input.getBooleanOr("HasVisualFire", false); @@ -168,30 +168,30 @@ this.customData = input.read("data", CustomData.CODEC).orElse(CustomData.EMPTY); this.tags.clear(); input.read("Tags", TAG_LIST_CODEC).ifPresent(this.tags::addAll); -@@ -2126,6 +_,8 @@ +@@ -2139,6 +_,8 @@ } else { - ItemEntity itementity = new ItemEntity(level, this.getX() + offset.x, this.getY() + offset.y, this.getZ() + offset.z, itemStack); - itementity.setDefaultPickUpDelay(); -+ if (captureDrops() != null) captureDrops().add(itementity); + ItemEntity entity = new ItemEntity(level, this.getX() + offset.x, this.getY() + offset.y, this.getZ() + offset.z, itemStack); + entity.setDefaultPickUpDelay(); ++ if (captureDrops() != null) captureDrops().add(entity); + else - level.addFreshEntity(itementity); - return itementity; + level.addFreshEntity(entity); + return entity; } -@@ -2184,11 +_,11 @@ +@@ -2197,11 +_,11 @@ } - ItemStack itemstack = player.getItemInHand(hand); -- if (itemstack.is(Items.SHEARS) && this.shearOffAllLeashConnections(player)) { -+ if (itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.shearOffAllLeashConnections(player)) { - itemstack.hurtAndBreak(1, player, hand); + ItemStack heldItem = player.getItemInHand(hand); +- if (heldItem.is(Items.SHEARS) && this.shearOffAllLeashConnections(player)) { ++ if (heldItem.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) && this.shearOffAllLeashConnections(player)) { + heldItem.hurtAndBreak(1, player, hand); return InteractionResult.SUCCESS; - } else if (this instanceof Mob mob -- && itemstack.is(Items.SHEARS) -+ && itemstack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) - && mob.canShearEquipment(player) + } else if (this instanceof Mob target +- && heldItem.is(Items.SHEARS) ++ && heldItem.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST) + && target.canShearEquipment(player) && !player.isSecondaryUseActive() - && this.attemptToShearEquipment(player, hand, itemstack, mob)) { -@@ -2296,6 +_,7 @@ + && this.attemptToShearEquipment(player, hand, heldItem, target)) { +@@ -2309,6 +_,7 @@ public void rideTick() { this.setDeltaMovement(Vec3.ZERO); @@ -199,7 +199,7 @@ this.tick(); if (this.isPassenger()) { this.getVehicle().positionRider(this); -@@ -2356,6 +_,7 @@ +@@ -2369,6 +_,7 @@ } } @@ -207,15 +207,15 @@ if (force || this.canRide(entityToRide) && entityToRide.canAddPassenger(this)) { if (this.isPassenger()) { this.stopRiding(); -@@ -2391,6 +_,7 @@ +@@ -2404,6 +_,7 @@ public void removeVehicle() { if (this.vehicle != null) { - Entity entity = this.vehicle; -+ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, entity, false)) return; + Entity oldVehicle = this.vehicle; ++ if (!net.minecraftforge.event.ForgeEventFactory.canMountEntity(this, oldVehicle, false)) return; this.vehicle = null; - entity.removePassenger(this); - Entity.RemovalReason entity$removalreason = this.getRemovalReason(); -@@ -2441,6 +_,8 @@ + oldVehicle.removePassenger(this); + Entity.RemovalReason removalReason = this.getRemovalReason(); +@@ -2454,6 +_,8 @@ return this.passengers.isEmpty(); } @@ -224,7 +224,7 @@ protected boolean couldAcceptPassenger() { return true; } -@@ -2638,7 +_,7 @@ +@@ -2650,7 +_,7 @@ } public boolean isVisuallyCrawling() { @@ -233,7 +233,7 @@ } public void setSwimming(final boolean swimming) { -@@ -2754,7 +_,7 @@ +@@ -2766,7 +_,7 @@ this.igniteForSeconds(8.0F); } @@ -242,7 +242,7 @@ } public void onAboveBubbleColumn(final boolean dragDown, final BlockPos pos) { -@@ -2881,7 +_,7 @@ +@@ -2885,7 +_,7 @@ } protected Component getTypeName() { @@ -251,7 +251,7 @@ } public boolean is(final Entity other) { -@@ -3191,6 +_,7 @@ +@@ -3194,6 +_,7 @@ return this.stringUUID; } @@ -259,7 +259,7 @@ public boolean isPushedByFluid() { return true; } -@@ -3597,6 +_,10 @@ +@@ -3602,6 +_,10 @@ return this.fluidInteraction.getFluidHeight(type); } @@ -270,7 +270,7 @@ public double getFluidJumpThreshold() { return this.getEyeHeight() < 0.4 ? 0.0 : 0.4; } -@@ -3609,7 +_,9 @@ +@@ -3614,7 +_,9 @@ return this.dimensions.height(); } @@ -280,7 +280,7 @@ return new ClientboundAddEntityPacket(this, serverEntity); } -@@ -3748,6 +_,11 @@ +@@ -3753,6 +_,11 @@ } } } @@ -292,10 +292,10 @@ } public void checkDespawn() { -@@ -3922,6 +_,83 @@ - float f1 = (float)Mth.lerp(d0, (double)this.getXRot(), targetXRot); - this.setPos(d1, d2, d3); - this.setRot(f, f1); +@@ -3927,6 +_,83 @@ + float xRot = (float)Mth.lerp(alpha, (double)this.getXRot(), targetXRot); + this.setPos(x, y, z); + this.setRot(yRot, xRot); + } + + private boolean canUpdate = true; diff --git a/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch index e958dcde14..98afa9846c 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityEquipment.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/entity/EntityEquipment.java @@ -49,7 +_,7 @@ for (Entry entry : this.items.entrySet()) { - ItemStack itemstack = entry.getValue(); - if (!itemstack.isEmpty()) { -- itemstack.inventoryTick(owner.level(), owner, entry.getKey()); -+ itemstack.inventoryTick(owner.level(), owner, entry.getKey(), -1); + ItemStack item = entry.getValue(); + if (!item.isEmpty()) { +- item.inventoryTick(owner.level(), owner, entry.getKey()); ++ item.inventoryTick(owner.level(), owner, entry.getKey(), -1); } } } diff --git a/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch b/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch index 547a540d04..3832e0d32f 100644 --- a/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/EntityFluidInteraction.java.patch @@ -18,8 +18,8 @@ + private net.minecraftforge.fluids.FluidType eyeFluid = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); public EntityFluidInteraction(final Set> fluids) { - for (TagKey tagkey : fluids) { - this.trackerByFluid.put(tagkey, new EntityFluidInteraction.Tracker()); + for (TagKey fluid : fluids) { + this.trackerByFluid.put(fluid, new EntityFluidInteraction.Tracker()); } + for (var entry : MODDED_TYPES.entrySet()) { + if (!fluids.contains(entry.getKey())) @@ -37,51 +37,51 @@ + this.isInFluid = false; + this.eyeFluid = net.minecraftforge.common.ForgeMod.EMPTY_TYPE.get(); + - AABB aabb = entity.getFluidInteractionBox(); - if (aabb != null) { - int i = Mth.floor(aabb.minX); + AABB box = entity.getFluidInteractionBox(); + if (box != null) { + int x0 = Mth.floor(box.minX); @@ -45,7 +_,7 @@ - double d1 = entity.getEyeY(); - int l1 = entity.getBlockZ(); - Fluid fluid = null; -- EntityFluidInteraction.Tracker entityfluidinteraction$tracker = null; + double eyeY = entity.getEyeY(); + int eyeBlockZ = entity.getBlockZ(); + Fluid lastFluidType = null; +- EntityFluidInteraction.Tracker tracker = null; + EntityFluidInteraction.Tracker[] trackers = null; - BlockGetter blockgetter = entity.level(); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + BlockGetter level = entity.level(); + BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos(); @@ -55,23 +_,26 @@ - blockpos$mutableblockpos.set(i2, j2, k2); - FluidState fluidstate = blockgetter.getFluidState(blockpos$mutableblockpos); - if (!fluidstate.isEmpty()) { + mutablePos.set(x, y, z); + FluidState fluidState = level.getFluidState(mutablePos); + if (!fluidState.isEmpty()) { + isInFluid = true; - double d2 = blockpos$mutableblockpos.getY(); - double d3 = d2 + fluidstate.getHeight(blockgetter, blockpos$mutableblockpos); - if (!(d3 < aabb.minY)) { - Fluid fluid1 = fluidstate.getType(); - if (fluid1 != fluid) { - fluid = fluid1; -- entityfluidinteraction$tracker = this.getTrackerFor(fluid1); -+ trackers = this.getTrackersFor(fluid1); + double fluidBottom = mutablePos.getY(); + double fluidTop = fluidBottom + fluidState.getHeight(level, mutablePos); + if (!(fluidTop < box.minY)) { + Fluid fluidType = fluidState.getType(); + if (fluidType != lastFluidType) { + lastFluidType = fluidType; +- tracker = this.getTrackerFor(fluidType); ++ trackers = this.getTrackersFor(fluidType); } -- if (entityfluidinteraction$tracker != null) { -+ for (var entityfluidinteraction$tracker : trackers) { - if (i2 == k1 && k2 == l1 && d1 >= d2 && d1 <= d3) { - entityfluidinteraction$tracker.eyesInside = true; -+ this.eyeFluid = fluid.getFluidType(); +- if (tracker != null) { ++ for (var tracker : trackers) { + if (x == eyeBlockX && z == eyeBlockZ && eyeY >= fluidBottom && eyeY <= fluidTop) { + tracker.eyesInside = true; ++ this.eyeFluid = lastFluidType.getFluidType(); } - entityfluidinteraction$tracker.height = Math.max(d3 - d0, entityfluidinteraction$tracker.height); + tracker.height = Math.max(fluidTop - entityY, tracker.height); - if (!ignoreCurrent) { -- Vec3 vec3 = fluidstate.getFlow(blockgetter, blockpos$mutableblockpos); -+ if (!ignoreCurrent || !fluidstate.getType().getFluidType().canPushEntity(entity)) { -+ Vec3 vec3 = fluidstate.getFlow(blockgetter, blockpos$mutableblockpos, entity); +- Vec3 flow = fluidState.getFlow(level, mutablePos); ++ if (!ignoreCurrent || !fluidState.getType().getFluidType().canPushEntity(entity)) { ++ Vec3 flow = fluidState.getFlow(level, mutablePos, entity); + - if (entityfluidinteraction$tracker.height < 0.4) { - vec3 = vec3.scale(entityfluidinteraction$tracker.height); + if (tracker.height < 0.4) { + flow = flow.scale(tracker.height); } @@ -118,15 +_,27 @@ - return flag; + return hasFluid; } - private EntityFluidInteraction.@Nullable Tracker getTrackerFor(final Fluid fluid) { @@ -90,8 +90,8 @@ + private EntityFluidInteraction.@Nullable Tracker[] getTrackersFor(final Fluid fluid) { + var ret = new java.util.ArrayList(1); for (Entry, EntityFluidInteraction.Tracker> entry : this.trackerByFluid.entrySet()) { - TagKey tagkey = entry.getKey(); - if (fluid.is(tagkey)) { + TagKey tag = entry.getKey(); + if (fluid.is(tag)) { - return entry.getValue(); + ret.add(entry.getValue()); } @@ -112,7 +112,7 @@ public void applyCurrentTo(final TagKey fluid, final Entity entity, final double scale) { @@ -141,6 +_,19 @@ - return entityfluidinteraction$tracker != null ? entityfluidinteraction$tracker.height : 0.0; + return tracker != null ? tracker.height : 0.0; } + public double getFluidHeight(final Fluid fluid) { @@ -133,8 +133,8 @@ } @@ -148,6 +_,45 @@ public boolean isEyeInFluid(final TagKey fluid) { - EntityFluidInteraction.Tracker entityfluidinteraction$tracker = this.trackerByFluid.get(fluid); - return entityfluidinteraction$tracker != null && entityfluidinteraction$tracker.eyesInside; + EntityFluidInteraction.Tracker tracker = this.trackerByFluid.get(fluid); + return tracker != null && tracker.eyesInside; + } + + public boolean isEyeInFluid(final Fluid fluid) { diff --git a/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch b/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch index 321b0c38dc..5e125b744e 100644 --- a/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ExperienceOrb.java.patch @@ -2,19 +2,19 @@ +++ b/net/minecraft/world/entity/ExperienceOrb.java @@ -136,7 +_,8 @@ this.applyEffectsFromBlocks(); - float f = 0.98F; + float friction = 0.98F; if (this.onGround()) { -- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; +- friction = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; + BlockPos pos = getBlockPosBelowThatAffectsMyMovement(); -+ f = this.level().getBlockState(pos).getFriction(this.level(), pos, this) * 0.98F; ++ friction = this.level().getBlockState(pos).getFriction(this.level(), pos, this) * 0.98F; } - this.setDeltaMovement(this.getDeltaMovement().scale(f)); -@@ -278,6 +_,7 @@ + this.setDeltaMovement(this.getDeltaMovement().scale(friction)); +@@ -277,6 +_,7 @@ public void playerTouch(final Player player) { - if (player instanceof ServerPlayer serverplayer) { + if (player instanceof ServerPlayer serverPlayer) { if (player.takeXpDelay == 0) { + if (net.minecraftforge.event.ForgeEventFactory.onPlayerPickupXp(player, this)) return; player.takeXpDelay = 2; player.take(this, 1); - int i = this.repairPlayerItems(serverplayer, this.getValue()); + int remaining = this.repairPlayerItems(serverPlayer, this.getValue()); diff --git a/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch b/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch index f5913ade3d..2312813865 100644 --- a/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LightningBolt.java.patch @@ -21,12 +21,12 @@ + } + private void powerLightningRod() { - BlockPos blockpos = this.getStrikePosition(); - BlockState blockstate = this.level().getBlockState(blockpos); + BlockPos strikePosition = this.getStrikePosition(); + BlockState stateBelow = this.level().getBlockState(strikePosition); @@ -150,6 +_,7 @@ ); - for (Entity entity : list1) { + for (Entity entity : entities) { + if (!net.minecraftforge.event.ForgeEventFactory.onEntityStruckByLightning(entity, this)) entity.thunderHit((ServerLevel)this.level(), this); } diff --git a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch index 5d72874683..b1dadac6e4 100644 --- a/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/LivingEntity.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/LivingEntity.java +++ b/net/minecraft/world/entity/LivingEntity.java -@@ -140,7 +_,7 @@ +@@ -139,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,7 +9,7 @@ private static final Logger LOGGER = LogUtils.getLogger(); private static final String TAG_ACTIVE_EFFECTS = "active_effects"; public static final String TAG_ATTRIBUTES = "attributes"; -@@ -195,6 +_,8 @@ +@@ -194,6 +_,8 @@ private static final int CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME_TICKS = 40; private static final int DEFAULT_CURRENT_IMPULSE_CONTEXT_RESET_GRACE_TIME = 0; private int currentImpulseContextResetGraceTime = 0; @@ -17,8 +17,8 @@ + @Deprecated public static final Predicate PLAYER_NOT_WEARING_DISGUISE_ITEM = livingEntity -> { if (livingEntity instanceof Player player) { - ItemStack itemstack = player.getItemBySlot(EquipmentSlot.HEAD); -@@ -279,7 +_,7 @@ + ItemStack helmet = player.getItemBySlot(EquipmentSlot.HEAD); +@@ -278,7 +_,7 @@ this.reapplyPosition(); this.setYRot(this.random.nextFloat() * (float) (Math.PI * 2)); this.yHeadRot = this.getYRot(); @@ -27,7 +27,7 @@ } @Override -@@ -338,7 +_,8 @@ +@@ -337,7 +_,8 @@ .add(Attributes.MOVEMENT_EFFICIENCY) .add(Attributes.ATTACK_KNOCKBACK) .add(Attributes.CAMERA_DISTANCE) @@ -37,17 +37,17 @@ } @Override -@@ -365,7 +_,8 @@ +@@ -364,7 +_,8 @@ - double d7 = Math.min(0.2F + d6 / 15.0, 2.5); - int i = (int)(150.0 * d7); -- serverlevel.sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState), d0, d1, d2, i, 0.0, 0.0, 0.0, 0.15F); -+ if (!onState.addLandingEffects((ServerLevel) this.level(), pos, onState, this, i)) -+ ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState).setPos(pos), d0, d1, d2, i, 0.0, 0.0, 0.0, 0.15F); + double scale = Math.min(0.2F + power / 15.0, 2.5); + int particles = (int)(150.0 * scale); +- level.sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState), x, y, z, particles, 0.0, 0.0, 0.0, 0.15F); ++ if (!onState.addLandingEffects((ServerLevel) this.level(), pos, onState, this, particles)) ++ ((ServerLevel)this.level()).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, onState).setPos(pos), x, y, z, particles, 0.0, 0.0, 0.0, 0.15F); } } -@@ -375,6 +_,7 @@ +@@ -374,6 +_,7 @@ } } @@ -55,28 +55,27 @@ public boolean canBreatheUnderwater() { return this.is(EntityTypeTags.CAN_BREATHE_UNDER_WATER); } -@@ -415,6 +_,10 @@ +@@ -414,6 +_,9 @@ } } -+ + int airSupply = this.getAirSupply(); + net.minecraftforge.common.ForgeHooks.onLivingBreathe(this, airSupply - decreaseAirSupply(airSupply), increaseAirSupply(airSupply) - airSupply); + if (false) // Forge: Handled in ForgeHooks#onLivingBreathe(LivingEntity, int, int) if (this.isEyeInFluid(FluidTags.WATER) - && !serverlevel1.getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) { - boolean flag1 = !this.canBreatheUnderwater() -@@ -764,6 +_,9 @@ + && !level.getBlockState(BlockPos.containing(this.getX(), this.getEyeY(), this.getZ())).is(Blocks.BUBBLE_COLUMN)) { + boolean canDrownInWater = !this.canBreatheUnderwater() +@@ -763,6 +_,9 @@ } else { - ItemEntity itementity = this.createItemStackToDrop(itemStack, randomly, thrownFromHand); - if (itementity != null) { + ItemEntity entity = this.createItemStackToDrop(itemStack, randomly, thrownFromHand); + if (entity != null) { + if (captureDrops() != null) -+ captureDrops().add(itementity); ++ captureDrops().add(entity); + else - this.level().addFreshEntity(itementity); + this.level().addFreshEntity(entity); } -@@ -806,7 +_,7 @@ +@@ -805,7 +_,7 @@ this.setPosToBed(sleepingPos); } }, this::clearSleepingPos); @@ -85,31 +84,31 @@ this.lastHurtByPlayer = EntityReference.read(input, "last_hurt_by_player"); this.lastHurtByPlayerMemoryTime = input.getIntOr("last_hurt_by_player_memory_time", 0); this.lastHurtByMob = EntityReference.read(input, "last_hurt_by_mob"); -@@ -832,8 +_,10 @@ - Holder holder = iterator.next(); - MobEffectInstance mobeffectinstance = this.activeEffects.get(holder); - if (!mobeffectinstance.tickServer(serverlevel, this, () -> this.onEffectUpdated(mobeffectinstance, true, null))) { -+ if (!net.minecraftforge.event.ForgeEventFactory.onLivingEffectExpire(this, mobeffectinstance)) { +@@ -831,8 +_,10 @@ + Holder mobEffect = iterator.next(); + MobEffectInstance effect = this.activeEffects.get(mobEffect); + if (!effect.tickServer(serverLevel, this, () -> this.onEffectUpdated(effect, true, null))) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onLivingEffectExpire(this, effect)) { iterator.remove(); - this.onEffectsRemoved(List.of(mobeffectinstance)); + this.onEffectsRemoved(List.of(effect)); + } - } else if (mobeffectinstance.getDuration() % 600 == 0) { - this.onEffectUpdated(mobeffectinstance, false, null); + } else if (effect.getDuration() % 600 == 0) { + this.onEffectUpdated(effect, false, null); } @@ -919,6 +_,7 @@ } } -+ d0 = net.minecraftforge.common.ForgeHooks.getEntityVisibilityMultiplier(this, targetingEntity, d0); - return d0; ++ visibilityPercent = net.minecraftforge.common.ForgeHooks.getEntityVisibilityMultiplier(this, targetingEntity, visibilityPercent); + return visibilityPercent; } @@ -992,6 +_,7 @@ } else { - MobEffectInstance mobeffectinstance = this.activeEffects.get(newEffect.getEffect()); - boolean flag = false; -+ net.minecraftforge.event.ForgeEventFactory.onLivingEffectAdd(this, mobeffectinstance, newEffect, source); - if (mobeffectinstance == null) { + MobEffectInstance effect = this.activeEffects.get(newEffect.getEffect()); + boolean changed = false; ++ net.minecraftforge.event.ForgeEventFactory.onLivingEffectAdd(this, effect, newEffect, source); + if (effect == null) { this.activeEffects.put(newEffect.getEffect(), newEffect); this.onEffectAdded(newEffect, source); @@ -1008,6 +_,10 @@ @@ -130,19 +129,19 @@ + if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, effect.get())) { + return false; + } - MobEffectInstance mobeffectinstance = this.removeEffectNoUpdate(effect); - if (mobeffectinstance != null) { - this.onEffectsRemoved(List.of(mobeffectinstance)); + MobEffectInstance effectInstance = this.removeEffectNoUpdate(effect); + if (effectInstance != null) { + this.onEffectsRemoved(List.of(effectInstance)); @@ -1082,6 +_,9 @@ this.effectsDirty = true; - for (MobEffectInstance mobeffectinstance : effects) { -+ if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, mobeffectinstance)) { + for (MobEffectInstance effect : effects) { ++ if (net.minecraftforge.event.ForgeEventFactory.onLivingEffectRemove(this, effect)) { + continue; + } - mobeffectinstance.getEffect().value().removeAttributeModifiers(this.getAttributes()); + effect.getEffect().value().removeAttributeModifiers(this.getAttributes()); - for (Entity entity : this.getPassengers()) { + for (Entity passenger : this.getPassengers()) { @@ -1129,9 +_,13 @@ } @@ -151,10 +150,10 @@ + if (ammount <= 0) { + return; + } - float f = this.getHealth(); - if (f > 0.0F) { -- this.setHealth(f + heal); -+ this.setHealth(f + ammount); + float health = this.getHealth(); + if (health > 0.0F) { +- this.setHealth(health + heal); ++ this.setHealth(health + ammount); } } @@ -171,31 +170,31 @@ @@ -1296,6 +_,10 @@ } - float f = blocksattacks.resolveBlockedDamage(source, damage, d0); -+ var ev = net.minecraftforge.event.ForgeEventFactory.onShieldBlock(this, source, f, itemstack); + float damageBlocked = blocksAttacks.resolveBlockedDamage(source, damage, angle); ++ var ev = net.minecraftforge.event.ForgeEventFactory.onShieldBlock(this, source, damageBlocked, blockingWith); + if (ev == null) return 0.0F; -+ f = ev.getBlockedDamage(); ++ damageBlocked = ev.getBlockedDamage(); + if (ev.shieldTakesDamage()) - blocksattacks.hurtBlockingItem(this.level(), itemstack, this, this.getUsedItemHand(), f); - if (f > 0.0F && !source.is(DamageTypeTags.IS_PROJECTILE) && source.getDirectEntity() instanceof LivingEntity livingentity) { - this.blockUsingItem(level, livingentity); + blocksAttacks.hurtBlockingItem(this.level(), blockingWith, this, this.getUsedItemHand(), damageBlocked); + if (damageBlocked > 0.0F && !source.is(DamageTypeTags.IS_PROJECTILE) && source.getDirectEntity() instanceof LivingEntity livingEntity) { + this.blockUsingItem(level, livingEntity); @@ -1329,7 +_,7 @@ - Entity entity = source.getEntity(); - if (entity instanceof Player player) { - this.setLastHurtByPlayer(player, 100); -- } else if (entity instanceof Wolf wolf && wolf.isTame()) { -+ } else if (entity instanceof net.minecraft.world.entity.TamableAnimal wolf && wolf.isTame()) { + Entity sourceEntity = source.getEntity(); + if (sourceEntity instanceof Player playerSource) { + this.setLastHurtByPlayer(playerSource, 100); +- } else if (sourceEntity instanceof Wolf wolf && wolf.isTame()) { ++ } else if (sourceEntity instanceof net.minecraft.world.entity.TamableAnimal wolf && wolf.isTame()) { if (wolf.getOwnerReference() != null) { this.setLastHurtByPlayer(wolf.getOwnerReference().getUUID(), 100); } else { @@ -1359,7 +_,7 @@ - for (InteractionHand interactionhand : InteractionHand.values()) { - ItemStack itemstack1 = this.getItemInHand(interactionhand); - deathprotection = itemstack1.get(DataComponents.DEATH_PROTECTION); -- if (deathprotection != null) { -+ if (deathprotection != null && net.minecraftforge.common.ForgeHooks.onLivingUseTotem(this, killingDamage, itemstack1, interactionhand)) { - itemstack = itemstack1.copy(); - itemstack1.shrink(1); + for (InteractionHand hand : InteractionHand.values()) { + ItemStack itemStack = this.getItemInHand(hand); + protection = itemStack.get(DataComponents.DEATH_PROTECTION); +- if (protection != null) { ++ if (protection != null && net.minecraftforge.common.ForgeHooks.onLivingUseTotem(this, killingDamage, itemStack, hand)) { + protectionItem = itemStack.copy(); + itemStack.shrink(1); break; @@ -1415,6 +_,7 @@ } @@ -203,36 +202,36 @@ public void die(final DamageSource source) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, source)) return; if (!this.isRemoved() && !this.dead) { - Entity entity = source.getEntity(); - LivingEntity livingentity = this.getKillCredit(); + Entity sourceEntity = source.getEntity(); + LivingEntity killer = this.getKillCredit(); @@ -1451,10 +_,10 @@ - if (this.level() instanceof ServerLevel serverlevel) { - boolean flag = false; + if (this.level() instanceof ServerLevel serverLevel) { + boolean var6 = false; if (killer instanceof WitherBoss) { -- if (serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, killer)) { - BlockPos blockpos = this.blockPosition(); - BlockState blockstate = Blocks.WITHER_ROSE.defaultBlockState(); -- if (this.level().getBlockState(blockpos).isAir() && blockstate.canSurvive(this.level(), blockpos)) { -+ if (this.level().isEmptyBlock(blockpos) && blockstate.canSurvive(this.level(), blockpos)) { - this.level().setBlock(blockpos, blockstate, 3); - flag = true; +- if (serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, killer)) { + BlockPos pos = this.blockPosition(); + BlockState state = Blocks.WITHER_ROSE.defaultBlockState(); +- if (this.level().getBlockState(pos).isAir() && state.canSurvive(this.level(), pos)) { ++ if (this.level().isEmptyBlock(pos) && state.canSurvive(this.level(), pos)) { + this.level().setBlock(pos, state, 3); + var6 = true; } @@ -1469,6 +_,7 @@ } protected void dropAllDeathLoot(final ServerLevel level, final DamageSource source) { + this.captureDrops(new java.util.ArrayList<>()); - boolean flag = this.lastHurtByPlayerMemoryTime > 0; + boolean playerKilled = this.lastHurtByPlayerMemoryTime > 0; if (this.shouldDropLoot(level)) { - this.dropFromLootTable(level, source, flag); + this.dropFromLootTable(level, source, playerKilled); @@ -1477,6 +_,11 @@ this.dropEquipment(level); this.dropExperience(level, source.getEntity()); + + var drops = captureDrops(null); -+ if (!net.minecraftforge.event.ForgeEventFactory.onLivingDrops(this, source, drops, flag)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onLivingDrops(this, source, drops, playerKilled)) { + drops.forEach(e -> level().addFreshEntity(e)); + } } @@ -260,74 +259,74 @@ power *= 1.0 - this.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE); if (!(power <= 0.0)) { this.needsSync = true; -@@ -1678,6 +_,13 @@ +@@ -1682,6 +_,13 @@ } else { - BlockPos blockpos = this.blockPosition(); - BlockState blockstate = this.getInBlockState(); -+ var ladderPos = net.minecraftforge.common.ForgeHooks.isLivingOnLadder(blockstate, level(), blockpos, this); + BlockPos ladderCheckPos = this.blockPosition(); + BlockState state = this.getInBlockState(); ++ var ladderPos = net.minecraftforge.common.ForgeHooks.isLivingOnLadder(state, level(), ladderCheckPos, this); + if (ladderPos.isPresent()) { + this.lastClimbablePos = ladderPos; + return true; + } else if (ladderPos != null) { + return false; + } - if (this.isFallFlying() && blockstate.is(BlockTags.CAN_GLIDE_THROUGH)) { + if (this.isFallFlying() && state.is(BlockTags.CAN_GLIDE_THROUGH)) { return false; - } else if (blockstate.is(BlockTags.CLIMBABLE)) { -@@ -1742,9 +_,11 @@ + } else if (state.is(BlockTags.CLIMBABLE)) { +@@ -1746,9 +_,11 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { + var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, fallDistance, damageModifier); + if (event == null) return false; - double d0; + double effectiveFallDistance; if (this.isIgnoringFallDamageFromCurrentImpulse()) { -- d0 = Math.min(fallDistance, this.currentImpulseImpactPos.y - this.getY()); -+ d0 = Math.min(event.getDistance(), this.currentImpulseImpactPos.y - this.getY()); - boolean flag = d0 <= 0.0; - if (flag) { +- effectiveFallDistance = Math.min(fallDistance, this.currentImpulseImpactPos.y - this.getY()); ++ effectiveFallDistance = Math.min(event.getDistance(), this.currentImpulseImpactPos.y - this.getY()); + boolean hasLandedAboveCurrentImpulseImpactPosY = effectiveFallDistance <= 0.0; + if (hasLandedAboveCurrentImpulseImpactPosY) { this.resetCurrentImpulseContext(); -@@ -1752,11 +_,11 @@ +@@ -1756,11 +_,11 @@ this.tryResetCurrentImpulseContext(); } } else { -- d0 = fallDistance; -+ d0 = event.getDistance(); +- effectiveFallDistance = fallDistance; ++ effectiveFallDistance = event.getDistance(); } -- boolean flag1 = super.causeFallDamage(d0, damageModifier, damageSource); -- int i = this.calculateFallDamage(d0, damageModifier); -+ boolean flag1 = super.causeFallDamage(d0, event.getDamageMultiplier(), damageSource); -+ int i = this.calculateFallDamage(d0, event.getDamageMultiplier()); - if (i > 0) { +- boolean damaged = super.causeFallDamage(effectiveFallDistance, damageModifier, damageSource); +- int dmg = this.calculateFallDamage(effectiveFallDistance, damageModifier); ++ boolean damaged = super.causeFallDamage(effectiveFallDistance, event.getDamageMultiplier(), damageSource); ++ int dmg = this.calculateFallDamage(effectiveFallDistance, event.getDamageMultiplier()); + if (dmg > 0) { this.resetCurrentImpulseContext(); - this.playSound(this.getFallDamageSound(i), 1.0F, 1.0F); -@@ -1819,9 +_,10 @@ - int i = Mth.floor(this.getX()); - int j = Mth.floor(this.getY() - 0.2F); - int k = Mth.floor(this.getZ()); -- BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); -+ BlockPos pos = new BlockPos(i, j, k); -+ BlockState blockstate = this.level().getBlockState(pos); - if (!blockstate.isAir()) { -- SoundType soundtype = blockstate.getSoundType(); -+ SoundType soundtype = blockstate.getSoundType(level(), pos, this); - this.playSound(soundtype.getFallSound(), soundtype.getVolume() * 0.5F, soundtype.getPitch() * 0.75F); + this.playSound(this.getFallDamageSound(dmg), 1.0F, 1.0F); +@@ -1823,9 +_,10 @@ + int xx = Mth.floor(this.getX()); + int yy = Mth.floor(this.getY() - 0.2F); + int zz = Mth.floor(this.getZ()); +- BlockState state = this.level().getBlockState(new BlockPos(xx, yy, zz)); ++ BlockPos pos = new BlockPos(xx, yy, zz); ++ BlockState state = this.level().getBlockState(pos); + if (!state.isAir()) { +- SoundType soundType = state.getSoundType(); ++ SoundType soundType = state.getSoundType(level(), pos, this); + this.playSound(soundType.getFallSound(), soundType.getVolume() * 0.5F, soundType.getPitch() * 0.75F); } } -@@ -1881,9 +_,9 @@ - float f2 = f1 - damage; - if (f2 > 0.0F && f2 < 3.4028235E37F) { +@@ -1885,9 +_,9 @@ + float damageResisted = oldDamage - damage; + if (damageResisted > 0.0F && damageResisted < 3.4028235E37F) { if (this instanceof ServerPlayer) { -- ((ServerPlayer)this).awardStat(Stats.DAMAGE_RESISTED, Math.round(f2 * 10.0F)); -+ ((ServerPlayer)this).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_RESISTED), Math.round(f2 * 10.0F)); +- ((ServerPlayer)this).awardStat(Stats.DAMAGE_RESISTED, Math.round(damageResisted * 10.0F)); ++ ((ServerPlayer)this).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_RESISTED), Math.round(damageResisted * 10.0F)); } else if (damageSource.getEntity() instanceof ServerPlayer) { -- ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(f2 * 10.0F)); -+ ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_DEALT_RESISTED), Math.round(f2 * 10.0F)); +- ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.DAMAGE_DEALT_RESISTED, Math.round(damageResisted * 10.0F)); ++ ((ServerPlayer)damageSource.getEntity()).awardStat(Stats.CUSTOM.get(Stats.DAMAGE_DEALT_RESISTED), Math.round(damageResisted * 10.0F)); } } } -@@ -1911,6 +_,8 @@ +@@ -1915,6 +_,8 @@ protected void actuallyHurt(final ServerLevel level, final DamageSource source, float dmg) { if (!this.isInvulnerableTo(level, source)) { @@ -335,16 +334,16 @@ + if (dmg <= 0) return; dmg = this.getDamageAfterArmorAbsorb(source, dmg); dmg = this.getDamageAfterMagicAbsorb(source, dmg); - float f1 = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); -@@ -1920,6 +_,7 @@ - serverplayer.awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(f * 10.0F)); + float var10 = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); +@@ -1924,6 +_,7 @@ + serverPlayer.awardStat(Stats.DAMAGE_DEALT_ABSORBED, Math.round(absorbedDamage * 10.0F)); } -+ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, f1); - if (f1 != 0.0F) { - this.getCombatTracker().recordDamage(source, f1); - this.setHealth(this.getHealth() - f1); -@@ -1981,6 +_,8 @@ ++ var10 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, var10); + if (var10 != 0.0F) { + this.getCombatTracker().recordDamage(source, var10); + this.setHealth(this.getHealth() - var10); +@@ -1987,6 +_,8 @@ } public void swing(final InteractionHand hand, final boolean sendToSwingingEntity) { @@ -353,13 +352,13 @@ if (!this.swinging || this.swingTime >= this.getCurrentSwingDuration() / 2 || this.swingTime < 0) { this.swingTime = -1; this.swinging = true; -@@ -2121,9 +_,10 @@ +@@ -2128,9 +_,10 @@ } private void swapHandItems() { -- ItemStack itemstack = this.getItemBySlot(EquipmentSlot.OFFHAND); +- ItemStack tmp = this.getItemBySlot(EquipmentSlot.OFFHAND); - this.setItemSlot(EquipmentSlot.OFFHAND, this.getItemBySlot(EquipmentSlot.MAINHAND)); -- this.setItemSlot(EquipmentSlot.MAINHAND, itemstack); +- this.setItemSlot(EquipmentSlot.MAINHAND, tmp); + var event = net.minecraftforge.event.ForgeEventFactory.onLivingSwapHandItems(this); + if (event == null) return; + this.setItemSlot(EquipmentSlot.OFFHAND, event.getItemSwappedToOffHand()); @@ -367,7 +366,7 @@ } @Override -@@ -2340,15 +_,18 @@ +@@ -2347,15 +_,18 @@ } this.needsSync = true; @@ -388,7 +387,7 @@ } protected float getWaterSlowDown() { -@@ -2370,8 +_,9 @@ +@@ -2377,8 +_,9 @@ } public void travel(final Vec3 input) { @@ -400,7 +399,7 @@ } else if (this.isFallFlying()) { this.travelFallFlying(input); } else { -@@ -2384,7 +_,7 @@ +@@ -2391,7 +_,7 @@ } protected boolean shouldTravelInFluid(final FluidState fluidState) { @@ -409,16 +408,16 @@ } protected void travelFlying(final Vec3 input, final float speed) { -@@ -2409,7 +_,7 @@ +@@ -2416,7 +_,7 @@ private void travelInAir(final Vec3 input) { - BlockPos blockpos = this.getBlockPosBelowThatAffectsMyMovement(); -- float f = this.onGround() ? this.level().getBlockState(blockpos).getBlock().getFriction() : 1.0F; -+ float f = this.onGround() ? this.level().getBlockState(blockpos).getFriction(level(), blockpos, this) : 1.0F; - float f1 = f * 0.91F; - Vec3 vec3 = this.handleRelativeFrictionAndCalculateMovement(input, f); - double d0 = vec3.y; -@@ -2432,10 +_,18 @@ + BlockPos posBelow = this.getBlockPosBelowThatAffectsMyMovement(); +- float blockFriction = this.onGround() ? this.level().getBlockState(posBelow).getBlock().getFriction() : 1.0F; ++ float blockFriction = this.onGround() ? this.level().getBlockState(posBelow).getFriction(level(), posBelow, this) : 1.0F; + float friction = blockFriction * 0.91F; + Vec3 movement = this.handleRelativeFrictionAndCalculateMovement(input, blockFriction); + double movementY = movement.y; +@@ -2439,10 +_,18 @@ } } @@ -429,33 +428,33 @@ + } + + private void travelInFluid(Vec3 input, FluidState fluidstate) { - boolean flag = this.getDeltaMovement().y <= 0.0; - double d0 = this.getY(); - double d1 = this.getEffectiveGravity(); -+ if (this.isInFluidType(fluidstate) && this.moveInFluid(fluidstate, input, d0)) { + boolean isFalling = this.getDeltaMovement().y <= 0.0; + double oldY = this.getY(); + double baseGravity = this.getEffectiveGravity(); ++ if (this.isInFluidType(fluidstate) && this.moveInFluid(fluidstate, input, oldY)) { + // Modded fluid handled it + } else if (this.isInWater()) { - this.travelInWater(input, d1, flag, d0); + this.travelInWater(input, baseGravity, isFalling, oldY); this.floatInWaterWhileRidden(); -@@ -2461,6 +_,7 @@ - f = 0.96F; +@@ -2468,6 +_,7 @@ + slowDown = 0.96F; } -+ f1 *= this.getAttributeValue(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()); - this.moveRelative(f1, input); ++ speed *= this.getAttributeValue(net.minecraftforge.common.ForgeMod.SWIM_SPEED.getHolder().get()); + this.moveRelative(speed, input); this.move(MoverType.SELF, this.getDeltaMovement()); - Vec3 vec3 = this.getDeltaMovement(); -@@ -2632,7 +_,7 @@ - double d0 = Mth.clamp(delta.x, -0.15F, 0.15F); - double d1 = Mth.clamp(delta.z, -0.15F, 0.15F); - double d2 = Math.max(delta.y, -0.15F); -- if (d2 < 0.0 && !this.getInBlockState().is(Blocks.SCAFFOLDING) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { -+ if (d2 < 0.0 && !this.getInBlockState().isScaffolding(this) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { - d2 = 0.0; + Vec3 ladderMovement = this.getDeltaMovement(); +@@ -2641,7 +_,7 @@ + double xd = Mth.clamp(delta.x, -0.15F, 0.15F); + double zd = Mth.clamp(delta.z, -0.15F, 0.15F); + double yd = Math.max(delta.y, -0.15F); +- if (yd < 0.0 && !this.getInBlockState().is(Blocks.SCAFFOLDING) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { ++ if (yd < 0.0 && !this.getInBlockState().isScaffolding(this) && this.isSuppressingSlidingDownLadder() && this instanceof Player) { + yd = 0.0; } -@@ -2675,6 +_,7 @@ +@@ -2684,6 +_,7 @@ @Override public void tick() { @@ -463,31 +462,31 @@ super.tick(); this.updatingUsingItem(); this.updateSwimAmount(); -@@ -2873,6 +_,7 @@ - ItemStack itemstack = this.lastEquipmentItems.get(equipmentslot); - ItemStack itemstack1 = this.getItemBySlot(equipmentslot); - if (this.equipmentHasChanged(itemstack, itemstack1)) { -+ net.minecraftforge.event.ForgeEventFactory.onLivingEquipmentChange(this, equipmentslot, itemstack, itemstack1); - if (map == null) { - map = Maps.newEnumMap(EquipmentSlot.class); +@@ -2882,6 +_,7 @@ + ItemStack previous = this.lastEquipmentItems.get(slot); + ItemStack current = this.getItemBySlot(slot); + if (this.equipmentHasChanged(previous, current)) { ++ net.minecraftforge.event.ForgeEventFactory.onLivingEquipmentChange(this, slot, previous, current); + if (changedItems == null) { + changedItems = Maps.newEnumMap(EquipmentSlot.class); } -@@ -3008,6 +_,10 @@ - profilerfiller.push("jump"); +@@ -3017,6 +_,10 @@ + profiler.push("jump"); if (this.jumping && this.isAffectedByFluids()) { - double d3; + double fluidHeight; + var fluidType = this.getMaxHeightFluidType(); + if (!fluidType.isAir()) { -+ d3 = this.getFluidTypeHeight(fluidType); ++ fluidHeight = this.getFluidTypeHeight(fluidType); + } else if (this.isInLava()) { - d3 = this.getFluidHeight(FluidTags.LAVA); + fluidHeight = this.getFluidHeight(FluidTags.LAVA); } else { -@@ -3018,15 +_,19 @@ - double d4 = this.getFluidJumpThreshold(); - if (!flag || this.onGround() && !(d3 > d4)) { - if (!this.isInLava() || this.onGround() && !(d3 > d4)) { -+ if (fluidType.isAir() || this.onGround() && !(d3 > d4)) { - if ((this.onGround() || flag && d3 <= d4) && this.noJumpDelay == 0) { +@@ -3027,15 +_,19 @@ + double fluidJumpThreshold = this.getFluidJumpThreshold(); + if (!inWaterAndHasFluidHeight || this.onGround() && !(fluidHeight > fluidJumpThreshold)) { + if (!this.isInLava() || this.onGround() && !(fluidHeight > fluidJumpThreshold)) { ++ if (fluidType.isAir() || this.onGround() && !(fluidHeight > fluidJumpThreshold)) { + if ((this.onGround() || inWaterAndHasFluidHeight && fluidHeight <= fluidJumpThreshold) && this.noJumpDelay == 0) { this.jumpFromGround(); this.noJumpDelay = 10; } @@ -504,7 +503,7 @@ } } else { this.noJumpDelay = 0; -@@ -3346,8 +_,11 @@ +@@ -3355,8 +_,11 @@ private void updatingUsingItem() { if (this.isUsingItem()) { @@ -517,7 +516,7 @@ this.updateUsingItem(this.useItem); } else { this.stopUsingItem(); -@@ -3390,8 +_,12 @@ +@@ -3399,8 +_,12 @@ } protected void updateUsingItem(final ItemStack useItem) { @@ -531,42 +530,42 @@ this.completeUsingItem(); } } -@@ -3419,8 +_,10 @@ +@@ -3428,8 +_,10 @@ public void startUsingItem(final InteractionHand hand) { - ItemStack itemstack = this.getItemInHand(hand); - if (!itemstack.isEmpty() && !this.isUsingItem()) { -+ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemstack, itemstack.getUseDuration(this)); + ItemStack itemStack = this.getItemInHand(hand); + if (!itemStack.isEmpty() && !this.isUsingItem()) { ++ int duration = net.minecraftforge.event.ForgeEventFactory.onItemUseStart(this, itemStack, itemStack.getUseDuration(this)); + if (duration < 0) return; - this.useItem = itemstack; -- this.useItemRemaining = itemstack.getUseDuration(this); + this.useItem = itemStack; +- this.useItemRemaining = itemStack.getUseDuration(this); + this.useItemRemaining = duration; if (!this.level().isClientSide()) { this.setLivingEntityFlag(1, true); this.setLivingEntityFlag(2, hand == InteractionHand.OFF_HAND); -@@ -3478,6 +_,9 @@ - vec31 = vec31.xRot(-this.getXRot() * (float) (Math.PI / 180.0)); - vec31 = vec31.yRot(-this.getYRot() * (float) (Math.PI / 180.0)); - vec31 = vec31.add(this.getX(), this.getEyeY(), this.getZ()); +@@ -3487,6 +_,9 @@ + p = p.xRot(-this.getXRot() * (float) (Math.PI / 180.0)); + p = p.yRot(-this.getYRot() * (float) (Math.PI / 180.0)); + p = p.add(this.getX(), this.getEyeY(), this.getZ()); + if (this.level() instanceof ServerLevel serverLevel) //Forge: Fix MC-2518 spawnParticle is nooped on server, need to use server specific variant -+ serverLevel.sendParticles(itemparticleoption, vec31.x, vec31.y, vec31.z, 1, vec3.x, vec3.y + 0.05D, vec3.z, 0.0D); ++ serverLevel.sendParticles(breakParticle, p.x, p.y, p.z, 1, d.x, d.y + 0.05D, d.z, 0.0D); + else - this.level().addParticle(itemparticleoption, vec31.x, vec31.y, vec31.z, vec3.x, vec3.y + 0.05, vec3.z); + this.level().addParticle(breakParticle, p.x, p.y, p.z, d.x, d.y + 0.05, d.z); } } -@@ -3490,7 +_,9 @@ +@@ -3499,7 +_,9 @@ this.releaseUsingItem(); } else { if (!this.useItem.isEmpty() && this.isUsingItem()) { + ItemStack copy = this.useItem.copy(); - ItemStack itemstack = this.useItem.finishUsingItem(this.level(), this); -+ itemstack = net.minecraftforge.event.ForgeEventFactory.onItemUseFinish(this, copy, getUseItemRemainingTicks(), itemstack); - if (itemstack != this.useItem) { - this.setItemInHand(interactionhand, itemstack); + ItemStack result = this.useItem.finishUsingItem(this.level(), this); ++ result = net.minecraftforge.event.ForgeEventFactory.onItemUseFinish(this, copy, getUseItemRemainingTicks(), result); + if (result != this.useItem) { + this.setItemInHand(hand, result); } -@@ -3524,7 +_,13 @@ - ItemStack itemstack = this.getItemInHand(this.getUsedItemHand()); - if (!this.useItem.isEmpty() && ItemStack.isSameItem(itemstack, this.useItem)) { - this.useItem = itemstack; +@@ -3533,7 +_,13 @@ + ItemStack itemInUsedHand = this.getItemInHand(this.getUsedItemHand()); + if (!this.useItem.isEmpty() && ItemStack.isSameItem(itemInUsedHand, this.useItem)) { + this.useItem = itemInUsedHand; + if (!net.minecraftforge.event.ForgeEventFactory.onUseItemStop(this, useItem, this.getUseItemRemainingTicks())) { + ItemStack copy = this instanceof Player ? useItem.copy() : null; this.useItem.releaseUsing(this.level(), this, this.getUseItemRemainingTicks()); @@ -577,26 +576,26 @@ if (this.useItem.useOnRelease()) { this.updatingUsingItem(); } -@@ -3534,6 +_,7 @@ +@@ -3543,6 +_,7 @@ } public void stopUsingItem() { + if (this.isUsingItem() && !this.useItem.isEmpty()) this.useItem.onStopUsing(this, useItemRemaining); if (!this.level().isClientSide()) { - boolean flag = this.isUsingItem(); + boolean wasUsingItem = this.isUsingItem(); this.recentKineticEnemies = null; -@@ -3702,8 +_,8 @@ +@@ -3704,8 +_,8 @@ } - BlockState blockstate = this.level().getBlockState(bedPosition); -- if (blockstate.getBlock() instanceof BedBlock) { -- this.level().setBlock(bedPosition, blockstate.setValue(BedBlock.OCCUPIED, true), 3); -+ if (blockstate.isBed(level(), bedPosition, this)) { -+ blockstate.setBedOccupied(level(), bedPosition, this, true); + BlockState blockState = this.level().getBlockState(bedPosition); +- if (blockState.getBlock() instanceof BedBlock) { +- this.level().setBlock(bedPosition, blockState.setValue(BedBlock.OCCUPIED, true), 3); ++ if (blockState.isBed(level(), bedPosition, this)) { ++ blockState.setBedOccupied(level(), bedPosition, this, true); } this.setPose(Pose.SLEEPING); -@@ -3718,15 +_,15 @@ +@@ -3720,15 +_,15 @@ } private boolean checkBedExists() { @@ -606,27 +605,27 @@ public void stopSleeping() { this.getSleepingPos().filter(this.level()::hasChunkAt).ifPresent(bedPosition -> { - BlockState blockstate = this.level().getBlockState(bedPosition); -- if (blockstate.getBlock() instanceof BedBlock) { -+ if (blockstate.isBed(level(), bedPosition, this)) { - Direction direction = blockstate.getValue(BedBlock.FACING); -- this.level().setBlock(bedPosition, blockstate.setValue(BedBlock.OCCUPIED, false), 3); -+ blockstate.setBedOccupied(level(), bedPosition, this, false); - Vec3 vec31 = BedBlock.findStandUpPosition(this.getType(), this.level(), bedPosition, direction, this.getYRot()).orElseGet(() -> { - BlockPos blockpos = bedPosition.above(); - return new Vec3(blockpos.getX() + 0.5, blockpos.getY() + 0.1, blockpos.getZ() + 0.5); -@@ -3746,7 +_,9 @@ + BlockState state = this.level().getBlockState(bedPosition); +- if (state.getBlock() instanceof BedBlock) { ++ if (state.isBed(level(), bedPosition, this)) { + Direction facing = state.getValue(BedBlock.FACING); +- this.level().setBlock(bedPosition, state.setValue(BedBlock.OCCUPIED, false), 3); ++ state.setBedOccupied(level(), bedPosition, this, false); + Vec3 standUp = BedBlock.findStandUpPosition(this.getType(), this.level(), bedPosition, facing, this.getYRot()).orElseGet(() -> { + BlockPos above = bedPosition.above(); + return new Vec3(above.getX() + 0.5, above.getY() + 0.1, above.getZ() + 0.5); +@@ -3748,7 +_,9 @@ public @Nullable Direction getBedOrientation() { - BlockPos blockpos = this.getSleepingPos().orElse(null); -- return blockpos != null ? BedBlock.getBedOrientation(this.level(), blockpos) : null; -+ if (blockpos == null) return Direction.UP; -+ BlockState state = this.level().getBlockState(blockpos); -+ return !state.isBed(level(), blockpos, this) ? Direction.UP : state.getBedDirection(level(), blockpos); + BlockPos bedPos = this.getSleepingPos().orElse(null); +- return bedPos != null ? BedBlock.getBedOrientation(this.level(), bedPos) : null; ++ if (bedPos == null) return Direction.UP; ++ BlockState state = this.level().getBlockState(bedPos); ++ return !state.isBed(level(), bedPos, this) ? Direction.UP : state.getBedDirection(level(), bedPos); } @Override -@@ -3755,7 +_,7 @@ +@@ -3757,7 +_,7 @@ } public ItemStack getProjectile(final ItemStack heldWeapon) { @@ -635,7 +634,7 @@ } private static byte entityEventForEquipmentBreak(final EquipmentSlot equipmentSlot) { -@@ -3807,6 +_,8 @@ +@@ -3809,6 +_,8 @@ } public final EquipmentSlot getEquipmentSlotForItem(final ItemStack itemStack) { @@ -644,7 +643,7 @@ Equippable equippable = itemStack.get(DataComponents.EQUIPPABLE); return equippable != null && this.canUseSlot(equippable.slot()) ? equippable.slot() : EquipmentSlot.MAINHAND; } -@@ -3970,5 +_,42 @@ +@@ -3972,5 +_,42 @@ } public record Fallsounds(SoundEvent small, SoundEvent big) { diff --git a/patches/minecraft/net/minecraft/world/entity/Mob.java.patch b/patches/minecraft/net/minecraft/world/entity/Mob.java.patch index 9fb32dee9c..de61e2bbb2 100644 --- a/patches/minecraft/net/minecraft/world/entity/Mob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/Mob.java.patch @@ -51,27 +51,27 @@ && this.canPickUpLoot() && this.isAlive() && !this.dead -- && serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this)) { - Vec3i vec3i = this.getPickupReach(); +- && serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this)) { + Vec3i pickupReach = this.getPickupReach(); - for (ItemEntity itementity : this.level() -@@ -658,6 +_,14 @@ + for (ItemEntity entity : this.level() +@@ -657,6 +_,14 @@ this.discard(); } else if (!this.isPersistenceRequired() && !this.requiresCustomPersistence()) { - Entity entity = this.level().getNearestPlayer(this, -1.0); + Entity player = this.level().getNearestPlayer(this, -1.0); + var result = net.minecraftforge.event.ForgeEventFactory.canEntityDespawn(this, (ServerLevel)this.level()); + if (result.isDenied()) { + noActionTime = 0; -+ entity = null; ++ player = null; + } else if (result.isAllowed()) { + this.discard(); -+ entity = null; ++ player = null; + } - if (entity != null) { - double d0 = entity.distanceToSqr(this); - int i = this.getType().getCategory().getDespawnDistance(); -@@ -1059,6 +_,16 @@ + if (player != null) { + double distSqr = player.distanceToSqr(this); + int instantDespawnDistance = this.getType().getCategory().getDespawnDistance(); +@@ -1058,6 +_,16 @@ } } @@ -88,16 +88,16 @@ public @Nullable SpawnGroupData finalizeSpawn( final ServerLevelAccessor level, final DifficultyInstance difficulty, final EntitySpawnReason spawnReason, final @Nullable SpawnGroupData groupData ) { -@@ -1071,6 +_,7 @@ +@@ -1070,6 +_,7 @@ } - this.setLeftHanded(randomsource.nextFloat() < 0.05F); + this.setLeftHanded(random.nextFloat() < 0.05F); + this.spawnReason = spawnReason; return groupData; } -@@ -1382,15 +_,25 @@ - return flag; +@@ -1383,15 +_,25 @@ + return wasHurt; } + @Deprecated // FORGE: use jumpInFluid instead @@ -123,7 +123,7 @@ @VisibleForTesting public void removeFreeWill() { this.removeAllGoals(goal -> true); -@@ -1416,6 +_,41 @@ +@@ -1417,6 +_,41 @@ @Override public @Nullable ItemStack getPickResult() { return SpawnEggItem.byId(this.getType()).map(ItemStack::new).orElse(null); diff --git a/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch b/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch index 38357879f4..c210084862 100644 --- a/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/SpawnPlacementTypes.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/SpawnPlacementTypes.java +++ b/net/minecraft/world/entity/SpawnPlacementTypes.java @@ -28,7 +_,7 @@ - BlockPos blockpos = blockPos.above(); - BlockPos blockpos1 = blockPos.below(); - BlockState blockstate = level.getBlockState(blockpos1); -- return !blockstate.isValidSpawn(level, blockpos1, type) -+ return !blockstate.isValidSpawn(level, blockpos1, this, type) + BlockPos above = blockPos.above(); + BlockPos below = blockPos.below(); + BlockState belowState = level.getBlockState(below); +- return !belowState.isValidSpawn(level, below, type) ++ return !belowState.isValidSpawn(level, below, this, type) ? false - : this.isValidEmptySpawnBlock(level, blockPos, type) && this.isValidEmptySpawnBlock(level, blockpos, type); + : this.isValidEmptySpawnBlock(level, blockPos, type) && this.isValidEmptySpawnBlock(level, above, type); } else { diff --git a/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch b/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch index 544a91a76c..5f80753e56 100644 --- a/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/SpawnPlacements.java.patch @@ -11,9 +11,9 @@ @@ -78,7 +_,8 @@ final EntityType type, final ServerLevelAccessor level, final EntitySpawnReason spawnReason, final BlockPos pos, final RandomSource random ) { - SpawnPlacements.Data spawnplacements$data = DATA_BY_TYPE.get(type); -- return spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)type, level, spawnReason, pos, random); -+ boolean vanillaResult = spawnplacements$data == null || spawnplacements$data.predicate.test((EntityType)type, level, spawnReason, pos, random); + SpawnPlacements.Data data = DATA_BY_TYPE.get(type); +- return data == null || data.predicate.test((EntityType)type, level, spawnReason, pos, random); ++ boolean vanillaResult = data == null || data.predicate.test((EntityType)type, level, spawnReason, pos, random); + return net.minecraftforge.event.ForgeEventFactory.checkSpawnPlacements(type, level, spawnReason, pos, random, vanillaResult); } diff --git a/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch b/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch index 4521d3060f..420d224ab9 100644 --- a/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/TamableAnimal.java.patch @@ -3,9 +3,9 @@ @@ -135,9 +_,9 @@ protected void feed(final Player player, final InteractionHand hand, final ItemStack itemStack, final float healingFactor, final float defaultHeal) { - FoodProperties foodproperties = itemStack.get(DataComponents.FOOD); + FoodProperties foodProperties = itemStack.get(DataComponents.FOOD); - this.usePlayerItem(player, hand, itemStack); - this.heal(foodproperties != null ? healingFactor * foodproperties.nutrition() : defaultHeal); + this.heal(foodProperties != null ? healingFactor * foodProperties.nutrition() : defaultHeal); this.playEatingSound(); + this.usePlayerItem(player, hand, itemStack); } @@ -20,11 +20,11 @@ + super.die(source); + + if (this.dead) - if (this.level() instanceof ServerLevel serverlevel - && serverlevel.getGameRules().get(GameRules.SHOW_DEATH_MESSAGES) - && this.getOwner() instanceof ServerPlayer serverplayer) { -- serverplayer.sendSystemMessage(this.getCombatTracker().getDeathMessage()); -+ serverplayer.sendSystemMessage(deathMessage); + if (this.level() instanceof ServerLevel serverLevel + && serverLevel.getGameRules().get(GameRules.SHOW_DEATH_MESSAGES) + && this.getOwner() instanceof ServerPlayer serverPlayer) { +- serverPlayer.sendSystemMessage(this.getCombatTracker().getDeathMessage()); ++ serverPlayer.sendSystemMessage(deathMessage); } - - super.die(source); diff --git a/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch index f38f2542a9..768b6b365b 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/Brain.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/ai/Brain.java +++ b/net/minecraft/world/entity/ai/Brain.java -@@ -259,6 +_,10 @@ +@@ -256,6 +_,10 @@ this.schedule = schedule; } @@ -11,7 +11,7 @@ public void setCoreActivities(final Set activities) { this.coreActivities = activities; } -@@ -460,6 +_,31 @@ +@@ -457,6 +_,31 @@ public boolean isBrainDead() { return this.memories.isEmpty() && this.sensors.isEmpty() && this.availableBehaviorsByPriority.isEmpty(); diff --git a/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch index aef61b29b6..7568317e51 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/attributes/AttributeSupplier.java.patch @@ -25,7 +25,7 @@ + } private AttributeInstance create(final Holder attribute) { - AttributeInstance attributeinstance = new AttributeInstance(attribute, attributeInstance -> { + AttributeInstance result = new AttributeInstance(attribute, attributeInstance -> { @@ -91,7 +_,8 @@ public AttributeSupplier build() { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch index ba269cd065..1fed431750 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java +++ b/net/minecraft/world/entity/ai/attributes/DefaultAttributes.java -@@ -188,11 +_,12 @@ +@@ -187,11 +_,12 @@ .build(); public static AttributeSupplier getSupplier(final EntityType type) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch index 9b06cbc7f4..fbefd3402b 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/CrossbowAttack.java.patch @@ -3,9 +3,9 @@ @@ -25,7 +_,7 @@ protected boolean checkExtraStartConditions(final ServerLevel level, final E body) { - LivingEntity livingentity = getAttackTarget(body); -- return body.isHolding(Items.CROSSBOW) && BehaviorUtils.canSee(body, livingentity) && BehaviorUtils.isWithinAttackRange(body, livingentity, 0); -+ return body.isHolding(is -> is.getItem() instanceof CrossbowItem) && BehaviorUtils.canSee(body, livingentity) && BehaviorUtils.isWithinAttackRange(body, livingentity, 0); + LivingEntity attackTarget = getAttackTarget(body); +- return body.isHolding(Items.CROSSBOW) && BehaviorUtils.canSee(body, attackTarget) && BehaviorUtils.isWithinAttackRange(body, attackTarget, 0); ++ return body.isHolding(is -> is.getItem() instanceof CrossbowItem) && BehaviorUtils.canSee(body, attackTarget) && BehaviorUtils.isWithinAttackRange(body, attackTarget, 0); } protected boolean canStillUse(final ServerLevel level, final E body, final long timestamp) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch index 4bfab8f426..a2b3c1290a 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/HarvestFarmland.java.patch @@ -10,14 +10,14 @@ } else if (!body.getVillagerData().profession().is(VillagerProfession.FARMER)) { return false; @@ -118,6 +_,11 @@ - level.setBlockAndUpdate(this.aboveFarmlandPos, blockstate1); - level.gameEvent(GameEvent.BLOCK_PLACE, this.aboveFarmlandPos, GameEvent.Context.of(body, blockstate1)); - flag = true; -+ } else if (itemstack.getItem() instanceof net.minecraftforge.common.IPlantable) { -+ if (((net.minecraftforge.common.IPlantable) itemstack.getItem()).getPlantType(level, aboveFarmlandPos) == net.minecraftforge.common.PlantType.CROP) { -+ level.setBlock(aboveFarmlandPos, ((net.minecraftforge.common.IPlantable) itemstack.getItem()).getPlant(level, aboveFarmlandPos), 3); -+ flag = true; + level.setBlockAndUpdate(this.aboveFarmlandPos, place); + level.gameEvent(GameEvent.BLOCK_PLACE, this.aboveFarmlandPos, GameEvent.Context.of(body, place)); + ok = true; ++ } else if (itemStack.getItem() instanceof net.minecraftforge.common.IPlantable) { ++ if (((net.minecraftforge.common.IPlantable) itemStack.getItem()).getPlantType(level, aboveFarmlandPos) == net.minecraftforge.common.PlantType.CROP) { ++ level.setBlock(aboveFarmlandPos, ((net.minecraftforge.common.IPlantable) itemStack.getItem()).getPlant(level, aboveFarmlandPos), 3); ++ ok = true; + } } - if (flag) { + if (ok) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch index 272126ac2c..31e31a0481 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/behavior/StartAttacking.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/ai/behavior/StartAttacking.java +++ b/net/minecraft/world/entity/ai/behavior/StartAttacking.java -@@ -30,7 +_,11 @@ - if (!body.canAttack(livingentity)) { +@@ -29,7 +_,11 @@ + if (!body.canAttack(targetEntity)) { return false; } else { -- attackTarget.set(livingentity); -+ var changeTargetEvent = net.minecraftforge.event.ForgeEventFactory.onLivingChangeTargetBehavior(body, livingentity); +- attackTarget.set(targetEntity); ++ var changeTargetEvent = net.minecraftforge.event.ForgeEventFactory.onLivingChangeTargetBehavior(body, targetEntity); + if (changeTargetEvent == null) + return false; + diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch index 74cd9f288c..8774cdbd17 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/EatBlockGoal.java.patch @@ -2,19 +2,19 @@ +++ b/net/minecraft/world/entity/ai/goal/EatBlockGoal.java @@ -61,7 +_,7 @@ if (this.eatAnimationTick == this.adjustedTickDelay(4)) { - BlockPos blockpos = this.mob.blockPosition(); - if (IS_EDIBLE.test(this.level.getBlockState(blockpos))) { + BlockPos pos = this.mob.blockPosition(); + if (IS_EDIBLE.test(this.level.getBlockState(pos))) { - if (getServerLevel(this.level).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.level), this.mob)) { - this.level.destroyBlock(blockpos, false); + this.level.destroyBlock(pos, false); } @@ -69,7 +_,7 @@ } else { - BlockPos blockpos1 = blockpos.below(); - if (this.level.getBlockState(blockpos1).is(Blocks.GRASS_BLOCK)) { + BlockPos below = pos.below(); + if (this.level.getBlockState(below).is(Blocks.GRASS_BLOCK)) { - if (getServerLevel(this.level).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.level), this.mob)) { - this.level.levelEvent(2001, blockpos1, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState())); - this.level.setBlock(blockpos1, Blocks.DIRT.defaultBlockState(), 2); + this.level.levelEvent(2001, below, Block.getId(Blocks.GRASS_BLOCK.defaultBlockState())); + this.level.setBlock(below, Blocks.DIRT.defaultBlockState(), 2); } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch index f5f27e8f56..9ad3e1ec80 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/MeleeAttackGoal.java.patch @@ -10,30 +10,30 @@ public MeleeAttackGoal(final PathfinderMob mob, final double speedModifier, final boolean followingTargetEvenIfNotSeen) { this.mob = mob; @@ -42,6 +_,15 @@ - } else if (!livingentity.isAlive()) { + } else if (!target.isAlive()) { return false; } else { + if (canPenalize) { + if (--this.ticksUntilNextPathRecalculation <= 0) { -+ this.path = this.mob.getNavigation().createPath(livingentity, 0); ++ this.path = this.mob.getNavigation().createPath(target, 0); + this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); + return this.path != null; + } else { + return true; + } + } - this.path = this.mob.getNavigation().createPath(livingentity, 0); - return this.path != null ? true : this.mob.isWithinMeleeAttackRange(livingentity); + this.path = this.mob.getNavigation().createPath(target, 0); + return this.path != null ? true : this.mob.isWithinMeleeAttackRange(target); } -@@ -106,6 +_,18 @@ - this.pathedTargetZ = livingentity.getZ(); +@@ -104,6 +_,18 @@ + this.pathedTargetZ = target.getZ(); this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7); - double d0 = this.mob.distanceToSqr(livingentity); + double targetDistanceSqr = this.mob.distanceToSqr(target); + if (this.canPenalize) { + this.ticksUntilNextPathRecalculation += failedPathFindingPenalty; + if (this.mob.getNavigation().getPath() != null) { -+ net.minecraft.world.level.pathfinder.Node finalPathPoint = this.mob.getNavigation().getPath().getEndNode(); -+ if (finalPathPoint != null && livingentity.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) ++ var finalPathPoint = this.mob.getNavigation().getPath().getEndNode(); ++ if (finalPathPoint != null && target.distanceToSqr(finalPathPoint.x, finalPathPoint.y, finalPathPoint.z) < 1) + failedPathFindingPenalty = 0; + else + failedPathFindingPenalty += 10; @@ -41,6 +41,6 @@ + failedPathFindingPenalty += 10; + } + } - if (d0 > 1024.0) { + if (targetDistanceSqr > 1024.0) { this.ticksUntilNextPathRecalculation += 10; - } else if (d0 > 256.0) { + } else if (targetDistanceSqr > 256.0) { diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch index 556a92b1da..986b766ffa 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RangedCrossbowAttackGoal.java.patch @@ -10,9 +10,9 @@ @Override @@ -99,7 +_,7 @@ - this.mob.getLookControl().setLookAt(livingentity, 30.0F, 30.0F); + this.mob.getLookControl().setLookAt(target, 30.0F, 30.0F); if (this.crossbowState == RangedCrossbowAttackGoal.CrossbowState.UNCHARGED) { - if (!flag2) { + if (!needsToMove) { - this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, Items.CROSSBOW)); + this.mob.startUsingItem(ProjectileUtil.getWeaponHoldingHand(this.mob, item -> item instanceof CrossbowItem)); this.crossbowState = RangedCrossbowAttackGoal.CrossbowState.CHARGING; diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch index 456058e5ba..cd49045c6c 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RemoveBlockGoal.java.patch @@ -9,13 +9,11 @@ return false; } else if (this.nextStartTick > 0) { this.nextStartTick--; -@@ -142,7 +_,8 @@ - ); - return chunkaccess == null +@@ -139,6 +_,6 @@ + ChunkAccess chunk = level.getChunk(SectionPos.blockToSectionCoord(pos.getX()), SectionPos.blockToSectionCoord(pos.getZ()), ChunkStatus.FULL, false); + return chunk == null ? false -- : chunkaccess.getBlockState(pos).is(this.blockToRemove) -+ : !chunkaccess.getBlockState(pos).canEntityDestroy(level, pos, this.removerMob) ? false -+ : chunkaccess.getBlockState(pos).is(this.blockToRemove) - && chunkaccess.getBlockState(pos.above()).isAir() - && chunkaccess.getBlockState(pos.above(2)).isAir(); +- : chunk.getBlockState(pos).is(this.blockToRemove) && chunk.getBlockState(pos.above()).isAir() && chunk.getBlockState(pos.above(2)).isAir(); ++ : chunk.getBlockState(pos).canEntityDestroy(level, pos, this.removerMob) && chunk.getBlockState(pos).is(this.blockToRemove) && chunk.getBlockState(pos.above()).isAir() && chunk.getBlockState(pos.above(2)).isAir(); } + } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch index f716a1089b..771a960db6 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java +++ b/net/minecraft/world/entity/ai/goal/RunAroundLikeCrazyGoal.java @@ -58,7 +_,7 @@ - if (entity instanceof Player player) { - int i = this.horse.getTemper(); - int j = this.horse.getMaxTemper(); -- if (j > 0 && this.horse.getRandom().nextInt(j) < i) { -+ if (j > 0 && this.horse.getRandom().nextInt(j) < i && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(horse, (Player)entity)) { + if (passenger instanceof Player player) { + int temper = this.horse.getTemper(); + int maxTemper = this.horse.getMaxTemper(); +- if (maxTemper > 0 && this.horse.getRandom().nextInt(maxTemper) < temper) { ++ if (maxTemper > 0 && this.horse.getRandom().nextInt(maxTemper) < temper && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(horse, player)) { this.horse.tameWithName(player); return; } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch index a91e71107a..e2a94beb01 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/goal/target/HurtByTargetGoal.java.patch @@ -3,11 +3,11 @@ @@ -83,6 +_,10 @@ } - mob = (Mob)iterator.next(); + other = (Mob)var5.next(); + // Fix NPE if modders do things vanilla doesn't expect. https://github.com/MinecraftForge/MinecraftForge/issues/7853 + if (this.mob.getLastHurtByMob() == null) + return; + - if (this.mob != mob - && mob.getTarget() == null - && (!(this.mob instanceof TamableAnimal) || ((TamableAnimal)this.mob).getOwner() == ((TamableAnimal)mob).getOwner()) + if (this.mob != other + && other.getTarget() == null + && (!(this.mob instanceof TamableAnimal) || ((TamableAnimal)this.mob).getOwner() == ((TamableAnimal)other).getOwner()) diff --git a/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch index 8d2fdb7964..42a450f176 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/navigation/PathNavigation.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/entity/ai/navigation/PathNavigation.java +++ b/net/minecraft/world/entity/ai/navigation/PathNavigation.java -@@ -242,10 +_,10 @@ - Vec3 vec3 = this.getTempMobPos(); +@@ -244,10 +_,10 @@ + Vec3 mobPos = this.getTempMobPos(); this.maxDistanceToWaypoint = this.mob.getBbWidth() > 0.75F ? this.mob.getBbWidth() / 2.0F : 0.75F - this.mob.getBbWidth() / 2.0F; - Vec3i vec3i = this.path.getNextNodePos(); -- double d0 = Math.abs(this.mob.getX() - (vec3i.getX() + 0.5)); -+ double d0 = Math.abs(this.mob.getX() - ((double)vec3i.getX() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 - double d1 = Math.abs(this.mob.getY() - vec3i.getY()); -- double d2 = Math.abs(this.mob.getZ() - (vec3i.getZ() + 0.5)); -- boolean flag = d0 < this.maxDistanceToWaypoint && d2 < this.maxDistanceToWaypoint && d1 < 1.0; -+ double d2 = Math.abs(this.mob.getZ() - ((double)vec3i.getZ() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 -+ boolean flag = d0 <= (double)this.maxDistanceToWaypoint && d2 <= (double)this.maxDistanceToWaypoint && d1 < 1.0D; //Forge: Fix MC-94054 - if (flag || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(vec3)) { + Vec3i currentNodePos = this.path.getNextNodePos(); +- double xDistance = Math.abs(this.mob.getX() - (currentNodePos.getX() + 0.5)); ++ double xDistance = Math.abs(this.mob.getX() - ((double)currentNodePos.getX() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 + double yDistance = Math.abs(this.mob.getY() - currentNodePos.getY()); +- double zDistance = Math.abs(this.mob.getZ() - (currentNodePos.getZ() + 0.5)); +- boolean isCloseEnoughToCurrentNode = xDistance < this.maxDistanceToWaypoint && zDistance < this.maxDistanceToWaypoint && yDistance < 1.0; ++ double zDistance = Math.abs(this.mob.getZ() - ((double)currentNodePos.getZ() + (this.mob.getBbWidth() + 1) / 2D)); //Forge: Fix MC-94054 ++ boolean isCloseEnoughToCurrentNode = xDistance <= (double)this.maxDistanceToWaypoint && zDistance <= (double)this.maxDistanceToWaypoint && yDistance < 1.0D; //Forge: Fix MC-94054 + if (isCloseEnoughToCurrentNode || this.canCutCorner(this.path.getNextNode().type) && this.shouldTargetNextNodeInDirection(mobPos)) { this.path.advance(); } diff --git a/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch index 625ea6aecc..ae05737f6b 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/village/VillageSiege.java.patch @@ -1,9 +1,9 @@ --- a/net/minecraft/world/entity/ai/village/VillageSiege.java +++ b/net/minecraft/world/entity/ai/village/VillageSiege.java @@ -78,7 +_,10 @@ - this.spawnX = blockpos.getX() + Mth.floor(Mth.cos(f) * 32.0F); - this.spawnY = blockpos.getY(); - this.spawnZ = blockpos.getZ() + Mth.floor(Mth.sin(f) * 32.0F); + this.spawnX = center.getX() + Mth.floor(Mth.cos(angle) * 32.0F); + this.spawnY = center.getY(); + this.spawnZ = center.getZ() + Mth.floor(Mth.sin(angle) * 32.0F); - if (this.findRandomSpawnPos(level, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)) != null) { + Vec3 siegeLocation = this.findRandomSpawnPos(level, new BlockPos(this.spawnX, this.spawnY, this.spawnZ)); + if (siegeLocation != null) { @@ -13,11 +13,11 @@ this.zombiesToSpawn = 20; break; @@ -98,7 +_,7 @@ - if (vec3 != null) { + if (spawnPos != null) { Zombie zombie; try { - zombie = new Zombie(level); + zombie = EntityType.ZOMBIE.create(level, EntitySpawnReason.EVENT); //Forge: Direct Initialization is deprecated, use EntityType. zombie.finalizeSpawn(level, level.getCurrentDifficultyAt(zombie.blockPosition()), EntitySpawnReason.EVENT, null); - } catch (Exception exception) { - LOGGER.warn("Failed to create zombie for village siege at {}", vec3, exception); + } catch (Exception var5) { + LOGGER.warn("Failed to create zombie for village siege at {}", spawnPos, var5); diff --git a/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch b/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch index a7cda5bfac..2d097ed54a 100644 --- a/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/ai/village/poi/PoiTypes.java.patch @@ -11,9 +11,9 @@ return ImmutableSet.copyOf(block.getStateDefinition().getPossibleStates()); @@ -95,7 +_,6 @@ ) { - PoiType poitype = new PoiType(matchingStates, maxTickets, validRange); - Registry.register(registry, id, poitype); + PoiType value = new PoiType(matchingStates, maxTickets, validRange); + Registry.register(registry, id, value); - registerBlockStates(registry.getOrThrow(id), matchingStates); - return poitype; + return value; } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch index 400ed425de..62dbc2071d 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/Animal.java.patch @@ -3,10 +3,10 @@ @@ -208,6 +_,17 @@ public void spawnChildFromBreeding(final ServerLevel level, final Animal partner) { - AgeableMob ageablemob = this.getBreedOffspring(level, partner); -+ final var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(this, partner, ageablemob); + AgeableMob offspring = this.getBreedOffspring(level, partner); ++ final var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(this, partner, offspring); + final boolean cancelled = net.minecraftforge.event.entity.living.BabyEntitySpawnEvent.BUS.post(event); -+ ageablemob = event.getChild(); ++ offspring = event.getChild(); + if (cancelled) { + //Reset the "inLove" state for the animals + this.setAge(6000); @@ -15,6 +15,6 @@ + partner.resetLove(); + return; + } - if (ageablemob != null) { - ageablemob.setBaby(true); - ageablemob.snapTo(this.getX(), this.getY(), this.getZ(), 0.0F, 0.0F); + if (offspring != null) { + offspring.setBaby(true); + offspring.snapTo(this.getX(), this.getY(), this.getZ(), 0.0F, 0.0F); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch index 6317c63315..ab3a3e43d2 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/allay/Allay.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/entity/animal/allay/Allay.java @@ -336,7 +_,7 @@ public boolean wantsToPickUp(final ServerLevel level, final ItemStack itemStack) { - ItemStack itemstack = this.getItemInHand(InteractionHand.MAIN_HAND); - return !itemstack.isEmpty() + ItemStack itemInHand = this.getItemInHand(InteractionHand.MAIN_HAND); + return !itemInHand.isEmpty() - && level.getGameRules().get(GameRules.MOB_GRIEFING) + && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this) && this.inventory.canAddItem(itemStack) - && this.allayConsidersItemEqual(itemstack, itemStack); + && this.allayConsidersItemEqual(itemInHand, itemStack); } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch index 0122e94011..722d03a4dc 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/bee/Bee.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/bee/Bee.java +++ b/net/minecraft/world/entity/animal/bee/Bee.java -@@ -483,7 +_,9 @@ +@@ -482,7 +_,9 @@ if (this.hivePos == null) { return null; } else { @@ -11,7 +11,7 @@ } } -@@ -649,13 +_,22 @@ +@@ -648,13 +_,22 @@ } @Override diff --git a/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch index 5f90c66e95..e03641f8c6 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/cow/MushroomCow.java.patch @@ -2,12 +2,12 @@ +++ b/net/minecraft/world/entity/animal/cow/MushroomCow.java @@ -114,7 +_,7 @@ - this.playSound(soundevent, 1.0F, 1.0F); + this.playSound(milkSound, 1.0F, 1.0F); return InteractionResult.SUCCESS; -- } else if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { -+ } else if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { - if (this.level() instanceof ServerLevel serverlevel) { - this.shear(serverlevel, SoundSource.PLAYERS, itemstack); +- } else if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { ++ } else if (false && itemStack.is(Items.SHEARS) && this.readyForShearing()) { + if (this.level() instanceof ServerLevel level) { + this.shear(level, SoundSource.PLAYERS, itemStack); this.gameEvent(GameEvent.SHEAR, player); @@ -170,15 +_,26 @@ @@ -42,7 +42,7 @@ @@ -254,6 +_,15 @@ } - return mushroomcow$variant2; + return babyVariant; + } + + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch index 8db3819f1d..dce7703313 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/equine/AbstractHorse.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/equine/AbstractHorse.java +++ b/net/minecraft/world/entity/animal/equine/AbstractHorse.java -@@ -144,6 +_,7 @@ +@@ -143,6 +_,7 @@ } this.addBehaviourGoals(); @@ -8,7 +8,7 @@ } protected void addBehaviourGoals() { -@@ -279,16 +_,19 @@ +@@ -278,16 +_,19 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { @@ -20,38 +20,38 @@ this.playSound(this.isBaby() ? SoundEvents.HORSE_LAND_BABY : SoundEvents.HORSE_LAND, 0.4F, 1.0F); } -- int i = this.calculateFallDamage(fallDistance, damageModifier); -+ int i = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); - if (i <= 0) { +- int dmg = this.calculateFallDamage(fallDistance, damageModifier); ++ int dmg = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); + if (dmg <= 0) { return false; } else { - this.hurt(damageSource, i); + this.hurt(damageSource, dmg); - this.propagateFallToPassengers(fallDistance, damageModifier, damageSource); + this.propagateFallToPassengers(event.getDistance(), event.getDamageMultiplier(), damageSource); this.playBlockFallSound(); return true; } -@@ -344,9 +_,9 @@ +@@ -343,9 +_,9 @@ protected void playStepSound(final BlockPos pos, final BlockState blockState) { if (!blockState.liquid()) { - BlockState blockstate = this.level().getBlockState(pos.above()); -- SoundType soundtype = blockState.getSoundType(); -+ SoundType soundtype = blockState.getSoundType(level(), pos, this); - if (blockstate.is(Blocks.SNOW)) { -- soundtype = blockstate.getSoundType(); -+ soundtype = blockstate.getSoundType(level(), pos.above(), this); + BlockState aboveState = this.level().getBlockState(pos.above()); +- SoundType soundType = blockState.getSoundType(); ++ SoundType soundType = blockState.getSoundType(level(), pos, this); + if (aboveState.is(Blocks.SNOW)) { +- soundType = aboveState.getSoundType(); ++ soundType = aboveState.getSoundType(level(), pos.above(), this); } if (this.isVehicle() && this.canGallop) { -@@ -778,6 +_,7 @@ - float f1 = Mth.cos(this.getYRot() * (float) (Math.PI / 180.0)); - this.setDeltaMovement(this.getDeltaMovement().add(-0.4F * f * amount, 0.0, 0.4F * f1 * amount)); +@@ -777,6 +_,7 @@ + float cos = Mth.cos(this.getYRot() * (float) (Math.PI / 180.0)); + this.setDeltaMovement(this.getDeltaMovement().add(-0.4F * sin * amount, 0.0, 0.4F * cos * amount)); } + net.minecraftforge.common.ForgeHooks.onLivingJump(this); } protected void playJumpSound() { -@@ -1028,6 +_,26 @@ +@@ -1027,6 +_,26 @@ public boolean hasInventoryChanged(final Container oldInventory) { return this.inventory != oldInventory; diff --git a/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch index ce0078bec2..ad486fff4a 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/equine/Llama.java.patch @@ -4,16 +4,16 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { -- int i = this.calculateFallDamage(fallDistance, damageModifier); +- int dmg = this.calculateFallDamage(fallDistance, damageModifier); + var event = net.minecraftforge.event.ForgeEventFactory.onLivingFall(this, fallDistance, damageModifier); + if (event == null) return false; -+ int i = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); - if (i <= 0) { ++ int dmg = this.calculateFallDamage(event.getDistance(), event.getDamageMultiplier()); + if (dmg <= 0) { return false; } else { - if (fallDistance >= 6.0) { + if (event.getDistance() >= 6.0) { - this.hurt(damageSource, i); + this.hurt(damageSource, dmg); - this.propagateFallToPassengers(fallDistance, damageModifier, damageSource); + this.propagateFallToPassengers(event.getDistance(), event.getDamageMultiplier(), damageSource); } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch index 09b0dbd893..8fed45b75d 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/equine/SkeletonTrapGoal.java.patch @@ -3,14 +3,14 @@ @@ -31,6 +_,13 @@ @Override public void tick() { - ServerLevel serverlevel = (ServerLevel)this.horse.level(); + ServerLevel level = (ServerLevel)this.horse.level(); + // Forge: Trigger the trap in a tick task to avoid crashes when mods add goals to skeleton horses + // (MC-206338/Forge PR #7509) -+ serverlevel.getServer().schedule(serverlevel.getServer().wrapRunnable(() -> this.convert(serverlevel))); ++ level.getServer().schedule(level.getServer().wrapRunnable(() -> this.convert(level))); + } + -+ private void convert(ServerLevel serverlevel) { ++ private void convert(ServerLevel level) { + if (!this.horse.isAlive()) return; - DifficultyInstance difficultyinstance = serverlevel.getCurrentDifficultyAt(this.horse.blockPosition()); + DifficultyInstance difficulty = level.getCurrentDifficultyAt(this.horse.blockPosition()); this.horse.setTrap(false); this.horse.setTamed(true); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch index f667dd8ac5..7974832cc4 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/feline/Cat.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/feline/Cat.java +++ b/net/minecraft/world/entity/animal/feline/Cat.java -@@ -474,7 +_,7 @@ +@@ -473,7 +_,7 @@ } private void tryToTame(final Player player) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch index 89727d4951..650478cc0a 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/feline/Ocelot.java.patch @@ -1,8 +1,8 @@ --- a/net/minecraft/world/entity/animal/feline/Ocelot.java +++ b/net/minecraft/world/entity/animal/feline/Ocelot.java @@ -161,7 +_,7 @@ - if ((this.temptGoal == null || this.temptGoal.isRunning()) && !this.isTrusting() && this.isFood(itemstack) && player.distanceToSqr(this) < 9.0) { - this.usePlayerItem(player, hand, itemstack); + if ((this.temptGoal == null || this.temptGoal.isRunning()) && !this.isTrusting() && this.isFood(itemStack) && player.distanceToSqr(this) < 9.0) { + this.usePlayerItem(player, hand, itemStack); if (!this.level().isClientSide()) { - if (this.random.nextInt(3) == 0) { + if (this.random.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, player)) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch index 93b2230e0e..051a109fff 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/fox/Fox.java.patch @@ -3,10 +3,10 @@ @@ -878,6 +_,17 @@ @Override protected void breed() { - Fox fox = (Fox)this.animal.getBreedOffspring(this.level, this.partner); -+ var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(animal, partner, fox); + Fox offspring = (Fox)this.animal.getBreedOffspring(this.level, this.partner); ++ var event = new net.minecraftforge.event.entity.living.BabyEntitySpawnEvent(animal, partner, offspring); + var eventWasCancelled = net.minecraftforge.event.entity.living.BabyEntitySpawnEvent.BUS.post(event); -+ fox = (Fox)event.getChild(); ++ offspring = (Fox)event.getChild(); + if (eventWasCancelled) { + //Reset the "inLove" state for the animals + this.animal.setAge(6000); @@ -15,18 +15,18 @@ + this.partner.resetLove(); + return; + } - if (fox != null) { - ServerPlayer serverplayer = this.animal.getLoveCause(); - ServerPlayer serverplayer1 = this.partner.getLoveCause(); + if (offspring != null) { + ServerPlayer animalLoveCause = this.animal.getLoveCause(); + ServerPlayer partnerLoveCause = this.partner.getLoveCause(); @@ -956,7 +_,7 @@ } protected void onReachedTarget() { - if (getServerLevel(Fox.this.level()).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(Fox.this.level()), Fox.this)) { - BlockState blockstate = Fox.this.level().getBlockState(this.blockPos); - if (blockstate.is(Blocks.SWEET_BERRY_BUSH)) { - this.pickSweetBerries(blockstate); + BlockState state = Fox.this.level().getBlockState(this.blockPos); + if (state.is(Blocks.SWEET_BERRY_BUSH)) { + this.pickSweetBerries(state); @@ -1016,7 +_,7 @@ @Override diff --git a/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch index e561961649..e513a6bc67 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/golem/CopperGolem.java.patch @@ -4,15 +4,15 @@ } Level level = this.level(); -- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: Moved to onSheared - if (level instanceof ServerLevel serverlevel) { - this.shear(serverlevel, SoundSource.PLAYERS, itemstack); +- if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemStack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: Moved to onSheared + if (level instanceof ServerLevel serverLevel) { + this.shear(serverLevel, SoundSource.PLAYERS, itemStack); this.gameEvent(GameEvent.SHEAR, player); @@ -427,6 +_,18 @@ - ItemStack itemstack = this.getItemBySlot(EQUIPMENT_SLOT_ANTENNA); + ItemStack itemStack = this.getItemBySlot(EQUIPMENT_SLOT_ANTENNA); this.setItemSlot(EQUIPMENT_SLOT_ANTENNA, ItemStack.EMPTY); - this.spawnAtLocation(level, itemstack, 1.5F); + this.spawnAtLocation(level, itemStack, 1.5F); + } + + @Override diff --git a/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch index b8e6e513aa..efa1ec8305 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/golem/SnowGolem.java.patch @@ -10,31 +10,31 @@ private static final byte PUMPKIN_FLAG = 16; private static final boolean DEFAULT_PUMPKIN = true; @@ -95,7 +_,7 @@ - this.hurtServer(serverlevel, this.damageSources().onFire(), 1.0F); + this.hurtServer(serverLevel, this.damageSources().onFire(), 1.0F); } -- if (!serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this)) { +- if (!serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this)) { return; } @@ -106,7 +_,7 @@ - int k = Mth.floor(this.getY()); - int l = Mth.floor(this.getZ() + (i / 2 % 2 * 2 - 1) * 0.25F); - BlockPos blockpos = new BlockPos(j, k, l); -- if (this.level().getBlockState(blockpos).isAir() && blockstate.canSurvive(this.level(), blockpos)) { -+ if (this.level().isEmptyBlock(blockpos) && blockstate.canSurvive(this.level(), blockpos)) { - this.level().setBlockAndUpdate(blockpos, blockstate); - this.level().gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(this, blockstate)); + int yy = Mth.floor(this.getY()); + int zz = Mth.floor(this.getZ() + (i / 2 % 2 * 2 - 1) * 0.25F); + BlockPos snowPos = new BlockPos(xx, yy, zz); +- if (this.level().getBlockState(snowPos).isAir() && snow.canSurvive(this.level(), snowPos)) { ++ if (this.level().isEmptyBlock(snowPos) && snow.canSurvive(this.level(), snowPos)) { + this.level().setBlockAndUpdate(snowPos, snow); + this.level().gameEvent(GameEvent.BLOCK_PLACE, snowPos, GameEvent.Context.of(this, snow)); } @@ -136,7 +_,7 @@ @Override protected InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemstack = player.getItemInHand(hand); -- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { //Forge: Moved to onSheared - if (this.level() instanceof ServerLevel serverlevel) { - this.shear(serverlevel, SoundSource.PLAYERS, itemstack); + ItemStack itemStack = player.getItemInHand(hand); +- if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemStack.is(Items.SHEARS) && this.readyForShearing()) { //Forge: Moved to onSheared + if (this.level() instanceof ServerLevel level) { + this.shear(level, SoundSource.PLAYERS, itemStack); this.gameEvent(GameEvent.SHEAR, player); @@ -193,4 +_,17 @@ public Vec3 getLeashOffset() { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch index 5696c2c99f..ae308792f5 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/parrot/Parrot.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/animal/parrot/Parrot.java +++ b/net/minecraft/world/entity/animal/parrot/Parrot.java -@@ -269,7 +_,7 @@ +@@ -268,7 +_,7 @@ } if (!this.level().isClientSide()) { diff --git a/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch index 819e5bdb7f..41465ec44a 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/pig/Pig.java.patch @@ -6,10 +6,10 @@ public void thunderHit(final ServerLevel level, final LightningBolt lightningBolt) { - if (level.getDifficulty() != Difficulty.PEACEFUL) { + if (level.getDifficulty() != Difficulty.PEACEFUL && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.ZOMBIFIED_PIGLIN, (timer) -> {})) { - ZombifiedPiglin zombifiedpiglin = this.convertTo(EntityType.ZOMBIFIED_PIGLIN, ConversionParams.single(this, false, true), zp -> { + ZombifiedPiglin zombifiedPiglin = this.convertTo(EntityType.ZOMBIFIED_PIGLIN, ConversionParams.single(this, false, true), zp -> { zp.populateDefaultEquipmentSlots(this.getRandom(), level.getCurrentDifficultyAt(this.blockPosition())); zp.setPersistenceRequired(); + net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zp); }); - if (zombifiedpiglin == null) { + if (zombifiedPiglin == null) { super.thunderHit(level, lightningBolt); diff --git a/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch index 2ec80e1736..112bce3741 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/rabbit/Rabbit.java.patch @@ -12,9 +12,9 @@ @@ -653,7 +_,7 @@ @Override protected boolean isValidTarget(final LevelReader level, final BlockPos pos) { - BlockState blockstate = level.getBlockState(pos); -- if (blockstate.is(BlockTags.SUPPORTS_CROPS) && this.wantsToRaid && !this.canRaid) { -+ if (blockstate.getBlock() instanceof net.minecraft.world.level.block.FarmlandBlock && this.wantsToRaid && !this.canRaid) { - blockstate = level.getBlockState(pos.above()); - if (blockstate.getBlock() instanceof CarrotBlock carrotblock && carrotblock.isMaxAge(blockstate)) { + BlockState state = level.getBlockState(pos); +- if (state.is(BlockTags.SUPPORTS_CROPS) && this.wantsToRaid && !this.canRaid) { ++ if ((state.is(BlockTags.SUPPORTS_CROPS) || state.getBlock() instanceof net.minecraft.world.level.block.FarmlandBlock) && this.wantsToRaid && !this.canRaid) { + state = level.getBlockState(pos.above()); + if (state.getBlock() instanceof CarrotBlock carrotBlock && carrotBlock.isMaxAge(state)) { this.canRaid = true; diff --git a/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch index 9b11fcd9f6..f55484dd3e 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/sheep/Sheep.java.patch @@ -3,11 +3,11 @@ @@ -137,7 +_,7 @@ @Override public InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemstack = player.getItemInHand(hand); -- if (itemstack.is(Items.SHEARS)) { -+ if (false && itemstack.is(Items.SHEARS)) { // Forge: Moved to onSheared - if (this.level() instanceof ServerLevel serverlevel && this.readyForShearing()) { - this.shear(serverlevel, SoundSource.PLAYERS, itemstack); + ItemStack itemStack = player.getItemInHand(hand); +- if (itemStack.is(Items.SHEARS)) { ++ if (false && itemStack.is(Items.SHEARS)) { // Forge: Moved to onSheared + if (this.level() instanceof ServerLevel level && this.readyForShearing()) { + this.shear(level, SoundSource.PLAYERS, itemStack); this.gameEvent(GameEvent.SHEAR, player); @@ -153,12 +_,27 @@ @@ -35,8 +35,8 @@ + // double indented to make the patch look nicer + for (var drop : items) { for (int i = 0; i < drop.getCount(); i++) { - ItemEntity itementity = this.spawnAtLocation(l, drop.copyWithCount(1), 1.0F); - if (itementity != null) { + ItemEntity entity = this.spawnAtLocation(l, drop.copyWithCount(1), 1.0F); + if (entity != null) { @@ -173,8 +_,14 @@ } } diff --git a/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch b/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch index c33806747a..24a75907c9 100644 --- a/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/animal/sniffer/Sniffer.java.patch @@ -4,8 +4,8 @@ if (this.tickCount % 10 == 0) { this.level() .playLocalSound( -- this.getX(), this.getY(), this.getZ(), blockstate.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false -+ this.getX(), this.getY(), this.getZ(), blockstate.getSoundType(level(), blockpos.below(), this).getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false +- this.getX(), this.getY(), this.getZ(), stateBelow.getSoundType().getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false ++ this.getX(), this.getY(), this.getZ(), stateBelow.getSoundType(level(), head.below(), this).getHitSound(), this.getSoundSource(), 0.5F, 0.5F, false ); } } diff --git a/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch b/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch index c3a9d284a1..26800b52d5 100644 --- a/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/boss/enderdragon/EnderDragon.java.patch @@ -43,32 +43,32 @@ this.processFlappingMovement(); if (this.level().isClientSide()) { this.setHealth(this.getHealth()); -@@ -438,7 +_,7 @@ - BlockPos blockpos = new BlockPos(k1, l1, i2); - BlockState blockstate = level.getBlockState(blockpos); - if (!blockstate.isAir() && !blockstate.is(BlockTags.DRAGON_TRANSPARENT)) { -- if (level.getGameRules().get(GameRules.MOB_GRIEFING) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { -+ if (net.minecraftforge.common.ForgeHooks.canEntityDestroy(level, blockpos, this) && !blockstate.is(BlockTags.DRAGON_IMMUNE)) { - flag1 = level.removeBlock(blockpos, false) || flag1; +@@ -434,7 +_,7 @@ + BlockPos blockPos = new BlockPos(x, y, z); + BlockState state = level.getBlockState(blockPos); + if (!state.isAir() && !state.is(BlockTags.DRAGON_TRANSPARENT)) { +- if (level.getGameRules().get(GameRules.MOB_GRIEFING) && !state.is(BlockTags.DRAGON_IMMUNE)) { ++ if (net.minecraftforge.common.ForgeHooks.canEntityDestroy(level, blockPos, this) && !state.is(BlockTags.DRAGON_IMMUNE)) { + destroyedBlock = level.removeBlock(blockPos, false) || destroyedBlock; } else { - flag = true; -@@ -537,7 +_,8 @@ + hitWall = true; +@@ -535,7 +_,8 @@ - if (this.level() instanceof ServerLevel serverlevel) { - if (this.dragonDeathTime > 150 && this.dragonDeathTime % 5 == 0 && serverlevel.getGameRules().get(GameRules.MOB_DROPS)) { -- ExperienceOrb.award(serverlevel, this.position(), Mth.floor(i * 0.08F)); -+ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)i * 0.08F)); -+ ExperienceOrb.award(serverlevel, this.position(), award); + if (this.level() instanceof ServerLevel level) { + if (this.dragonDeathTime > 150 && this.dragonDeathTime % 5 == 0 && level.getGameRules().get(GameRules.MOB_DROPS)) { +- ExperienceOrb.award(level, this.position(), Mth.floor(xpCount * 0.08F)); ++ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)xpCount * 0.08F)); ++ ExperienceOrb.award(level, this.position(), award); } if (this.dragonDeathTime == 1 && !this.isSilent()) { -@@ -555,7 +_,8 @@ +@@ -553,7 +_,8 @@ - if (this.dragonDeathTime >= 200 && this.level() instanceof ServerLevel serverlevel1) { - if (serverlevel1.getGameRules().get(GameRules.MOB_DROPS)) { -- ExperienceOrb.award(serverlevel1, this.position(), Mth.floor(i * 0.2F)); -+ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)i * 0.2F)); -+ ExperienceOrb.award(serverlevel1, this.position(), award); + if (this.dragonDeathTime >= 200 && this.level() instanceof ServerLevel level) { + if (level.getGameRules().get(GameRules.MOB_DROPS)) { +- ExperienceOrb.award(level, this.position(), Mth.floor(xpCount * 0.2F)); ++ int award = net.minecraftforge.event.ForgeEventFactory.getExperienceDrop(this, this.getUnlimitedLastHurtByPlayer(), Mth.floor((float)xpCount * 0.2F)); ++ ExperienceOrb.award(level, this.position(), award); } if (this.dragonFight != null) { @@ -77,9 +77,9 @@ public void recreateFromPacket(final ClientboundAddEntityPacket packet) { super.recreateFromPacket(packet); + if (true) return; // Forge: Fix MC-158205: Moved into setId() - EnderDragonPart[] aenderdragonpart = this.getSubEntities(); + EnderDragonPart[] subEntities = this.getSubEntities(); - for (int i = 0; i < aenderdragonpart.length; i++) { + for (int i = 0; i < subEntities.length; i++) { @@ -876,5 +_,15 @@ @Override protected float sanitizeScale(final float scale) { diff --git a/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch b/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch index be377916c3..a7a2fe46e7 100644 --- a/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/boss/wither/WitherBoss.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/world/entity/boss/wither/WitherBoss.java +++ b/net/minecraft/world/entity/boss/wither/WitherBoss.java -@@ -323,7 +_,7 @@ +@@ -320,7 +_,7 @@ if (this.destroyBlocksTick > 0) { this.destroyBlocksTick--; - if (this.destroyBlocksTick == 0 && level.getGameRules().get(GameRules.MOB_GRIEFING)) { + if (this.destroyBlocksTick == 0 && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, this)) { - boolean flag = false; - int l = Mth.floor(this.getBbWidth() / 2.0F + 1.0F); - int i1 = Mth.floor(this.getBbHeight()); -@@ -332,7 +_,7 @@ - this.getBlockX() - l, this.getBlockY(), this.getBlockZ() - l, this.getBlockX() + l, this.getBlockY() + i1, this.getBlockZ() + l + boolean destroyed = false; + int width = Mth.floor(this.getBbWidth() / 2.0F + 1.0F); + int height = Mth.floor(this.getBbHeight()); +@@ -334,7 +_,7 @@ + this.getBlockZ() + width )) { - BlockState blockstate = level.getBlockState(blockpos); -- if (canDestroy(blockstate)) { -+ if (blockstate.canEntityDestroy(level, blockpos, this) && net.minecraftforge.event.ForgeEventFactory.onEntityDestroyBlock(this, blockpos, blockstate)) { - flag = level.destroyBlock(blockpos, true, this) || flag; + BlockState state = level.getBlockState(blockPos); +- if (canDestroy(state)) { ++ if (state.canEntityDestroy(level, blockPos, this) && net.minecraftforge.event.ForgeEventFactory.onEntityDestroyBlock(this, blockPos, state)) { + destroyed = level.destroyBlock(blockPos, true, this) || destroyed; } } -@@ -351,6 +_,10 @@ +@@ -353,6 +_,10 @@ } } diff --git a/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch index 5921b6ac02..cc145b6837 100644 --- a/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/decoration/HangingEntity.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/entity/decoration/HangingEntity.java @@ -85,6 +_,8 @@ } else { - boolean flag = BlockPos.betweenClosedStream(this.calculateSupportBox()).allMatch(pos -> { - BlockState blockstate = this.level().getBlockState(pos); + boolean isSupported = BlockPos.betweenClosedStream(this.calculateSupportBox()).allMatch(pos -> { + BlockState state = this.level().getBlockState(pos); + if (net.minecraft.world.level.block.Block.canSupportCenter(this.level(), pos, this.getDirection())) + return true; - return blockstate.isSolid() || DiodeBlock.isDiode(blockstate); + return state.isSolid() || DiodeBlock.isDiode(state); }); - return flag && this.canCoexist(false); + return isSupported && this.canCoexist(false); diff --git a/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch index 3225ebca83..023ddf2829 100644 --- a/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java +++ b/net/minecraft/world/entity/decoration/LeashFenceKnotEntity.java -@@ -73,7 +_,7 @@ +@@ -75,7 +_,7 @@ if (this.level().isClientSide()) { return InteractionResult.SUCCESS; } else { - if (player.getItemInHand(hand).is(Items.SHEARS)) { + if (player.getItemInHand(hand).canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { - InteractionResult interactionresult = super.interact(player, hand, location); - if (interactionresult instanceof InteractionResult.Success interactionresult$success && interactionresult$success.wasItemInteraction()) { - return interactionresult; + InteractionResult result = super.interact(player, hand, location); + if (result instanceof InteractionResult.Success success && success.wasItemInteraction()) { + return result; diff --git a/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch index 8f83fb5675..6c13e6ac93 100644 --- a/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/item/FallingBlockEntity.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/entity/item/FallingBlockEntity.java +++ b/net/minecraft/world/entity/item/FallingBlockEntity.java -@@ -158,7 +_,7 @@ - if (this.level() instanceof ServerLevel serverlevel && (this.isAlive() || this.forceTickAfterTeleportToDuplicate)) { - BlockPos blockpos = this.blockPosition(); - boolean flag = this.blockState.getBlock() instanceof ConcretePowderBlock; -- boolean flag1 = flag && this.level().getFluidState(blockpos).is(FluidTags.WATER); -+ boolean flag1 = flag && this.blockState.canBeHydrated(this.level(), blockpos, this.level().getFluidState(blockpos), blockpos); - double d0 = this.getDeltaMovement().lengthSqr(); - if (flag && d0 > 1.0) { - BlockHitResult blockhitresult = this.level() -@@ -167,7 +_,7 @@ +@@ -157,7 +_,7 @@ + if (this.level() instanceof ServerLevel serverLevel && (this.isAlive() || this.forceTickAfterTeleportToDuplicate)) { + BlockPos pos = this.blockPosition(); + boolean isConcrete = this.blockState.getBlock() instanceof ConcretePowderBlock; +- boolean isStuckInWater = isConcrete && this.level().getFluidState(pos).is(FluidTags.WATER); ++ boolean isStuckInWater = isConcrete && this.blockState.canBeHydrated(this.level(), pos, this.level().getFluidState(pos), pos); + double moveVec = this.getDeltaMovement().lengthSqr(); + if (isConcrete && moveVec > 1.0) { + BlockHitResult clip = this.level() +@@ -166,7 +_,7 @@ new Vec3(this.xo, this.yo, this.zo), this.position(), ClipContext.Block.COLLIDER, ClipContext.Fluid.SOURCE_ONLY, this ) ); -- if (blockhitresult.getType() != HitResult.Type.MISS && this.level().getFluidState(blockhitresult.getBlockPos()).is(FluidTags.WATER)) { -+ if (blockhitresult.getType() != HitResult.Type.MISS && this.blockState.canBeHydrated(this.level(), blockpos, this.level().getFluidState(blockhitresult.getBlockPos()), blockhitresult.getBlockPos())) { - blockpos = blockhitresult.getBlockPos(); - flag1 = true; +- if (clip.getType() != HitResult.Type.MISS && this.level().getFluidState(clip.getBlockPos()).is(FluidTags.WATER)) { ++ if (clip.getType() != HitResult.Type.MISS && this.blockState.canBeHydrated(this.level(), pos, this.level().getFluidState(clip.getBlockPos()), clip.getBlockPos())) { + pos = clip.getBlockPos(); + isStuckInWater = true; } diff --git a/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch index 5046babcb5..0a632c420a 100644 --- a/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/item/ItemEntity.java.patch @@ -30,7 +30,7 @@ @@ -127,6 +_,10 @@ this.yo = this.getY(); this.zo = this.getZ(); - Vec3 vec3 = this.getDeltaMovement(); + Vec3 oldMovement = this.getDeltaMovement(); + var fluidType = this.getMaxHeightFluidType(); + if (!fluidType.isAir() && !fluidType.isVanilla() && this.getFluidTypeHeight(fluidType) > 0.1F) { + fluidType.setItemMovement(this); @@ -40,14 +40,14 @@ } else if (this.isInLava() && this.getFluidHeight(FluidTags.LAVA) > 0.1F) { @@ -151,7 +_,8 @@ this.applyEffectsFromBlocks(); - float f = 0.98F; + float friction = 0.98F; if (this.onGround()) { -- f = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; +- friction = this.level().getBlockState(this.getBlockPosBelowThatAffectsMyMovement()).getBlock().getFriction() * 0.98F; + BlockPos groundPos = getBlockPosBelowThatAffectsMyMovement(); -+ f = this.level().getBlockState(groundPos).getFriction(level(), groundPos, this) * 0.98F; ++ friction = this.level().getBlockState(groundPos).getFriction(level(), groundPos, this) * 0.98F; } - this.setDeltaMovement(this.getDeltaMovement().multiply(f, 0.98, f)); + this.setDeltaMovement(this.getDeltaMovement().multiply(friction, 0.98, friction)); @@ -183,7 +_,16 @@ } } @@ -96,19 +96,19 @@ public void playerTouch(final Player player) { if (!this.level().isClientSide()) { + if (this.pickupDelay > 0) return; - ItemStack itemstack = this.getItem(); - Item item = itemstack.getItem(); - int i = itemstack.getCount(); -- if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && player.getInventory().add(itemstack)) { + ItemStack itemStack = this.getItem(); + Item item = itemStack.getItem(); + int orgCount = itemStack.getCount(); +- if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && player.getInventory().add(itemStack)) { + int hook = net.minecraftforge.event.ForgeEventFactory.onItemPickup(this, player); + if (hook < 0) return; -+ ItemStack copy = itemstack.copy(); -+ if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && (hook == 1 || i <= 0 || player.getInventory().add(itemstack))) { -+ i = copy.getCount() - itemstack.getCount(); -+ copy.setCount(i); ++ ItemStack copy = itemStack.copy(); ++ if (this.pickupDelay == 0 && (this.target == null || this.target.equals(player.getUUID())) && (hook == 1 || orgCount <= 0 || player.getInventory().add(itemStack))) { ++ orgCount = copy.getCount() - itemStack.getCount(); ++ copy.setCount(orgCount); + net.minecraftforge.event.ForgeEventFactory.firePlayerItemPickupEvent(player, this, copy); - player.take(this, i); - if (itemstack.isEmpty()) { + player.take(this, orgCount); + if (itemStack.isEmpty()) { this.discard(); @@ -421,7 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch index db4a7fd4ce..dd11a4d067 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/CrossbowAttackMob.java.patch @@ -4,12 +4,12 @@ void onCrossbowAttackPerformed(); default void performCrossbowAttack(final LivingEntity body, final float crossbowPower) { -- InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(body, Items.CROSSBOW); -+ InteractionHand interactionhand = ProjectileUtil.getWeaponHoldingHand(body, item -> item instanceof CrossbowItem); - ItemStack itemstack = body.getItemInHand(interactionhand); -- if (itemstack.getItem() instanceof CrossbowItem crossbowitem) { +- InteractionHand hand = ProjectileUtil.getWeaponHoldingHand(body, Items.CROSSBOW); ++ InteractionHand hand = ProjectileUtil.getWeaponHoldingHand(body, item -> item instanceof CrossbowItem); + ItemStack usedItem = body.getItemInHand(hand); +- if (usedItem.getItem() instanceof CrossbowItem crossbow) { + if (body.isHolding(is -> is.getItem() instanceof CrossbowItem)) { -+ var crossbowitem = (CrossbowItem) itemstack.getItem(); - crossbowitem.performShooting( - body.level(), body, interactionhand, itemstack, crossbowPower, 14 - body.level().getDifficulty().getId() * 4, this.getTarget() - ); ++ var crossbow = (CrossbowItem) usedItem.getItem(); + crossbow.performShooting(body.level(), body, hand, usedItem, crossbowPower, 14 - body.level().getDifficulty().getId() * 4, this.getTarget()); + } + diff --git a/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch index 2ab9861e0b..f905ee625d 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/EnderMan.java.patch @@ -5,11 +5,11 @@ @Override public void setTarget(final @Nullable LivingEntity target) { - super.setTarget(target); - AttributeInstance attributeinstance = this.getAttribute(Attributes.MOVEMENT_SPEED); + AttributeInstance movementSpeed = this.getAttribute(Attributes.MOVEMENT_SPEED); if (target == null) { this.targetChangeTime = 0; @@ -135,6 +_,7 @@ - attributeinstance.addTransientModifier(SPEED_MODIFIER_ATTACKING); + movementSpeed.addTransientModifier(SPEED_MODIFIER_ATTACKING); } } + super.setTarget(target); //Forge: Moved down to allow event handlers to write data manager values. @@ -26,18 +26,18 @@ @Override @@ -285,8 +_,10 @@ - boolean flag = blockstate.blocksMotion(); - boolean flag1 = blockstate.getFluidState().is(FluidTags.WATER); - if (flag && !flag1) { + boolean couldStandOn = blockState.blocksMotion(); + boolean isWet = blockState.getFluidState().is(FluidTags.WATER); + if (couldStandOn && !isWet) { + var event = net.minecraftforge.event.ForgeEventFactory.onEnderManTeleport(this, x, y, z); + if (event == null) return false; - Vec3 vec3 = this.position(); -- boolean flag2 = this.randomTeleport(x, y, z, true); -+ boolean flag2 = this.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true); - if (flag2) { - this.level().gameEvent(GameEvent.TELEPORT, vec3, GameEvent.Context.of(this)); + Vec3 oldPos = this.position(); +- boolean result = this.randomTeleport(x, y, z, true); ++ boolean result = this.randomTeleport(event.getTargetX(), event.getTargetY(), event.getTargetZ(), true); + if (result) { + this.level().gameEvent(GameEvent.TELEPORT, oldPos, GameEvent.Context.of(this)); if (!this.isSilent()) { -@@ -443,7 +_,7 @@ +@@ -441,7 +_,7 @@ if (this.enderman.getCarriedBlock() == null) { return false; } else { @@ -46,16 +46,16 @@ ? false : this.enderman.getRandom().nextInt(reducedTickDelay(2000)) == 0; } -@@ -463,7 +_,7 @@ - BlockState blockstate2 = this.enderman.getCarriedBlock(); - if (blockstate2 != null) { - blockstate2 = Block.updateFromNeighbourShapes(blockstate2, this.enderman.level(), blockpos); -- if (this.canPlaceBlock(level, blockpos, blockstate2, blockstate, blockstate1, blockpos1)) { -+ if (this.canPlaceBlock(level, blockpos, blockstate2, blockstate, blockstate1, blockpos1) && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(enderman, net.minecraftforge.common.util.BlockSnapshot.create(level.dimension(), level, blockpos1), net.minecraft.core.Direction.UP)) { - level.setBlock(blockpos, blockstate2, 3); - level.gameEvent(GameEvent.BLOCK_PLACE, blockpos, GameEvent.Context.of(this.enderman, blockstate2)); +@@ -461,7 +_,7 @@ + BlockState carried = this.enderman.getCarriedBlock(); + if (carried != null) { + carried = Block.updateFromNeighbourShapes(carried, this.enderman.level(), pos); +- if (this.canPlaceBlock(level, pos, carried, targetState, belowState, below)) { ++ if (this.canPlaceBlock(level, pos, carried, targetState, belowState, below) && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(enderman, net.minecraftforge.common.util.BlockSnapshot.create(level.dimension(), level, below), net.minecraft.core.Direction.UP)) { + level.setBlock(pos, carried, 3); + level.gameEvent(GameEvent.BLOCK_PLACE, pos, GameEvent.Context.of(this.enderman, carried)); this.enderman.setCarriedBlock(null); -@@ -477,6 +_,7 @@ +@@ -475,6 +_,7 @@ return targetState.isAir() && !belowState.isAir() && !belowState.is(Blocks.BEDROCK) @@ -63,7 +63,7 @@ && belowState.isCollisionShapeFullBlock(level, below) && carried.canSurvive(level, pos) && level.getEntities(this.enderman, AABB.unitCubeFromLowerCorner(Vec3.atLowerCornerOf(pos))).isEmpty(); -@@ -587,7 +_,7 @@ +@@ -585,7 +_,7 @@ if (this.enderman.getCarriedBlock() != null) { return false; } else { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch index d2cb7f7410..e4897bd9a6 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/MagmaCube.java.patch @@ -1,8 +1,8 @@ --- a/net/minecraft/world/entity/monster/MagmaCube.java +++ b/net/minecraft/world/entity/monster/MagmaCube.java @@ -71,17 +_,28 @@ - float f = this.getSize() * 0.1F; - this.setDeltaMovement(vec3.x, this.getJumpPower() + f, vec3.z); + float sizeJumpBoostPower = this.getSize() * 0.1F; + this.setDeltaMovement(movement.x, this.getJumpPower() + sizeJumpBoostPower, movement.z); this.needsSync = true; + net.minecraftforge.common.ForgeHooks.onLivingJump(this); } @@ -16,8 +16,8 @@ + + private void jumpInLiquidInternal(java.util.function.BooleanSupplier isLava, Runnable onSuper) { + if (isLava.getAsBoolean()) { - Vec3 vec3 = this.getDeltaMovement(); - this.setDeltaMovement(vec3.x, 0.22F + this.getSize() * 0.05F, vec3.z); + Vec3 movement = this.getDeltaMovement(); + this.setDeltaMovement(movement.x, 0.22F + this.getSize() * 0.05F, movement.z); this.needsSync = true; } else { - super.jumpInLiquid(type); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch index 00f779df41..9c67dfdcc4 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Monster.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/entity/monster/Monster.java @@ -149,9 +_,9 @@ if (heldWeapon.getItem() instanceof ProjectileWeaponItem) { - Predicate predicate = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); - ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); -- return itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, itemstack.isEmpty() ? new ItemStack(Items.ARROW) : itemstack); + Predicate supportedProjectiles = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); + ItemStack heldProjectile = ProjectileWeaponItem.getHeldProjectile(this, supportedProjectiles); +- return heldProjectile.isEmpty() ? new ItemStack(Items.ARROW) : heldProjectile; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, heldProjectile.isEmpty() ? new ItemStack(Items.ARROW) : heldProjectile); } else { - return ItemStack.EMPTY; + return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, ItemStack.EMPTY); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch index f2abdcf19f..1b01e8ecf1 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Ravager.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/Ravager.java +++ b/net/minecraft/world/entity/monster/Ravager.java @@ -142,7 +_,7 @@ - this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(Mth.lerp(0.1, d1, d0)); + this.getAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(Mth.lerp(0.1, baseValue, maxSpeed)); } -- if (this.level() instanceof ServerLevel serverlevel && this.horizontalCollision && serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (this.level() instanceof ServerLevel serverlevel && this.horizontalCollision && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this)) { - boolean flag = false; - AABB aabb = this.getBoundingBox().inflate(0.2); +- if (this.level() instanceof ServerLevel serverLevel && this.horizontalCollision && serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (this.level() instanceof ServerLevel serverLevel && this.horizontalCollision && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this)) { + boolean destroyedBlock = false; + AABB bb = this.getBoundingBox().inflate(0.2); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch index 50eeb606b7..b1f67664dc 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Shulker.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/monster/Shulker.java +++ b/net/minecraft/world/entity/monster/Shulker.java -@@ -384,6 +_,12 @@ - && this.level().noCollision(this, new AABB(blockpos1).deflate(1.0E-6))) { - Direction direction = this.findAttachableSurface(blockpos1); - if (direction != null) { -+ var event = new net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity(this, blockpos1.getX(), blockpos1.getY(), blockpos1.getZ()); -+ if (net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity.BUS.post(event)) direction = null; -+ blockpos1 = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ()); +@@ -390,6 +_,12 @@ + && this.level().noCollision(this, new AABB(target).deflate(1.0E-6))) { + Direction attachmentDirection = this.findAttachableSurface(target); + if (attachmentDirection != null) { ++ var event = new net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity(this, target.getX(), target.getY(), target.getZ()); ++ if (net.minecraftforge.event.entity.EntityTeleportEvent.EnderEntity.BUS.post(event)) attachmentDirection = null; ++ target = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ()); + } + -+ if (direction != null) { ++ if (attachmentDirection != null) { this.unRide(); - this.setAttachFace(direction); + this.setAttachFace(attachmentDirection); this.playSound(SoundEvents.SHULKER_TELEPORT, 1.0F, 1.0F); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch index 8bf8bfb76f..168299362d 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Silverfish.java.patch @@ -3,18 +3,18 @@ @@ -139,7 +_,7 @@ return false; } else { - RandomSource randomsource = this.mob.getRandom(); -- if (getServerLevel(this.mob).getGameRules().get(GameRules.MOB_GRIEFING) && randomsource.nextInt(reducedTickDelay(10)) == 0) { -+ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.mob.level()), this.mob) && randomsource.nextInt(reducedTickDelay(10)) == 0) { - this.selectedDirection = Direction.getRandom(randomsource); - BlockPos blockpos = BlockPos.containing(this.mob.getX(), this.mob.getY() + 0.5, this.mob.getZ()).relative(this.selectedDirection); - BlockState blockstate = this.mob.level().getBlockState(blockpos); + RandomSource random = this.mob.getRandom(); +- if (getServerLevel(this.mob).getGameRules().get(GameRules.MOB_GRIEFING) && random.nextInt(reducedTickDelay(10)) == 0) { ++ if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(this.mob.level()), this.mob) && random.nextInt(reducedTickDelay(10)) == 0) { + this.selectedDirection = Direction.getRandom(random); + BlockPos pos = BlockPos.containing(this.mob.getX(), this.mob.getY() + 0.5, this.mob.getZ()).relative(this.selectedDirection); + BlockState blockState = this.mob.level().getBlockState(pos); @@ -210,7 +_,7 @@ - BlockState blockstate = level.getBlockState(blockpos1); - Block block = blockstate.getBlock(); + BlockState blockState = level.getBlockState(testPos); + Block block = blockState.getBlock(); if (block instanceof InfestedBlock) { - if (getServerLevel(level).getGameRules().get(GameRules.MOB_GRIEFING)) { + if (net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(getServerLevel(level), this.silverfish)) { - level.destroyBlock(blockpos1, true, this.silverfish); + level.destroyBlock(testPos, true, this.silverfish); } else { - level.setBlock(blockpos1, ((InfestedBlock)block).hostStateByInfested(level.getBlockState(blockpos1)), 3); + level.setBlock(testPos, ((InfestedBlock)block).hostStateByInfested(level.getBlockState(testPos)), 3); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch index d0b40ce95d..d966a2ff1c 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/Slime.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/entity/monster/Slime.java +++ b/net/minecraft/world/entity/monster/Slime.java @@ -139,6 +_,8 @@ - float f = this.getDimensions(this.getPose()).width() * 2.0F; - float f1 = f / 2.0F; + float size = this.getDimensions(this.getPose()).width() * 2.0F; + float radius = size / 2.0F; + // Forge: Don't spawn particles if it's handled by the implementation itself + if (!spawnCustomParticles()) - for (int i = 0; i < f * 16.0F; i++) { - float f2 = this.random.nextFloat() * (float) (Math.PI * 2); - float f3 = this.random.nextFloat() * 0.5F + 0.5F; + for (int i = 0; i < size * 16.0F; i++) { + float dir = this.random.nextFloat() * (float) (Math.PI * 2); + float d = this.random.nextFloat() * 0.5F + 0.5F; @@ -156,6 +_,12 @@ this.wasOnGround = this.onGround(); this.decreaseSquish(); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch index 04e74aca46..eb07ec8326 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/creaking/Creaking.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/creaking/Creaking.java +++ b/net/minecraft/world/entity/monster/creaking/Creaking.java -@@ -458,7 +_,7 @@ - for (Player player : list) { +@@ -466,7 +_,7 @@ + for (Player player : players) { if (this.canAttack(player) && !this.isAlliedTo(player)) { - flag1 = true; -- if ((!flag || LivingEntity.PLAYER_NOT_WEARING_DISGUISE_ITEM.test(player)) -+ if ((!flag || net.minecraftforge.common.ForgeHooks.isNotDisguised(this).test(player)) + hasPotentialTarget = true; +- if ((!active || LivingEntity.PLAYER_NOT_WEARING_DISGUISE_ITEM.test(player)) ++ if ((!active || net.minecraftforge.common.ForgeHooks.isNotDisguised(this).test(player)) && this.isLookingAtMe( player, 0.5, false, true, this.getEyeY(), this.getY() + 0.5 * this.getScale(), (this.getEyeY() + this.getY()) / 2.0 )) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch index 0fc753b705..65f6ef83a6 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/hoglin/Hoglin.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/monster/hoglin/Hoglin.java +++ b/net/minecraft/world/entity/monster/hoglin/Hoglin.java -@@ -141,7 +_,7 @@ +@@ -140,7 +_,7 @@ HoglinAi.updateActivity(this); if (this.isConverting()) { this.timeInOverworld++; @@ -9,7 +9,7 @@ this.makeSound(SoundEvents.HOGLIN_CONVERTED_TO_ZOMBIFIED); this.finishConversion(); } -@@ -237,9 +_,7 @@ +@@ -236,9 +_,7 @@ } private void finishConversion() { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch index adfc9bfb5f..c4be3cb13f 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/illager/Evoker.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/monster/illager/Evoker.java +++ b/net/minecraft/world/entity/monster/illager/Evoker.java -@@ -304,7 +_,7 @@ +@@ -311,7 +_,7 @@ return false; } else { - ServerLevel serverlevel = getServerLevel(Evoker.this.level()); -- if (!serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, Evoker.this)) { + ServerLevel level = getServerLevel(Evoker.this.level()); +- if (!level.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, Evoker.this)) { return false; } else { - List list = serverlevel.getNearbyEntities( + List entities = level.getNearbyEntities( diff --git a/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch index 5dbdd1a45b..09b7d0bd19 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/illager/Illusioner.java.patch @@ -4,13 +4,13 @@ @Override public void performRangedAttack(final LivingEntity target, final float power) { -- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - ItemStack itemstack1 = this.getProjectile(itemstack); - AbstractArrow abstractarrow = ProjectileUtil.getMobArrow(this, itemstack1, power, itemstack); +- ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); ++ ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); + ItemStack projectile = this.getProjectile(bowItem); + AbstractArrow arrow = ProjectileUtil.getMobArrow(this, projectile, power, bowItem); + if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem bow) { -+ abstractarrow = bow.customArrow(abstractarrow); ++ arrow = bow.customArrow(arrow); + } - double d0 = target.getX() - this.getX(); - double d1 = target.getY(0.3333333333333333) - abstractarrow.getY(); - double d2 = target.getZ() - this.getZ(); + double xd = target.getX() - this.getX(); + double yd = target.getY(0.3333333333333333) - arrow.getY(); + double zd = target.getZ() - this.getZ(); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch index 5750557767..e7e7eb7fc8 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java +++ b/net/minecraft/world/entity/monster/piglin/AbstractPiglin.java -@@ -85,7 +_,7 @@ +@@ -84,7 +_,7 @@ this.timeInOverworld = 0; } @@ -9,14 +9,14 @@ this.playConvertedSound(); this.finishConversion(level); } -@@ -106,7 +_,10 @@ +@@ -105,7 +_,10 @@ this.convertTo( EntityType.ZOMBIFIED_PIGLIN, ConversionParams.single(this, true, true), - zombified -> zombified.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)) -+ p_449701_ -> { -+ p_449701_.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)); -+ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, p_449701_); ++ zombified -> { ++ zombified.addEffect(new MobEffectInstance(MobEffects.NAUSEA, 200, 0)); ++ net.minecraftforge.event.ForgeEventFactory.onLivingConvert(this, zombified); + } ); } diff --git a/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch index 73239fc941..f5f126308d 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/piglin/PiglinAi.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/monster/piglin/PiglinAi.java +++ b/net/minecraft/world/entity/monster/piglin/PiglinAi.java -@@ -646,7 +_,7 @@ +@@ -652,7 +_,7 @@ public static boolean isWearingSafeArmor(final LivingEntity livingEntity) { - for (EquipmentSlot equipmentslot : EquipmentSlotGroup.ARMOR) { -- if (livingEntity.getItemBySlot(equipmentslot).is(ItemTags.PIGLIN_SAFE_ARMOR)) { -+ if (livingEntity.getItemBySlot(equipmentslot).makesPiglinsNeutral(livingEntity)) { + for (EquipmentSlot slot : EquipmentSlotGroup.ARMOR) { +- if (livingEntity.getItemBySlot(slot).is(ItemTags.PIGLIN_SAFE_ARMOR)) { ++ if (livingEntity.getItemBySlot(slot).makesPiglinsNeutral(livingEntity)) { return true; } } -@@ -797,7 +_,7 @@ +@@ -803,7 +_,7 @@ } private static boolean hasCrossbow(final LivingEntity body) { @@ -18,7 +18,7 @@ } private static void admireGoldItem(final LivingEntity body) { -@@ -809,7 +_,7 @@ +@@ -815,7 +_,7 @@ } private static boolean isBarterCurrency(final ItemStack itemStack) { diff --git a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch index bc12858ee7..ef78ee63be 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/AbstractSkeleton.java.patch @@ -4,22 +4,22 @@ if (this.level() != null && !this.level().isClientSide()) { this.goalSelector.removeGoal(this.meleeGoal); this.goalSelector.removeGoal(this.bowGoal); -- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - if (itemstack.is(Items.BOW)) { - int i = this.getHardAttackInterval(); +- ItemStack usedWeapon = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); ++ ItemStack usedWeapon = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); + if (usedWeapon.is(Items.BOW)) { + int minAttackInterval = this.getHardAttackInterval(); if (this.level().getDifficulty() != Difficulty.HARD) { @@ -163,9 +_,12 @@ @Override public void performRangedAttack(final LivingEntity target, final float power) { -- ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); -+ ItemStack itemstack = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); - ItemStack itemstack1 = this.getProjectile(itemstack); - AbstractArrow abstractarrow = this.getArrow(itemstack1, power, itemstack); +- ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, Items.BOW)); ++ ItemStack bowItem = this.getItemInHand(ProjectileUtil.getWeaponHoldingHand(this, item -> item instanceof net.minecraft.world.item.BowItem)); + ItemStack projectile = this.getProjectile(bowItem); + AbstractArrow arrow = this.getArrow(projectile, power, bowItem); + if (this.getMainHandItem().getItem() instanceof net.minecraft.world.item.BowItem bow) { -+ abstractarrow = bow.customArrow(abstractarrow); ++ arrow = bow.customArrow(arrow); + } - double d0 = target.getX() - this.getX(); - double d1 = target.getY(0.3333333333333333) - abstractarrow.getY(); - double d2 = target.getZ() - this.getZ(); + double xd = target.getX() - this.getX(); + double yd = target.getY(0.3333333333333333) - arrow.getY(); + double zd = target.getZ() - this.getZ(); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch index ec435bcad1..a02464845b 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/skeleton/Bogged.java.patch @@ -3,11 +3,11 @@ @@ -70,7 +_,7 @@ @Override protected InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemstack = player.getItemInHand(hand); -- if (itemstack.is(Items.SHEARS) && this.readyForShearing()) { -+ if (false && itemstack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: move to onSheared - if (this.level() instanceof ServerLevel serverlevel) { - this.shear(serverlevel, SoundSource.PLAYERS, itemstack); + ItemStack itemStack = player.getItemInHand(hand); +- if (itemStack.is(Items.SHEARS) && this.readyForShearing()) { ++ if (false && itemStack.is(Items.SHEARS) && this.readyForShearing()) { // Forge: move to onSheared + if (this.level() instanceof ServerLevel level) { + this.shear(level, SoundSource.PLAYERS, itemStack); this.gameEvent(GameEvent.SHEAR, player); @@ -137,5 +_,17 @@ @Override diff --git a/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch index 1c33cd8e54..8f3035e69f 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/zombie/Zombie.java.patch @@ -22,7 +22,7 @@ public boolean convertVillagerToZombieVillager(final ServerLevel level, final Villager villager) { + if (!net.minecraftforge.event.ForgeEventFactory.canLivingConvert(villager, EntityType.ZOMBIE_VILLAGER, (timer) -> {})) + return false; - ZombieVillager zombievillager = villager.convertTo( + ZombieVillager zombieVillager = villager.convertTo( EntityType.ZOMBIE_VILLAGER, ConversionParams.single(villager, true, true), @@ -267,6 +_,7 @@ @@ -34,36 +34,36 @@ level.levelEvent(null, 1026, this.blockPosition(), 0); } @@ -289,19 +_,26 @@ - livingentity = (LivingEntity)source.getEntity(); + target = (LivingEntity)source.getEntity(); } -- if (livingentity != null -+ var vanilla = (livingentity != null +- if (target != null ++ var vanilla = (target != null && level.getDifficulty() == Difficulty.HARD && this.random.nextFloat() < this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE) - && level.isSpawningMonsters()) { + && level.isSpawningMonsters()); - int i = Mth.floor(this.getX()); - int j = Mth.floor(this.getY()); - int k = Mth.floor(this.getZ()); - EntityType entitytype = this.getType(); -- Zombie zombie = entitytype.create(level, EntitySpawnReason.REINFORCEMENT); -- if (zombie == null) { + int x = Mth.floor(this.getX()); + int y = Mth.floor(this.getY()); + int z = Mth.floor(this.getZ()); + EntityType type = this.getType(); +- Zombie reinforcement = type.create(level, EntitySpawnReason.REINFORCEMENT); +- if (reinforcement == null) { - return true; - } - + -+ var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), i, j, k, livingentity, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE)); ++ var event = net.minecraftforge.event.ForgeEventFactory.fireZombieSummonAid(this, level(), x, y, z, target, this.getAttributeValue(Attributes.SPAWN_REINFORCEMENTS_CHANCE)); + -+ Zombie zombie = null; ++ Zombie reinforcement = null; + if (event.getResult().isAllowed() || (vanilla && event.getResult().isDefault())) { + if (event.getCustomSummonedAid() != null) -+ zombie = event.getCustomSummonedAid(); ++ reinforcement = event.getCustomSummonedAid(); + else -+ zombie = entitytype.create(this.level(), EntitySpawnReason.REINFORCEMENT); ++ reinforcement = type.create(this.level(), EntitySpawnReason.REINFORCEMENT); + } + -+ if (zombie != null) { - for (int l = 0; l < 50; l++) { - int i1 = i + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); - int j1 = j + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); ++ if (reinforcement != null) { + for (int i = 0; i < 50; i++) { + int xt = x + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); + int yt = y + Mth.nextInt(this.random, 7, 40) * Mth.nextInt(this.random, -1, 1); diff --git a/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch b/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch index b9e1b18979..2004d22310 100644 --- a/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/monster/zombie/ZombieVillager.java.patch @@ -2,8 +2,8 @@ +++ b/net/minecraft/world/entity/monster/zombie/ZombieVillager.java @@ -156,7 +_,7 @@ if (!this.level().isClientSide() && this.isAlive() && this.isConverting()) { - int i = this.getConversionProgress(); - this.villagerConversionTime -= i; + int amount = this.getConversionProgress(); + this.villagerConversionTime -= amount; - if (this.villagerConversionTime <= 0) { + if (this.villagerConversionTime <= 0 && net.minecraftforge.event.ForgeEventFactory.canLivingConvert(this, EntityType.VILLAGER, (timer) -> this.villagerConversionTime = timer)) { this.finishConversion((ServerLevel)this.level()); diff --git a/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch index 7b56306d99..01f58a9ac1 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/CatSpawner.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/npc/CatSpawner.java +++ b/net/minecraft/world/entity/npc/CatSpawner.java -@@ -66,12 +_,12 @@ +@@ -65,12 +_,12 @@ private void spawnCat(final BlockPos spawnPos, final ServerLevel level, final boolean makePersistent) { Cat cat = EntityType.CAT.create(level, EntitySpawnReason.NATURAL); if (cat != null) { diff --git a/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch index c26680700b..8fd26e9ce2 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/villager/Villager.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/npc/villager/Villager.java +++ b/net/minecraft/world/entity/npc/villager/Villager.java -@@ -299,7 +_,7 @@ +@@ -298,7 +_,7 @@ @Override public InteractionResult mobInteract(final Player player, final InteractionHand hand) { - ItemStack itemstack = player.getItemInHand(hand); -- if (itemstack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping()) { -+ if (itemstack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping() || player.isSecondaryUseActive()) { + ItemStack itemStack = player.getItemInHand(hand); +- if (itemStack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping()) { ++ if (itemStack.is(Items.VILLAGER_SPAWN_EGG) || !this.isAlive() || this.isTrading() || this.isSleeping() || player.isSecondaryUseActive()) { return super.mobInteract(player, hand); } else if (this.isBaby()) { this.setUnhappy(); -@@ -760,7 +_,7 @@ +@@ -759,7 +_,7 @@ @Override public void thunderHit(final ServerLevel level, final LightningBolt lightningBolt) { diff --git a/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch b/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch index 36e59d98b5..3ca0097a88 100644 --- a/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/npc/villager/VillagerType.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/npc/villager/VillagerType.java +++ b/net/minecraft/world/entity/npc/villager/VillagerType.java -@@ -80,4 +_,9 @@ +@@ -79,4 +_,9 @@ public static ResourceKey byBiome(final Holder biome) { return biome.unwrapKey().map(BY_BIOME::get).orElse(PLAINS); } diff --git a/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch b/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch index b0aade4ba3..fc24080eb9 100644 --- a/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/player/Inventory.java.patch @@ -13,28 +13,28 @@ && ItemStack.isSameItemSameComponents(slotItemStack, newItemStack) @@ -169,7 +_,7 @@ - for (int k = 0; k < 9; k++) { - int l = (this.selected + k) % 9; -- if (!this.items.get(l).isEnchanted()) { -+ if (!this.items.get(l).isNotReplaceableByPickAction(this.player, l)) { - return l; + for (int slotx = 0; slotx < 9; slotx++) { + int index = (this.selected + slotx) % 9; +- if (!this.items.get(index).isEnchanted()) { ++ if (!this.items.get(index).isNotReplaceableByPickAction(this.player, index)) { + return index; } } @@ -240,7 +_,7 @@ for (int i = 0; i < this.items.size(); i++) { - ItemStack itemstack = this.getItem(i); - if (!itemstack.isEmpty()) { -- itemstack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null); -+ itemstack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null, i); + ItemStack itemStack = this.getItem(i); + if (!itemStack.isEmpty()) { +- itemStack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null); ++ itemStack.inventoryTick(this.player.level(), this.player, i == this.selected ? EquipmentSlot.MAINHAND : null, i); } } } @@ -290,6 +_,8 @@ - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.forThrowable(throwable, "Adding item to inventory"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Item being added"); -+ crashreportcategory.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); -+ crashreportcategory.setDetail("Item Class", () -> itemStack.getItem().getClass().getName()); - crashreportcategory.setDetail("Item ID", Item.getId(itemStack.getItem())); - crashreportcategory.setDetail("Item data", itemStack.getDamageValue()); - crashreportcategory.setDetail("Item name", () -> itemStack.getHoverName().getString()); + } catch (Throwable var6) { + CrashReport report = CrashReport.forThrowable(var6, "Adding item to inventory"); + CrashReportCategory category = report.addCategory("Item being added"); ++ category.setDetail("Registry Name", () -> String.valueOf(net.minecraftforge.registries.ForgeRegistries.ITEMS.getKey(itemStack.getItem()))); ++ category.setDetail("Item Class", () -> itemStack.getItem().getClass().getName()); + category.setDetail("Item ID", Item.getId(itemStack.getItem())); + category.setDetail("Item data", itemStack.getDamageValue()); + category.setDetail("Item name", () -> itemStack.getHoverName().getString()); diff --git a/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch b/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch index 8a0b691ab6..6d4782f074 100644 --- a/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/player/Player.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/player/Player.java +++ b/net/minecraft/world/entity/player/Player.java -@@ -124,7 +_,7 @@ +@@ -123,7 +_,7 @@ import net.minecraft.world.scores.Team; import org.jspecify.annotations.Nullable; @@ -9,7 +9,7 @@ public static final int MAX_HEALTH = 20; public static final int SLEEP_DURATION = 100; public static final int WAKE_UP_DURATION = 10; -@@ -172,6 +_,9 @@ +@@ -171,6 +_,9 @@ private Optional lastDeathLocation = Optional.empty(); public @Nullable FishingHook fishing; protected float hurtDir; @@ -19,7 +19,7 @@ public Player(final Level level, final GameProfile gameProfile) { super(EntityType.PLAYER, level); -@@ -180,6 +_,17 @@ +@@ -179,6 +_,17 @@ this.inventory = new Inventory(this, this.equipment); this.inventoryMenu = new InventoryMenu(this.inventory, !level.isClientSide(), this); this.containerMenu = this.inventoryMenu; @@ -37,7 +37,7 @@ } @Override -@@ -213,7 +_,8 @@ +@@ -212,7 +_,8 @@ .add(Attributes.MINING_EFFICIENCY) .add(Attributes.SWEEPING_DAMAGE_RATIO) .add(Attributes.WAYPOINT_TRANSMIT_RANGE, 6.0E7) @@ -47,7 +47,7 @@ } @Override -@@ -227,6 +_,7 @@ +@@ -226,6 +_,7 @@ @Override public void tick() { @@ -55,7 +55,7 @@ this.noPhysics = this.isSpectator(); if (this.isSpectator() || this.isPassenger()) { this.setOnGround(false); -@@ -243,7 +_,7 @@ +@@ -242,7 +_,7 @@ } if (!this.level().isClientSide() @@ -64,7 +64,7 @@ this.stopSleepInBed(false, true); } } else if (this.sleepCounter > 0) { -@@ -279,6 +_,7 @@ +@@ -278,6 +_,7 @@ this.cooldowns.tick(); this.updatePlayerPose(); @@ -72,7 +72,7 @@ } @Override -@@ -338,6 +_,10 @@ +@@ -337,6 +_,10 @@ } protected void updatePlayerPose() { @@ -81,17 +81,17 @@ + return; + } if (this.canPlayerFitWithinBlocksAndEntitiesWhen(Pose.SWIMMING)) { - Pose pose = this.getDesiredPose(); - Pose pose1; -@@ -522,6 +_,7 @@ + Pose desiredPose = this.getDesiredPose(); + Pose actualPose; +@@ -521,6 +_,7 @@ @Override public void die(final DamageSource source) { + if (net.minecraftforge.event.ForgeEventFactory.onLivingDeath(this, source)) return; super.die(source); this.reapplyPosition(); - if (!this.isSpectator() && this.level() instanceof ServerLevel serverlevel) { -@@ -578,10 +_,15 @@ + if (!this.isSpectator() && this.level() instanceof ServerLevel level) { +@@ -577,10 +_,15 @@ } public @Nullable ItemEntity drop(final ItemStack itemStack, final boolean thrownFromHand) { @@ -105,16 +105,16 @@ + } + + public float getDestroySpeed(BlockState state, @Nullable BlockPos pos) { - float f = this.inventory.getSelectedItem().getDestroySpeed(state); - if (f > 1.0F) { - f += (float)this.getAttributeValue(Attributes.MINING_EFFICIENCY); -@@ -610,11 +_,14 @@ - f /= 5.0F; + float speed = this.inventory.getSelectedItem().getDestroySpeed(state); + if (speed > 1.0F) { + speed += (float)this.getAttributeValue(Attributes.MINING_EFFICIENCY); +@@ -609,11 +_,14 @@ + speed /= 5.0F; } -+ f = net.minecraftforge.event.ForgeEventFactory.getBreakSpeed(this, state, f, pos); ++ speed = net.minecraftforge.event.ForgeEventFactory.getBreakSpeed(this, state, speed, pos); + - return f; + return speed; } public boolean hasCorrectToolForDrops(final BlockState state) { @@ -124,7 +124,7 @@ } @Override -@@ -675,6 +_,7 @@ +@@ -674,6 +_,7 @@ @Override public boolean hurtServer(final ServerLevel level, final DamageSource source, float damage) { @@ -132,7 +132,7 @@ if (this.isInvulnerableTo(level, source)) { return false; } else if (this.abilities.invulnerable && !source.is(DamageTypeTags.BYPASSES_INVULNERABILITY)) { -@@ -743,10 +_,13 @@ +@@ -742,10 +_,13 @@ @Override protected void actuallyHurt(final ServerLevel level, final DamageSource source, float dmg) { if (!this.isInvulnerableTo(level, source)) { @@ -140,13 +140,13 @@ + if (dmg <= 0) return; dmg = this.getDamageAfterArmorAbsorb(source, dmg); dmg = this.getDamageAfterMagicAbsorb(source, dmg); - float f1 = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); - this.setAbsorptionAmount(this.getAbsorptionAmount() - (dmg - f1)); -+ f1 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, f1); - float f = dmg - f1; - if (f > 0.0F && f < 3.4028235E37F) { - this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(f * 10.0F)); -@@ -824,6 +_,10 @@ + float var8 = Math.max(dmg - this.getAbsorptionAmount(), 0.0F); + this.setAbsorptionAmount(this.getAbsorptionAmount() - (dmg - var8)); ++ var8 = net.minecraftforge.common.ForgeHooks.onLivingDamage(this, source, var8); + float absorbedDamage = dmg - var8; + if (absorbedDamage > 0.0F && absorbedDamage < 3.4028235E37F) { + this.awardStat(Stats.DAMAGE_ABSORBED, Math.round(absorbedDamage * 10.0F)); +@@ -823,6 +_,10 @@ return InteractionResult.PASS; } else { @@ -154,69 +154,69 @@ + if (net.minecraftforge.event.entity.player.PlayerInteractEvent.EntityInteractSpecific.BUS.post(event)) { + return event.getCancellationResult(); + } - ItemStack itemstack = this.getItemInHand(hand); - ItemStack itemstack1 = itemstack.copy(); - InteractionResult interactionresult = entity.interact(this, hand, location); -@@ -832,6 +_,10 @@ - itemstack.setCount(itemstack1.getCount()); + ItemStack itemStack = this.getItemInHand(hand); + ItemStack itemStackClone = itemStack.copy(); + InteractionResult interact = entity.interact(this, hand, location); +@@ -831,6 +_,10 @@ + itemStack.setCount(itemStackClone.getCount()); } -+ if (!this.abilities.instabuild && itemstack.isEmpty()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, hand.asEquipmentSlot()); ++ if (!this.abilities.instabuild && itemStack.isEmpty()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemStackClone, hand.asEquipmentSlot()); + } + - return interactionresult; + return interact; } else { - if (!itemstack.isEmpty() && entity instanceof LivingEntity) { -@@ -843,6 +_,7 @@ - if (interactionresult1.consumesAction()) { + if (!itemStack.isEmpty() && entity instanceof LivingEntity) { +@@ -842,6 +_,7 @@ + if (interactionResult.consumesAction()) { this.level().gameEvent(GameEvent.ENTITY_INTERACT, entity.position(), GameEvent.Context.of(this)); - if (itemstack.isEmpty() && !this.hasInfiniteMaterials()) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemstack1, hand.asEquipmentSlot()); + if (itemStack.isEmpty() && !this.hasInfiniteMaterials()) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(this, itemStackClone, hand.asEquipmentSlot()); this.setItemInHand(hand, ItemStack.EMPTY); } -@@ -942,6 +_,7 @@ +@@ -941,6 +_,7 @@ } public void attack(final Entity entity) { + if (!net.minecraftforge.common.ForgeHooks.onPlayerAttackTarget(this, entity)) return; if (!this.cannotAttack(entity)) { - float f = this.isAutoSpinAttack() ? this.autoSpinAttackDmg : (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE); - ItemStack itemstack = this.getWeaponItem(); -@@ -963,8 +_,10 @@ + float baseDamage = this.isAutoSpinAttack() ? this.autoSpinAttackDmg : (float)this.getAttributeValue(Attributes.ATTACK_DAMAGE); + ItemStack attackingItemStack = this.getWeaponItem(); +@@ -962,8 +_,10 @@ - f += itemstack.getItem().getAttackDamageBonus(entity, f, damagesource); - boolean flag2 = flag && this.canCriticalAttack(entity); -+ var hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(this, entity, flag2, flag2 ? 1.5F : 1.0F); -+ flag2 = hitResult != null; - if (flag2) { -- f *= 1.5F; -+ f *= hitResult.getDamageModifier(); + baseDamage += attackingItemStack.getItem().getAttackDamageBonus(entity, baseDamage, damageSource); + boolean criticalAttack = fullStrengthAttack && this.canCriticalAttack(entity); ++ var hitResult = net.minecraftforge.common.ForgeHooks.getCriticalHit(this, entity, criticalAttack, criticalAttack ? 1.5F : 1.0F); ++ criticalAttack = hitResult != null; + if (criticalAttack) { +- baseDamage *= 1.5F; ++ baseDamage *= hitResult.getDamageModifier(); } - float f3 = f + f2; -@@ -1036,7 +_,7 @@ - double d0 = this.getKnownMovement().horizontalDistanceSqr(); - double d1 = this.getSpeed() * 2.5; - if (d0 < Mth.square(d1)) { + float totalDamage = baseDamage + magicBoost; +@@ -1035,7 +_,7 @@ + double approximateSpeedSq = this.getKnownMovement().horizontalDistanceSqr(); + double maxSpeedForSweepAttack = this.getSpeed() * 2.5; + if (approximateSpeedSq < Mth.square(maxSpeedForSweepAttack)) { - return this.getItemInHand(InteractionHand.MAIN_HAND).is(ItemTags.SWORDS); + return this.getItemInHand(InteractionHand.MAIN_HAND).canPerformAction(net.minecraftforge.common.ToolActions.SWORD_SWEEP); } } -@@ -1079,8 +_,8 @@ +@@ -1078,8 +_,8 @@ private void itemAttackInteraction(final Entity entity, final ItemStack attackingItemStack, final DamageSource damageSource, final boolean applyToTarget) { - Entity entityx = entity; + Entity hurtTarget = entity; - if (entity instanceof EnderDragonPart) { -- entityx = ((EnderDragonPart)entity).parentMob; +- hurtTarget = ((EnderDragonPart)entity).parentMob; + if (entity instanceof net.minecraftforge.entity.PartEntity pe) { -+ entityx = pe.getParent(); ++ hurtTarget = pe.getParent(); } - boolean flag = false; -@@ -1105,6 +_,7 @@ + boolean itemHurtEnemy = false; +@@ -1104,6 +_,7 @@ } else { this.setItemInHand(InteractionHand.OFF_HAND, ItemStack.EMPTY); } @@ -224,16 +224,16 @@ } } } -@@ -1145,7 +_,7 @@ - if (this.level() instanceof ServerLevel serverlevel) { - float f = 1.0F + (float)this.getAttributeValue(Attributes.SWEEPING_DAMAGE_RATIO) * baseDamage; +@@ -1144,7 +_,7 @@ + if (this.level() instanceof ServerLevel serverLevel) { + float var12 = 1.0F + (float)this.getAttributeValue(Attributes.SWEEPING_DAMAGE_RATIO) * baseDamage; -- for (LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, entity.getBoundingBox().inflate(1.0, 0.25, 1.0))) { -+ for (LivingEntity livingentity : this.level().getEntitiesOfClass(LivingEntity.class, this.getItemInHand(InteractionHand.MAIN_HAND).getSweepHitBox(this, entity))) { - if (livingentity != this - && livingentity != entity - && !this.isAlliedTo(livingentity) -@@ -1311,6 +_,7 @@ +- for (LivingEntity nearby : this.level().getEntitiesOfClass(LivingEntity.class, entity.getBoundingBox().inflate(1.0, 0.25, 1.0))) { ++ for (LivingEntity nearby : this.level().getEntitiesOfClass(LivingEntity.class, this.getItemInHand(InteractionHand.MAIN_HAND).getSweepHitBox(this, entity))) { + if (nearby != this + && nearby != entity + && !this.isAlliedTo(nearby) +@@ -1310,6 +_,7 @@ } public void stopSleepInBed(final boolean forcefulWakeUp, final boolean updateLevelList) { @@ -241,7 +241,7 @@ super.stopSleeping(); if (this.level() instanceof ServerLevel && updateLevelList) { ((ServerLevel)this.level()).updateSleepingPlayerList(); -@@ -1420,6 +_,7 @@ +@@ -1421,6 +_,7 @@ @Override public boolean causeFallDamage(final double fallDistance, final float damageModifier, final DamageSource damageSource) { if (this.abilities.mayfly) { @@ -249,23 +249,23 @@ return false; } else { if (fallDistance >= 2.0) { -@@ -1454,13 +_,13 @@ +@@ -1455,13 +_,13 @@ protected void playStepSound(final BlockPos onPos, final BlockState onState) { if (this.isInWater()) { this.waterSwimSound(); - this.playMuffledStepSound(onState); + this.playMuffledStepSound(onState, onPos); } else { - BlockPos blockpos = this.getPrimaryStepSoundBlockPos(onPos); - if (!onPos.equals(blockpos)) { - BlockState blockstate = this.level().getBlockState(blockpos); - if (blockstate.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)) { -- this.playCombinationStepSounds(blockstate, onState); -+ this.playCombinationStepSounds(blockstate, onState, blockpos, onPos); + BlockPos primaryStepSoundPos = this.getPrimaryStepSoundBlockPos(onPos); + if (!onPos.equals(primaryStepSoundPos)) { + BlockState primaryStepState = this.level().getBlockState(primaryStepSoundPos); + if (primaryStepState.is(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)) { +- this.playCombinationStepSounds(primaryStepState, onState); ++ this.playCombinationStepSounds(primaryStepState, onState, primaryStepSoundPos, onPos); } else { - super.playStepSound(blockpos, blockstate); + super.playStepSound(primaryStepSoundPos, primaryStepState); } -@@ -1490,7 +_,13 @@ +@@ -1491,7 +_,13 @@ this.tryResetCurrentImpulseContext(); } @@ -280,7 +280,7 @@ this.increaseScore(i); this.experienceProgress = this.experienceProgress + (float)i / this.getXpNeededForNextLevel(); this.totalExperience = Mth.clamp(this.totalExperience + i, 0, Integer.MAX_VALUE); -@@ -1518,7 +_,7 @@ +@@ -1519,7 +_,7 @@ } public void onEnchantmentPerformed(final ItemStack itemStack, final int enchantmentCost) { @@ -289,7 +289,7 @@ if (this.experienceLevel < 0) { this.experienceLevel = 0; this.experienceProgress = 0.0F; -@@ -1528,7 +_,13 @@ +@@ -1529,7 +_,13 @@ this.enchantmentSeed = this.random.nextInt(); } @@ -304,35 +304,35 @@ this.experienceLevel = IntMath.saturatedAdd(this.experienceLevel, amount); if (this.experienceLevel < 0) { this.experienceLevel = 0; -@@ -1667,7 +_,13 @@ +@@ -1668,7 +_,13 @@ @Override public Component getDisplayName() { -- MutableComponent mutablecomponent = PlayerTeam.formatNameForTeam(this.getTeam(), this.getName()); +- MutableComponent result = PlayerTeam.formatNameForTeam(this.getTeam(), this.getName()); + if (this.displayname == null) { + this.displayname = net.minecraftforge.event.ForgeEventFactory.getPlayerDisplayName(this, this.getName()); + } -+ MutableComponent mutablecomponent = Component.literal(""); -+ mutablecomponent = prefixes.stream().reduce(mutablecomponent, MutableComponent::append); -+ mutablecomponent = mutablecomponent.append(PlayerTeam.formatNameForTeam(this.getTeam(), this.displayname)); -+ mutablecomponent = suffixes.stream().reduce(mutablecomponent, MutableComponent::append); - return this.decorateDisplayNameComponent(mutablecomponent); ++ MutableComponent result = Component.literal(""); ++ result = prefixes.stream().reduce(result, MutableComponent::append); ++ result = result.append(PlayerTeam.formatNameForTeam(this.getTeam(), this.displayname)); ++ result = suffixes.stream().reduce(result, MutableComponent::append); + return this.decorateDisplayNameComponent(result); } -@@ -1857,18 +_,19 @@ - Predicate predicate = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); - ItemStack itemstack = ProjectileWeaponItem.getHeldProjectile(this, predicate); - if (!itemstack.isEmpty()) { -- return itemstack; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, itemstack); +@@ -1860,18 +_,19 @@ + Predicate supportedProjectiles = ((ProjectileWeaponItem)heldWeapon.getItem()).getSupportedHeldProjectiles(); + ItemStack heldProjectile = ProjectileWeaponItem.getHeldProjectile(this, supportedProjectiles); + if (!heldProjectile.isEmpty()) { +- return heldProjectile; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, heldProjectile); } else { - predicate = ((ProjectileWeaponItem)heldWeapon.getItem()).getAllSupportedProjectiles(); + supportedProjectiles = ((ProjectileWeaponItem)heldWeapon.getItem()).getAllSupportedProjectiles(); for (int i = 0; i < this.inventory.getContainerSize(); i++) { - ItemStack itemstack1 = this.inventory.getItem(i); - if (predicate.test(itemstack1)) { -- return itemstack1; -+ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, itemstack1); + ItemStack itemStack = this.inventory.getItem(i); + if (supportedProjectiles.test(itemStack)) { +- return itemStack; ++ return net.minecraftforge.common.ForgeHooks.getProjectile(this, heldWeapon, heldProjectile); } } @@ -342,9 +342,9 @@ } } } -@@ -1989,6 +_,54 @@ - double d0 = this.blockInteractionRange() + buffer; - return new AABB(pos).distanceToSqr(this.getEyePosition()) < d0 * d0; +@@ -1992,6 +_,54 @@ + double maxRange = this.blockInteractionRange() + buffer; + return new AABB(pos).distanceToSqr(this.getEyePosition()) < maxRange * maxRange; } + + public Collection getPrefixes() { diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch index 952f0d7bc2..c484ae4a55 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/FireworkRocketEntity.java.patch @@ -12,5 +12,5 @@ + + @Override public DoubleDoubleImmutablePair calculateHorizontalHurtKnockbackDirection(final LivingEntity hurtEntity, final DamageSource damageSource) { - double d0 = hurtEntity.position().x - this.position().x; - double d1 = hurtEntity.position().z - this.position().z; + double dx = hurtEntity.position().x - this.position().x; + double dz = hurtEntity.position().z - this.position().z; diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch index 091b24e54e..d326c5d0c9 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/FishingHook.java.patch @@ -1,55 +1,55 @@ --- a/net/minecraft/world/entity/projectile/FishingHook.java +++ b/net/minecraft/world/entity/projectile/FishingHook.java -@@ -251,8 +_,8 @@ +@@ -253,8 +_,8 @@ if (owner.canInteractWithLevel()) { - ItemStack itemstack = owner.getMainHandItem(); - ItemStack itemstack1 = owner.getOffhandItem(); -- boolean flag = itemstack.is(Items.FISHING_ROD); -- boolean flag1 = itemstack1.is(Items.FISHING_ROD); -+ boolean flag = itemstack.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); -+ boolean flag1 = itemstack1.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); - if ((flag || flag1) && this.distanceToSqr(owner) <= 1024.0) { + ItemStack selectedItem = owner.getMainHandItem(); + ItemStack selectedItemOffHand = owner.getOffhandItem(); +- boolean mainHandIsFishing = selectedItem.is(Items.FISHING_ROD); +- boolean offHandIsFishing = selectedItemOffHand.is(Items.FISHING_ROD); ++ boolean mainHandIsFishing = selectedItem.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); ++ boolean offHandIsFishing = selectedItemOffHand.canPerformAction(net.minecraftforge.common.ToolActions.FISHING_ROD_CAST); + if ((mainHandIsFishing || offHandIsFishing) && this.distanceToSqr(owner) <= 1024.0) { return false; } -@@ -264,6 +_,7 @@ +@@ -266,6 +_,7 @@ private void checkCollision() { - HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); -+ if (hitresult.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) - this.hitTargetOrDeflectSelf(hitresult); + HitResult hitResult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); ++ if (hitResult.getType() == HitResult.Type.MISS || !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitResult)) + this.hitTargetOrDeflectSelf(hitResult); } -@@ -453,6 +_,7 @@ - Player player = this.getPlayerOwner(); - if (!this.level().isClientSide() && player != null && !this.shouldStopFishing(player)) { - int i = 0; +@@ -447,6 +_,7 @@ + Player owner = this.getPlayerOwner(); + if (!this.level().isClientSide() && owner != null && !this.shouldStopFishing(owner)) { + int dmg = 0; + net.minecraftforge.event.entity.player.ItemFishedEvent event = null; if (this.hookedIn != null) { this.pullEntity(this.hookedIn); - CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, rod, this, Collections.emptyList()); -@@ -463,10 +_,16 @@ + CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)owner, rod, this, Collections.emptyList()); +@@ -457,10 +_,16 @@ .withParameter(LootContextParams.ORIGIN, this.position()) .withParameter(LootContextParams.TOOL, rod) .withParameter(LootContextParams.THIS_ENTITY, this) + .withParameter(LootContextParams.ATTACKING_ENTITY, this.getOwner()) - .withLuck(this.luck + player.getLuck()) + .withLuck(this.luck + owner.getLuck()) .create(LootContextParamSets.FISHING); - LootTable loottable = this.level().getServer().reloadableRegistries().getLootTable(BuiltInLootTables.FISHING); - List list = loottable.getRandomItems(lootparams); -+ event = new net.minecraftforge.event.entity.player.ItemFishedEvent(list, this.onGround() ? 2 : 1, this); + LootTable lootTable = this.level().getServer().reloadableRegistries().getLootTable(BuiltInLootTables.FISHING); + List items = lootTable.getRandomItems(params); ++ event = new net.minecraftforge.event.entity.player.ItemFishedEvent(items, this.onGround() ? 2 : 1, this); + if (net.minecraftforge.event.entity.player.ItemFishedEvent.BUS.post(event)) { + this.discard(); + return event.getRodDamage(); + } - CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)player, rod, this, list); + CriteriaTriggers.FISHING_ROD_HOOKED.trigger((ServerPlayer)owner, rod, this, items); - for (ItemStack itemstack : list) { -@@ -492,7 +_,7 @@ + for (ItemStack itemStack : items) { +@@ -486,7 +_,7 @@ } this.discard(); -- return i; -+ return event == null ? i : event.getRodDamage(); +- return dmg; ++ return event == null ? dmg : event.getRodDamage(); } else { return 0; } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch index da4ffbc292..a3df8f40cc 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/LlamaSpit.java.patch @@ -2,11 +2,11 @@ +++ b/net/minecraft/world/entity/projectile/LlamaSpit.java @@ -43,7 +_,8 @@ super.tick(); - Vec3 vec3 = this.getDeltaMovement(); - HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); -- this.hitTargetOrDeflectSelf(hitresult); -+ if (hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) -+ this.hitTargetOrDeflectSelf(hitresult); - double d0 = this.getX() + vec3.x; - double d1 = this.getY() + vec3.y; - double d2 = this.getZ() + vec3.z; + Vec3 movement = this.getDeltaMovement(); + HitResult hitResult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity); +- this.hitTargetOrDeflectSelf(hitResult); ++ if (hitResult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitResult)) ++ this.hitTargetOrDeflectSelf(hitResult); + double x = this.getX() + movement.x; + double y = this.getY() + movement.y; + double z = this.getZ() + movement.z; diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch index 26017c4257..7702952934 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/Projectile.java.patch @@ -3,9 +3,9 @@ @@ -363,7 +_,7 @@ @Override public boolean mayInteract(final ServerLevel level, final BlockPos pos) { - Entity entity = this.getOwner(); -- return entity instanceof Player ? entity.mayInteract(level, pos) : entity == null || level.getGameRules().get(GameRules.MOB_GRIEFING); -+ return entity instanceof Player ? entity.mayInteract(level, pos) : entity == null || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, entity); + Entity owner = this.getOwner(); +- return owner instanceof Player ? owner.mayInteract(level, pos) : owner == null || level.getGameRules().get(GameRules.MOB_GRIEFING); ++ return owner instanceof Player ? owner.mayInteract(level, pos) : owner == null || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(level, owner); } public boolean mayBreak(final ServerLevel level) { diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch index 0699accf74..d7381e8823 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ProjectileUtil.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/entity/projectile/ProjectileUtil.java +++ b/net/minecraft/world/entity/projectile/ProjectileUtil.java @@ -127,7 +_,7 @@ - Vec3 vec31 = optional.get(); - double d1 = from.distanceToSqr(vec31); - if (d1 < d0 || d0 == 0.0) { -- if (entity1.getRootVehicle() == except.getRootVehicle()) { -+ if (entity1.getRootVehicle() == except.getRootVehicle() && !entity1.canRiderInteract()) { - if (d0 == 0.0) { - entity = entity1; - vec3 = vec31; -@@ -266,8 +_,13 @@ + Vec3 location = clipPoint.get(); + double dd = from.distanceToSqr(location); + if (dd < nearest || nearest == 0.0) { +- if (entity.getRootVehicle() == except.getRootVehicle()) { ++ if (entity.getRootVehicle() == except.getRootVehicle() && !entity.canRiderInteract()) { + if (nearest == 0.0) { + hovered = entity; + hoveredPos = location; +@@ -268,8 +_,13 @@ } } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch index 72d334cb43..2f3eb5757b 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ShulkerBullet.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/entity/projectile/ShulkerBullet.java +++ b/net/minecraft/world/entity/projectile/ShulkerBullet.java -@@ -215,7 +_,7 @@ +@@ -217,7 +_,7 @@ this.handlePortal(); } -- if (hitresult != null && this.isAlive() && hitresult.getType() != HitResult.Type.MISS) { -+ if (hitresult != null && this.isAlive() && hitresult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { - this.hitTargetOrDeflectSelf(hitresult); +- if (hitResult != null && this.isAlive() && hitResult.getType() != HitResult.Type.MISS) { ++ if (hitResult != null && this.isAlive() && hitResult.getType() != HitResult.Type.MISS && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitResult)) { + this.hitTargetOrDeflectSelf(hitResult); } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch index 41d4112127..39f52acee7 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/ThrowableProjectile.java.patch @@ -4,8 +4,8 @@ this.updateRotation(); this.applyEffectsFromBlocks(); super.tick(); -- if (hitresult.getType() != HitResult.Type.MISS && this.isAlive()) { -+ if (hitresult.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { - this.hitTargetOrDeflectSelf(hitresult); +- if (result.getType() != HitResult.Type.MISS && this.isAlive()) { ++ if (result.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, result)) { + this.hitTargetOrDeflectSelf(result); } } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch index 3b81caadd6..14cc9a55d8 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/arrow/AbstractArrow.java.patch @@ -17,7 +17,7 @@ this.clearFire(); } -@@ -585,7 +_,7 @@ +@@ -595,7 +_,7 @@ protected boolean canHitEntity(final Entity entity) { return entity instanceof Player && this.getOwner() instanceof Player player && !player.canHarmPlayer((Player)entity) ? false diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch index 65590d2f72..dc1b951871 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/AbstractHurtingProjectile.java.patch @@ -4,8 +4,8 @@ this.igniteForSeconds(1.0F); } -- if (hitresult.getType() != HitResult.Type.MISS && this.isAlive()) { -+ if (hitresult.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitresult)) { - this.hitTargetOrDeflectSelf(hitresult); +- if (hitResult.getType() != HitResult.Type.MISS && this.isAlive()) { ++ if (hitResult.getType() != HitResult.Type.MISS && this.isAlive() && !net.minecraftforge.event.ForgeEventFactory.onProjectileImpact(this, hitResult)) { + this.hitTargetOrDeflectSelf(hitResult); } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch index 414c0ed86b..8570580e42 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/LargeFireball.java.patch @@ -3,9 +3,9 @@ @@ -31,7 +_,7 @@ protected void onHit(final HitResult hitResult) { super.onHit(hitResult); - if (this.level() instanceof ServerLevel serverlevel) { -- boolean flag = serverlevel.getGameRules().get(GameRules.MOB_GRIEFING); -+ boolean flag = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, this.getOwner()); - this.level().explode(this, this.getX(), this.getY(), this.getZ(), this.explosionPower, flag, Level.ExplosionInteraction.MOB); + if (this.level() instanceof ServerLevel serverLevel) { +- boolean grief = serverLevel.getGameRules().get(GameRules.MOB_GRIEFING); ++ boolean grief = net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, this.getOwner()); + this.level().explode(this, this.getX(), this.getY(), this.getZ(), this.explosionPower, grief, Level.ExplosionInteraction.MOB); this.discard(); } diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch index 453ccada82..28fb9346af 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/entity/projectile/hurtingprojectile/SmallFireball.java @@ -51,7 +_,7 @@ super.onHitBlock(hitResult); - if (this.level() instanceof ServerLevel serverlevel) { - Entity entity = this.getOwner(); -- if (!(entity instanceof Mob) || serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (!(entity instanceof Mob) || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, entity)) { - BlockPos blockpos = hitResult.getBlockPos().relative(hitResult.getDirection()); - if (this.level().isEmptyBlock(blockpos)) { - this.level().setBlockAndUpdate(blockpos, BaseFireBlock.getState(this.level(), blockpos)); + if (this.level() instanceof ServerLevel serverLevel) { + Entity owner = this.getOwner(); +- if (!(owner instanceof Mob) || serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (!(owner instanceof Mob) || net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, owner)) { + BlockPos pos = hitResult.getBlockPos().relative(hitResult.getDirection()); + if (this.level().isEmptyBlock(pos)) { + this.level().setBlockAndUpdate(pos, BaseFireBlock.getState(this.level(), pos)); diff --git a/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch b/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch index d5244c229f..1ed3a715c1 100644 --- a/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java.patch @@ -1,25 +1,25 @@ --- a/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java +++ b/net/minecraft/world/entity/projectile/throwableitemprojectile/ThrownEnderpearl.java @@ -102,6 +_,13 @@ - Vec3 vec3 = this.oldPosition(); - if (entity instanceof ServerPlayer serverplayer) { - if (serverplayer.connection.isAcceptingMessages()) { -+ var event = net.minecraftforge.event.ForgeEventFactory.onEnderPearlLand(serverplayer, this.getX(), this.getY(), this.getZ(), this, 5.0F, hitResult); + Vec3 teleportPos = this.oldPosition(); + if (owner instanceof ServerPlayer player) { + if (player.connection.isAcceptingMessages()) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onEnderPearlLand(player, this.getX(), this.getY(), this.getZ(), this, 5.0F, hitResult); + if (event == null) { + this.discard(); + return; + } -+ vec3 = event.getTarget(); ++ teleportPos = event.getTarget(); + - if (this.random.nextFloat() < 0.05F && serverlevel.isSpawningMonsters()) { - Endermite endermite = EntityType.ENDERMITE.create(serverlevel, EntitySpawnReason.TRIGGERED); + if (this.random.nextFloat() < 0.05F && level.isSpawningMonsters()) { + Endermite endermite = EntityType.ENDERMITE.create(level, EntitySpawnReason.TRIGGERED); if (endermite != null) { @@ -122,7 +_,7 @@ - if (serverplayer1 != null) { - serverplayer1.resetFallDistance(); - serverplayer1.resetCurrentImpulseContext(); -- serverplayer1.hurtServer(serverplayer.level(), this.damageSources().enderPearl(), 5.0F); -+ serverplayer1.hurtServer(serverplayer.level(), this.damageSources().enderPearl(), event.getAttackDamage()); + if (newOwner != null) { + newOwner.resetFallDistance(); + newOwner.resetCurrentImpulseContext(); +- newOwner.hurtServer(player.level(), this.damageSources().enderPearl(), 5.0F); ++ newOwner.hurtServer(player.level(), this.damageSources().enderPearl(), event.getAttackDamage()); } - this.playSound(serverlevel, vec3); + this.playSound(level, teleportPos); diff --git a/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch b/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch index 0186384999..d8b8991cb5 100644 --- a/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/raid/Raid.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/entity/raid/Raid.java +++ b/net/minecraft/world/entity/raid/Raid.java -@@ -830,7 +_,7 @@ +@@ -829,7 +_,7 @@ } } @@ -9,7 +9,7 @@ VINDICATOR(EntityType.VINDICATOR, new int[]{0, 0, 2, 0, 1, 4, 2, 5}), EVOKER(EntityType.EVOKER, new int[]{0, 0, 0, 0, 0, 1, 1, 2}), PILLAGER(EntityType.PILLAGER, new int[]{0, 4, 3, 3, 4, 4, 4, 2}), -@@ -844,6 +_,20 @@ +@@ -843,6 +_,20 @@ private RaiderType(final EntityType entityType, final int[] spawnsPerWaveBeforeBonus) { this.entityType = entityType; this.spawnsPerWaveBeforeBonus = spawnsPerWaveBeforeBonus; diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch index eba148ab08..543677c903 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/ContainerEntity.java.patch @@ -3,10 +3,10 @@ @@ -101,6 +_,9 @@ this.setContainerLootTable(null); - LootParams.Builder lootparams$builder = new LootParams.Builder((ServerLevel)this.level()).withParameter(LootContextParams.ORIGIN, this.position()); + LootParams.Builder builder = new LootParams.Builder((ServerLevel)this.level()).withParameter(LootContextParams.ORIGIN, this.position()); + // Forge: set the chest to killer_entity for loot context. + if (this instanceof net.minecraft.world.entity.vehicle.minecart.AbstractMinecartContainer entityContainer) -+ lootparams$builder.withParameter(LootContextParams.ATTACKING_ENTITY, entityContainer); ++ builder.withParameter(LootContextParams.ATTACKING_ENTITY, entityContainer); if (player != null) { - lootparams$builder.withLuck(player.getLuck()).withParameter(LootContextParams.THIS_ENTITY, player); + builder.withLuck(player.getLuck()).withParameter(LootContextParams.THIS_ENTITY, player); } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch index 2935d225bf..787936290d 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/boat/AbstractBoat.java.patch @@ -10,39 +10,39 @@ private static final EntityDataAccessor DATA_ID_PADDLE_RIGHT = SynchedEntityData.defineId(AbstractBoat.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor DATA_ID_BUBBLE_TIME = SynchedEntityData.defineId(AbstractBoat.class, EntityDataSerializers.INT); @@ -416,7 +_,7 @@ - for (int i2 = i1; i2 < j1; i2++) { - blockpos$mutableblockpos.set(l1, k1, i2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(FluidTags.WATER)) { -+ if (this.canBoatInFluid(fluidstate)) { - f = Math.max(f, fluidstate.getHeight(this.level(), blockpos$mutableblockpos)); + for (int z = minZ; z < maxZ; z++) { + pos.set(x, y, z); + FluidState fluidState = this.level().getFluidState(pos); +- if (fluidState.is(FluidTags.WATER)) { ++ if (this.canBoatInFluid(fluidState)) { + blockHeight = Math.max(blockHeight, fluidState.getHeight(this.level(), pos)); } -@@ -462,7 +_,7 @@ - voxelshape, - BooleanOp.AND - )) { -- f += blockstate.getBlock().getFriction(); -+ f += blockstate.getFriction(this.level(), blockpos$mutableblockpos, this); - k1++; +@@ -458,7 +_,7 @@ + BlockState blockState = this.level().getBlockState(blockPos); + if (!(blockState.getBlock() instanceof LilyPadBlock) + && Shapes.joinIsNotEmpty(blockState.getCollisionShape(this.level(), blockPos).move(blockPos), boatShape, BooleanOp.AND)) { +- friction += blockState.getBlock().getFriction(); ++ friction += blockState.getFriction(this.level(), blockPos, this); + count++; } } -@@ -491,7 +_,7 @@ - for (int i2 = i1; i2 < j1; i2++) { - blockpos$mutableblockpos.set(k1, l1, i2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(FluidTags.WATER)) { -+ if (this.canBoatInFluid(fluidstate)) { - float f = l1 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos); - this.waterLevel = Math.max((double)f, this.waterLevel); - flag |= aabb.minY < f; -@@ -520,7 +_,7 @@ - for (int i2 = i1; i2 < j1; i2++) { - blockpos$mutableblockpos.set(k1, l1, i2); - FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos); -- if (fluidstate.is(FluidTags.WATER) && d0 < blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos)) { -+ if (this.canBoatInFluid(fluidstate) && d0 < blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos)) { - if (!fluidstate.isSource()) { +@@ -487,7 +_,7 @@ + for (int z = minZ; z < maxZ; z++) { + pos.set(x, y, z); + FluidState fluidState = this.level().getFluidState(pos); +- if (fluidState.is(FluidTags.WATER)) { ++ if (this.canBoatInFluid(fluidState)) { + float height = y + fluidState.getHeight(this.level(), pos); + this.waterLevel = Math.max((double)height, this.waterLevel); + inWater |= bb.minY < height; +@@ -516,7 +_,7 @@ + for (int z = z0; z < z1; z++) { + pos.set(x, y, z); + FluidState fluidState = this.level().getFluidState(pos); +- if (fluidState.is(FluidTags.WATER) && maxY < pos.getY() + fluidState.getHeight(this.level(), pos)) { ++ if (this.canBoatInFluid(fluidState) && maxY < pos.getY() + fluidState.getHeight(this.level(), pos)) { + if (!fluidState.isSource()) { return AbstractBoat.Status.UNDER_FLOWING_WATER; } @@ -722,7 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch index bd5ae354b5..e20144b8d2 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/AbstractMinecart.java.patch @@ -36,14 +36,14 @@ } @Override -@@ -365,16 +_,24 @@ +@@ -367,16 +_,24 @@ } protected void comeOffTrack(final ServerLevel level) { -- double d0 = this.getMaxSpeed(level); -+ double d0 = this.onGround() ? this.getMaxSpeed(level) : getMaxSpeedAirLateral(); - Vec3 vec3 = this.getDeltaMovement(); - this.setDeltaMovement(Mth.clamp(vec3.x, -d0, d0), vec3.y, Mth.clamp(vec3.z, -d0, d0)); +- double maxSpeed = this.getMaxSpeed(level); ++ double maxSpeed = this.onGround() ? this.getMaxSpeed(level) : getMaxSpeedAirLateral(); + Vec3 movement = this.getDeltaMovement(); + this.setDeltaMovement(Mth.clamp(movement.x, -maxSpeed, maxSpeed), movement.y, Mth.clamp(movement.z, -maxSpeed, maxSpeed)); if (this.onGround()) { this.setDeltaMovement(this.getDeltaMovement().scale(0.5)); } @@ -63,16 +63,16 @@ } } -@@ -431,7 +_,7 @@ +@@ -433,7 +_,7 @@ public Vec3 getRedstoneDirection(final BlockPos pos) { - BlockState blockstate = this.level().getBlockState(pos); - if (blockstate.is(Blocks.POWERED_RAIL) && blockstate.getValue(PoweredRailBlock.POWERED)) { -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), pos, this); - if (railshape == RailShape.EAST_WEST) { + BlockState state = this.level().getBlockState(pos); + if (state.is(Blocks.POWERED_RAIL) && state.getValue(PoweredRailBlock.POWERED)) { +- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); ++ RailShape shape = ((BaseRailBlock)state.getBlock()).getRailDirection(state, this.level(), pos, this); + if (shape == RailShape.EAST_WEST) { if (this.isRedstoneConductor(pos.west())) { return new Vec3(1.0, 0.0, 0.0); -@@ -602,5 +_,42 @@ +@@ -604,5 +_,42 @@ public boolean isFurnace() { return false; diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch index 8fd49d5283..e9461c28f4 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java.patch @@ -1,29 +1,30 @@ --- a/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java +++ b/net/minecraft/world/entity/vehicle/minecart/NewMinecartBehavior.java -@@ -169,7 +_,7 @@ +@@ -153,7 +_,7 @@ public void adjustToRails(final BlockPos targetBlockPos, final BlockState currentState, final boolean instant) { if (BaseRailBlock.isRail(currentState)) { -- RailShape railshape = currentState.getValue(((BaseRailBlock)currentState.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)currentState.getBlock()).getRailDirection(currentState, this.level(), targetBlockPos, this.minecart); - Pair pair = AbstractMinecart.exits(railshape); - Vec3 vec3 = new Vec3(pair.getFirst()).scale(0.5); - Vec3 vec31 = new Vec3(pair.getSecond()).scale(0.5); -@@ -257,11 +_,11 @@ - if (flag) { +- RailShape shape = currentState.getValue(((BaseRailBlock)currentState.getBlock()).getShapeProperty()); ++ RailShape shape = ((BaseRailBlock)currentState.getBlock()).getRailDirection(currentState, this.level(), targetBlockPos, this.minecart); + Pair exits = AbstractMinecart.exits(shape); + Vec3 exit0 = new Vec3(exits.getFirst()).scale(0.5); + Vec3 exit1 = new Vec3(exits.getSecond()).scale(0.5); +@@ -244,12 +_,12 @@ + if (onRails) { this.minecart.resetFallDistance(); this.minecart.setOldPosAndRot(); -- if (blockstate.is(Blocks.ACTIVATOR_RAIL)) { -+ if (blockstate.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { - this.minecart.activateMinecart(level, blockpos.getX(), blockpos.getY(), blockpos.getZ(), blockstate.getValue(PoweredRailBlock.POWERED)); +- if (currentState.is(Blocks.ACTIVATOR_RAIL)) { ++ if (currentState.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { + this.minecart + .activateMinecart(level, currentPos.getX(), currentPos.getY(), currentPos.getZ(), currentState.getValue(PoweredRailBlock.POWERED)); } -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), blockpos, this.minecart); - Vec3 vec31 = this.calculateTrackSpeed(level, vec3.horizontal(), newminecartbehavior$trackiteration, blockpos, blockstate, railshape); - if (newminecartbehavior$trackiteration.firstIteration) { - newminecartbehavior$trackiteration.movementLeft = vec31.horizontalDistance(); -@@ -397,7 +_,7 @@ +- RailShape shape = currentState.getValue(((BaseRailBlock)currentState.getBlock()).getShapeProperty()); ++ RailShape shape = ((BaseRailBlock)currentState.getBlock()).getRailDirection(currentState, this.level(), currentPos, this.minecart); + Vec3 newDeltaMovement = this.calculateTrackSpeed(level, initialStepDeltaMovement.horizontal(), trackIteration, currentPos, currentState, shape); + if (trackIteration.firstIteration) { + trackIteration.movementLeft = newDeltaMovement.horizontalDistance(); +@@ -384,7 +_,7 @@ } private Vec3 calculateHaltTrackSpeed(final Vec3 deltaMovement, final BlockState state) { @@ -32,7 +33,7 @@ return deltaMovement.length() < 0.03 ? Vec3.ZERO : deltaMovement.scale(0.5); } else { return deltaMovement; -@@ -405,7 +_,7 @@ +@@ -392,7 +_,7 @@ } private Vec3 calculateBoostTrackSpeed(final Vec3 deltaMovement, final BlockPos pos, final BlockState state) { @@ -41,12 +42,12 @@ if (deltaMovement.length() > 0.01) { return deltaMovement.normalize().scale(deltaMovement.length() + 0.06); } else { -@@ -457,7 +_,7 @@ - BlockState blockstate = this.level().getBlockState(BlockPos.containing(vec36)); - if (flag) { - if (BaseRailBlock.isRail(blockstate)) { -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), BlockPos.containing(vec36), this.minecart); - if (this.restAtVShape(shape, railshape)) { +@@ -444,7 +_,7 @@ + BlockState newBlockState = this.level().getBlockState(BlockPos.containing(newPosition)); + if (inHill) { + if (BaseRailBlock.isRail(newBlockState)) { +- RailShape newRailShape = newBlockState.getValue(((BaseRailBlock)newBlockState.getBlock()).getShapeProperty()); ++ RailShape newRailShape = ((BaseRailBlock)newBlockState.getBlock()).getRailDirection(newBlockState, this.level(), BlockPos.containing(newPosition), this.minecart); + if (this.restAtVShape(shape, newRailShape)) { return 0.0; } diff --git a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch index 33b39e5fcd..53f4548353 100644 --- a/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch +++ b/patches/minecraft/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java.patch @@ -1,93 +1,94 @@ --- a/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java +++ b/net/minecraft/world/entity/vehicle/minecart/OldMinecartBehavior.java @@ -60,9 +_,9 @@ - BlockState blockstate = this.level().getBlockState(blockpos); - boolean onRails = BaseRailBlock.isRail(blockstate); + BlockState state = this.level().getBlockState(var11); + boolean onRails = BaseRailBlock.isRail(state); this.minecart.setOnRails(onRails); - if (onRails) { + if (this.minecart.canUseRail() && onRails) { - this.moveAlongTrack(serverlevel); -- if (blockstate.is(Blocks.ACTIVATOR_RAIL)) { -+ if (blockstate.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { - this.minecart - .activateMinecart(serverlevel, blockpos.getX(), blockpos.getY(), blockpos.getZ(), blockstate.getValue(PoweredRailBlock.POWERED)); + this.moveAlongTrack(level); +- if (state.is(Blocks.ACTIVATOR_RAIL)) { ++ if (state.getBlock() instanceof PoweredRailBlock power && power.isActivatorRail()) { + this.minecart.activateMinecart(level, var11.getX(), var11.getY(), var11.getZ(), state.getValue(PoweredRailBlock.POWERED)); } -@@ -113,18 +_,19 @@ - d1 = blockpos.getY(); - boolean flag = false; - boolean flag1 = false; -- if (blockstate.is(Blocks.POWERED_RAIL)) { -+ BaseRailBlock baserailblock = (BaseRailBlock)blockstate.getBlock(); -+ if (blockstate.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail()) { - flag = blockstate.getValue(PoweredRailBlock.POWERED); - flag1 = !flag; + } else { +@@ -112,18 +_,19 @@ + y = pos.getY(); + boolean powerTrack = false; + boolean haltTrack = false; +- if (state.is(Blocks.POWERED_RAIL)) { ++ BaseRailBlock baserailblock = (BaseRailBlock)state.getBlock(); ++ if (state.getBlock() instanceof PoweredRailBlock powered && !powered.isActivatorRail()) { + powerTrack = state.getValue(PoweredRailBlock.POWERED); + haltTrack = !powerTrack; } -- double d3 = 0.0078125; -+ double d3 = getSlopeAdjustment(); +- double slideSpeed = 0.0078125; ++ double slideSpeed = getSlopeAdjustment(); if (this.minecart.isInWater()) { - d3 *= 0.2; + slideSpeed *= 0.2; } - Vec3 vec31 = this.getDeltaMovement(); -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = baserailblock.getRailDirection(blockstate, this.level(), blockpos, this.minecart); - switch (railshape) { + Vec3 movement = this.getDeltaMovement(); +- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); ++ RailShape shape = baserailblock.getRailDirection(state, this.level(), pos, this.minecart); + switch (shape) { case ASCENDING_EAST: - this.setDeltaMovement(vec31.add(-d3, 0.0, 0.0)); -@@ -176,7 +_,7 @@ + this.setDeltaMovement(movement.add(-slideSpeed, 0.0, 0.0)); +@@ -175,7 +_,7 @@ } } -- if (flag1) { -+ if (flag1 && shouldDoRailFunctions()) { - double d20 = this.getDeltaMovement().horizontalDistance(); - if (d20 < 0.03) { +- if (haltTrack) { ++ if (haltTrack && shouldDoRailFunctions()) { + double speedLength = this.getDeltaMovement().horizontalDistance(); + if (speedLength < 0.03) { this.setDeltaMovement(Vec3.ZERO); -@@ -205,10 +_,7 @@ - d0 = d21 + d4 * d12; - d2 = d9 + d5 * d12; - this.setPos(d0, d1, d2); -- double d23 = this.minecart.isVehicle() ? 0.75 : 1.0; -- double d24 = this.minecart.getMaxSpeed(level); -- vec31 = this.getDeltaMovement(); -- this.minecart.move(MoverType.SELF, new Vec3(Mth.clamp(d23 * vec31.x, -d24, d24), 0.0, Mth.clamp(d23 * vec31.z, -d24, d24))); +@@ -204,11 +_,7 @@ + x = x0 + xD * progress; + z = z0 + zD * progress; + this.setPos(x, y, z); +- double scale = this.minecart.isVehicle() ? 0.75 : 1.0; +- double maxSpeed = this.minecart.getMaxSpeed(level); +- movement = this.getDeltaMovement(); +- this.minecart +- .move(MoverType.SELF, new Vec3(Mth.clamp(scale * movement.x, -maxSpeed, maxSpeed), 0.0, Mth.clamp(scale * movement.z, -maxSpeed, maxSpeed))); + this.moveMinecartOnRail(level); - if (vec3i.getY() != 0 - && Mth.floor(this.minecart.getX()) - blockpos.getX() == vec3i.getX() - && Mth.floor(this.minecart.getZ()) - blockpos.getZ() == vec3i.getZ()) { -@@ -240,7 +_,11 @@ - this.setDeltaMovement(d25 * (j - blockpos.getX()), vec36.y, d25 * (i - blockpos.getZ())); + if (exit0.getY() != 0 && Mth.floor(this.minecart.getX()) - pos.getX() == exit0.getX() && Mth.floor(this.minecart.getZ()) - pos.getZ() == exit0.getZ()) { + this.setPos(this.minecart.getX(), this.minecart.getY() + exit0.getY(), this.minecart.getZ()); + } else if (exit1.getY() != 0 +@@ -238,7 +_,11 @@ + this.setDeltaMovement(otherPow * (xn - pos.getX()), vec3.y, otherPow * (zn - pos.getZ())); } -- if (flag) { +- if (powerTrack) { + if (shouldDoRailFunctions()) { -+ baserailblock.onMinecartPass(blockstate, level(), blockpos, this.minecart); ++ baserailblock.onMinecartPass(state, level(), pos, this.minecart); + } + -+ if (flag && shouldDoRailFunctions()) { - Vec3 vec37 = this.getDeltaMovement(); - double d26 = vec37.horizontalDistance(); - if (d26 > 0.01) { -@@ -283,7 +_,7 @@ ++ if (powerTrack && shouldDoRailFunctions()) { + Vec3 vec3 = this.getDeltaMovement(); + double speedLength = vec3.horizontalDistance(); + if (speedLength > 0.01) { +@@ -281,7 +_,7 @@ - BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); - if (BaseRailBlock.isRail(blockstate)) { -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), new BlockPos(i, j, k), this.minecart); - y = j; - if (railshape.isSlope()) { - y = j + 1; -@@ -321,7 +_,7 @@ + BlockState state = this.level().getBlockState(new BlockPos(xt, yt, zt)); + if (BaseRailBlock.isRail(state)) { +- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); ++ RailShape shape = ((BaseRailBlock)state.getBlock()).getRailDirection(state, this.level(), new BlockPos(xt, yt, zt), this.minecart); + y = yt; + if (shape.isSlope()) { + y = yt + 1; +@@ -319,7 +_,7 @@ - BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k)); - if (BaseRailBlock.isRail(blockstate)) { -- RailShape railshape = blockstate.getValue(((BaseRailBlock)blockstate.getBlock()).getShapeProperty()); -+ RailShape railshape = ((BaseRailBlock)blockstate.getBlock()).getRailDirection(blockstate, this.level(), new BlockPos(i, j, k), this.minecart); - Pair pair = AbstractMinecart.exits(railshape); - Vec3i vec3i = pair.getFirst(); - Vec3i vec3i1 = pair.getSecond(); -@@ -414,5 +_,20 @@ + BlockState state = this.level().getBlockState(new BlockPos(xt, yt, zt)); + if (BaseRailBlock.isRail(state)) { +- RailShape shape = state.getValue(((BaseRailBlock)state.getBlock()).getShapeProperty()); ++ RailShape shape = ((BaseRailBlock)state.getBlock()).getRailDirection(state, this.level(), new BlockPos(xt, yt, zt), this.minecart); + Pair exits = AbstractMinecart.exits(shape); + Vec3i exit0 = exits.getFirst(); + Vec3i exit1 = exits.getSecond(); +@@ -412,5 +_,20 @@ @Override public double getSlowdownFactor() { return this.minecart.isVehicle() ? 0.997 : 0.96; diff --git a/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch index fb1aade29d..e39a21a12f 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AbstractContainerMenu.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/inventory/AbstractContainerMenu.java +++ b/net/minecraft/world/inventory/AbstractContainerMenu.java -@@ -438,6 +_,7 @@ - ItemStack itemstack10 = this.getCarried(); - player.updateTutorialInventoryAction(itemstack10, slot7.getItem(), clickaction); - if (!this.tryItemClickBehaviourOverride(player, clickaction, slot7, itemstack9, itemstack10)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.onItemStackedOn(itemstack10, itemstack9, slot7, clickaction, player, createCarriedSlotAccess())) - if (itemstack9.isEmpty()) { - if (!itemstack10.isEmpty()) { - int i3 = clickaction == ClickAction.PRIMARY ? itemstack10.getCount() : 1; -@@ -658,7 +_,7 @@ - ItemStack itemstack = slot.getItem(); - if (!itemstack.isEmpty() && ItemStack.isSameItemSameComponents(itemStack, itemstack)) { - int j = itemstack.getCount() + itemStack.getCount(); -- int k = slot.getMaxStackSize(itemstack); -+ int k = Math.min(slot.getMaxStackSize(itemstack), itemstack.getMaxStackSize()); - if (j <= k) { +@@ -436,6 +_,7 @@ + ItemStack carried = this.getCarried(); + player.updateTutorialInventoryAction(carried, slotx.getItem(), clickAction); + if (!this.tryItemClickBehaviourOverride(player, clickAction, slotx, clicked, carried)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.onItemStackedOn(carried, clicked, slotx, clickAction, player, createCarriedSlotAccess())) + if (clicked.isEmpty()) { + if (!carried.isEmpty()) { + int amount = clickAction == ClickAction.PRIMARY ? carried.getCount() : 1; +@@ -654,7 +_,7 @@ + ItemStack target = slot.getItem(); + if (!target.isEmpty() && ItemStack.isSameItemSameComponents(itemStack, target)) { + int totalStack = target.getCount() + itemStack.getCount(); +- int maxStackSize = slot.getMaxStackSize(target); ++ int maxStackSize = Math.min(slot.getMaxStackSize(target), target.getMaxStackSize()); + if (totalStack <= maxStackSize) { itemStack.setCount(0); - itemstack.setCount(j); + target.setCount(totalStack); diff --git a/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch index 9c54dca6e4..c7ebd6ab50 100644 --- a/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/AnvilMenu.java.patch @@ -1,48 +1,48 @@ --- a/net/minecraft/world/inventory/AnvilMenu.java +++ b/net/minecraft/world/inventory/AnvilMenu.java -@@ -79,6 +_,8 @@ +@@ -77,6 +_,8 @@ player.giveExperienceLevels(-this.cost.get()); } + float breakChance = net.minecraftforge.event.ForgeEventFactory.onAnvilRepair(player, carried, AnvilMenu.this.inputSlots.getItem(0), AnvilMenu.this.inputSlots.getItem(1)).getBreakChance(); + if (this.repairItemCountCost > 0) { - ItemStack itemstack = this.inputSlots.getItem(1); - if (!itemstack.isEmpty() && itemstack.getCount() > this.repairItemCountCost) { -@@ -101,7 +_,7 @@ + ItemStack addition = this.inputSlots.getItem(1); + if (!addition.isEmpty() && addition.getCount() > this.repairItemCountCost) { +@@ -99,7 +_,7 @@ this.inputSlots.setItem(0, ItemStack.EMPTY); this.access.execute((level, pos) -> { - BlockState blockstate = level.getBlockState(pos); -- if (!player.hasInfiniteMaterials() && blockstate.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < 0.12F) { -+ if (!player.hasInfiniteMaterials() && blockstate.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < breakChance) { - BlockState blockstate1 = AnvilBlock.damage(blockstate); - if (blockstate1 == null) { + BlockState state = level.getBlockState(pos); +- if (!player.hasInfiniteMaterials() && state.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < 0.12F) { ++ if (!player.hasInfiniteMaterials() && state.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < breakChance) { + BlockState newBlockState = AnvilBlock.damage(state); + if (newBlockState == null) { level.removeBlock(pos, false); -@@ -130,8 +_,11 @@ - ItemEnchantments.Mutable itemenchantments$mutable = new ItemEnchantments.Mutable(EnchantmentHelper.getEnchantmentsForCrafting(itemstack1)); - j += (long)itemstack.getOrDefault(DataComponents.REPAIR_COST, 0).intValue() + itemstack2.getOrDefault(DataComponents.REPAIR_COST, 0).intValue(); +@@ -128,8 +_,11 @@ + ItemEnchantments.Mutable enchantments = new ItemEnchantments.Mutable(EnchantmentHelper.getEnchantmentsForCrafting(result)); + tax += (long)input.getOrDefault(DataComponents.REPAIR_COST, 0).intValue() + addition.getOrDefault(DataComponents.REPAIR_COST, 0).intValue(); this.repairItemCountCost = 0; -+ boolean flag = false; ++ boolean usingBook = false; + -+ if (!net.minecraftforge.common.ForgeHooks.onAnvilChange(this, itemstack, itemstack2, resultSlots, itemName, j, this.player)) return; - if (!itemstack2.isEmpty()) { -- boolean flag = itemstack2.has(DataComponents.STORED_ENCHANTMENTS); -+ flag = itemstack2.has(DataComponents.STORED_ENCHANTMENTS); - if (itemstack1.isDamageableItem() && itemstack.isValidRepairItem(itemstack2)) { - int l2 = Math.min(itemstack1.getDamageValue(), itemstack1.getMaxDamage() / 4); - if (l2 <= 0) { -@@ -235,6 +_,10 @@ - itemstack1.remove(DataComponents.CUSTOM_NAME); ++ if (!net.minecraftforge.common.ForgeHooks.onAnvilChange(this, input, addition, resultSlots, itemName, tax, this.player)) return; + if (!addition.isEmpty()) { +- boolean usingBook = addition.has(DataComponents.STORED_ENCHANTMENTS); ++ usingBook = addition.has(DataComponents.STORED_ENCHANTMENTS); + if (result.isDamageableItem() && input.isValidRepairItem(addition)) { + int repairAmount = Math.min(result.getDamageValue(), result.getMaxDamage() / 4); + if (repairAmount <= 0) { +@@ -233,6 +_,10 @@ + result.remove(DataComponents.CUSTOM_NAME); } -+ if (flag && !itemstack1.isBookEnchantable(itemstack2)) { -+ itemstack1 = ItemStack.EMPTY; ++ if (usingBook && !result.isBookEnchantable(addition)) { ++ result = ItemStack.EMPTY; + } + - int k2 = i <= 0 ? 0 : (int)Mth.clamp(j + i, 0L, 2147483647L); - this.cost.set(k2); - if (i <= 0) { -@@ -306,5 +_,9 @@ + int finalPrice = price <= 0 ? 0 : (int)Mth.clamp(tax + price, 0L, 2147483647L); + this.cost.set(finalPrice); + if (price <= 0) { +@@ -304,5 +_,9 @@ public int getCost() { return this.cost.get(); diff --git a/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch index 1463d1a285..25cc4af7a3 100644 --- a/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/BeaconMenu.java.patch @@ -3,13 +3,13 @@ @@ -92,10 +_,8 @@ } - slot.onQuickCraft(itemstack1, itemstack); -- } else if (!this.paymentSlot.hasItem() && this.paymentSlot.mayPlace(itemstack1) && itemstack1.getCount() == 1) { -- if (!this.moveItemStackTo(itemstack1, 0, 1, false)) { + slot.onQuickCraft(stack, clicked); +- } else if (!this.paymentSlot.hasItem() && this.paymentSlot.mayPlace(stack) && stack.getCount() == 1) { +- if (!this.moveItemStackTo(stack, 0, 1, false)) { - return ItemStack.EMPTY; - } -+ } else if (this.moveItemStackTo(itemstack1, 0, 1, false)) { //Forge Fix Shift Clicking in beacons with stacks larger then 1. ++ } else if (this.moveItemStackTo(stack, 0, 1, false)) { //Forge Fix Shift Clicking in beacons with stacks larger then 1. + return ItemStack.EMPTY; } else if (slotIndex >= 1 && slotIndex < 28) { - if (!this.moveItemStackTo(itemstack1, 28, 37, false)) { + if (!this.moveItemStackTo(stack, 28, 37, false)) { return ItemStack.EMPTY; diff --git a/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch index d372d8fd27..701b3abb7b 100644 --- a/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/BrewingStandMenu.java.patch @@ -3,26 +3,26 @@ @@ -45,9 +_,9 @@ this.brewingStand = brewingStand; this.brewingStandData = brewingStandData; - PotionBrewing potionbrewing = inventory.player.level().potionBrewing(); + PotionBrewing potionBrewing = inventory.player.level().potionBrewing(); - this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 0, 56, 51)); - this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 1, 79, 58)); - this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 2, 102, 51)); -+ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 0, 56, 51, potionbrewing)); -+ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 1, 79, 58, potionbrewing)); -+ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 2, 102, 51, potionbrewing)); - this.ingredientSlot = this.addSlot(new BrewingStandMenu.IngredientsSlot(potionbrewing, brewingStand, 3, 79, 17)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 0, 56, 51, potionBrewing)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 1, 79, 58, potionBrewing)); ++ this.addSlot(new BrewingStandMenu.PotionSlot(brewingStand, 2, 102, 51, potionBrewing)); + this.ingredientSlot = this.addSlot(new BrewingStandMenu.IngredientsSlot(potionBrewing, brewingStand, 3, 79, 17)); this.addSlot(new BrewingStandMenu.FuelSlot(brewingStand, 4, 17, 17)); this.addDataSlots(brewingStandData); -@@ -76,7 +_,7 @@ - if (!this.moveItemStackTo(itemstack1, 3, 4, false)) { +@@ -75,7 +_,7 @@ + if (!this.moveItemStackTo(stack, 3, 4, false)) { return ItemStack.EMPTY; } -- } else if (BrewingStandMenu.PotionSlot.mayPlaceItem(itemstack)) { -+ } else if (this.slots.get(0).mayPlace(itemstack)) { // Forge: Use the slot's place which goes through custom recipes. - if (!this.moveItemStackTo(itemstack1, 0, 3, false)) { +- } else if (BrewingStandMenu.PotionSlot.mayPlaceItem(clicked)) { ++ } else if (this.slots.get(0).mayPlace(clicked)) { // Forge: Use the slot's place which goes through custom recipes. + if (!this.moveItemStackTo(stack, 0, 3, false)) { return ItemStack.EMPTY; } -@@ -158,12 +_,23 @@ +@@ -157,12 +_,23 @@ } public static class PotionSlot extends Slot { @@ -46,11 +46,11 @@ return mayPlaceItem(itemStack); } -@@ -176,6 +_,7 @@ +@@ -175,6 +_,7 @@ public void onTake(final Player player, final ItemStack carried) { - Optional> optional = carried.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); - if (optional.isPresent() && player instanceof ServerPlayer serverplayer) { + Optional> potion = carried.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); + if (potion.isPresent() && player instanceof ServerPlayer serverPlayer) { + net.minecraftforge.event.ForgeEventFactory.onPlayerBrewedPotion(player, carried); - CriteriaTriggers.BREWED_POTION.trigger(serverplayer, optional.get()); + CriteriaTriggers.BREWED_POTION.trigger(serverPlayer, potion.get()); } diff --git a/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch index 6d9da3c3de..3b654fc18d 100644 --- a/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/EnchantmentMenu.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/inventory/EnchantmentMenu.java +++ b/net/minecraft/world/inventory/EnchantmentMenu.java -@@ -75,7 +_,7 @@ +@@ -74,7 +_,7 @@ @Override public boolean mayPlace(final ItemStack itemStack) { @@ -9,40 +9,40 @@ } @Override -@@ -103,23 +_,24 @@ - if (!itemstack.isEmpty() && itemstack.isEnchantable()) { +@@ -102,23 +_,24 @@ + if (!itemStack.isEmpty() && itemStack.isEnchantable()) { this.access.execute((level, pos) -> { - IdMap> idmap = level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); -- int j = 0; -+ float j = 0; + IdMap> holders = level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT).asHolderIdMap(); +- int bookcases = 0; ++ float bookcases = 0; - for (BlockPos blockpos : EnchantingTableBlock.BOOKSHELF_OFFSETS) { - if (EnchantingTableBlock.isValidBookShelf(level, pos, blockpos)) { -- j++; -+ j += level.getBlockState(pos.offset(blockpos)).getEnchantPowerBonus(level, pos.offset(blockpos)); + for (BlockPos offset : EnchantingTableBlock.BOOKSHELF_OFFSETS) { + if (EnchantingTableBlock.isValidBookShelf(level, pos, offset)) { +- bookcases++; ++ bookcases += level.getBlockState(pos.offset(offset)).getEnchantPowerBonus(level, pos.offset(offset)); } } this.random.setSeed(this.enchantmentSeed.get()); - for (int k = 0; k < 3; k++) { -- this.costs[k] = EnchantmentHelper.getEnchantmentCost(this.random, k, j, itemstack); -+ this.costs[k] = EnchantmentHelper.getEnchantmentCost(this.random, k, (int)j, itemstack); - this.enchantClue[k] = -1; - this.levelClue[k] = -1; - if (this.costs[k] < k + 1) { - this.costs[k] = 0; + for (int ixx = 0; ixx < 3; ixx++) { +- this.costs[ixx] = EnchantmentHelper.getEnchantmentCost(this.random, ixx, bookcases, itemStack); ++ this.costs[ixx] = EnchantmentHelper.getEnchantmentCost(this.random, ixx, (int)bookcases, itemStack); + this.enchantClue[ixx] = -1; + this.levelClue[ixx] = -1; + if (this.costs[ixx] < ixx + 1) { + this.costs[ixx] = 0; } -+ this.costs[k] = net.minecraftforge.event.ForgeEventFactory.onEnchantmentLevelSet(level, pos, k, (int)j, itemstack, costs[k]); ++ this.costs[ixx] = net.minecraftforge.event.ForgeEventFactory.onEnchantmentLevelSet(level, pos, ixx, (int)bookcases, itemStack, costs[ixx]); } - for (int l = 0; l < 3; l++) { -@@ -246,7 +_,7 @@ - if (!this.moveItemStackTo(itemstack1, 2, 38, true)) { + for (int ix = 0; ix < 3; ix++) { +@@ -245,7 +_,7 @@ + if (!this.moveItemStackTo(stack, 2, 38, true)) { return ItemStack.EMPTY; } -- } else if (itemstack1.is(Items.LAPIS_LAZULI)) { -+ } else if (itemstack1.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS)) { - if (!this.moveItemStackTo(itemstack1, 1, 2, true)) { +- } else if (stack.is(Items.LAPIS_LAZULI)) { ++ } else if (stack.is(net.minecraftforge.common.Tags.Items.ENCHANTING_FUELS)) { + if (!this.moveItemStackTo(stack, 1, 2, true)) { return ItemStack.EMPTY; } diff --git a/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch b/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch index 6edafc7e09..a5cf3b5bda 100644 --- a/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/GrindstoneMenu.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/inventory/GrindstoneMenu.java +++ b/net/minecraft/world/inventory/GrindstoneMenu.java -@@ -43,6 +_,7 @@ +@@ -42,6 +_,7 @@ } }; private final ContainerLevelAccess access; @@ -8,7 +8,7 @@ public GrindstoneMenu(final int containerId, final Inventory inventory) { this(containerId, inventory, ContainerLevelAccess.NULL); -@@ -58,7 +_,7 @@ +@@ -57,7 +_,7 @@ @Override public boolean mayPlace(final ItemStack itemStack) { @@ -17,7 +17,7 @@ } }); this.addSlot(new Slot(this.repairSlots, 1, 49, 40) { -@@ -68,7 +_,7 @@ +@@ -67,7 +_,7 @@ @Override public boolean mayPlace(final ItemStack itemStack) { @@ -26,7 +26,7 @@ } }); this.addSlot(new Slot(this.resultSlots, 2, 129, 34) { -@@ -83,6 +_,7 @@ +@@ -82,6 +_,7 @@ @Override public void onTake(final Player player, final ItemStack carried) { @@ -34,15 +34,15 @@ access.execute((level, pos) -> { if (level instanceof ServerLevel) { ExperienceOrb.award((ServerLevel)level, Vec3.atCenterOf(pos), this.getExperienceAmount(level)); -@@ -95,6 +_,7 @@ +@@ -94,6 +_,7 @@ } private int getExperienceAmount(final Level level) { + if (xp > -1) return xp; - int i = 0; - i += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(0)); - i += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(1)); -@@ -138,6 +_,17 @@ + int amount = 0; + amount += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(0)); + amount += this.getExperienceFromItem(GrindstoneMenu.this.repairSlots.getItem(1)); +@@ -137,6 +_,17 @@ } private ItemStack computeResult(final ItemStack input, final ItemStack additional) { @@ -57,6 +57,6 @@ + this.xp = Integer.MIN_VALUE; + } + - boolean flag = !input.isEmpty() || !additional.isEmpty(); - if (!flag) { + boolean hasAnItem = !input.isEmpty() || !additional.isEmpty(); + if (!hasAnItem) { return ItemStack.EMPTY; diff --git a/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch b/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch index d3cfff9f31..d2b1863b6f 100644 --- a/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch +++ b/patches/minecraft/net/minecraft/world/inventory/ResultSlot.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/inventory/ResultSlot.java +++ b/net/minecraft/world/inventory/ResultSlot.java -@@ -51,6 +_,7 @@ +@@ -50,6 +_,7 @@ protected void checkTakeAchievements(final ItemStack carried) { if (this.removeCount > 0) { carried.onCraftedBy(this.player, this.removeCount); + net.minecraftforge.event.ForgeEventFactory.firePlayerCraftingEvent(this.player, carried, this.craftSlots); } - if (this.container instanceof RecipeCraftingHolder recipecraftingholder) { -@@ -86,7 +_,9 @@ - CraftingInput craftinginput = craftinginput$positioned.input(); - int i = craftinginput$positioned.left(); - int j = craftinginput$positioned.top(); + if (this.container instanceof RecipeCraftingHolder recipeCraftingHolder) { +@@ -85,7 +_,9 @@ + CraftingInput input = positionedRecipe.input(); + int recipeLeft = positionedRecipe.left(); + int recipeTop = positionedRecipe.top(); + net.minecraftforge.common.ForgeHooks.setCraftingPlayer(player); - NonNullList nonnulllist = this.getRemainingItems(craftinginput, player.level()); + NonNullList remaining = this.getRemainingItems(input, player.level()); + net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null); - for (int k = 0; k < craftinginput.height(); k++) { - for (int l = 0; l < craftinginput.width(); l++) { + for (int y = 0; y < input.height(); y++) { + for (int x = 0; x < input.width(); x++) { diff --git a/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch b/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch index d0eee74502..9172e67b60 100644 --- a/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/AxeItem.java.patch @@ -4,38 +4,38 @@ if (playerHasBlockingItemUseIntent(context)) { return InteractionResult.PASS; } else { -- Optional optional = this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos)); -+ Optional optional = this.evaluateNewBlockState(level, blockpos, player, level.getBlockState(blockpos), context); - if (optional.isEmpty()) { +- Optional newBlock = this.evaluateNewBlockState(level, pos, player, level.getBlockState(pos)); ++ Optional newBlock = this.evaluateNewBlockState(level, pos, player, level.getBlockState(pos), context); + if (newBlock.isEmpty()) { return InteractionResult.PASS; } else { @@ -92,17 +_,24 @@ } private Optional evaluateNewBlockState(final Level level, final BlockPos pos, final @Nullable Player player, final BlockState oldState) { -- Optional optional = this.getStripped(oldState); +- Optional strippedBlock = this.getStripped(oldState); + return this.evaluateNewBlockState(level, pos, player, oldState, null); + } + + private Optional evaluateNewBlockState(final Level level, final BlockPos pos, final @Nullable Player player, final BlockState oldState, final @Nullable UseOnContext ctx) { + var strip = ctx == null ? null : oldState.getToolModifiedState(ctx, net.minecraftforge.common.ToolActions.AXE_STRIP, false); -+ Optional optional = strip != null ? Optional.of(strip) : this.getStripped(oldState); - if (optional.isPresent()) { ++ Optional strippedBlock = strip != null ? Optional.of(strip) : this.getStripped(oldState); + if (strippedBlock.isPresent()) { level.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); - return optional; + return strippedBlock; } else { -- Optional optional1 = WeatheringCopper.getPrevious(oldState); +- Optional scrapedBlock = WeatheringCopper.getPrevious(oldState); + var scrape = ctx == null ? null : oldState.getToolModifiedState(ctx, net.minecraftforge.common.ToolActions.AXE_STRIP, false); -+ Optional optional1 = scrape != null ? Optional.of(scrape) : WeatheringCopper.getPrevious(oldState); - if (optional1.isPresent()) { ++ Optional scrapedBlock = scrape != null ? Optional.of(scrape) : WeatheringCopper.getPrevious(oldState); + if (scrapedBlock.isPresent()) { spawnSoundAndParticle(level, pos, player, oldState, SoundEvents.AXE_SCRAPE, 3005); - return optional1; + return scrapedBlock; } else { -- Optional optional2 = Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) +- Optional waxoffBlock = Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) + var waxOff = ctx == null ? null : oldState.getToolModifiedState(ctx, net.minecraftforge.common.ToolActions.AXE_WAX_OFF, false); -+ Optional optional2 = waxOff != null ? Optional.of(waxOff) : Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) ++ Optional waxoffBlock = waxOff != null ? Optional.of(waxOff) : Optional.ofNullable(HoneycombItem.WAX_OFF_BY_BLOCK.get().get(oldState.getBlock())) .map(b -> b.withPropertiesOf(oldState)); - if (optional2.isPresent()) { + if (waxoffBlock.isPresent()) { spawnSoundAndParticle(level, pos, player, oldState, SoundEvents.AXE_WAX_OFF, 3004); @@ -129,5 +_,16 @@ private Optional getStripped(final BlockState state) { diff --git a/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch b/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch index 8ef00f7518..0fc126de93 100644 --- a/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BlockItem.java.patch @@ -1,20 +1,18 @@ --- a/net/minecraft/world/item/BlockItem.java +++ b/net/minecraft/world/item/BlockItem.java -@@ -76,11 +_,11 @@ +@@ -76,9 +_,9 @@ } } -- SoundType soundtype = blockstate1.getSoundType(); -+ SoundType soundtype = blockstate1.getSoundType(level, blockpos, placeContext.getPlayer()); +- SoundType soundType = placedState.getSoundType(); ++ SoundType soundType = placedState.getSoundType(level, pos, placeContext.getPlayer()); level.playSound( - player, - blockpos, -- this.getPlaceSound(blockstate1), -+ this.getPlaceSound(blockstate1, level, blockpos, placeContext.getPlayer()), - SoundSource.BLOCKS, - (soundtype.getVolume() + 1.0F) / 2.0F, - soundtype.getPitch() * 0.8F -@@ -93,10 +_,16 @@ +- player, pos, this.getPlaceSound(placedState), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F ++ player, pos, this.getPlaceSound(placedState, level, pos, placeContext.getPlayer()), SoundSource.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F + ); + level.gameEvent(GameEvent.BLOCK_PLACE, pos, GameEvent.Context.of(player, placedState)); + itemStack.consume(1, player); +@@ -88,10 +_,16 @@ } } @@ -31,7 +29,7 @@ public @Nullable BlockPlaceContext updatePlacementContext(final BlockPlaceContext context) { return context; } -@@ -191,6 +_,10 @@ +@@ -186,6 +_,10 @@ public void registerBlocks(final Map map, final Item item) { map.put(this.getBlock(), item); diff --git a/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch b/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch index 63202c15b3..656b388bae 100644 --- a/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BoneMealItem.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/item/BoneMealItem.java +++ b/net/minecraft/world/item/BoneMealItem.java -@@ -38,7 +_,7 @@ - BlockPos blockpos = context.getClickedPos(); - BlockPos blockpos1 = blockpos.relative(context.getClickedFace()); - ItemStack itemstack = context.getItemInHand(); -- if (growCrop(itemstack, level, blockpos)) { -+ if (applyBonemeal(itemstack, level, blockpos, context.getPlayer())) { +@@ -37,7 +_,7 @@ + BlockPos pos = context.getClickedPos(); + BlockPos relative = pos.relative(context.getClickedFace()); + ItemStack boneMealStack = context.getItemInHand(); +- if (growCrop(boneMealStack, level, pos)) { ++ if (applyBonemeal(boneMealStack, level, pos, context.getPlayer())) { if (!level.isClientSide()) { - itemstack.causeUseVibration(context.getPlayer(), GameEvent.ITEM_INTERACT_FINISH); - level.levelEvent(1505, blockpos, 15); -@@ -62,8 +_,18 @@ + boneMealStack.causeUseVibration(context.getPlayer(), GameEvent.ITEM_INTERACT_FINISH); + level.levelEvent(1505, pos, 15); +@@ -61,8 +_,18 @@ } } @@ -22,9 +22,9 @@ + } + + public static boolean applyBonemeal(final ItemStack itemStack, final Level level, final BlockPos pos, net.minecraft.world.entity.player.Player player) { - BlockState blockstate = level.getBlockState(pos); -+ int hook = net.minecraftforge.event.ForgeEventFactory.onApplyBonemeal(player, level, pos, blockstate, itemStack); + BlockState state = level.getBlockState(pos); ++ int hook = net.minecraftforge.event.ForgeEventFactory.onApplyBonemeal(player, level, pos, state, itemStack); + if (hook != 0) return hook > 0; - if (blockstate.getBlock() instanceof BonemealableBlock bonemealableblock && bonemealableblock.isValidBonemealTarget(level, pos, blockstate)) { + if (state.getBlock() instanceof BonemealableBlock block && block.isValidBonemealTarget(level, pos, state)) { if (level instanceof ServerLevel) { - if (bonemealableblock.isBonemealSuccess(level, level.getRandom(), pos, blockstate)) { + if (block.isBonemealSuccess(level, level.getRandom(), pos, state)) { diff --git a/patches/minecraft/net/minecraft/world/item/BowItem.java.patch b/patches/minecraft/net/minecraft/world/item/BowItem.java.patch index e0d7631219..49c793e511 100644 --- a/patches/minecraft/net/minecraft/world/item/BowItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BowItem.java.patch @@ -3,19 +3,19 @@ @@ -32,6 +_,9 @@ return false; } else { - int i = this.getUseDuration(itemStack, entity) - remainingTime; -+ i = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(itemStack, level, player, i, true); -+ if (i < 0) return false; + int timeHeld = this.getUseDuration(itemStack, entity) - remainingTime; ++ timeHeld = net.minecraftforge.event.ForgeEventFactory.onArrowLoose(itemStack, level, player, timeHeld, true); ++ if (timeHeld < 0) return false; + - float f = getPowerForTime(i); - if (f < 0.1) { + float pow = getPowerForTime(timeHeld); + if (pow < 0.1) { return false; @@ -95,6 +_,8 @@ public InteractionResult use(final Level level, final Player player, final InteractionHand hand) { - ItemStack itemstack = player.getItemInHand(hand); - boolean flag = !player.getProjectile(itemstack).isEmpty(); -+ var ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemstack, level, player, hand, flag); + ItemStack itemStack = player.getItemInHand(hand); + boolean foundProjectile = !player.getProjectile(itemStack).isEmpty(); ++ var ret = net.minecraftforge.event.ForgeEventFactory.onArrowNock(itemStack, level, player, hand, foundProjectile); + if (ret != null) return ret; - if (!player.hasInfiniteMaterials() && !flag) { + if (!player.hasInfiniteMaterials() && !foundProjectile) { return InteractionResult.FAIL; } else { diff --git a/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch index 3f638517e7..6da9bf480f 100644 --- a/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/BucketItem.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/BucketItem.java +++ b/net/minecraft/world/item/BucketItem.java -@@ -34,9 +_,21 @@ +@@ -34,15 +_,29 @@ public class BucketItem extends Item implements DispensibleContainerItem { private final Fluid content; @@ -22,36 +22,35 @@ } @Override -@@ -45,6 +_,8 @@ - BlockHitResult blockhitresult = getPlayerPOVHitResult( - level, player, this.content == Fluids.EMPTY ? ClipContext.Fluid.SOURCE_ONLY : ClipContext.Fluid.NONE - ); -+ var ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(player, level, itemstack, blockhitresult); + public InteractionResult use(final Level level, final Player player, final InteractionHand hand) { + ItemStack itemStack = player.getItemInHand(hand); + BlockHitResult hitResult = getPlayerPOVHitResult(level, player, this.content == Fluids.EMPTY ? ClipContext.Fluid.SOURCE_ONLY : ClipContext.Fluid.NONE); ++ var ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(player, level, itemStack, hitResult); + if (ret != null) return ret; - if (blockhitresult.getType() == HitResult.Type.MISS) { + if (hitResult.getType() == HitResult.Type.MISS) { return InteractionResult.PASS; - } else if (blockhitresult.getType() != HitResult.Type.BLOCK) { -@@ -61,7 +_,7 @@ - ItemStack itemstack3 = bucketpickup.pickupBlock(player, level, blockpos, blockstate1); - if (!itemstack3.isEmpty()) { + } else if (hitResult.getType() != HitResult.Type.BLOCK) { +@@ -59,7 +_,7 @@ + ItemStack taken = bucketPickupBlock.pickupBlock(player, level, pos, blockState); + if (!taken.isEmpty()) { player.awardStat(Stats.ITEM_USED.get(this)); -- bucketpickup.getPickupSound().ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); -+ bucketpickup.getPickupSound(blockstate1).ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); - level.gameEvent(player, GameEvent.FLUID_PICKUP, blockpos); - ItemStack itemstack2 = ItemUtils.createFilledResult(itemstack, player, itemstack3); +- bucketPickupBlock.getPickupSound().ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); ++ bucketPickupBlock.getPickupSound(blockState).ifPresent(soundEvent -> player.playSound(soundEvent, 1.0F, 1.0F)); + level.gameEvent(player, GameEvent.FLUID_PICKUP, pos); + ItemStack result = ItemUtils.createFilledResult(itemStack, player, taken); if (!level.isClientSide()) { -@@ -75,8 +_,8 @@ +@@ -73,8 +_,8 @@ return InteractionResult.FAIL; } else { - BlockState blockstate = level.getBlockState(blockpos); -- BlockPos blockpos2 = blockstate.getBlock() instanceof LiquidBlockContainer && this.content == Fluids.WATER ? blockpos : blockpos1; -- if (this.emptyContents(player, level, blockpos2, blockhitresult)) { -+ BlockPos blockpos2 = canBlockContainFluid(level, blockpos, blockstate) ? blockpos : blockpos1; -+ if (this.emptyContents(player, level, blockpos2, blockhitresult, itemstack)) { - this.checkExtraContent(player, level, itemstack, blockpos2); + BlockState clicked = level.getBlockState(pos); +- BlockPos placePos = clicked.getBlock() instanceof LiquidBlockContainer && this.content == Fluids.WATER ? pos : directionOffsetPos; +- if (this.emptyContents(player, level, placePos, hitResult)) { ++ BlockPos placePos = canBlockContainFluid(level, pos, clicked) ? pos : directionOffsetPos; ++ if (this.emptyContents(player, level, placePos, hitResult, itemStack)) { + this.checkExtraContent(player, level, itemStack, placePos); if (player instanceof ServerPlayer) { - CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayer)player, blockpos2, itemstack); -@@ -100,8 +_,13 @@ + CriteriaTriggers.PLACED_BLOCK.trigger((ServerPlayer)player, placePos, itemStack); +@@ -98,8 +_,13 @@ public void checkExtraContent(final @Nullable LivingEntity user, final Level level, final ItemStack itemStack, final BlockPos pos) { } @@ -61,42 +60,42 @@ + return this.emptyContents(user, level, pos, hitResult, null); + } + -+ public boolean emptyContents(final @Nullable LivingEntity user, final Level level, final BlockPos pos, final @Nullable BlockHitResult hitResult, final @Nullable ItemStack container) { - if (!(this.content instanceof FlowingFluid flowingfluid)) { ++ public boolean emptyContents(final @Nullable LivingEntity user, final Level level, final BlockPos pos, final @Nullable BlockHitResult hitResult, final @Nullable ItemStack containerItem) { + if (!(this.content instanceof FlowingFluid flowingFluid)) { return false; } else { -@@ -113,8 +_,12 @@ - || block instanceof LiquidBlockContainer liquidblockcontainer - && liquidblockcontainer.canPlaceLiquid(user, level, pos, blockstate, this.content); - boolean flag3 = blockstate.isAir() || flag2 && (!flag1 || hitResult == null); -+ java.util.Optional containedFluidStack = java.util.Optional.ofNullable(container).flatMap(net.minecraftforge.fluids.FluidUtil::getFluidContained); - if (!flag3) { +@@ -110,8 +_,12 @@ + boolean placeLiquid = mayReplace + || block instanceof LiquidBlockContainer container && container.canPlaceLiquid(user, level, pos, blockState, this.content); + boolean canPlaceFluidInsideBlock = blockState.isAir() || placeLiquid && (!shiftKeyDown || hitResult == null); ++ var containedFluidStack = java.util.Optional.ofNullable(containerItem).flatMap(net.minecraftforge.fluids.FluidUtil::getFluidContained); + if (!canPlaceFluidInsideBlock) { - return hitResult != null && this.emptyContents(user, level, hitResult.getBlockPos().relative(hitResult.getDirection()), null); -+ return hitResult != null && this.emptyContents(user, level, hitResult.getBlockPos().relative(hitResult.getDirection()), null, container); ++ return hitResult != null && this.emptyContents(user, level, hitResult.getBlockPos().relative(hitResult.getDirection()), null, containerItem); + } else if (containedFluidStack.isPresent() && this.content.getFluidType().isVaporizedOnPlacement(level, pos, containedFluidStack.get())) { + this.content.getFluidType().onVaporize(user, level, pos, containedFluidStack.get()); + return true; } else if (level.environmentAttributes().getValue(EnvironmentAttributes.WATER_EVAPORATES, pos) && this.content.is(FluidTags.WATER)) { - int l = pos.getX(); - int i = pos.getY(); -@@ -131,7 +_,7 @@ + int x = pos.getX(); + int y = pos.getY(); +@@ -124,7 +_,7 @@ } return true; -- } else if (block instanceof LiquidBlockContainer liquidblockcontainer1 && this.content == Fluids.WATER) { -+ } else if (block instanceof LiquidBlockContainer liquidblockcontainer1 && liquidblockcontainer1.canPlaceLiquid(user, level, pos, blockstate, content) && this.content == Fluids.WATER) { - liquidblockcontainer1.placeLiquid(level, pos, blockstate, flowingfluid.getSource(false)); +- } else if (block instanceof LiquidBlockContainer containerx && this.content == Fluids.WATER) { ++ } else if (block instanceof LiquidBlockContainer containerx && containerx.canPlaceLiquid(user, level, pos, blockState, content) && this.content == Fluids.WATER) { + containerx.placeLiquid(level, pos, blockState, flowingFluid.getSource(false)); this.playEmptySound(user, level, pos); return true; -@@ -152,8 +_,33 @@ +@@ -145,8 +_,33 @@ protected void playEmptySound(final @Nullable LivingEntity user, final LevelAccessor level, final BlockPos pos) { - SoundEvent soundevent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; + SoundEvent soundEvent = this.content.is(FluidTags.LAVA) ? SoundEvents.BUCKET_EMPTY_LAVA : SoundEvents.BUCKET_EMPTY; + var custom = this.content.getFluidType().getSound(user, level, pos, net.minecraftforge.common.SoundActions.BUCKET_EMPTY); + if (custom != null) { -+ soundevent = custom; ++ soundEvent = custom; + } - level.playSound(user, pos, soundevent, SoundSource.BLOCKS, 1.0F, 1.0F); + level.playSound(user, pos, soundEvent, SoundSource.BLOCKS, 1.0F, 1.0F); level.gameEvent(user, GameEvent.FLUID_PLACE, pos); + } + diff --git a/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch b/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch index a47e0dc36d..6e9ea0beb1 100644 --- a/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch +++ b/patches/minecraft/net/minecraft/world/item/CreativeModeTab.java.patch @@ -54,11 +54,11 @@ @@ -100,7 +_,7 @@ public void buildContents(final CreativeModeTab.ItemDisplayParameters parameters) { - CreativeModeTab.ItemDisplayBuilder creativemodetab$itemdisplaybuilder = new CreativeModeTab.ItemDisplayBuilder(this, parameters.enabledFeatures); -- this.displayItemsGenerator.accept(parameters, creativemodetab$itemdisplaybuilder); -+ net.minecraftforge.common.ForgeHooks.onCreativeModeTabBuildContents(this, this.displayItemsGenerator, parameters, creativemodetab$itemdisplaybuilder); - this.displayItems = creativemodetab$itemdisplaybuilder.tabContents; - this.displayItemsSearchTab = creativemodetab$itemdisplaybuilder.searchTabContents; + CreativeModeTab.ItemDisplayBuilder displayList = new CreativeModeTab.ItemDisplayBuilder(this, parameters.enabledFeatures); +- this.displayItemsGenerator.accept(parameters, displayList); ++ net.minecraftforge.common.ForgeHooks.onCreativeModeTabBuildContents(this, this.displayItemsGenerator, parameters, displayList); + this.displayItems = displayList.tabContents; + this.displayItemsSearchTab = displayList.searchTabContents; } @@ -117,6 +_,22 @@ return this.displayItemsSearchTab.contains(stack); @@ -108,7 +108,7 @@ return this; } -@@ -175,13 +_,80 @@ +@@ -175,11 +_,80 @@ return this; } @@ -185,10 +185,8 @@ if ((this.type == CreativeModeTab.Type.HOTBAR || this.type == CreativeModeTab.Type.INVENTORY) && this.displayItemsGenerator != EMPTY_GENERATOR) { throw new IllegalStateException("Special tabs can't have display items"); } else { -- CreativeModeTab creativemodetab = new CreativeModeTab( -- this.row, this.column, this.type, this.displayName, this.iconGenerator, this.displayItemsGenerator -- ); -+ CreativeModeTab creativemodetab = this.tabFactory.apply(this); - creativemodetab.alignedRight = this.alignedRight; - creativemodetab.showTitle = this.showTitle; - creativemodetab.canScroll = this.canScroll; +- CreativeModeTab tab = new CreativeModeTab(this.row, this.column, this.type, this.displayName, this.iconGenerator, this.displayItemsGenerator); ++ CreativeModeTab tab = this.tabFactory.apply(this); + tab.alignedRight = this.alignedRight; + tab.showTitle = this.showTitle; + tab.canScroll = this.canScroll; diff --git a/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch b/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch index ab206d9169..1874ab130d 100644 --- a/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/CrossbowItem.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/item/CrossbowItem.java +++ b/net/minecraft/world/item/CrossbowItem.java -@@ -177,6 +_,7 @@ +@@ -185,6 +_,7 @@ final @Nullable LivingEntity targetOverride ) { - if (level instanceof ServerLevel serverlevel) { + if (level instanceof ServerLevel serverLevel) { + if (shooter instanceof Player player && net.minecraftforge.event.ForgeEventFactory.onArrowLoose(weapon, shooter.level(), player, 1, true) < 0) return; - ChargedProjectiles chargedprojectiles = weapon.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY); - if (chargedprojectiles != null && !chargedprojectiles.isEmpty()) { - this.shoot(serverlevel, shooter, hand, weapon, chargedprojectiles.itemCopies(), power, uncertainty, shooter instanceof Player, targetOverride); + ChargedProjectiles charged = weapon.set(DataComponents.CHARGED_PROJECTILES, ChargedProjectiles.EMPTY); + if (charged != null && !charged.isEmpty()) { + this.shoot(serverLevel, shooter, hand, weapon, charged.itemCopies(), power, uncertainty, shooter instanceof Player, targetOverride); diff --git a/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch b/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch index 4db27efb05..4f670b94f4 100644 --- a/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/FishingRodItem.java.patch @@ -3,10 +3,10 @@ @@ -24,7 +_,11 @@ if (player.fishing != null) { if (!level.isClientSide()) { - int i = player.fishing.retrieve(itemstack); -+ ItemStack original = itemstack.copy(); - itemstack.hurtAndBreak(i, player, hand.asEquipmentSlot()); -+ if (itemstack.isEmpty()) { + int dmg = player.fishing.retrieve(itemStack); ++ ItemStack original = itemStack.copy(); + itemStack.hurtAndBreak(dmg, player, hand.asEquipmentSlot()); ++ if (itemStack.isEmpty()) { + net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, original, hand.asEquipmentSlot()); + } } diff --git a/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch b/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch index 1c37971385..db5e52a847 100644 --- a/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/HoeItem.java.patch @@ -16,11 +16,11 @@ @@ -44,7 +_,8 @@ public InteractionResult useOn(final UseOnContext context) { Level level = context.getLevel(); - BlockPos blockpos = context.getClickedPos(); -- Pair, Consumer> pair = TILLABLES.get(level.getBlockState(blockpos).getBlock()); -+ BlockState toolModifiedState = level.getBlockState(blockpos).getToolModifiedState(context, net.minecraftforge.common.ToolActions.HOE_TILL, false); -+ Pair, Consumer> pair = toolModifiedState == null ? null : Pair.of(ctx -> true, changeIntoState(toolModifiedState)); - if (pair == null) { + BlockPos pos = context.getClickedPos(); +- Pair, Consumer> logicPair = TILLABLES.get(level.getBlockState(pos).getBlock()); ++ BlockState toolModifiedState = level.getBlockState(pos).getToolModifiedState(context, net.minecraftforge.common.ToolActions.HOE_TILL, false); ++ Pair, Consumer> logicPair = toolModifiedState == null ? null : Pair.of(ctx -> true, changeIntoState(toolModifiedState)); + if (logicPair == null) { return InteractionResult.PASS; } else { @@ -84,5 +_,10 @@ diff --git a/patches/minecraft/net/minecraft/world/item/Item.java.patch b/patches/minecraft/net/minecraft/world/item/Item.java.patch index 4bf667d719..234e298456 100644 --- a/patches/minecraft/net/minecraft/world/item/Item.java.patch +++ b/patches/minecraft/net/minecraft/world/item/Item.java.patch @@ -19,7 +19,7 @@ public static final Identifier BASE_ATTACK_SPEED_ID = Identifier.withDefaultNamespace("base_attack_speed"); public static final int DEFAULT_MAX_STACK_SIZE = 64; @@ -145,6 +_,7 @@ - LOGGER.error("Item classes should end with Item and {} doesn't.", s); + LOGGER.error("Item classes should end with Item and {} doesn't.", className); } } + initClient(); diff --git a/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch b/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch index f9339ef948..b787f90009 100644 --- a/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ItemStack.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/ItemStack.java +++ b/net/minecraft/world/item/ItemStack.java -@@ -102,7 +_,7 @@ +@@ -100,7 +_,7 @@ import org.jspecify.annotations.Nullable; import org.slf4j.Logger; @@ -9,7 +9,7 @@ private static final List OP_NBT_WARNING = List.of( Component.translatable("item.op_warning.line1").withStyle(ChatFormatting.RED, ChatFormatting.BOLD), Component.translatable("item.op_warning.line2").withStyle(ChatFormatting.RED), -@@ -260,12 +_,15 @@ +@@ -258,12 +_,15 @@ } private ItemStack(final Holder item, final int count, final PatchedDataComponentMap components) { @@ -25,7 +25,7 @@ this.item = null; this.components = new PatchedDataComponentMap(DataComponentMap.EMPTY); } -@@ -358,13 +_,22 @@ +@@ -356,13 +_,22 @@ } public InteractionResult useOn(final UseOnContext context) { @@ -39,25 +39,25 @@ + + private InteractionResult onItemUse(UseOnContext context, java.util.function.Function callback) { Player player = context.getPlayer(); - BlockPos blockpos = context.getClickedPos(); - if (player != null && !player.getAbilities().mayBuild && !this.canPlaceOnBlockInAdventureMode(new BlockInWorld(context.getLevel(), blockpos, false))) { + BlockPos pos = context.getClickedPos(); + if (player != null && !player.getAbilities().mayBuild && !this.canPlaceOnBlockInAdventureMode(new BlockInWorld(context.getLevel(), pos, false))) { return InteractionResult.PASS; } else { - Item item = this.getItem(); -- InteractionResult interactionresult = item.useOn(context); -+ InteractionResult interactionresult = callback.apply(context); - if (player != null - && interactionresult instanceof InteractionResult.Success interactionresult$success - && interactionresult$success.wasItemInteraction()) { -@@ -447,18 +_,26 @@ + Item usedItem = this.getItem(); +- InteractionResult result = usedItem.useOn(context); ++ InteractionResult result = callback.apply(context); + if (player != null && result instanceof InteractionResult.Success success && success.wasItemInteraction()) { + player.awardStat(Stats.ITEM_USED.get(usedItem)); + } +@@ -443,18 +_,26 @@ } public void hurtAndBreak(final int amount, final ServerLevel level, final @Nullable ServerPlayer player, final Consumer onBreak) { -- int i = this.processDurabilityChange(amount, level, player); +- int newAmount = this.processDurabilityChange(amount, level, player); + // FORGE: use context-sensitive sister of processDurabilityChange that calls IForgeItem.damageItem -+ int i = this.processDurabilityChange(amount, level, player, true, onBreak); - if (i != 0) { - this.applyDamage(this.getDamageValue() + i, player, onBreak); ++ int newAmount = this.processDurabilityChange(amount, level, player, true, onBreak); + if (newAmount != 0) { + this.applyDamage(this.getDamageValue() + newAmount, player, onBreak); } } @@ -77,30 +77,30 @@ return amount > 0 ? EnchantmentHelper.processDurabilityChange(level, this, amount) : amount; } } -@@ -498,7 +_,13 @@ - amount, - serverlevel, - owner instanceof ServerPlayer serverplayer ? serverplayer : null, -- brokenItem -> owner.onEquippedItemBroken(brokenItem, slot) -+ brokenItem -> { -+ if (owner instanceof Player player) { -+ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, this, slot); -+ if (player.getUseItem() == this) player.stopUsingItem(); // Forge: fix MC-168573 +@@ -491,7 +_,13 @@ + public void hurtAndBreak(final int amount, final LivingEntity owner, final EquipmentSlot slot) { + if (owner.level() instanceof ServerLevel serverLevel) { + this.hurtAndBreak( +- amount, serverLevel, owner instanceof ServerPlayer player ? player : null, brokenItem -> owner.onEquippedItemBroken(brokenItem, slot) ++ amount, serverLevel, owner instanceof ServerPlayer player ? player : null, brokenItem -> { ++ if (owner instanceof Player ownerPlayer) { ++ net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(ownerPlayer, this, slot); ++ if (ownerPlayer.getUseItem() == this) ownerPlayer.stopUsingItem(); // Forge: fix MC-168573 + } + owner.onEquippedItemBroken(brokenItem, slot); + } ); } } -@@ -857,6 +_,7 @@ - List list = Lists.newArrayList(); - list.add(this.getStyledHoverName()); - this.addDetailsToTooltip(context, tooltipdisplay, player, tooltipFlag, list::add); -+ net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, player, list, tooltipFlag); - return list; +@@ -850,6 +_,7 @@ + List lines = Lists.newArrayList(); + lines.add(this.getStyledHoverName()); + this.addDetailsToTooltip(context, display, player, tooltipFlag, lines::add); ++ net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, player, lines, tooltipFlag); + return lines; } } -@@ -1105,6 +_,7 @@ +@@ -1097,6 +_,7 @@ } } diff --git a/patches/minecraft/net/minecraft/world/item/Items.java.patch b/patches/minecraft/net/minecraft/world/item/Items.java.patch index 762c1d7b7c..de2393b1e7 100644 --- a/patches/minecraft/net/minecraft/world/item/Items.java.patch +++ b/patches/minecraft/net/minecraft/world/item/Items.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/Items.java +++ b/net/minecraft/world/item/Items.java -@@ -2359,7 +_,25 @@ +@@ -2358,7 +_,25 @@ } private static Item registerBlock(final Block block, final Block... alternatives) { @@ -25,14 +25,14 @@ + }; + }); - for (Block blockx : alternatives) { - Item.BY_BLOCK.put(blockx, item); -@@ -2402,10 +_,6 @@ + for (Block alternative : alternatives) { + Item.BY_BLOCK.put(alternative, item); +@@ -2401,10 +_,6 @@ private static Item registerItem(final ResourceKey key, final Function itemFactory, final Item.Properties properties) { Item item = itemFactory.apply(properties.setId(key)); -- if (item instanceof BlockItem blockitem) { -- blockitem.registerBlocks(Item.BY_BLOCK, item); +- if (item instanceof BlockItem blockItem) { +- blockItem.registerBlocks(Item.BY_BLOCK, item); - } - return Registry.register(BuiltInRegistries.ITEM, key, item); diff --git a/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch b/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch index a25f5ff592..f414a50d6f 100644 --- a/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/MobBucketItem.java.patch @@ -36,8 +36,8 @@ - Mob mob = this.type.create(level, EntityType.createDefaultStackConfig(level, itemStack, null), spawnPos, EntitySpawnReason.BUCKET, true, false); + Mob mob = this.getFishType().create(level, EntityType.createDefaultStackConfig(level, itemStack, null), spawnPos, EntitySpawnReason.BUCKET, true, false); if (mob instanceof Bucketable bucketable) { - CustomData customdata = itemStack.getOrDefault(DataComponents.BUCKET_ENTITY_DATA, CustomData.EMPTY); - bucketable.loadFromBucketTag(customdata.copyTag()); + CustomData entityData = itemStack.getOrDefault(DataComponents.BUCKET_ENTITY_DATA, CustomData.EMPTY); + bucketable.loadFromBucketTag(entityData.copyTag()); @@ -52,5 +_,13 @@ level.addFreshEntityWithPassengers(mob); mob.playAmbientSound(); diff --git a/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch b/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch index c07bb2ac52..e281479691 100644 --- a/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ProjectileWeaponItem.java.patch @@ -2,27 +2,27 @@ +++ b/net/minecraft/world/item/ProjectileWeaponItem.java @@ -95,6 +_,7 @@ ) { - ArrowItem arrowitem = projectile.getItem() instanceof ArrowItem arrowitem1 ? arrowitem1 : (ArrowItem)Items.ARROW; - AbstractArrow abstractarrow = arrowitem.createArrow(level, projectile, shooter, weapon); -+ abstractarrow = customArrow(abstractarrow); + ArrowItem arrowItem = projectile.getItem() instanceof ArrowItem arrow ? arrow : (ArrowItem)Items.ARROW; + AbstractArrow arrowx = arrowItem.createArrow(level, projectile, shooter, weapon); ++ arrowx = customArrow(arrowx); if (isCrit) { - abstractarrow.setCritArrow(true); + arrowx.setCritArrow(true); } -@@ -109,9 +_,10 @@ - int i = shooter.level() instanceof ServerLevel serverlevel ? EnchantmentHelper.processProjectileCount(serverlevel, weapon, shooter, 1) : 1; - List list = new ArrayList<>(i); - ItemStack itemstack1 = projectile.copy(); +@@ -111,9 +_,10 @@ + : 1; + List drawn = new ArrayList<>(numProjectiles); + ItemStack projectileCopy = projectile.copy(); + boolean infinite = projectile.getItem() instanceof ArrowItem arrow && arrow.isInfinite(projectile, weapon, shooter); - for (int j = 0; j < i; j++) { -- ItemStack itemstack = useAmmo(weapon, j == 0 ? projectile : itemstack1, shooter, j > 0); -+ ItemStack itemstack = useAmmo(weapon, j == 0 ? projectile : itemstack1, shooter, j > 0 || infinite); - if (!itemstack.isEmpty()) { - list.add(itemstack); + for (int i = 0; i < numProjectiles; i++) { +- ItemStack drawnStack = useAmmo(weapon, i == 0 ? projectile : projectileCopy, shooter, i > 0); ++ ItemStack drawnStack = useAmmo(weapon, i == 0 ? projectile : projectileCopy, shooter, i > 0 || infinite); + if (!drawnStack.isEmpty()) { + drawn.add(drawnStack); } -@@ -139,5 +_,9 @@ +@@ -141,5 +_,9 @@ - return itemstack; + return used; } + } + diff --git a/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch b/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch index faa41c8618..800b99c334 100644 --- a/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch +++ b/patches/minecraft/net/minecraft/world/item/ShovelItem.java.patch @@ -4,14 +4,14 @@ return InteractionResult.PASS; } else { Player player = context.getPlayer(); -- BlockState blockstate1 = FLATTENABLES.get(blockstate.getBlock()); -+ BlockState blockstate1 = blockstate.getToolModifiedState(context, net.minecraftforge.common.ToolActions.SHOVEL_FLATTEN, false); - BlockState blockstate2 = null; -- if (blockstate1 != null && level.getBlockState(blockpos.above()).isAir()) { -+ if (blockstate1 != null && level.isEmptyBlock(blockpos.above())) { - level.playSound(player, blockpos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); - blockstate2 = blockstate1; - } else if (blockstate.getBlock() instanceof CampfireBlock && blockstate.getValue(CampfireBlock.LIT)) { +- BlockState newState = FLATTENABLES.get(blockState.getBlock()); ++ BlockState newState = blockState.getToolModifiedState(context, net.minecraftforge.common.ToolActions.SHOVEL_FLATTEN, false); + BlockState updatedState = null; +- if (newState != null && level.getBlockState(pos.above()).isAir()) { ++ if (newState != null && level.isEmptyBlock(pos.above())) { + level.playSound(player, pos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); + updatedState = newState; + } else if (blockState.getBlock() instanceof CampfireBlock && blockState.getValue(CampfireBlock.LIT)) { @@ -70,5 +_,15 @@ return InteractionResult.PASS; } diff --git a/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch b/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch index db618528a1..3a26d1fdf5 100644 --- a/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch +++ b/patches/minecraft/net/minecraft/world/item/alchemy/PotionBrewing.java.patch @@ -57,8 +57,8 @@ + /** @deprecated Forge: use hasMix(ItemStack, ItemStack)*/ public boolean hasPotionMix(final ItemStack source, final ItemStack ingredient) { - Optional> optional = source.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); - if (optional.isEmpty()) { + Optional> potion = source.getOrDefault(DataComponents.POTION_CONTENTS, PotionContents.EMPTY).potion(); + if (potion.isEmpty()) { @@ -102,6 +_,19 @@ } @@ -103,10 +103,10 @@ + } + public static PotionBrewing bootstrap(final FeatureFlagSet enabledFeatures) { - PotionBrewing.Builder potionbrewing$builder = new PotionBrewing.Builder(enabledFeatures); - addVanillaMixes(potionbrewing$builder); -+ net.minecraftforge.event.ForgeEventFactory.onBrewingRecipeRegister(potionbrewing$builder, enabledFeatures); - return potionbrewing$builder.build(); + PotionBrewing.Builder builder = new PotionBrewing.Builder(enabledFeatures); + addVanillaMixes(builder); ++ net.minecraftforge.event.ForgeEventFactory.onBrewingRecipeRegister(builder, enabledFeatures); + return builder.build(); } @@ -197,6 +_,7 @@ diff --git a/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch b/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch index 5653ab27e4..85f0f844d2 100644 --- a/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch +++ b/patches/minecraft/net/minecraft/world/item/component/CustomData.java.patch @@ -9,5 +9,5 @@ + } + public static void update(final DataComponentType component, final ItemStack itemStack, final Consumer consumer) { - CustomData customdata = itemStack.getOrDefault(component, EMPTY).update(consumer); - if (customdata.tag.isEmpty()) { + CustomData newData = itemStack.getOrDefault(component, EMPTY).update(consumer); + if (newData.tag.isEmpty()) { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch index 738e31b1eb..556426ce03 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java +++ b/net/minecraft/world/item/crafting/BannerDuplicateRecipe.java -@@ -98,7 +_,7 @@ - for (int i = 0; i < nonnulllist.size(); i++) { - ItemStack itemstack = input.getItem(i); - if (!itemstack.isEmpty()) { -- ItemStackTemplate itemstacktemplate = itemstack.getItem().getCraftingRemainder(); -+ ItemStackTemplate itemstacktemplate = itemstack.getCraftingRemainder(); - if (itemstacktemplate != null) { - nonnulllist.set(i, itemstacktemplate.create()); - } else if (!itemstack.getOrDefault(DataComponents.BANNER_PATTERNS, BannerPatternLayers.EMPTY).layers().isEmpty()) { +@@ -97,7 +_,7 @@ + for (int slot = 0; slot < result.size(); slot++) { + ItemStack itemStack = input.getItem(slot); + if (!itemStack.isEmpty()) { +- ItemStackTemplate remainder = itemStack.getItem().getCraftingRemainder(); ++ ItemStackTemplate remainder = itemStack.getCraftingRemainder(); + if (remainder != null) { + result.set(slot, remainder.create()); + } else if (!itemStack.getOrDefault(DataComponents.BANNER_PATTERNS, BannerPatternLayers.EMPTY).layers().isEmpty()) { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch index 2eb08ed87a..bb1f36ea96 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/BookCloningRecipe.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/crafting/BookCloningRecipe.java +++ b/net/minecraft/world/item/crafting/BookCloningRecipe.java -@@ -131,7 +_,7 @@ +@@ -130,7 +_,7 @@ - for (int i = 0; i < nonnulllist.size(); i++) { - ItemStack itemstack = input.getItem(i); -- ItemStackTemplate itemstacktemplate = itemstack.getItem().getCraftingRemainder(); -+ ItemStackTemplate itemstacktemplate = itemstack.getCraftingRemainder(); - if (itemstacktemplate != null) { - nonnulllist.set(i, itemstacktemplate.create()); - } else if (itemstack.has(DataComponents.WRITTEN_BOOK_CONTENT)) { + for (int slot = 0; slot < result.size(); slot++) { + ItemStack itemStack = input.getItem(slot); +- ItemStackTemplate remainder = itemStack.getItem().getCraftingRemainder(); ++ ItemStackTemplate remainder = itemStack.getCraftingRemainder(); + if (remainder != null) { + result.set(slot, remainder.create()); + } else if (itemStack.has(DataComponents.WRITTEN_BOOK_CONTENT)) { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch index 6a1512f8e3..70076f9f32 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/CraftingRecipe.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/item/crafting/CraftingRecipe.java +++ b/net/minecraft/world/item/crafting/CraftingRecipe.java @@ -27,8 +_,7 @@ - NonNullList nonnulllist = NonNullList.withSize(input.size(), ItemStack.EMPTY); + NonNullList result = NonNullList.withSize(input.size(), ItemStack.EMPTY); - for (int i = 0; i < nonnulllist.size(); i++) { -- Item item = input.getItem(i).getItem(); -- ItemStackTemplate itemstacktemplate = item.getCraftingRemainder(); -+ ItemStackTemplate itemstacktemplate = input.getItem(i).getCraftingRemainder(); - nonnulllist.set(i, itemstacktemplate != null ? itemstacktemplate.create() : ItemStack.EMPTY); + for (int slot = 0; slot < result.size(); slot++) { +- Item item = input.getItem(slot).getItem(); +- ItemStackTemplate remainder = item.getCraftingRemainder(); ++ ItemStackTemplate remainder = input.getItem(slot).getCraftingRemainder(); + result.set(slot, remainder != null ? remainder.create() : ItemStack.EMPTY); } diff --git a/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch index 413a9fab4e..bf0d8d4359 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/Ingredient.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/Ingredient.java +++ b/net/minecraft/world/item/crafting/Ingredient.java -@@ -24,18 +_,26 @@ +@@ -23,18 +_,26 @@ import net.minecraft.world.level.ItemLike; public class Ingredient implements Predicate, StackedContents.IngredientInfo> { @@ -33,9 +33,9 @@ values.unwrap().ifRight(directValues -> { if (directValues.isEmpty()) { throw new UnsupportedOperationException("Ingredients can't be empty"); -@@ -107,5 +_,50 @@ +@@ -106,5 +_,50 @@ } else { - return slotdisplay; + return inputDisplay; } + } + diff --git a/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch index dfeb371ee6..c46060b222 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/RecipeManager.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/RecipeManager.java +++ b/net/minecraft/world/item/crafting/RecipeManager.java -@@ -63,15 +_,22 @@ +@@ -61,15 +_,22 @@ private SelectableRecipe.SingleInputSet stonecutterRecipes = SelectableRecipe.SingleInputSet.empty(); private List allDisplays = List.of(); private Map>, List> recipeToDisplay = Map.of(); @@ -17,18 +17,18 @@ } protected RecipeMap prepare(final ResourceManager manager, final ProfilerFiller profiler) { - SortedMap> sortedmap = new TreeMap<>(); + SortedMap> recipes = new TreeMap<>(); SimpleJsonResourceReloadListener.scanDirectory( -- manager, RECIPE_LISTER, this.registries.createSerializationContext(JsonOps.INSTANCE), Recipe.CODEC, sortedmap -+ manager, RECIPE_LISTER, this.context.wrap(this.registries.createSerializationContext(JsonOps.INSTANCE)), Recipe.CODEC, sortedmap +- manager, RECIPE_LISTER, this.registries.createSerializationContext(JsonOps.INSTANCE), Recipe.CODEC, recipes ++ manager, RECIPE_LISTER, this.context.wrap(this.registries.createSerializationContext(JsonOps.INSTANCE)), Recipe.CODEC, recipes ); - List> list = new ArrayList<>(sortedmap.size()); - sortedmap.forEach((id, recipe) -> { -@@ -88,6 +_,7 @@ + List> recipeHolders = new ArrayList<>(recipes.size()); + recipes.forEach((id, recipe) -> { +@@ -86,6 +_,7 @@ } public void finalizeRecipeLoading(final FeatureFlagSet enabledFlags) { + //net.minecraftforge.event.ForgeEventFactory.onTagsUpdated(this.registries, false, false); - List> list = new ArrayList<>(); - List list1 = RECIPE_PROPERTY_SETS.entrySet() + List> stonecutterRecipes = new ArrayList<>(); + List propertySetCollectors = RECIPE_PROPERTY_SETS.entrySet() .stream() diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch index 44956beb32..4c42452a08 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipe.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/ShapedRecipe.java +++ b/net/minecraft/world/item/crafting/ShapedRecipe.java -@@ -16,7 +_,19 @@ +@@ -15,7 +_,19 @@ import net.minecraft.world.item.crafting.display.SlotDisplay; import net.minecraft.world.level.Level; @@ -21,7 +21,7 @@ public static final MapCodec MAP_CODEC = RecordCodecBuilder.mapCodec( i -> i.group( Recipe.CommonInfo.MAP_CODEC.forGetter(o -> o.commonInfo), -@@ -78,6 +_,16 @@ +@@ -77,6 +_,16 @@ public int getHeight() { return this.pattern.height(); diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch index e0868266cd..c8be94512a 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapedRecipePattern.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/ShapedRecipePattern.java +++ b/net/minecraft/world/item/crafting/ShapedRecipePattern.java -@@ -204,18 +_,22 @@ +@@ -203,18 +_,22 @@ return this.ingredients; } @@ -17,13 +17,13 @@ } else if (strings.isEmpty()) { return DataResult.error(() -> "Invalid pattern: empty pattern not allowed"); } else { - int i = strings.getFirst().length(); + int firstLength = strings.getFirst().length(); - for (String s : strings) { -- if (s.length() > 3) { + for (String line : strings) { +- if (line.length() > 3) { - return DataResult.error(() -> "Invalid pattern: too many columns, 3 is maximum"); -+ if (s.length() > ShapedRecipe.MAX_HEIGHT) { ++ if (line.length() > ShapedRecipe.MAX_HEIGHT) { + return DataResult.error(() -> "Invalid pattern: too many columns, " + ShapedRecipe.MAX_HEIGHT + " is maximum"); } - if (i != s.length()) { + if (firstLength != line.length()) { diff --git a/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch b/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch index b9c2ceef46..84301529be 100644 --- a/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch +++ b/patches/minecraft/net/minecraft/world/item/crafting/ShapelessRecipe.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/item/crafting/ShapelessRecipe.java +++ b/net/minecraft/world/item/crafting/ShapelessRecipe.java -@@ -21,7 +_,7 @@ +@@ -20,7 +_,7 @@ Recipe.CommonInfo.MAP_CODEC.forGetter(o -> o.commonInfo), CraftingRecipe.CraftingBookInfo.MAP_CODEC.forGetter(o -> o.bookInfo), ItemStackTemplate.CODEC.fieldOf("result").forGetter(o -> o.result), @@ -9,7 +9,7 @@ ) .apply(i, ShapelessRecipe::new) ); -@@ -39,6 +_,7 @@ +@@ -38,6 +_,7 @@ public static final RecipeSerializer SERIALIZER = new RecipeSerializer<>(MAP_CODEC, STREAM_CODEC); private final ItemStackTemplate result; private final List ingredients; @@ -17,7 +17,7 @@ public ShapelessRecipe( final Recipe.CommonInfo commonInfo, final CraftingRecipe.CraftingBookInfo bookInfo, final ItemStackTemplate result, final List ingredients -@@ -46,6 +_,7 @@ +@@ -45,6 +_,7 @@ super(commonInfo, bookInfo); this.result = result; this.ingredients = ingredients; @@ -25,7 +25,7 @@ } @Override -@@ -61,10 +_,12 @@ +@@ -60,10 +_,12 @@ public boolean matches(final CraftingInput input, final Level level) { if (input.ingredientCount() != this.ingredients.size()) { return false; diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch index c6a9267b6d..77af83fa5c 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/EnchantmentHelper.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/item/enchantment/EnchantmentHelper.java +++ b/net/minecraft/world/item/enchantment/EnchantmentHelper.java -@@ -612,7 +_,7 @@ +@@ -602,7 +_,7 @@ public static List getAvailableEnchantmentResults(final int value, final ItemStack itemStack, final Stream> source) { - List list = Lists.newArrayList(); - boolean flag = itemStack.is(Items.BOOK); -- source.filter(enchantment -> enchantment.value().isPrimaryItem(itemStack) || flag).forEach(holder -> { -+ source.filter(enchantment -> itemStack.canApplyAtEnchantingTable(enchantment) || flag).forEach(holder -> { + List results = Lists.newArrayList(); + boolean isBook = itemStack.is(Items.BOOK); +- source.filter(enchantment -> enchantment.value().isPrimaryItem(itemStack) || isBook).forEach(holder -> { ++ source.filter(enchantment -> itemStack.canApplyAtEnchantingTable(enchantment) || isBook).forEach(holder -> { Enchantment enchantment = holder.value(); - for (int i = enchantment.getMaxLevel(); i >= enchantment.getMinLevel(); i--) { + for (int level = enchantment.getMaxLevel(); level >= enchantment.getMinLevel(); level--) { diff --git a/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch b/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch index f18a22f854..bec1e9be00 100644 --- a/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch +++ b/patches/minecraft/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java +++ b/net/minecraft/world/item/enchantment/effects/ReplaceDisk.java -@@ -48,6 +_,7 @@ - for (BlockPos blockpos1 : BlockPos.betweenClosed(blockpos.offset(-i, 0, -i), blockpos.offset(i, Math.min(j - 1, 0), i))) { - if (blockpos1.distToCenterSqr(position.x(), blockpos1.getY() + 0.5, position.z()) < Mth.square(i) - && this.predicate.map(p -> p.test(serverLevel, blockpos1)).orElse(true) -+ && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(entity, net.minecraftforge.common.util.BlockSnapshot.create(serverLevel.dimension(), serverLevel, blockpos), net.minecraft.core.Direction.UP) - && serverLevel.setBlockAndUpdate(blockpos1, this.blockState.getState(serverLevel, randomsource, blockpos1))) { - this.triggerGameEvent.ifPresent(event -> serverLevel.gameEvent(entity, (Holder)event, blockpos1)); +@@ -47,6 +_,7 @@ + for (BlockPos pos : BlockPos.betweenClosed(centerBlock.offset(-dist, 0, -dist), centerBlock.offset(dist, Math.min(height - 1, 0), dist))) { + if (pos.distToCenterSqr(position.x(), pos.getY() + 0.5, position.z()) < Mth.square(dist) + && this.predicate.map(p -> p.test(serverLevel, pos)).orElse(true) ++ && !net.minecraftforge.event.ForgeEventFactory.onBlockPlace(entity, net.minecraftforge.common.util.BlockSnapshot.create(serverLevel.dimension(), serverLevel, centerBlock), net.minecraft.core.Direction.UP) + && serverLevel.setBlockAndUpdate(pos, this.blockState.getState(serverLevel, random, pos))) { + this.triggerGameEvent.ifPresent(event -> serverLevel.gameEvent(entity, (Holder)event, pos)); } diff --git a/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch index ddb16b6f1e..a58fe4335b 100644 --- a/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/BaseSpawner.java.patch @@ -1,26 +1,27 @@ --- a/net/minecraft/world/level/BaseSpawner.java +++ b/net/minecraft/world/level/BaseSpawner.java -@@ -146,14 +_,15 @@ +@@ -146,15 +_,16 @@ - entity.snapTo(entity.getX(), entity.getY(), entity.getZ(), randomsource.nextFloat() * 360.0F, 0.0F); + entity.snapTo(entity.getX(), entity.getY(), entity.getZ(), random.nextFloat() * 360.0F, 0.0F); if (entity instanceof Mob mob) { -- if (spawndata.getCustomSpawnRules().isEmpty() && !mob.checkSpawnRules(level, EntitySpawnReason.SPAWNER) +- if (nextSpawnData.getCustomSpawnRules().isEmpty() && !mob.checkSpawnRules(level, EntitySpawnReason.SPAWNER) - || !mob.checkSpawnObstruction(level)) { -+ if (!net.minecraftforge.event.ForgeEventFactory.checkSpawnPositionSpawner(mob, level, EntitySpawnReason.SPAWNER, spawndata, this)) { ++ if (!net.minecraftforge.event.ForgeEventFactory.checkSpawnPositionSpawner(mob, level, EntitySpawnReason.SPAWNER, nextSpawnData, this)) { continue; } - boolean flag1 = spawndata.getEntityToSpawn().size() == 1 && spawndata.getEntityToSpawn().getString("id").isPresent(); -- if (flag1) { + boolean hasNoConfiguration = nextSpawnData.getEntityToSpawn().size() == 1 + && nextSpawnData.getEntityToSpawn().getString("id").isPresent(); +- if (hasNoConfiguration) { - ((Mob)entity).finalizeSpawn(level, level.getCurrentDifficultyAt(entity.blockPosition()), EntitySpawnReason.SPAWNER, null); + // Forge: Patch in FinalizeSpawn for spawners so it may be fired unconditionally, instead of only when vanilla normally would trigger it. -+ var event = net.minecraftforge.event.ForgeEventFactory.onFinalizeSpawnSpawner(mob, level, level.getCurrentDifficultyAt(entity.blockPosition()), null, valueinput, this); -+ if (event != null && flag1) { ++ var event = net.minecraftforge.event.ForgeEventFactory.onFinalizeSpawnSpawner(mob, level, level.getCurrentDifficultyAt(entity.blockPosition()), null, input, this); ++ if (event != null && hasNoConfiguration) { + mob.finalizeSpawn(level, event.getDifficulty(), EntitySpawnReason.SPAWNER, null); } - spawndata.getEquipment().ifPresent(mob::equip); -@@ -270,5 +_,14 @@ + nextSpawnData.getEquipment().ifPresent(mob::equip); +@@ -271,5 +_,14 @@ public double getOSpin() { return this.oSpin; diff --git a/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch b/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch index 270fd943b1..cd03031fdc 100644 --- a/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch +++ b/patches/minecraft/net/minecraft/world/level/DataPackConfig.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/DataPackConfig.java +++ b/net/minecraft/world/level/DataPackConfig.java -@@ -16,7 +_,7 @@ +@@ -15,7 +_,7 @@ private final List disabled; public DataPackConfig(final List enabled, final List disabled) { @@ -9,7 +9,7 @@ this.disabled = ImmutableList.copyOf(disabled); } -@@ -26,5 +_,9 @@ +@@ -25,5 +_,9 @@ public List getDisabled() { return this.disabled; diff --git a/patches/minecraft/net/minecraft/world/level/Level.java.patch b/patches/minecraft/net/minecraft/world/level/Level.java.patch index 86cf72c35b..3dc8493f6c 100644 --- a/patches/minecraft/net/minecraft/world/level/Level.java.patch +++ b/patches/minecraft/net/minecraft/world/level/Level.java.patch @@ -32,7 +32,7 @@ } else if (!this.isClientSide() && this.isDebug()) { @@ -222,11 +_,35 @@ } else { - LevelChunk levelchunk = this.getChunkAt(pos); + LevelChunk chunk = this.getChunkAt(pos); Block block = blockState.getBlock(); + + pos = pos.immutable(); // Forge - prevent mutable BlockPos leaks @@ -42,14 +42,14 @@ + this.capturedBlockSnapshots.add(blockSnapshot); + } + - BlockState blockstate = levelchunk.setBlockState(pos, blockState, updateFlags); - if (blockstate == null) { + BlockState oldState = chunk.setBlockState(pos, blockState, updateFlags); + if (oldState == null) { + if (blockSnapshot != null) this.capturedBlockSnapshots.remove(blockSnapshot); return false; } else { - BlockState blockstate1 = this.getBlockState(pos); + BlockState newState = this.getBlockState(pos); + if (blockSnapshot == null) { // Don't notify clients or update physics while capturing blockstates -+ this.markAndNotifyBlock(pos, levelchunk, blockstate, blockState, updateFlags, updateLimit); ++ this.markAndNotifyBlock(pos, chunk, oldState, blockState, updateFlags, updateLimit); + } + + return true; @@ -58,19 +58,19 @@ + } + + // Split off from original setBlockState(BlockPos, BlockState, int, int) method in order to directly send client and physic updates -+ public void markAndNotifyBlock(final BlockPos pos, final @Nullable LevelChunk levelchunk, final BlockState blockstate, final BlockState blockState, @Block.UpdateFlags final int updateFlags, final int updateLimit) { ++ public void markAndNotifyBlock(final BlockPos pos, final @Nullable LevelChunk chunk, final BlockState oldState, final BlockState blockState, @Block.UpdateFlags final int updateFlags, final int updateLimit) { + Block block = blockState.getBlock(); -+ BlockState blockstate1 = getBlockState(pos); ++ BlockState newState = getBlockState(pos); + { + { - if (blockstate1 == blockState) { - if (blockstate != blockstate1) { - this.setBlocksDirty(pos, blockstate, blockstate1); + if (newState == blockState) { + if (oldState != newState) { + this.setBlocksDirty(pos, oldState, newState); @@ -253,9 +_,8 @@ } - this.updatePOIOnBlockStateChange(pos, blockstate, blockstate1); -+ blockState.onBlockStateChange(this, pos, blockstate); + this.updatePOIOnBlockStateChange(pos, oldState, newState); ++ blockState.onBlockStateChange(this, pos, oldState); } - - return true; @@ -111,15 +111,15 @@ try { + net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackStart(entity); tick.accept(entity); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking entity"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Entity being ticked"); - entity.fillCrashReportCategory(crashreportcategory); + } catch (Throwable var6) { + CrashReport report = CrashReport.forThrowable(var6, "Ticking entity"); + CrashReportCategory category = report.addCategory("Entity being ticked"); + entity.fillCrashReportCategory(category); + if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringEntities.get()) { -+ com.mojang.logging.LogUtils.getLogger().error("{}", crashreport.getFriendlyReport(net.minecraft.ReportType.CRASH)); ++ com.mojang.logging.LogUtils.getLogger().error("{}", report.getFriendlyReport(net.minecraft.ReportType.CRASH)); + entity.discard(); + } else - throw new ReportedException(crashreport); + throw new ReportedException(report); + } finally { + net.minecraftforge.server.timings.TimeTracker.ENTITY_UPDATE.trackEnd(entity); } @@ -133,53 +133,52 @@ } public boolean isLoaded(final BlockPos pos) { -@@ -776,9 +_,9 @@ +@@ -774,8 +_,8 @@ } }); -- for (EnderDragonPart enderdragonpart : this.dragonParts()) { -+ for (var enderdragonpart : this.getPartEntities()) { - if (enderdragonpart != except -- && enderdragonpart.parentMob != except -+ && enderdragonpart.getParent() != except - && selector.test(enderdragonpart) - && bb.intersects(enderdragonpart.getBoundingBox())) { - list.add(enderdragonpart); -@@ -813,8 +_,8 @@ +- for (EnderDragonPart dragonPart : this.dragonParts()) { +- if (dragonPart != except && dragonPart.parentMob != except && selector.test(dragonPart) && bb.intersects(dragonPart.getBoundingBox())) { ++ for (var dragonPart : this.getPartEntities()) { ++ if (dragonPart != except && dragonPart.getParent() != except && selector.test(dragonPart) && bb.intersects(dragonPart.getBoundingBox())) { + output.add(dragonPart); + } + } +@@ -808,8 +_,8 @@ } } -- if (e instanceof EnderDragon enderdragon) { -- for (EnderDragonPart enderdragonpart : enderdragon.getSubEntities()) { +- if (e instanceof EnderDragon enderDragon) { +- for (EnderDragonPart subEntity : enderDragon.getSubEntities()) { + if (e.isMultipartEntity()) { -+ for (var enderdragonpart : e.getParts()) { - T t = type.tryCast(enderdragonpart); - if (t != null && selector.test(t)) { - output.add(t); -@@ -1000,17 +_,16 @@ ++ for (var subEntity : e.getParts()) { + T castSubPart = type.tryCast(subEntity); + if (castSubPart != null && selector.test(castSubPart)) { + output.add(castSubPart); +@@ -993,17 +_,16 @@ public abstract Scoreboard getScoreboard(); public void updateNeighbourForOutputSignal(final BlockPos pos, final Block changedBlock) { - for (Direction direction : Direction.Plane.HORIZONTAL) { + for (Direction direction : Direction.getUpdateOrder()) { - BlockPos blockpos = pos.relative(direction); - if (this.hasChunkAt(blockpos)) { - BlockState blockstate = this.getBlockState(blockpos); -- if (blockstate.is(Blocks.COMPARATOR)) { -- this.neighborChanged(blockstate, blockpos, changedBlock, null, false); -- } else if (blockstate.isRedstoneConductor(this, blockpos)) { -+ blockstate.onNeighborChange(this, blockpos, pos); -+ if (blockstate.isRedstoneConductor(this, blockpos)) { - blockpos = blockpos.relative(direction); - blockstate = this.getBlockState(blockpos); -- if (blockstate.is(Blocks.COMPARATOR)) { -- this.neighborChanged(blockstate, blockpos, changedBlock, null, false); -+ if (blockstate.getWeakChanges(this, blockpos)) { -+ blockstate.onNeighborChange(this, blockpos, pos); + BlockPos relativePos = pos.relative(direction); + if (this.hasChunkAt(relativePos)) { + BlockState state = this.getBlockState(relativePos); +- if (state.is(Blocks.COMPARATOR)) { +- this.neighborChanged(state, relativePos, changedBlock, null, false); +- } else if (state.isRedstoneConductor(this, relativePos)) { ++ state.onNeighborChange(this, relativePos, pos); ++ if (state.isRedstoneConductor(this, relativePos)) { + relativePos = relativePos.relative(direction); + state = this.getBlockState(relativePos); +- if (state.is(Blocks.COMPARATOR)) { +- this.neighborChanged(state, relativePos, changedBlock, null, false); ++ if (state.getWeakChanges(this, relativePos)) { ++ state.onNeighborChange(this, relativePos, pos); } } } -@@ -1095,6 +_,20 @@ +@@ -1088,6 +_,20 @@ } public abstract ClockManager clockManager(); diff --git a/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch b/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch index 0b313df067..9722a00e86 100644 --- a/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/LevelSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/LevelSettings.java +++ b/net/minecraft/world/level/LevelSettings.java -@@ -7,8 +_,12 @@ +@@ -6,8 +_,12 @@ import net.minecraft.world.Difficulty; public record LevelSettings( @@ -12,12 +12,12 @@ + } + public static LevelSettings parse(final Dynamic input, final WorldDataConfiguration loadConfig) { - GameType gametype = GameType.byId(input.get("GameType").asInt(0)); + GameType gameType = GameType.byId(input.get("GameType").asInt(0)); return new LevelSettings( -@@ -16,12 +_,13 @@ - gametype, +@@ -15,12 +_,13 @@ + gameType, input.get("difficulty_settings").read(LevelSettings.DifficultySettings.CODEC).result().orElse(LevelSettings.DifficultySettings.DEFAULT), - input.get("allowCommands").asBoolean(gametype == GameType.CREATIVE), + input.get("allowCommands").asBoolean(gameType == GameType.CREATIVE), - loadConfig + loadConfig, + net.minecraftforge.common.ForgeHooks.parseLifecycle(input.get("forgeLifecycle").asString("stable")) @@ -30,7 +30,7 @@ } public LevelSettings withDifficulty(final Difficulty difficulty) { -@@ -30,7 +_,8 @@ +@@ -29,7 +_,8 @@ this.gameType, new LevelSettings.DifficultySettings(difficulty, this.difficultySettings.hardcore(), this.difficultySettings.locked()), this.allowCommands, @@ -40,7 +40,7 @@ ); } -@@ -40,16 +_,21 @@ +@@ -39,16 +_,21 @@ this.gameType, new LevelSettings.DifficultySettings(this.difficultySettings.difficulty(), this.difficultySettings.hardcore(), locked), this.allowCommands, diff --git a/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch index afe44eabfc..5bc9116ad7 100644 --- a/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/NaturalSpawner.java.patch @@ -4,21 +4,21 @@ for (Entity entity : entities) { if (!(entity instanceof Mob mob && (mob.isPersistenceRequired() || mob.requiresCustomPersistence()))) { -- MobCategory mobcategory = entity.getType().getCategory(); -+ MobCategory mobcategory = entity.getClassification(true); - if (mobcategory != MobCategory.MISC) { - BlockPos blockpos = entity.blockPosition(); - chunkGetter.query( -@@ -222,7 +_,7 @@ - l1++; +- MobCategory category = entity.getType().getCategory(); ++ MobCategory category = entity.getClassification(true); + if (category != MobCategory.MISC) { + BlockPos pos = entity.blockPosition(); + chunkGetter.query(ChunkPos.pack(pos), chunk -> { +@@ -214,7 +_,7 @@ + groupSize++; level.addFreshEntityWithPassengers(mob); spawnCallback.run(mob, chunk); -- if (j >= mob.getMaxSpawnClusterSize()) { -+ if (j >= net.minecraftforge.event.ForgeEventFactory.getMaxSpawnPackSize(mob)) { +- if (clusterSize >= mob.getMaxSpawnClusterSize()) { ++ if (clusterSize >= net.minecraftforge.event.ForgeEventFactory.getMaxSpawnPackSize(mob)) { return; } -@@ -299,7 +_,7 @@ +@@ -291,7 +_,7 @@ return nearestPlayerDistanceSqr > mob.getType().getCategory().getDespawnDistance() * mob.getType().getCategory().getDespawnDistance() && mob.removeWhenFarAway(nearestPlayerDistanceSqr) ? false @@ -27,7 +27,7 @@ } private static Optional getRandomSpawnMobAt( -@@ -335,9 +_,11 @@ +@@ -327,9 +_,11 @@ final BlockPos pos, final @Nullable Holder biome ) { @@ -42,22 +42,22 @@ } public static boolean isInNetherFortressBounds( -@@ -430,8 +_,7 @@ +@@ -420,8 +_,7 @@ - entity.snapTo(d0, blockpos.getY(), d1, random.nextFloat() * 360.0F, 0.0F); + entity.snapTo(fx, pos.getY(), fz, random.nextFloat() * 360.0F, 0.0F); if (entity instanceof Mob mob - && mob.checkSpawnRules(level, EntitySpawnReason.CHUNK_GENERATION) - && mob.checkSpawnObstruction(level)) { + && net.minecraftforge.event.ForgeEventFactory.checkSpawnPosition(mob, level, EntitySpawnReason.CHUNK_GENERATION)) { - spawngroupdata = mob.finalizeSpawn( - level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.CHUNK_GENERATION, spawngroupdata + groupSpawnData = mob.finalizeSpawn( + level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.CHUNK_GENERATION, groupSpawnData ); -@@ -542,7 +_,7 @@ +@@ -530,7 +_,7 @@ } - this.spawnPotential.addCharge(blockpos, d0); -- MobCategory mobcategory = entitytype.getCategory(); -+ MobCategory mobcategory = mob.getClassification(true); - this.mobCategoryCounts.addTo(mobcategory, 1); - this.localMobCapCalculator.addMob(ChunkPos.containing(blockpos), mobcategory); + this.spawnPotential.addCharge(pos, charge); +- MobCategory category = type.getCategory(); ++ MobCategory category = mob.getClassification(true); + this.mobCategoryCounts.addTo(category, 1); + this.localMobCapCalculator.addMob(ChunkPos.containing(pos), category); } diff --git a/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch b/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch index a26d1b7f6a..4045707180 100644 --- a/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch +++ b/patches/minecraft/net/minecraft/world/level/ServerExplosion.java.patch @@ -1,31 +1,31 @@ --- a/net/minecraft/world/level/ServerExplosion.java +++ b/net/minecraft/world/level/ServerExplosion.java @@ -167,7 +_,7 @@ - return new ObjectArrayList<>(set); + return new ObjectArrayList<>(toBlowSet); } - private void hurtEntities() { + private void hurtEntities(List blocks) { if (!(this.radius < 1.0E-5F)) { - float f = this.radius * 2.0F; - int i = Mth.floor(this.center.x - f - 1.0); + float doubleRadius = this.radius * 2.0F; + int x0 = Mth.floor(this.center.x - doubleRadius - 1.0); @@ -177,7 +_,9 @@ - int i1 = Mth.floor(this.center.z - f - 1.0); - int j1 = Mth.floor(this.center.z + f + 1.0); + int z0 = Mth.floor(this.center.z - doubleRadius - 1.0); + int z1 = Mth.floor(this.center.z + doubleRadius + 1.0); -- for (Entity entity : this.level.getEntities(this.source, new AABB(i, k, i1, j, l, j1))) { -+ var entities = this.level.getEntities(this.source, new AABB(i, k, i1, j, l, j1)); -+ net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.level, this, blocks, entities, f); +- for (Entity entity : this.level.getEntities(this.source, new AABB(x0, y0, z0, x1, y1, z1))) { ++ var entities = this.level.getEntities(this.source, new AABB(x0, y0, z0, x1, y1, z1)); ++ net.minecraftforge.event.ForgeEventFactory.onExplosionDetonate(this.level, this, blocks, entities, doubleRadius); + for (Entity entity : entities) { if (!entity.ignoreExplosion(this)) { - double d0 = Math.sqrt(entity.distanceToSqr(this.center)) / f; - if (!(d0 > 1.0)) { + double dist = Math.sqrt(entity.distanceToSqr(this.center)) / doubleRadius; + if (!(dist > 1.0)) { @@ -233,7 +_,7 @@ public int explode() { this.level.gameEvent(this.source, GameEvent.EXPLODE, this.center); - List list = this.calculateExplodedPositions(); + List toBlow = this.calculateExplodedPositions(); - this.hurtEntities(); -+ this.hurtEntities(list); ++ this.hurtEntities(toBlow); if (this.interactsWithBlocks()) { - ProfilerFiller profilerfiller = Profiler.get(); - profilerfiller.push("explosion_blocks"); + ProfilerFiller profiler = Profiler.get(); + profiler.push("explosion_blocks"); diff --git a/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch b/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch index 4e4b9d6ea4..fcab7843ad 100644 --- a/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch +++ b/patches/minecraft/net/minecraft/world/level/SignalGetter.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/level/SignalGetter.java @@ -65,7 +_,7 @@ default int getSignal(final BlockPos pos, final Direction direction) { - BlockState blockstate = this.getBlockState(pos); - int i = blockstate.getSignal(this, pos, direction); -- return blockstate.isRedstoneConductor(this, pos) ? Math.max(i, this.getDirectSignalTo(pos)) : i; -+ return blockstate.shouldCheckWeakPower(this, pos, direction) ? Math.max(i, this.getDirectSignalTo(pos)) : i; + BlockState state = this.getBlockState(pos); + int signal = state.getSignal(this, pos, direction); +- return state.isRedstoneConductor(this, pos) ? Math.max(signal, this.getDirectSignalTo(pos)) : signal; ++ return state.shouldCheckWeakPower(this, pos, direction) ? Math.max(signal, this.getDirectSignalTo(pos)) : signal; } default boolean hasNeighborSignal(final BlockPos blockPos) { diff --git a/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch b/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch index e78aab7828..c61d6c873e 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/Biome.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/Biome.java +++ b/net/minecraft/world/level/biome/Biome.java -@@ -37,9 +_,9 @@ +@@ -36,9 +_,9 @@ public final class Biome { public static final Codec DIRECT_CODEC = RecordCodecBuilder.create( i -> i.group( @@ -12,7 +12,7 @@ BiomeGenerationSettings.CODEC.forGetter(b -> b.generationSettings), MobSpawnSettings.CODEC.forGetter(b -> b.mobSettings) ) -@@ -67,8 +_,10 @@ +@@ -66,8 +_,10 @@ @Deprecated(forRemoval = true) public static final PerlinSimplexNoise BIOME_INFO_NOISE = new PerlinSimplexNoise(new WorldgenRandom(new LegacyRandomSource(2345L)), ImmutableList.of(0)); private static final int TEMPERATURE_CACHE_SIZE = 1024; @@ -23,15 +23,15 @@ private final MobSpawnSettings mobSettings; private final EnvironmentAttributeMap attributes; private final BiomeSpecialEffects specialEffects; -@@ -85,6 +_,7 @@ - long2floatlinkedopenhashmap.defaultReturnValue(Float.NaN); - return long2floatlinkedopenhashmap; +@@ -84,6 +_,7 @@ + map.defaultReturnValue(Float.NaN); + return map; }); + private final net.minecraftforge.common.world.ModifiableBiomeInfo modifiableBiomeInfo; private Biome( final Biome.ClimateSettings climateSettings, -@@ -98,10 +_,11 @@ +@@ -97,10 +_,11 @@ this.mobSettings = mobSettings; this.attributes = attributes; this.specialEffects = specialEffects; @@ -44,7 +44,7 @@ } public boolean hasPrecipitation() { -@@ -200,7 +_,7 @@ +@@ -202,7 +_,7 @@ } public BiomeGenerationSettings getGenerationSettings() { @@ -53,7 +53,7 @@ } public int getGrassColor(final double x, final double z) { -@@ -253,6 +_,31 @@ +@@ -255,6 +_,31 @@ public int getWaterColor() { return this.specialEffects.waterColor(); diff --git a/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch b/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch index ecb47140dd..32e97a6bf5 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/BiomeGenerationSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/BiomeGenerationSettings.java +++ b/net/minecraft/world/level/biome/BiomeGenerationSettings.java -@@ -93,6 +_,17 @@ +@@ -92,6 +_,17 @@ protected final List>> carvers = new ArrayList<>(); protected final List>> features = new ArrayList<>(); @@ -18,7 +18,7 @@ public BiomeGenerationSettings.PlainBuilder addFeature(final GenerationStep.Decoration step, final Holder feature) { return this.addFeature(step.ordinal(), feature); } -@@ -101,6 +_,11 @@ +@@ -100,6 +_,11 @@ this.addFeatureStepsUpTo(index); this.features.get(index).add(feature); return this; diff --git a/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch b/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch index 2823eb2266..b700cd0340 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/BiomeSpecialEffects.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/BiomeSpecialEffects.java +++ b/net/minecraft/world/level/biome/BiomeSpecialEffects.java -@@ -29,6 +_,10 @@ +@@ -28,6 +_,10 @@ .apply(i, BiomeSpecialEffects::new) ); @@ -11,7 +11,7 @@ public static class Builder { protected OptionalInt waterColor = OptionalInt.empty(); protected Optional foliageColorOverride = Optional.empty(); -@@ -36,6 +_,10 @@ +@@ -35,6 +_,10 @@ protected Optional grassColorOverride = Optional.empty(); protected BiomeSpecialEffects.GrassColorModifier grassColorModifier = BiomeSpecialEffects.GrassColorModifier.NONE; @@ -22,7 +22,7 @@ public BiomeSpecialEffects.Builder waterColor(final int waterColor) { this.waterColor = OptionalInt.of(waterColor); return this; -@@ -72,7 +_,7 @@ +@@ -71,7 +_,7 @@ } } @@ -31,7 +31,7 @@ NONE("none") { @Override public int modifyColor(final double x, final double z, final int baseColor) { -@@ -94,9 +_,16 @@ +@@ -93,9 +_,16 @@ }; private final String name; @@ -50,7 +50,7 @@ private GrassColorModifier(final String name) { this.name = name; -@@ -109,6 +_,30 @@ +@@ -108,6 +_,30 @@ @Override public String getSerializedName() { return this.name; diff --git a/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch b/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch index fa2f93ca8d..61b0203e7b 100644 --- a/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch +++ b/patches/minecraft/net/minecraft/world/level/biome/MobSpawnSettings.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/biome/MobSpawnSettings.java +++ b/net/minecraft/world/level/biome/MobSpawnSettings.java -@@ -44,6 +_,8 @@ +@@ -43,6 +_,8 @@ private final float creatureGenerationProbability; private final Map> spawners; private final Map, MobSpawnSettings.MobSpawnCost> mobSpawnCosts; @@ -9,7 +9,7 @@ private MobSpawnSettings( final float creatureGenerationProbability, -@@ -53,6 +_,8 @@ +@@ -52,6 +_,8 @@ this.creatureGenerationProbability = creatureGenerationProbability; this.spawners = ImmutableMap.copyOf(spawners); this.mobSpawnCosts = ImmutableMap.copyOf(mobSpawnCosts); @@ -18,7 +18,7 @@ } public WeightedList getMobs(final MobCategory category) { -@@ -65,6 +_,14 @@ +@@ -64,6 +_,14 @@ public float getCreatureProbability() { return this.creatureGenerationProbability; diff --git a/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch index 63995d9cd6..a8c65d1e04 100644 --- a/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/AttachedStemBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/AttachedStemBlock.java +++ b/net/minecraft/world/level/block/AttachedStemBlock.java -@@ -91,7 +_,7 @@ +@@ -90,7 +_,7 @@ @Override protected boolean mayPlaceOn(final BlockState state, final BlockGetter level, final BlockPos pos) { diff --git a/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch index 3332f9b5ed..ee5352661c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BambooStalkBlock.java.patch @@ -16,18 +16,18 @@ - if (random.nextInt(3) == 0 && level.isEmptyBlock(pos.above()) && level.getRawBrightness(pos.above(), 0) >= 9) { + boolean vanilla = random.nextInt(3) == 0; + if (level.isEmptyBlock(pos.above()) && level.getRawBrightness(pos.above(), 0) >= 9) { - int i = this.getHeightBelowUpToMax(level, pos) + 1; -- if (i < 16) { -+ if (i < 16 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, vanilla)) { - this.growBamboo(state, level, pos, random, i); + int height = this.getHeightBelowUpToMax(level, pos) + 1; +- if (height < 16) { ++ if (height < 16 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, vanilla)) { + this.growBamboo(state, level, pos, random, height); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } } -@@ -227,5 +_,11 @@ +@@ -230,5 +_,11 @@ } - return i; + return height; + } + + @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch index db922be865..8ce4e29514 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BaseFireBlock.java.patch @@ -3,17 +3,17 @@ @@ -161,6 +_,7 @@ if (!oldState.is(state.getBlock())) { if (inPortalDimension(level)) { - Optional optional = PortalShape.findEmptyPortalShape(level, pos, Direction.Axis.X); -+ optional = net.minecraftforge.event.ForgeEventFactory.onTrySpawnPortal(level, pos, optional); - if (optional.isPresent()) { - optional.get().createPortalBlocks(level); + Optional optionalShape = PortalShape.findEmptyPortalShape(level, pos, Direction.Axis.X); ++ optionalShape = net.minecraftforge.event.ForgeEventFactory.onTrySpawnPortal(level, pos, optionalShape); + if (optionalShape.isPresent()) { + optionalShape.get().createPortalBlocks(level); return; @@ -203,7 +_,7 @@ - boolean flag = false; + boolean hasObsidian = false; - for (Direction direction : Direction.values()) { -- if (level.getBlockState(blockpos$mutableblockpos.set(pos).move(direction)).is(Blocks.OBSIDIAN)) { -+ if (level.getBlockState(blockpos$mutableblockpos.set(pos).move(direction)).isPortalFrame(level, blockpos$mutableblockpos)) { - flag = true; + for (Direction face : Direction.values()) { +- if (level.getBlockState(testPos.set(pos).move(face)).is(Blocks.OBSIDIAN)) { ++ if (level.getBlockState(testPos.set(pos).move(face)).isPortalFrame(level, testPos)) { + hasObsidian = true; break; } diff --git a/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch index d43f09eb68..64678f5dc7 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BaseRailBlock.java.patch @@ -13,9 +13,9 @@ final BlockState state, final Level level, final BlockPos pos, final Block block, final @Nullable Orientation orientation, final boolean movedByPiston ) { if (!level.isClientSide() && level.getBlockState(pos).is(this)) { -- RailShape railshape = state.getValue(this.getShapeProperty()); -+ RailShape railshape = getRailDirection(state, level, pos, null); - if (shouldBeRemoved(pos, level, railshape)) { +- RailShape shape = state.getValue(this.getShapeProperty()); ++ RailShape shape = getRailDirection(state, level, pos, null); + if (shouldBeRemoved(pos, level, shape)) { dropResources(state, level, pos); level.removeBlock(pos, movedByPiston); @@ -125,7 +_,7 @@ @@ -28,7 +28,7 @@ } @@ -146,6 +_,11 @@ - return blockstate.setValue(this.getShapeProperty(), flag1 ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH).setValue(WATERLOGGED, flag); + return state.setValue(this.getShapeProperty(), isEastWest ? RailShape.EAST_WEST : RailShape.NORTH_SOUTH).setValue(WATERLOGGED, isWaterSource); } + /** diff --git a/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch index 1d595e181a..a0028ac91d 100644 --- a/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/BeehiveBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/BeehiveBlock.java +++ b/net/minecraft/world/level/block/BeehiveBlock.java @@ -160,7 +_,7 @@ - boolean flag = false; - if (i >= 5) { + boolean hiveEmptied = false; + if (honeyLevel >= 5) { Item item = itemStack.getItem(); -- if (level instanceof ServerLevel serverlevel && itemStack.is(Items.SHEARS)) { -+ if (level instanceof ServerLevel serverlevel && itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { - dropHoneycomb(serverlevel, itemStack, state, level.getBlockEntity(pos), player, pos); +- if (level instanceof ServerLevel serverLevel && itemStack.is(Items.SHEARS)) { ++ if (level instanceof ServerLevel serverLevel && itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_HARVEST)) { + dropHoneycomb(serverLevel, itemStack, state, level.getBlockEntity(pos), player, pos); level.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.BEEHIVE_SHEAR, SoundSource.BLOCKS, 1.0F, 1.0F); itemStack.hurtAndBreak(1, player, hand.asEquipmentSlot()); diff --git a/patches/minecraft/net/minecraft/world/level/block/Block.java.patch b/patches/minecraft/net/minecraft/world/level/block/Block.java.patch index 70dbd9ad41..5da70a8c26 100644 --- a/patches/minecraft/net/minecraft/world/level/block/Block.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/Block.java.patch @@ -15,15 +15,15 @@ private static final LoadingCache SHAPE_FULL_BLOCK_CACHE = CacheBuilder.newBuilder() .maximumSize(512L) .weakKeys() -@@ -253,6 +_,7 @@ - LOGGER.error("Block classes should end with Block and {} doesn't.", s); +@@ -251,6 +_,7 @@ + LOGGER.error("Block classes should end with Block and {} doesn't.", className); } } + initClient(); } public static boolean isExceptionForConnection(final BlockState state) { -@@ -303,7 +_,12 @@ +@@ -301,7 +_,12 @@ } } @@ -33,10 +33,10 @@ + } + + public static boolean shouldRenderFace(final BlockGetter level, final BlockPos pos, final BlockState state, final BlockState neighborState, final Direction direction) { - VoxelShape voxelshape = neighborState.getFaceOcclusionShape(direction.getOpposite()); - if (voxelshape == Shapes.block()) { + VoxelShape occluder = neighborState.getFaceOcclusionShape(direction.getOpposite()); + if (occluder == Shapes.block()) { return false; -@@ -398,17 +_,22 @@ +@@ -396,17 +_,22 @@ } } @@ -54,23 +54,23 @@ + final ItemStack tool, + final boolean dropXp ) { - if (level instanceof ServerLevel serverlevel) { - getDrops(state, serverlevel, pos, blockEntity, breaker, tool).forEach(stack -> popResource(level, pos, stack)); -- state.spawnAfterBreak(serverlevel, pos, tool, true); -+ state.spawnAfterBreak(serverlevel, pos, tool, dropXp); + if (level instanceof ServerLevel serverLevel) { + getDrops(state, serverLevel, pos, blockEntity, breaker, tool).forEach(stack -> popResource(level, pos, stack)); +- state.spawnAfterBreak(serverLevel, pos, tool, true); ++ state.spawnAfterBreak(serverLevel, pos, tool, dropXp); } } -@@ -438,7 +_,7 @@ +@@ -436,7 +_,7 @@ } private static void popResource(final Level level, final Supplier entityFactory, final ItemStack itemStack) { -- if (level instanceof ServerLevel serverlevel && !itemStack.isEmpty() && serverlevel.getGameRules().get(GameRules.BLOCK_DROPS)) { -+ if (level instanceof ServerLevel serverlevel && !itemStack.isEmpty() && serverlevel.getGameRules().get(GameRules.BLOCK_DROPS) && !level.restoringBlockSnapshots) { - ItemEntity itementity = entityFactory.get(); - itementity.setDefaultPickUpDelay(); - level.addFreshEntity(itementity); -@@ -446,11 +_,12 @@ +- if (level instanceof ServerLevel serverLevel && !itemStack.isEmpty() && serverLevel.getGameRules().get(GameRules.BLOCK_DROPS)) { ++ if (level instanceof ServerLevel serverLevel && !itemStack.isEmpty() && serverLevel.getGameRules().get(GameRules.BLOCK_DROPS) && !level.restoringBlockSnapshots) { + ItemEntity entity = entityFactory.get(); + entity.setDefaultPickUpDelay(); + level.addFreshEntity(entity); +@@ -444,11 +_,12 @@ } public void popExperience(final ServerLevel level, final BlockPos pos, final int amount) { @@ -84,7 +84,7 @@ public float getExplosionResistance() { return this.explosionResistance; } -@@ -475,7 +_,8 @@ +@@ -473,7 +_,8 @@ ) { player.awardStat(Stats.BLOCK_MINED.get(this)); player.causeFoodExhaustion(0.005F); @@ -94,7 +94,7 @@ } public void setPlacedBy(final Level level, final BlockPos pos, final BlockState state, final @Nullable LivingEntity by, final ItemStack itemStack) { -@@ -497,6 +_,7 @@ +@@ -495,6 +_,7 @@ entity.setDeltaMovement(entity.getDeltaMovement().multiply(1.0, 0.0, 1.0)); } @@ -102,7 +102,7 @@ public float getFriction() { return this.friction; } -@@ -567,7 +_,7 @@ +@@ -565,7 +_,7 @@ this.item = Item.byBlock(this); } @@ -111,7 +111,7 @@ } public boolean hasDynamicShape() { -@@ -632,6 +_,79 @@ +@@ -630,6 +_,79 @@ public int hashCode() { return System.identityHashCode(this.first) * 31 + System.identityHashCode(this.second); } diff --git a/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch b/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch index 2ef4a20ddc..9bf6f47d87 100644 --- a/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/Blocks.java.patch @@ -17,9 +17,9 @@ - - static { - for (Block block : BuiltInRegistries.BLOCK) { -- for (BlockState blockstate : block.getStateDefinition().getPossibleStates()) { -- Block.BLOCK_STATE_REGISTRY.add(blockstate); -- blockstate.initCache(); +- for (BlockState state : block.getStateDefinition().getPossibleStates()) { +- Block.BLOCK_STATE_REGISTRY.add(state); +- state.initCache(); - } - } } diff --git a/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch index 3652b5d983..577502a100 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CactusBlock.java.patch @@ -22,12 +22,12 @@ } + if (!net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, true)) return; - if (j == 8 && this.canSurvive(this.defaultBlockState(), level, pos.above())) { - double d0 = i >= 3 ? 0.25 : 0.1; - if (random.nextDouble() <= d0) { + if (age == 8 && this.canSurvive(this.defaultBlockState(), level, pos.above())) { + double chanceToGrowFlower = height >= 3 ? 0.25 : 0.1; + if (random.nextDouble() <= chanceToGrowFlower) { @@ -78,6 +_,7 @@ - if (j < 15) { - level.setBlock(pos, state.setValue(AGE, j + 1), 260); + if (age < 15) { + level.setBlock(pos, state.setValue(AGE, age + 1), 260); } + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } @@ -36,9 +36,9 @@ @@ -119,7 +_,7 @@ } - BlockState blockstate1 = level.getBlockState(pos.below()); -- return (blockstate1.is(this) || blockstate1.is(BlockTags.SUPPORTS_CACTUS)) && !level.getBlockState(pos.above()).liquid(); -+ return blockstate1.canSustainPlant(level, pos, Direction.UP, this) && !level.getBlockState(pos.above()).liquid(); + BlockState belowState = level.getBlockState(pos.below()); +- return (belowState.is(this) || belowState.is(BlockTags.SUPPORTS_CACTUS)) && !level.getBlockState(pos.above()).liquid(); ++ return belowState.canSustainPlant(level, pos, Direction.UP, this) && !level.getBlockState(pos.above()).liquid(); } @Override diff --git a/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch index 055b7915b4..9deaf39f07 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CactusFlowerBlock.java.patch @@ -3,8 +3,8 @@ @@ -31,6 +_,6 @@ @Override protected boolean mayPlaceOn(final BlockState state, final BlockGetter level, final BlockPos pos) { - BlockState blockstate = level.getBlockState(pos); -- return blockstate.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockstate.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER); -+ return blockstate.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockstate.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER) || blockstate.getBlock() instanceof FarmlandBlock; + BlockState blockBelow = level.getBlockState(pos); +- return blockBelow.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockBelow.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER); ++ return blockBelow.is(BlockTags.SUPPORT_OVERRIDE_CACTUS_FLOWER) || blockBelow.isFaceSturdy(level, pos, Direction.UP, SupportType.CENTER) || blockBelow.getBlock() instanceof FarmlandBlock; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch index 940ff7a907..1048e0a315 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CampfireBlock.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/CampfireBlock.java +++ b/net/minecraft/world/level/block/CampfireBlock.java -@@ -271,7 +_,7 @@ +@@ -270,7 +_,7 @@ return true; } -- boolean flag = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockstate.getCollisionShape(level, pos, CollisionContext.empty()), BooleanOp.AND); -+ boolean flag = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockstate.getCollisionShape(level, blockpos, CollisionContext.empty()), BooleanOp.AND); // FORGE: Fix MC-201374 - if (flag) { - BlockState blockstate1 = level.getBlockState(blockpos.below()); - return isLitCampfire(blockstate1); +- boolean smokeBlocked = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockState.getCollisionShape(level, pos, CollisionContext.empty()), BooleanOp.AND); ++ boolean smokeBlocked = Shapes.joinIsNotEmpty(SHAPE_VIRTUAL_POST, blockState.getCollisionShape(level, posToCheck, CollisionContext.empty()), BooleanOp.AND); // FORGE: Fix MC-201374 + if (smokeBlocked) { + BlockState belowState = level.getBlockState(posToCheck.below()); + return isLitCampfire(belowState); diff --git a/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch index d246058089..97cdda45c1 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ChestBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/ChestBlock.java +++ b/net/minecraft/world/level/block/ChestBlock.java -@@ -369,7 +_,8 @@ +@@ -368,7 +_,8 @@ @Override protected BlockState mirror(final BlockState state, final Mirror mirror) { diff --git a/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch index d64303969e..ec7947bafe 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ChorusFlowerBlock.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/level/block/ChorusFlowerBlock.java +++ b/net/minecraft/world/level/block/ChorusFlowerBlock.java -@@ -66,7 +_,7 @@ - BlockPos blockpos = pos.above(); - if (level.isEmptyBlock(blockpos) && blockpos.getY() <= level.getMaxY()) { - int i = state.getValue(AGE); -- if (i < 5) { -+ if (i < 5 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, blockpos, state, true)) { - boolean flag = false; - boolean flag1 = false; - BlockState blockstate = level.getBlockState(pos.below()); -@@ -124,6 +_,7 @@ +@@ -65,7 +_,7 @@ + BlockPos above = pos.above(); + if (level.isEmptyBlock(above) && above.getY() <= level.getMaxY()) { + int currentAge = state.getValue(AGE); +- if (currentAge < 5) { ++ if (currentAge < 5 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, above, state, true)) { + boolean growUpwards = false; + boolean pillarOnSupportBlock = false; + BlockState belowState = level.getBlockState(pos.below()); +@@ -121,6 +_,7 @@ } else { this.placeDeadFlower(level, pos); } diff --git a/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch index e66c11da26..802af346aa 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CocoaBlock.java.patch @@ -6,10 +6,10 @@ protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { - if (level.getRandom().nextInt(5) == 0) { + { - int i = state.getValue(AGE); -- if (i < 2) { -+ if (i < 2 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, level.getRandom().nextInt(5) == 0)) { - level.setBlock(pos, state.setValue(AGE, i + 1), 2); + int age = state.getValue(AGE); +- if (age < 2) { ++ if (age < 2 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, level.getRandom().nextInt(5) == 0)) { + level.setBlock(pos, state.setValue(AGE, age + 1), 2); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } diff --git a/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch index 559288e26a..2b9bcbec80 100644 --- a/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/ConcretePowderBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/ConcretePowderBlock.java +++ b/net/minecraft/world/level/block/ConcretePowderBlock.java -@@ -36,7 +_,7 @@ +@@ -35,7 +_,7 @@ @Override public void onLand(final Level level, final BlockPos pos, final BlockState state, final BlockState replacedBlock, final FallingBlockEntity entity) { @@ -9,8 +9,8 @@ level.setBlock(pos, this.concrete.defaultBlockState(), 3); } } -@@ -49,20 +_,24 @@ - return shouldSolidify(blockgetter, blockpos, blockstate) ? this.concrete.defaultBlockState() : super.getStateForPlacement(context); +@@ -48,20 +_,24 @@ + return shouldSolidify(level, pos, replacedBlock) ? this.concrete.defaultBlockState() : super.getStateForPlacement(context); } + private static boolean shouldSolidify(final BlockGetter level, final BlockPos pos, final BlockState state, final net.minecraft.world.level.material.FluidState fluidState) { @@ -24,21 +24,21 @@ - private static boolean touchesLiquid(final BlockGetter level, final BlockPos pos) { + private static boolean touchesLiquid(final BlockGetter level, BlockPos pos, BlockState state) { - boolean flag = false; - BlockPos.MutableBlockPos blockpos$mutableblockpos = pos.mutable(); + boolean touchesLiquid = false; + BlockPos.MutableBlockPos testPos = pos.mutable(); for (Direction direction : Direction.values()) { - BlockState blockstate = level.getBlockState(blockpos$mutableblockpos); -- if (direction != Direction.DOWN || canSolidify(blockstate)) { -+ if (direction != Direction.DOWN || state.canBeHydrated(level, pos, blockstate.getFluidState(), blockpos$mutableblockpos)) { - blockpos$mutableblockpos.setWithOffset(pos, direction); - blockstate = level.getBlockState(blockpos$mutableblockpos); -- if (canSolidify(blockstate) && !blockstate.isFaceSturdy(level, pos, direction.getOpposite())) { -+ if (state.canBeHydrated(level, pos, blockstate.getFluidState(), blockpos$mutableblockpos) && !blockstate.isFaceSturdy(level, pos, direction.getOpposite())) { - flag = true; + BlockState blockState = level.getBlockState(testPos); +- if (direction != Direction.DOWN || canSolidify(blockState)) { ++ if (direction != Direction.DOWN || state.canBeHydrated(level, pos, blockState.getFluidState(), testPos)) { + testPos.setWithOffset(pos, direction); + blockState = level.getBlockState(testPos); +- if (canSolidify(blockState) && !blockState.isFaceSturdy(level, pos, direction.getOpposite())) { ++ if (state.canBeHydrated(level, pos, blockState.getFluidState(), testPos) && !blockState.isFaceSturdy(level, pos, direction.getOpposite())) { + touchesLiquid = true; break; } -@@ -87,7 +_,7 @@ +@@ -86,7 +_,7 @@ final BlockState neighbourState, final RandomSource random ) { diff --git a/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch index 886c415d29..6538cf0c9c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CoralBlock.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/block/CoralBlock.java +++ b/net/minecraft/world/level/block/CoralBlock.java -@@ -61,9 +_,10 @@ +@@ -60,9 +_,10 @@ } protected boolean scanForWater(final BlockGetter level, final BlockPos blockPos) { + BlockState state = level.getBlockState(blockPos); for (Direction direction : Direction.values()) { - FluidState fluidstate = level.getFluidState(blockPos.relative(direction)); -- if (fluidstate.is(FluidTags.WATER)) { -+ if (state.canBeHydrated(level, blockPos, fluidstate, blockPos.relative(direction))) { + FluidState fluidState = level.getFluidState(blockPos.relative(direction)); +- if (fluidState.is(FluidTags.WATER)) { ++ if (state.canBeHydrated(level, blockPos, fluidState, blockPos.relative(direction))) { return true; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch index 93bdc523f5..72c4e0bb36 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CrafterBlock.java.patch @@ -5,29 +5,29 @@ ) { Direction direction = blockState.getValue(ORIENTATION).front(); + var itemhandler = net.minecraftforge.items.VanillaInventoryCodeHooks.getItemHandler(level, pos.relative(direction), direction.getOpposite()).orElse(null); - Container container = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); - ItemStack itemstack = results.copy(); - if (container != null && (container instanceof CrafterBlockEntity || results.getCount() > container.getMaxStackSize(results))) { - while (!itemstack.isEmpty()) { - ItemStack itemstack2 = itemstack.copyWithCount(1); - ItemStack itemstack1 = HopperBlockEntity.addItem(blockEntity, container, itemstack2, direction.getOpposite()); -+ if (itemhandler != null && !itemstack1.isEmpty()) // Vanilla insert failed, try IItemHandler -+ itemstack1 = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack1, false); - if (!itemstack1.isEmpty()) { + Container into = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); + ItemStack remaining = results.copy(); + if (into != null && (into instanceof CrafterBlockEntity || results.getCount() > into.getMaxStackSize(results))) { + while (!remaining.isEmpty()) { + ItemStack copy = remaining.copyWithCount(1); + ItemStack itemStack = HopperBlockEntity.addItem(blockEntity, into, copy, direction.getOpposite()); ++ if (itemhandler != null && !itemStack.isEmpty()) // Vanilla insert failed, try IItemHandler ++ itemStack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemStack, false); + if (!itemStack.isEmpty()) { break; } @@ -209,10 +_,14 @@ - while (!itemstack.isEmpty()) { - int i = itemstack.getCount(); - itemstack = HopperBlockEntity.addItem(blockEntity, container, itemstack, direction.getOpposite()); -+ if (itemhandler != null && i == itemstack.getCount()) // Vanilla insert failed, try IItemHandler -+ itemstack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack, false); - if (i == itemstack.getCount()) { + while (!remaining.isEmpty()) { + int oldSize = remaining.getCount(); + remaining = HopperBlockEntity.addItem(blockEntity, into, remaining, direction.getOpposite()); ++ if (itemhandler != null && oldSize == remaining.getCount()) // Vanilla insert failed, try IItemHandler ++ remaining = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, remaining, false); + if (oldSize == remaining.getCount()) { break; } } + } else { -+ itemstack = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, itemstack, false); ++ remaining = net.minecraftforge.items.ItemHandlerHelper.insertItem(itemhandler, remaining, false); } - if (!itemstack.isEmpty()) { + if (!remaining.isEmpty()) { diff --git a/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch index e24e03bb40..b1f8f5aa24 100644 --- a/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/CropBlock.java.patch @@ -10,34 +10,34 @@ protected IntegerProperty getAgeProperty() { @@ -81,8 +_,9 @@ - int i = this.getAge(state); - if (i < this.getMaxAge()) { - float f = getGrowthSpeed(this, level, pos); -- if (random.nextInt((int)(25.0F / f) + 1) == 0) { -+ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt((int)(25.0F / f) + 1) == 0)) { - level.setBlock(pos, this.getStateForAge(i + 1), 2); + int age = this.getAge(state); + if (age < this.getMaxAge()) { + float growthSpeed = getGrowthSpeed(this, level, pos); +- if (random.nextInt((int)(25.0F / growthSpeed) + 1) == 0) { ++ if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt((int)(25.0F / growthSpeed) + 1) == 0)) { + level.setBlock(pos, this.getStateForAge(age + 1), 2); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } } @@ -105,9 +_,9 @@ - for (int j = -1; j <= 1; j++) { - float f1 = 0.0F; - BlockState blockstate = level.getBlockState(blockpos.offset(i, 0, j)); -- if (blockstate.is(BlockTags.GROWS_CROPS)) { -+ if (blockstate.canSustainPlant(level, blockpos.offset(i, 0, j), net.minecraft.core.Direction.UP, (net.minecraftforge.common.IPlantable)type)) { - f1 = 1.0F; -- if (blockstate.getValueOrElse(FarmlandBlock.MOISTURE, 0) > 0) { -+ if (blockstate.isFertile(level, blockpos.offset(i, 0, j))) { - f1 = 3.0F; + for (int zz = -1; zz <= 1; zz++) { + float blockSpeed = 0.0F; + BlockState blockState = level.getBlockState(below.offset(xx, 0, zz)); +- if (blockState.is(BlockTags.GROWS_CROPS)) { ++ if (blockState.canSustainPlant(level, below.offset(xx, 0, zz), net.minecraft.core.Direction.UP, (net.minecraftforge.common.IPlantable)type)) { + blockSpeed = 1.0F; +- if (blockState.getValueOrElse(FarmlandBlock.MOISTURE, 0) > 0) { ++ if (blockState.isFertile(level, below.offset(xx, 0, zz))) { + blockSpeed = 3.0F; } } @@ -159,7 +_,7 @@ final InsideBlockEffectApplier effectApplier, final boolean isPrecise ) { -- if (level instanceof ServerLevel serverlevel && entity instanceof Ravager && serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) { -+ if (level instanceof ServerLevel serverlevel && entity instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverlevel, entity)) { - serverlevel.destroyBlock(pos, true, entity); +- if (level instanceof ServerLevel serverLevel && entity instanceof Ravager && serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) { ++ if (level instanceof ServerLevel serverLevel && entity instanceof Ravager && net.minecraftforge.event.ForgeEventFactory.getMobGriefingEvent(serverLevel, entity)) { + serverLevel.destroyBlock(pos, true, entity); } diff --git a/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch index 6f6dc6505e..ef9b8bde3e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DetectorRailBlock.java.patch @@ -12,16 +12,16 @@ } @@ -154,7 +_,10 @@ - return list.get(0).getCommandBlock().getSuccessCount(); + return commandBlocks.get(0).getCommandBlock().getSuccessCount(); } -- List list1 = this.getInteractingMinecartOfType(level, pos, AbstractMinecart.class, EntitySelector.CONTAINER_ENTITY_SELECTOR); +- List entities = this.getInteractingMinecartOfType(level, pos, AbstractMinecart.class, EntitySelector.CONTAINER_ENTITY_SELECTOR); + List carts = this.getInteractingMinecartOfType(level, pos, AbstractMinecart.class, e -> e.isAlive()); + if (!carts.isEmpty() && carts.get(0).getComparatorLevel() > -1) return carts.get(0).getComparatorLevel(); -+ List list1 = carts.stream().filter(EntitySelector.CONTAINER_ENTITY_SELECTOR).toList(); ++ List entities = carts.stream().filter(EntitySelector.CONTAINER_ENTITY_SELECTOR).toList(); + - if (!list1.isEmpty()) { - return AbstractContainerMenu.getRedstoneSignalFromContainer((Container)list1.get(0)); + if (!entities.isEmpty()) { + return AbstractContainerMenu.getRedstoneSignalFromContainer((Container)entities.get(0)); } @@ -190,6 +_,6 @@ diff --git a/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch index 4706c7c0a9..36f3e9ceb6 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DiodeBlock.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/block/DiodeBlock.java +++ b/net/minecraft/world/level/block/DiodeBlock.java -@@ -177,6 +_,9 @@ +@@ -178,6 +_,9 @@ Direction direction = state.getValue(FACING); - BlockPos blockpos = pos.relative(direction.getOpposite()); + BlockPos oppositePos = pos.relative(direction.getOpposite()); Orientation orientation = ExperimentalRedstoneUtils.initialOrientation(level, direction.getOpposite(), Direction.UP); + if (net.minecraftforge.event.ForgeEventFactory.onNeighborNotify(level, pos, level.getBlockState(pos), java.util.EnumSet.of(direction.getOpposite()), false)) { + return; + } - level.neighborChanged(blockpos, this, orientation); - level.updateNeighborsAtExceptFromFacing(blockpos, this, direction, orientation); + level.neighborChanged(oppositePos, this, orientation); + level.updateNeighborsAtExceptFromFacing(oppositePos, this, direction, orientation); } diff --git a/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch index 40a99dd83c..3e2b355924 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DoublePlantBlock.java.patch @@ -3,8 +3,8 @@ @@ -79,6 +_,7 @@ return super.canSurvive(state, level, pos); } else { - BlockState blockstate = level.getBlockState(pos.below()); + BlockState belowState = level.getBlockState(pos.below()); + if (state.getBlock() != this) return super.canSurvive(state, level, pos); //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. - return blockstate.is(this) && blockstate.getValue(HALF) == DoubleBlockHalf.LOWER; + return belowState.is(this) && belowState.getValue(HALF) == DoubleBlockHalf.LOWER; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch index 31148742c9..d91f08f9ac 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DropExperienceBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/DropExperienceBlock.java +++ b/net/minecraft/world/level/block/DropExperienceBlock.java -@@ -30,8 +_,13 @@ +@@ -29,8 +_,13 @@ @Override protected void spawnAfterBreak(final BlockState state, final ServerLevel level, final BlockPos pos, final ItemStack tool, final boolean dropExperience) { super.spawnAfterBreak(state, level, pos, tool, dropExperience); diff --git a/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch index 4f1ef406d8..934255a286 100644 --- a/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/DropperBlock.java.patch @@ -3,9 +3,9 @@ @@ -56,7 +_,7 @@ level.levelEvent(1001, pos, 0); } else { - ItemStack itemstack = dispenserblockentity.getItem(i); -- if (!itemstack.isEmpty()) { -+ if (!itemstack.isEmpty() && net.minecraftforge.items.VanillaInventoryCodeHooks.dropperInsertHook(level, pos, dispenserblockentity, i, itemstack)) { + ItemStack itemStack = blockEntity.getItem(slot); +- if (!itemStack.isEmpty()) { ++ if (!itemStack.isEmpty() && net.minecraftforge.items.VanillaInventoryCodeHooks.dropperInsertHook(level, pos, blockEntity, slot, itemStack)) { Direction direction = level.getBlockState(pos).getValue(FACING); - Container container = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); - ItemStack itemstack1; + Container into = HopperBlockEntity.getContainerAt(level, pos.relative(direction)); + ItemStack remaining; diff --git a/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch index c87f502932..6607ee5ddc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/EnchantingTableBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/EnchantingTableBlock.java +++ b/net/minecraft/world/level/block/EnchantingTableBlock.java -@@ -46,7 +_,7 @@ +@@ -45,7 +_,7 @@ } public static boolean isValidBookShelf(final Level level, final BlockPos pos, final BlockPos offset) { diff --git a/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch index e6e9db89cb..a0834c0c7c 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FarmlandBlock.java.patch @@ -3,12 +3,12 @@ @@ -108,10 +_,7 @@ @Override public void fallOn(final Level level, final BlockState state, final BlockPos pos, final Entity entity, final double fallDistance) { - if (level instanceof ServerLevel serverlevel + if (level instanceof ServerLevel serverLevel - && level.getRandom().nextFloat() < fallDistance - 0.5 - && entity instanceof LivingEntity -- && (entity instanceof Player || serverlevel.getGameRules().get(GameRules.MOB_GRIEFING)) +- && (entity instanceof Player || serverLevel.getGameRules().get(GameRules.MOB_GRIEFING)) - && entity.getBbWidth() * entity.getBbWidth() * entity.getBbHeight() > 0.512F) { -+ && net.minecraftforge.common.ForgeHooks.onFarmlandTrample(serverlevel, pos, state, fallDistance, entity)) { // Forge: Move logic to Entity#canTrample ++ && net.minecraftforge.common.ForgeHooks.onFarmlandTrample(serverLevel, pos, state, fallDistance, entity)) { // Forge: Move logic to Entity#canTrample turnToDirt(entity, state, level, pos); } @@ -25,9 +25,9 @@ private static boolean isNearWater(final LevelReader level, final BlockPos pos) { + BlockState state = level.getBlockState(pos); - for (BlockPos blockpos : BlockPos.betweenClosed(pos.offset(-4, 0, -4), pos.offset(4, 1, 4))) { -- if (level.getFluidState(blockpos).is(FluidTags.WATER)) { -+ if (state.canBeHydrated(level, pos, level.getFluidState(blockpos), blockpos)) { + for (BlockPos blockPos : BlockPos.betweenClosed(pos.offset(-4, 0, -4), pos.offset(4, 1, 4))) { +- if (level.getFluidState(blockPos).is(FluidTags.WATER)) { ++ if (state.canBeHydrated(level, pos, level.getFluidState(blockPos), blockPos)) { return true; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch index a7954ff440..99255f7d5b 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FenceGateBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/FenceGateBlock.java +++ b/net/minecraft/world/level/block/FenceGateBlock.java -@@ -58,6 +_,8 @@ +@@ -57,6 +_,8 @@ Util.mapValues(SHAPE_OCCLUSION, v -> v.move(0.0, -0.1875, 0.0).optimize()) ); private final WoodType type; @@ -9,7 +9,7 @@ @Override public MapCodec codec() { -@@ -65,8 +_,14 @@ +@@ -64,8 +_,14 @@ } public FenceGateBlock(final WoodType type, final BlockBehaviour.Properties properties) { @@ -25,30 +25,30 @@ this.registerDefaultState(this.stateDefinition.any().setValue(OPEN, false).setValue(POWERED, false).setValue(IN_WALL, false)); } -@@ -162,7 +_,7 @@ +@@ -160,7 +_,7 @@ - boolean flag = state.getValue(OPEN); + boolean opens = state.getValue(OPEN); level.playSound( -- player, pos, flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F -+ player, pos, flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F +- player, pos, opens ? this.type.fenceGateOpen() : this.type.fenceGateClose(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ++ player, pos, opens ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ); - level.gameEvent(player, flag ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos); + level.gameEvent(player, opens ? GameEvent.BLOCK_OPEN : GameEvent.BLOCK_CLOSE, pos); return InteractionResult.SUCCESS; -@@ -176,7 +_,7 @@ - boolean flag = state.getValue(OPEN); - level.setBlockAndUpdate(pos, state.setValue(OPEN, !flag)); +@@ -174,7 +_,7 @@ + boolean open = state.getValue(OPEN); + level.setBlockAndUpdate(pos, state.setValue(OPEN, !open)); level.playSound( -- null, pos, flag ? this.type.fenceGateClose() : this.type.fenceGateOpen(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F -+ null, pos, flag ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F +- null, pos, open ? this.type.fenceGateClose() : this.type.fenceGateOpen(), SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ++ null, pos, open ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F ); - level.gameEvent(flag ? GameEvent.BLOCK_CLOSE : GameEvent.BLOCK_OPEN, pos, GameEvent.Context.of(state)); + level.gameEvent(open ? GameEvent.BLOCK_CLOSE : GameEvent.BLOCK_OPEN, pos, GameEvent.Context.of(state)); } -@@ -196,7 +_,7 @@ +@@ -194,7 +_,7 @@ level.playSound( null, pos, -- flag ? this.type.fenceGateOpen() : this.type.fenceGateClose(), -+ flag ? this.openSound : this.closeSound, +- hasPower ? this.type.fenceGateOpen() : this.type.fenceGateClose(), ++ hasPower ? this.openSound : this.closeSound, SoundSource.BLOCKS, 1.0F, level.getRandom().nextFloat() * 0.1F + 0.9F diff --git a/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch index 076bae73be..d3345ceeed 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FireBlock.java.patch @@ -2,57 +2,57 @@ +++ b/net/minecraft/world/level/block/FireBlock.java @@ -115,13 +_,13 @@ protected BlockState getStateForPlacement(final BlockGetter level, final BlockPos pos) { - BlockPos blockpos = pos.below(); - BlockState blockstate = level.getBlockState(blockpos); -- if (!this.canBurn(blockstate) && !blockstate.isFaceSturdy(level, blockpos, Direction.UP)) { -+ if (!this.canCatchFire(level, pos, Direction.UP) && !blockstate.isFaceSturdy(level, blockpos, Direction.UP)) { - BlockState blockstate1 = this.defaultBlockState(); + BlockPos below = pos.below(); + BlockState belowState = level.getBlockState(below); +- if (!this.canBurn(belowState) && !belowState.isFaceSturdy(level, below, Direction.UP)) { ++ if (!this.canCatchFire(level, pos, Direction.UP) && !belowState.isFaceSturdy(level, below, Direction.UP)) { + BlockState result = this.defaultBlockState(); for (Direction direction : Direction.values()) { - BooleanProperty booleanproperty = PROPERTY_BY_DIRECTION.get(direction); - if (booleanproperty != null) { -- blockstate1 = blockstate1.setValue(booleanproperty, this.canBurn(level.getBlockState(pos.relative(direction)))); -+ blockstate1 = blockstate1.setValue(booleanproperty, Boolean.valueOf(this.canCatchFire(level, pos.relative(direction), direction.getOpposite()))); + BooleanProperty property = PROPERTY_BY_DIRECTION.get(direction); + if (property != null) { +- result = result.setValue(property, this.canBurn(level.getBlockState(pos.relative(direction)))); ++ result = result.setValue(property, Boolean.valueOf(this.canCatchFire(level, pos.relative(direction), direction.getOpposite()))); } } @@ -146,7 +_,7 @@ } - BlockState blockstate = level.getBlockState(pos.below()); -- boolean flag = blockstate.is(level.dimensionType().infiniburn()); -+ boolean flag = blockstate.isFireSource(level, pos, Direction.UP); - int i = state.getValue(AGE); - if (!flag && level.isRaining() && this.isNearRain(level, pos) && random.nextFloat() < 0.2F + i * 0.03F) { + BlockState belowState = level.getBlockState(pos.below()); +- boolean infiniBurn = belowState.is(level.dimensionType().infiniburn()); ++ boolean infiniBurn = belowState.isFireSource(level, pos, Direction.UP); + int age = state.getValue(AGE); + if (!infiniBurn && level.isRaining() && this.isNearRain(level, pos) && random.nextFloat() < 0.2F + age * 0.03F) { level.removeBlock(pos, false); @@ -167,7 +_,7 @@ return; } -- if (i == 15 && random.nextInt(4) == 0 && !this.canBurn(level.getBlockState(pos.below()))) { -+ if (i == 15 && random.nextInt(4) == 0 && !this.canCatchFire(level, pos.below(), Direction.UP)) { +- if (age == 15 && random.nextInt(4) == 0 && !this.canBurn(level.getBlockState(pos.below()))) { ++ if (age == 15 && random.nextInt(4) == 0 && !this.canCatchFire(level, pos.below(), Direction.UP)) { level.removeBlock(pos, false); return; } @@ -175,12 +_,12 @@ - boolean flag1 = level.environmentAttributes().getValue(EnvironmentAttributes.INCREASED_FIRE_BURNOUT, pos); - int k = flag1 ? -50 : 0; -- this.checkBurnOut(level, pos.east(), 300 + k, random, i); -- this.checkBurnOut(level, pos.west(), 300 + k, random, i); -- this.checkBurnOut(level, pos.below(), 250 + k, random, i); -- this.checkBurnOut(level, pos.above(), 250 + k, random, i); -- this.checkBurnOut(level, pos.north(), 300 + k, random, i); -- this.checkBurnOut(level, pos.south(), 300 + k, random, i); -+ this.checkBurnOut(level, pos.east(), 300 + k, random, i, Direction.WEST); -+ this.checkBurnOut(level, pos.west(), 300 + k, random, i, Direction.EAST); -+ this.checkBurnOut(level, pos.below(), 250 + k, random, i, Direction.UP); -+ this.checkBurnOut(level, pos.above(), 250 + k, random, i, Direction.DOWN); -+ this.checkBurnOut(level, pos.north(), 300 + k, random, i, Direction.SOUTH); -+ this.checkBurnOut(level, pos.south(), 300 + k, random, i, Direction.NORTH); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + boolean increasedBurnout = level.environmentAttributes().getValue(EnvironmentAttributes.INCREASED_FIRE_BURNOUT, pos); + int extra = increasedBurnout ? -50 : 0; +- this.checkBurnOut(level, pos.east(), 300 + extra, random, age); +- this.checkBurnOut(level, pos.west(), 300 + extra, random, age); +- this.checkBurnOut(level, pos.below(), 250 + extra, random, age); +- this.checkBurnOut(level, pos.above(), 250 + extra, random, age); +- this.checkBurnOut(level, pos.north(), 300 + extra, random, age); +- this.checkBurnOut(level, pos.south(), 300 + extra, random, age); ++ this.checkBurnOut(level, pos.east(), 300 + extra, random, age, Direction.WEST); ++ this.checkBurnOut(level, pos.west(), 300 + extra, random, age, Direction.EAST); ++ this.checkBurnOut(level, pos.below(), 250 + extra, random, age, Direction.UP); ++ this.checkBurnOut(level, pos.above(), 250 + extra, random, age, Direction.DOWN); ++ this.checkBurnOut(level, pos.north(), 300 + extra, random, age, Direction.SOUTH); ++ this.checkBurnOut(level, pos.south(), 300 + extra, random, age, Direction.NORTH); + BlockPos.MutableBlockPos testPos = new BlockPos.MutableBlockPos(); - for (int l = -1; l <= 1; l++) { + for (int xx = -1; xx <= 1; xx++) { @@ -221,33 +_,31 @@ || level.isRainingAt(testPos.south()); } @@ -72,20 +72,20 @@ } - private void checkBurnOut(final Level level, final BlockPos pos, final int chance, final RandomSource random, final int age) { -- int i = this.getBurnOdds(level.getBlockState(pos)); +- int odds = this.getBurnOdds(level.getBlockState(pos)); + private void checkBurnOut(final Level level, final BlockPos pos, final int chance, final RandomSource random, final int age, final Direction face) { -+ int i = level.getBlockState(pos).getFlammability(level, pos, face); - if (random.nextInt(chance) < i) { - BlockState blockstate = level.getBlockState(pos); -+ blockstate.onCaughtFire(level, pos, face, null); ++ int odds = level.getBlockState(pos).getFlammability(level, pos, face); + if (random.nextInt(chance) < odds) { + BlockState oldState = level.getBlockState(pos); ++ oldState.onCaughtFire(level, pos, face, null); if (random.nextInt(age + 10) < 5 && !level.isRainingAt(pos)) { - int j = Math.min(age + random.nextInt(5) / 4, 15); - level.setBlock(pos, this.getStateWithAge(level, pos, j), 3); + int newAge = Math.min(age + random.nextInt(5) / 4, 15); + level.setBlock(pos, this.getStateWithAge(level, pos, newAge), 3); } else { level.removeBlock(pos, false); } - -- Block block = blockstate.getBlock(); +- Block block = oldState.getBlock(); - if (block instanceof TntBlock) { - TntBlock.prime(level, pos); - } @@ -104,12 +104,12 @@ @@ -274,13 +_,14 @@ for (Direction direction : Direction.values()) { - BlockState blockstate = level.getBlockState(pos.relative(direction)); -- i = Math.max(this.getIgniteOdds(blockstate), i); -+ i = Math.max(blockstate.getFireSpreadSpeed(level, pos.relative(direction), direction.getOpposite()), i); + BlockState blockState = level.getBlockState(pos.relative(direction)); +- odds = Math.max(this.getIgniteOdds(blockState), odds); ++ odds = Math.max(blockState.getFireSpreadSpeed(level, pos.relative(direction), direction.getOpposite()), odds); } - return i; + return odds; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch index 9c1e316842..e834b7e983 100644 --- a/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/FlowerPotBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/FlowerPotBlock.java +++ b/net/minecraft/world/level/block/FlowerPotBlock.java -@@ -44,9 +_,31 @@ +@@ -43,9 +_,31 @@ } public FlowerPotBlock(final Block potted, final BlockBehaviour.Properties properties) { @@ -34,17 +34,17 @@ } @Override -@@ -65,7 +_,7 @@ +@@ -64,7 +_,7 @@ final BlockHitResult hitResult ) { - BlockState blockstate = (itemStack.getItem() instanceof BlockItem blockitem -- ? POTTED_BY_CONTENT.getOrDefault(blockitem.getBlock(), Blocks.AIR) -+ ? getEmptyPot().fullPots.getOrDefault(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey(blockitem.getBlock()), net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.AIR)).get() + BlockState newContents = (itemStack.getItem() instanceof BlockItem blockItem +- ? POTTED_BY_CONTENT.getOrDefault(blockItem.getBlock(), Blocks.AIR) ++ ? getEmptyPot().fullPots.getOrDefault(net.minecraftforge.registries.ForgeRegistries.BLOCKS.getKey(blockItem.getBlock()), net.minecraftforge.registries.ForgeRegistries.BLOCKS.getDelegateOrThrow(Blocks.AIR)).get() : Blocks.AIR) .defaultBlockState(); - if (blockstate.isAir()) { -@@ -93,7 +_,7 @@ - player.drop(itemstack, false); + if (newContents.isAir()) { +@@ -92,7 +_,7 @@ + player.drop(plant, false); } - level.setBlock(pos, Blocks.FLOWER_POT.defaultBlockState(), 3); @@ -52,7 +52,7 @@ level.gameEvent(player, GameEvent.BLOCK_CHANGE, pos); return InteractionResult.SUCCESS; } -@@ -125,7 +_,7 @@ +@@ -124,7 +_,7 @@ } public Block getPotted() { @@ -61,7 +61,7 @@ } @Override -@@ -160,5 +_,24 @@ +@@ -159,5 +_,24 @@ } else { return state.is(Blocks.POTTED_CLOSED_EYEBLOSSOM) ? Blocks.POTTED_OPEN_EYEBLOSSOM.defaultBlockState() : state; } diff --git a/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch index c974ea5f03..affd25cb75 100644 --- a/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/GrowingPlantHeadBlock.java.patch @@ -8,10 +8,10 @@ + var vanilla = random.nextDouble() < this.growPerTickProbability; + var target = pos.relative(this.growthDirection); + if (state.getValue(AGE) < 25 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, target, level.getBlockState(target), vanilla)) { - BlockPos blockpos = pos.relative(this.growthDirection); - if (this.canGrowInto(level.getBlockState(blockpos))) { - level.setBlockAndUpdate(blockpos, this.getGrowIntoState(state, level.getRandom())); -+ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, blockpos, level.getBlockState(blockpos)); + BlockPos growthPos = pos.relative(this.growthDirection); + if (this.canGrowInto(level.getBlockState(growthPos))) { + level.setBlockAndUpdate(growthPos, this.getGrowIntoState(state, level.getRandom())); ++ net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, growthPos, level.getBlockState(growthPos)); } } } diff --git a/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch index c80ec25edb..02758f99bc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/LiquidBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/LiquidBlock.java +++ b/net/minecraft/world/level/block/LiquidBlock.java -@@ -53,7 +_,8 @@ +@@ -52,7 +_,8 @@ i -> i.group(FLOWING_FLUID.fieldOf("fluid").forGetter(b -> b.fluid), propertiesCodec()).apply(i, LiquidBlock::new) ); public static final IntegerProperty LEVEL = BlockStateProperties.LEVEL; @@ -10,7 +10,7 @@ private final List stateCache; public static final ImmutableList POSSIBLE_FLOW_DIRECTIONS = ImmutableList.of( Direction.DOWN, Direction.SOUTH, Direction.NORTH, Direction.EAST, Direction.WEST -@@ -65,6 +_,7 @@ +@@ -64,6 +_,7 @@ return CODEC; } @@ -18,7 +18,7 @@ public LiquidBlock(final FlowingFluid fluid, final BlockBehaviour.Properties properties) { super(properties); this.fluid = fluid; -@@ -77,6 +_,19 @@ +@@ -76,6 +_,19 @@ this.stateCache.add(fluid.getFlowing(8, true)); this.registerDefaultState(this.stateDefinition.any().setValue(LEVEL, 0)); @@ -38,15 +38,15 @@ } @Override -@@ -125,6 +_,7 @@ +@@ -124,6 +_,7 @@ @Override protected FluidState getFluidState(final BlockState state) { - int i = state.getValue(LEVEL); + int level = state.getValue(LEVEL); + if (!fluidStateCacheInitialized) initFluidStateCache(); - return this.stateCache.get(Math.min(i, 8)); + return this.stateCache.get(Math.min(level, 8)); } -@@ -150,7 +_,7 @@ +@@ -149,7 +_,7 @@ @Override protected void onPlace(final BlockState state, final Level level, final BlockPos pos, final BlockState oldState, final boolean movedByPiston) { @@ -55,7 +55,7 @@ level.scheduleTick(pos, state.getFluidState().getType(), this.fluid.getTickDelay(level)); } -@@ -198,7 +_,7 @@ +@@ -197,7 +_,7 @@ protected void neighborChanged( final BlockState state, final Level level, final BlockPos pos, final Block block, final @Nullable Orientation orientation, final boolean movedByPiston ) { @@ -64,15 +64,15 @@ level.scheduleTick(pos, state.getFluidState().getType(), this.fluid.getTickDelay(level)); } -@@ -214,6 +_,7 @@ +@@ -213,6 +_,7 @@ } } + @Deprecated // FORGE: Use FluidInteractionRegistry#canInteract instead private boolean shouldSpreadLiquid(final Level level, final BlockPos pos, final BlockState state) { if (this.fluid.is(FluidTags.LAVA)) { - boolean flag = level.getBlockState(pos.below()).is(Blocks.SOUL_SOIL); -@@ -260,5 +_,24 @@ + boolean isOverSoulSoil = level.getBlockState(pos.below()).is(Blocks.SOUL_SOIL); +@@ -259,5 +_,24 @@ @Override public Optional getPickupSound() { return this.fluid.getPickupSound(); diff --git a/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch index d808cb38f3..4cda0bf3ad 100644 --- a/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/MushroomBlock.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/world/level/block/MushroomBlock.java +++ b/net/minecraft/world/level/block/MushroomBlock.java -@@ -86,7 +_,7 @@ - BlockState blockstate = level.getBlockState(blockpos); - return blockstate.is(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT) - ? true -- : level.getRawBrightness(pos, 0) < 13 && this.mayPlaceOn(blockstate, level, blockpos); -+ : level.getRawBrightness(pos, 0) < 13 && blockstate.canSustainPlant(level, blockpos, net.minecraft.core.Direction.UP, this); +@@ -83,7 +_,7 @@ + protected boolean canSurvive(final BlockState state, final LevelReader level, final BlockPos pos) { + BlockPos belowPos = pos.below(); + BlockState below = level.getBlockState(belowPos); +- return below.is(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT) ? true : level.getRawBrightness(pos, 0) < 13 && this.mayPlaceOn(below, level, belowPos); ++ return below.is(BlockTags.OVERRIDES_MUSHROOM_LIGHT_REQUIREMENT) ? true : level.getRawBrightness(pos, 0) < 13 && below.canSustainPlant(level, belowPos, net.minecraft.core.Direction.UP, this); } public boolean growMushroom(final ServerLevel level, final BlockPos pos, final BlockState state, final RandomSource random) { -@@ -94,8 +_,10 @@ - if (optional.isEmpty()) { +@@ -91,8 +_,10 @@ + if (feature.isEmpty()) { return false; } else { -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, optional.get()); ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, feature.get()); + if (event.getResult().isDenied()) return false; level.removeBlock(pos, false); -- if (optional.get().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { +- if (feature.get().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { + if (event.getFeature().value().place(level, level.getChunkSource().getGenerator(), random, pos)) { return true; } else { diff --git a/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch index 26a4807f44..6aea05dc2f 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NetherFungusBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/NetherFungusBlock.java +++ b/net/minecraft/world/level/block/NetherFungusBlock.java -@@ -82,5 +_,10 @@ +@@ -81,5 +_,10 @@ @Override public void performBonemeal(final ServerLevel level, final RandomSource random, final BlockPos pos, final BlockState state) { this.getFeature(level).ifPresent(feature -> feature.value().place(level, level.getChunkSource().getGenerator(), random, pos)); diff --git a/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch index 46dc3bb4e8..c42fe54bec 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NetherWartBlock.java.patch @@ -3,10 +3,10 @@ @@ -51,9 +_,10 @@ @Override protected void randomTick(BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { - int i = state.getValue(AGE); -- if (i < 3 && random.nextInt(10) == 0) { -+ if (i < 3 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(10) == 0)) { - state = state.setValue(AGE, i + 1); + int age = state.getValue(AGE); +- if (age < 3 && random.nextInt(10) == 0) { ++ if (age < 3 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(10) == 0)) { + state = state.setValue(AGE, age + 1); level.setBlock(pos, state, 2); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } diff --git a/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch index 50b155b569..96515ff319 100644 --- a/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/NoteBlock.java.patch @@ -15,15 +15,15 @@ @Override protected boolean triggerEvent(final BlockState state, final Level level, final BlockPos pos, final int b0, final int b1) { -- NoteBlockInstrument noteblockinstrument = state.getValue(INSTRUMENT); +- NoteBlockInstrument instrument = state.getValue(INSTRUMENT); + var event = net.minecraftforge.event.ForgeEventFactory.onNotePlay(level, pos, state, state.getValue(NOTE), state.getValue(INSTRUMENT)); + if (event == null) return false; + var newState = state.setValue(NOTE, event.getVanillaNoteId()).setValue(INSTRUMENT, event.getInstrument()); -+ NoteBlockInstrument noteblockinstrument = newState.getValue(INSTRUMENT); - float f; - if (noteblockinstrument.isTunable()) { -- int i = state.getValue(NOTE); -+ int i = newState.getValue(NOTE); - f = getPitchFromNote(i); - level.addParticle(ParticleTypes.NOTE, pos.getX() + 0.5, pos.getY() + 1.2, pos.getZ() + 0.5, i / 24.0, 0.0, 0.0); ++ NoteBlockInstrument instrument = newState.getValue(INSTRUMENT); + float pitch; + if (instrument.isTunable()) { +- int note = state.getValue(NOTE); ++ int note = newState.getValue(NOTE); + pitch = getPitchFromNote(note); + level.addParticle(ParticleTypes.NOTE, pos.getX() + 0.5, pos.getY() + 1.2, pos.getZ() + 0.5, note / 24.0, 0.0, 0.0); } else { diff --git a/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch index dd15e2e28a..2f6a3bd8ce 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PoweredRailBlock.java.patch @@ -26,46 +26,45 @@ } @@ -35,7 +_,7 @@ - int j = pos.getY(); - int k = pos.getZ(); - boolean flag = true; -- RailShape railshape = state.getValue(SHAPE); -+ RailShape railshape = state.getValue(getShapeProperty()); - switch (railshape) { + int y = pos.getY(); + int z = pos.getZ(); + boolean checkBelow = true; +- RailShape shape = state.getValue(SHAPE); ++ RailShape shape = state.getValue(getShapeProperty()); + switch (shape) { case NORTH_SOUTH: if (forward) { -@@ -104,10 +_,10 @@ +@@ -104,17 +_,17 @@ protected boolean isSameRailWithPower(final Level level, final BlockPos pos, final boolean forward, final int searchDepth, final RailShape dir) { - BlockState blockstate = level.getBlockState(pos); -- if (!blockstate.is(this)) { -+ if (!(blockstate.getBlock() instanceof PoweredRailBlock other) || this.isActivatorRail() != other.isActivatorRail()) { + BlockState state = level.getBlockState(pos); +- if (!state.is(this)) { ++ if (!(state.getBlock() instanceof PoweredRailBlock other) || this.isActivatorRail() != other.isActivatorRail()) { return false; } else { -- RailShape railshape = blockstate.getValue(SHAPE); -+ RailShape railshape = other.getRailDirection(blockstate, level, pos, null); - if (dir != RailShape.EAST_WEST - || railshape != RailShape.NORTH_SOUTH && railshape != RailShape.ASCENDING_NORTH && railshape != RailShape.ASCENDING_SOUTH) { +- RailShape myShape = state.getValue(SHAPE); ++ RailShape myShape = other.getRailDirection(state, level, pos, null); + if (dir != RailShape.EAST_WEST || myShape != RailShape.NORTH_SOUTH && myShape != RailShape.ASCENDING_NORTH && myShape != RailShape.ASCENDING_SOUTH) { if (dir != RailShape.NORTH_SOUTH -@@ -115,7 +_,7 @@ - if (!blockstate.getValue(POWERED)) { + || myShape != RailShape.EAST_WEST && myShape != RailShape.ASCENDING_EAST && myShape != RailShape.ASCENDING_WEST) { + if (!state.getValue(POWERED)) { return false; } else { -- return level.hasNeighborSignal(pos) ? true : this.findPoweredRailSignal(level, pos, blockstate, forward, searchDepth + 1); -+ return level.hasNeighborSignal(pos) ? true : other.findPoweredRailSignal(level, pos, blockstate, forward, searchDepth + 1); +- return level.hasNeighborSignal(pos) ? true : this.findPoweredRailSignal(level, pos, state, forward, searchDepth + 1); ++ return level.hasNeighborSignal(pos) ? true : other.findPoweredRailSignal(level, pos, state, forward, searchDepth + 1); } } else { return false; -@@ -135,7 +_,7 @@ - if (flag1 != flag) { - level.setBlock(pos, state.setValue(POWERED, flag1), 3); +@@ -134,7 +_,7 @@ + if (shouldPower != isPowered) { + level.setBlock(pos, state.setValue(POWERED, shouldPower), 3); level.updateNeighborsAt(pos.below(), this); - if (state.getValue(SHAPE).isSlope()) { + if (state.getValue(getShapeProperty()).isSlope()) { level.updateNeighborsAt(pos.above(), this); } } -@@ -162,6 +_,10 @@ +@@ -161,6 +_,10 @@ @Override protected void createBlockStateDefinition(final StateDefinition.Builder builder) { diff --git a/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch index 1083fad13e..524f64ecd0 100644 --- a/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/PumpkinBlock.java.patch @@ -7,5 +7,5 @@ - if (!itemStack.is(Items.SHEARS)) { + if (!itemStack.canPerformAction(net.minecraftforge.common.ToolActions.SHEARS_CARVE)) { return super.useItemOn(itemStack, state, level, pos, player, hand, hitResult); - } else if (level instanceof ServerLevel serverlevel) { - Direction direction = hitResult.getDirection(); + } else if (level instanceof ServerLevel serverLevel) { + Direction clickedDirection = hitResult.getDirection(); diff --git a/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch b/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch index 53327dbcbd..a0bc94aa5f 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RailState.java.patch @@ -11,68 +11,68 @@ this.pos = pos; this.state = state; this.block = (BaseRailBlock)state.getBlock(); -- RailShape railshape = state.getValue(this.block.getShapeProperty()); +- RailShape direction = state.getValue(this.block.getShapeProperty()); - this.isStraight = this.block.isStraight(); -+ RailShape railshape = this.block.getRailDirection(state, level, pos, null); ++ RailShape direction = this.block.getRailDirection(state, level, pos, null); + this.isStraight = !this.block.isFlexibleRail(state, level, pos); + this.canMakeSlopes = this.block.canMakeSlopes(state, level, pos); - this.updateConnections(railshape); + this.updateConnections(direction); } @@ -176,7 +_,7 @@ } } -- if (railshape == RailShape.NORTH_SOUTH) { -+ if (railshape == RailShape.NORTH_SOUTH && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos.above())) { - railshape = RailShape.ASCENDING_NORTH; +- if (shape == RailShape.NORTH_SOUTH) { ++ if (shape == RailShape.NORTH_SOUTH && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, north.above())) { + shape = RailShape.ASCENDING_NORTH; } @@ -186,7 +_,7 @@ } } -- if (railshape == RailShape.EAST_WEST) { -+ if (railshape == RailShape.EAST_WEST && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos3.above())) { - railshape = RailShape.ASCENDING_EAST; +- if (shape == RailShape.EAST_WEST) { ++ if (shape == RailShape.EAST_WEST && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, east.above())) { + shape = RailShape.ASCENDING_EAST; } @@ -198,6 +_,11 @@ - if (railshape == null) { - railshape = RailShape.NORTH_SOUTH; + if (shape == null) { + shape = RailShape.NORTH_SOUTH; + } + -+ if (!this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid ++ if (!this.block.isValidRailShape(shape)) { // Forge: allow rail block to decide if the new shape is valid + this.connections.remove(rail.pos); + return; } - this.state = this.state.setValue(this.block.getShapeProperty(), railshape); + this.state = this.state.setValue(this.block.getShapeProperty(), shape); @@ -302,7 +_,7 @@ } } -- if (railshape == RailShape.NORTH_SOUTH) { -+ if (railshape == RailShape.NORTH_SOUTH && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos.above())) { - railshape = RailShape.ASCENDING_NORTH; +- if (shape == RailShape.NORTH_SOUTH) { ++ if (shape == RailShape.NORTH_SOUTH && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, north.above())) { + shape = RailShape.ASCENDING_NORTH; } @@ -312,7 +_,7 @@ } } -- if (railshape == RailShape.EAST_WEST) { -+ if (railshape == RailShape.EAST_WEST && canMakeSlopes) { - if (BaseRailBlock.isRail(this.level, blockpos3.above())) { - railshape = RailShape.ASCENDING_EAST; +- if (shape == RailShape.EAST_WEST) { ++ if (shape == RailShape.EAST_WEST && canMakeSlopes) { + if (BaseRailBlock.isRail(this.level, east.above())) { + shape = RailShape.ASCENDING_EAST; } @@ -322,7 +_,7 @@ } } -- if (railshape == null) { -+ if (railshape == null || !this.block.isValidRailShape(railshape)) { // Forge: allow rail block to decide if the new shape is valid - railshape = defaultShape; +- if (shape == null) { ++ if (shape == null || !this.block.isValidRailShape(shape)) { // Forge: allow rail block to decide if the new shape is valid + shape = defaultShape; } diff --git a/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch index 108ccb12bd..87973efc87 100644 --- a/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/RedStoneWireBlock.java.patch @@ -1,28 +1,28 @@ --- a/net/minecraft/world/level/block/RedStoneWireBlock.java +++ b/net/minecraft/world/level/block/RedStoneWireBlock.java -@@ -244,7 +_,7 @@ - BlockState blockstate = level.getBlockState(blockpos); +@@ -242,7 +_,7 @@ + BlockState relativeState = level.getBlockState(relativePos); if (canConnectUp) { - boolean flag = blockstate.getBlock() instanceof TrapDoorBlock || this.canSurviveOn(level, blockpos, blockstate); -- if (flag && shouldConnectTo(level.getBlockState(blockpos.above()))) { -+ if (flag && level.getBlockState(blockpos.above()).canRedstoneConnectTo(level, blockpos.above(), null)) { - if (blockstate.isFaceSturdy(level, blockpos, direction.getOpposite())) { + boolean isPlaceableAbove = relativeState.getBlock() instanceof TrapDoorBlock || this.canSurviveOn(level, relativePos, relativeState); +- if (isPlaceableAbove && shouldConnectTo(level.getBlockState(relativePos.above()))) { ++ if (isPlaceableAbove && level.getBlockState(relativePos.above()).canRedstoneConnectTo(level, relativePos.above(), null)) { + if (relativeState.isFaceSturdy(level, relativePos, direction.getOpposite())) { return RedstoneSide.UP; } -@@ -253,10 +_,14 @@ +@@ -251,10 +_,14 @@ } } -- return !shouldConnectTo(blockstate, direction) -- && (blockstate.isRedstoneConductor(level, blockpos) || !shouldConnectTo(level.getBlockState(blockpos.below()))) +- return !shouldConnectTo(relativeState, direction) +- && (relativeState.isRedstoneConductor(level, relativePos) || !shouldConnectTo(level.getBlockState(relativePos.below()))) - ? RedstoneSide.NONE - : RedstoneSide.SIDE; -+ if (blockstate.canRedstoneConnectTo(level, blockpos, direction)) { ++ if (relativeState.canRedstoneConnectTo(level, relativePos, direction)) { + return RedstoneSide.SIDE; -+ } else if (blockstate.isRedstoneConductor(level, blockpos)) { ++ } else if (relativeState.isRedstoneConductor(level, relativePos)) { + return RedstoneSide.NONE; + } else { -+ BlockPos blockPosBelow = blockpos.below(); ++ BlockPos blockPosBelow = relativePos.below(); + return level.getBlockState(blockPosBelow).canRedstoneConnectTo(level, blockPosBelow, null) ? RedstoneSide.SIDE : RedstoneSide.NONE; + } } diff --git a/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch index cc52c409f2..84dea3faff 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SaplingBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/SaplingBlock.java +++ b/net/minecraft/world/level/block/SaplingBlock.java -@@ -44,6 +_,7 @@ +@@ -43,6 +_,7 @@ @Override protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { diff --git a/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch index 4d8cda0d3b..bf57b5a8f8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpawnerBlock.java.patch @@ -6,9 +6,9 @@ super.spawnAfterBreak(state, level, pos, tool, dropExperience); - if (dropExperience) { + if (false && dropExperience) { // Forge: moved to getExpDrop - RandomSource randomsource = level.getRandom(); - int i = 15 + randomsource.nextInt(15) + randomsource.nextInt(15); - this.popExperience(level, pos, i); + RandomSource random = level.getRandom(); + int magicCount = 15 + random.nextInt(15) + random.nextInt(15); + this.popExperience(level, pos, magicCount); } + } + diff --git a/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch index 0fc44ada10..6adf106c89 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpongeBlock.java.patch @@ -1,19 +1,19 @@ --- a/net/minecraft/world/level/block/SpongeBlock.java +++ b/net/minecraft/world/level/block/SpongeBlock.java -@@ -53,6 +_,7 @@ +@@ -52,6 +_,7 @@ } private boolean removeWaterBreadthFirstSearch(final Level level, final BlockPos startPos) { + BlockState spongeState = level.getBlockState(startPos); - return BlockPos.breadthFirstTraversal( - startPos, - 6, -@@ -68,7 +_,7 @@ - } else { - BlockState blockstate = level.getBlockState(pos); - FluidState fluidstate = level.getFluidState(pos); -- if (!fluidstate.is(FluidTags.WATER)) { -+ if (!spongeState.canBeHydrated(level, startPos, fluidstate, pos)) { - return BlockPos.TraversalNodeStatus.SKIP; - } else if (blockstate.getBlock() instanceof BucketPickup bucketpickup - && !bucketpickup.pickupBlock(null, level, pos, blockstate).isEmpty()) { + return BlockPos.breadthFirstTraversal(startPos, 6, 65, (pos, consumer) -> { + for (Direction direction : ALL_DIRECTIONS) { + consumer.accept(pos.relative(direction)); +@@ -62,7 +_,7 @@ + } else { + BlockState state = level.getBlockState(pos); + FluidState fluidState = level.getFluidState(pos); +- if (!fluidState.is(FluidTags.WATER)) { ++ if (!spongeState.canBeHydrated(level, startPos, fluidState, pos)) { + return BlockPos.TraversalNodeStatus.SKIP; + } else if (state.getBlock() instanceof BucketPickup bucketPickup && !bucketPickup.pickupBlock(null, level, pos, state).isEmpty()) { + return BlockPos.TraversalNodeStatus.ACCEPT; diff --git a/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch index f662040538..fac93f9e19 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SpreadingSnowyBlock.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/block/SpreadingSnowyBlock.java +++ b/net/minecraft/world/level/block/SpreadingSnowyBlock.java @@ -50,8 +_,10 @@ - Optional optional = registry.getOptional(this.baseBlock); - if (!optional.isEmpty()) { + Optional baseBlock = blocks.getOptional(this.baseBlock); + if (!baseBlock.isEmpty()) { if (!canStayAlive(state, level, pos)) { + if (!level.isAreaLoaded(pos, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading - level.setBlockAndUpdate(pos, optional.get().defaultBlockState()); + level.setBlockAndUpdate(pos, baseBlock.get().defaultBlockState()); } else { + if (!level.isAreaLoaded(pos, 3)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light and spreading if (level.getMaxLocalRawBrightness(pos.above()) >= 9) { - BlockState blockstate = this.defaultBlockState(); + BlockState defaultBlockState = this.defaultBlockState(); diff --git a/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch index 24f643571d..f254b11706 100644 --- a/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/StemBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/StemBlock.java +++ b/net/minecraft/world/level/block/StemBlock.java -@@ -77,14 +_,16 @@ +@@ -76,14 +_,16 @@ @Override protected boolean mayPlaceOn(final BlockState state, final BlockGetter level, final BlockPos pos) { @@ -12,23 +12,23 @@ protected void randomTick(BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { + if (!level.isAreaLoaded(pos, 1)) return; // Forge: prevent loading unloaded chunks when checking neighbor's light if (level.getRawBrightness(pos, 0) >= 9) { - float f = CropBlock.getGrowthSpeed(this, level, pos); -- if (random.nextInt((int)(25.0F / f) + 1) == 0) { -+ var vanilla = random.nextInt((int)(25.0F / f) + 1) == 0; + float growthSpeed = CropBlock.getGrowthSpeed(this, level, pos); +- if (random.nextInt((int)(25.0F / growthSpeed) + 1) == 0) { ++ var vanilla = random.nextInt((int)(25.0F / growthSpeed) + 1) == 0; + if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, vanilla)) { - int i = state.getValue(AGE); - if (i < 7) { - state = state.setValue(AGE, i + 1); -@@ -93,7 +_,7 @@ + int age = state.getValue(AGE); + if (age < 7) { + state = state.setValue(AGE, age + 1); +@@ -92,7 +_,7 @@ Direction direction = Direction.Plane.HORIZONTAL.getRandomDirection(random); - BlockPos blockpos = pos.relative(direction); - BlockState blockstate = level.getBlockState(blockpos.below()); -- if (level.getBlockState(blockpos).isAir() && blockstate.is(this.fruitSupportBlocks)) { -+ if (level.getBlockState(blockpos).isAir() && (blockstate.is(this.fruitSupportBlocks) || blockstate.getBlock() instanceof FarmlandBlock)) { - Registry registry = level.registryAccess().lookupOrThrow(Registries.BLOCK); - Optional optional = registry.getOptional(this.fruit); - Optional optional1 = registry.getOptional(this.attachedStem); -@@ -103,6 +_,7 @@ + BlockPos relative = pos.relative(direction); + BlockState stateBelow = level.getBlockState(relative.below()); +- if (level.getBlockState(relative).isAir() && stateBelow.is(this.fruitSupportBlocks)) { ++ if (level.getBlockState(relative).isAir() && (stateBelow.is(this.fruitSupportBlocks) || stateBelow.getBlock() instanceof FarmlandBlock)) { + Registry blocks = level.registryAccess().lookupOrThrow(Registries.BLOCK); + Optional fruit = blocks.getOptional(this.fruit); + Optional stem = blocks.getOptional(this.attachedStem); +@@ -102,6 +_,7 @@ } } } @@ -36,7 +36,7 @@ } } } -@@ -135,5 +_,10 @@ +@@ -134,5 +_,10 @@ @Override protected void createBlockStateDefinition(final StateDefinition.Builder builder) { builder.add(AGE); diff --git a/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch index f8e563c098..07dd2b1c81 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SugarCaneBlock.java.patch @@ -11,15 +11,15 @@ private static final VoxelShape SHAPE = Block.column(12.0, 0.0, 16.0); @@ -57,12 +_,15 @@ - if (i < 3) { - int j = state.getValue(AGE); + if (height < 3) { + int age = state.getValue(AGE); + if (net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, true)) { - if (j == 15) { + if (age == 15) { level.setBlockAndUpdate(pos.above(), this.defaultBlockState()); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos.above(), this.defaultBlockState()); level.setBlock(pos, state.setValue(AGE, 0), 260); } else { - level.setBlock(pos, state.setValue(AGE, j + 1), 260); + level.setBlock(pos, state.setValue(AGE, age + 1), 260); } + } } @@ -31,15 +31,15 @@ protected boolean canSurvive(final BlockState state, final LevelReader level, final BlockPos pos) { + BlockState soil = level.getBlockState(pos.below()); + if (soil.canSustainPlant(level, pos.below(), Direction.UP, this)) return true; - BlockState blockstate = level.getBlockState(pos.below()); - if (blockstate.is(this)) { + BlockState stateBelow = level.getBlockState(pos.below()); + if (stateBelow.is(this)) { return true; @@ -97,7 +_,7 @@ for (Direction direction : Direction.Plane.HORIZONTAL) { - BlockState blockstate1 = level.getBlockState(blockpos.relative(direction)); - FluidState fluidstate = level.getFluidState(blockpos.relative(direction)); -- if (fluidstate.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockstate1.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY)) { -+ if (fluidstate.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockstate1.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || state.canBeHydrated(level, pos, fluidstate, blockpos.relative(direction))) { + BlockState blockState = level.getBlockState(below.relative(direction)); + FluidState fluidState = level.getFluidState(below.relative(direction)); +- if (fluidState.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockState.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY)) { ++ if (fluidState.is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || blockState.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY) || state.canBeHydrated(level, pos, fluidState, below.relative(direction))) { return true; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch index 949a436983..1319def1dc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/SweetBerryBushBlock.java.patch @@ -3,12 +3,12 @@ @@ -71,10 +_,11 @@ @Override protected void randomTick(final BlockState state, final ServerLevel level, final BlockPos pos, final RandomSource random) { - int i = state.getValue(AGE); -- if (i < 3 && random.nextInt(5) == 0 && level.getRawBrightness(pos.above(), 0) >= 9) { -+ if (i < 3 && level.getRawBrightness(pos.above(), 0) >= 9 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(5) == 0)) { - BlockState blockstate = state.setValue(AGE, i + 1); - level.setBlock(pos, blockstate, 2); - level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(blockstate)); + int age = state.getValue(AGE); +- if (age < 3 && random.nextInt(5) == 0 && level.getRawBrightness(pos.above(), 0) >= 9) { ++ if (age < 3 && level.getRawBrightness(pos.above(), 0) >= 9 && net.minecraftforge.common.ForgeHooks.onCropsGrowPre(level, pos, state, random.nextInt(5) == 0)) { + BlockState newState = state.setValue(AGE, age + 1); + level.setBlock(pos, newState, 2); + level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(newState)); + net.minecraftforge.common.ForgeHooks.onCropsGrowPost(level, pos, state); } } diff --git a/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch index 3aec1d172c..85960d6414 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TntBlock.java.patch @@ -38,8 +38,8 @@ + @Deprecated //Forge: Prefer using IForgeBlock#onCaughtFire private static boolean prime(final Level level, final BlockPos pos, final @Nullable LivingEntity source) { - if (level instanceof ServerLevel serverlevel && serverlevel.getGameRules().get(GameRules.TNT_EXPLODES)) { - PrimedTnt primedtnt = new PrimedTnt(level, pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, source); + if (level instanceof ServerLevel serverLevel && serverLevel.getGameRules().get(GameRules.TNT_EXPLODES)) { + PrimedTnt tnt = new PrimedTnt(level, pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5, source); @@ -110,7 +_,7 @@ if (!itemStack.is(Items.FLINT_AND_STEEL) && !itemStack.is(Items.FIRE_CHARGE)) { return super.useItemOn(itemStack, state, level, pos, player, hand, hitResult); @@ -50,12 +50,12 @@ Item item = itemStack.getItem(); if (itemStack.is(Items.FLINT_AND_STEEL)) { @@ -136,7 +_,7 @@ - Entity entity = projectile.getOwner(); + Entity owner = projectile.getOwner(); if (projectile.isOnFire() - && projectile.mayInteract(serverlevel, blockpos) -- && prime(level, blockpos, entity instanceof LivingEntity ? (LivingEntity)entity : null)) { -+ && onCaughtFire(state, level, blockpos, null, entity instanceof LivingEntity ? (LivingEntity)entity : null)) { - level.removeBlock(blockpos, false); + && projectile.mayInteract(serverLevel, pos) +- && prime(level, pos, owner instanceof LivingEntity ? (LivingEntity)owner : null)) { ++ && onCaughtFire(state, level, pos, null, owner instanceof LivingEntity livingOwner ? livingOwner : null)) { + level.removeBlock(pos, false); } } @@ -150,5 +_,9 @@ diff --git a/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch index 4bf4f864d7..b86a6ca924 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TrapDoorBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/TrapDoorBlock.java +++ b/net/minecraft/world/level/block/TrapDoorBlock.java -@@ -198,4 +_,14 @@ +@@ -196,4 +_,14 @@ protected BlockSetType getType() { return this.type; } diff --git a/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch index d591c0be6b..6a3705dd27 100644 --- a/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/TripWireBlock.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/TripWireBlock.java +++ b/net/minecraft/world/level/block/TripWireBlock.java -@@ -114,7 +_,7 @@ +@@ -113,7 +_,7 @@ @Override public BlockState playerWillDestroy(final Level level, final BlockPos pos, final BlockState state, final Player player) { diff --git a/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch index c6e9af1307..07acf2acd8 100644 --- a/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/VegetationBlock.java.patch @@ -21,11 +21,11 @@ @@ -43,6 +_,9 @@ @Override protected boolean canSurvive(final BlockState state, final LevelReader level, final BlockPos pos) { - BlockPos blockpos = pos.below(); + BlockPos below = pos.below(); + if (state.getBlock() == this) { //Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. -+ return level.getBlockState(blockpos).canSustainPlant(level, blockpos, Direction.UP, this); ++ return level.getBlockState(below).canSustainPlant(level, below, Direction.UP, this); + } - return this.mayPlaceOn(level.getBlockState(blockpos), level, blockpos); + return this.mayPlaceOn(level.getBlockState(below), level, below); } @@ -54,5 +_,11 @@ diff --git a/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch index 60710b01a8..37df0fbd33 100644 --- a/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/VineBlock.java.patch @@ -15,6 +15,6 @@ if (level.getGameRules().get(GameRules.SPREAD_VINES)) { - if (random.nextInt(4) == 0) { + if (random.nextInt(4) == 0 && level.isAreaLoaded(pos, 4)) { // Forge: check area to prevent loading unloaded chunks - Direction direction = Direction.getRandom(random); - BlockPos blockpos = pos.above(); - if (direction.getAxis().isHorizontal() && !state.getValue(getPropertyForFace(direction))) { + Direction testDirection = Direction.getRandom(random); + BlockPos abovePos = pos.above(); + if (testDirection.getAxis().isHorizontal() && !state.getValue(getPropertyForFace(testDirection))) { diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch index cf902c3caf..41eb79789e 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/AbstractFurnaceBlockEntity.java.patch @@ -47,29 +47,29 @@ output.store("RecipesUsed", RECIPES_USED_CODEC, this.recipesUsed); } @@ -164,13 +_,13 @@ - if (recipeholder != null) { - int i = entity.getMaxStackSize(); - ItemStack itemstack2 = recipeholder.value().assemble(singlerecipeinput); -- if (!itemstack2.isEmpty() && canBurn(entity.items, i, itemstack2)) { -+ if (!itemstack2.isEmpty() && entity.canBurn(entity.items, i, itemstack2)) { - if (!flag1) { - int j = entity.getBurnDuration(level.fuelValues(), itemstack); - entity.litTimeRemaining = j; - entity.litTotalTime = j; - if (j > 0) { -- consumeFuel(entity.items, itemstack); -+ entity.consumeFuel(entity.items, itemstack); - flag1 = true; - flag = true; + if (recipe != null) { + int maxStackSize = entity.getMaxStackSize(); + ItemStack burnResult = recipe.value().assemble(input); +- if (!burnResult.isEmpty() && canBurn(entity.items, maxStackSize, burnResult)) { ++ if (!burnResult.isEmpty() && entity.canBurn(entity.items, maxStackSize, burnResult)) { + if (!isLit) { + int newLitTime = entity.getBurnDuration(level.fuelValues(), fuel); + entity.litTimeRemaining = newLitTime; + entity.litTotalTime = newLitTime; + if (newLitTime > 0) { +- consumeFuel(entity.items, fuel); ++ entity.consumeFuel(entity.items, fuel); + isLit = true; + changed = true; } @@ -181,7 +_,7 @@ if (entity.cookingTimer == entity.cookingTotalTime) { entity.cookingTimer = 0; - entity.cookingTotalTime = recipeholder.value().cookingTime(); -- burn(entity.items, itemstack1, itemstack2); -+ entity.burn(entity.items, itemstack1, itemstack2); - entity.setRecipeUsed(recipeholder); - flag = true; + entity.cookingTotalTime = recipe.value().cookingTime(); +- burn(entity.items, ingredient, burnResult); ++ entity.burn(entity.items, ingredient, burnResult); + entity.setRecipeUsed(recipe); + changed = true; } @@ -210,16 +_,16 @@ } @@ -77,21 +77,21 @@ - private static void consumeFuel(final NonNullList items, final ItemStack fuel) { + protected void consumeFuel(final NonNullList items, final ItemStack fuel) { - Item item = fuel.getItem(); + Item fuelItem = fuel.getItem(); - fuel.shrink(1); - if (fuel.isEmpty()) { -- ItemStackTemplate itemstacktemplate = item.getCraftingRemainder(); +- ItemStackTemplate remainder = fuelItem.getCraftingRemainder(); + if (fuel.count() == 1) { -+ ItemStackTemplate itemstacktemplate = fuel.getCraftingRemainder(); - items.set(1, itemstacktemplate != null ? itemstacktemplate.create() : ItemStack.EMPTY); ++ ItemStackTemplate remainder = fuel.getCraftingRemainder(); + items.set(1, remainder != null ? remainder.create() : ItemStack.EMPTY); } + fuel.shrink(1); } - private static boolean canBurn(final NonNullList items, final int maxStackSize, final ItemStack burnResult) { + protected boolean canBurn(final NonNullList items, final int maxStackSize, final ItemStack burnResult) { - ItemStack itemstack = items.get(2); - if (itemstack.isEmpty()) { + ItemStack resultItemStack = items.get(2); + if (resultItemStack.isEmpty()) { return true; @@ -232,7 +_,7 @@ } @@ -99,12 +99,12 @@ - private static void burn(final NonNullList items, final ItemStack inputItemStack, final ItemStack result) { + protected void burn(final NonNullList items, final ItemStack inputItemStack, final ItemStack result) { - ItemStack itemstack = items.get(2); - if (itemstack.isEmpty()) { + ItemStack resultItemStack = items.get(2); + if (resultItemStack.isEmpty()) { items.set(2, result.copy()); @@ -371,6 +_,35 @@ - for (ItemStack itemstack : this.items) { - contents.accountStack(itemstack); + for (ItemStack itemStack : this.items) { + contents.accountStack(itemStack); } + } + diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch index be4c757c69..3ef51f39ee 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/BeaconBlockEntity.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/block/entity/BeaconBlockEntity.java +++ b/net/minecraft/world/level/block/entity/BeaconBlockEntity.java -@@ -141,8 +_,8 @@ +@@ -140,8 +_,8 @@ - for (int i1 = 0; i1 < 10 && blockpos.getY() <= l; i1++) { - BlockState blockstate = level.getBlockState(blockpos); -- if (blockstate.getBlock() instanceof BeaconBeamBlock beaconbeamblock) { -- int j1 = beaconbeamblock.getColor().getTextureDiffuseColor(); -+ int j1 = blockstate.getBeaconColorMultiplier(level, blockpos, pos); -+ if (j1 != -1) { + for (int i = 0; i < 10 && checkPos.getY() <= lastSetBlock; i++) { + BlockState state = level.getBlockState(checkPos); +- if (state.getBlock() instanceof BeaconBeamBlock beaconBeamBlock) { +- int color = beaconBeamBlock.getColor().getTextureDiffuseColor(); ++ int color = state.getBeaconColorMultiplier(level, checkPos, pos); ++ if (color != -1) { if (entity.checkingBeamSections.size() <= 1) { - beaconbeamowner$section = new BeaconBeamOwner.Section(j1); - entity.checkingBeamSections.add(beaconbeamowner$section); + lastBeamSection = new BeaconBeamOwner.Section(color); + entity.checkingBeamSections.add(lastBeamSection); diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch index a87441d396..dd663455ab 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java +++ b/net/minecraft/world/level/block/entity/BrewingStandBlockEntity.java @@ -180,9 +_,10 @@ - for (int i = 0; i < 3; i++) { - items.set(i, potionbrewing.mix(itemstack, items.get(i))); + for (int dest = 0; dest < 3; dest++) { + items.set(dest, potionBrewing.mix(ingredient, items.get(dest))); } + net.minecraftforge.event.ForgeEventFactory.onPotionBrewed(items); -+ ItemStackTemplate itemstacktemplate = itemstack.getCraftingRemainder(); - itemstack.shrink(1); -- ItemStackTemplate itemstacktemplate = itemstack.getItem().getCraftingRemainder(); - if (itemstacktemplate != null) { - if (itemstack.isEmpty()) { - itemstack = itemstacktemplate.create(); ++ ItemStackTemplate remainder = ingredient.getCraftingRemainder(); + ingredient.shrink(1); +- ItemStackTemplate remainder = ingredient.getItem().getCraftingRemainder(); + if (remainder != null) { + if (ingredient.isEmpty()) { + ingredient = remainder.create(); @@ -221,6 +_,9 @@ if (slot == 3) { - PotionBrewing potionbrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; - return potionbrewing.isIngredient(itemStack); + PotionBrewing potionBrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; + return potionBrewing.isIngredient(itemStack); + } else if (slot != 4) { + PotionBrewing potionbrewing = this.level != null ? this.level.potionBrewing() : PotionBrewing.EMPTY; + return this.getItem(slot).isEmpty() && potionbrewing.isValidInput(itemStack); diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch index cc6b2a7fb7..3d92102bd2 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/ConduitBlockEntity.java.patch @@ -1,13 +1,13 @@ --- a/net/minecraft/world/level/block/entity/ConduitBlockEntity.java +++ b/net/minecraft/world/level/block/entity/ConduitBlockEntity.java -@@ -148,8 +_,8 @@ - BlockPos blockpos1 = worldPosition.offset(j1, k1, l1); - BlockState blockstate = level.getBlockState(blockpos1); +@@ -149,8 +_,8 @@ + BlockPos testPos = worldPosition.offset(ox, oy, ozx); + BlockState testBlock = level.getBlockState(testPos); -- for (Block block : VALID_BLOCKS) { -- if (blockstate.is(block)) { +- for (Block type : VALID_BLOCKS) { +- if (testBlock.is(type)) { + { -+ if (blockstate.isConduitFrame(level, blockpos1, worldPosition)) { - effectBlocks.add(blockpos1); ++ if (testBlock.isConduitFrame(level, testPos, worldPosition)) { + effectBlocks.add(testPos); } } diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch index 4d99d967ce..405f8ffafc 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/FuelValues.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/block/entity/FuelValues.java +++ b/net/minecraft/world/level/block/entity/FuelValues.java -@@ -25,7 +_,11 @@ +@@ -24,7 +_,11 @@ } public boolean isFuel(final ItemStack itemStack) { @@ -13,7 +13,7 @@ } public SequencedSet fuelItems() { -@@ -33,7 +_,16 @@ +@@ -32,7 +_,16 @@ } public int burnDuration(final ItemStack itemStack) { diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch index b3fdae3c79..1854dd3606 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/HopperBlockEntity.java.patch @@ -14,10 +14,10 @@ public static boolean suckInItems(final Level level, final Hopper hopper) { + Boolean ret = net.minecraftforge.items.VanillaInventoryCodeHooks.extractHook(level, hopper); + if (ret != null) return ret; - BlockPos blockpos = BlockPos.containing(hopper.getLevelX(), hopper.getLevelY() + 1.0, hopper.getLevelZ()); - BlockState blockstate = level.getBlockState(blockpos); - Container container = getSourceContainer(level, hopper, blockpos, blockstate); -@@ -452,5 +_,14 @@ + BlockPos blockPos = BlockPos.containing(hopper.getLevelX(), hopper.getLevelY() + 1.0, hopper.getLevelZ()); + BlockState blockState = level.getBlockState(blockPos); + Container container = getSourceContainer(level, hopper, blockPos, blockState); +@@ -454,5 +_,14 @@ @Override protected AbstractContainerMenu createMenu(final int containerId, final Inventory inventory) { return new HopperMenu(containerId, inventory, this); diff --git a/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch index 2ddd14150f..5cbf076895 100644 --- a/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java +++ b/net/minecraft/world/level/block/entity/SpawnerBlockEntity.java @@ -37,6 +_,13 @@ - level.sendBlockUpdated(pos, blockstate, blockstate, 260); + level.sendBlockUpdated(pos, state, state, 260); } } + diff --git a/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch b/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch index 1381d170a6..264e201f4d 100644 --- a/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/grower/TreeGrower.java.patch @@ -1,12 +1,12 @@ --- a/net/minecraft/world/level/block/grower/TreeGrower.java +++ b/net/minecraft/world/level/block/grower/TreeGrower.java -@@ -128,6 +_,9 @@ - ResourceKey> resourcekey = this.getConfiguredMegaFeature(random); - if (resourcekey != null) { - Holder> holder = level.registryAccess().lookupOrThrow(Registries.CONFIGURED_FEATURE).get(resourcekey).orElse(null); -+ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, holder); -+ holder = event.getFeature(); +@@ -131,6 +_,9 @@ + .lookupOrThrow(Registries.CONFIGURED_FEATURE) + .get(megaFeatureKey) + .orElse(null); ++ var event = net.minecraftforge.event.ForgeEventFactory.blockGrowFeature(level, random, pos, featureHolder); ++ featureHolder = event.getFeature(); + if (event.getResult().isDenied()) return false; - if (holder != null) { - for (int i = 0; i >= -1; i--) { - for (int j = 0; j >= -1; j--) { + if (featureHolder != null) { + for (int dx = 0; dx >= -1; dx--) { + for (int dz = 0; dz >= -1; dz--) { diff --git a/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch b/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch index 6ce710b0c8..2488659999 100644 --- a/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/piston/PistonBaseBlock.java.patch @@ -1,30 +1,30 @@ --- a/net/minecraft/world/level/block/piston/PistonBaseBlock.java +++ b/net/minecraft/world/level/block/piston/PistonBaseBlock.java -@@ -169,6 +_,7 @@ +@@ -164,6 +_,7 @@ - RandomSource randomsource = level.getRandom(); + RandomSource random = level.getRandom(); if (b0 == 0) { + if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(level, pos, direction, true)) return false; if (!this.moveBlocks(level, pos, direction, true)) { return false; } -@@ -177,6 +_,7 @@ - level.playSound(null, pos, SoundEvents.PISTON_EXTEND, SoundSource.BLOCKS, 0.5F, randomsource.nextFloat() * 0.25F + 0.6F); - level.gameEvent(GameEvent.BLOCK_ACTIVATE, pos, GameEvent.Context.of(blockstate)); +@@ -172,6 +_,7 @@ + level.playSound(null, pos, SoundEvents.PISTON_EXTEND, SoundSource.BLOCKS, 0.5F, random.nextFloat() * 0.25F + 0.6F); + level.gameEvent(GameEvent.BLOCK_ACTIVATE, pos, GameEvent.Context.of(extendedState)); } else if (b0 == 1 || b0 == 2) { + if (net.minecraftforge.event.ForgeEventFactory.onPistonMovePre(level, pos, direction, false)) return false; - BlockEntity blockentity = level.getBlockEntity(pos.relative(direction)); - if (blockentity instanceof PistonMovingBlockEntity) { - ((PistonMovingBlockEntity)blockentity).finalTick(); -@@ -226,6 +_,7 @@ - level.gameEvent(GameEvent.BLOCK_DEACTIVATE, pos, GameEvent.Context.of(blockstate1)); + BlockEntity prevBlockEntity = level.getBlockEntity(pos.relative(direction)); + if (prevBlockEntity instanceof PistonMovingBlockEntity) { + ((PistonMovingBlockEntity)prevBlockEntity).finalTick(); +@@ -221,6 +_,7 @@ + level.gameEvent(GameEvent.BLOCK_DEACTIVATE, pos, GameEvent.Context.of(movingPistonState)); } + net.minecraftforge.event.ForgeEventFactory.onPistonMovePost(level, pos, direction, (b0 == 0)); return true; } -@@ -377,6 +_,11 @@ +@@ -369,6 +_,11 @@ @Override protected BlockState rotate(final BlockState state, final Rotation rotation) { return state.setValue(FACING, rotation.rotate(state.getValue(FACING))); diff --git a/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch b/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch index 013a0b0852..8f66434ff9 100644 --- a/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java +++ b/net/minecraft/world/level/block/piston/PistonMovingBlockEntity.java @@ -126,7 +_,7 @@ - List list = level.getEntities(null, PistonMath.getMovementArea(aabb, direction, d0).minmax(aabb)); - if (!list.isEmpty()) { - List list1 = voxelshape.toAabbs(); -- boolean flag = self.movedState.is(Blocks.SLIME_BLOCK); -+ boolean flag = self.movedState.isSlimeBlock(); - Iterator iterator = list.iterator(); + List entities = level.getEntities(null, PistonMath.getMovementArea(aabb, movement, deltaProgress).minmax(aabb)); + if (!entities.isEmpty()) { + List shapeAabbs = shape.toAabbs(); +- boolean causeBounce = self.movedState.is(Blocks.SLIME_BLOCK); ++ boolean causeBounce = self.movedState.isSlimeBlock(); + Iterator var12 = entities.iterator(); while (true) { diff --git a/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch b/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch index 8a68473bd0..6e5e4f335d 100644 --- a/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/piston/PistonStructureResolver.java.patch @@ -3,9 +3,9 @@ @@ -50,7 +_,7 @@ } else { for (int i = 0; i < this.toPush.size(); i++) { - BlockPos blockpos = this.toPush.get(i); -- if (isSticky(this.level.getBlockState(blockpos)) && !this.addBranchingBlocks(blockpos)) { -+ if (this.level.getBlockState(blockpos).isStickyBlock() && !this.addBranchingBlocks(blockpos)) { + BlockPos pos = this.toPush.get(i); +- if (isSticky(this.level.getBlockState(pos)) && !this.addBranchingBlocks(pos)) { ++ if (this.level.getBlockState(pos).isStickyBlock() && !this.addBranchingBlocks(pos)) { return false; } } @@ -26,42 +26,42 @@ - } - private boolean addBlockLine(final BlockPos start, final Direction direction) { - BlockState blockstate = this.level.getBlockState(start); -- if (blockstate.isAir()) { + BlockState nextState = this.level.getBlockState(start); +- if (nextState.isAir()) { + if (level.isEmptyBlock(start)) { return true; - } else if (!PistonBaseBlock.isPushable(blockstate, this.level, start, this.pushDirection, false, direction)) { + } else if (!PistonBaseBlock.isPushable(nextState, this.level, start, this.pushDirection, false, direction)) { return true; @@ -86,12 +_,12 @@ - if (i + this.toPush.size() > 12) { + if (blockCount + this.toPush.size() > 12) { return false; } else { -- while (isSticky(blockstate)) { -+ while (blockstate.isStickyBlock()) { - BlockPos blockpos = start.relative(this.pushDirection.getOpposite(), i); - BlockState blockstate1 = blockstate; - blockstate = this.level.getBlockState(blockpos); - if (blockstate.isAir() -- || !canStickToEachOther(blockstate1, blockstate) -+ || !(blockstate1.canStickTo(blockstate) && blockstate.canStickTo(blockstate1)) - || !PistonBaseBlock.isPushable(blockstate, this.level, blockpos, this.pushDirection, false, this.pushDirection.getOpposite()) - || blockpos.equals(this.pistonPos)) { +- while (isSticky(nextState)) { ++ while (nextState.isStickyBlock()) { + BlockPos pos = start.relative(this.pushDirection.getOpposite(), blockCount); + BlockState previousState = nextState; + nextState = this.level.getBlockState(pos); + if (nextState.isAir() +- || !canStickToEachOther(previousState, nextState) ++ || !(previousState.canStickTo(nextState) && nextState.canStickTo(previousState)) + || !PistonBaseBlock.isPushable(nextState, this.level, pos, this.pushDirection, false, this.pushDirection.getOpposite()) + || pos.equals(this.pistonPos)) { break; @@ -119,7 +_,7 @@ - for (int k = 0; k <= j + l; k++) { - BlockPos blockpos2 = this.toPush.get(k); -- if (isSticky(this.level.getBlockState(blockpos2)) && !this.addBranchingBlocks(blockpos2)) { -+ if (this.level.getBlockState(blockpos2).isStickyBlock() && !this.addBranchingBlocks(blockpos2)) { + for (int j = 0; j <= collisionPos + blocksAdded; j++) { + BlockPos blockPos = this.toPush.get(j); +- if (isSticky(this.level.getBlockState(blockPos)) && !this.addBranchingBlocks(blockPos)) { ++ if (this.level.getBlockState(blockPos).isStickyBlock() && !this.addBranchingBlocks(blockPos)) { return false; } } -@@ -174,7 +_,7 @@ +@@ -173,7 +_,7 @@ if (direction.getAxis() != this.pushDirection.getAxis()) { - BlockPos blockpos = fromPos.relative(direction); - BlockState blockstate1 = this.level.getBlockState(blockpos); -- if (canStickToEachOther(blockstate1, blockstate) && !this.addBlockLine(blockpos, direction)) { -+ if (blockstate1.canStickTo(blockstate) && blockstate.canStickTo(blockstate1) && !this.addBlockLine(blockpos, direction)) { + BlockPos neighbourPos = fromPos.relative(direction); + BlockState neighbourState = this.level.getBlockState(neighbourPos); +- if (canStickToEachOther(neighbourState, fromState) && !this.addBlockLine(neighbourPos, direction)) { ++ if (neighbourState.canStickTo(fromState) && fromState.canStickTo(neighbourState) && !this.addBlockLine(neighbourPos, direction)) { return false; } } diff --git a/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch b/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch index 31425e5253..5ebedf6168 100644 --- a/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch +++ b/patches/minecraft/net/minecraft/world/level/block/state/BlockBehaviour.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/level/block/state/BlockBehaviour.java +++ b/net/minecraft/world/level/block/state/BlockBehaviour.java -@@ -181,7 +_,7 @@ +@@ -180,7 +_,7 @@ if (!state.isAir() && explosion.getBlockInteraction() != Explosion.BlockInteraction.TRIGGER_BLOCK) { Block block = state.getBlock(); - boolean flag = explosion.getIndirectSourceEntity() instanceof Player; + boolean doDropExperienceHack = explosion.getIndirectSourceEntity() instanceof Player; - if (block.dropFromExplosion(explosion)) { + if (state.canDropFromExplosion(level, pos, explosion)) { - BlockEntity blockentity = state.hasBlockEntity() ? level.getBlockEntity(pos) : null; - LootParams.Builder lootparams$builder = new LootParams.Builder(level) + BlockEntity blockEntity = state.hasBlockEntity() ? level.getBlockEntity(pos) : null; + LootParams.Builder params = new LootParams.Builder(level) .withParameter(LootContextParams.ORIGIN, Vec3.atCenterOf(pos)) -@@ -196,8 +_,7 @@ - state.getDrops(lootparams$builder).forEach(stack -> onHit.accept(stack, pos)); +@@ -195,8 +_,7 @@ + state.getDrops(params).forEach(stack -> onHit.accept(stack, pos)); } - level.setBlock(pos, Blocks.AIR.defaultBlockState(), 3); @@ -19,14 +19,14 @@ } } -@@ -358,12 +_,15 @@ - if (f == -1.0F) { +@@ -357,12 +_,15 @@ + if (destroySpeed == -1.0F) { return 0.0F; } else { -- int i = player.hasCorrectToolForDrops(state) ? 30 : 100; -- return player.getDestroySpeed(state) / f / i; -+ int i = net.minecraftforge.common.ForgeHooks.isCorrectToolForDrops(state, player) ? 30 : 100; -+ return player.getDestroySpeed(state, pos) / f / (float)i; +- int modifier = player.hasCorrectToolForDrops(state) ? 30 : 100; +- return player.getDestroySpeed(state) / destroySpeed / modifier; ++ int modifier = net.minecraftforge.common.ForgeHooks.isCorrectToolForDrops(state, player) ? 30 : 100; ++ return player.getDestroySpeed(state, pos) / destroySpeed / (float)modifier; } } @@ -37,7 +37,7 @@ } protected void attack(final BlockState state, final Level level, final BlockPos pos, final Player player) { -@@ -406,6 +_,8 @@ +@@ -405,6 +_,8 @@ return this.isRandomlyTicking; } @@ -46,7 +46,7 @@ protected SoundType getSoundType(final BlockState state) { return this.soundType; } -@@ -426,6 +_,10 @@ +@@ -425,6 +_,10 @@ return this.properties.destroyTime; } @@ -57,7 +57,7 @@ public abstract static class BlockStateBase extends StateHolder implements TypedInstance { private static final Direction[] DIRECTIONS = Direction.values(); private static final VoxelShape[] EMPTY_OCCLUSION_SHAPES = Util.make(new VoxelShape[DIRECTIONS.length], s -> Arrays.fill(s, Shapes.empty())); -@@ -577,12 +_,14 @@ +@@ -576,12 +_,14 @@ return this.useShapeForLightOcclusion; } @@ -73,7 +73,7 @@ } public boolean ignitedByLava() { -@@ -595,9 +_,11 @@ +@@ -594,9 +_,11 @@ } public MapColor getMapColor(final BlockGetter level, final BlockPos pos) { @@ -86,7 +86,7 @@ public BlockState rotate(final Rotation rotation) { return this.getBlock().rotate(this.asState(), rotation); } -@@ -651,6 +_,8 @@ +@@ -650,6 +_,8 @@ } public PushReaction getPistonPushReaction() { @@ -95,7 +95,7 @@ return this.pushReaction; } -@@ -1005,7 +_,7 @@ +@@ -1004,7 +_,7 @@ private BlockBehaviour.StateArgumentPredicate> isValidSpawn = (state, level, pos, entityType) -> state.isFaceSturdy( level, pos, Direction.UP ) diff --git a/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch index 9c38e0a8c9..474b928f65 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/ChunkAccess.java.patch @@ -13,23 +13,23 @@ + } + + public void findBlocks(final java.util.function.BiPredicate predicate, final BiConsumer consumer) { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + BlockPos.MutableBlockPos mutablePos = new BlockPos.MutableBlockPos(); - for (int i = this.getMinSectionY(); i <= this.getMaxSectionY(); i++) { - LevelChunkSection levelchunksection = this.getSection(this.getSectionIndexFromSectionY(i)); -- if (levelchunksection.maybeHas(predicate)) { -+ if (levelchunksection.maybeHas(state -> predicate.test(state, BlockPos.ZERO))) { - BlockPos blockpos = SectionPos.of(this.chunkPos, i).origin(); + for (int sectionY = this.getMinSectionY(); sectionY <= this.getMaxSectionY(); sectionY++) { + LevelChunkSection section = this.getSection(this.getSectionIndexFromSectionY(sectionY)); +- if (section.maybeHas(predicate)) { ++ if (section.maybeHas(state -> predicate.test(state, BlockPos.ZERO))) { + BlockPos origin = SectionPos.of(this.chunkPos, sectionY).origin(); - for (int j = 0; j < 16; j++) { - for (int k = 0; k < 16; k++) { - for (int l = 0; l < 16; l++) { - BlockState blockstate = levelchunksection.getBlockState(l, j, k); -- if (predicate.test(blockstate)) { -- consumer.accept(blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k), blockstate); -+ blockpos$mutableblockpos.setWithOffset(blockpos, l, j, k); -+ if (predicate.test(blockstate, blockpos$mutableblockpos.immutable())) { -+ consumer.accept(blockpos$mutableblockpos, blockstate); + for (int y = 0; y < 16; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + BlockState state = section.getBlockState(x, y, z); +- if (predicate.test(state)) { +- consumer.accept(mutablePos.setWithOffset(origin, x, y, z), state); ++ mutablePos.setWithOffset(origin, x, y, z); ++ if (predicate.test(state, mutablePos.immutable())) { ++ consumer.accept(mutablePos, state); } } } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch index a814638c00..5108f8e047 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/LevelChunk.java.patch @@ -17,39 +17,39 @@ } public LevelChunk(final ServerLevel level, final ProtoChunk protoChunk, final LevelChunk.@Nullable PostLoadProcessor postLoad) { -@@ -321,7 +_,7 @@ - if (!levelchunksection.getBlockState(j, k, l).is(block)) { +@@ -323,7 +_,7 @@ + if (!section.getBlockState(localX, localY, localZ).is(newBlock)) { return null; } else { - if (!this.level.isClientSide() && (flags & 512) == 0) { + if (!this.level.isClientSide() && (flags & 512) == 0 && !this.level.captureBlockSnapshots) { - state.onPlace(this.level, pos, blockstate, flag2); + state.onPlace(this.level, pos, oldState, movedByPiston); } -@@ -368,6 +_,12 @@ +@@ -370,6 +_,12 @@ public @Nullable BlockEntity getBlockEntity(final BlockPos pos, final LevelChunk.EntityCreationType creationType) { - BlockEntity blockentity = this.blockEntities.get(pos); + BlockEntity blockEntity = this.blockEntities.get(pos); + -+ if (blockentity != null && blockentity.isRemoved()) { ++ if (blockEntity != null && blockEntity.isRemoved()) { + blockEntities.remove(pos); -+ blockentity = null; ++ blockEntity = null; + } + - if (blockentity == null) { - CompoundTag compoundtag = this.pendingBlockEntities.remove(pos); - if (compoundtag != null) { -@@ -385,9 +_,6 @@ - this.addAndRegisterBlockEntity(blockentity); + if (blockEntity == null) { + CompoundTag tag = this.pendingBlockEntities.remove(pos); + if (tag != null) { +@@ -387,9 +_,6 @@ + this.addAndRegisterBlockEntity(blockEntity); } } -- } else if (blockentity.isRemoved()) { +- } else if (blockEntity.isRemoved()) { - this.blockEntities.remove(pos); - return null; } - return blockentity; -@@ -402,6 +_,7 @@ + return blockEntity; +@@ -404,6 +_,7 @@ this.level.onBlockEntityAdded(blockEntity); this.updateBlockEntityTicker(blockEntity); @@ -57,34 +57,31 @@ } } -@@ -453,9 +_,14 @@ +@@ -455,9 +_,14 @@ public @Nullable CompoundTag getBlockEntityNbtForSaving(final BlockPos blockPos, final HolderLookup.Provider registryAccess) { - BlockEntity blockentity = this.getBlockEntity(blockPos); - if (blockentity != null && !blockentity.isRemoved()) { + BlockEntity blockEntity = this.getBlockEntity(blockPos); + if (blockEntity != null && !blockEntity.isRemoved()) { + try { - CompoundTag compoundtag1 = blockentity.saveWithFullMetadata(this.level.registryAccess()); - compoundtag1.putBoolean("keepPacked", false); - return compoundtag1; + CompoundTag result = blockEntity.saveWithFullMetadata(this.level.registryAccess()); + result.putBoolean("keepPacked", false); + return result; + } catch (Exception e) { -+ LOGGER.error("A BlockEntity type {} has thrown an exception trying to write state. It will not persist, Report this to the mod author", blockentity.getClass().getName(), e); ++ LOGGER.error("A BlockEntity type {} has thrown an exception trying to write state. It will not persist, Report this to the mod author", blockEntity.getClass().getName(), e); + return null; + } } else { - CompoundTag compoundtag = this.pendingBlockEntities.get(blockPos); - if (compoundtag != null) { -@@ -537,9 +_,10 @@ - (pos, type, tag) -> { - BlockEntity blockentity = this.getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); - if (blockentity != null && tag != null && blockentity.getType() == type) { -- blockentity.loadWithComponents( -+ var input = ( - TagValueInput.create(problemreporter$scopedcollector.forChild(blockentity.problemPath()), this.level.registryAccess(), tag) - ); -+ blockentity.handleUpdateTag(input, this.level.registryAccess()); - } + CompoundTag result = this.pendingBlockEntities.get(blockPos); + if (result != null) { +@@ -538,7 +_,7 @@ + blockEntities.accept((pos, type, tag) -> { + BlockEntity blockEntity = this.getBlockEntity(pos, LevelChunk.EntityCreationType.IMMEDIATE); + if (blockEntity != null && tag != null && blockEntity.getType() == type) { +- blockEntity.loadWithComponents(TagValueInput.create(reporter.forChild(blockEntity.problemPath()), this.level.registryAccess(), tag)); ++ blockEntity.handleUpdateTag(TagValueInput.create(reporter.forChild(blockEntity.problemPath()), this.level.registryAccess(), tag), this.level.registryAccess()); } - ); -@@ -679,6 +_,7 @@ + }); + } +@@ -677,6 +_,7 @@ } public void clearAllBlockEntities() { @@ -92,15 +89,15 @@ this.blockEntities.values().forEach(BlockEntity::setRemoved); this.blockEntities.clear(); this.tickersInLevel.values().forEach(ticker -> ticker.rebind(NULL_TICKER)); -@@ -686,6 +_,7 @@ +@@ -684,6 +_,7 @@ } public void registerAllBlockEntitiesAfterLevelLoad() { + this.level.addFreshBlockEntities(this.blockEntities.values()); this.blockEntities.values().forEach(blockEntity -> { - if (this.level instanceof ServerLevel serverlevel) { - this.addGameEventListener(blockEntity, serverlevel); -@@ -738,6 +_,24 @@ + if (this.level instanceof ServerLevel serverLevel) { + this.addGameEventListener(blockEntity, serverLevel); +@@ -730,6 +_,24 @@ return new LevelChunk.BoundTickingBlockEntity<>(blockEntity, ticker); } @@ -125,27 +122,27 @@ private class BoundTickingBlockEntity implements TickingBlockEntity { private final T blockEntity; private final BlockEntityTicker ticker; -@@ -757,6 +_,7 @@ - if (LevelChunk.this.isTicking(blockpos)) { +@@ -749,6 +_,7 @@ + if (LevelChunk.this.isTicking(pos)) { try { - ProfilerFiller profilerfiller = Profiler.get(); + ProfilerFiller profiler = Profiler.get(); + net.minecraftforge.server.timings.TimeTracker.BLOCK_ENTITY_UPDATE.trackStart(blockEntity); - profilerfiller.push(this::getType); - BlockState blockstate = LevelChunk.this.getBlockState(blockpos); - if (this.blockEntity.getType().isValid(blockstate)) { -@@ -778,6 +_,11 @@ - CrashReport crashreport = CrashReport.forThrowable(throwable, "Ticking block entity"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Block entity being ticked"); - this.blockEntity.fillCrashReportCategory(crashreportcategory); + profiler.push(this::getType); + BlockState blockState = LevelChunk.this.getBlockState(pos); + if (this.blockEntity.getType().isValid(blockState)) { +@@ -770,6 +_,11 @@ + CrashReport report = CrashReport.forThrowable(var5, "Ticking block entity"); + CrashReportCategory category = report.addCategory("Block entity being ticked"); + this.blockEntity.fillCrashReportCategory(category); + if (net.minecraftforge.common.ForgeConfig.SERVER.removeErroringBlockEntities.get()) { -+ LOGGER.error("{}", crashreport.getFriendlyReport(net.minecraft.ReportType.CRASH)); ++ LOGGER.error("{}", report.getFriendlyReport(net.minecraft.ReportType.CRASH)); + blockEntity.setRemoved(); + LevelChunk.this.removeBlockEntity(blockEntity.getBlockPos()); + } else - throw new ReportedException(crashreport); + throw new ReportedException(report); } } -@@ -851,6 +_,33 @@ +@@ -843,6 +_,33 @@ public String toString() { return this.ticker + " "; } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch index 1bad85c6fd..71dc0443e4 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java.patch @@ -1,18 +1,18 @@ --- a/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java +++ b/net/minecraft/world/level/chunk/status/ChunkStatusTasks.java -@@ -215,9 +_,15 @@ - levelchunk.setFullStatus(generationchunkholder::getFullStatus); - levelchunk.runPostLoad(); - levelchunk.setLoaded(true); -+ try { -+ generationchunkholder.currentlyLoading = levelchunk; // Forge - bypass the future chain when getChunk is called, this prevents deadlocks. - levelchunk.registerAllBlockEntitiesAfterLevelLoad(); - levelchunk.registerTickContainerInLevel(serverlevel); - levelchunk.setUnsavedListener(context.unsavedListener()); -+ net.minecraftforge.event.ForgeEventFactory.onChunkLoad(levelchunk, !(protochunk instanceof ImposterProtoChunk)); -+ } finally { -+ generationchunkholder.currentlyLoading = null; // Forge - Stop bypassing the future chain. -+ } - return levelchunk; - }, - context.mainThreadExecutor() +@@ -201,9 +_,15 @@ + levelChunk.setFullStatus(holder::getFullStatus); + levelChunk.runPostLoad(); + levelChunk.setLoaded(true); ++ try { ++ holder.currentlyLoading = levelChunk; // Forge - bypass the future chain when getChunk is called, this prevents deadlocks. + levelChunk.registerAllBlockEntitiesAfterLevelLoad(); + levelChunk.registerTickContainerInLevel(level); + levelChunk.setUnsavedListener(context.unsavedListener()); ++ net.minecraftforge.event.ForgeEventFactory.onChunkLoad(levelChunk, !(protoChunk instanceof ImposterProtoChunk)); ++ } finally { ++ holder.currentlyLoading = null; // Forge - Stop bypassing the future chain. ++ } + return levelChunk; + }, context.mainThreadExecutor()); + } diff --git a/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch b/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch index 55f8e8d5f3..0bf07cc637 100644 --- a/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/chunk/storage/EntityStorage.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/level/chunk/storage/EntityStorage.java +++ b/net/minecraft/world/level/chunk/storage/EntityStorage.java -@@ -108,9 +_,13 @@ - TagValueOutput tagvalueoutput = TagValueOutput.createWithContext( - problemreporter$scopedcollector.forChild(e.problemPath()), e.registryAccess() - ); -+ try { - if (e.save(tagvalueoutput)) { - CompoundTag compoundtag1 = tagvalueoutput.buildResult(); - listtag.add(compoundtag1); -+ } -+ } catch (Exception exception) { -+ LOGGER.error("An Entity type {} has thrown an exception trying to write state. It will not persist. Report this to the mod author", e.getType(), exception); - } - } - ); +@@ -97,9 +_,13 @@ + ListTag entities = new ListTag(); + chunk.getEntities().forEach(e -> { + TagValueOutput output = TagValueOutput.createWithContext(reporter.forChild(e.problemPath()), e.registryAccess()); ++ try { + if (e.save(output)) { + CompoundTag result = output.buildResult(); + entities.add(result); ++ } ++ } catch (Exception exception) { ++ LOGGER.error("An Entity type {} has thrown an exception trying to write state. It will not persist. Report this to the mod author", e.getType(), exception); + } + }); + CompoundTag chunkTag = NbtUtils.addCurrentDataVersion(new CompoundTag()); diff --git a/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch b/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch index 12e2a5402f..820bdd085b 100644 --- a/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch +++ b/patches/minecraft/net/minecraft/world/level/dimension/end/EnderDragonFight.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/dimension/end/EnderDragonFight.java +++ b/net/minecraft/world/level/dimension/end/EnderDragonFight.java -@@ -586,6 +_,14 @@ +@@ -581,6 +_,14 @@ } } diff --git a/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch b/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch index f7431c229d..9ebf8fde53 100644 --- a/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/entity/PersistentEntitySectionManager.java.patch @@ -48,14 +48,14 @@ } @@ -395,9 +_,13 @@ PersistentEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); - EntitySection entitysection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(i); - entitysection.add(this.entity); + EntitySection newSection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(newSectionPos); + newSection.add(this.entity); + long oldSectionKey = currentSectionKey; - this.currentSection = entitysection; - this.currentSectionKey = i; - this.updateStatus(visibility, entitysection.getStatus()); + this.currentSection = newSection; + this.currentSectionKey = newSectionPos; + this.updateStatus(previousStatus, newSection.getStatus()); + if (this.realEntity != null) { -+ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, i); ++ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, newSectionPos); + } } } diff --git a/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch b/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch index 63426b7617..c163b96882 100644 --- a/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/entity/TransientEntitySectionManager.java.patch @@ -18,19 +18,19 @@ } @@ -108,6 +_,7 @@ TransientEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection); - EntitySection entitysection = TransientEntitySectionManager.this.sectionStorage.getOrCreateSection(i); - entitysection.add(this.entity); + EntitySection newSection = TransientEntitySectionManager.this.sectionStorage.getOrCreateSection(newSectionPos); + newSection.add(this.entity); + long oldSectionKey = currentSectionKey; - this.currentSection = entitysection; - this.currentSectionKey = i; + this.currentSection = newSection; + this.currentSectionKey = newSectionPos; TransientEntitySectionManager.this.callbacks.onSectionChange(this.entity); @@ -119,6 +_,9 @@ - } else if (!flag && flag1) { + } else if (!wasTicking && isTicking) { TransientEntitySectionManager.this.callbacks.onTickingStart(this.entity); } + } + if (this.realEntity != null) { -+ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, i); ++ net.minecraftforge.event.ForgeEventFactory.onEntityEnterSection(this.realEntity, oldSectionKey, newSectionPos); } } } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch index 81292972f6..4148998ca7 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/Beardifier.java.patch @@ -1,14 +1,14 @@ --- a/net/minecraft/world/level/levelgen/Beardifier.java +++ b/net/minecraft/world/level/levelgen/Beardifier.java -@@ -52,6 +_,11 @@ +@@ -51,6 +_,11 @@ - for (StructurePiece structurepiece : structurestart.getPieces()) { - if (structurepiece.isCloseToChunk(chunkPos, 12)) { -+ if (structurepiece instanceof net.minecraftforge.common.world.PieceBeardifierModifier pieceBeardifierModifier) { + for (StructurePiece piece : start.getPieces()) { + if (piece.isCloseToChunk(chunkPos, 12)) { ++ if (piece instanceof net.minecraftforge.common.world.PieceBeardifierModifier pieceBeardifierModifier) { + if (pieceBeardifierModifier.getTerrainAdjustment() != TerrainAdjustment.NONE) { -+ list1.add(new Beardifier.Rigid(pieceBeardifierModifier.getBeardifierBox(), pieceBeardifierModifier.getTerrainAdjustment(), pieceBeardifierModifier.getGroundLevelDelta())); ++ rigids.add(new Beardifier.Rigid(pieceBeardifierModifier.getBeardifierBox(), pieceBeardifierModifier.getTerrainAdjustment(), pieceBeardifierModifier.getGroundLevelDelta())); + } + } else - if (structurepiece instanceof PoolElementStructurePiece poolelementstructurepiece) { - StructureTemplatePool.Projection structuretemplatepool$projection = poolelementstructurepiece.getElement().getProjection(); - if (structuretemplatepool$projection == StructureTemplatePool.Projection.RIGID) { + if (piece instanceof PoolElementStructurePiece poolPiece) { + StructureTemplatePool.Projection projection = poolPiece.getElement().getProjection(); + if (projection == StructureTemplatePool.Projection.RIGID) { diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch index bdcd391b23..bf5d375d8f 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/DebugLevelSource.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/DebugLevelSource.java +++ b/net/minecraft/world/level/levelgen/DebugLevelSource.java -@@ -142,4 +_,10 @@ +@@ -140,4 +_,10 @@ public int getSeaLevel() { return 63; } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch index 61aa7eb110..5fe72aeda7 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/PhantomSpawner.java.patch @@ -1,32 +1,32 @@ --- a/net/minecraft/world/level/levelgen/PhantomSpawner.java +++ b/net/minecraft/world/level/levelgen/PhantomSpawner.java @@ -33,13 +_,18 @@ - for (ServerPlayer serverplayer : level.players()) { - if (!serverplayer.isSpectator()) { - BlockPos blockpos = serverplayer.blockPosition(); -- if (!level.dimensionType().hasSkyLight() || blockpos.getY() >= level.getSeaLevel() && level.canSeeSky(blockpos)) { - DifficultyInstance difficultyinstance = level.getCurrentDifficultyAt(blockpos); -+ var vanillaPosition = (!level.dimensionType().hasSkyLight() || blockpos.getY() >= level.getSeaLevel() && level.canSeeSky(blockpos)); -+ var count = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); -+ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnPhantom(serverplayer, count); + for (ServerPlayer player : level.players()) { + if (!player.isSpectator()) { + BlockPos playerPos = player.blockPosition(); +- if (!level.dimensionType().hasSkyLight() || playerPos.getY() >= level.getSeaLevel() && level.canSeeSky(playerPos)) { + DifficultyInstance difficulty = level.getCurrentDifficultyAt(playerPos); ++ var vanillaPosition = (!level.dimensionType().hasSkyLight() || playerPos.getY() >= level.getSeaLevel() && level.canSeeSky(playerPos)); ++ var count = 1 + random.nextInt(difficulty.getDifficulty().getId() + 1); ++ var event = net.minecraftforge.event.ForgeEventFactory.onPlayerSpawnPhantom(player, count); + var eventResult = event.getResult(); + if (eventResult.isDenied()) continue; + if (vanillaPosition || eventResult.isAllowed()) { - if (difficultyinstance.isHarderThan(randomsource.nextFloat() * 3.0F)) { - ServerStatsCounter serverstatscounter = serverplayer.getStats(); - int i = Mth.clamp(serverstatscounter.getValue(Stats.CUSTOM.get(Stats.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); - int j = 24000; -- if (randomsource.nextInt(i) >= 72000) { -+ if (eventResult.isAllowed() || randomsource.nextInt(i) >= 72000) { - BlockPos blockpos1 = blockpos.above(20 + randomsource.nextInt(15)) - .east(-10 + randomsource.nextInt(21)) - .south(-10 + randomsource.nextInt(21)); + if (difficulty.isHarderThan(random.nextFloat() * 3.0F)) { + ServerStatsCounter stats = player.getStats(); + int value = Mth.clamp(stats.getValue(Stats.CUSTOM.get(Stats.TIME_SINCE_REST)), 1, Integer.MAX_VALUE); + int dayLength = 24000; +- if (random.nextInt(value) >= 72000) { ++ if (eventResult.isAllowed() || random.nextInt(value) >= 72000) { + BlockPos spawnPos = playerPos.above(20 + random.nextInt(15)) + .east(-10 + random.nextInt(21)) + .south(-10 + random.nextInt(21)); @@ -47,7 +_,7 @@ - FluidState fluidstate = level.getFluidState(blockpos1); - if (NaturalSpawner.isValidEmptySpawnBlock(level, blockpos1, blockstate, fluidstate, EntityType.PHANTOM)) { - SpawnGroupData spawngroupdata = null; -- int k = 1 + randomsource.nextInt(difficultyinstance.getDifficulty().getId() + 1); -+ int k = event.getPhantomsToSpawn(); + FluidState fluidState = level.getFluidState(spawnPos); + if (NaturalSpawner.isValidEmptySpawnBlock(level, spawnPos, blockState, fluidState, EntityType.PHANTOM)) { + SpawnGroupData groupData = null; +- int groupSize = 1 + random.nextInt(difficulty.getDifficulty().getId() + 1); ++ int groupSize = event.getPhantomsToSpawn(); - for (int l = 0; l < k; l++) { + for (int i = 0; i < groupSize; i++) { Phantom phantom = EntityType.PHANTOM.create(level, EntitySpawnReason.NATURAL); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch index 01c1b2026a..be4ef92502 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/WorldDimensions.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/WorldDimensions.java +++ b/net/minecraft/world/level/levelgen/WorldDimensions.java -@@ -37,7 +_,7 @@ +@@ -36,7 +_,7 @@ public record WorldDimensions(Map, LevelStem> dimensions) { public static final MapCodec CODEC = RecordCodecBuilder.mapCodec( diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch index 0663badd03..bfc7c3ee04 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java +++ b/net/minecraft/world/level/levelgen/feature/MonsterRoomFeature.java -@@ -131,6 +_,6 @@ +@@ -128,6 +_,6 @@ } private EntityType randomEntityId(final RandomSource random) { diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch index 6355a3511c..eee77ce551 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java.patch @@ -1,10 +1,10 @@ --- a/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java +++ b/net/minecraft/world/level/levelgen/feature/treedecorators/AlterGroundDecorator.java @@ -58,6 +_,7 @@ - BlockPos blockpos = pos.above(i); - BlockState blockstate = this.provider.getOptionalState(context.level(), context.random(), blockpos); - if (blockstate != null) { -+ blockstate = net.minecraftforge.event.ForgeEventFactory.alterGround(context.level(), context.random(), blockpos, blockstate); - context.setBlock(blockpos, blockstate); + BlockPos cursor = pos.above(dy); + BlockState replaceWith = this.provider.getOptionalState(context.level(), context.random(), cursor); + if (replaceWith != null) { ++ replaceWith = net.minecraftforge.event.ForgeEventFactory.alterGround(context.level(), context.random(), cursor, replaceWith); + context.setBlock(cursor, replaceWith); break; } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch index 84ed98f18f..36b7e245d8 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java.patch @@ -2,10 +2,10 @@ +++ b/net/minecraft/world/level/levelgen/feature/trunkplacers/TrunkPlacer.java @@ -68,6 +_,8 @@ ) { - BlockState blockstate = config.belowTrunkProvider.getOptionalState(level, random, pos); - if (blockstate != null) { + BlockState blockBelowTrunk = config.belowTrunkProvider.getOptionalState(level, random, pos); + if (blockBelowTrunk != null) { + var levelReader = (net.minecraft.world.level.LevelReader)level; + if (!levelReader.getBlockState(pos).onTreeGrow(levelReader, trunkSetter, random, pos, config)) - trunkSetter.accept(pos, blockstate); + trunkSetter.accept(pos, blockBelowTrunk); } } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch index 408f6294c8..8bf474c925 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructurePiece.java.patch @@ -7,6 +7,6 @@ + if (BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()) == null) { // FORGE: Friendlier error then the Null String error below. + throw new RuntimeException("StructurePiece \"" + this.getClass().getName() + "\": \"" + this.getType() + "\" unregistered, serializing impossible."); + } - CompoundTag compoundtag = new CompoundTag(); - compoundtag.putString("id", BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()).toString()); - compoundtag.store("BB", BoundingBox.CODEC, this.boundingBox); + CompoundTag tag = new CompoundTag(); + tag.putString("id", BuiltInRegistries.STRUCTURE_PIECE.getKey(this.getType()).toString()); + tag.store("BB", BoundingBox.CODEC, this.boundingBox); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch index ce30309de7..4122d3467d 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/StructureStart.java.patch @@ -2,11 +2,11 @@ +++ b/net/minecraft/world/level/levelgen/structure/StructureStart.java @@ -103,6 +_,9 @@ public CompoundTag createTag(final StructurePieceSerializationContext context, final ChunkPos chunkPos) { - CompoundTag compoundtag = new CompoundTag(); + CompoundTag tag = new CompoundTag(); if (this.isValid()) { + if (context.registryAccess().lookupOrThrow(Registries.STRUCTURE).getKey(this.getStructure()) == null) { // FORGE: This is just a more friendly error instead of the 'Null String' below + throw new RuntimeException("StructureStart \"" + this.getClass().getName() + "\": \"" + this.getStructure() + "\" unregistered, serializing impossible."); + } - compoundtag.putString("id", context.registryAccess().lookupOrThrow(Registries.STRUCTURE).getKey(this.structure).toString()); - compoundtag.putInt("ChunkX", chunkPos.x()); - compoundtag.putInt("ChunkZ", chunkPos.z()); + tag.putString("id", context.registryAccess().lookupOrThrow(Registries.STRUCTURE).getKey(this.structure).toString()); + tag.putInt("ChunkX", chunkPos.x()); + tag.putInt("ChunkZ", chunkPos.z()); diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch index 8bf52c77d6..09b212a493 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java +++ b/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplate.java -@@ -256,6 +_,10 @@ +@@ -250,6 +_,10 @@ return transform(pos, settings.getMirror(), settings.getRotation(), settings.getRotationPivot()); } @@ -11,30 +11,30 @@ public boolean placeInWorld( final ServerLevelAccessor level, final BlockPos position, -@@ -282,7 +_,7 @@ - int l = Integer.MIN_VALUE; - int i1 = Integer.MIN_VALUE; - int j1 = Integer.MIN_VALUE; -- List list4 = processBlockInfos(level, position, referencePos, settings, list); -+ List list4 = processBlockInfos(level, position, referencePos, settings, list, this); +@@ -276,7 +_,7 @@ + int maxX = Integer.MIN_VALUE; + int maxY = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; +- List processedBlockInfoList = processBlockInfos(level, position, referencePos, settings, blockInfoList); ++ List processedBlockInfoList = processBlockInfos(level, position, referencePos, settings, blockInfoList, this); - try (ProblemReporter.ScopedCollector problemreporter$scopedcollector = new ProblemReporter.ScopedCollector(LOGGER)) { - for (StructureTemplate.StructureBlockInfo structuretemplate$structureblockinfo : list4) { -@@ -406,10 +_,10 @@ + try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(LOGGER)) { + for (StructureTemplate.StructureBlockInfo blockInfo : processedBlockInfoList) { +@@ -396,10 +_,10 @@ position, settings.getMirror(), settings.getRotation(), - settings.getRotationPivot(), - boundingbox, + boundingBox, settings.shouldFinalizeEntities(), -- problemreporter$scopedcollector -+ problemreporter$scopedcollector, +- reporter ++ reporter, + settings ); } } -@@ -458,12 +_,21 @@ - ); +@@ -442,12 +_,21 @@ + }); } + /** @@ -54,18 +54,18 @@ + List blockInfoList, + @Nullable StructureTemplate template ) { - List list = new ArrayList<>(); - List list1 = new ArrayList<>(); -@@ -479,7 +_,7 @@ + List originalBlockInfoList = new ArrayList<>(); + List processedBlockInfoList = new ArrayList<>(); +@@ -460,7 +_,7 @@ + Iterator iterator = settings.getProcessors().iterator(); - while (structuretemplate$structureblockinfo1 != null && iterator.hasNext()) { - structuretemplate$structureblockinfo1 = iterator.next() -- .processBlock(level, position, referencePos, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, settings); -+ .processBlock(level, position, referencePos, structuretemplate$structureblockinfo, structuretemplate$structureblockinfo1, settings, template); + while (processedBlockInfo != null && iterator.hasNext()) { +- processedBlockInfo = iterator.next().processBlock(level, position, referencePos, blockInfo, processedBlockInfo, settings); ++ processedBlockInfo = iterator.next().processBlock(level, position, referencePos, blockInfo, processedBlockInfo, settings, template); } - if (structuretemplate$structureblockinfo1 != null) { -@@ -500,17 +_,17 @@ + if (processedBlockInfo != null) { +@@ -481,17 +_,17 @@ final BlockPos position, final Mirror mirror, final Rotation rotation, @@ -76,20 +76,20 @@ + final ProblemReporter problemReporter, + final StructurePlaceSettings placementIn ) { -- for (StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : this.entityInfoList) { -- BlockPos blockpos = transform(structuretemplate$structureentityinfo.blockPos, mirror, rotation, pivot).offset(position); +- for (StructureTemplate.StructureEntityInfo entityInfo : this.entityInfoList) { +- BlockPos blockPos = transform(entityInfo.blockPos, mirror, rotation, pivot).offset(position); + var entities = processEntityInfos(this, level, position, placementIn, this.entityInfoList); -+ for (StructureTemplate.StructureEntityInfo structuretemplate$structureentityinfo : entities) { -+ BlockPos blockpos = structuretemplate$structureentityinfo.blockPos; // FORGE: Position will have already been transformed by processEntityInfos - if (boundingBox == null || boundingBox.isInside(blockpos)) { - CompoundTag compoundtag = structuretemplate$structureentityinfo.nbt.copy(); -- Vec3 vec3 = transform(structuretemplate$structureentityinfo.pos, mirror, rotation, pivot); -- Vec3 vec31 = vec3.add(position.getX(), position.getY(), position.getZ()); -+ Vec3 vec31 = structuretemplate$structureentityinfo.pos; // FORGE: Position will have already been transformed by processEntityInfos - ListTag listtag = new ListTag(); - listtag.add(DoubleTag.valueOf(vec31.x)); - listtag.add(DoubleTag.valueOf(vec31.y)); -@@ -532,6 +_,30 @@ ++ for (StructureTemplate.StructureEntityInfo entityInfo : entities) { ++ BlockPos blockPos = entityInfo.blockPos; // FORGE: Position will have already been transformed by processEntityInfos + if (boundingBox == null || boundingBox.isInside(blockPos)) { + CompoundTag tag = entityInfo.nbt.copy(); +- Vec3 relativePos = transform(entityInfo.pos, mirror, rotation, pivot); +- Vec3 pos = relativePos.add(position.getX(), position.getY(), position.getZ()); ++ Vec3 pos = entityInfo.pos; // FORGE: Position will have already been transformed by processEntityInfos + ListTag posTag = new ListTag(); + posTag.add(DoubleTag.valueOf(pos.x)); + posTag.add(DoubleTag.valueOf(pos.y)); +@@ -513,6 +_,30 @@ } } } diff --git a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch index d080f2ddf0..fbc7da494b 100644 --- a/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch +++ b/patches/minecraft/net/minecraft/world/level/levelgen/structure/templatesystem/StructureTemplateManager.java.patch @@ -3,8 +3,8 @@ @@ -77,6 +_,7 @@ } - builder.add(this.resourceManagerSource); -+ builder.add(net.minecraftforge.common.ForgeHooks.emptyStructureSource()); - this.sources = builder.build(); + sources.add(this.resourceManagerSource); ++ sources.add(net.minecraftforge.common.ForgeHooks.emptyStructureSource()); + this.sources = sources.build(); } diff --git a/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch b/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch index 157ec10d2b..d84e29b260 100644 --- a/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch +++ b/patches/minecraft/net/minecraft/world/level/lighting/BlockLightEngine.java.patch @@ -1,20 +1,20 @@ --- a/net/minecraft/world/level/lighting/BlockLightEngine.java +++ b/net/minecraft/world/level/lighting/BlockLightEngine.java -@@ -109,7 +_,7 @@ +@@ -110,7 +_,7 @@ } private int getEmission(final long blockNode, final BlockState state) { -- int i = state.getLightEmission(); -+ int i = state.getLightEmission(chunkSource.getLevel(), mutablePos); - return i > 0 && this.storage.lightOnInSection(SectionPos.blockToSection(blockNode)) ? i : 0; +- int emission = state.getLightEmission(); ++ int emission = state.getLightEmission(chunkSource.getLevel(), mutablePos); + return emission > 0 && this.storage.lightOnInSection(SectionPos.blockToSection(blockNode)) ? emission : 0; } -@@ -119,7 +_,7 @@ - LightChunk lightchunk = this.chunkSource.getChunkForLighting(pos.x(), pos.z()); - if (lightchunk != null) { - lightchunk.findBlockLightSources((lightPos, state) -> { -- int i = state.getLightEmission(); -+ int i = state.getLightEmission(chunkSource.getLevel(), lightPos); - this.enqueueIncrease(lightPos.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(i, isEmptyShape(state))); +@@ -120,7 +_,7 @@ + LightChunk chunk = this.chunkSource.getChunkForLighting(pos.x(), pos.z()); + if (chunk != null) { + chunk.findBlockLightSources((lightPos, state) -> { +- int lightEmission = state.getLightEmission(); ++ int lightEmission = state.getLightEmission(chunkSource.getLevel(), lightPos); + this.enqueueIncrease(lightPos.asLong(), LightEngine.QueueEntry.increaseLightFromEmission(lightEmission, isEmptyShape(state))); }); } diff --git a/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch b/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch index b95cbf6518..1e94362bac 100644 --- a/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/FlowingFluid.java.patch @@ -1,24 +1,24 @@ --- a/net/minecraft/world/level/material/FlowingFluid.java +++ b/net/minecraft/world/level/material/FlowingFluid.java -@@ -172,7 +_,7 @@ - BlockState blockstate = level.getBlockState(blockpos); - FluidState fluidstate = blockstate.getFluidState(); - if (fluidstate.getType().isSame(this) && canPassThroughWall(direction, level, pos, state, blockpos, blockstate)) { -- if (fluidstate.isSource()) { -+ if (fluidstate.isSource() && net.minecraftforge.event.ForgeEventFactory.canCreateFluidSource(level, blockpos, blockstate, fluidstate.canConvertToSource(level, blockpos))) { - j++; +@@ -169,7 +_,7 @@ + BlockState blockState = level.getBlockState(relativePos); + FluidState fluidState = blockState.getFluidState(); + if (fluidState.getType().isSame(this) && canPassThroughWall(direction, level, pos, state, relativePos, blockState)) { +- if (fluidState.isSource()) { ++ if (fluidState.isSource() && net.minecraftforge.event.ForgeEventFactory.canCreateFluidSource(level, relativePos, blockState, fluidState.canConvertToSource(level, relativePos))) { + neighbourSources++; } -@@ -180,7 +_,7 @@ +@@ -177,7 +_,7 @@ } } -- if (j >= 2 && this.canConvertToSource(level)) { -+ if (j >= 2) { - BlockState blockstate1 = level.getBlockState(blockpos$mutableblockpos.setWithOffset(pos, Direction.DOWN)); - FluidState fluidstate1 = blockstate1.getFluidState(); - if (blockstate1.isSolid() || this.isSourceBlockOfThisType(fluidstate1)) { -@@ -265,6 +_,15 @@ +- if (neighbourSources >= 2 && this.canConvertToSource(level)) { ++ if (neighbourSources >= 2) { + BlockState belowState = level.getBlockState(mutablePos.setWithOffset(pos, Direction.DOWN)); + FluidState belowFluid = belowState.getFluidState(); + if (belowState.isSolid() || this.isSourceBlockOfThisType(belowFluid)) { +@@ -262,6 +_,15 @@ return this.getSource().defaultFluidState().setValue(FALLING, falling); } diff --git a/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch b/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch index bb5082301f..63a2dcba5e 100644 --- a/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch +++ b/patches/minecraft/net/minecraft/world/level/material/LavaFluid.java.patch @@ -1,22 +1,22 @@ --- a/net/minecraft/world/level/material/LavaFluid.java +++ b/net/minecraft/world/level/material/LavaFluid.java @@ -93,7 +_,7 @@ - BlockState blockstate = level.getBlockState(blockpos); - if (blockstate.isAir()) { - if (this.hasFlammableNeighbours(level, blockpos)) { -- level.setBlockAndUpdate(blockpos, BaseFireBlock.getState(level, blockpos)); -+ level.setBlockAndUpdate(blockpos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, blockpos, pos, Blocks.FIRE.defaultBlockState())); + BlockState blockState = level.getBlockState(testPos); + if (blockState.isAir()) { + if (this.hasFlammableNeighbours(level, testPos)) { +- level.setBlockAndUpdate(testPos, BaseFireBlock.getState(level, testPos)); ++ level.setBlockAndUpdate(testPos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, testPos, pos, Blocks.FIRE.defaultBlockState())); return; } - } else if (blockstate.blocksMotion()) { + } else if (blockState.blocksMotion()) { @@ -107,8 +_,8 @@ return; } -- if (level.isEmptyBlock(blockpos1.above()) && this.isFlammable(level, blockpos1)) { -- level.setBlockAndUpdate(blockpos1.above(), BaseFireBlock.getState(level, blockpos1)); -+ if (level.isEmptyBlock(blockpos1.above()) && this.isFlammable(level, blockpos1, Direction.UP)) { -+ level.setBlockAndUpdate(blockpos1.above(), net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, blockpos1.above(), pos, Blocks.FIRE.defaultBlockState())); +- if (level.isEmptyBlock(testPos.above()) && this.isFlammable(level, testPos)) { +- level.setBlockAndUpdate(testPos.above(), BaseFireBlock.getState(level, testPos)); ++ if (level.isEmptyBlock(testPos.above()) && this.isFlammable(level, testPos, Direction.UP)) { ++ level.setBlockAndUpdate(testPos.above(), net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, testPos.above(), pos, Blocks.FIRE.defaultBlockState())); } } } @@ -47,13 +47,12 @@ @Override public @Nullable ParticleOptions getDripParticle() { return ParticleTypes.DRIPPING_LAVA; -@@ -206,7 +_,8 @@ - FluidState fluidstate = level.getFluidState(pos); - if (this.is(FluidTags.LAVA) && fluidstate.is(FluidTags.WATER)) { +@@ -206,7 +_,7 @@ + FluidState fluidState = level.getFluidState(pos); + if (this.is(FluidTags.LAVA) && fluidState.is(FluidTags.WATER)) { if (state.getBlock() instanceof LiquidBlock) { - level.setBlock(pos, Blocks.STONE.defaultBlockState(), 3); + level.setBlock(pos, net.minecraftforge.event.ForgeEventFactory.fireFluidPlaceBlockEvent(level, pos, pos, Blocks.STONE.defaultBlockState()), 3); -+ } this.fizz(level, pos); diff --git a/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch b/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch index 9e983b6a82..78aa176a4f 100644 --- a/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch +++ b/patches/minecraft/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java.patch @@ -1,11 +1,11 @@ --- a/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java +++ b/net/minecraft/world/level/pathfinder/WalkNodeEvaluator.java @@ -484,6 +_,16 @@ - for (int k = -1; k <= 1; k++) { - if (i != 0 || k != 0) { - PathType pathtype = context.getPathTypeFromState(x + i, y + j, z + k); + for (int dz = -1; dz <= 1; dz++) { + if (dx != 0 || dz != 0) { + PathType pathType = context.getPathTypeFromState(x + dx, y + dy, z + dz); + -+ var pos = new BlockPos(x + i, y + j, z + k); ++ var pos = new BlockPos(x + dx, y + dy, z + dz); + var blockstate = context.level().getBlockState(pos); + + var adjacentBlockPathType = blockstate.getAdjacentBlockPathType(context.level(), pos, null, blockPathType); @@ -14,35 +14,35 @@ + var adjacentFluidPathType = blockstate.getFluidState().getAdjacentBlockPathType(context.level(), pos, null, blockPathType); + if (adjacentFluidPathType != null) return adjacentFluidPathType; + - if (pathtype == PathType.DAMAGING) { + if (pathType == PathType.DAMAGING) { return PathType.DAMAGING_IN_NEIGHBOR; } @@ -510,6 +_,10 @@ protected static PathType getPathTypeFromState(final BlockGetter level, final BlockPos pos) { - BlockState blockstate = level.getBlockState(pos); - Block block = blockstate.getBlock(); + BlockState blockState = level.getBlockState(pos); + Block block = blockState.getBlock(); + -+ var type = blockstate.getBlockPathType(level, pos, null); ++ var type = blockState.getBlockPathType(level, pos, null); + if (type != null) return type; + - if (blockstate.isAir()) { + if (blockState.isAir()) { return PathType.OPEN; - } else if (blockstate.is(BlockTags.TRAPDOORS) || blockstate.is(Blocks.LILY_PAD) || blockstate.is(Blocks.BIG_DRIPLEAF)) { + } else if (blockState.is(BlockTags.TRAPDOORS) || blockState.is(Blocks.LILY_PAD) || blockState.is(Blocks.BIG_DRIPLEAF)) { @@ -524,6 +_,8 @@ return PathType.COCOA; - } else if (!blockstate.is(Blocks.WITHER_ROSE) && !blockstate.is(Blocks.POINTED_DRIPSTONE)) { - FluidState fluidstate = blockstate.getFluidState(); -+ var nonLoggableFluidPathType = fluidstate.getBlockPathType(level, pos, null, false); + } else if (!blockState.is(Blocks.WITHER_ROSE) && !blockState.is(Blocks.POINTED_DRIPSTONE)) { + FluidState fluidState = blockState.getFluidState(); ++ var nonLoggableFluidPathType = fluidState.getBlockPathType(level, pos, null, false); + if (nonLoggableFluidPathType != null) return nonLoggableFluidPathType; - if (fluidstate.is(FluidTags.LAVA)) { + if (fluidState.is(FluidTags.LAVA)) { return PathType.LAVA; - } else if (isBurningBlock(blockstate)) { + } else if (isBurningBlock(blockState)) { @@ -544,6 +_,8 @@ - if (!blockstate.isPathfindable(PathComputationType.LAND)) { + if (!blockState.isPathfindable(PathComputationType.LAND)) { return PathType.BLOCKED; } else { -+ var loggableFluidPathType = fluidstate.getBlockPathType(level, pos, null, true); ++ var loggableFluidPathType = fluidState.getBlockPathType(level, pos, null, true); + if (loggableFluidPathType != null) return loggableFluidPathType; - return fluidstate.is(FluidTags.WATER) ? PathType.WATER : PathType.OPEN; + return fluidState.is(FluidTags.WATER) ? PathType.WATER : PathType.OPEN; } } else { diff --git a/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch b/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch index a9aadca86b..62ceed9b2e 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/LevelStorageSource.java.patch @@ -1,7 +1,7 @@ --- a/net/minecraft/world/level/storage/LevelStorageSource.java +++ b/net/minecraft/world/level/storage/LevelStorageSource.java -@@ -571,6 +_,11 @@ - return dynamic; +@@ -572,6 +_,11 @@ + return unfixedDataTag; } + public CompoundTag getDataTagRaw(final boolean useFallback) throws IOException { @@ -11,16 +11,16 @@ + public Dynamic getUnfixedDataTag(final boolean useFallback) throws IOException { this.checkLock(); - Path path = this.getDataFile(useFallback); -@@ -590,6 +_,7 @@ - CompoundTag compoundtag = levelData.createTag(singleplayerUUID); - CompoundTag compoundtag1 = new CompoundTag(); - compoundtag1.put("Data", compoundtag); -+ net.minecraftforge.common.ForgeHooks.writeAdditionalLevelSaveData(levelData, compoundtag1); - this.saveLevelData(compoundtag1); + Path dataFile = this.getDataFile(useFallback); +@@ -591,6 +_,7 @@ + CompoundTag dataTag = levelData.createTag(singleplayerUUID); + CompoundTag root = new CompoundTag(); + root.put("Data", dataTag); ++ net.minecraftforge.common.ForgeHooks.writeAdditionalLevelSaveData(levelData, root); + this.saveLevelData(root); } -@@ -616,6 +_,10 @@ +@@ -617,6 +_,10 @@ public Optional getIconFile() { return !this.lock.isValid() ? Optional.empty() : Optional.of(this.levelDirectory.iconFile()); diff --git a/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch b/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch index c636bf9385..981ea03650 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/LevelSummary.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/storage/LevelSummary.java +++ b/net/minecraft/world/level/storage/LevelSummary.java -@@ -15,7 +_,7 @@ +@@ -14,7 +_,7 @@ import org.apache.commons.lang3.StringUtils; import org.jspecify.annotations.Nullable; diff --git a/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch b/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch index c8b6ac29ae..d95e213bb1 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/PlayerDataStorage.java.patch @@ -1,16 +1,16 @@ --- a/net/minecraft/world/level/storage/PlayerDataStorage.java +++ b/net/minecraft/world/level/storage/PlayerDataStorage.java @@ -41,6 +_,7 @@ - Path path2 = path.resolve(player.getStringUUID() + ".dat"); - Path path3 = path.resolve(player.getStringUUID() + ".dat_old"); - Util.safeReplaceFile(path2, path1, path3); + Path realFile = playerDirPath.resolve(player.getStringUUID() + ".dat"); + Path oldFile = playerDirPath.resolve(player.getStringUUID() + ".dat_old"); + Util.safeReplaceFile(realFile, tmpFile, oldFile); + net.minecraftforge.event.ForgeEventFactory.firePlayerSavingEvent(player, playerDir, player.getStringUUID()); - } catch (Exception exception) { + } catch (Exception var11) { LOGGER.warn("Failed to save player data for {}", player.getPlainTextName()); } @@ -83,5 +_,9 @@ - int i = NbtUtils.getDataVersion(tag); - return DataFixTypes.PLAYER.updateToCurrentVersion(this.fixerUpper, tag, i); + int version = NbtUtils.getDataVersion(tag); + return DataFixTypes.PLAYER.updateToCurrentVersion(this.fixerUpper, tag, version); }); + } + diff --git a/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch b/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch index 809dbcc9dd..0b997fda25 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/SavedDataStorage.java.patch @@ -3,11 +3,11 @@ @@ -122,6 +_,10 @@ } - int i = NbtUtils.getDataVersion(compoundtag, 1343); + int version = NbtUtils.getDataVersion(tag, 1343); + // Forge: Allow the data fixer to be null, leaving the modder responsible for keeping track of their own data formats + if (type == null) -+ compoundtag1 = compoundtag; ++ var8 = tag; + else - compoundtag1 = type.update(this.fixerUpper, compoundtag, i, newVersion); + var8 = type.update(this.fixerUpper, tag, version, newVersion); } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch index d64b673fbb..c5c35e3750 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootContext.java.patch @@ -79,12 +79,12 @@ public ServerLevel getLevel() { return this.params.getLevel(); } -@@ -141,7 +_,7 @@ - RandomSource randomsource = Optional.ofNullable(this.random) - .or(() -> randomSequenceKey.map(minecraftserver::getRandomSequence)) - .orElseGet(serverlevel::getRandom); -- return new LootContext(this.params, randomsource, minecraftserver.reloadableRegistries().lookup()); -+ return new LootContext(this.params, randomsource, minecraftserver.reloadableRegistries().lookup(), queriedLootTableId); +@@ -139,7 +_,7 @@ + ServerLevel level = this.getLevel(); + MinecraftServer server = level.getServer(); + RandomSource random = Optional.ofNullable(this.random).or(() -> randomSequenceKey.map(server::getRandomSequence)).orElseGet(level::getRandom); +- return new LootContext(this.params, random, server.reloadableRegistries().lookup()); ++ return new LootContext(this.params, random, server.reloadableRegistries().lookup(), queriedLootTableId); } } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch index 71222d49dc..0a2c7fd3e0 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootParams.java.patch @@ -18,8 +18,8 @@ } @@ -92,6 +_,10 @@ public LootParams create(final ContextKeySet contextKeySet) { - ContextMap contextmap = this.params.create(contextKeySet); - return new LootParams(this.level, contextmap, this.dynamicDrops, this.luck); + ContextMap keySet = this.params.create(contextKeySet); + return new LootParams(this.level, keySet, this.dynamicDrops, this.luck); + } + + public LootParams create() { diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch index a1116b8098..9495a14e85 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootPool.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/storage/loot/LootPool.java +++ b/net/minecraft/world/level/storage/loot/LootPool.java -@@ -33,10 +_,13 @@ +@@ -32,10 +_,13 @@ LootItemCondition.DIRECT_CODEC.listOf().optionalFieldOf("conditions", List.of()).forGetter(p -> p.conditions), LootItemFunctions.ROOT_CODEC.listOf().optionalFieldOf("functions", List.of()).forGetter(p -> p.functions), NumberProviders.CODEC.fieldOf("rolls").forGetter(p -> p.rolls), @@ -15,7 +15,7 @@ private final List entries; private final List conditions; private final Predicate compositeCondition; -@@ -44,6 +_,8 @@ +@@ -43,6 +_,8 @@ private final BiFunction compositeFunction; private NumberProvider rolls; private NumberProvider bonusRolls; @@ -24,7 +24,7 @@ private LootPool( final List entries, -@@ -52,6 +_,18 @@ +@@ -51,6 +_,18 @@ final NumberProvider rolls, final NumberProvider bonusRolls ) { @@ -43,7 +43,7 @@ this.entries = entries; this.conditions = conditions; this.compositeCondition = Util.allOf(conditions); -@@ -59,6 +_,8 @@ +@@ -58,6 +_,8 @@ this.compositeFunction = LootItemFunctions.compose(functions); this.rolls = rolls; this.bonusRolls = bonusRolls; @@ -52,7 +52,7 @@ } private void addRandomItem(final Consumer result, final LootContext context) { -@@ -118,12 +_,35 @@ +@@ -117,12 +_,35 @@ return new LootPool.Builder(); } @@ -88,7 +88,7 @@ public LootPool.Builder setRolls(final NumberProvider rolls) { this.rolls = rolls; -@@ -154,8 +_,18 @@ +@@ -153,8 +_,18 @@ return this; } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch index 3a4b7e54c1..7f9008ce24 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/LootTable.java.patch @@ -1,6 +1,6 @@ --- a/net/minecraft/world/level/storage/loot/LootTable.java +++ b/net/minecraft/world/level/storage/loot/LootTable.java -@@ -40,7 +_,7 @@ +@@ -39,7 +_,7 @@ i -> i.group( LootContextParamSets.CODEC.lenientOptionalFieldOf("type", DEFAULT_PARAM_SET).forGetter(t -> t.paramSet), Identifier.CODEC.optionalFieldOf("random_sequence").forGetter(t -> t.randomSequence), @@ -9,7 +9,7 @@ LootItemFunctions.ROOT_CODEC.listOf().optionalFieldOf("functions", List.of()).forGetter(t -> t.functions) ) .apply(i, LootTable::new) -@@ -59,7 +_,7 @@ +@@ -58,7 +_,7 @@ ) { this.paramSet = paramSet; this.randomSequence = randomSequence; @@ -18,7 +18,7 @@ this.functions = functions; this.compositeFunction = LootItemFunctions.compose(functions); } -@@ -82,10 +_,12 @@ +@@ -81,10 +_,12 @@ }; } @@ -29,9 +29,9 @@ + @Deprecated // Use a non-'Raw' version of 'getRandomItems', so that the Forge Global Loot Modifiers will be applied public void getRandomItemsRaw(final LootContext context, final Consumer output) { - LootContext.VisitedEntry visitedentry = LootContext.createVisitedEntry(this); - if (context.pushVisitedElement(visitedentry)) { -@@ -102,18 +_,19 @@ + LootContext.VisitedEntry breadcrumb = LootContext.createVisitedEntry(this); + if (context.pushVisitedElement(breadcrumb)) { +@@ -101,18 +_,19 @@ } public void getRandomItems(final LootParams params, final long optionalLootTableSeed, final Consumer output) { @@ -55,17 +55,17 @@ } public ObjectArrayList getRandomItems(final LootParams params, final RandomSource randomSource) { -@@ -130,7 +_,8 @@ +@@ -129,7 +_,8 @@ private ObjectArrayList getRandomItems(final LootContext context) { - ObjectArrayList objectarraylist = new ObjectArrayList<>(); -- this.getRandomItems(context, objectarraylist::add); -+ this.getRandomItemsRaw(context, createStackSplitter(context.getLevel(), objectarraylist::add)); -+ objectarraylist = net.minecraftforge.common.ForgeHooks.modifyLoot(this, objectarraylist, context); - return objectarraylist; + ObjectArrayList result = new ObjectArrayList<>(); +- this.getRandomItems(context, result::add); ++ this.getRandomItemsRaw(context, createStackSplitter(context.getLevel(), result::add)); ++ result = net.minecraftforge.common.ForgeHooks.modifyLoot(this, result, context); + return result; } -@@ -215,6 +_,68 @@ +@@ -214,6 +_,68 @@ public static LootTable.Builder lootTable() { return new LootTable.Builder(); diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch index 754a85516f..86b37b2817 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java.patch @@ -1,21 +1,21 @@ --- a/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java +++ b/net/minecraft/world/level/storage/loot/functions/EnchantedCountIncreaseFunction.java -@@ -73,8 +_,12 @@ +@@ -72,8 +_,12 @@ @Override public ItemStack run(final ItemStack itemStack, final LootContext context) { - Entity entity = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); -- if (entity instanceof LivingEntity livingentity) { -- int i = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); -+ int i = 0; + Entity killer = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); +- if (killer instanceof LivingEntity entity) { +- int level = EnchantmentHelper.getEnchantmentLevel(this.enchantment, entity); ++ int level = 0; + if (this.enchantment.is(Enchantments.LOOTING)) -+ i = context.getLootingModifier(); -+ else if (entity instanceof LivingEntity livingentity) -+ i = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); ++ level = context.getLootingModifier(); ++ else if (killer instanceof LivingEntity livingentity) ++ level = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); + - if (i == 0) { + if (level == 0) { return itemStack; } -@@ -84,7 +_,6 @@ +@@ -83,7 +_,6 @@ if (this.hasLimit()) { itemStack.limitSize(this.limit); } diff --git a/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch b/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch index ff80c549ac..c85a4d3836 100644 --- a/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch +++ b/patches/minecraft/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java.patch @@ -1,15 +1,15 @@ --- a/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java +++ b/net/minecraft/world/level/storage/loot/predicates/LootItemRandomChanceWithEnchantedBonusCondition.java -@@ -41,7 +_,11 @@ +@@ -40,7 +_,11 @@ public boolean test(final LootContext context) { - Entity entity = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); -- int i = entity instanceof LivingEntity livingentity ? EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity) : 0; -+ int i = 0; + Entity killerEntity = context.getOptionalParameter(LootContextParams.ATTACKING_ENTITY); +- int enchantmentLevel = killerEntity instanceof LivingEntity livingKiller ? EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingKiller) : 0; ++ int enchantmentLevel = 0; + if (this.enchantment.is(Enchantments.LOOTING)) -+ i = context.getLootingModifier(); -+ else if (entity instanceof LivingEntity livingentity) -+ i = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); - float f = i > 0 ? this.enchantedChance.calculate(i) : this.unenchantedChance; - return context.getRandom().nextFloat() < f; ++ enchantmentLevel = context.getLootingModifier(); ++ else if (killerEntity instanceof LivingEntity livingentity) ++ enchantmentLevel = EnchantmentHelper.getEnchantmentLevel(this.enchantment, livingentity); + float chance = enchantmentLevel > 0 ? this.enchantedChance.calculate(enchantmentLevel) : this.unenchantedChance; + return context.getRandom().nextFloat() < chance; }