Skip to content
Work in progress. These docs describe Spawnite at launch, and some parts are still being built.

Inventory

Inventory gives an entity a bag: a fixed number of slots, each empty or holding one stack of an item. You register each item once by name, give the entity <Inventory slots={20} />, and the verbs add, remove, move, split and count the stacks. The player’s character needs none in a game that lists inventory() in its plugins: the plugin gives it a bag of 16 slots, or as many as <CharacterSpawn>’s bagSlots says, and the equipment slots. The player’s save keeps both where the game’s save includes inventory, as Saving progress says; a game that does not keeps no bag across a reload. A room gives the character the same bag and slots, empty each time the player joins, and restores them from the player’s save where the game includes inventory.

Its props are in InventoryProps.

An entity takes one <Inventory> and one <Equipment />. A second of either inside the same <Entity> throws in development. A built game logs it once, and the second neither resizes nor removes what the first gave.

An item’s definition is registered by name, as a model is, and every copy shares it:

  • displayName is what a player reads.
  • model is the registered model a Loot and a dropped copy are drawn as.
  • color is the colour of the glowing gem a Loot draws when the item names no model. It defaults to white.
  • maxStack is the most one slot holds. It defaults to 1, so a sword takes a slot of its own.
  • equip says where it is worn and what it changes while it is, as Equipment describes.
  • use says what using it does, as Using an item describes.
  • tags are the words a target matches the item by: ["key", "gold"].

A copy in a bag is an ItemStack: { item, count, data? }. item is the registered name and count is how many copies the slot holds. data holds only what differs for this copy, such as a rolled modifier.

Two stacks merge only when their item and their data are equal. A copy with rolled data never stacks with a plain one, so an item needs no flag to say it is unique.

All come from @spawnite/engine/inventory, the plugin’s own entry. Each takes the writer first, a step or an authority, then the entity, as every verb that writes does, so a system and a logic component call them alike. A page in a room sends the matching command instead, as Saving and replication says:

  • addItem(writer, entity, stack) fills the stacks it can merge with first, then empty slots, each up to the max stack. It returns the count it took, which is less than asked when the bag is full, so a pickup knows what to leave on the ground.
  • removeItem(writer, entity, { item, count }) takes up to count copies, whatever their data, from the first slot on, and returns the count it took.
  • moveStack(writer, entity, { from, to }) moves a slot’s stack into another slot, and returns whether anything moved. Onto a stack it can merge with, it tops that stack up to the max and leaves the rest where it was. Onto any other stack, the two swap.
  • splitStack(writer, entity, { from, to, count }) moves part of a stack into an empty slot, and returns whether it did.
  • countItem(entity, item) counts the copies across every stack.
  • hasItem(entity, item) says whether the bag holds at least one.
  • addInventory(writer, entity, slots) gives an entity a bag, for a system that spawns one without the component. A changed count keeps the stacks in the slots that remain.

InventoryTrait holds the slots in its stacks list field. Read the array with readTrait(entity, InventoryTrait)?.stacks in a system or useTrait(entity, InventoryTrait)?.stacks in a view. Each edit session publishes a new array and leaves an earlier reader’s array unchanged.

The verbs record one change per slot they write. To edit slots directly, use editList(writer, entity, InventoryTrait.fields.stacks): set changes one slot, resize grows with empty slots or cuts from the end, and copyFrom replaces the bag whole.

A count that is not a whole number above zero throws, and so does an item nobody registered. A writer of another world or over another entity throws before the verb reads a slot, naming the verb.

useInventory mirrors the player’s bag for a HUD, as useWallet mirrors the player’s coins. Its slots hold one entry a slot, null where the slot is empty. It reads the bag of the player’s character through the plugin’s page component, which Game mounts, so it follows the character through a respawn, a switch of what the player controls and a reconnect, and it changes only when the bag does.

useItemCount(item) reads how many of one item that bag holds, across every stack and whatever each copy’s data, as countItem counts them in a system, and re-renders only when the count changes. A HUD’s key count is <Counter icon="key" label="Keys" value={useItemCount("key")} /> in a Panel, with no sum over slots of the game’s own.

<Bag /> in a Hud is the engine’s panel over that store: a column of buttons up the right edge, one a stack, each reading its display name and count. The right edge keeps it clear of the stick a thumb steers by at the bottom left and of an ActionBar’s arc at the bottom right. Its slot stands it in another of the HUD’s regions, as a Panel’s does, such as <Bag slot={Slot.TopLeft} />. A press wears an item that has an equip and uses any other, and an empty slot draws nothing. A game that wants another look writes its own from useInventory.

Under a camera that captures the cursor, as in a shooter, no click reaches the bag’s buttons, so a game shows it as a screen the player opens and frees the cursor while it shows, as every game with an inventory does. It puts useFreeCursor(open) beside it, or a Panel with freeCursor around the game’s own bag. In development, the engine warns of a bag shown in play with nothing freeing the cursor. Roblox draws a default Backpack bar a game can turn off and replace, and Minecraft draws its own inventory screen.

<Equipment /> gives an entity the engine’s equipment slots, the values of EquipmentSlot: head, body, hands, feet, ring1, ring2, neck, mainhand and offhand. The list is fixed, as Minecraft’s is, and a game leaves the slots it does not use empty.

An item that can be worn names its slot and what it changes in equip:

  • slot is an EquipmentSlot, or "ring" for whichever ring slot is free.
  • modifiers holds a StatModifier’s flat, percent and more by stat name. A copy’s own data.modifiers replaces its definition’s, so a ring rolled stronger than its kind is one copy’s data.

Two verbs move an item between the bag and a slot:

  • equipItem(writer, entity, from) wears the stack in bag slot from, and adds each modifier to the entity’s stats with the source equip:<slot>. What the slot wore goes into bag slot from, and its modifiers come off. It returns false, and changes nothing, for an empty slot, an item with no equip, or an entity without <Equipment />. It wears the whole stack, so three rings stacked in one bag slot go on as one ring, and their modifiers apply once.
  • unequipItem(writer, entity, slot) puts what the slot wears into the bag’s first empty slot and removes its modifiers by that source. It returns false, and the item stays on, when the bag has no empty slot.

The source is the slot’s, so two identical rings in ring1 and ring2 are two sources, and taking one off leaves the other’s modifiers. useInventory carries what the player’s character wears as equipment, by slot. Unmounting <Equipment /> removes the slots, what they wear, and the modifiers that put on the stats.

Minecraft keys a worn item’s attribute modifiers by its slot and removes them when the item leaves it. Unreal’s Lyra keeps a handle for each grant, and Unity’s common Kryzarel pattern removes by the source object. Equipment keys by slot, as Minecraft does, because a slot is a string a save and a room carry as they are, where a handle or an object is not.

import { Entity, Stats } from "@spawnite/engine";
import { Equipment, Inventory, defineItem } from "@spawnite/engine/inventory";
defineItem("ring-of-speed", {
displayName: "Ring of speed",
equip: { slot: "ring", modifiers: { speed: { percent: 0.1 } } },
});
export function Wearer() {
return (
<Entity>
<Stats speed={{ base: 6 }} />
<Inventory slots={20} />
<Equipment />
</Entity>
);
}

An item’s use says what using it does. Its effects are a closed set that the step runs on the server, on the entity that uses the item:

  • { type: "heal", amount } adds amount to its health, never past the maximum, as dealHealing by its user, so a view of heals hears it. defineItem throws for an amount below 0 or not finite, naming the item.
  • { type: "modify", stat, flat, percent, more, seconds } adds a stat modifier under the source use:<item>. With seconds, it is a buff that ends when they run out. A second use of the item replaces what the first put on, so a buff restarts its seconds rather than stacking.
  • { type: "coins", amount } pays amount coins into its wallet, as addCoins does. The step checks every coin effect of a use before it runs the first effect, so a use whose coins the wallet could not hold throws and changes nothing.

consume: true spends one copy from the slot the use named. cooldownSeconds is how long before the same entity can use the item again. The cooldown runs in the entity’s CooldownsTrait under item: and the item’s name. Items that name the same cooldownGroup, a key from defineCooldown, share one cooldown under that key: using one holds them all, and a game’s skill that starts the same key holds them too.

activateItem(authority, entity, { slot, target }) asks the step to use the stack in bag slot slot, on target when one is named, on the world the authority decides outcomes on. The step runs each use before the behaviours: the effects, then the target, then the copy it spends and the cooldown. A use does nothing, and spends nothing, in any of these cases:

  • The slot is empty.
  • The item is still cooling down.
  • The item has no effects, and no target accepts it.

The step runs a use only where the simulation has the say: a client’s world fed from a room runs none, so a page sends inventory.commands.use with sendCommand, as the button below does, and the room runs the use on its copy of the character. Playing alone, the same send runs on the next step. A cooldown the use starts on a player’s character reaches the player’s page as the room’s grant, so no prediction check names it.

An effect the set lacks is the game’s own: a trait and a server system keyed on the item’s tags, as the entity page says for every consequence.

import {
Button,
Hud,
Panel,
Slot,
sendCommand,
useCharacter,
useWorld,
} from "@spawnite/engine";
import { defineItem, inventory } from "@spawnite/engine/inventory";
defineItem("potion", {
displayName: "Potion of healing",
maxStack: 10,
use: {
effects: [{ type: "heal", amount: 30 }],
consume: true,
cooldownSeconds: 1,
},
});
/** Drinks what the first slot of the player's bag holds: a command the
* next step runs, alone and in a room alike. */
export function DrinkButton() {
const world = useWorld();
const character = useCharacter();
return (
<Hud>
<Panel slot={Slot.Bottom}>
<Button
onPress={() => {
if (character)
void sendCommand(
world,
inventory.commands.use,
{ slot: 0, target: null },
{ entity: character },
);
}}
>
Drink
</Button>
</Panel>
</Hud>
);
}

A target says which items it takes. Its accepts is a list of tags, separated by spaces, and an item used on it matches when the item’s tags hold every one. An empty accepts takes every item, since there is no tag for the item to miss.

The engine’s own target is the Lock: <Lock accepts="key gold" /> opens when an item with both tags is used on it. Locks and keys covers it, with a door that opens on a key the player picked up, built and tested end to end.

A game’s own target is a trait with an accepts field, made a target once with defineItemTarget(trait), and a server system. When an item matches, the step emits the ItemAcceptedEvent event on the target, naming the item, and the system reads it with readEvents:

import {
defineTrait,
readEvents,
setTrait,
type AuthoritativeStep,
type World,
} from "@spawnite/engine/core";
import {
ItemAcceptedEvent,
defineItemTarget,
} from "@spawnite/engine/inventory";
/** Soil that takes a seed, and the seed it grows. */
export const SoilTrait = defineTrait("soil", { accepts: "seed", planted: "" });
defineItemTarget(SoilTrait);
/** Plants each seed a soil took. */
export function plantSeeds(_world: World, step: AuthoritativeStep) {
for (const { entity: soil, record } of readEvents(step, ItemAcceptedEvent))
if (soil?.has(SoilTrait))
setTrait(step, soil, SoilTrait, { planted: record.item });
}

Minecraft’s consumable and use_cooldown components are the model for use: a closed list of effects the server runs, a copy spent, and a cooldown by item. Stardew’s machines and Minecraft’s cow_food tag say on the target what it takes, as accepts does. Unreal’s Lyra has the target grant an ability, Roblox runs a script on each tool, and Unity and Godot leave use to code. Use takes Minecraft’s data and the target’s list of tags, because both are data an agent writes and the server runs.

Where the game’s save includes inventory.saves.bag, the save keeps the player’s bag, one entry a slot and null where the slot is empty, and what the character wears, by slot, under kits.inventory.bag:

  • The engine reads the character’s bag and its worn items there, each stack as it is: { item, count, data? }. An emptied bag is saved as empty, so a reload never brings back what the character used.
  • The engine lays the saved bag and worn items on the character once its spawn has set it up, so a game’s save code never names them. Its bag then has <CharacterSpawn>’s bagSlots slots, or more where the saved bag had more: a larger saved bag keeps its size and every stack in it, and a smaller one grows to bagSlots.
  • A stack whose item the game no longer registers throws as the save loads in development, naming the item. A published game keeps the stack in the player’s record and out of the character’s bag, so a version that registers the item again restores it, and the rest of the save loads.
  • A worn item’s modifiers go back on the character’s stats from the item as it is registered now, so a changed definition takes effect on the next load, and a dropped item’s modifiers go with it. The item adds them with saved: false, so the save’s stats leave them out, and a game that saves stats and not the bag keeps exactly what the character has on.
  • A game whose player has no character keeps a stack inside its own save with the plugin’s codec, itemStack.toSave(stack) and itemStack.fromSave(saved). It calls restoreInventory(writer, entity, inventory) and restoreEquipment(writer, entity, equipment) in its own restore.
  • A save with neither part loads as before.

Unity’s Opsive and Godot’s gloot save each stack as its definition’s id, its count and the values it overrides, as a save here keeps item, count and data. Unity’s Chop Chop sample skips an id it no longer knows. The load here drops one too, and says so in development, so the agent sees what a save lost. Roblox and Unreal leave the save to the game.

In a room, the room owns the character’s bag and worn items, and streams them to the player alone:

  • After each delta that changed them, the room sends the player’s client an owned message with what changed of the character’s inventory and equipment, and the player’s page writes it onto the character. useInventory mirrors it there as it does alone.
  • Every other player’s stream carries neither, and neither counts toward the stream’s hash. Another player sees a worn item through the stats it changes, which every client receives.
  • A client asks the room for a change to the character’s bag with one of the inventory’s commands, one for each verb: move, split, use, equip, unequip and drop, each acting through the character. The room runs that verb on its own copy of the character, in the order it took them, and its word to the player alone carries what it made.
  • The room checks each command’s fields before it runs the verb, and the verb’s own checks refuse a slot the character’s bag does not have.
  • On the player’s page, a view sends the command, sendCommand(world, inventory.commands.equip, { slot }, { entity: character }), as <Bag /> does: the verbs write, and a page in a room holds no writer. The page predicts nothing: the change shows when the room’s word to the player arrives. A use’s target goes by its streamed id, and the room runs the use only where the target stands within 1.5 m of the character, Interact’s default reach.

Unreal’s Lyra keeps the inventory on the player’s controller, which exists only on the server and its owner, and Roblox replicates a Backpack to every player. A bag here goes to its owner alone, as Lyra’s does, because what a player carries belongs to them.

dumpState, the headless dump and the entity inspector show a bag under inventory and what an entity wears under equipment, and its hash covers them. The room’s stream to every client leaves both out, as Saving and replication says.

In the AI tree, a bag is a fact for each stack it carries, carrying Potion of healing ×3, and an action for each item that does something: use for one with a use or tags, wear for one with a slot. A worn item is a fact, wearing Ring of speed. An item goes by its display name, or by the name it was registered under where the game no longer registers it.

Server. A bag holds what a player owns, what the character wears changes its stats, and what it uses changes its health or stats, the player’s wallet or a lock.

Engine or game Held item Container Stacking A full bag
Roblox a whole Tool, no count an unbounded Backpack none never full
Unreal, Lyra a definition class; an instance with tag stacks an unbounded list never merged never full
Unity, Opsive a definition asset plus an amount fixed slots, a list or a weight up to 99, only when attributes are equal returns the amount added
Godot, gloot a JSON prototype plus overrides a list, a grid or a weight a max per prototype; equal overrides merge returns false
PlayCanvas none none none none
Minecraft an item type plus per-stack components fixed slots a max per type; equal components merge takes what fits; the rest stays on the ground

Inventory takes Minecraft’s shape: a definition per item, a stack that stores only what differs, fixed slots, and stacks that merge when their data is equal. Most players know that shape, and it maps onto a trait. Like Opsive’s AddItem, addItem returns what it took, so a full bag is an answer rather than an error. It leaves out a grid, a weight cap and a category filter, which no engine builds in and every game does differently.

An item takes two entries. Its definition goes in the game’s items file, which each scene that names the item imports:

import { defineItem } from "@spawnite/engine/inventory";
defineItem("potion", {
displayName: "Potion",
color: "crimson",
maxStack: 10,
});

A Loot of it lies in a scene with a <CharacterSpawn>, whose character takes it into its bag as it walks over it; the engine draws it, and <Bag /> shows it:

// Excerpt of src/scenes/Run.tsx
<Entity position={[4, 0, -2]}>
<Loot item="potion" count={3} />
</Entity>