From 533dc6a11e447aa91778d37ce3e2284e843a17de Mon Sep 17 00:00:00 2001 From: Algent Date: Fri, 4 Sep 2026 23:48:10 +0200 Subject: [PATCH] feat: add Java part traversal --- JAVA_MIGRATION.md | 16 ++- JAVA_MIGRATION_CONSUMER_AUDIT.md | 29 ++++- JAVA_MIGRATION_HANDOFF.md | 35 +++--- README.md | 1 + docs/api/PART_TRAVERSAL.md | 101 ++++++++++++++++++ docs/migration/HISTORY.md | 22 ++++ .../TileMultipartLifecycleFunctionalTest.java | 36 +++++++ .../codechicken/multipart/TileMultipart.java | 46 +++++++- .../TileMultipartCharacterizationTest.java | 93 ++++++++++++++++ .../examples/PartTraversalExample.java | 27 +++++ 10 files changed, 383 insertions(+), 23 deletions(-) create mode 100644 docs/api/PART_TRAVERSAL.md create mode 100644 src/test/java/codechicken/multipart/examples/PartTraversalExample.java diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 4b4e038..f37e53a 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -522,15 +522,15 @@ changes separate from mechanical compiler extraction, and do not add a deprecati #### 9.1 — Scala-typed signatures -Each row keeps its existing descriptor for binary compatibility and gains a Java-shaped sibling. Two rows already have -their sibling and only need the annotation and javadoc. +Each row keeps its existing descriptor for binary compatibility and gains a Java-shaped sibling. The registry +`registerParts` sibling already exists and still needs the annotation and javadoc. | Deprecate | Java-shaped replacement | Notes | | --- | --- | --- | -| `TileMultipart.partList(): scala.collection.Seq` | `jPartList(): java.util.List` | Sibling already exists | +| `TileMultipart.partList(): scala.collection.Seq` | `jPartList(): java.util.List` | Getter deprecated; captured-sequence view documented in the [guide and compiling example](docs/api/PART_TRAVERSAL.md). Setter/loading migrations remain separate | | `MultiPartRegistry.registerParts(IPartFactory2, scala.collection.Seq)` | `registerParts(IPartFactory2, String...)` | Sibling already exists | | `MicroMaterialRegistry.getIdMap(): scala.Tuple2[]` | `materialCount(): int` plus existing `materialName(int)` and `getMaterial(int)` | Implemented with static/companion deprecation; [guide and compiling example](docs/api/MATERIAL_ENUMERATION.md). Consumer release/adoption remains pending | -| `TileMultipart.operate(scala.Function1)` | `forEachPart(java.util.function.Consumer)` | Preserve the existing skip-unbound-part behavior | +| `TileMultipart.operate(scala.Function1)` | `forEachPart(java.util.function.Consumer)` | Implemented through the legacy virtual hook; preserves captured traversal, detached-part filtering and callback failures. Lifecycle still calls `operate` | | `TileMultipart.occlusionTest(scala.collection.Seq, TMultiPart)` | `occlusionTest(Collection, TMultiPart)` | | | `TileMultipart.loadParts(scala.collection.Iterable)` | `loadParts(Collection)` | Schematica and GuideNH reflect the Scala descriptor; see Phase 10 | | `TileMultipart.partList_$eq(scala.collection.Seq)` | `setPartList(List)` | GuideNH reflects the `_$eq` name; see Phase 10 | @@ -545,6 +545,8 @@ same-name overload there invites a silent wrong-overload bind. - [ ] Add the missing Java-shaped siblings over shared behavior, preserving legacy override dispatch and avoiding recursive forwarding as required by the API migration design. - [x] Add and document `materialCount()` with existing indexed lookups; retain and deprecate both `getIdMap()` entries. +- [x] Document `jPartList()` and add `forEachPart(Consumer)`; deprecate the legacy getter/callback entries while retaining + their override dispatch. JVM and generated-tile Forge cases cover the [documented contract](docs/api/PART_TRAVERSAL.md). - [ ] Mark all nine rows `@Deprecated` with javadoc naming the replacement. - [ ] Confirm every original descriptor still exists in the ABI fixture after the change. - [ ] Document the supported API with compiling usage examples and an old-to-new migration guide. Validate Java @@ -560,9 +562,13 @@ deprecation, and no new dependency for a marker annotation. Verified against all 28 consumer checkouts as having **zero external callers**: `TileMultipart.addPart_impl`, `addPart_do`, `remPart_impl`, `writeAddPart`, `partAdded`, `partRemoved`, `from`, -`copyFrom`, `loadFrom`, `setValid`, `getOrConvertTile2`, `operate`; `MicroMaterialRegistry.setupIDMap`, +`copyFrom`, `loadFrom`, `setValid`, `getOrConvertTile2`; `MicroMaterialRegistry.setupIDMap`, `calcMaxCuttingStrength`, `loadIcons`, `writeIDMap`, `readIDMap`. +`TileMultipart.operate` also has no audited external callers, but remains a supported legacy override hook. It is +deprecated for callers in favor of `forEachPart`; lifecycle dispatch still uses it. Keep that explicit contract rather +than applying the internal-only marker to it. The new convenience method does not replace the lifecycle override hook. + Two similar-looking members **are** externally load-bearing and must not be marked internal: | Member | Consumer | Call site | diff --git a/JAVA_MIGRATION_CONSUMER_AUDIT.md b/JAVA_MIGRATION_CONSUMER_AUDIT.md index 7d64466..2f17c1c 100644 --- a/JAVA_MIGRATION_CONSUMER_AUDIT.md +++ b/JAVA_MIGRATION_CONSUMER_AUDIT.md @@ -491,14 +491,20 @@ behavior: ## Java API adoption ledger This ledger tracks migration of a specific legacy contract, not completion of an entire consumer's migration. -The FMP material-enumeration addition is implemented on `algent/java`, with the -[documented Java replacement](docs/api/MATERIAL_ENUMERATION.md) and a compiling example. It is not yet a released -minimum dependency version. Unlisted contracts remain governed by the inventories above. +Material enumeration and tile collection/traversal access are implemented on `algent/java`, with +[material](docs/api/MATERIAL_ENUMERATION.md) and [part traversal](docs/api/PART_TRAVERSAL.md) guides and compiling Java +examples. Neither addition is yet tied to a released minimum dependency version. Unlisted contracts remain governed +by the inventories above. | Legacy contract | Consumer and inspected source | Supported replacement | Consumer migration/release | Target-pack adoption and removal gate | | --- | --- | --- | --- | --- | | `MicroMaterialRegistry.getIdMap(): scala.Tuple2[]` | UtilitiesInExcess `3e107a1fe9bc15fcb6a808242ffda1354dac7c3a`: `FMPRecipeLoader.run`, `UEMultipartItem.getSubItems` | `materialCount()` with `materialName(int)` and, when needed, `getMaterial(int)` | Source patch and first released version pending; checkout used as reference only | No migrated pack version verified; retain the bridge | | `MicroMaterialRegistry.getIdMap(): scala.Tuple2[]` | Extra Utilities 1.2.12 decompiled reference: both NEI microblock handlers and `multipart.microblock.ItemMicroBlock` | Same ID-based Java enumeration | No editable upstream consumer in scope; retirement/replacement remains pending | Verify Extra Utilities is absent and its replacement uses the new API before retiring this dependency | +| `TileMultipart.partList(): scala.collection.Seq` | ProjectRed `e173952e96a4`: illumination aggregation, packet indices and rendered-part lookup | `jPartList()` with unchanged indices, filters and aggregation | Source patch and release pending; Scala consumer code may remain Scala | No migrated pack version verified; retain the getter and external trait support | +| `TileMultipart.partList(): scala.collection.Seq` | OpenComputers `2c00f79be24b`: cable/print/network searches and aggregation | `jPartList()` with the same search/aggregation semantics | Source patch and release pending | No migrated pack version verified; retain the getter | +| `TileMultipart.partList(): scala.collection.Seq` | AE2 `87f2b3817c2a`: `FMPPlacementHelper.getPart` and `removePart` | Iterate `jPartList()`; retain last-match lookup and removal/break behavior | Source patch and release pending | No migrated pack version verified; retain the getter | +| `TileMultipart.partList(): scala.collection.Seq` | Extra Utilities 1.2.12: multipart renderer iterators | Iterate `jPartList()` without adding detached-part filtering | Retirement/replacement pending | Confirm absence or migration in the target pack before retiring the getter | +| `TileMultipart.partList(): scala.collection.Seq` plus reflective getter/setter/loading | GuideNH `7d8fb44e77b9`: `Ae2ForgeMultipartBridge`, `ForgeMultipartHelpers` | `jPartList()` for reads; Java setter/loading replacements still pending | Read migration alone does not migrate client-tile reconstruction | Retain `partList`, `partList_$eq` and `loadParts` until their separate gates pass | Evidence for the FMP addition is under ignored `run/migration-material-enumeration-reference/`. The original reference-compiled Scala consumer still exercises the companion and tuple-array descriptor. The new compiling Java @@ -508,6 +514,23 @@ they do not establish that an updated UtilitiesInExcess release has shipped or e FMP's own `ItemMicroPart` and `MicroRecipe$` still use the legacy array internally. Their migration, any additional retained companion users, and the other Scala-facing contracts remain separate removal gates. +Tile traversal evidence is under ignored `run/migration-part-traversal-reference/`. Re-scanning the supplied Java/Scala +sources found no FMP `operate` calls/overrides or `forEachPart` name collisions; two unrelated no-argument renderer +`operate()` implementations were excluded. The existing `operate(Function1)` override hook nevertheless remains +supported. The Java convenience delegates through it, while lifecycle callbacks continue calling it directly. +Deprecation is caller guidance, not permission to remove or bypass existing overrides. All 538 frozen pre-change JVM +tests, including the legacy getter/callback subclass cases, run against the addition without recompilation. + +Existing `jPartList()` consumers such as ProjectBlue, BuildCraftCompat, GT5U, WitchingGadgets, MatterManipulator and +UtilitiesInExcess already have Java collection access. They need no rename for this contract. The new `forEachPart` +convenience is not a blanket replacement for their loops: its detached-part filtering can change read/query behavior. +The reference checkouts were not edited, built or counted as released migrations. + +The installed GTNH daily `2026-09-04+719` rescan scanned 241 jars and excluded one FMP jar. Its 27 consumers still +reference the exact same 35 inherited types, 255 members, 76 other types and 20 reflection strings as the frozen +`+678` inventory, compared by full row rather than counts alone. The report is archived with the traversal evidence; +source revisions above remain the inspected checkout revisions, not a claim of source parity with every newer jar. + ## Practical priority for the current branch 1. Keep the existing `+678` ABI fixture as the exact binary floor and correct failures before source cleanup. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 732788e..79f5543 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -16,7 +16,7 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes ## Current state and next target -**535 plain-JVM tests and 238 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **224 Java +**542 plain-JVM tests and 239 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **224 Java files and 9 Scala files / 747 nonblank Scala lines**. The packaged inventory has 443 classes. Review follow-up: restored packet-scheduler callback mutation behavior with the original Scala hash-map traversal, @@ -31,25 +31,32 @@ use, but no override triggering these three regressions was found. All 443 class payloads and 116 generated dumps are retained. The agreed next milestone is the documented consumer-facing Java API, followed by consumer release/adoption and final Scala removal; see the plan's API migration design and Phases 8–10. -Latest API addition: `MicroMaterialRegistry.materialCount()` completes ID-based enumeration with the existing -`materialName(int)` and `getMaterial(int)` methods. Both `getIdMap()` entries are deprecated with unchanged descriptors -and live-array behavior. Two baseline cases were committed first as `9b78099`; three further JVM cases and one Forge -case cover the new API and a compiling Java example. All 532 pre-change compiled tests pass with their recorded -version. The 443 class APIs retain all existing members, with one public static method added; 17 ScalaSignature -payloads, 3,746 existing method bodies and 116 generated dumps are unchanged apart from expected deprecation metadata -and build-version literals. Evidence: `run/migration-material-enumeration-reference/`. +Latest API addition: `TileMultipart.forEachPart(Consumer)` reuses the existing adapter and virtual `operate` hook. +`jPartList()` now documents its captured-sequence view. Both legacy getter/callback entries are deprecated while +retaining their descriptors and bodies. Three baseline tests were committed first as `5c1e760`; four further JVM cases, +a compiling Java example and one Forge generated-tile case cover the new API. All 538 pre-change compiled tests pass +with their recorded version. The 443 class APIs retain all existing members, with one method added; 17 ScalaSignature +payloads, 3,747 existing method bodies and 116 generated dumps are unchanged apart from expected deprecation metadata +and build-version literals. Evidence: `run/migration-part-traversal-reference/`. -The [material enumeration guide](docs/api/MATERIAL_ENUMERATION.md) documents lifecycle, server ID ordering and failure -boundaries. The consumer audit's adoption ledger records the inspected UtilitiesInExcess revision and Extra Utilities -1.2.12; their source migrations, releases and pack adoption remain pending. The supplied checkouts remain reference-only. +The [part traversal guide](docs/api/PART_TRAVERSAL.md) covers ownership, callback mutation/reentrancy, failure timing, +detached/rebound parts and override dispatch. Lifecycle still uses `operate`; overriding `forEachPart` alone does not +intercept lifecycle callbacks. The adoption ledger names five legacy-getter consumers and the remaining GuideNH +setter/loading gap. The installed `+719` pack rescan matches every member/type/reflection row in the `+678` floor: +27 consumers, 35 inherited types, 255 members, 76 other types and 20 strings. Consumer releases/adoption remain pending. + +`MicroMaterialRegistry.materialCount()` and its indexed lookups are also complete, with both `getIdMap()` entries +deprecated; see the [material enumeration guide](docs/api/MATERIAL_ENUMERATION.md) and previous history entry. +The supplied consumer checkouts remain reference-only. **Next priority: close the Java API gaps in Phases 2 and 9 and map consumer migrations in Phase 10.** Reuse the existing Java surface; supply missing capabilities, precise contracts, migration guidance and compiling examples. Cover subclass/override behavior and generated extensions as well as ordinary calls. ProjectRed's illuminated microblocks are the representative external extension case. Consumer mods may remain Scala internally while adopting this API. -The next bounded API candidate is `TileMultipart` collection/traversal access, preserving legacy getter and callback -overrides, captured-sequence mutation behavior and detached-part filtering. Do not repeat material enumeration as an -unimplemented gap or treat its FMP-side completion as consumer adoption. +The next bounded API candidate is Java tile loading/state access: `loadParts(Collection)` and +`setPartList(List)`, with distinct binding/lifecycle contracts and preserved legacy setter/loading dispatch. +GuideNH's client-tile reconstruction makes the old descriptors load-bearing. Do not repeat material enumeration or +tile read/traversal access as unimplemented gaps, or treat FMP-side completion as consumer adoption. Pause mechanical extraction of retained Scala shells unless it enables that API, fixes a demonstrated issue or has a measured benefit. `ScalaSignature.ClassSymbolRef.info` remains an optional bounded extraction, not the default next diff --git a/README.md b/README.md index 9bdda68..dda12df 100644 --- a/README.md +++ b/README.md @@ -18,3 +18,4 @@ Implementation of all parts of the API should be clean and easy in Java. The min Java API migration guides: * [Enumerating microblock materials](docs/api/MATERIAL_ENUMERATION.md), including a compiling example and legacy API replacements. +* [Reading and visiting multipart parts](docs/api/PART_TRAVERSAL.md), including collection ownership, callback behavior and legacy overrides. diff --git a/docs/api/PART_TRAVERSAL.md b/docs/api/PART_TRAVERSAL.md new file mode 100644 index 0000000..2f72e1c --- /dev/null +++ b/docs/api/PART_TRAVERSAL.md @@ -0,0 +1,101 @@ +# Reading and visiting multipart parts from Java + +Use `TileMultipart.jPartList()` for ordered collection access. The `algent/java` branch also adds +`forEachPart(Consumer)` for callbacks that skip detached parts. Consumers using the new method must require +an FMP release containing it; no minimum released version is established yet. Both methods work on generated tiles. + +## Examples + +Read all part types in list order: + +```java +public static List partTypes(TileMultipart tile) { + List types = new ArrayList<>(); + for (TMultiPart part : tile.jPartList()) { + types.add(part.getType()); + } + return types; +} +``` + +To visit only parts that still have a tile binding: + +```java +public static List boundPartTypes(TileMultipart tile) { + List types = new ArrayList<>(); + tile.forEachPart(part -> types.add(part.getType())); + return types; +} +``` + +The [complete Java example](../../src/test/java/codechicken/multipart/examples/PartTraversalExample.java) compiles and +runs in the normal test task. Its imports and compiled references contain no Scala types. FMP still needs its retained +Scala runtime internally. The example also compiles with Scala excluded from its classpath. The returned name lists +are independent copies. + +## Collection ownership and ordering + +`jPartList()` wraps the sequence returned by the virtual `partList()` getter at that call. It preserves every entry, +its index and its object identity, including detached parts. Use it for indexing, searches, serialization and ordinary +iteration. It does not require parts to have joined a world. + +Normal FMP additions/removals replace an immutable sequence. A previously returned Java list keeps the old sequence; +call `jPartList()` again for the tile's new contents. A legacy setter or getter override can instead supply a mutable +sequence, in which case mutations of that sequence remain visible through its Java view. Therefore the method does +not promise either an independent snapshot or an unmodifiable list for every implementation. + +Treat the view as read-only. Editing it, even when the backing sequence permits it, does not perform part binding, +slot updates, notifications or synchronization. Use `TileMultipart.addPart(world, pos, part)` and `tile.remPart(part)` +for normal world changes, retaining their returned tile because adding/removing capabilities can replace the tile +instance. To capture independent list storage, use `new ArrayList<>(tile.jPartList())`; the part objects remain shared. + +## Callback behavior + +Use the game thread. The default `forEachPart` traversal has the same behavior as the legacy `operate` hook: + +- Capture the current sequence once and visit it in order. Normal additions during a callback publish a new sequence, + so the current traversal does not visit the added parts. +- Check `part.tile() != null` immediately before each callback. A part detached by an earlier callback is skipped; + a part rebound to another tile is still visited. This check is not an ownership test against the original tile. +- A nested traversal captures the sequence anew and can observe the updated list. Each call has its own traversal state. +- Propagate the original callback exception immediately and stop that traversal. Side effects already performed remain. +- Preserve the iterator behavior of legacy mutable sequences. Do not structurally mutate such a sequence during traversal. +- Pass a non-null callback. For compatibility, there is no eager null check: with the default hook, null throws + `NullPointerException` only when a bound part reaches the callback. Empty/all-detached sequences invoke nothing. + +`tile.jPartList().forEach(action)` visits every entry, including detached parts. It is not equivalent to +`tile.forEachPart(action)`. Preserve the consumer's original filtering and callback behavior when migrating. + +## Overrides and legacy entry points + +The dispatch paths are `jPartList()` → virtual `partList()`, and `forEachPart(consumer)` → virtual `operate(adapter)`. +The existing Java adapter and traversal implementation are shared; the legacy methods keep their descriptors and +bodies. Both legacy methods are deprecated for callers, with replacements named in their Javadocs. + +Existing getter and `operate` overrides remain supported and can customize these behaviors. Lifecycle callbacks still +call `operate` directly. Overriding `forEachPart` intercepts calls to that convenience method only; it does not intercept +ticks, chunk callbacks or other lifecycle dispatch. Keep a legacy `operate` override in place if it supplies that hook. +No replacement lifecycle override contract is introduced by this addition. + +## Consumer migration + +| Existing use | Java replacement | +| --- | --- | +| `partList().size()` / `isEmpty()` / `indexOf(part)` | The corresponding `jPartList()` list method | +| Scala sequence indexing (`partList().apply(index)` or `tile.partList(index)`) | `tile.jPartList().get(index)` | +| Scala iterator for reading/searching every part | Enhanced `for` loop over `tile.jPartList()` | +| `operate(scalaFunction)` callback | `forEachPart(javaConsumer)`; preserve any existing hook overrides | + +AE2's placement helper and Extra Utilities' renderer loops can use `jPartList()` without adding detached-part filtering. +ProjectRed's illumination calculations and packet/render indices, and OpenComputers' cable/print/network searches, +must retain their original order, filters and aggregation. Those mods can remain Scala internally while calling Java +collection methods. Existing Java consumers already using `jPartList()` need no rename. + +GuideNH also reflects `partList`, `partList_$eq` and `loadParts` while reconstructing client tiles. Moving read-only +uses to the Java getter does not migrate its setter/loading contracts. Their Java replacements and the consumer patch, +release and pack adoption remain separate work. No reference checkout was edited. + +The [adoption ledger](../../JAVA_MIGRATION_CONSUMER_AUDIT.md#java-api-adoption-ledger) records inspected revisions and +the remaining release gates. JVM checks cover both getter forms, mutable storage, callback mutation/reentrancy, +detached/rebound parts, override dispatch and failures. The Forge test removes and adds real parts during traversal +of a generated slotted tile. Client rendering and full-pack adoption remain manual release checks. diff --git a/docs/migration/HISTORY.md b/docs/migration/HISTORY.md index 3eed760..4e59669 100644 --- a/docs/migration/HISTORY.md +++ b/docs/migration/HISTORY.md @@ -1741,3 +1741,25 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m - Added the material-enumeration guide and the first consumer adoption ledger rows. UtilitiesInExcess's two source call sites and Extra Utilities' tuple-array readers have supported replacements; consumer changes, releases and pack adoption remain pending. Evidence is under ignored `run/migration-material-enumeration-reference/`. + +### 2026-09-04 — Java tile collection and traversal API + +- Committed three baseline cases first as `5c1e760`, pinning captured Java views, lifecycle override dispatch, + non-null binding checks and callback failure propagation. Saved the pre-API jar, source, reports, generated dumps + and all 538 compiled JVM tests before implementation. +- Added `TileMultipart.forEachPart(Consumer)` through the existing adapter and virtual `operate` hook. + Documented the existing `jPartList()` view and deprecated `partList()`/`operate(Function1)` for callers, retaining + their descriptors, bodies and override contracts. Lifecycle still calls `operate` directly; no new lifecycle hook + or independently maintained traversal was introduced. +- Added four JVM cases, a compiling Java example and one Forge generated-tile case that removes/adds real parts + during traversal. Normal/clean style and build checks pass: 542 JVM tests, 239 Java 8 Forge tests and all 538 frozen + pre-change tests. The example also compiles with Scala excluded from its classpath and has no Scala bytecode references. +- Binary comparison retains all 443 class APIs with exactly one new public instance method and two deprecations. + All 17 ScalaSignature payloads, 3,747 existing method bodies and 116 generated dumps are unchanged, allowing only + the expected deprecation metadata and build-version literals. No production class or dependency was added. +- Added the traversal guide and consumer ledger entries for ProjectRed, OpenComputers, AE2, Extra Utilities and + GuideNH. Getter migration does not cover GuideNH's reflective setter/loading contracts. The supplied source search + found no FMP `operate` overrides or `forEachPart` collisions; existing override support remains required. +- Rescanned the installed GTNH daily `2026-09-04+719`: 241 jars scanned, one FMP jar excluded, 27 consumers. All + 386 member/type/reflection rows match the frozen `+678` inventory; consumer version changes do not permit bridge + removal. Reference checkouts were not modified. Evidence: `run/migration-part-traversal-reference/`. diff --git a/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java b/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java index 89d9227..be1c8da 100644 --- a/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java +++ b/src/functionalTest/java/codechicken/multipart/test/TileMultipartLifecycleFunctionalTest.java @@ -27,6 +27,7 @@ class TileMultipartLifecycleFunctionalTest { private static final BlockCoord ADD_REMOVE_POS = new BlockCoord(32, 200, 32); private static final BlockCoord MOVE_FROM = new BlockCoord(34, 200, 32); private static final BlockCoord MOVE_TO = new BlockCoord(36, 200, 32); + private static final BlockCoord TRAVERSAL_POS = new BlockCoord(38, 200, 32); @Test void addAndRemovePreserveOrderSlotsAndPartCallbackOrder() { @@ -121,6 +122,41 @@ class TileMultipartLifecycleFunctionalTest { } } + @Test + void javaTraversalSurvivesRealPartRemovalAndAdditionOnAGeneratedTile() { + World world = world(); + clear(world, TRAVERSAL_POS); + List events = new ArrayList<>(); + RecordingPart first = new RecordingPart("first", 2, events); + RecordingPart removed = new RecordingPart("removed", 7, events); + RecordingPart added = new RecordingPart("added", 8, events); + + try { + TileMultipart.addPart(world, TRAVERSAL_POS, first); + TileMultipart tile = TileMultipart.addPart(world, TRAVERSAL_POS, removed); + List captured = tile.jPartList(); + List visited = new ArrayList<>(); + tile.forEachPart(part -> { + visited.add(part); + if (part == first) { + assertSame(tile, tile.remPart(removed)); + assertSame(tile, TileMultipart.addPart(world, TRAVERSAL_POS, added)); + } + }); + + assertTrue(tile instanceof TSlottedTile); + assertEquals(Arrays.asList(first), visited); + assertEquals(Arrays.asList(first, removed), captured); + assertEquals(Arrays.asList(first, added), tile.jPartList()); + assertNull(removed.tile()); + assertNull(tile.partMap(7)); + assertSame(added, tile.partMap(8)); + assertSame(tile, added.tile()); + } finally { + clear(world, TRAVERSAL_POS); + } + } + private static World world() { World world = MinecraftServer.getServer().worldServers[0]; world.getChunkFromBlockCoords(ADD_REMOVE_POS.x, ADD_REMOVE_POS.z); diff --git a/src/main/scala/codechicken/multipart/TileMultipart.java b/src/main/scala/codechicken/multipart/TileMultipart.java index 56d0702..2bfe869 100644 --- a/src/main/scala/codechicken/multipart/TileMultipart.java +++ b/src/main/scala/codechicken/multipart/TileMultipart.java @@ -44,6 +44,11 @@ public class TileMultipart extends TileEntity implements IChunkLoadTile { private boolean doesTick = false; + /** + * @deprecated Use {@link #jPartList()} for Java collection access. Retained as the virtual storage accessor for + * existing subclasses and binaries. + */ + @Deprecated public Seq partList() { return partList; } @@ -82,16 +87,55 @@ public class TileMultipart extends TileEntity implements IChunkLoadTile { return null; } - /** Implicit java conversion of part list. */ + /** + * Returns an ordered Java view of the sequence returned by {@link #partList()} at this call. Includes detached + * parts; replacing the tile's sequence does not update an existing view. Normally the sequence is immutable, but a + * mutable sequence supplied through the legacy setter remains live through this view. + * + *

+ * Treat the view as read-only: list edits do not perform multipart binding, notifications or synchronization. Use + * {@link #addPart(World, BlockCoord, TMultiPart)} and {@link #remPart(TMultiPart)} for world changes. Copy into an + * {@link ArrayList} when independent list storage is needed; the parts themselves remain shared. + * + * @return a view of the captured sequence, with its original order and part identities + */ public List jPartList() { return JavaConversions.seqAsJavaList(partList()); } + /** + * Visits parts in sequence order, skipping those whose {@link TMultiPart#tile()} is null when reached. Delegates + * through the legacy {@link #operate(Function1)} hook, so existing overrides still control traversal. + * + *

+ * The default hook captures {@link #partList()} once. Normal additions publish a new sequence and are not visited + * by the current call; parts detached by an earlier callback are skipped. A part rebound to another tile is still + * visited. Legacy mutable sequences retain their own iterator behavior and must not be structurally edited during + * traversal. Each nested call captures its own sequence. Callback exceptions propagate immediately, stopping the + * current traversal. + * + *

+ * Call on the game thread. Lifecycle callbacks continue to dispatch through {@code operate}, not through overrides + * of this convenience method. With the default hook, a null callback fails only when a bound part is visited. + * + * @param consumer action to apply to each visited part + */ + public void forEachPart(Consumer consumer) { + operate(action(consumer)); + } + @Override public boolean canUpdate() { return doesTick; } + /** + * Legacy traversal hook, also used by multipart lifecycle callbacks. + * + * @deprecated Call {@link #forEachPart(Consumer)} from Java. Existing overrides remain supported and intercept both + * that API and lifecycle callbacks; keep such overrides here while this compatibility hook is retained. + */ + @Deprecated // Direct list traversal avoids measured iterator/wrapper allocations; the setter also accepts other Seq types. @SuppressWarnings("unchecked") public void operate(Function1 f) { diff --git a/src/test/java/codechicken/multipart/TileMultipartCharacterizationTest.java b/src/test/java/codechicken/multipart/TileMultipartCharacterizationTest.java index 9a936b2..b1513c7 100644 --- a/src/test/java/codechicken/multipart/TileMultipartCharacterizationTest.java +++ b/src/test/java/codechicken/multipart/TileMultipartCharacterizationTest.java @@ -21,6 +21,7 @@ import net.minecraft.util.Vec3; import org.junit.jupiter.api.Test; import codechicken.lib.raytracer.ExtendedMOP; +import codechicken.multipart.examples.PartTraversalExample; import scala.Function1; import scala.Tuple2; import scala.collection.JavaConversions; @@ -332,6 +333,98 @@ class TileMultipartCharacterizationTest { assertEquals(Arrays.asList("rebound"), visited); } + @Test + void javaTraversalKeepsAccessorDispatchAndCallbackMutationSemantics() { + AccessorTile tile = new AccessorTile(); + CountingPart first = new CountingPart("first"); + CountingPart removed = new CountingPart("removed"); + CountingPart rebound = new CountingPart("rebound"); + CountingPart added = new CountingPart("added"); + tile.parts = seq(first, removed, rebound); + tile.loadFrom(new TileMultipart()); + List visited = new ArrayList<>(); + List nested = new ArrayList<>(); + + tile.forEachPart(part -> { + visited.add(part.getType()); + if (part == first) { + tile.partList_$eq(seq(first, rebound, added)); + removed.bind(null); + rebound.bind(new TileMultipart()); + added.bind(tile); + tile.forEachPart(p -> nested.add(p.getType())); + } + }); + + assertEquals(Arrays.asList("first", "rebound"), visited); + assertEquals(Arrays.asList("first", "rebound", "added"), nested); + } + + @Test + void javaTraversalUsesTheLegacyOverrideAndDoesNotReplaceItsLifecycleHook() { + CountingPart supplied = new CountingPart("supplied"); + List calls = new ArrayList<>(); + TileMultipart tile = new TileMultipart() { + + @Override + public void operate(Function1 f) { + calls.add("operate"); + f.apply(supplied); + } + + @Override + public void forEachPart(Consumer consumer) { + calls.add("forEachPart"); + super.forEachPart(consumer); + } + }; + List visited = new ArrayList<>(); + tile.forEachPart(visited::add); + tile.onChunkLoad(); + + assertEquals(Arrays.asList("forEachPart", "operate", "operate"), calls); + assertEquals(Arrays.asList(supplied), visited); + assertEquals(1, supplied.chunkLoads); + } + + @Test + void javaTraversalRetainsMutableSequenceAndCallbackFailureBehavior() { + TileMultipart tile = new TileMultipart(); + tile.forEachPart(null); + CountingPart detached = new CountingPart("detached"); + tile.partList_$eq(seq(detached)); + tile.forEachPart(null); + detached.bind(tile); + assertThrows(NullPointerException.class, () -> tile.forEachPart(null)); + + CountingPart last = new CountingPart("last"); + last.bind(tile); + tile.partList_$eq(JavaConversions.asScalaBuffer(new ArrayList<>(Arrays.asList(detached, last)))); + List visited = new ArrayList<>(); + tile.forEachPart(visited::add); + assertEquals(Arrays.asList(detached, last), visited); + visited.clear(); + IllegalStateException failure = new IllegalStateException("callback failed"); + assertSame(failure, assertThrows(IllegalStateException.class, () -> tile.forEachPart(part -> { + visited.add(part); + throw failure; + }))); + assertEquals(Arrays.asList(detached), visited); + } + + @Test + void javaExamplesDistinguishCollectionAccessFromBoundPartTraversal() { + TileMultipart tile = new TileMultipart(); + CountingPart first = new CountingPart("first"); + CountingPart detached = new CountingPart("detached"); + tile.addPart_do(first); + tile.addPart_do(detached); + detached.bind(null); + + assertEquals(Arrays.asList("first", "detached"), PartTraversalExample.partTypes(tile)); + assertEquals(Arrays.asList("first"), PartTraversalExample.boundPartTypes(tile)); + } + @Test void ticksOnlyOnceATickingPartIsPresent() { TileMultipart quiet = new TileMultipart(); diff --git a/src/test/java/codechicken/multipart/examples/PartTraversalExample.java b/src/test/java/codechicken/multipart/examples/PartTraversalExample.java new file mode 100644 index 0000000..72e656c --- /dev/null +++ b/src/test/java/codechicken/multipart/examples/PartTraversalExample.java @@ -0,0 +1,27 @@ +package codechicken.multipart.examples; + +import java.util.ArrayList; +import java.util.List; + +import codechicken.multipart.TMultiPart; +import codechicken.multipart.TileMultipart; + +/** Compiling examples for docs/api/PART_TRAVERSAL.md; call on the game thread. */ +public final class PartTraversalExample { + + private PartTraversalExample() {} + + public static List partTypes(TileMultipart tile) { + List types = new ArrayList<>(); + for (TMultiPart part : tile.jPartList()) { + types.add(part.getType()); + } + return types; + } + + public static List boundPartTypes(TileMultipart tile) { + List types = new ArrayList<>(); + tile.forEachPart(part -> types.add(part.getType())); + return types; + } +}