User Tools

Site Tools


tutorial:inventory

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
tutorial:inventory [2019/08/06 15:31] fudgetutorial:inventory [2026/01/24 02:29] (current) – try_with_empty_hand i believe infinitychances
Line 1: Line 1:
 ====== Storing items in a block as an Inventory ====== ====== Storing items in a block as an Inventory ======
-The standard way to store items in a BlockEntity is to make it an ''Inventory'' +:!: This page has been updated for mojmap. Because of this change, the class known as "Inventory" in yarn mappings is now called "Container." See [[https://docs.fabricmc.net/develop/migrating-mappings/#whats-going-on-with-mappings|What's Going On With Mappings]] for more detail. 
-This allows hoppers (or other mods) to insert and extract items from your BlockEntity without any extra work.  + 
-===== Implementing Inventory ===== +Make sure you've [[tutorial:blockentity|made a block entity]] before reading this tutorial.   
-''Inventory'' is just an interface, which means the actual ''ItemStack'' state will need to be stored on your ''BlockEntity''. + 
-A ''DefaultedList<ItemStack>'' can be used as an easy way to store  these ''ItemStacks'',  +The simplest way to store items in a BlockEntity is to make it ''Container''. This allows hoppers (or other mods) to insert and extract items from your BlockEntity without any extra work. For more flexible and complex ways to store items, refer to the [[tutorial:transfer-api_item_storage|Item transfer with Storage<ItemVariant>]] tutorial. 
-as it can be set to default to ''ItemStack.Empty'', which is the proper way of saying that there is no item in a slot. + 
-Implementing ''Inventory'' is fairly simple, but is tedious and prone to error,  +This tutorial is written for 1.21.11. For older versions, some methods may change. 
-so we'll use a default implementation of it which only requires giving it a ''DefaultList<ItemStack>'' (copy this as a new file): + 
-<code java ImplementedInventory.java>+===== Implementing Container ===== 
 + 
 +''Container'' is just an interface, which means the actual ''ItemStack'' state will need to be stored on your ''BlockEntity''. A ''NonNullList<ItemStack>'' can be used as an easy way to store  these ''ItemStacks'', as it can be set to default to ''ItemStack.Empty'', which is the proper way of saying that there is no item in a slot. Implementing ''Container'' is fairly simple, but is tedious and prone to error, so we'll use a default implementation of it which only requires giving it a ''NonNullList<ItemStack>'' (copy this as a new file): 
 + 
 +<code java ImplementedContainer.java>
 /** /**
- * A simple {@code Inventory} implementation with only default methods + an item list getter.+ * A simple {@code Container} implementation with only default methods + an item list getter.
  *  *
- Originally by Juuz+ @author Juuz
  */  */
-public interface ImplementedInventory extends Inventory {+public interface ImplementedContainer extends Container { 
     /**     /**
-     Gets the item list of this inventory.+     Retrieves the item list of this container.
      * Must return the same instance every time it's called.      * Must return the same instance every time it's called.
      */      */
-    DefaultedList<ItemStack> getItems(); +    NonNullList<ItemStack> getItems(); 
-    // Creation+    
     /**     /**
-     * Creates an inventory from the item list.+     * Creates a container from the item list.
      */      */
-    static ImplementedInventory of(DefaultedList<ItemStack> items) {+    static ImplementedContainer of(NonNullList<ItemStack> items) {
         return () -> items;         return () -> items;
     }     }
 +    
     /**     /**
-     * Creates a new inventory with the size.+     * Creates a new container with the specified size.
      */      */
-    static ImplementedInventory ofSize(int size) { +    static ImplementedContainer ofSize(int size) { 
-        return of(DefaultedList.ofSize(size, ItemStack.EMPTY));+        return of(NonNullList.withSize(size, ItemStack.EMPTY));
     }     }
-    // Inventory+    
     /**     /**
-     * Returns the inventory size.+     * Returns the container size.
      */      */
     @Override     @Override
-    default int getInvSize() {+    default int getContainerSize() {
         return getItems().size();         return getItems().size();
     }     }
 +    
     /**     /**
-     * @return true if this inventory has only empty stacks, false otherwise+     * Checks if the container is empty. 
 +     * @return true if this container has only empty stacks, false otherwise.
      */      */
     @Override     @Override
-    default boolean isInvEmpty() { +    default boolean isEmpty() { 
-        for (int i = 0; i < getInvSize(); i++) { +        for (int i = 0; i < getContainerSize(); i++) { 
-            ItemStack stack = getInvStack(i);+            ItemStack stack = getItem(i);
             if (!stack.isEmpty()) {             if (!stack.isEmpty()) {
                 return false;                 return false;
Line 54: Line 62:
         return true;         return true;
     }     }
 +    
     /**     /**
-     Gets the item in the slot.+     Retrieves the item in the slot.
      */      */
     @Override     @Override
-    default ItemStack getInvStack(int slot) {+    default ItemStack getItem(int slot) {
         return getItems().get(slot);         return getItems().get(slot);
     }     }
 +    
     /**     /**
-     Takes a stack of the size from the slot. +     Removes items from a container slot. 
-     <p>(default implementation) If there are less items in the slot than what are requested, +     @param slot  The slot to remove from. 
-     * takes all items in that slot.+     * @param count How many items to remove. If there are less items in the slot than what are requested, 
 +                  takes all items in that slot.
      */      */
     @Override     @Override
-    default ItemStack takeInvStack(int slot, int count) { +    default ItemStack removeItem(int slot, int count) { 
-        ItemStack result = Inventories.splitStack(getItems(), slot, count);+        ItemStack result = ContainerHelper.removeItem(getItems(), slot, count);
         if (!result.isEmpty()) {         if (!result.isEmpty()) {
-            markDirty();+            setChanged();
         }         }
         return result;         return result;
     }     }
 +    
     /**     /**
-     * Removes the current stack in the {@code slot} and returns it.+     * Removes all items from a container slot. 
 +     @param slot The slot to remove from.
      */      */
     @Override     @Override
-    default ItemStack removeInvStack(int slot) { +    default ItemStack removeItemNoUpdate(int slot) { 
-        return Inventories.removeStack(getItems(), slot);+        return ContainerHelper.takeItem(getItems(), slot);
     }     }
 +    
     /**     /**
-     * Replaces the current stack in the {@code slotwith the provided stack. +     * Replaces the current stack in a container slot with the provided stack. 
-     <p>If the stack is too big for this inventory ({@link Inventory#getInvMaxStackAmount()}), +     @param slot  The container slot of which to replace the itemstack. 
-     * it gets resized to this inventory's maximum amount.+     * @param stack The replacing itemstack. If the stack is too big for 
 +                  this container ({@link Container#getMaxStackSize()}), 
 +                  it gets resized to this container's maximum amount.
      */      */
     @Override     @Override
-    default void setInvStack(int slot, ItemStack stack) {+    default void setItem(int slot, ItemStack stack) {
         getItems().set(slot, stack);         getItems().set(slot, stack);
-        if (stack.getCount() > getInvMaxStackAmount()) { +        if (stack.getCount() > stack.getMaxStackSize()) { 
-            stack.setCount(getInvMaxStackAmount());+            stack.setCount(stack.getMaxStackSize());
         }         }
     }     }
 +    
     /**     /**
-     * Clears {@linkplain #getItems() the item list}}.+     * Clears the container.
      */      */
     @Override     @Override
-    default void clear() {+    default void clearContent() {
         getItems().clear();         getItems().clear();
     }     }
 +    
 +    /**
 +     * Marks the state as dirty.
 +     * Must be called after changes in the container, so that the game can properly save
 +     * the container contents and notify neighboring blocks of container changes.
 +     */ 
     @Override     @Override
-    default void markDirty() {+    default void setChanged() {
         // Override if you want behavior.         // Override if you want behavior.
     }     }
 +    
 +    /**
 +     * @return true if the player can use the container, false otherwise.
 +     */ 
     @Override     @Override
-    default boolean canPlayerUseInv(PlayerEntity player) {+    default boolean stillValid(Player player) {
         return true;         return true;
     }     }
 } }
 </code> </code>
-Now in your ''BlockEntity'' Implement ''ImplementedInventory'',  + 
-and provide it with an instance of ''DefaultedList<ItemStack> items'' that stores the items. +Now in your ''BlockEntity'', implement ''ImplementedContainer'', and provide it with an instance of ''NonNullList<ItemStack> items'' that stores the items. For this example we'll store a maximum of 2 items in the container
-For this example we'll store a maximum of 2 items in the inventory+<code java DemoBlockEntity.java> 
-<code java> +public class DemoBlockEntity extends BlockEntity implements ImplementedContainer 
-public class DemoBlockEntity extends BlockEntity implements ImplementedInventory +    private final NonNullList<ItemStack> items = NonNullList.withSize(2, ItemStack.EMPTY);
-    private final DefaultedList<ItemStack> items = DefaultedList.ofSize(2, ItemStack.EMPTY);+
  
     @Override     @Override
-    public DefaultedList<ItemStack> getItems() {+    public NonNullList<ItemStack> getItems() {
         return items;         return items;
     }     }
-    ...+    [...]
  
 } }
  
 </code> </code>
--->>>>>>>Remember markDirty() <<<<<<<<<--  +We're also gonna need to save the inventories to NBT and load it from there. ''Container'' has helper methods that make this very easy: 
-We're also gonna need to save the inventories to tag and load it from there.  +<code java DemoBlockEntity.java> 
-''Inventories'' has helper methods that makes this very easy: +public class DemoBlockEntity extends BlockEntity implements ImplementedContainer 
-<code java> +    [...]
-public class DemoBlockEntity extends BlockEntity implements ImplementedInventory +
-    ...+
     @Override     @Override
-    public void fromTag(CompoundTag tag) { +    public void loadAdditional(ValueInput valueInput) { 
-        super.fromTag(tag); +        super.loadAdditional(valueInput); 
-        Inventories.fromTag(tag,items);+        items.clear(); 
 +        ContainerHelper.loadAllItems(valueInput, items);
     }     }
  
     @Override     @Override
-    public CompoundTag toTag(CompoundTag tag) { +    public void saveAdditional(ValueOutput valueOutput) { 
-        Inventories.toTag(tag,items); +        super.saveAdditional(valueOutput); 
-        return super.toTag(tag);+        ContainerHelper.saveAllItems(valueOutput, items);
     }     }
 } }
 </code> </code>
-===== Extracting and inserting from your inventory ===== + 
-Remember that the same thing can be done with any inventory...+===== Extracting and inserting from your container ===== 
 + 
 +In our block class, we'll override the ''onUse'' behavior to insert and extract items from our inventory. Note that this can be done to any ''Inventory'' instance, not just our own (so you could do the same thing to a chest block, for example). 
 + 
 +First we'll handle inserting into the container. The player will insert the item he is holding if he is holding one. It'll go into the first slot if it is empty, or to the second slot if the first one is empty, or if the second is empty too we'll print some information about the container.  
 + 
 +Note that we call ''copy()'' when inserting the ''ItemStack'' into the container so it doesn't get destroyed alongside the player's ''ItemStack''
 +<code java DemoBlock.java> 
 +public class DemoBlock extends BaseEntityBlock { 
 +    [...] 
 +    @Override 
 +    protected InteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { 
 +        if (level.isClient) return InteractionResult.SUCCESS; 
 +         
 +        if (!(level.getBlockEntity(pos) instanceof DemoBlockEntity blockEntity)) { 
 +            return InteractionResult.PASS; 
 +        } 
 + 
 +        if (!player.getItemInHand(hand).isEmpty()) { 
 +            // Check what is the first open slot and put an item from the player's hand there 
 +            if (blockEntity.getItem(0).isEmpty()) { 
 +                // Put the stack the player is holding into the container 
 +                blockEntity.setItem(0, player.getItemInHand(hand).copy()); 
 +                // Remove the stack from the player's hand 
 +                player.getItemInHand(hand).setCount(0); 
 +            } else if (blockEntity.getItem(1).isEmpty()) { 
 +                blockEntity.setItem(1, player.getItemInHand(hand).copy()); 
 +                player.getItemInHand(hand).setCount(0); 
 +            } else { 
 +                // If the container is full we'll notify the player 
 +                player.displayClientMessage(Component.literal("The inventory is full! The first slot holds ") 
 +                    .append(blockEntity.getItem(0).getItemName()) 
 +                    .append(" and the second slot holds ") 
 +                    .append(blockEntity.getItem(1).getItemName())); 
 +            } 
 +        }  
 +        return InteractionResult.SUCCESS; 
 +    } 
 +
 +</code> 
 + 
 + 
 +We'll have the opposite behavior when the player is not holding an item. We'll take the item from the second slot, and then the first one if the second is empty.  
 +If the first is empty we pass it to default behavior. 
 +<code java DemoBlock.java> 
 +public class DemoBlock extends BaseEntityBlock { 
 +    [...] 
 +    @Override 
 +    protected InteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { 
 +        ... 
 +        if (!player.getItemInHand(hand).isEmpty()) { 
 +            ... 
 +        } else { 
 +            // If the player is not holding anything we'll get give him the items in the block entity one by one 
 + 
 +            // Find the first slot that has an item and give it to the player 
 +            if (!blockEntity.getItem(1).isEmpty()) { 
 +                // Give the player the stack in the container 
 +                player.getInventory().placeItemBackInInventory(blockEntity.getItem(1)); 
 +                // Remove the stack from the container 
 +                blockEntity.removeItem(1); 
 +            } else if (!blockEntity.getItem(0).isEmpty()) { 
 +                player.getInventory().placeItemBackInInventory(blockEntity.getItem(0)); 
 +                blockEntity.removeItem(0); 
 +            } else { 
 +                return InteractionResult.TRY_WITH_EMPTY_HAND; 
 +            } 
 +        } 
 +         
 +        return InteractionResult.SUCCESS; 
 +    } 
 +
 +</code> 
 + 
 +===== Implementing WorldlyContainer ===== 
 +If you want to have different logic based on what side things (hopper or other mods) interact with your block you need to implement ''WorldlyContainer''. If say you wanted to make it so you cannot insert from the upper side of the block, you would do this: 
 + 
 +<code java DemoBlockEntity.java> 
 +public class DemoBlockEntity extends BlockEntity implements ImplementedContainer, WorldlyContainer{ 
 +    [...] 
 +    @Override 
 +    public int[] getSlotsForFace(Direction side) { 
 +        // Just return an array of all slots 
 +        return IntStream.of(getItems().size()).toArray(); 
 +    } 
 + 
 +    @Override 
 +    public boolean canPlaceItemThroughFace(int slot, ItemStack stack, Direction direction) { 
 +        return direction != Direction.UP; 
 +    } 
 + 
 +    @Override 
 +    public boolean canTakeItemThroughFace(int slot, ItemStack stack, Direction direction) { 
 +        return true; 
 +    } 
 +
 +</code> 
tutorial/inventory.1565105491.txt.gz · Last modified: 2019/08/06 15:31 by fudge