docs: demonstrate Java microblock extensions

This commit is contained in:
Algent committed 2026-09-05 17:45:57 +02:00
1 parent c41ed8d7a4
commit 9fd64d3db1
15 files changed
+636 -28

No files matched your search

+5 -2
View File
@@ -64,7 +64,7 @@ The phase checklists include recurring verification rules, historical work and c
| Workstream | Remaining deliverables | Gate |
| --- | --- | --- |
| Complete the supported Java surface | ProjectRed-style illuminated microblock extension example with generated/side coverage; converter and extension/lifecycle guidance; safe Java compilation guidance for transformed traits; supported orientation customization for Et Futurum and saw-strength customization for Iguana; finish the audited reflection/legacy-use map | Next FMP milestone; direct typed calls and documented override behavior, without requiring consumer reflection |
| Complete the supported Java surface | Physical-client validation of the documented illuminated microblock example; converter and broader extension/lifecycle guidance; safe Java compilation guidance for transformed traits; supported orientation customization for Et Futurum and saw-strength customization for Iguana; finish the audited reflection/legacy-use map | Next FMP milestone; direct typed calls and documented override behavior, without requiring consumer reflection |
| Migrate consumers and adopt releases | Patch GuideNH/Schematica to their documented APIs; migrate ProjectRed's external trait and other Scala/helper users, including OpenComputers, ProjectBlue and ForgeRelocationFMP; direct Galacticraft integration; Et Futurum/Iguana migrations; UtilitiesInExcess enumeration and `mat`/`material` fix; complete the full adoption ledger beyond these hotspots | Source patches, released versions and actual target-pack jars must all be recorded; reference checkouts are not migrated |
| Measure and improve performance | Fresh realistic profiles, ranked candidates, bounded improvements and repeated paired measurements; distinguish FMP implementation gains from migrated-consumer gains and report variability/regressions | Phase 4b starts when API/extension workloads are stable; it can overlap consumer adoption |
| Validate releases | Complete client rendering/particles/lighting/interaction and integration checklist; old-world, multiplayer, movement and preview checks; packaged/obfuscated artifacts on supported runtimes; optional-mod absent/present loading; actual patched-world MCPC hook where supported | Automated Forge tests do not replace physical-client/full-pack evidence; repeat affected checks after consumer migration and Scala removal |
@@ -772,6 +772,9 @@ placeholder, rather than lost material data. Extra Utilities writes `mat` as wel
UtilitiesInExcess's `extrautils:*` aliases; there is no legacy-conversion risk in the fix.
- [x] Land the two Phase 7 Java-mixin prerequisites with generated Java-trait fixtures.
- [x] Provide the [Java illuminated microblock example](docs/api/MICROBLOCK_EXTENSIONS.md), including real Forge
registration, all shape families, material/persistence/light contracts, server stripping and a headless retained
client-body probe. The three example sources compile without Scala. Physical-client rendering remains a release gate.
- [ ] Land the ProjectRed `LightMicroblock` Java rewrite with a fixture proving equivalent generated microblocks on
both sides.
- [ ] Migrate Galacticraft to direct registration in gated compatibility code; exact-signature reflection is an interim option.
@@ -787,7 +790,7 @@ UtilitiesInExcess's `extrautils:*` aliases; there is no legacy-conversion risk i
reflection, material trait callbacks, fresh-part/shape ownership and a compiling example. Keep physical-client
validation and public-setter versus private-field override behavior explicit; [guide](docs/api/MICROBLOCK_CREATION.md).
- [x] Document and validate GuideNH's direct typed material query through existing `block()` / `meta()` accessors;
[guide](docs/api/MATERIAL_ACCESS.md). Consumer adoption and the representative external Java extension remain open.
[guide](docs/api/MATERIAL_ACCESS.md). Consumer adoption and physical-client validation of the Java extension example remain open.
- [ ] Patch those four consumers and record the released versions that no longer need the private shapes.
- [ ] Track all legacy FMP dependencies in the adoption ledger, including trait helper/companion calls and reflection
outside the cleanup table; verify the released jars actually selected for the target pack.
+8
View File
@@ -248,3 +248,11 @@ this does not authorize removing or narrowing these members. The shipped `TileMu
and `internalPartChange(TMultiPart): void` calls remain supported and are documented in the API guide, as are existing
legacy override contracts. The registry's internal `loadIcons()` dispatcher is distinct from its supported material
interface callback. The `+719` rescan retains all 386 member/type/reflection rows across the same 27 consumers.
### Java illuminated extension example
`MicroblockGenerator.registerTrait(String)` now documents its existing Java input path and pre-loading constraint.
The [three-file example](docs/api/MICROBLOCK_EXTENSIONS.md) uses typed FMP entry points, with no additions or changes
to the production API. ProjectRed still ships its external Scala trait; the Java example does not authorize retiring
its old class/helper contracts or signature ingestion. Consumer release, pack adoption and internal dependency gates
remain in force. The example itself lives only in the functional-test source set.
+17
View File
@@ -512,6 +512,7 @@ tied to a released minimum dependency version. Unlisted contracts remain governe
| Legacy contract | Consumer and inspected source | Supported replacement | Consumer migration/release | Target-pack adoption and removal gate |
| --- | --- | --- | --- | --- |
| External Scala `LightMicroblock` registered through `MicroblockGenerator.registerTrait` | ProjectRed `e173952e96a4`: `illumination/lightmicroblocks.scala` | Java source trait registered by name, `IGeneratedMaterial`, typed sibling traversal and halo helper; [example](docs/api/MICROBLOCK_EXTENSIONS.md) | FMP example tested; consumer rewrite/release, existing config/halo wiring and physical-client checks pending | Retain external Scala trait ingestion until released-consumer adoption and internal Scala-trait removal |
| `MultiPartRegistry$.registerParts(IPartFactory2, Seq)` and existing array calls | ProjectRed `e173952e96a4`: transmission, expansion and fabrication proxies | `MultiPartRegistry.registerPartFactory` with existing `IPartFactory2` methods and unchanged IDs | Source patch and release pending; Boolean-factory proxies separately need the two-method adapter described in the guide | No migrated pack version verified; retain all registration bridges and external trait support |
| `MultiPartRegistry$.registerParts(Function2, Seq)` | ForgeRelocationFMP `49a810b8c63b`: proxy init registering `rfmp_frame` | `IPartFactory2` creating a fresh `FramePart` on both paths, registered through `registerPartFactory` | Source patch and release pending; preserve `rfmp_frame` and keep converter/pass-through registration | No migrated pack version verified; retain the function companion descriptor |
| `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 |
@@ -685,6 +686,22 @@ new deprecations are introduced; `operate`, `getOrConvertTile2` and material `lo
legacy/extension contracts. No consumer checkout was modified or counted as migrated.
Evidence: `run/migration-api-boundary-reference/`, including source revisions and reviewed caller searches.
## Java illuminated microblock extension
The ProjectRed-style [Java example](docs/api/MICROBLOCK_EXTENSIONS.md) uses public name-based registration and
`IGeneratedMaterial`; no consumer reflection or Scala classpath is needed. Register the input before class loading,
keep inherited access in an ordinary helper with Object parameters, and dispatch via the stable Microblock base.
The example preserves metadata 16–31, cutter metadata modulo 16, all-shape trait selection, strict sibling selection,
size-based light rounding/capping, pass-zero halo submission and the hollow opening's trimmed strips. It adds no
part NBT or packet fields. A distinct test lamp supplies the fixture; stock materials keep their exact assertions.
The baseline extends retained external Scala-trait composition to all five built-in shape families. Four added Forge
cases cover Java registration/shape composition, material persistence, light behavior, halo geometry and a retained
client-body compiler probe. That probe removes only the test input's side annotation to exercise generated dispatch
headlessly; it is not physical-client evidence. Actual client construction/rendering and consumer configuration/halo
integration remain adoption checks. Reference checkouts and released-consumer status are unchanged.
Evidence: `run/migration-illuminated-extension-reference/`; frozen consumers retain 571 JVM and 274 Forge cases.
## Practical priority for the current branch
1. Keep the existing `+678` ABI fixture as the exact binary floor and correct failures before source cleanup.
+25 -22
View File
@@ -17,7 +17,7 @@ migration checkout; `codex/tile-compatibility-fixes` was deleted after its fixes
## Current state and next target
**571 plain-JVM tests and 273 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **225 Java
**571 plain-JVM tests and 278 Java 8 Forge tests pass, with zero failures/errors/skips.** Sources total **225 Java
files and 9 Scala files / 747 nonblank Scala lines**. The packaged inventory has 444 classes.
Review follow-up: restored packet-scheduler callback mutation behavior with the original Scala hash-map traversal,
@@ -32,16 +32,18 @@ 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 work completes the bounded Phase 9.2 internal-boundary documentation. A fresh audit of 28 source
checkouts and active Extra Utilities compatibility found no external calls to the 15 listed hooks; the five
material-registry companion bridges carry the same internal marker. `bindPart` and `internalPartChange` remain
supported for OpenComputers/ProjectRed. The material `IMicroMaterial.loadIcons` callback and existing legacy override
contracts remain supported. One JVM and one Forge baseline were committed first as `8b12dfe`, pinning local callback
mutation/failures and cache-only binding with caller-cleared old slots. All 571 archived JVM tests and the unchanged
archived Forge mod's 273 cases pass. Production APIs and behavior remain unchanged: 444 class APIs, 17 ScalaSignature
payloads, 3,761 method bodies and all 116 generated dump names/hashes match. No visibility changes, deprecations or
annotation dependency were added. Evidence: `run/migration-api-boundary-reference/`;
[boundary guide](docs/API.md#supported-api-and-internal-hooks), [caller audit](JAVA_MIGRATION_CONSUMER_AUDIT.md#api-boundary-audit).
Latest API work adds a ProjectRed-style Java illuminated microblock example. Existing `registerTrait(String)` selects
Java input without loading it first; `IGeneratedMaterial` adds the extension for all shapes/sides. Thin trait methods
pass Object to an ordinary helper, which uses typed Java traversal and geometry. Registration, metadata/cutter
semantics, shape/persistence, light aggregation and ordinary/hollow halo bounds are documented and tested. One Forge
baseline was committed first as `c41ed8d`, covering external Scala composition across all five shapes. Four Java
example cases bring the suite to 571 JVM / 278 Forge tests. The three example files compile without Scala.
All 571 archived JVM and 274 archived Forge tests pass; the archived Forge mod is unchanged. Production APIs/bodies
remain unchanged (444 classes, 17 ScalaSignature payloads, 3,761 methods). The 120 baseline dump bodies are
retained after mapping only allocation-order microblock self-names; ten additional dumps cover the Java trait, five shapes and retained client-body compiler probe.
That probe is headless, not a physical-client render check. ProjectRed's config/halo wiring, released migration and
pack adoption remain pending. Evidence: `run/migration-illuminated-extension-reference/`;
[extension guide](docs/api/MICROBLOCK_EXTENSIONS.md).
Direct typed calls are the intended end state for supported integrations. Optional dependencies should isolate typed
compatibility code behind presence/version checks; reflection snippets in earlier guides are temporary legacy
@@ -65,17 +67,16 @@ adoption remain pending. Checkouts remain reference-only. The installed `+719` p
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 candidate is a representative external Java microblock extension based on ProjectRed's
`LightMicroblock` / `LightMicroMaterial` contract. Trace its registration, material behavior, state and side-only
callbacks; provide a compiling Java example with generated Forge coverage. Keep the reference checkout untouched
and retain the external Scala trait path until consumer release/adoption. Compiler prerequisites are complete, but
that alone does not establish the complete extension contract or physical-client rendering.
The next bounded candidate is converter registration and lifecycle guidance: trace `IPartConverter` callers,
conversion selection and ownership, then add a compiling Java example with focused characterization. The broader
source-compilation story for transformed tile traits and other audited reflection use cases remain separate work.
The illuminated microblock example supplies the representative Java extension, but physical-client construction,
connector-dependent halos, lighting and consumer adoption still need their recorded checks.
Progress: all ten Phase 9.1 table rows and Phase 9.2's internal markers are complete, plus the separate Schematica
registry lookup, staged Java tile generation, microblock-creation guidance and typed GuideNH material query.
Remaining work includes converter/extension guidance and other audited reflection use cases. Then consumer patches,
releases and pack adoption must precede final Scala removal and client/pack release validation; it is not a percentage
of the whole migration.
Progress: all ten Phase 9.1 table rows and Phase 9.2's internal markers are complete, plus Schematica registry lookup,
staged Java tile generation, microblock creation, typed material access and the Java illuminated extension example.
Remaining work includes converter/broader extension guidance and other audited reflection use cases. Consumer patches,
releases and pack adoption still precede final Scala removal and client/pack release validation.
Extra Utilities remains an active supported consumer. UtilitiesInExcess is the intended replacement, but the support
switch awaits approval and actual target-pack adoption. Retain existing contracts until those gates pass. The
@@ -151,10 +152,12 @@ persists. Six early ASM extractions lacked characterization; their backfill is c
JUnit XML: `build/test-results/test/TEST-*.xml` and `run/server/junit-out/TEST-*.xml`. Count tests, failures, errors and
skips; do not infer them from Gradle's task summary. The Forge runner validates its own reports, and its dependent CI
job must stay required. The ignored local server EULA is already accepted.
Archived test mods predating the illuminated fixture lamp must use a separate disposable world; reusing the current
test world triggers Forge's missing-mapping prompt. Restore server.properties after such archived runs.
Generated dumps: `run/server/asm/multipart/**/*.txt`; enumerate recursively and assert a nonzero expected count.
Compare names and hashes first. Investigate differences before normalizing only proven debug/private-name changes.
The current baseline emits 116 dumps, including the deterministic definition, compiler and feature fixtures.
The current baseline emits 130 dumps, including the deterministic definition, compiler and feature fixtures.
### Binary and fixture checks
+5
View File
@@ -83,6 +83,11 @@ entries complete.
| [ ] | Join a server whose material set differs from the client | The client is disconnected with the missing material list, not a crash | `readIDMap` |
| [ ] | Join a server whose multipart type set differs from the client | The client is disconnected with the ordered missing-part list, not a crash | `MultipartCPH.handlePartRegistration` |
The [Java illuminated extension example](docs/api/MICROBLOCK_EXTENSIONS.md) has dedicated-server and headless halo
coverage. When adopting it in ProjectRed, rerun the illuminated shape/lighting checks above on a physical client,
including hollow connector widths and all sides, pass filtering and the existing halo queue/configuration. Neither
its callback-side input tests nor its retained client-body probe validates actual client generation or GPU output.
## Not yet covered anywhere
- [ ] A focused pre-optimization CPU/allocation baseline now exists in `JAVA_MIGRATION_PROFILE.md`. A representative
+5 -3
View File
@@ -25,6 +25,7 @@ Existing reflective binaries remain supported until consumer release and pack ad
| Enumerate microblock materials by numeric ID | `materialCount()`, `materialName(int)`, `getMaterial(int)` — [material enumeration](api/MATERIAL_ENUMERATION.md) |
| Read a microblock material's block and metadata | `BlockMicroMaterial.block()`, `meta()` — [typed GuideNH query, identity and overrides](api/MATERIAL_ACCESS.md) |
| Create a microblock with the requested material and side | `MicroblockGenerator.create(MicroblockClass, int, boolean)` — [construction, material traits and GuideNH migration](api/MICROBLOCK_CREATION.md) |
| Add material-specific behavior to generated microblocks | `registerTrait(String)` and `IGeneratedMaterial` — [illuminated Java extension, compilation and side contracts](api/MICROBLOCK_EXTENSIONS.md) |
| Read/index/search a tile's parts | `jPartList()` — [part collection ownership and order](api/PART_TRAVERSAL.md#collection-ownership-and-ordering) |
| Run callbacks while skipping detached parts | `forEachPart(Consumer)` — [callback and override behavior](api/PART_TRAVERSAL.md#callback-behavior) |
| Rebuild parts on an already prepared composite tile | `loadPartList(Collection)` — [part loading](api/PART_LOADING.md) |
@@ -102,9 +103,10 @@ Deprecated Scala-facing entry points remain callable, with their descriptors and
Follow the method-specific guide: a Java sibling is not automatically a replacement override hook, and reflection
must select the intended parameter types when a method is overloaded.
Converter documentation, remaining generator/reflection replacements
and complete external microblock extension guidance are still pending. In particular, ProjectRed's Scala microblock traits
remain a supported dependency; registration signatures alone do not prove a complete Java replacement.
An [illuminated Java microblock extension](api/MICROBLOCK_EXTENSIONS.md) now covers registration, material traits,
light aggregation and halo geometry, with compiling examples and Forge coverage. Its physical-client rendering and
ProjectRed adoption remain open. Converter documentation, broader extension/compilation guidance and the remaining
audited reflection replacements are still pending. ProjectRed's existing Scala traits remain supported until adoption.
All ten entries in the plan's Phase 9.1 API table have Java replacements. That table is a bounded list of signatures;
the broader API, extension and consumer adoption work above remains open.
+90
View File
@@ -0,0 +1,90 @@
# Extend generated microblocks from Java
Use `MicroblockGenerator.registerTrait(String)` with a Java source trait, then add its returned ID from an
`IGeneratedMaterial.addTraits` callback. The existing public API selects the Java compiler path automatically;
consumers do not need reflection, Scala types, companion lookup or direct compiler calls.
This example follows ProjectRed's illuminated microblock contract. It comprises three compiling Java files:
- [IlluminatedMicroblockTrait](../../src/functionalTest/java/codechicken/multipart/examples/IlluminatedMicroblockTrait.java):
the generated extension's dynamic-render flag, light value and client render callback.
- [IlluminatedMicroMaterial](../../src/functionalTest/java/codechicken/multipart/examples/IlluminatedMicroMaterial.java):
block-backed material and material-provided trait selection, including cutter metadata handling.
- [IlluminatedMicroblockExample](../../src/functionalTest/java/codechicken/multipart/examples/IlluminatedMicroblockExample.java):
registration, ordinary Java implementation, configuration supplier and halo-renderer adapter.
Copy/adapt these into the consumer's own package; update the literal registration name accordingly. They are example
sources in FMP's functional-test source set, not production classes shipped for consumers to depend on.
## Registration and compilation
1. Register the consumer's lamp block first. During mod initialization, call `registerMaterials(lamp)` once, on both
physical sides and before FMP creates the material-ID map. The helper registers the trait before materials.
2. Wire `dimLampParts` to a supplier of the consumer's current configuration. On the physical client, set
`haloRenderer` to its halo queue before rendering; ProjectRed can forward to `RenderHalo.addLight(x, y, z, colour, box)`.
Keep renderer-only dependencies out of common initialization. The helper supplies no renderer fallback.
3. Retain the consumer's existing material names, metadata 16 through 31, configuration defaults and block identity.
The test fixture uses its own lamp block; a real ProjectRed migration uses ProjectRed's registered lamp.
4. Create parts through the [public microblock creation API](MICROBLOCK_CREATION.md). The material adds the same
extension ID for every shape and both sides, without clearing the borrowed bit set. The generator also selects
the shape's built-in traits and client trait where applicable. Repeated construction reuses the generated class,
not the instance. Changing a part's material afterward does not regenerate its traits.
**Register the Java trait by name before loading it.** A Java class literal is appropriate for retained Scala
interfaces, but can load the untransformed Java input too early. Name-based registration is a supported generator
operation, not consumer reflection. IDs are local to this generator and must not be persisted or reused as tile-trait IDs.
The Java input extends `Microblock`, is abstract, and has a public no-argument constructor calling `super(0)`.
FMP discards that direct super call; the composite's real constructor receives the requested material ID. No extra
trait state is needed for this extension. Keep the input top-level, without nested/anonymous classes or lambdas.
After registration FMP rewrites that class into an interface. Do not instantiate it, subclass its raw class from
ordinary consumer Java, or invoke inherited members through that raw class type. `instanceof` works after
registration; dispatch uses stable `Microblock` methods. For new extension-specific methods, declare a separate
ordinary capability interface rather than emitting class calls against the transformed input.
The existing transformer cannot safely handle all inherited field/method accesses in a trait body. Its thin overrides
therefore delegate to an ordinary helper using an **Object parameter**, then cast to `Microblock` in that helper.
This forces the required runtime cast and keeps loops, allocation and callbacks outside the transformed input.
The three example files compile with Scala excluded from the Java classpath; they use Java 8 syntax because that is
the verified joint-compilation/test boundary. See the [compiler constraints](../../JAVA_MIGRATION_HANDOFF.md#retained-compiler-constraints).
## Behavioral contract
- The dynamic-render flag is always true. The client callback submits halos only on pass zero. It uses the part's
tile coordinates, not the supplied camera-relative render position; colour is material metadata minus 16.
- Cutter strength asks the block for the harvest level at `meta() % 16`, preserving the illuminated metadata bit's
exclusion. Ordinary block/meta access remains virtual through the supported methods.
- With dimming enabled, collect all siblings carrying this extension, sum `getSize() / 8.0`, multiply by 15,
truncate to an integer, then cap at 15. Capture the matching parts before invoking size callbacks. With dimming
disabled, any matching sibling gives light 15, otherwise zero. Do not substitute volume for encoded size.
- Read `tile().jPartList()` without detached-part filtering: this preserves the reference's membership behavior.
The part must be bound before querying light; an unbound part fails rather than inventing a light value. Callback
failures propagate. This example adds no stored per-part state, NBT keys or packet fields.
- Ordinary halos copy collision boxes and expand them by 0.025; source boxes remain untouched. Hollow halos instead
use four rotated strips around the current connector opening. Their middle strips are trimmed along the opening,
so simply expanding hollow collision boxes does not reproduce the same geometry. Halo boxes are newly allocated
and may be retained by the renderer queue. Configuration and renderer access run on the owning game/render thread.
`@SideOnly(CLIENT)` belongs on the trait's render override. The common light flag/value remain present on the server.
The helper uses common geometry types, allowing headless verification; only the supplied halo renderer needs a client.
This is a behavior-preserving migration example, not a performance optimization or a replacement rendering engine.
## Validation and adoption
The separately committed baseline proves the retained external Scala trait composes with face, hollow, corner, edge
and post shapes, with fresh instances, class reuse, correct material identity and no implicit binding. The Java
example's Forge tests cover initialization registration, all 16 material variants, both callback-side inputs, all
five generated shape families, persistence, light aggregation and server stripping of the client override.
Geometry tests cover ordinary collision-box ownership and hollow halos on all six faces.
A headless compiler probe retains the actual compiled client method in a uniquely named test trait by removing its
side annotation from the test input. It checks generated dispatch, pass filtering and queued coordinates/colour/bounds.
That is **not** a physical-client construction, side-selection or GPU test. Existing side-filtering tests cover the
compiler separately; actual client generation, connector-dependent halos, lighting and previews remain required
checks in the [manual checklist](../../JAVA_MIGRATION_MANUAL_CHECKS.md).
ProjectRed's reference checkout is unchanged. Its migration must preserve registration order/names, wire the existing
configuration and halo queue, release the consumer, and validate the released jar in the pack. Keep ProjectRed's
external Scala trait and FMP's Scala-signature support until adoption and removal gates pass; the example does not
close consumer adoption or every other extension contract. See the [API index](../API.md).
+35
View File
@@ -2040,3 +2040,38 @@ differences belong in the [divergence ledger](../../JAVA_MIGRATION_DIVERGENCES.m
- Documentation-only change: checked wording, local links and diff whitespace. No production sources or fixtures
changed; the existing 571 JVM / 273 Forge checkpoint remains the runtime evidence. The post-commit build verifies
clean artifact versions under the existing workflow.
### 2026-09-05 — Java illuminated microblock extension example
- Traced ProjectRed `e173952e96a4`'s illuminated material/trait through registration, metadata, light aggregation and
client halo geometry. The existing public `MicroblockGenerator.registerTrait(String)` already selects Java input;
no production implementation change or new API was needed. Added Javadocs for registration before class loading.
- Committed baseline `c41ed8d` first: one Forge test proves retained external Scala-trait composition and class reuse
across face, hollow, corner, edge and post shapes. The baseline has 571 JVM / 274 Forge cases and 120 generated dumps.
- Added three compiling Java example files: an abstract top-level trait, block-backed generated material and ordinary
helper with consumer-supplied configuration/halo rendering. The trait uses Object-parameter delegation to avoid the
transformer's inherited-access constraints. Consumers call only public typed FMP APIs; no reflection or Scala
compile dependency is needed. The common light behavior and SideOnly client callback remain separate.
- Four Forge tests cover initialization registration of all metadata 16–31, both addTraits side inputs, all five
generated shape families, fresh instances/class caching, constructor material identity and saved state. Light
tests cover rounding/capping, matching membership, detached siblings, config switching and unbound failure. Halo
tests preserve collision-box ownership and the hollow opening's trimmed strips across all six orientations.
- A uniquely named headless compiler probe retains the actual Java client method by removing only its test-input
side annotation, then verifies generated dispatch, pass filtering and queued coordinates/colour/bounds. It does
not establish physical-client generation, side selection or GPU correctness. Those checks and consumer config/halo
wiring remain explicit adoption gates; ProjectRed's checkout/released code were not changed.
- The test mod registers a distinct lamp and 16 known fixture materials. The default-content test retains an exact
inventory assertion, including these additions, rather than ignoring unexpected entries. Archived consumers use
a separate disposable world: the old test mod cannot load a world containing the new fixture block without a
missing-mapping prompt. The original test-world configuration was restored after the archived run.
- Validation: normal and clean formatting/checkstyle/build plus Java 8 Forge pass with **571 JVM / 278 Forge tests**,
zero failures/errors/skips. All **571 archived JVM / 274 archived Forge** cases pass, with a byte-identical archived
Forge mod. Production remains **444 class APIs, 17 ScalaSignature payloads and 3,761 unchanged method bodies**;
the 120 baseline dump bodies are retained after mapping only allocation-order microblock self-names, and ten
extension/probe dumps are added. All other baseline dump hashes match exactly. The three examples compile
with Scala excluded and have no Scala/reflection bytecode references. The `+719` pack retains all 386 member/type/
reflection rows across 27 consumers. Packaged source and Java 8 bytecode are checked; the post-commit build verifies
all five mod versions in dev/release jars. Evidence: `run/migration-illuminated-extension-reference/`.
- Updated the API index, plan, adoption ledger and manual checklist. Next bounded task: converter registration and
lifecycle guidance; broader transformed-tile compilation guidance and remaining audited reflection replacements
remain separate. The performance pass, consumer release/adoption and final Scala removal gates are unchanged.
@@ -0,0 +1,30 @@
package codechicken.multipart.examples;
import java.util.BitSet;
import net.minecraft.block.Block;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockGenerator.IGeneratedMaterial;
/** Example material whose upper metadata bit means illuminated and low bits select the lamp colour. */
public final class IlluminatedMicroMaterial extends BlockMicroMaterial implements IGeneratedMaterial {
private final int traitId;
public IlluminatedMicroMaterial(Block lamp, int meta, int traitId) {
super(lamp, meta);
this.traitId = traitId;
}
@Override
public void addTraits(BitSet traits, MicroblockClass microClass, boolean client) {
traits.set(traitId);
}
@Override
public int getCutterStrength() {
return block().getHarvestLevel(meta() % 16);
}
}
@@ -0,0 +1,122 @@
package codechicken.multipart.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.BooleanSupplier;
import net.minecraft.block.Block;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Transformation;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.HollowMicroblock;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockGenerator;
import codechicken.multipart.TMultiPart;
/** Compiling example for docs/api/MICROBLOCK_EXTENSIONS.md; the consumer supplies its config and halo renderer. */
public final class IlluminatedMicroblockExample {
public static BooleanSupplier dimLampParts = () -> false;
/**
* Install on the physical client before rendering, e.g. a lambda forwarding to ProjectRed's RenderHalo.addLight.
*/
public static HaloRenderer haloRenderer;
public interface HaloRenderer {
void addLight(int x, int y, int z, int colour, Cuboid6 bounds);
}
private IlluminatedMicroblockExample() {}
/** Call once during mod initialization, after the lamp block is registered and before FMP builds material IDs. */
public static void registerMaterials(Block lamp) {
int traitId = MicroblockGenerator.registerTrait("codechicken.multipart.examples.IlluminatedMicroblockTrait");
for (int meta = 16; meta < 32; meta++) {
MicroMaterialRegistry.registerMaterial(
new IlluminatedMicroMaterial(lamp, meta, traitId),
BlockMicroMaterial.materialKey(lamp, meta));
}
}
/** Object is deliberate: the transformed trait interface does not inherit Microblock in the JVM type system. */
public static int lightValue(Object trait) {
Microblock part = (Microblock) trait;
if (dimLampParts.getAsBoolean()) {
// Capture matching parts before size callbacks, as the reference's strict collection pipeline does.
List<Microblock> selected = new ArrayList<>();
for (TMultiPart sibling : part.tile().jPartList()) {
if (sibling instanceof IlluminatedMicroblockTrait) selected.add((Microblock) sibling);
}
double total = 0;
for (Microblock sibling : selected) total += sibling.getSize() / 8D;
return Math.min(15, (int) (15 * total));
}
for (TMultiPart sibling : part.tile().jPartList()) {
if (sibling instanceof IlluminatedMicroblockTrait) return 15;
}
return 0;
}
/** Halo submission is a client responsibility; the geometry itself is headlessly testable. */
public static void renderHalo(Object trait, int pass) {
if (pass != 0) return;
Microblock part = (Microblock) trait;
List<Cuboid6> boxes = haloBoxes(part);
int colour = ((IlluminatedMicroMaterial) part.getIMaterial()).meta() - 16;
for (Cuboid6 box : boxes) haloRenderer.addLight(part.x(), part.y(), part.z(), colour, box);
}
public static List<Cuboid6> haloBoxes(Microblock part) {
double expansion = 0.025;
if (part instanceof HollowMicroblock) {
int size = ((HollowMicroblock) part).getHollowSize();
double near = 0.5 - size / 32D;
double far = 0.5 + size / 32D;
double thickness = (part.shape() >> 4) / 8D;
Transformation rotation = Rotation.sideRotations[part.shape() & 15].at(Vector3.center);
List<Cuboid6> boxes = Arrays.asList(
new Cuboid6(
-expansion,
-expansion,
-expansion,
1 + expansion,
thickness + expansion,
near + expansion),
new Cuboid6(
-expansion,
-expansion,
far - expansion,
1 + expansion,
thickness + expansion,
1 + expansion),
new Cuboid6(
-expansion,
-expansion,
near + expansion,
near + expansion,
thickness + expansion,
far - expansion),
new Cuboid6(
far - expansion,
-expansion,
near + expansion,
1 + expansion,
thickness + expansion,
far - expansion));
for (Cuboid6 box : boxes) box.apply(rotation);
return boxes;
}
List<Cuboid6> source = new ArrayList<>();
for (Cuboid6 box : part.getCollisionBoxes()) source.add(box);
List<Cuboid6> expanded = new ArrayList<>();
for (Cuboid6 box : source) expanded.add(box.copy().expand(expansion));
return expanded;
}
}
@@ -0,0 +1,30 @@
package codechicken.multipart.examples;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.Microblock;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/** Register by name before loading this Java class; FMP transforms it into a runtime trait interface. */
public abstract class IlluminatedMicroblockTrait extends Microblock {
public IlluminatedMicroblockTrait() {
super(0);
}
@Override
public boolean shouldRenderDynamic() {
return true;
}
@Override
public int getLightValue() {
return IlluminatedMicroblockExample.lightValue(this);
}
@Override
@SideOnly(Side.CLIENT)
public void renderDynamic(Vector3 pos, float frame, int pass) {
IlluminatedMicroblockExample.renderHalo(this, pass);
}
}
@@ -395,6 +395,11 @@ class DefaultContentFunctionalTest {
add(expectedNames, expectedRemaps, Blocks.grass, "minecraft:grass", 0);
add(expectedNames, expectedRemaps, Blocks.mycelium, "minecraft:mycelium", 0);
expectedNames.add(MissingMicroMaterial.key());
for (int meta = 16; meta < 32; meta++) {
expectedNames.add(
codechicken.microblock.BlockMicroMaterial
.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, meta));
}
Collections.sort(expectedNames);
Tuple2<String, IMicroMaterial>[] idMap = MicroMaterialRegistry.getIdMap();
@@ -407,12 +412,14 @@ class DefaultContentFunctionalTest {
assertEquals(TopMicroMaterial.class, entry._2().getClass());
} else if (MissingMicroMaterial.key().equals(entry._1())) {
assertSame(MissingMicroMaterial$.MODULE$, entry._2());
} else if (entry._1().startsWith("ForgeMultipartTests:illuminated_lamp_")) {
assertEquals(codechicken.multipart.examples.IlluminatedMicroMaterial.class, entry._2().getClass());
} else {
assertEquals(BlockMicroMaterial.class, entry._2().getClass(), entry._1());
}
}
assertEquals(103, expectedNames.size());
assertEquals(119, expectedNames.size());
assertEquals(expectedNames, actualNames);
assertEquals(expectedRemaps, materialRemaps());
}
@@ -5,6 +5,8 @@ import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
@@ -21,12 +23,14 @@ import org.junit.platform.reporting.legacy.xml.LegacyXmlReportGeneratingListener
import codechicken.microblock.MicroblockGenerator;
import codechicken.multipart.MultipartGenerator;
import codechicken.multipart.examples.IlluminatedMicroblockExample;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerAboutToStartEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.registry.GameRegistry;
@Mod(
modid = "ForgeMultipartTests",
@@ -42,9 +46,12 @@ public final class ForgeMultipartFunctionalTestMod {
static boolean serverAboutToStart;
static boolean serverStarted;
static int externalScalaMicroblockTraitId;
static Block illuminatedLamp;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
illuminatedLamp = new Block(Material.glass) {};
GameRegistry.registerBlock(illuminatedLamp, "illuminated_lamp");
preInitialized = true;
}
@@ -54,6 +61,7 @@ public final class ForgeMultipartFunctionalTestMod {
MultipartGenerator.registerPassThroughInterface(GeneratorPassThroughFixture.class.getName(), false, true);
externalScalaMicroblockTraitId = MicroblockGenerator
.registerTrait("codechicken.multipart.test.ExternalScalaMicroblockFixture");
IlluminatedMicroblockExample.registerMaterials(illuminatedLamp);
initialized = true;
}
@@ -0,0 +1,228 @@
package codechicken.multipart.test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.nbt.NBTTagCompound;
import org.junit.jupiter.api.Test;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import codechicken.lib.asm.ASMHelper;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Vector3;
import codechicken.microblock.BlockMicroMaterial;
import codechicken.microblock.CornerMicroClass$;
import codechicken.microblock.EdgeMicroClass$;
import codechicken.microblock.FaceMicroClass$;
import codechicken.microblock.HollowMicroClass$;
import codechicken.microblock.MicroMaterialRegistry;
import codechicken.microblock.Microblock;
import codechicken.microblock.MicroblockClass;
import codechicken.microblock.MicroblockGenerator;
import codechicken.microblock.PostMicroClass$;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.examples.IlluminatedMicroMaterial;
import codechicken.multipart.examples.IlluminatedMicroblockExample;
import codechicken.multipart.examples.IlluminatedMicroblockTrait;
class IlluminatedMicroblockFunctionalTest {
@Test
void registeredJavaMaterialComposesWithEveryShapeAndKeepsPersistenceAndClassCaching() throws Exception {
assertTrue(IlluminatedMicroblockTrait.class.isInterface());
assertThrows(
NoSuchMethodException.class,
() -> IlluminatedMicroblockTrait.class
.getDeclaredMethod("renderDynamic", Vector3.class, float.class, int.class));
for (int meta = 16; meta < 32; meta++) {
IlluminatedMicroMaterial material = (IlluminatedMicroMaterial) MicroMaterialRegistry
.getMaterial(BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, meta));
assertSame(ForgeMultipartFunctionalTestMod.illuminatedLamp, material.block());
assertEquals(meta, material.meta());
BitSet server = new BitSet();
server.set(10000);
BitSet client = (BitSet) server.clone();
material.addTraits(server, FaceMicroClass$.MODULE$, false);
material.addTraits(client, FaceMicroClass$.MODULE$, true);
assertEquals(server, client);
assertEquals(2, server.cardinality());
}
for (MicroblockClass factory : families()) {
Microblock first = create(factory, 19);
Microblock second = create(factory, 31);
assertTrue(first instanceof IlluminatedMicroblockTrait);
assertSame(factory, first.microClass());
assertSame(first.getClass(), second.getClass());
assertNotSame(first, second);
assertTrue(first.shouldRenderDynamic());
assertNull(first.tile());
first.setShape(3, slot(factory));
NBTTagCompound tag = new NBTTagCompound();
first.save(tag);
assertEquals(
BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, 19),
tag.getString("material"));
second.load(tag);
assertEquals(first.shape(), second.shape());
assertEquals(first.material(), second.material());
}
List<Integer> seenMetadata = new ArrayList<>();
Block lamp = new Block(Material.glass) {
@Override
public int getHarvestLevel(int metadata) {
seenMetadata.add(metadata);
return metadata;
}
};
for (int meta = 16; meta < 32; meta++) {
assertEquals(meta - 16, new IlluminatedMicroMaterial(lamp, meta, 0).getCutterStrength());
}
assertEquals(16, seenMetadata.size());
}
@Test
void lightAggregationUsesOnlyTraitMembersWithReferenceRoundingAndNoDetachedFilter() {
Microblock first = create(FaceMicroClass$.MODULE$, 16);
Microblock second = create(CornerMicroClass$.MODULE$, 17);
Microblock plain = FaceMicroClass$.MODULE$.create(false, MicroMaterialRegistry.materialID("minecraft:stone"));
TileMultipart tile = new TileMultipart();
first.bind(tile);
first.setShape(1, 0);
second.setShape(2, 7);
tile.setPartList(Arrays.asList(first, plain, second));
try {
IlluminatedMicroblockExample.dimLampParts = () -> true;
assertEquals(5, first.getLightValue());
assertNull(second.tile(), "Detached siblings are deliberately included by jPartList traversal");
second.setShape(7, 7);
assertEquals(15, first.getLightValue());
tile.setPartList(Arrays.asList(plain));
assertEquals(0, first.getLightValue());
IlluminatedMicroblockExample.dimLampParts = () -> false;
assertEquals(0, first.getLightValue());
tile.setPartList(Arrays.asList(second));
assertEquals(15, first.getLightValue());
first.bind(null);
assertThrows(NullPointerException.class, first::getLightValue);
} finally {
IlluminatedMicroblockExample.dimLampParts = () -> false;
}
}
@Test
void haloGeometryCopiesCollisionBoundsAndKeepsHollowOpeningOnEverySide() {
for (MicroblockClass factory : new MicroblockClass[] { FaceMicroClass$.MODULE$, CornerMicroClass$.MODULE$,
EdgeMicroClass$.MODULE$, PostMicroClass$.MODULE$ }) {
Microblock part = create(factory, 16);
part.setShape(2, slot(factory));
List<Cuboid6> original = new ArrayList<>();
for (Cuboid6 box : part.getCollisionBoxes()) original.add(box.copy());
List<Cuboid6> halo = IlluminatedMicroblockExample.haloBoxes(part);
assertEquals(original.size(), halo.size());
int i = 0;
for (Cuboid6 box : part.getCollisionBoxes()) {
assertBox(original.get(i), box);
assertBox(original.get(i).copy().expand(0.025), halo.get(i));
i++;
}
}
Microblock hollow = create(HollowMicroClass$.MODULE$, 18);
for (int side = 0; side < 6; side++) {
hollow.setShape(2, side);
List<Cuboid6> halo = IlluminatedMicroblockExample.haloBoxes(hollow);
assertEquals(4, halo.size());
// Default opening width is 8/16. These golden local bounds include the reference's trimmed middle strips.
Cuboid6[] local = { new Cuboid6(-0.025, -0.025, -0.025, 1.025, 0.275, 0.275),
new Cuboid6(-0.025, -0.025, 0.725, 1.025, 0.275, 1.025),
new Cuboid6(-0.025, -0.025, 0.275, 0.275, 0.275, 0.725),
new Cuboid6(0.725, -0.025, 0.275, 1.025, 0.275, 0.725) };
for (int i = 0; i < 4; i++) {
assertBox(local[i].apply(Rotation.sideRotations[side].at(Vector3.center)), halo.get(i));
}
}
}
@Test
void retainedClientMethodCompilesAndSubmitsHaloWithoutAClientOrGpu() throws Exception {
// Exercise the actual compiled client body with a uniquely named compiler probe. This does not simulate a
// physical
// client.
try {
ClassNode input = ASMHelper.createClassNode(
Launch.classLoader.getClassBytes("codechicken.multipart.examples.IlluminatedMicroblockTrait"),
0);
input.name = "codechicken/multipart/test/IlluminatedClientProbe";
MethodNode render = input.methods.stream().map(m -> (MethodNode) m)
.filter(m -> m.name.equals("renderDynamic")).findFirst().get();
assertTrue(render.visibleAnnotations.stream().anyMatch(a -> a.desc.endsWith("/SideOnly;")));
render.visibleAnnotations.clear(); // Keep just this body for the headless compiler probe.
MixinClassesFunctionalTest.COMPILER.registerJavaTrait(input);
Class<?> composite = MixinClassesFunctionalTest.COMPILER.mixinClasses(
"codechicken/multipart/test/IlluminatedClientComposite",
"codechicken/microblock/Microblock",
MixinClassesFunctionalTest.seq("codechicken/microblock/FaceMicroblock", input.name));
Microblock part = (Microblock) composite.getConstructor(int.class).newInstance(
MicroMaterialRegistry.materialID(
BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, 21)));
part.setShape(2, 0);
TileMultipart tile = new TileMultipart();
tile.xCoord = 4;
tile.yCoord = 5;
tile.zCoord = 6;
part.bind(tile);
List<Cuboid6> submitted = new ArrayList<>();
IlluminatedMicroblockExample.haloRenderer = (x, y, z, colour, bounds) -> {
assertEquals(Arrays.asList(4, 5, 6, 5), Arrays.asList(x, y, z, colour));
submitted.add(bounds);
};
java.lang.reflect.Method method = composite
.getDeclaredMethod("renderDynamic", Vector3.class, float.class, int.class);
method.invoke(part, new Vector3(99, 99, 99), 0.5F, 1);
assertTrue(submitted.isEmpty());
method.invoke(part, new Vector3(99, 99, 99), 0.5F, 0);
assertEquals(1, submitted.size());
assertBox(IlluminatedMicroblockExample.haloBoxes(part).get(0), submitted.get(0));
} finally {
IlluminatedMicroblockExample.haloRenderer = null;
}
}
private static int slot(MicroblockClass factory) {
if (factory == CornerMicroClass$.MODULE$) return 7;
if (factory == EdgeMicroClass$.MODULE$) return 15;
return 0;
}
private static MicroblockClass[] families() {
return new MicroblockClass[] { FaceMicroClass$.MODULE$, HollowMicroClass$.MODULE$, CornerMicroClass$.MODULE$,
EdgeMicroClass$.MODULE$, PostMicroClass$.MODULE$ };
}
private static Microblock create(MicroblockClass factory, int meta) {
return MicroblockGenerator.create(
factory,
MicroMaterialRegistry.materialID(
BlockMicroMaterial.materialKey(ForgeMultipartFunctionalTestMod.illuminatedLamp, meta)),
false);
}
private static void assertBox(Cuboid6 expected, Cuboid6 actual) {
assertEquals(expected.min.x, actual.min.x, 1e-9);
assertEquals(expected.min.y, actual.min.y, 1e-9);
assertEquals(expected.min.z, actual.min.z, 1e-9);
assertEquals(expected.max.x, actual.max.x, 1e-9);
assertEquals(expected.max.y, actual.max.y, 1e-9);
assertEquals(expected.max.z, actual.max.z, 1e-9);
}
}
@@ -36,10 +36,30 @@ public final class MicroblockGenerator {
return MicroblockGenerator$.MODULE$.getId(trait);
}
/**
* Registers an already loadable trait, including retained Scala trait interfaces. For a Java source trait that FMP
* must rewrite into an interface, use {@link #registerTrait(String)} before its class is loaded instead.
*/
public static int registerTrait(Class<?> trait) {
return MicroblockGenerator$.MODULE$.registerTrait(trait);
}
/**
* Registers a microblock trait by binary name (dots or slashes accepted), returning its generator-local ID.
* Existing registration returns the same ID. Use this overload for Java source traits before any class literal,
* instance or other use loads that class; FMP must first transform its class bytes into a runtime interface.
* Register during mod initialization, before material registration and construction that require this trait.
*
* Java input is a top-level class extending Microblock (possibly abstract), with a no-argument constructor. Its
* direct superclass constructor call is discarded during trait initialization; the generated microblock receives
* the real material ID. Client-only overrides must carry SideOnly(CLIENT). The existing transformer has bytecode
* restrictions: keep inherited state access and substantial logic in an ordinary helper, passing the trait as
* Object and casting to Microblock there. Do not instantiate or invoke a transformed trait as a Java class. Use
* stable Microblock methods or a separately declared capability interface for consumer dispatch.
*
* The material's {@link IGeneratedMaterial#addTraits(BitSet, MicroblockClass, boolean)} callback adds this ID to
* each requested shape/side. Registration does not register a material or remove the retained Scala trait path.
*/
public static int registerTrait(String trait) {
return MicroblockGenerator$.MODULE$.registerTrait(trait);
}