Skip to content

Commit

Permalink
more BlockPos to long
Browse files Browse the repository at this point in the history
  • Loading branch information
thiakil committed Sep 1, 2024
1 parent 297d2a7 commit a484cdf
Show file tree
Hide file tree
Showing 10 changed files with 129 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ public class CursedTransporterItemHandler implements IItemHandler {
private final Set<ItemStack> seenExecutedStacks = Collections.newSetFromMap(new IdentityHashMap<>());
private final LogisticalTransporterBase transporter;
private final LongSupplier currentTickSupplier;
private final BlockPos fromPos;
private final long fromPos;
private long lastTick;

public CursedTransporterItemHandler(LogisticalTransporterBase transporter, BlockPos fromPos, LongSupplier currentTickSupplier) {
public CursedTransporterItemHandler(LogisticalTransporterBase transporter, long fromPos, LongSupplier currentTickSupplier) {
this.transporter = transporter;
this.fromPos = fromPos;
this.currentTickSupplier = currentTickSupplier;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,16 @@ public List<AcceptorData> calculateAcceptors(TransitRequest request, Transporter
Map<GlobalPos, Set<TransporterStack>> additionalFlowingStacks, LogisticalTransporterBase start) {
List<AcceptorData> toReturn = new ArrayList<>();
for (Long2ObjectMap.Entry<Map<Direction, IItemHandler>> entry : acceptorCache.getAcceptorEntrySet()) {
BlockPos pos = BlockPos.of(entry.getLongKey());
if (!pos.equals(stack.homeLocation)) {
BlockEntity acceptor = WorldUtils.getTileEntity(getWorld(), chunkMap, pos);
long pos = entry.getLongKey();
if (pos != stack.homeLocation) {
BlockPos blockPos = BlockPos.of(pos);
BlockEntity acceptor = WorldUtils.getTileEntity(getWorld(), chunkMap, blockPos);
Map<TransitResponse, AcceptorData> dataMap = new HashMap<>();
GlobalPos position = GlobalPos.of(getWorld().dimension(), pos);
GlobalPos position = GlobalPos.of(getWorld().dimension(), blockPos);
for (Map.Entry<Direction, IItemHandler> acceptorEntry : entry.getValue().entrySet()) {
IItemHandler handler = acceptorEntry.getValue();
Direction side = acceptorEntry.getKey();
PathfinderCache.CachedPath cachedPath = PathfinderCache.getSingleCache(start, pos, side);
PathfinderCache.CachedPath cachedPath = PathfinderCache.getSingleCache(start, blockPos, side);
if (cachedPath != null && !TransporterPathfinder.checkPath(this, cachedPath.path(), stack)) {
continue;//invalid path, no need to simulate
}
Expand All @@ -77,7 +78,7 @@ public List<AcceptorData> calculateAcceptors(TransitRequest request, Transporter
AcceptorData data = dataMap.get(response);
if (data == null) {
//If we don't, add a new acceptor data for the response and position with side
data = new AcceptorData(pos, response, opposite);
data = new AcceptorData(blockPos, response, opposite);
dataMap.put(response, data);
toReturn.add(data);
//Note: In theory this shouldn't cause any issues if some exposed slots overlap but are for
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public void onUpdateServer() {
}
}
if (!transit.isEmpty()) {
BlockPos pos = getBlockPos();
long pos = getWorldPositionLong();
InventoryNetwork network = getTransmitterNetwork();
//Update stack positions
IntSet deletes = new IntOpenHashSet();
Expand All @@ -200,11 +200,11 @@ public void onUpdateServer() {
if (stack.progress >= 100) {
long prevSet = Long.MAX_VALUE;
if (stack.hasPath()) {
int currentIndex = stack.getPath().indexOf(pos.asLong());
if (currentIndex == 0) { //Necessary for transition reasons, not sure why
if (stack.getPath().getLong(0) == pos) { //Necessary for transition reasons, not sure why
deletes.add(stackId);
continue;
}
int currentIndex = stack.getPath().indexOf(pos);
long next = stack.getPath().getLong(currentIndex - 1);
if (next != Long.MAX_VALUE) {
if (!stack.isFinal(this)) {
Expand Down Expand Up @@ -269,7 +269,7 @@ public void onUpdateServer() {
if (nextPos == Long.MAX_VALUE) {
tryRecalculate = true;
} else {
Direction nextSide = stack.getSide(pos, nextPos);
Direction nextSide = stack.getSide(getWorldPositionLong(), nextPos);
LogisticalTransporterBase nextTransmitter = network.getTransmitter(nextPos);
if (nextTransmitter == null && stack.getPathType().noTarget() && stack.getPath().size() == 2) {
//If there is no next transmitter, and it was an idle path, assume that we are idling
Expand Down Expand Up @@ -424,9 +424,7 @@ private boolean recalculate(int stackId, TransporterStack stack, long from) {

//Only add to needsSync if true is being returned; otherwise it gets added to deletes
needsSync.put(stackId, stack);
if (from != Long.MAX_VALUE) {
stack.originalLocation = BlockPos.of(from);
}
stack.originalLocation = from;
return true;
}

Expand All @@ -445,25 +443,25 @@ private <BE extends BlockEntity> TransitResponse insert(@Nullable BE outputter,
int min, boolean doEmit, PathCalculator<BE> pathCalculator) {
Direction from = WorldUtils.sideDifference(getBlockPos(), outputterPos);
if (from != null && canReceiveFrom(from.getOpposite())) {
TransporterStack stack = createInsertStack(outputterPos.immutable(), color);
TransporterStack stack = createInsertStack(outputterPos.asLong(), color);
if (stack.canInsertToTransporterNN(this, from, outputter)) {
return updateTransit(doEmit, stack, pathCalculator.calculate(stack, request, outputter, this, min, doEmit));
}
}
return request.getEmptyResponse();
}

public TransitResponse insertUnchecked(BlockPos outputterPos, TransitRequest request, @Nullable EnumColor color, boolean doEmit, int min) {
public TransitResponse insertUnchecked(long outputterPos, TransitRequest request, @Nullable EnumColor color, boolean doEmit, int min) {
TransporterStack stack = createInsertStack(outputterPos, color);
return updateTransit(doEmit, stack, stack.recalculatePath(request, this, min, doEmit));
}

public <BE extends BlockEntity> TransitResponse insertUnchecked(BE outputter, TransitRequest request, @Nullable EnumColor color, boolean doEmit, int min, PathCalculator<BE> pathCalculator) {
TransporterStack stack = createInsertStack(outputter.getBlockPos(), color);
TransporterStack stack = createInsertStack(outputter.getBlockPos().asLong(), color);
return updateTransit(doEmit, stack, pathCalculator.calculate(stack, request, outputter, this, min, doEmit));
}

public TransporterStack createInsertStack(BlockPos outputterCoord, @Nullable EnumColor color) {
public TransporterStack createInsertStack(long outputterCoord, @Nullable EnumColor color) {
TransporterStack stack = new TransporterStack();
stack.originalLocation = outputterCoord;
stack.homeLocation = outputterCoord;
Expand All @@ -478,7 +476,7 @@ private TransitResponse updateTransit(boolean doEmit, TransporterStack stack, Tr
if (doEmit) {
int stackId = nextId++;
addStack(stackId, stack);
PacketUtils.sendToAllTracking(PacketTransporterSync.create(getBlockPos(), stackId, stack), getTransmitterTile());
PacketUtils.sendToAllTracking(PacketTransporterSync.create(getWorldPositionLong(), stackId, stack), getTransmitterTile());
getTransmitterTile().markForSave();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,16 +173,16 @@ public static IdlePathData getIdlePath(LogisticalTransporterBase start, Transpor
if (network == null) {
return null;
}
if (stack.homeLocation != null) {
if (stack.homeLocation != Long.MAX_VALUE) {
Long2ObjectMap<ChunkAccess> chunkMap = new Long2ObjectOpenHashMap<>();
//We are idling use the base stack
Pathfinder p = new Pathfinder(network, start.getLevel(), stack.homeLocation, start.getBlockPos(), stack, stack.itemStack,
Pathfinder p = new Pathfinder(network, start.getLevel(), BlockPos.of(stack.homeLocation), start.getBlockPos(), stack, stack.itemStack,
(level, pos, tile, s, resp, side) -> TransporterUtils.canInsert(level, pos, tile, s.color, resp, side, true));
p.find(chunkMap);
if (p.hasPath()) {
return new IdlePathData(p.getPath(), Path.HOME);
}
stack.homeLocation = null;
stack.homeLocation = Long.MAX_VALUE;
}

IdlePath d = new IdlePath(network, start.getBlockPos(), stack);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,10 @@
import mekanism.common.lib.inventory.TransitRequest.TransitResponse;
import mekanism.common.util.NBTUtils;
import mekanism.common.util.WorldUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.GlobalPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
Expand All @@ -44,7 +42,7 @@ public class TransporterStack {
public static StreamCodec<RegistryFriendlyByteBuf, TransporterStack> STREAM_CODEC = NeoForgeStreamCodecs.composite(
EnumColor.OPTIONAL_STREAM_CODEC, stack -> Optional.ofNullable(stack.color),
ByteBufCodecs.VAR_INT, stack -> stack.progress,
BlockPos.STREAM_CODEC, stack -> stack.originalLocation,
ByteBufCodecs.VAR_LONG, stack -> stack.originalLocation,
Path.STREAM_CODEC, TransporterStack::getPathType,
ByteBufCodecs.optional(ByteBufCodecs.VAR_LONG), stack -> stack.clientNext == Long.MAX_VALUE ? Optional.empty() : Optional.of(stack.clientNext),
ByteBufCodecs.optional(ByteBufCodecs.VAR_LONG), stack -> stack.clientPrev == Long.MAX_VALUE ? Optional.empty() : Optional.of(stack.clientPrev),
Expand All @@ -71,10 +69,14 @@ public class TransporterStack {
public boolean initiatedPath = false;

public Direction idleDir = null;
public BlockPos originalLocation;
public BlockPos homeLocation;

//packed BlockPos-es
public long originalLocation = Long.MAX_VALUE;
public long homeLocation = Long.MAX_VALUE;
private long clientNext = Long.MAX_VALUE;
private long clientPrev = Long.MAX_VALUE;
//

@Nullable
private Path pathType;
private LongList pathToTarget = new LongArrayList();
Expand All @@ -96,7 +98,7 @@ public void writeToUpdateTag(HolderLookup.Provider provider, LogisticalTransport
NBTUtils.writeEnum(updateTag, SerializationConstants.COLOR, color);
}
updateTag.putInt(SerializationConstants.PROGRESS, progress);
updateTag.put(SerializationConstants.ORIGINAL_LOCATION, NbtUtils.writeBlockPos(originalLocation));
updateTag.putLong(SerializationConstants.ORIGINAL_LOCATION, originalLocation);
NBTUtils.writeEnum(updateTag, SerializationConstants.PATH_TYPE, getPathType());
long next = getNext(transporter);
if (next != Long.MAX_VALUE) {
Expand All @@ -114,7 +116,7 @@ public void writeToUpdateTag(HolderLookup.Provider provider, LogisticalTransport
public void readFromUpdateTag(HolderLookup.Provider provider, CompoundTag updateTag) {
this.color = NBTUtils.getEnum(updateTag, SerializationConstants.COLOR, EnumColor.BY_ID);
progress = updateTag.getInt(SerializationConstants.PROGRESS);
NBTUtils.setBlockPosIfPresent(updateTag, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord);
NBTUtils.setLongIfPresent(updateTag, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord);
NBTUtils.setEnumIfPresent(updateTag, SerializationConstants.PATH_TYPE, Path.BY_ID, type -> pathType = type);

//todo is backcompat needed?
Expand All @@ -137,13 +139,13 @@ public void write(HolderLookup.Provider provider, CompoundTag nbtTags) {
}

nbtTags.putInt(SerializationConstants.PROGRESS, progress);
nbtTags.put(SerializationConstants.ORIGINAL_LOCATION, NbtUtils.writeBlockPos(originalLocation));
nbtTags.putLong(SerializationConstants.ORIGINAL_LOCATION, originalLocation);

if (idleDir != null) {
NBTUtils.writeEnum(nbtTags, SerializationConstants.IDLE_DIR, idleDir);
}
if (homeLocation != null) {
nbtTags.put(SerializationConstants.HOME_LOCATION, NbtUtils.writeBlockPos(homeLocation));
if (homeLocation != Long.MAX_VALUE) {
nbtTags.putLong(SerializationConstants.HOME_LOCATION, homeLocation);
}
if (pathType != null) {
NBTUtils.writeEnum(nbtTags, SerializationConstants.PATH_TYPE, pathType);
Expand All @@ -156,12 +158,15 @@ public void write(HolderLookup.Provider provider, CompoundTag nbtTags) {
public void read(HolderLookup.Provider provider, CompoundTag nbtTags) {
this.color = NBTUtils.getEnum(nbtTags, SerializationConstants.COLOR, EnumColor.BY_ID);
progress = nbtTags.getInt(SerializationConstants.PROGRESS);
NBTUtils.setBlockPosIfPresent(nbtTags, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord);
NBTUtils.setBlockPosIfPresent(nbtTags, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord.asLong());//TODO 1.22 remove backcompat
NBTUtils.setLongIfPresent(nbtTags, SerializationConstants.ORIGINAL_LOCATION, coord -> originalLocation = coord);
NBTUtils.setEnumIfPresent(nbtTags, SerializationConstants.IDLE_DIR, Direction::from3DDataValue, dir -> idleDir = dir);
NBTUtils.setBlockPosIfPresent(nbtTags, SerializationConstants.HOME_LOCATION, coord -> homeLocation = coord);
NBTUtils.setBlockPosIfPresent(nbtTags, SerializationConstants.HOME_LOCATION, coord -> homeLocation = coord.asLong());//TODO 1.22 remove backcompat
NBTUtils.setLongIfPresent(nbtTags, SerializationConstants.HOME_LOCATION, coord -> homeLocation = coord);
NBTUtils.setEnumIfPresent(nbtTags, SerializationConstants.PATH_TYPE, Path.BY_ID, type -> pathType = type);
if (nbtTags.contains(SerializationConstants.ITEM_OVERSIZED)) {
itemStack = SerializerHelper.parseOversized(provider, nbtTags.get(SerializationConstants.ITEM_OVERSIZED)).orElse(ItemStack.EMPTY);
Tag oversizedTag = nbtTags.get(SerializationConstants.ITEM_OVERSIZED);
if (oversizedTag != null) {
itemStack = SerializerHelper.parseOversized(provider, oversizedTag).orElse(ItemStack.EMPTY);
} else if (nbtTags.contains(SerializationConstants.ITEM, Tag.TAG_COMPOUND)) {//TODO - 1.22: Remove this legacy way of loading data
itemStack = ItemStack.parseOptional(provider, nbtTags.getCompound(SerializationConstants.ITEM));
} else {//TODO - 1.22: Remove this legacy way of loading data
Expand Down Expand Up @@ -248,7 +253,7 @@ public boolean calculateIdle(LogisticalTransporterBase transporter) {
idleDir = null;
}
setPath(transporter.getLevel(), newPath.path(), newPath.type(), true);
originalLocation = transporter.getBlockPos();
originalLocation = transporter.getWorldPositionLong();
initiatedPath = true;
return true;
}
Expand All @@ -258,18 +263,18 @@ public boolean isFinal(LogisticalTransporterBase transporter) {
}

//TODO - 1.20.5: Re-evaluate this method
public TransporterStack updateForPos(BlockPos pos) {
public TransporterStack updateForPos(long pos) {
clientNext = getNext(pos);
clientPrev = getPrev(pos.asLong());
clientPrev = getPrev(pos);
return this;
}

public long getNext(LogisticalTransporterBase transporter) {
return transporter.isRemote() ? clientNext : getNext(transporter.getBlockPos());
return transporter.isRemote() ? clientNext : getNext(transporter.getWorldPositionLong());
}

private long getNext(BlockPos pos) {
int index = pathToTarget.indexOf(pos.asLong()) - 1;
private long getNext(long pos) {
int index = pathToTarget.indexOf(pos) - 1;
if (index < 0) {
return Long.MAX_VALUE;
}
Expand All @@ -285,7 +290,7 @@ private long getPrev(long pos) {
if (index < pathToTarget.size()) {
return pathToTarget.getLong(index);
}
return originalLocation.asLong();
return originalLocation;
}

public Direction getSide(LogisticalTransporterBase transporter) {
Expand All @@ -308,10 +313,10 @@ public Direction getSide(LogisticalTransporterBase transporter) {
return side == null ? Direction.DOWN : side;
}

public Direction getSide(BlockPos pos, long target) {
public Direction getSide(long pos, long target) {
Direction side = null;
if (target != Long.MAX_VALUE) {
side = WorldUtils.sideDifference(target, pos.asLong());
side = WorldUtils.sideDifference(target, pos);
}
//TODO: See getSide(Transporter) for why we null check and then return down
return side == null ? Direction.DOWN : side;
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/mekanism/common/network/PacketUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ public static BlockEntity blockEntity(IPayloadContext context, BlockPos pos) {
return WorldUtils.getTileEntity(context.player().level(), pos);
}

@Nullable
public static BlockEntity blockEntity(IPayloadContext context, long pos) {
return WorldUtils.getTileEntity(context.player().level(), pos);
}

/**
* Send this message to the server.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,24 @@
import mekanism.common.network.IMekanismPacket;
import mekanism.common.network.PacketUtils;
import mekanism.common.tile.transmitter.TileEntityLogisticalTransporterBase;
import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import org.jetbrains.annotations.NotNull;

public record PacketTransporterBatch(BlockPos pos, IntSet deletes, Int2ObjectMap<TransporterStack> updates) implements IMekanismPacket {
public record PacketTransporterBatch(long pos, IntSet deletes, Int2ObjectMap<TransporterStack> updates) implements IMekanismPacket {

public static final CustomPacketPayload.Type<PacketTransporterBatch> TYPE = new CustomPacketPayload.Type<>(Mekanism.rl("transporter_batch"));
public static final StreamCodec<RegistryFriendlyByteBuf, PacketTransporterBatch> STREAM_CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketTransporterBatch::pos,
ByteBufCodecs.VAR_LONG, PacketTransporterBatch::pos,
ByteBufCodecs.VAR_INT.apply(ByteBufCodecs.collection(IntOpenHashSet::new)), PacketTransporterBatch::deletes,
ByteBufCodecs.map(Int2ObjectOpenHashMap::new, ByteBufCodecs.VAR_INT, TransporterStack.STREAM_CODEC), PacketTransporterBatch::updates,
PacketTransporterBatch::new
);

public static PacketTransporterBatch create(BlockPos pos, IntSet deletes, Int2ObjectMap<TransporterStack> updates) {
public static PacketTransporterBatch create(long pos, IntSet deletes, Int2ObjectMap<TransporterStack> updates) {
for (TransporterStack stack : updates.values()) {
stack.updateForPos(pos);
}
Expand Down
Loading

0 comments on commit a484cdf

Please sign in to comment.