====== Creating a Container Block======
In this tutorial we will create simple storage block similar to a dispenser, explaining how to build a user interface with the ''ScreenHandler'' API from Fabric and Vanilla Minecraft along the way.
Let us first explain some vocabulary:
**Screenhandler:**
A ''ScreenHandler'' is a class responsible for synchronizing inventory contents between the client and the server. It can sync additional integer values like furnace progress as well, which will be showed in the next tutorial.
Our subclass will have two constructors here: one will be used on the server side and will contain the real ''Inventory'' and another one will be used on the client side to hold the ''ItemStack''s and synchronize them.
**Screen:**
The ''Screen'' class only exists on the client and will render the background and other decorations for your ''ScreenHandler''.
===== Block and BlockEntity classes =====
First we need to create the ''Block'' and its ''BlockEntity''.
public class BoxBlock extends BlockWithEntity {
protected BoxBlock(Settings settings) {
super(settings);
}
// This method is required since 1.20.5.
@Override
protected MapCodec extends BoxBlock> getCodec() {
return createCodec(BoxBlock::new);
}
@Override
public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {
return new BoxBlockEntity(pos, state);
}
@Override
public BlockRenderType getRenderType(BlockState state) {
// With inheriting from BlockWithEntity this defaults to INVISIBLE, so we need to change that!
return BlockRenderType.MODEL;
}
@Override
public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit) {
if (!world.isClient) {
// This will call the createScreenHandlerFactory method from BlockWithEntity, which will return our blockEntity casted to
// a namedScreenHandlerFactory. If your block class does not extend BlockWithEntity, it needs to implement createScreenHandlerFactory.
NamedScreenHandlerFactory screenHandlerFactory = state.createScreenHandlerFactory(world, pos);
if (screenHandlerFactory != null) {
// With this call the server will request the client to open the appropriate Screenhandler
player.openHandledScreen(screenHandlerFactory);
}
}
return ActionResult.SUCCESS;
}
// This method will drop all items onto the ground when the block is broken
@Override
public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {
if (state.getBlock() != newState.getBlock()) {
BlockEntity blockEntity = world.getBlockEntity(pos);
if (blockEntity instanceof BoxBlockEntity boxBlockEntity) {
ItemScatterer.spawn(world, pos, boxblockEntity);
// update comparators
world.updateComparators(pos,this);
}
super.onStateReplaced(state, world, pos, newState, moved);
}
}
@Override
public boolean hasComparatorOutput(BlockState state) {
return true;
}
@Override
public int getComparatorOutput(BlockState state, World world, BlockPos pos) {
return ScreenHandler.calculateComparatorOutput(world.getBlockEntity(pos));
}
}
Now we will create our ''BlockEntity'', it will use the ''ImplementedInventory'' interface from the [[tutorial:inventory|Inventory Tutorial]].
public class BoxBlockEntity extends BlockEntity implements NamedScreenHandlerFactory, ImplementedInventory {
private final DefaultedList inventory = DefaultedList.ofSize(9, ItemStack.EMPTY);
public BoxBlockEntity(BlockPos pos, BlockState state) {
super(ExampleMod.BOX_BLOCK_ENTITY, pos, state);
}
// From the ImplementedInventory Interface
@Override
public DefaultedList getItems() {
return inventory;
}
// These Methods are from the NamedScreenHandlerFactory Interface
// createMenu creates the ScreenHandler itself
// `getDisplayName` will Provide its name which is normally shown at the top
@Override
public ScreenHandler createMenu(int syncId, PlayerInventory playerInventory, PlayerEntity player) {
// We provide *this* to the screenHandler as our class Implements Inventory
// Only the Server has the Inventory at the start, this will be synced to the client in the ScreenHandler
return new BoxScreenHandler(syncId, playerInventory, this);
}
@Override
public Text getDisplayName() {
// for 1.19+
return Text.translatable(getCachedState().getBlock().getTranslationKey());
// for earlier versions
// return new TranslatableText(getCachedState().getBlock().getTranslationKey());
}
// For the following two methods, for earlier versions, remove the parameter `registryLookup`.
@Override
public void readNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) {
super.readNbt(nbt, registryLookup);
Inventories.readNbt(nbt, this.inventory, registryLookup);
}
@Override
public NbtCompound writeNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup) {
super.writeNbt(nbt, registryLookup);
Inventories.writeNbt(nbt, this.inventory, registryLookup);
return nbt;
}
}
===== Registering Block, BlockItem and BlockEntity =====
In this example, the block, block item and block entity are directly registered in ''ExampleMod'' class. You may also need to consider placing them into separate classes (see [[blocks]] and [[blockentity]]) when actually developing mods.
public class ExampleMod implements ModInitializer {
// For versions before 1.21, replace `Identifier.of` with `new Identifier`.
public static final Block BOX_BLOCK = Registry.register(Registries.BLOCK, Identifier.of("tutorial", "box_block"),
new BoxBlock(AbstractBlock.Settings.copyOf(Blocks.CHEST)));
public static final BlockItem BOX_BLOCK_ITEM = Registry.register(Registries.ITEM, Identifier.of("tutorial", "block"),
new BlockItem(BOX_BLOCK, new Item.Settings()));
public static final BlockEntityType BOX_BLOCK_ENTITY = Registry.register(Registry.BLOCK_ENTITY_TYPE, Identifier.of("tutorial", "box_block"),
BlockEntityType.Builder.create(BoxBlockEntity::new, BOX_BLOCK).build());
// In 1.17 use FabricBlockEntityTypeBuilder instead of BlockEntityType.Builder
// public static final BlockEntityType BOX_BLOCK_ENTITY = Registry.register(Registry.BLOCK_ENTITY_TYPE, new Identifier("tutorial", "box_block"),
// FabricBlockEntityTypeBuilder.create(BoxBlockEntity::new, BOX_BLOCK).build(null));;
@Override
public void onInitialize() {
}
}
===== ScreenHandler and Screen =====
As explained earlier, we need both a ''ScreenHandler'' and a ''HandledScreen'' to display and sync the GUI. ''ScreenHandler'' classes are used to synchronize GUI state between the server and the client. ''HandledScreen'' classes are fully client-sided and are responsible for drawing GUI elements.
public class BoxScreenHandler extends ScreenHandler {
private final Inventory inventory;
// This constructor gets called on the client when the server wants it to open the screenHandler,
// The client will call the other constructor with an empty Inventory and the screenHandler will automatically
// sync this empty inventory with the inventory on the server.
public BoxScreenHandler(int syncId, PlayerInventory playerInventory) {
this(syncId, playerInventory, new SimpleInventory(9));
}
// This constructor gets called from the BlockEntity on the server without calling the other constructor first, the server knows the inventory of the container
// and can therefore directly provide it as an argument. This inventory will then be synced to the client.
public BoxScreenHandler(int syncId, PlayerInventory playerInventory, Inventory inventory) {
super(ExampleMod.BOX_SCREEN_HANDLER, syncId);
checkSize(inventory, 9);
this.inventory = inventory;
// some inventories do custom logic when a player opens it.
inventory.onOpen(playerInventory.player);
// This will place the slot in the correct locations for a 3x3 Grid. The slots exist on both server and client!
// This will not render the background of the slots however, this is the Screens job
int m;
int l;
// Our inventory
for (m = 0; m < 3; ++m) {
for (l = 0; l < 3; ++l) {
this.addSlot(new Slot(inventory, l + m * 3, 62 + l * 18, 17 + m * 18));
}
}
// The player inventory
for (m = 0; m < 3; ++m) {
for (l = 0; l < 9; ++l) {
this.addSlot(new Slot(playerInventory, l + m * 9 + 9, 8 + l * 18, 84 + m * 18));
}
}
// The player Hotbar
for (m = 0; m < 9; ++m) {
this.addSlot(new Slot(playerInventory, m, 8 + m * 18, 142));
}
}
@Override
public boolean canUse(PlayerEntity player) {
return this.inventory.canPlayerUse(player);
}
// Shift + Player Inv Slot
@Override
public ItemStack quickMove(PlayerEntity player, int invSlot) {
ItemStack newStack = ItemStack.EMPTY;
Slot slot = this.slots.get(invSlot);
if (slot != null && slot.hasStack()) {
ItemStack originalStack = slot.getStack();
newStack = originalStack.copy();
if (invSlot < this.inventory.size()) {
if (!this.insertItem(originalStack, this.inventory.size(), this.slots.size(), true)) {
return ItemStack.EMPTY;
}
} else if (!this.insertItem(originalStack, 0, this.inventory.size(), false)) {
return ItemStack.EMPTY;
}
if (originalStack.isEmpty()) {
slot.setStack(ItemStack.EMPTY);
} else {
slot.markDirty();
}
}
return newStack;
}
}
public class BoxScreen extends HandledScreen {
// A path to the gui texture. In this example we use the texture from the dispenser
private static final Identifier TEXTURE = Identifier.ofVanilla("textures/gui/container/dispenser.png");
// For versions before 1.21:
// private static final Identifier TEXTURE = new Identifier("minecraft", "textures/gui/container/dispenser.png");
public BoxScreen(BoxScreenHandler handler, PlayerInventory inventory, Text title) {
super(handler, inventory, title);
}
@Override
protected void drawBackground(DrawContext context, float delta, int mouseX, int mouseY) {
RenderSystem.setShader(GameRenderer::getPositionTexProgram);
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.setShaderTexture(0, TEXTURE);
int x = (width - backgroundWidth) / 2;
int y = (height - backgroundHeight) / 2;
context.drawTexture(TEXTURE, x, y, 0, 0, backgroundWidth, backgroundHeight);
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
renderBackground(context, mouseX, mouseY, delta);
super.render(context, mouseX, mouseY, delta);
drawMouseoverTooltip(context, mouseX, mouseY);
}
@Override
protected void init() {
super.init();
// Center the title
titleX = (backgroundWidth - textRenderer.getWidth(title)) / 2;
}
}
===== Registering our Screen and ScreenHandler =====
As screens are a client-only concept, we can only register them on the client.
@Environment(EnvType.CLIENT)
public class ExampleClientMod implements ClientModInitializer {
@Override
public void onInitializeClient() {
HandledScreens.register(ExampleMod.BOX_SCREEN_HANDLER, BoxScreen::new);
}
}
Don't forget to register this entrypoint in ''fabric.mod.json'' if you haven't done it yet:
{
/* ... */
"entrypoints": {
/* ... */
"client": [
"net.fabricmc.example.ExampleModClient"
]
},
/* ... */
}
''ScreenHandler''s exist both on the client and on the server and therefore have to be registered on both.
public class ExampleMod implements ModInitializer {
[...]
public static final ScreenHandlerType BOX_SCREEN_HANDLER = Registry.register(Registries.SCREEN_HANDLER, Identifier.of("tutorial", "box_block"), new ScreenHandlerType<>(BoxScreenHandler::new, FeatureSet.empty()));
@Override
public void onInitialize() {
[...]
}
}
===== Result =====
You have now created your own container Block, you could easily change it to contain a smaller or bigger Inventory. Maybe even apply a texture :-P
{{:tutorial:bildschirmfoto_vom_2020-08-14_18-32-07.png?nolink&400|}}
===== Further Reading =====
* [[tutorial:extendedscreenhandler|Syncing Custom Data with Extended ScreenHandlers when screen is opened]]
* [[tutorial:propertydelegates|Syncing Integers continuously with PropertyDelegates]]
An example mod using the ''ScreenHandler'' API: [[https://github.com/FabricMC/fabric/tree/1.16/fabric-screen-handler-api-v1/src/testmod|ExampleMod on Github]].