Java Code Examples for net.minecraft.tileentity.TileEntity#writeToNBT()

The following examples show how to use net.minecraft.tileentity.TileEntity#writeToNBT() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CraftBlockState.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public CraftBlockState(final Block block) {
    this.world = (CraftWorld) block.getWorld();
    this.x = block.getX();
    this.y = block.getY();
    this.z = block.getZ();
    this.type = block.getTypeId();
    this.chunk = (CraftChunk) block.getChunk();
    this.flag = 3;

    createData(block.getData());
    TileEntity te = world.getHandle().getTileEntity(new BlockPos(this.x, this.y, this.z));
    if (te != null) {
        nbt = new NBTTagCompound();
        te.writeToNBT(nbt);
    } else nbt = null;
}
 
Example 2
Source File: PacketRequestTE.java    From LookingGlass with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handle(ByteBuf data, EntityPlayer player) {
	if (ModConfigs.disabled) return;
	int dim = data.readInt();
	int xPos = data.readInt();
	int yPos = data.readInt();
	int zPos = data.readInt();

	if (!DimensionManager.isDimensionRegistered(dim)) return;
	WorldServer world = MinecraftServer.getServer().worldServerForDimension(dim);
	if (world == null) return;
	TileEntity tile = world.getTileEntity(xPos, yPos, zPos);
	if (tile != null) {
		//FIXME: This is currently a very "forceful" method of doing this, and not technically guaranteed to produce correct results
		// This would be much better handled by using the getDescriptionPacket method and wrapping that packet in a LookingGlass
		// packet to control delivery timing, allowing for processing the packet while the correct target world is the active world
		// This idea requires that that system be in place, though, so until then this hack will hopefully hold.
		NBTTagCompound tag = new NBTTagCompound();
		tile.writeToNBT(tag);
		ServerPacketDispatcher.getInstance().addPacket(player, PacketTileEntityNBT.createPacket(xPos, yPos, zPos, tag, dim));
	}
}
 
Example 3
Source File: ItemUtils.java    From litematica with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ItemStack storeTEInStack(ItemStack stack, TileEntity te)
{
    NBTTagCompound nbt = te.writeToNBT(new NBTTagCompound());

    if (stack.getItem() == Items.SKULL && nbt.hasKey("Owner"))
    {
        NBTTagCompound tagOwner = nbt.getCompoundTag("Owner");
        NBTTagCompound tagSkull = new NBTTagCompound();

        tagSkull.setTag("SkullOwner", tagOwner);
        stack.setTagCompound(tagSkull);

        return stack;
    }
    else
    {
        NBTTagCompound tagLore = new NBTTagCompound();
        NBTTagList tagList = new NBTTagList();

        tagList.appendTag(new NBTTagString("(+NBT)"));
        tagLore.setTag("Lore", tagList);
        stack.setTagInfo("display", tagLore);
        stack.setTagInfo("BlockEntityTag", nbt);

        return stack;
    }
}
 
Example 4
Source File: ForgeQueue_All.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public CompoundTag getTag(TileEntity tile) {
    try {
        NBTTagCompound tag = new NBTTagCompound();
        tile.writeToNBT(tag); // readTagIntoEntity
        CompoundTag result = (CompoundTag) methodToNative.invoke(null, tag);
        return result;
    } catch (Exception e) {
        MainUtil.handleError(e);
        return null;
    }
}
 
Example 5
Source File: TileRequestPacket.java    From NBTEdit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handleServerSide(EntityPlayerMP player) {
	TileEntity te = player.worldObj.getTileEntity(x, y, z);
	if (te != null) {
		NBTTagCompound tag = new NBTTagCompound();
		te.writeToNBT(tag);
		NBTEdit.DISPATCHER.sendTo(new TileNBTPacket(x, y, z, tag), player);
	}
	else
		sendMessageToPlayer(player, SECTION_SIGN + "cError - There is no TileEntity at ("+x+","+y+","+z+")");
}
 
Example 6
Source File: MsgTileEntities.java    From archimedes-ships with MIT License 5 votes vote down vote up
@Override
public void encodeInto(ChannelHandlerContext ctx, ByteBuf buf) throws IOException
{
	super.encodeInto(ctx, buf);
	tagCompound = new NBTTagCompound();
	NBTTagList list = new NBTTagList();
	for (TileEntity te : ship.getShipChunk().chunkTileEntityMap.values())
	{
		NBTTagCompound nbt = new NBTTagCompound();
		if (te instanceof TileEntityHelm)
		{
			((TileEntityHelm) te).writeNBTforSending(nbt);
		} else
		{
			te.writeToNBT(nbt);
		}
		list.appendTag(nbt);
	}
	tagCompound.setTag("list", list);
	DataOutputStream out = new DataOutputStream(new ByteBufOutputStream(buf));
	try
	{
		CompressedStreamTools.write(tagCompound, out);
		out.flush();
	} catch (IOException e)
	{
		throw e;
	} finally
	{
		out.close();
	}
}
 
Example 7
Source File: ForgeQueue_All.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public CompoundTag getTag(TileEntity tile) {
    try {
        NBTTagCompound tag = new NBTTagCompound();
        tile.writeToNBT(tag); // readTagIntoEntity
        return (CompoundTag) methodToNative.invoke(null, tag);
    } catch (Exception e) {
        MainUtil.handleError(e);
        return null;
    }
}
 
Example 8
Source File: EntityShip.java    From archimedes-ships with MIT License 5 votes vote down vote up
@Override
protected void writeEntityToNBT(NBTTagCompound compound)
{
	super.writeEntityToNBT(compound);
	ByteArrayOutputStream baos = new ByteArrayOutputStream(shipChunk.getMemoryUsage());
	DataOutputStream out = new DataOutputStream(baos);
	try
	{
		ChunkIO.writeAll(out, shipChunk);
		out.flush();
		out.close();
	} catch (IOException e)
	{
		e.printStackTrace();
	}
	compound.setByteArray("chunk", baos.toByteArray());
	compound.setByte("seatX", (byte) seatX);
	compound.setByte("seatY", (byte) seatY);
	compound.setByte("seatZ", (byte) seatZ);
	compound.setByte("front", (byte) frontDirection);
	
	if (!shipChunk.chunkTileEntityMap.isEmpty())
	{
		NBTTagList tileentities = new NBTTagList();
		for (TileEntity tileentity : shipChunk.chunkTileEntityMap.values())
		{
			NBTTagCompound comp = new NBTTagCompound();
			tileentity.writeToNBT(comp);
			tileentities.appendTag(comp);
		}
		compound.setTag("tileent", tileentities);
	}
	
	compound.setString("name", info.shipName);
	if (info.owner != null)
	{
		compound.setString("owner", info.owner);
	}
}
 
Example 9
Source File: ForgeQueue_All.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
public CompoundTag getTag(TileEntity tile) {
    try {
        NBTTagCompound tag = new NBTTagCompound();
        tile.writeToNBT(tag); // readTagIntoEntity
        CompoundTag result = (CompoundTag) methodToNative.invoke(null, tag);
        return result;
    } catch (Exception e) {
        MainUtil.handleError(e);
        return null;
    }
}
 
Example 10
Source File: MessageNBTUpdate.java    From ExNihiloAdscensio with MIT License 5 votes vote down vote up
public MessageNBTUpdate(TileEntity te)
{
	this.x = te.getPos().getX();
	this.y = te.getPos().getY();
	this.z = te.getPos().getZ();
	this.tag = te.writeToNBT(new NBTTagCompound());
}
 
Example 11
Source File: HackableMobSpawner.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isHacked(IBlockAccess world, int x, int y, int z){
    TileEntity te = world.getTileEntity(x, y, z);
    if(te != null) {
        NBTTagCompound tag = new NBTTagCompound();
        te.writeToNBT(tag);
        if(tag.hasKey("RequiredPlayerRange") && tag.getShort("RequiredPlayerRange") == 0) return true;
    }
    return false;
}
 
Example 12
Source File: PacketSendNBTPacket.java    From PneumaticCraft with GNU General Public License v3.0 4 votes vote down vote up
public PacketSendNBTPacket(TileEntity te){
    super(te.xCoord, te.yCoord, te.zCoord);
    tag = new NBTTagCompound();
    te.writeToNBT(tag);
}
 
Example 13
Source File: TemplateEnderUtilities.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void takeBlocksFromWorld(World worldIn, BlockPos posStart, BlockPos posEndRelative, boolean takeEntities, boolean cbCrossWorld)
{
    BlockPos endPos = posStart.add(posEndRelative);
    List<TemplateEnderUtilities.TemplateBlockInfo> list = Lists.<TemplateEnderUtilities.TemplateBlockInfo>newArrayList();
    List<TemplateEnderUtilities.TemplateBlockInfo> list1 = Lists.<TemplateEnderUtilities.TemplateBlockInfo>newArrayList();
    List<TemplateEnderUtilities.TemplateBlockInfo> list2 = Lists.<TemplateEnderUtilities.TemplateBlockInfo>newArrayList();

    this.size = PositionUtils.getAreaSizeFromRelativeEndPosition(posEndRelative);

    for (BlockPos.MutableBlockPos posMutable : BlockPos.getAllInBoxMutable(posStart, endPos))
    {
        BlockPos posRelative = posMutable.subtract(posStart);
        IBlockState state = worldIn.getBlockState(posMutable);

        TileEntity te = worldIn.getTileEntity(posMutable);

        if (te != null)
        {
            NBTTagCompound tag = new NBTTagCompound();

            if (cbCrossWorld)
            {
                tag = chiselsAndBitsHandler.writeChiselsAndBitsTileToNBT(tag, te);
            }
            else
            {
                tag = te.writeToNBT(tag);
            }

            tag.removeTag("x");
            tag.removeTag("y");
            tag.removeTag("z");

            list1.add(new TemplateEnderUtilities.TemplateBlockInfo(posRelative, state, tag));
        }
        else if (state.isFullBlock() == false && state.isFullCube() == false)
        {
            list2.add(new TemplateEnderUtilities.TemplateBlockInfo(posRelative, state, null));
        }
        else
        {
            list.add(new TemplateEnderUtilities.TemplateBlockInfo(posRelative, state, null));
        }
    }

    this.blocks.clear();
    this.blocks.addAll(list);
    this.blocks.addAll(list1);
    this.blocks.addAll(list2);

    if (takeEntities)
    {
        this.takeEntitiesFromWorld(worldIn, posStart, posEndRelative);
    }
    else
    {
        this.entities.clear();
    }
}
 
Example 14
Source File: MoveBlocks.java    From Valkyrien-Skies with Apache License 2.0 4 votes vote down vote up
private static void copyTileEntityToPos(World world, BlockPos oldPos, BlockPos newPos,
    Optional<PhysicsObject> physicsObjectOptional) {
    // Make a copy of the tile entity at oldPos to newPos
    TileEntity worldTile = world.getTileEntity(oldPos);
    if (worldTile != null) {
        NBTTagCompound tileEntNBT = new NBTTagCompound();
        TileEntity newInstance;
        if (worldTile instanceof IRelocationAwareTile) {
            CoordinateSpaceType coordinateSpaceType =
                physicsObjectOptional.isPresent() ? CoordinateSpaceType.SUBSPACE_COORDINATES
                    : CoordinateSpaceType.GLOBAL_COORDINATES;

            ShipTransform transform = new ShipTransform(newPos.getX() - oldPos.getX(),
                newPos.getY() - oldPos.getY(), newPos.getZ() - oldPos.getZ());

            newInstance = ((IRelocationAwareTile) worldTile)
                .createRelocatedTile(newPos, transform, coordinateSpaceType);
        } else {
            tileEntNBT = worldTile.writeToNBT(tileEntNBT);
            // Change the block position to be inside of the Ship
            tileEntNBT.setInteger("x", newPos.getX());
            tileEntNBT.setInteger("y", newPos.getY());
            tileEntNBT.setInteger("z", newPos.getZ());
            newInstance = TileEntity.create(world, tileEntNBT);
        }
        // Order the IVSNodeProvider to move by the given offset.
        if (newInstance instanceof IVSNodeProvider) {
            ((IVSNodeProvider) newInstance).shiftInternalData(newPos.subtract(oldPos));
            if (physicsObjectOptional.isPresent()) {
                ((IVSNodeProvider) newInstance)
                    .getNode()
                    .setParentPhysicsObject(physicsObjectOptional.get());
            } else {
                ((IVSNodeProvider) newInstance)
                    .getNode()
                    .setParentPhysicsObject(null);
            }
        }

        try {
            world.setTileEntity(newPos, newInstance);
            physicsObjectOptional
                .ifPresent(physicsObject -> physicsObject.onSetTileEntity(newPos, newInstance));
            newInstance.markDirty();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 15
Source File: SimpleNetTileEntity.java    From OpenModsLib with MIT License 4 votes vote down vote up
public static SPacketUpdateTileEntity writeToPacket(TileEntity te) {
	NBTTagCompound data = new NBTTagCompound();
	te.writeToNBT(data);
	return new SPacketUpdateTileEntity(te.getPos(), 42, data);
}
 
Example 16
Source File: TileEntityHandler.java    From OmniOcular with Apache License 2.0 4 votes vote down vote up
@Override
public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) {
    if (te != null)
        te.writeToNBT(tag);
    return tag;
}
 
Example 17
Source File: SchematicCreationUtils.java    From litematica with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void takeBlocksFromWorld(LitematicaSchematic schematic, World world, List<SelectionBox> boxes)
{
    BlockPos.MutableBlockPos posMutable = new BlockPos.MutableBlockPos(0, 0, 0);
    long totalBlocks = 0;

    for (SelectionBox box : boxes)
    {
        String regionName = box.getName();
        ISchematicRegion region = schematic.getSchematicRegion(regionName);
        ILitematicaBlockStateContainer container = region != null ? region.getBlockStateContainer() : null;
        Map<BlockPos, NBTTagCompound> blockEntityMap = region != null ? region.getBlockEntityMap() : null;
        Map<BlockPos, NextTickListEntry> tickMap = region != null ? region.getBlockTickMap() : null;

        if (container == null || blockEntityMap == null || tickMap == null)
        {
            InfoUtils.showGuiOrInGameMessage(MessageType.ERROR, "litematica.message.error.schematic_save.missing_container", regionName);
            continue;
        }

        Vec3i size = box.getSize();
        final int sizeX = Math.abs(size.getX());
        final int sizeY = Math.abs(size.getY());
        final int sizeZ = Math.abs(size.getZ());

        // We want to loop nice & easy from 0 to n here, but the per-sub-region pos1 can be at
        // any corner of the area. Thus we need to offset from the total area origin
        // to the minimum/negative (ie. 0,0 in the loop) corner here.
        final BlockPos minCorner = fi.dy.masa.malilib.util.PositionUtils.getMinCorner(box.getPos1(), box.getPos2());
        final int startX = minCorner.getX();
        final int startY = minCorner.getY();
        final int startZ = minCorner.getZ();

        for (int y = 0; y < sizeY; ++y)
        {
            for (int z = 0; z < sizeZ; ++z)
            {
                for (int x = 0; x < sizeX; ++x)
                {
                    posMutable.setPos(x + startX, y + startY, z + startZ);
                    IBlockState state = world.getBlockState(posMutable).getActualState(world, posMutable);
                    container.setBlockState(x, y, z, state);

                    if (state.getBlock() != Blocks.AIR)
                    {
                        ++totalBlocks;
                    }

                    if (state.getBlock().hasTileEntity())
                    {
                        TileEntity te = world.getTileEntity(posMutable);

                        if (te != null)
                        {
                            // TODO Add a TileEntity NBT cache from the Chunk packets, to get the original synced data (too)
                            BlockPos pos = new BlockPos(x, y, z);
                            NBTTagCompound tag = te.writeToNBT(new NBTTagCompound());
                            NBTUtils.writeBlockPosToTag(pos, tag);
                            blockEntityMap.put(pos, tag);
                        }
                    }
                }
            }
        }

        if (world instanceof WorldServer)
        {
            IntBoundingBox structureBB = IntBoundingBox.createProper(
                    startX,         startY,         startZ,
                    startX + sizeX, startY + sizeY, startZ + sizeZ);
            List<NextTickListEntry> pendingTicks = ((WorldServer) world).getPendingBlockUpdates(structureBB.toVanillaBox(), false);

            if (pendingTicks != null)
            {
                final int listSize = pendingTicks.size();
                final long currentTime = world.getTotalWorldTime();

                // The getPendingBlockUpdates() method doesn't check the y-coordinate... :-<
                for (int i = 0; i < listSize; ++i)
                {
                    NextTickListEntry entry = pendingTicks.get(i);

                    if (entry.position.getY() >= startY && entry.position.getY() < structureBB.maxY)
                    {
                        // Store the delay, ie. relative time
                        BlockPos posRelative = new BlockPos(
                                entry.position.getX() - minCorner.getX(),
                                entry.position.getY() - minCorner.getY(),
                                entry.position.getZ() - minCorner.getZ());
                        NextTickListEntry newEntry = new NextTickListEntry(posRelative, entry.getBlock());
                        newEntry.setPriority(entry.priority);
                        newEntry.setScheduledTime(entry.scheduledTime - currentTime);

                        tickMap.put(posRelative, newEntry);
                    }
                }
            }
        }
    }

    schematic.setTotalBlocksReadFromWorld(totalBlocks);
}
 
Example 18
Source File: TileEntityDrawbridge.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean retractOneBlock(int position, FakePlayer player, boolean takeNonPlaced, boolean playPistonSound)
{
    World world = this.getWorld();
    BlockPos pos = this.getPos().offset(this.getFacing(), position + 1);

    if (world.isBlockLoaded(pos, world.isRemote == false) == false)
    {
        return false;
    }

    IBlockState state = world.getBlockState(pos);

    if ((takeNonPlaced || state == this.blockStatesPlaced[position]) &&
        state.getBlock().isAir(state, world, pos) == false &&
        state.getBlockHardness(world, pos) >= 0f)
    {
        ItemStack stack = BlockUtils.getPickBlockItemStack(world, pos, player, EnumFacing.UP);

        if (stack.isEmpty() == false)
        {
            NBTTagCompound nbt = null;
            final int invPosition = this.isAdvanced() ? position : 0;

            if (state.getBlock().hasTileEntity(state))
            {
                TileEntity te = world.getTileEntity(pos);

                if (te != null)
                {
                    TileUtils.storeTileEntityInStack(stack, te, false);
                    nbt = te.writeToNBT(new NBTTagCompound());
                    NBTUtils.removePositionFromTileEntityNBT(nbt);
                }
            }

            if (this.itemHandlerDrawbridge.insertItem(invPosition, stack, false).isEmpty())
            {
                this.blockInfoTaken[position] = new BlockInfo(state, nbt);
                this.numTaken++;

                if (playPistonSound)
                {
                    world.playSound(null, pos, SoundEvents.BLOCK_PISTON_CONTRACT, SoundCategory.BLOCKS, 0.5f, 0.7f);
                }
                else
                {
                    BlockUtils.playBlockBreakSound(world, pos);
                }

                BlockUtils.setBlockToAirWithoutSpillingContents(world, pos);

                this.blockStatesPlaced[position] = null;

                return true;
            }
        }
    }

    return false;
}
 
Example 19
Source File: BlockBusFluidStorage.java    From ExtraCells1 with MIT License 4 votes vote down vote up
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float offsetX, float offsetY, float offsetZ)
{
	if (!world.isRemote)
	{
		ItemStack currentItem = player.inventory.getCurrentItem();
		if (currentItem != null)
		{
			IMemoryCard card = Util.getAppEngApi().getMemoryCardHandler();
			TileEntity blockTE = world.getBlockTileEntity(x, y, z);

			if (card.isMemoryCard(currentItem))
			{
				if (player.isSneaking())
				{
					NBTTagCompound nbt = new NBTTagCompound();
					blockTE.writeToNBT(nbt);
					nbt.removeTag("x");
					nbt.removeTag("y");
					nbt.removeTag("z");
					blockTE.readFromNBT(nbt);
					card.setMemoryCardContents(currentItem, getUnlocalizedName() + ".name", nbt);
					player.sendChatToPlayer(new ChatMessageComponent().addText(StatCollector.translateToLocal("ChatMsg.SettingsSaved")));
					return true;
				} else if (card.getSettingsName(currentItem).equals(getUnlocalizedName() + ".name") || card.getSettingsName(currentItem).equals("AppEng.GuiITooltip.Blank"))
				{
					blockTE.readFromNBT(card.getData(currentItem));
					Packet description = blockTE.getDescriptionPacket();
					if (description != null)
						PacketDispatcher.sendPacketToAllPlayers(description);
					player.sendChatToPlayer(new ChatMessageComponent().addText(StatCollector.translateToLocal("ChatMsg.SettingsLoaded")));
					return true;
				} else
				{
					player.sendChatToPlayer(new ChatMessageComponent().addText(StatCollector.translateToLocal("ChatMsg.IncorrectDevice")));
					return true;
				}
			}
		}
		if (world.getBlockTileEntity(x, y, z) == null || player.isSneaking())
		{
			return false;
		}
		PacketDispatcher.sendPacketToPlayer(world.getBlockTileEntity(x, y, z).getDescriptionPacket(), (Player) player);
		player.openGui(Extracells.instance, 2, world, x, y, z);
	}
	return true;
}
 
Example 20
Source File: BlockBusFluidExport.java    From ExtraCells1 with MIT License 4 votes vote down vote up
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float offsetX, float offsetY, float offsetZ)
{
	if (!world.isRemote)
	{
		ItemStack currentItem = player.inventory.getCurrentItem();
		if (currentItem != null)
		{
			IMemoryCard card = Util.getAppEngApi().getMemoryCardHandler();
			TileEntity blockTE = world.getBlockTileEntity(x, y, z);

			if (card.isMemoryCard(currentItem))
			{
				if (player.isSneaking())
				{
					NBTTagCompound nbt = new NBTTagCompound();
					blockTE.writeToNBT(nbt);
					nbt.removeTag("x");
					nbt.removeTag("y");
					nbt.removeTag("z");
					blockTE.readFromNBT(nbt);
					card.setMemoryCardContents(currentItem, getUnlocalizedName() + ".name", nbt);
					player.sendChatToPlayer(new ChatMessageComponent().addText(StatCollector.translateToLocal("ChatMsg.SettingsSaved")));
					return true;
				} else if (card.getSettingsName(currentItem).equals(getUnlocalizedName() + ".name") || card.getSettingsName(currentItem).equals("AppEng.GuiITooltip.Blank"))
				{
					blockTE.readFromNBT(card.getData(currentItem));
					Packet description = blockTE.getDescriptionPacket();
					if (description != null)
						PacketDispatcher.sendPacketToAllPlayers(description);
					player.sendChatToPlayer(new ChatMessageComponent().addText(StatCollector.translateToLocal("ChatMsg.SettingsLoaded")));
					return true;
				} else
				{
					player.sendChatToPlayer(new ChatMessageComponent().addText(StatCollector.translateToLocal("ChatMsg.IncorrectDevice")));
					return true;
				}
			}
		}
		if (world.getBlockTileEntity(x, y, z) == null || player.isSneaking())
		{
			return false;
		}
		player.openGui(Extracells.instance, 4, world, x, y, z);
	}
	return true;
}