Jump to content

Reading from NBT issue


BourgeoisArab

Recommended Posts

I am trying to make a custom cauldron and working out how to make it store water properly. I have it filling and emptying, but if it's filled, and I log out and then log in, it isn't filled anymore. I think it has something to do with my readFromNBT method, but I'm not sure. Can anyone point out where I went wrong?

 

Here is my Tile Entity class for it:

package jakoubeck503.alchemicalinstillation.common.tileentity;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidEvent;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import net.minecraftforge.fluids.IFluidTank;

public class TEBrewingCauldron extends TileEntity implements IFluidTank, IFluidHandler {

private FluidTank tank = new FluidTank(FluidContainerRegistry.BUCKET_VOLUME);
private boolean boiling = false;

public TEBrewingCauldron() {
	System.out.println("Creating a new tile entity...");
}

public void setBoiling(boolean par1) {
	this.boiling = par1;
	System.out.println("Cauldron " + (this.boiling==true ? "is" : "isn't") + " boiling!");
}

public boolean getBoiling() {
	return this.boiling;
}

public boolean isFillable() {
	if (tank.getFluid()!=null) {
		if (tank.getFluid().getFluid()==FluidRegistry.WATER && tank.getFluidAmount()<FluidContainerRegistry.BUCKET_VOLUME){
			return true;
		} else return false;
	} else return true;
}

@Override
    public void readFromNBT(NBTTagCompound nbt) {
	System.out.println("Reading from NBT...");
	super.readFromNBT(nbt);
        if (!nbt.hasKey("Empty")) {
            FluidStack fluid = this.tank.getFluid().loadFluidStackFromNBT(nbt);
            System.out.println(fluid.amount + "mB of " + fluid.getFluid());

            if (fluid!=null) {
                this.tank.setFluid(fluid);
            }
        }
        if (tank.getFluid().getFluid()!=FluidRegistry.WATER){
        	System.out.println("ERROR! Not equal to water...");
        }
    }

@Override
    public void writeToNBT(NBTTagCompound nbt) {
    	System.out.println("Writing to NBT...");
    	super.writeToNBT(nbt);
        if (tank.getFluid()!=null) {
        	tank.getFluid().writeToNBT(nbt);
        } else {
            nbt.setString("Empty", "");
        }
    }

@Override
public FluidStack getFluid() {
	return tank.getFluid();
}

@Override
public int getFluidAmount() {
	if (tank.getFluid()==null) {
		return 0;
	} else return tank.getFluidAmount();
}

@Override
public int getCapacity() {
	return tank.getCapacity();
}

@Override
public FluidTankInfo getInfo() {
	return tank.getInfo();
}

@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
	// TODO Auto-generated method stub
	return tank.fill(resource, doFill);
}

@Override
public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
	// TODO Auto-generated method stub
	return null;
}

@Override
public boolean canFill(ForgeDirection from, Fluid fluid) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public boolean canDrain(ForgeDirection from, Fluid fluid) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public FluidTankInfo[] getTankInfo(ForgeDirection from) {
	// TODO Auto-generated method stub
	return null;
}

    private void setFluid(FluidStack f) {
	this.tank.setFluid(f);
}

@Override
public int fill(FluidStack resource, boolean doFill) {
	return tank.fill(resource, doFill);
}

@Override
public FluidStack drain(int maxDrain, boolean doDrain) {
	return tank.drain(maxDrain, doDrain);
}


}

Link to comment
Share on other sites

Now, I am not the best with NBT but I think I see a problem. Your are using the key Empty a bit oddly. Imagine this situation.

 

1. You place a cauldron down. It is empty.

2. writeToNBT gets called. Since the tank is empty, "Empty" gets set a value

nbt.setString("Empty", "");

3. You put water in, writeToNBT gets called again.

4. Quit the world and log back in.

5.  readFromNBT runs. Here is the problem. On the first if statement it checks if the key "Empty" exists. It does! You set it earlier, it hasn't been removed in any way. Because it exists the rest of the code between the brackets is ignored. Fluid never gets set.

 

NOTE: I could be COMPLETELY wrong. However this feels right to me. i recommend you change the Empty key completely. Maybe to some kind of boolean? Not too familiar with NBT so you'll have to figure it out.

 

Good Luck

An average guy who mods Minecraft. If you need help and are willing to use your brain, don't be afraid to ask.

 

Also, check out the Unofficial Minecraft Coder Pack (MCP) Prerelease Center for the latest from the MCP Team!

 

Was I helpful? Leave some karma/thanks! :)

Link to comment
Share on other sites

I've tried to do it the way it is in TileFluidHandler, but still it doesn't work. Does that mean the problem is elsewhere? Like my cauldron block class:

package jakoubeck503.alchemicalinstillation.common.block;

import jakoubeck503.alchemicalinstillation.AlchemicalInstillation;
import jakoubeck503.alchemicalinstillation.common.tileentity.TEBrewingCauldron;

import java.util.List;

import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockBrewingCauldron extends BlockContainer {

    @SideOnly(Side.CLIENT)
    private IIcon iicon;
    
public BlockBrewingCauldron() {
	super(Material.iron);
	setCreativeTab(AlchemicalInstillation.tabAlchemicalInstillation);
	this.setBlockName("blockBrewingCauldron");
	this.setBlockTextureName(AlchemicalInstillation.modid + ":" + "brewingCauldron_side");
	this.setHardness(1.0F);
	this.setResistance(2.0F);
}

public TileEntity createNewTileEntity(World world, int i1) {
	return new TEBrewingCauldron();
}

public TileEntity getTileEntity(World world, int x, int y, int z) {
	return world.getTileEntity(x, y, z);
}

    public void setBlockBoundsForItemRender() {
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
    }
    
    public boolean isOpaqueCube() {
        return false;
    }
    
    public int getRenderType() {
        return -1;
    }

    public boolean renderAsNormalBlock() {
        return false;
    }
    
    public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB axis, List list, Entity entity) {
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.3125F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        float f = 0.125F;
        this.setBlockBounds(0.0F, 0.0F, 0.0F, f, 1.0F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, f);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBounds(1.0F - f, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBounds(0.0F, 0.0F, 1.0F - f, 1.0F, 1.0F, 1.0F);
        super.addCollisionBoxesToList(world, x, y, z, axis, list, entity);
        this.setBlockBoundsForItemRender();
    }
    
    @Override
    @SubscribeEvent
    public boolean onBlockEventReceived(World world, int x, int y, int z, int something, int different) {
    	System.out.println("BLOCK CHANGE!!!");
    	if (world.getBlock(x, y - 1, z)==Blocks.fire || world.getBlock(x, y - 1, z)==Blocks.lava) {
    		System.out.println("LAVA AND FIRE!!!");
    		TEBrewingCauldron entity =  (TEBrewingCauldron) world.getTileEntity(x, y, z);
    		entity.setBoiling(true);
    		return true;
    	} else return false;
    }
    
    @Override
    public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) {
    	TEBrewingCauldron tileEntity = (TEBrewingCauldron) world.getTileEntity(x, y, z);
    	
    	if (tileEntity==null || player.isSneaking()) {
    		return false;
    	}
    	
    	ItemStack heldItem = player.getCurrentEquippedItem();
    	
    	if (heldItem!=null) {
    		if (heldItem.getItem()==Items.water_bucket) {
    			if (tileEntity.isFillable()) {
    				tileEntity.fill(ForgeDirection.UP, new FluidStack(FluidRegistry.WATER, FluidContainerRegistry.BUCKET_VOLUME), true);
    				if (!player.capabilities.isCreativeMode)
    					player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.bucket));
    			}
    			return true;
    		}
    		
    		if (heldItem.getItem()==Items.glass_bottle && tileEntity.getFluidAmount()>=333){
    			tileEntity.drain(ForgeDirection.UP, 333, true);
    			if (!player.capabilities.isCreativeMode)
    				player.inventory.setInventorySlotContents(player.inventory.currentItem, FluidContainerRegistry.fillFluidContainer(
    						FluidRegistry.getFluidStack(FluidRegistry.WATER.getName(), 333), FluidContainerRegistry.EMPTY_BOTTLE));
    			return true;
    		}
    		if (heldItem.getItem()==Items.bucket && tileEntity.getFluidAmount()>=FluidContainerRegistry.BUCKET_VOLUME){
    			tileEntity.drain(ForgeDirection.UP, FluidContainerRegistry.BUCKET_VOLUME, true);
    			if (!player.capabilities.isCreativeMode)
    				player.inventory.setInventorySlotContents(player.inventory.currentItem, FluidContainerRegistry.fillFluidContainer(
    						FluidRegistry.getFluidStack(FluidRegistry.WATER.getName(), FluidContainerRegistry.BUCKET_VOLUME), FluidContainerRegistry.EMPTY_BUCKET));
    			return true;
    		}

    	}
    	return false;
    }


}


Link to comment
Share on other sites

The problem is when the tile is unloaded and reloaded the nbt is only loaded on the server to fix this add the following methods to your tile.

@Override
public Packet getDescriptionPacket() {
	NBTTagCompound tagCompound = new NBTTagCompound();
	writeToNBT(tagCompound);
	return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, tagCompound);
}

@Override
public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) {
	readFromNBT(pkt.func_148857_g());
}

 

they will read the nbt from the server and send it to the client. they are called every time the tile is loaded or the block is updated.

I am the author of Draconic Evolution

Link to comment
Share on other sites

You need to all markDirty() whenever something in your tile entity changes, so that it will be written out when the world is saved.

 

Also, you need to implement getDescriptionPacket() and onDescriptionPacket() even for a single-player environment. There is still a server and a client in single player (they just exist in the same process) and they need to be kept in sync.

Link to comment
Share on other sites

I am positively flummoxed now. I've marked the tile entity dirty and added this piece of code:

    @Override
    public void updateEntity() {
    	System.out.println(this.getFluidAmount() + "mB");
    }

When I place the cauldron down, it prints out "0mB" continuously, as expected. When I fill it, again it continuously prints "1000mB". However if leave it full and re-log, the console does this (if I leave the cauldron empty, it's normal after re-logging):

0mB
0mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
0mB
1000mB
1000mB

 

Does anybody have any explanation as to what is going on here?

Link to comment
Share on other sites

The

readFromNBT()

method only gets called on the server side. So the server knows the saved value (1000mB), but the client still has the default value (0mB). To solve this add the methods from brandon3055 post.

Don't PM me with questions. They will be ignored! Make a thread on the appropriate board for support.

 

1.12 -> 1.13 primer by williewillus.

 

1.7.10 and older versions of Minecraft are no longer supported due to it's age! Update to the latest version for support.

 

http://www.howoldisminecraft1710.today/

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

    • They were already updated, and just to double check I even did a cleanup and fresh update from that same page. I'm quite sure drivers are not the problem here. 
    • i tried downloading the drivers but it says no AMD graphics hardware has been detected    
    • Update your AMD/ATI drivers - get the drivers from their website - do not update via system  
    • As the title says i keep on crashing on forge 1.20.1 even without any mods downloaded, i have the latest drivers (nvidia) and vanilla minecraft works perfectly fine for me logs: https://pastebin.com/5UR01yG9
    • Hello everyone, I'm making this post to seek help for my modded block, It's a special block called FrozenBlock supposed to take the place of an old block, then after a set amount of ticks, it's supposed to revert its Block State, Entity, data... to the old block like this :  The problem I have is that the system breaks when handling multi blocks (I tried some fix but none of them worked) :  The bug I have identified is that the function "setOldBlockFields" in the item's "setFrozenBlock" function gets called once for the 1st block of multiblock getting frozen (as it should), but gets called a second time BEFORE creating the first FrozenBlock with the data of the 1st block, hence giving the same data to the two FrozenBlock :   Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=head] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@73681674 BlockEntityData : id:"minecraft:bed",x:3,y:-60,z:-6} Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=3, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=2, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} here is the code inside my custom "freeze" item :    @Override     public @NotNull InteractionResult useOn(@NotNull UseOnContext pContext) {         if (!pContext.getLevel().isClientSide() && pContext.getHand() == InteractionHand.MAIN_HAND) {             BlockPos blockPos = pContext.getClickedPos();             BlockPos secondBlockPos = getMultiblockPos(blockPos, pContext.getLevel().getBlockState(blockPos));             if (secondBlockPos != null) {                 createFrozenBlock(pContext, secondBlockPos);             }             createFrozenBlock(pContext, blockPos);             return InteractionResult.SUCCESS;         }         return super.useOn(pContext);     }     public static void createFrozenBlock(UseOnContext pContext, BlockPos blockPos) {         BlockState oldState = pContext.getLevel().getBlockState(blockPos);         BlockEntity oldBlockEntity = oldState.hasBlockEntity() ? pContext.getLevel().getBlockEntity(blockPos) : null;         CompoundTag oldBlockEntityData = oldState.hasBlockEntity() ? oldBlockEntity.serializeNBT() : null;         if (oldBlockEntity != null) {             pContext.getLevel().removeBlockEntity(blockPos);         }         BlockState FrozenBlock = setFrozenBlock(oldState, oldBlockEntity, oldBlockEntityData);         pContext.getLevel().setBlockAndUpdate(blockPos, FrozenBlock);     }     public static BlockState setFrozenBlock(BlockState blockState, @Nullable BlockEntity blockEntity, @Nullable CompoundTag blockEntityData) {         BlockState FrozenBlock = BlockRegister.FROZEN_BLOCK.get().defaultBlockState();         ((FrozenBlock) FrozenBlock.getBlock()).setOldBlockFields(blockState, blockEntity, blockEntityData);         return FrozenBlock;     }  
  • Topics

×
×
  • Create New...

Important Information

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