diff --git a/src/main/java/de/ellpeck/prettypipes/Utility.java b/src/main/java/de/ellpeck/prettypipes/Utility.java index 974da7e..01a0d1d 100644 --- a/src/main/java/de/ellpeck/prettypipes/Utility.java +++ b/src/main/java/de/ellpeck/prettypipes/Utility.java @@ -7,10 +7,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.Style; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.network.chat.*; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Containers; @@ -53,7 +50,7 @@ public final class Utility { return Direction.fromNormal(diff.getX(), diff.getY(), diff.getZ()); } - public static void addTooltip(String name, List tooltip) { + public static void addTooltip(String name, List tooltip) { if (Screen.hasShiftDown()) { var content = I18n.get("info." + PrettyPipes.ID + "." + name).split("\n"); for (var s : content) diff --git a/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameEntity.java b/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameEntity.java index a49050c..890edf8 100644 --- a/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameEntity.java +++ b/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameEntity.java @@ -1,21 +1,15 @@ package de.ellpeck.prettypipes.entities; import de.ellpeck.prettypipes.Registry; -import de.ellpeck.prettypipes.network.NetworkLocation; import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.pipe.PipeBlock; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.network.IPacket; -import net.minecraft.network.PacketBuffer; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.sounds.SoundEvents; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.world.GameRules; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; @@ -26,15 +20,10 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.HitResult; import net.minecraftforge.entity.IEntityAdditionalSpawnData; -import net.minecraftforge.fml.network.NetworkHooks; -import net.minecraftforge.network.ICustomPacket; -import net.minecraftforge.network.NetworkHooks; import javax.annotation.Nullable; -import java.util.List; public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawnData { @@ -63,15 +52,15 @@ public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawn return; if (this.tickCount % 40 != 0) return; - PipeNetwork network = PipeNetwork.get(this.level); - BlockPos attached = getAttachedPipe(this.level, this.pos, this.direction); + var network = PipeNetwork.get(this.level); + var attached = getAttachedPipe(this.level, this.pos, this.direction); if (attached != null) { - BlockPos node = network.getNodeFromPipe(attached); + var node = network.getNodeFromPipe(attached); if (node != null) { - ItemStack stack = this.getItem(); + var stack = this.getItem(); if (!stack.isEmpty()) { - List items = network.getOrderedNetworkItems(node); - int amount = items.stream().mapToInt(i -> i.getItemAmount(this.level, stack)).sum(); + var items = network.getOrderedNetworkItems(node); + var amount = items.stream().mapToInt(i -> i.getItemAmount(this.level, stack)).sum(); this.entityData.set(AMOUNT, amount); return; } @@ -86,9 +75,9 @@ public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawn } private static BlockPos getAttachedPipe(Level world, BlockPos pos, Direction direction) { - for (int i = 1; i <= 2; i++) { - BlockPos offset = pos.relative(direction.getOpposite(), i); - BlockState state = world.getBlockState(offset); + for (var i = 1; i <= 2; i++) { + var offset = pos.relative(direction.getOpposite(), i); + var state = world.getBlockState(offset); if (state.getBlock() instanceof PipeBlock) return offset; } @@ -130,7 +119,7 @@ public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawn if (entityIn == null) this.getItem().setEntityRepresentation(null); } else { - ItemStack itemstack = this.getItem(); + var itemstack = this.getItem(); this.setItem(ItemStack.EMPTY); if (entityIn instanceof Player playerentity) { if (playerentity.isCreative()) { @@ -158,26 +147,20 @@ public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawn return InteractionResult.FAIL; } - @Override public ItemStack getPickedResult(HitResult target) { return new ItemStack(Registry.pipeFrameItem); } @Override - public ICustomPacket createSpawnPacket() { - return NetworkHooks.getEntitySpawningPacket(this); + public void writeSpawnData(FriendlyByteBuf buffer) { + buffer.writeBlockPos(this.pos); + buffer.writeInt(this.direction.ordinal()); } @Override - public void writeSpawnData(PacketBuffer buffer) { - buffer.writeBlockPos(this.hangingPosition); - buffer.writeInt(this.facingDirection.getIndex()); - } - - @Override - public void readSpawnData(PacketBuffer additionalData) { - this.hangingPosition = additionalData.readBlockPos(); - this.updateFacingWithBoundingBox(Direction.values()[additionalData.readInt()]); + public void readSpawnData(FriendlyByteBuf additionalData) { + this.pos = additionalData.readBlockPos(); + this.direction = Direction.values()[additionalData.readInt()]; } } diff --git a/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameRenderer.java b/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameRenderer.java index b4ec701..05f1e86 100644 --- a/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameRenderer.java +++ b/src/main/java/de/ellpeck/prettypipes/entities/PipeFrameRenderer.java @@ -1,42 +1,37 @@ package de.ellpeck.prettypipes.entities; -import com.mojang.blaze3d.matrix.MatrixStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.IRenderTypeBuffer; -import net.minecraft.client.renderer.entity.EntityRendererManager; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.math.Vector3f; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.client.renderer.entity.ItemFrameRenderer; -import net.minecraft.entity.item.ItemFrameEntity; -import net.minecraft.util.Direction; -import net.minecraft.util.math.vector.Matrix4f; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraft.util.math.vector.Vector3f; -public class PipeFrameRenderer extends ItemFrameRenderer { - public PipeFrameRenderer(EntityRendererManager renderManagerIn) { - super(renderManagerIn, Minecraft.getInstance().getItemRenderer()); +public class PipeFrameRenderer extends ItemFrameRenderer { + + public PipeFrameRenderer(EntityRendererProvider.Context renderManagerIn) { + super(renderManagerIn); } @Override - public void render(ItemFrameEntity entityIn, float entityYaw, float partialTicks, MatrixStack matrixStackIn, IRenderTypeBuffer bufferIn, int packedLightIn) { + public void render(PipeFrameEntity entityIn, float entityYaw, float partialTicks, PoseStack matrixStackIn, MultiBufferSource bufferIn, int packedLightIn) { super.render(entityIn, entityYaw, partialTicks, matrixStackIn, bufferIn, packedLightIn); - matrixStackIn.push(); - Direction direction = entityIn.getHorizontalFacing(); - Vector3d vec3d = this.getRenderOffset(entityIn, partialTicks); - matrixStackIn.translate(-vec3d.getX(), -vec3d.getY(), -vec3d.getZ()); - matrixStackIn.translate(direction.getXOffset() * 0.46875, direction.getYOffset() * 0.46875, direction.getZOffset() * 0.46875); - matrixStackIn.rotate(Vector3f.XP.rotationDegrees(entityIn.rotationPitch)); - matrixStackIn.rotate(Vector3f.YP.rotationDegrees(180.0F - entityIn.rotationYaw)); + matrixStackIn.pushPose(); + var direction = entityIn.getDirection(); + var vec3d = this.getRenderOffset(entityIn, partialTicks); + matrixStackIn.translate(-vec3d.x, -vec3d.y, -vec3d.z); + matrixStackIn.translate(direction.getStepX() * 0.46875, direction.getStepY() * 0.46875, direction.getStepZ() * 0.46875); + matrixStackIn.mulPose(Vector3f.XP.rotationDegrees(entityIn.getXRot())); + matrixStackIn.mulPose(Vector3f.YP.rotationDegrees(180.0F - entityIn.getYRot())); - FontRenderer font = this.getFontRendererFromRenderManager(); - int amount = ((PipeFrameEntity) entityIn).getAmount(); - String ammountStrg = amount < 0 ? "?" : String.valueOf(amount); - float x = 0.5F - font.getStringWidth(ammountStrg) / 2F; - Matrix4f matrix4f = matrixStackIn.getLast().getMatrix(); + var font = this.getFont(); + var amount = entityIn.getAmount(); + var ammountStrg = amount < 0 ? "?" : String.valueOf(amount); + var x = 0.5F - font.width(ammountStrg) / 2F; + var matrix4f = matrixStackIn.last().pose(); matrixStackIn.translate(0, 0.285F, 0.415F); matrixStackIn.scale(-0.02F, -0.02F, 0.02F); - font.renderString(ammountStrg, x, 0, 0xFFFFFF, true, matrix4f, bufferIn, false, 0, packedLightIn); + font.drawInBatch(ammountStrg, x, 0, 0xFFFFFF, true, matrix4f, bufferIn, false, 0, packedLightIn); - matrixStackIn.pop(); + matrixStackIn.popPose(); } } diff --git a/src/main/java/de/ellpeck/prettypipes/items/ModuleItem.java b/src/main/java/de/ellpeck/prettypipes/items/ModuleItem.java index 1e4872e..b018d8e 100644 --- a/src/main/java/de/ellpeck/prettypipes/items/ModuleItem.java +++ b/src/main/java/de/ellpeck/prettypipes/items/ModuleItem.java @@ -5,14 +5,14 @@ import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.item.Item; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.world.World; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.items.IItemHandler; @@ -28,14 +28,14 @@ public abstract class ModuleItem extends Item implements IModule { private final String name; public ModuleItem(String name) { - super(new Properties().group(Registry.GROUP).maxStackSize(16)); + super(new Properties().tab(Registry.GROUP).stacksTo(16)); this.name = name; } @Override @OnlyIn(Dist.CLIENT) - public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) { - super.addInformation(stack, worldIn, tooltip, flagIn); + public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List tooltip, TooltipFlag flagIn) { + super.appendHoverText(stack, worldIn, tooltip, flagIn); Utility.addTooltip(this.name, tooltip); } @@ -65,7 +65,7 @@ public abstract class ModuleItem extends Item implements IModule { } @Override - public AbstractPipeContainer getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { + public AbstractPipeContainer getContainer(ItemStack module, PipeBlockEntity tile, int windowId, Inventory inv, Player player, int moduleIndex) { return null; } diff --git a/src/main/java/de/ellpeck/prettypipes/items/PipeFrameItem.java b/src/main/java/de/ellpeck/prettypipes/items/PipeFrameItem.java index 2f591d6..eca98fe 100644 --- a/src/main/java/de/ellpeck/prettypipes/items/PipeFrameItem.java +++ b/src/main/java/de/ellpeck/prettypipes/items/PipeFrameItem.java @@ -3,71 +3,68 @@ package de.ellpeck.prettypipes.items; import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.entities.PipeFrameEntity; -import net.minecraft.block.BlockState; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.entity.EntityType; -import net.minecraft.entity.item.HangingEntity; -import net.minecraft.entity.item.ItemFrameEntity; -import net.minecraft.entity.item.PaintingEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.Item; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.chat.Component; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.decoration.HangingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.item.ItemUseContext; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.util.ActionResultType; -import net.minecraft.util.Direction; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.world.World; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.Level; import javax.annotation.Nullable; import java.util.List; public class PipeFrameItem extends Item { + public PipeFrameItem() { - super(new Properties().group(Registry.GROUP)); + super(new Properties().tab(Registry.GROUP)); } // HangingEntityItem copypasta mostly, since it hardcodes the entities bleh @Override - public ActionResultType onItemUse(ItemUseContext context) { - BlockPos blockpos = context.getPos(); - Direction direction = context.getFace(); - BlockPos blockpos1 = blockpos.offset(direction); - PlayerEntity playerentity = context.getPlayer(); - ItemStack itemstack = context.getItem(); + public InteractionResult useOn(UseOnContext context) { + var blockpos = context.getClickedPos(); + var direction = context.getClickedFace(); + var blockpos1 = blockpos.relative(direction); + var playerentity = context.getPlayer(); + var itemstack = context.getItemInHand(); if (playerentity != null && !this.canPlace(playerentity, direction, itemstack, blockpos1)) { - return ActionResultType.FAIL; + return InteractionResult.FAIL; } else { - World world = context.getWorld(); + var world = context.getLevel(); HangingEntity hangingentity = new PipeFrameEntity(Registry.pipeFrameEntity, world, blockpos1, direction); - CompoundTag CompoundTag = itemstack.getTag(); - if (CompoundTag != null) { - EntityType.applyItemNBT(world, playerentity, hangingentity, CompoundTag); + var compoundTag = itemstack.getTag(); + if (compoundTag != null) { + EntityType.updateCustomEntityTag(world, playerentity, hangingentity, compoundTag); } - if (hangingentity.onValidSurface()) { - if (!world.isRemote) { - hangingentity.playPlaceSound(); - world.addEntity(hangingentity); + if (hangingentity.survives()) { + if (!world.isClientSide) { + hangingentity.playPlacementSound(); + world.addFreshEntity(hangingentity); } itemstack.shrink(1); - return ActionResultType.SUCCESS; + return InteractionResult.SUCCESS; } else { - return ActionResultType.CONSUME; + return InteractionResult.CONSUME; } } } - protected boolean canPlace(PlayerEntity playerIn, Direction directionIn, ItemStack itemStackIn, BlockPos posIn) { - return !directionIn.getAxis().isVertical() && playerIn.canPlayerEdit(posIn, directionIn, itemStackIn) && PipeFrameEntity.canPlace(playerIn.world, posIn, directionIn); + protected boolean canPlace(Player playerIn, Direction directionIn, ItemStack itemStackIn, BlockPos posIn) { + return !directionIn.getAxis().isVertical() && playerIn.mayUseItemAt(posIn, directionIn, itemStackIn) && PipeFrameEntity.canPlace(playerIn.level, posIn, directionIn); } @Override - public void addInformation(ItemStack stack, @Nullable World worldIn, List tooltip, ITooltipFlag flagIn) { - super.addInformation(stack, worldIn, tooltip, flagIn); + public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List tooltip, TooltipFlag flagIn) { + super.appendHoverText(stack, worldIn, tooltip, flagIn); Utility.addTooltip(this.getRegistryName().getPath(), tooltip); } } diff --git a/src/main/java/de/ellpeck/prettypipes/items/WrenchItem.java b/src/main/java/de/ellpeck/prettypipes/items/WrenchItem.java index 9ce2809..d719e54 100644 --- a/src/main/java/de/ellpeck/prettypipes/items/WrenchItem.java +++ b/src/main/java/de/ellpeck/prettypipes/items/WrenchItem.java @@ -5,47 +5,44 @@ import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.pipe.ConnectionType; import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlockEntity; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.client.util.ITooltipFlag; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.enchantment.Enchantments; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.item.*; -import net.minecraft.state.EnumProperty; -import net.minecraft.util.ActionResultType; -import net.minecraft.util.Direction; -import net.minecraft.util.SoundCategory; -import net.minecraft.util.SoundEvents; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.shapes.VoxelShape; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.world.World; +import net.minecraft.network.chat.Component; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.EntityBlock; import java.util.List; -import java.util.Map; public class WrenchItem extends Item { public WrenchItem() { - super(new Item.Properties().maxStackSize(1).group(Registry.GROUP)); + super(new Item.Properties().stacksTo(1).tab(Registry.GROUP)); } @Override - public ActionResultType onItemUse(ItemUseContext context) { - World world = context.getWorld(); - BlockPos pos = context.getPos(); - PlayerEntity player = context.getPlayer(); - BlockState state = world.getBlockState(pos); + public InteractionResult useOn(UseOnContext context) { + var world = context.getLevel(); + var pos = context.getClickedPos(); + var player = context.getPlayer(); + var state = world.getBlockState(pos); if (!(state.getBlock() instanceof PipeBlock)) - return ActionResultType.PASS; - PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, world, pos); + return InteractionResult.PASS; + var tile = Utility.getBlockEntity(PipeBlockEntity.class, world, pos); if (tile == null) - return ActionResultType.FAIL; + return InteractionResult.FAIL; - if (player.isSneaking()) { - if (!world.isRemote) { + if (player.isCrouching()) { + if (!world.isClientSide) { if (tile.cover != null) { // remove the cover tile.removeCover(player, context.getHand()); @@ -53,64 +50,64 @@ public class WrenchItem extends Item { } else { // remove the pipe PipeBlock.dropItems(world, pos, player); - Block.spawnDrops(state, world, pos, tile, null, ItemStack.EMPTY); + Block.dropResources(state, world, pos, tile, null, ItemStack.EMPTY); world.removeBlock(pos, false); } - world.playSound(null, pos, SoundEvents.ENTITY_ITEM_FRAME_REMOVE_ITEM, SoundCategory.PLAYERS, 1, 1); + world.playSound(null, pos, SoundEvents.ITEM_FRAME_REMOVE_ITEM, SoundSource.PLAYERS, 1, 1); } - return ActionResultType.func_233537_a_(world.isRemote); + return InteractionResult.sidedSuccess(world.isClientSide); } // placing covers if (tile.cover == null) { - ItemStack offhand = player.getHeldItemOffhand(); + var offhand = player.getOffhandItem(); if (offhand.getItem() instanceof BlockItem) { - if (!world.isRemote) { - BlockItemUseContext blockContext = new BlockItemUseContext(context); - Block block = ((BlockItem) offhand.getItem()).getBlock(); - BlockState cover = block.getStateForPlacement(blockContext); - if (cover != null && !block.hasTileEntity(cover)) { + if (!world.isClientSide) { + var blockContext = new BlockPlaceContext(context); + var block = ((BlockItem) offhand.getItem()).getBlock(); + var cover = block.getStateForPlacement(blockContext); + if (cover != null && !(block instanceof EntityBlock)) { tile.cover = cover; Utility.sendBlockEntityToClients(tile); offhand.shrink(1); - world.playSound(null, pos, SoundEvents.ENTITY_ITEM_FRAME_ADD_ITEM, SoundCategory.PLAYERS, 1, 1); + world.playSound(null, pos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.PLAYERS, 1, 1); } } - return ActionResultType.func_233537_a_(world.isRemote); + return InteractionResult.sidedSuccess(world.isClientSide); } } // disabling directions - for (Map.Entry entry : PipeBlock.DIR_SHAPES.entrySet()) { - AxisAlignedBB box = entry.getValue().getBoundingBox().offset(pos).grow(0.001F); - if (!box.contains(context.getHitVec())) + for (var entry : PipeBlock.DIR_SHAPES.entrySet()) { + var box = entry.getValue().bounds().move(pos).inflate(0.001F); + if (!box.contains(context.getClickLocation())) continue; - EnumProperty prop = PipeBlock.DIRECTIONS.get(entry.getKey()); - ConnectionType curr = state.get(prop); + var prop = PipeBlock.DIRECTIONS.get(entry.getKey()); + var curr = state.getValue(prop); if (curr == ConnectionType.DISCONNECTED) continue; - if (!world.isRemote) { - ConnectionType newType = curr == ConnectionType.BLOCKED ? ConnectionType.CONNECTED : ConnectionType.BLOCKED; - BlockPos otherPos = pos.offset(entry.getKey()); - BlockState otherState = world.getBlockState(otherPos); + if (!world.isClientSide) { + var newType = curr == ConnectionType.BLOCKED ? ConnectionType.CONNECTED : ConnectionType.BLOCKED; + var otherPos = pos.relative(entry.getKey()); + var otherState = world.getBlockState(otherPos); if (otherState.getBlock() instanceof PipeBlock) { - otherState = otherState.with(PipeBlock.DIRECTIONS.get(entry.getKey().getOpposite()), newType); - world.setBlockState(otherPos, otherState); + otherState = otherState.setValue(PipeBlock.DIRECTIONS.get(entry.getKey().getOpposite()), newType); + world.setBlockAndUpdate(otherPos, otherState); PipeBlock.onStateChanged(world, otherPos, otherState); } - BlockState newState = state.with(prop, newType); - world.setBlockState(pos, newState); + var newState = state.setValue(prop, newType); + world.setBlockAndUpdate(pos, newState); PipeBlock.onStateChanged(world, pos, newState); - world.playSound(null, pos, SoundEvents.ENTITY_ITEM_FRAME_ROTATE_ITEM, SoundCategory.PLAYERS, 1, 1); + world.playSound(null, pos, SoundEvents.ITEM_FRAME_ROTATE_ITEM, SoundSource.PLAYERS, 1, 1); } - return ActionResultType.func_233537_a_(world.isRemote); + return InteractionResult.sidedSuccess(world.isClientSide); } - return ActionResultType.PASS; + return InteractionResult.PASS; } @Override - public void addInformation(ItemStack stack, World worldIn, List tooltip, ITooltipFlag flagIn) { + public void appendHoverText(ItemStack stack, Level worldIn, List tooltip, TooltipFlag flagIn) { Utility.addTooltip(this.getRegistryName().getPath(), tooltip); } diff --git a/src/main/java/de/ellpeck/prettypipes/misc/EquatableItemStack.java b/src/main/java/de/ellpeck/prettypipes/misc/EquatableItemStack.java index e597a1e..1303566 100644 --- a/src/main/java/de/ellpeck/prettypipes/misc/EquatableItemStack.java +++ b/src/main/java/de/ellpeck/prettypipes/misc/EquatableItemStack.java @@ -5,21 +5,11 @@ import net.minecraft.world.item.ItemStack; import java.util.Arrays; import java.util.Objects; -public class EquatableItemStack { - - public final ItemStack stack; - public final ItemEquality[] equalityTypes; - - public EquatableItemStack(ItemStack stack, ItemEquality... equalityTypes) { - this.stack = stack; - this.equalityTypes = equalityTypes; - } +public record EquatableItemStack(ItemStack stack, ItemEquality... equalityTypes) { public boolean equals(Object o) { - if (o instanceof EquatableItemStack) { - EquatableItemStack other = (EquatableItemStack) o; + if (o instanceof EquatableItemStack other) return Arrays.equals(this.equalityTypes, other.equalityTypes) && ItemEquality.compareItems(this.stack, other.stack, this.equalityTypes); - } return false; } diff --git a/src/main/java/de/ellpeck/prettypipes/misc/ItemFilter.java b/src/main/java/de/ellpeck/prettypipes/misc/ItemFilter.java index 4825595..34843c4 100644 --- a/src/main/java/de/ellpeck/prettypipes/misc/ItemFilter.java +++ b/src/main/java/de/ellpeck/prettypipes/misc/ItemFilter.java @@ -9,6 +9,8 @@ import net.minecraft.ChatFormatting; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.Widget; import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.Direction; +import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.TranslatableComponent; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; @@ -42,7 +44,7 @@ public class ItemFilter extends ItemStackHandler { public List getSlots(int x, int y) { List slots = new ArrayList<>(); - for (int i = 0; i < this.getSlots(); i++) + for (var i = 0; i < this.getSlots(); i++) slots.add(new FilterSlot(this, i, x + i % 9 * 18, y + i / 9 * 18, true)); return slots; } @@ -51,14 +53,14 @@ public class ItemFilter extends ItemStackHandler { public List getButtons(Screen gui, int x, int y) { List buttons = new ArrayList<>(); if (this.canModifyWhitelist) { - Supplier whitelistText = () -> new TranslatableComponent("info." + PrettyPipes.ID + "." + (this.isWhitelist ? "whitelist" : "blacklist")); + var whitelistText = (Supplier) () -> new TranslatableComponent("info." + PrettyPipes.ID + "." + (this.isWhitelist ? "whitelist" : "blacklist")); buttons.add(new Button(x, y, 70, 20, whitelistText.get(), button -> { - PacketButton.sendAndExecute(this.pipe.getPos(), PacketButton.ButtonResult.FILTER_CHANGE, 0); + PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 0); button.setMessage(whitelistText.get()); })); } if (this.canPopulateFromInventories) { - buttons.add(new Button(x + 72, y, 70, 20, new TranslatableComponent("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getPos(), PacketButton.ButtonResult.FILTER_CHANGE, 1)) { + buttons.add(new Button(x + 72, y, 70, 20, new TranslatableComponent("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 1)) { @Override public void renderToolTip(PoseStack matrix, int x, int y) { gui.renderTooltip(matrix, new TranslatableComponent("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY), x, y); @@ -75,19 +77,19 @@ public class ItemFilter extends ItemStackHandler { this.save(); } else if (id == 1 && this.canPopulateFromInventories) { // populate filter from inventories - List filters = this.pipe.getFilters(); - for (Direction direction : Direction.values()) { - IItemHandler handler = this.pipe.getItemHandler(direction); + var filters = this.pipe.getFilters(); + for (var direction : Direction.values()) { + var handler = this.pipe.getItemHandler(direction); if (handler == null) continue; - for (int i = 0; i < handler.getSlots(); i++) { - ItemStack stack = handler.getStackInSlot(i); + for (var i = 0; i < handler.getSlots(); i++) { + var stack = handler.getStackInSlot(i); if (stack.isEmpty() || this.isFiltered(stack)) continue; - ItemStack copy = stack.copy(); + var copy = stack.copy(); copy.setCount(1); // try inserting into ourselves and any filter increase modifiers - for (ItemFilter filter : filters) { + for (var filter : filters) { if (ItemHandlerHelper.insertItem(filter, copy, false).isEmpty()) { filter.save(); break; @@ -103,11 +105,11 @@ public class ItemFilter extends ItemStackHandler { } private boolean isFiltered(ItemStack stack) { - ItemEquality[] types = getEqualityTypes(this.pipe); + var types = getEqualityTypes(this.pipe); // also check if any filter increase modules have the item we need for (ItemStackHandler handler : this.pipe.getFilters()) { - for (int i = 0; i < handler.getSlots(); i++) { - ItemStack filter = handler.getStackInSlot(i); + for (var i = 0; i < handler.getSlots(); i++) { + var filter = handler.getStackInSlot(i); if (filter.isEmpty()) continue; if (ItemEquality.compareItems(stack, filter, types)) @@ -126,7 +128,7 @@ public class ItemFilter extends ItemStackHandler { @Override public CompoundTag serializeNBT() { - CompoundTag nbt = super.serializeNBT(); + var nbt = super.serializeNBT(); if (this.canModifyWhitelist) nbt.putBoolean("whitelist", this.isWhitelist); return nbt; @@ -152,6 +154,7 @@ public class ItemFilter extends ItemStackHandler { } public interface IFilteredContainer { + ItemFilter getFilter(); } } diff --git a/src/main/java/de/ellpeck/prettypipes/packets/PacketCraftingModuleTransfer.java b/src/main/java/de/ellpeck/prettypipes/packets/PacketCraftingModuleTransfer.java index f6458a7..e21c5d7 100644 --- a/src/main/java/de/ellpeck/prettypipes/packets/PacketCraftingModuleTransfer.java +++ b/src/main/java/de/ellpeck/prettypipes/packets/PacketCraftingModuleTransfer.java @@ -1,12 +1,12 @@ package de.ellpeck.prettypipes.packets; import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.network.PacketBuffer; -import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.ItemStackHandler; +import net.minecraftforge.network.NetworkEvent; import java.util.ArrayList; import java.util.List; @@ -26,24 +26,24 @@ public class PacketCraftingModuleTransfer { } - public static PacketCraftingModuleTransfer fromBytes(PacketBuffer buf) { + public static PacketCraftingModuleTransfer fromBytes(FriendlyByteBuf buf) { PacketCraftingModuleTransfer packet = new PacketCraftingModuleTransfer(); packet.inputs = new ArrayList<>(); for (int i = buf.readInt(); i > 0; i--) - packet.inputs.add(buf.readItemStack()); + packet.inputs.add(buf.readItem()); packet.outputs = new ArrayList<>(); for (int i = buf.readInt(); i > 0; i--) - packet.outputs.add(buf.readItemStack()); + packet.outputs.add(buf.readItem()); return packet; } - public static void toBytes(PacketCraftingModuleTransfer packet, PacketBuffer buf) { + public static void toBytes(PacketCraftingModuleTransfer packet, FriendlyByteBuf buf) { buf.writeInt(packet.inputs.size()); for (ItemStack stack : packet.inputs) - buf.writeItemStack(stack); + buf.writeItem(stack); buf.writeInt(packet.outputs.size()); for (ItemStack stack : packet.outputs) - buf.writeItemStack(stack); + buf.writeItem(stack); } @SuppressWarnings("Convert2Lambda") @@ -51,13 +51,12 @@ public class PacketCraftingModuleTransfer { ctx.get().enqueueWork(new Runnable() { @Override public void run() { - PlayerEntity player = ctx.get().getSender(); - if (player.openContainer instanceof CraftingModuleContainer) { - CraftingModuleContainer container = (CraftingModuleContainer) player.openContainer; + Player player = ctx.get().getSender(); + if (player.containerMenu instanceof CraftingModuleContainer container) { copy(container.input, message.inputs); copy(container.output, message.outputs); container.modified = true; - container.detectAndSendChanges(); + container.broadcastChanges(); } } }); diff --git a/src/main/java/de/ellpeck/prettypipes/packets/PacketGhostSlot.java b/src/main/java/de/ellpeck/prettypipes/packets/PacketGhostSlot.java index bd4ea1d..9f900ee 100644 --- a/src/main/java/de/ellpeck/prettypipes/packets/PacketGhostSlot.java +++ b/src/main/java/de/ellpeck/prettypipes/packets/PacketGhostSlot.java @@ -6,11 +6,10 @@ import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; -import net.minecraft.entity.player.PlayerEntity; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.math.BlockPos; -import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraftforge.network.NetworkEvent; import java.util.Map; import java.util.function.Consumer; @@ -30,35 +29,35 @@ public class PacketGhostSlot { } - public static PacketGhostSlot fromBytes(PacketBuffer buf) { + public static PacketGhostSlot fromBytes(FriendlyByteBuf buf) { PacketGhostSlot packet = new PacketGhostSlot(); packet.pos = buf.readBlockPos(); packet.stacks = ArrayListMultimap.create(); for (int i = buf.readInt(); i > 0; i--) - packet.stacks.put(buf.readInt(), buf.readItemStack()); + packet.stacks.put(buf.readInt(), buf.readItem()); return packet; } - public static void toBytes(PacketGhostSlot packet, PacketBuffer buf) { + public static void toBytes(PacketGhostSlot packet, FriendlyByteBuf buf) { buf.writeBlockPos(packet.pos); buf.writeInt(packet.stacks.size()); for (Map.Entry entry : packet.stacks.entries()) { buf.writeInt(entry.getKey()); - buf.writeItemStack(entry.getValue()); + buf.writeItem(entry.getValue()); } } @SuppressWarnings("Convert2Lambda") public static void onMessage(PacketGhostSlot message, Supplier ctx) { - Consumer doIt = p -> { - CraftingTerminalBlockEntity tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, p.world, message.pos); + Consumer doIt = p -> { + CraftingTerminalBlockEntity tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, p.level, message.pos); if (tile != null) tile.setGhostItems(message.stacks); }; // this whole thing is a dirty hack for allowing the same packet to be used // both client -> server and server -> client without any classloading issues - PlayerEntity player = ctx.get().getSender(); + Player player = ctx.get().getSender(); // are we on the client? if (player == null) { ctx.get().enqueueWork(new Runnable() { diff --git a/src/main/java/de/ellpeck/prettypipes/packets/PacketHandler.java b/src/main/java/de/ellpeck/prettypipes/packets/PacketHandler.java index 3f45a18..35d3ed4 100644 --- a/src/main/java/de/ellpeck/prettypipes/packets/PacketHandler.java +++ b/src/main/java/de/ellpeck/prettypipes/packets/PacketHandler.java @@ -2,18 +2,10 @@ package de.ellpeck.prettypipes.packets; import de.ellpeck.prettypipes.PrettyPipes; import net.minecraft.core.BlockPos; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IWorld; -import net.minecraft.world.World; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; -import net.minecraftforge.fml.network.NetworkRegistry; -import net.minecraftforge.fml.network.PacketDistributor; -import net.minecraftforge.fml.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.simple.SimpleChannel; diff --git a/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlock.java b/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlock.java index 2a87f62..9b8925c 100644 --- a/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlock.java +++ b/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlock.java @@ -33,7 +33,6 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.items.CapabilityItemHandler; -import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.network.NetworkHooks; import org.apache.commons.lang3.mutable.MutableObject; @@ -60,31 +59,31 @@ public class PipeBlock extends BaseEntityBlock { .build(); static { - for (Direction dir : Direction.values()) + for (var dir : Direction.values()) DIRECTIONS.put(dir, EnumProperty.create(dir.getName(), ConnectionType.class)); } public PipeBlock() { super(Block.Properties.of(Material.STONE).strength(2).sound(SoundType.STONE).noOcclusion()); - BlockState state = this.defaultBlockState().setValue(BlockStateProperties.WATERLOGGED, false); - for (EnumProperty prop : DIRECTIONS.values()) + var state = this.defaultBlockState().setValue(BlockStateProperties.WATERLOGGED, false); + for (var prop : DIRECTIONS.values()) state = state.setValue(prop, ConnectionType.DISCONNECTED); this.registerDefaultState(state); } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) { - PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); + var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); if (tile == null) return InteractionResult.PASS; if (!tile.canHaveModules()) return InteractionResult.PASS; - ItemStack stack = player.getItemInHand(handIn); + var stack = player.getItemInHand(handIn); if (stack.getItem() instanceof IModule) { - ItemStack copy = stack.copy(); + var copy = stack.copy(); copy.setCount(1); - ItemStack remain = ItemHandlerHelper.insertItem(tile.modules, copy, false); + var remain = ItemHandlerHelper.insertItem(tile.modules, copy, false); if (remain.isEmpty()) { stack.shrink(1); return InteractionResult.SUCCESS; @@ -110,7 +109,7 @@ public class PipeBlock extends BaseEntityBlock { @Override public void neighborChanged(BlockState state, Level worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) { - BlockState newState = this.createState(worldIn, pos, state); + var newState = this.createState(worldIn, pos, state); if (newState != state) { worldIn.setBlockAndUpdate(pos, newState); onStateChanged(worldIn, pos, newState); @@ -144,7 +143,7 @@ public class PipeBlock extends BaseEntityBlock { public VoxelShape getCollisionShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) { return this.cacheAndGetShape(state, worldIn, pos, s -> s.getCollisionShape(worldIn, pos, context), COLL_SHAPE_CACHE, s -> { // make the shape a bit higher so we can jump up onto a higher block - MutableObject newShape = new MutableObject<>(Shapes.empty()); + var newShape = new MutableObject(Shapes.empty()); s.forAllBoxes((x1, y1, z1, x2, y2, z2) -> newShape.setValue(Shapes.join(Shapes.create(x1, y1, z1, x2, y2 + 3 / 16F, z2), newShape.getValue(), BooleanOp.OR))); return newShape.getValue().optimize(); }); @@ -153,7 +152,7 @@ public class PipeBlock extends BaseEntityBlock { private VoxelShape cacheAndGetShape(BlockState state, BlockGetter worldIn, BlockPos pos, Function coverShapeSelector, Map, VoxelShape> cache, Function shapeModifier) { VoxelShape coverShape = null; BlockState cover = null; - PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); + var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); if (tile != null && tile.cover != null) { cover = tile.cover; // try catch since the block might expect to find itself at the position @@ -162,11 +161,11 @@ public class PipeBlock extends BaseEntityBlock { } catch (Exception ignored) { } } - Pair key = Pair.of(state, cover); - VoxelShape shape = cache.get(key); + var key = Pair.of(state, cover); + var shape = cache.get(key); if (shape == null) { shape = CENTER_SHAPE; - for (Map.Entry> entry : DIRECTIONS.entrySet()) { + for (var entry : DIRECTIONS.entrySet()) { if (state.getValue(entry.getValue()).isConnected()) shape = Shapes.or(shape, DIR_SHAPES.get(entry.getKey())); } @@ -180,14 +179,14 @@ public class PipeBlock extends BaseEntityBlock { } private BlockState createState(Level world, BlockPos pos, BlockState curr) { - BlockState state = this.defaultBlockState(); - FluidState fluid = world.getFluidState(pos); + var state = this.defaultBlockState(); + var fluid = world.getFluidState(pos); if (fluid.is(FluidTags.WATER) && fluid.getAmount() == 8) state = state.setValue(BlockStateProperties.WATERLOGGED, true); - for (Direction dir : Direction.values()) { - EnumProperty prop = DIRECTIONS.get(dir); - ConnectionType type = this.getConnectionType(world, pos, dir, state); + for (var dir : Direction.values()) { + var prop = DIRECTIONS.get(dir); + var type = this.getConnectionType(world, pos, dir, state); // don't reconnect on blocked faces if (type.isConnected() && curr.getValue(prop) == ConnectionType.BLOCKED) type = ConnectionType.BLOCKED; @@ -197,23 +196,23 @@ public class PipeBlock extends BaseEntityBlock { } protected ConnectionType getConnectionType(Level world, BlockPos pos, Direction direction, BlockState state) { - BlockPos offset = pos.relative(direction); + var offset = pos.relative(direction); if (!world.isLoaded(offset)) return ConnectionType.DISCONNECTED; - Direction opposite = direction.getOpposite(); - BlockEntity tile = world.getBlockEntity(offset); + var opposite = direction.getOpposite(); + var tile = world.getBlockEntity(offset); if (tile != null) { - IPipeConnectable connectable = tile.getCapability(Registry.pipeConnectableCapability, opposite).orElse(null); + var connectable = tile.getCapability(Registry.pipeConnectableCapability, opposite).orElse(null); if (connectable != null) return connectable.getConnectionType(pos, direction); - IItemHandler handler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, opposite).orElse(null); + var handler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, opposite).orElse(null); if (handler != null) return ConnectionType.CONNECTED; } - IItemHandler blockHandler = Utility.getBlockItemHandler(world, offset, opposite); + var blockHandler = Utility.getBlockItemHandler(world, offset, opposite); if (blockHandler != null) return ConnectionType.CONNECTED; - BlockState offState = world.getBlockState(offset); + var offState = world.getBlockState(offset); if (hasLegsTo(world, offState, offset, direction)) { if (DIRECTIONS.values().stream().noneMatch(d -> state.getValue(d) == ConnectionType.LEGS)) return ConnectionType.LEGS; @@ -231,19 +230,19 @@ public class PipeBlock extends BaseEntityBlock { public static void onStateChanged(Level world, BlockPos pos, BlockState newState) { // wait a few ticks before checking if we have to drop our modules, so that things like iron -> gold chest work - PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, world, pos); + var tile = Utility.getBlockEntity(PipeBlockEntity.class, world, pos); if (tile != null) tile.moduleDropCheck = 5; - PipeNetwork network = PipeNetwork.get(world); - int connections = 0; - boolean force = false; - for (Direction dir : Direction.values()) { - ConnectionType value = newState.getValue(DIRECTIONS.get(dir)); + var network = PipeNetwork.get(world); + var connections = 0; + var force = false; + for (var dir : Direction.values()) { + var value = newState.getValue(DIRECTIONS.get(dir)); if (!value.isConnected()) continue; connections++; - BlockState otherState = world.getBlockState(pos.relative(dir)); + var otherState = world.getBlockState(pos.relative(dir)); // force a node if we're connecting to a different block (inventory etc.) if (otherState.getBlock() != newState.getBlock()) { force = true; @@ -261,7 +260,7 @@ public class PipeBlock extends BaseEntityBlock { @Override public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) { if (state.getBlock() != newState.getBlock()) { - PipeNetwork network = PipeNetwork.get(worldIn); + var network = PipeNetwork.get(worldIn); network.removeNode(pos); network.onPipeChanged(pos, state); super.onRemove(state, worldIn, pos, newState, isMoving); @@ -281,7 +280,7 @@ public class PipeBlock extends BaseEntityBlock { @Override public int getAnalogOutputSignal(BlockState state, Level world, BlockPos pos) { - PipeBlockEntity pipe = Utility.getBlockEntity(PipeBlockEntity.class, world, pos); + var pipe = Utility.getBlockEntity(PipeBlockEntity.class, world, pos); if (pipe == null) return 0; return Math.min(15, pipe.getItems().size()); @@ -290,7 +289,7 @@ public class PipeBlock extends BaseEntityBlock { @org.jetbrains.annotations.Nullable @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { - return new PipeBlockEntity(); + return new PipeBlockEntity(Registry.pipeTileEntity, pos, state); } @Override @@ -299,10 +298,10 @@ public class PipeBlock extends BaseEntityBlock { } public static void dropItems(Level worldIn, BlockPos pos, Player player) { - PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); + var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); if (tile != null) { Utility.dropInventory(tile, tile.modules); - for (IPipeItem item : tile.getItems()) + for (var item : tile.getItems()) item.drop(worldIn, item.getContent()); if (tile.cover != null) tile.removeCover(player, InteractionHand.MAIN_HAND); diff --git a/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlockEntity.java b/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlockEntity.java index c043fa8..c863192 100644 --- a/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlockEntity.java +++ b/src/main/java/de/ellpeck/prettypipes/pipe/PipeBlockEntity.java @@ -10,45 +10,32 @@ import de.ellpeck.prettypipes.network.NetworkLock; import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.pipe.containers.MainPipeContainer; import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.container.Container; -import net.minecraft.inventory.container.INamedContainerProvider; -import net.minecraft.item.Item; import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; import net.minecraft.nbt.NbtUtils; +import net.minecraft.nbt.Tag; +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.Containers; import net.minecraft.world.InteractionHand; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NBTUtil; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.play.server.SUpdateTileEntityPacket; -import net.minecraft.profiler.IProfiler; -import net.minecraft.tileentity.ITickableTileEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.tileentity.TileEntityType; -import net.minecraft.util.Direction; -import net.minecraft.util.Hand; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BaseContainerBlockEntity; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.server.ServerWorld; +import net.minecraft.world.phys.AABB; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.common.util.Lazy; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.CapabilityItemHandler; @@ -64,7 +51,7 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; -public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeConnectable { +public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeConnectable { public final ItemStackHandler modules = new ItemStackHandler(3) { @Override @@ -91,6 +78,10 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo private final LazyOptional lazyThis = LazyOptional.of(() -> this); private final Lazy workRandomizer = Lazy.of(() -> this.level.random.nextInt(200)); + public PipeBlockEntity(BlockEntityType type, BlockPos p_155229_, BlockState p_155230_) { + super(type, p_155229_, p_155230_); + } + @Override public void onChunkUnloaded() { PipeNetwork.get(this.level).uncachePipe(this.worldPosition); @@ -103,9 +94,9 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo compound.put("requests", Utility.serializeAll(this.craftIngredientRequests)); if (this.cover != null) compound.put("cover", NbtUtils.writeBlockState(this.cover)); - ListTag results = new ListTag(); - for (Pair triple : this.craftResultRequests) { - CompoundTag nbt = new CompoundTag(); + var results = new ListTag(); + for (var triple : this.craftResultRequests) { + var nbt = new CompoundTag(); nbt.putLong("dest_pipe", triple.getLeft().asLong()); nbt.put("item", triple.getRight().serializeNBT()); results.add(nbt); @@ -120,11 +111,11 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo this.moduleDropCheck = compound.getInt("module_drop_check"); this.cover = compound.contains("cover") ? NbtUtils.readBlockState(compound.getCompound("cover")) : null; this.craftIngredientRequests.clear(); - this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", NBT.TAG_COMPOUND), NetworkLock::new)); + this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), NetworkLock::new)); this.craftResultRequests.clear(); - ListTag results = compound.getList("craft_results", NBT.TAG_COMPOUND); - for (int i = 0; i < results.size(); i++) { - CompoundTag nbt = results.getCompound(i); + var results = compound.getList("craft_results", Tag.TAG_COMPOUND); + for (var i = 0; i < results.size(); i++) { + var nbt = results.getCompound(i); this.craftResultRequests.add(Pair.of( BlockPos.of(nbt.getLong("dest_pipe")), ItemStack.of(nbt.getCompound("item")))); @@ -135,25 +126,26 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo @Override public CompoundTag getUpdateTag() { // sync pipe items on load - CompoundTag nbt = this.write(new CompoundTag()); + CompoundTag nbt = this.save(new CompoundTag()); nbt.put("items", Utility.serializeAll(this.getItems())); return nbt; } @Override - public void handleUpdateTag(BlockState state, CompoundTag nbt) { - this.read(state, nbt); - List items = this.getItems(); + public void handleUpdateTag(CompoundTag nbt) { + this.load(nbt); + var items = this.getItems(); items.clear(); - items.addAll(Utility.deserializeAll(nbt.getList("items", NBT.TAG_COMPOUND), IPipeItem::load)); + items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load)); } @Override - public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) { - this.read(this.getBlockState(), pkt.getNbtCompound()); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { + this.load(pkt.getTag()); } - @Override + // TODO tick + /* @Override public void tick() { // invalidate our pressurizer reference if it was removed if (this.pressurizer != null && this.pressurizer.isRemoved()) @@ -172,10 +164,10 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } profiler.startSection("ticking_modules"); - int prio = 0; - Iterator> modules = this.streamModules().iterator(); + var prio = 0; + var modules = this.streamModules().iterator(); while (modules.hasNext()) { - Pair module = modules.next(); + var module = modules.next(); module.getRight().tick(module.getLeft(), this); prio += module.getRight().getPriority(module.getLeft(), this); } @@ -188,19 +180,19 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } profiler.startSection("ticking_items"); - List items = this.getItems(); - for (int i = items.size() - 1; i >= 0; i--) + var items = this.getItems(); + for (var i = items.size() - 1; i >= 0; i--) items.get(i).updateInPipe(this); if (items.size() != this.lastItemAmount) { this.lastItemAmount = items.size(); this.world.updateComparatorOutputLevel(this.pos, this.getBlockState().getBlock()); } profiler.endSection(); - } + }*/ public List getItems() { if (this.items == null) - this.items = PipeNetwork.get(this.world).getItemsInPipe(this.pos); + this.items = PipeNetwork.get(this.level).getItemsInPipe(this.worldPosition); return this.items; } @@ -213,23 +205,23 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public boolean isConnected(Direction dir) { - return this.getBlockState().get(PipeBlock.DIRECTIONS.get(dir)).isConnected(); + return this.getBlockState().getValue(PipeBlock.DIRECTIONS.get(dir)).isConnected(); } public Pair getAvailableDestinationOrConnectable(ItemStack stack, boolean force, boolean preventOversending) { - Pair dest = this.getAvailableDestination(stack, force, preventOversending); + var dest = this.getAvailableDestination(stack, force, preventOversending); if (dest != null) return dest; // if there's no available destination, try inserting into terminals etc. - for (Direction dir : Direction.values()) { - IPipeConnectable connectable = this.getPipeConnectable(dir); + for (var dir : Direction.values()) { + var connectable = this.getPipeConnectable(dir); if (connectable == null) continue; - ItemStack connectableRemain = connectable.insertItem(this.getPos(), dir, stack, true); + var connectableRemain = connectable.insertItem(this.worldPosition, dir, stack, true); if (connectableRemain.getCount() != stack.getCount()) { - ItemStack inserted = stack.copy(); + var inserted = stack.copy(); inserted.shrink(connectableRemain.getCount()); - return Pair.of(this.getPos().offset(dir), inserted); + return Pair.of(this.worldPosition.relative(dir), inserted); } } return null; @@ -240,47 +232,47 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo return null; if (!force && this.streamModules().anyMatch(m -> !m.getRight().canAcceptItem(m.getLeft(), this, stack))) return null; - for (Direction dir : Direction.values()) { - IItemHandler handler = this.getItemHandler(dir); + for (var dir : Direction.values()) { + var handler = this.getItemHandler(dir); if (handler == null) continue; - ItemStack remain = ItemHandlerHelper.insertItem(handler, stack, true); + var remain = ItemHandlerHelper.insertItem(handler, stack, true); // did we insert anything? if (remain.getCount() == stack.getCount()) continue; - ItemStack toInsert = stack.copy(); + var toInsert = stack.copy(); toInsert.shrink(remain.getCount()); // limit to the max amount that modules allow us to insert - int maxAmount = this.streamModules().mapToInt(m -> m.getRight().getMaxInsertionAmount(m.getLeft(), this, stack, handler)).min().orElse(Integer.MAX_VALUE); + var maxAmount = this.streamModules().mapToInt(m -> m.getRight().getMaxInsertionAmount(m.getLeft(), this, stack, handler)).min().orElse(Integer.MAX_VALUE); if (maxAmount < toInsert.getCount()) toInsert.setCount(maxAmount); - BlockPos offset = this.pos.offset(dir); + BlockPos offset = this.worldPosition.relative(dir); if (preventOversending || maxAmount < Integer.MAX_VALUE) { - PipeNetwork network = PipeNetwork.get(this.world); + var network = PipeNetwork.get(this.level); // these are the items that are currently in the pipes, going to this inventory - int onTheWay = network.getItemsOnTheWay(offset, null); + var onTheWay = network.getItemsOnTheWay(offset, null); if (onTheWay > 0) { if (maxAmount < Integer.MAX_VALUE) { // these are the items on the way, limited to items of the same type as stack - int onTheWaySame = network.getItemsOnTheWay(offset, stack); + var onTheWaySame = network.getItemsOnTheWay(offset, stack); // check if any modules are limiting us if (toInsert.getCount() + onTheWaySame > maxAmount) toInsert.setCount(maxAmount - onTheWaySame); } // totalSpace will be the amount of items that fit into the attached container - int totalSpace = 0; - for (int i = 0; i < handler.getSlots(); i++) { - ItemStack copy = stack.copy(); - int maxStackSize = copy.getMaxStackSize(); + var totalSpace = 0; + for (var i = 0; i < handler.getSlots(); i++) { + var copy = stack.copy(); + var maxStackSize = copy.getMaxStackSize(); // if the container can store more than 64 items in this slot, then it's likely // a barrel or similar, meaning that the slot limit matters more than the max stack size - int limit = handler.getSlotLimit(i); + var limit = handler.getSlotLimit(i); if (limit > 64) maxStackSize = limit; copy.setCount(maxStackSize); // this is an inaccurate check since it ignores the fact that some slots might // have space for items of other types, but it'll be good enough for us - ItemStack left = handler.insertItem(i, copy, true); + var left = handler.insertItem(i, copy, true); totalSpace += maxStackSize - left.getCount(); } // if the items on the way plus the items we're trying to move are too much, reduce @@ -300,8 +292,8 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public float getItemSpeed(ItemStack stack) { - float moduleSpeed = (float) this.streamModules().mapToDouble(m -> m.getRight().getItemSpeedIncrease(m.getLeft(), this)).sum(); - float pressureSpeed = this.pressurizer != null && this.pressurizer.pressurizeItem(stack, true) ? 0.45F : 0; + var moduleSpeed = (float) this.streamModules().mapToDouble(m -> m.getRight().getItemSpeedIncrease(m.getLeft(), this)).sum(); + var pressureSpeed = this.pressurizer != null && this.pressurizer.pressurizeItem(stack, true) ? 0.45F : 0; return 0.05F + moduleSpeed + pressureSpeed; } @@ -316,13 +308,13 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public int getCraftableAmount(Consumer unavailableConsumer, ItemStack stack, Stack dependencyChain) { - int total = 0; - Iterator> modules = this.streamModules().iterator(); + var total = 0; + var modules = this.streamModules().iterator(); while (modules.hasNext()) { - Pair module = modules.next(); + var module = modules.next(); // make sure we don't factor in recursive dependencies like ingot -> block -> ingot etc. if (dependencyChain.stream().noneMatch(d -> ItemEquality.compareItems(module.getLeft(), d, ItemEquality.NBT))) { - int amount = module.getRight().getCraftableAmount(module.getLeft(), this, unavailableConsumer, stack, dependencyChain); + var amount = module.getRight().getCraftableAmount(module.getLeft(), this, unavailableConsumer, stack, dependencyChain); if (amount > 0) total += amount; } @@ -331,9 +323,9 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public ItemStack craft(BlockPos destPipe, Consumer unavailableConsumer, ItemStack stack, Stack dependencyChain) { - Iterator> modules = this.streamModules().iterator(); + var modules = this.streamModules().iterator(); while (modules.hasNext()) { - Pair module = modules.next(); + var module = modules.next(); stack = module.getRight().craft(module.getLeft(), this, destPipe, unavailableConsumer, stack, dependencyChain); if (stack.isEmpty()) break; @@ -342,7 +334,7 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public IItemHandler getItemHandler(Direction dir) { - IItemHandler handler = this.getNeighborCap(dir, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY); + var handler = this.getNeighborCap(dir, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY); if (handler != null) return handler; return Utility.getBlockItemHandler(this.level, this.worldPosition.relative(dir), dir.getOpposite()); @@ -351,15 +343,15 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo public T getNeighborCap(Direction dir, Capability cap) { if (!this.isConnected(dir)) return null; - BlockPos pos = this.worldPosition.relative(dir); - BlockEntity tile = this.level.getBlockEntity(pos); + var pos = this.worldPosition.relative(dir); + var tile = this.level.getBlockEntity(pos); if (tile != null) return tile.getCapability(cap, dir.getOpposite()).orElse(null); return null; } public IPipeConnectable getPipeConnectable(Direction dir) { - BlockEntity tile = this.level.getBlockEntity(this.worldPosition.relative(dir)); + var tile = this.level.getBlockEntity(this.worldPosition.relative(dir)); if (tile != null) return tile.getCapability(Registry.pipeConnectableCapability, dir.getOpposite()).orElse(null); return null; @@ -370,10 +362,10 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public boolean canHaveModules() { - for (Direction dir : Direction.values()) { + for (var dir : Direction.values()) { if (this.isConnectedInventory(dir)) return true; - IPipeConnectable connectable = this.getPipeConnectable(dir); + var connectable = this.getPipeConnectable(dir); if (connectable != null && connectable.allowsModules(this.worldPosition, dir)) return true; } @@ -386,8 +378,8 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo public Stream> streamModules() { Stream.Builder> builder = Stream.builder(); - for (int i = 0; i < this.modules.getSlots(); i++) { - ItemStack stack = this.modules.getStackInSlot(i); + for (var i = 0; i < this.modules.getSlots(); i++) { + var stack = this.modules.getStackInSlot(i); if (stack.isEmpty()) continue; builder.accept(Pair.of(stack, (IModule) stack.getItem())); @@ -396,10 +388,10 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo } public void removeCover(Player player, InteractionHand hand) { - if (this.level.isRemote) + if (this.level.isClientSide) return; - List drops = Block.getDrops(this.cover, (ServerLevel) this.level, this.worldPosition, null, player, player.getItemInHand(hand)); - for (ItemStack drop : drops) + var drops = Block.getDrops(this.cover, (ServerLevel) this.level, this.worldPosition, null, player, player.getItemInHand(hand)); + for (var drop : drops) Containers.dropItemStack(this.level, this.worldPosition.getX(), this.worldPosition.getY(), this.worldPosition.getZ(), drop); this.cover = null; } @@ -424,28 +416,28 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo public void setRemoved() { super.setRemoved(); this.getItems().clear(); - PipeNetwork network = PipeNetwork.get(this.level); - for (NetworkLock lock : this.craftIngredientRequests) + var network = PipeNetwork.get(this.level); + for (var lock : this.craftIngredientRequests) network.resolveNetworkLock(lock); this.lazyThis.invalidate(); } @Override - public ITextComponent getDisplayName() { - return new TranslationTextComponent("container." + PrettyPipes.ID + ".pipe"); + public Component getDisplayName() { + return new TranslatableComponent("container." + PrettyPipes.ID + ".pipe"); } @Nullable @Override - public Container createMenu(int window, PlayerInventory inv, PlayerEntity player) { - return new MainPipeContainer(Registry.pipeContainer, window, player, PipeBlockEntity.this.pos); + public AbstractContainerMenu createMenu(int window, Inventory inv, Player player) { + return new MainPipeContainer(Registry.pipeContainer, window, player, PipeBlockEntity.this.worldPosition); } @Override @OnlyIn(Dist.CLIENT) - public AxisAlignedBB getRenderBoundingBox() { + public AABB getRenderBoundingBox() { // our render bounding box should always be the full block in case we're covered - return new AxisAlignedBB(this.pos); + return new AABB(this.worldPosition); } @Override @@ -457,8 +449,8 @@ public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeCo @Override public ConnectionType getConnectionType(BlockPos pipePos, Direction direction) { - BlockState state = this.world.getBlockState(pipePos.offset(direction)); - if (state.get(PipeBlock.DIRECTIONS.get(direction.getOpposite())) == ConnectionType.BLOCKED) + BlockState state = this.level.getBlockState(pipePos.relative(direction)); + if (state.getValue(PipeBlock.DIRECTIONS.get(direction.getOpposite())) == ConnectionType.BLOCKED) return ConnectionType.BLOCKED; return ConnectionType.CONNECTED; } diff --git a/src/main/java/de/ellpeck/prettypipes/pipe/containers/AbstractPipeGui.java b/src/main/java/de/ellpeck/prettypipes/pipe/containers/AbstractPipeGui.java index adccff6..a5d2100 100644 --- a/src/main/java/de/ellpeck/prettypipes/pipe/containers/AbstractPipeGui.java +++ b/src/main/java/de/ellpeck/prettypipes/pipe/containers/AbstractPipeGui.java @@ -1,30 +1,22 @@ package de.ellpeck.prettypipes.pipe.containers; -import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.PoseStack; import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.packets.PacketButton; import de.ellpeck.prettypipes.packets.PacketHandler; -import net.minecraft.client.audio.SimpleSound; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.Widget; -import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; -import net.minecraft.client.gui.screens.inventory.ContainerScreen; -import net.minecraft.client.gui.widget.Widget; import net.minecraft.client.resources.sounds.SimpleSoundInstance; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.container.Slot; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.Style; +import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.SoundEvents; -import net.minecraft.util.text.ITextComponent; +import net.minecraftforge.items.SlotItemHandler; import java.util.ArrayList; import java.util.List; @@ -93,10 +85,9 @@ public abstract class AbstractPipeGui> extend tab.draw(matrix); // draw the slots since we're using a blank ui - for (Slot slot : this.container.inventorySlots) { - if (slot.inventory == this.playerInventory) - continue; - this.blit(matrix, this.guiLeft + slot.xPos - 1, this.guiTop + slot.yPos - 1, 176, 62, 18, 18); + for (Slot slot : this.menu.slots) { + if (slot instanceof SlotItemHandler) + this.blit(matrix, this.leftPos + slot.x - 1, this.topPos + slot.y - 1, 176, 62, 18, 18); } } @@ -112,12 +103,12 @@ public abstract class AbstractPipeGui> extend private void initTabs() { this.tabs.clear(); this.tabs.add(new Tab(new ItemStack(Registry.pipeBlock), 0, -1)); - for (int i = 0; i < this.container.tile.modules.getSlots(); i++) { - ItemStack stack = this.container.tile.modules.getStackInSlot(i); + for (int i = 0; i < this.menu.tile.modules.getSlots(); i++) { + ItemStack stack = this.menu.tile.modules.getStackInSlot(i); if (stack.isEmpty()) continue; IModule module = (IModule) stack.getItem(); - if (module.hasContainer(stack, this.container.tile)) + if (module.hasContainer(stack, this.menu.tile)) this.tabs.add(new Tab(stack, this.tabs.size(), i)); } } @@ -156,7 +147,7 @@ public abstract class AbstractPipeGui> extend private void drawForeground(PoseStack matrix, int mouseX, int mouseY) { if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32) return; - AbstractPipeGui.this.renderTooltip(matrix, this.moduleStack.getDisplayName(), mouseX - AbstractPipeGui.this.guiLeft, mouseY - AbstractPipeGui.this.guiTop); + AbstractPipeGui.this.renderTooltip(matrix, this.moduleStack.getDisplayName(), mouseX - AbstractPipeGui.this.leftPos, mouseY - AbstractPipeGui.this.topPos); } private boolean onClicked(double mouseX, double mouseY, int button) { diff --git a/src/main/java/de/ellpeck/prettypipes/pipe/containers/MainPipeGui.java b/src/main/java/de/ellpeck/prettypipes/pipe/containers/MainPipeGui.java index 9400c48..87d9ce2 100644 --- a/src/main/java/de/ellpeck/prettypipes/pipe/containers/MainPipeGui.java +++ b/src/main/java/de/ellpeck/prettypipes/pipe/containers/MainPipeGui.java @@ -1,8 +1,6 @@ package de.ellpeck.prettypipes.pipe.containers; -import net.minecraft.entity.player.PlayerInventory; import net.minecraft.network.chat.Component; -import net.minecraft.util.text.ITextComponent; import net.minecraft.world.entity.player.Inventory; public class MainPipeGui extends AbstractPipeGui { diff --git a/src/main/java/de/ellpeck/prettypipes/pipe/modules/extraction/ExtractionModuleContainer.java b/src/main/java/de/ellpeck/prettypipes/pipe/modules/extraction/ExtractionModuleContainer.java index fe5a10d..66969c3 100644 --- a/src/main/java/de/ellpeck/prettypipes/pipe/modules/extraction/ExtractionModuleContainer.java +++ b/src/main/java/de/ellpeck/prettypipes/pipe/modules/extraction/ExtractionModuleContainer.java @@ -3,10 +3,10 @@ package de.ellpeck.prettypipes.pipe.modules.extraction; import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter.IFilteredContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.container.ContainerType; -import net.minecraft.inventory.container.Slot; -import net.minecraft.util.math.BlockPos; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.inventory.Slot; import javax.annotation.Nullable; @@ -14,7 +14,7 @@ public class ExtractionModuleContainer extends AbstractPipeContainer type, int id, PlayerEntity player, BlockPos pos, int moduleIndex) { + public ExtractionModuleContainer(@Nullable MenuType type, int id, Player player, BlockPos pos, int moduleIndex) { super(type, id, player, pos, moduleIndex); } @@ -26,8 +26,8 @@ public class ExtractionModuleContainer extends AbstractPipeContainer getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { - return new ExtractionModuleContainer(Registry.extractionModuleContainer, windowId, player, tile.getPos(), moduleIndex); + public AbstractPipeContainer getContainer(ItemStack module, PipeBlockEntity tile, int windowId, Inventory inv, Player player, int moduleIndex) { + return new ExtractionModuleContainer(Registry.extractionModuleContainer, windowId, player, tile.getBlockPos(), moduleIndex); } @Override diff --git a/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerBlockEntity.java b/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerBlockEntity.java index 803cb9d..a7c3713 100644 --- a/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerBlockEntity.java +++ b/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerBlockEntity.java @@ -2,29 +2,23 @@ package de.ellpeck.prettypipes.pressurizer; import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.Registry; -import de.ellpeck.prettypipes.Utility; -import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.pipe.ConnectionType; import de.ellpeck.prettypipes.pipe.IPipeConnectable; -import de.ellpeck.prettypipes.pipe.PipeBlockEntity; -import net.minecraft.block.BlockState; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.entity.player.PlayerInventory; -import net.minecraft.inventory.container.Container; -import net.minecraft.inventory.container.INamedContainerProvider; -import net.minecraft.world.item.ItemStack; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.play.server.SUpdateTileEntityPacket; -import net.minecraft.tileentity.ITickableTileEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.tileentity.TileEntityType; -import net.minecraft.util.Direction; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TranslationTextComponent; -import net.minecraft.world.World; +import net.minecraft.network.Connection; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.world.MenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.energy.CapabilityEnergy; @@ -33,15 +27,15 @@ import net.minecraftforge.energy.IEnergyStorage; import javax.annotation.Nullable; -public class PressurizerBlockEntity extends BlockEntity implements INamedContainerProvider, ITickableTileEntity, IPipeConnectable { +public class PressurizerBlockEntity extends BlockEntity implements MenuProvider, IPipeConnectable { private final ModifiableEnergyStorage storage = new ModifiableEnergyStorage(64000, 512, 0); private final LazyOptional lazyStorage = LazyOptional.of(() -> this.storage); private final LazyOptional lazyThis = LazyOptional.of(() -> this); private int lastEnergy; - public PressurizerBlockEntity() { - super(Registry.pressurizerTileEntity); + public PressurizerBlockEntity(BlockEntityType type, BlockPos pos, BlockState state) { + super(type, pos, state); } public boolean pressurizeItem(ItemStack stack, boolean simulate) { @@ -62,41 +56,41 @@ public class PressurizerBlockEntity extends BlockEntity implements INamedContain } @Override - public CompoundTag write(CompoundTag compound) { + public CompoundTag save(CompoundTag compound) { compound.putInt("energy", this.getEnergy()); - return super.write(compound); + return super.save(compound); } @Override - public void read(BlockState state, CompoundTag nbt) { + public void load(CompoundTag nbt) { this.storage.setEnergyStored(nbt.getInt("energy")); - super.read(state, nbt); + super.load(nbt); } @Override public CompoundTag getUpdateTag() { - return this.write(new CompoundTag()); + return this.save(new CompoundTag()); } @Override - public void handleUpdateTag(BlockState state, CompoundTag tag) { - this.read(state, tag); + public void handleUpdateTag(CompoundTag tag) { + this.load(tag); } @Override - public void onDataPacket(NetworkManager net, SUpdateTileEntityPacket pkt) { - this.read(this.getBlockState(), pkt.getNbtCompound()); + public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) { + this.load(pkt.getTag()); } @Override - public ITextComponent getDisplayName() { - return new TranslationTextComponent("container." + PrettyPipes.ID + ".pressurizer"); + public Component getDisplayName() { + return new TranslatableComponent("container." + PrettyPipes.ID + ".pressurizer"); } @Nullable @Override - public Container createMenu(int window, PlayerInventory inv, PlayerEntity player) { - return new PressurizerContainer(Registry.pressurizerContainer, window, player, this.pos); + public AbstractContainerMenu createMenu(int window, Inventory inv, Player player) { + return new PressurizerContainer(Registry.pressurizerContainer, window, player, this.worldPosition); } @Override @@ -111,13 +105,14 @@ public class PressurizerBlockEntity extends BlockEntity implements INamedContain } @Override - public void remove() { - super.remove(); + public void setRemoved() { + super.setRemoved(); this.lazyStorage.invalidate(); this.lazyThis.invalidate(); } - @Override + // TODO tick + /*@Override public void tick() { if (this.world.isRemote) return; @@ -141,7 +136,7 @@ public class PressurizerBlockEntity extends BlockEntity implements INamedContain this.lastEnergy = this.storage.getEnergyStored(); Utility.sendBlockEntityToClients(this); } - } + }*/ @Override public ConnectionType getConnectionType(BlockPos pipePos, Direction direction) { diff --git a/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerContainer.java b/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerContainer.java index a11a6d2..5bcedbb 100644 --- a/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerContainer.java +++ b/src/main/java/de/ellpeck/prettypipes/pressurizer/PressurizerContainer.java @@ -2,40 +2,36 @@ package de.ellpeck.prettypipes.pressurizer; import de.ellpeck.prettypipes.Utility; import net.minecraft.core.BlockPos; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.inventory.container.Container; -import net.minecraft.inventory.container.ContainerType; -import net.minecraft.inventory.container.Slot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; -import net.minecraft.util.math.BlockPos; import javax.annotation.Nullable; public class PressurizerContainer extends AbstractContainerMenu { + public final PressurizerBlockEntity tile; public PressurizerContainer(@Nullable MenuType type, int id, Player player, BlockPos pos) { super(type, id); this.tile = Utility.getBlockEntity(PressurizerBlockEntity.class, player.level, pos); - for (int l = 0; l < 3; ++l) - for (int j1 = 0; j1 < 9; ++j1) + for (var l = 0; l < 3; ++l) + for (var j1 = 0; j1 < 9; ++j1) this.addSlot(new Slot(player.getInventory(), j1 + l * 9 + 9, 8 + j1 * 18, 55 + l * 18)); - for (int i1 = 0; i1 < 9; ++i1) + for (var i1 = 0; i1 < 9; ++i1) this.addSlot(new Slot(player.getInventory(), i1, 8 + i1 * 18, 113)); } @Override - public ItemStack transferStackInSlot(PlayerEntity player, int slotIndex) { - return Utility.transferStackInSlot(this, this::mergeItemStack, player, slotIndex, stack -> null); + public ItemStack quickMoveStack(Player player, int slotIndex) { + return Utility.transferStackInSlot(this, this::moveItemStackTo, player, slotIndex, stack -> null); } @Override - public boolean canInteractWith(PlayerEntity playerIn) { + public boolean stillValid(Player player) { return true; } }