Jump to content

[SOLVED] Read/Write Compressed NBT from/to DataStream


coolAlias

Recommended Posts

SOLUTION: Don't try to send the entire inventory as NBT. Just iterate through the contents and use Packet.writeItemStack to write each itemstack to the stream.

 

I'm trying to synchronize an inventory stored in IExtendedEntityProperties on loading so as to display something in the HUD. It works fine as soon as I open the inventory at least once, but before that, all the client-side data is null.

 

I tried sending a compressed version of the NBT from server to client, much like the TileEntity packet, and printing parNBTTagCompound.toString() shows it has all the correct information before being sent. However, once I send and receive the data, there's nothing there.

 

Is this one of those cases where you can't use the assignment operator '=' ? Or is there something else going on here?

 

Code:

 

 

Writing:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(bos);


// parNBTTagCompound.toString() shows all correct information at this point	
try {
byte[] abyte = CompressedStreamTools.compress(parNBTTagCompound);
outputStream.writeShort((short) abyte.length);
outputStream.write(abyte);
} catch (Exception ex) {
ex.printStackTrace();
}

PacketDispatcher.sendPacketToPlayer(PacketDispatcher.getPacket(ModInfo.CHANNEL, bos.toByteArray()), (Player) player);

 

Reading:

NBTTagCompound tag;

try {
short short1 = inputStream.readShort();
byte[] abyte = new byte[short1];
        inputStream.readFully(abyte);
        tag = CompressedStreamTools.decompress(abyte);
} catch (IOException e) {
e.printStackTrace();
return;
}
// tag doesn't have anything in it?!

 

 

Link to comment
Share on other sites

EDIT: Ok, sorry I'm a bit slow... I don't know what I was thinking trying to send the entire inventory in a single NBT compound <facepalm>. I used Packet.write/readItemStack, iterating through the inventory, and it works great. Wow... thank you guys for your patience. I'm sure it must be tough sometimes  :-[

 

Thanks for the ideas. I tried using read/writeCompressed instead, but it has the same result. The NBT tag is correct when preparing the packet, but either during the writing or reading process it gets translated into null. It shouldn't make a difference, but the NBT Tag is for an IInventory storing some ItemStacks.

 

Actually, I think it does. I just tried storing another variable directly into the tag compound and it was sent and received correctly, but the items stored in a tag list appended to the compound don't get written to the packet. Sending the tag list compound shows the tag list correctly, but it doesn't contain any tags. So it looks like I have to manually go through and write/read every individual tag compound? There has to be a better way than that, right?

 

The Packet methods were where I found the code with the byte array from earlier. I didn't use the actual methods because I didn't make a subclass of Packet, just a static method to build the packet as a customPayload250, and writeNBTTagCompound is protected.

 

Code with read/writeCompressed instead:

 

 

Writing:

// This shows correct data stored in NBT
System.out.println("Preparing NBT packet. Data: " + compound.toString());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream outputStream = new DataOutputStream(bos);

try {
CompressedStreamTools.writeCompressed(compound, outputStream);
} catch (Exception ex) {
ex.printStackTrace();
}

PacketDispatcher.sendPacketToPlayer(PacketDispatcher.getPacket(ModInfo.CHANNEL, bos.toByteArray()), (Player) player);

Reading:

NBTTagCompound tag;

try {
        tag = CompressedStreamTools.readCompressed(inputStream);
} catch (IOException e) {
e.printStackTrace();
return;
}
// But here is still null...
System.out.println("NBT Tag from packet: " + tag.toString());

ExtendedPlayer.get(player).customInventory.readFromNBT(tag);

 

 

Link to comment
Share on other sites

Should read/writeCompressed work for any format of NBTTagCompound? One would think so, and I haven't done anything weird with mine, so far as I know. It's all pretty basic stuff in the Inventory and ExtendedPlayer classes.

 

Like I mentioned earlier, I got it working by writing each ItemStack to the outputStream, but I'm curious why the NBT method didn't work.

 

I make the call to 'sync' onEntityJoinWorld and the packet is handled like I showed earlier with the compressed stream tools. I've checked and everything is getting called properly, it's just the NBT read/write that was messed up.

 

Code:

 

 

I use the player's NBT Tag Compound so that the inventory can save/load an 'active' slot, i.e. a slot that can be used with a key press rather than by holding the item.

 

From IExtendedEntityProperties class 'ExtendedPlayer'

public final InventoryCustom inventory;

public ExtendedPlayer(EntityPlayer player)
{
this.player = player;
this.inventory= new InventoryCustom(player.getEntityData());
}

@Override
public final void saveNBTData(NBTTagCompound compound)
{
        // I save to a new tag to avoid conflicts with the vanilla tag identifiers
NBTTagCompound properties = new NBTTagCompound();
inventory.writeToNBT(properties);
compound.setTag(EXT_PROP_NAME, properties);
}

@Override
public final void loadNBTData(NBTTagCompound compound)
{
NBTTagCompound properties = (NBTTagCompound) compound.getTag(EXT_PROP_NAME);
inventory.readFromNBT(properties);
}

public final void sync()
{
if (FMLCommonHandler.instance().getEffectiveSide().isServer()) {
	PacketHandler.sendSyncInventoryPacket(player, inventory);
}
}

 

NBT stuff from Inventory:

private final NBTTagCompound compound;

public InventoryEye(NBTTagCompound compound) {
this.compound = compound;
}

public int getActiveSlot() {
return compound.getByte("ActiveSlot");
}

public void setActiveSlot(int index) {
if (index >= 0 && index < ACTIVE_SLOT)
	compound.setByte("ActiveSlot", (byte) index);
else
	compound.setByte("ActiveSlot", (byte) 0);
}

public void nextActiveSlot() {
setActiveSlot(getActiveSlot() + 1);
}

@Override
public ItemStack getStackInSlot(int slot)
{
if (slot == ACTIVE_SLOT) {
	return items[getActiveSlot()];
} else {
	return items[slot];
}
}

public void readFromNBT(NBTTagCompound compound)
{
NBTTagList items = compound.getTagList("CustomInventory");

for (int i = 0; i < items.tagCount(); ++i)
{
	NBTTagCompound item = (NBTTagCompound) items.tagAt(i);
	byte slot = item.getByte("Slot");

	if (slot >= 0 && slot < getSizeInventory()) {
		setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(item));
	}
}

setActiveSlot(compound.getByte("ActiveSlot"));
}

public void writeToNBT(NBTTagCompound compound)
{
NBTTagList items = new NBTTagList();

for (int i = 0; i < getSizeInventory(); ++i)
{
	if (getStackInSlot(i) != null)
	{
		NBTTagCompound item = new NBTTagCompound();
		item.setByte("Slot", (byte) i);
		getStackInSlot(i).writeToNBT(item);
		items.appendTag(item);
	}
}

compound.setTag("CustomInventory", items);
compound.setByte("ActiveSlot", (byte) getActiveSlot());
}

 

Link to comment
Share on other sites

Ah, it's left over from the wiki Packet Handling tutorial ;) Didn't know it was any more costly to use than worldObj.isRemote.

 

Anyway, yes, my packet handler uses ids, I write a byte to the beginning of every custom payload packet that is the packet id, I just left that part out of the earlier code that used compressed stream tools because the problem wasn't sending/receiving the packet. That was working fine. The problem was that using the code from earlier took my inventory nbt tag with stuff in it and wrote or read it as null.

 

I mentioned several of the steps I took to debug, including writing other things to the nbt tag that were successful, so the packets and handling are fine. For example, I could use 'compound.setInteger("Tag1", 5)' in the inventory writeNBT method and it would be handled fine by the packet, but adding a TagList to 'compound' didn't work. I forget what I did, but at one point I got the name of the TagList to process correctly, but the list was empty on the receiving end (but not on the sending end).

 

The Inventory loads and saves fine, which suggests the NBT is all in proper order.

 

It seems like writeCompressed only writes data directly in the tag compound, but not any other tags stored within the tag. That seems dead wrong to me, but from what I've tried that's how it appears to be.

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

    • Ok. Thanks. by the way, will this crash in any circumstances? public boolean onLeftClickEntity(ItemStack stack, Player player, Entity entity) { if (entity instanceof LivingEntity){ LivingEntity victim = (LivingEntity) entity; if(!victim.isDeadOrDying() && victim.getHealth()>0){ victim.setHealth(0); return true; } } return false; }  
    • You shouldn't be extracting the mod .jar, just place it in your mods folder.
    • so basically another rundown of my probelm. Im the admin of a 1.20.1 modded server. Were using forge 47.2.0 but tested this issue in other forge versions too on sevrer and client side. so the forge version isnt the issue. The bug happens in following instances. Were using the attacks of the jujutsucraft mod by orca normally. And for everyone that stands there nothing changes. But everyone who wasnt in the chunks before or who relogins again those chunks will appear invisible for the most part. I tried fixing this be removing and adding following mods in many combinations. Embeddium, canary, memoryleakfix, ai improvements, Krypton reforges, better chunkloading, radium reforged, embeddium plus, farsight, betterchunkloading, oculus I tested most of these mods alone and in differents combinations with each other and without the mods. What i noticed is zhat when i removed  . most invisible chunks will return or semi return. and only ine or two chunks stay invisible. I rechanged those mids mostly on the cöient side but also some in the serveside. Ir most likely isnt an issue with another non performance mod since i noticed this thing with embeddium. Ans also the problem wasnt there im the beginning of the server. Granted since then we updated some of the mods that add content and their lib mod. But i went to every big mods discord and community that we have and i didnt find someone else havinf that chunk problem. Heres the link to a video of the Problem. https://streamable.com/9v1if2     heres the link to the modlist: https://ibb.co/myF8dtX     Pleaee im foghting for months with this problem. All the performance mods kn the modlist are for sure not the issue i tested without all of them.
    • It looks like you're only setting the health if the thing you are hitting is a player.  
    • It sounds like you accidentally have two items that are both named "orange". Ensure that you give items unique names in the string when you register them. That's one of the more annoying errors to track down if you don't know what's causing it, though.
  • Topics

×
×
  • Create New...

Important Information

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