Skip to content

Mods for NeoForge and Fabric

Blocks and items

New blocks, items and other content the client has to know need a mod on the player's side. Once any plugin adds to one of these registries, vanilla clients are refused: minecraft:block, minecraft:block_entity_type, minecraft:data_component_type (only types with a network codec), minecraft:entity_type, minecraft:item, minecraft:menu, minecraft:particle_type or minecraft:custom_stat. Players then need NeoForge or Fabric with the matching mod, or the Obsidian client with the mod; the mods may load in any order. For server-side plugins that vanilla clients can join, see Gameplay and the world.

ObsidianMod is a working mod built on this API alone: its tick counter is a block with state, hooks, a block entity, redstone, light and a loot table together.

Build and pack a mod as described in Building and packing. The archive holds the mod and its own libraries; the host provides the API and NBT. Reference engine projects with Private="false" and NuGet packages with ExcludeAssets="runtime". A mod that uses NBT types needs a direct Obsidian.Nbt reference. Building against an engine checkout may need its vanilla assets generated first (see the build notes).

Blocks in code

public override void ConfigureRegistry(IPluginRegistry registry)
{
    var lamp = registry.RegisterBlock("ruby:lamp", new BlockProperties
    {
        StateProperties = [StateProperty.Bool("lit"), StateProperty.Int("power", 0, 3)],
        DefaultState = new Dictionary<string, string> { ["lit"] = "false" },
        Hardness = 0.5f,
        LightEmission = 7,
        Behavior = new LampBehavior()
    });

    var lit = lamp.With(lamp.DefaultState, "lit", "true");
}

The block's identifier is in the plugin's namespace. Unless Item is null, an item with the same identifier places the block, and drops when the block has no loot table.

  • LightEmission is every state's light level. StateLightEmission gives each state its own, from its property values (StateLightEmission = values => values["lit"] == "true" ? 15 : 0); changing to a state with another level relights the area. Light level, opacity and collision can't change on hot reload: the old settings stay until a restart.
  • A client mod declares the same properties and values in the same order: bool properties are true, false, int ones ascending, enum ones in the order given.
  • A block is a full block to collide with and aim at, unless StateShapes gives a state its own BlockShapes(collision, outline) in blocks (see Shapes and multipart blocks), or null for a full block:
StateShapes = values =>
{
    List<BoundingBox> boxes = [new(new VectorD(0.25, 0, 0.25), new VectorD(0.75, 1, 0.75))];
    if (values["north"] == "true")
        boxes.Add(new(new VectorD(0.375, 0.5, 0), new VectorD(0.625, 0.875, 0.25)));

    return new BlockShapes(boxes, boxes);
}

StateLightEmission and StateShapes are asked once per state as the block registers, on the server and on the Obsidian client, which both run ConfigureRegistry. Collision, mob navigation, aiming and the client's movement prediction use the shapes, and a block entity's own shapes win where it has some. The shapes also decide which faces hold attached blocks, as vanilla's do (SupportType.Full, Center and Rigid). Opaque still decides light and face culling, and a block without HasCollision has no collision boxes. Connected Obsidian clients keep the shapes their copy of the mod gave until they reload their mods.

Structures rotate and mirror the block by its properties named like vanilla's: facing, axis, rotation (0 to 15, like a standing sign's) and north, east, south and west (a fence's connections). Other properties are kept, and a block without the turned state (a facing without east, say) stays as it is.

Block hooks

public sealed class PipeBehavior : IBlockBehavior
{
    // The block's type, from RegisterBlock.
    public BlockType Pipe { get; set; } = null!;

    public IBlock? GetStateForPlacement(BlockPlaceContext context) =>
        this.Pipe.With(context.Block, "facing", context.NearestLookDirection.Opposite().ToString().ToLowerInvariant());

    public void OnPlaced(BlockPlacedContext context) =>
        context.Level.ScheduleTick(context.Position, context.State, delay: 4);

    public void NeighborChanged(NeighborChangedContext context)
    {
        // It breaks when the block below it goes.
        if (context.Level.GetBlock(context.Position + Vector.Down).IsAir)
            context.Level.DestroyBlock(context.Position, dropItems: true);
    }

    public void Tick(BlockContext context) => context.Level.ScheduleTick(context.Position, context.State, delay: 4);
}

A block's Behavior gets vanilla's block hooks; each defaults to doing nothing:

  • UseAsync: a player uses the block (right-clicks it without sneaking), before the item in their hand.
  • GetStateForPlacement: the state a player places the block in. The BlockPlaceContext gives the player, hand and item, the clicked block and face, where on it they clicked (ClickedAt, 0 to 1 on each axis), where the block goes, and the player's HorizontalDirection and NearestLookDirection. Null rejects the placement.
  • OnPlaced: the block was placed, or changed state (OldState says which).
  • OnRemoved: another block replaced it.
  • NeighborChanged: a neighbour changed (SourcePosition, and SourceBlock, the state it replaced).
  • UpdateShape: the block's state after the neighbour in Direction became NeighborState: a fence's connections, say, or air for a block that lost its support, which destroys it.
  • Tick: a tick scheduled with ScheduleTick came due.
  • RandomTick: a random tick, for blocks registered with RandomlyTicks = true. Near players, each block gets one about once every 68 seconds at the default speed (see Saplings).
  • EntityInsideAsync and SteppedOnAsync: each tick an entity's box overlaps the block, or the entity stands on it.

The hooks with a Level run synchronously while the level's block updates wait for them, so keep them short. Read and change blocks through that IBlockLevel (GetBlock, IsFaceSturdy, SetBlock, RemoveBlock, DestroyBlock, ScheduleTick, HasScheduledTick, UpdateNeighbors, its redstone signals and the level's Random), not through ILevel's asynchronous methods.

  • Neighbour and shape updates caused inside a neighbour or shape hook run after it returns, in vanilla's order. Placement and removal hooks run during the block change, so a change inside them can run further hooks before they return: keep such chains bounded.
  • IBlockLevel.GetBlockEntity reads the block's block entity, but a hook may run on a player's thread while block entities tick. Only read what's safe to read (a field written whole), and change the block entity on its own tick.
  • A hook that throws is logged, and the level goes on. No hook runs once the plugin starts unloading.

IsFaceSturdy(position, face, support = SupportType.Full), on IBlockLevel and ILevel, asks whether a block's face can hold an attachment. The face is the queried block's: for a bud hanging below a block, ask for that block's BlockFace.Down. It returns false outside the build range or loaded chunks, and never loads a chunk.

Block changes, scheduled ticks and the placement event work the same for vanilla's blocks and mods' (see Block updates).

Redstone hooks

public sealed class SensorBehavior : IBlockBehavior
{
    // The block's type, from RegisterBlock, with a "powered" property.
    public BlockType Sensor { get; set; } = null!;

    // It powers every side while powered, like a lever; dust connects to it.
    public bool IsSignalSource(IBlock state) => true;

    public int GetSignal(SignalContext context) => this.Sensor.GetValue(context.State, "powered") == "true" ? 15 : 0;

    // Comparators facing away from it read 1 to 15.
    public bool HasAnalogOutput(IBlock state) => true;

    public int GetAnalogOutput(SignalContext context) => 8;

    // It turns on and off with the power it gets, like a lamp, and tells its neighbours.
    public void NeighborChanged(NeighborChangedContext context)
    {
        var powered = context.Level.HasNeighborSignal(context.Position);
        var state = this.Sensor.With(context.State, "powered", powered ? "true" : "false");
        context.Level.SetBlock(context.Position, state);
    }
}

How blocks read power is described in Redstone.

A plugin block takes part through its behaviour's hooks, which default to giving no power:

  • IsSignalSource: whether it gives power. Dust connects to it from every side.
  • GetSignal and GetDirectSignal: its weak and strong power toward the neighbour asking (SignalContext.Direction points from that neighbour to it). They run whenever a neighbour reads its power, so keep them a quick read of the state.
  • HasAnalogOutput and GetAnalogOutput: what a comparator facing away from it reads, like a container's fullness.

When its power changes, tell the neighbours with IBlockLevel.UpdateNeighbors; a block change with neighbour updates does it for you. For strong power, update the neighbours of the block it powers through too, as levers do. Power that changes outside the block's hooks (from a block entity's tick, say) uses ILevel.UpdateNeighbors(position, source). Comparators are told by block changes and by the block entity's SetChanged; otherwise call IBlockLevel.UpdateAnalogOutput.

React to power in NeighborChanged, which runs when the power around the block may have changed. While the plugin is unloaded or unloading, its blocks give no power and no analog output, and the circuits around them update as it unloads and loads again.

Saplings

registry.RegisterBlock("ruby:ruby_sapling", new BlockProperties
{
    StateProperties = [StateProperty.Int("stage", 0, 1)],
    HasCollision = false,
    Opaque = false,
    Hardness = 0,
    TreeGrower = new TreeGrower
    {
        Tree = "ruby:ruby_tree",
        MegaTree = "ruby:huge_ruby_tree",
        SecondaryTree = "minecraft:fancy_oak",
        SecondaryChance = 0.1f
    }
});

A block with a TreeGrower is a sapling, and grows like vanilla's. With a stage property the first step sets it to 1 and the second grows the tree; without one, every step grows it.

Its trees are configured features named by identifier: vanilla's, or ones from worldgen/configured_feature files (see World generation features). They're looked up as the sapling grows, so a reload or override applies at once. Four saplings in a square grow the MegaTree, a flower within two blocks makes it grow its Flowers tree, and SecondaryChance picks the secondary tree.

A sapling whose feature is missing or can't be placed stays a sapling, as does one whose tree would reach a chunk that isn't loaded. Saplings stop growing while their plugin is unloaded.

Block loot

A plugin block ruby:ore uses the loot table ruby:blocks/ore, loaded from data/ruby/loot_table/blocks/ore.json:

{
  "type": "minecraft:block",
  "pools": [
    {
      "rolls": 1,
      "entries": [
        {
          "type": "minecraft:item",
          "name": "ruby:gem",
          "functions": [
            { "function": "minecraft:set_count", "count": 2 },
            { "function": "minecraft:explosion_decay" }
          ]
        }
      ]
    }
  ]
}

BlockProperties.LootTable names another table, such as ruby:rewards/ore; JSON block definitions use lootTable. Without an explicit table, a plugin block whose default table is absent drops its own item. An explicit table that is missing, or a table with no pools, drops nothing.

A plugin's block entity adds what its CollectComponents sets, in the plugin's component types, and reads it back in ApplyComponents (see Block entities); a plugin block without a loot table drops its item with those values.

When a break needs a plugin block entity's components, the block breaks on the level's next tick.

How blocks drop and loot tables are read is described in Block drops.

Block sounds

Sound events are registered with RegisterSound (see Sounds), like the chime below.

Set BlockProperties.SoundType to a BlockSoundProperties. Break, Step, Place, Hit and Fall are sound events; Volume and Pitch default to 1. Build it with vanilla identifiers, registered events, or a mix:

registry.RegisterBlock("ruby:machine", new BlockProperties
{
    SoundType = BlockSoundProperties.Stone with
    {
        Break = chime,
        Place = chime,
        Volume = 0.7f
    }
});

Declare the same type on both sides. The client plays its own hit, step, placement and break sounds from it, and the server sends placement and break sounds to the other players nearby. Unloading resets the plugin's blocks to stone sounds. Fall is accepted, but the client doesn't play landing sounds yet.

Portal blocks

A portal (see Travel and portals) can fill with a block of the mod's own. That makes its portals unambiguous and keeps them inert when the plugin unloads:

var frame = registry.RegisterBlock("ruby:portal_frame");
var gateway = registry.RegisterBlock("ruby:crystal_portal", new BlockProperties
{
    StateProperties = [StateProperty.Enum("axis", "x", "z")],
    HasCollision = false,
    Opaque = false
});

var portal = registry.RegisterPortal("ruby:crystal_gate", new PortalProperties
{
    IsFrame = frame.Is,
    FrameBlock = frame.DefaultState,
    PortalBlock = gateway.DefaultState,
    Igniter = ItemsRegistry.Diamond,
    WaitTicks = 40,
    ResolveTarget = level =>
    {
        var world = level is IDimension child ? child.ParentWorld : level as IWorld;
        return level.DimensionName == "ruby:crystal_world"
            ? world
            : world?.GetLevel("ruby:crystal_world");
    }
});

Blocks from JSON

Each data/<namespace>/blocks/<name>.json in the plugin's data folder is a block, shaped like an entry of vanilla's blocks report:

{
  "properties": {
    "lit": ["true", "false"],
    "power": ["0", "1", "2", "3"],
    "color": ["red", "green"]
  },
  "default": { "lit": "false" },
  "hardness": 0.5,
  "lightEmission": 7,
  "behavior": "Ruby.LampBehavior",
  "item": { "maxStackSize": 16 }
}

True and false make a bool property and consecutive numbers an int one; anything else is an enum property in the order listed. The other keys are BlockProperties' in camel case (hasCollision, opaque, hardness, explosionResistance, requiresCorrectTool, lightEmission, lootTable). behavior is an IBlockBehavior type's full name, treeGrower makes a sapling ({"tree": "ruby:ruby_tree"}), and item is false for a block without an item.

A source generator makes a RubyBlocks class (from the namespace) in the plugin assembly's namespace: a property per block, a typed state per block with properties (RubyBlocks.LampState, with From(IBlock) and ToBlock()), and enums for enum properties. Register them from ConfigureRegistry:

RubyBlocks.Register(registry);
var state = new RubyBlocks.LampState(Lit: true, Power: 2, Color: RubyBlocks.LampColor.Green).ToBlock();

Obsidian.MSBuild gives the data files to the generator; without it, add the data folder's files as AdditionalFiles.

Items

var pickaxe = registry.RegisterItem("ruby:ruby_pickaxe", new ItemProperties
{
    MaxStackSize = 1,
    MaxDamage = 900,
    Enchantable = 12,
    Tool = ComponentBuilder.Tool with
    {
        Rules =
        [
            new ToolRule
            {
                Blocks = new IdSet { Type = 0, TagName = "minecraft:incorrect_for_iron_tool" },
                CorrectDropForBlocks = false
            },
            new ToolRule
            {
                Blocks = new IdSet { Type = 0, TagName = "minecraft:mineable/pickaxe" },
                Speed = 7,
                CorrectDropForBlocks = true
            }
        ]
    },
    AttributeModifiers =
    [
        new AttributeModifier
        {
            Id = AttributeIds.AttackDamage,
            Name = "minecraft:base_attack_damage",
            Value = 4,
            Operation = AttributeOperation.Add,
            Slot = AttributeSlot.MainHand
        }
    ],
    Behavior = new RubyPickaxeBehavior()
});

registry.RegisterItem("ruby:ruby_apple", new ItemProperties
{
    Food = ComponentBuilder.Food with { Nutrition = 4, SaturationModifier = 0.3f }
});

registry.RegisterItem("ruby:ruby_helmet", new ItemProperties
{
    MaxStackSize = 1,
    MaxDamage = 300,
    Equippable = ComponentBuilder.Equippable with { Slot = EquipmentSlot.Helmet },
    AttributeModifiers =
    [
        new AttributeModifier
        {
            Id = AttributeIds.Armor,
            Name = "minecraft:armor.helmet",
            Value = 3,
            Operation = AttributeOperation.Add,
            Slot = AttributeSlot.Head
        }
    ]
});

A plugin's item is in its namespace and keeps its id across reloads. Unloading the plugin drops its behaviour but not the item, its properties or its stacks.

Default components. MaxStackSize, MaxDamage, Enchantable, and Tool, Food, Consumable, Equippable and AttributeModifiers built from ComponentBuilder with a with expression, are the item's default components, like a vanilla item's. Every stack has them unless it sets or removes its own. They aren't sent or saved with stacks, since the client mod registers the same item with the same properties. Obsidian honours them as it does vanilla's:

  • Tool: its rules (the first match decides) give the mining speed and whether the item is the correct tool for a block's drops, by block tag (Type = 0 and TagName) or by block ids. Breaking a block that doesn't break instantly wears the item. Mining speed is up to the client: the server doesn't time breaking.
  • Food: a player eats the item by using it (at any hunger with CanAlwaysEat). Consumable sets how it's eaten and the effects it gives; it defaults to vanilla's food and does nothing without Food. Its effects must be ComponentConsumeEffect or EffectWithProbability values; registration rejects other IConsumeEffect types.
  • Equippable: a player wears the item in its slot by using it or placing it in the armour slot. ComponentBuilder.Equippable has vanilla's defaults; set the slot.
  • AttributeModifiers: what the item adds while it's in the modifier's slot, by attribute id (AttributeIds). A player gets every one (see Attributes); mobs apply only their equipment's armour, toughness and knockback resistance.

Changing an item's defaults in a reload reaches stacks made, loaded or received afterwards.

Item hooks. An item's Behavior (an IItemBehavior) gets these hooks, each doing nothing by default:

  • UseAsync: a player uses the item without aiming at a block (right-clicks the air), before vanilla's handling (eating, equipping). Returning true handles the use.
  • UseOnBlockAsync: a player uses the item on a block, after the block's own use and before the item places a block.
  • UseOnEntityAsync: a player uses the item on a living entity (ItemUseOnEntityContext.Entity). It runs after the entity's own interaction (trading, feeding an animal, a plugin entity's IEntityBehavior.InteractAsync), and only when that didn't take it. Rideable mobs give the item its use before the player mounts, so it may run twice in one use when it returns false. In creative mode the context's Stack is a copy.
  • InventoryTickAsync: each tick, for every stack of the item in a player's inventory. The ItemInventoryTickContext gives the stack, its Slot (5 to 8 armour, 9 to 35 the main inventory, 36 to 44 the hotbar, 45 the off hand) and its EquipmentSlot (MainHand for the selected slot, IsSelected). It runs holding the inventory's lock: change the stack or inventory through their own members, and don't wait on anything that takes the lock, like a click. It may hurt or kill the holder. Inventories are only scanned while some item implements this hook, so leave it out when the item doesn't need it.

The use hooks run without the inventory lock, so they may hurt the player and wait. No hook starts once the plugin begins unloading, and one that throws is logged.

Item components

var charge = registry.RegisterComponentType(
    "ruby:charge",
    new ComponentCodec<int>(value => new NbtTag<int>("", value), tag => ((NbtTag<int>)tag).Value),
    new ComponentNetworkCodec<int>((writer, value) => writer.WriteVarInt(value), reader => reader.ReadVarInt()));

stack.Set(charge, stack.Get(charge) + 1);
if (stack.TryGet(charge, out var charges)) { /* ... */ }
stack.Remove(charge);

A data component type, like NeoForge's DataComponentType, holds a plugin's own data on stacks of any item. RegisterComponentType<TValue>(identifier, codec, networkCodec) returns a PluginComponentType<TValue>, which ItemStack.TryGet, Get, Set and Remove take. Values are immutable on the stack: Set a new one to change it. A plugin's type is never an item's default component.

  • Saving. The ComponentCodec saves a value as NBT, in the stack's components under the type's identifier beside vanilla's ({ id, count, components: { "minecraft:damage": 3, "ruby:charge": 2 } }).
  • Clients. With a ComponentNetworkCodec, the type is synced to NeoForge, Fabric and Obsidian clients, which must register the same type, and its values are sent with stacks. Like a plugin's items, it keeps vanilla clients out. Without a network codec, the type and its values stay on the server, and vanilla clients can still join. If NBT loses the distinctions the client hashes by (for click prediction), set ComponentNetworkCodec<TValue>.Hash, for example Hash = ComponentHash.Boolean for a boolean codec.
  • Unloading. The types keep their ids, and stacks keep their values as saved and still stack, but the values aren't sent to clients meanwhile. Through an unloaded plugin's handle, TryGet returns false, Get returns default and Set throws InvalidOperationException: use the new handle after a reload.
  • Block entities. A plugin's block entity keeps its data on its block's item through CollectComponents and ApplyComponents (see Block entities).

Stacks are saved with every vanilla component Obsidian models and the plugins' components, and keep NBT Obsidian doesn't understand. A few vanilla components that clients can send aren't modelled yet, such as weapon, tooltip_display, break_sound and mobs' */variant components; saving a stack leaves those out.

Creative tabs

registry.RegisterCreativeTab("ruby:rubies", new CreativeTabProperties
{
    Title = new ChatMessage { Translate = "itemGroup.ruby.rubies" },
    Icon = pickaxe,
    After = "minecraft:spawn_eggs",
    Items = [pickaxe],
    DisplayItems = () => RubyVariants.All.Select(variant => variant.Item)
});

registry.AddToCreativeTab("minecraft:tools_and_utilities", [pickaxe], after: ItemsRegistry.NetheritePickaxe);

Like a NeoForge mod's creative tabs, a plugin's are registered in ConfigureRegistry on both sides, and shown by the Obsidian client:

  • Tabs. RegisterCreativeTab(identifier, properties) adds a tab. Its Title is a translation key or plain text (ChatMessage.Simple), its Icon an item. It shows Items, then whatever DisplayItems gives each time the creative inventory opens. Tabs without items aren't shown. Tabs go after vanilla's in load order, or right after the tab named by After.
  • Adding to tabs. AddToCreativeTab(tab, items, after) adds items, the plugin's or vanilla's, to any tab, like NeoForge's BuildCreativeModeTabContentsEvent: at the end, or right after after's stacks.
  • Pages and search. Tabs are paged as on NeoForge: vanilla's fill the first page and plugins' follow. The search tab finds plugins' items too. An item in no tab isn't shown anywhere, so put it in one.
  • Servers. Creative tabs are the client's: the server only checks the registrations. A creative player can still take any item, a plugin's included.
  • Unloading. A plugin's tabs and additions are removed when it unloads and come back on reload.

Block entities

public sealed class Counter : BlockEntity
{
    private int ticks;

    protected override void Load(NbtCompound tag) =>
        this.ticks = tag.TryGetTagValue<int>("ticks", out var ticks) ? ticks : 0;

    protected override void Save(NbtCompound tag) => tag.Add(new NbtTag<int>("ticks", this.ticks));

    protected override ValueTask TickAsync()
    {
        this.ticks++;
        this.SetChanged();

        if (this.ticks % 20 == 0)
            this.SendUpdate();

        return ValueTask.CompletedTask;
    }

    protected override NbtCompound? GetUpdateData() => new() { new NbtTag<int>("ticks", this.ticks) };
}

var counter = registry.RegisterBlock("ruby:counter");
registry.RegisterBlockEntity<Counter>("ruby:counter", counter);

A block entity type, like NeoForge's BlockEntityType, gives the plugin's blocks a BlockEntity. The server creates one whenever one of its blocks is set, however it's set (a player, plugin code, world generation or a structure), and removes it when the block changes to one without its type, calling OnRemoved before a container's items drop. NeoForge and Fabric mods register the same type for the same blocks; the Obsidian client uses the same registration code.

  • Saving. The block entity is saved in its chunk, and Load reads back what Save wrote. Call SetChanged whenever the saved data changes; the level calls Save at the end of its tick.
  • Ticking. TickAsync runs once a tick while the chunk ticks (a player is within the simulation distance) and the block still has the type. Level is the level it's in, and BlockPosition its block.
  • Clients. GetUpdateData is what clients get: with the chunk, and at the end of a tick in which the block entity called SendUpdate. The Obsidian client keeps it as a snapshot that client shape providers read (see Client).
  • Client ticks. On the Obsidian client, a mod's block entity also gets a live instance of its class, loaded with Load from the update data each time an update arrives. Override ClientTick for what only players see (animations, particles, sounds): it runs 20 times a second on the game's thread while the world isn't paused, never on the server. With using Obsidian.API.Client, this.GetClientWorld() gives the client's read-only world during Load and ClientTick (see World queries in Client). On the client Level is null, and SetChanged and SendUpdate do nothing. The instance is dropped (IsRemoved) when its block changes, its chunk unloads, the player leaves or the mod unloads. One that throws isn't ticked again until the next update.
  • Items. CollectComponents(ItemStack item) sets values of the plugin's own component types on the block's item as the block breaks, and ApplyComponents(ItemStack item) reads them back when a player places the block with that item. A block without a loot table drops its item with those values; a loot table copies them with copy_components ("source": "block_entity", "include": ["ruby:ticks"]), as ObsidianMod's tick counter does. ApplyComponents runs before anything else reaches the new block entity, with Level still null. Neither runs while the plugin is unloading or gone, and creative pick-block with data isn't supported.
  • Lifecycle. Like NeoForge's onLoad and onChunkUnloaded, OnLoad runs once the block entity is live in its level, before its first TickAsync: after it's placed, its chunk loads or its plugin loads again. OnChunkUnloaded runs when its chunk unloads, after the chunk's final save: drop what refers to it there, and don't change the world. A block removal calls OnRemoved instead; a plugin unloading and the server stopping call neither.
  • Neighbours. ILevel.GetLoadedBlockEntity and ILevel.GetLoadedBlock read loaded chunks without loading anything (see Level tickers). In a block hook, IBlockLevel.GetBlockEntity and GetBlock already do.
  • Server. Server is the plugin's own IServer: a machine finds its plugin's recipes with this.Server?.FindRecipe(type, inputs). It's null while the block entity isn't in a level.
  • Threads. The server calls Load, Save, TickAsync, GetUpdateData, CollectComponents, OnLoad, OnRemoved and OnChunkUnloaded on the level's tick, one at a time, and saves and sends copies of what they returned, so the block entity needs no locks of its own. Only a new block entity's constructor and ApplyComponents may run on the placing thread.
  • Generation. In chunks still generating or loading, a plugin's block entities are kept as saved data until the chunk is complete.

A level ticker runs code once a tick for what spans many block entities, such as a network of cables (see Level tickers).

Shapes and multipart blocks

Override BlockEntity.GetShapes() to return a BlockShapes(collision, outline): two lists of BoundingBox in block-local coordinates, each box with positive volume inside the unit cube. Empty lists mean no collision or no selection; null keeps the state's usual shapes. Shapes that follow the block state alone need no block entity: see StateShapes in Blocks in code.

The server takes the shapes when it creates or loads the block entity, at the end of a tick after SetChanged or SendUpdate, and right after each break hook. For clients to see a change, call SetChanged and SendUpdate, put the data that decides the shapes in GetUpdateData, and register a client shape provider that builds the same shapes from it.

IBlockBehavior.BreakAsync(BlockBreakContext) runs before a player's break removes the block, after the break event allowed it. Its Hit is a BlockShapeHit(Position, ClickedAt, Face, BoxIndex) from the server's own raycast of the outline within the player's reach; BoxIndex is the nearest box hit, in the outline list's order. A miss or a block in the way prevents the hook and the break. BlockUseContext.ClickedAt is the hit point of a use, like BlockPlaceContext.ClickedAt.

To remove one part and keep the block:

  • set BlockBreakContext.IsCancelled, then mark and sync the block entity's change. Leave it false when the last part goes;
  • add the part's stack to BlockBreakContext.ExtraDrops. They spawn even when the break is cancelled, but not for creative or spectator players or with block_drops off, and they stay after the plugin unloads.

An exception discards the extra drops and cancels the break.

public async ValueTask BreakAsync(BlockBreakContext context)
{
    if (await context.Player.Level.GetBlockEntityAsync(context.Hit.Position) is CableBus cable
        && cable.RemovePart(context.Hit.BoxIndex) is ItemStack removed)
    {
        context.ExtraDrops.Add(removed);
        cable.SetChanged();
        cable.SendUpdate();
        context.IsCancelled = true;
    }
}

Container block entities

A ContainerBlockEntity holds a BaseContainer (its Inventory), saved like vanilla's containers (Items, CustomName, and a LootTable it's waiting for). Its items drop when the block is removed unless DropsContents is false. Changes to its items are saved without SetChanged. When the block goes, the windows showing the inventory close. Vanilla's containers are ContainerBlockEntitys too (see Item access).

A container that derives state from its items, like a machine checking the patterns it holds, overrides protected override void OnItemsChanged() instead of comparing its slots every tick. It's called at the end of the level's tick after the items changed (once however many changes came in), and once after the block entity joins the level, following OnLoad. Every change is heard: clicks in any menu, item access from hoppers and plugins, LockInventory changes and a loot table filling it. A plain SetChanged doesn't call it. It holds no lock, so it may take LockInventory.

A container block entity gives item access to its inventory, which hoppers, pipes and other plugins use:

// A machine that takes ore from the side it's fed from, and gives its output from below.
public sealed class Crusher() : ContainerBlockEntity(new Container(9) { Title = "Crusher" })
{
    protected override IReadOnlyList<int> GetSlots(BlockFace? side) => side switch
    {
        BlockFace.Down => [8],
        null => base.GetSlots(side),
        _ => [0, 1, 2, 3]
    };

    protected override bool CanInsert(int slot, ItemStack stack, BlockFace? side) =>
        side is null || slot < 8 && stack.Is(ItemsRegistry.IronOre);

    protected override ValueTask TickAsync()
    {
        // Push one item a tick into whatever is below, through its top face, planning both ends first.
        var below = this.Level?.GetItemAccess(this.BlockPosition + Vector.Down, BlockFace.Up);
        var output = this.GetItemAccess(side: null)!;

        if (below is not null
            && output.Extract(8, 1, simulate: true) is ItemStack planned
            && below.Insert(planned, simulate: true) is null
            && output.Extract(8, 1) is ItemStack taken
            && below.Insert(taken) is ItemStack refused)
        {
            // A player's click came between the plan and the move: put back what was refused.
            output.Insert(8, refused);
        }

        return ValueTask.CompletedTask;
    }
}

By default the access reaches every slot from every side. Override:

  • GetSlots(side), CanInsert(slot, stack, side) and CanExtract(slot, stack, side) for per-side and per-slot rules;
  • protected override int SlotLimit(int slot, ItemStack stack) to limit a slot's stack size, for example slot == 0 ? 1 : base.SlotLimit(slot, stack) for a single-item input. The slot is the inventory's index, and zero refuses insertion. Item access, hoppers, windows and container-backed MenuSlots follow it; direct Inventory.SetItem calls don't;
  • GetItemAccess(side) to give your own access instead.

These run from any thread with the inventory's lock held: read Inventory and don't wait on anything. Any other block entity exposes items by implementing IItemAccessProvider, and a block without a block entity, like vanilla's composter, by returning one from IBlockBehavior.GetItemAccess(ItemAccessContext), which is asked first; make it thread-safe. A container block entity holds at most ContainerBlockEntity.MaxSlots (256) slots; a bigger inventory throws when it's constructed.

For a machine's conversion inside its own inventory, take the protected IDisposable? LockInventory() in a synchronous part of TickAsync. Null means the inventory is unavailable. With the handle held, read and change Inventory directly: match the ingredient, check the output's space, consume the ingredient and write the result, all before disposing the handle. Don't await, call item access (even your own) or take other locks while holding it. The sample grinder shows this pattern.

When the plugin unloads, its block entities are saved into their chunks and let go of, and the windows showing its containers close, so no player takes out an item the reload brings back. While it's gone they're kept as saved data, and they come back on the level's next tick once it loads again. A container kept as data still spills its items when its block is removed, even with DropsContents false.

var pouch = registry.RegisterMenu("ruby:pouch", rows: 1, columns: 5);

var container = new MenuContainer(pouch, "Ruby pouch");
container.SetItem(0, new ItemStack(ItemsRegistry.Diamond, 3));
await player.OpenInventoryAsync(container);

A plugin's menu type is a grid of 1 to 6 rows of 1 to 9 slots above the player's inventory, numbered row by row and followed by the player's 36 slots (MenuContainer.PlayerSlotCount). Items move in it like a chest's; a ContainerClickEventArgs handler cancels or handles clicks. Several players can have the same container open: their clicks take turns, and each sees the others' changes.

A NeoForge or Fabric mod's menu type with the same identifier and slots shows it, and the Obsidian client shows it like a chest or with the mod's screen (see Client). The type keeps its id and shape across reloads; registering it again with another shape throws. Unloading closes its menus, with a ContainerClosedEventArgs the plugin still handles, and opening one does nothing until the type is registered again.

Machine menus

// A crusher's menu: ore in its inventory, its own buffer behind item access (an IItemAccess), progress and a button.
public sealed class CrusherMenu : MenuContainer
{
    private readonly Crusher crusher;

    public CrusherMenu(MenuDefinition menu, Crusher crusher) : base(menu, "Crusher")
    {
        this.crusher = crusher;
        this.Slots =
        [
            new MenuSlot(crusher.Inventory, 0) { MayPlace = item => item.Is(ItemsRegistry.IronOre) },
            new MenuSlot(crusher.Buffer, 0) { MaxStackSize = 16 },
            new MenuSlot(crusher.Inventory, 8) { MayPlace = _ => false }
        ];
        this.BlockEntity = crusher;
        this.DataSlots = 1;
    }

    public override short GetData(int index) => (short)this.crusher.Progress;

    // Ore goes to the input, anything else to the buffer; the menu's stacks go back to the player.
    protected override IReadOnlyList<MenuSlotRange> QuickMove(IPlayer player, int slot, ItemStack stack) =>
        slot < this.Size
            ? base.QuickMove(player, slot, stack)
            : stack.Is(ItemsRegistry.IronOre)
                ? [new MenuSlotRange(0, 1)]
                : [new MenuSlotRange(1, 2)];

    protected override bool ClickButton(IPlayer player, int button)
    {
        this.crusher.Paused = button == 0;

        return false;
    }

    protected override void WriteOpenData(IPlayer player, INetStreamWriter writer) =>
        writer.WritePosition(this.crusher.BlockPosition);
}

var crusherMenu = registry.RegisterMenu("ruby:crusher", rows: 1, columns: 3);
await player.OpenInventoryAsync(new CrusherMenu(crusherMenu, crusher));

A MenuContainer keeps its slots' items itself unless Slots says where each is kept, like NeoForge's SlotItemHandler: in a container's slot (new MenuSlot(container, index)), behind item access (new MenuSlot(itemAccess, index)), or in the menu itself (new MenuSlot()). Each slot has its own rules: MayPlace, MayPickup and MaxStackSize. They run during clicks with locks held, so they must not wait. Where slots go on screen is the client's business: a mod's client side gives their positions with MenuScreenProperties.

  • A slot kept in a container changes under that container's lock, so players with the container open elsewhere take turns and see the changes.
  • A slot behind item access moves its items through the access as the click ends. If the access no longer holds what the click took (a pipe took it meanwhile), the click is undone; what it refuses goes back to the player or drops. Each access call must be atomic and mustn't wait on a container's lock. Outside a click, change such a slot through its access; SetItem throws.
  • Don't show a container's slots both ways in one menu.

Subclass MenuContainer for the rest, like NeoForge's AbstractContainerMenu. These run inside calls into the plugin that registered the menu type, never once it's unloading:

  • QuickMove(player, slot, stack) decides shift-clicks: it returns ranges of the window's slots (the menu's from 0, then the player's 36), tried in turn until one takes some of the stack. Each tops up stacks of the same item, then fills its first empty slot that takes the item, from its end when Reverse is set. By default it works like a chest.
  • DataSlots and GetData(index) are short values like a furnace's progress, sent as the menu opens and then once a tick when they change. By default GetData returns what SetData set.
  • ClickButton(player, button) handles a button of the mod's screen: the client sends a number, which means whatever the menu says. It runs like a click; return true when it changed the slots, so that the viewers are sent them.
  • WriteOpenData(player, writer) writes extra data as the menu opens, like NeoForge's openMenu with a buffer. NeoForge clients and the Obsidian client get it; other clients get vanilla's open screen packet, which carries none.
  • BlockEntity binds the menu to a block entity. It closes when the block entity is removed, or once the player's eyes are farther than their block reach plus 4 blocks from its block. StillValid(player) adds a check of your own, made every tick and on every click.
  • Closed(player) runs once each time the menu stops being open for a player: they close it, another window opens, it's no longer valid, they die, change level or leave, or the plugin unloads. Give back what a crafting-grid style slot held there, say. It runs after the window closed, even while the plugin unloads. Menus a ServerPlayer "opens" have no window, so they're never closed this way.

Player extensions

// Two charm slots each player keeps, shown next to their inventory, opened with a key; worn charms take effect.
public sealed class CharmsPlugin : PluginBase, IClientPlugin
{
    private AttachmentType<ItemStack?[]> charms = null!;
    private MenuDefinition charmMenu = null!;
    private Item swiftCharm = null!;
    private Item cloudCharm = null!;

    public override void ConfigureRegistry(IPluginRegistry registry)
    {
        this.swiftCharm = registry.RegisterItem("ruby:swift_charm");
        this.cloudCharm = registry.RegisterItem("ruby:cloud_charm");

        // A death drops the charms unless keep_inventory is on; copyOnDeath: true would keep them anyway.
        this.charms = registry.RegisterAttachment("ruby:charms", ItemAttachments.Codec, ItemAttachments.NetworkCodec);
        this.charms.Changed += holder =>
        {
            if (holder is IPlayer player)
                this.ApplyCharms(player);
        };

        this.charmMenu = registry.RegisterMenu("ruby:charms", rows: 1, columns: 2);
        registry.MapPayload<OpenCharms>(PayloadPhase.Play, PayloadDirection.Serverbound, this.OpenCharmsAsync);
    }

    public void ConfigureClient(IClientRegistry registry)
    {
        var open = registry.RegisterKeyBinding("ruby:open_charms", "key.keyboard.j", "ruby:charms");
        open.Pressed += () => registry.Connection.SendPayload(new OpenCharms());

        registry.RegisterMenuScreen("ruby:charms", new MenuScreenProperties
        {
            Texture = "ruby:gui/container/charms",
            Slots = [new(71, 35), new(89, 35)]
        });
    }

    // Modifiers and abilities aren't saved: apply them as a player joins too, from a PlayerJoinEventArgs handler.
    public void ApplyCharms(IPlayer player)
    {
        var worn = player.GetAttachment(this.charms) ?? [];

        if (worn.Any(item => item?.Is(this.swiftCharm) == true))
            player.SetAttributeModifier(
                "minecraft:movement_speed", "ruby:swift_charm", 0.1, AttributeOperation.MulBase);
        else
            player.RemoveAttributeModifier("minecraft:movement_speed", "ruby:swift_charm");

        if (worn.Any(item => item?.Is(this.cloudCharm) == true))
            player.SetMovementAbilities("ruby:cloud_charm", new MovementAbilities { ExtraJumps = 1 });
        else
            player.RemoveMovementAbilities("ruby:cloud_charm");
    }

    private async ValueTask OpenCharmsAsync(OpenCharms payload, PayloadContext context)
    {
        if (context.Player is IPlayer player)
            await player.OpenInventoryAsync(new CharmMenu(this.charmMenu, player, this.charms));
    }
}

// The player's charm slots: charms only, one in each.
public sealed class CharmMenu : MenuContainer
{
    public CharmMenu(MenuDefinition menu, IPlayer player, AttachmentType<ItemStack?[]> charms) : base(menu, "Charms")
    {
        var worn = player.GetItemAccess(charms, slotCount: 2);
        this.Slots =
        [
            .. Enumerable.Range(0, 2).Select(slot => new MenuSlot(worn, slot)
            {
                MayPlace = item => RubyTags.Items.Charms.Contains(item.Holder.Id),
                MaxStackSize = 1
            })
        ];
    }
}

public sealed record OpenCharms : ICustomPayload<OpenCharms>
{
    public static string Channel => "ruby:open_charms";

    public static OpenCharms Read(INetStreamReader reader) => new();

    public void Write(INetStreamWriter writer)
    {
    }
}

Extra player slots, for accessories and the like, are built from pieces the engine already has rather than an accessory API: the items are kept in a player attachment, and the mod's own menu shows them next to the player's inventory. The inventory window itself doesn't change, since vanilla clients can't be given more slots in it.

  • Storage. An attachment registered with ItemAttachments.Codec holds the slots' stacks (ItemStack?[], null for an empty slot), saved like vanilla's minecraft:container component, for at most ItemAttachments.MaxSlots (256) slots. ItemAttachments.NetworkCodec syncs it to the Obsidian client, whose mod reads it with TryGetPlayerAttachment, to show it on its HUD say. It's saved with the player and kept through dimension changes.
  • Deaths. With keep_inventory off, a death empties these attachments, unless registered with copyOnDeath, after the player's own inventory: items with the curse of vanishing are destroyed and the rest dropped. With the rule on, for a spectator, or with copyOnDeath, they're kept. An unloaded plugin's attachment is left as saved.
  • Access. holder.GetItemAccess(type, slotCount) is item access to the first slotCount slots, which a menu shows with new MenuSlot(access, index) and its rules. Each call changes the saved value directly, so the attachment stays the only copy of the items. The slots take any item; the rules belong to the menu. Once the plugin unloads or the player leaves, the access takes and gives nothing.
  • Opening. The menu needs no block entity: it stays open until the player closes it. Open it from a payload a key binding sends, as above, from an item's use, or from a command. Override StillValid for a menu showing another player's slots. The Obsidian client's inventory screen has no button for mods' menus; a mod's own screen can have one that sends the payload.
  • Effects. AttachmentType.Changed is raised after a holder's value changes: by the plugin, through item access (a click too), or at a death. It isn't raised as a player joins. Apply what worn items do with attribute modifiers and movement abilities on changes, on joins, and to online players in OnLoadedAsync after a hot reload. Unloading takes the plugin's movement abilities back but not its attribute modifiers: remove those in OnUnloadingAsync.

Reload. Unloading closes the plugin's menus and releases its menu screens, slot rules, Changed handlers and key bindings. The items stay in the attachment's saved data, through saves and deaths, until the plugin loads again.

ObsidianMod's charm slots (Charms/) are this example built out, with a screen in Razor, and its moth counts its rides in an entity attachment.

Custom statistics

Register a custom statistic in ConfigureRegistry with RegisterCustomStatistic("ruby:machines"), which returns its protocol id. It's synced to NeoForge and Fabric clients, which must register the same entry. Its id stays after the plugin unloads, but incrementing it is refused meanwhile; saved values are kept. The Obsidian client's plugin registry can't register custom statistics yet.

Players' statistics and advancements are described in Progress.

Particle types

var spark = registry.RegisterParticle("ruby:spark");

level.SpawnParticles(spark, position, count: 8, spread: new VectorF(0.2f), speed: 0.05f);

A plugin's particle type is a particle without options, like NeoForge's SimpleParticleType. ILevel.SpawnParticles sends the ParticleDefinition that RegisterParticle returns like any particle (see Particles). The type keeps its id across reloads. Clients draw it: a NeoForge or Fabric mod registers a particle type with the same identifier and a provider, and the Obsidian client draws it with the mod's sprites (see Client).

Client sounds

In ConfigureClient, keep IClientRegistry.Sounds, an IClientSounds. Afterwards, call Play(sound, position, category = SoundCategory.Master, volume = 1, pitch = 1) or PlayUi(SoundEvent sound, float volume = 1, float pitch = 1) from screens, client ticks or payload handlers, on any thread. UI sounds aren't positional, play while the world is paused and work without a server. Calls return false while the mod is inactive or audio is unavailable. After a reload, use the Sounds of the new ConfigureClient: the old one stops working.

Supply assets/<namespace>/sounds.json and assets/<namespace>/sounds/<path>.ogg in the mod archive, like vanilla resource packs. Definitions merge with vanilla and player packs, including replace, event references and subtitles; an archive needs no pack.mcmeta. ObsidianMod declares obsidianmod:counter.chime, referring to vanilla's amethyst chime in its sounds.json, and uses it for its counter's placement and break sounds.

On this page