Search in sources :

Example 1 with MenuProvider

use of net.minecraft.world.MenuProvider in project SpongeCommon by SpongePowered.

the class InventoryEventFactory method displayContainer.

@org.checkerframework.checker.nullness.qual.Nullable
public static AbstractContainerMenu displayContainer(final ServerPlayer player, final Inventory inventory, final Component displayName) {
    final net.minecraft.world.inventory.AbstractContainerMenu previousContainer = player.containerMenu;
    final net.minecraft.world.inventory.AbstractContainerMenu container;
    Optional<ViewableInventory> viewable = inventory.asViewable();
    if (viewable.isPresent()) {
        if (viewable.get() instanceof MenuProvider) {
            MenuProvider namedContainerProvider = (MenuProvider) viewable.get();
            if (displayName != null) {
                namedContainerProvider = new SimpleMenuProvider(namedContainerProvider, SpongeAdventure.asVanilla(displayName));
            }
            player.openMenu(namedContainerProvider);
        } else if (viewable.get() instanceof CarriedInventory) {
            Optional carrier = ((CarriedInventory) viewable.get()).carrier();
            if (carrier.get() instanceof AbstractHorse) {
                player.openHorseInventory(((AbstractHorse) carrier.get()), ((Container) viewable.get()));
            }
        } else if (viewable.get() instanceof Merchant) {
            Merchant merchant = (Merchant) viewable.get();
            net.minecraft.network.chat.Component display = null;
            int level = 0;
            if (merchant instanceof Villager) {
                display = ((Villager) merchant).getDisplayName();
                level = ((Villager) merchant).getVillagerData().getLevel();
            } else if (merchant instanceof WanderingTrader) {
                display = ((WanderingTrader) merchant).getDisplayName();
                level = 1;
            }
            if (displayName != null) {
                display = SpongeAdventure.asVanilla(displayName);
            }
            OptionalInt containerId = player.openMenu(new SimpleMenuProvider((id, playerInv, p) -> new MerchantMenu(id, playerInv, merchant), display));
            if (containerId.isPresent() && !merchant.getOffers().isEmpty()) {
                player.sendMerchantOffers(containerId.getAsInt(), merchant.getOffers(), level, merchant.getVillagerXp(), merchant.showProgressBar(), merchant.canRestock());
            }
        }
    }
    container = player.containerMenu;
    if (previousContainer == container) {
        return null;
    }
    if (!InventoryEventFactory.callInteractContainerOpenEvent(player)) {
        return null;
    }
    if (container instanceof ContainerBridge) {
        // This overwrites the normal container behaviour and allows viewing
        // inventories that are more than 8 blocks away
        // This currently actually only works for the Containers mixed into
        // by InteractableContainerMixin ; but throws no errors for other
        // containers
        // Allow viewing inventory; except when dead
        ((ContainerBridge) container).bridge$setCanInteractWith(p -> !p.removed);
    }
    return container;
}
Also used : EnchantItemEvent(org.spongepowered.api.event.item.inventory.EnchantItemEvent) LivingEntity(net.minecraft.world.entity.LivingEntity) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) SimpleMenuProvider(net.minecraft.world.SimpleMenuProvider) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) ContainerBridge(org.spongepowered.common.bridge.world.inventory.container.ContainerBridge) EffectTransactor(org.spongepowered.common.event.tracking.context.transaction.EffectTransactor) Enchantment(org.spongepowered.api.item.enchantment.Enchantment) Villager(net.minecraft.world.entity.npc.Villager) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) PlayerInventoryTransaction(org.spongepowered.common.event.tracking.context.transaction.inventory.PlayerInventoryTransaction) MerchantMenu(net.minecraft.world.inventory.MerchantMenu) TransactionalCaptureSupplier(org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier) Transaction(org.spongepowered.api.data.Transaction) HopperBlockEntity(net.minecraft.world.level.block.entity.HopperBlockEntity) InteractContainerEvent(org.spongepowered.api.event.item.inventory.container.InteractContainerEvent) Merchant(net.minecraft.world.item.trading.Merchant) Player(net.minecraft.world.entity.player.Player) EnchantmentInstance(net.minecraft.world.item.enchantment.EnchantmentInstance) InventoryUtil(org.spongepowered.common.inventory.util.InventoryUtil) List(java.util.List) ItemEntity(net.minecraft.world.entity.item.ItemEntity) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) ChangeInventoryEvent(org.spongepowered.api.event.item.inventory.ChangeInventoryEvent) CarriedInventory(org.spongepowered.api.item.inventory.type.CarriedInventory) Optional(java.util.Optional) MenuProvider(net.minecraft.world.MenuProvider) EnchantmentMenu(net.minecraft.world.inventory.EnchantmentMenu) ItemStack(net.minecraft.world.item.ItemStack) ViewableInventory(org.spongepowered.api.item.inventory.type.ViewableInventory) WanderingTrader(net.minecraft.world.entity.npc.WanderingTrader) Inventory(org.spongepowered.api.item.inventory.Inventory) NonNull(org.checkerframework.checker.nullness.qual.NonNull) AbstractContainerMenu(net.minecraft.world.inventory.AbstractContainerMenu) OptionalInt(java.util.OptionalInt) Supplier(java.util.function.Supplier) TransferInventoryEvent(org.spongepowered.api.event.item.inventory.TransferInventoryEvent) ArrayList(java.util.ArrayList) ServerPlayer(net.minecraft.server.level.ServerPlayer) Container(net.minecraft.world.Container) TrackingUtil(org.spongepowered.common.event.tracking.TrackingUtil) ItemStackUtil(org.spongepowered.common.item.util.ItemStackUtil) Component(net.kyori.adventure.text.Component) CauseStackManager(org.spongepowered.api.event.CauseStackManager) Nullable(org.checkerframework.checker.nullness.qual.Nullable) UpdateAnvilEvent(org.spongepowered.api.event.item.inventory.UpdateAnvilEvent) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Item(org.spongepowered.api.entity.Item) ContainerUtil(org.spongepowered.common.inventory.util.ContainerUtil) Slot(org.spongepowered.api.item.inventory.Slot) SpongeCommon(org.spongepowered.common.SpongeCommon) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) Entity(org.spongepowered.api.entity.Entity) AnvilMenu(net.minecraft.world.inventory.AnvilMenu) TrackedInventoryBridge(org.spongepowered.common.bridge.world.inventory.container.TrackedInventoryBridge) SpongeRandomEnchantmentListBuilder(org.spongepowered.common.item.enchantment.SpongeRandomEnchantmentListBuilder) AbstractHorse(net.minecraft.world.entity.animal.horse.AbstractHorse) ChangeEntityEquipmentEvent(org.spongepowered.api.event.entity.ChangeEntityEquipmentEvent) PacketPhaseUtil(org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil) Collections(java.util.Collections) MerchantMenu(net.minecraft.world.inventory.MerchantMenu) AbstractHorse(net.minecraft.world.entity.animal.horse.AbstractHorse) CarriedInventory(org.spongepowered.api.item.inventory.type.CarriedInventory) Optional(java.util.Optional) AbstractContainerMenu(net.minecraft.world.inventory.AbstractContainerMenu) OptionalInt(java.util.OptionalInt) ContainerBridge(org.spongepowered.common.bridge.world.inventory.container.ContainerBridge) SimpleMenuProvider(net.minecraft.world.SimpleMenuProvider) MenuProvider(net.minecraft.world.MenuProvider) ViewableInventory(org.spongepowered.api.item.inventory.type.ViewableInventory) SimpleMenuProvider(net.minecraft.world.SimpleMenuProvider) Merchant(net.minecraft.world.item.trading.Merchant) Villager(net.minecraft.world.entity.npc.Villager) WanderingTrader(net.minecraft.world.entity.npc.WanderingTrader) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 2 with MenuProvider

use of net.minecraft.world.MenuProvider in project SpongeCommon by SpongePowered.

the class CloseMenuTransaction method reopen.

private void reopen(final ServerPlayer player, final AbstractContainerMenu container) {
    if (container.getSlot(0) == null) {
        return;
    }
    if (!(container instanceof InventoryMenu)) {
        // Inventory closed by client, reopen window and send container
        player.containerMenu = container;
        final Slot slot = container.getSlot(0);
        final net.minecraft.world.Container slotInventory = slot.container;
        final net.minecraft.network.chat.@Nullable Component title;
        // TODO get name from last open
        if (slotInventory instanceof MenuProvider) {
            title = ((MenuProvider) slotInventory).getDisplayName();
        } else {
            // expected fallback for unknown types
            title = null;
        }
        slotInventory.startOpen(player);
        player.connection.send(new ClientboundOpenScreenPacket(container.containerId, container.getType(), title));
        // resync data to client
        player.refreshContainer(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.
    }
}
Also used : InventoryMenu(net.minecraft.world.inventory.InventoryMenu) Slot(net.minecraft.world.inventory.Slot) ClientboundOpenScreenPacket(net.minecraft.network.protocol.game.ClientboundOpenScreenPacket) MenuProvider(net.minecraft.world.MenuProvider) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 3 with MenuProvider

use of net.minecraft.world.MenuProvider in project MinecraftForge by MinecraftForge.

the class ContainerTypeTest method onRightClick.

private void onRightClick(PlayerInteractEvent.RightClickBlock event) {
    if (!event.getWorld().isClientSide && event.getHand() == InteractionHand.MAIN_HAND) {
        if (event.getWorld().getBlockState(event.getPos()).getBlock() == Blocks.SPONGE) {
            String text = "Hello World!";
            NetworkHooks.openGui((ServerPlayer) event.getPlayer(), new MenuProvider() {

                @Override
                public AbstractContainerMenu createMenu(int p_createMenu_1_, Inventory p_createMenu_2_, Player p_createMenu_3_) {
                    SimpleContainer inv = new SimpleContainer(9);
                    for (int i = 0; i < inv.getContainerSize(); i++) {
                        inv.setItem(i, new ItemStack(Items.DIAMOND));
                    }
                    return new TestContainer(p_createMenu_1_, inv, text);
                }

                @Override
                public Component getDisplayName() {
                    return new TextComponent("Test");
                }
            }, extraData -> {
                extraData.writeUtf(text);
            });
        }
    }
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) ServerPlayer(net.minecraft.server.level.ServerPlayer) Player(net.minecraft.world.entity.player.Player) AbstractContainerMenu(net.minecraft.world.inventory.AbstractContainerMenu) SimpleContainer(net.minecraft.world.SimpleContainer) ItemStack(net.minecraft.world.item.ItemStack) Component(net.minecraft.network.chat.Component) TextComponent(net.minecraft.network.chat.TextComponent) MenuProvider(net.minecraft.world.MenuProvider) Inventory(net.minecraft.world.entity.player.Inventory)

Example 4 with MenuProvider

use of net.minecraft.world.MenuProvider in project SpongeCommon by SpongePowered.

the class ServerPlayerGameModeMixin_Tracker method useItemOn.

/**
 * @author Morph
 * @reason Fire interact block event.
 */
@Overwrite
public InteractionResult useItemOn(final ServerPlayer playerIn, final Level worldIn, final ItemStack stackIn, final InteractionHand handIn, final BlockHitResult blockRaytraceResultIn) {
    final BlockPos blockpos = blockRaytraceResultIn.getBlockPos();
    final BlockState blockstate = worldIn.getBlockState(blockpos);
    // Sponge start
    final BlockSnapshot snapshot = ((ServerWorld) (worldIn)).createSnapshot(VecHelper.toVector3i(blockpos));
    final Vector3d hitVec = Vector3d.from(blockRaytraceResultIn.getBlockPos().getX(), blockRaytraceResultIn.getBlockPos().getY(), blockRaytraceResultIn.getBlockPos().getZ());
    final org.spongepowered.api.util.Direction direction = DirectionFacingProvider.INSTANCE.getKey(blockRaytraceResultIn.getDirection()).get();
    final InteractBlockEvent.Secondary event = SpongeCommonEventFactory.callInteractBlockEventSecondary(playerIn, stackIn, hitVec, snapshot, direction, handIn);
    if (event.isCancelled()) {
        return InteractionResult.FAIL;
    }
    final Tristate useItem = event.useItemResult();
    final Tristate useBlock = event.useBlockResult();
    // Sponge end
    if (this.gameModeForPlayer == GameType.SPECTATOR) {
        final MenuProvider inamedcontainerprovider = blockstate.getMenuProvider(worldIn, blockpos);
        if (inamedcontainerprovider != null) {
            playerIn.openMenu(inamedcontainerprovider);
            final Vector3i pos = VecHelper.toVector3i(blockRaytraceResultIn.getBlockPos());
            final ServerLocation location = ServerLocation.of((ServerWorld) worldIn, pos);
            try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
                frame.pushCause(playerIn);
                frame.addContext(EventContextKeys.BLOCK_HIT, ((ServerWorld) (worldIn)).createSnapshot(pos));
                ((ContainerBridge) playerIn.containerMenu).bridge$setOpenLocation(location);
                if (!InventoryEventFactory.callInteractContainerOpenEvent(playerIn)) {
                    return InteractionResult.SUCCESS;
                }
            }
            return InteractionResult.SUCCESS;
        } else {
            return InteractionResult.PASS;
        }
    } else {
        final boolean flag = !playerIn.getMainHandItem().isEmpty() || !playerIn.getOffhandItem().isEmpty();
        final boolean flag1 = playerIn.isSecondaryUseActive() && flag;
        final ItemStack copiedStack = stackIn.copy();
        if (useBlock != Tristate.FALSE && !flag1) {
            // Sponge check useBlock
            final AbstractContainerMenu lastOpenContainer = playerIn.containerMenu;
            final InteractionResult result = blockstate.use(worldIn, playerIn, handIn, blockRaytraceResultIn);
            if (result.consumesAction() && lastOpenContainer != playerIn.containerMenu) {
                final Vector3i pos = VecHelper.toVector3i(blockRaytraceResultIn.getBlockPos());
                final ServerLocation location = ServerLocation.of((ServerWorld) worldIn, pos);
                try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) {
                    frame.pushCause(playerIn);
                    frame.addContext(EventContextKeys.BLOCK_HIT, ((ServerWorld) (worldIn)).createSnapshot(pos));
                    ((ContainerBridge) playerIn.containerMenu).bridge$setOpenLocation(location);
                    if (!InventoryEventFactory.callInteractContainerOpenEvent(playerIn)) {
                        return InteractionResult.FAIL;
                    }
                }
            }
            if (result.consumesAction()) {
                CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(playerIn, blockpos, copiedStack);
                return result;
            }
        }
        if (!stackIn.isEmpty() && !playerIn.getCooldowns().isOnCooldown(stackIn.getItem())) {
            // Sponge start
            if (useItem == Tristate.FALSE) {
                return InteractionResult.PASS;
            }
            // Sponge end
            final UseOnContext itemusecontext = new UseOnContext(playerIn, handIn, blockRaytraceResultIn);
            final InteractionResult result;
            if (this.isCreative()) {
                final int i = stackIn.getCount();
                result = stackIn.useOn(itemusecontext);
                stackIn.setCount(i);
            } else {
                result = stackIn.useOn(itemusecontext);
                // Sponge start - log change in hand
                final PhaseContext<@NonNull ?> context = PhaseTracker.SERVER.getPhaseContext();
                final TransactionalCaptureSupplier transactor = context.getTransactor();
                transactor.logPlayerInventoryChange(this.player, PlayerInventoryTransaction.EventCreator.STANDARD);
                this.player.inventoryMenu.broadcastChanges();
            // Sponge end
            }
            if (result.consumesAction()) {
                CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(playerIn, blockpos, copiedStack);
            }
            return result;
        } else {
            return InteractionResult.PASS;
        }
    }
}
Also used : ServerLocation(org.spongepowered.api.world.server.ServerLocation) Tristate(org.spongepowered.api.util.Tristate) ContainerBridge(org.spongepowered.common.bridge.world.inventory.container.ContainerBridge) ServerWorld(org.spongepowered.api.world.server.ServerWorld) InteractionResult(net.minecraft.world.InteractionResult) InteractBlockEvent(org.spongepowered.api.event.block.InteractBlockEvent) TransactionalCaptureSupplier(org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier) AbstractContainerMenu(net.minecraft.world.inventory.AbstractContainerMenu) CauseStackManager(org.spongepowered.api.event.CauseStackManager) BlockPos(net.minecraft.core.BlockPos) BlockSnapshot(org.spongepowered.api.block.BlockSnapshot) UseOnContext(net.minecraft.world.item.context.UseOnContext) MenuProvider(net.minecraft.world.MenuProvider) BlockState(net.minecraft.world.level.block.state.BlockState) Vector3d(org.spongepowered.math.vector.Vector3d) Vector3i(org.spongepowered.math.vector.Vector3i) ItemStack(net.minecraft.world.item.ItemStack) Overwrite(org.spongepowered.asm.mixin.Overwrite)

Aggregations

MenuProvider (net.minecraft.world.MenuProvider)4 AbstractContainerMenu (net.minecraft.world.inventory.AbstractContainerMenu)3 ItemStack (net.minecraft.world.item.ItemStack)3 ServerPlayer (net.minecraft.server.level.ServerPlayer)2 Player (net.minecraft.world.entity.player.Player)2 Nullable (org.checkerframework.checker.nullness.qual.Nullable)2 CauseStackManager (org.spongepowered.api.event.CauseStackManager)2 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 List (java.util.List)1 Optional (java.util.Optional)1 OptionalInt (java.util.OptionalInt)1 Supplier (java.util.function.Supplier)1 Component (net.kyori.adventure.text.Component)1 BlockPos (net.minecraft.core.BlockPos)1 Component (net.minecraft.network.chat.Component)1 TextComponent (net.minecraft.network.chat.TextComponent)1 ClientboundOpenScreenPacket (net.minecraft.network.protocol.game.ClientboundOpenScreenPacket)1 Container (net.minecraft.world.Container)1 InteractionResult (net.minecraft.world.InteractionResult)1