net.minecraftforge.items.IItemHandler Java Examples

The following examples show how to use net.minecraftforge.items.IItemHandler. 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: TileEntitySimple.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private IItemHandlerModifiable getItemHandlerCapability(@Nullable EnumFacing facing)
{
    Capability<IItemHandler> capability = CapabilityItemHandler.ITEM_HANDLER_CAPABILITY;

    List<IItemHandlerModifiable> handlers = Lists.newLinkedList();

    for (TileEntityModule module : modules.values())
    {
        if (module.hasCapability(capability, facing))
            handlers.add((IItemHandlerModifiable) module.getCapability(capability, facing));
    }

    if (handlers.size() == 1)
        return handlers.get(0);
    else if (handlers.size() > 1)
        return new CombinedInvWrapper(handlers.toArray(new IItemHandlerModifiable[handlers.size()]));
    else
        return null;
}
 
Example #2
Source File: UtilItemModular.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns either the player's inventory, or a bound, linked inventory that has items matching <b>templateStack</b>,
 * or null if no matching items are found.
 */
public static IItemHandler getPlayerOrBoundInventoryWithItems(ItemStack toolStack, ItemStack templateStack, EntityPlayer player)
{
    IItemHandler inv = player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
    int slot = InventoryUtils.getSlotOfFirstMatchingItemStack(inv, templateStack);

    if (slot != -1)
    {
        return inv;
    }

    inv = getBoundInventory(toolStack, player, 30);

    if (inv != null)
    {
        slot = InventoryUtils.getSlotOfFirstMatchingItemStack(inv, templateStack);

        if (slot != -1)
        {
            return inv;
        }
    }

    return null;
}
 
Example #3
Source File: ItemQuickStacker.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos,
        EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ)
{
    if (player.isSneaking())
    {
        TileEntity te = world.getTileEntity(pos);

        if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side))
        {
            IItemHandler inv = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side);

            if (world.isRemote == false && inv != null)
            {
                quickStackItems(player, player.getHeldItem(hand), inv);
            }

            return EnumActionResult.SUCCESS;
        }
    }

    return super.onItemUse(player, world, pos, hand, side, hitX, hitY, hitZ);
}
 
Example #4
Source File: InventoryUtils.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns the minimum stack size from the inventory <b>inv</b> from
 * stacks that are not empty, or -1 if all stacks are empty.
 * @param inv
 * @return minimum stack size from the inventory, or -1 if all stacks are empty
 */
public static int getMinNonEmptyStackSize(IItemHandler inv)
{
    int minSize = -1;
    final int invSize = inv.getSlots();

    for (int slot = 0; slot < invSize; slot++)
    {
        ItemStack stack = inv.getStackInSlot(slot);

        if (stack.isEmpty() == false && (stack.getCount() < minSize || minSize < 0))
        {
            minSize = stack.getCount();
        }
    }

    return minSize;
}
 
Example #5
Source File: CoverRoboticArm.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected int doKeepExact(IItemHandler itemHandler, IItemHandler myItemHandler, int maxTransferAmount) {
    Map<Object, GroupItemInfo> currentItemAmount = doCountDestinationInventoryItemsByMatchIndex(itemHandler, myItemHandler);
    Map<Object, GroupItemInfo> sourceItemAmounts = doCountDestinationInventoryItemsByMatchIndex(myItemHandler, itemHandler);
    Iterator<Object> iterator = sourceItemAmounts.keySet().iterator();
    while (iterator.hasNext()) {
        Object filterSlotIndex = iterator.next();
        GroupItemInfo sourceInfo = sourceItemAmounts.get(filterSlotIndex);
        int itemToKeepAmount = itemFilterContainer.getSlotTransferLimit(sourceInfo.filterSlot, sourceInfo.itemStackTypes);
        int itemAmount = 0;
        if (currentItemAmount.containsKey(filterSlotIndex)) {
            GroupItemInfo destItemInfo = currentItemAmount.get(filterSlotIndex);
            itemAmount = destItemInfo.totalCount;
        }
        if (itemAmount < itemToKeepAmount) {
            sourceInfo.totalCount = itemToKeepAmount - itemAmount;
        } else {
            iterator.remove();
        }
    }
    return doTransferItemsByGroup(itemHandler, myItemHandler, sourceItemAmounts, maxTransferAmount);
}
 
Example #6
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static ItemStack insertItem(IItemHandler handler, ItemStack insert, boolean simulate) {
    insert = insert.copy();
    for (int pass = 0; pass < 2; pass++) {
        for (int slot = 0; slot < handler.getSlots(); slot++) {
            ItemStack stack = handler.getStackInSlot(slot);
            if (pass == 0 && stack.isEmpty()) {
                continue;
            }
            if (insert.isEmpty()) {
                return ItemStack.EMPTY;
            }
            insert = handler.insertItem(slot, insert, simulate);
        }
    }

    return insert;
}
 
Example #7
Source File: InventoryUtils.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns a map of how many slots contain the same item, for each item found in the inventory.
 */
public static Map<ItemType, Integer> getSlotCountPerItem(IItemHandler inv)
{
    Map<ItemType, Integer> slots = new HashMap<ItemType, Integer>();
    final int invSize = inv.getSlots();

    for (int slot = 0; slot < invSize; slot++)
    {
        ItemStack stackTmp = inv.getStackInSlot(slot);

        if (stackTmp.isEmpty() == false)
        {
            ItemType item = new ItemType(stackTmp);
            Integer count = slots.get(item);
            count = (count != null) ? count + 1 : 1;
            slots.put(item, Integer.valueOf(count));
        }
    }

    return slots;
}
 
Example #8
Source File: InventoryItemSource.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean refreshItemHandler(boolean simulated) {
    this.lastItemHandlerUpdateTick = world.getTotalWorldTime();
    IItemHandler newItemHandler = computeItemHandler();
    if (newItemHandler == null) {
        if (!simulated && invalidationCallback != null) {
            invalidationCallback.run();
        }
        this.cachedRefreshResult = false;
        return false;
    }
    if (!newItemHandler.equals(itemHandler) || newItemHandler.getSlots() != itemHandler.getSlots()) {
        this.itemHandler = newItemHandler;
        if (!simulated) {
            recomputeItemStackCount();
        }
        this.cachedRefreshResult = false;
        return false;
    }
    this.cachedRefreshResult = true;
    return true;
}
 
Example #9
Source File: CapabilityProviderItem.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
private IItemHandlerModifiable getItemHandlerCapability(@Nullable EnumFacing facing)
{
    Capability<IItemHandler> capability = CapabilityItemHandler.ITEM_HANDLER_CAPABILITY;

    List<IItemHandlerModifiable> handlers = Lists.newLinkedList();

    for (ItemModule module : modules.values())
    {
        if (module.hasCapability(capability, facing))
            handlers.add((IItemHandlerModifiable) module.getCapability(capability, facing));
    }

    if (handlers.size() == 1)
        return handlers.get(0);
    else if (handlers.size() > 1)
        return new CombinedInvWrapper(handlers.toArray(new IItemHandlerModifiable[handlers.size()]));
    else
        return null;
}
 
Example #10
Source File: Misc.java    From Logistics-Pipes-2 with MIT License 5 votes vote down vote up
public static void spawnInventoryInWorld(World world, double x, double y, double z, IItemHandler inventory){
	if (inventory != null && !world.isRemote){
		for (int i = 0; i < inventory.getSlots(); i ++){
			if (inventory.getStackInSlot(i) != ItemStack.EMPTY){
				world.spawnEntity(new EntityItem(world,x,y,z,inventory.getStackInSlot(i)));
			}
		}
	}
}
 
Example #11
Source File: TileEntityEnderUtilitiesInventory.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Stores a cached snapshot of the current inventory in a compound tag <b>InvCache</b>.
 * It is meant for tooltip use in the ItemBlocks.
 * @param nbt
 * @return
 */
public NBTTagCompound getCachedInventory(NBTTagCompound nbt, int maxEntries)
{
    IItemHandler inv = this.getBaseItemHandler();

    if (inv != null)
    {
        nbt = NBTUtils.storeCachedInventory(nbt, inv, maxEntries);
    }

    return nbt;
}
 
Example #12
Source File: ContainerSuperchest.java    From YouTubeModdingTutorial with MIT License 5 votes vote down vote up
private void addOwnSlots() {
    IItemHandler itemHandler = this.te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);

    int slotIndex = 0;
    for (int row = 0; row < 3; ++row) {
        for (int col = 0; col < 9; ++col) {
            int x = 10 + col * 18;
            int y = row * 18 + 8;
            this.addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y));
        }
    }
}
 
Example #13
Source File: ContainerFastFurnace.java    From YouTubeModdingTutorial with MIT License 5 votes vote down vote up
private void addOwnSlots() {
    IItemHandler itemHandler = this.te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
    int x = 10;
    int y = 26;

    int slotIndex = 0;
    addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y)); x += 18;
    addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y)); x += 18;
    addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y));

    x = 118;
    addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y)); x += 18;
    addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y)); x += 18;
    addSlotToContainer(new SlotItemHandler(itemHandler, slotIndex++, x, y));
}
 
Example #14
Source File: BlockUtils.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void getDropAndSetToAir(World world, EntityPlayer player, BlockPos pos, EnumFacing side, boolean addToInventory)
{
    if (player.capabilities.isCreativeMode == false)
    {
        ItemStack stack = BlockUtils.getPickBlockItemStack(world, pos, player, side);

        if (stack.isEmpty() == false)
        {
            if (addToInventory)
            {
                IItemHandler inv = player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);

                if (inv != null)
                {
                    stack = InventoryUtils.tryInsertItemStackToInventory(inv, stack);
                }
            }

            if (stack.isEmpty() == false)
            {
                EntityUtils.dropItemStacksInWorld(world, pos, stack, -1, true);
            }
        }
    }

    setBlockToAirWithBreakSound(world, pos);
}
 
Example #15
Source File: InventoryUtils.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Tries to fill all the existing stacks in invDst from invSrc within the provided slot ranges.
 */
public static InvResult fillStacksOfMatchingItemsWithinSlotRange(IItemHandler invSrc, IItemHandler invDst, SlotRange slotsSrc, SlotRange slotsDst)
{
    boolean movedAll = true;
    boolean movedSome = false;
    InvResult result = InvResult.MOVED_NOTHING;
    final int lastSlot = Math.min(slotsSrc.lastInc, invSrc.getSlots() - 1);

    for (int slot = slotsSrc.first; slot <= lastSlot; slot++)
    {
        ItemStack stack = invSrc.getStackInSlot(slot);

        if (stack.isEmpty() == false)
        {
            List<Integer> matchingSlots = getSlotNumbersOfMatchingStacksWithinSlotRange(invDst, stack, slotsDst);

            for (int dstSlot : matchingSlots)
            {
                result = tryMoveAllItemsWithinSlotRange(invSrc, invDst, new SlotRange(slot, 1), new SlotRange(dstSlot, 1));

                if (result != InvResult.MOVED_NOTHING)
                {
                    movedSome = true;
                }
                else
                {
                    movedAll = false;
                }
            }
        }
    }

    return movedAll ? InvResult.MOVED_ALL : (movedSome ? InvResult.MOVED_SOME : InvResult.MOVED_NOTHING);
}
 
Example #16
Source File: ModificationTable.java    From MiningGadgets with MIT License 5 votes vote down vote up
@Override
public void onReplaced(BlockState state, World worldIn, BlockPos pos, BlockState newState, boolean isMoving) {
    if (newState.getBlock() != this) {
        TileEntity tileEntity = worldIn.getTileEntity(pos);
        if (tileEntity != null) {
            LazyOptional<IItemHandler> cap = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
            cap.ifPresent(handler -> {
                for(int i = 0; i < handler.getSlots(); ++i) {
                    InventoryHelper.spawnItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), handler.getStackInSlot(i));
                }
            });
        }
        super.onReplaced(state, worldIn, pos, newState, isMoving);
    }
}
 
Example #17
Source File: RecipeMapMultiblockController.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected boolean checkStructureComponents(List<IMultiblockPart> parts, Map<MultiblockAbility<Object>, List<Object>> abilities) {
    //basically check minimal requirements for inputs count
    //noinspection SuspiciousMethodCalls
    int itemInputsCount = abilities.getOrDefault(MultiblockAbility.IMPORT_ITEMS, Collections.emptyList())
        .stream().map(it -> (IItemHandler) it).mapToInt(IItemHandler::getSlots).sum();
    //noinspection SuspiciousMethodCalls
    int fluidInputsCount = abilities.getOrDefault(MultiblockAbility.IMPORT_FLUIDS, Collections.emptyList()).size();
    //noinspection SuspiciousMethodCalls
    return itemInputsCount >= recipeMap.getMinInputs() &&
        fluidInputsCount >= recipeMap.getMinFluidInputs() &&
        abilities.containsKey(MultiblockAbility.INPUT_ENERGY);
}
 
Example #18
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static int getInsertableQuantity(IItemHandler handler, ItemStack stack) {
    ItemStack copy = ItemUtils.copyStack(stack, Integer.MAX_VALUE);
    int quantity = 0;
    for (int slot = 0; slot < handler.getSlots(); slot++) {
        if (canInsertStack(handler, slot, copy)) {
            ItemStack left = handler.insertItem(slot, copy, true);
            if (left.isEmpty()) {
                quantity += copy.getCount();
            } else {
                quantity += copy.getCount() - left.getCount();
            }
        }
    }
    return quantity;
}
 
Example #19
Source File: ItemEnderSword.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
private IItemHandler getLinkedInventoryWithChecks(ItemStack toolStack, EntityPlayer player)
{
    SwordMode mode = SwordMode.fromStack(toolStack);
    // Modes: 0: normal; 1: Add drops to player's inventory; 2: Transport drops to Link Crystal's bound destination

    // 0: normal mode; do nothing
    if (mode == SwordMode.NORMAL)
    {
        return null;
    }

    // 1: Add drops to player's inventory; To allow this, we require at least the lowest tier Ender Core (active) installed
    if (mode == SwordMode.PLAYER && this.getMaxModuleTier(toolStack, ModuleType.TYPE_ENDERCORE) >= ItemEnderPart.ENDER_CORE_TYPE_ACTIVE_BASIC)
    {
        return player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP); // main inventory
    }
    // 2: Teleport drops to the Link Crystal's bound target; To allow this, we require an active second tier Ender Core
    // For cross-dimensional item teleport we require the third tier of active Ender Core
    else if (mode == SwordMode.REMOTE &&
            this.getMaxModuleTier(toolStack, ModuleType.TYPE_ENDERCORE) >= ItemEnderPart.ENDER_CORE_TYPE_ACTIVE_ENHANCED &&
            UtilItemModular.useEnderCharge(toolStack, ENDER_CHARGE_COST, true))
    {
        TargetData target = TargetData.getTargetFromSelectedModule(toolStack, ModuleType.TYPE_LINKCRYSTAL);

        // For cross-dimensional item teleport we require the third tier of active Ender Core
        if (target == null ||
            (target.dimension != player.getEntityWorld().provider.getDimension() &&
             this.getMaxModuleTier(toolStack, ModuleType.TYPE_ENDERCORE) != ItemEnderPart.ENDER_CORE_TYPE_ACTIVE_ADVANCED))
        {
            return null;
        }

        return UtilItemModular.getBoundInventory(toolStack, player, 15);
    }

    return null;
}
 
Example #20
Source File: CoverConveyor.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected boolean doTransferItemsExact(IItemHandler itemHandler, IItemHandler myItemHandler, TypeItemInfo itemInfo) {
    if (conveyorMode == ConveyorMode.IMPORT) {
        return moveInventoryItemsExact(itemHandler, myItemHandler, itemInfo);
    } else if (conveyorMode == ConveyorMode.EXPORT) {
        return moveInventoryItemsExact(myItemHandler, itemHandler, itemInfo);
    }
    return false;
}
 
Example #21
Source File: CartHopperBehaviourItems.java    From Signals with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isCartEmpty(IItemHandler capability, List<Pair<TileEntity, EnumFacing>> filters){
    for(int i = 0; i < capability.getSlots(); i++) {
        ItemStack stack = capability.getStackInSlot(i);
        if(!stack.isEmpty() && passesFilters(stack, filters)) return false; //If there still is a stack which does pass the given filters.
    }
    return true;
}
 
Example #22
Source File: CoverConveyor.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Map<ItemStackKey, TypeItemInfo> doCountSourceInventoryItemsByType(IItemHandler itemHandler, IItemHandler myItemHandler) {
    if (conveyorMode == ConveyorMode.IMPORT) {
        return countInventoryItemsByType(itemHandler);
    } else if (conveyorMode == ConveyorMode.EXPORT) {
        return countInventoryItemsByType(myItemHandler);
    }
    return Collections.emptyMap();
}
 
Example #23
Source File: CoverConveyor.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Map<Object, GroupItemInfo> doCountDestinationInventoryItemsByMatchIndex(IItemHandler itemHandler, IItemHandler myItemHandler) {
    if (conveyorMode == ConveyorMode.IMPORT) {
        return countInventoryItemsByMatchSlot(myItemHandler);
    } else if (conveyorMode == ConveyorMode.EXPORT) {
        return countInventoryItemsByMatchSlot(itemHandler);
    }
    return Collections.emptyMap();
}
 
Example #24
Source File: InventoryUtils.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Counts the matching stacks.
 * Checks for insertion or extraction.
 *
 * @param handler The inventory.
 * @param filter  What we are checking for.
 * @param insert  If we are checking for insertion or extraction.
 * @return The total number of items of the specified filter type.
 */
public static int countMatchingStacks(IItemHandler handler, ItemStack filter, boolean insert) {

    int c = 0;
    for (int slot = 0; slot < handler.getSlots(); slot++) {
        ItemStack stack = handler.getStackInSlot(slot);
        if (!stack.isEmpty() && ItemUtils.areStacksSameType(filter, stack) && (insert ? canInsertStack(handler, slot, stack) : canExtractStack(handler, slot))) {
            c += stack.getCount();
        }
    }
    return c;
}
 
Example #25
Source File: ContainerInventorySwapper.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void addPlayerInventorySlots(int posX, int posY)
{
    super.addPlayerInventorySlots(posX, posY);

    // Player armor slots
    posX = 8 + this.xOffset;
    posY = 57;

    this.playerArmorSlots = new MergeSlotRange(this.inventorySlots.size(), 4);

    for (int i = 0; i < 4; i++)
    {
        this.addSlotToContainer(new SlotItemHandlerArmor(this, this.playerInv, i, 39 - i, posX, posY + i * 18));
    }

    if (this.baublesLoaded)
    {
        this.playerBaublesSlots = new MergeSlotRange(this.inventorySlots.size(), 7);

        // Add the Baubles slots as a priority slot range for shift+click merging
        this.addMergeSlotRangePlayerToExt(this.inventorySlots.size(), 7);
        IItemHandler inv = baublesProvider.getBaublesInventory(this.player);
        posX = 8;

        for (int i = 0; i < 7; i++)
        {
            this.addSlotToContainer(new SlotItemHandlerBaubles(this, inv, i, posX, posY + i * 18));
        }
    }
}
 
Example #26
Source File: TileEntityQuickStackerAdvanced.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void quickStackToInventories(World world, EntityPlayer player, long enabledSlotsMask,
        List<BlockPosDistance> positions, FilterSettings filter)
{
    IItemHandler playerInv = player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null);
    boolean movedSome = false;

    for (BlockPosDistance posDist : positions)
    {
        TileEntity te = world.getTileEntity(posDist.pos);

        if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP))
        {
            IItemHandler inv = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);

            if (inv != null)
            {
                Result result = quickStackItems(playerInv, inv, enabledSlotsMask, player.isSneaking() == false, filter);

                if (result != Result.MOVED_NONE)
                {
                    Effects.spawnParticlesFromServer(world.provider.getDimension(), posDist.pos, EnumParticleTypes.VILLAGER_HAPPY);
                    movedSome = true;
                }

                if (result == Result.MOVED_ALL)
                {
                    break;
                }
            }
        }
    }

    if (movedSome)
    {
        world.playSound(null, player.getPosition(), SoundEvents.ENTITY_ENDERMEN_TELEPORT, SoundCategory.MASTER, 0.5f, 1.8f);
    }
}
 
Example #27
Source File: CraftingRecipeMemory.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void notifyRecipePerformed(IItemHandler craftingGrid, ItemStack resultStack) {
    MemorizedRecipe recipe = findOrCreateRecipe(resultStack);
    if (recipe != null) {
        recipe.updateCraftingMatrix(craftingGrid);
        recipe.timesUsed++;
    }
}
 
Example #28
Source File: TileEntityCreationStation.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds one more of each item in the recipe into the crafting grid, if possible
 * @param invId
 * @param recipeId
 */
protected boolean addOneSetOfRecipeItemsIntoGrid(IItemHandler invCrafting, int invId, int recipeId, EntityPlayer player)
{
    invId = MathHelper.clamp(invId, 0, 1);
    int maskOreDict = invId == 1 ? MODE_BIT_RIGHT_CRAFTING_OREDICT : MODE_BIT_LEFT_CRAFTING_OREDICT;
    boolean useOreDict = (this.modeMask & maskOreDict) != 0;

    IItemHandlerModifiable playerInv = (IItemHandlerModifiable) player.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP);
    IItemHandler invWrapper = new CombinedInvWrapper(this.itemInventory, playerInv);

    NonNullList<ItemStack> template = this.getRecipeItems(invId);
    InventoryUtils.clearInventoryToMatchTemplate(invCrafting, invWrapper, template);

    return InventoryUtils.restockInventoryBasedOnTemplate(invCrafting, invWrapper, template, 1, true, useOreDict);
}
 
Example #29
Source File: CoverRoboticArm.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected int doTransferExact(IItemHandler itemHandler, IItemHandler myItemHandler, int maxTransferAmount) {
    Map<ItemStackKey, TypeItemInfo> sourceItemAmount = doCountSourceInventoryItemsByType(itemHandler, myItemHandler);
    Iterator<ItemStackKey> iterator = sourceItemAmount.keySet().iterator();
    while (iterator.hasNext()) {
        ItemStackKey key = iterator.next();
        TypeItemInfo sourceInfo = sourceItemAmount.get(key);
        int itemAmount = sourceInfo.totalCount;
        Set<ItemStackKey> matchedItems = Collections.singleton(key);
        int itemToMoveAmount = itemFilterContainer.getSlotTransferLimit(sourceInfo.filterSlot, matchedItems);
        if (itemAmount >= itemToMoveAmount) {
            sourceInfo.totalCount = itemToMoveAmount;
        } else {
            iterator.remove();
        }
    }

    int itemsTransferred = 0;
    int maxTotalTransferAmount = maxTransferAmount + itemsTransferBuffered;
    boolean notEnoughTransferRate = false;
    for (TypeItemInfo itemInfo : sourceItemAmount.values()) {
        if(maxTotalTransferAmount >= itemInfo.totalCount) {
            boolean result = doTransferItemsExact(itemHandler, myItemHandler, itemInfo);
            itemsTransferred += result ? itemInfo.totalCount : 0;
            maxTotalTransferAmount -= result ? itemInfo.totalCount : 0;
        } else {
            notEnoughTransferRate = true;
        }
    }
    //if we didn't transfer anything because of too small transfer rate, buffer it
    if (itemsTransferred == 0 && notEnoughTransferRate) {
        itemsTransferBuffered += maxTransferAmount;
    } else {
        //otherwise, if transfer succeed, empty transfer buffer value
        itemsTransferBuffered = 0;
    }
    return Math.min(itemsTransferred, maxTransferAmount);
}
 
Example #30
Source File: InventoryUtils.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param inv
 * @return true if all the slots in the inventory are empty
 */
public static boolean isInventoryEmpty(IItemHandler inv)
{
    final int invSize = inv.getSlots();

    for (int slot = 0; slot < invSize; slot++)
    {
        if (inv.getStackInSlot(slot).isEmpty() == false)
        {
            return false;
        }
    }

    return true;
}