refactor: port TileMultipart to Java

Converts the central tile class and its companion object. TileMultipartClient
moves to its own Scala file unchanged: it is registered with the ASM
generator through registerTrait, so converting it is Phase 5
registerJavaTrait work rather than part of this step.

Every public member of the reference survives except protected$worldObj,
the accessor Scala emitted so the dropItems closure could reach the
protected field; no jar references it, and TileMultipartClient lost
nothing including its generated super accessor for markRender. All five
Scala-typed descriptors are preserved: partList and its setter, operate,
getOrConvertTile2's Tuple2, loadParts, and the Tuple2 rayTraceAll stores
into ExtendedMOP.data.

partList stays an immutable Scala List republished on each mutation, which
matches the reference semantics exactly and takes no performance decision;
that belongs to Phase 4 with profiling. Internal callers still go through
operate rather than a private loop, so a trait overriding it still sees
every call.

Recompiled Scala consumers need four adjustments, all source-only:
partList.apply(i) for indexing, renderID_$eq for assignment, an explicit
cast on getOrConvertTile2._2, and an explicit AbstractFunction1 for
operate since 2.11 will not adapt a lambda to Function1[_, BoxedUnit].
Eleven, one, two and one in-repo call sites respectively.

31 anonfun classes collapse to one Java anonymous class.

Validated with 90 plain-JVM tests, a clean build, and the Java 8 Forge
dedicated-server suite, which is the load-bearing check here because the
ASM generator builds composite tiles on top of this class.
This commit is contained in:
Algent committed 2026-08-15 11:15:03 +02:00
1 parent beb0995e60
commit cacc9a30a8
12 files changed
+1063 -826

No files matched your search

+79
View File
@@ -613,3 +613,82 @@ overloads build.
registration needs FML's active mod container, so real startup is the only place both factory overloads actually
run, and the suite resolves a part registered through each.
- Error paths that log remain uncovered headless, as before, because the multipart logger is null until preInit.
## 2026-08-14 — TileMultipart Java port
The central tile. Twelve jars reference it and about twenty-five of its members. `TileMultipartClient` was split into
its own Scala file and deliberately **not** converted: it is registered with the ASM generator through
`registerTrait`, so converting it is Phase 5 `registerJavaTrait` work with different machinery.
### Observable behavior
No known divergence. Parts are still appended in order, the list is still replaced rather than mutated so a previously
published `Seq` never changes under a caller, `operate` still skips parts whose tile is null, ticking still starts on
the first ticking part and stops when the last one leaves, `getLightValue` is still max-or-zero while
`getExplosionResistance` is still max-or-throws, occlusion still requires agreement in both directions, and
`canReplacePart` still excludes the outgoing part while rejecting a part already present.
`handlePacket` case 254 resolves the tile twice, once for the receiver and once for the argument, because the
reference used a by-name local def that re-evaluated `TileCache.findTile` at each use. Argument order is preserved.
The `assert` calls on part count, client removal and client addition become explicit `AssertionError` throws with the
same messages, since Scala's `assert` is always enabled here and Java's is not.
### Storage
`partList` remains a `scala.collection.immutable.List` published through `partList()Lscala/collection/Seq;`, which
five jars link against. Mutations copy to a Java list, mutate, and republish through `JavaConversions`, matching the
reference's allocate-a-new-Seq semantics exactly. No performance decision is taken here; that is Phase 4 work and
needs profiling first.
`operate` keeps its `(Lscala/Function1;)V` descriptor and internal callers still go through it, wrapping their action
in an `AbstractFunction1`. That preserves both the virtual dispatch, so any trait overriding `operate` still sees
every call, and the reference's per-call allocation.
### Preserved Scala-typed descriptors
- `partList()Lscala/collection/Seq;` and `partList_$eq(Lscala/collection/Seq;)V`
- `operate(Lscala/Function1;)V`
- `getOrConvertTile2(...)Lscala/Tuple2;`
- `loadParts(Lscala/collection/Iterable;)V`
- `rayTraceAll` still stores a `scala.Tuple2` into `ExtendedMOP.data`, which `EdgeMicroblock` reads back through
`getData[(Int, _)]`.
### Removed API
`protected$worldObj(TileMultipart)`, the public accessor Scala emitted so the `dropItems` closure could reach the
protected field. It is a compiler artifact and no jar references it. `TileMultipartClient` lost nothing, including its
generated super accessor for `markRender`, which Scala regenerated correctly against the Java superclass.
### Recompiled Scala consumers
The largest source-only divergence so far. Scala reads the Java signatures rather than a ScalaSignature, so:
- `tile.partList(i)` no longer parses as an index; it must be `tile.partList.apply(i)`. Eleven in-repo call sites
were updated.
- `TileMultipart.renderID = x` must become `renderID_$eq(x)`.
- `getOrConvertTile2` returns `Tuple2[TileMultipart, Object]` rather than `(TileMultipart, Boolean)`, so `_2` needs an
explicit cast. Two in-repo call sites.
- `operate { p => ... }` no longer accepts a lambda, because Scala 2.11 will not adapt `TMultiPart => Unit` to
`Function1[TMultiPart, BoxedUnit]`. The one in-repo caller, `TTileChangeTile`, now builds an `AbstractFunction1`.
Binary compatibility is unaffected in all four cases.
### Compiler artifacts
Accepted divergence: all 31 `TileMultipart$$anonfun$*` classes are removed, replaced by one Java anonymous class for
the `operate` adapter.
### Validation
- `TileMultipartCharacterizationTest`: 12 tests, 0 failures, 0 errors, unchanged from the Scala baseline.
- Complete plain-JVM suite: 90 tests, 0 failures, 0 errors.
- Clean `spotlessApply checkstyleTest build`: passing.
- Java 8 Forge dedicated-server suite: 5 tests, 0 failures, 0 errors. This is the load-bearing check: the ASM
generator builds composite tiles that extend this class and mix Scala traits into it, and the suite still generates
a `TSlottedTile` composite and two microblock classes.
- Every public member of the reference is still present except `protected$worldObj`, verified by name-level diff, and
`partList`, `operate`, `jPartList`, `getOrConvertTile2`, `multiPartChange`, `rayTraceAll` and `dropItems` were
checked descriptor by descriptor.
- World-dependent paths, NBT round trips through `createFromNBT`, and desc packets are not covered by tests and stay
on the manual checklist.
@@ -43,7 +43,8 @@ object EdgePlacement extends PlacementProperties {
val part = PostMicroClass.create(pmt.world.isRemote, pmt.material)
part.setShape(pmt.size, pmt.hit.sideHit >> 1)
if (pmt.doExpand) {
val hpart = pmt.htile.partList(ExtendedMOP.getData[(Int, _)](pmt.hit)._1)
val hpart =
pmt.htile.partList.apply(ExtendedMOP.getData[(Int, _)](pmt.hit)._1)
if (hpart.getType == PostMicroClass.getName) {
val mpart = hpart.asInstanceOf[Microblock]
if (mpart.material == pmt.material && mpart.getSize + pmt.size < 8) {
@@ -88,7 +88,9 @@ class MicroblockPlacement(
val oppMod = player.isControlDown
val internal = d < 1 && htile != null
val doExpand =
internal && !gtile._2 && !player.isSneaking && !(oppMod && useOppMod) && pp
internal && !gtile._2.asInstanceOf[
Boolean
] && !player.isSneaking && !(oppMod && useOppMod) && pp
.expand(slot, hit.sideHit)
val side = hit.sideHit
@@ -101,7 +103,7 @@ class MicroblockPlacement(
return null
if (doExpand) {
val hpart = htile.partList(ExtendedMOP.getData[(Int, _)](hit)._1)
val hpart = htile.partList.apply(ExtendedMOP.getData[(Int, _)](hit)._1)
if (hpart.getType == mcrClass.getName) {
val mpart = hpart.asInstanceOf[CommonMicroblock]
if (mpart.material == material && mpart.getSize + size < 8)
@@ -54,11 +54,11 @@ object BlockMultipart {
return false
val (index, mop) = reduceMOP(hit)
if (tile.partList(index).drawHighlight(mop, player, frame))
if (tile.partList.apply(index).drawHighlight(mop, player, frame))
return true
tile
.partList(index)
tile.partList
.apply(index)
.collisionRayTrace(
RayTracer.getStartVec(player),
RayTracer.getEndVec(player)
@@ -156,8 +156,8 @@ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
val (index, mop) = reduceMOP(hit)
if (world.isRemote) {
tile
.partList(index)
tile.partList
.apply(index)
.addDestroyEffects(mop, Minecraft.getMinecraft.effectRenderer)
return true
}
@@ -225,7 +225,7 @@ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
if (tile != null) {
val (index, mop) = reduceMOP(hit)
if (index < tile.partList.size)
tile.partList(index).addHitEffects(mop, effectRenderer)
tile.partList.apply(index).addHitEffects(mop, effectRenderer)
}
return true
@@ -272,7 +272,7 @@ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
return null
}
val (index, mop) = reduceMOP(hit)
return tile.partList(index).pickItem(mop)
return tile.partList.apply(index).pickItem(mop)
}
return null
}
@@ -288,7 +288,7 @@ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
val tile = getTile(world, x, y, z)
if (hit != null && tile != null) {
val (index, mop) = reduceMOP(hit)
return tile.partList(index).getStrength(mop, player) / 30f
return tile.partList.apply(index).getStrength(mop, player) / 30f
}
return 1 / 100f
@@ -340,7 +340,7 @@ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
return false
val (index, mop) = reduceMOP(hit)
return tile.partList(index).activate(player, mop, player.getHeldItem)
return tile.partList.apply(index).activate(player, mop, player.getHeldItem)
}
override def onBlockClicked(
@@ -359,7 +359,7 @@ class BlockMultipart extends Block(new Material(MapColor.stoneColor)) {
return
val (index, mop) = reduceMOP(hit)
tile.partList(index).click(player, mop, player.getHeldItem)
tile.partList.apply(index).click(player, mop, player.getHeldItem)
}
override def isProvidingStrongPower(
@@ -81,13 +81,15 @@ object MultipartGenerator extends ScratchBitSet {
pos: BlockCoord,
part: TMultiPart
): TileMultipart = {
val (tile, converted) = TileMultipart.getOrConvertTile2(world, pos)
val gtile = TileMultipart.getOrConvertTile2(world, pos)
val tile = gtile._1
val converted = gtile._2.asInstanceOf[Boolean]
val bitset = setTraits(part, world.isRemote)
var ntile = tile
if (ntile != null) {
if (converted) { // perform client conversion
ntile.partList(0).invalidateConvertedTile()
ntile.partList.apply(0).invalidateConvertedTile()
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block, 0, 0)
silentAddTile(world, pos, ntile)
PacketCustom.sendToChunk(
@@ -96,8 +98,8 @@ object MultipartGenerator extends ScratchBitSet {
pos.x >> 4,
pos.z >> 4
)
ntile.partList(0).onConverted()
ntile.writeAddPart(ntile.partList(0))
ntile.partList.apply(0).onConverted()
ntile.writeAddPart(ntile.partList.apply(0))
}
val tileTraits = tileTraitMap(tile.getClass)
@@ -25,7 +25,7 @@ import com.gtnewhorizons.angelica.api.ThreadSafeISBRH
object MultipartRenderer
extends TileEntitySpecialRenderer
with ISimpleBlockRenderingHandler {
TileMultipart.renderID = RenderingRegistry.getNextAvailableRenderId
TileMultipart.renderID_$eq(RenderingRegistry.getNextAvailableRenderId)
override def renderTileEntityAt(
t: TileEntity,
@@ -79,7 +79,7 @@ object MultipartRenderer
Int
] && hitInfo._1 >= 0 && hitInfo._1 < tmpart.partList.size
)
tmpart.partList(hitInfo._1).drawBreaking(renderer)
tmpart.partList.apply(hitInfo._1).drawBreaking(renderer)
}
return false
}
@@ -213,7 +213,7 @@ object TickScheduler extends WorldExtensionInstantiator {
chunk.chunkTileEntityMap.get(new ChunkPosition(pos.x, pos.y, pos.z))
if (tile.isInstanceOf[TileMultipart])
tickList += new PartTickEntry(
tile.asInstanceOf[TileMultipart].partList(tag.getByte("i")),
tile.asInstanceOf[TileMultipart].partList.apply(tag.getByte("i")),
tag.getLong("time"),
false
)
@@ -0,0 +1,72 @@
package codechicken.multipart;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.vec.BlockCoord;
import codechicken.lib.vec.Vector3;
import scala.Tuple2;
/**
* Scala companion singleton. Retained because compiled Scala consumers read MODULE$ and call these instance methods.
*/
public final class TileMultipart$ {
public static final TileMultipart$ MODULE$ = new TileMultipart$();
private TileMultipart$() {}
public int renderID() {
return TileMultipart.renderID();
}
public void renderID_$eq(int value) {
TileMultipart.renderID_$eq(value);
}
public TileMultipart getOrConvertTile(World world, BlockCoord pos) {
return TileMultipart.getOrConvertTile(world, pos);
}
public Tuple2<TileMultipart, Object> getOrConvertTile2(World world, BlockCoord pos) {
return TileMultipart.getOrConvertTile2(world, pos);
}
public TileMultipart getTile(World world, BlockCoord pos) {
return TileMultipart.getTile(world, pos);
}
public boolean checkNoEntityCollision(World world, BlockCoord pos, TMultiPart part) {
return TileMultipart.checkNoEntityCollision(world, pos, part);
}
public boolean canPlacePart(World world, BlockCoord pos, TMultiPart part) {
return TileMultipart.canPlacePart(world, pos, part);
}
public boolean replaceable(World world, BlockCoord pos) {
return TileMultipart.replaceable(world, pos);
}
public TileMultipart addPart(World world, BlockCoord pos, TMultiPart part) {
return TileMultipart.addPart(world, pos, part);
}
public void handleDescPacket(World world, BlockCoord pos, PacketCustom packet) {
TileMultipart.handleDescPacket(world, pos, packet);
}
public void handlePacket(BlockCoord pos, World world, int i, PacketCustom packet) {
TileMultipart.handlePacket(pos, world, i, packet);
}
public TileMultipart createFromNBT(NBTTagCompound tag) {
return TileMultipart.createFromNBT(tag);
}
public void dropItem(ItemStack stack, World world, Vector3 pos) {
TileMultipart.dropItem(stack, world, pos);
}
}
@@ -0,0 +1,723 @@
package codechicken.multipart;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import codechicken.lib.data.MCDataOutput;
import codechicken.lib.packet.PacketCustom;
import codechicken.lib.raytracer.ExtendedMOP;
import codechicken.lib.vec.BlockCoord;
import codechicken.lib.vec.Cuboid6;
import codechicken.lib.vec.Vector3;
import codechicken.lib.world.IChunkLoadTile;
import codechicken.multipart.handler.MultipartCompatiblity;
import codechicken.multipart.handler.MultipartProxy;
import codechicken.multipart.handler.MultipartSPH;
import scala.Function1;
import scala.Tuple2;
import scala.collection.JavaConversions;
import scala.collection.Seq;
import scala.runtime.AbstractFunction1;
import scala.runtime.BoxedUnit;
public class TileMultipart extends TileEntity implements IChunkLoadTile {
/** List of parts in this tile space. */
private Seq<TMultiPart> partList = emptyParts();
private boolean doesTick = false;
public Seq<TMultiPart> partList() {
return partList;
}
public void partList_$eq(Seq<TMultiPart> parts) {
partList = parts;
}
public void from(TileMultipart that) {
copyFrom(that);
loadFrom(that);
}
/**
* This method should be used for copying all the data from the fields in that container tile. This method will be
* automatically generated on java tile traits with fields if it is not overridden.
*/
public void copyFrom(TileMultipart that) {
partList = that.partList;
doesTick = that.doesTick;
}
public void loadFrom(TileMultipart that) {
for (TMultiPart part : parts()) {
part.bind(this);
}
if (doesTick) {
doesTick = false;
setTicking(true);
}
}
/** Overidden in TSlottedTile when a part that goes in a slot is added. */
public TMultiPart partMap(int slot) {
return null;
}
/** Implicit java conversion of part list. */
public List<TMultiPart> jPartList() {
return JavaConversions.seqAsJavaList(partList);
}
@Override
public boolean canUpdate() {
return doesTick;
}
public void operate(Function1<TMultiPart, BoxedUnit> f) {
for (TMultiPart p : parts()) {
if (p.tile() != null) {
f.apply(p);
}
}
}
@Override
public void updateEntity() {
operate(action(TMultiPart::update));
}
@Override
public void onChunkUnload() {
operate(action(TMultiPart::onChunkUnload));
}
@Override
public void onChunkLoad() {
operate(action(TMultiPart::onChunkLoad));
}
public final void setValid(boolean b) {
if (b) {
super.validate();
} else {
super.invalidate();
}
}
public void onMoved() {
operate(action(TMultiPart::onMoved));
}
@Override
public void invalidate() {
if (!isInvalid()) {
super.invalidate();
if (worldObj != null) {
for (TMultiPart part : parts()) {
part.onWorldSeparate();
}
if (worldObj.isRemote) {
TileCache.remove(this);
}
}
}
}
@Override
public void validate() {
super.validate();
if (worldObj != null && worldObj.isRemote) {
TileCache.add(this);
}
}
/**
* Called by parts when they have changed in some form that affects the world. Notifies neighbor blocks, the world
* and parts that share this host and recalculates lighting.
*/
public void notifyPartChange(TMultiPart part) {
internalPartChange(part);
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, MultipartProxy.block());
worldObj.func_147451_t(xCoord, yCoord, zCoord);
}
/** Notifies parts sharing this host of a change. */
public void internalPartChange(TMultiPart part) {
operate(action(p -> {
if (part != p) {
p.onPartChanged(part);
}
}));
}
/** Notifies all parts not in the passed collection of a change from all the parts in the collection. */
public void multiPartChange(Collection<TMultiPart> parts) {
operate(action(p -> {
if (!parts.contains(p)) {
for (TMultiPart changed : parts) {
p.onPartChanged(changed);
}
}
}));
}
/** Notifies neighboring blocks that this tile has changed. */
public void notifyTileChange() {
worldObj.func_147453_f(xCoord, yCoord, zCoord, MultipartProxy.block());
}
public void onNeighborBlockChange() {
operate(action(TMultiPart::onNeighborChanged));
}
/** Blank implementation, overriden by TTileChangeTile. */
public void onNeighborTileChange(int tileX, int tileY, int tileZ) {}
/** Blank implementation, overriden by TTileChangeTile. */
public boolean getWeakChanges() {
return false;
}
public int getLightValue() {
int max = 0;
for (TMultiPart part : parts()) {
int l = part.getLightValue();
if (l > max) {
max = l;
}
}
return max;
}
public float getExplosionResistance(Entity entity) {
List<TMultiPart> parts = parts();
if (parts.isEmpty()) {
// Matches the reference, where max on an empty view throws.
throw new UnsupportedOperationException("empty.max");
}
float max = Float.NEGATIVE_INFINITY;
for (TMultiPart part : parts) {
max = Math.max(max, part.explosionResistance(entity));
}
return max;
}
/** Callback for parts to mark the chunk as needs saving. */
@Override
public void markDirty() {
worldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this);
}
/** Mark this block space for a render update. */
public void markRender() {
worldObj.func_147479_m(xCoord, yCoord, zCoord);
}
/** 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);
worldObj.notifyBlocksOfNeighborChange(pos.x, pos.y, pos.z, MultipartProxy.block());
}
public boolean isSolid(int side) {
TMultiPart part = partMap(side);
return part instanceof TFacePart && ((TFacePart) part).solid(side);
}
public boolean canPlaceTorchOnTop() {
for (TMultiPart part : parts()) {
if (part.canPlaceTorchOnTop()) {
return true;
}
}
return isSolid(1);
}
private void setTicking(boolean tick) {
if (doesTick == tick) {
return;
}
doesTick = tick;
if (worldObj != null && worldObj.getTileEntity(xCoord, yCoord, zCoord) == this) {
if (tick) {
worldObj.addTileEntity(this);
} else {
worldObj.func_147457_a(this);
}
}
}
/** Returns true if part can be added to this space. */
public boolean canAddPart(TMultiPart part) {
return compatibilityAllows(worldObj, xCoord, yCoord, zCoord) && !parts().contains(part)
&& occlusionTest(partList, part);
}
/**
* Returns true if opart can be replaced with npart (note opart and npart may be the exact same object).
* <p>
* This function should be used for testing if a part can change it's shape (eg. rotation, expansion, cable
* connection). For example, to test whether a cable part can connect to it's neighbor: set the cable part's
* bounding boxes as if the connection is established, call canReplacePart(part, part), and if it succeeds perform
* the connection, else revert the bounding box.
*/
public boolean canReplacePart(TMultiPart opart, TMultiPart npart) {
List<TMultiPart> olist = new ArrayList<>();
for (TMultiPart part : parts()) {
if (part != opart) {
olist.add(part);
}
}
if (olist.contains(npart)) {
return false;
}
return occlusionTest(toSeq(olist), npart);
}
/** Returns true if parts do not occlude npart. */
public boolean occlusionTest(Seq<TMultiPart> parts, TMultiPart npart) {
for (TMultiPart part : JavaConversions.seqAsJavaList(parts)) {
if (!part.occlusionTest(npart) || !npart.occlusionTest(part)) {
return false;
}
}
return true;
}
/** Get the write stream for updates to part. */
public MCDataOutput getWriteStream(TMultiPart part) {
return writeStream().writeByte(parts().indexOf(part));
}
private MCDataOutput writeStream() {
return MultipartSPH.getTileStream(worldObj, new BlockCoord(this));
}
public void addPart_impl(TMultiPart part) {
if (!worldObj.isRemote) {
writeAddPart(part);
}
addPart_do(part);
part.onAdded();
partAdded(part);
notifyPartChange(part);
notifyTileChange();
markDirty();
markRender();
}
public void writeAddPart(TMultiPart part) {
MCDataOutput stream = writeStream().writeByte(253);
MultiPartRegistry.writePartID(stream, part);
part.writeDesc(stream);
}
public void addPart_do(TMultiPart part) {
if (partList.size() >= 250) {
throw new AssertionError(
"assertion failed: Tried to add more than 250 parts to the one tile. You're doing it wrong");
}
List<TMultiPart> next = parts();
next.add(part);
partList = toSeq(next);
bindPart(part);
part.bind(this);
if (!doesTick && part.doesTick()) {
setTicking(true);
}
}
/** Bind this part to an internal cache. Provided for trait overrides, do not call externally. */
public void bindPart(TMultiPart part) {}
/** Called when a part is added (placement). Provided for trait overrides, do not call externally. */
public void partAdded(TMultiPart part) {}
/**
* Removes part from this tile. Note that due to the operation sync, the part may not be removed until the call
* stack has been passed to all other parts in the space.
*/
public TileMultipart remPart(TMultiPart part) {
if (worldObj.isRemote) {
throw new AssertionError("assertion failed: Cannot remove multi parts from a client tile");
}
return remPart_impl(part);
}
public TileMultipart remPart_impl(TMultiPart part) {
remPart_do(part, !worldObj.isRemote);
if (!isInvalid()) {
TileMultipart tile = MultipartGenerator$.MODULE$.partRemoved(this);
tile.notifyPartChange(part);
tile.markDirty();
tile.markRender();
return tile;
}
return null;
}
private int remPart_do(TMultiPart part, boolean sendPacket) {
List<TMultiPart> current = parts();
int r = current.indexOf(part);
if (r < 0) {
throw new IllegalArgumentException("Tried to remove a non-existant part");
}
part.preRemove();
current.remove(r);
partList = toSeq(current);
if (sendPacket) {
writeStream().writeByte(254).writeByte(r);
}
partRemoved(part, r);
part.onRemoved();
part.tile_$eq(null);
if (current.isEmpty()) {
worldObj.setBlockToAir(xCoord, yCoord, zCoord);
} else if (part.doesTick() && doesTick) {
boolean ntick = false;
for (TMultiPart p : current) {
ntick |= p.doesTick();
}
if (!ntick) {
setTicking(false);
}
}
return r;
}
/** Remove this part from internal cache. Provided for trait overrides, do not call externally. */
public void partRemoved(TMultiPart part, int p) {}
public void loadParts(scala.collection.Iterable<TMultiPart> parts) {
clearParts();
for (TMultiPart p : JavaConversions.asJavaIterable(parts)) {
addPart_do(p);
}
if (worldObj != null) {
if (worldObj.isRemote) {
operate(action(TMultiPart::onWorldJoin));
}
notifyPartChange(null);
}
}
/** Remove all parts from internal cache. Provided for trait overrides, do not call externally. */
public void clearParts() {
partList = emptyParts();
}
/** Writes the description of this tile, and all parts composing it, to packet. */
public void writeDesc(MCDataOutput packet) {
packet.writeByte(partList.size());
for (TMultiPart part : parts()) {
MultiPartRegistry.writePartID(packet, part);
part.writeDesc(packet);
}
}
/** Perform a raytrace returning all intersecting parts sorted nearest to farthest. */
public Iterable<ExtendedMOP> rayTraceAll(Vec3 start, Vec3 end) {
List<ExtendedMOP> list = new ArrayList<>();
List<TMultiPart> parts = parts();
for (int i = 0; i < parts.size(); i++) {
Object mop = parts.get(i).collisionRayTrace(start, end);
if (mop instanceof ExtendedMOP) {
ExtendedMOP extended = (ExtendedMOP) mop;
extended.data = new Tuple2<>(i, extended.data);
list.add(extended);
}
}
Collections.sort(list);
return list;
}
/** Perform a raytrace returning the nearest intersecting part. */
public ExtendedMOP collisionRayTrace(Vec3 start, Vec3 end) {
for (ExtendedMOP mop : rayTraceAll(start, end)) {
return mop;
}
return null;
}
/** Drop and remove part at index (internal mining callback). */
public void harvestPart(int index, ExtendedMOP hit, EntityPlayer player) {
TMultiPart part = parts().get(index);
if (part != null) {
part.harvest(hit, player);
}
}
/** Utility function for dropping items around the center of this space. */
public void dropItems(Iterable<ItemStack> items) {
Vector3 pos = Vector3.fromTileEntityCenter(this);
for (ItemStack item : items) {
dropItem(item, worldObj, pos);
}
}
@Override
public final void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
NBTTagList taglist = new NBTTagList();
for (TMultiPart part : parts()) {
NBTTagCompound parttag = new NBTTagCompound();
parttag.setString("id", part.getType());
part.save(parttag);
taglist.appendTag(parttag);
}
tag.setTag("parts", taglist);
}
/** Internal callback. */
public void onEntityCollision(Entity entity) {
operate(action(p -> p.onEntityCollision(entity)));
}
/** Internal callback, overriden in TRedstoneTile. */
public int strongPowerLevel(int side) {
return 0;
}
/** Internal callback, overriden in TRedstoneTile. */
public int weakPowerLevel(int side) {
return 0;
}
/** Internal callback, overriden in TRedstoneTile. */
public boolean canConnectRedstone(int side) {
return false;
}
/** Mutable snapshot of the current parts. Mutating it does not affect the published Seq. */
private List<TMultiPart> parts() {
return new ArrayList<>(JavaConversions.seqAsJavaList(partList));
}
private static Seq<TMultiPart> toSeq(List<TMultiPart> parts) {
return JavaConversions.asScalaBuffer(parts).toList();
}
private static Seq<TMultiPart> emptyParts() {
return toSeq(Collections.emptyList());
}
/** Wraps a Java action as the Scala function operate takes, so overrides of operate still see every call. */
private static Function1<TMultiPart, BoxedUnit> action(Consumer<TMultiPart> action) {
return new AbstractFunction1<TMultiPart, BoxedUnit>() {
@Override
public BoxedUnit apply(TMultiPart part) {
action.accept(part);
return BoxedUnit.UNIT;
}
};
}
@SuppressWarnings("unchecked")
private static boolean compatibilityAllows(World world, int x, int y, int z) {
return (Boolean) MultipartCompatiblity.canAddPart()
.apply(world, Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(z));
}
// Static helpers, formerly the TileMultipart companion object.
private static int renderID = -1;
public static int renderID() {
return renderID;
}
public static void renderID_$eq(int value) {
renderID = value;
}
/** Gets a multipart tile instance at pos, converting if necessary. */
public static TileMultipart getOrConvertTile(World world, BlockCoord pos) {
return getOrConvertTile2(world, pos)._1();
}
/**
* Gets a multipart tile instance at pos, converting if necessary. Note converted tiles are merely a structure
* formality, they do not actually exist in world until they are required to by the addition of another multipart to
* their space.
*
* @return the tile or null if there was none, and true if the tile is a result of a conversion
*/
public static Tuple2<TileMultipart, Object> getOrConvertTile2(World world, BlockCoord pos) {
TileEntity t = world.getTileEntity(pos.x, pos.y, pos.z);
if (t instanceof TileMultipart) {
return new Tuple2<>((TileMultipart) t, Boolean.FALSE);
}
TMultiPart p = MultiPartRegistry.convertBlock(world, pos, world.getBlock(pos.x, pos.y, pos.z));
if (p != null) {
TileMultipart tile = MultipartGenerator$.MODULE$
.generateCompositeTile(null, toSeq(Collections.singletonList(p)), world.isRemote);
tile.xCoord = pos.x;
tile.yCoord = pos.y;
tile.zCoord = pos.z;
tile.setWorldObj(world);
tile.addPart_do(p);
return new Tuple2<>(tile, Boolean.TRUE);
}
return new Tuple2<>(null, Boolean.FALSE);
}
/** Gets the multipart tile instance at pos, or null if it doesn't exist or is not a multipart tile. */
public static TileMultipart getTile(World world, BlockCoord pos) {
TileEntity t = world.getTileEntity(pos.x, pos.y, pos.z);
return t instanceof TileMultipart ? (TileMultipart) t : null;
}
public static boolean checkNoEntityCollision(World world, BlockCoord pos, TMultiPart part) {
for (Cuboid6 b : part.getCollisionBoxes()) {
if (!world.checkNoEntityCollision(b.toAABB().offset(pos.x, pos.y, pos.z))) {
return false;
}
}
return true;
}
/**
* Returns whether part can be added to the space at pos. Will do conversions as necessary. This function is the
* recommended way to add parts to the world.
*/
public static boolean canPlacePart(World world, BlockCoord pos, TMultiPart part) {
if (!checkNoEntityCollision(world, pos, part)) {
return false;
}
TileMultipart t = getOrConvertTile(world, pos);
if (t != null) {
return t.canAddPart(part);
} else if (!compatibilityAllows(world, pos.x, pos.y, pos.z)) {
return false;
}
return replaceable(world, pos);
}
/** Returns if the block at pos is replaceable (air, vines etc). */
public static boolean replaceable(World world, BlockCoord pos) {
net.minecraft.block.Block block = world.getBlock(pos.x, pos.y, pos.z);
return block.isAir(world, pos.x, pos.y, pos.z) || block.isReplaceable(world, pos.x, pos.y, pos.z);
}
/**
* Adds a part to a block space. canPlacePart should always be called first. The addition of parts on the client is
* handled internally.
*/
public static TileMultipart addPart(World world, BlockCoord pos, TMultiPart part) {
if (world.isRemote) {
throw new AssertionError("assertion failed: Cannot add multi parts to a client tile.");
}
return MultipartGenerator$.MODULE$.addPart(world, pos, part);
}
/** Constructs this tile and its parts from a desc packet. */
public static void handleDescPacket(World world, BlockCoord pos, PacketCustom packet) {
int nparts = packet.readUByte();
List<TMultiPart> parts = new ArrayList<>();
for (int i = 0; i < nparts; i++) {
TMultiPart part = MultiPartRegistry.readPart(packet);
part.readDesc(packet);
parts.add(part);
}
if (parts.isEmpty()) {
return;
}
TileEntity t = world.getTileEntity(pos.x, pos.y, pos.z);
TileMultipart tilemp = MultipartGenerator$.MODULE$.generateCompositeTile(t, toSeq(parts), true);
if (tilemp != t) {
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block());
MultipartGenerator.silentAddTile(world, pos, tilemp);
}
tilemp.loadParts(toSeq(parts));
tilemp.notifyTileChange();
tilemp.markRender();
}
/** Handles an update packet, addition, removal and otherwise. */
public static void handlePacket(BlockCoord pos, World world, int i, PacketCustom packet) {
if (i == 253) {
TMultiPart part = MultiPartRegistry.readPart(packet);
part.readDesc(packet);
MultipartGenerator$.MODULE$.addPart(world, pos, part);
} else if (i == 254) {
// The reference resolves the tile separately for the receiver and the argument.
TileMultipart receiver = TileCache.findTile(world, pos);
TMultiPart removed = TileCache.findTile(world, pos).partList().apply(packet.readUByte());
receiver.remPart_impl(removed);
} else {
TileCache.findTile(world, pos).partList().apply(i).read(packet);
}
}
/** Creates this tile from an NBT tag. */
public static TileMultipart createFromNBT(NBTTagCompound tag) {
NBTTagList partList = tag.getTagList("parts", 10);
List<TMultiPart> parts = new ArrayList<>();
for (int i = 0; i < partList.tagCount(); i++) {
NBTTagCompound partTag = partList.getCompoundTagAt(i);
String partID = partTag.getString("id");
TMultiPart part = MultiPartRegistry.loadPart(partID, partTag);
if (part != null) {
part.load(partTag);
parts.add(part);
}
}
if (parts.isEmpty()) {
return null;
}
TileMultipart tmb = MultipartGenerator$.MODULE$.generateCompositeTile(null, toSeq(parts), false);
tmb.readFromNBT(tag);
tmb.loadParts(toSeq(parts));
return tmb;
}
/** Drops an item around pos. */
public static void dropItem(ItemStack stack, World world, Vector3 pos) {
EntityItem item = new EntityItem(world, pos.x, pos.y, pos.z, stack);
item.motionX = world.rand.nextGaussian() * 0.05;
item.motionY = world.rand.nextGaussian() * 0.05 + 0.2;
item.motionZ = world.rand.nextGaussian() * 0.05;
item.delayBeforeCanPickup = 10;
world.spawnEntityInWorld(item);
}
}
@@ -1,802 +0,0 @@
package codechicken.multipart
import net.minecraft.tileentity.TileEntity
import scala.collection.mutable.ListBuffer
import codechicken.lib.packet.PacketCustom
import codechicken.lib.vec.{BlockCoord, Cuboid6, Vector3}
import net.minecraft.world.{IBlockAccess, World}
import java.util.List
import net.minecraft.nbt.NBTTagCompound
import codechicken.lib.data.MCDataOutput
import codechicken.multipart.handler.{
MultipartCompatiblity,
MultipartProxy,
MultipartSPH
}
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagList
import java.util.Random
import net.minecraft.entity.item.EntityItem
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.Entity
import scala.collection.JavaConversions._
import java.util.Collection
import codechicken.lib.raytracer.ExtendedMOP
import net.minecraft.util.{AxisAlignedBB, Vec3}
import java.lang.Iterable
import codechicken.lib.world.IChunkLoadTile
import net.minecraft.block.Block
import net.minecraft.client.renderer.RenderBlocks
import net.minecraftforge.client.ForgeHooksClient
class TileMultipart extends TileEntity with IChunkLoadTile {
/** List of parts in this tile space
*/
var partList = Seq[TMultiPart]()
private var doesTick = false
private[multipart] def from(that: TileMultipart) {
copyFrom(that)
loadFrom(that)
}
/** This method should be used for copying all the data from the fields in
* that container tile. This method will be automatically generated on java
* tile traits with fields if it is not overridden.
*/
def copyFrom(that: TileMultipart) {
partList = that.partList
doesTick = that.doesTick
}
def loadFrom(that: TileMultipart) {
partList.foreach(_.bind(this))
if (doesTick) {
doesTick = false
setTicking(true)
}
}
/** Overidden in TSlottedTile when a part that goes in a slot is added
*/
def partMap(slot: Int): TMultiPart = null
/** Implicit java conversion of part list
*/
def jPartList(): List[TMultiPart] = partList
override def canUpdate = doesTick
def operate(f: (TMultiPart) => Unit) {
val it = partList.iterator
while (it.hasNext) {
val p = it.next()
if (p.tile != null) f(p)
}
}
override def updateEntity() {
operate(_.update())
}
override def onChunkUnload() {
operate(_.onChunkUnload())
}
override def onChunkLoad() {
operate(_.onChunkLoad())
}
final def setValid(b: Boolean) {
if (b)
super.validate()
else
super.invalidate()
}
def onMoved() {
operate(_.onMoved())
}
override def invalidate() {
if (!isInvalid) {
super.invalidate()
if (worldObj != null) {
partList.foreach(_.onWorldSeparate())
if (worldObj.isRemote)
TileCache.remove(this)
}
}
}
override def validate() {
super.validate()
if (worldObj != null && worldObj.isRemote)
TileCache.add(this)
}
/** Called by parts when they have changed in some form that affects the
* world. Notifies neighbor blocks, the world and parts that share this host
* and recalculates lighting
*/
def notifyPartChange(part: TMultiPart) {
internalPartChange(part)
worldObj.markBlockForUpdate(xCoord, yCoord, zCoord)
worldObj.notifyBlocksOfNeighborChange(
xCoord,
yCoord,
zCoord,
MultipartProxy.block
)
worldObj.func_147451_t(xCoord, yCoord, zCoord)
}
/** Notifies parts sharing this host of a change
*/
def internalPartChange(part: TMultiPart) {
operate(p => if (part != p) p.onPartChanged(part))
}
/** Notifies all parts not in the passed collection of a change from all the
* parts in the collection
*/
def multiPartChange(parts: Collection[TMultiPart]) {
operate(p => if (!parts.contains(p)) parts.foreach(p.onPartChanged))
}
/** Notifies neighboring blocks that this tile has changed
*/
def notifyTileChange() {
worldObj.func_147453_f(xCoord, yCoord, zCoord, MultipartProxy.block)
}
def onNeighborBlockChange() {
operate(_.onNeighborChanged())
}
/** Blank implementation, overriden by TTileChangeTile
*/
def onNeighborTileChange(tileX: Int, tileY: Int, tileZ: Int) {}
/** Blank implementation, overriden by TTileChangeTile
*/
def getWeakChanges = false
def getLightValue: Int = {
if (partList.isEmpty) {
return 0
}
var max = 0
val it = partList.iterator
while (it.hasNext) {
val l = it.next().getLightValue
if (l > max) max = l
}
max
}
def getExplosionResistance(entity: Entity) =
partList.view.map(_.explosionResistance(entity)).max
/** Callback for parts to mark the chunk as needs saving
*/
override def markDirty() {
worldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this)
}
/** Mark this block space for a render update.
*/
def markRender() {
worldObj.func_147479_m(xCoord, yCoord, zCoord)
}
/** Helper function for calling a second level notify on a side (eg indirect
* power from a lever)
*/
def notifyNeighborChange(side: Int) {
val pos = new BlockCoord(this).offset(side)
worldObj.notifyBlocksOfNeighborChange(
pos.x,
pos.y,
pos.z,
MultipartProxy.block
)
}
def isSolid(side: Int) = partMap(side) match {
case face: TFacePart => face.solid(side)
case _ => false
}
def canPlaceTorchOnTop = partList.exists(_.canPlaceTorchOnTop) || isSolid(1)
private def setTicking(tick: Boolean) {
if (doesTick == tick)
return
doesTick = tick
if (
worldObj != null && worldObj.getTileEntity(xCoord, yCoord, zCoord) == this
) {
if (tick)
worldObj.addTileEntity(this)
else
worldObj.func_147457_a(this)
}
}
/** Returns true if part can be added to this space
*/
def canAddPart(part: TMultiPart) =
MultipartCompatiblity.canAddPart(worldObj, xCoord, yCoord, zCoord) &&
!partList.contains(part) &&
occlusionTest(partList, part)
/** Returns true if opart can be replaced with npart (note opart and npart may
* be the exact same object)
*
* This function should be used for testing if a part can change it's shape
* (eg. rotation, expansion, cable connection) For example, to test whether a
* cable part can connect to it's neighbor:
* 1. Set the cable part's bounding boxes as if the connection is
* established 2. Call canReplacePart(part, part) 3. If canReplacePart
* succeeds, perform connection, else, revert bounding box
*/
def canReplacePart(opart: TMultiPart, npart: TMultiPart): Boolean = {
val olist = partList.filterNot(_ == opart)
if (olist.contains(npart))
return false
return occlusionTest(olist, npart)
}
/** Returns true if parts do not occlude npart
*/
def occlusionTest(parts: Seq[TMultiPart], npart: TMultiPart): Boolean = {
return parts.forall(part =>
part.occlusionTest(npart) && npart.occlusionTest(part)
)
}
/** Get the write stream for updates to part
*/
def getWriteStream(part: TMultiPart): MCDataOutput =
getWriteStream.writeByte(partList.indexOf(part))
private def getWriteStream =
MultipartSPH.getTileStream(worldObj, new BlockCoord(this))
private[multipart] def addPart_impl(part: TMultiPart) {
if (!worldObj.isRemote)
writeAddPart(part)
addPart_do(part)
part.onAdded()
partAdded(part)
notifyPartChange(part)
notifyTileChange()
markDirty()
markRender()
}
private[multipart] def writeAddPart(part: TMultiPart) {
val stream = getWriteStream.writeByte(253)
MultiPartRegistry.writePartID(stream, part)
part.writeDesc(stream)
}
private[multipart] def addPart_do(part: TMultiPart) {
assert(
partList.size < 250,
"Tried to add more than 250 parts to the one tile. You're doing it wrong"
)
partList = partList :+ part
bindPart(part)
part.bind(this)
if (!doesTick && part.doesTick)
setTicking(true)
}
/** Bind this part to an internal cache. Provided for trait overrides, do not
* call externally.
*/
def bindPart(part: TMultiPart) {}
/** Called when a part is added (placement) Provided for trait overrides, do
* not call externally.
*/
def partAdded(part: TMultiPart) {}
/** Removes part from this tile. Note that due to the operation sync, the part
* may not be removed until the call stack has been passed to all other parts
* in the space.
*/
def remPart(part: TMultiPart): TileMultipart = {
assert(!worldObj.isRemote, "Cannot remove multi parts from a client tile")
remPart_impl(part)
}
private[multipart] def remPart_impl(part: TMultiPart): TileMultipart = {
remPart_do(part, !worldObj.isRemote)
if (!isInvalid) {
val tile = MultipartGenerator.partRemoved(this)
tile.notifyPartChange(part)
tile.markDirty()
tile.markRender()
return tile
}
return null
}
private def remPart_do(part: TMultiPart, sendPacket: Boolean): Int = {
val r = partList.indexOf(part)
if (r < 0)
throw new IllegalArgumentException("Tried to remove a non-existant part")
val removedLightValue = part.getLightValue
part.preRemove()
partList = partList.filterNot(_ == part)
if (sendPacket)
getWriteStream.writeByte(254).writeByte(r)
partRemoved(part, r)
part.onRemoved()
part.tile = null
if (partList.isEmpty) {
worldObj.setBlockToAir(xCoord, yCoord, zCoord)
} else {
if (part.doesTick && doesTick) {
var ntick = false
partList.foreach(part => ntick |= part.doesTick)
if (!ntick)
setTicking(false)
}
}
return r
}
/** Remove this part from internal cache. Provided for trait overrides, do not
* call externally.
*/
def partRemoved(part: TMultiPart, p: Int) {}
private[multipart] def loadParts(parts: scala.Iterable[TMultiPart]) {
clearParts()
parts.foreach(p => addPart_do(p))
if (worldObj != null) {
if (worldObj.isRemote)
operate(_.onWorldJoin())
notifyPartChange(null)
}
}
/** Remove all parts from internal cache Provided for trait overrides, do not
* call externally.
*/
def clearParts() {
partList = Seq()
}
/** Writes the description of this tile, and all parts composing it, to packet
*/
def writeDesc(packet: MCDataOutput) {
packet.writeByte(partList.size)
partList.foreach { part =>
MultiPartRegistry.writePartID(packet, part)
part.writeDesc(packet)
}
}
/** Perform a raytrace returning all intersecting parts sorted nearest to
* farthest
*/
def rayTraceAll(start: Vec3, end: Vec3): Iterable[ExtendedMOP] = {
var list = ListBuffer[ExtendedMOP]()
for ((p, i) <- partList.view.zipWithIndex)
p.collisionRayTrace(start, end) match {
case mop: ExtendedMOP =>
mop.data = (i, mop.data)
list += mop
case _ =>
}
return list.sorted
}
/** Perform a raytrace returning the nearest intersecting part
*/
def collisionRayTrace(start: Vec3, end: Vec3): ExtendedMOP =
rayTraceAll(start, end).headOption.getOrElse(null)
/** Drop and remove part at index (internal mining callback)
*/
def harvestPart(index: Int, hit: ExtendedMOP, player: EntityPlayer) =
partList(index) match {
case null =>
case part => part.harvest(hit, player)
}
/** Utility function for dropping items around the center of this space
*/
def dropItems(items: Iterable[ItemStack]) {
val pos = Vector3.fromTileEntityCenter(this)
items.foreach(item => TileMultipart.dropItem(item, worldObj, pos))
}
final override def writeToNBT(tag: NBTTagCompound) {
super.writeToNBT(tag)
val taglist = new NBTTagList
partList.foreach { part =>
val parttag = new NBTTagCompound
parttag.setString("id", part.getType)
part.save(parttag)
taglist.appendTag(parttag)
}
tag.setTag("parts", taglist)
}
/** Internal callback
*/
def onEntityCollision(entity: Entity) {
operate(_.onEntityCollision(entity))
}
/** Internal callback, overriden in TRedstoneTile
*/
def strongPowerLevel(side: Int) = 0
/** Internal callback, overriden in TRedstoneTile
*/
def weakPowerLevel(side: Int) = 0
/** Internal callback, overriden in TRedstoneTile
*/
def canConnectRedstone(side: Int) = false
}
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()
}
}
/** Static class with multipart manipulation helper functions
*/
object TileMultipart {
var renderID = -1
/** Gets a multipar ttile instance at pos, converting if necessary.
*/
def getOrConvertTile(world: World, pos: BlockCoord) =
getOrConvertTile2(world, pos)._1
/** Gets a multipart tile instance at pos, converting if necessary. Note
* converted tiles are merely a structure formality, they do not actually
* exist in world until they are required to by the addition of another
* multipart to their space.
* @return
* (The tile or null if there was none, true if the tile is a result of a
* conversion)
*/
def getOrConvertTile2(
world: World,
pos: BlockCoord
): (TileMultipart, Boolean) = {
val t = world.getTileEntity(pos.x, pos.y, pos.z)
if (t.isInstanceOf[TileMultipart])
return (t.asInstanceOf[TileMultipart], false)
val p = MultiPartRegistry.convertBlock(
world,
pos,
world.getBlock(pos.x, pos.y, pos.z)
)
if (p != null) {
val t =
MultipartGenerator.generateCompositeTile(null, Seq(p), world.isRemote)
t.xCoord = pos.x
t.yCoord = pos.y
t.zCoord = pos.z
t.setWorldObj(world)
t.addPart_do(p)
return (t, true)
}
return (null, false)
}
/** Gets the multipart tile instance at pos, or null if it doesn't exist or is
* not a multipart tile
*/
def getTile(world: World, pos: BlockCoord) =
world.getTileEntity(pos.x, pos.y, pos.z) match {
case t: TileMultipart => t
case _ => null
}
def checkNoEntityCollision(world: World, pos: BlockCoord, part: TMultiPart) =
part.getCollisionBoxes.forall(b =>
world.checkNoEntityCollision(b.toAABB.offset(pos.x, pos.y, pos.z))
)
/** Returns whether part can be added to the space at pos. Will do conversions
* as necessary. This function is the recommended way to add parts to the
* world.
*/
def canPlacePart(world: World, pos: BlockCoord, part: TMultiPart): Boolean = {
if (!checkNoEntityCollision(world, pos, part))
return false
val t = getOrConvertTile(world, pos)
if (t != null)
return t.canAddPart(part)
else if (!MultipartCompatiblity.canAddPart(world, pos.x, pos.y, pos.z))
return false
if (!replaceable(world, pos))
return false
return true
}
/** Returns if the block at pos is replaceable (air, vines etc)
*/
def replaceable(world: World, pos: BlockCoord): Boolean = {
val block = world.getBlock(pos.x, pos.y, pos.z)
return block.isAir(world, pos.x, pos.y, pos.z) || block.isReplaceable(
world,
pos.x,
pos.y,
pos.z
)
}
/** Adds a part to a block space. canPlacePart should always be called first.
* The addition of parts on the client is handled internally.
*/
def addPart(
world: World,
pos: BlockCoord,
part: TMultiPart
): TileMultipart = {
assert(!world.isRemote, "Cannot add multi parts to a client tile.")
return MultipartGenerator.addPart(world, pos, part)
}
/** Constructs this tile and its parts from a desc packet
*/
def handleDescPacket(world: World, pos: BlockCoord, packet: PacketCustom) {
val nparts = packet.readUByte
val parts = new ListBuffer[TMultiPart]()
for (i <- 0 until nparts) {
val part = MultiPartRegistry.readPart(packet)
part.readDesc(packet)
parts += part
}
if (parts.size == 0)
return
val t = world.getTileEntity(pos.x, pos.y, pos.z)
val tilemp = MultipartGenerator.generateCompositeTile(t, parts, true)
if (tilemp != t) {
world.setBlock(pos.x, pos.y, pos.z, MultipartProxy.block)
MultipartGenerator.silentAddTile(world, pos, tilemp)
}
tilemp.loadParts(parts)
tilemp.notifyTileChange()
tilemp.markRender()
}
/** Handles an update packet, addition, removal and otherwise
*/
def handlePacket(
pos: BlockCoord,
world: World,
i: Int,
packet: PacketCustom
) {
def tilemp = TileCache.findTile(world, pos)
i match {
case 253 =>
val part = MultiPartRegistry.readPart(packet)
part.readDesc(packet)
MultipartGenerator.addPart(world, pos, part)
case 254 => tilemp.remPart_impl(tilemp.partList(packet.readUByte))
case _ => tilemp.partList(i).read(packet)
}
}
/** Creates this tile from an NBT tag
*/
def createFromNBT(tag: NBTTagCompound): TileMultipart = {
val partList = tag.getTagList("parts", 10)
val parts = ListBuffer[TMultiPart]()
for (i <- 0 until partList.tagCount) {
val partTag = partList.getCompoundTagAt(i)
val partID = partTag.getString("id")
val part = MultiPartRegistry.loadPart(partID, partTag)
if (part != null) {
part.load(partTag)
parts += part
}
}
if (parts.size == 0)
return null
val tmb = MultipartGenerator.generateCompositeTile(null, parts, false)
tmb.readFromNBT(tag)
tmb.loadParts(parts)
return tmb
}
/** Drops an item around pos
*/
def dropItem(stack: ItemStack, world: World, pos: Vector3) {
val item = new EntityItem(world, pos.x, pos.y, pos.z, stack)
item.motionX = world.rand.nextGaussian() * 0.05
item.motionY = world.rand.nextGaussian() * 0.05 + 0.2
item.motionZ = world.rand.nextGaussian() * 0.05
item.delayBeforeCanPickup = 10
world.spawnEntityInWorld(item)
}
}
@@ -0,0 +1,154 @@
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()
}
}
@@ -1,6 +1,8 @@
package codechicken.multipart.scalatraits
import codechicken.multipart.TMultiPart
import scala.runtime.AbstractFunction1
import scala.runtime.BoxedUnit
import codechicken.multipart.INeighborTileChange
import codechicken.multipart.TileMultipart
import codechicken.lib.vec.BlockCoord
@@ -48,10 +50,14 @@ trait TTileChangeTile extends TileMultipart {
return
val weak = diff == 2
operate { p =>
if (p.isInstanceOf[INeighborTileChange])
p.asInstanceOf[INeighborTileChange].onNeighborTileChanged(side, weak)
}
// TileMultipart.operate is declared in Java, so the function must be built explicitly rather than as a lambda.
operate(new AbstractFunction1[TMultiPart, BoxedUnit] {
def apply(p: TMultiPart): BoxedUnit = {
if (p.isInstanceOf[INeighborTileChange])
p.asInstanceOf[INeighborTileChange].onNeighborTileChanged(side, weak)
BoxedUnit.UNIT
}
})
}
override def getWeakChanges() = weakTileChanges