package net.mattias.pedestals.core.world.inventory; import…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
package net.mattias.pedestals.core.world.inventory;
import net.mattias.pedestals.core.registry.ModBlocks; import net.mattias.pedestals.core.registry.ModMenus; import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ContainerLevelAccess; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.neoforged.neoforge.items.SlotItemHandler;
public class PedestalMenu extends AbstractContainerMenu { public final PedestalBlockEntity blockEntity; private final Level level;
public PedestalMenu(int pContainerId, Inventory inv, FriendlyByteBuf extraData) {
this(pContainerId, inv, inv.player.level().getBlockEntity(extraData.readBlockPos()));
}
public PedestalMenu(int pContainerId, Inventory inv, BlockEntity blockEntity) {
super(ModMenus.PEDESTAL.get(), pContainerId);
this.blockEntity = ((PedestalBlockEntity) blockEntity);
this.level = inv.player.level();
addPlayerInventory(inv);
addPlayerHotbar(inv);
this.addSlot(new SlotItemHandler(this.blockEntity.inventory, 0, 80, 35));
}
// CREDIT GOES TO: diesieben07 | https://github.com/diesieben07/SevenCommons
// must assign a slot number to each of the slots used by the GUI.
// For this container, we can see both the tile inventory's slots as well as the player inventory slots and the hotbar.
// Each time we add a Slot to the container, it automatically increases the slotIndex, which means
// 0 - 8 = hotbar slots (which will map to the InventoryPlayer slot numbers 0 - 8)
// 9 - 35 = player inventory slots (which map to the InventoryPlayer slot numbers 9 - 35)
// 36 - 44 = TileInventory slots, which map to our TileEntity slot numbers 0 - 8)
private static final int HOTBAR_SLOT_COUNT = 9;
private static final int PLAYER_INVENTORY_ROW_COUNT = 3;
private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9;
private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT;
private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT;
private static final int VANILLA_FIRST_SLOT_INDEX = 0;
private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT;
// THIS YOU HAVE TO DEFINE!
private static final int TE_INVENTORY_SLOT_COUNT = 1; // must be the number of slots you have!
@Override
public ItemStack quickMoveStack(Player playerIn, int pIndex) {
Slot sourceSlot = slots.get(pIndex);
if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY; //EMPTY_ITEM
ItemStack sourceStack = sourceSlot.getItem();
ItemStack copyOfSourceStack = sourceStack.copy();
// Check if the slot clicked is one of the vanilla container slots
if (pIndex < VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT) {
// This is a vanilla container slot so merge the stack into the tile inventory
if (!moveItemStackTo(sourceStack, TE_INVENTORY_FIRST_SLOT_INDEX, TE_INVENTORY_FIRST_SLOT_INDEX
+ TE_INVENTORY_SLOT_COUNT, false)) {
return ItemStack.EMPTY; // EMPTY_ITEM
}
} else if (pIndex < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) {
// This is a TE slot so merge the stack into the players inventory
if (!moveItemStackTo(sourceStack, VANILLA_FIRST_SLOT_INDEX, VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) {
return ItemStack.EMPTY;
}
} else {
System.out.println("Invalid slotIndex:" + pIndex);
return ItemStack.EMPTY;
}
// If stack size == 0 (the entire stack was moved) set slot contents to null
if (sourceStack.getCount() == 0) {
sourceSlot.set(ItemStack.EMPTY);
} else {
sourceSlot.setChanged();
}
sourceSlot.onTake(playerIn, sourceStack);
return copyOfSourceStack;
}
@Override
public boolean stillValid(Player pPlayer) {
return stillValid(ContainerLevelAccess.create(level, blockEntity.getBlockPos()),
pPlayer, ModBlocks.PEDESTAL.get());
}
private void addPlayerInventory(Inventory playerInventory) {
for (int i = 0; i < 3; ++i) {
for (int l = 0; l < 9; ++l) {
this.addSlot(new Slot(playerInventory, l + i * 9 + 9, 8 + l * 18, 84 + i * 18));
}
}
}
private void addPlayerHotbar(Inventory playerInventory) {
for (int i = 0; i < 9; ++i) {
this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142));
}
}
}
package net.mattias.pedestals.core.world.block;
import com.mojang.serialization.MapCodec; import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity; import net.mattias.pedestals.core.world.inventory.PedestalMenu; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.Containers; import net.minecraft.world.InteractionHand; import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.SimpleMenuProvider; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable;
public class PedestalBlock extends BaseEntityBlock { public static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 13, 14); public static final MapCodec CODEC = simpleCodec(PedestalBlock::new);
public PedestalBlock(Properties properties) {
super(properties);
}
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return CODEC;
}
@Override
protected VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) {
return SHAPE;
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) {
return new PedestalBlockEntity(pPos, pState);
}
@Override
protected RenderShape getRenderShape(BlockState pState) {
return RenderShape.MODEL;
}
@Override
protected void onRemove(BlockState pState, Level pLevel, BlockPos pPos,
BlockState pNewState, boolean pMovedByPiston) {
if(pState.getBlock() != pNewState.getBlock()) {
if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) {
pedestalBlockEntity.drops();
pLevel.updateNeighbourForOutputSignal(pPos, this);
}
}
super.onRemove(pState, pLevel, pPos, pNewState, pMovedByPiston);
}
@Override
protected ItemInteractionResult useItemOn(ItemStack pStack, BlockState pState, Level pLevel, BlockPos pPos,
Player pPlayer, InteractionHand pHand, BlockHitResult pHitResult) {
if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) {
if(pPlayer.isCrouching() && !pLevel.isClientSide()) {
pPlayer.openMenu(new PedestalMenu(pContainerId, pPlayer.getInventory(), pedestalBlockEntity));
return ItemInteractionResult.SUCCESS;
}
if(pedestalBlockEntity.inventory.getStackInSlot(0).isEmpty() && !pStack.isEmpty()) {
pedestalBlockEntity.inventory.insertItem(0, pStack.copy(), false);
pStack.shrink(1);
pLevel.playSound(pPlayer, pPos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 1f, 2f);
} else if(pStack.isEmpty()) {
ItemStack stackOnPedestal = pedestalBlockEntity.inventory.extractItem(0, 1, false);
pPlayer.setItemInHand(InteractionHand.MAIN_HAND, stackOnPedestal);
pedestalBlockEntity.clearContents();
pLevel.playSound(pPlayer, pPos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 1f, 1f);
}
}
return ItemInteractionResult.SUCCESS;
}
}
Send whole classes back with fix
Okay, here are the complete classes with the fix applied.
The primary issue was how the menu was being opened in PedestalBlock. Instead of manually creating a PedestalMenu and passing the pContainerId (which was undefined in that context), you should leverage the MenuProvider interface that your PedestalBlockEntity already implements.
Here's the corrected code:
1. PedestalBlock.java
package net.mattias.pedestals.core.world.block;
import com.mojang.serialization.MapCodec;
import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity;
import net.mattias.pedestals.core.world.inventory.PedestalMenu; // Keep this import, it's good practice even if not directly called here
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.Containers;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.ItemInteractionResult;
import net.minecraft.world.SimpleMenuProvider; // This is no longer used for opening the menu, but is fine to keep if you had other uses
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.jetbrains.annotations.Nullable;
public class PedestalBlock extends BaseEntityBlock {
public static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 13, 14);
public static final MapCodec<PedestalBlock> CODEC = simpleCodec(PedestalBlock::new);
public PedestalBlock(Properties properties) {
super(properties);
}
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return CODEC;
}
@Override
protected VoxelShape getShape(BlockState pState, BlockGetter pLevel, BlockPos pPos, CollisionContext pContext) {
return SHAPE;
}
@Nullable
@Override
public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) {
return new PedestalBlockEntity(pPos, pState);
}
@Override
protected RenderShape getRenderShape(BlockState pState) {
return RenderShape.MODEL;
}
@Override
protected void onRemove(BlockState pState, Level pLevel, BlockPos pPos,
BlockState pNewState, boolean pMovedByPiston) {
if(pState.getBlock() != pNewState.getBlock()) {
if(pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) {
pedestalBlockEntity.drops();
pLevel.updateNeighbourForOutputSignal(pPos, this);
}
}
super.onRemove(pState, pLevel, pPos, pNewState, pMovedByPiston);
}
@Override
protected ItemInteractionResult useItemOn(ItemStack pStack, BlockState pState, Level pLevel, BlockPos pPos,
Player pPlayer, InteractionHand pHand, BlockHitResult pHitResult) {
// Check if the block entity exists at the position
if (pLevel.getBlockEntity(pPos) instanceof PedestalBlockEntity pedestalBlockEntity) {
// Server side check is important for opening menus
if (!pLevel.isClientSide()) {
// If player is crouching, open the GUI
if (pPlayer.isCrouching()) {
// Use the block entity as the MenuProvider.
// This correctly calls pedestalBlockEntity.createMenu() internally
// and passes the necessary data (including container ID) to open the screen.
((ServerPlayer) pPlayer).openMenu(pedestalBlockEntity, pHitResult.getBlockPos());
return ItemInteractionResult.SUCCESS;
}
// Handle item insertion/removal when not crouching
if (pedestalBlockEntity.inventory.getStackInSlot(0).isEmpty() && !pStack.isEmpty()) {
pedestalBlockEntity.inventory.insertItem(0, pStack.copy(), false);
pStack.shrink(1); // Consume one item from player's hand
pLevel.playSound(pPlayer, pPos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 1f, 2f);
} else if (pStack.isEmpty()) {
// Player is trying to take the item from the pedestal
ItemStack stackOnPedestal = pedestalBlockEntity.inventory.extractItem(0, 1, false);
if (!stackOnPedestal.isEmpty()) {
pPlayer.setItemInHand(InteractionHand.MAIN_HAND, stackOnPedestal);
pedestalBlockEntity.clearContents(); // Ensure the inventory slot is truly empty
pLevel.playSound(pPlayer, pPos, SoundEvents.ITEM_PICKUP, SoundSource.BLOCKS, 1f, 1f);
}
}
}
// Return SUCCESS even if it's client-side to prevent default interaction
// unless we've already handled it (like insertion/removal logic)
// For the menu opening part, it's crucial to only do it on server side.
return ItemInteractionResult.SUCCESS;
}
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; // Fallback if no block entity or other logic applied
}
}
2. PedestalMenu.java
package net.mattias.pedestals.core.world.inventory;
import net.mattias.pedestals.core.registry.ModBlocks;
import net.mattias.pedestals.core.registry.ModMenus;
import net.mattias.pedestals.core.world.block.entity.PedestalBlockEntity;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ContainerLevelAccess;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.neoforged.neoforge.items.SlotItemHandler;
public class PedestalMenu extends AbstractContainerMenu {
public final PedestalBlockEntity blockEntity;
private final Level level;
/**
* Constructor for when the container is created on the client side via a network packet.
* Reads the BlockPos from the buffer to find the correct BlockEntity.
*/
public PedestalMenu(int pContainerId, Inventory inv, FriendlyByteBuf extraData) {
// We need to get the BlockEntity using the BlockPos from the packet.
// The PedestalBlockEntity's createMenu method is responsible for setting up the MenuProvider.
// The player will have the correct BlockPos.
this(pContainerId, inv, inv.player.level().getBlockEntity(extraData.readBlockPos()));
}
/**
* Constructor for when the container is created directly on the server side.
* Takes the BlockEntity directly.
*/
public PedestalMenu(int pContainerId, Inventory inv, BlockEntity blockEntity) {
super(ModMenus.PEDESTAL.get(), pContainerId);
// Safely cast the BlockEntity to our specific PedestalBlockEntity
if (blockEntity instanceof PedestalBlockEntity pedestalBE) {
this.blockEntity = pedestalBE;
} else {
// If the block entity is not a PedestalBlockEntity, something is wrong.
// In a real scenario, you might want to throw an exception or handle this more gracefully.
// For now, we'll use a placeholder or null, but this should ideally not happen.
throw new IllegalArgumentException("BlockEntity is not a PedestalBlockEntity!");
}
this.level = inv.player.level();
// Add player inventory and hotbar slots
addPlayerInventory(inv);
addPlayerHotbar(inv);
// Add the slot for the item in the pedestal
// The coordinates are relative to the GUI background texture.
this.addSlot(new SlotItemHandler(this.blockEntity.inventory, 0, 80, 35));
}
// Helper method to add the player's inventory slots
private void addPlayerInventory(Inventory playerInventory) {
// Rows 0-2 of player inventory
for (int i = 0; i < 3; ++i) {
for (int l = 0; l < 9; ++l) {
// Parameters: Inventory, slot index in inventory, x pos, y pos
this.addSlot(new Slot(playerInventory, l + i * 9 + 9, 8 + l * 18, 84 + i * 18));
}
}
}
// Helper method to add the player's hotbar slots
private void addPlayerHotbar(Inventory playerInventory) {
// Hotbar slots 0-8
for (int i = 0; i < 9; ++i) {
// Parameters: Inventory, slot index in inventory, x pos, y pos
this.addSlot(new Slot(playerInventory, i, 8 + i * 18, 142));
}
}
// CREDIT GOES TO: diesieben07 | https://github.com/diesieben07/SevenCommons
// This method handles the "quick move" (shift-clicking) functionality.
// It determines where an item should go when clicked in the GUI.
@Override
public ItemStack quickMoveStack(Player playerIn, int pIndex) {
Slot sourceSlot = slots.get(pIndex);
// If the clicked slot is empty or null, do nothing.
if (sourceSlot == null || !sourceSlot.hasItem()) return ItemStack.EMPTY;
ItemStack sourceStack = sourceSlot.getItem();
ItemStack copyOfSourceStack = sourceStack.copy(); // Keep a copy for returning later
// Calculate slot indices for clarity and maintainability
// These numbers define which slots belong to the player inventory and which to the block entity.
final int PLAYER_INVENTORY_START_INDEX = 0; // Start of player inventory slots (hotbar + main inv)
final int PLAYER_INVENTORY_END_INDEX = VANILLA_SLOT_COUNT - 1; // End of player inventory slots
final int PEDESTAL_SLOT_START_INDEX = VANILLA_SLOT_COUNT; // Start of block entity inventory slots
final int PEDESTAL_SLOT_END_INDEX = PEDESTAL_SLOT_START_INDEX + TE_INVENTORY_SLOT_COUNT - 1; // End of block entity inventory slots
// Check if the slot clicked is one of the player's inventory/hotbar slots
if (pIndex >= PLAYER_INVENTORY_START_INDEX && pIndex <= PLAYER_INVENTORY_END_INDEX) {
// Try to move the item from the player inventory to the block entity inventory (the pedestal slot)
// moveItemStackTo attempts to move the stack into the target slot(s).
// If it succeeds, it returns true.
// Parameters: stack, startIndex of target, endIndex of target, allowSameStack
if (!moveItemStackTo(sourceStack, PEDESTAL_SLOT_START_INDEX, PEDESTAL_SLOT_END_INDEX + 1, false)) {
// If it failed to move to the block entity inventory, do nothing.
return ItemStack.EMPTY;
}
}
// Check if the slot clicked is one of the block entity's inventory slots (the pedestal slot)
else if (pIndex >= PEDESTAL_SLOT_START_INDEX && pIndex <= PEDESTAL_SLOT_END_INDEX) {
// Try to move the item from the block entity inventory back to the player's inventory.
if (!moveItemStackTo(sourceStack, PLAYER_INVENTORY_START_INDEX, PLAYER_INVENTORY_END_INDEX + 1, false)) {
// If it failed to move to the player inventory, do nothing.
return ItemStack.EMPTY;
}
} else {
// This case should theoretically not be reached if all slots are handled correctly.
// Logging an error can help debug if it ever happens.
System.err.println("Invalid slotIndex encountered in quickMoveStack: " + pIndex);
return ItemStack.EMPTY;
}
// --- Post-move operations ---
// If stack size is 0 after the move, it means the entire stack was transferred.
// Set the source slot to empty.
if (sourceStack.getCount() == 0) {
sourceSlot.set(ItemStack.EMPTY);
} else {
// Otherwise, update the source slot to reflect the remaining items.
sourceSlot.setChanged();
}
// Trigger the onTake callback for the source slot, which is important for some item logic.
sourceSlot.onTake(playerIn, sourceStack);
// Return the copy of the original stack that was moved.
return copyOfSourceStack;
}
/**
* Checks if the player can still interact with this container.
* This is called frequently to ensure the GUI remains open only as long as the player
* is close enough to the block.
*/
@Override
public boolean stillValid(Player pPlayer) {
// `stillValid` method from AbstractContainerMenu is used to check if the player is still close to the block.
// We use ContainerLevelAccess to provide the level and position.
return stillValid(ContainerLevelAccess.create(level, blockEntity.getBlockPos()),
pPlayer, ModBlocks.PEDESTAL.get()); // The last parameter is the block associated with this container.
}
// These constants are for slot indexing and are good practice for readability.
// They are used in the quickMoveStack method.
private static final int HOTBAR_SLOT_COUNT = 9;
private static final int PLAYER_INVENTORY_ROW_COUNT = 3;
private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9;
private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT;
private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT; // Total slots in player inventory + hotbar
private static final int VANILLA_FIRST_SLOT_INDEX = 0; // Player inventory starts at index 0 in the slots list
// Slot indices for the TileEntity inventory (the pedestal's item)
// The pedestal has only 1 slot.
private static final int TE_INVENTORY_SLOT_COUNT = 1;
// The first slot index for the tile entity inventory starts immediately after the player's inventory slots.
private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_SLOT_COUNT;
}