PipeNetwork is error-free!

This commit is contained in:
Ell 2021-12-02 14:44:26 +01:00
parent b991f8575f
commit 077b09c37d
48 changed files with 738 additions and 727 deletions

View file

@ -95,7 +95,7 @@ repositories {
configurations { configurations {
embed embed
compile.extendsFrom(embed) implementation.extendsFrom(embed)
} }
dependencies { dependencies {

View file

@ -9,7 +9,7 @@ import de.ellpeck.prettypipes.packets.PacketHandler;
import de.ellpeck.prettypipes.pipe.IPipeConnectable; import de.ellpeck.prettypipes.pipe.IPipeConnectable;
import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeRenderer; import de.ellpeck.prettypipes.pipe.PipeRenderer;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import de.ellpeck.prettypipes.pipe.containers.MainPipeContainer; import de.ellpeck.prettypipes.pipe.containers.MainPipeContainer;
import de.ellpeck.prettypipes.pipe.containers.MainPipeGui; import de.ellpeck.prettypipes.pipe.containers.MainPipeGui;
@ -40,31 +40,39 @@ import de.ellpeck.prettypipes.pressurizer.PressurizerContainer;
import de.ellpeck.prettypipes.pressurizer.PressurizerGui; import de.ellpeck.prettypipes.pressurizer.PressurizerGui;
import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity; import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity;
import de.ellpeck.prettypipes.terminal.CraftingTerminalBlock; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlock;
import de.ellpeck.prettypipes.terminal.CraftingTerminalTileEntity; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlock; import de.ellpeck.prettypipes.terminal.ItemTerminalBlock;
import de.ellpeck.prettypipes.terminal.ItemTerminalTileEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer; import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalGui; import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalGui;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.client.gui.ScreenManager; import net.minecraft.client.gui.ScreenManager;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.entity.EntityClassification; import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntityType; import net.minecraft.entity.EntityType;
import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.MenuType;
import net.minecraft.item.BlockItem; import net.minecraft.item.BlockItem;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemGroup;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.INBT; import net.minecraft.nbt.INBT;
import net.minecraft.tileentity.TileEntityType; import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.Direction; import net.minecraft.util.Direction;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityInject;
import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.extensions.IForgeContainerType; import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.extensions.IForgeMenuType;
import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.client.registry.ClientRegistry;
@ -86,46 +94,46 @@ import java.util.function.BiFunction;
@Mod.EventBusSubscriber(bus = Bus.MOD) @Mod.EventBusSubscriber(bus = Bus.MOD)
public final class Registry { public final class Registry {
public static final ItemGroup GROUP = new ItemGroup(PrettyPipes.ID) { public static final CreativeModeTab GROUP = new CreativeModeTab(PrettyPipes.ID) {
@Override @Override
public ItemStack createIcon() { public ItemStack makeIcon() {
return new ItemStack(wrenchItem); return new ItemStack(wrenchItem);
} }
}; };
@CapabilityInject(PipeNetwork.class) public static Capability<PipeNetwork> pipeNetworkCapability = CapabilityManager.get(new CapabilityToken<>() {
public static Capability<PipeNetwork> pipeNetworkCapability; });
@CapabilityInject(IPipeConnectable.class) public static Capability<IPipeConnectable> pipeConnectableCapability = CapabilityManager.get(new CapabilityToken<>() {
public static Capability<IPipeConnectable> pipeConnectableCapability; });
public static Item wrenchItem; public static Item wrenchItem;
public static Item pipeFrameItem; public static Item pipeFrameItem;
public static Block pipeBlock; public static Block pipeBlock;
public static TileEntityType<PipeTileEntity> pipeTileEntity; public static BlockEntityType<PipeBlockEntity> pipeTileEntity;
public static ContainerType<MainPipeContainer> pipeContainer; public static MenuType<MainPipeContainer> pipeContainer;
public static Block itemTerminalBlock; public static Block itemTerminalBlock;
public static TileEntityType<ItemTerminalTileEntity> itemTerminalTileEntity; public static BlockEntityType<ItemTerminalBlockEntity> itemTerminalTileEntity;
public static ContainerType<ItemTerminalContainer> itemTerminalContainer; public static MenuType<ItemTerminalContainer> itemTerminalContainer;
public static Block craftingTerminalBlock; public static Block craftingTerminalBlock;
public static TileEntityType<CraftingTerminalTileEntity> craftingTerminalTileEntity; public static BlockEntityType<CraftingTerminalBlockEntity> craftingTerminalTileEntity;
public static ContainerType<CraftingTerminalContainer> craftingTerminalContainer; public static MenuType<CraftingTerminalContainer> craftingTerminalContainer;
public static EntityType<PipeFrameEntity> pipeFrameEntity; public static EntityType<PipeFrameEntity> pipeFrameEntity;
public static Block pressurizerBlock; public static Block pressurizerBlock;
public static TileEntityType<PressurizerBlockEntity> pressurizerTileEntity; public static BlockEntityType<PressurizerBlockEntity> pressurizerTileEntity;
public static ContainerType<PressurizerContainer> pressurizerContainer; public static MenuType<PressurizerContainer> pressurizerContainer;
public static ContainerType<ExtractionModuleContainer> extractionModuleContainer; public static MenuType<ExtractionModuleContainer> extractionModuleContainer;
public static ContainerType<FilterModuleContainer> filterModuleContainer; public static MenuType<FilterModuleContainer> filterModuleContainer;
public static ContainerType<RetrievalModuleContainer> retrievalModuleContainer; public static MenuType<RetrievalModuleContainer> retrievalModuleContainer;
public static ContainerType<StackSizeModuleContainer> stackSizeModuleContainer; public static MenuType<StackSizeModuleContainer> stackSizeModuleContainer;
public static ContainerType<FilterIncreaseModuleContainer> filterIncreaseModuleContainer; public static MenuType<FilterIncreaseModuleContainer> filterIncreaseModuleContainer;
public static ContainerType<CraftingModuleContainer> craftingModuleContainer; public static MenuType<CraftingModuleContainer> craftingModuleContainer;
public static ContainerType<FilterModifierModuleContainer> filterModifierModuleContainer; public static MenuType<FilterModifierModuleContainer> filterModifierModuleContainer;
@SubscribeEvent @SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event) { public static void registerBlocks(RegistryEvent.Register<Block> event) {
@ -166,9 +174,9 @@ public final class Registry {
@SubscribeEvent @SubscribeEvent
public static void registerTiles(RegistryEvent.Register<TileEntityType<?>> event) { public static void registerTiles(RegistryEvent.Register<TileEntityType<?>> event) {
event.getRegistry().registerAll( event.getRegistry().registerAll(
pipeTileEntity = (TileEntityType<PipeTileEntity>) TileEntityType.Builder.create(PipeTileEntity::new, pipeBlock).build(null).setRegistryName("pipe"), pipeTileEntity = (TileEntityType<PipeBlockEntity>) TileEntityType.Builder.create(PipeBlockEntity::new, pipeBlock).build(null).setRegistryName("pipe"),
itemTerminalTileEntity = (TileEntityType<ItemTerminalTileEntity>) TileEntityType.Builder.create(ItemTerminalTileEntity::new, itemTerminalBlock).build(null).setRegistryName("item_terminal"), itemTerminalTileEntity = (TileEntityType<ItemTerminalBlockEntity>) TileEntityType.Builder.create(ItemTerminalBlockEntity::new, itemTerminalBlock).build(null).setRegistryName("item_terminal"),
craftingTerminalTileEntity = (TileEntityType<CraftingTerminalTileEntity>) TileEntityType.Builder.create(CraftingTerminalTileEntity::new, craftingTerminalBlock).build(null).setRegistryName("crafting_terminal"), craftingTerminalTileEntity = (TileEntityType<CraftingTerminalBlockEntity>) TileEntityType.Builder.create(CraftingTerminalBlockEntity::new, craftingTerminalBlock).build(null).setRegistryName("crafting_terminal"),
pressurizerTileEntity = (TileEntityType<PressurizerBlockEntity>) TileEntityType.Builder.create(PressurizerBlockEntity::new, pressurizerBlock).build(null).setRegistryName("pressurizer") pressurizerTileEntity = (TileEntityType<PressurizerBlockEntity>) TileEntityType.Builder.create(PressurizerBlockEntity::new, pressurizerBlock).build(null).setRegistryName("pressurizer")
); );
} }
@ -181,12 +189,12 @@ public final class Registry {
} }
@SubscribeEvent @SubscribeEvent
public static void registerContainers(RegistryEvent.Register<ContainerType<?>> event) { public static void registerContainers(RegistryEvent.Register<MenuType<?>> event) {
event.getRegistry().registerAll( event.getRegistry().registerAll(
pipeContainer = (ContainerType<MainPipeContainer>) IForgeContainerType.create((windowId, inv, data) -> new MainPipeContainer(pipeContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("pipe"), pipeContainer = (MenuType<MainPipeContainer>) IForgeMenuType.create((windowId, inv, data) -> new MainPipeContainer(pipeContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("pipe"),
itemTerminalContainer = (ContainerType<ItemTerminalContainer>) IForgeContainerType.create((windowId, inv, data) -> new ItemTerminalContainer(itemTerminalContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("item_terminal"), itemTerminalContainer = (MenuType<ItemTerminalContainer>) IForgeMenuType.create((windowId, inv, data) -> new ItemTerminalContainer(itemTerminalContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("item_terminal"),
craftingTerminalContainer = (ContainerType<CraftingTerminalContainer>) IForgeContainerType.create((windowId, inv, data) -> new CraftingTerminalContainer(craftingTerminalContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("crafting_terminal"), craftingTerminalContainer = (MenuType<CraftingTerminalContainer>) IForgeMenuType.create((windowId, inv, data) -> new CraftingTerminalContainer(craftingTerminalContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("crafting_terminal"),
pressurizerContainer = (ContainerType<PressurizerContainer>) IForgeContainerType.create((windowId, inv, data) -> new PressurizerContainer(pressurizerContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("pressurizer"), pressurizerContainer = (MenuType<PressurizerContainer>) IForgeMenuType.create((windowId, inv, data) -> new PressurizerContainer(pressurizerContainer, windowId, inv.player, data.readBlockPos())).setRegistryName("pressurizer"),
extractionModuleContainer = createPipeContainer("extraction_module"), extractionModuleContainer = createPipeContainer("extraction_module"),
filterModuleContainer = createPipeContainer("filter_module"), filterModuleContainer = createPipeContainer("filter_module"),
retrievalModuleContainer = createPipeContainer("retrieval_module"), retrievalModuleContainer = createPipeContainer("retrieval_module"),
@ -197,9 +205,9 @@ public final class Registry {
); );
} }
private static <T extends AbstractPipeContainer<?>> ContainerType<T> createPipeContainer(String name) { private static <T extends AbstractPipeContainer<?>> MenuType<T> createPipeContainer(String name) {
return (ContainerType<T>) IForgeContainerType.create((windowId, inv, data) -> { return (MenuType<T>) IForgeMenuType.create((windowId, inv, data) -> {
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, inv.player.world, data.readBlockPos()); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, inv.player.world, data.readBlockPos());
int moduleIndex = data.readInt(); int moduleIndex = data.readInt();
ItemStack moduleStack = tile.modules.getStackInSlot(moduleIndex); ItemStack moduleStack = tile.modules.getStackInSlot(moduleIndex);
return ((IModule) moduleStack.getItem()).getContainer(moduleStack, tile, windowId, inv, inv.player, moduleIndex); return ((IModule) moduleStack.getItem()).getContainer(moduleStack, tile, windowId, inv, inv.player, moduleIndex);
@ -220,22 +228,23 @@ public final class Registry {
} }
public static final class Client { public static final class Client {
public static void setup(FMLClientSetupEvent event) { public static void setup(FMLClientSetupEvent event) {
RenderTypeLookup.setRenderLayer(pipeBlock, RenderType.getCutout()); RenderTypeLookup.setRenderLayer(pipeBlock, RenderType.getCutout());
ClientRegistry.bindTileEntityRenderer(pipeTileEntity, PipeRenderer::new); ClientRegistry.bindTileEntityRenderer(pipeTileEntity, PipeRenderer::new);
RenderingRegistry.registerEntityRenderingHandler(pipeFrameEntity, PipeFrameRenderer::new); RenderingRegistry.registerEntityRenderingHandler(pipeFrameEntity, PipeFrameRenderer::new);
ScreenManager.registerFactory(pipeContainer, MainPipeGui::new); MenuScreens.register(pipeContainer, MainPipeGui::new);
ScreenManager.registerFactory(itemTerminalContainer, ItemTerminalGui::new); MenuScreens.register(itemTerminalContainer, ItemTerminalGui::new);
ScreenManager.registerFactory(pressurizerContainer, PressurizerGui::new); MenuScreens.register(pressurizerContainer, PressurizerGui::new);
ScreenManager.registerFactory(craftingTerminalContainer, CraftingTerminalGui::new); MenuScreens.register(craftingTerminalContainer, CraftingTerminalGui::new);
ScreenManager.registerFactory(extractionModuleContainer, ExtractionModuleGui::new); MenuScreens.register(extractionModuleContainer, ExtractionModuleGui::new);
ScreenManager.registerFactory(filterModuleContainer, FilterModuleGui::new); MenuScreens.register(filterModuleContainer, FilterModuleGui::new);
ScreenManager.registerFactory(retrievalModuleContainer, RetrievalModuleGui::new); MenuScreens.register(retrievalModuleContainer, RetrievalModuleGui::new);
ScreenManager.registerFactory(stackSizeModuleContainer, StackSizeModuleGui::new); MenuScreens.register(stackSizeModuleContainer, StackSizeModuleGui::new);
ScreenManager.registerFactory(filterIncreaseModuleContainer, FilterIncreaseModuleGui::new); MenuScreens.register(filterIncreaseModuleContainer, FilterIncreaseModuleGui::new);
ScreenManager.registerFactory(craftingModuleContainer, CraftingModuleGui::new); MenuScreens.register(craftingModuleContainer, CraftingModuleGui::new);
ScreenManager.registerFactory(filterModifierModuleContainer, FilterModifierModuleGui::new); MenuScreens.register(filterModifierModuleContainer, FilterModifierModuleGui::new);
} }
} }

View file

@ -5,25 +5,23 @@ import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.resources.language.I18n; import net.minecraft.client.resources.language.I18n;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.network.chat.*; 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.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.Containers; import net.minecraft.world.Containers;
import net.minecraft.world.WorldlyContainer;
import net.minecraft.world.WorldlyContainerHolder; import net.minecraft.world.WorldlyContainerHolder;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraft.world.level.BlockGetter;
import net.minecraft.nbt.ListTag;
import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.wrapper.SidedInvWrapper; import net.minecraftforge.items.wrapper.SidedInvWrapper;
@ -36,7 +34,7 @@ import java.util.function.Function;
public final class Utility { public final class Utility {
public static <T extends BlockEntity> T getBlockEntity(Class<T> type, LevelAccessor world, BlockPos pos) { public static <T extends BlockEntity> T getBlockEntity(Class<T> type, BlockGetter world, BlockPos pos) {
var tile = world.getBlockEntity(pos); var tile = world.getBlockEntity(pos);
return type.isInstance(tile) ? (T) tile : null; return type.isInstance(tile) ? (T) tile : null;
} }

View file

@ -4,36 +4,34 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.network.NetworkLocation; import de.ellpeck.prettypipes.network.NetworkLocation;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlock;
import net.minecraft.block.BlockState;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.item.ItemFrameEntity;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.FilledMapItem; import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.world.entity.EntityType; import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.decoration.ItemFrame;
import net.minecraft.world.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.network.IPacket;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.GameRules; import net.minecraft.world.GameRules;
import net.minecraft.world.World; import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.decoration.ItemFrame;
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.Level;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.storage.MapData; import net.minecraft.world.phys.HitResult;
import net.minecraftforge.entity.IEntityAdditionalSpawnData; import net.minecraftforge.entity.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.network.NetworkHooks; import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.network.ICustomPacket;
import net.minecraftforge.network.NetworkHooks;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.List; import java.util.List;
@ -83,8 +81,8 @@ public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawn
} }
@Override @Override
public boolean onValidSurface() { public boolean survives() {
return super.onValidSurface() && canPlace(this.world, this.hangingPosition, this.facingDirection); return super.survives() && canPlace(this.level, this.pos, this.direction);
} }
private static BlockPos getAttachedPipe(Level world, BlockPos pos, Direction direction) { private static BlockPos getAttachedPipe(Level world, BlockPos pos, Direction direction) {
@ -97,77 +95,77 @@ public class PipeFrameEntity extends ItemFrame implements IEntityAdditionalSpawn
return null; return null;
} }
public static boolean canPlace(World world, BlockPos pos, Direction direction) { public static boolean canPlace(Level world, BlockPos pos, Direction direction) {
return getAttachedPipe(world, pos, direction) != null; return getAttachedPipe(world, pos, direction) != null;
} }
public int getAmount() { public int getAmount() {
return this.dataManager.get(AMOUNT); return this.entityData.get(AMOUNT);
} }
@Override @Override
public boolean attackEntityFrom(DamageSource source, float amount) { public boolean hurt(DamageSource source, float amount) {
if (this.isInvulnerableTo(source)) { if (this.isInvulnerableTo(source)) {
return false; return false;
} else if (!source.isExplosion() && !this.getDisplayedItem().isEmpty()) { } else if (!source.isExplosion() && !this.getItem().isEmpty()) {
if (!this.world.isRemote) { if (!this.level.isClientSide) {
this.dropItemOrSelf(source.getTrueSource(), false); this.dropItemOrSelf(source.getDirectEntity(), false);
this.playSound(SoundEvents.ENTITY_ITEM_FRAME_REMOVE_ITEM, 1.0F, 1.0F); this.playSound(SoundEvents.ITEM_FRAME_REMOVE_ITEM, 1.0F, 1.0F);
} }
return true; return true;
} else { } else {
return super.attackEntityFrom(source, amount); return super.hurt(source, amount);
} }
} }
@Override @Override
public void onBroken(@Nullable Entity brokenEntity) { public void dropItem(@Nullable Entity brokenEntity) {
this.playSound(SoundEvents.ENTITY_ITEM_FRAME_BREAK, 1.0F, 1.0F); this.playSound(SoundEvents.ITEM_FRAME_BREAK, 1.0F, 1.0F);
this.dropItemOrSelf(brokenEntity, true); this.dropItemOrSelf(brokenEntity, true);
} }
private void dropItemOrSelf(@Nullable Entity entityIn, boolean b) { private void dropItemOrSelf(@Nullable Entity entityIn, boolean b) {
if (!this.world.getGameRules().getBoolean(GameRules.DO_ENTITY_DROPS)) { if (!this.level.getGameRules().getBoolean(GameRules.RULE_DOENTITYDROPS)) {
if (entityIn == null) if (entityIn == null)
this.getDisplayedItem().setAttachedEntity(null); this.getItem().setEntityRepresentation(null);
} else { } else {
ItemStack itemstack = this.getDisplayedItem(); ItemStack itemstack = this.getItem();
this.setDisplayedItem(ItemStack.EMPTY); this.setItem(ItemStack.EMPTY);
if (entityIn instanceof PlayerEntity) { if (entityIn instanceof Player playerentity) {
PlayerEntity playerentity = (PlayerEntity) entityIn; if (playerentity.isCreative()) {
if (playerentity.abilities.isCreativeMode) { itemstack.setEntityRepresentation(null);
itemstack.setAttachedEntity(null);
return; return;
} }
} }
if (b) if (b)
this.entityDropItem(Registry.pipeFrameItem); this.spawnAtLocation(Registry.pipeFrameItem);
if (!itemstack.isEmpty()) { if (!itemstack.isEmpty()) {
itemstack = itemstack.copy(); itemstack = itemstack.copy();
itemstack.setAttachedEntity(null); itemstack.setEntityRepresentation(null);
this.entityDropItem(itemstack); this.spawnAtLocation(itemstack);
} }
} }
} }
@Override @Override
public ActionResultType processInitialInteract(PlayerEntity player, Hand hand) { public InteractionResult interact(Player player, InteractionHand hand) {
if (this.getDisplayedItem().isEmpty()) if (this.getItem().isEmpty())
return super.processInitialInteract(player, hand); return super.interact(player, hand);
return ActionResultType.FAIL; return InteractionResult.FAIL;
} }
@Override @Override
public ItemStack getPickedResult(RayTraceResult target) { public ItemStack getPickedResult(HitResult target) {
return new ItemStack(Registry.pipeFrameItem); return new ItemStack(Registry.pipeFrameItem);
} }
@Override @Override
public IPacket<?> createSpawnPacket() { public ICustomPacket<?> createSpawnPacket() {
return NetworkHooks.getEntitySpawningPacket(this); return NetworkHooks.getEntitySpawningPacket(this);
} }

View file

@ -1,12 +1,12 @@
package de.ellpeck.prettypipes.items; package de.ellpeck.prettypipes.items;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.core.BlockPos;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import java.util.List; import java.util.List;
@ -15,33 +15,33 @@ import java.util.function.Consumer;
public interface IModule { public interface IModule {
void tick(ItemStack module, PipeTileEntity tile); void tick(ItemStack module, PipeBlockEntity tile);
boolean canNetworkSee(ItemStack module, PipeTileEntity tile); boolean canNetworkSee(ItemStack module, PipeBlockEntity tile);
boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack); boolean canAcceptItem(ItemStack module, PipeBlockEntity tile, ItemStack stack);
int getMaxInsertionAmount(ItemStack module, PipeTileEntity tile, ItemStack stack, IItemHandler destination); int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination);
int getPriority(ItemStack module, PipeTileEntity tile); int getPriority(ItemStack module, PipeBlockEntity tile);
boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other); boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other);
boolean hasContainer(ItemStack module, PipeTileEntity tile); boolean hasContainer(ItemStack module, PipeBlockEntity tile);
AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex); AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, Inventory inv, Player player, int moduleIndex);
float getItemSpeedIncrease(ItemStack module, PipeTileEntity tile); float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile);
boolean canPipeWork(ItemStack module, PipeTileEntity tile); boolean canPipeWork(ItemStack module, PipeBlockEntity tile);
List<ItemStack> getAllCraftables(ItemStack module, PipeTileEntity tile); List<ItemStack> getAllCraftables(ItemStack module, PipeBlockEntity tile);
int getCraftableAmount(ItemStack module, PipeTileEntity tile, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain); int getCraftableAmount(ItemStack module, PipeBlockEntity tile, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain);
ItemStack craft(ItemStack module, PipeTileEntity tile, BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain); ItemStack craft(ItemStack module, PipeBlockEntity tile, BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain);
Integer getCustomNextNode(ItemStack module, PipeTileEntity tile, List<BlockPos> nodes, int index); Integer getCustomNextNode(ItemStack module, PipeBlockEntity tile, List<BlockPos> nodes, int index);
ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile); ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile);
} }

View file

@ -3,7 +3,7 @@ package de.ellpeck.prettypipes.items;
import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
@ -40,67 +40,67 @@ public abstract class ModuleItem extends Item implements IModule {
} }
@Override @Override
public void tick(ItemStack module, PipeTileEntity tile) { public void tick(ItemStack module, PipeBlockEntity tile) {
} }
@Override @Override
public boolean canNetworkSee(ItemStack module, PipeTileEntity tile) { public boolean canNetworkSee(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack) { public boolean canAcceptItem(ItemStack module, PipeBlockEntity tile, ItemStack stack) {
return true; return true;
} }
@Override @Override
public int getMaxInsertionAmount(ItemStack module, PipeTileEntity tile, ItemStack stack, IItemHandler destination) { public int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination) {
return Integer.MAX_VALUE; return Integer.MAX_VALUE;
} }
@Override @Override
public int getPriority(ItemStack module, PipeTileEntity tile) { public int getPriority(ItemStack module, PipeBlockEntity tile) {
return 0; return 0;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return null; return null;
} }
@Override @Override
public float getItemSpeedIncrease(ItemStack module, PipeTileEntity tile) { public float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile) {
return 0; return 0;
} }
@Override @Override
public boolean canPipeWork(ItemStack module, PipeTileEntity tile) { public boolean canPipeWork(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public List<ItemStack> getAllCraftables(ItemStack module, PipeTileEntity tile) { public List<ItemStack> getAllCraftables(ItemStack module, PipeBlockEntity tile) {
return Collections.emptyList(); return Collections.emptyList();
} }
@Override @Override
public int getCraftableAmount(ItemStack module, PipeTileEntity tile, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) { public int getCraftableAmount(ItemStack module, PipeBlockEntity tile, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) {
return 0; return 0;
} }
@Override @Override
public ItemStack craft(ItemStack module, PipeTileEntity tile, BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) { public ItemStack craft(ItemStack module, PipeBlockEntity tile, BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) {
return stack; return stack;
} }
@Override @Override
public Integer getCustomNextNode(ItemStack module, PipeTileEntity tile, List<BlockPos> nodes, int index) { public Integer getCustomNextNode(ItemStack module, PipeBlockEntity tile, List<BlockPos> nodes, int index) {
return null; return null;
} }
@Override @Override
public ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile) { public ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile) {
return null; return null;
} }
} }

View file

@ -4,7 +4,7 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.pipe.ConnectionType; import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
@ -40,7 +40,7 @@ public class WrenchItem extends Item {
BlockState state = world.getBlockState(pos); BlockState state = world.getBlockState(pos);
if (!(state.getBlock() instanceof PipeBlock)) if (!(state.getBlock() instanceof PipeBlock))
return ActionResultType.PASS; return ActionResultType.PASS;
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, world, pos); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, world, pos);
if (tile == null) if (tile == null)
return ActionResultType.FAIL; return ActionResultType.FAIL;

View file

@ -1,11 +1,11 @@
package de.ellpeck.prettypipes.misc; package de.ellpeck.prettypipes.misc;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.world.entity.player.Player;
import net.minecraft.inventory.container.Container; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.inventory.container.Slot;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler; import net.minecraftforge.items.SlotItemHandler;
import org.jetbrains.annotations.NotNull;
public class FilterSlot extends SlotItemHandler { public class FilterSlot extends SlotItemHandler {
@ -16,9 +16,9 @@ public class FilterSlot extends SlotItemHandler {
this.onlyOneItem = onlyOneItem; this.onlyOneItem = onlyOneItem;
} }
public static boolean checkFilter(Container container, int slotId, PlayerEntity player) { public static boolean checkFilter(AbstractContainerMenu container, int slotId, Player player) {
if (slotId >= 0 && slotId < container.inventorySlots.size()) { if (slotId >= 0 && slotId < container.slots.size()) {
Slot slot = container.getSlot(slotId); var slot = container.getSlot(slotId);
if (slot instanceof FilterSlot) { if (slot instanceof FilterSlot) {
((FilterSlot) slot).slotClick(player); ((FilterSlot) slot).slotClick(player);
return true; return true;
@ -27,32 +27,33 @@ public class FilterSlot extends SlotItemHandler {
return false; return false;
} }
private void slotClick(PlayerEntity player) { private void slotClick(Player player) {
ItemStack heldStack = player.inventory.getItemStack(); var heldStack = player.inventoryMenu.getCarried();
ItemStack stackInSlot = this.getStack(); var stackInSlot = this.getItem();
if (!stackInSlot.isEmpty() && heldStack.isEmpty()) { if (!stackInSlot.isEmpty() && heldStack.isEmpty()) {
this.putStack(ItemStack.EMPTY); this.safeInsert(ItemStack.EMPTY);
} else if (!heldStack.isEmpty()) { } else if (!heldStack.isEmpty()) {
ItemStack s = heldStack.copy(); var s = heldStack.copy();
if (this.onlyOneItem) if (this.onlyOneItem)
s.setCount(1); s.setCount(1);
this.putStack(s); this.safeInsert(s);
} }
} }
@Override @Override
public boolean isItemValid(ItemStack stack) { public boolean mayPlace(@NotNull ItemStack stack) {
return false; return false;
} }
@Override @Override
public void putStack(ItemStack stack) { public ItemStack safeInsert(ItemStack stack) {
super.putStack(stack.copy()); return super.safeInsert(stack.copy());
} }
@Override @Override
public boolean canTakeStack(PlayerEntity playerIn) { public boolean mayPickup(Player playerIn) {
return false; return false;
} }
} }

View file

@ -3,7 +3,7 @@ package de.ellpeck.prettypipes.misc;
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.PoseStack;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.packets.PacketButton; import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem; import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.Button;
@ -25,14 +25,14 @@ import java.util.function.Supplier;
public class ItemFilter extends ItemStackHandler { public class ItemFilter extends ItemStackHandler {
private final ItemStack stack; private final ItemStack stack;
private final PipeTileEntity pipe; private final PipeBlockEntity pipe;
public boolean isWhitelist; public boolean isWhitelist;
public boolean canPopulateFromInventories; public boolean canPopulateFromInventories;
public boolean canModifyWhitelist = true; public boolean canModifyWhitelist = true;
private boolean modified; private boolean modified;
public ItemFilter(int size, ItemStack stack, PipeTileEntity pipe) { public ItemFilter(int size, ItemStack stack, PipeBlockEntity pipe) {
super(size); super(size);
this.stack = stack; this.stack = stack;
this.pipe = pipe; this.pipe = pipe;
@ -144,7 +144,7 @@ public class ItemFilter extends ItemStackHandler {
this.modified = true; this.modified = true;
} }
public static ItemEquality[] getEqualityTypes(PipeTileEntity pipe) { public static ItemEquality[] getEqualityTypes(PipeBlockEntity pipe) {
return pipe.streamModules() return pipe.streamModules()
.filter(m -> m.getRight() instanceof FilterModifierModuleItem) .filter(m -> m.getRight() instanceof FilterModifierModuleItem)
.map(m -> ((FilterModifierModuleItem) m.getRight()).getEqualityType(m.getLeft())) .map(m -> ((FilterModifierModuleItem) m.getRight()).getEqualityType(m.getLeft()))

View file

@ -1,13 +1,12 @@
package de.ellpeck.prettypipes.network; package de.ellpeck.prettypipes.network;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NBTUtil; import net.minecraft.world.level.Level;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
@ -33,7 +32,7 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
this.deserializeNBT(nbt); this.deserializeNBT(nbt);
} }
public List<Integer> getStackSlots(World world, ItemStack stack, ItemEquality... equalityTypes) { public List<Integer> getStackSlots(Level world, ItemStack stack, ItemEquality... equalityTypes) {
if (this.isEmpty(world)) if (this.isEmpty(world))
return Collections.emptyList(); return Collections.emptyList();
return this.getItems(world).entrySet().stream() return this.getItems(world).entrySet().stream()
@ -41,7 +40,7 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
.map(Map.Entry::getKey).collect(Collectors.toList()); .map(Map.Entry::getKey).collect(Collectors.toList());
} }
public int getItemAmount(World world, ItemStack stack, ItemEquality... equalityTypes) { public int getItemAmount(Level world, ItemStack stack, ItemEquality... equalityTypes) {
if (this.isEmpty(world)) if (this.isEmpty(world))
return 0; return 0;
return this.getItems(world).entrySet().stream() return this.getItems(world).entrySet().stream()
@ -49,7 +48,7 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
.mapToInt(kv -> kv.getValue().getCount()).sum(); .mapToInt(kv -> kv.getValue().getCount()).sum();
} }
public Map<Integer, ItemStack> getItems(World world) { public Map<Integer, ItemStack> getItems(Level world) {
if (this.itemCache == null) { if (this.itemCache == null) {
IItemHandler handler = this.getItemHandler(world); IItemHandler handler = this.getItemHandler(world);
if (handler != null) { if (handler != null) {
@ -68,27 +67,27 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
return this.itemCache; return this.itemCache;
} }
public boolean canExtract(World world, int slot) { public boolean canExtract(Level world, int slot) {
IItemHandler handler = this.getItemHandler(world); IItemHandler handler = this.getItemHandler(world);
return handler != null && !handler.extractItem(slot, 1, true).isEmpty(); return handler != null && !handler.extractItem(slot, 1, true).isEmpty();
} }
public IItemHandler getItemHandler(World world) { public IItemHandler getItemHandler(Level world) {
if (this.handlerCache == null) { if (this.handlerCache == null) {
PipeNetwork network = PipeNetwork.get(world); PipeNetwork network = PipeNetwork.get(world);
PipeTileEntity pipe = network.getPipe(this.pipePos); PipeBlockEntity pipe = network.getPipe(this.pipePos);
this.handlerCache = pipe.getItemHandler(this.direction); this.handlerCache = pipe.getItemHandler(this.direction);
} }
return this.handlerCache; return this.handlerCache;
} }
public boolean isEmpty(World world) { public boolean isEmpty(Level world) {
Map<Integer, ItemStack> items = this.getItems(world); Map<Integer, ItemStack> items = this.getItems(world);
return items == null || items.isEmpty(); return items == null || items.isEmpty();
} }
public BlockPos getPos() { public BlockPos getPos() {
return this.pipePos.offset(this.direction); return this.pipePos.relative(this.direction);
} }
@Override @Override

View file

@ -5,7 +5,7 @@ import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.pipe.IPipeConnectable; import de.ellpeck.prettypipes.pipe.IPipeConnectable;
import de.ellpeck.prettypipes.pipe.IPipeItem; import de.ellpeck.prettypipes.pipe.IPipeItem;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.client.renderer.model.ItemCameraTransforms;
@ -95,7 +95,7 @@ public class PipeItem implements IPipeItem {
} }
@Override @Override
public void updateInPipe(PipeTileEntity currPipe) { public void updateInPipe(PipeBlockEntity currPipe) {
// this prevents pipes being updated after one another // this prevents pipes being updated after one another
// causing an item that just switched to tick twice // causing an item that just switched to tick twice
long worldTick = currPipe.getWorld().getGameTime(); long worldTick = currPipe.getWorld().getGameTime();
@ -112,7 +112,7 @@ public class PipeItem implements IPipeItem {
if (!myPos.equals(currPipe.getPos()) && (currPipe.getPos().equals(this.getDestPipe()) || !myPos.equals(this.startInventory))) { if (!myPos.equals(currPipe.getPos()) && (currPipe.getPos().equals(this.getDestPipe()) || !myPos.equals(this.startInventory))) {
// we're done with the current pipe, so switch to the next one // we're done with the current pipe, so switch to the next one
currPipe.getItems().remove(this); currPipe.getItems().remove(this);
PipeTileEntity next = this.getNextTile(currPipe, true); PipeBlockEntity next = this.getNextTile(currPipe, true);
if (next == null) { if (next == null) {
if (!currPipe.getWorld().isRemote) { if (!currPipe.getWorld().isRemote) {
if (currPipe.getPos().equals(this.getDestPipe())) { if (currPipe.getPos().equals(this.getDestPipe())) {
@ -134,7 +134,7 @@ public class PipeItem implements IPipeItem {
if (dist < currSpeed * currSpeed) { if (dist < currSpeed * currSpeed) {
// we're past the start of the pipe, so move to the center of the next pipe // we're past the start of the pipe, so move to the center of the next pipe
BlockPos nextPos; BlockPos nextPos;
PipeTileEntity next = this.getNextTile(currPipe, false); PipeBlockEntity next = this.getNextTile(currPipe, false);
if (next == null || next == currPipe) { if (next == null || next == currPipe) {
if (currPipe.getPos().equals(this.getDestPipe())) { if (currPipe.getPos().equals(this.getDestPipe())) {
nextPos = this.destInventory; nextPos = this.destInventory;
@ -177,7 +177,7 @@ public class PipeItem implements IPipeItem {
} }
} }
protected void onPathObstructed(PipeTileEntity currPipe, boolean tryReturn) { protected void onPathObstructed(PipeBlockEntity currPipe, boolean tryReturn) {
if (currPipe.getWorld().isRemote) if (currPipe.getWorld().isRemote)
return; return;
PipeNetwork network = PipeNetwork.get(currPipe.getWorld()); PipeNetwork network = PipeNetwork.get(currPipe.getWorld());
@ -203,7 +203,7 @@ public class PipeItem implements IPipeItem {
item.world.addEntity(item); item.world.addEntity(item);
} }
protected ItemStack store(PipeTileEntity currPipe) { protected ItemStack store(PipeBlockEntity currPipe) {
Direction dir = Utility.getDirectionFromOffset(this.destInventory, this.getDestPipe()); Direction dir = Utility.getDirectionFromOffset(this.destInventory, this.getDestPipe());
IPipeConnectable connectable = currPipe.getPipeConnectable(dir); IPipeConnectable connectable = currPipe.getPipeConnectable(dir);
if (connectable != null) if (connectable != null)
@ -214,7 +214,7 @@ public class PipeItem implements IPipeItem {
return this.stack; return this.stack;
} }
protected PipeTileEntity getNextTile(PipeTileEntity currPipe, boolean progress) { protected PipeBlockEntity getNextTile(PipeBlockEntity currPipe, boolean progress) {
if (this.path.size() <= this.currentTile + 1) if (this.path.size() <= this.currentTile + 1)
return null; return null;
BlockPos pos = this.path.get(this.currentTile + 1); BlockPos pos = this.path.get(this.currentTile + 1);
@ -289,7 +289,7 @@ public class PipeItem implements IPipeItem {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void render(PipeTileEntity tile, MatrixStack matrixStack, Random random, float partialTicks, int light, int overlay, IRenderTypeBuffer buffer) { public void render(PipeBlockEntity tile, MatrixStack matrixStack, Random random, float partialTicks, int light, int overlay, IRenderTypeBuffer buffer) {
matrixStack.translate( matrixStack.translate(
MathHelper.lerp(partialTicks, this.lastX, this.x), MathHelper.lerp(partialTicks, this.lastX, this.x),
MathHelper.lerp(partialTicks, this.lastY, this.y), MathHelper.lerp(partialTicks, this.lastY, this.y),

View file

@ -11,29 +11,21 @@ import de.ellpeck.prettypipes.packets.PacketHandler;
import de.ellpeck.prettypipes.packets.PacketItemEnterPipe; import de.ellpeck.prettypipes.packets.PacketItemEnterPipe;
import de.ellpeck.prettypipes.pipe.IPipeItem; import de.ellpeck.prettypipes.pipe.IPipeItem;
import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.block.BlockState;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.nbt.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NBTUtil; import net.minecraft.nbt.NbtUtils;
import net.minecraft.util.Direction; import net.minecraft.nbt.Tag;
import net.minecraft.util.math.BlockPos; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.IItemHandler;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.jgrapht.GraphPath;
import org.jgrapht.ListenableGraph; import org.jgrapht.ListenableGraph;
import org.jgrapht.alg.interfaces.ShortestPathAlgorithm;
import org.jgrapht.alg.shortestpath.DijkstraShortestPath; import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
import org.jgrapht.event.GraphEdgeChangeEvent; import org.jgrapht.event.GraphEdgeChangeEvent;
import org.jgrapht.event.GraphListener; import org.jgrapht.event.GraphListener;
@ -56,7 +48,7 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public final ListenableGraph<BlockPos, NetworkEdge> graph; public final ListenableGraph<BlockPos, NetworkEdge> graph;
private final DijkstraShortestPath<BlockPos, NetworkEdge> dijkstra; private final DijkstraShortestPath<BlockPos, NetworkEdge> dijkstra;
private final Map<BlockPos, List<BlockPos>> nodeToConnectedNodes = new HashMap<>(); private final Map<BlockPos, List<BlockPos>> nodeToConnectedNodes = new HashMap<>();
private final Map<BlockPos, PipeTileEntity> tileCache = new HashMap<>(); private final Map<BlockPos, PipeBlockEntity> tileCache = new HashMap<>();
private final ListMultimap<BlockPos, IPipeItem> pipeItems = ArrayListMultimap.create(); private final ListMultimap<BlockPos, IPipeItem> pipeItems = ArrayListMultimap.create();
private final ListMultimap<BlockPos, NetworkLock> networkLocks = ArrayListMultimap.create(); private final ListMultimap<BlockPos, NetworkLock> networkLocks = ArrayListMultimap.create();
private final Level world; private final Level world;
@ -77,13 +69,13 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
@Override @Override
public CompoundTag serializeNBT() { public CompoundTag serializeNBT() {
CompoundTag nbt = new CompoundTag(); var nbt = new CompoundTag();
ListTag nodes = new ListTag(); var nodes = new ListTag();
for (BlockPos node : this.graph.vertexSet()) for (var node : this.graph.vertexSet())
nodes.add(NbtUtils.writeBlockPos(node)); nodes.add(NbtUtils.writeBlockPos(node));
nbt.put("nodes", nodes); nbt.put("nodes", nodes);
ListTag edges = new ListTag(); var edges = new ListTag();
for (NetworkEdge edge : this.graph.edgeSet()) for (var edge : this.graph.edgeSet())
edges.add(edge.serializeNBT()); edges.add(edge.serializeNBT());
nbt.put("edges", edges); nbt.put("edges", edges);
nbt.put("items", Utility.serializeAll(this.pipeItems.values())); nbt.put("items", Utility.serializeAll(this.pipeItems.values()));
@ -97,15 +89,15 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
this.pipeItems.clear(); this.pipeItems.clear();
this.networkLocks.clear(); this.networkLocks.clear();
ListTag nodes = nbt.getList("nodes", Tag.TAG_COMPOUND); var nodes = nbt.getList("nodes", Tag.TAG_COMPOUND);
for (int i = 0; i < nodes.size(); i++) for (var i = 0; i < nodes.size(); i++)
this.graph.addVertex(NBTUtil.readBlockPos(nodes.getCompound(i))); this.graph.addVertex(NbtUtils.readBlockPos(nodes.getCompound(i)));
ListTag edges = nbt.getList("edges", Tag.TAG_COMPOUND); var edges = nbt.getList("edges", Tag.TAG_COMPOUND);
for (int i = 0; i < edges.size(); i++) for (var i = 0; i < edges.size(); i++)
this.addEdge(new NetworkEdge(edges.getCompound(i))); this.addEdge(new NetworkEdge(edges.getCompound(i)));
for (IPipeItem item : Utility.deserializeAll(nbt.getList("items", NBT.TAG_COMPOUND), IPipeItem::load)) for (var item : Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load))
this.pipeItems.put(item.getCurrentPipe(), item); this.pipeItems.put(item.getCurrentPipe(), item);
for (NetworkLock lock : Utility.deserializeAll(nbt.getList("locks", NBT.TAG_COMPOUND), NetworkLock::new)) for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), NetworkLock::new))
this.createNetworkLock(lock); this.createNetworkLock(lock);
} }
@ -126,12 +118,12 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
} }
public void onPipeChanged(BlockPos pos, BlockState state) { public void onPipeChanged(BlockPos pos, BlockState state) {
List<NetworkEdge> neighbors = this.createAllEdges(pos, state, true); var neighbors = this.createAllEdges(pos, state, true);
// if we only have one neighbor, then there can't be any new connections // if we only have one neighbor, then there can't be any new connections
if (neighbors.size() <= 1 && !this.isNode(pos)) if (neighbors.size() <= 1 && !this.isNode(pos))
return; return;
for (NetworkEdge edge : neighbors) { for (var edge : neighbors) {
BlockPos end = edge.getEndPipe(); var end = edge.getEndPipe();
this.refreshNode(end, this.world.getBlockState(end)); this.refreshNode(end, this.world.getBlockState(end));
} }
} }
@ -143,24 +135,24 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public ItemStack routeItem(BlockPos startPipePos, BlockPos startInventory, ItemStack stack, BiFunction<ItemStack, Float, IPipeItem> itemSupplier, boolean preventOversending) { public ItemStack routeItem(BlockPos startPipePos, BlockPos startInventory, ItemStack stack, BiFunction<ItemStack, Float, IPipeItem> itemSupplier, boolean preventOversending) {
if (!this.isNode(startPipePos)) if (!this.isNode(startPipePos))
return stack; return stack;
if (!this.world.isBlockLoaded(startPipePos)) if (!this.world.isLoaded(startPipePos))
return stack; return stack;
PipeTileEntity startPipe = this.getPipe(startPipePos); var startPipe = this.getPipe(startPipePos);
if (startPipe == null) if (startPipe == null)
return stack; return stack;
this.startProfile("find_destination"); this.startProfile("find_destination");
List<BlockPos> nodes = this.getOrderedNetworkNodes(startPipePos); var nodes = this.getOrderedNetworkNodes(startPipePos);
for (int i = 0; i < nodes.size(); i++) { for (var i = 0; i < nodes.size(); i++) {
BlockPos pipePos = nodes.get(startPipe.getNextNode(nodes, i)); var pipePos = nodes.get(startPipe.getNextNode(nodes, i));
if (!this.world.isBlockLoaded(pipePos)) if (!this.world.isLoaded(pipePos))
continue; continue;
PipeTileEntity pipe = this.getPipe(pipePos); var pipe = this.getPipe(pipePos);
Pair<BlockPos, ItemStack> dest = pipe.getAvailableDestination(stack, false, preventOversending); var dest = pipe.getAvailableDestination(stack, false, preventOversending);
if (dest == null || dest.getLeft().equals(startInventory)) if (dest == null || dest.getLeft().equals(startInventory))
continue; continue;
Function<Float, IPipeItem> sup = speed -> itemSupplier.apply(dest.getRight(), speed); var sup = (Function<Float, IPipeItem>) speed -> itemSupplier.apply(dest.getRight(), speed);
if (this.routeItemToLocation(startPipePos, startInventory, pipe.getPos(), dest.getLeft(), dest.getRight(), sup)) { if (this.routeItemToLocation(startPipePos, startInventory, pipe.getBlockPos(), dest.getLeft(), dest.getRight(), sup)) {
ItemStack remain = stack.copy(); var remain = stack.copy();
remain.shrink(dest.getRight().getCount()); remain.shrink(dest.getRight().getCount());
this.endProfile(); this.endProfile();
return remain; return remain;
@ -173,17 +165,17 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public boolean routeItemToLocation(BlockPos startPipePos, BlockPos startInventory, BlockPos destPipePos, BlockPos destInventory, ItemStack stack, Function<Float, IPipeItem> itemSupplier) { public boolean routeItemToLocation(BlockPos startPipePos, BlockPos startInventory, BlockPos destPipePos, BlockPos destInventory, ItemStack stack, Function<Float, IPipeItem> itemSupplier) {
if (!this.isNode(startPipePos) || !this.isNode(destPipePos)) if (!this.isNode(startPipePos) || !this.isNode(destPipePos))
return false; return false;
if (!this.world.isBlockLoaded(startPipePos) || !this.world.isBlockLoaded(destPipePos)) if (!this.world.isLoaded(startPipePos) || !this.world.isLoaded(destPipePos))
return false; return false;
PipeTileEntity startPipe = this.getPipe(startPipePos); var startPipe = this.getPipe(startPipePos);
if (startPipe == null) if (startPipe == null)
return false; return false;
this.startProfile("get_path"); this.startProfile("get_path");
GraphPath<BlockPos, NetworkEdge> path = this.dijkstra.getPath(startPipePos, destPipePos); var path = this.dijkstra.getPath(startPipePos, destPipePos);
this.endProfile(); this.endProfile();
if (path == null) if (path == null)
return false; return false;
IPipeItem item = itemSupplier.apply(startPipe.getItemSpeed(stack)); var item = itemSupplier.apply(startPipe.getItemSpeed(stack));
item.setDestination(startInventory, destInventory, path); item.setDestination(startInventory, destInventory, path);
startPipe.addNewItem(item); startPipe.addNewItem(item);
PacketHandler.sendToAllLoaded(this.world, startPipePos, new PacketItemEnterPipe(startPipePos, item)); PacketHandler.sendToAllLoaded(this.world, startPipePos, new PacketItemEnterPipe(startPipePos, item));
@ -191,9 +183,9 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
} }
public ItemStack requestItem(BlockPos destPipe, BlockPos destInventory, ItemStack stack, ItemEquality... equalityTypes) { public ItemStack requestItem(BlockPos destPipe, BlockPos destInventory, ItemStack stack, ItemEquality... equalityTypes) {
ItemStack remain = stack.copy(); var remain = stack.copy();
// check existing items // check existing items
for (NetworkLocation location : this.getOrderedNetworkItems(destPipe)) { for (var location : this.getOrderedNetworkItems(destPipe)) {
remain = this.requestExistingItem(location, destPipe, destInventory, null, remain, equalityTypes); remain = this.requestExistingItem(location, destPipe, destInventory, null, remain, equalityTypes);
if (remain.isEmpty()) if (remain.isEmpty())
return remain; return remain;
@ -203,10 +195,10 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
} }
public ItemStack requestCraftedItem(BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) { public ItemStack requestCraftedItem(BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) {
for (Pair<BlockPos, ItemStack> craftable : this.getAllCraftables(destPipe)) { for (var craftable : this.getAllCraftables(destPipe)) {
if (!ItemEquality.compareItems(stack, craftable.getRight(), equalityTypes)) if (!ItemEquality.compareItems(stack, craftable.getRight(), equalityTypes))
continue; continue;
PipeTileEntity pipe = this.getPipe(craftable.getLeft()); var pipe = this.getPipe(craftable.getLeft());
if (pipe == null) if (pipe == null)
continue; continue;
stack = pipe.craft(destPipe, unavailableConsumer, stack, dependencyChain); stack = pipe.craft(destPipe, unavailableConsumer, stack, dependencyChain);
@ -224,21 +216,21 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
if (location.getPos().equals(destInventory)) if (location.getPos().equals(destInventory))
return stack; return stack;
// make sure we don't pull any locked items // make sure we don't pull any locked items
int amount = location.getItemAmount(this.world, stack, equalityTypes); var amount = location.getItemAmount(this.world, stack, equalityTypes);
if (amount <= 0) if (amount <= 0)
return stack; return stack;
amount -= this.getLockedAmount(location.getPos(), stack, ignoredLock, equalityTypes); amount -= this.getLockedAmount(location.getPos(), stack, ignoredLock, equalityTypes);
if (amount <= 0) if (amount <= 0)
return stack; return stack;
ItemStack remain = stack.copy(); var remain = stack.copy();
// make sure we only extract less than or equal to the requested amount // make sure we only extract less than or equal to the requested amount
if (remain.getCount() < amount) if (remain.getCount() < amount)
amount = remain.getCount(); amount = remain.getCount();
remain.shrink(amount); remain.shrink(amount);
for (int slot : location.getStackSlots(this.world, stack, equalityTypes)) { for (int slot : location.getStackSlots(this.world, stack, equalityTypes)) {
// try to extract from that location's inventory and send the item // try to extract from that location's inventory and send the item
IItemHandler handler = location.getItemHandler(this.world); var handler = location.getItemHandler(this.world);
ItemStack extracted = handler.extractItem(slot, amount, true); var extracted = handler.extractItem(slot, amount, true);
if (this.routeItemToLocation(location.pipePos, location.getPos(), destPipe, destInventory, extracted, speed -> itemSupplier.apply(extracted, speed))) { if (this.routeItemToLocation(location.pipePos, location.getPos(), destPipe, destInventory, extracted, speed -> itemSupplier.apply(extracted, speed))) {
handler.extractItem(slot, extracted.getCount(), false); handler.extractItem(slot, extracted.getCount(), false);
amount -= extracted.getCount(); amount -= extracted.getCount();
@ -249,10 +241,10 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
return remain; return remain;
} }
public PipeTileEntity getPipe(BlockPos pos) { public PipeBlockEntity getPipe(BlockPos pos) {
PipeTileEntity tile = this.tileCache.get(pos); var tile = this.tileCache.get(pos);
if (tile == null || tile.isRemoved()) { if (tile == null || tile.isRemoved()) {
tile = Utility.getBlockEntity(PipeTileEntity.class, this.world, pos); tile = Utility.getBlockEntity(PipeBlockEntity.class, this.world, pos);
this.tileCache.put(pos, tile); this.tileCache.put(pos, tile);
} }
return tile; return tile;
@ -265,14 +257,14 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public List<Pair<BlockPos, ItemStack>> getCurrentlyCrafting(BlockPos node, ItemEquality... equalityTypes) { public List<Pair<BlockPos, ItemStack>> getCurrentlyCrafting(BlockPos node, ItemEquality... equalityTypes) {
this.startProfile("get_currently_crafting"); this.startProfile("get_currently_crafting");
List<Pair<BlockPos, ItemStack>> items = new ArrayList<>(); List<Pair<BlockPos, ItemStack>> items = new ArrayList<>();
Iterator<PipeTileEntity> craftingPipes = this.getAllCraftables(node).stream().map(c -> this.getPipe(c.getLeft())).distinct().iterator(); var craftingPipes = this.getAllCraftables(node).stream().map(c -> this.getPipe(c.getLeft())).distinct().iterator();
while (craftingPipes.hasNext()) { while (craftingPipes.hasNext()) {
PipeTileEntity pipe = craftingPipes.next(); var pipe = craftingPipes.next();
for (Pair<BlockPos, ItemStack> request : pipe.craftResultRequests) { for (var request : pipe.craftResultRequests) {
BlockPos dest = request.getLeft(); var dest = request.getLeft();
ItemStack stack = request.getRight(); var stack = request.getRight();
// add up all the items that should go to the same location // add up all the items that should go to the same location
Optional<Pair<BlockPos, ItemStack>> existing = items.stream() var existing = items.stream()
.filter(s -> s.getLeft().equals(dest) && ItemEquality.compareItems(s.getRight(), stack, equalityTypes)) .filter(s -> s.getLeft().equals(dest) && ItemEquality.compareItems(s.getRight(), stack, equalityTypes))
.findFirst(); .findFirst();
if (existing.isPresent()) { if (existing.isPresent()) {
@ -297,25 +289,25 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
return Collections.emptyList(); return Collections.emptyList();
this.startProfile("get_all_craftables"); this.startProfile("get_all_craftables");
List<Pair<BlockPos, ItemStack>> craftables = new ArrayList<>(); List<Pair<BlockPos, ItemStack>> craftables = new ArrayList<>();
for (BlockPos dest : this.getOrderedNetworkNodes(node)) { for (var dest : this.getOrderedNetworkNodes(node)) {
if (!this.world.isBlockLoaded(dest)) if (!this.world.isLoaded(dest))
continue; continue;
PipeTileEntity pipe = this.getPipe(dest); var pipe = this.getPipe(dest);
for (ItemStack stack : pipe.getAllCraftables()) for (var stack : pipe.getAllCraftables())
craftables.add(Pair.of(pipe.getPos(), stack)); craftables.add(Pair.of(pipe.getBlockPos(), stack));
} }
this.endProfile(); this.endProfile();
return craftables; return craftables;
} }
public int getCraftableAmount(BlockPos node, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) { public int getCraftableAmount(BlockPos node, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) {
int total = 0; var total = 0;
for (Pair<BlockPos, ItemStack> pair : this.getAllCraftables(node)) { for (var pair : this.getAllCraftables(node)) {
if (!ItemEquality.compareItems(pair.getRight(), stack, equalityTypes)) if (!ItemEquality.compareItems(pair.getRight(), stack, equalityTypes))
continue; continue;
if (!this.world.isBlockLoaded(pair.getLeft())) if (!this.world.isLoaded(pair.getLeft()))
continue; continue;
PipeTileEntity pipe = this.getPipe(pair.getLeft()); var pipe = this.getPipe(pair.getLeft());
if (pipe != null) if (pipe != null)
total += pipe.getCraftableAmount(unavailableConsumer, stack, dependencyChain); total += pipe.getCraftableAmount(unavailableConsumer, stack, dependencyChain);
} }
@ -327,20 +319,20 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
return Collections.emptyList(); return Collections.emptyList();
this.startProfile("get_network_items"); this.startProfile("get_network_items");
List<NetworkLocation> info = new ArrayList<>(); List<NetworkLocation> info = new ArrayList<>();
for (BlockPos dest : this.getOrderedNetworkNodes(node)) { for (var dest : this.getOrderedNetworkNodes(node)) {
if (!this.world.isBlockLoaded(dest)) if (!this.world.isLoaded(dest))
continue; continue;
PipeTileEntity pipe = this.getPipe(dest); var pipe = this.getPipe(dest);
if (!pipe.canNetworkSee()) if (!pipe.canNetworkSee())
continue; continue;
for (Direction dir : Direction.values()) { for (var dir : Direction.values()) {
IItemHandler handler = pipe.getItemHandler(dir); var handler = pipe.getItemHandler(dir);
if (handler == null) if (handler == null)
continue; continue;
// check if this handler already exists (double-connected pipes, double chests etc.) // check if this handler already exists (double-connected pipes, double chests etc.)
if (info.stream().anyMatch(l -> handler.equals(l.getItemHandler(this.world)))) if (info.stream().anyMatch(l -> handler.equals(l.getItemHandler(this.world))))
continue; continue;
NetworkLocation location = new NetworkLocation(dest, dir); var location = new NetworkLocation(dest, dir);
if (!location.isEmpty(this.world)) if (!location.isEmpty(this.world))
info.add(location); info.add(location);
} }
@ -370,7 +362,7 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
private void refreshNode(BlockPos pos, BlockState state) { private void refreshNode(BlockPos pos, BlockState state) {
this.startProfile("refresh_node"); this.startProfile("refresh_node");
this.graph.removeAllEdges(new ArrayList<>(this.graph.edgesOf(pos))); this.graph.removeAllEdges(new ArrayList<>(this.graph.edgesOf(pos)));
for (NetworkEdge edge : this.createAllEdges(pos, state, false)) for (var edge : this.createAllEdges(pos, state, false))
this.addEdge(edge); this.addEdge(edge);
this.endProfile(); this.endProfile();
} }
@ -384,11 +376,11 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public BlockPos getNodeFromPipe(BlockPos pos) { public BlockPos getNodeFromPipe(BlockPos pos) {
if (this.isNode(pos)) if (this.isNode(pos))
return pos; return pos;
BlockState state = this.world.getBlockState(pos); var state = this.world.getBlockState(pos);
if (!(state.getBlock() instanceof PipeBlock)) if (!(state.getBlock() instanceof PipeBlock))
return null; return null;
for (Direction dir : Direction.values()) { for (var dir : Direction.values()) {
NetworkEdge edge = this.createEdge(pos, state, dir, false); var edge = this.createEdge(pos, state, dir, false);
if (edge != null) if (edge != null)
return edge.getEndPipe(); return edge.getEndPipe();
} }
@ -398,8 +390,8 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
private List<NetworkEdge> createAllEdges(BlockPos pos, BlockState state, boolean ignoreCurrBlocked) { private List<NetworkEdge> createAllEdges(BlockPos pos, BlockState state, boolean ignoreCurrBlocked) {
this.startProfile("create_all_edges"); this.startProfile("create_all_edges");
List<NetworkEdge> edges = new ArrayList<>(); List<NetworkEdge> edges = new ArrayList<>();
for (Direction dir : Direction.values()) { for (var dir : Direction.values()) {
NetworkEdge edge = this.createEdge(pos, state, dir, ignoreCurrBlocked); var edge = this.createEdge(pos, state, dir, ignoreCurrBlocked);
if (edge != null) if (edge != null)
edges.add(edge); edges.add(edge);
} }
@ -408,14 +400,14 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
} }
private NetworkEdge createEdge(BlockPos pos, BlockState state, Direction dir, boolean ignoreCurrBlocked) { private NetworkEdge createEdge(BlockPos pos, BlockState state, Direction dir, boolean ignoreCurrBlocked) {
if (!ignoreCurrBlocked && !state.get(PipeBlock.DIRECTIONS.get(dir)).isConnected()) if (!ignoreCurrBlocked && !state.getValue(PipeBlock.DIRECTIONS.get(dir)).isConnected())
return null; return null;
BlockPos currPos = pos.offset(dir); var currPos = pos.relative(dir);
BlockState currState = this.world.getBlockState(currPos); var currState = this.world.getBlockState(currPos);
if (!(currState.getBlock() instanceof PipeBlock)) if (!(currState.getBlock() instanceof PipeBlock))
return null; return null;
this.startProfile("create_edge"); this.startProfile("create_edge");
NetworkEdge edge = new NetworkEdge(); var edge = new NetworkEdge();
edge.pipes.add(pos); edge.pipes.add(pos);
edge.pipes.add(currPos); edge.pipes.add(currPos);
@ -427,12 +419,12 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
return edge; return edge;
} }
boolean found = false; var found = false;
for (Direction nextDir : Direction.values()) { for (var nextDir : Direction.values()) {
if (!currState.get(PipeBlock.DIRECTIONS.get(nextDir)).isConnected()) if (!currState.getValue(PipeBlock.DIRECTIONS.get(nextDir)).isConnected())
continue; continue;
BlockPos offset = currPos.offset(nextDir); var offset = currPos.relative(nextDir);
BlockState offState = this.world.getBlockState(offset); var offState = this.world.getBlockState(offset);
if (!(offState.getBlock() instanceof PipeBlock)) if (!(offState.getBlock() instanceof PipeBlock))
continue; continue;
if (edge.pipes.contains(offset)) if (edge.pipes.contains(offset))
@ -453,10 +445,10 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public List<BlockPos> getOrderedNetworkNodes(BlockPos node) { public List<BlockPos> getOrderedNetworkNodes(BlockPos node) {
if (!this.isNode(node)) if (!this.isNode(node))
return Collections.emptyList(); return Collections.emptyList();
List<BlockPos> ret = this.nodeToConnectedNodes.get(node); var ret = this.nodeToConnectedNodes.get(node);
if (ret == null) { if (ret == null) {
this.startProfile("compile_connected_nodes"); this.startProfile("compile_connected_nodes");
ShortestPathAlgorithm.SingleSourcePaths<BlockPos, NetworkEdge> paths = this.dijkstra.getPaths(node); var paths = this.dijkstra.getPaths(node);
// sort destinations first by their priority (eg trash pipes should be last) // sort destinations first by their priority (eg trash pipes should be last)
// and then by their distance from the specified node // and then by their distance from the specified node
ret = Streams.stream(new BreadthFirstIterator<>(this.graph, node)) ret = Streams.stream(new BreadthFirstIterator<>(this.graph, node))
@ -472,7 +464,7 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public void clearDestinationCache(BlockPos... nodes) { public void clearDestinationCache(BlockPos... nodes) {
this.startProfile("clear_node_cache"); this.startProfile("clear_node_cache");
// remove caches for the nodes // remove caches for the nodes
for (BlockPos node : nodes) for (var node : nodes)
this.nodeToConnectedNodes.keySet().remove(node); this.nodeToConnectedNodes.keySet().remove(node);
// remove caches that contain the nodes as a destination // remove caches that contain the nodes as a destination
this.nodeToConnectedNodes.values().removeIf(cached -> Arrays.stream(nodes).anyMatch(cached::contains)); this.nodeToConnectedNodes.values().removeIf(cached -> Arrays.stream(nodes).anyMatch(cached::contains));
@ -485,7 +477,7 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
public Stream<IPipeItem> getPipeItemsOnTheWay(BlockPos goalInv) { public Stream<IPipeItem> getPipeItemsOnTheWay(BlockPos goalInv) {
this.startProfile("get_pipe_items_on_the_way"); this.startProfile("get_pipe_items_on_the_way");
Stream<IPipeItem> ret = this.pipeItems.values().stream().filter(i -> i.getDestInventory().equals(goalInv)); var ret = this.pipeItems.values().stream().filter(i -> i.getDestInventory().equals(goalInv));
this.endProfile(); this.endProfile();
return ret; return ret;
} }
@ -515,11 +507,11 @@ public class PipeNetwork implements ICapabilitySerializable<CompoundTag>, GraphL
} }
public void startProfile(String name) { public void startProfile(String name) {
this.world.getProfiler().startSection(() -> PrettyPipes.ID + ":pipe_network_" + name); this.world.getProfiler().push(() -> PrettyPipes.ID + ":pipe_network_" + name);
} }
public void endProfile() { public void endProfile() {
this.world.getProfiler().endSection(); this.world.getProfiler().pop();
} }
public static PipeNetwork get(Level world) { public static PipeNetwork get(Level world) {

View file

@ -4,25 +4,35 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.misc.ItemFilter.IFilteredContainer; import de.ellpeck.prettypipes.misc.ItemFilter.IFilteredContainer;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleContainer; import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleContainer;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem; import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem;
import de.ellpeck.prettypipes.pipe.modules.stacksize.StackSizeModuleItem; import de.ellpeck.prettypipes.pipe.modules.stacksize.StackSizeModuleItem;
import de.ellpeck.prettypipes.terminal.CraftingTerminalTileEntity; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalTileEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
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.item.ItemStack;
import net.minecraft.network.PacketBuffer; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkHooks; import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkHooks;
import org.apache.logging.log4j.util.TriConsumer; import org.apache.logging.log4j.util.TriConsumer;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -44,7 +54,7 @@ public class PacketButton {
} }
public static PacketButton fromBytes(PacketBuffer buf) { public static PacketButton fromBytes(FriendlyByteBuf buf) {
PacketButton packet = new PacketButton(); PacketButton packet = new PacketButton();
packet.pos = buf.readBlockPos(); packet.pos = buf.readBlockPos();
packet.result = ButtonResult.values()[buf.readByte()]; packet.result = ButtonResult.values()[buf.readByte()];
@ -52,7 +62,7 @@ public class PacketButton {
return packet; return packet;
} }
public static void toBytes(PacketButton packet, PacketBuffer buf) { public static void toBytes(PacketButton packet, FriendlyByteBuf buf) {
buf.writeBlockPos(packet.pos); buf.writeBlockPos(packet.pos);
buf.writeByte(packet.result.ordinal()); buf.writeByte(packet.result.ordinal());
buf.writeVarIntArray(packet.data); buf.writeVarIntArray(packet.data);
@ -63,7 +73,7 @@ public class PacketButton {
ctx.get().enqueueWork(new Runnable() { ctx.get().enqueueWork(new Runnable() {
@Override @Override
public void run() { public void run() {
PlayerEntity player = ctx.get().getSender(); Player player = ctx.get().getSender();
message.result.action.accept(message.pos, message.data, player); message.result.action.accept(message.pos, message.data, player);
} }
}); });
@ -77,22 +87,23 @@ public class PacketButton {
public enum ButtonResult { public enum ButtonResult {
PIPE_TAB((pos, data, player) -> { PIPE_TAB((pos, data, player) -> {
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, player.world, pos); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, player.level, pos);
if (data[0] < 0) { if (data[0] < 0) {
NetworkHooks.openGui((ServerPlayerEntity) player, tile, pos); NetworkHooks.openGui((ServerPlayer) player, tile, pos);
} else { } else {
ItemStack stack = tile.modules.getStackInSlot(data[0]); ItemStack stack = tile.modules.getStackInSlot(data[0]);
NetworkHooks.openGui((ServerPlayerEntity) player, new INamedContainerProvider() { NetworkHooks.openGui((ServerPlayer) player, new MenuProvider() {
@Override @Override
public ITextComponent getDisplayName() { public Component getDisplayName() {
return stack.getDisplayName(); return stack.getDisplayName();
} }
@Nullable @Nullable
@Override @Override
public Container createMenu(int windowId, PlayerInventory inv, PlayerEntity player) { public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data[0]); return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data[0]);
} }
}, buf -> { }, buf -> {
buf.writeBlockPos(pos); buf.writeBlockPos(pos);
buf.writeInt(data[0]); buf.writeInt(data[0]);
@ -100,34 +111,34 @@ public class PacketButton {
} }
}), }),
FILTER_CHANGE((pos, data, player) -> { FILTER_CHANGE((pos, data, player) -> {
IFilteredContainer container = (IFilteredContainer) player.openContainer; IFilteredContainer container = (IFilteredContainer) player.containerMenu;
ItemFilter filter = container.getFilter(); ItemFilter filter = container.getFilter();
filter.onButtonPacket(data[0]); filter.onButtonPacket(data[0]);
}), }),
STACK_SIZE_MODULE_BUTTON((pos, data, player) -> { STACK_SIZE_MODULE_BUTTON((pos, data, player) -> {
AbstractPipeContainer<?> container = (AbstractPipeContainer<?>) player.openContainer; AbstractPipeContainer<?> container = (AbstractPipeContainer<?>) player.containerMenu;
StackSizeModuleItem.setLimitToMaxStackSize(container.moduleStack, !StackSizeModuleItem.getLimitToMaxStackSize(container.moduleStack)); StackSizeModuleItem.setLimitToMaxStackSize(container.moduleStack, !StackSizeModuleItem.getLimitToMaxStackSize(container.moduleStack));
}), }),
STACK_SIZE_AMOUNT((pos, data, player) -> { STACK_SIZE_AMOUNT((pos, data, player) -> {
AbstractPipeContainer<?> container = (AbstractPipeContainer<?>) player.openContainer; AbstractPipeContainer<?> container = (AbstractPipeContainer<?>) player.containerMenu;
StackSizeModuleItem.setMaxStackSize(container.moduleStack, data[0]); StackSizeModuleItem.setMaxStackSize(container.moduleStack, data[0]);
}), }),
CRAFT_TERMINAL_REQUEST((pos, data, player) -> { CRAFT_TERMINAL_REQUEST((pos, data, player) -> {
CraftingTerminalTileEntity tile = Utility.getBlockEntity(CraftingTerminalTileEntity.class, player.world, pos); CraftingTerminalBlockEntity tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level, pos);
tile.requestCraftingItems(player, data[0]); tile.requestCraftingItems(player, data[0]);
}), }),
CANCEL_CRAFTING((pos, data, player) -> { CANCEL_CRAFTING((pos, data, player) -> {
ItemTerminalTileEntity tile = Utility.getBlockEntity(ItemTerminalTileEntity.class, player.world, pos); ItemTerminalBlockEntity tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level, pos);
tile.cancelCrafting(); tile.cancelCrafting();
}), }),
TAG_FILTER((pos, data, player) -> { TAG_FILTER((pos, data, player) -> {
FilterModifierModuleContainer container = (FilterModifierModuleContainer) player.openContainer; FilterModifierModuleContainer container = (FilterModifierModuleContainer) player.containerMenu;
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data[0])); FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data[0]));
}); });
public final TriConsumer<BlockPos, int[], PlayerEntity> action; public final TriConsumer<BlockPos, int[], Player> action;
ButtonResult(TriConsumer<BlockPos, int[], PlayerEntity> action) { ButtonResult(TriConsumer<BlockPos, int[], Player> action) {
this.action = action; this.action = action;
} }
} }

View file

@ -3,8 +3,9 @@ package de.ellpeck.prettypipes.packets;
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap; import com.google.common.collect.ListMultimap;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.CraftingTerminalTileEntity; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.network.PacketBuffer; import net.minecraft.network.PacketBuffer;
@ -50,7 +51,7 @@ public class PacketGhostSlot {
@SuppressWarnings("Convert2Lambda") @SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketGhostSlot message, Supplier<NetworkEvent.Context> ctx) { public static void onMessage(PacketGhostSlot message, Supplier<NetworkEvent.Context> ctx) {
Consumer<PlayerEntity> doIt = p -> { Consumer<PlayerEntity> doIt = p -> {
CraftingTerminalTileEntity tile = Utility.getBlockEntity(CraftingTerminalTileEntity.class, p.world, message.pos); CraftingTerminalBlockEntity tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, p.world, message.pos);
if (tile != null) if (tile != null)
tile.setGhostItems(message.stacks); tile.setGhostItems(message.stacks);
}; };

View file

@ -1,15 +1,22 @@
package de.ellpeck.prettypipes.packets; package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import net.minecraft.core.BlockPos;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IWorld; import net.minecraft.world.IWorld;
import net.minecraft.world.World; 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.NetworkRegistry;
import net.minecraftforge.fml.network.PacketDistributor; import net.minecraftforge.fml.network.PacketDistributor;
import net.minecraftforge.fml.network.simple.SimpleChannel; import net.minecraftforge.fml.network.simple.SimpleChannel;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;
public final class PacketHandler { public final class PacketHandler {
@ -26,12 +33,12 @@ public final class PacketHandler {
network.registerMessage(5, PacketCraftingModuleTransfer.class, PacketCraftingModuleTransfer::toBytes, PacketCraftingModuleTransfer::fromBytes, PacketCraftingModuleTransfer::onMessage); network.registerMessage(5, PacketCraftingModuleTransfer.class, PacketCraftingModuleTransfer::toBytes, PacketCraftingModuleTransfer::fromBytes, PacketCraftingModuleTransfer::onMessage);
} }
public static void sendToAllLoaded(World world, BlockPos pos, Object message) { public static void sendToAllLoaded(Level world, BlockPos pos, Object message) {
network.send(PacketDistributor.TRACKING_CHUNK.with(() -> world.getChunkAt(pos)), message); network.send(PacketDistributor.TRACKING_CHUNK.with(() -> world.getChunkAt(pos)), message);
} }
public static void sendTo(PlayerEntity player, Object message) { public static void sendTo(Player player, Object message) {
network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), message); network.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), message);
} }
public static void sendToServer(Object message) { public static void sendToServer(Object message) {

View file

@ -2,12 +2,12 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.pipe.IPipeItem; import de.ellpeck.prettypipes.pipe.IPipeItem;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.PacketBuffer; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.util.math.BlockPos; import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkEvent;
import java.util.function.Supplier; import java.util.function.Supplier;
@ -25,16 +25,16 @@ public class PacketItemEnterPipe {
} }
public static PacketItemEnterPipe fromBytes(PacketBuffer buf) { public static PacketItemEnterPipe fromBytes(FriendlyByteBuf buf) {
PacketItemEnterPipe client = new PacketItemEnterPipe(); PacketItemEnterPipe client = new PacketItemEnterPipe();
client.tilePos = buf.readBlockPos(); client.tilePos = buf.readBlockPos();
client.item = buf.readCompoundTag(); client.item = buf.readNbt();
return client; return client;
} }
public static void toBytes(PacketItemEnterPipe packet, PacketBuffer buf) { public static void toBytes(PacketItemEnterPipe packet, FriendlyByteBuf buf) {
buf.writeBlockPos(packet.tilePos); buf.writeBlockPos(packet.tilePos);
buf.writeCompoundTag(packet.item); buf.writeNbt(packet.item);
} }
@SuppressWarnings("Convert2Lambda") @SuppressWarnings("Convert2Lambda")
@ -43,10 +43,10 @@ public class PacketItemEnterPipe {
@Override @Override
public void run() { public void run() {
Minecraft mc = Minecraft.getInstance(); Minecraft mc = Minecraft.getInstance();
if (mc.world == null) if (mc.level == null)
return; return;
IPipeItem item = IPipeItem.load(message.item); IPipeItem item = IPipeItem.load(message.item);
PipeTileEntity pipe = Utility.getBlockEntity(PipeTileEntity.class, mc.world, message.tilePos); PipeBlockEntity pipe = Utility.getBlockEntity(PipeBlockEntity.class, mc.level, message.tilePos);
if (pipe != null) if (pipe != null)
pipe.getItems().add(item); pipe.getItems().add(item);
} }

View file

@ -2,13 +2,9 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.inventory.container.Container;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraftforge.network.NetworkEvent;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.network.NetworkEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -30,37 +26,37 @@ public class PacketNetworkItems {
} }
public static PacketNetworkItems fromBytes(PacketBuffer buf) { public static PacketNetworkItems fromBytes(FriendlyByteBuf buf) {
PacketNetworkItems client = new PacketNetworkItems(); PacketNetworkItems client = new PacketNetworkItems();
client.items = new ArrayList<>(); client.items = new ArrayList<>();
for (int i = buf.readVarInt(); i > 0; i--) { for (int i = buf.readVarInt(); i > 0; i--) {
ItemStack stack = buf.readItemStack(); ItemStack stack = buf.readItem();
stack.setCount(buf.readVarInt()); stack.setCount(buf.readVarInt());
client.items.add(stack); client.items.add(stack);
} }
client.craftables = new ArrayList<>(); client.craftables = new ArrayList<>();
for (int i = buf.readVarInt(); i > 0; i--) for (int i = buf.readVarInt(); i > 0; i--)
client.craftables.add(buf.readItemStack()); client.craftables.add(buf.readItem());
client.currentlyCrafting = new ArrayList<>(); client.currentlyCrafting = new ArrayList<>();
for (int i = buf.readVarInt(); i > 0; i--) for (int i = buf.readVarInt(); i > 0; i--)
client.currentlyCrafting.add(buf.readItemStack()); client.currentlyCrafting.add(buf.readItem());
return client; return client;
} }
public static void toBytes(PacketNetworkItems packet, PacketBuffer buf) { public static void toBytes(PacketNetworkItems packet, FriendlyByteBuf buf) {
buf.writeVarInt(packet.items.size()); buf.writeVarInt(packet.items.size());
for (ItemStack stack : packet.items) { for (ItemStack stack : packet.items) {
ItemStack copy = stack.copy(); ItemStack copy = stack.copy();
copy.setCount(1); copy.setCount(1);
buf.writeItemStack(copy); buf.writeItem(copy);
buf.writeVarInt(stack.getCount()); buf.writeVarInt(stack.getCount());
} }
buf.writeVarInt(packet.craftables.size()); buf.writeVarInt(packet.craftables.size());
for (ItemStack stack : packet.craftables) for (ItemStack stack : packet.craftables)
buf.writeItemStack(stack); buf.writeItem(stack);
buf.writeVarInt(packet.currentlyCrafting.size()); buf.writeVarInt(packet.currentlyCrafting.size());
for (ItemStack stack : packet.currentlyCrafting) for (ItemStack stack : packet.currentlyCrafting)
buf.writeItemStack(stack); buf.writeItem(stack);
} }
@SuppressWarnings("Convert2Lambda") @SuppressWarnings("Convert2Lambda")
@ -69,8 +65,8 @@ public class PacketNetworkItems {
@Override @Override
public void run() { public void run() {
Minecraft mc = Minecraft.getInstance(); Minecraft mc = Minecraft.getInstance();
if (mc.currentScreen instanceof ItemTerminalGui) if (mc.screen instanceof ItemTerminalGui terminal)
((ItemTerminalGui) mc.currentScreen).updateItemList(message.items, message.craftables, message.currentlyCrafting); terminal.updateItemList(message.items, message.craftables, message.currentlyCrafting);
} }
}); });
ctx.get().setPacketHandled(true); ctx.get().setPacketHandled(true);

View file

@ -1,12 +1,16 @@
package de.ellpeck.prettypipes.packets; package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.ItemTerminalTileEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.entity.player.PlayerEntity; 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.world.item.ItemStack;
import net.minecraft.network.PacketBuffer; import net.minecraft.network.PacketBuffer;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.network.NetworkEvent;
import java.util.function.Supplier; import java.util.function.Supplier;
@ -26,17 +30,17 @@ public class PacketRequest {
} }
public static PacketRequest fromBytes(PacketBuffer buf) { public static PacketRequest fromBytes(FriendlyByteBuf buf) {
PacketRequest packet = new PacketRequest(); PacketRequest packet = new PacketRequest();
packet.pos = buf.readBlockPos(); packet.pos = buf.readBlockPos();
packet.stack = buf.readItemStack(); packet.stack = buf.readItem();
packet.amount = buf.readVarInt(); packet.amount = buf.readVarInt();
return packet; return packet;
} }
public static void toBytes(PacketRequest packet, PacketBuffer buf) { public static void toBytes(PacketRequest packet, FriendlyByteBuf buf) {
buf.writeBlockPos(packet.pos); buf.writeBlockPos(packet.pos);
buf.writeItemStack(packet.stack); buf.writeItem(packet.stack);
buf.writeVarInt(packet.amount); buf.writeVarInt(packet.amount);
} }
@ -45,8 +49,8 @@ public class PacketRequest {
ctx.get().enqueueWork(new Runnable() { ctx.get().enqueueWork(new Runnable() {
@Override @Override
public void run() { public void run() {
PlayerEntity player = ctx.get().getSender(); Player player = ctx.get().getSender();
ItemTerminalTileEntity tile = Utility.getBlockEntity(ItemTerminalTileEntity.class, player.world, message.pos); ItemTerminalBlockEntity tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level, message.pos);
message.stack.setCount(message.amount); message.stack.setCount(message.amount);
tile.requestItem(player, message.stack); tile.requestItem(player, message.stack);
} }

View file

@ -1,8 +1,8 @@
package de.ellpeck.prettypipes.pipe; package de.ellpeck.prettypipes.pipe;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
public interface IPipeConnectable { public interface IPipeConnectable {

View file

@ -1,16 +1,13 @@
package de.ellpeck.prettypipes.pipe; package de.ellpeck.prettypipes.pipe;
import com.google.common.collect.ImmutableMap; import com.mojang.blaze3d.vertex.PoseStack;
import com.google.common.collect.Maps;
import com.mojang.blaze3d.matrix.MatrixStack;
import de.ellpeck.prettypipes.network.NetworkEdge; import de.ellpeck.prettypipes.network.NetworkEdge;
import de.ellpeck.prettypipes.network.PipeItem; import de.ellpeck.prettypipes.network.PipeItem;
import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.math.BlockPos; import net.minecraft.world.level.Level;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.common.util.INBTSerializable;
@ -31,9 +28,9 @@ public interface IPipeItem extends INBTSerializable<CompoundTag> {
void setDestination(BlockPos startInventory, BlockPos destInventory, GraphPath<BlockPos, NetworkEdge> path); void setDestination(BlockPos startInventory, BlockPos destInventory, GraphPath<BlockPos, NetworkEdge> path);
void updateInPipe(PipeTileEntity currPipe); void updateInPipe(PipeBlockEntity currPipe);
void drop(World world, ItemStack stack); void drop(Level world, ItemStack stack);
BlockPos getDestPipe(); BlockPos getDestPipe();
@ -44,7 +41,7 @@ public interface IPipeItem extends INBTSerializable<CompoundTag> {
int getItemsOnTheWay(BlockPos goalInv); int getItemsOnTheWay(BlockPos goalInv);
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
void render(PipeTileEntity tile, MatrixStack matrixStack, Random random, float partialTicks, int light, int overlay, IRenderTypeBuffer buffer); void render(PipeBlockEntity tile, PoseStack matrixStack, Random random, float partialTicks, int light, int overlay);
static IPipeItem load(CompoundTag nbt) { static IPipeItem load(CompoundTag nbt) {
// TODO legacy compat, remove eventually // TODO legacy compat, remove eventually

View file

@ -5,49 +5,33 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.fluid.Fluids;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.tags.FluidTags;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.state.EnumProperty; import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.state.StateContainer; import net.minecraft.world.level.BlockGetter;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tags.FluidTags;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.shapes.IBooleanFunction;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.World;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.block.state.properties.EnumProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.BooleanOp;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.ItemHandlerHelper;
@ -91,7 +75,7 @@ public class PipeBlock extends BaseEntityBlock {
@Override @Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) { public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, worldIn, pos); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile == null) if (tile == null)
return InteractionResult.PASS; return InteractionResult.PASS;
if (!tile.canHaveModules()) if (!tile.canHaveModules())
@ -114,62 +98,62 @@ public class PipeBlock extends BaseEntityBlock {
} }
@Override @Override
protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) { protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(DIRECTIONS.values().toArray(new EnumProperty[0])); builder.add(DIRECTIONS.values().toArray(new EnumProperty[0]));
builder.add(BlockStateProperties.WATERLOGGED); builder.add(BlockStateProperties.WATERLOGGED);
} }
@Override @Override
public FluidState getFluidState(BlockState state) { public FluidState getFluidState(BlockState state) {
return state.get(BlockStateProperties.WATERLOGGED) ? Fluids.WATER.getStillFluidState(false) : super.getFluidState(state); return state.getValue(BlockStateProperties.WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state);
} }
@Override @Override
public void neighborChanged(BlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) { public void neighborChanged(BlockState state, Level worldIn, BlockPos pos, Block blockIn, BlockPos fromPos, boolean isMoving) {
BlockState newState = this.createState(worldIn, pos, state); BlockState newState = this.createState(worldIn, pos, state);
if (newState != state) { if (newState != state) {
worldIn.setBlockState(pos, newState); worldIn.setBlockAndUpdate(pos, newState);
onStateChanged(worldIn, pos, newState); onStateChanged(worldIn, pos, newState);
} }
} }
@Nullable @Nullable
@Override @Override
public BlockState getStateForPlacement(BlockItemUseContext context) { public BlockState getStateForPlacement(BlockPlaceContext context) {
return this.createState(context.getWorld(), context.getPos(), this.getDefaultState()); return this.createState(context.getLevel(), context.getClickedPos(), this.defaultBlockState());
} }
@Override @Override
public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) { public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor worldIn, BlockPos currentPos, BlockPos facingPos) {
if (stateIn.get(BlockStateProperties.WATERLOGGED)) if (stateIn.getValue(BlockStateProperties.WATERLOGGED))
worldIn.getPendingFluidTicks().scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickRate(worldIn)); worldIn.scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickDelay(worldIn));
return super.updatePostPlacement(stateIn, facing, facingState, worldIn, currentPos, facingPos); return super.updateShape(stateIn, facing, facingState, worldIn, currentPos, facingPos);
} }
@Override @Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { public void setPlacedBy(Level worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
onStateChanged(worldIn, pos, state); onStateChanged(worldIn, pos, state);
} }
@Override @Override
public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) { public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {
return this.cacheAndGetShape(state, worldIn, pos, s -> s.getShape(worldIn, pos, context), SHAPE_CACHE, null); return this.cacheAndGetShape(state, worldIn, pos, s -> s.getShape(worldIn, pos, context), SHAPE_CACHE, null);
} }
@Override @Override
public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) { 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 -> { 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 // make the shape a bit higher so we can jump up onto a higher block
MutableObject<VoxelShape> newShape = new MutableObject<>(VoxelShapes.empty()); MutableObject<VoxelShape> newShape = new MutableObject<>(Shapes.empty());
s.forEachBox((x1, y1, z1, x2, y2, z2) -> newShape.setValue(VoxelShapes.combine(VoxelShapes.create(x1, y1, z1, x2, y2 + 3 / 16F, z2), newShape.getValue(), IBooleanFunction.OR))); 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().simplify(); return newShape.getValue().optimize();
}); });
} }
private VoxelShape cacheAndGetShape(BlockState state, IBlockReader worldIn, BlockPos pos, Function<BlockState, VoxelShape> coverShapeSelector, Map<Pair<BlockState, BlockState>, VoxelShape> cache, Function<VoxelShape, VoxelShape> shapeModifier) { private VoxelShape cacheAndGetShape(BlockState state, BlockGetter worldIn, BlockPos pos, Function<BlockState, VoxelShape> coverShapeSelector, Map<Pair<BlockState, BlockState>, VoxelShape> cache, Function<VoxelShape, VoxelShape> shapeModifier) {
VoxelShape coverShape = null; VoxelShape coverShape = null;
BlockState cover = null; BlockState cover = null;
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, worldIn, pos); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile != null && tile.cover != null) { if (tile != null && tile.cover != null) {
cover = tile.cover; cover = tile.cover;
// try catch since the block might expect to find itself at the position // try catch since the block might expect to find itself at the position
@ -183,41 +167,41 @@ public class PipeBlock extends BaseEntityBlock {
if (shape == null) { if (shape == null) {
shape = CENTER_SHAPE; shape = CENTER_SHAPE;
for (Map.Entry<Direction, EnumProperty<ConnectionType>> entry : DIRECTIONS.entrySet()) { for (Map.Entry<Direction, EnumProperty<ConnectionType>> entry : DIRECTIONS.entrySet()) {
if (state.get(entry.getValue()).isConnected()) if (state.getValue(entry.getValue()).isConnected())
shape = VoxelShapes.or(shape, DIR_SHAPES.get(entry.getKey())); shape = Shapes.or(shape, DIR_SHAPES.get(entry.getKey()));
} }
if (shapeModifier != null) if (shapeModifier != null)
shape = shapeModifier.apply(shape); shape = shapeModifier.apply(shape);
if (coverShape != null) if (coverShape != null)
shape = VoxelShapes.or(shape, coverShape); shape = Shapes.or(shape, coverShape);
cache.put(key, shape); cache.put(key, shape);
} }
return shape; return shape;
} }
private BlockState createState(World world, BlockPos pos, BlockState curr) { private BlockState createState(Level world, BlockPos pos, BlockState curr) {
BlockState state = this.getDefaultState(); BlockState state = this.defaultBlockState();
FluidState fluid = world.getFluidState(pos); FluidState fluid = world.getFluidState(pos);
if (fluid.isTagged(FluidTags.WATER) && fluid.getLevel() == 8) if (fluid.is(FluidTags.WATER) && fluid.getAmount() == 8)
state = state.with(BlockStateProperties.WATERLOGGED, true); state = state.setValue(BlockStateProperties.WATERLOGGED, true);
for (Direction dir : Direction.values()) { for (Direction dir : Direction.values()) {
EnumProperty<ConnectionType> prop = DIRECTIONS.get(dir); EnumProperty<ConnectionType> prop = DIRECTIONS.get(dir);
ConnectionType type = this.getConnectionType(world, pos, dir, state); ConnectionType type = this.getConnectionType(world, pos, dir, state);
// don't reconnect on blocked faces // don't reconnect on blocked faces
if (type.isConnected() && curr.get(prop) == ConnectionType.BLOCKED) if (type.isConnected() && curr.getValue(prop) == ConnectionType.BLOCKED)
type = ConnectionType.BLOCKED; type = ConnectionType.BLOCKED;
state = state.with(prop, type); state = state.setValue(prop, type);
} }
return state; return state;
} }
protected ConnectionType getConnectionType(World world, BlockPos pos, Direction direction, BlockState state) { protected ConnectionType getConnectionType(Level world, BlockPos pos, Direction direction, BlockState state) {
BlockPos offset = pos.offset(direction); BlockPos offset = pos.relative(direction);
if (!world.isBlockLoaded(offset)) if (!world.isLoaded(offset))
return ConnectionType.DISCONNECTED; return ConnectionType.DISCONNECTED;
Direction opposite = direction.getOpposite(); Direction opposite = direction.getOpposite();
TileEntity tile = world.getTileEntity(offset); BlockEntity tile = world.getBlockEntity(offset);
if (tile != null) { if (tile != null) {
IPipeConnectable connectable = tile.getCapability(Registry.pipeConnectableCapability, opposite).orElse(null); IPipeConnectable connectable = tile.getCapability(Registry.pipeConnectableCapability, opposite).orElse(null);
if (connectable != null) if (connectable != null)
@ -231,23 +215,23 @@ public class PipeBlock extends BaseEntityBlock {
return ConnectionType.CONNECTED; return ConnectionType.CONNECTED;
BlockState offState = world.getBlockState(offset); BlockState offState = world.getBlockState(offset);
if (hasLegsTo(world, offState, offset, direction)) { if (hasLegsTo(world, offState, offset, direction)) {
if (DIRECTIONS.values().stream().noneMatch(d -> state.get(d) == ConnectionType.LEGS)) if (DIRECTIONS.values().stream().noneMatch(d -> state.getValue(d) == ConnectionType.LEGS))
return ConnectionType.LEGS; return ConnectionType.LEGS;
} }
return ConnectionType.DISCONNECTED; return ConnectionType.DISCONNECTED;
} }
protected static boolean hasLegsTo(World world, BlockState state, BlockPos pos, Direction direction) { protected static boolean hasLegsTo(Level world, BlockState state, BlockPos pos, Direction direction) {
if (state.getBlock() instanceof WallBlock || state.getBlock() instanceof FenceBlock) if (state.getBlock() instanceof WallBlock || state.getBlock() instanceof FenceBlock)
return direction == Direction.DOWN; return direction == Direction.DOWN;
if (state.getMaterial() == Material.ROCK || state.getMaterial() == Material.IRON) if (state.getMaterial() == Material.STONE || state.getMaterial() == Material.METAL)
return hasEnoughSolidSide(world, pos, direction.getOpposite()); return canSupportCenter(world, pos, direction.getOpposite());
return false; return false;
} }
public static void onStateChanged(World world, BlockPos pos, BlockState newState) { 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 // wait a few ticks before checking if we have to drop our modules, so that things like iron -> gold chest work
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, world, pos); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, world, pos);
if (tile != null) if (tile != null)
tile.moduleDropCheck = 5; tile.moduleDropCheck = 5;
@ -255,11 +239,11 @@ public class PipeBlock extends BaseEntityBlock {
int connections = 0; int connections = 0;
boolean force = false; boolean force = false;
for (Direction dir : Direction.values()) { for (Direction dir : Direction.values()) {
ConnectionType value = newState.get(DIRECTIONS.get(dir)); ConnectionType value = newState.getValue(DIRECTIONS.get(dir));
if (!value.isConnected()) if (!value.isConnected())
continue; continue;
connections++; connections++;
BlockState otherState = world.getBlockState(pos.offset(dir)); BlockState otherState = world.getBlockState(pos.relative(dir));
// force a node if we're connecting to a different block (inventory etc.) // force a node if we're connecting to a different block (inventory etc.)
if (otherState.getBlock() != newState.getBlock()) { if (otherState.getBlock() != newState.getBlock()) {
force = true; force = true;
@ -275,53 +259,53 @@ public class PipeBlock extends BaseEntityBlock {
} }
@Override @Override
public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) { public void onRemove(BlockState state, Level worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
if (state.getBlock() != newState.getBlock()) { if (state.getBlock() != newState.getBlock()) {
PipeNetwork network = PipeNetwork.get(worldIn); PipeNetwork network = PipeNetwork.get(worldIn);
network.removeNode(pos); network.removeNode(pos);
network.onPipeChanged(pos, state); network.onPipeChanged(pos, state);
super.onReplaced(state, worldIn, pos, newState, isMoving); super.onRemove(state, worldIn, pos, newState, isMoving);
} }
} }
@Override @Override
public void onBlockHarvested(World worldIn, BlockPos pos, BlockState state, PlayerEntity player) { public void playerWillDestroy(Level worldIn, BlockPos pos, BlockState state, Player player) {
dropItems(worldIn, pos, player); dropItems(worldIn, pos, player);
super.onBlockHarvested(worldIn, pos, state, player); super.playerWillDestroy(worldIn, pos, state, player);
} }
@Override @Override
public boolean hasComparatorInputOverride(BlockState state) { public boolean hasAnalogOutputSignal(BlockState state) {
return true; return true;
} }
@Override @Override
public int getComparatorInputOverride(BlockState blockState, World worldIn, BlockPos pos) { public int getAnalogOutputSignal(BlockState state, Level world, BlockPos pos) {
PipeTileEntity pipe = Utility.getBlockEntity(PipeTileEntity.class, worldIn, pos); PipeBlockEntity pipe = Utility.getBlockEntity(PipeBlockEntity.class, world, pos);
if (pipe == null) if (pipe == null)
return 0; return 0;
return Math.min(15, pipe.getItems().size()); return Math.min(15, pipe.getItems().size());
} }
@Nullable @org.jetbrains.annotations.Nullable
@Override @Override
public TileEntity createNewTileEntity(IBlockReader worldIn) { public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return new PipeTileEntity(); return new PipeBlockEntity();
} }
@Override @Override
public BlockRenderType getRenderType(BlockState state) { public RenderShape getRenderShape(BlockState state) {
return BlockRenderType.MODEL; return RenderShape.MODEL;
} }
public static void dropItems(World worldIn, BlockPos pos, PlayerEntity player) { public static void dropItems(Level worldIn, BlockPos pos, Player player) {
PipeTileEntity tile = Utility.getBlockEntity(PipeTileEntity.class, worldIn, pos); PipeBlockEntity tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile != null) { if (tile != null) {
Utility.dropInventory(tile, tile.modules); Utility.dropInventory(tile, tile.modules);
for (IPipeItem item : tile.getItems()) for (IPipeItem item : tile.getItems())
item.drop(worldIn, item.getContent()); item.drop(worldIn, item.getContent());
if (tile.cover != null) if (tile.cover != null)
tile.removeCover(player, Hand.MAIN_HAND); tile.removeCover(player, InteractionHand.MAIN_HAND);
} }
} }
} }

View file

@ -13,6 +13,7 @@ import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Container;
@ -20,6 +21,10 @@ import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.Containers;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NBTUtil; import net.minecraft.nbt.NBTUtil;
@ -35,6 +40,8 @@ import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent; 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.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.server.ServerWorld; import net.minecraft.world.server.ServerWorld;
@ -57,7 +64,7 @@ import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
public class PipeTileEntity extends BlockEntity implements INamedContainerProvider, ITickableTileEntity, IPipeConnectable { public class PipeBlockEntity extends BaseContainerBlockEntity implements IPipeConnectable {
public final ItemStackHandler modules = new ItemStackHandler(3) { public final ItemStackHandler modules = new ItemStackHandler(3) {
@Override @Override
@ -65,7 +72,7 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
var item = stack.getItem(); var item = stack.getItem();
if (!(item instanceof IModule module)) if (!(item instanceof IModule module))
return false; return false;
return PipeTileEntity.this.streamModules().allMatch(m -> module.isCompatible(stack, PipeTileEntity.this, m.getRight()) && m.getRight().isCompatible(m.getLeft(), PipeTileEntity.this, module)); return PipeBlockEntity.this.streamModules().allMatch(m -> module.isCompatible(stack, PipeBlockEntity.this, m.getRight()) && m.getRight().isCompatible(m.getLeft(), PipeBlockEntity.this, module));
} }
@Override @Override
@ -81,7 +88,7 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
protected List<IPipeItem> items; protected List<IPipeItem> items;
private int lastItemAmount; private int lastItemAmount;
private int priority; private int priority;
private final LazyOptional<PipeTileEntity> lazyThis = LazyOptional.of(() -> this); private final LazyOptional<PipeBlockEntity> lazyThis = LazyOptional.of(() -> this);
private final Lazy<Integer> workRandomizer = Lazy.of(() -> this.level.random.nextInt(200)); private final Lazy<Integer> workRandomizer = Lazy.of(() -> this.level.random.nextInt(200));
@Override @Override
@ -338,21 +345,21 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
IItemHandler handler = this.getNeighborCap(dir, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY); IItemHandler handler = this.getNeighborCap(dir, CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
if (handler != null) if (handler != null)
return handler; return handler;
return Utility.getBlockItemHandler(this.world, this.pos.offset(dir), dir.getOpposite()); return Utility.getBlockItemHandler(this.level, this.worldPosition.relative(dir), dir.getOpposite());
} }
public <T> T getNeighborCap(Direction dir, Capability<T> cap) { public <T> T getNeighborCap(Direction dir, Capability<T> cap) {
if (!this.isConnected(dir)) if (!this.isConnected(dir))
return null; return null;
BlockPos pos = this.pos.offset(dir); BlockPos pos = this.worldPosition.relative(dir);
TileEntity tile = this.world.getTileEntity(pos); BlockEntity tile = this.level.getBlockEntity(pos);
if (tile != null) if (tile != null)
return tile.getCapability(cap, dir.getOpposite()).orElse(null); return tile.getCapability(cap, dir.getOpposite()).orElse(null);
return null; return null;
} }
public IPipeConnectable getPipeConnectable(Direction dir) { public IPipeConnectable getPipeConnectable(Direction dir) {
TileEntity tile = this.world.getTileEntity(this.pos.offset(dir)); BlockEntity tile = this.level.getBlockEntity(this.worldPosition.relative(dir));
if (tile != null) if (tile != null)
return tile.getCapability(Registry.pipeConnectableCapability, dir.getOpposite()).orElse(null); return tile.getCapability(Registry.pipeConnectableCapability, dir.getOpposite()).orElse(null);
return null; return null;
@ -367,7 +374,7 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
if (this.isConnectedInventory(dir)) if (this.isConnectedInventory(dir))
return true; return true;
IPipeConnectable connectable = this.getPipeConnectable(dir); IPipeConnectable connectable = this.getPipeConnectable(dir);
if (connectable != null && connectable.allowsModules(this.pos, dir)) if (connectable != null && connectable.allowsModules(this.worldPosition, dir))
return true; return true;
} }
return false; return false;
@ -388,17 +395,17 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
return builder.build(); return builder.build();
} }
public void removeCover(PlayerEntity player, Hand hand) { public void removeCover(Player player, InteractionHand hand) {
if (this.world.isRemote) if (this.level.isRemote)
return; return;
List<ItemStack> drops = Block.getDrops(this.cover, (ServerWorld) this.world, this.pos, null, player, player.getHeldItem(hand)); List<ItemStack> drops = Block.getDrops(this.cover, (ServerLevel) this.level, this.worldPosition, null, player, player.getItemInHand(hand));
for (ItemStack drop : drops) for (ItemStack drop : drops)
Block.spawnAsEntity(this.world, this.pos, drop); Containers.dropItemStack(this.level, this.worldPosition.getX(), this.worldPosition.getY(), this.worldPosition.getZ(), drop);
this.cover = null; this.cover = null;
} }
public boolean shouldWorkNow(int speed) { public boolean shouldWorkNow(int speed) {
return (this.world.getGameTime() + this.workRandomizer.get()) % speed == 0; return (this.level.getGameTime() + this.workRandomizer.get()) % speed == 0;
} }
public int getNextNode(List<BlockPos> nodes, int index) { public int getNextNode(List<BlockPos> nodes, int index) {
@ -414,10 +421,10 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
} }
@Override @Override
public void remove() { public void setRemoved() {
super.remove(); super.setRemoved();
this.getItems().clear(); this.getItems().clear();
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
for (NetworkLock lock : this.craftIngredientRequests) for (NetworkLock lock : this.craftIngredientRequests)
network.resolveNetworkLock(lock); network.resolveNetworkLock(lock);
this.lazyThis.invalidate(); this.lazyThis.invalidate();
@ -431,7 +438,7 @@ public class PipeTileEntity extends BlockEntity implements INamedContainerProvid
@Nullable @Nullable
@Override @Override
public Container createMenu(int window, PlayerInventory inv, PlayerEntity player) { public Container createMenu(int window, PlayerInventory inv, PlayerEntity player) {
return new MainPipeContainer(Registry.pipeContainer, window, player, PipeTileEntity.this.pos); return new MainPipeContainer(Registry.pipeContainer, window, player, PipeBlockEntity.this.pos);
} }
@Override @Override

View file

@ -1,54 +1,45 @@
package de.ellpeck.prettypipes.pipe; package de.ellpeck.prettypipes.pipe;
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.BlockModelRenderer; import net.minecraft.core.BlockPos;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.model.data.EmptyModelData; import net.minecraftforge.client.model.pipeline.ForgeBlockModelRenderer;
import java.util.Random; import java.util.Random;
public class PipeRenderer extends TileEntityRenderer<PipeTileEntity> { public class PipeRenderer implements BlockEntityRenderer<PipeBlockEntity> {
private final Random random = new Random(); private final Random random = new Random();
public PipeRenderer(TileEntityRendererDispatcher disp) {
super(disp);
}
@Override @Override
public void render(PipeTileEntity tile, float partialTicks, MatrixStack matrixStack, IRenderTypeBuffer buffer, int light, int overlay) { public void render(PipeBlockEntity tile, float partialTicks, PoseStack matrixStack, MultiBufferSource source, int light, int overlay) {
if (!tile.getItems().isEmpty()) { if (!tile.getItems().isEmpty()) {
matrixStack.push(); matrixStack.pushPose();
BlockPos tilePos = tile.getPos(); BlockPos tilePos = tile.getBlockPos();
matrixStack.translate(-tilePos.getX(), -tilePos.getY(), -tilePos.getZ()); matrixStack.translate(-tilePos.getX(), -tilePos.getY(), -tilePos.getZ());
for (IPipeItem item : tile.getItems()) { for (IPipeItem item : tile.getItems()) {
matrixStack.push(); matrixStack.pushPose();
item.render(tile, matrixStack, this.random, partialTicks, light, overlay, buffer); item.render(tile, matrixStack, this.random, partialTicks, light, overlay);
matrixStack.pop(); matrixStack.popPose();
} }
matrixStack.pop(); matrixStack.popPose();
} }
if (tile.cover != null) { if (tile.cover != null) {
matrixStack.push(); matrixStack.pushPose();
BlockModelRenderer.enableCache(); ForgeBlockModelRenderer.enableCaching();
for (RenderType layer : RenderType.getBlockRenderTypes()) { // TODO figure out how to render covers, maybe finally use baked models bleh
/*for (RenderType layer : RenderType.chunkBufferLayers()) {
if (!RenderTypeLookup.canRenderInLayer(tile.cover, layer)) if (!RenderTypeLookup.canRenderInLayer(tile.cover, layer))
continue; continue;
ForgeHooksClient.setRenderLayer(layer); ForgeHooksClient.setRenderType(layer);
Minecraft.getInstance().getBlockRendererDispatcher().renderBlock(tile.cover, matrixStack, buffer, light, overlay, EmptyModelData.INSTANCE); Minecraft.getInstance().getBlockRenderer().renderBatched(tile.cover,tile.getBlockPos(),null, matrixStack,null, light, overlay, EmptyModelData.INSTANCE);
} }*/
ForgeHooksClient.setRenderLayer(null); ForgeHooksClient.setRenderType(null);
BlockModelRenderer.disableCache(); ForgeBlockModelRenderer.clearCache();
matrixStack.pop(); matrixStack.popPose();
} }
} }
} }

View file

@ -3,28 +3,28 @@ package de.ellpeck.prettypipes.pipe.containers;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.misc.FilterSlot; import de.ellpeck.prettypipes.misc.FilterSlot;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.core.BlockPos;
import net.minecraft.inventory.container.ClickType; import net.minecraft.world.entity.player.Player;
import net.minecraft.inventory.container.Container; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.inventory.container.ContainerType; import net.minecraft.world.inventory.ClickType;
import net.minecraft.inventory.container.Slot; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public abstract class AbstractPipeContainer<T extends IModule> extends Container { public abstract class AbstractPipeContainer<T extends IModule> extends AbstractContainerMenu {
public final PipeTileEntity tile; public final PipeBlockEntity tile;
public final T module; public final T module;
public final int moduleIndex; public final int moduleIndex;
public final ItemStack moduleStack; public final ItemStack moduleStack;
public AbstractPipeContainer(@Nullable ContainerType<?> type, int id, PlayerEntity player, BlockPos pos, int moduleIndex) { public AbstractPipeContainer(@Nullable MenuType<?> type, int id, Player player, BlockPos pos, int moduleIndex) {
super(type, id); super(type, id);
this.tile = Utility.getBlockEntity(PipeTileEntity.class, player.world, pos); this.tile = Utility.getBlockEntity(PipeBlockEntity.class, player.level, pos);
this.moduleStack = moduleIndex < 0 ? null : this.tile.modules.getStackInSlot(moduleIndex); this.moduleStack = moduleIndex < 0 ? null : this.tile.modules.getStackInSlot(moduleIndex);
this.module = moduleIndex < 0 ? null : (T) this.moduleStack.getItem(); this.module = moduleIndex < 0 ? null : (T) this.moduleStack.getItem();
this.moduleIndex = moduleIndex; this.moduleIndex = moduleIndex;
@ -32,23 +32,18 @@ public abstract class AbstractPipeContainer<T extends IModule> extends Container
// needs to be done here so transferStackInSlot works correctly, bleh // needs to be done here so transferStackInSlot works correctly, bleh
this.addSlots(); this.addSlots();
for (int l = 0; l < 3; ++l) for (var l = 0; l < 3; ++l)
for (int j1 = 0; j1 < 9; ++j1) for (var j1 = 0; j1 < 9; ++j1)
this.addSlot(new Slot(player.inventory, j1 + l * 9 + 9, 8 + j1 * 18, 89 + l * 18 + 32)); this.addSlot(new Slot(player.getInventory(), j1 + l * 9 + 9, 8 + j1 * 18, 89 + l * 18 + 32));
for (int i1 = 0; i1 < 9; ++i1) for (var i1 = 0; i1 < 9; ++i1)
this.addSlot(new Slot(player.inventory, i1, 8 + i1 * 18, 147 + 32)); this.addSlot(new Slot(player.getInventory(), i1, 8 + i1 * 18, 147 + 32));
} }
protected abstract void addSlots(); protected abstract void addSlots();
@Override @Override
public boolean canInteractWith(PlayerEntity playerIn) { public ItemStack quickMoveStack(Player player, int slotIndex) {
return true; return Utility.transferStackInSlot(this, this::moveItemStackTo, player, slotIndex, stack -> {
}
@Override
public ItemStack transferStackInSlot(PlayerEntity player, int slotIndex) {
return Utility.transferStackInSlot(this, this::mergeItemStack, player, slotIndex, stack -> {
if (stack.getItem() instanceof IModule) if (stack.getItem() instanceof IModule)
return Pair.of(0, 3); return Pair.of(0, 3);
return null; return null;
@ -56,9 +51,14 @@ public abstract class AbstractPipeContainer<T extends IModule> extends Container
} }
@Override @Override
public ItemStack slotClick(int slotId, int dragType, ClickType clickTypeIn, PlayerEntity player) { public void clicked(int slotId, int dragType, ClickType clickTypeIn, Player player) {
if (FilterSlot.checkFilter(this, slotId, player)) if (FilterSlot.checkFilter(this, slotId, player))
return ItemStack.EMPTY; return;
return super.slotClick(slotId, dragType, clickTypeIn, player); super.clicked(slotId, dragType, clickTypeIn, player);
}
@Override
public boolean stillValid(Player player) {
return true;
} }
} }

View file

@ -1,16 +1,26 @@
package de.ellpeck.prettypipes.pipe.containers; package de.ellpeck.prettypipes.pipe.containers;
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.PoseStack;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.packets.PacketButton; import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.packets.PacketHandler; import de.ellpeck.prettypipes.packets.PacketHandler;
import net.minecraft.client.audio.SimpleSound; 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.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.gui.widget.Widget;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Slot; import net.minecraft.inventory.container.Slot;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.SoundEvents; import net.minecraft.util.SoundEvents;
@ -19,16 +29,16 @@ import net.minecraft.util.text.ITextComponent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extends ContainerScreen<T> { public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extends AbstractContainerScreen<T> {
protected static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/pipe.png"); protected static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/pipe.png");
private final List<Tab> tabs = new ArrayList<>(); private final List<Tab> tabs = new ArrayList<>();
private final ItemStack[] lastItems = new ItemStack[this.container.tile.modules.getSlots()]; private final ItemStack[] lastItems = new ItemStack[this.menu.tile.modules.getSlots()];
public AbstractPipeGui(T screenContainer, PlayerInventory inv, ITextComponent titleIn) { public AbstractPipeGui(T screenContainer, Inventory inv, Component titleIn) {
super(screenContainer, inv, titleIn); super(screenContainer, inv, titleIn);
this.xSize = 176; this.imageWidth = 176;
this.ySize = 171 + 32; this.imageHeight = 171 + 32;
} }
@Override @Override
@ -38,12 +48,12 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
} }
@Override @Override
public void tick() { public void containerTick() {
super.tick(); super.containerTick();
boolean changed = false; boolean changed = false;
for (int i = 0; i < this.container.tile.modules.getSlots(); i++) { for (int i = 0; i < this.menu.tile.modules.getSlots(); i++) {
ItemStack stack = this.container.tile.modules.getStackInSlot(i); ItemStack stack = this.menu.tile.modules.getStackInSlot(i);
if (stack != this.lastItems[i]) { if (stack != this.lastItems[i]) {
this.lastItems[i] = stack; this.lastItems[i] = stack;
changed = true; changed = true;
@ -54,28 +64,30 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
} }
@Override @Override
public void render(MatrixStack matrix, int mouseX, int mouseY, float partialTicks) { public void render(PoseStack matrix, int mouseX, int mouseY, float partialTicks) {
this.renderBackground(matrix); this.renderBackground(matrix);
super.render(matrix, mouseX, mouseY, partialTicks); super.render(matrix, mouseX, mouseY, partialTicks);
for (Widget widget : this.buttons) { for (Widget widget : this.renderables) {
if (widget.isHovered()) if (widget instanceof AbstractWidget abstractWidget) {
widget.renderToolTip(matrix, mouseX, mouseY); if (abstractWidget.isHoveredOrFocused())
abstractWidget.renderToolTip(matrix, mouseX, mouseY);
}
} }
this.func_230459_a_(matrix, mouseX, mouseY); this.renderTooltip(matrix, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerForegroundLayer(MatrixStack matrix, int mouseX, int mouseY) { protected void renderLabels(PoseStack matrix, int mouseX, int mouseY) {
this.font.drawString(matrix, this.playerInventory.getDisplayName().getString(), 8, this.ySize - 96 + 2, 4210752); this.font.draw(matrix, this.playerInventoryTitle.getString(), 8, this.imageHeight - 96 + 2, 4210752);
this.font.drawString(matrix, this.title.getString(), 8, 6 + 32, 4210752); this.font.draw(matrix, this.title.getString(), 8, 6 + 32, 4210752);
for (Tab tab : this.tabs) for (Tab tab : this.tabs)
tab.drawForeground(matrix, mouseX, mouseY); tab.drawForeground(matrix, mouseX, mouseY);
} }
@Override @Override
protected void drawGuiContainerBackgroundLayer(MatrixStack matrix, float partialTicks, int mouseX, int mouseY) { protected void renderBg(PoseStack matrix, float partialTicks, int mouseX, int mouseY) {
this.getMinecraft().getTextureManager().bindTexture(TEXTURE); this.getMinecraft().getTextureManager().bindForSetup(TEXTURE);
this.blit(matrix, this.guiLeft, this.guiTop + 32, 0, 0, 176, 171); this.blit(matrix, this.leftPos, this.topPos + 32, 0, 0, 176, 171);
for (Tab tab : this.tabs) for (Tab tab : this.tabs)
tab.draw(matrix); tab.draw(matrix);
@ -111,6 +123,7 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
} }
private class Tab { private class Tab {
private final ItemStack moduleStack; private final ItemStack moduleStack;
private final int index; private final int index;
private final int x; private final int x;
@ -119,16 +132,16 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
public Tab(ItemStack moduleStack, int tabIndex, int index) { public Tab(ItemStack moduleStack, int tabIndex, int index) {
this.moduleStack = moduleStack; this.moduleStack = moduleStack;
this.index = index; this.index = index;
this.x = AbstractPipeGui.this.guiLeft + 5 + tabIndex * 28; this.x = AbstractPipeGui.this.leftPos + 5 + tabIndex * 28;
this.y = AbstractPipeGui.this.guiTop; this.y = AbstractPipeGui.this.topPos;
} }
private void draw(MatrixStack matrix) { private void draw(PoseStack matrix) {
int y = 2; int y = 2;
int v = 0; int v = 0;
int height = 30; int height = 30;
int itemOffset = 9; int itemOffset = 9;
if (this.index == AbstractPipeGui.this.container.moduleIndex) { if (this.index == AbstractPipeGui.this.menu.moduleIndex) {
y = 0; y = 0;
v = 30; v = 30;
height = 32; height = 32;
@ -136,25 +149,25 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
} }
AbstractPipeGui.this.blit(matrix, this.x, this.y + y, 176, v, 28, height); AbstractPipeGui.this.blit(matrix, this.x, this.y + y, 176, v, 28, height);
AbstractPipeGui.this.itemRenderer.renderItemIntoGUI(this.moduleStack, this.x + 6, this.y + itemOffset); AbstractPipeGui.this.itemRenderer.renderGuiItem(this.moduleStack, this.x + 6, this.y + itemOffset);
AbstractPipeGui.this.getMinecraft().getTextureManager().bindTexture(TEXTURE); AbstractPipeGui.this.getMinecraft().getTextureManager().bindForSetup(TEXTURE);
} }
private void drawForeground(MatrixStack matrix, int mouseX, int mouseY) { private void drawForeground(PoseStack matrix, int mouseX, int mouseY) {
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32) if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32)
return; 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.guiLeft, mouseY - AbstractPipeGui.this.guiTop);
} }
private boolean onClicked(double mouseX, double mouseY, int button) { private boolean onClicked(double mouseX, double mouseY, int button) {
if (this.index == AbstractPipeGui.this.container.moduleIndex) if (this.index == AbstractPipeGui.this.menu.moduleIndex)
return false; return false;
if (button != 0) if (button != 0)
return false; return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32) if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32)
return false; return false;
PacketHandler.sendToServer(new PacketButton(AbstractPipeGui.this.container.tile.getPos(), PacketButton.ButtonResult.PIPE_TAB, this.index)); PacketHandler.sendToServer(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, this.index));
AbstractPipeGui.this.getMinecraft().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1)); AbstractPipeGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true; return true;
} }
} }

View file

@ -1,15 +1,16 @@
package de.ellpeck.prettypipes.pipe.containers; package de.ellpeck.prettypipes.pipe.containers;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.core.BlockPos;
import net.minecraft.inventory.container.ContainerType; import net.minecraft.world.entity.player.Player;
import net.minecraft.util.math.BlockPos; import net.minecraft.world.inventory.MenuType;
import net.minecraftforge.items.SlotItemHandler; import net.minecraftforge.items.SlotItemHandler;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class MainPipeContainer extends AbstractPipeContainer<IModule> { public class MainPipeContainer extends AbstractPipeContainer<IModule> {
public MainPipeContainer(@Nullable ContainerType<?> type, int id, PlayerEntity player, BlockPos pos) {
public MainPipeContainer(@Nullable MenuType<?> type, int id, Player player, BlockPos pos) {
super(type, id, player, pos, -1); super(type, id, player, pos, -1);
} }

View file

@ -1,10 +1,13 @@
package de.ellpeck.prettypipes.pipe.containers; package de.ellpeck.prettypipes.pipe.containers;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.chat.Component;
import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.entity.player.Inventory;
public class MainPipeGui extends AbstractPipeGui<MainPipeContainer> { public class MainPipeGui extends AbstractPipeGui<MainPipeContainer> {
public MainPipeGui(MainPipeContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) {
public MainPipeGui(MainPipeContainer screenContainer, Inventory inv, Component titleIn) {
super(screenContainer, inv, titleIn); super(screenContainer, inv, titleIn);
} }
} }

View file

@ -3,7 +3,7 @@ package de.ellpeck.prettypipes.pipe.modules;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier; import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
public class HighPriorityModuleItem extends ModuleItem { public class HighPriorityModuleItem extends ModuleItem {
@ -15,17 +15,17 @@ public class HighPriorityModuleItem extends ModuleItem {
} }
@Override @Override
public int getPriority(ItemStack module, PipeTileEntity tile) { public int getPriority(ItemStack module, PipeBlockEntity tile) {
return this.priority; return this.priority;
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof HighPriorityModuleItem) && !(other instanceof LowPriorityModuleItem); return !(other instanceof HighPriorityModuleItem) && !(other instanceof LowPriorityModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
} }

View file

@ -3,7 +3,7 @@ package de.ellpeck.prettypipes.pipe.modules;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier; import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
public class LowPriorityModuleItem extends ModuleItem { public class LowPriorityModuleItem extends ModuleItem {
@ -15,17 +15,17 @@ public class LowPriorityModuleItem extends ModuleItem {
} }
@Override @Override
public int getPriority(ItemStack module, PipeTileEntity tile) { public int getPriority(ItemStack module, PipeBlockEntity tile) {
return this.priority; return this.priority;
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof LowPriorityModuleItem) && !(other instanceof HighPriorityModuleItem); return !(other instanceof LowPriorityModuleItem) && !(other instanceof HighPriorityModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
} }

View file

@ -2,7 +2,7 @@ package de.ellpeck.prettypipes.pipe.modules;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
public class RedstoneModuleItem extends ModuleItem { public class RedstoneModuleItem extends ModuleItem {
@ -13,17 +13,17 @@ public class RedstoneModuleItem extends ModuleItem {
} }
@Override @Override
public boolean canPipeWork(ItemStack module, PipeTileEntity tile) { public boolean canPipeWork(ItemStack module, PipeBlockEntity tile) {
return !tile.getWorld().isBlockPowered(tile.getPos()); return !tile.getWorld().isBlockPowered(tile.getPos());
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return other != this; return other != this;
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
} }

View file

@ -2,7 +2,7 @@ package de.ellpeck.prettypipes.pipe.modules;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@ -19,17 +19,17 @@ public class SortingModuleItem extends ModuleItem {
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof SortingModuleItem); return !(other instanceof SortingModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
@Override @Override
public Integer getCustomNextNode(ItemStack module, PipeTileEntity tile, List<BlockPos> nodes, int index) { public Integer getCustomNextNode(ItemStack module, PipeBlockEntity tile, List<BlockPos> nodes, int index) {
switch (this.type) { switch (this.type) {
case ROUND_ROBIN: case ROUND_ROBIN:
// store an ever-increasing index and choose destinations based on that // store an ever-increasing index and choose destinations based on that

View file

@ -3,7 +3,7 @@ package de.ellpeck.prettypipes.pipe.modules;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier; import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
public class SpeedModuleItem extends ModuleItem { public class SpeedModuleItem extends ModuleItem {
@ -15,17 +15,17 @@ public class SpeedModuleItem extends ModuleItem {
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof SpeedModuleItem); return !(other instanceof SpeedModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
@Override @Override
public float getItemSpeedIncrease(ItemStack module, PipeTileEntity tile) { public float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile) {
return this.speedIncrease; return this.speedIncrease;
} }
} }

View file

@ -9,10 +9,10 @@ import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.network.NetworkLocation; import de.ellpeck.prettypipes.network.NetworkLocation;
import de.ellpeck.prettypipes.network.NetworkLock; import de.ellpeck.prettypipes.network.NetworkLock;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import de.ellpeck.prettypipes.terminal.CraftingTerminalTileEntity; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalTileEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -41,32 +41,32 @@ public class CraftingModuleItem extends ModuleItem {
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return true; return true;
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new CraftingModuleContainer(Registry.craftingModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new CraftingModuleContainer(Registry.craftingModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }
@Override @Override
public boolean canNetworkSee(ItemStack module, PipeTileEntity tile) { public boolean canNetworkSee(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
@Override @Override
public boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack) { public boolean canAcceptItem(ItemStack module, PipeBlockEntity tile, ItemStack stack) {
return false; return false;
} }
@Override @Override
public void tick(ItemStack module, PipeTileEntity tile) { public void tick(ItemStack module, PipeBlockEntity tile) {
if (!tile.shouldWorkNow(this.speed) || !tile.canWork()) if (!tile.shouldWorkNow(this.speed) || !tile.canWork())
return; return;
PipeNetwork network = PipeNetwork.get(tile.getWorld()); PipeNetwork network = PipeNetwork.get(tile.getWorld());
@ -99,7 +99,7 @@ public class CraftingModuleItem extends ModuleItem {
ItemEquality[] equalityTypes = ItemFilter.getEqualityTypes(tile); ItemEquality[] equalityTypes = ItemFilter.getEqualityTypes(tile);
for (Pair<BlockPos, ItemStack> request : tile.craftResultRequests) { for (Pair<BlockPos, ItemStack> request : tile.craftResultRequests) {
ItemStack remain = request.getRight().copy(); ItemStack remain = request.getRight().copy();
PipeTileEntity destPipe = network.getPipe(request.getLeft()); PipeBlockEntity destPipe = network.getPipe(request.getLeft());
if (destPipe != null) { if (destPipe != null) {
Pair<BlockPos, ItemStack> dest = destPipe.getAvailableDestinationOrConnectable(remain, true, true); Pair<BlockPos, ItemStack> dest = destPipe.getAvailableDestinationOrConnectable(remain, true, true);
if (dest == null) if (dest == null)
@ -125,7 +125,7 @@ public class CraftingModuleItem extends ModuleItem {
} }
@Override @Override
public List<ItemStack> getAllCraftables(ItemStack module, PipeTileEntity tile) { public List<ItemStack> getAllCraftables(ItemStack module, PipeBlockEntity tile) {
List<ItemStack> ret = new ArrayList<>(); List<ItemStack> ret = new ArrayList<>();
ItemStackHandler output = this.getOutput(module); ItemStackHandler output = this.getOutput(module);
for (int i = 0; i < output.getSlots(); i++) { for (int i = 0; i < output.getSlots(); i++) {
@ -137,7 +137,7 @@ public class CraftingModuleItem extends ModuleItem {
} }
@Override @Override
public int getCraftableAmount(ItemStack module, PipeTileEntity tile, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) { public int getCraftableAmount(ItemStack module, PipeBlockEntity tile, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) {
PipeNetwork network = PipeNetwork.get(tile.getWorld()); PipeNetwork network = PipeNetwork.get(tile.getWorld());
List<NetworkLocation> items = network.getOrderedNetworkItems(tile.getPos()); List<NetworkLocation> items = network.getOrderedNetworkItems(tile.getPos());
ItemEquality[] equalityTypes = ItemFilter.getEqualityTypes(tile); ItemEquality[] equalityTypes = ItemFilter.getEqualityTypes(tile);
@ -149,7 +149,7 @@ public class CraftingModuleItem extends ModuleItem {
ItemStack out = output.getStackInSlot(i); ItemStack out = output.getStackInSlot(i);
if (!out.isEmpty() && ItemEquality.compareItems(out, stack, equalityTypes)) { if (!out.isEmpty() && ItemEquality.compareItems(out, stack, equalityTypes)) {
// figure out how many crafting operations we can actually do with the input items we have in the network // figure out how many crafting operations we can actually do with the input items we have in the network
int availableCrafts = CraftingTerminalTileEntity.getAvailableCrafts(tile, input.getSlots(), input::getStackInSlot, k -> true, s -> items, unavailableConsumer, addDependency(dependencyChain, module), equalityTypes); int availableCrafts = CraftingTerminalBlockEntity.getAvailableCrafts(tile, input.getSlots(), input::getStackInSlot, k -> true, s -> items, unavailableConsumer, addDependency(dependencyChain, module), equalityTypes);
if (availableCrafts > 0) if (availableCrafts > 0)
craftable += out.getCount() * availableCrafts; craftable += out.getCount() * availableCrafts;
} }
@ -158,7 +158,7 @@ public class CraftingModuleItem extends ModuleItem {
} }
@Override @Override
public ItemStack craft(ItemStack module, PipeTileEntity tile, BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) { public ItemStack craft(ItemStack module, PipeBlockEntity tile, BlockPos destPipe, Consumer<ItemStack> unavailableConsumer, ItemStack stack, Stack<ItemStack> dependencyChain) {
// check if we can craft the required amount of items // check if we can craft the required amount of items
int craftableAmount = this.getCraftableAmount(module, tile, unavailableConsumer, stack, dependencyChain); int craftableAmount = this.getCraftableAmount(module, tile, unavailableConsumer, stack, dependencyChain);
if (craftableAmount <= 0) if (craftableAmount <= 0)
@ -179,7 +179,7 @@ public class CraftingModuleItem extends ModuleItem {
continue; continue;
ItemStack copy = in.copy(); ItemStack copy = in.copy();
copy.setCount(in.getCount() * toCraft); copy.setCount(in.getCount() * toCraft);
Pair<List<NetworkLock>, ItemStack> ret = ItemTerminalTileEntity.requestItemLater(tile.getWorld(), tile.getPos(), items, unavailableConsumer, copy, addDependency(dependencyChain, module), equalityTypes); Pair<List<NetworkLock>, ItemStack> ret = ItemTerminalBlockEntity.requestItemLater(tile.getWorld(), tile.getPos(), items, unavailableConsumer, copy, addDependency(dependencyChain, module), equalityTypes);
tile.craftIngredientRequests.addAll(ret.getLeft()); tile.craftIngredientRequests.addAll(ret.getLeft());
} }

View file

@ -6,7 +6,7 @@ import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier; import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
@ -30,7 +30,7 @@ public class ExtractionModuleItem extends ModuleItem {
} }
@Override @Override
public void tick(ItemStack module, PipeTileEntity tile) { public void tick(ItemStack module, PipeBlockEntity tile) {
if (!tile.shouldWorkNow(this.speed) || !tile.canWork()) if (!tile.shouldWorkNow(this.speed) || !tile.canWork())
return; return;
ItemFilter filter = this.getItemFilter(module, tile); ItemFilter filter = this.getItemFilter(module, tile);
@ -56,32 +56,32 @@ public class ExtractionModuleItem extends ModuleItem {
} }
@Override @Override
public boolean canNetworkSee(ItemStack module, PipeTileEntity tile) { public boolean canNetworkSee(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
@Override @Override
public boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack) { public boolean canAcceptItem(ItemStack module, PipeBlockEntity tile, ItemStack stack) {
return false; return false;
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof ExtractionModuleItem); return !(other instanceof ExtractionModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new ExtractionModuleContainer(Registry.extractionModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new ExtractionModuleContainer(Registry.extractionModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }
@Override @Override
public ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile) { public ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile) {
return new ItemFilter(this.filterSlots, module, tile); return new ItemFilter(this.filterSlots, module, tile);
} }
} }

View file

@ -4,7 +4,7 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
@ -18,22 +18,22 @@ public class FilterIncreaseModuleItem extends ModuleItem {
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return true; return true;
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new FilterIncreaseModuleContainer(Registry.filterIncreaseModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new FilterIncreaseModuleContainer(Registry.filterIncreaseModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }
@Override @Override
public ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile) { public ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile) {
ItemFilter filter = new ItemFilter(18, module, tile); ItemFilter filter = new ItemFilter(18, module, tile);
filter.canModifyWhitelist = false; filter.canModifyWhitelist = false;
return filter; return filter;

View file

@ -5,7 +5,7 @@ import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier; import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
@ -23,28 +23,28 @@ public class FilterModuleItem extends ModuleItem {
} }
@Override @Override
public boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack) { public boolean canAcceptItem(ItemStack module, PipeBlockEntity tile, ItemStack stack) {
ItemFilter filter = this.getItemFilter(module, tile); ItemFilter filter = this.getItemFilter(module, tile);
return filter.isAllowed(stack); return filter.isAllowed(stack);
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof FilterModuleItem); return !(other instanceof FilterModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new FilterModuleContainer(Registry.filterModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new FilterModuleContainer(Registry.filterModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }
@Override @Override
public ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile) { public ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile) {
ItemFilter filter = new ItemFilter(this.filterSlots, module, tile); ItemFilter filter = new ItemFilter(this.filterSlots, module, tile);
filter.canPopulateFromInventories = this.canPopulateFromInventories; filter.canPopulateFromInventories = this.canPopulateFromInventories;
return filter; return filter;

View file

@ -4,7 +4,7 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import joptsimple.internal.Strings; import joptsimple.internal.Strings;
import net.minecraft.client.util.ITooltipFlag; import net.minecraft.client.util.ITooltipFlag;
@ -29,17 +29,17 @@ public class FilterModifierModuleItem extends ModuleItem {
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return other != this; return other != this;
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return this.type == ItemEquality.Type.TAG; return this.type == ItemEquality.Type.TAG;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new FilterModifierModuleContainer(Registry.filterModifierModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new FilterModifierModuleContainer(Registry.filterModifierModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }

View file

@ -7,7 +7,7 @@ import de.ellpeck.prettypipes.items.ModuleTier;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
@ -30,7 +30,7 @@ public class RetrievalModuleItem extends ModuleItem {
} }
@Override @Override
public void tick(ItemStack module, PipeTileEntity tile) { public void tick(ItemStack module, PipeBlockEntity tile) {
if (!tile.shouldWorkNow(this.speed) || !tile.canWork()) if (!tile.shouldWorkNow(this.speed) || !tile.canWork())
return; return;
PipeNetwork network = PipeNetwork.get(tile.getWorld()); PipeNetwork network = PipeNetwork.get(tile.getWorld());
@ -57,32 +57,32 @@ public class RetrievalModuleItem extends ModuleItem {
} }
@Override @Override
public boolean canNetworkSee(ItemStack module, PipeTileEntity tile) { public boolean canNetworkSee(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
@Override @Override
public boolean canAcceptItem(ItemStack module, PipeTileEntity tile, ItemStack stack) { public boolean canAcceptItem(ItemStack module, PipeBlockEntity tile, ItemStack stack) {
return false; return false;
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof RetrievalModuleItem); return !(other instanceof RetrievalModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new RetrievalModuleContainer(Registry.retrievalModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new RetrievalModuleContainer(Registry.retrievalModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }
@Override @Override
public ItemFilter getItemFilter(ItemStack module, PipeTileEntity tile) { public ItemFilter getItemFilter(ItemStack module, PipeBlockEntity tile) {
ItemFilter filter = new ItemFilter(this.filterSlots, module, tile); ItemFilter filter = new ItemFilter(this.filterSlots, module, tile);
filter.canModifyWhitelist = false; filter.canModifyWhitelist = false;
filter.isWhitelist = true; filter.isWhitelist = true;

View file

@ -4,7 +4,7 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
@ -42,7 +42,7 @@ public class StackSizeModuleItem extends ModuleItem {
} }
@Override @Override
public int getMaxInsertionAmount(ItemStack module, PipeTileEntity tile, ItemStack stack, IItemHandler destination) { public int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination) {
int max = getMaxStackSize(module); int max = getMaxStackSize(module);
if (getLimitToMaxStackSize(module)) if (getLimitToMaxStackSize(module))
max = Math.min(max, stack.getMaxStackSize()); max = Math.min(max, stack.getMaxStackSize());
@ -61,17 +61,17 @@ public class StackSizeModuleItem extends ModuleItem {
} }
@Override @Override
public boolean isCompatible(ItemStack module, PipeTileEntity tile, IModule other) { public boolean isCompatible(ItemStack module, PipeBlockEntity tile, IModule other) {
return !(other instanceof StackSizeModuleItem); return !(other instanceof StackSizeModuleItem);
} }
@Override @Override
public boolean hasContainer(ItemStack module, PipeTileEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return true; return true;
} }
@Override @Override
public AbstractPipeContainer<?> getContainer(ItemStack module, PipeTileEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) { public AbstractPipeContainer<?> getContainer(ItemStack module, PipeBlockEntity tile, int windowId, PlayerInventory inv, PlayerEntity player, int moduleIndex) {
return new StackSizeModuleContainer(Registry.stackSizeModuleContainer, windowId, player, tile.getPos(), moduleIndex); return new StackSizeModuleContainer(Registry.stackSizeModuleContainer, windowId, player, tile.getPos(), moduleIndex);
} }
} }

View file

@ -6,7 +6,7 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.ConnectionType; import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.IPipeConnectable; import de.ellpeck.prettypipes.pipe.IPipeConnectable;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
@ -129,7 +129,7 @@ public class PressurizerBlockEntity extends BlockEntity implements INamedContain
for (BlockPos node : network.getOrderedNetworkNodes(offset)) { for (BlockPos node : network.getOrderedNetworkNodes(offset)) {
if (!this.world.isBlockLoaded(node)) if (!this.world.isBlockLoaded(node))
continue; continue;
PipeTileEntity pipe = network.getPipe(node); PipeBlockEntity pipe = network.getPipe(node);
if (pipe != null) if (pipe != null)
pipe.pressurizer = this; pipe.pressurizer = this;
} }

View file

@ -10,7 +10,7 @@ public class CraftingTerminalBlock extends ItemTerminalBlock {
@Nullable @Nullable
@Override @Override
public TileEntity createNewTileEntity(IBlockReader worldIn) { public TileEntity createNewTileEntity(IBlockReader worldIn) {
return new CraftingTerminalTileEntity(); return new CraftingTerminalBlockEntity();
} }
} }

View file

@ -12,12 +12,13 @@ import de.ellpeck.prettypipes.network.NetworkLocation;
import de.ellpeck.prettypipes.network.PipeNetwork; import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.packets.PacketGhostSlot; import de.ellpeck.prettypipes.packets.PacketGhostSlot;
import de.ellpeck.prettypipes.packets.PacketHandler; import de.ellpeck.prettypipes.packets.PacketHandler;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer; import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Container;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.Direction; import net.minecraft.util.Direction;
@ -36,18 +37,18 @@ import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
public class CraftingTerminalTileEntity extends ItemTerminalTileEntity { public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
public final ItemStackHandler craftItems = new ItemStackHandler(9) { public final ItemStackHandler craftItems = new ItemStackHandler(9) {
@Override @Override
protected void onContentsChanged(int slot) { protected void onContentsChanged(int slot) {
for (PlayerEntity playerEntity : CraftingTerminalTileEntity.this.getLookingPlayers()) for (Player playerEntity : CraftingTerminalBlockEntity.this.getLookingPlayers())
playerEntity.openContainer.onCraftMatrixChanged(null); playerEntity.containerMenu.onCraftMatrixChanged(null);
} }
}; };
public final ItemStackHandler ghostItems = new ItemStackHandler(9); public final ItemStackHandler ghostItems = new ItemStackHandler(9);
public CraftingTerminalTileEntity() { public CraftingTerminalBlockEntity() {
super(Registry.craftingTerminalTileEntity); super(Registry.craftingTerminalTileEntity);
} }
@ -85,7 +86,7 @@ public class CraftingTerminalTileEntity extends ItemTerminalTileEntity {
} }
// check craftables // check craftables
if (amount <= 0 && highestAmount <= 0) { if (amount <= 0 && highestAmount <= 0) {
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
if (pipe != null) if (pipe != null)
amount = PipeNetwork.get(this.world).getCraftableAmount(pipe.getPos(), null, stack, new Stack<>(), ItemEquality.NBT); amount = PipeNetwork.get(this.world).getCraftableAmount(pipe.getPos(), null, stack, new Stack<>(), ItemEquality.NBT);
} }
@ -107,7 +108,7 @@ public class CraftingTerminalTileEntity extends ItemTerminalTileEntity {
} }
public void requestCraftingItems(PlayerEntity player, int maxAmount) { public void requestCraftingItems(PlayerEntity player, int maxAmount) {
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
if (pipe == null) if (pipe == null)
return; return;
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.world);
@ -161,7 +162,7 @@ public class CraftingTerminalTileEntity extends ItemTerminalTileEntity {
@Override @Override
public ItemStack insertItem(BlockPos pipePos, Direction direction, ItemStack remain, boolean simulate) { public ItemStack insertItem(BlockPos pipePos, Direction direction, ItemStack remain, boolean simulate) {
BlockPos pos = pipePos.offset(direction); BlockPos pos = pipePos.offset(direction);
CraftingTerminalTileEntity tile = Utility.getBlockEntity(CraftingTerminalTileEntity.class, this.world, pos); CraftingTerminalBlockEntity tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, this.world, pos);
if (tile != null) { if (tile != null) {
remain = remain.copy(); remain = remain.copy();
int lowestSlot = -1; int lowestSlot = -1;
@ -194,7 +195,7 @@ public class CraftingTerminalTileEntity extends ItemTerminalTileEntity {
return remain; return remain;
} }
public static int getAvailableCrafts(PipeTileEntity tile, int slots, Function<Integer, ItemStack> inputFunction, Predicate<Integer> isGhost, Function<EquatableItemStack, Collection<NetworkLocation>> locationsFunction, Consumer<ItemStack> unavailableConsumer, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) { public static int getAvailableCrafts(PipeBlockEntity tile, int slots, Function<Integer, ItemStack> inputFunction, Predicate<Integer> isGhost, Function<EquatableItemStack, Collection<NetworkLocation>> locationsFunction, Consumer<ItemStack> unavailableConsumer, Stack<ItemStack> dependencyChain, ItemEquality... equalityTypes) {
PipeNetwork network = PipeNetwork.get(tile.getWorld()); PipeNetwork network = PipeNetwork.get(tile.getWorld());
// the highest amount we can craft with the items we have // the highest amount we can craft with the items we have
int lowestAvailable = Integer.MAX_VALUE; int lowestAvailable = Integer.MAX_VALUE;

View file

@ -35,7 +35,7 @@ public class ItemTerminalBlock extends ContainerBlock {
@Override @Override
public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult result) { public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult result) {
ItemTerminalTileEntity tile = Utility.getBlockEntity(ItemTerminalTileEntity.class, worldIn, pos); ItemTerminalBlockEntity tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, worldIn, pos);
if (tile == null) if (tile == null)
return ActionResultType.PASS; return ActionResultType.PASS;
String reason = tile.getInvalidTerminalReason(); String reason = tile.getInvalidTerminalReason();
@ -54,7 +54,7 @@ public class ItemTerminalBlock extends ContainerBlock {
@Override @Override
public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) { public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
if (state.getBlock() != newState.getBlock()) { if (state.getBlock() != newState.getBlock()) {
ItemTerminalTileEntity tile = Utility.getBlockEntity(ItemTerminalTileEntity.class, worldIn, pos); ItemTerminalBlockEntity tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, worldIn, pos);
if (tile != null) if (tile != null)
Utility.dropInventory(tile, tile.items); Utility.dropInventory(tile, tile.items);
super.onReplaced(state, worldIn, pos, newState, isMoving); super.onReplaced(state, worldIn, pos, newState, isMoving);
@ -64,7 +64,7 @@ public class ItemTerminalBlock extends ContainerBlock {
@Nullable @Nullable
@Override @Override
public TileEntity createNewTileEntity(IBlockReader worldIn) { public TileEntity createNewTileEntity(IBlockReader worldIn) {
return new ItemTerminalTileEntity(); return new ItemTerminalBlockEntity();
} }
@Override @Override

View file

@ -13,13 +13,18 @@ import de.ellpeck.prettypipes.packets.PacketHandler;
import de.ellpeck.prettypipes.packets.PacketNetworkItems; import de.ellpeck.prettypipes.packets.PacketNetworkItems;
import de.ellpeck.prettypipes.pipe.ConnectionType; import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.IPipeConnectable; import de.ellpeck.prettypipes.pipe.IPipeConnectable;
import de.ellpeck.prettypipes.pipe.PipeTileEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import net.minecraft.ChatFormatting;
import net.minecraft.block.BlockState; import net.minecraft.block.BlockState;
import net.minecraft.core.Direction;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.tileentity.ITickableTileEntity;
@ -32,6 +37,7 @@ import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.common.util.LazyOptional;
@ -45,7 +51,7 @@ import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ItemTerminalTileEntity extends TileEntity implements INamedContainerProvider, ITickableTileEntity, IPipeConnectable { public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnectable {
public final ItemStackHandler items = new ItemStackHandler(12) { public final ItemStackHandler items = new ItemStackHandler(12) {
@Override @Override
@ -57,26 +63,19 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
private final Queue<NetworkLock> existingRequests = new LinkedList<>(); private final Queue<NetworkLock> existingRequests = new LinkedList<>();
private final LazyOptional<IPipeConnectable> lazyThis = LazyOptional.of(() -> this); private final LazyOptional<IPipeConnectable> lazyThis = LazyOptional.of(() -> this);
protected ItemTerminalTileEntity(TileEntityType<?> tileEntityTypeIn) { // TODO tick
super(tileEntityTypeIn); /* @Override
}
public ItemTerminalTileEntity() {
this(Registry.itemTerminalTileEntity);
}
@Override
public void tick() { public void tick() {
if (this.world.isRemote) if (this.level.isRemote)
return; return;
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
if (pipe == null) if (pipe == null)
return; return;
boolean update = false; boolean update = false;
int interval = pipe.pressurizer != null ? 2 : 10; int interval = pipe.pressurizer != null ? 2 : 10;
if (this.world.getGameTime() % interval == 0) { if (this.level.getGameTime() % interval == 0) {
for (int i = 6; i < 12; i++) { for (int i = 6; i < 12; i++) {
ItemStack extracted = this.items.extractItem(i, Integer.MAX_VALUE, true); ItemStack extracted = this.items.extractItem(i, Integer.MAX_VALUE, true);
if (extracted.isEmpty()) if (extracted.isEmpty())
@ -96,26 +95,26 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
} }
} }
if (this.world.getGameTime() % 100 == 0 || update) { if (this.level.getGameTime() % 100 == 0 || update) {
PlayerEntity[] lookingPlayers = this.getLookingPlayers(); PlayerEntity[] lookingPlayers = this.getLookingPlayers();
if (lookingPlayers.length > 0) if (lookingPlayers.length > 0)
this.updateItems(lookingPlayers); this.updateItems(lookingPlayers);
} }
} }*/
@Override @Override
public void remove() { public void setRemoved() {
super.remove(); super.setRemoved();
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
for (NetworkLock lock : this.existingRequests) for (NetworkLock lock : this.existingRequests)
network.resolveNetworkLock(lock); network.resolveNetworkLock(lock);
this.lazyThis.invalidate(); this.lazyThis.invalidate();
} }
public String getInvalidTerminalReason() { public String getInvalidTerminalReason() {
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
long pipes = Arrays.stream(Direction.values()) long pipes = Arrays.stream(Direction.values())
.map(d -> network.getPipe(this.pos.offset(d))) .map(d -> network.getPipe(this.worldPosition.relative(d)))
.filter(Objects::nonNull).count(); .filter(Objects::nonNull).count();
if (pipes <= 0) if (pipes <= 0)
return "info." + PrettyPipes.ID + ".no_pipe_connected"; return "info." + PrettyPipes.ID + ".no_pipe_connected";
@ -124,43 +123,42 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
return null; return null;
} }
public PipeTileEntity getConnectedPipe() { public PipeBlockEntity getConnectedPipe() {
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
for (Direction dir : Direction.values()) { for (Direction dir : Direction.values()) {
PipeTileEntity pipe = network.getPipe(this.pos.offset(dir)); PipeBlockEntity pipe = network.getPipe(this.worldPosition.relative(dir));
if (pipe != null) if (pipe != null)
return pipe; return pipe;
} }
return null; return null;
} }
public void updateItems(PlayerEntity... playersToSync) { public void updateItems(Player... playersToSync) {
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
if (pipe == null) if (pipe == null)
return; return;
this.networkItems = this.collectItems(ItemEquality.NBT); this.networkItems = this.collectItems(ItemEquality.NBT);
if (playersToSync.length > 0) { if (playersToSync.length > 0) {
List<ItemStack> clientItems = this.networkItems.values().stream().map(NetworkItem::asStack).collect(Collectors.toList()); List<ItemStack> clientItems = this.networkItems.values().stream().map(NetworkItem::asStack).collect(Collectors.toList());
List<ItemStack> clientCraftables = PipeNetwork.get(this.world).getAllCraftables(pipe.getPos()).stream().map(Pair::getRight).collect(Collectors.toList()); List<ItemStack> clientCraftables = PipeNetwork.get(this.level).getAllCraftables(pipe.getPos()).stream().map(Pair::getRight).collect(Collectors.toList());
List<ItemStack> currentlyCrafting = this.getCurrentlyCrafting().stream().sorted(Comparator.comparingInt(ItemStack::getCount).reversed()).collect(Collectors.toList()); List<ItemStack> currentlyCrafting = this.getCurrentlyCrafting().stream().sorted(Comparator.comparingInt(ItemStack::getCount).reversed()).collect(Collectors.toList());
for (PlayerEntity player : playersToSync) { for (Player player : playersToSync) {
if (!(player.openContainer instanceof ItemTerminalContainer)) if (!(player.containerMenu instanceof ItemTerminalContainer container))
continue; continue;
ItemTerminalTileEntity tile = ((ItemTerminalContainer) player.openContainer).tile; if (container.tile != this)
if (tile != this)
continue; continue;
PacketHandler.sendTo(player, new PacketNetworkItems(clientItems, clientCraftables, currentlyCrafting)); PacketHandler.sendTo(player, new PacketNetworkItems(clientItems, clientCraftables, currentlyCrafting));
} }
} }
} }
public void requestItem(PlayerEntity player, ItemStack stack) { public void requestItem(Player player, ItemStack stack) {
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
network.startProfile("terminal_request_item"); network.startProfile("terminal_request_item");
this.updateItems(); this.updateItems();
int requested = this.requestItemImpl(stack, onItemUnavailable(player)); int requested = this.requestItemImpl(stack, onItemUnavailable(player));
if (requested > 0) { if (requested > 0) {
player.sendMessage(new TranslationTextComponent("info." + PrettyPipes.ID + ".sending", requested, stack.getDisplayName()).setStyle(Style.EMPTY.setFormatting(TextFormatting.GREEN)), UUID.randomUUID()); player.sendMessage(new TranslatableComponent("info." + PrettyPipes.ID + ".sending", requested, stack.getDisplayName()).setStyle(Style.EMPTY.setFormatting(TextFormatting.GREEN)), UUID.randomUUID());
} else { } else {
onItemUnavailable(player).accept(stack); onItemUnavailable(player).accept(stack);
} }
@ -170,27 +168,27 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
public int requestItemImpl(ItemStack stack, Consumer<ItemStack> unavailableConsumer) { public int requestItemImpl(ItemStack stack, Consumer<ItemStack> unavailableConsumer) {
NetworkItem item = this.networkItems.get(new EquatableItemStack(stack, ItemEquality.NBT)); NetworkItem item = this.networkItems.get(new EquatableItemStack(stack, ItemEquality.NBT));
Collection<NetworkLocation> locations = item == null ? Collections.emptyList() : item.getLocations(); Collection<NetworkLocation> locations = item == null ? Collections.emptyList() : item.getLocations();
Pair<List<NetworkLock>, ItemStack> ret = requestItemLater(this.world, this.getConnectedPipe().getPos(), locations, unavailableConsumer, stack, new Stack<>(), ItemEquality.NBT); Pair<List<NetworkLock>, ItemStack> ret = requestItemLater(this.level, this.getConnectedPipe().getPos(), locations, unavailableConsumer, stack, new Stack<>(), ItemEquality.NBT);
this.existingRequests.addAll(ret.getLeft()); this.existingRequests.addAll(ret.getLeft());
return stack.getCount() - ret.getRight().getCount(); return stack.getCount() - ret.getRight().getCount();
} }
protected PlayerEntity[] getLookingPlayers() { protected Player[] getLookingPlayers() {
return this.world.getPlayers().stream() return this.level.getPlayers().stream()
.filter(p -> p.openContainer instanceof ItemTerminalContainer) .filter(p -> p.openContainer instanceof ItemTerminalContainer)
.filter(p -> ((ItemTerminalContainer) p.openContainer).tile == this) .filter(p -> ((ItemTerminalContainer) p.openContainer).tile == this)
.toArray(PlayerEntity[]::new); .toArray(PlayerEntity[]::new);
} }
private Map<EquatableItemStack, NetworkItem> collectItems(ItemEquality... equalityTypes) { private Map<EquatableItemStack, NetworkItem> collectItems(ItemEquality... equalityTypes) {
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
network.startProfile("terminal_collect_items"); network.startProfile("terminal_collect_items");
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
Map<EquatableItemStack, NetworkItem> items = new HashMap<>(); Map<EquatableItemStack, NetworkItem> items = new HashMap<>();
for (NetworkLocation location : network.getOrderedNetworkItems(pipe.getPos())) { for (NetworkLocation location : network.getOrderedNetworkItems(pipe.getPos())) {
for (Map.Entry<Integer, ItemStack> entry : location.getItems(this.world).entrySet()) { for (Map.Entry<Integer, ItemStack> entry : location.getItems(this.level).entrySet()) {
// make sure we can extract from this slot to display it // make sure we can extract from this slot to display it
if (!location.canExtract(this.world, entry.getKey())) if (!location.canExtract(this.level, entry.getKey()))
continue; continue;
EquatableItemStack equatable = new EquatableItemStack(entry.getValue(), equalityTypes); EquatableItemStack equatable = new EquatableItemStack(entry.getValue(), equalityTypes);
NetworkItem item = items.computeIfAbsent(equatable, NetworkItem::new); NetworkItem item = items.computeIfAbsent(equatable, NetworkItem::new);
@ -202,8 +200,8 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
} }
private List<ItemStack> getCurrentlyCrafting() { private List<ItemStack> getCurrentlyCrafting() {
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
if (pipe == null) if (pipe == null)
return Collections.emptyList(); return Collections.emptyList();
List<Pair<BlockPos, ItemStack>> crafting = network.getCurrentlyCrafting(pipe.getPos()); List<Pair<BlockPos, ItemStack>> crafting = network.getCurrentlyCrafting(pipe.getPos());
@ -211,12 +209,12 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
} }
public void cancelCrafting() { public void cancelCrafting() {
PipeNetwork network = PipeNetwork.get(this.world); PipeNetwork network = PipeNetwork.get(this.level);
PipeTileEntity pipe = this.getConnectedPipe(); PipeBlockEntity pipe = this.getConnectedPipe();
if (pipe == null) if (pipe == null)
return; return;
for (Pair<BlockPos, ItemStack> craftable : network.getAllCraftables(pipe.getPos())) { for (Pair<BlockPos, ItemStack> craftable : network.getAllCraftables(pipe.getPos())) {
PipeTileEntity otherPipe = network.getPipe(craftable.getLeft()); PipeBlockEntity otherPipe = network.getPipe(craftable.getLeft());
if (otherPipe != null) { if (otherPipe != null) {
for (NetworkLock lock : otherPipe.craftIngredientRequests) for (NetworkLock lock : otherPipe.craftIngredientRequests)
network.resolveNetworkLock(lock); network.resolveNetworkLock(lock);
@ -270,7 +268,7 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
@Override @Override
public ItemStack insertItem(BlockPos pipePos, Direction direction, ItemStack stack, boolean simulate) { public ItemStack insertItem(BlockPos pipePos, Direction direction, ItemStack stack, boolean simulate) {
BlockPos pos = pipePos.offset(direction); BlockPos pos = pipePos.offset(direction);
ItemTerminalTileEntity tile = Utility.getBlockEntity(ItemTerminalTileEntity.class, world, pos); ItemTerminalBlockEntity tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, world, pos);
if (tile != null) if (tile != null)
return ItemHandlerHelper.insertItemStacked(tile.items, stack, simulate); return ItemHandlerHelper.insertItemStacked(tile.items, stack, simulate);
return stack; return stack;
@ -313,7 +311,7 @@ public class ItemTerminalTileEntity extends TileEntity implements INamedContaine
return Pair.of(requests, remain); return Pair.of(requests, remain);
} }
public static Consumer<ItemStack> onItemUnavailable(PlayerEntity player) { public static Consumer<ItemStack> onItemUnavailable(Player player) {
return s -> player.sendMessage(new TranslationTextComponent("info." + PrettyPipes.ID + ".not_found", s.getDisplayName()).setStyle(Style.EMPTY.setFormatting(TextFormatting.RED)), UUID.randomUUID()); return s -> player.sendMessage(new TranslatableComponent("info." + PrettyPipes.ID + ".not_found", s.getDisplayName()).setStyle(Style.EMPTY.applyFormat(ChatFormatting.RED)), UUID.randomUUID());
} }
} }

View file

@ -1,7 +1,7 @@
package de.ellpeck.prettypipes.terminal.containers; package de.ellpeck.prettypipes.terminal.containers;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.CraftingTerminalTileEntity; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.CraftResultInventory; import net.minecraft.inventory.CraftResultInventory;
@ -76,7 +76,7 @@ public class CraftingTerminalContainer extends ItemTerminalContainer {
return super.slotClick(slotId, dragType, clickTypeIn, player); return super.slotClick(slotId, dragType, clickTypeIn, player);
} }
public CraftingTerminalTileEntity getTile() { public CraftingTerminalBlockEntity getTile() {
return (CraftingTerminalTileEntity) this.tile; return (CraftingTerminalBlockEntity) this.tile;
} }
} }

View file

@ -1,13 +1,10 @@
package de.ellpeck.prettypipes.terminal.containers; package de.ellpeck.prettypipes.terminal.containers;
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.packets.PacketButton; import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.packets.PacketHandler; import de.ellpeck.prettypipes.packets.PacketHandler;
import de.ellpeck.prettypipes.packets.PacketRequest; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.CraftingTerminalTileEntity;
import net.minecraft.client.gui.widget.Widget; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
@ -40,7 +37,7 @@ public class CraftingTerminalGui extends ItemTerminalGui {
@Override @Override
public void tick() { public void tick() {
super.tick(); super.tick();
CraftingTerminalTileEntity tile = this.getCraftingContainer().getTile(); CraftingTerminalBlockEntity tile = this.getCraftingContainer().getTile();
this.requestButton.active = false; this.requestButton.active = false;
for (int i = 0; i < tile.craftItems.getSlots(); i++) { for (int i = 0; i < tile.craftItems.getSlots(); i++) {
ItemStack stack = tile.getRequestedCraftItem(i); ItemStack stack = tile.getRequestedCraftItem(i);
@ -56,7 +53,7 @@ public class CraftingTerminalGui extends ItemTerminalGui {
super.drawGuiContainerForegroundLayer(matrix, mouseX, mouseY); super.drawGuiContainerForegroundLayer(matrix, mouseX, mouseY);
CraftingTerminalContainer container = this.getCraftingContainer(); CraftingTerminalContainer container = this.getCraftingContainer();
CraftingTerminalTileEntity tile = container.getTile(); CraftingTerminalBlockEntity tile = container.getTile();
for (int i = 0; i < tile.ghostItems.getSlots(); i++) { for (int i = 0; i < tile.ghostItems.getSlots(); i++) {
if (!tile.craftItems.getStackInSlot(i).isEmpty()) if (!tile.craftItems.getStackInSlot(i).isEmpty())
continue; continue;

View file

@ -1,40 +1,37 @@
package de.ellpeck.prettypipes.terminal.containers; package de.ellpeck.prettypipes.terminal.containers;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.ItemTerminalTileEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.entity.player.PlayerEntity; import net.minecraft.core.BlockPos;
import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.world.entity.player.Player;
import net.minecraft.inventory.container.ClickType; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.inventory.container.Container; import net.minecraft.world.inventory.MenuType;
import net.minecraft.inventory.container.ContainerType; import net.minecraft.world.inventory.Slot;
import net.minecraft.inventory.container.Slot;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.items.SlotItemHandler; import net.minecraftforge.items.SlotItemHandler;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class ItemTerminalContainer extends Container { public class ItemTerminalContainer extends AbstractContainerMenu {
public final ItemTerminalTileEntity tile; public final ItemTerminalBlockEntity tile;
public ItemTerminalContainer(@Nullable ContainerType<?> type, int id, PlayerEntity player, BlockPos pos) { public ItemTerminalContainer(@Nullable MenuType<?> type, int id, Player player, BlockPos pos) {
super(type, id); super(type, id);
this.tile = Utility.getBlockEntity(ItemTerminalTileEntity.class, player.world, pos); this.tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level, pos);
this.addOwnSlots(player); this.addOwnSlots(player);
int off = this.getSlotXOffset(); int off = this.getSlotXOffset();
for (int l = 0; l < 3; ++l) for (int l = 0; l < 3; ++l)
for (int j1 = 0; j1 < 9; ++j1) for (int j1 = 0; j1 < 9; ++j1)
this.addSlot(new Slot(player.inventory, j1 + l * 9 + 9, 8 + off + j1 * 18, 154 + l * 18)); this.addSlot(new Slot(player.getInventory(), j1 + l * 9 + 9, 8 + off + j1 * 18, 154 + l * 18));
for (int i1 = 0; i1 < 9; ++i1) for (int i1 = 0; i1 < 9; ++i1)
this.addSlot(new Slot(player.inventory, i1, 8 + off + i1 * 18, 212)); this.addSlot(new Slot(player.getInventory(), i1, 8 + off + i1 * 18, 212));
} }
protected void addOwnSlots(PlayerEntity player) { protected void addOwnSlots(Player player) {
int off = this.getSlotXOffset(); int off = this.getSlotXOffset();
for (int i = 0; i < 6; i++) for (int i = 0; i < 6; i++)
this.addSlot(new SlotItemHandler(this.tile.items, i, 8 + off + i % 3 * 18, 102 + i / 3 * 18)); this.addSlot(new SlotItemHandler(this.tile.items, i, 8 + off + i % 3 * 18, 102 + i / 3 * 18));
@ -47,12 +44,12 @@ public class ItemTerminalContainer extends Container {
} }
@Override @Override
public ItemStack transferStackInSlot(PlayerEntity player, int slotIndex) { public ItemStack quickMoveStack(Player player, int slotIndex) {
return Utility.transferStackInSlot(this, this::mergeItemStack, player, slotIndex, stack -> Pair.of(6, 12)); return Utility.transferStackInSlot(this, this::moveItemStackTo, player, slotIndex, stack -> Pair.of(6, 12));
} }
@Override @Override
public boolean canInteractWith(PlayerEntity playerIn) { public boolean stillValid(Player player) {
return true; return true;
} }
} }

View file

@ -8,13 +8,19 @@ import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.packets.PacketHandler; import de.ellpeck.prettypipes.packets.PacketHandler;
import de.ellpeck.prettypipes.packets.PacketRequest; import de.ellpeck.prettypipes.packets.PacketRequest;
import joptsimple.internal.Strings; import joptsimple.internal.Strings;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.gui.widget.Widget; import net.minecraft.client.gui.widget.Widget;
import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.InputMappings; import net.minecraft.client.util.InputMappings;
import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.MathHelper;
@ -27,12 +33,12 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> { public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContainer> {
private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/item_terminal.png"); private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/item_terminal.png");
public List<ItemStack> currentlyCrafting; public List<ItemStack> currentlyCrafting;
public TextFieldWidget search; public EditBox search;
// craftables have the second parameter set to true // craftables have the second parameter set to true
private final List<Pair<ItemStack, Boolean>> sortedItems = new ArrayList<>(); private final List<Pair<ItemStack, Boolean>> sortedItems = new ArrayList<>();
@ -50,23 +56,23 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
private ItemStack hoveredCrafting; private ItemStack hoveredCrafting;
private boolean isScrolling; private boolean isScrolling;
public ItemTerminalGui(ItemTerminalContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { public ItemTerminalGui(ItemTerminalContainer screenContainer, Inventory inv, Component titleIn) {
super(screenContainer, inv, titleIn); super(screenContainer, inv, titleIn);
this.xSize = 176 + 15; this.imageWidth = 176 + 15;
this.ySize = 236; this.imageHeight = 236;
} }
@Override @Override
protected void init() { protected void init() {
super.init(); super.init();
this.search = this.addButton(new TextFieldWidget(this.font, this.guiLeft + this.getXOffset() + 97, this.guiTop + 6, 86, 8, new StringTextComponent(""))); this.search = this.addWidget(new EditBox(this.font, this.leftPos + this.getXOffset() + 97, this.topPos + 6, 86, 8, new StringTextComponent("")));
this.search.setEnableBackgroundDrawing(false); this.search.setBordered(false);
this.lastSearchText = ""; this.lastSearchText = "";
if (this.items != null) if (this.items != null)
this.updateWidgets(); this.updateWidgets();
this.plusButton = this.addButton(new Button(this.guiLeft + this.getXOffset() + 95 - 7 + 12, this.guiTop + 103, 12, 12, new StringTextComponent("+"), button -> { this.plusButton = this.addWidget(new Button(this.leftPos + this.getXOffset() + 95 - 7 + 12, this.topPos + 103, 12, 12, new StringTextComponent("+"), button -> {
int modifier = requestModifier(); int modifier = requestModifier();
if (modifier > 1 && this.requestAmount == 1) { if (modifier > 1 && this.requestAmount == 1) {
this.requestAmount = modifier; this.requestAmount = modifier;
@ -77,23 +83,23 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
if (this.requestAmount > 384) if (this.requestAmount > 384)
this.requestAmount = 384; this.requestAmount = 384;
})); }));
this.minusButton = this.addButton(new Button(this.guiLeft + this.getXOffset() + 95 - 7 - 24, this.guiTop + 103, 12, 12, new StringTextComponent("-"), button -> { this.minusButton = this.addWidget(new Button(this.leftPos + this.getXOffset() + 95 - 7 - 24, this.topPos + 103, 12, 12, new StringTextComponent("-"), button -> {
this.requestAmount -= requestModifier(); this.requestAmount -= requestModifier();
if (this.requestAmount < 1) if (this.requestAmount < 1)
this.requestAmount = 1; this.requestAmount = 1;
})); }));
this.minusButton.active = false; this.minusButton.active = false;
this.requestButton = this.addButton(new Button(this.guiLeft + this.getXOffset() + 95 - 7 - 25, this.guiTop + 115, 50, 20, new TranslationTextComponent("info." + PrettyPipes.ID + ".request"), button -> { this.requestButton = this.addWidget(new Button(this.leftPos + this.getXOffset() + 95 - 7 - 25, this.topPos + 115, 50, 20, new TranslationTextComponent("info." + PrettyPipes.ID + ".request"), button -> {
Optional<ItemTerminalWidget> widget = this.streamWidgets().filter(w -> w.selected).findFirst(); Optional<ItemTerminalWidget> widget = this.streamWidgets().filter(w -> w.selected).findFirst();
if (!widget.isPresent()) if (!widget.isPresent())
return; return;
ItemStack stack = widget.get().stack.copy(); ItemStack stack = widget.get().stack.copy();
stack.setCount(1); stack.setCount(1);
PacketHandler.sendToServer(new PacketRequest(this.container.tile.getPos(), stack, this.requestAmount)); PacketHandler.sendToServer(new PacketRequest(this.menu.tile.getBlockPos(), stack, this.requestAmount));
this.requestAmount = 1; this.requestAmount = 1;
})); }));
this.requestButton.active = false; this.requestButton.active = false;
this.orderButton = this.addButton(new Button(this.guiLeft - 22, this.guiTop, 20, 20, new StringTextComponent(""), button -> { this.orderButton = this.addWidget(new Button(this.leftPos - 22, this.topPos, 20, 20, new TextComponent(""), button -> {
if (this.sortedItems == null) if (this.sortedItems == null)
return; return;
PlayerPrefs prefs = PlayerPrefs.get(); PlayerPrefs prefs = PlayerPrefs.get();
@ -101,7 +107,7 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
prefs.save(); prefs.save();
this.updateWidgets(); this.updateWidgets();
})); }));
this.ascendingButton = this.addButton(new Button(this.guiLeft - 22, this.guiTop + 22, 20, 20, new StringTextComponent(""), button -> { this.ascendingButton = this.addButton(new Button(this.leftPos - 22, this.topPos + 22, 20, 20, new StringTextComponent(""), button -> {
if (this.sortedItems == null) if (this.sortedItems == null)
return; return;
PlayerPrefs prefs = PlayerPrefs.get(); PlayerPrefs prefs = PlayerPrefs.get();
@ -109,12 +115,12 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
prefs.save(); prefs.save();
this.updateWidgets(); this.updateWidgets();
})); }));
this.cancelCraftingButton = this.addButton(new Button(this.guiLeft + this.xSize + 4, this.guiTop + 4 + 64, 54, 20, new TranslationTextComponent("info." + PrettyPipes.ID + ".cancel_all"), b -> { this.cancelCraftingButton = this.addButton(new Button(this.leftPos + this.xSize + 4, this.topPos + 4 + 64, 54, 20, new TranslationTextComponent("info." + PrettyPipes.ID + ".cancel_all"), b -> {
})); }));
this.cancelCraftingButton.visible = false; this.cancelCraftingButton.visible = false;
for (int y = 0; y < 4; y++) { for (int y = 0; y < 4; y++) {
for (int x = 0; x < 9; x++) for (int x = 0; x < 9; x++)
this.addButton(new ItemTerminalWidget(this.guiLeft + this.getXOffset() + 8 + x * 18, this.guiTop + 18 + y * 18, x, y, this)); this.addButton(new ItemTerminalWidget(this.leftPos + this.getXOffset() + 8 + x * 18, this.topPos + 18 + y * 18, x, y, this));
} }
} }
@ -141,7 +147,7 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
@Override @Override
public boolean mouseClicked(double mouseX, double mouseY, int button) { public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (button == 0 && mouseX >= this.guiLeft + this.getXOffset() + 172 && this.guiTop + mouseY >= 18 && mouseX < this.guiLeft + this.getXOffset() + 172 + 12 && mouseY < this.guiTop + 18 + 70) { if (button == 0 && mouseX >= this.leftPos + this.getXOffset() + 172 && this.topPos + mouseY >= 18 && mouseX < this.leftPos + this.getXOffset() + 172 + 12 && mouseY < this.topPos + 18 + 70) {
this.isScrolling = true; this.isScrolling = true;
return true; return true;
} }
@ -172,7 +178,7 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
@Override @Override
public boolean mouseDragged(double mouseX, double mouseY, int i, double j, double k) { public boolean mouseDragged(double mouseX, double mouseY, int i, double j, double k) {
if (this.isScrolling) { if (this.isScrolling) {
float percentage = MathHelper.clamp(((float) mouseY - (this.guiTop + 18) - 7.5F) / (70 - 15), 0, 1); float percentage = MathHelper.clamp(((float) mouseY - (this.topPos + 18) - 7.5F) / (70 - 15), 0, 1);
int offset = (int) (percentage * (float) (this.sortedItems.size() / 9 - 3)); int offset = (int) (percentage * (float) (this.sortedItems.size() / 9 - 3));
if (offset != this.scrollOffset) { if (offset != this.scrollOffset) {
this.scrollOffset = offset; this.scrollOffset = offset;
@ -300,26 +306,26 @@ public class ItemTerminalGui extends ContainerScreen<ItemTerminalContainer> {
@Override @Override
protected void drawGuiContainerBackgroundLayer(MatrixStack matrix, float partialTicks, int mouseX, int mouseY) { protected void drawGuiContainerBackgroundLayer(MatrixStack matrix, float partialTicks, int mouseX, int mouseY) {
this.getMinecraft().getTextureManager().bindTexture(this.getTexture()); this.getMinecraft().getTextureManager().bindTexture(this.getTexture());
this.blit(matrix, this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); this.blit(matrix, this.leftPos, this.topPos, 0, 0, this.xSize, this.ySize);
if (this.sortedItems != null && this.sortedItems.size() >= 9 * 4) { if (this.sortedItems != null && this.sortedItems.size() >= 9 * 4) {
float percentage = this.scrollOffset / (float) (this.sortedItems.size() / 9 - 3); float percentage = this.scrollOffset / (float) (this.sortedItems.size() / 9 - 3);
this.blit(matrix, this.guiLeft + this.getXOffset() + 172, this.guiTop + 18 + (int) (percentage * (70 - 15)), 232, 241, 12, 15); this.blit(matrix, this.leftPos + this.getXOffset() + 172, this.topPos + 18 + (int) (percentage * (70 - 15)), 232, 241, 12, 15);
} else { } else {
this.blit(matrix, this.guiLeft + this.getXOffset() + 172, this.guiTop + 18, 244, 241, 12, 15); this.blit(matrix, this.leftPos + this.getXOffset() + 172, this.topPos + 18, 244, 241, 12, 15);
} }
// draw the items that are currently crafting // draw the items that are currently crafting
this.hoveredCrafting = ItemStack.EMPTY; this.hoveredCrafting = ItemStack.EMPTY;
if (this.currentlyCrafting != null && !this.currentlyCrafting.isEmpty()) { if (this.currentlyCrafting != null && !this.currentlyCrafting.isEmpty()) {
this.getMinecraft().getTextureManager().bindTexture(TEXTURE); this.getMinecraft().getTextureManager().bindTexture(TEXTURE);
this.blit(matrix, this.guiLeft + this.xSize, this.guiTop + 4, 191, 0, 65, 89); this.blit(matrix, this.leftPos + this.xSize, this.topPos + 4, 191, 0, 65, 89);
int x = 0; int x = 0;
int y = 0; int y = 0;
for (ItemStack stack : this.currentlyCrafting) { for (ItemStack stack : this.currentlyCrafting) {
int itemX = this.guiLeft + this.xSize + 4 + x * 18; int itemX = this.leftPos + this.xSize + 4 + x * 18;
int itemY = this.guiTop + 4 + 16 + y * 18; int itemY = this.topPos + 4 + 16 + y * 18;
this.itemRenderer.renderItemAndEffectIntoGUI(stack, itemX, itemY); this.itemRenderer.renderItemAndEffectIntoGUI(stack, itemX, itemY);
this.itemRenderer.renderItemOverlayIntoGUI(this.font, stack, itemX, itemY, String.valueOf(stack.getCount())); this.itemRenderer.renderItemOverlayIntoGUI(this.font, stack, itemX, itemY, String.valueOf(stack.getCount()));
if (mouseX >= itemX && mouseY >= itemY && mouseX < itemX + 16 && mouseY < itemY + 18) if (mouseX >= itemX && mouseY >= itemY && mouseX < itemX + 16 && mouseY < itemY + 18)