refactor: port client tile traits to java

Preserve the exact generated client interfaces, render-cache behavior, and ordered display ticks.

Teach Java mixin generation to linearize a registered parent and exclude transient runtime caches from copying.
This commit is contained in:
Algent committed 2026-08-30 15:25:15 +02:00
1 parent 6417e9b731
commit 970e888b7f
17 files changed
+448 -227

No files matched your search

@@ -7,6 +7,8 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
@@ -43,11 +45,11 @@ class TileMultipartClientFunctionalTest {
setParts(tile, dynamicOnly, fixed, ticking);
TileMultipartClient client = (TileMultipartClient) tile;
client.updateRenderCache();
invokeUpdateRenderCache(client);
assertArrayEquals(new TMultiPart[] { fixed }, staticCache(client));
assertArrayEquals(new TMultiPart[] { dynamicOnly, ticking }, dynamicCache(client));
assertTrue(client.hasDynamicParts());
assertTrue((Boolean) invokeClient(client, "hasDynamicParts", boolean.class));
assertEquals(1, dynamicOnly.doesTickCalls);
assertEquals(1, dynamicOnly.dynamicCalls);
assertEquals(1, fixed.doesTickCalls);
@@ -66,11 +68,11 @@ class TileMultipartClientFunctionalTest {
tile.partList_$eq(null);
TileMultipartClient client = (TileMultipartClient) tile;
client.updateRenderCache();
invokeUpdateRenderCache(client);
assertEquals(0, staticCache(client).length);
assertEquals(0, dynamicCache(client).length);
assertFalse(client.hasDynamicParts());
assertFalse((Boolean) invokeClient(client, "hasDynamicParts", boolean.class));
assertBounds(cachedBounds(client), -3.0, 7.0, 11.0, -2.0, 8.0, 12.0);
}
@@ -84,8 +86,9 @@ class TileMultipartClientFunctionalTest {
assertNull(staticCache(client));
assertNull(cachedBounds(client));
assertFalse(client.shouldRenderInPass(17));
AxisAlignedBB bounds = client.getRenderBoundingBox();
assertFalse(
(Boolean) invokeClient(client, "shouldRenderInPass", boolean.class, new Class<?>[] { int.class }, 17));
AxisAlignedBB bounds = (AxisAlignedBB) invokeClient(client, "getRenderBoundingBox", AxisAlignedBB.class);
assertEquals(0, staticCache(client).length);
assertEquals(0, dynamicCache(client).length);
@@ -95,24 +98,32 @@ class TileMultipartClientFunctionalTest {
@Test
void dynamicRenderingReturnsBeforeTouchingTheCacheWhenTheFlagIsFalse() throws Exception {
TileMultipartClient client = (TileMultipartClient) newClientTile();
TileMultipart tile = newClientTile();
TileMultipartClient client = (TileMultipartClient) tile;
RenderPart dynamic = new RenderPart("dynamic", true, false, Cuboid6.full);
setDynamicCache(client, new TMultiPart[] { dynamic });
client.hasDynamicParts_$eq(false);
invokeClient(client, "hasDynamicParts_$eq", void.class, new Class<?>[] { boolean.class }, false);
client.renderDynamic(null, 0.5F, 1);
invokeClient(
client,
"renderDynamic",
void.class,
new Class<?>[] { codechicken.lib.vec.Vector3.class, float.class, int.class },
null,
0.5F,
1);
assertEquals(0, dynamic.renderDynamicCalls);
}
@Test
void baseRandomDisplayTickIsANoOp() {
void baseRandomDisplayTickIsANoOp() throws Exception {
TileMultipartClient client = (TileMultipartClient) newClientTile();
client.randomDisplayTick(new Random(1L));
invokeClient(client, "randomDisplayTick", void.class, new Class<?>[] { Random.class }, new Random(1L));
}
@Test
void randomDisplayTickVisitsOnlyMatchingPartsInOrderWithTheSameRandom() {
void randomDisplayTickVisitsOnlyMatchingPartsInOrderWithTheSameRandom() throws Exception {
TileMultipart tile = newRandomDisplayTickTile();
List<String> calls = new ArrayList<>();
DisplayPart first = new DisplayPart("first", calls);
@@ -121,7 +132,12 @@ class TileMultipartClientFunctionalTest {
setParts(tile, first, skipped, second);
Random random = new Random(2L);
((TRandomDisplayTickTile) tile).randomDisplayTick(random);
invokeClient(
(TileMultipartClient) tile,
"randomDisplayTick",
void.class,
new Class<?>[] { Random.class },
random);
assertEquals(Arrays.asList("first", "second"), calls);
assertSame(random, first.lastRandom);
@@ -146,6 +162,30 @@ class TileMultipartClientFunctionalTest {
tile.partList_$eq(JavaConversions.asScalaBuffer(Arrays.asList(parts)).toList());
}
private static void invokeUpdateRenderCache(TileMultipartClient client) throws Exception {
invokeClient(client, "updateRenderCache", void.class);
}
private static Object invokeClient(TileMultipartClient client, String name, Class<?> returnType, Object... args)
throws Exception {
return invokeClient(client, name, returnType, new Class<?>[0], args);
}
private static Object invokeClient(TileMultipartClient client, String name, Class<?> returnType,
Class<?>[] parameterTypes, Object... args) throws Exception {
try {
return MethodHandles.publicLookup()
.findVirtual(TileMultipartClient.class, name, MethodType.methodType(returnType, parameterTypes))
.bindTo(client).invokeWithArguments(args);
} catch (Exception exception) {
throw exception;
} catch (Error error) {
throw error;
} catch (Throwable throwable) {
throw new AssertionError(throwable);
}
}
private static TMultiPart[] staticCache(TileMultipartClient client) throws Exception {
return (TMultiPart[]) generatedField(client, "staticCache").get(client);
}
@@ -194,9 +194,9 @@ public class BlockMultipart extends Block {
public boolean addHitEffects(World world, MovingObjectPosition hit, EffectRenderer effectRenderer) {
TileMultipartClient tile = getClientTile(world, hit.blockX, hit.blockY, hit.blockZ);
if (tile != null) {
// TileMultipartClient is a Scala trait, so it is a bare interface here and carries no TileMultipart
// members.
TileMultipart parts = (TileMultipart) tile;
// The mixin transformer turns TileMultipartClient into an interface at runtime, so retain the cast in
// bytecode even though the Java source model extends TileMultipart.
TileMultipart parts = TileMultipart.class.cast(tile);
Tuple2<Object, ExtendedMOP> reduced = reduceMOP(hit);
int index = (Integer) reduced._1();
if (index < parts.partList().size()) {
@@ -291,7 +291,7 @@ public class BlockMultipart extends Block {
public void randomDisplayTick(World world, int x, int y, int z, Random random) {
TileMultipartClient tile = getClientTile(world, x, y, z);
if (tile != null) {
tile.randomDisplayTick(random);
TileMultipart.class.cast(tile).randomDisplayTick(random);
}
}
@@ -35,7 +35,9 @@ object MultipartGenerator extends ScratchBitSet {
private val partTraitMap_c = Map[Class[_], BitSet]()
private val partTraitMap_s = Map[Class[_], BitSet]()
private val clientTraitId =
MultipartMixinFactory.registerTrait(classOf[TileMultipartClient])
MultipartMixinFactory.registerTrait(
"codechicken.multipart.TileMultipartClient"
)
private def partTraitMap(client: Boolean) =
if (client) partTraitMap_c else partTraitMap_s
@@ -50,7 +50,7 @@ public final class MultipartRenderer$ extends TileEntitySpecialRenderer implemen
state.pullLightmapInstance();
state.useNormals = true;
client.renderDynamic(new Vector3(x, y, z), f, MinecraftForgeClient.getRenderPass());
tile.renderDynamic(new Vector3(x, y, z), f, MinecraftForgeClient.getRenderPass());
}
@Override
@@ -80,7 +80,7 @@ public final class MultipartRenderer$ extends TileEntitySpecialRenderer implemen
CCRenderState state = CCRenderState.instance();
state.resetInstance();
state.lightMatrix.locate(world, x, y, z);
boolean b = client.renderStatic(world, new Vector3(x, y, z), renderer);
boolean b = tile.renderStatic(world, new Vector3(x, y, z), renderer);
state.lightMatrix.access = null;
return b;
}
@@ -4,8 +4,10 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
@@ -14,6 +16,7 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import codechicken.lib.data.MCDataOutput;
@@ -259,6 +262,17 @@ public class TileMultipart extends TileEntity implements IChunkLoadTile {
worldObj.func_147479_m(xCoord, yCoord, zCoord);
}
/** Client render hook overridden by generated tiles carrying TileMultipartClient. */
public boolean renderStatic(IBlockAccess world, Vector3 position, RenderBlocks renderer) {
return false;
}
/** Client render hook overridden by generated tiles carrying TileMultipartClient. */
public void renderDynamic(Vector3 position, float frame, int pass) {}
/** Client particle hook overridden by generated tiles carrying TRandomDisplayTickTile. */
public void randomDisplayTick(Random random) {}
/** Helper function for calling a second level notify on a side (eg indirect power from a lever). */
public void notifyNeighborChange(int side) {
BlockCoord pos = new BlockCoord(this).offset(side);
@@ -0,0 +1,183 @@
package codechicken.multipart;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.ForgeHooksClient;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import scala.collection.Iterator;
import scala.collection.Seq;
/** Client-side multipart render-cache mixin. */
public class TileMultipartClient extends TileMultipart {
private transient AxisAlignedBB cachedRenderBounds;
private transient TMultiPart[] staticCache;
private transient TMultiPart[] dynamicCache;
public transient boolean hasDynamicParts;
public boolean hasDynamicParts() {
return hasDynamicParts;
}
public void hasDynamicParts_$eq(boolean value) {
hasDynamicParts = value;
}
public void updateRenderCache() {
Seq<TMultiPart> parts = TileMultipartClientAccess.partList(this);
if (parts != null) {
List<TMultiPart> dynamicParts = new ArrayList<>();
List<TMultiPart> staticParts = new ArrayList<>();
Iterator<TMultiPart> iterator = parts.iterator();
while (iterator.hasNext()) {
TMultiPart part = iterator.next();
if (part.doesTick() || part.shouldRenderDynamic()) {
dynamicParts.add(part);
} else {
staticParts.add(part);
}
}
TMultiPart[] statics = staticParts.toArray(new TMultiPart[staticParts.size()]);
TMultiPart[] dynamics = dynamicParts.toArray(new TMultiPart[dynamicParts.size()]);
Cuboid6 bounds = null;
for (TMultiPart part : statics) {
Cuboid6 partBounds = part.getRenderBounds();
if (bounds == null) {
bounds = partBounds.copy();
} else {
bounds.enclose(partBounds);
}
}
for (TMultiPart part : dynamics) {
Cuboid6 partBounds = part.getRenderBounds();
if (bounds == null) {
bounds = partBounds.copy();
} else {
bounds.enclose(partBounds);
}
}
if (bounds == null) {
bounds = Cuboid6.full;
}
bounds.add(TileMultipartClientAccess.position(this));
cachedRenderBounds = bounds.toAABB();
staticCache = statics;
dynamicCache = dynamics;
hasDynamicParts = dynamics.length > 0;
} else {
staticCache = new TMultiPart[0];
dynamicCache = new TMultiPart[0];
hasDynamicParts = false;
cachedRenderBounds = TileMultipartClientAccess.fullBlockBounds(this);
}
}
@Override
public boolean renderStatic(IBlockAccess world, Vector3 vector, RenderBlocks renderer) {
if (staticCache == null) {
updateRenderCache();
}
boolean rendered = false;
TMultiPart[] statics = staticCache;
if (statics != null) {
for (TMultiPart part : statics) {
rendered |= TileMultipartClientAccess.renderPart(part, world, vector, renderer);
}
}
TMultiPart[] dynamics = dynamicCache;
if (dynamics != null) {
for (TMultiPart part : dynamics) {
rendered |= TileMultipartClientAccess.renderPart(part, world, vector, renderer);
}
}
return rendered;
}
@Override
public void renderDynamic(Vector3 position, float frame, int pass) {
if (!hasDynamicParts) {
return;
}
TMultiPart[] dynamics = dynamicCache;
if (dynamics != null) {
for (TMultiPart part : dynamics) {
if (part != null) {
part.renderDynamic(position, frame, pass);
}
}
}
}
@Override
public void randomDisplayTick(Random random) {}
@Override
public boolean shouldRenderInPass(int pass) {
if (staticCache == null) {
updateRenderCache();
}
return hasDynamicParts;
}
@Override
public AxisAlignedBB getRenderBoundingBox() {
if (cachedRenderBounds == null) {
updateRenderCache();
}
return cachedRenderBounds;
}
@Override
public void markRender() {
super.markRender();
updateRenderCache();
}
}
/** Keeps inherited tile access and client rendering calls outside the generated trait transformer. */
final class TileMultipartClientAccess {
private TileMultipartClientAccess() {}
static Seq<TMultiPart> partList(Object tile) {
return ((TileMultipart) tile).partList();
}
static Vector3 position(Object tile) {
return Vector3.fromTileEntity((TileMultipart) tile);
}
static AxisAlignedBB fullBlockBounds(Object tile) {
TileMultipart multipart = (TileMultipart) tile;
return AxisAlignedBB.getBoundingBox(
multipart.xCoord,
multipart.yCoord,
multipart.zCoord,
multipart.xCoord + 1,
multipart.yCoord + 1,
multipart.zCoord + 1);
}
static boolean renderPart(TMultiPart part, IBlockAccess world, Vector3 vector, RenderBlocks renderer) {
if (part == null) {
return false;
}
if (part instanceof ISBRHPart) {
return ((ISBRHPart) part).renderWorldBlock(world, (int) vector.x, (int) vector.y, (int) vector.z, renderer);
}
return part.renderStatic(vector, ForgeHooksClient.getWorldRenderPass());
}
}
@@ -1,154 +0,0 @@
package codechicken.multipart
import java.util.Random
import codechicken.lib.vec.{Cuboid6, Vector3}
import net.minecraft.client.renderer.RenderBlocks
import net.minecraft.util.AxisAlignedBB
import net.minecraft.world.IBlockAccess
import net.minecraftforge.client.ForgeHooksClient
import scala.collection.JavaConversions._
trait TileMultipartClient extends TileMultipart {
private var cachedRenderBounds: AxisAlignedBB = null
private var staticCache: Array[TMultiPart] = null
private var dynamicCache: Array[TMultiPart] = null
var hasDynamicParts: Boolean = false
def updateRenderCache() {
if (partList != null) {
val (dynamic, static) =
partList.partition(p => p.doesTick || p.shouldRenderDynamic)
val sArr = static.toArray
val dArr = dynamic.toArray
var c: Cuboid6 = null
var i = 0
val allParts = sArr ++ dArr
while (i < allParts.length) {
val b = allParts(i).getRenderBounds
if (c == null) c = b.copy
else c.enclose(b)
i += 1
}
if (c == null) c = Cuboid6.full
c.add(Vector3.fromTileEntity(this))
cachedRenderBounds = c.toAABB
staticCache = sArr
dynamicCache = dArr
hasDynamicParts = dArr.length > 0
} else {
staticCache = Array.empty
dynamicCache = Array.empty
hasDynamicParts = false
cachedRenderBounds = AxisAlignedBB.getBoundingBox(
xCoord,
yCoord,
zCoord,
xCoord + 1,
yCoord + 1,
zCoord + 1
)
}
}
def renderStatic(
world: IBlockAccess,
vec: Vector3,
renderer: RenderBlocks
) = {
if (staticCache == null)
updateRenderCache()
var rendered = false
def renderPart(part: TMultiPart): Unit = {
if (part == null)
return
part match {
case isbrh: ISBRHPart =>
if (
isbrh.renderWorldBlock(
world,
vec.x.toInt,
vec.y.toInt,
vec.z.toInt,
renderer
)
) {
rendered = true
}
case _ =>
if (
part.renderStatic(
vec,
ForgeHooksClient.getWorldRenderPass
)
) {
rendered = true
}
}
}
val statics = staticCache
if (statics != null) {
var i = 0
val len = statics.length
while (i < len) {
renderPart(statics(i))
i += 1
}
}
val dynamics = dynamicCache
if (dynamics != null) {
var i = 0
val len = dynamics.length
while (i < len) {
renderPart(dynamics(i))
i += 1
}
}
rendered
}
def renderDynamic(pos: Vector3, frame: Float, pass: Int) {
if (!hasDynamicParts) return
val dynamics = dynamicCache
if (dynamics != null) {
var i = 0
val len = dynamics.length
while (i < len) {
if (dynamics(i) != null) dynamics(i).renderDynamic(pos, frame, pass)
i += 1
}
}
}
def randomDisplayTick(random: Random) {}
override def shouldRenderInPass(pass: Int) = {
if (staticCache == null) updateRenderCache()
hasDynamicParts
}
override def getRenderBoundingBox = {
if (cachedRenderBounds == null) updateRenderCache()
cachedRenderBounds
}
override def markRender(): Unit = {
super.markRender()
updateRenderCache()
}
}
@@ -556,7 +556,7 @@ object ASMMixinCompiler {
"Cannot register abstract class " + cnode.name + " as a java mixin trait. Use scala"
)
// val parentTraits = getAndRegisterParentTraits(cnode)
val parentTrait = getMixinInfo(cnode.superName)
val fields = cnode.fields
.map(f => (f.name, FieldMixin(f.name, f.desc, f.access)))
.toMap
@@ -591,7 +591,7 @@ object ASMMixinCompiler {
cnode.name,
null,
"java/lang/Object",
Array(cnode.interfaces: _*)
(cnode.interfaces ++ parentTrait.map(_.name)).distinct.toArray
)
def fname(name: String) = fields(name).accessName(cnode.name)
@@ -787,7 +787,14 @@ object ASMMixinCompiler {
staticTransform(mv, mnode)
}
cnode.methods.foreach(convertMethod)
def isGeneratedFieldAccessor(mnode: MethodNode) = fields.values.exists {
field =>
val name = field.accessName(cnode.name)
mnode.name == name && mnode.desc == "()" + field.desc ||
mnode.name == name + "_$eq" && mnode.desc == "(" + field.desc + ")V"
}
cnode.methods.filterNot(isGeneratedFieldAccessor).foreach(convertMethod)
define(inode.name, createBytes(inode, 0))
define(tnode.name, createBytes(tnode, 0))
@@ -796,8 +803,8 @@ object ASMMixinCompiler {
tnode.name,
MixinInfo(
tnode.name,
cnode.superName,
Seq(),
parentTrait.map(_.parent).getOrElse(cnode.superName),
parentTrait.toSeq,
fields.values.toSeq,
methods,
supers
@@ -67,10 +67,17 @@ class ASMMixinFactory[T](
}
val info = getClassInfo(cnode)
def concreteParent(info: ClassInfo): ClassInfo = info.superClass.map {
case i if i.isTrait => concreteParent(i)
case i => i
}.get
def concreteParent(info: ClassInfo): ClassInfo = getMixinInfo(
info.name
) match {
case Some(mixin) => getClassInfo(mixin.parent)
case None =>
info.superClass.map {
case i if i.isTrait || getMixinInfo(i.name).isDefined =>
concreteParent(i)
case i => i
}.get
}
val parentName = concreteParent(info).name
def checkParent(info: ClassInfo): Boolean =
@@ -14,8 +14,9 @@ import scala.collection.JavaConversions._
object MultipartMixinFactory extends ASMMixinFactory(classOf[TileMultipart]) {
override protected def autoCompleteJavaTrait(cnode: ClassNode) {
val copyFields = cnode.fields.filter(f => (f.access & ACC_TRANSIENT) == 0)
if (
!cnode.fields.isEmpty && findMethod(
!copyFields.isEmpty && findMethod(
new ObfMapping(
cnode.name,
"copyFrom",
@@ -45,7 +46,7 @@ object MultipartMixinFactory extends ASMMixinFactory(classOf[TileMultipart]) {
val end = new Label()
mv.visitJumpInsn(IFEQ, end)
cnode.fields.foreach { f =>
copyFields.foreach { f =>
mv.visitVarInsn(ALOAD, 0)
mv.visitVarInsn(ALOAD, 1)
mv.visitFieldInsn(GETFIELD, cnode.name, f.name, f.desc)
@@ -28,15 +28,6 @@ class MultipartProxy_serverImpl {
config = new ConfigFile(new File(cfgdir, "multipart.cfg"))
.setComment("Multipart API config file")
GameRegistry.registerBlock(
new BlockMultipart().setBlockName("multipart"),
null,
"block"
)
block = Block.blockRegistry
.getObject("ForgeMultipart:block")
.asInstanceOf[BlockMultipart]
MultipartGenerator.registerTrait(
"codechicken.multipart.TSlottedPart",
"codechicken.multipart.scalatraits.TSlottedTile"
@@ -72,6 +63,15 @@ class MultipartProxy_serverImpl {
"codechicken.multipart.scalatraits.TTileChangeTile"
)
GameRegistry.registerBlock(
new BlockMultipart().setBlockName("multipart"),
null,
"block"
)
block = Block.blockRegistry
.getObject("ForgeMultipart:block")
.asInstanceOf[BlockMultipart]
MultipartSaveLoad.hookLoader()
}
@@ -0,0 +1,34 @@
package codechicken.multipart.scalatraits;
import java.util.Random;
import codechicken.multipart.IRandomDisplayTick;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
import codechicken.multipart.TileMultipartClient;
import scala.collection.Iterator;
/** Client mixin that dispatches random display ticks only to interested parts. */
public class TRandomDisplayTickTile extends TileMultipartClient {
@Override
public void randomDisplayTick(Random random) {
TRandomDisplayTickTileAccess.randomDisplayTick(this, random);
}
}
/** Keeps inherited part-list access outside the generated trait transformer. */
final class TRandomDisplayTickTileAccess {
private TRandomDisplayTickTileAccess() {}
static void randomDisplayTick(Object tile, Random random) {
Iterator<TMultiPart> parts = ((TileMultipart) tile).partList().iterator();
while (parts.hasNext()) {
TMultiPart part = parts.next();
if (part instanceof IRandomDisplayTick) {
((IRandomDisplayTick) part).randomDisplayTick(random);
}
}
}
}
@@ -1,14 +0,0 @@
package codechicken.multipart.scalatraits
import codechicken.multipart.TileMultipartClient
import codechicken.multipart.IRandomDisplayTick
import java.util.Random
/** Saves processor time looping on tiles that don't need it
*/
trait TRandomDisplayTickTile extends TileMultipartClient {
override def randomDisplayTick(random: Random) {
for (p @ (_p: IRandomDisplayTick) <- partList.iterator)
p.randomDisplayTick(random)
}
}