Example usage for net.minecraftforge.items IItemHandler extractItem

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

Introduction

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

Prototype

@Nonnull
ItemStack extractItem(int slot, int amount, boolean simulate);

Source Link

Document

Extracts an ItemStack from the given slot.

Usage

From source file:blusunrize.immersiveengineering.common.blocks.metal.conveyors.ConveyorExtract.java

@Override
public void onUpdate(TileEntity tile, EnumFacing facing) {
    if (!tile.getWorld().isRemote) {
        if (this.transferCooldown > 0) {
            this.transferCooldown--;
        }/*from  ww  w.  java  2  s .  c o m*/
        if (!isPowered(tile) && this.transferCooldown <= 0) {
            World world = tile.getWorld();
            BlockPos neighbour = tile.getPos().offset(this.extractDirection);
            if (!world.isAirBlock(neighbour)) {
                TileEntity neighbourTile = world.getTileEntity(neighbour);
                if (neighbourTile != null && neighbourTile.hasCapability(
                        CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, this.extractDirection.getOpposite())) {
                    IItemHandler itemHandler = neighbourTile.getCapability(
                            CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, this.extractDirection.getOpposite());
                    for (int i = 0; i < itemHandler.getSlots(); i++) {
                        ItemStack extractItem = itemHandler.extractItem(i, 1, true);
                        if (!extractItem.isEmpty()) {
                            extractItem = itemHandler.extractItem(i, 1, false);
                            EntityItem entity = new EntityItem(world, tile.getPos().getX() + .5,
                                    tile.getPos().getY() + .1875, tile.getPos().getZ() + .5, extractItem);
                            entity.motionX = 0;
                            entity.motionY = 0;
                            entity.motionZ = 0;
                            world.spawnEntity(entity);
                            this.onItemDeployed(tile, entity, facing);
                            this.transferCooldown = this.transferTickrate;
                            return;
                        }
                    }
                }
            }
        }
    }
}

From source file:blusunrize.immersiveengineering.common.blocks.wooden.TileEntitySorter.java

public ItemStack pullItem(EnumFacing outputSide, int amount, boolean simulate) {
    if (!world.isRemote && canRoute()) {
        boolean first = startRouting();
        for (EnumFacing side : EnumFacing.values())
            if (side != outputSide) {
                TileEntity neighbourTile = world.getTileEntity(getPos().offset(side));
                if (neighbourTile != null && neighbourTile
                        .hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side.getOpposite())) {
                    Predicate<ItemStack> concatFilter = null;
                    IItemHandler itemHandler = neighbourTile
                            .getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side.getOpposite());
                    for (int i = 0; i < itemHandler.getSlots(); i++) {
                        ItemStack extractItem = itemHandler.extractItem(i, amount, true);
                        if (!extractItem.isEmpty()) {
                            if (concatFilter == null)//Init the filter here, to save on resources
                                concatFilter = this.concatFilters(outputSide, side);
                            if (concatFilter.test(extractItem)) {
                                if (first)
                                    routed = null;
                                if (!simulate)
                                    itemHandler.extractItem(i, amount, false);
                                return extractItem;
                            }/*  w  ww.ja  v  a  2 s .c  o  m*/
                        }
                    }
                }
            }
        if (first)
            routed = null;
    }
    return ItemStack.EMPTY;
}

From source file:com.buuz135.industrial.item.addon.movility.ItemStackTransferAddon.java

License:Open Source License

@Override
public boolean actionTransfer(World world, BlockPos pos, EnumFacing facing, int transferAmount) {
    TileEntity tileEntityOrigin = world.getTileEntity(pos);
    TileEntity tileEntityDestination = world.getTileEntity(pos.offset(facing));
    if (tileEntityOrigin != null && tileEntityDestination != null
            && tileEntityOrigin.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, facing)
            && tileEntityDestination.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                    facing.getOpposite())) {
        IItemHandler itemHandlerOrigin = getCapabilityOriginByMode(tileEntityOrigin, tileEntityDestination,
                facing);/*from   w  ww  .ja  v a 2s .  com*/
        IItemHandler itemHandlerDestination = getCapabilityDestinationByMode(tileEntityOrigin,
                tileEntityDestination, facing);
        for (int i = 0; i < itemHandlerOrigin.getSlots(); ++i) {
            ItemStack input = itemHandlerOrigin.extractItem(i, transferAmount, true);
            if (!input.isEmpty()) {
                ItemStack result = ItemHandlerHelper.insertItem(itemHandlerDestination, input, true);
                int amountInserted = input.getCount() - result.getCount();
                if (amountInserted > 0) {
                    result = ItemHandlerHelper.insertItem(itemHandlerDestination,
                            itemHandlerOrigin.extractItem(i, amountInserted, false), false);
                    if (!result.isEmpty())
                        ItemHandlerHelper.insertItem(itemHandlerOrigin, result, false);
                    return true;
                }
            }
        }
    }
    return false;
}

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

License:Open Source License

@Override
public void update() {
    if (getWorld().isRemote)
        return;//from  w  w w  .j  a v  a 2  s  .  c o m
    items.removeIf(entityItem -> entityItem.getItem().isEmpty() || entityItem.isDead);
    if (items.size() >= 20)
        return;
    if (getWorld().getTotalWorldTime() % (fast ? 10 : 20) == 0) {
        IItemHandler itemHandler = getHandlerCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY);
        if (itemHandler != null) {
            for (int i = 0; i < itemHandler.getSlots(); i++) {
                ItemStack stack = itemHandler.extractItem(i, 4, true);
                if (stack.isEmpty() || whitelist != filter.matches(stack))
                    continue;
                EntityItem item = new EntityItem(getWorld(), getPos().getX() + 0.5, getPos().getY() + 0.5,
                        getPos().getZ() + 0.5);
                item.motionX = 0;
                item.motionY = 0;
                item.motionZ = 0;
                item.setPickupDelay(40);
                item.setItem(itemHandler.extractItem(i, 4, false));
                if (getWorld().spawnEntity(item)) {
                    items.add(item);
                }
                break;
            }
        }
    }
    if (getContainer() instanceof TileEntityConveyor) {
        IFluidTank tank = ((TileEntityConveyor) getContainer()).getTank();
        IFluidHandler fluidHandler = getHandlerCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY);
        if (fluidHandler != null && fluidHandler.drain(250, false) != null
                && ((FluidTank) tank).canFillFluidType(fluidHandler.drain(250, false))
                && whitelist == filter.matches(fluidHandler.drain(250, false))) {
            FluidStack drain = fluidHandler.drain(tank.fill(fluidHandler.drain(250, false), true), true);
            if (drain != null && drain.amount > 0)
                getContainer().requestFluidSync();
        }
    }
}

From source file:com.elytradev.thermionics.api.impl.RotaryGridRecipe.java

License:Open Source License

@Override
public ItemStack performCraft(IItemHandler inv) {

    for (int i = 0; i < 9; i++) {
        if (ingredients[i] != null) {
            if (ingredients[i] instanceof ItemStack) {
                inv.extractItem(i, ((ItemStack) ingredients[i]).getCount(), false);
            } else {
                inv.extractItem(i, 1, false);
            }/*from  w  ww .j  a v a2s  .  co m*/
        }
    }

    return result.copy();
}

From source file:com.elytradev.thermionics.data.MashTunRecipe.java

License:Open Source License

/** Applies the recipe to the storage provided, determining whether or not the output should be produced. Optionally
 * consumes the items.//from w  w w  .j  ava 2 s  .  co m
 */
public boolean apply(FluidTank tank, IItemHandler inventory, boolean consume) {
    if (consume && !apply(tank, inventory, false))
        return false; //Always dry-run before destructive ops
    if (tank.getFluid() == null)
        return false;
    //Next line shouldn't happen but it pays to plan for the impossible
    if (tank.getFluid().getFluid() != FluidRegistry.WATER)
        return false;
    if (tank.getFluidAmount() < water)
        return false;

    FluidStack fluidExtracted = tank.drainInternal(water, consume);
    if (fluidExtracted.amount < water)
        return false;

    int remaining = count;
    for (int i = 0; i < inventory.getSlots(); i++) {
        ItemStack stack = inventory.getStackInSlot(i);
        if (stack.isEmpty())
            continue;
        if (item.apply(stack)) {
            ItemStack extracted = inventory.extractItem(i, remaining, !consume);
            if (extracted.isEmpty())
                continue;
            remaining -= extracted.getCount();
        }
    }
    return remaining <= 0;
}

From source file:com.lothrazar.cyclicmagic.block.cablepump.item.TileEntityItemPump.java

License:Open Source License

public void tryImport() {
    if (this.getStackInSlot(SLOT_TRANSFER).isEmpty() == false) {
        return;//im full leave me alone
    }//ww w  .  j  a v a 2 s.  com
    EnumFacing importFromSide = this.getCurrentFacing();
    BlockPos posTarget = pos.offset(importFromSide);
    TileEntity tileTarget = world.getTileEntity(posTarget);
    if (tileTarget == null) {
        return;
    }
    ItemStack itemTarget;
    if (tileTarget.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, importFromSide.getOpposite())) {
        IItemHandler itemHandlerFrom = tileTarget.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                importFromSide.getOpposite());
        for (int i = 0; i < itemHandlerFrom.getSlots(); i++) {
            itemTarget = itemHandlerFrom.getStackInSlot(i);
            if (itemTarget.isEmpty()) {
                continue;
            }
            //check against whitelist/blacklist system
            if (this.isStackInvalid(itemTarget)) {
                //          ModCyclic.logger.log("not valid " + itemTarget.getDisplayName());
                continue;
            }
            //passed filter check, so do the transaction
            ItemStack pulled = itemHandlerFrom.extractItem(i, this.speed, false);
            if (pulled != null && pulled.isEmpty() == false) {
                this.setInventorySlotContents(SLOT_TRANSFER, pulled.copy());
                return;
            }
        }
    }
}

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/* ww  w  .jav  a 2  s  .c  om*/
 */
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.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)));
                        }//w w  w  .  j a v  a2  s .co  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.util.WorldUtil.java

public static boolean doItemInteraction(int slotExtract, int slotInsert, TileEntity extract, TileEntity insert,
        EnumFacing extractSide, EnumFacing insertSide) {
    if (extract.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, extractSide)
            && insert.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, insertSide)) {
        IItemHandler extractCap = extract.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                extractSide);//from w w  w  .j ava2s .  c om
        IItemHandler insertCap = insert.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY,
                insertSide);

        ItemStack theoreticalExtract = extractCap.extractItem(slotExtract, Integer.MAX_VALUE, true);
        if (StackUtil.isValid(theoreticalExtract)) {
            ItemStack remaining = insertCap.insertItem(slotInsert, theoreticalExtract, false);
            if (!ItemStack.areItemStacksEqual(remaining, theoreticalExtract)) {
                int toExtract = !StackUtil.isValid(remaining) ? StackUtil.getStackSize(theoreticalExtract)
                        : StackUtil.getStackSize(theoreticalExtract) - StackUtil.getStackSize(remaining);
                extractCap.extractItem(slotExtract, toExtract, false);
                return true;
            }
        }
    }
    return false;
}