Jump to content

[1.16.5] NBT value is similar to every other block instance


Recommended Posts

Posted

Hey guys,

I have a problem with my custom block model tile entity.

I wanna create a fire hose block that stores the waterlevel in NBT. Players have to refill it with a water bucket within the screen container. My problem is that the water level gets saved in the NBT data but if I create another instance of the block, it has the same value as the previous block. My assumption is that the blocks always use the same instance of the first generated tile entity. I tried to get the tile entity via the world and the position but it doesn't work either. 

I attached my code. I hope one of you guys can help me! :)

Screen Image

Image

Block class

Spoiler
package de.j3ramy.edom.block;

import de.j3ramy.edom.container.FireHoseBoxContainer;
import de.j3ramy.edom.tileentity.FireHoseBoxTile;
import de.j3ramy.edom.tileentity.ModTileEntities;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.HorizontalBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.state.StateContainer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
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.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;

import javax.annotation.Nullable;
import java.util.stream.Stream;

public class FireHoseBox extends HorizontalBlock {

    static final VoxelShape SHAPE_N = Stream.of(
            Block.makeCuboidShape(0, 2, 0, 16, 16, 6),
            Block.makeCuboidShape(2, 8, 6, 3, 10, 6.5),
            Block.makeCuboidShape(11, 0, 3, 12, 2, 4),
            Block.makeCuboidShape(11, 0, 0, 12, 1, 3),
            Block.makeCuboidShape(9, 0, 0, 10, 1, 3),
            Block.makeCuboidShape(9, 0, 3, 10, 2, 4)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    static final VoxelShape SHAPE_W = Stream.of(
            Block.makeCuboidShape(0, 2, 0, 6, 16, 16),
            Block.makeCuboidShape(6, 8, 13, 6.5, 10, 14),
            Block.makeCuboidShape(3, 0, 4, 4, 2, 5),
            Block.makeCuboidShape(0, 0, 4, 3, 1, 5),
            Block.makeCuboidShape(0, 0, 6, 3, 1, 7),
            Block.makeCuboidShape(3, 0, 6, 4, 2, 7)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    static final VoxelShape SHAPE_S = Stream.of(
            Block.makeCuboidShape(0, 2, 10, 16, 16, 16),
            Block.makeCuboidShape(13, 8, 9.5, 14, 10, 10),
            Block.makeCuboidShape(4, 0, 12, 5, 2, 13),
            Block.makeCuboidShape(4, 0, 13, 5, 1, 16),
            Block.makeCuboidShape(6, 0, 13, 7, 1, 16),
            Block.makeCuboidShape(6, 0, 12, 7, 2, 13)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    static final VoxelShape SHAPE_E = Stream.of(
            Block.makeCuboidShape(10, 2, 0, 16, 16, 16),
            Block.makeCuboidShape(9.5, 8, 2, 10, 10, 3),
            Block.makeCuboidShape(12, 0, 11, 13, 2, 12),
            Block.makeCuboidShape(13, 0, 11, 16, 1, 12),
            Block.makeCuboidShape(13, 0, 9, 16, 1, 10),
            Block.makeCuboidShape(12, 0, 9, 13, 2, 10)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    FireHoseBoxTile tileEntity;

    public FireHoseBox(Properties props) {
        super(props);
    }

    @Override
    public VoxelShape getShape(BlockState state, IBlockReader p_220053_2_, BlockPos p_220053_3_, ISelectionContext p_220053_4_) {
        switch (state.get(HORIZONTAL_FACING)){
            case SOUTH: return SHAPE_S;
            case EAST: return SHAPE_E;
            case WEST: return SHAPE_W;
            default: return SHAPE_N;
        }
    }

    @Override
    protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
        builder.add(HORIZONTAL_FACING);
    }

    @Nullable
    @Override
    public BlockState getStateForPlacement(BlockItemUseContext context) {
        return this.getDefaultState().with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing());
    }

    @Override
    public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {

        if(!worldIn.isRemote){
            worldIn.playSound(null, pos, SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 1, 1);
            tileEntity = (FireHoseBoxTile) worldIn.getTileEntity(pos);

            if(tileEntity == null)
                return ActionResultType.SUCCESS;

            if(player.isCrouching())
                return ActionResultType.SUCCESS;

            INamedContainerProvider containerProvider = createContainerProvider(worldIn, pos);
            NetworkHooks.openGui((ServerPlayerEntity) player, containerProvider, tileEntity.getPos());

        }

        return ActionResultType.SUCCESS;
    }

    private INamedContainerProvider createContainerProvider(World world, BlockPos pos) {
        return new INamedContainerProvider(){

            @Override
            public Container createMenu(int i, PlayerInventory playerInv, PlayerEntity playerEntity) {
                return new FireHoseBoxContainer(i, world, pos, playerInv, playerEntity, tileEntity);
            }

            @Override
            public ITextComponent getDisplayName() {
                return new TranslationTextComponent("");
            }
        };
    }

    @Override
    public boolean hasTileEntity(BlockState state) {
        return true;
    }

    @Nullable
    @Override
    public TileEntity createTileEntity(BlockState state, IBlockReader world) {
        return ModTileEntities.FIRE_HOSE_BOX_TILE.get().create();
    }
}

 

Tile entity

Spoiler
package de.j3ramy.edom.tileentity;

import de.j3ramy.edom.item.ModItems;
import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class FireHoseBoxTile extends TileEntity {

    public final ItemStackHandler itemHandler = createHandler();
    private final LazyOptional<IItemHandler> handler = LazyOptional.of(() -> itemHandler);

    private static int waterLevel = 0;
    private static final int maxWaterLevel = 45;
    private static final int waterLevelInterval = 15;

    public int getWaterLevel() {
        return waterLevel;
    }

    public FireHoseBoxTile(TileEntityType<?> tileEntityType) {
        super(tileEntityType);
    }

    public FireHoseBoxTile(){
        this(ModTileEntities.FIRE_HOSE_BOX_TILE.get());
    }

    @Override
    public void read(BlockState state, CompoundNBT nbt) {
        itemHandler.deserializeNBT(nbt.getCompound("inv"));

        if(nbt.contains("waterLevel"))
            waterLevel = nbt.getInt("waterLevel");

        super.read(state, nbt);
    }

    @Override
    public CompoundNBT write(CompoundNBT nbt) {
        super.write(nbt);
        nbt.put("inv", itemHandler.serializeNBT());
        nbt.putInt("waterLevel", waterLevel);
        return nbt;
    }

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        //Place code for setting that atm storage is only clickable from one side...
        if(cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
            return handler.cast();

        return super.getCapability(cap, side);
    }

    private ItemStackHandler createHandler(){
        return new ItemStackHandler(2){
            @Override
            protected void onContentsChanged(int slot) {
                if(world == null)
                    return;

                if(isItemValid(slot, getStackInSlot(slot))){
                    if(slot == 0 && waterLevel > 0)
                        waterLevel -= waterLevelInterval;

                    if(slot == 1 && waterLevel < maxWaterLevel){
                        itemHandler.getStackInSlot(1).shrink(1);

                        if(!world.isRemote)
                            fillFireBox();
                    }
                }

            }

            @Override
            public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
                switch(slot){
                    case 0: return stack.getItem() == Items.WATER_BUCKET;
                    case 1: return stack.getItem() == Items.WATER_BUCKET && waterLevel < maxWaterLevel;
                }
                return false;
            }

            @Override
            public int getSlotLimit(int slot) {
                return 1;
            }

            @Nonnull
            @Override
            public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {
                if(!isItemValid(slot, stack)){
                    return stack;
                }

                return super.insertItem(slot, stack, simulate);
            }
        };
    }

    void fillFireBox(){
        System.out.println("Before: " + waterLevel);
        waterLevel += waterLevelInterval;

        System.out.println("Afterwards: " + waterLevel);
    }
}

 

Container

Spoiler
package de.j3ramy.edom.container;

import de.j3ramy.edom.block.ModBlocks;
import de.j3ramy.edom.tileentity.FireHoseBoxTile;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IWorldPosCallable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;

public class FireHoseBoxContainer extends Container {

    private final TileEntity tileEntity;
    private final PlayerEntity playerEntity;
    private final IItemHandler playerInventory;

    public FireHoseBoxContainer(int windowId, World world, BlockPos pos, PlayerInventory playerInventory, PlayerEntity player, FireHoseBoxTile tile){
        super(ModContainers.FIRE_HOSE_BOX_CONTAINER.get(), windowId);

        this.tileEntity = world.getTileEntity(pos);
        this.playerEntity = player;
        this.playerInventory = new InvWrapper(playerInventory);

        if(tileEntity != null){
            tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h ->{
                addSlot(new SlotItemHandler(h, 0, 62, 33));
                addSlot(new SlotItemHandler(h, 1, 154, 7));
            });
        }

        layoutPlayerInventorySlots(8, 86); //Position of player inventory
    }

    public TileEntity getTileEntity() {
        return tileEntity;
    }

    @Override
    public boolean canInteractWith(PlayerEntity playerIn) {
        if(tileEntity.getWorld() == null)
            return false;

        return isWithinUsableDistance(IWorldPosCallable.of(tileEntity.getWorld(), tileEntity.getPos()), playerIn, ModBlocks.FIRE_HOSE_BOX.get());
    }

    private int addSlotRange(IItemHandler handler, int index, int x, int y, int amount, int dx) {
        for (int i = 0; i < amount; i++) {
            addSlot(new SlotItemHandler(handler, index, x, y));
            x += dx;
            index++;
        }

        return index;
    }

    private void addSlotBox(IItemHandler handler, int index, int x, int y, int horAmount, int dx, int verAmount, int dy) {
        for (int j = 0; j < verAmount; j++) {
            index = addSlotRange(handler, index, x, y, horAmount, dx);
            y += dy;
        }
    }

    private void layoutPlayerInventorySlots(int leftCol, int topRow) {
        addSlotBox(playerInventory, 9, leftCol, topRow, 9, 18, 3, 18);

        topRow += 58;
        addSlotRange(playerInventory, 0, leftCol, topRow, 9, 18);
    }

    private static final int HOTBAR_SLOT_COUNT = 9;
    private static final int PLAYER_INVENTORY_ROW_COUNT = 3;
    private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9;
    private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT;
    private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT;
    private static final int VANILLA_FIRST_SLOT_INDEX = 0;
    private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT;
    // THIS YOU HAVE TO DEFINE!
    private static final int TE_INVENTORY_SLOT_COUNT = 2;  // must match TileEntityInventoryBasic.NUMBER_OF_SLOTS

    @Override
    public ItemStack transferStackInSlot(PlayerEntity playerIn, int index) {
        Slot sourceSlot = inventorySlots.get(index);
        if (sourceSlot == null || !sourceSlot.getHasStack()) return ItemStack.EMPTY;  //EMPTY_ITEM
        ItemStack sourceStack = sourceSlot.getStack();
        ItemStack copyOfSourceStack = sourceStack.copy();

        // Check if the slot clicked is one of the vanilla container slots
        if (index < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) {
            // This is a vanilla container slot so merge the stack into the tile inventory
            if (!mergeItemStack(sourceStack, TE_INVENTORY_FIRST_SLOT_INDEX, TE_INVENTORY_FIRST_SLOT_INDEX
                    + TE_INVENTORY_SLOT_COUNT, false)) {
                return ItemStack.EMPTY;  // EMPTY_ITEM
            }
        } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) {
            // This is a TE slot so merge the stack into the players inventory
            if (!mergeItemStack(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) {
                return ItemStack.EMPTY;
            }
        } else {
            return ItemStack.EMPTY;
        }
        // If stack size == 0 (the entire stack was moved) set slot contents to null
        if (sourceStack.getCount() == 0) {
            sourceSlot.putStack(ItemStack.EMPTY);
        } else {
            sourceSlot.onSlotChanged();
        }
        sourceSlot.onTake(playerEntity, sourceStack);
        return copyOfSourceStack;
    }


}

 

Screen

Spoiler
package de.j3ramy.edom.screen;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import de.j3ramy.edom.EdomMod;
import de.j3ramy.edom.container.FireHoseBoxContainer;
import de.j3ramy.edom.tileentity.FireHoseBoxTile;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class FireHoseBoxScreen extends ContainerScreen<FireHoseBoxContainer> {

    private final ResourceLocation GUI = new ResourceLocation(EdomMod.MOD_ID, "textures/gui/fire_hose_box_gui.png");
    FireHoseBoxContainer container;

    public FireHoseBoxScreen(FireHoseBoxContainer screenContainer, PlayerInventory inv, ITextComponent title) {
        super(screenContainer, inv, title);

        this.container = screenContainer;
    }

    @Override
    public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
        this.renderBackground(matrixStack);
        super.render(matrixStack, mouseX, mouseY, partialTicks);
        this.renderHoveredTooltip(matrixStack, mouseX, mouseY);
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int x, int y) {
        RenderSystem.color4f(1f, 1f, 1f, 1f);

        if(minecraft != null)
            this.minecraft.getTextureManager().bindTexture(GUI);

        int i = this.guiLeft;
        int j = this.guiTop;
        this.blit(matrixStack, i, j, 0, 0, this.xSize, this.ySize);

        FireHoseBoxTile te = (FireHoseBoxTile) container.getTileEntity();

        int yPos = j + 26 + te.getWaterLevel();
        this.blit(matrixStack, i + 156, yPos, 176, 0, 12, 1);

        //System.out.println(te.getWaterLevel());
    }
}

 

 

Posted

Thanks for the answer!

I changed it to the following but it hasn't solved the problem:

Spoiler
package de.j3ramy.edom.block;

import de.j3ramy.edom.container.FireHoseBoxContainer;
import de.j3ramy.edom.tileentity.FireHoseBoxTile;
import de.j3ramy.edom.tileentity.ModTileEntities;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.HorizontalBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.state.StateContainer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvents;
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.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;

import javax.annotation.Nullable;
import java.util.stream.Stream;

public class FireHoseBox extends HorizontalBlock {

    static final VoxelShape SHAPE_N = Stream.of(
            Block.makeCuboidShape(0, 2, 0, 16, 16, 6),
            Block.makeCuboidShape(2, 8, 6, 3, 10, 6.5),
            Block.makeCuboidShape(11, 0, 3, 12, 2, 4),
            Block.makeCuboidShape(11, 0, 0, 12, 1, 3),
            Block.makeCuboidShape(9, 0, 0, 10, 1, 3),
            Block.makeCuboidShape(9, 0, 3, 10, 2, 4)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    static final VoxelShape SHAPE_W = Stream.of(
            Block.makeCuboidShape(0, 2, 0, 6, 16, 16),
            Block.makeCuboidShape(6, 8, 13, 6.5, 10, 14),
            Block.makeCuboidShape(3, 0, 4, 4, 2, 5),
            Block.makeCuboidShape(0, 0, 4, 3, 1, 5),
            Block.makeCuboidShape(0, 0, 6, 3, 1, 7),
            Block.makeCuboidShape(3, 0, 6, 4, 2, 7)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    static final VoxelShape SHAPE_S = Stream.of(
            Block.makeCuboidShape(0, 2, 10, 16, 16, 16),
            Block.makeCuboidShape(13, 8, 9.5, 14, 10, 10),
            Block.makeCuboidShape(4, 0, 12, 5, 2, 13),
            Block.makeCuboidShape(4, 0, 13, 5, 1, 16),
            Block.makeCuboidShape(6, 0, 13, 7, 1, 16),
            Block.makeCuboidShape(6, 0, 12, 7, 2, 13)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    static final VoxelShape SHAPE_E = Stream.of(
            Block.makeCuboidShape(10, 2, 0, 16, 16, 16),
            Block.makeCuboidShape(9.5, 8, 2, 10, 10, 3),
            Block.makeCuboidShape(12, 0, 11, 13, 2, 12),
            Block.makeCuboidShape(13, 0, 11, 16, 1, 12),
            Block.makeCuboidShape(13, 0, 9, 16, 1, 10),
            Block.makeCuboidShape(12, 0, 9, 13, 2, 10)
    ).reduce((v1, v2) -> VoxelShapes.combineAndSimplify(v1, v2, IBooleanFunction.OR)).get();

    public FireHoseBox(Properties props) {
        super(props);
    }

    @Override
    public VoxelShape getShape(BlockState state, IBlockReader p_220053_2_, BlockPos p_220053_3_, ISelectionContext p_220053_4_) {
        switch (state.get(HORIZONTAL_FACING)){
            case SOUTH: return SHAPE_S;
            case EAST: return SHAPE_E;
            case WEST: return SHAPE_W;
            default: return SHAPE_N;
        }
    }

    @Override
    protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {
        builder.add(HORIZONTAL_FACING);
    }

    @Nullable
    @Override
    public BlockState getStateForPlacement(BlockItemUseContext context) {
        return this.getDefaultState().with(HORIZONTAL_FACING, context.getPlacementHorizontalFacing());
    }

    @Override
    public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {

        if(!worldIn.isRemote){
            worldIn.playSound(null, pos, SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN, SoundCategory.BLOCKS, 1, 1);
            FireHoseBoxTile tileEntity = (FireHoseBoxTile) worldIn.getTileEntity(pos);

            if(tileEntity == null)
                return ActionResultType.SUCCESS;

            if(player.isCrouching())
                return ActionResultType.SUCCESS;

            INamedContainerProvider containerProvider = createContainerProvider(worldIn, pos);
            NetworkHooks.openGui((ServerPlayerEntity) player, containerProvider, tileEntity.getPos());

        }

        return ActionResultType.SUCCESS;
    }

    private INamedContainerProvider createContainerProvider(World world, BlockPos pos) {
        return new INamedContainerProvider(){

            @Override
            public Container createMenu(int i, PlayerInventory playerInv, PlayerEntity playerEntity) {
                return new FireHoseBoxContainer(i, world, pos, playerInv, playerEntity, (FireHoseBoxTile) world.getTileEntity(pos));
            }

            @Override
            public ITextComponent getDisplayName() {
                return new TranslationTextComponent("");
            }
        };
    }

    @Override
    public boolean hasTileEntity(BlockState state) {
        return true;
    }

    @Nullable
    @Override
    public TileEntity createTileEntity(BlockState state, IBlockReader world) {
        return ModTileEntities.FIRE_HOSE_BOX_TILE.get().create();
    }
}

 

 

Posted

Oh nice. Thanks for that hint.

I only knew that static means that you don't need an instance of a class but it also means that the value of the static variable is the same in every instance.

It seems to work for now :)

 

Posted

Hey guys, I ran in another problem now.

I am trying to sync the water level between server and client. Client because I want to use it in the Screen class. But the water level is always 0 in the Screen class. I've read that I need to override getUpdateTag() and handleUpdateTag().

But I don't now what to override. I googled a lot but I'm not figuring out how that should work.

Tile entity

Spoiler
package de.j3ramy.edom.tileentity;

import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemStackHandler;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class FireHoseBoxTile extends TileEntity {

    public final ItemStackHandler itemHandler = createHandler();
    private final LazyOptional<IItemHandler> handler = LazyOptional.of(() -> itemHandler);

    private int waterLevel = 0;
    private static final int MAX_WATER_LEVEL = 45;
    private static final int STEPS = 3;
    private static final int WATER_LEVEL_INTERVAL = MAX_WATER_LEVEL / STEPS;

    private static final int HOSE_SLOT = 0;
    private static final int FILL_SLOT = 1;

    public int getWaterLevel() {
        return this.waterLevel;
    }

    public FireHoseBoxTile(TileEntityType<?> tileEntityType) {
        super(tileEntityType);
    }

    public FireHoseBoxTile(){
        this(ModTileEntities.FIRE_HOSE_BOX_TILE.get());
    }

    @Override
    public void read(BlockState state, CompoundNBT nbt) {
        itemHandler.deserializeNBT(nbt.getCompound("inv"));

        if(nbt.contains("waterLevel"))
            this.waterLevel = nbt.getInt("waterLevel");

        super.read(state, nbt);
    }

    @Override
    public CompoundNBT write(CompoundNBT nbt) {
        nbt.put("inv", itemHandler.serializeNBT());
        nbt.putInt("waterLevel", this.waterLevel);
        return super.write(nbt);
    }

    @Override
    public CompoundNBT getUpdateTag() {
        return super.getUpdateTag();
    }

    @Override
    public void handleUpdateTag(BlockState state, CompoundNBT tag) {
        super.handleUpdateTag(state, tag);
    }

    @Nonnull
    @Override
    public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {
        //Place code for setting that atm storage is only clickable from one side...
        if(cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
            return handler.cast();

        return super.getCapability(cap, side);
    }

    private ItemStackHandler createHandler(){
        return new ItemStackHandler(2){
            @Override
            protected void onContentsChanged(int slot) {
                if(world == null)
                    return;

                if(!isItemValid(slot, getStackInSlot(slot))){
                    return;
                }

                switch (slot){
                    case HOSE_SLOT:  break;
                    case FILL_SLOT: fillFireBox(); break;
                }
            }

            @Override
            public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
                switch(slot){
                    case HOSE_SLOT: return stack.getItem() == Items.WATER_BUCKET;
                    case FILL_SLOT: return stack.getItem() == Items.WATER_BUCKET;
                }
                return false;
            }

            @Override
            public int getSlotLimit(int slot) {
                return 1;
            }

            @Nonnull
            @Override
            public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) {

                return super.insertItem(slot, stack, simulate);
            }
        };
    }

    void fillFireBox(){
        if(this.waterLevel < MAX_WATER_LEVEL){
            itemHandler.getStackInSlot(FILL_SLOT).shrink(1);
            this.waterLevel += WATER_LEVEL_INTERVAL;
        }
    }
}

 

Screen

Spoiler
package de.j3ramy.edom.screen;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import de.j3ramy.edom.EdomMod;
import de.j3ramy.edom.container.FireHoseBoxContainer;
import de.j3ramy.edom.tileentity.FireHoseBoxTile;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class FireHoseBoxScreen extends ContainerScreen<FireHoseBoxContainer> {

    private final ResourceLocation GUI = new ResourceLocation(EdomMod.MOD_ID, "textures/gui/fire_hose_box_gui.png");
    FireHoseBoxContainer container;

    public FireHoseBoxScreen(FireHoseBoxContainer screenContainer, PlayerInventory inv, ITextComponent title) {
        super(screenContainer, inv, title);

        this.container = screenContainer;
    }

    @Override
    public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
        this.renderBackground(matrixStack);
        super.render(matrixStack, mouseX, mouseY, partialTicks);
        this.renderHoveredTooltip(matrixStack, mouseX, mouseY);
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int x, int y) {
        RenderSystem.color4f(1f, 1f, 1f, 1f);

        if(minecraft != null)
            this.minecraft.getTextureManager().bindTexture(GUI);

        int i = this.guiLeft;
        int j = this.guiTop;
        this.blit(matrixStack, i, j, 0, 0, this.xSize, this.ySize);

        FireHoseBoxTile te = (FireHoseBoxTile) container.getTileEntity();
        FireHoseBoxTile tileEntity = (FireHoseBoxTile) te.getWorld().getTileEntity(te.getPos());

        int yPos = j + 26 + tileEntity.getWaterLevel();
        this.blit(matrixStack, i + 156, yPos, 176, 0, 12, 1);
    }
}

 

 

Posted (edited)

Either I'm just blind or there is no addDataSlot in AbstractFurnaceContainer ^^

 

Edited by diesieben07
removed copyright protected Mojang code
Posted

Oh sorry I didn't know that. 

I just added the method but I don't know if it's right. May you have a look:

Spoiler
package de.j3ramy.edom.container;

import de.j3ramy.edom.block.ModBlocks;
import de.j3ramy.edom.tileentity.FireHoseBoxTile;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IWorldPosCallable;
import net.minecraft.util.IntReferenceHolder;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import net.minecraftforge.items.wrapper.InvWrapper;

public class FireHoseBoxContainer extends Container {

    private final FireHoseBoxTile tileEntity;
    private final PlayerEntity playerEntity;
    private final IItemHandler playerInventory;

    public FireHoseBoxContainer(int windowId, World world, BlockPos pos, PlayerInventory playerInventory, PlayerEntity player, FireHoseBoxTile tile){
        super(ModContainers.FIRE_HOSE_BOX_CONTAINER.get(), windowId);

        this.tileEntity = tile;
        this.playerEntity = player;
        this.playerInventory = new InvWrapper(playerInventory);

        if(tileEntity != null){
            tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h ->{
                addSlot(new SlotItemHandler(h, 0, 62, 33));
                addSlot(new SlotItemHandler(h, 1, 154, 7));
            });
        }

        layoutPlayerInventorySlots(8, 86); //Position of player inventory
    }

    public TileEntity getTileEntity() {
        return tileEntity;
    }

	...

    @Override
    protected IntReferenceHolder trackInt(IntReferenceHolder intIn) {
        intIn.set(tileEntity.getWaterLevel());
        return super.trackInt(intIn);
    }
}

 

 

Posted

I have to call it where? Sorry, but the syncing is new to me and I don't really understand it. Because if I have to call it, I have to save the value somewhere right? Or is this done automatically in the tile entity or container class?

Posted

Okay thanks, I think I figured out. 

Now, the water level indicator in the screen class only gets updated when I open the container obviously because I set the water level in the constructor of the container class.

I want to achieve that the value gets updated when I put a water bucket in the slot, so actually in the tile entity item handler. Is that possible or do I always have to reopen the container?

Container constructor

Spoiler
public FireHoseBoxContainer(int windowId, World world, BlockPos pos, PlayerInventory playerInventory, PlayerEntity player, FireHoseBoxTile tile){
        super(ModContainers.FIRE_HOSE_BOX_CONTAINER.get(), windowId);

        this.tileEntity = tile;
        this.playerEntity = player;
        this.playerInventory = new InvWrapper(playerInventory);

        if(tileEntity != null){
            tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).ifPresent(h ->{
                addSlot(new SlotItemHandler(h, 0, 62, 33));
                addSlot(new SlotItemHandler(h, 1, 154, 7));
            });
        }

        layoutPlayerInventorySlots(8, 86); //Position of player inventory

        data = new IntArray(1);
        data.set(0, tile.getWaterLevel());
        this.trackIntArray(data);
    }

 

Screen class

Spoiler
package de.j3ramy.edom.screen;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import de.j3ramy.edom.EdomMod;
import de.j3ramy.edom.container.FireHoseBoxContainer;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class FireHoseBoxScreen extends ContainerScreen<FireHoseBoxContainer> {

    private final ResourceLocation GUI = new ResourceLocation(EdomMod.MOD_ID, "textures/gui/fire_hose_box_gui.png");
    FireHoseBoxContainer container;

    public FireHoseBoxScreen(FireHoseBoxContainer screenContainer, PlayerInventory inv, ITextComponent title) {
        super(screenContainer, inv, title);

        this.container = screenContainer;
    }

    @Override
    public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
        this.renderBackground(matrixStack);
        super.render(matrixStack, mouseX, mouseY, partialTicks);
        this.renderHoveredTooltip(matrixStack, mouseX, mouseY);
    }

    @Override
    protected void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int x, int y) {
        RenderSystem.color4f(1f, 1f, 1f, 1f);

        if(minecraft != null)
            this.minecraft.getTextureManager().bindTexture(GUI);

        int i = this.guiLeft;
        int j = this.guiTop;
        this.blit(matrixStack, i, j, 0, 0, this.xSize, this.ySize);

        //FireHoseBoxTile te = (FireHoseBoxTile) container.getTileEntity();

        int yPos = j + 26 + container.getData().get(0);
        this.blit(matrixStack, i + 156, yPos, 176, 0, 12, 1);
    }
}

 

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.