Jump to content

[1.8][SOLVED] Tile Entity dosen't save integer in private field


TheCrafter4000

Recommended Posts

Hello guys,

 

I'm making an furnace with 2 input and fuel slots, but when I wanted to set the burntime in a function it does not save it in my field.

 

My Tile Entity class:

package tc4modpack.thecrafter4000.tc4ores.fusion;

import java.util.Arrays;

import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.gui.IUpdatePlayerListBox;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class FusionTileEntity extends TileEntity implements IInventory, IUpdatePlayerListBox{

/** 0 = Input Left,
 *  1 = Input Right,
 *  2 = Fuel Left,
 *  3 = Fuel Right,
 *  4 = Fusion Output */
private ItemStack[] inventory = new ItemStack[ getSizeInventory() ];
/** The burntime for the left slot*/
private int burntime0 = 0;
/** The burntime for the right slot*/
private int burntime1 = 0;
private int cooktime = 0;

@Override public void readFromNBT(NBTTagCompound compound) {
	super.readFromNBT(compound);
	int i = 0;
	for( ItemStack s : inventory ) {
		inventory[ i ] = null;
		if( compound.hasKey( "slot_" +i ) ) inventory[ i ] = ItemStack.loadItemStackFromNBT( compound.getCompoundTag( "slot_" +i ) );
		i++;
	}
	burntime0 = compound.getInteger("burntime0");
	burntime1 = compound.getInteger("burntime1");
	cooktime = compound.getInteger("cooktime");
}

@Override public void writeToNBT( NBTTagCompound tag ) {
	super.writeToNBT( tag );
	NBTTagCompound[] stacks = new NBTTagCompound[ getSizeInventory() ];
	Arrays.fill( stacks, new NBTTagCompound() );
	int i = 0;
	for( NBTTagCompound c : stacks ) {
		tag.removeTag( "slot_" + i );
		if( inventory[ i ] != null ) {
			inventory[ i ].writeToNBT( c );
			tag.setTag("slot_" + i , c );
		}
		i++;
	}
	tag.setInteger("burntime0", burntime0);
	tag.setInteger("burntime1", burntime1);
	tag.setInteger("cooktime", cooktime);
}

@Override public String getName() {
	return "Fusion Furnace";
}

@Override public boolean hasCustomName() {
	return true;
}

@Override public IChatComponent getDisplayName() {
	return new ChatComponentText( getName() );
}

@Override public int getSizeInventory() {
	return 5;
}

@Override public ItemStack getStackInSlot(int index) {
	return inventory[ index ];
}

@Override public ItemStack decrStackSize(int index, int count) {
	if (inventory[index] != null)
	{
		ItemStack itemstack;

		if (inventory[index].stackSize <= count)
		{
			itemstack = inventory[index];
			inventory[index] = null;
			markDirty();
			return itemstack;
		}
		else
		{
			itemstack = inventory[index].splitStack(count);

			if (inventory[index].stackSize == 0)
			{
				inventory[index] = null;
			}

			markDirty();
			return itemstack;
		}
	}
	else
	{
		return null;
	}
}

@Override public ItemStack getStackInSlotOnClosing(int index) {
	return getStackInSlot( index );
}

@Override public void setInventorySlotContents(int index, ItemStack stack) {
	inventory[ index ] = stack;
}

@Override public int getInventoryStackLimit() {
	return 64;
}

@Override public boolean isUseableByPlayer(EntityPlayer player) {
	return true;
}

@Override public void openInventory(EntityPlayer player) {}

@Override public void closeInventory(EntityPlayer player) {}

@Override public boolean isItemValidForSlot(int index, ItemStack stack) {
	switch( index ) {
	case 0: return true;
	case 1: return true;
	case 2: return TileEntityFurnace.isItemFuel( stack );
	case 3: return TileEntityFurnace.isItemFuel( stack );
	default: return false;
	}

}

@Override public int getField(int id) {
	return (id==0) ? burntime0 : burntime1;
}

@Override public void setField(int id, int value) {
	switch( id ) {
	case 0: burntime0 = value;
	case 1: burntime1 = value;
	}
}

@Override public int getFieldCount() {
	return 2;
}

@Override public void clear() {
	inventory = new ItemStack[ getSizeInventory() ];
}

@Override public void update() {
	if( !worldObj.isRemote ) { // Server Side
		System.out.println( burntime0 + "," + burntime1 + "," + cooktime + "," + isAktivated() );
		if( isAktivated() ) { // if it burns
			if( burntime0 > 0 ) burntime0--; // increase burntime
			else stopBurning();
			if( burntime1 > 0 ) burntime1--;
			else stopBurning();
			if( inventory[0] != null && inventory[1] != null ) cooktime++; // if it burns it increase the cooktime
			else cooktime = 0;
			if( cooktime >= 200 ) { // if its finished
				cooktime = 0;
				if( inventory[0].stackSize > 1 ) inventory[0].stackSize = inventory[0].stackSize-1;
				else inventory[0] = null;
				if( inventory[1].stackSize > 1 ) inventory[1].stackSize = inventory[1].stackSize-1;
				else inventory[1] = null;
				inventory[4] = new ItemStack( Items.beef );
			}
		}
		else if( cooktime > 0 ) cooktime--;
		if( !isAktivated() && canSmelt() ) { // if it does not burn but it can
			startBurning(); // it starts burning
			System.out.println( "Startet Burning" );
		}
		System.out.println( burntime0 + "," + burntime1 + "," + cooktime + "," + isAktivated() );
	}
}

protected boolean canSmelt() {
	if( inventory[0] != null && inventory[1] != null && (inventory[2] != null || burntime0 > 0 ) && (inventory[3] != null || burntime1 > 0 ) ) return true;
	return false;
}

protected boolean isAktivated() {
	return (Boolean) worldObj.getBlockState(pos).getValue(FusionFurnace.ACTIVATED);
}

protected void startBurning() {
	System.out.println( "An" );
	FusionFurnace.activate( worldObj, pos, true );
	if( burntime0 <= 0 && inventory[2] != null ) {
//			burntime0 = TileEntityFurnace.getItemBurnTime( inventory[2] );
		burntime0 = 1600;
		if( inventory[2].stackSize > 1 ) inventory[2].stackSize = inventory[2].stackSize-1;
		else inventory[2] = null;
	}
	if( burntime1 <= 0 && inventory[3] != null ) {
//			burntime1 = TileEntityFurnace.getItemBurnTime( inventory[3] );
		burntime1 = 1500;
		if( inventory[3].stackSize > 1 ) inventory[3].stackSize = inventory[3].stackSize-1;
		else inventory[3] = null;
	}
}

protected void stopBurning() {
	System.out.println( "Aus" );
	FusionFurnace.activate( worldObj, pos, false );
}

public static boolean isBurning( FusionTileEntity entity ) {
	return (entity.burntime0 > 0 && entity.burntime1 > 0);
}
}

 

The output log is magic:

[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:update:165]: 0,0,0,false // First run
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:startBurning:202]: An // starts burning
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionFurnace:activate:91]: Aktive //sets blockState
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:update:185]: Startet Burning // stated burning
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:update:187]: 1600,1500,0,true // end of the first run
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:update:165]: 0,0,0,true // second run the values are zero! WHY?
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:stopBurning:220]: Aus
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionFurnace:activate:91]: Aktive
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:stopBurning:220]: Aus
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionFurnace:activate:91]: Aktive
[22:13:09] [server thread/INFO] [sTDOUT]: [tc4modpack.thecrafter4000.tc4ores.fusion.FusionTileEntity:update:187]: 0,0,0,false

 

After the first run the values are reset. I don't know [glow=red,2,300]WHY[/glow], can anybody help me?

Sorry if there are mistakes in my english

Link to comment
Share on other sites

Stil trying to figure it out but:

 

if (cooktime >= 200) {
      do something with inventory slots
}

What if the inventory slots are null? Always check if they are null.

 

Could you post the block, gui, container, and guiHandler classes please? That would speed things up a bit..

I might be terribly wrong.. Like really, really wrong. But I'm just trying to help.

Link to comment
Share on other sites

also, you check

slot.stacksize > 1

which means that if you put one item in, it won't smelt.

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

if you put one item in, it won't smelt

 

Yeah, your right.

 

What if the inventory slots are null? Always check if they are null.

 

Your're right too.

 

My Container Class:

 

package tc4modpack.thecrafter4000.tc4ores.fusion;

import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.inventory.SlotFurnaceFuel;
import net.minecraft.inventory.SlotFurnaceOutput;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;

public class FusionContainer extends Container {

private FusionTileEntity entity;
private IBlockState block;

public FusionContainer( InventoryPlayer player, World world, BlockPos pos ) {
	entity = (FusionTileEntity) world.getTileEntity(pos);
	block = world.getBlockState(pos);
	addSlotToContainer( new Slot( entity, 0, 26,18 ) );
	addSlotToContainer( new SlotFurnaceFuel( entity, 2, 26,54 ) );

	addSlotToContainer( new SlotFurnaceOutput( player.player, entity, 4, 44,26 ) );

	addSlotToContainer( new Slot( entity, 1, 62,18 ) );
	addSlotToContainer( new SlotFurnaceFuel( entity, 3, 62,54 ) );

	for (int i = 0; i < 3; ++i)
	{
		for (int j = 0; j < 9; ++j)
		{
			addSlotToContainer(new Slot(player, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
		}
	}

	for (int i = 0; i < 9; ++i)
	{
		addSlotToContainer(new Slot(player, i, 8 + i * 18, 142));
	}
}

@Override public boolean canInteractWith(EntityPlayer playerIn) {
	return true;
}

@Override public ItemStack transferStackInSlot(EntityPlayer playerIn, int fromSlot) {
	ItemStack previous = null;
	Slot slot = (Slot) inventorySlots.get(fromSlot);

	if (slot != null && slot.getHasStack()) {
		ItemStack current = slot.getStack();
		previous = current.copy();

		if (fromSlot < 14) {
			// From TE Inventory to Player Inventory
			if (!mergeItemStack(current,14, inventorySlots.size(), true))
				return null;
		} else {
			// From Player Inventory to TE Inventory
			if (!mergeItemStack(current, 0, 14, false))
				return null;
		}

		if (current.stackSize == 0)
			slot.putStack((ItemStack) null);
		else
			slot.onSlotChanged();

		if (current.stackSize == previous.stackSize)
			return null;
		slot.onPickupFromSlot(playerIn, current);
	}
	return previous;
}
}

 

My Gui Class:

 

package tc4modpack.thecrafter4000.tc4ores.fusion;

import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;

public class FusionGui extends GuiContainer {

private InventoryPlayer player;
private FusionTileEntity entity;

public FusionGui( InventoryPlayer player, World world, BlockPos pos ) {
	super( new FusionContainer( player, world, pos ) );

	this.player = player;
	entity = (FusionTileEntity) world.getTileEntity(pos);

	xSize = 176;
	ySize = 166;
}

@Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
	GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
	mc.getTextureManager().bindTexture( new ResourceLocation("tc4ores:textures/gui/fusion.png") );
	this.drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);
}

@Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
	String s = entity.getDisplayName().getUnformattedText();
	fontRendererObj.drawString(s, 88 - fontRendererObj.getStringWidth(s) / 2, 6, 4210752);            //#404040
	fontRendererObj.drawString(player.getDisplayName().getUnformattedText(), 8, 72, 4210752);      //#404040
}
}

 

My Block Class:

 

package tc4modpack.thecrafter4000.tc4ores.fusion;

import java.util.List;

import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import scala.actors.threadpool.Arrays;
import tc4modpack.thecrafter4000.api.block.IMetaBlockName;
import tc4modpack.thecrafter4000.tc4ores.TC4Ores;

public class FusionFurnace extends BlockContainer implements IMetaBlockName{

public static final PropertyDirection FACING = PropertyDirection.create("facing");
public static final PropertyBool ACTIVATED = PropertyBool.create("activated");

/** A List of all BlockStates the Block can have */
private final IBlockState[] BlockStates = new IBlockState[] {
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.NORTH ).withProperty(FusionFurnace.ACTIVATED, true),
		getDefaultState(),
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.EAST ).withProperty(FusionFurnace.ACTIVATED, true),
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.EAST ).withProperty(FusionFurnace.ACTIVATED, false),
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.SOUTH ).withProperty(FusionFurnace.ACTIVATED, true),
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.SOUTH ).withProperty(FusionFurnace.ACTIVATED, false),
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.WEST ).withProperty(FusionFurnace.ACTIVATED, true),
		getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.WEST ).withProperty(FusionFurnace.ACTIVATED, false)
};

public FusionFurnace( Material materialIn, String name ) {
	super( materialIn );
	setUnlocalizedName( name );
	setDefaultState( super.getDefaultState().withProperty(FusionFurnace.FACING, EnumFacing.NORTH).withProperty(FusionFurnace.ACTIVATED, false) );
}

@Override public TileEntity createNewTileEntity(World worldIn, int meta) {
	return new FusionTileEntity();
}

@Override public String getSpecialName(ItemStack stack) {
	return "";
}

@Override public int getRenderType() {
	return 3;
}

@Override protected BlockState createBlockState() {
	return new BlockState( this, new IProperty[]{ FusionFurnace.FACING, FusionFurnace.ACTIVATED } );
}

@Override public IBlockState getStateFromMeta(int meta) {
	return BlockStates[ meta ];
}

@Override public int getMetaFromState(IBlockState state) {
	List<IBlockState> list = Arrays.asList(BlockStates);
	int i = list.indexOf( state );
	if( i == -1 ) i = 1;
	return i;
}

@Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ) {
	playerIn.openGui(TC4Ores.instance, 0, worldIn, pos.getX(), pos.getY(), pos.getZ());
	return true;
}

@Override public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
	switch( placer.getHorizontalFacing().getOpposite() ) {
	case NORTH: return BlockStates[1];
	case EAST:  return BlockStates[3];
	case SOUTH: return BlockStates[5];
	case WEST:  return BlockStates[7];
	default: {
		return getDefaultState();
	}
	}
}

static void activate( World world, BlockPos pos, boolean on ) {
	System.out.println( "Aktive" );
	world.setBlockState( pos, world.getBlockState( pos ).withProperty(FusionFurnace.ACTIVATED, on) );
}
}

 

My GuiHandler Class:

 

package tc4modpack.thecrafter4000.tc4ores;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import tc4modpack.thecrafter4000.tc4ores.fusion.FusionContainer;
import tc4modpack.thecrafter4000.tc4ores.fusion.FusionGui;


public class TC4GuiHandler implements IGuiHandler{

public static final int FUSION_GUI = 0;

@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	if( ID == TC4GuiHandler.FUSION_GUI ) return new FusionContainer( player.inventory, world, new BlockPos( x,y,z ));
	return null;
}

@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
	if( ID == TC4GuiHandler.FUSION_GUI ) return new FusionGui( player.inventory , world, new BlockPos( x,y,z ));
	return null;
}

}

Sorry if there are mistakes in my english

Link to comment
Share on other sites

  • 2 weeks later...

Aha, that new default behavior frustrated one of my recent mods too. Your TE class needs to override a method:

 

    @Override
    public boolean shouldRefresh(World w, BlockPos pos, IBlockState oldState, IBlockState newState) {
        ...
    }

 

Be sure that it returns true when a refresh is really in order, otherwise you could leave stale TE's in the world. Look at the super to see what I mean.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

Link to comment
Share on other sites

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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I am creating a mod that adds new armor sets and changes how armor sets are crafted. When the player interacts with the block it fails to open the gui, but I get no error or stacktrace. All of my registration classes are being called correctly. LightArmorBenchScreen's constructor, render, and renderbg methods are not being called at all. Here is the code: package net.leeveygames.celestial.blocks.custom; import net.leeveygames.celestial.Celestial; import net.leeveygames.celestial.blocks.entity.CelestialBlockEntities; import net.leeveygames.celestial.blocks.entity.LightArmorBenchBlockEntity; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.network.NetworkHooks; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LightArmorBenchBlock extends BaseEntityBlock { public static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 12, 16); public LightArmorBenchBlock(Properties pProperties) { super(pProperties); } @Override public VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) { return SHAPE; } @Override public RenderShape getRenderShape(BlockState pState) { return RenderShape.MODEL; } @Override public void onRemove(BlockState pState, Level pLevel, BlockPos pPos, BlockState pNewState, boolean pIsMoving) { if (pState.getBlock() != pNewState.getBlock()) { BlockEntity blockEntity = pLevel.getBlockEntity(pPos); if (blockEntity instanceof LightArmorBenchBlockEntity) { ((LightArmorBenchBlockEntity) blockEntity).drops(); } } super.onRemove(pState, pLevel, pPos, pNewState, pIsMoving); } @NotNull @Override public InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, BlockHitResult pHit) { if(pLevel.isClientSide()) return InteractionResult.SUCCESS; BlockEntity be = pLevel.getBlockEntity(pPos); if (be instanceof LightArmorBenchBlockEntity blockEntity) { ServerPlayer player = (ServerPlayer)pPlayer; Celestial.LOGGER.info("Opening Screen."); NetworkHooks.openScreen(player, blockEntity, pPos); } return InteractionResult.CONSUME; } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) { return new LightArmorBenchBlockEntity(pPos, pState); } @Nullable @Override public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level pLevel, BlockState pState, BlockEntityType<T> pBlockEntityType) { if(pLevel.isClientSide()) { return null; } return createTickerHelper(pBlockEntityType, CelestialBlockEntities.LIGHT_ARMOR_BENCH_BLOCK_ENTITY.get(), (pLevel1, pPos, pState1, pBlockEntity) -> pBlockEntity.tick(pLevel1, pPos, pState1)); } }   package net.leeveygames.celestial.screen; import net.leeveygames.celestial.Celestial; import net.leeveygames.celestial.blocks.CelestialBlocks; import net.leeveygames.celestial.blocks.entity.LightArmorBenchBlockEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.*; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.SlotItemHandler; public class LightArmorBenchMenu extends AbstractContainerMenu { public final LightArmorBenchBlockEntity blockEntity; private final Level level; public LightArmorBenchMenu(int pContainerId, Inventory inv, FriendlyByteBuf extraData) { this(pContainerId, inv, inv.player.level().getBlockEntity(extraData.readBlockPos())); Celestial.LOGGER.info("Creating Light Armor Bench Menu. Client"); } public LightArmorBenchMenu(int pContainerId, Inventory inv, BlockEntity entity) { super(CelestialMenuTypes.LIGHT_ARMOR_BENCH_MENU.get(), pContainerId); Celestial.LOGGER.info("Creating Light Armor Bench Menu. Server"); checkContainerSize(inv, 2); blockEntity = ((LightArmorBenchBlockEntity) entity); this.level = inv.player.level(); addPlayerInventory(inv); addPlayerHotbar(inv); createLightArmorBenchSlots(blockEntity); } private void createLightArmorBenchSlots(LightArmorBenchBlockEntity blockEntity) { Celestial.LOGGER.info("Creating Light Armor Bench Slots."); this.blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(iItemHandler -> { this.addSlot(new SlotItemHandler(iItemHandler, 0, 11, 15)); this.addSlot(new SlotItemHandler(iItemHandler, 1, 82, 33)); this.addSlot(new SlotItemHandler(iItemHandler, 2, 133, 33)); }); } // CREDIT GOES TO: diesieben07 | https://github.com/diesieben07/SevenCommons // must assign a slot number to each of the slots used by the GUI. // For this container, we can see both the tile inventory's slots as well as the player inventory slots and the hotbar. // Each time we add a Slot to the container, it automatically increases the slotIndex, which means // 0 - 8 = hotbar slots (which will map to the InventoryPlayer slot numbers 0 - 8) // 9 - 35 = player inventory slots (which map to the InventoryPlayer slot numbers 9 - 35) // 36 - 44 = TileInventory slots, which map to our TileEntity slot numbers 0 - 8) 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 be the number of slots you have! @Override public ItemStack quickMoveStack(Player playerIn, int pIndex) { Slot sourceSlot = slots.get(pIndex); if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; //EMPTY_ITEM ItemStack sourceStack = sourceSlot.getItem(); ItemStack copyOfSourceStack = sourceStack.copy(); // Check if the slot clicked is one of the vanilla container slots if (pIndex < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) { // This is a vanilla container slot so merge the stack into the tile inventory if (!moveItemStackTo(sourceStack, TE_INVENTORY_FIRST_SLOT_INDEX, TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT, false)) { return ItemStack.EMPTY; // EMPTY_ITEM } } else if (pIndex < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) { // This is a TE slot so merge the stack into the players inventory if (!moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) { return ItemStack.EMPTY; } } else { System.out.println("Invalid slotIndex:" + pIndex); return ItemStack.EMPTY; } // If stack size == 0 (the entire stack was moved) set slot contents to null if (sourceStack.getCount() == 0) { sourceSlot.set(ItemStack.EMPTY); } else { sourceSlot.setChanged(); } sourceSlot.onTake(playerIn, sourceStack); return copyOfSourceStack; } @Override public boolean stillValid(Player pPlayer) { return stillValid(ContainerLevelAccess.create(level, blockEntity.getBlockPos()), pPlayer, CelestialBlocks.LIGHT_ARMOR_BENCH.get()); } private void addPlayerInventory(Inventory playerInventory) { Celestial.LOGGER.info("Creating Player Inventory."); for (int i = 0; i < 3; ++i) { for (int l = 0; l < 9; ++l) { this.addSlot(new Slot(playerInventory, l + i * 9 + 9, 8 + l * 18, 84 + i * 18)); } } } private void addPlayerHotbar(Inventory playerInventory) { Celestial.LOGGER.info("Creating Player Hotbar."); for (int i = 0; i < 9; ++i) { this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142)); } } }   package net.leeveygames.celestial.screen; import com.mojang.blaze3d.systems.RenderSystem; import net.leeveygames.celestial.Celestial; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Inventory; public class LightArmorBenchScreen extends AbstractContainerScreen<LightArmorBenchMenu> { private static final ResourceLocation TEXTURE = new ResourceLocation(Celestial.MOD_ID, "textures/gui/LightArmorBenchGUI.png"); public LightArmorBenchScreen(LightArmorBenchMenu pMenu, Inventory pPlayerInventory, Component pTitle) { super(pMenu, pPlayerInventory, pTitle); Celestial.LOGGER.info("Creating Light Armor Bench Screen."); this.imageWidth = 176; this.imageHeight = 166; } @Override protected void init() { Celestial.LOGGER.info("Screen init."); super.init(); } @Override protected void renderBg(GuiGraphics guiGraphics, float pPartialTick, int pMouseX, int pMouseY) { Celestial.LOGGER.info("Render Background Method."); RenderSystem.setShader(GameRenderer::getPositionTexShader); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.setShaderTexture(0, TEXTURE); guiGraphics.blit(TEXTURE, this.leftPos, this.topPos, 0, 0, this.imageWidth, this.imageHeight); } @Override public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float delta) { Celestial.LOGGER.info("Render Method."); renderBackground(guiGraphics); super.render(guiGraphics, mouseX, mouseY, delta); renderTooltip(guiGraphics, mouseX, mouseY); } }   package net.leeveygames.celestial.blocks.entity; import net.leeveygames.celestial.screen.LightArmorBenchMenu; import net.minecraft.client.gui.screens.inventory.FurnaceScreen; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.Container; import net.minecraft.world.Containers; import net.minecraft.world.MenuProvider; import net.minecraft.world.SimpleContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerData; import net.minecraft.world.inventory.FurnaceMenu; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class LightArmorBenchBlockEntity extends BlockEntity implements MenuProvider { private final ItemStackHandler itemHandler = new ItemStackHandler(3) { @Override protected void onContentsChanged(int slot) { super.onContentsChanged(slot); LightArmorBenchBlockEntity.this.setChanged(); } }; private static final int INPUT_SLOT = 0; private static final int OUTPUT_SLOT = 1; private LazyOptional<IItemHandler> lazyItemHandler = LazyOptional.empty(); public LightArmorBenchBlockEntity(BlockPos pPos, BlockState pBlockState) { super(CelestialBlockEntities.LIGHT_ARMOR_BENCH_BLOCK_ENTITY.get(), pPos, pBlockState); } @Override public @NotNull <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) { if(cap == ForgeCapabilities.ITEM_HANDLER) { return lazyItemHandler.cast(); } return super.getCapability(cap, side); } @Override public void onLoad() { super.onLoad(); lazyItemHandler = LazyOptional.of(() -> itemHandler); } @Override public void invalidateCaps() { super.invalidateCaps(); lazyItemHandler.invalidate(); } public void drops() { SimpleContainer inventory = new SimpleContainer(itemHandler.getSlots()); for(int i = 0; i < itemHandler.getSlots(); i++) { inventory.setItem(i, itemHandler.getStackInSlot(i)); } Containers.dropContents(this.level, this.worldPosition, inventory); } @Override public Component getDisplayName() { return Component.translatable("block.celestial.light_armor_bench"); } @Nullable @Override public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) { return new LightArmorBenchMenu(pContainerId, pPlayerInventory, this); } @Override protected void saveAdditional(CompoundTag pTag) { pTag.put("inventory", itemHandler.serializeNBT()); super.saveAdditional(pTag); } @Override public void load(CompoundTag pTag) { super.load(pTag); itemHandler.deserializeNBT(pTag.getCompound("inventory")); } public void tick(Level pLevel, BlockPos pPos, BlockState pState) { } }   Here is the console output: https://pastebin.com/krgExnYT
  • Topics

×
×
  • Create New...

Important Information

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