diff --git a/README.md b/README.md index 28ea6cf..383b1c5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

Build - Minecraft 26.2 + Minecraft 26.1 | 26.2 | 26.3 Fabric Java 25 MIT @@ -14,7 +14,7 @@ **See where it lands, and how far the spread can carry it.** -Trajectory Projected is a client-side mod for Minecraft **26.2 / Fabric** that +Trajectory Projected is a client-side mod for Minecraft **26.1–26.3 / Fabric** that shows where your bow, crossbow, trident or thrown item will land. The flight is simulated tick by tick in the order vanilla uses, from the same position and rotation the server will fire with, so the line follows the real arrow rather @@ -77,10 +77,17 @@ casts; see [Accuracy](#accuracy). ## Getting started -Install **Fabric Loader 0.19.3+**, **Fabric API 0.161.0+26.2** and **Java 25**, -then place the Trajectory Projected JAR from +Install **Fabric Loader 0.19.3+**, **Fabric API** and **Java 25**, then place the +Trajectory Projected JAR for your Minecraft version from [Releases](https://github.com/WilyFoxM/TrajectoryProjected/releases) in your -Minecraft instance's `mods` folder. +Minecraft instance's `mods` folder. Each version has its own file: + +| File | Minecraft | Fabric API | +| --- | --- | --- | +| `+26.1.x` | 26.1, 26.1.1, 26.1.2 | 0.145.1 or newer | +| `+26.2` | 26.2 | 0.161.0 or newer | +| `+26.3` | 26.3 | 0.166.2 or newer | + Nothing needs to be installed on the server. Press **F7** in-game to open settings. A key to turn trajectories on and off can be @@ -94,7 +101,7 @@ and Russian translations are included. ## Compatibility -Built for Minecraft **26.2** with Fabric. I play with **Sodium** (0.9.2 tested). +Built for Minecraft **26.1.x, 26.2 and 26.3** with Fabric. I play on 26.2 with **Sodium** (0.9.2 tested). With **Iris** (1.11.4 tested) and a shader pack active, the line, markers and spread zone are drawn over the pack's finished image, so they look the same as without @@ -102,6 +109,10 @@ shaders and stay sharp; they are not lit or fogged by the pack. Checked with Complementary Reimagined r5.8.1 and BSL v10.1.8. Without a pack, Iris changes nothing. +On 26.3 the mod has been checked in a local client run with Sodium 0.9.2. Iris 1.11.7 does not +start on 26.3 even without this mod, so shaders there are untested. On 26.1.x the line over a +Complementary pack has been checked with Iris 1.11.4. + Other rendering mods have not been tested. On multiplayer I have tested one small server of my own; the results are under @@ -115,6 +126,10 @@ each tick, water, entity hitboxes and the random spread. Unit tests compare it w vanilla's formulas, which says nothing about the game itself, so I also measured it in game. +The measurements below were made on 26.2. Each version's file follows its own vanilla, +and the unit tests run against each version's code; 26.1.x and 26.3 have not been +measured in game separately. + I fired 334 logged bow shots and compared each prediction with the launch the server sent and with where the arrow stopped. The first 30 partial draws on the server exposed a bug in how the mod counted the draw. It is fixed, and the table shows the diff --git a/build.fabric.gradle.kts b/build.fabric.gradle.kts index dfae67f..e043689 100644 --- a/build.fabric.gradle.kts +++ b/build.fabric.gradle.kts @@ -57,6 +57,40 @@ val metadata = tasks.processResources { inputs.properties(metadata) filesMatching("fabric.mod.json") { expand(metadata) } + + // 26.3 compiles shaders to SPIR-V: `#include` instead of `#moj_import`, and every stage input + // and output needs an explicit location. Sources keep the older form; this rewrites them. + if (sc.current.parsed >= "26.3") { + val locations = + mapOf( + // Vertex attributes, in the order of DefaultVertexFormat.POSITION_TEX_COLOR. + "Position" to 0, "UV0" to 1, "Color" to 2, + // Vertex outputs and fragment inputs. + "discCoord" to 0, "vertexColor" to 1, + // Fragment output. + "fragColor" to 0, + ) + val declaration = Regex("""^(in|out) \w+ (\w+);""") + // Closures are not part of the task's up-to-date check; the table is. + inputs.property("shaderLocations", locations.toString()) + filesMatching(listOf("assets/*/shaders/**/*.vsh", "assets/*/shaders/**/*.fsh")) { + val file = path + filter { line -> + val variable = declaration.find(line)?.groupValues?.get(2) + when { + line.startsWith("#version") -> + "$line\n#extension GL_ARB_separate_shader_objects : require" + line.startsWith("#moj_import") -> line.replaceFirst("#moj_import", "#include") + variable != null -> { + val location = + locations[variable] ?: error("No shader location for $variable in $file") + "layout(location = $location) $line" + } + else -> line + } + } + } + } } tasks.jar { diff --git a/settings.gradle.kts b/settings.gradle.kts index d436c4f..480668b 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -18,7 +18,9 @@ plugins { stonecutter { create(rootProject) { // One node per Minecraft version, all built by build.fabric.gradle.kts. + version("26.1.2", "26.1.2").buildscript("build.fabric.gradle.kts") version("26.2", "26.2").buildscript("build.fabric.gradle.kts") + version("26.3", "26.3").buildscript("build.fabric.gradle.kts") vcsVersion = "26.2" } } diff --git a/src/dev/java/ru/wilyfox/trajectory/dev/ShotLog.java b/src/dev/java/ru/wilyfox/trajectory/dev/ShotLog.java index bfc4bdb..0d65c94 100644 --- a/src/dev/java/ru/wilyfox/trajectory/dev/ShotLog.java +++ b/src/dev/java/ru/wilyfox/trajectory/dev/ShotLog.java @@ -14,7 +14,6 @@ import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.Minecraft; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityTypes; import net.minecraft.world.entity.projectile.arrow.Arrow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,7 +61,7 @@ static void released(ShotPreview.Prediction prediction) { } static void entityLoaded(Entity entity) { - if (pending == null || entity.getType() != EntityTypes.ARROW) { + if (pending == null || !(entity instanceof Arrow)) { return; } Minecraft minecraft = Minecraft.getInstance(); diff --git a/src/main/java/ru/wilyfox/trajectory/client/AfterLevel.java b/src/main/java/ru/wilyfox/trajectory/client/AfterLevel.java index 0ea3064..afe0a07 100644 --- a/src/main/java/ru/wilyfox/trajectory/client/AfterLevel.java +++ b/src/main/java/ru/wilyfox/trajectory/client/AfterLevel.java @@ -1,28 +1,20 @@ package ru.wilyfox.trajectory.client; -import com.mojang.blaze3d.buffers.GpuBuffer; import com.mojang.blaze3d.buffers.GpuBufferSlice; import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.systems.RenderPass; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.ByteBufferBuilder; -import com.mojang.blaze3d.vertex.MeshData; import com.mojang.blaze3d.vertex.PoseStack; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.ArrayList; import java.util.List; -import java.util.Optional; -import java.util.OptionalDouble; import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.SubmitNodeCollector; import net.minecraft.client.renderer.rendertype.RenderType; import org.joml.Matrix4f; import org.joml.Matrix4fc; import ru.wilyfox.trajectory.TrajectoryProjected; +import ru.wilyfox.trajectory.compat.Gpu; /** * Drawing after the level has been rendered, onto the finished image, depth-tested against the main @@ -89,57 +81,17 @@ public static void flush() { return; } try { - RenderTarget target = Minecraft.getInstance().gameRenderer.mainRenderTarget(); - GpuBufferSlice transforms = - RenderSystem.getDynamicUniforms().writeTransform(new Matrix4f(viewRotation)); + RenderTarget target = Gpu.mainTarget(); + GpuBufferSlice transforms = Gpu.writeTransform(new Matrix4f(viewRotation)); for (Recorded r : RECORDED) { - draw(target, transforms, r); + Gpu.drawNow( + target, transforms, r.type(), builder -> r.geometry().render(r.pose(), builder)); } } finally { RECORDED.clear(); } } - private static void draw(RenderTarget target, GpuBufferSlice transforms, Recorded r) { - RenderType type = r.type(); - try (ByteBufferBuilder bytes = new ByteBufferBuilder(type.format().getVertexSize() * 256)) { - BufferBuilder builder = new BufferBuilder(bytes, type.primitiveTopology(), type.format()); - r.geometry().render(r.pose(), builder); - try (MeshData mesh = builder.build()) { - if (mesh == null) { - return; - } - int indexCount = mesh.drawState().indexCount(); - RenderSystem.AutoStorageIndexBuffer indices = - RenderSystem.getSequentialBuffer(type.primitiveTopology()); - GpuBuffer indexBuffer = indices.getBuffer(indexCount); - try (GpuBuffer vertices = - RenderSystem.getDevice() - .createBuffer( - () -> "Trajectory Projected after shaders", - GpuBuffer.USAGE_VERTEX, - mesh.vertexBuffer())) { - try (RenderPass pass = - RenderSystem.getDevice() - .createCommandEncoder() - .createRenderPass( - () -> "Trajectory Projected after shaders", - target.getColorTextureView(), - Optional.empty(), - target.useDepth ? target.getDepthTextureView() : null, - OptionalDouble.empty())) { - pass.setPipeline(type.pipeline()); - RenderSystem.bindDefaultUniforms(pass); - pass.setUniform("DynamicTransforms", transforms); - pass.setVertexBuffer(0, vertices.slice()); - pass.setIndexBuffer(indexBuffer, indices.type()); - pass.drawIndexed(indexCount, 1, 0, 0, 0); - } - } - } - } - } - private static MethodHandle resolve(String method) { if (!IRIS) { return null; diff --git a/src/main/java/ru/wilyfox/trajectory/client/DotRenderer.java b/src/main/java/ru/wilyfox/trajectory/client/DotRenderer.java index 0c7f201..197017c 100644 --- a/src/main/java/ru/wilyfox/trajectory/client/DotRenderer.java +++ b/src/main/java/ru/wilyfox/trajectory/client/DotRenderer.java @@ -3,7 +3,6 @@ import com.mojang.blaze3d.pipeline.DepthStencilState; import com.mojang.blaze3d.pipeline.RenderPipeline; import com.mojang.blaze3d.platform.CompareOp; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import java.util.ArrayList; @@ -27,6 +26,7 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import org.joml.Vector3f; +import ru.wilyfox.trajectory.compat.Gpu; import ru.wilyfox.trajectory.config.TrajectoryConfig; import ru.wilyfox.trajectory.sim.Aabb; import ru.wilyfox.trajectory.sim.Face; @@ -48,42 +48,38 @@ final class DotRenderer { private static final String MOD_ID = "trajectory_projected"; private static final RenderPipeline VISIBLE = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/dots")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withCull(false) .build(); - /** Passes only where terrain is in front of the dot (the depth buffer is reversed). */ + /** Passes only where terrain is in front of the dot. */ private static final RenderPipeline HIDDEN = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/dots_hidden")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot_hidden")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) - .withDepthStencilState(new DepthStencilState(CompareOp.LESS_THAN, false)) + .withDepthStencilState(new DepthStencilState(Gpu.BEHIND, false)) .withCull(false) .build(); /** The hit marker on a living target: an anti-aliased cross instead of a disc. */ private static final RenderPipeline CROSS = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/cross")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/cross")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withCull(false) .build(); private static final RenderPipeline CROSS_HIDDEN = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/cross_hidden")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/cross_hidden")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) - .withDepthStencilState(new DepthStencilState(CompareOp.LESS_THAN, false)) + .withDepthStencilState(new DepthStencilState(Gpu.BEHIND, false)) .withCull(false) .build(); @@ -93,21 +89,19 @@ final class DotRenderer { * outlined) is chosen per dot from a ray to the real path point it stands for. */ private static final RenderPipeline OVERLAY = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/dots_overlay")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withDepthStencilState(new DepthStencilState(CompareOp.ALWAYS_PASS, false)) .withCull(false) .build(); private static final RenderPipeline OVERLAY_HIDDEN = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/dots_overlay_hidden")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot_hidden")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withDepthStencilState(new DepthStencilState(CompareOp.ALWAYS_PASS, false)) .withCull(false) .build(); @@ -124,11 +118,10 @@ final class DotRenderer { /** The spread zone on block faces: a projected decal, depth-tested, never written to depth. */ private static final RenderPipeline ZONE = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/zone")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/zone")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withCull(false) .build(); @@ -143,13 +136,13 @@ final class DotRenderer { * depth test frame by frame. A bias following the surface's slope covers that shift. */ private static final RenderPipeline ZONE_OVER_SHADERS = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/zone_over_shaders")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/zone")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withDepthStencilState( - new DepthStencilState(DepthStencilState.DEFAULT.depthTest(), false, 2.0F, 0.0F)) + new DepthStencilState( + DepthStencilState.DEFAULT.depthTest(), false, Gpu.TOWARDS_CAMERA * 2.0F, 0.0F)) .withCull(false) .build(); @@ -168,21 +161,19 @@ final class DotRenderer { /** The hook of a fishing rod where it will land: a ghost of the bobber. */ private static final RenderPipeline BOBBER = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/bobber")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/bobber")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) .withCull(false) .build(); private static final RenderPipeline BOBBER_HIDDEN = - RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + Gpu.texColorQuads(RenderPipelines.DEBUG_FILLED_SNIPPET) .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/bobber_hidden")) .withVertexShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/dot")) .withFragmentShader(Identifier.fromNamespaceAndPath(MOD_ID, "core/bobber_hidden")) - .withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR) - .withDepthStencilState(new DepthStencilState(CompareOp.LESS_THAN, false)) + .withDepthStencilState(new DepthStencilState(Gpu.BEHIND, false)) .withCull(false) .build(); diff --git a/src/main/java/ru/wilyfox/trajectory/client/ShotPreview.java b/src/main/java/ru/wilyfox/trajectory/client/ShotPreview.java index dd350b7..9e1a5cb 100644 --- a/src/main/java/ru/wilyfox/trajectory/client/ShotPreview.java +++ b/src/main/java/ru/wilyfox/trajectory/client/ShotPreview.java @@ -11,6 +11,7 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.ItemStackTemplate; import net.minecraft.world.item.Items; import net.minecraft.world.item.component.ChargedProjectiles; import net.minecraft.world.item.component.Fireworks; @@ -333,7 +334,7 @@ private static Prediction crossbow( if (shooter == null) { return null; } - List items = charged.itemCopies(); + List items = charged.items().stream().map(ItemStackTemplate::create).toList(); List charges = new ArrayList<>(items.size()); for (ItemStack item : items) { charges.add( diff --git a/src/main/java/ru/wilyfox/trajectory/compat/Gpu.java b/src/main/java/ru/wilyfox/trajectory/compat/Gpu.java new file mode 100644 index 0000000..24aa331 --- /dev/null +++ b/src/main/java/ru/wilyfox/trajectory/compat/Gpu.java @@ -0,0 +1,142 @@ +package ru.wilyfox.trajectory.compat; + +import com.mojang.blaze3d.buffers.GpuBuffer; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.pipeline.RenderTarget; +import com.mojang.blaze3d.platform.CompareOp; +import com.mojang.blaze3d.systems.RenderPass; +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.ByteBufferBuilder; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.MeshData; +import java.util.OptionalDouble; +import java.util.function.Consumer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.rendertype.RenderType; +import org.joml.Matrix4f; +//? if >=26.2 { +import java.util.Optional; +//?} else { +/*import com.mojang.blaze3d.vertex.VertexFormat; +import java.util.OptionalInt; +import org.joml.Vector3f; +import org.joml.Vector4f; +*///?} + +/** GPU calls whose shape differs between Minecraft versions. Render thread. */ +public final class Gpu { + private static final String LABEL = "Trajectory Projected after level"; + + /** + * Passes where something already drawn is nearer than the fragment: the path behind terrain. Depth + * is reversed since 26.2 (cleared to 0, nearer is greater); before, nearer is smaller. + */ + //? if >=26.2 { + public static final CompareOp BEHIND = CompareOp.LESS_THAN; + //?} else { + /*public static final CompareOp BEHIND = CompareOp.GREATER_THAN; + *///?} + + /** The sign of a depth bias that moves a fragment towards the camera. */ + //? if >=26.2 { + public static final float TOWARDS_CAMERA = 1.0F; + //?} else { + /*public static final float TOWARDS_CAMERA = -1.0F; + *///?} + + private Gpu() {} + + /** A pipeline builder on {@code snippet} for {@code POSITION_TEX_COLOR} quads. */ + public static RenderPipeline.Builder texColorQuads(RenderPipeline.Snippet snippet) { + //? if >=26.2 { + // The snippets we build on already draw quads. + return RenderPipeline.builder(snippet).withVertexBinding(0, DefaultVertexFormat.POSITION_TEX_COLOR); + //?} else { + /*return RenderPipeline.builder(snippet) + .withVertexFormat(DefaultVertexFormat.POSITION_TEX_COLOR, VertexFormat.Mode.QUADS); + *///?} + } + + /** The main render target, which the level is drawn into. */ + public static RenderTarget mainTarget() { + //? if >=26.2 { + return Minecraft.getInstance().gameRenderer.mainRenderTarget(); + //?} else { + /*return Minecraft.getInstance().getMainRenderTarget(); + *///?} + } + + /** Writes {@code modelView} into this frame's dynamic transforms, with no tint or offset. */ + public static GpuBufferSlice writeTransform(Matrix4f modelView) { + //? if >=26.2 { + return RenderSystem.getDynamicUniforms().writeTransform(modelView); + //?} else { + /*return RenderSystem.getDynamicUniforms() + .writeTransform(modelView, new Vector4f(1.0F, 1.0F, 1.0F, 1.0F), new Vector3f(), new Matrix4f()); + *///?} + } + + /** + * Builds the geometry {@code fill} writes and draws it at once with {@code type}'s pipeline onto + * {@code target}, depth-tested against its depth buffer. + */ + public static void drawNow( + RenderTarget target, GpuBufferSlice transforms, RenderType type, Consumer fill) { + //? if >=26.2 { + var topology = type.primitiveTopology(); + //?} else { + /*var topology = type.mode(); + *///?} + try (ByteBufferBuilder bytes = new ByteBufferBuilder(type.format().getVertexSize() * 256)) { + BufferBuilder builder = new BufferBuilder(bytes, topology, type.format()); + fill.accept(builder); + try (MeshData mesh = builder.build()) { + if (mesh == null) { + return; + } + int indexCount = mesh.drawState().indexCount(); + RenderSystem.AutoStorageIndexBuffer indices = RenderSystem.getSequentialBuffer(topology); + GpuBuffer indexBuffer = indices.getBuffer(indexCount); + try (GpuBuffer vertices = + RenderSystem.getDevice().createBuffer(() -> LABEL, GpuBuffer.USAGE_VERTEX, mesh.vertexBuffer())) { + //? if >=26.3 { + /*boolean depth = target.hasDepth(); + *///?} else { + boolean depth = target.useDepth; + //?} + try (RenderPass pass = + RenderSystem.getDevice() + .createCommandEncoder() + .createRenderPass( + () -> LABEL, + target.getColorTextureView(), + //? if >=26.2 { + Optional.empty(), + //?} else { + /*OptionalInt.empty(), + *///?} + depth ? target.getDepthTextureView() : null, + OptionalDouble.empty())) { + //? if >=26.3 { + /*pass.setPipeline(RenderSystem.getCompiledPipeline(type.pipeline())); + *///?} else { + pass.setPipeline(type.pipeline()); + //?} + RenderSystem.bindDefaultUniforms(pass); + pass.setUniform("DynamicTransforms", transforms); + pass.setIndexBuffer(indexBuffer, indices.type()); + //? if >=26.2 { + pass.setVertexBuffer(0, vertices.slice()); + pass.drawIndexed(indexCount, 1, 0, 0, 0); + //?} else { + /*pass.setVertexBuffer(0, vertices); + pass.drawIndexed(0, 0, indexCount, 1); + *///?} + } + } + } + } + } +} diff --git a/src/main/java/ru/wilyfox/trajectory/compat/Screens.java b/src/main/java/ru/wilyfox/trajectory/compat/Screens.java new file mode 100644 index 0000000..e808b6f --- /dev/null +++ b/src/main/java/ru/wilyfox/trajectory/compat/Screens.java @@ -0,0 +1,50 @@ +package ru.wilyfox.trajectory.compat; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.screens.Overlay; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; + +/** + * Version seam for the screen, the loading overlay and the overlay message: 26.2 moved them from {@code Minecraft} and + * {@code Gui} into {@code Gui} and its {@code Hud}. Client thread. + */ +public final class Screens { + private Screens() {} + + /** The open screen, or {@code null} in game. */ + public static Screen current(Minecraft minecraft) { + //? if >=26.2 { + return minecraft.gui.screen(); + //?} else { + /*return minecraft.screen; + *///?} + } + + /** Opens {@code screen}, or closes the open one when {@code null}. */ + public static void open(Minecraft minecraft, Screen screen) { + //? if >=26.2 { + minecraft.gui.setScreen(screen); + //?} else { + /*minecraft.setScreen(screen); + *///?} + } + + /** Shows {@code message} above the hotbar. */ + public static void overlayMessage(Minecraft minecraft, Component message) { + //? if >=26.2 { + minecraft.gui.hud.setOverlayMessage(message, false); + //?} else { + /*minecraft.gui.setOverlayMessage(message, false); + *///?} + } + + /** The loading overlay, or {@code null} when none is shown. */ + public static Overlay loadingOverlay(Minecraft minecraft) { + //? if >=26.2 { + return minecraft.gui.overlay(); + //?} else { + /*return minecraft.getOverlay(); + *///?} + } +} diff --git a/src/main/java/ru/wilyfox/trajectory/gui/SettingRow.java b/src/main/java/ru/wilyfox/trajectory/gui/SettingRow.java index 7ef2192..1763eb9 100644 --- a/src/main/java/ru/wilyfox/trajectory/gui/SettingRow.java +++ b/src/main/java/ru/wilyfox/trajectory/gui/SettingRow.java @@ -137,7 +137,7 @@ public boolean isMouseOver(double x, double y) { @Override protected boolean isValidClickButton(MouseButtonInfo button) { - return button.button() == 0; + return button.button() == InputConstants.MOUSE_BUTTON_LEFT; } @Override @@ -150,7 +150,13 @@ public void onPress(InputWithModifiers input) { dragRemainder = 0; return; } - option.change().accept(input instanceof MouseButtonEvent mouse && mouse.button() == 1 ? -1 : 1); + option + .change() + .accept( + input instanceof MouseButtonEvent mouse + && mouse.button() == InputConstants.MOUSE_BUTTON_RIGHT + ? -1 + : 1); owner.saveChanges(); refresh(); } @@ -159,10 +165,7 @@ public void onPress(InputWithModifiers input) { protected void onDrag(MouseButtonEvent event, double dx, double dy) { if (!dragging) return; // MouseHandler retains the mouse-down modifiers throughout the drag. - var window = Minecraft.getInstance().getWindow(); - boolean fine = - InputConstants.isKeyDown(window, org.lwjgl.glfw.GLFW.GLFW_KEY_LEFT_SHIFT) - || InputConstants.isKeyDown(window, org.lwjgl.glfw.GLFW.GLFW_KEY_RIGHT_SHIFT); + boolean fine = Minecraft.getInstance().hasShiftDown(); dragRemainder += (event.x() - dragX) / (fine ? 12 : 3); dragX = event.x(); int steps = (int) dragRemainder; diff --git a/src/main/java/ru/wilyfox/trajectory/gui/SettingsKeyBinding.java b/src/main/java/ru/wilyfox/trajectory/gui/SettingsKeyBinding.java index 18d2c05..2922e57 100644 --- a/src/main/java/ru/wilyfox/trajectory/gui/SettingsKeyBinding.java +++ b/src/main/java/ru/wilyfox/trajectory/gui/SettingsKeyBinding.java @@ -7,8 +7,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.resources.Identifier; -import org.lwjgl.glfw.GLFW; import ru.wilyfox.trajectory.TrajectoryProjected; +import ru.wilyfox.trajectory.compat.Screens; import ru.wilyfox.trajectory.config.TrajectoryConfig; /** @@ -24,15 +24,13 @@ public final class SettingsKeyBinding { KeyMappingHelper.registerKeyMapping( new KeyMapping( "key." + TrajectoryProjected.MOD_ID + ".open_settings", - InputConstants.Type.KEYSYM, - GLFW.GLFW_KEY_F7, + InputConstants.KEY_F7, CATEGORY)); private static final KeyMapping TOGGLE = KeyMappingHelper.registerKeyMapping( new KeyMapping( "key." + TrajectoryProjected.MOD_ID + ".toggle", - InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), CATEGORY)); @@ -49,14 +47,14 @@ public static void register() { while (TOGGLE.consumeClick()) { toggle = !toggle; } - if (client.player == null || client.gui.screen() != null) { + if (client.player == null || Screens.current(client) != null) { return; } if (toggle) { toggle(client); } if (open) { - client.gui.setScreen(new TrajectoryScreen(null)); + Screens.open(client, new TrajectoryScreen(null)); } }); } @@ -69,9 +67,9 @@ private static void toggle(Minecraft client) { } catch (RuntimeException failure) { TrajectoryProjected.LOGGER.error("Could not save settings", failure); } - client.gui.hud.setOverlayMessage( + Screens.overlayMessage( + client, Component.translatable( - SettingsCatalog.PREFIX + (config.enabled ? "toggled.on" : "toggled.off")), - false); + SettingsCatalog.PREFIX + (config.enabled ? "toggled.on" : "toggled.off"))); } } diff --git a/src/main/java/ru/wilyfox/trajectory/gui/TrajectoryScreen.java b/src/main/java/ru/wilyfox/trajectory/gui/TrajectoryScreen.java index f14b04a..f01bc37 100644 --- a/src/main/java/ru/wilyfox/trajectory/gui/TrajectoryScreen.java +++ b/src/main/java/ru/wilyfox/trajectory/gui/TrajectoryScreen.java @@ -1,5 +1,6 @@ package ru.wilyfox.trajectory.gui; +import com.mojang.blaze3d.platform.InputConstants; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -10,11 +11,13 @@ import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.components.Tooltip; +import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.input.KeyEvent; import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.network.chat.Component; import ru.wilyfox.trajectory.TrajectoryProjected; +import ru.wilyfox.trajectory.compat.Screens; import ru.wilyfox.trajectory.config.TrajectoryConfig; /** Standalone settings: categories, global search and clipped, accessible controls. */ @@ -113,7 +116,7 @@ protected void init() { Component.translatable(SettingsCatalog.PREFIX + "reset"), () -> { finishDrags(); - minecraft.gui.setScreen(new ResetConfirmation()); + Screens.open(minecraft, new ResetConfirmation()); }, () -> false)); done = @@ -320,7 +323,7 @@ public boolean mouseScrolled(double mx, double my, double dx, double dy) { @Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { - if (event.button() == 0 + if (event.button() == InputConstants.MOUSE_BUTTON_LEFT && maxScroll > 0 && event.x() >= contentX + contentWidth - 8 && event.x() <= contentX + contentWidth @@ -369,17 +372,25 @@ public boolean mouseDragged(MouseButtonEvent event, double dx, double dy) { @Override public boolean mouseReleased(MouseButtonEvent event) { - if (event.button() == 0) { + if (event.button() == InputConstants.MOUSE_BUTTON_LEFT) { scrollbarDragging = false; finishDrags(); } return super.mouseReleased(event); } + /** The focused component at the end of {@code path}; the same walk works in every 26.x. */ + private static GuiEventListener leaf(ComponentPath path) { + while (path instanceof ComponentPath.Path node) { + path = node.childPath(); + } + return path.component(); + } + @Override protected void changeFocus(ComponentPath path) { super.changeFocus(path); - if (path != null && path.leafComponent() instanceof SettingRow row) { + if (path != null && leaf(path) instanceof SettingRow row) { if (row.getY() < viewportTop) scroll -= viewportTop - row.getY(); if (row.getBottom() > viewportBottom) scroll += row.getBottom() - viewportBottom; positionRows(); @@ -388,7 +399,7 @@ protected void changeFocus(ComponentPath path) { @Override public boolean keyPressed(KeyEvent event) { - if (event.hasControlDown() && event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_F) { + if (event.hasControlDown() && event.key() == InputConstants.KEY_F) { setFocused(search); return true; } @@ -397,12 +408,11 @@ public boolean keyPressed(KeyEvent event) { return true; } if (getFocused() != search - && (event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_PAGE_DOWN - || event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_PAGE_UP)) { + && (event.key() == InputConstants.KEY_PAGEDOWN + || event.key() == InputConstants.KEY_PAGEUP)) { finishDrags(); scroll += - (event.key() == org.lwjgl.glfw.GLFW.GLFW_KEY_PAGE_DOWN ? 1 : -1) - * (viewportBottom - viewportTop); + (event.key() == InputConstants.KEY_PAGEDOWN ? 1 : -1) * (viewportBottom - viewportTop); positionRows(); return true; } @@ -425,7 +435,7 @@ public void removed() { @Override public void onClose() { finishDrags(); - if (saveChanges()) minecraft.gui.setScreen(parent); + if (saveChanges()) Screens.open(minecraft, parent); } private final class ResetConfirmation extends Screen { @@ -487,7 +497,7 @@ public boolean isPauseScreen() { @Override public void onClose() { - minecraft.gui.setScreen(TrajectoryScreen.this); + Screens.open(minecraft, TrajectoryScreen.this); } } } diff --git a/src/main/java/ru/wilyfox/trajectory/mixin/GameRendererAfterLevelMixin.java b/src/main/java/ru/wilyfox/trajectory/mixin/GameRendererAfterLevelMixin.java deleted file mode 100644 index e12398b..0000000 --- a/src/main/java/ru/wilyfox/trajectory/mixin/GameRendererAfterLevelMixin.java +++ /dev/null @@ -1,54 +0,0 @@ -package ru.wilyfox.trajectory.mixin; - -import com.llamalad7.mixinextras.injector.wrapoperation.Operation; -import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; -import com.mojang.blaze3d.buffers.GpuBufferSlice; -import com.mojang.blaze3d.resource.GraphicsResourceAllocator; -import net.minecraft.client.DeltaTracker; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.state.level.CameraRenderState; -import org.joml.Matrix4fc; -import org.joml.Vector4f; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import ru.wilyfox.trajectory.client.AfterLevel; - -/** - * Right after the level render, before the hand: water and other translucent layers are drawn and - * composed by then, as is an Iris shader pack's frame, and what was recorded for {@link AfterLevel} - * is drawn on top. - */ -@Mixin(GameRenderer.class) -abstract class GameRendererAfterLevelMixin { - @WrapOperation( - method = "renderLevel", - at = - @At( - value = "INVOKE", - target = - "Lnet/minecraft/client/renderer/LevelRenderer;render(Lcom/mojang/blaze3d/resource/GraphicsResourceAllocator;Lnet/minecraft/client/DeltaTracker;ZLnet/minecraft/client/renderer/state/level/CameraRenderState;Lorg/joml/Matrix4fc;Lcom/mojang/blaze3d/buffers/GpuBufferSlice;Lorg/joml/Vector4f;Z)V")) - private void trajectory$drawAfterLevel( - LevelRenderer levelRenderer, - GraphicsResourceAllocator allocator, - DeltaTracker deltaTracker, - boolean renderOutline, - CameraRenderState cameraState, - Matrix4fc modelViewMatrix, - GpuBufferSlice terrainFog, - Vector4f fogColor, - boolean shouldCreateFog, - Operation original) { - original.call( - levelRenderer, - allocator, - deltaTracker, - renderOutline, - cameraState, - modelViewMatrix, - terrainFog, - fogColor, - shouldCreateFog); - AfterLevel.flush(); - } -} diff --git a/src/main/java/ru/wilyfox/trajectory/mixin/HudCrosshairMixin.java b/src/main/java/ru/wilyfox/trajectory/mixin/compat/CrosshairMixin.java similarity index 85% rename from src/main/java/ru/wilyfox/trajectory/mixin/HudCrosshairMixin.java rename to src/main/java/ru/wilyfox/trajectory/mixin/compat/CrosshairMixin.java index 0d29349..349fbc1 100644 --- a/src/main/java/ru/wilyfox/trajectory/mixin/HudCrosshairMixin.java +++ b/src/main/java/ru/wilyfox/trajectory/mixin/compat/CrosshairMixin.java @@ -1,21 +1,30 @@ -package ru.wilyfox.trajectory.mixin; +package ru.wilyfox.trajectory.mixin.compat; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.mojang.blaze3d.pipeline.RenderPipeline; import net.minecraft.client.gui.GuiGraphicsExtractor; -import net.minecraft.client.gui.Hud; import net.minecraft.resources.Identifier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import ru.wilyfox.trajectory.client.CrosshairTurn; +//? if >=26.2 { +import net.minecraft.client.gui.Hud; +//?} else { +/*import net.minecraft.client.gui.Gui; +*///?} /** * Rotates the crosshair sprite around its center while a drawn bow would hit a living entity. Only - * the crosshair itself turns; the attack indicator below it is drawn by later calls. + * the crosshair itself turns; the attack indicator below it is drawn by later calls. The crosshair + * moved from {@code Gui} to {@code Hud} in 26.2. */ +//? if >=26.2 { @Mixin(Hud.class) -abstract class HudCrosshairMixin { +//?} else { +/*@Mixin(Gui.class) +*///?} +abstract class CrosshairMixin { @WrapOperation( method = "extractCrosshair", at = diff --git a/src/main/java/ru/wilyfox/trajectory/mixin/compat/GameRendererAfterLevelMixin.java b/src/main/java/ru/wilyfox/trajectory/mixin/compat/GameRendererAfterLevelMixin.java new file mode 100644 index 0000000..c010da4 --- /dev/null +++ b/src/main/java/ru/wilyfox/trajectory/mixin/compat/GameRendererAfterLevelMixin.java @@ -0,0 +1,123 @@ +package ru.wilyfox.trajectory.mixin.compat; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import com.mojang.blaze3d.buffers.GpuBufferSlice; +import com.mojang.blaze3d.resource.GraphicsResourceAllocator; +import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.state.level.CameraRenderState; +import org.joml.Vector4f; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import ru.wilyfox.trajectory.client.AfterLevel; +//? if <26.3 { +import net.minecraft.client.DeltaTracker; +import org.joml.Matrix4fc; +//?} +//? if <26.2 { +/*import net.minecraft.client.renderer.chunk.ChunkSectionsToRender; +*///?} + +/** + * Right after the level render, before the hand: water and other translucent layers are drawn and + * composed by then, as is an Iris shader pack's frame, and what was recorded for {@link AfterLevel} + * is drawn on top. + */ +@Mixin(GameRenderer.class) +abstract class GameRendererAfterLevelMixin { + //? if >=26.3 { + /*@WrapOperation( + method = "renderLevel", + at = + @At( + value = "INVOKE", + target = + "Lnet/minecraft/client/renderer/LevelRenderer;render(Lcom/mojang/blaze3d/resource/GraphicsResourceAllocator;ZLnet/minecraft/client/renderer/state/level/CameraRenderState;Lcom/mojang/blaze3d/buffers/GpuBufferSlice;Lorg/joml/Vector4f;ZZ)V")) + private void trajectory$drawAfterLevel( + LevelRenderer levelRenderer, + GraphicsResourceAllocator allocator, + boolean renderOutline, + CameraRenderState cameraState, + GpuBufferSlice terrainFog, + Vector4f fogColor, + boolean shouldRenderSky, + boolean consistentDepthRequired, + Operation original) { + original.call( + levelRenderer, + allocator, + renderOutline, + cameraState, + terrainFog, + fogColor, + shouldRenderSky, + consistentDepthRequired); + AfterLevel.flush(); + } + *///?} else if >=26.2 { + @WrapOperation( + method = "renderLevel", + at = + @At( + value = "INVOKE", + target = + "Lnet/minecraft/client/renderer/LevelRenderer;render(Lcom/mojang/blaze3d/resource/GraphicsResourceAllocator;Lnet/minecraft/client/DeltaTracker;ZLnet/minecraft/client/renderer/state/level/CameraRenderState;Lorg/joml/Matrix4fc;Lcom/mojang/blaze3d/buffers/GpuBufferSlice;Lorg/joml/Vector4f;Z)V")) + private void trajectory$drawAfterLevel( + LevelRenderer levelRenderer, + GraphicsResourceAllocator allocator, + DeltaTracker deltaTracker, + boolean renderOutline, + CameraRenderState cameraState, + Matrix4fc modelViewMatrix, + GpuBufferSlice terrainFog, + Vector4f fogColor, + boolean shouldCreateFog, + Operation original) { + original.call( + levelRenderer, + allocator, + deltaTracker, + renderOutline, + cameraState, + modelViewMatrix, + terrainFog, + fogColor, + shouldCreateFog); + AfterLevel.flush(); + } + //?} else { + /*@WrapOperation( + method = "renderLevel", + at = + @At( + value = "INVOKE", + target = + "Lnet/minecraft/client/renderer/LevelRenderer;renderLevel(Lcom/mojang/blaze3d/resource/GraphicsResourceAllocator;Lnet/minecraft/client/DeltaTracker;ZLnet/minecraft/client/renderer/state/level/CameraRenderState;Lorg/joml/Matrix4fc;Lcom/mojang/blaze3d/buffers/GpuBufferSlice;Lorg/joml/Vector4f;ZLnet/minecraft/client/renderer/chunk/ChunkSectionsToRender;)V")) + private void trajectory$drawAfterLevel( + LevelRenderer levelRenderer, + GraphicsResourceAllocator allocator, + DeltaTracker deltaTracker, + boolean renderOutline, + CameraRenderState cameraState, + Matrix4fc modelViewMatrix, + GpuBufferSlice terrainFog, + Vector4f fogColor, + boolean shouldRenderSky, + ChunkSectionsToRender chunkSections, + Operation original) { + original.call( + levelRenderer, + allocator, + deltaTracker, + renderOutline, + cameraState, + modelViewMatrix, + terrainFog, + fogColor, + shouldRenderSky, + chunkSections); + AfterLevel.flush(); + } + *///?} +} diff --git a/src/main/java/ru/wilyfox/trajectory/sim/ArrowFlight.java b/src/main/java/ru/wilyfox/trajectory/sim/ArrowFlight.java index cf83bed..ca1d85f 100644 --- a/src/main/java/ru/wilyfox/trajectory/sim/ArrowFlight.java +++ b/src/main/java/ru/wilyfox/trajectory/sim/ArrowFlight.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; +import ru.wilyfox.trajectory.sim.compat.VanillaRules; /** * Flight of an arrow or a trident, tick by tick, in the order of vanilla 26.2 {@code @@ -89,7 +90,14 @@ public static Trajectory simulate( Aabb searchArea = box(pos).expandTowards(vel).inflate(1.0); List hits = - entityHits(world, origin, blocks.location(), searchArea, margin(tickCount), leftOwner); + entityHits( + world, + origin, + blocks.location(), + searchArea, + margin(tickCount), + leftOwner, + VanillaRules.ARROW_MARGIN_HIT_ON_SURFACE); if (!hits.isEmpty()) { hits.sort(Comparator.comparingDouble(h -> origin.distanceToSqr(h.target().position()))); Hit first = hits.getFirst(); @@ -163,10 +171,18 @@ static boolean outsideShooter(WorldView world, Aabb projectile, Vec3d vel) { /** * {@code ProjectileUtil.getManyEntityHitResult} with {@code includeFromEntity = false}: exact box - * hits, and hits within the margin that are confirmed by a ray towards the box center. + * hits, and hits within the margin that are confirmed by a ray towards the box center. A margin + * hit lands on the box surface when {@code projectSurface} is set, else where the ray enters the + * inflated box. */ static List entityHits( - WorldView world, Vec3d from, Vec3d to, Aabb area, float margin, boolean leftOwner) { + WorldView world, + Vec3d from, + Vec3d to, + Aabb area, + float margin, + boolean leftOwner, + boolean projectSurface) { List hits = new ArrayList<>(); for (WorldView.EntityTarget target : world.entities(area)) { if (target.shooterGroup() && !leftOwner) { @@ -197,7 +213,7 @@ static List entityHits( Vec3d surface = box.clip(outside, towards); if (surface != null) { - hits.add(new Hit(target, surface)); + hits.add(new Hit(target, projectSurface ? surface : outside)); } } return hits; diff --git a/src/main/java/ru/wilyfox/trajectory/sim/FishingHookFlight.java b/src/main/java/ru/wilyfox/trajectory/sim/FishingHookFlight.java index b8dfd81..e21b054 100644 --- a/src/main/java/ru/wilyfox/trajectory/sim/FishingHookFlight.java +++ b/src/main/java/ru/wilyfox/trajectory/sim/FishingHookFlight.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import ru.wilyfox.trajectory.sim.compat.VanillaRules; /** * Flight of a fishing hook, tick by tick, in the order of vanilla 26.2 {@code FishingHook.tick}. @@ -16,7 +17,7 @@ * entity is hooked, a block sets the speed to the squared distance to it ({@code onHitBlock} * with {@code HitResult.distanceTo}, which is squared); *

  • bobbing: horizontal velocity × 0.9, and a random pull towards the water surface; - *
  • gravity 0.03 out of water and off the ground; + *
  • gravity ({@link VanillaRules#FISHING_HOOK_GRAVITY}) out of water and off the ground; *
  • {@code move(SELF)} with collisions; in flight, ground or a wall sets the velocity to zero; *
  • velocity × 0.92. * @@ -31,7 +32,7 @@ public final class FishingHookFlight { /** {@code EntityTypes.FISHING_BOBBER}: {@code sized(0.25F, 0.25F)}. */ public static final float SIZE = 0.25F; - public static final double GRAVITY = 0.03; + public static final double GRAVITY = VanillaRules.FISHING_HOOK_GRAVITY; public static final double INERTIA = 0.92; diff --git a/src/main/java/ru/wilyfox/trajectory/sim/compat/VanillaRules.java b/src/main/java/ru/wilyfox/trajectory/sim/compat/VanillaRules.java new file mode 100644 index 0000000..dee83dd --- /dev/null +++ b/src/main/java/ru/wilyfox/trajectory/sim/compat/VanillaRules.java @@ -0,0 +1,27 @@ +package ru.wilyfox.trajectory.sim.compat; + +/** Projectile rules that differ between the Minecraft versions this build targets. */ +public final class VanillaRules { + private VanillaRules() {} + + /** + * {@code FishingHook} gravity per tick: the literal {@code 0.03} through 26.2; since 26.3 it is + * {@code getDefaultGravity()}, which returns the float {@code 0.03F} widened to double. + */ + //? if >=26.3 { + /*public static final double FISHING_HOOK_GRAVITY = 0.03F; + *///?} else { + public static final double FISHING_HOOK_GRAVITY = 0.03; + //?} + + /** + * Where an arrow's hit within the entity margin lands ({@code AbstractArrow.findHitEntities}): + * projected onto the entity's box through 26.2; since 26.3 the arrow passes {@code + * projectSurfaceHitLocation = false} and the hit stays where the ray enters the inflated box. + */ + //? if >=26.3 { + /*public static final boolean ARROW_MARGIN_HIT_ON_SURFACE = false; + *///?} else { + public static final boolean ARROW_MARGIN_HIT_ON_SURFACE = true; + //?} +} diff --git a/src/main/resources/trajectory_projected.mixins.json b/src/main/resources/trajectory_projected.mixins.json index 5c42f47..dacce23 100644 --- a/src/main/resources/trajectory_projected.mixins.json +++ b/src/main/resources/trajectory_projected.mixins.json @@ -3,8 +3,8 @@ "package": "ru.wilyfox.trajectory.mixin", "compatibilityLevel": "JAVA_25", "client": [ - "GameRendererAfterLevelMixin", - "HudCrosshairMixin", + "compat.GameRendererAfterLevelMixin", + "compat.CrosshairMixin", "LocalPlayerAccessor", "LocalPlayerSendPositionMixin" ], diff --git a/src/test/java/ru/wilyfox/trajectory/sim/ArrowFlightTest.java b/src/test/java/ru/wilyfox/trajectory/sim/ArrowFlightTest.java index 5d72f15..9abe0aa 100644 --- a/src/test/java/ru/wilyfox/trajectory/sim/ArrowFlightTest.java +++ b/src/test/java/ru/wilyfox/trajectory/sim/ArrowFlightTest.java @@ -5,6 +5,7 @@ import java.util.List; import org.junit.jupiter.api.Test; +import ru.wilyfox.trajectory.sim.compat.VanillaRules; class ArrowFlightTest { private static final Vec3d SPAWN = new Vec3d(0.0, 65.52, 0.0); @@ -107,6 +108,14 @@ void nearMissIsCaughtOnceTheMarginHasGrown() { Trajectory t = ArrowFlight.simulate(new Vec3d(0.4, 66.5, 0.0), new Vec3d(0, 0, 3), world, 12); assertEquals(Trajectory.End.ENTITY, t.end()); assertTrue(t.ticks() >= 8); + if (VanillaRules.ARROW_MARGIN_HIT_ON_SURFACE) { + // Projected onto the box, whose side is at x = 0.3. + assertTrue(t.last().x() <= 0.3 + 1.0E-9, "on the box: " + t.last()); + } else { + // Left where the path enters the inflated box, still 0.1 beside the side. + assertEquals(0.4, t.last().x(), 1.0E-9); + assertTrue(t.last().z() < 26.0 - 0.3, "before the box: " + t.last()); + } } @Test diff --git a/src/test/java/ru/wilyfox/trajectory/sim/FishingHookTest.java b/src/test/java/ru/wilyfox/trajectory/sim/FishingHookTest.java index 797a192..29f5db2 100644 --- a/src/test/java/ru/wilyfox/trajectory/sim/FishingHookTest.java +++ b/src/test/java/ru/wilyfox/trajectory/sim/FishingHookTest.java @@ -48,9 +48,9 @@ void theHookFallsWithGravityBeforeTheMoveAndInertiaAfter() { Vec3d v = new Vec3d(0.0, 0.2, 0.5); Trajectory path = HOOK.simulate(spawn, v, world); List p = path.points(); - Vec3d first = v.add(0.0, -0.03, 0.0); + Vec3d first = v.add(0.0, -FishingHookFlight.GRAVITY, 0.0); assertEquals(0.0, Math.sqrt(p.get(1).distanceToSqr(spawn.add(first))), 1.0e-12); - Vec3d second = first.scale(0.92).add(0.0, -0.03, 0.0); + Vec3d second = first.scale(0.92).add(0.0, -FishingHookFlight.GRAVITY, 0.0); assertEquals(0.0, Math.sqrt(p.get(2).distanceToSqr(p.get(1).add(second))), 1.0e-12); } @@ -59,10 +59,12 @@ void nearABlockTheSpeedBecomesTheSquaredDistance() { TestWorld world = TestWorld.floorAt(64.0); Trajectory path = HOOK.simulate(new Vec3d(0.5, 64.5, 0.5), new Vec3d(0, -0.9, 0), world); List p = path.points(); - // Ray meets the floor 0.5 below: speed 0.25, then gravity: down 0.28, short of the floor. - assertEquals(64.22, p.get(1).y(), 1.0e-9); - // Next: 0.2576 down along the ray meets the floor 0.22 below: speed 0.0484, then gravity. - assertEquals(64.22 - 0.0484 - 0.03, p.get(2).y(), 1.0e-9); + // Ray meets the floor 0.5 below: speed 0.25, then gravity (0.03): short of the floor. + double y1 = 64.5 - 0.25 - FishingHookFlight.GRAVITY; + assertEquals(y1, p.get(1).y(), 1.0e-9); + // Next: the ray meets the floor about 0.22 below: speed is that squared, then gravity. + double gap = y1 - 64.0; + assertEquals(y1 - gap * gap - FishingHookFlight.GRAVITY, p.get(2).y(), 1.0e-9); } @Test diff --git a/src/test/java/ru/wilyfox/trajectory/sim/NearestEntityHitTest.java b/src/test/java/ru/wilyfox/trajectory/sim/NearestEntityHitTest.java index 4fdd93c..35d3f9f 100644 --- a/src/test/java/ru/wilyfox/trajectory/sim/NearestEntityHitTest.java +++ b/src/test/java/ru/wilyfox/trajectory/sim/NearestEntityHitTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; +import ru.wilyfox.trajectory.sim.compat.VanillaRules; /** * {@code ProjectileUtil.getEntityHitResult} with a margin, as throwables, fireworks, the fishing @@ -32,7 +33,10 @@ void locationIsWhereTheSegmentEntersTheInflatedBox() { assertEquals(0.0, hit.location().x(), EPS); assertEquals(1.0, hit.location().y(), EPS); // Arrows report the entry into the real box instead. - ArrowFlight.Hit arrow = ArrowFlight.entityHits(world, from, to, AREA, MARGIN, false).getFirst(); + ArrowFlight.Hit arrow = + ArrowFlight.entityHits( + world, from, to, AREA, MARGIN, false, VanillaRules.ARROW_MARGIN_HIT_ON_SURFACE) + .getFirst(); assertEquals(-0.3, arrow.location().z(), EPS); } @@ -50,7 +54,10 @@ void marginHitCountsWithoutTheRayToTheCenter() { assertNotNull(hit); assertEquals(0.5, hit.location().x(), EPS); assertEquals(-0.6, hit.location().z(), EPS); - assertTrue(ArrowFlight.entityHits(world, from, to, AREA, MARGIN, false).isEmpty()); + assertTrue( + ArrowFlight.entityHits( + world, from, to, AREA, MARGIN, false, VanillaRules.ARROW_MARGIN_HIT_ON_SURFACE) + .isEmpty()); } @Test diff --git a/stonecutter.gradle.kts b/stonecutter.gradle.kts index 7488191..23a4379 100644 --- a/stonecutter.gradle.kts +++ b/stonecutter.gradle.kts @@ -9,6 +9,22 @@ stonecutter parameters { properties { tags(current.version) } + + // 26.3 moved the GPU API from com.mojang.blaze3d into com.mojang.renderpearl.api. Sources keep + // the 26.2 names; the swap covers imports and mixin descriptors alike. + val renderpearl = current.parsed >= "26.3" + for ((old, new) in listOf( + "com.mojang.blaze3d.buffers.GpuBuffer" to "com.mojang.renderpearl.api.buffers.GpuBuffer", + "com.mojang.blaze3d.systems.RenderPass" to "com.mojang.renderpearl.api.commands.RenderPass", + "com.mojang.blaze3d.pipeline.RenderPipeline" to "com.mojang.renderpearl.api.pipeline.RenderPipeline", + "com.mojang.blaze3d.pipeline.DepthStencilState" to "com.mojang.renderpearl.api.pipeline.DepthStencilState", + "com.mojang.blaze3d.platform.CompareOp" to "com.mojang.renderpearl.api.pipeline.CompareOp", + )) { + replacements { + string(renderpearl) { replace(old, new) } + string(renderpearl) { replace(old.replace('.', '/'), new.replace('.', '/')) } + } + } } // Formatting: google-java-format over every Java source. Spotless is not used, because it @@ -33,7 +49,7 @@ val javaSources = fileTree(rootDir) { include("src/**/*.java") // Version seams hold Stonecutter conditions (`//? if`), which google-java-format would turn // into plain comments (`// ? if`). - exclude("src/main/java/ru/wilyfox/trajectory/compat/**") + exclude("src/main/java/ru/wilyfox/trajectory/**/compat/**") } fun registerFormat(name: String, description: String, vararg mode: String) = diff --git a/stonecutter.properties.toml b/stonecutter.properties.toml index e15708a..068e564 100644 --- a/stonecutter.properties.toml +++ b/stonecutter.properties.toml @@ -1,9 +1,19 @@ -mod.version = "1.0.0" +mod.version = "1.1.0-dev.1" mod.group = "ru.wilyfox.trajectory" mod.archives = "trajectory-projected" deps.fabric_loader = "0.19.3" +["26.1.2"] +# Built against 26.1.2; the same jar runs on 26.1 and 26.1.1. +mod.mc_label = "26.1.x" +mod.mc_compat = "~26.1" +deps.fabric_api = "0.155.3+26.1.2" +# The newest Fabric API for 26.1, so the jar loads there. +deps.fabric_api_min = "0.145.1" +deps.sodium = "mc26.1.2-0.9.2-fabric" +deps.iris = "1.11.4+26.1-fabric" + ["26.2"] # Shown in the jar's version and name. mod.mc_label = "26.2" @@ -15,3 +25,11 @@ deps.fabric_api_min = "0.161.0" # Optional rendering mods for local runs only (-PwithSodium, -PwithIris). deps.sodium = "mc26.2-0.9.2-fabric" deps.iris = "1.11.4+26.2-fabric" + +["26.3"] +mod.mc_label = "26.3" +mod.mc_compat = "~26.3" +deps.fabric_api = "0.166.2+26.3" +deps.fabric_api_min = "0.166.2" +deps.sodium = "mc26.3-0.9.2-fabric" +deps.iris = "1.11.7+26.3-fabric"