Search in sources :

Example 11 with TileEntityMekanism

use of mekanism.common.tile.base.TileEntityMekanism in project Mekanism by mekanism.

the class ItemRecipeData method applyToStack.

@Override
public boolean applyToStack(ItemStack stack) {
    if (slots.isEmpty()) {
        return true;
    }
    Item item = stack.getItem();
    boolean isBin = item instanceof ItemBlockBin;
    Optional<IItemHandler> capability = stack.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).resolve();
    List<IInventorySlot> slots = new ArrayList<>();
    if (capability.isPresent()) {
        IItemHandler itemHandler = capability.get();
        for (int i = 0; i < itemHandler.getSlots(); i++) {
            int slot = i;
            slots.add(new DummyInventorySlot(itemHandler.getSlotLimit(slot), itemStack -> itemHandler.isItemValid(slot, itemStack), isBin));
        }
    } else if (item instanceof BlockItem) {
        TileEntityMekanism tile = getTileFromBlock(((BlockItem) item).getBlock());
        if (tile == null || !tile.persistInventory()) {
            // Something went wrong
            return false;
        }
        for (int i = 0; i < tile.getSlots(); i++) {
            int slot = i;
            slots.add(new DummyInventorySlot(tile.getSlotLimit(slot), itemStack -> tile.isItemValid(slot, itemStack), isBin));
        }
    } else if (item instanceof ItemRobit) {
        // Inventory slots
        for (int slotY = 0; slotY < 3; slotY++) {
            for (int slotX = 0; slotX < 9; slotX++) {
                slots.add(new DummyInventorySlot(BasicInventorySlot.DEFAULT_LIMIT, BasicInventorySlot.alwaysTrue, false));
            }
        }
        // Energy slot
        slots.add(new DummyInventorySlot(BasicInventorySlot.DEFAULT_LIMIT, itemStack -> {
            if (EnergyCompatUtils.hasStrictEnergyHandler(itemStack)) {
                return true;
            }
            ItemStackToEnergyRecipe foundRecipe = MekanismRecipeType.ENERGY_CONVERSION.getInputCache().findTypeBasedRecipe(null, itemStack);
            return foundRecipe != null && !foundRecipe.getOutput(itemStack).isZero();
        }, false));
        // Smelting input slot
        slots.add(new DummyInventorySlot(BasicInventorySlot.DEFAULT_LIMIT, itemStack -> MekanismRecipeType.SMELTING.getInputCache().containsInput(null, itemStack), false));
        // Smelting output slot
        slots.add(new DummyInventorySlot(BasicInventorySlot.DEFAULT_LIMIT, BasicInventorySlot.alwaysTrue, false));
    } else if (item instanceof ISustainedInventory) {
        // Fallback just save it all
        for (IInventorySlot slot : this.slots) {
            if (!slot.isEmpty()) {
                // We have no information about what our item supports, but we have at least some stacks we want to transfer
                ((ISustainedInventory) stack.getItem()).setInventory(DataHandlerUtils.writeContainers(this.slots), stack);
                return true;
            }
        }
        return true;
    } else {
        return false;
    }
    if (slots.isEmpty()) {
        // We don't actually have any tanks in the output
        return true;
    }
    // TODO: Improve the logic so that it maybe tries multiple different slot combinations
    IMekanismInventory outputHandler = new IMekanismInventory() {

        @Nonnull
        @Override
        public List<IInventorySlot> getInventorySlots(@Nullable Direction side) {
            return slots;
        }

        @Override
        public void onContentsChanged() {
        }
    };
    boolean hasData = false;
    for (IInventorySlot slot : this.slots) {
        if (!slot.isEmpty()) {
            if (!ItemHandlerHelper.insertItemStacked(outputHandler, slot.getStack(), false).isEmpty()) {
                // If we have a remainder something failed so bail
                return false;
            }
            hasData = true;
        }
    }
    if (hasData) {
        // We managed to transfer it all into valid slots, so save it to the stack
        ((ISustainedInventory) stack.getItem()).setInventory(DataHandlerUtils.writeContainers(slots), stack);
    }
    return true;
}
Also used : IInventorySlot(mekanism.api.inventory.IInventorySlot) IItemHandler(net.minecraftforge.items.IItemHandler) EnergyCompatUtils(mekanism.common.integration.energy.EnergyCompatUtils) IMekanismInventory(mekanism.api.inventory.IMekanismInventory) Item(net.minecraft.item.Item) BasicInventorySlot(mekanism.common.inventory.slot.BasicInventorySlot) Direction(net.minecraft.util.Direction) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault) ArrayList(java.util.ArrayList) ItemStack(net.minecraft.item.ItemStack) ItemHandlerHelper(net.minecraftforge.items.ItemHandlerHelper) Nonnull(javax.annotation.Nonnull) NonNull(mekanism.api.annotations.NonNull) ItemBlockBin(mekanism.common.item.block.ItemBlockBin) Nullable(javax.annotation.Nullable) TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) ISustainedInventory(mekanism.common.tile.interfaces.ISustainedInventory) ListNBT(net.minecraft.nbt.ListNBT) MekanismRecipeType(mekanism.common.recipe.MekanismRecipeType) ItemRobit(mekanism.common.item.ItemRobit) Predicate(java.util.function.Predicate) DataHandlerUtils(mekanism.api.DataHandlerUtils) List(java.util.List) FieldsAreNonnullByDefault(mekanism.api.annotations.FieldsAreNonnullByDefault) IInventorySlot(mekanism.api.inventory.IInventorySlot) BlockItem(net.minecraft.item.BlockItem) NBTConstants(mekanism.api.NBTConstants) CapabilityItemHandler(net.minecraftforge.items.CapabilityItemHandler) ItemStackToEnergyRecipe(mekanism.api.recipes.ItemStackToEnergyRecipe) Optional(java.util.Optional) TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) ISustainedInventory(mekanism.common.tile.interfaces.ISustainedInventory) IItemHandler(net.minecraftforge.items.IItemHandler) ItemRobit(mekanism.common.item.ItemRobit) ArrayList(java.util.ArrayList) BlockItem(net.minecraft.item.BlockItem) Direction(net.minecraft.util.Direction) ItemBlockBin(mekanism.common.item.block.ItemBlockBin) Item(net.minecraft.item.Item) BlockItem(net.minecraft.item.BlockItem) ItemStackToEnergyRecipe(mekanism.api.recipes.ItemStackToEnergyRecipe) IMekanismInventory(mekanism.api.inventory.IMekanismInventory) Nullable(javax.annotation.Nullable)

Example 12 with TileEntityMekanism

use of mekanism.common.tile.base.TileEntityMekanism in project Mekanism by mekanism.

the class PacketDropperUse method handle.

@Override
public void handle(NetworkEvent.Context context) {
    PlayerEntity player = context.getSender();
    if (player == null || tankId < 0) {
        return;
    }
    ItemStack stack = player.inventory.getCarried();
    if (!stack.isEmpty() && stack.getItem() instanceof ItemGaugeDropper) {
        TileEntityMekanism tile = WorldUtils.getTileEntity(TileEntityMekanism.class, player.level, pos);
        if (tile != null) {
            if (tile instanceof TileEntityMultiblock) {
                MultiblockData structure = ((TileEntityMultiblock<?>) tile).getMultiblock();
                if (structure.isFormed()) {
                    handleTankType(structure, player, stack, new Coord4D(structure.getBounds().getCenter(), player.level));
                }
            } else {
                if (action == DropperAction.DUMP_TANK && !player.isCreative()) {
                    // If the dropper is being used to dump the tank and the player is not in creative
                    // check if the block the tank is in is a tiered block and if it is, and it is creative
                    // don't allow clearing the tank
                    Block block = tile.getBlockType();
                    if (Attribute.has(block, AttributeTier.class) && Attribute.get(block, AttributeTier.class).getTier().getBaseTier() == BaseTier.CREATIVE) {
                        return;
                    }
                }
                handleTankType(tile, player, stack, tile.getTileCoord());
            }
        }
    }
}
Also used : TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) AttributeTier(mekanism.common.block.attribute.AttributeTier) ItemGaugeDropper(mekanism.common.item.ItemGaugeDropper) TileEntityMultiblock(mekanism.common.tile.prefab.TileEntityMultiblock) Coord4D(mekanism.api.Coord4D) Block(net.minecraft.block.Block) ItemStack(net.minecraft.item.ItemStack) MultiblockData(mekanism.common.lib.multiblock.MultiblockData) PlayerEntity(net.minecraft.entity.player.PlayerEntity) ServerPlayerEntity(net.minecraft.entity.player.ServerPlayerEntity)

Example 13 with TileEntityMekanism

use of mekanism.common.tile.base.TileEntityMekanism in project Mekanism by mekanism.

the class ItemConfigurator method useOn.

@Nonnull
@Override
public ActionResultType useOn(ItemUseContext context) {
    PlayerEntity player = context.getPlayer();
    World world = context.getLevel();
    if (!world.isClientSide && player != null) {
        BlockPos pos = context.getClickedPos();
        Direction side = context.getClickedFace();
        ItemStack stack = context.getItemInHand();
        TileEntity tile = WorldUtils.getTileEntity(world, pos);
        ConfiguratorMode mode = getMode(stack);
        if (mode.isConfigurating()) {
            // Configurate
            TransmissionType transmissionType = Objects.requireNonNull(mode.getTransmission(), "Configurating state requires transmission type");
            if (tile instanceof ISideConfiguration && ((ISideConfiguration) tile).getConfig().supports(transmissionType)) {
                ISideConfiguration config = (ISideConfiguration) tile;
                ConfigInfo info = config.getConfig().getConfig(transmissionType);
                if (info != null) {
                    RelativeSide relativeSide = RelativeSide.fromDirections(config.getDirection(), side);
                    DataType dataType = info.getDataType(relativeSide);
                    if (!player.isShiftKeyDown()) {
                        player.sendMessage(MekanismUtils.logFormat(MekanismLang.CONFIGURATOR_VIEW_MODE.translate(transmissionType, dataType.getColor(), dataType, dataType.getColor().getColoredName())), Util.NIL_UUID);
                    } else if (SecurityUtils.canAccess(player, tile)) {
                        if (!player.isCreative()) {
                            IEnergyContainer energyContainer = StorageUtils.getEnergyContainer(stack, 0);
                            FloatingLong energyPerConfigure = MekanismConfig.gear.configuratorEnergyPerConfigure.get();
                            if (energyContainer == null || energyContainer.extract(energyPerConfigure, Action.SIMULATE, AutomationType.MANUAL).smallerThan(energyPerConfigure)) {
                                return ActionResultType.FAIL;
                            }
                            energyContainer.extract(energyPerConfigure, Action.EXECUTE, AutomationType.MANUAL);
                        }
                        DataType old = dataType;
                        dataType = info.incrementDataType(relativeSide);
                        if (dataType != old) {
                            player.sendMessage(MekanismUtils.logFormat(MekanismLang.CONFIGURATOR_TOGGLE_MODE.translate(transmissionType, dataType.getColor(), dataType, dataType.getColor().getColoredName())), Util.NIL_UUID);
                            config.getConfig().sideChanged(transmissionType, relativeSide);
                        }
                    } else {
                        SecurityUtils.displayNoAccess(player);
                    }
                }
                return ActionResultType.SUCCESS;
            }
            if (SecurityUtils.canAccess(player, tile)) {
                Optional<IConfigurable> capability = CapabilityUtils.getCapability(tile, Capabilities.CONFIGURABLE_CAPABILITY, side).resolve();
                if (capability.isPresent()) {
                    IConfigurable config = capability.get();
                    if (player.isShiftKeyDown()) {
                        return config.onSneakRightClick(player, side);
                    }
                    return config.onRightClick(player, side);
                }
            } else {
                SecurityUtils.displayNoAccess(player);
                return ActionResultType.SUCCESS;
            }
        } else if (mode == ConfiguratorMode.EMPTY) {
            // Empty
            if (tile instanceof IMekanismInventory) {
                IMekanismInventory inv = (IMekanismInventory) tile;
                if (inv.hasInventory()) {
                    if (SecurityUtils.canAccess(player, tile)) {
                        boolean creative = player.isCreative();
                        IEnergyContainer energyContainer = creative ? null : StorageUtils.getEnergyContainer(stack, 0);
                        if (!creative && energyContainer == null) {
                            return ActionResultType.FAIL;
                        }
                        // TODO: Switch this to items being handled by TileEntityMekanism, energy handled here (via lambdas?)
                        FloatingLong energyPerItemDump = MekanismConfig.gear.configuratorEnergyPerItem.get();
                        for (IInventorySlot inventorySlot : inv.getInventorySlots(null)) {
                            if (!inventorySlot.isEmpty()) {
                                if (!creative) {
                                    if (energyContainer.extract(energyPerItemDump, Action.SIMULATE, AutomationType.MANUAL).smallerThan(energyPerItemDump)) {
                                        break;
                                    }
                                    energyContainer.extract(energyPerItemDump, Action.EXECUTE, AutomationType.MANUAL);
                                }
                                Block.popResource(world, pos, inventorySlot.getStack().copy());
                                inventorySlot.setEmpty();
                            }
                        }
                        return ActionResultType.SUCCESS;
                    } else {
                        SecurityUtils.displayNoAccess(player);
                        return ActionResultType.FAIL;
                    }
                }
            }
        } else if (mode == ConfiguratorMode.ROTATE) {
            // Rotate
            if (tile instanceof TileEntityMekanism) {
                if (SecurityUtils.canAccess(player, tile)) {
                    TileEntityMekanism tileMekanism = (TileEntityMekanism) tile;
                    if (Attribute.get(tileMekanism.getBlockType(), AttributeStateFacing.class).canRotate()) {
                        if (!player.isShiftKeyDown()) {
                            tileMekanism.setFacing(side);
                        } else if (player.isShiftKeyDown()) {
                            tileMekanism.setFacing(side.getOpposite());
                        }
                    }
                } else {
                    SecurityUtils.displayNoAccess(player);
                }
            }
            return ActionResultType.SUCCESS;
        } else if (mode == ConfiguratorMode.WRENCH) {
            // Wrench
            return ActionResultType.PASS;
        }
    }
    return ActionResultType.PASS;
}
Also used : IInventorySlot(mekanism.api.inventory.IInventorySlot) TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) World(net.minecraft.world.World) ConfigInfo(mekanism.common.tile.component.config.ConfigInfo) Direction(net.minecraft.util.Direction) IConfigurable(mekanism.api.IConfigurable) ConfiguratorMode(mekanism.common.item.ItemConfigurator.ConfiguratorMode) AttributeStateFacing(mekanism.common.block.attribute.AttributeStateFacing) PlayerEntity(net.minecraft.entity.player.PlayerEntity) TileEntity(net.minecraft.tileentity.TileEntity) FloatingLong(mekanism.api.math.FloatingLong) IEnergyContainer(mekanism.api.energy.IEnergyContainer) TransmissionType(mekanism.common.lib.transmitter.TransmissionType) RelativeSide(mekanism.api.RelativeSide) DataType(mekanism.common.tile.component.config.DataType) IMekanismInventory(mekanism.api.inventory.IMekanismInventory) BlockPos(net.minecraft.util.math.BlockPos) ItemStack(net.minecraft.item.ItemStack) ISideConfiguration(mekanism.common.tile.interfaces.ISideConfiguration) Nonnull(javax.annotation.Nonnull)

Example 14 with TileEntityMekanism

use of mekanism.common.tile.base.TileEntityMekanism in project Mekanism by mekanism.

the class ItemRobit method useOn.

@Nonnull
@Override
public ActionResultType useOn(ItemUseContext context) {
    PlayerEntity player = context.getPlayer();
    if (player == null) {
        return ActionResultType.PASS;
    }
    World world = context.getLevel();
    BlockPos pos = context.getClickedPos();
    TileEntityMekanism chargepad = WorldUtils.getTileEntity(TileEntityChargepad.class, world, pos);
    if (chargepad != null) {
        if (!chargepad.getActive()) {
            if (!world.isClientSide) {
                ItemStack stack = context.getItemInHand();
                EntityRobit robit = EntityRobit.create(world, pos.getX() + 0.5, pos.getY() + 0.1, pos.getZ() + 0.5);
                if (robit == null) {
                    return ActionResultType.FAIL;
                }
                robit.setHome(chargepad.getTileCoord());
                IEnergyContainer energyContainer = StorageUtils.getEnergyContainer(stack, 0);
                if (energyContainer != null) {
                    robit.getEnergyContainer().setEnergy(energyContainer.getEnergy());
                }
                UUID ownerUUID = getOwnerUUID(stack);
                if (ownerUUID == null) {
                    robit.setOwnerUUID(player.getUUID());
                    // If the robit doesn't already have an owner, make sure we portray this
                    Mekanism.packetHandler.sendToAll(new PacketSecurityUpdate(player.getUUID(), null));
                } else {
                    robit.setOwnerUUID(ownerUUID);
                }
                robit.setInventory(getInventory(stack));
                robit.setCustomName(getRobitName(stack));
                robit.setSecurityMode(getSecurity(stack));
                robit.setSkin(getRobitSkin(stack), player);
                world.addFreshEntity(robit);
                stack.shrink(1);
            }
            return ActionResultType.SUCCESS;
        }
    }
    return ActionResultType.PASS;
}
Also used : TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) IEnergyContainer(mekanism.api.energy.IEnergyContainer) EntityRobit(mekanism.common.entity.EntityRobit) BlockPos(net.minecraft.util.math.BlockPos) World(net.minecraft.world.World) ItemStack(net.minecraft.item.ItemStack) UUID(java.util.UUID) PacketSecurityUpdate(mekanism.common.network.to_client.PacketSecurityUpdate) PlayerEntity(net.minecraft.entity.player.PlayerEntity) Nonnull(javax.annotation.Nonnull)

Example 15 with TileEntityMekanism

use of mekanism.common.tile.base.TileEntityMekanism in project Mekanism by mekanism.

the class ItemTierInstaller method useOn.

@Nonnull
@Override
public ActionResultType useOn(ItemUseContext context) {
    PlayerEntity player = context.getPlayer();
    World world = context.getLevel();
    if (world.isClientSide || player == null) {
        return ActionResultType.PASS;
    }
    BlockPos pos = context.getClickedPos();
    BlockState state = world.getBlockState(pos);
    Block block = state.getBlock();
    if (Attribute.has(block, AttributeUpgradeable.class)) {
        AttributeUpgradeable upgradeableBlock = Attribute.get(block, AttributeUpgradeable.class);
        BaseTier baseTier = Attribute.getBaseTier(block);
        if (baseTier == fromTier && baseTier != toTier) {
            BlockState upgradeState = upgradeableBlock.upgradeResult(state, toTier);
            if (state == upgradeState) {
                return ActionResultType.PASS;
            }
            TileEntity tile = WorldUtils.getTileEntity(world, pos);
            if (tile instanceof ITierUpgradable) {
                if (tile instanceof TileEntityMekanism && !((TileEntityMekanism) tile).playersUsing.isEmpty()) {
                    return ActionResultType.FAIL;
                }
                IUpgradeData upgradeData = ((ITierUpgradable) tile).getUpgradeData();
                if (upgradeData == null) {
                    if (((ITierUpgradable) tile).canBeUpgraded()) {
                        Mekanism.logger.warn("Got no upgrade data for block {} at position: {} in {} but it said it would be able to provide some.", block, pos, world);
                        return ActionResultType.FAIL;
                    }
                } else {
                    world.setBlockAndUpdate(pos, upgradeState);
                    // TODO: Make it so it doesn't have to be a TileEntityMekanism?
                    TileEntityMekanism upgradedTile = WorldUtils.getTileEntity(TileEntityMekanism.class, world, pos);
                    if (upgradedTile == null) {
                        Mekanism.logger.warn("Error upgrading block at position: {} in {}.", pos, world);
                        return ActionResultType.FAIL;
                    } else {
                        if (tile instanceof ITileDirectional && ((ITileDirectional) tile).isDirectional()) {
                            upgradedTile.setFacing(((ITileDirectional) tile).getDirection());
                        }
                        upgradedTile.parseUpgradeData(upgradeData);
                        upgradedTile.sendUpdatePacket();
                        upgradedTile.setChanged();
                        if (!player.isCreative()) {
                            context.getItemInHand().shrink(1);
                        }
                        return ActionResultType.SUCCESS;
                    }
                }
            }
        }
    }
    return ActionResultType.PASS;
}
Also used : TileEntity(net.minecraft.tileentity.TileEntity) TileEntityMekanism(mekanism.common.tile.base.TileEntityMekanism) ITileDirectional(mekanism.common.tile.interfaces.ITileDirectional) BlockState(net.minecraft.block.BlockState) ITierUpgradable(mekanism.common.tile.interfaces.ITierUpgradable) IUpgradeData(mekanism.common.upgrade.IUpgradeData) AttributeUpgradeable(mekanism.common.block.attribute.AttributeUpgradeable) Block(net.minecraft.block.Block) BlockPos(net.minecraft.util.math.BlockPos) World(net.minecraft.world.World) BaseTier(mekanism.api.tier.BaseTier) PlayerEntity(net.minecraft.entity.player.PlayerEntity) Nonnull(javax.annotation.Nonnull)

Aggregations

TileEntityMekanism (mekanism.common.tile.base.TileEntityMekanism)15 ItemStack (net.minecraft.item.ItemStack)9 Nonnull (javax.annotation.Nonnull)8 Item (net.minecraft.item.Item)6 TileEntity (net.minecraft.tileentity.TileEntity)6 ArrayList (java.util.ArrayList)5 ISideConfiguration (mekanism.common.tile.interfaces.ISideConfiguration)5 Block (net.minecraft.block.Block)5 Nullable (javax.annotation.Nullable)4 SubstanceType (mekanism.common.tile.base.SubstanceType)4 ISustainedInventory (mekanism.common.tile.interfaces.ISustainedInventory)4 PlayerEntity (net.minecraft.entity.player.PlayerEntity)4 BlockItem (net.minecraft.item.BlockItem)4 IEnergyContainer (mekanism.api.energy.IEnergyContainer)3 ISustainedData (mekanism.common.tile.interfaces.ISustainedData)3 ServerPlayerEntity (net.minecraft.entity.player.ServerPlayerEntity)3 Direction (net.minecraft.util.Direction)3 BlockPos (net.minecraft.util.math.BlockPos)3 World (net.minecraft.world.World)3 List (java.util.List)2