Java Code Examples for net.minecraft.item.ItemStack#getTag()

The following examples show how to use net.minecraft.item.ItemStack#getTag() . 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: EnergyHolderItem.java    From Galacticraft-Rewoven with MIT License 6 votes vote down vote up
/**
 * Attempt to insert energy into this battery.
 *
 * @param battery     The battery that energy should be added to.
 * @param energyToAdd The amount of energy to add to the battery.
 * @return The amount of energy that could not be added to this battery
 */
default int insert(ItemStack battery, int energyToAdd) {
    if (isInfinite()) {
        // Don't insert any energy.
        return energyToAdd;
    }

    if (battery.getTag() != null && battery.getTag().contains("Energy")) {
        int stored = battery.getTag().getInt("Energy");
        if (stored + energyToAdd <= getMaxEnergy(battery)) {
            GalacticraftEnergy.setEnergy(battery, stored + energyToAdd);
        } else {
            int failed = (stored + energyToAdd) - getMaxEnergy(battery);
            GalacticraftEnergy.setEnergy(battery, stored + (energyToAdd - failed));
            return failed;
        }
    }
    return energyToAdd;
}
 
Example 2
Source File: EnergyHolderItem.java    From Galacticraft-Rewoven with MIT License 6 votes vote down vote up
/**
 * Attempt to extract energy from this battery.
 *
 * @param battery        The battery that energy should be removed from.
 * @param energyToRemove The amount of energy to remove from the battery.
 * @return The amount of energy that could not be removed from this battery
 */
default int extract(ItemStack battery, int energyToRemove) {
    if (isInfinite()) {
        // Allow extracting any amount.
        return 0;
    }

    if (battery.getTag() != null && battery.getTag().contains("Energy")) {
        int stored = battery.getTag().getInt("Energy");
        if (stored >= energyToRemove) {
            GalacticraftEnergy.setEnergy(battery, stored - energyToRemove);
            return 0;
        } else {
            int failed = (stored - energyToRemove) * -1;
            GalacticraftEnergy.setEnergy(battery, 0);
            return failed;
        }
    }
    return energyToRemove;
}
 
Example 3
Source File: ItemContentUtils.java    From bleachhack-1.14 with GNU General Public License v3.0 6 votes vote down vote up
public static List<ItemStack> getItemsInContainer(ItemStack item) {
	List<ItemStack> items = new ArrayList<>(Collections.nCopies(27, new ItemStack(Items.AIR)));
	CompoundTag nbt = item.getTag();
	
	if (nbt != null && nbt.contains("BlockEntityTag")) {
		CompoundTag nbt2 = nbt.getCompound("BlockEntityTag");
		if (nbt2.contains("Items")) {
			ListTag nbt3 = (ListTag) nbt2.get("Items");
			for (int i = 0; i < nbt3.size(); i++) {
				items.set(nbt3.getCompound(i).getByte("Slot"), ItemStack.fromTag(nbt3.getCompound(i)));
			}
		}
	}
	
	return items;
}
 
Example 4
Source File: ViewNbtCmd.java    From Wurst7 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void call(String[] args) throws CmdException
{
	ClientPlayerEntity player = MC.player;
	ItemStack stack = player.inventory.getMainHandStack();
	if(stack.isEmpty())
		throw new CmdError("You must hold an item in your main hand.");
	
	CompoundTag tag = stack.getTag();
	String nbt = tag == null ? "" : tag.asString();
	
	switch(String.join(" ", args).toLowerCase())
	{
		case "":
		ChatUtils.message("NBT: " + nbt);
		break;
		
		case "copy":
		MC.keyboard.setClipboard(nbt);
		ChatUtils.message("NBT data copied to clipboard.");
		break;
		
		default:
		throw new CmdSyntaxError();
	}
}
 
Example 5
Source File: ItemContentUtils.java    From bleachhack-1.14 with GNU General Public License v3.0 6 votes vote down vote up
public static List<ItemStack> getItemsInContainer(ItemStack item) {
	List<ItemStack> items = new ArrayList<>(Collections.nCopies(27, new ItemStack(Items.AIR)));
	CompoundTag nbt = item.getTag();
	
	if (nbt != null && nbt.containsKey("BlockEntityTag")) {
		CompoundTag nbt2 = nbt.getCompound("BlockEntityTag");
		if (nbt2.containsKey("Items")) {
			ListTag nbt3 = (ListTag) nbt2.getTag("Items");
			for (int i = 0; i < nbt3.size(); i++) {
				items.set(nbt3.getCompoundTag(i).getByte("Slot"), ItemStack.fromTag(nbt3.getCompoundTag(i)));
			}
		}
	}
	
	return items;
}
 
Example 6
Source File: ItemContentUtils.java    From bleachhack-1.14 with GNU General Public License v3.0 6 votes vote down vote up
public static List<ItemStack> getItemsInContainer(ItemStack item) {
	List<ItemStack> items = new ArrayList<>(Collections.nCopies(27, new ItemStack(Items.AIR)));
	CompoundTag nbt = item.getTag();
	
	if (nbt != null && nbt.contains("BlockEntityTag")) {
		CompoundTag nbt2 = nbt.getCompound("BlockEntityTag");
		if (nbt2.contains("Items")) {
			ListTag nbt3 = (ListTag) nbt2.get("Items");
			for (int i = 0; i < nbt3.size(); i++) {
				items.set(nbt3.getCompound(i).getByte("Slot"), ItemStack.fromTag(nbt3.getCompound(i)));
			}
		}
	}
	
	return items;
}
 
Example 7
Source File: MCDataOutput.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Writes an {@link ItemStack} to the stream.
 * The <code>limitedTag</code> parameter, can be used to force the use of
 * the stack {@link ItemStack#getShareTag()} instead of its {@link ItemStack#getTag()}.
 * Under normal circumstances in Server -> Client sync, not all NBT tags are required,
 * to be sent to the client. For Example, the inventory of a pouch / bag(Containers sync it).
 * However, in Client -> Server sync, the entire tag may be required, modders can choose,
 * if they want a stacks full tag or not. The default is to use {@link ItemStack#getShareTag()}.
 * <p>
 * It should also be noted that this implementation writes the {@link ItemStack#getCount()}
 * as a varInt opposed to a byte, as that is favourable in some cases.
 *
 * @param stack      The {@link ItemStack}.
 * @param limitedTag Weather to use the stacks {@link ItemStack#getShareTag()} instead.
 * @return The same stream.
 */
default MCDataOutput writeItemStack(ItemStack stack, boolean limitedTag) {
    if (stack.isEmpty()) {
        writeBoolean(false);
    } else {
        writeBoolean(true);
        Item item = stack.getItem();
        writeRegistryIdUnsafe(ForgeRegistries.ITEMS, item);
        writeVarInt(stack.getCount());
        CompoundNBT nbt = null;
        if (item.isDamageable() || item.shouldSyncTag()) {
            nbt = limitedTag ? stack.getShareTag() : stack.getTag();
        }
        writeCompoundNBT(nbt);
    }
    return this;
}
 
Example 8
Source File: InventoryHelper.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static boolean cleanUpShulkerBoxTag(ItemStack stack)
{
    boolean changed = false;
    CompoundTag tag = stack.getTag();

    if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND))
        return false;

    CompoundTag bet = tag.getCompound("BlockEntityTag");
    if (bet.contains("Items", TAG_LIST) && bet.getList("Items", TAG_COMPOUND).isEmpty())
    {
        bet.remove("Items");
        changed = true;
    }

    if (bet.isEmpty())
    {
        tag.remove("BlockEntityTag");
        changed = true;
    }
    if (tag.isEmpty())
    {
        stack.setTag(null);
        changed = true;
    }
    return changed;
}
 
Example 9
Source File: CmdEnchant.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public void enchant(ItemStack item, Enchantment e, int level) {
	if (item.getTag() == null) item.setTag(new CompoundTag());
	if (!item.getTag().contains("Enchantments", 9)) {
		item.getTag().put("Enchantments", new ListTag());
    }

    ListTag listnbt = item.getTag().getList("Enchantments", 10);
    CompoundTag compoundnbt = new CompoundTag();
    compoundnbt.putString("id", String.valueOf(Registry.ENCHANTMENT.getId(e)));
    compoundnbt.putInt("lvl", level);
    listnbt.add(compoundnbt);
}
 
Example 10
Source File: ItemContentUtils.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public static List<List<String>> getTextInBook(ItemStack item) {
	List<String> pages = new ArrayList<>();
	CompoundTag nbt = item.getTag();
	
	if (nbt != null && nbt.contains("pages")) {
		ListTag nbt2 = nbt.getList("pages", 8);
		for (int i = 0; i < nbt2.size(); i++) pages.add(nbt2.getString(i));
	}
	
	List<List<String>> finalPages = new ArrayList<>();
	
	for (String s: pages) {
		String buffer = "";
		List<String> pageBuffer = new ArrayList<>();
		
		for (char c: s.toCharArray()) {
			if (MinecraftClient.getInstance().textRenderer.getStringWidth(buffer) > 114 || buffer.endsWith("\n")) {
				pageBuffer.add(buffer.replace("\n", ""));
				buffer = "";
			}
			
			buffer += c;
		}
		pageBuffer.add(buffer);
		finalPages.add(pageBuffer);
	}
	
	return finalPages;
}
 
Example 11
Source File: CmdEnchant.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public void enchant(ItemStack item, Enchantment e, int level) {
	if (item.getTag() == null) item.setTag(new CompoundTag());
	if (!item.getTag().contains("Enchantments", 9)) {
		item.getTag().put("Enchantments", new ListTag());
    }

    ListTag listnbt = item.getTag().getList("Enchantments", 10);
    CompoundTag compoundnbt = new CompoundTag();
    compoundnbt.putString("id", String.valueOf(Registry.ENCHANTMENT.getId(e)));
    compoundnbt.putInt("lvl", level);
    listnbt.add(compoundnbt);
}
 
Example 12
Source File: ItemContentUtils.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public static List<List<String>> getTextInBook(ItemStack item) {
	List<String> pages = new ArrayList<>();
	CompoundTag nbt = item.getTag();
	
	if (nbt != null && nbt.contains("pages")) {
		ListTag nbt2 = nbt.getList("pages", 8);
		for (int i = 0; i < nbt2.size(); i++) pages.add(nbt2.getString(i));
	}
	
	List<List<String>> finalPages = new ArrayList<>();
	
	for (String s: pages) {
		String buffer = "";
		List<String> pageBuffer = new ArrayList<>();
		
		for (char c: s.toCharArray()) {
			if (MinecraftClient.getInstance().textRenderer.getWidth(buffer) > 114 || buffer.endsWith("\n")) {
				pageBuffer.add(buffer.replace("\n", ""));
				buffer = "";
			}
			
			buffer += c;
		}
		pageBuffer.add(buffer);
		finalPages.add(pageBuffer);
	}
	
	return finalPages;
}
 
Example 13
Source File: CmdPeek.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCommand(String command, String[] args) throws Exception {
	ItemStack item = mc.player.inventory.getCurrentItem();
	
	if (!(item.getItem() instanceof BlockItem)) {
		BleachLogger.errorMessage("Must be holding a containter to peek.");
		return;
	}
	
	if (!(((BlockItem) item.getItem()).getBlock() instanceof ContainerBlock)) {
		BleachLogger.errorMessage("Must be holding a containter to peek.");
		return;
	}
	
	NonNullList<ItemStack> items = NonNullList.withSize(27, new ItemStack(Items.AIR));
	CompoundNBT nbt = item.getTag();
	
	if (nbt != null && nbt.contains("BlockEntityTag")) {
		CompoundNBT itemnbt = nbt.getCompound("BlockEntityTag");
		if (itemnbt.contains("Items")) ItemStackHelper.loadAllItems(itemnbt, items);
	}
	
	Inventory inv = new Inventory(items.toArray(new ItemStack[27]));
	
	BleachQueue.queue.add(() -> {
		mc.displayGuiScreen(new ShulkerBoxScreen(
				new ShulkerBoxContainer(420, mc.player.inventory, inv),
				mc.player.inventory,
				item.getDisplayName()));
	});
}
 
Example 14
Source File: CmdEnchant.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public void enchant(ItemStack item, Enchantment e, int level) {
	if (item.getTag() == null) item.setTag(new CompoundTag());
	if (!item.getTag().containsKey("Enchantments", 9)) {
		item.getTag().put("Enchantments", new ListTag());
    }

    ListTag listnbt = item.getTag().getList("Enchantments", 10);
    CompoundTag compoundnbt = new CompoundTag();
    compoundnbt.putString("id", String.valueOf(Registry.ENCHANTMENT.getId(e)));
    compoundnbt.putInt("lvl", level);
    listnbt.add(compoundnbt);
}
 
Example 15
Source File: ItemContentUtils.java    From bleachhack-1.14 with GNU General Public License v3.0 5 votes vote down vote up
public static List<List<String>> getTextInBook(ItemStack item) {
	List<String> pages = new ArrayList<>();
	CompoundTag nbt = item.getTag();
	
	if (nbt != null && nbt.containsKey("pages")) {
		ListTag nbt2 = nbt.getList("pages", 8);
		for (int i = 0; i < nbt2.size(); i++) pages.add(nbt2.getString(i));
	}
	
	List<List<String>> finalPages = new ArrayList<>();
	
	for (String s: pages) {
		String buffer = "";
		List<String> pageBuffer = new ArrayList<>();
		
		for (char c: s.toCharArray()) {
			if (MinecraftClient.getInstance().textRenderer.getStringWidth(buffer) > 114 || buffer.endsWith("\n")) {
				pageBuffer.add(buffer.replace("\n", ""));
				buffer = "";
			}
			
			buffer += c;
		}
		pageBuffer.add(buffer);
		finalPages.add(pageBuffer);
	}
	
	return finalPages;
}
 
Example 16
Source File: InventoryHelper.java    From fabric-carpet with MIT License 5 votes vote down vote up
public static boolean shulkerBoxHasItems(ItemStack stack)
{
    CompoundTag tag = stack.getTag();

    if (tag == null || !tag.contains("BlockEntityTag", TAG_COMPOUND))
        return false;

    CompoundTag bet = tag.getCompound("BlockEntityTag");
    return bet.contains("Items", TAG_LIST) && !bet.getList("Items", TAG_COMPOUND).isEmpty();
}
 
Example 17
Source File: Frequency.java    From EnderStorage with MIT License 5 votes vote down vote up
public static Frequency readFromStack(ItemStack stack) {
    if (stack.hasTag()) {
        CompoundNBT stackTag = stack.getTag();
        if (stackTag.contains("Frequency")) {
            return new Frequency(stackTag.getCompound("Frequency"));
        }
    }
    return new Frequency();
}
 
Example 18
Source File: EnergyHolderItem.java    From Galacticraft-Rewoven with MIT License 5 votes vote down vote up
default int getEnergy(ItemStack battery) {
    if (battery.getTag() != null && battery.getTag().contains("Energy")) {
        return battery.getTag().getInt("Energy");
    } else {
        return 0;
    }
}
 
Example 19
Source File: ConfigurableElectricMachineBlock.java    From Galacticraft-Rewoven with MIT License 4 votes vote down vote up
@Override
@Environment(EnvType.CLIENT)
public final void buildTooltip(ItemStack itemStack_1, BlockView blockView_1, List<Text> list_1, TooltipContext tooltipContext_1) {
    Text text = machineInfo(itemStack_1, blockView_1, tooltipContext_1);
    if (text != null) {
        List<Text> info = new ArrayList<>();
        for (StringRenderable s : MinecraftClient.getInstance().textRenderer.wrapLines(text, 150)) {
            info.add(new LiteralText(s.getString()).setStyle(Style.EMPTY.withColor(Formatting.DARK_GRAY)));
        }
        if (!info.isEmpty()) {
            if (Screen.hasShiftDown()) {
                list_1.addAll(info);
            } else {
                list_1.add(new TranslatableText("tooltip.galacticraft-rewoven.press_shift").setStyle(Style.EMPTY.withColor(Formatting.DARK_GRAY)));
            }
        }
    }

    if (itemStack_1 != null && itemStack_1.getTag() != null && itemStack_1.getTag().contains("BlockEntityTag")) {
        list_1.add(new LiteralText(""));
        list_1.add(new TranslatableText("ui.galacticraft-rewoven.machine.current_energy", itemStack_1.getTag().getCompound("BlockEntityTag").getInt("Energy")).setStyle(Style.EMPTY.withColor(Formatting.AQUA)));
        list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config.owner", itemStack_1.getTag().getCompound("BlockEntityTag").getString("OwnerUsername")).setStyle(Style.EMPTY.withColor(Formatting.BLUE)));
        if (itemStack_1.getTag().getCompound("BlockEntityTag").getBoolean("Public")) {
            list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config_2").setStyle(Style.EMPTY
                    .withColor(Formatting.GRAY)).append(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config.public_2")
                    .setStyle(Style.EMPTY.withColor(Formatting.GREEN))));

        } else if (itemStack_1.getTag().getCompound("BlockEntityTag").getBoolean("Party")) {
            list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config_2").setStyle(Style.EMPTY
                    .withColor(Formatting.GRAY)).append(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config.space_race_2")
                    .setStyle(Style.EMPTY.withColor(Formatting.DARK_GRAY))));

        } else {
            list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config_2").setStyle(Style.EMPTY
                    .withColor(Formatting.GRAY)).append(new TranslatableText("ui.galacticraft-rewoven.tabs.security_config.private_2")
                    .setStyle(Style.EMPTY.withColor(Formatting.DARK_RED))));

        }

        if (itemStack_1.getTag().getCompound("BlockEntityTag").getString("Redstone").equals("DISABLED")) {
            list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.redstone_activation_config_2").setStyle(Style.EMPTY.withColor(Formatting.RED)).append(new TranslatableText("ui.galacticraft-rewoven.tabs.redstone_activation_config.ignore_2").setStyle(Style.EMPTY.withColor(Formatting.GRAY))));
        } else if (itemStack_1.getTag().getCompound("BlockEntityTag").getString("Redstone").equals("OFF")) {
            list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.redstone_activation_config_2").setStyle(Style.EMPTY.withColor(Formatting.RED)).append(new TranslatableText("ui.galacticraft-rewoven.tabs.redstone_activation_config.redstone_means_off_2").setStyle(Style.EMPTY.withColor(Formatting.DARK_RED))));
        } else {
            list_1.add(new TranslatableText("ui.galacticraft-rewoven.tabs.redstone_activation_config_2").setStyle(Style.EMPTY.withColor(Formatting.RED)).append(new TranslatableText("ui.galacticraft-rewoven.tabs.redstone_activation_config.redstone_means_on_2").setStyle(Style.EMPTY.withColor(Formatting.DARK_RED))));
        }

    }
}
 
Example 20
Source File: IForgeItem.java    From patchwork-api with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Override this method to change the NBT data being sent to the client. You
 * should ONLY override this when you have no other choice, as this might change
 * behavior client side!
 *
 * <p>Note that this will sometimes be applied multiple times, the following MUST
 * be supported:
 * Item item = stack.getItem();
 * CompoundTag nbtShare1 = item.getShareTag(stack);
 * stack.setTagCompound(nbtShare1);
 * CompoundTag nbtShare2 = item.getShareTag(stack);
 * assert nbtShare1.equals(nbtShare2);
 *
 * @param stack The stack to send the NBT tag for
 * @return The NBT tag
 */
@Nullable
default CompoundTag getShareTag(ItemStack stack) {
	return stack.getTag();
}