From 1cb2cc4cc6d616713328f513267ebbea0968e1e0 Mon Sep 17 00:00:00 2001 From: Algent Date: Fri, 28 Aug 2026 10:48:19 +0300 Subject: [PATCH] refactor: port redstone interaction unit to java --- JAVA_MIGRATION.md | 36 +- JAVA_MIGRATION_DIVERGENCES.md | 45 +++ JAVA_MIGRATION_HANDOFF.md | 27 +- JAVA_MIGRATION_PROFILE.md | 22 +- .../multipart/IFaceRedstonePart.java | 7 + .../multipart/IMaskedRedstonePart.java | 7 + .../multipart/IRedstoneConnector.java | 9 + .../multipart/IRedstoneConnectorBlock.java | 11 + .../codechicken/multipart/IRedstonePart.java | 11 + .../codechicken/multipart/IRedstonePart.scala | 310 ------------------ .../codechicken/multipart/IRedstoneTile.java | 7 + .../multipart/RedstoneInteractions$.java | 151 +++++++++ .../multipart/RedstoneInteractions.java | 58 ++++ 13 files changed, 366 insertions(+), 335 deletions(-) create mode 100644 src/main/scala/codechicken/multipart/IFaceRedstonePart.java create mode 100644 src/main/scala/codechicken/multipart/IMaskedRedstonePart.java create mode 100644 src/main/scala/codechicken/multipart/IRedstoneConnector.java create mode 100644 src/main/scala/codechicken/multipart/IRedstoneConnectorBlock.java create mode 100644 src/main/scala/codechicken/multipart/IRedstonePart.java delete mode 100644 src/main/scala/codechicken/multipart/IRedstonePart.scala create mode 100644 src/main/scala/codechicken/multipart/IRedstoneTile.java create mode 100644 src/main/scala/codechicken/multipart/RedstoneInteractions$.java create mode 100644 src/main/scala/codechicken/multipart/RedstoneInteractions.java diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 050475c..037b8cc 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -24,8 +24,8 @@ No trustworthy tool will produce a maintainable Java port automatically. A decom ## Current status The binary and source-level consumer audits, low-coupling Phase 3 queue, audit-derived immediate compatibility gate, -and focused pre-optimization profile are complete. Phase 4 can now begin with the measured `TileMultipart` traversal -path; see `JAVA_MIGRATION_PROFILE.md`. +focused profile, first traversal optimization, and complete redstone interaction helper unit are complete. Phase 4 +continues with `MicroRecipe`'s non-local-return category; see `JAVA_MIGRATION_PROFILE.md`. That audit found and this branch has now repaired one existing regression: Schematica 1.12.6 reflects the original private `MultiPartRegistry$` field `codechicken$multipart$MultiPartRegistry$$typeMap` and casts it to a Scala mutable map. The @@ -322,18 +322,18 @@ and the already-ported registry again supports Schematica. ### Phase 4 — Convert measured hot paths -- [ ] Characterize result ordering, callback timing, early exits, and edge cases before changing traversal code. -- [ ] Rewrite `TileMultipart.updateEntity()` as allocation-free indexed or array traversal. +- [x] Characterize result ordering, callback timing, early exits, and edge cases before changing traversal code. +- [x] Rewrite `TileMultipart` update/operate traversal without per-call collection allocation. - [ ] Rewrite redstone queries without closure allocation or `IntRef` boxing. - [ ] Replace non-local returns in slot/recipe scans with ordinary Java control flow. - [ ] Use fastutil only where profiling and data shape justify it. -- [ ] Re-profile the same scenarios and record both improvements and regressions. +- [x] Re-profile the same scenarios and record both improvements and regressions. -Status: ready to start. The compatibility gate and initial profile are complete. First freeze `operate` behavior when -callbacks add or remove parts, then remove the measured per-traversal `ArrayList`/array/wrapper materialization while -retaining the public Scala `Seq` and `operate(Function1)` ABI. Re-run the focused profile immediately. The next broader -unit is the whole `IRedstonePart.scala` file: its six related traits and load-bearing `RedstoneInteractions$` must be -characterized and ported together. +Status: active. `operate` now preserves its captured-sequence mutation semantics without collection materialization, +and the six-interface `IRedstonePart`/`RedstoneInteractions$` unit is ported with its class list and descriptors intact. +The comparison proves its allocation is owned by `scalatraits/TRedstoneTile.scala`, so that part waits for Phase 5. +Next characterize and port `MicroRecipe.scala`, replacing its closure-backed scans and non-local returns with ordinary +Java loops. Exit condition: identified steady-state Scala allocation sites are removed with compatible results. @@ -402,7 +402,7 @@ The work should move from low to high risk while keeping a buildable mixed-langu Extensive tests are both possible and recommended here. Their purpose is not to prove that the current Scala behavior is ideal; it is to make its observable behavior explicit before translation, so every later difference is intentional. The repository now has a Java-8-compatible JUnit Jupiter suite and a small Forge integration runner. The current -baseline is 130 plain-JVM tests and 28 Forge server tests. Minecraft 1.7.10 does not provide the modern GameTest +baseline is 139 plain-JVM tests and 31 Forge server tests. Minecraft 1.7.10 does not provide the modern GameTest framework, so game-dependent coverage continues through the existing narrow Forge harness rather than a second test framework. @@ -643,3 +643,17 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec allocates 80.5 bytes. CPU and allocation sites point to `TileMultipart.parts()` collection copies and Scala redstone `IntRef`/closure traversal. Full methodology and rerun commands are in `JAVA_MIGRATION_PROFILE.md`. - The expanded baseline is 130 plain-JVM tests and 28 Forge server tests, all passing. + +### 2026-08-28 + +- Ported all six interfaces and `RedstoneInteractions` from `IRedstonePart.scala` as one unit. The emitted class list is + unchanged, every public descriptor is unchanged, and `RedstoneInteractions$.MODULE$` remains the implementation + singleton behind the static façade. +- Added six plain-JVM tests for interface shape, façade/companion members, maps, part-mask precedence, connector routing, + and neighbor coordinate transforms, plus three Forge tests for initialized vanilla blocks, world power routing, the + redstone-wire metadata fallback, and generated `IRedstoneTile` selection. +- Re-profiled immediately before and after the port. Allocation stayed at roughly 4.02 GB / 80.5 B per generated + three-query iteration, and JFR retained the same `TRedstoneTile` Scala closure/iterator sites. That cost belongs to + the Phase 5 generated-trait conversion, not this helper unit. +- Chose `MicroRecipe.scala` as the next independent Phase 4 unit because its nested collection scans compile early + exits into `NonLocalReturnControl`; characterize all five recipe paths and precedence before porting it. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index 2273120..6f4a25d 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -1266,3 +1266,48 @@ failure rather than a silent one, but it will recur in every remaining renderer - What stays manual, and it is everything this class actually does: static block rendering, dynamic part rendering, the breaking overlay on the struck part, inventory rendering, and the render id being claimed exactly once. None of it can run without a client, so all of it is on the checklist. + +## 2026-08-28 — IRedstonePart and RedstoneInteractions Java port + +The complete source unit: six abstract interfaces plus the routing singleton. ProjectRed, ProjectBlue, WR-CBE, +Extra Utilities, OpenComputers and AE2 consume this surface; ProjectRed also reads `RedstoneInteractions$.MODULE$` +directly, so the companion cannot be collapsed into a static utility class. + +### Observable behavior + +No known divergence. Plain, face, and custom-mask parts retain the same precedence and bit masks. Connector tiles +still win over connector blocks, which still win over vanilla handling. Neighbor lookups retain the same coordinate +offset and opposite-side transform. Full-connect blocks, wire/comparator visual masks, repeater orientation, the +redstone-wire metadata fallback, and `Block.canConnectRedstone` retain their existing branches. Java uses +`Objects.equals` where Scala used null-safe `==`. + +`vanillaSideMap`, `sideVanillaMap`, and `fullVanillaBlocks` remain singleton-owned objects returned by identity from +both published classes. `fullVanillaBlocks` deliberately remains a `scala.collection.immutable.Set` so its +descriptor and existing Scala consumers do not change. + +### Supported JVM API + +The emitted class list is unchanged: the six interface classes, `RedstoneInteractions`, and +`RedstoneInteractions$`. Every public member and descriptor is unchanged. `RedstoneInteractions` remains the static +façade and `RedstoneInteractions$.MODULE$` remains the implementation instance. The Java façade necessarily has a +private constructor where Scala's static-forwarder class emitted none; no consumer references constructors on either +class. + +The six Scala traits contained only abstract members, so they emitted no `$class` helpers and need no compatibility +bridges. Their Scala signatures disappear, but inheritance and JVM method descriptors are identical. + +### Performance boundary + +The fresh Scala baseline measured 80.4 B per generated redstone three-query iteration; the Java result measured +80.5 B. Post-port JFR still attributes the work to Scala `List.foreach`, `Iterator.foreach`, `PartMap.edgeBetween`, and +the generated strong-power closure in `scalatraits/TRedstoneTile.scala`. This port therefore claims no performance +gain. Removing that allocation requires the later `registerJavaTrait` conversion and is explicitly deferred. + +### Validation + +- `RedstoneInteractionsCharacterizationTest`: 6 tests, covering every interface shape and pure routing branch. +- Complete plain-JVM suite: 139 tests, 0 failures, 0 errors. +- Java 8 Forge dedicated-server suite: 31 tests, 0 failures, 0 errors; three tests cover initialized vanilla state, + actual world routing, and a generated redstone tile. +- Clean `spotlessApply checkstyleTest build`: passing. +- Class list and public members diffed against the pre-port build; no characterization assertion changed. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 932cc01..1936ea3 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -12,7 +12,7 @@ what breaks, and what is left. The other documents hold the reasoning. | `JAVA_MIGRATION_MANUAL_CHECKS.md` | What no automated test can cover, and must be checked by hand in a client | | `JAVA_MIGRATION_PROFILE.md` | The focused baseline, first measured result, findings, and exact rerun command | -Branch: `algent/java`. Base: `master`. 64 commits including the first profiled optimization. +Branch: `algent/java`. Base: `master`. 66 commits including the redstone interaction unit. ## The one rule that matters @@ -66,7 +66,7 @@ awk -F'"' '/ 0) { - var m = world.getIndirectPowerLevelTo(x, y, z, side ^ 1) - if (m < 15 && block == Blocks.redstone_wire) - m = - Math.max(m, world.getBlockMetadata(x, y, z)) // painful vanilla kludge - return m - } - return 0 - } - - def vanillaToSide(vside: Int) = sideVanillaMap(vside + 1) - - /** Get the connection mask of the block on side of (x, y, z). - * @param power, - * whether the connection mask is for signal transfer or visual connection. - * (some blocks accept power without visual connection) - */ - def otherConnectionMask( - world: IBlockAccess, - x: Int, - y: Int, - z: Int, - side: Int, - power: Boolean - ): Int = - getConnectionMask( - world, - x + offsetsXForSide(side), - y + offsetsYForSide(side), - z + offsetsZForSide(side), - side ^ 1, - power - ) - - /** Get the connection mask of part on side - */ - def connectionMask(p: TMultiPart, side: Int): Int = { - if ( - p.isInstanceOf[IRedstonePart] && p - .asInstanceOf[IRedstonePart] - .canConnectRedstone(side) - ) { - if (p.isInstanceOf[IFaceRedstonePart]) { - val fside = p.asInstanceOf[IFaceRedstonePart].getFace - if ((side & 6) == (fside & 6)) - return 0x10 - - return 1 << rotationTo(side & 6, fside) - } else if (p.isInstanceOf[IMaskedRedstonePart]) { - return p.asInstanceOf[IMaskedRedstonePart].getConnectionMask(side) - } - return 0x1f - } - return 0 - } - - /** @param power - * If true, don't test canConnectRedstone on blocks, just get a power - * transmission mask rather than a visual connection - */ - def getConnectionMask( - world: IBlockAccess, - x: Int, - y: Int, - z: Int, - side: Int, - power: Boolean - ): Int = { - val tile = world.getTileEntity(x, y, z) - if (tile.isInstanceOf[IRedstoneConnector]) - return tile.asInstanceOf[IRedstoneConnector].getConnectionMask(side) - - val block = world.getBlock(x, y, z) - if (block.isInstanceOf[IRedstoneConnectorBlock]) - return block - .asInstanceOf[IRedstoneConnectorBlock] - .getConnectionMask(world, x, y, z, side) - - return vanillaConnectionMask(block, world, x, y, z, side, power) - } - - /** Returns the connection mask for a vanilla block - */ - def vanillaConnectionMask( - block: Block, - world: IBlockAccess, - x: Int, - y: Int, - z: Int, - side: Int, - power: Boolean - ): Int = { - if (fullVanillaBlocks(block)) - return 0x1f - - /** so that these can be conducted to from face parts on the other side of - * the block. Due to vanilla's in adequecy with redstone/logic on walls - */ - if ( - block == Blocks.redstone_wire || block == Blocks.powered_comparator || block == Blocks.unpowered_comparator - ) { - if (side != 0) - return if (power) 0x1f else 4 - - return 0 - } - - val vside = vanillaSideMap(side) - if ( - block == Blocks.powered_repeater || block == Blocks.unpowered_repeater - ) // stupid minecraft hardcodes - { - val meta = world.getBlockMetadata(x, y, z) - if (vside == (meta & 3) || vside == Direction.rotateOpposite(meta & 3)) - return if (power) 0x1f else 4 - - return 0 - } - - if ( - power || block.canConnectRedstone(world, x, y, z, vside) - ) // some blocks accept power without visualising connections - return 0x1f - - return 0 - } -} diff --git a/src/main/scala/codechicken/multipart/IRedstoneTile.java b/src/main/scala/codechicken/multipart/IRedstoneTile.java new file mode 100644 index 0000000..00f2703 --- /dev/null +++ b/src/main/scala/codechicken/multipart/IRedstoneTile.java @@ -0,0 +1,7 @@ +package codechicken.multipart; + +/** Internal interface for multipart tiles hosting {@link IRedstonePart}. */ +public interface IRedstoneTile extends IRedstoneConnector { + + int openConnections(int side); +} diff --git a/src/main/scala/codechicken/multipart/RedstoneInteractions$.java b/src/main/scala/codechicken/multipart/RedstoneInteractions$.java new file mode 100644 index 0000000..eb714ab --- /dev/null +++ b/src/main/scala/codechicken/multipart/RedstoneInteractions$.java @@ -0,0 +1,151 @@ +package codechicken.multipart; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Objects; + +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Direction; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import codechicken.lib.vec.Rotation; +import scala.collection.JavaConversions; +import scala.collection.immutable.Set; + +/** Scala-compatible singleton carrying the redstone interaction implementation. */ +public final class RedstoneInteractions$ { + + public static final RedstoneInteractions$ MODULE$ = new RedstoneInteractions$(); + + private final int[] vanillaSideMap = { -2, -1, 0, 2, 3, 1 }; + private final int[] sideVanillaMap = { 1, 2, 5, 3, 4 }; + private final Set fullVanillaBlocks = JavaConversions.asScalaSet( + new HashSet<>( + Arrays.asList( + Blocks.redstone_torch, + Blocks.unlit_redstone_torch, + Blocks.lever, + Blocks.stone_button, + Blocks.wooden_button, + Blocks.redstone_block))) + .toSet(); + + private RedstoneInteractions$() {} + + public int[] vanillaSideMap() { + return vanillaSideMap; + } + + public int[] sideVanillaMap() { + return sideVanillaMap; + } + + public Set fullVanillaBlocks() { + return fullVanillaBlocks; + } + + public int getPowerTo(TMultiPart part, int side) { + TileMultipart tile = part.tile(); + return getPowerTo( + tile.getWorldObj(), + tile.xCoord, + tile.yCoord, + tile.zCoord, + side, + ((IRedstoneTile) tile).openConnections(side) & connectionMask(part, side)); + } + + public int getPowerTo(World world, int x, int y, int z, int side, int mask) { + return getPower( + world, + x + net.minecraft.util.Facing.offsetsXForSide[side], + y + net.minecraft.util.Facing.offsetsYForSide[side], + z + net.minecraft.util.Facing.offsetsZForSide[side], + side ^ 1, + mask); + } + + public int getPower(World world, int x, int y, int z, int side, int mask) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof IRedstoneConnector) { + return ((IRedstoneConnector) tile).weakPowerLevel(side, mask); + } + + Block block = world.getBlock(x, y, z); + if (block instanceof IRedstoneConnectorBlock) { + return ((IRedstoneConnectorBlock) block).weakPowerLevel(world, x, y, z, side, mask); + } + + if ((vanillaConnectionMask(block, world, x, y, z, side, true) & mask) > 0) { + int power = world.getIndirectPowerLevelTo(x, y, z, side ^ 1); + if (power < 15 && Objects.equals(block, Blocks.redstone_wire)) { + power = Math.max(power, world.getBlockMetadata(x, y, z)); + } + return power; + } + return 0; + } + + public int vanillaToSide(int vanillaSide) { + return sideVanillaMap[vanillaSide + 1]; + } + + public int otherConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) { + return getConnectionMask( + world, + x + net.minecraft.util.Facing.offsetsXForSide[side], + y + net.minecraft.util.Facing.offsetsYForSide[side], + z + net.minecraft.util.Facing.offsetsZForSide[side], + side ^ 1, + power); + } + + public int connectionMask(TMultiPart part, int side) { + if (!(part instanceof IRedstonePart) || !((IRedstonePart) part).canConnectRedstone(side)) { + return 0; + } + if (part instanceof IFaceRedstonePart) { + int face = ((IFaceRedstonePart) part).getFace(); + return (side & 6) == (face & 6) ? 0x10 : 1 << Rotation.rotationTo(side & 6, face); + } + if (part instanceof IMaskedRedstonePart) { + return ((IMaskedRedstonePart) part).getConnectionMask(side); + } + return 0x1F; + } + + public int getConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof IRedstoneConnector) { + return ((IRedstoneConnector) tile).getConnectionMask(side); + } + + Block block = world.getBlock(x, y, z); + if (block instanceof IRedstoneConnectorBlock) { + return ((IRedstoneConnectorBlock) block).getConnectionMask(world, x, y, z, side); + } + return vanillaConnectionMask(block, world, x, y, z, side, power); + } + + public int vanillaConnectionMask(Block block, IBlockAccess world, int x, int y, int z, int side, boolean power) { + if (fullVanillaBlocks.contains(block)) { + return 0x1F; + } + + if (Objects.equals(block, Blocks.redstone_wire) || Objects.equals(block, Blocks.powered_comparator) + || Objects.equals(block, Blocks.unpowered_comparator)) { + return side == 0 ? 0 : power ? 0x1F : 4; + } + + int vanillaSide = vanillaSideMap[side]; + if (Objects.equals(block, Blocks.powered_repeater) || Objects.equals(block, Blocks.unpowered_repeater)) { + int metadata = world.getBlockMetadata(x, y, z) & 3; + return vanillaSide == metadata || vanillaSide == Direction.rotateOpposite[metadata] ? power ? 0x1F : 4 : 0; + } + + return power || block.canConnectRedstone(world, x, y, z, vanillaSide) ? 0x1F : 0; + } +} diff --git a/src/main/scala/codechicken/multipart/RedstoneInteractions.java b/src/main/scala/codechicken/multipart/RedstoneInteractions.java new file mode 100644 index 0000000..730defa --- /dev/null +++ b/src/main/scala/codechicken/multipart/RedstoneInteractions.java @@ -0,0 +1,58 @@ +package codechicken.multipart; + +import net.minecraft.block.Block; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; + +import scala.collection.immutable.Set; + +/** Static forwarders for Java and existing bytecode; implementation remains on {@link RedstoneInteractions$}. */ +public final class RedstoneInteractions { + + private RedstoneInteractions() {} + + public static int[] vanillaSideMap() { + return RedstoneInteractions$.MODULE$.vanillaSideMap(); + } + + public static int[] sideVanillaMap() { + return RedstoneInteractions$.MODULE$.sideVanillaMap(); + } + + public static Set fullVanillaBlocks() { + return RedstoneInteractions$.MODULE$.fullVanillaBlocks(); + } + + public static int getPowerTo(TMultiPart part, int side) { + return RedstoneInteractions$.MODULE$.getPowerTo(part, side); + } + + public static int getPowerTo(World world, int x, int y, int z, int side, int mask) { + return RedstoneInteractions$.MODULE$.getPowerTo(world, x, y, z, side, mask); + } + + public static int getPower(World world, int x, int y, int z, int side, int mask) { + return RedstoneInteractions$.MODULE$.getPower(world, x, y, z, side, mask); + } + + public static int vanillaToSide(int vanillaSide) { + return RedstoneInteractions$.MODULE$.vanillaToSide(vanillaSide); + } + + public static int otherConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) { + return RedstoneInteractions$.MODULE$.otherConnectionMask(world, x, y, z, side, power); + } + + public static int connectionMask(TMultiPart part, int side) { + return RedstoneInteractions$.MODULE$.connectionMask(part, side); + } + + public static int getConnectionMask(IBlockAccess world, int x, int y, int z, int side, boolean power) { + return RedstoneInteractions$.MODULE$.getConnectionMask(world, x, y, z, side, power); + } + + public static int vanillaConnectionMask(Block block, IBlockAccess world, int x, int y, int z, int side, + boolean power) { + return RedstoneInteractions$.MODULE$.vanillaConnectionMask(block, world, x, y, z, side, power); + } +}