Search in sources :

Example 1 with ContainerPlayer

use of net.minecraft.inventory.ContainerPlayer in project SpongeForge by SpongePowered.

the class MixinPlayerInteractionManager method processRightClickBlock.

/**
 * @author gabizou - May 5th, 2016
 * @reason Rewrite the firing of interact block events with forge hooks
 * Note: This is a dirty merge of Aaron's SpongeCommon writeup of the interaction events and
 * Forge's additions. There's some overlay between the two events, specifically that there
 * is a SpongeEvent thrown before the ForgeEvent, and yet both are checked in various
 * if statements.
 */
@Overwrite
public EnumActionResult processRightClickBlock(EntityPlayer player, World worldIn, ItemStack stack, EnumHand hand, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ) {
    if (this.gameType == GameType.SPECTATOR) {
        TileEntity tileentity = worldIn.getTileEntity(pos);
        if (tileentity instanceof ILockableContainer) {
            Block block = worldIn.getBlockState(pos).getBlock();
            ILockableContainer ilockablecontainer = (ILockableContainer) tileentity;
            if (ilockablecontainer instanceof TileEntityChest && block instanceof BlockChest) {
                ilockablecontainer = ((BlockChest) block).getLockableContainer(worldIn, pos);
            }
            if (ilockablecontainer != null) {
                player.displayGUIChest(ilockablecontainer);
                return EnumActionResult.SUCCESS;
            }
        } else if (tileentity instanceof IInventory) {
            player.displayGUIChest((IInventory) tileentity);
            return EnumActionResult.SUCCESS;
        }
        return EnumActionResult.PASS;
    }
    // Store reference of current player's itemstack in case it changes
    ItemStack oldStack = stack.copy();
    InteractBlockEvent.Secondary event;
    BlockSnapshot currentSnapshot = ((org.spongepowered.api.world.World) worldIn).createSnapshot(pos.getX(), pos.getY(), pos.getZ());
    event = SpongeCommonEventFactory.callInteractBlockEventSecondary(player, oldStack, VecHelper.toVector3d(pos.add(hitX, hitY, hitZ)), currentSnapshot, DirectionFacingProvider.getInstance().getKey(facing).get(), hand);
    if (!ItemStack.areItemStacksEqual(oldStack, this.player.getHeldItem(hand))) {
        SpongeCommonEventFactory.playerInteractItemChanged = true;
    }
    TileEntity tileEntity = worldIn.getTileEntity(pos);
    if (event.isCancelled()) {
        final IBlockState state = worldIn.getBlockState(pos);
        if (state.getBlock() == Blocks.COMMAND_BLOCK) {
            // CommandBlock GUI opens solely on the client, we need to force it close on cancellation
            this.player.connection.sendPacket(new SPacketCloseWindow(0));
        } else if (state.getProperties().containsKey(BlockDoor.HALF)) {
            // client to resolve this
            if (state.getValue(BlockDoor.HALF) == BlockDoor.EnumDoorHalf.LOWER) {
                this.player.connection.sendPacket(new SPacketBlockChange(worldIn, pos.up()));
            } else {
                this.player.connection.sendPacket(new SPacketBlockChange(worldIn, pos.down()));
            }
        } else if (!stack.isEmpty()) {
            // Stopping the placement of a door or double plant causes artifacts (ghosts) on the top-side of the block. We need to remove it
            if (stack.getItem() instanceof ItemDoor || (stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().equals(Blocks.DOUBLE_PLANT))) {
                this.player.connection.sendPacket(new SPacketBlockChange(worldIn, pos.up(2)));
            }
        }
        // since we don't want to undo that
        if (tileEntity != null && this.player.openContainer instanceof ContainerPlayer) {
            this.player.closeScreen();
        }
        SpongeCommonEventFactory.interactBlockEventCancelled = true;
        return EnumActionResult.FAIL;
    }
    net.minecraft.item.Item item = stack.isEmpty() ? null : stack.getItem();
    EnumActionResult ret = item == null ? EnumActionResult.PASS : item.onItemUseFirst(player, worldIn, pos, facing, hitX, hitY, hitZ, hand);
    if (ret != EnumActionResult.PASS) {
        return ret;
    }
    boolean bypass = true;
    final ItemStack[] itemStacks = { player.getHeldItemMainhand(), player.getHeldItemOffhand() };
    for (ItemStack s : itemStacks) {
        bypass = bypass && (s.isEmpty() || s.getItem().doesSneakBypassUse(s, worldIn, pos, player));
    }
    EnumActionResult result = EnumActionResult.PASS;
    if (!player.isSneaking() || bypass || event.getUseBlockResult() == Tristate.TRUE) {
        // also, store the result instead of returning immediately
        if (event.getUseBlockResult() != Tristate.FALSE) {
            IBlockState iblockstate = worldIn.getBlockState(pos);
            Container lastOpenContainer = player.openContainer;
            result = iblockstate.getBlock().onBlockActivated(worldIn, pos, iblockstate, player, hand, facing, hitX, hitY, hitZ) ? EnumActionResult.SUCCESS : EnumActionResult.FAIL;
            // if itemstack changed, avoid restore
            if (!ItemStack.areItemStacksEqual(oldStack, this.player.getHeldItem(hand))) {
                SpongeCommonEventFactory.playerInteractItemChanged = true;
            }
            result = this.handleOpenEvent(lastOpenContainer, this.player, currentSnapshot, result);
        } else {
            this.player.connection.sendPacket(new SPacketBlockChange(this.world, pos));
            result = TristateUtil.toActionResult(event.getUseItemResult());
        }
    }
    // This handles the event not cancelled and block not activated
    if (result != EnumActionResult.SUCCESS && tileEntity != null && hand == EnumHand.MAIN_HAND) {
        this.player.closeScreen();
    }
    // store result instead of returning
    if (stack.isEmpty()) {
        result = EnumActionResult.PASS;
    } else if (player.getCooldownTracker().hasCooldown(stack.getItem())) {
        result = EnumActionResult.PASS;
    } else if (stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock() instanceof BlockCommandBlock && !player.canUseCommand(2, "")) {
        result = EnumActionResult.FAIL;
    } else {
        if ((result != EnumActionResult.SUCCESS && event.getUseItemResult() != Tristate.FALSE || result == EnumActionResult.SUCCESS && event.getUseItemResult() == Tristate.TRUE)) {
            int meta = stack.getMetadata();
            int size = stack.getCount();
            result = stack.onItemUse(player, worldIn, pos, hand, facing, hitX, hitY, hitZ);
            // nest isCreative check instead of calling the method twice.
            if (this.isCreative()) {
                stack.setItemDamage(meta);
                stack.setCount(size);
            }
        }
    }
    if (!ItemStack.areItemStacksEqual(player.getHeldItem(hand), oldStack) || result != EnumActionResult.SUCCESS) {
        player.openContainer.detectAndSendChanges();
    }
    return result;
// Sponge end
}
Also used : ItemDoor(net.minecraft.item.ItemDoor) BlockCommandBlock(net.minecraft.block.BlockCommandBlock) World(net.minecraft.world.World) TileEntity(net.minecraft.tileentity.TileEntity) ILockableContainer(net.minecraft.world.ILockableContainer) EnumActionResult(net.minecraft.util.EnumActionResult) ILockableContainer(net.minecraft.world.ILockableContainer) Container(net.minecraft.inventory.Container) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) SPacketCloseWindow(net.minecraft.network.play.server.SPacketCloseWindow) IInventory(net.minecraft.inventory.IInventory) TileEntityChest(net.minecraft.tileentity.TileEntityChest) IBlockState(net.minecraft.block.state.IBlockState) BlockChest(net.minecraft.block.BlockChest) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) ItemBlock(net.minecraft.item.ItemBlock) SPacketBlockChange(net.minecraft.network.play.server.SPacketBlockChange) ContainerPlayer(net.minecraft.inventory.ContainerPlayer) Block(net.minecraft.block.Block) BlockCommandBlock(net.minecraft.block.BlockCommandBlock) ItemBlock(net.minecraft.item.ItemBlock) ItemStack(net.minecraft.item.ItemStack) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Example 2 with ContainerPlayer

use of net.minecraft.inventory.ContainerPlayer in project LogisticsPipes by RS485.

the class ModulePropertiesUpdate method processPacket.

@Override
public void processPacket(EntityPlayer player) {
    final LogisticsModule module = this.getLogisticsModule(player, LogisticsModule.class);
    if (module == null) {
        return;
    }
    // sync updated properties
    module.readFromNBT(tag);
    if (!getType().isInWorld() && player.openContainer instanceof ContainerPlayer) {
        // FIXME: saveInformation & markDirty on module property change? should be called only once
        // sync slot in player inventory and mark player inventory dirty
        ItemModuleInformationManager.saveInformation(player.inventory.mainInventory.get(getPositionInt()), module);
        player.inventory.markDirty();
    }
    MainProxy.runOnServer(player.world, () -> () -> {
        // resync client; always
        MainProxy.sendPacketToPlayer(fromPropertyHolder(module).setModulePos(module), player);
    });
}
Also used : ContainerPlayer(net.minecraft.inventory.ContainerPlayer) LogisticsModule(logisticspipes.modules.LogisticsModule)

Example 3 with ContainerPlayer

use of net.minecraft.inventory.ContainerPlayer in project SpongeCommon by SpongePowered.

the class SpongeCommonEventFactory method callInteractInventoryCloseEvent.

public static InteractInventoryEvent.Close callInteractInventoryCloseEvent(Container container, EntityPlayerMP player, ItemStackSnapshot lastCursor, ItemStackSnapshot newCursor, boolean clientSource) {
    Transaction<ItemStackSnapshot> cursorTransaction = new Transaction<>(lastCursor, newCursor);
    final InteractInventoryEvent.Close event = SpongeEventFactory.createInteractInventoryEventClose(Sponge.getCauseStackManager().getCurrentCause(), cursorTransaction, ContainerUtil.fromNative(container));
    SpongeImpl.postEvent(event);
    if (event.isCancelled()) {
        if (clientSource && container.getSlot(0) != null) {
            if (!(container instanceof ContainerPlayer)) {
                // Inventory closed by client, reopen window and send
                // container
                player.openContainer = container;
                final String guiId;
                final Slot slot = container.getSlot(0);
                final IInventory slotInventory = slot.inventory;
                if (slotInventory instanceof IInteractionObject) {
                    guiId = ((IInteractionObject) slotInventory).getGuiID();
                } else {
                    // expected fallback for unknown types
                    guiId = "minecraft:container";
                }
                slotInventory.openInventory(player);
                player.connection.sendPacket(new SPacketOpenWindow(container.windowId, guiId, slotInventory.getDisplayName(), slotInventory.getSizeInventory()));
                // resync data to client
                player.sendContainerToPlayer(container);
            } else {
            // TODO: Maybe print a warning or throw an exception here?
            // The player gui cannot be opened from the
            // server so allowing this event to be cancellable when the
            // GUI has been closed already would result
            // in opening the wrong GUI window.
            }
        }
        // Handle cursor
        if (!event.getCursorTransaction().isValid()) {
            handleCustomCursor(player, event.getCursorTransaction().getOriginal());
        }
    } else {
        IMixinContainer mixinContainer = (IMixinContainer) player.openContainer;
        mixinContainer.getCapturedTransactions().clear();
        mixinContainer.setCaptureInventory(false);
        // Handle cursor
        if (!event.getCursorTransaction().isValid()) {
            handleCustomCursor(player, event.getCursorTransaction().getOriginal());
        } else if (event.getCursorTransaction().getCustom().isPresent()) {
            handleCustomCursor(player, event.getCursorTransaction().getFinal());
        }
        if (!clientSource && player.openContainer != null && player.connection != null) {
            player.closeScreen();
        }
    }
    return event;
}
Also used : ContainerPlayer(net.minecraft.inventory.ContainerPlayer) IInventory(net.minecraft.inventory.IInventory) IMixinContainer(org.spongepowered.common.interfaces.IMixinContainer) IInteractionObject(net.minecraft.world.IInteractionObject) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) Transaction(org.spongepowered.api.data.Transaction) InteractInventoryEvent(org.spongepowered.api.event.item.inventory.InteractInventoryEvent) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) SPacketSetSlot(net.minecraft.network.play.server.SPacketSetSlot) Slot(net.minecraft.inventory.Slot) SPacketOpenWindow(net.minecraft.network.play.server.SPacketOpenWindow)

Example 4 with ContainerPlayer

use of net.minecraft.inventory.ContainerPlayer in project ForestryMC by ForestryMC.

the class ResupplyHandler method resupply.

@Override
public void resupply(EntityPlayer player) {
    // Do not attempt resupplying if this backpack is already opened.
    if (!(player.openContainer instanceof ContainerPlayer)) {
        return;
    }
    for (ItemStack backpack : getBackpacks(player.inventory)) {
        if (ItemBackpack.getMode(backpack) == BackpackMode.RESUPPLY) {
            // Load their inventory
            ItemBackpack backpackItem = (ItemBackpack) backpack.getItem();
            ItemInventory backpackInventory = new ItemInventoryBackpack(player, backpackItem.getBackpackSize(), backpack);
            Event event = new BackpackResupplyEvent(player, backpackItem.getDefinition(), backpackInventory);
            if (!MinecraftForge.EVENT_BUS.post(event)) {
                for (int i = 0; i < backpackInventory.getSizeInventory(); i++) {
                    ItemStack itemStack = backpackInventory.getStackInSlot(i);
                    if (topOffPlayerInventory(player, itemStack)) {
                        backpackInventory.setInventorySlotContents(i, itemStack);
                        break;
                    }
                }
            }
        }
    }
}
Also used : ContainerPlayer(net.minecraft.inventory.ContainerPlayer) ItemInventory(forestry.core.inventory.ItemInventory) ItemInventoryBackpack(forestry.storage.inventory.ItemInventoryBackpack) BackpackResupplyEvent(forestry.api.storage.BackpackResupplyEvent) Event(net.minecraftforge.fml.common.eventhandler.Event) BackpackResupplyEvent(forestry.api.storage.BackpackResupplyEvent) ItemBackpack(forestry.storage.items.ItemBackpack) ItemStack(net.minecraft.item.ItemStack)

Example 5 with ContainerPlayer

use of net.minecraft.inventory.ContainerPlayer in project LogisticsPipes by RS485.

the class ModuleCoordinatesPacket method getLogisticsModule.

@SuppressWarnings("unchecked")
public <T> T getLogisticsModule(EntityPlayer player, Class<T> clazz) {
    LogisticsModule module;
    if (type == ModulePositionType.IN_PIPE) {
        moduleBased = true;
        LogisticsTileGenericPipe pipe = this.getPipe(player.getEntityWorld(), LTGPCompletionCheck.NONE);
        moduleBased = false;
        if (!(pipe.pipe instanceof CoreRoutedPipe)) {
            throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", pipe didn't exsist", this);
        }
        module = ((CoreRoutedPipe) pipe.pipe).getLogisticsModule();
    } else if (type == ModulePositionType.IN_HAND) {
        if (MainProxy.isServer(player.getEntityWorld())) {
            if (player.openContainer instanceof DummyModuleContainer) {
                DummyModuleContainer dummy = (DummyModuleContainer) player.openContainer;
                module = dummy.getModule();
            } else if (player.openContainer instanceof ContainerPlayer) {
                module = ItemModule.getLogisticsModule(player, getPositionInt());
                if (module == null) {
                    throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", module not found at slot " + getPositionInt(), this);
                }
            } else {
                throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", no DummyModuleContainer open and the player is in another GUI", this);
            }
        } else {
            module = MainProxy.proxy.getModuleFromGui();
            if (module == null) {
                module = ItemModule.getLogisticsModule(player, getPositionInt());
            }
            if (module == null) {
                throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", GUI didn't provide the module and module not found at slot " + getPositionInt(), this);
            }
        }
    } else {
        moduleBased = true;
        LogisticsTileGenericPipe pipe = this.getPipe(player.getEntityWorld(), LTGPCompletionCheck.NONE);
        moduleBased = false;
        if (!(pipe.pipe instanceof CoreRoutedPipe)) {
            throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", pipe didn't exsist", this);
        } else if (!pipe.isInitialized()) {
            return null;
        }
        if (!(pipe.pipe instanceof PipeLogisticsChassis)) {
            throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", pipe wasn't a chassi pipe", this);
        }
        module = ((PipeLogisticsChassis) pipe.pipe).getSubModule(positionInt);
    }
    if (module != null) {
        if (!(clazz.isAssignableFrom(module.getClass()))) {
            throw new TargetNotFoundException("Couldn't find " + clazz.getName() + ", found " + module.getClass(), this);
        }
    } else {
        throw new TargetNotFoundException("Couldn't find " + clazz.getName(), this);
    }
    return (T) module;
}
Also used : ContainerPlayer(net.minecraft.inventory.ContainerPlayer) DummyModuleContainer(logisticspipes.utils.gui.DummyModuleContainer) LogisticsModule(logisticspipes.modules.LogisticsModule) TargetNotFoundException(logisticspipes.network.exception.TargetNotFoundException) LogisticsTileGenericPipe(logisticspipes.pipes.basic.LogisticsTileGenericPipe) PipeLogisticsChassis(logisticspipes.pipes.PipeLogisticsChassis) CoreRoutedPipe(logisticspipes.pipes.basic.CoreRoutedPipe)

Aggregations

ContainerPlayer (net.minecraft.inventory.ContainerPlayer)5 LogisticsModule (logisticspipes.modules.LogisticsModule)2 IInventory (net.minecraft.inventory.IInventory)2 ItemStack (net.minecraft.item.ItemStack)2 BackpackResupplyEvent (forestry.api.storage.BackpackResupplyEvent)1 ItemInventory (forestry.core.inventory.ItemInventory)1 ItemInventoryBackpack (forestry.storage.inventory.ItemInventoryBackpack)1 ItemBackpack (forestry.storage.items.ItemBackpack)1 TargetNotFoundException (logisticspipes.network.exception.TargetNotFoundException)1 PipeLogisticsChassis (logisticspipes.pipes.PipeLogisticsChassis)1 CoreRoutedPipe (logisticspipes.pipes.basic.CoreRoutedPipe)1 LogisticsTileGenericPipe (logisticspipes.pipes.basic.LogisticsTileGenericPipe)1 DummyModuleContainer (logisticspipes.utils.gui.DummyModuleContainer)1 Block (net.minecraft.block.Block)1 BlockChest (net.minecraft.block.BlockChest)1 BlockCommandBlock (net.minecraft.block.BlockCommandBlock)1 IBlockState (net.minecraft.block.state.IBlockState)1 Container (net.minecraft.inventory.Container)1 Slot (net.minecraft.inventory.Slot)1 ItemBlock (net.minecraft.item.ItemBlock)1