Java Code Examples for net.minecraft.inventory.IInventory#setInventorySlotContents()

The following examples show how to use net.minecraft.inventory.IInventory#setInventorySlotContents() . 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: ShapedOreEnergyTransferRecipe.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void chargeStackFromComponents(ItemStack toolStack, IInventory ingredients, Predicate<ItemStack> chargePredicate, boolean transferMaxCharge) {
    IElectricItem electricItem = toolStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    long totalMaxCharge = 0L;
    if (electricItem != null && electricItem.getMaxCharge() > 0L) {
        for (int slotIndex = 0; slotIndex < ingredients.getSizeInventory(); slotIndex++) {
            ItemStack stackInSlot = ingredients.getStackInSlot(slotIndex);
            if(!chargePredicate.test(stackInSlot)) {
                continue;
            }
            IElectricItem batteryItem = stackInSlot.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
            if (batteryItem == null) {
                continue;
            }
            totalMaxCharge += batteryItem.getMaxCharge();
            long discharged = batteryItem.discharge(Long.MAX_VALUE, Integer.MAX_VALUE, true, true, false);
            electricItem.charge(discharged, Integer.MAX_VALUE, true, false);
            if (discharged > 0L) {
                ingredients.setInventorySlotContents(slotIndex, stackInSlot);
            }
        }
    }
    if(electricItem instanceof ElectricItem && transferMaxCharge) {
        ((ElectricItem) electricItem).setMaxChargeOverride(totalMaxCharge);
    }
}
 
Example 2
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Static default implementation for IInventory method
 */
@Nonnull
public static ItemStack decrStackSize(IInventory inv, int slot, int size) {
    ItemStack item = inv.getStackInSlot(slot);

    if (!item.isEmpty()) {
        if (item.getCount() <= size) {
            inv.setInventorySlotContents(slot, ItemStack.EMPTY);
            inv.markDirty();
            return item;
        }
        ItemStack itemstack1 = item.split(size);
        if (item.getCount() == 0) {
            inv.setInventorySlotContents(slot, ItemStack.EMPTY);
        } else {
            inv.setInventorySlotContents(slot, item);
        }

        inv.markDirty();
        return itemstack1;
    }
    return ItemStack.EMPTY;
}
 
Example 3
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Static default implementation for IInventory method
 */
public static ItemStack decrStackSize(IInventory inv, int slot, int size) {
    ItemStack item = inv.getStackInSlot(slot);

    if (item != null) {
        if (item.stackSize <= size) {
            inv.setInventorySlotContents(slot, null);
            inv.markDirty();
            return item;
        }
        ItemStack itemstack1 = item.splitStack(size);
        if (item.stackSize == 0)
            inv.setInventorySlotContents(slot, null);
        else
            inv.setInventorySlotContents(slot, item);

        inv.markDirty();
        return itemstack1;
    }
    return null;
}
 
Example 4
Source File: AdapterWritingDesk.java    From OpenPeripheral-Integration with MIT License 6 votes vote down vote up
@ScriptCallable(returnTypes = ReturnType.BOOLEAN, description = "Pull an item from the target inventory into any slot in the current one. Returns true if item was consumed")
public boolean pullNotebookPage(TileEntity desk,
		@Arg(name = "deskSlot") Index deskSlot,
		@Arg(name = "direction", description = "The direction of the other inventory)") ForgeDirection direction,
		@Arg(name = "fromSlot", description = "The slot in the other inventory that you're pulling from") Index fromSlot) {

	IInventory inv = getTargetTile(desk, direction);

	fromSlot.checkElementIndex("input slot", inv.getSizeInventory());

	ItemStack stack = inv.getStackInSlot(fromSlot.value);
	Preconditions.checkNotNull(stack, "Other inventory empty");

	final NotebookWrapper wrapper = createInventoryWrapper(desk, deskSlot);

	ItemStack added = wrapper.addPage(stack);
	inv.setInventorySlotContents(fromSlot.value, added);
	inv.markDirty();
	return added == null;
}
 
Example 5
Source File: AdapterInventory.java    From OpenPeripheral-Integration with MIT License 6 votes vote down vote up
@Asynchronous(false)
@ScriptCallable(description = "Condense and tidy the stacks in an inventory")
public void condenseItems(IInventory target) {
	IInventory inventory = InventoryUtils.getInventory(target);
	List<ItemStack> stacks = Lists.newArrayList();
	for (int i = 0; i < inventory.getSizeInventory(); i++) {
		ItemStack sta = inventory.getStackInSlot(i);
		if (sta != null) stacks.add(sta.copy());
		inventory.setInventorySlotContents(i, null);
	}

	for (ItemStack stack : stacks)
		ItemDistribution.insertItemIntoInventory(inventory, stack, ForgeDirection.UNKNOWN, ANY_SLOT);

	target.markDirty();
}
 
Example 6
Source File: TileEntityBase.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
public static void readInventoryFromNBT(NBTTagCompound tag, IInventory inventory, String tagName){
    ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()];
    readInventoryFromNBT(tag, stacks, tagName);
    for(int i = 0; i < stacks.length; i++) {
        inventory.setInventorySlotContents(i, stacks[i]);
    }
}
 
Example 7
Source File: IOHelper.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
public static ItemStack extract(IInventory inventory, ForgeDirection direction, int slot, boolean simulate){

        ItemStack itemstack = inventory.getStackInSlot(slot);

        if(itemstack != null && canExtractItemFromInventory(inventory, itemstack, slot, direction.ordinal())) {
            if(!simulate) inventory.setInventorySlotContents(slot, null);
            return itemstack;
        }
        return null;
    }
 
Example 8
Source File: DroneEntityAIInventoryImport.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
private boolean importItems(ChunkPosition pos, boolean simulate){
    IInventory inv = IOHelper.getInventoryForTE(drone.getWorld().getTileEntity(pos.chunkPosX, pos.chunkPosY, pos.chunkPosZ));
    if(inv != null) {
        Set<Integer> accessibleSlots = PneumaticCraftUtils.getAccessibleSlotsForInventoryAndSides(inv, ((ISidedWidget)widget).getSides());
        for(Integer i : accessibleSlots) {
            ItemStack stack = inv.getStackInSlot(i);
            if(stack != null && IOHelper.canExtractItemFromInventory(inv, stack, i, ((ISidedWidget)widget).getSides())) {
                if(widget.isItemValidForFilters(stack)) {
                    ItemStack importedStack = stack.copy();
                    if(((ICountWidget)widget).useCount()) importedStack.stackSize = Math.min(importedStack.stackSize, getRemainingCount());
                    ItemStack remainder = IOHelper.insert(drone.getInventory(), importedStack.copy(), 0, simulate);
                    int removedItems = importedStack.stackSize - (remainder != null ? remainder.stackSize : 0);
                    if(!simulate) {
                        ItemStack newStack = stack.copy();
                        newStack.stackSize = stack.stackSize - removedItems;
                        inv.setInventorySlotContents(i, newStack.stackSize > 0 ? newStack : null);
                        decreaseCount(removedItems);
                        drone.addAir(null, -PneumaticValues.DRONE_USAGE_INV);
                        if(((ICountWidget)widget).useCount() && getRemainingCount() <= 0) return false;
                    } else if(removedItems > 0) {
                        return true;
                    } else {
                        drone.addDebugEntry("gui.progWidget.inventoryImport.debug.filledToMax", pos);
                    }
                } else {
                    drone.addDebugEntry("gui.progWidget.inventoryImport.debug.stackdoesntPassFilter", pos);
                }
            }
        }
    } else {
        drone.addDebugEntry("gui.progWidget.inventory.debug.noInventory", pos);
    }

    return false;
}
 
Example 9
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Consumes one item from slot in inv with support for containers.
 */
public static void consumeItem(IInventory inv, int slot) {
    ItemStack stack = inv.getStackInSlot(slot);
    Item item = stack.getItem();
    if (item.hasContainerItem(stack)) {
        ItemStack container = item.getContainerItem(stack);
        inv.setInventorySlotContents(slot, container);
    } else {
        inv.decrStackSize(slot, 1);
    }
}
 
Example 10
Source File: ItemSubCollar.java    From ForbiddenMagic with Do What The F*ck You Want To Public License 5 votes vote down vote up
/**
 * Returns true if the item can be used on the given entity, e.g. shears on sheep.
 */
@Override
public boolean itemInteractionForEntity(ItemStack itemstack, EntityPlayer player, EntityLivingBase entity)
{
    if (entity.worldObj.isRemote)
    {
        return false;
    }
    if (entity instanceof EntityPlayer)
    {
        EntityPlayer sub = (EntityPlayer)entity;
        IInventory baubles = BaublesApi.getBaubles(sub);
        if(baubles.getStackInSlot(0) == null) {
            if(!itemstack.hasTagCompound()){
                NBTTagCompound tag = new NBTTagCompound();
                itemstack.setTagCompound(tag);
            }
            itemstack.stackTagCompound.setString("owner", player.getDisplayName());
            baubles.setInventorySlotContents(0, itemstack.copy());
            itemstack.stackSize = 0;
            sub.addChatMessage(new ChatComponentText(StatCollector.translateToLocal("message.collar.placescollar").replace("%s", player.getDisplayName())));
            player.addChatMessage(new ChatComponentText(StatCollector.translateToLocal("message.collar.youplacecollar").replace("%s", sub.getDisplayName())));
            return true;
        }
        else
            player.addChatMessage(new ChatComponentText(StatCollector.translateToLocal("message.collar.alreadywearing").replace("%s", sub.getDisplayName())));
    }
    return false;
}
 
Example 11
Source File: AdapterInventory.java    From OpenPeripheral-Integration with MIT License 5 votes vote down vote up
@Asynchronous(false)
@ScriptCallable(description = "Destroy a stack")
public void destroyStack(IInventory target,
		@Arg(name = "slotNumber", description = "The slot number") Index slot) {
	IInventory inventory = InventoryUtils.getInventory(target);
	slot.checkElementIndex("slot id", inventory.getSizeInventory());
	inventory.setInventorySlotContents(slot.value, null);
	inventory.markDirty();
}
 
Example 12
Source File: StorageChunk.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
public static StorageChunk cutWorldBB(World worldObj, AxisAlignedBB bb) {
	StorageChunk chunk = StorageChunk.copyWorldBB(worldObj, bb);
	for(int x = (int)bb.minX; x <= bb.maxX; x++) {
		for(int z = (int)bb.minZ; z <= bb.maxZ; z++) {
			for(int y = (int)bb.minY; y<= bb.maxY; y++) {

				BlockPos pos = new BlockPos(x, y, z);
				//Workaround for dupe
				TileEntity tile = worldObj.getTileEntity(pos);
				if(tile instanceof IInventory) {
					IInventory inv = (IInventory) tile;
					for(int i = 0; i < inv.getSizeInventory(); i++) {
						inv.setInventorySlotContents(i, ItemStack.EMPTY);
					}
				}

				worldObj.setBlockState(pos, Blocks.AIR.getDefaultState(),2);
			}
		}
	}

	//Carpenter's block's dupe
	for(Object entity : worldObj.getEntitiesWithinAABB(EntityItem.class, bb.grow(5, 5, 5)) ) {
		((Entity)entity).setDead();
	}

	return chunk;
}
 
Example 13
Source File: SignalsUtils.java    From Signals with GNU General Public License v3.0 5 votes vote down vote up
public static void readInventoryFromNBT(NBTTagCompound tag, IInventory inventory, String tagName){
    ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()];
    readInventoryFromNBT(tag, stacks, tagName);
    for(int i = 0; i < stacks.length; i++) {
        inventory.setInventorySlotContents(i, stacks[i]);
    }
}
 
Example 14
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Consumes one item from slot in inv with support for containers.
 */
public static void consumeItem(IInventory inv, int slot) {
    ItemStack stack = inv.getStackInSlot(slot);
    Item item = stack.getItem();
    if (item.hasContainerItem(stack)) {
        ItemStack container = item.getContainerItem(stack);
        inv.setInventorySlotContents(slot, container);
    } else {
        inv.decrStackSize(slot, 1);
    }
}
 
Example 15
Source File: GraveyardGenerator.java    From ToroQuest with GNU General Public License v3.0 5 votes vote down vote up
protected void addLootToChest(IInventory chest) {
	for (int i = 0; i < chest.getSizeInventory(); i++) {
		int roll = rand.nextInt(8);

		if (roll == 0) {
			chest.setInventorySlotContents(i, new ItemStack(Items.BONE, rand.nextInt(5) + 1));
		} else if (roll == 1) {
			chest.setInventorySlotContents(i, new ItemStack(Items.ROTTEN_FLESH, rand.nextInt(5) + 1));
		} else if (roll == 2) {
			if (rand.nextInt(20) == 0) {
				chest.setInventorySlotContents(i, new ItemStack(NICE_STUFF[rand.nextInt(NICE_STUFF.length)]));
			}
		}
	}
}
 
Example 16
Source File: TileRocketUnloader.java    From AdvancedRocketry with MIT License 4 votes vote down vote up
@Override
public void update() {

	//Move a stack of items
	if(!world.isRemote && rocket != null ) {
		boolean isAllowedToOperate = (inputstate == RedstoneState.OFF || isStateActive(inputstate, getStrongPowerForSides(world, getPos())));

		List<TileEntity> tiles = rocket.storage.getInventoryTiles();
		boolean foundStack = false;
		boolean rocketContainsNoItems = true;
		out:
			//Function returns if something can be moved
			for(TileEntity tile : tiles) {
				if(tile instanceof IInventory && !(tile instanceof TileGuidanceComputer)) {
					IInventory inv = ((IInventory)tile);
					for(int i = 0; i < inv.getSizeInventory(); i++) {
						if(!inv.getStackInSlot(i).isEmpty()) {
							rocketContainsNoItems = false;
							//Loop though this inventory's slots and find a suitible one
							for(int j = 0; j < getSizeInventory(); j++) {
								if(getStackInSlot(j).isEmpty()) {
									if(isAllowedToOperate) {
										inventory.setInventorySlotContents(j, inv.getStackInSlot(i));
										inv.setInventorySlotContents(i,ItemStack.EMPTY);
									}
									break out;
								}
								else if(!inv.getStackInSlot(i).isEmpty() && isItemValidForSlot(j, inv.getStackInSlot(i))) {
									if(isAllowedToOperate) {
										ItemStack stack2 = inv.decrStackSize(i, getStackInSlot(j).getMaxStackSize() - getStackInSlot(j).getCount());
										getStackInSlot(j).setCount(getStackInSlot(j).getCount() + stack2.getCount());
									}
									if(inv.getStackInSlot(i).isEmpty())
										break out;
									foundStack = true;
								}
							}
						}

						if(foundStack)
							break out;
					}
				}
			}

		//Update redstone state
		setRedstoneState(rocketContainsNoItems);

	}
}
 
Example 17
Source File: WorldTickEventHandler.java    From Et-Futurum with The Unlicense 4 votes vote down vote up
@SubscribeEvent
public void tick(WorldTickEvent event) {
	if (event.side != Side.SERVER || event.phase != Phase.END || isReplacing)
		return;

	if (replacements == null) {
		replacements = new HashMap<Block, Block>();
		if (EtFuturum.enableBrewingStands)
			replacements.put(Blocks.brewing_stand, ModBlocks.brewing_stand);
		if (EtFuturum.enableColourfulBeacons)
			replacements.put(Blocks.beacon, ModBlocks.beacon);
		if (EtFuturum.enableEnchants)
			replacements.put(Blocks.enchanting_table, ModBlocks.enchantment_table);
		if (EtFuturum.enableInvertedDaylightSensor)
			replacements.put(Blocks.daylight_detector, ModBlocks.daylight_sensor);
	}

	if (replacements.isEmpty())
		return;

	isReplacing = true;
	World world = event.world;

	for (int i = 0; i < world.loadedTileEntityList.size(); i++) {
		TileEntity tile = (TileEntity) world.loadedTileEntityList.get(i);
		int x = tile.xCoord;
		int y = tile.yCoord;
		int z = tile.zCoord;
		Block replacement = replacements.get(world.getBlock(x, y, z));
		if (replacement != null && ((IConfigurable) replacement).isEnabled()) {
			NBTTagCompound nbt = new NBTTagCompound();
			tile.writeToNBT(nbt);
			if (tile instanceof IInventory) {
				IInventory invt = (IInventory) tile;
				for (int j = 0; j < invt.getSizeInventory(); j++)
					invt.setInventorySlotContents(j, null);
			}
			world.setBlock(x, y, z, replacement);
			TileEntity newTile = world.getTileEntity(x, y, z);
			newTile.readFromNBT(nbt);
			break;
		}
	}
	isReplacing = false;
}
 
Example 18
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Static default implementation for IInventory method
 */
public static ItemStack getStackInSlotOnClosing(IInventory inv, int slot) {
    ItemStack stack = inv.getStackInSlot(slot);
    inv.setInventorySlotContents(slot, null);
    return stack;
}
 
Example 19
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Static default implementation for IInventory method
 */
public static ItemStack removeStackFromSlot(IInventory inv, int slot) {
    ItemStack stack = inv.getStackInSlot(slot);
    inv.setInventorySlotContents(slot, ItemStack.EMPTY);
    return stack;
}