Example usage for net.minecraftforge.items IItemHandler insertItem

List of usage examples for net.minecraftforge.items IItemHandler insertItem

Introduction

In this page you can find the example usage for net.minecraftforge.items IItemHandler insertItem.

Prototype

@Nonnull
ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate);

Source Link

Document

Inserts an ItemStack into the given slot and return the remainder.

Usage

From source file:com.buuz135.industrial.proxy.block.BlockLabel.java

License:Open Source License

@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn,
        EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
    TileEntity entity = worldIn.getTileEntity(pos.offset(state.getValue(FACING)));
    TileEntity self = worldIn.getTileEntity(pos);
    if (!worldIn.isRemote && self instanceof TileEntityLabel && entity instanceof IHasDisplayStack
            && !((IHasDisplayStack) entity).getItemStack()
                    .hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) {
        if (playerIn.isSneaking()) {
            playerIn.playSound(SoundEvents.BLOCK_LEVER_CLICK, 1, 1);
            if (((TileEntityLabel) self).getFormatType() == TileEntityLabel.FormatType.STACKS)
                ((TileEntityLabel) self).setFormatType(TileEntityLabel.FormatType.MILL);
            else//from  w  w w.  ja  v  a 2s .  c om
                ((TileEntityLabel) self).setFormatType(TileEntityLabel.FormatType.STACKS);
        } else if (entity instanceof BlackHoleUnitTile
                && entity.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.NORTH)) {
            ItemStack stack = playerIn.getHeldItem(hand);
            if (!stack.isEmpty() && ((BlackHoleUnitTile) entity).canInsertItem(stack)) {
                playerIn.setHeldItem(hand,
                        entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.NORTH)
                                .insertItem(0, stack, false));
            } else if (System.currentTimeMillis() - INTERACTION_LOGGER.getOrDefault(playerIn.getUniqueID(),
                    System.currentTimeMillis()) < 300) {
                IItemHandler handler = entity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                        EnumFacing.NORTH);
                for (ItemStack itemStack : playerIn.inventory.mainInventory) {
                    if (!itemStack.isEmpty() && handler.insertItem(0, itemStack, true).isEmpty()) {
                        handler.insertItem(0, itemStack.copy(), false);
                        itemStack.setCount(0);
                    }
                }
            }
            INTERACTION_LOGGER.put(playerIn.getUniqueID(), System.currentTimeMillis());
        }
    }
    return true;
}

From source file:com.buuz135.industrial.proxy.block.upgrade.ConveyorDroppingUpgrade.java

License:Open Source License

@Override
public void handleEntity(Entity entity) {
    super.handleEntity(entity);
    if (entity instanceof EntityPlayer)
        return;/*from   w  w w . j  a  v  a2s  .  c o  m*/
    if (whitelist != filter.matches(entity))
        return;
    if (entity instanceof EntityItem) {
        TileEntity tile = getWorld().getTileEntity(getPos().offset(EnumFacing.DOWN));
        if (tile != null && tile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, EnumFacing.UP)) {
            IItemHandler handler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                    EnumFacing.UP);
            if (getBoundingBox().aabb().offset(getPos()).grow(0.01).intersects(entity.getEntityBoundingBox())) {
                ItemStack stack = ((EntityItem) entity).getItem();
                for (int i = 0; i < handler.getSlots(); i++) {
                    stack = handler.insertItem(i, stack, false);
                    if (stack.isEmpty()) {
                        entity.setDead();
                        break;
                    } else {
                        ((EntityItem) entity).setItem(stack);
                    }
                }
            }
        }
    }
    if (entity.isDead)
        return;
    double entityHeight = entity.getEntityBoundingBox().maxY - entity.getEntityBoundingBox().minY;
    BlockPos pos = this.getPos().down((int) Math.ceil(entityHeight));
    boolean space = true;
    for (int y = pos.getY(); y < this.getPos().getY(); ++y) {
        if (!this.getWorld().isAirBlock(new BlockPos(pos.getX(), y, pos.getZ()))) {
            space = false;
            break;
        }
    }
    if (space) {
        entity.motionX = 0;
        entity.motionY = 0;
        entity.motionZ = 0;
        entity.setPosition(pos.getX() + 0.5, pos.getY() - 0.1, pos.getZ() + 0.5);
        entity.onGround = false;
    }
}

From source file:com.buuz135.industrial.proxy.block.upgrade.ConveyorInsertionUpgrade.java

License:Open Source License

@Override
public void handleEntity(Entity entity) {
    if (getWorld().isRemote)
        return;/*w w w  .jav  a  2s . c o  m*/
    if (entity instanceof EntityItem) {
        IItemHandler handler = getHandlerCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
        if (handler != null && getWorkingBox().aabb().offset(getPos()).grow(0.01)
                .intersects(entity.getEntityBoundingBox())) {
            if (whitelist != filter.matches((EntityItem) entity))
                return;
            ItemStack stack = ((EntityItem) entity).getItem();
            for (int i = 0; i < handler.getSlots(); i++) {
                stack = handler.insertItem(i, stack, false);
                if (stack.isEmpty()) {
                    entity.setDead();
                    break;
                } else {
                    ((EntityItem) entity).setItem(stack);
                }
            }
        }
    }
}

From source file:com.buuz135.industrial.tile.misc.ItemSplitterTile.java

License:Open Source License

@Override
protected void innerUpdate() {
    if (this.world.isRemote)
        return;//w  w w  .  ja v  a2s  . co m
    if (++tick <= 4)
        return;
    for (EnumFacing facing : this.getSideConfig().getSidesForColor(EnumDyeColor.ORANGE)) {
        BlockPos side = this.pos.offset(facing);
        if (this.world.getTileEntity(side) != null && this.world.getTileEntity(side)
                .hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing.getOpposite())) {
            TileEntity tileEntity = this.world.getTileEntity(side);
            IItemHandler handler = tileEntity.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                    facing.getOpposite());
            for (int i = 0; i < handler.getSlots(); ++i) {
                if (!handler.getStackInSlot(i).isEmpty() && (handler.getStackInSlot(i).getCount() >= size
                        || handler.getStackInSlot(i).getCount() >= handler.getStackInSlot(i).getMaxStackSize()))
                    continue;
                ItemStack handlerStack = handler.getStackInSlot(i);
                ItemStack posible = ItemStack.EMPTY;
                boolean hasWorked = false;
                for (int x = 0; x < input.getSlots(); ++x) {
                    if (!input.getStackInSlot(x).isEmpty()
                            && (handlerStack.isEmpty() || input.getStackInSlot(x).isItemEqual(handlerStack))) {
                        posible = input.getStackInSlot(x);
                        if (!posible.isEmpty()) {
                            ItemStack def = posible.copy();
                            def.setCount(1);
                            def = handler.insertItem(i, def, false);
                            if (def.isEmpty())
                                posible.shrink(1);
                            else
                                continue;
                            hasWorked = true;
                            break;
                        }
                    }
                }
                if (hasWorked)
                    break;
            }
        }
    }
    tick = 0;
}

From source file:com.lothrazar.cyclicmagic.util.UtilItemStack.java

License:Open Source License

public static ItemStack tryDepositToHandler(World world, BlockPos posSide, EnumFacing sideOpp,
        ItemStack stackToExport) {/*w w  w. j  a  va  2 s.c  o m*/
    TileEntity tileTarget = world.getTileEntity(posSide);
    if (tileTarget == null
            || tileTarget.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, sideOpp) == false) {
        return stackToExport;
    }
    try {
        IItemHandler itemHandlerDeposit = tileTarget
                .getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, sideOpp);
        for (int i = 0; i < itemHandlerDeposit.getSlots(); i++) {
            //in theory this should never be null, but ive seen external mods have that happen
            //or other weird things hence the try catch 
            //https://github.com/Lothrazar/Cyclic/issues/1021
            ItemStack leftBehindAfterInsert = itemHandlerDeposit.insertItem(i, stackToExport, false);
            if (leftBehindAfterInsert == null) {
                continue;//i seen it
            }
            //so toExport is 60. leftbehind is 50, this means 10 were deposited. success
            if (leftBehindAfterInsert.getCount() < stackToExport.getCount()) {
                return leftBehindAfterInsert.copy();
            }
        }
    } catch (Exception e) {
        ModCyclic.logger.error("Error inserting item into capability handler ", e);
    }
    return stackToExport;
}

From source file:com.teambr.bookshelf.util.InventoryUtils.java

License:Creative Commons License

/**
 * Used to move items from one inventory to another. You can wrap it if you have to
 *     but since you'll be calling from us, there shouldn't be an issue
 *
 * @param source The source inventory, can be IInventory, ISideInventory, or preferably IItemHandler
 * @param fromSlot The from slot, -1 for any
 * @param target The target inventory, can be IInventory, ISideInventory, or preferably IItemHandler
 * @param intoSlot The slot to move into the target, -1 for any
 * @param maxAmount The max amount to move/extract
 * @param dir The direction moving into, so the face of the fromInventory
 * @param doMove True to actually do the move, false to simulate
 * @return True if something was moved//www .  ja va2  s . c  o m
 */
public static boolean moveItemInto(Object source, int fromSlot, Object target, int intoSlot, int maxAmount,
        EnumFacing dir, boolean doMove, boolean checkSidedSource, boolean checkSidedTarget) {
    // Null Checks
    if (source == null || target == null)
        return false;

    // Object to hold source
    IItemHandler fromInventory;

    // If source is not an item handler, attempt to cast
    if (!(source instanceof IItemHandler)) {
        if (source instanceof IInventory) {
            if (!(source instanceof ISidedInventory))
                fromInventory = new InvWrapper((IInventory) source); // Wrap vanilla inventory
            else
                fromInventory = new SidedInvWrapper((ISidedInventory) source, dir.getOpposite()); // Wrap sided
        } else
            return false; // Not valid
    } else {
        // Cast item handlers
        fromInventory = (IItemHandler) source;
    }

    // If required, check for sidedness on tiles
    if (checkSidedSource) {
        if (source instanceof TileEntity) {
            TileEntity tile = (TileEntity) source;
            if (tile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, dir))
                fromInventory = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, dir);
            else
                return false; // Source does not want to expose access
        }
    }

    IItemHandler targetInventory;

    // If sink is not an item handler, attempt to cast
    if (!(target instanceof IItemHandler)) {
        if (target instanceof IInventory) {
            if (!(target instanceof ISidedInventory))
                targetInventory = new InvWrapper((IInventory) target); // Wrap vanilla inventory
            else
                targetInventory = new SidedInvWrapper((ISidedInventory) target, dir); // Wrap sided
        } else
            return false; // Not valid
    } else {
        // Cast item handlers
        targetInventory = (IItemHandler) target;
    }

    // If required, check for sidedness on tiles
    if (checkSidedTarget) {
        if (target instanceof TileEntity) {
            TileEntity tile = (TileEntity) target;
            if (tile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, dir.getOpposite()))
                targetInventory = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                        dir.getOpposite());
            else
                return false; // Target does not want to expose access
        }
    }

    // Load slots
    List<Integer> fromSlots = new ArrayList<>();
    List<Integer> toSlots = new ArrayList<>();

    // Add From Slots
    if (fromSlot != -1)
        fromSlots.add(fromSlot);
    else
        for (int x = 0; x < fromInventory.getSlots(); x++)
            fromSlots.add(x);

    // Add to slots
    if (intoSlot != -1)
        toSlots.add(intoSlot);
    else
        for (int x = 0; x < targetInventory.getSlots(); x++)
            toSlots.add(x);

    // Do actual movement
    for (Integer fromSlot1 : fromSlots) { // Cycle fromInventory
        if (fromInventory.getStackInSlot(fromSlot1) != null) { // If we have something
            ItemStack fromStack = fromInventory.extractItem(fromSlot1, maxAmount, true); // Simulate to get stack
            if (!fromStack.isEmpty()) { // Make sure we got something
                for (Integer toSlot : toSlots) { // Cycle to inventory
                    int slotID = toSlot; // Grab slot
                    ItemStack movedStack = targetInventory.insertItem(slotID, fromStack.copy(), !doMove); // Try insert
                    if (!ItemStack.areItemStacksEqual(fromStack, movedStack)) { // If a change was made to the stack
                        fromInventory.extractItem(fromSlot1,
                                (!movedStack.isEmpty()) ? fromStack.getCount() - movedStack.getCount()
                                        : maxAmount,
                                !doMove); // Extract from original
                        return true; // Exit
                    }
                }
            }
        }
    }
    return false; // Failed to move something
}

From source file:de.ellpeck.actuallyadditions.mod.items.ItemBag.java

@Override
public EnumActionResult onItemUse(EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand,
        EnumFacing facing, float hitX, float hitY, float hitZ) {
    ItemStack stack = playerIn.getHeldItem(hand);
    if (!this.isVoid) {
        TileEntity tile = worldIn.getTileEntity(pos);
        if (tile != null && tile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing)) {
            if (!worldIn.isRemote) {
                IItemHandler handler = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                        facing);//from   w  w  w.j  av  a 2  s.com
                if (handler != null) {
                    boolean changed = false;

                    ItemStackHandlerCustom inv = new ItemStackHandlerCustom(
                            ContainerBag.getSlotAmount(this.isVoid));
                    ItemDrill.loadSlotsFromNBT(inv, stack);

                    for (int j = 4; j < inv.getSlots(); j++) {
                        ItemStack invStack = inv.getStackInSlot(j);
                        if (StackUtil.isValid(invStack)) {
                            for (int i = 0; i < handler.getSlots(); i++) {
                                ItemStack remain = handler.insertItem(i, invStack, false);
                                if (!ItemStack.areItemStacksEqual(remain, invStack)) {
                                    inv.setStackInSlot(j, StackUtil.validateCopy(remain));
                                    changed = true;

                                    if (!StackUtil.isValid(remain)) {
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (changed) {
                        ItemDrill.writeSlotsToNBT(inv, stack);
                    }
                }
            }
            return EnumActionResult.SUCCESS;
        }
    }
    return EnumActionResult.PASS;
}

From source file:de.ellpeck.actuallyadditions.mod.tile.TileEntityDistributorItem.java

@Override
public void updateEntity() {
    super.updateEntity();

    if (!this.world.isRemote) {
        boolean shouldMarkDirty = false;

        IItemHandler handlerUp = this.handlersAround.get(EnumFacing.UP);
        if (handlerUp != null) {
            for (int i = 0; i < handlerUp.getSlots(); i++) {

                ItemStack pullable = handlerUp.extractItem(i, 1, true);
                if (StackUtil.isValid(pullable) && (!StackUtil.isValid(this.slots.getStackInSlot(0))
                        || ItemUtil.canBeStacked(this.slots.getStackInSlot(0), pullable))) {
                    ItemStack pulled = handlerUp.extractItem(i, 1, false);
                    if (StackUtil.isValid(pulled)) {
                        if (!StackUtil.isValid(this.slots.getStackInSlot(0))) {
                            this.slots.setStackInSlot(0, pulled.copy());
                        } else {
                            this.slots.setStackInSlot(0, StackUtil.addStackSize(this.slots.getStackInSlot(0),
                                    StackUtil.getStackSize(pulled)));
                        }/*from w ww.ja v a  2s .  c o m*/
                        shouldMarkDirty = true;
                    }
                }

                if (StackUtil.isValid(this.slots.getStackInSlot(0))
                        && StackUtil.getStackSize(this.slots.getStackInSlot(0)) >= this.slots.getStackInSlot(0)
                                .getMaxStackSize()) {
                    break;
                }
            }
        }

        if (!this.handlersAround.isEmpty()
                && (!this.handlersAround.containsKey(EnumFacing.UP) || this.handlersAround.size() >= 2)
                && StackUtil.isValid(this.slots.getStackInSlot(0))) {
            EnumFacing[] allFacings = EnumFacing.values();
            do {
                this.putSide++;

                if (this.putSide >= 6) {
                    this.putSide = 0;
                }
            } while (allFacings[this.putSide] == EnumFacing.UP
                    || !this.handlersAround.containsKey(allFacings[this.putSide]));

            EnumFacing putFacing = allFacings[this.putSide];
            IItemHandler handler = this.handlersAround.get(putFacing);
            if (handler != null) {
                int aroundAmount = this.handlersAround.containsKey(EnumFacing.UP)
                        ? this.handlersAround.size() - 1
                        : this.handlersAround.size();
                int amount = StackUtil.getStackSize(this.slots.getStackInSlot(0)) / aroundAmount;
                if (amount <= 0) {
                    amount = StackUtil.getStackSize(this.slots.getStackInSlot(0));
                }

                if (amount > 0) {
                    ItemStack toInsert = this.slots.getStackInSlot(0).copy();
                    toInsert = StackUtil.setStackSize(toInsert, amount);

                    for (int i = 0; i < handler.getSlots(); i++) {
                        ItemStack notInserted = handler.insertItem(i, toInsert.copy(), false);
                        if (!StackUtil.isValid(notInserted)) {
                            this.slots.setStackInSlot(0,
                                    StackUtil.addStackSize(this.slots.getStackInSlot(0), -amount));

                            shouldMarkDirty = true;
                            break;
                        } else if (StackUtil.getStackSize(notInserted) != StackUtil
                                .getStackSize(this.slots.getStackInSlot(0))) {
                            this.slots.setStackInSlot(0, StackUtil.addStackSize(this.slots.getStackInSlot(0),
                                    -StackUtil.getStackSize(notInserted)));
                            toInsert = notInserted;

                            shouldMarkDirty = true;
                        }
                    }

                    if (!StackUtil.isValid(this.slots.getStackInSlot(0))) {
                        this.slots.setStackInSlot(0, StackUtil.getNull());
                        shouldMarkDirty = true;
                    }
                }
            }
        }

        if (shouldMarkDirty) {
            this.markDirty();
        }
    }
}

From source file:de.ellpeck.actuallyadditions.mod.tile.TileEntityFishingNet.java

private ItemStack storeInContainer(ItemStack stack) {
    for (EnumFacing side : EnumFacing.values()) {
        TileEntity tile = this.tilesAround[side.ordinal()];
        if (tile != null) {
            if (tile.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side.getOpposite())) {
                IItemHandler cap = tile.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                        side.getOpposite());
                if (cap != null) {
                    for (int i = 0; i < cap.getSlots(); i++) {
                        stack = cap.insertItem(i, stack, false);

                        if (!StackUtil.isValid(stack)) {
                            return StackUtil.getNull();
                        }/* w w  w.  ja  v  a  2s  .com*/
                    }
                }
            }
        }
    }
    return stack;
}

From source file:de.ellpeck.actuallyadditions.mod.tile.TileEntityItemViewerHopping.java

@Override
public void updateEntity() {
    super.updateEntity();

    if (!this.world.isRemote && this.world.getTotalWorldTime() % 10 == 0) {
        if (this.handlerToPullFrom != null) {
            WorldUtil.doItemInteraction(this.handlerToPullFrom, this.itemHandler, 4);
        } else {/*from   w w w. j av a2 s.  c o  m*/
            if (this.world.getTotalWorldTime() % 20 == 0) {
                List<EntityItem> items = this.world.getEntitiesWithinAABB(EntityItem.class,
                        new AxisAlignedBB(this.pos.getX(), this.pos.getY() + 0.5, this.pos.getZ(),
                                this.pos.getX() + 1, this.pos.getY() + 2, this.pos.getZ() + 1));
                if (items != null && !items.isEmpty()) {
                    for (EntityItem item : items) {
                        if (item != null && !item.isDead) {
                            if (ActuallyAdditions.commonCapsLoaded) {
                                Object slotless = this.itemHandler.getSlotlessHandler();
                                if (slotless instanceof ISlotlessItemHandler) {
                                    ItemStack left = ((ISlotlessItemHandler) slotless)
                                            .insertItem(item.getItem(), false);
                                    item.setItem(left);

                                    if (!StackUtil.isValid(left)) {
                                        item.setDead();
                                        continue;
                                    }
                                }
                            }

                            IItemHandler handler = this.itemHandler.getNormalHandler();
                            if (handler != null) {
                                for (int i = 0; i < handler.getSlots(); i++) {
                                    ItemStack left = handler.insertItem(i, item.getItem(), false);
                                    item.setItem(left);

                                    if (!StackUtil.isValid(left)) {
                                        item.setDead();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (this.handlerToPushTo != null) {
            WorldUtil.doItemInteraction(this.itemHandler, this.handlerToPushTo, 4);
        }
    }
}