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

The following examples show how to use net.minecraft.item.ItemStack#setCount() . 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: BlockSnow.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune)
{
    if (content.snowball != null)
    {
        ItemStack stack = content.snowball.getItemStack().copy();
        stack.setCount((state.getValue(LAYERS) + 1) * stack.getCount());

        drops.add(stack);
    }

    Optional<BlockDrop[]> blockDrops = getContent().drop.get(getSubtype(state));
    if (blockDrops.isPresent())
    {
        drops.addAll(ItemHelper.getDroppedStacks(blockDrops.get(), fortune));
    }
}
 
Example 2
Source File: UpgradeFueled.java    From BetterChests with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void update(IUpgradableBlock chest, ItemStack stack) {
	if (UpgradeHelper.INSTANCE.getFrequencyTick(chest, stack, 64) != 0) {
		return;
	}
	IEnergyStorage storage = chest.getEnergyStorage();
	if (storage.getEnergyStored() >= storage.getMaxEnergyStored()) {
		return;
	}

	IBetterChest inv = (IBetterChest) chest;
	IFilter filter = inv.getFilterFor(stack);

	int slot = InvUtil.findInInvInternal(inv, null, test -> TileEntityFurnace.getItemBurnTime(test) > 0 && filter.matchesStack(test));
	if (slot != -1) {
		ItemStack current = inv.getStackInSlot(slot);
		int provided = TileEntityFurnace.getItemBurnTime(current) * Config.INSTANCE.energyFueled;
		if (storage.receiveEnergy(provided, true) == provided) {
			storage.receiveEnergy(provided, false);
			current.setCount(current.getCount() - 1);
			inv.markDirty();
		}
	}
}
 
Example 3
Source File: ModularUIGui.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void renderItemStackOnMouse(int mouseX, int mouseY) {
    InventoryPlayer inventory = this.mc.player.inventory;
    ItemStack itemStack = this.draggedStack.isEmpty() ? inventory.getItemStack() : this.draggedStack;

    if (!itemStack.isEmpty()) {
        int dragOffset = this.draggedStack.isEmpty() ? 8 : 16;
        if (!this.draggedStack.isEmpty() && this.isRightMouseClick) {
            itemStack = itemStack.copy();
            itemStack.setCount(MathHelper.ceil((float) itemStack.getCount() / 2.0F));

        } else if (this.dragSplitting && this.dragSplittingSlots.size() > 1) {
            itemStack = itemStack.copy();
            itemStack.setCount(this.dragSplittingRemnant);
        }
        this.drawItemStack(itemStack, mouseX - guiLeft - 8, mouseY - guiTop - dragOffset, null);
    }
}
 
Example 4
Source File: ContainerCustomSlotClick.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void middleClickSlot(int slotNum, EntityPlayer player)
{
    if (player.capabilities.isCreativeMode &&
        this.playerMainSlotsIncHotbar.contains(slotNum) &&
        player.inventory.getItemStack().isEmpty() &&
        this.getSlot(slotNum).getHasStack())
    {
        ItemStack stack = this.getSlot(slotNum).getStack().copy();
        stack.setCount(stack.getMaxStackSize());
        player.inventory.setItemStack(stack);
    }
    else
    {
        this.swapSlots(slotNum, player);
    }
}
 
Example 5
Source File: TileEntitySeedStorage.java    From AgriCraft with MIT License 6 votes vote down vote up
@Override
public ItemStack decrStackSize(int slot, int amount) {
    if (slotsList == null || slot >= slotsList.size() || (!this.hasLockedSeed())) {
        return null;
    }
    if (!this.getWorld().isRemote) {
        ItemStack stackInSlot = null;
        SeedStorageSlot slotAt = this.slotsList.get(slot);
        if (slotAt != null) {
            stackInSlot = slotAt.toStack();
            stackInSlot.setCount(Math.min(amount, slotAt.count));
            if (slotAt.count <= amount) {
                this.slots.remove(slotAt.getId());
                this.slotsList.remove(slotAt);
                slotAt.count = 0;
            } else {
                slotAt.count = slotAt.count - amount;
            }
        }
        this.syncSlotToClient(slotAt);
        return stackInSlot;
    }
    return null;
}
 
Example 6
Source File: ContainerBarrel.java    From BetterChests with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ItemStack decrStackSize(int amount) {
	ItemStack ret = getBarrel().getDummy().copy();
	amount = Math.min(amount, ret.getMaxStackSize());
	int gotten = 0;
	for (int i : getBarrel().getSlotsForFace(null)) {
		if (ItemUtil.areItemsSameMatchingIdDamageNbt(ret, getBarrel().getStackInSlot(i))) {
			gotten += getBarrel().decrStackSize(i, amount - gotten).getCount();
			if (gotten >= amount) {
				break;
			}
		}
	}
	ret.setCount(gotten);
	onSlotChanged();
	return ret;
}
 
Example 7
Source File: InventoryUtils.java    From OpenModsLib with MIT License 6 votes vote down vote up
public static boolean tryMergeStacks(@Nonnull ItemStack stackToMerge, @Nonnull ItemStack stackInSlot) {
	if (stackInSlot.isEmpty() || !stackInSlot.isItemEqual(stackToMerge) || !ItemStack.areItemStackTagsEqual(stackToMerge, stackInSlot)) return false;

	int newStackSize = stackInSlot.getCount() + stackToMerge.getCount();

	final int maxStackSize = stackToMerge.getMaxStackSize();
	if (newStackSize <= maxStackSize) {
		stackToMerge.setCount(0);
		stackInSlot.setCount(newStackSize);
		return true;
	} else if (stackInSlot.getCount() < maxStackSize) {
		stackToMerge.shrink(maxStackSize - stackInSlot.getCount());
		stackInSlot.setCount(maxStackSize);
		return true;
	}

	return false;
}
 
Example 8
Source File: ChoppingBlockTileEntity.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void spawnItemStack(World worldIn, double x, double y, double z, ItemStack stack)
{
    while (stack.getCount() > 0)
    {
        int i = /*RANDOM.nextInt(3) +*/ 1;

        if (i > stack.getCount())
        {
            i = stack.getCount();
        }

        ItemStack copy = stack.copy();
        copy.setCount(i);
        stack.grow(-i);

        Block.spawnAsEntity(worldIn, new BlockPos(x, y, z), stack);
    }
}
 
Example 9
Source File: FWInventory.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ItemStack decrStackSize(int slot, int amount) {
	ItemStack stack = getStackInSlot(slot);
	ItemStack ret = stack.copy();
	ret.setCount(Math.min(ret.getCount(), amount));
	stack.setCount(stack.getCount() - ret.getCount());
	if (stack.getCount() <= 0) {
		setInventorySlotContents(slot, null);
		return ItemStack.EMPTY;
	}
	markDirty();
	return ret;
}
 
Example 10
Source File: ItemListSlotWidget.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void setCreativeHeldItem(ItemStack itemStack) {
    InventoryPlayer inventory = gui.entityPlayer.inventory;
    if (!itemStack.isEmpty() && inventory.getItemStack().isEmpty()) {
        itemStack.setCount(itemStack.getMaxStackSize());
        inventory.setItemStack(itemStack);
    }
}
 
Example 11
Source File: CocoaHandler.java    From BetterChests with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean handlePlant(IBetterChest chest, Collection<ItemStack> items, World world, BlockPos pos) {

	EnumFacing jungleBlock = EnumFacing.UP;
	for (EnumFacing side : EnumFacing.HORIZONTALS) {
		if (isJungleTree(world.getBlockState(pos.offset(side)))) {
			jungleBlock = side;
			break;
		}
	}
	world.setBlockState(pos, Blocks.COCOA.getDefaultState().withProperty(BlockCocoa.FACING, jungleBlock));
	ItemStack stack = items.stream().filter(this::canPlantStack).findFirst().get();
	stack.setCount(stack.getCount() - 1);
	return true;
}
 
Example 12
Source File: ItemChestUpgrade.java    From BetterChests with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) {
	if (world.isRemote) {
		return EnumActionResult.PASS;
	}
	IBlockState state = world.getBlockState(pos);
	TileEntity te = world.getTileEntity(pos);
	if (state.getBlock() == Blocks.CHEST && te instanceof TileEntityChest) {
		TileEntityChest chest = (TileEntityChest) te;
		ItemStack[] items = new ItemStack[chest.getSizeInventory()];
		for (int i = 0; i < items.length; i++) {
			items[i] = chest.getStackInSlot(i);
			chest.setInventorySlotContents(i, ItemStack.EMPTY);
		}
		IBlockState newState = BlocksItemsBetterChests.betterchest.getDefaultState().withProperty(BlockBetterChest.directions, state.getValue(BlockChest.FACING));
		world.setBlockState(pos, newState, 2);
		TileEntityBChest newte = new TileEntityBChest();
		world.setTileEntity(pos, newte);
		for (int i = 0; i < items.length; i++) {
			newte.getChestPart().setInventorySlotContents(i, items[i]);
		}
		world.notifyBlockUpdate(pos, state, newState, 1);
		ItemStack heldItem = player.getHeldItem(hand);
		heldItem.setCount(heldItem.getCount() - 1);
		return EnumActionResult.SUCCESS;
	}
	return EnumActionResult.PASS;
}
 
Example 13
Source File: BlockCrop.java    From TFC2 with GNU General Public License v3.0 5 votes vote down vote up
/*******************************************************************************
 * 1. Content
 *******************************************************************************/

@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
	if(worldIn.isRemote)
		return false;

	IslandMap map = Core.getMapForWorld(worldIn, pos);
	TileCrop tile = (TileCrop) worldIn.getTileEntity(pos);
	CropEvent.Harvest event = new CropEvent.Harvest(worldIn, map, pos);
	Global.EVENT_BUS.post(event);
	//If the event is canceled then skip all of our code.
	if(!event.isCanceled())
	{
		((World)worldIn).setBlockToAir(pos);

		if(tile.getGrowthStage() >= tile.getCropType().getGrowthStages() - 1)
		{
			Collection produce = FoodRegistry.getInstance().getProduceForCrop(tile.getCropType().getName());
			Iterator iter = produce.iterator();
			while(iter.hasNext())
			{
				ItemStack is = ((ItemStack) iter.next()).copy();
				is.setCount(1);
				if(is.getItem() instanceof IFood)
					Food.setDecayTimer(is, worldIn.getWorldTime()+Food.getExpirationTimer(is));
				Core.dropItem(worldIn, pos.getX()+0.5, pos.getY()+0.5, pos.getZ()+0.5, is);
			}
		}
	}
	return true;
}
 
Example 14
Source File: MetaTileEntityQuantumChest.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Nonnull
@Override
public ItemStack getStackInSlot(int slot) {
    ItemStack itemStack = MetaTileEntityQuantumChest.this.itemStack;
    long itemsStored = MetaTileEntityQuantumChest.this.itemsStoredInside;
    if (itemStack.isEmpty() || itemsStored == 0L) {
        return ItemStack.EMPTY;
    }
    ItemStack resultStack = itemStack.copy();
    resultStack.setCount((int) itemsStored);
    return resultStack;
}
 
Example 15
Source File: MetaItem.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ItemStack getContainerItem(ItemStack itemStack) {
    T item = getItem(itemStack);
    if (item == null) {
        return ItemStack.EMPTY;
    }
    itemStack = itemStack.copy();
    itemStack.setCount(1);
    IItemContainerItemProvider provider = item.getContainerItemProvider();
    return provider == null ? ItemStack.EMPTY : provider.getContainerItem(itemStack);
}
 
Example 16
Source File: ItemPetContract.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public boolean itemInteractionForEntity(ItemStack stack, EntityPlayer player, EntityLivingBase target, EnumHand hand)
{
    if (target instanceof EntityTameable)
    {
        if (player.getEntityWorld().isRemote == false)
        {
            if (this.isSigned(stack))
            {
                UUID targetOwner = ((EntityTameable) target).getOwnerId();
                UUID signedOwner = this.getOwnerUUID(stack);

                // This contract is signed by the current owner of the target,
                // and the contract is for this target entity, and the player is not the owner
                // -> change the owner of the target.
                if (targetOwner != null && targetOwner.equals(signedOwner) &&
                    target.getUniqueID().equals(this.getSubjectUUID(stack)) &&
                    player.getUniqueID().equals(signedOwner) == false)
                {
                    ((EntityTameable) target).setTamed(true);
                    ((EntityTameable) target).setOwnerId(player.getUniqueID());

                    // See EntityTameable#handleStatusUpdate()
                    player.getEntityWorld().setEntityState(target, (byte) 7);

                    stack.shrink(1);
                }
            }
            // Blank contract - if the target is tamed, and owned by the player, sign the contract
            else
            {
                if (((EntityTameable) target).isTamed() && ((EntityTameable) target).isOwner(player))
                {
                    ItemStack stackSigned = stack.copy();
                    stackSigned.setCount(1);

                    this.signContract(stackSigned, player, target);

                    if (player.addItemStackToInventory(stackSigned) == false)
                    {
                        player.dropItem(stackSigned, false);
                    }

                    stack.shrink(1);
                }
            }
        }

        return true;
    }

    return super.itemInteractionForEntity(stack, player, target, hand);
}
 
Example 17
Source File: FacadeRegistryPlugin.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static IRecipeWrapper createFacadeRecipe(ItemStack itemStack, Material material, int facadeAmount) {
    itemStack.setCount(facadeAmount);
    return new FacadeRecipeWrapper(new ResourceLocation(GTValues.MODID, "facade_" + material),
        OreDictUnifier.get(OrePrefix.plate, material), itemStack);
}
 
Example 18
Source File: ItemStackHandlerBasic.java    From enderutilities with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
@Nonnull
public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate)
{
    if (stack.isEmpty() || this.isItemValidForSlot(slot, stack) == false)
    {
        return stack;
    }

    ItemStack existingStack = this.items.get(slot);
    int existingStackSize = existingStack.getCount();
    boolean hasStack = existingStack.isEmpty() == false;
    int max = this.getItemStackLimit(slot, stack);

    if (this.allowCustomStackSizes == false)
    {
        max = Math.min(max, stack.getMaxStackSize());
    }

    // Existing items in the target slot
    if (hasStack)
    {
        // If the slot is already full, or the to-be-inserted item is different
        if (existingStackSize >= max ||
            stack.getItem() != existingStack.getItem() ||
            stack.getMetadata() != existingStack.getMetadata() ||
            ItemStack.areItemStackTagsEqual(stack, existingStack) == false)
        {
            return stack;
        }
    }

    int amount = Math.min(max - existingStackSize, stack.getCount());

    if (amount <= 0)
    {
        return stack;
    }

    if (simulate == false)
    {
        if (hasStack)
        {
            existingStack.grow(amount);
        }
        else
        {
            ItemStack newStack = stack.copy();
            newStack.setCount(amount);
            this.items.set(slot, newStack);
        }

        this.onContentsChanged(slot);
    }

    if (amount < stack.getCount())
    {
        ItemStack stackRemaining = stack.copy();
        stackRemaining.shrink(amount);

        return stackRemaining;
    }
    else
    {
        return ItemStack.EMPTY;
    }
}
 
Example 19
Source File: ModuleExtract.java    From Logistics-Pipes-2 with MIT License 4 votes vote down vote up
@Override
public boolean execute(TileRoutedPipe te) {
	if(ticksTillOp!=0) {
		ticksTillOp-=1;
	}else {
		
		ticksTillOp=References.MOD_BASE_OPERATION_RATE;
		if(te.hasInventory() && te.hasNetwork()) {
			boolean hasWorked = false;
			int tryDest = 0;
			int tryItem = 0;
			ArrayList<ItemStack> stacks = te.getItemsInInventory(te.getNetwork().getDirectionForDestination(te.nodeID));
			try {
				if(!stacks.isEmpty()) {
					Item item = stacks.get(tryItem).getItem();
					while(!te.getNetwork().hasStorageForItem(item) && tryItem<stacks.size()) {
						tryItem+=1;
						item = stacks.get(tryItem).getItem();
						LogisticsPipes2.logger.log(Level.INFO, "Module:" + this.MODULE_ID + " has skipped an Itemstack!");
					}
					UUID nodeT = te.getNetwork().getClosestStorageNode(item, te.nodeID, tryDest);
					while(!hasWorked) {
						if(nodeT==null) {
							return false;
						}
						if(nodeT.equals(te.nodeID)) {
							tryDest+=1;
							nodeT = te.getNetwork().getClosestStorageNode(item, te.nodeID, tryDest);
							LogisticsPipes2.logger.log(Level.INFO, "Module:" + this.MODULE_ID + " avoided Self-Routing!");
							continue;
						}
						
						ItemStack stack = stacks.get(tryItem).copy();
						if(stack.getCount()>References.MOD_EXTRACT_BASE_COUNT) {
							stack.setCount(References.MOD_EXTRACT_BASE_COUNT);
						}
						te.routeItemTo(nodeT, stack);
						hasWorked=true;
					}
				}
			} catch (Exception e) {
				return false;
			}
		}
	}
	
	return true;
}
 
Example 20
Source File: RecipeMapFluidCanner.java    From GregTech with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
@Nullable
public Recipe findRecipe(long voltage, List<ItemStack> inputs, List<FluidStack> fluidInputs, int outputFluidTankCapacity) {
    Recipe recipe = super.findRecipe(voltage, inputs, fluidInputs, outputFluidTankCapacity);
    if (inputs.size() == 0 || inputs.get(0).isEmpty() || recipe != null)
        return recipe;

    // Fail early if input isn't a fluid container
    if (!inputs.get(0).hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null))
        return null;

    // Make a copy to use for creating recipes
    ItemStack inputStack = inputs.get(0).copy();
    inputStack.setCount(1);

    // Make another copy to use for draining and filling
    ItemStack fluidHandlerItemStack = inputStack.copy();
    IFluidHandlerItem fluidHandlerItem = fluidHandlerItemStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null);
    if (fluidHandlerItem == null)
        return null;

    FluidStack containerFluid = fluidHandlerItem.drain(Integer.MAX_VALUE, true);
    if (containerFluid != null) {
        //if we actually drained something, then it's draining recipe
        return recipeBuilder()
            //we can reuse recipe as long as input container stack fully matches our one
            .inputs(new CountableIngredient(new NBTIngredient(inputStack), 1))
            .outputs(fluidHandlerItem.getContainer())
            .fluidOutputs(containerFluid)
            .duration(Math.max(16, containerFluid.amount / 64)).EUt(4)
            .build().getResult();
    }

    //if we didn't drain anything, try filling container
    if (!fluidInputs.isEmpty() && fluidInputs.get(0) != null) {
        FluidStack inputFluid = fluidInputs.get(0).copy();
        inputFluid.amount = fluidHandlerItem.fill(inputFluid, true);
        if (inputFluid.amount > 0) {
            return recipeBuilder()
                //we can reuse recipe as long as input container stack fully matches our one
                .inputs(new CountableIngredient(new NBTIngredient(inputStack), 1))
                .fluidInputs(inputFluid)
                .outputs(fluidHandlerItem.getContainer())
                .duration(Math.max(16, inputFluid.amount / 64)).EUt(4)
                .build().getResult();
        }
    }
    return null;
}