Entity
<Entity model position> spawns a koota entity on mount and destroys it on unmount, except on a page in a room, where it binds to the room’s, as In a room says. It publishes itself through a context, so useEntity() inside reads that entity and nothing else. UI inside an Entity lives as long as the entity exists.
The children mount once the entity exists and unmount on the commit after it dies, whether the Entity unmounted or a system destroyed the entity mid-frame. They are its logic, such as its behaviours, and the room mounts them too. On a page, Entity draws one group at its pose and binds it to the entity, so a system that moves or turns the entity’s transform moves what the group holds.
Its view
Section titled “Its view”view is what the entity is drawn as: a component the page renders inside the entity’s group, handed the entity, and a room never mounts. Left out, the entity draws its model looping its clip, or the view a plugin registered for a trait it holds with defineTraitView, such as the gem loot draws in its item’s colour. The first registered trait it holds decides, and the registration’s return forgets it. view={false} draws nothing, while model still shapes a hull collider and tells the room’s pages what the entity is. A view that loads suspends inside its own boundary, so the entity’s logic stays mounted while it loads.
import { Entity, type EntityViewProps } from "@spawnite/engine";
function LanternView(_: EntityViewProps) { return ( <mesh position-y={1}> <sphereGeometry args={[0.3]} /> <meshStandardMaterial color="orange" /> </mesh> );}
export function Lantern() { return <Entity position={[0, 0, -4]} view={LanternView} />;}Define the view once, outside the component that renders the Entity: view={() => <mesh />} is a new component each render, which draws anew each time and warns in development. What differs between two entities of one view, such as a colour, goes on a trait the prefab sets, which the view reads with useTrait(entity, Trait), as Logic and views shows. A prefab takes a view too, and an Entity’s own, false included, goes over its prefab’s. Logic and views says where the rest of a scene’s drawing goes.
In a room
Section titled “In a room”A game in a room has one scene, which the room mounts headless and every page mounts to draw it. An Entity takes its identity from its place in the scene: for each element from the scene’s root down to it, the key the game gave it, or its index among its siblings. The room spawns the entity and streams it under that place. On a page, the Entity spawns nothing: it binds to the entity the room streams at its place, draws its model and its children on it, and leaves its position and its behaviours’ traits to the stream. A game with a list of entities gives each a key, so an entity keeps its identity when the list changes. The engine draws what no Entity of the scene draws, including the other players’ characters, unless Game sets replicas={false}.
A page holds only the entities it may see. An entity a system spawns with visibility, or later passes to setVisibility, reaches only the pages its audience names, and each trait reaches the pages its reach names: Choose who a trait reaches shows both. A scene places what every page may know exists, so a secret entity is spawned by a system rather than placed.
An entity’s pose is where it stands, how it is turned and how large it is: position, rotation and scale on the Entity, and the TransformTrait trait’s three fields of the same names on the entity. The trait’s pose is always the world’s, as Unity’s transform.position and Roblox’s CFrame are. Metres, right-handed, y up; at rest an entity faces negative z.
An Entity nested in another reads its position and rotation in its parent’s frame, as the parent stood when the child spawned, so a court copies by moving one Entity. The child does not follow its parent afterwards, since a body lives in the world’s space: unlike a Unity child, and like Instantiate(prefab, parent) with a local position. Its scale stays its own, and its group draws at its own pose, outside its parent’s.
positionis[x, y, z]in metres.rotationis three Euler angles in radians,[x, y, z]in three.js’s default order, as React Three Fiber’srotationprop takes them, or aQuaternion. The trait stores it as a quaternion.scaleis one number for every axis, three, or aVector3, and 1 when left out. It is the entity’s own.
The collider turns and scales with the entity, so a box tilted on x is a ramp a walker climbs, and a box of size [1, 1, 1] at scale [4, 1, 8] is a 4 by 1 by 8 box. A sphere takes one scale for every axis and a capsule the same scale across x and z: any other scale throws when its body is built, naming the shape, since neither shape can stretch. What the entity’s view draws turns and scales with the entity too, so a model needs no group of its own to turn it.
// Excerpt of src/scenes/Run.tsx<Entity position={[0, 0, 10]} rotation={[-0.3, 0, 0]} scale={[4, 1, 8]} collider={{ shape: box({ size: [1, 1, 1] }) }}/>A system reads the pose with readTrait(entity, TransformTrait). That record is read-only. Write through the step with editTrait, setTrait or updateEach, as Writing a trait describes.
A rotation read off the record is a ReadonlyQuaternion, which needs no clone to compare or blend:
- Its own
equals,dotandangleTotake another read rotation or a writable one, as a read vector’sdistanceTodoes. slerpRotations(target, { from, to, fraction })sets your ownQuaternionpart of the way from one rotation to another, as three’sslerpQuaternionsand Unity’sQuaternion.Slerpdo.turnTowards(rotation, to, maxRadians)turns one by at most an angle, andmeasureTurn(from, to)measures the angle between two.
These three run on the engine’s exact trigonometry, so the room and every page reach the same numbers, which three’s own methods do not promise.
To spawn with a pose, give the trait a whole record: TransformTrait(createTransform({ position: [0, 1, 0] })). createTransform fills each field. A partial record fails to typecheck.
Prefabs, spawning and destroying
Section titled “Prefabs, spawning and destroying”definePrefab(name, { traits, model, view, animation, body, collider }) declares one kind of entity, at module scope in a module the room and every page import. A scene places one with <Entity prefab={wolf} position={[4, 0, 10]} />, and a system spawns more with spawn(step, wolf, { position, rotation, scale, traits }). Both run the same code, so the two carry the same traits, stream alike and dump alike, and each carries PrefabTrait with the prefab’s name.
Each spawn copies the prefab’s records and its own, so no two entities share a list, and a spawn’s own traits go over the prefab’s field by field. A copy of a prefab, such as { ...wolf }, spawns as the prefab. A prefab whose collider is its model’s hull names its model, and a spawn throws where the model’s corners wrap no body, as a scene’s Entity does. An Entity’s own model, animation, body and collider go over its prefab’s, and so do a spawn’s own body and collider. A prefab with placed: false spawns entities with no pose, such as a ledger; any other spawns at the origin unless the spawn gives a pose. Unity’s prefab and Instantiate are the model.
Each page draws a spawned or streamed entity of a prefab with the prefab’s view, found by its name. So a copy with another view throws, at the scene’s Entity and at a spawn: define the variant under its own name. A streamed entity whose prefab the page never defined draws as its model, with a warning in development.
A scene’s Entity carries a trait of the game’s own, such as a boss’s mark, through its prefab, <Entity prefab={boss}>, as the Match page’s boss shows. It carries one through its own traits too, such as one lantern’s colour: <Entity prefab={lantern} traits={[LanternTrait({ color: "red" })]} />. Its own go over the prefab’s field by field, as a spawn’s do, and a change of a field after spawn sets that field again; Logic and views says what else holds. A trait that a behaviour child sets goes through that behaviour alone, as Behaviours says.
Who may spawn and destroy is a type, as who may deal damage is:
spawntakes anAuthority: the room’s step in a system with norunsOn, or a step narrowed byif (step.authoritative).requireAuthority(world)takes the writable world the engine or a test holds. A view cannot spawn what the room streams.destroy(authority, entity)takes the same, or the onefindAuthority(writer, entity)gives over an entity only this page holds. Every field a trait names underentitiesthat held the entity reads null from that moment, and a list drops it, so a system later in the tick never reads a dead entity.spawnLocal(writer, prefab, options)makes an entity only that world holds, such as a placement ghost or preview. No stream carries it. Pass a system’s step, a view’s writer, a setup writer or an authority. A re-run refuses it.
spawn, spawnLocal and destroy are the ways a game makes and removes entities. Its lint refuses koota’s own writes.
The crate on the body section is one such prefab.
Spawn one at runtime
Section titled “Spawn one at runtime”A system spawns an entity at runtime with spawn(step, prefab, { position }): a wave of monsters, a summoned pet, a drop. definePrefab declares the kind once, its traits, its model and its collider, and a scene places the same prefab with <Entity prefab={wolf} />, so both carry the same traits. A spawn is an outcome, so it takes the room’s step, in a system with no runsOn or inside if (step.authoritative); a step on a page in a room is no authority, so a spawn there does not typecheck. Every streamed trait goes to every page: the engine’s, such as TransformTrait, ModelTrait and HealthTrait, and each a game makes with defineTrait. The engine draws the entity as its model, unless Game sets replicas={false}.
A prefab also sets how often a room sends its entities and how finely, with sendsPerSecond, farSendsPerSecond and positionPrecision, as Send one kind of entity less often says.
A body spawnCharacterBody spawned draws in the appearance setCharacterAppearance gives it, an avatar, a model or a primitive by the names each page registers, as the Player page says, or else as the default capsule.
In a game played alone the engine draws the same entity in the same view, with nothing to mount. At zero health the entity is removed, as Health says. The engine’s tests run this spawner against a real room and alone:
import { ChaseTrait, createQuery, definePlugin, definePrefab, defineTrait, HealthTrait, readEach, readTickRate, spawn, TargetableTrait, type AuthoritativeStep, defineSystem, Phase,} from "@spawnite/engine/core";import { Vector3 } from "three";
// Wolves spawned at runtime, built as a creator's plugin is, from the// engine's public entry alone: the room spawns a wolf at once and every// two seconds after, at the next spot of its den, up to three at once.// Each is one prefab, which a scene places with `<Entity prefab={wolf} />`// and the spawner spawns the same: a model that chases the nearest// player's character, can be targeted, and is removed at zero health. Its// traits stream, so every page draws it, and a game played alone draws it// the same way.
/** Marks a wolf, so the spawner counts its own; the stream carries it. */export const WolfTrait = defineTrait("outsideWolf");/** The most wolves standing at once. */export const wolvesAtOnce = 3;/** Seconds between two wolves. */export const wolfSeconds = 2;const den = [new Vector3(8, 0, 0), new Vector3(0, 0, 8), new Vector3(-8, 0, 0)];const wolves = createQuery(WolfTrait);
/** One wolf: what a scene places and what the spawner spawns. */export const wolf = definePrefab("outsideWolf", { traits: [ WolfTrait, HealthTrait({ current: 30, maximum: 30 }), ChaseTrait({ speed: 3, reach: 1 }), TargetableTrait, ], model: "wolf",});
export const spawner = definePlugin(() => ({ name: "spawner", // No runsOn: the room alone spawns, and a game played alone is its // own room. systems: [ defineSystem({ name: "wolves", phase: Phase.Rules, run: spawnWolves, }), ],}));
function spawnWolves(step: AuthoritativeStep) { const world = step.world; if (step.tick % Math.round(wolfSeconds * readTickRate(step)) !== 0) return; let standing = 0; readEach(world, wolves, () => standing++); if (standing >= wolvesAtOnce) return; spawn(step, wolf, { position: den[standing] });}Unity’s Instantiate, Unreal’s SpawnActor, Godot’s instantiate() and Roblox’s Clone copy a prefab or a template, and definePrefab is the same idea. Each spawn copies the prefab’s records, and the spawn’s own traits go over them field by field, so traits: [HealthTrait({ current: 10 })] keeps the prefab’s maximum. An entity with no prefab, such as a match record, is spawn(step, { traits: [...] }), and destroy(step, entity) takes any entity away, nulling every reference a trait holds to it.
Attaching one entity to another
Section titled “Attaching one entity to another”attach(authority, child, parent, { offset, rotation }) makes the child’s pose follow its parent’s every step, after the physics step, as Roblox’s weld holds one part to another and Unreal attaches one actor to another. The child’s TransformTrait stays its pose in the world; AttachmentTrait holds the offset, in metres along the parent’s axes, and the rotation after the parent’s. An option left out keeps where the child stands from the parent now, as Unity’s SetParent keeps the world pose. A chain stands parents first, so a flag on a turret on a tank follows both.
detach(authority, child)lets the child go where it stands, with its parent’s speed, so a rider who jumps off a moving kart keeps going. A character stands upright again, since its controller turns it about the vertical alone.- Destroying a parent lets each child go where it stood, in the same destroy.
- An attached entity takes no part in collisions: a walker’s capsule and a collider’s body leave the physics world until it lets go.
- Scale is the child’s own and never follows the parent’s: a scaled kart does not scale its rider, and an offset stays in metres. A system that grows a mount and its rider together sets both scales.
attachtakes the same authority asdestroy: the room’s step, the authorityuseAuthorityEffecthands a logic component, orfindAuthority(writer, child)for an entity only this page holds. An attachment that would make a loop, or one to an entity that is gone, attaches nothing:attachreturns the reason, anAttachRefusal, and a development world throws, naming both entities.- A predicted system may write the child’s
AttachmentTraitoffsetandrotation, such as a turret it aims on the player’s kart, and every page streams the attachment. - A page draws a rider from its parent’s drawn pose, so it never slides against the saddle while the kart blends between sends or eases out of a correction.
import type { Entity } from "@spawnite/engine/core";import { attach, detach, type AuthoritativeStep } from "@spawnite/engine";
/** Seats `rider` on `kart`, 0.6 m up and 0.2 m back from its middle. */export function mount(step: AuthoritativeStep, rider: Entity, kart: Entity) { attach(step, rider, kart, { offset: [0, 0.6, 0.2] });}
/** Lets `rider` go where the rider sits, with the kart's speed. */export function dismount(step: AuthoritativeStep, rider: Entity) { detach(step, rider);}Owners and copies
Section titled “Owners and copies”An entity may belong to another, its owner, as Unreal’s actor has an owner. spawn(step, ball, { owner: court }) gives it one, setOwner(step, entity, owner) changes it, and findOwner(world, entity) and readOwnedEntities(world, owner) read it. The engine never destroys what an owner owns: a plugin decides that, as a match destroys what it owns at each reset. Each <Entity> and <Npc> under <OwnedBy entity={court}> spawns owned by it, and <Match> puts its children in one.
packEntities(world, entities) keeps entities as they stand, as data a checkpoint keeps, and spawnPacked(step, packed) spawns a copy of each later, as Godot’s PackedScene packs and instantiates. A reference inside the pack points at the copy, and one outside keeps its target. A copy keeps its entity’s scene place, so the scene’s <Entity> at that place takes the copy up, on the room, alone and on every page, with nothing written over it. { scenePlaces: false } spawns a clone beside the original instead.
Models
Section titled “Models”A model is a GLTF file. registerModel(name, model) keeps a model under the name: its file’s entry in the game’s model manifest, or a bare url. <Entity model> draws that file’s scene inside the entity’s group, stood on its lowest point at the entity’s feet, each entity with its own copy on the one loaded geometry. The file’s front is +z, as glTF puts it, and the engine turns the model half a turn so that its front faces the way the entity does, along -z at rest. Godot names +z a model’s front in the same way, while its nodes look along -z. InstancedModel, a map’s model props and the scatter draw the file unturned, with only their own yaw, so at a turn or yaw of 0 its front faces +z.
A file centred on its origin, as the kit’s come, is lifted by half its height, and one whose origin is its feet does not move. <CharacterSpawn> and InstancedModel stand the same file the same way, so a model placed at y = 0 stands on flat ground whichever draws it. The children stand while it loads. readModel(name) throws on a name nobody registered, which an <Entity model> with that name does as well, into the game’s boundary, as Landscape does for a map. The engine registers no model of its own.
A model with animations plays one of them by name. animation names the clip the entity loops, as the file names it: <Entity model="duck" animation="walk" /> walks the kit’s duck, whose other clips are idle, attack and dead. Set animation to another name to switch clips. Each entity plays the clip on its own copy of the model’s skeleton, so two ducks move apart. Every entity looping a clip of one model draws in that model’s skinned batch: one draw for each of its meshes, however many stand. A name the file lacks plays nothing, and a dev world warns once with the names the file has. Models says how to name the clips when you make the model.
Entities that mount together start their loops together, so a field of copies moves in step. animationOffset starts the loop partway through, as a share of the clip’s length: <Entity model="duck" animation="walk" animationOffset={0.5} /> starts halfway, and an offset past 1 wraps. The entity reads the offset as the loop starts, so a new value waits for the next animation. Give each copy its own offset, such as a random one fixed per copy, as Unity’s Cycle Offset does.
playClip(entity, name) plays one of the file’s clips once over the loop, then fades back to the loop. A hit or an attack plays this way: playClip(wolf, "hit"). The clip fades in over fadeSeconds, 0.15 s by default, and fades out over its last fadeSeconds. A second call starts the clip again, the same clip included. { hold: true } holds the last frame instead, as a death does, until stopClip(entity) fades it back or the next playClip replaces it. On a model that loops nothing, the clip plays at full weight, and a clip that does not hold returns the model to its rest pose at its end. The call writes the OneShotClipTrait trait, so call it from a system or an event: a room streams the trait, and every page plays the clip. A page that joins after a clip started plays none of it, except a held clip, which it plays from the start and holds. A name the file lacks plays nothing and stops the clip the layer plays, as stopClip does, and a dev world warns once with the names the file has.
layer: ClipLayer.UpperBody plays the clip on the bones from the model’s spine up, while its loop goes on driving its hips and legs. start, end and speed play part of the clip. useAfterPose leans or turns the posed model each frame, as the player page says for the player’s model. The spine is the model’s first bone whose name holds spine or abdomen: the kit duck’s Spine holds its head, so playClip(duck, "attack", { layer: ClipLayer.UpperBody }) attacks with its head while its legs walk.
The other engines name the same thing a montage (Unreal), an Animator trigger on an AvatarMask layer (Unity), a one-shot node in an AnimationTree (Godot) and an animation track played at a priority (Roblox).
A walker takes its size from its model, and nobody types the numbers. A player’s character is the one exception: it is 1.4 m tall and 0.35 m in radius unless <CharacterSpawn> sets height or radius, as the player page says. The flow runs as follows:
spawnite add asset <id>copies a model into the game’spublic/assets/folder and bakes that folder intosrc/models.json. Each file’s entry holds its path, its bounds, the capsule that fits inside it, which has the model’s height and a radius of half its smallest extent, and the corners of its convex hull. It also holds thecollidera map’s prop and an InstancedModel stand the model as, as A placed model’s collider says.- The game’s
src/models.tsregisters every entry under its file’s id, and under the game’s own names for it, such as the arena’smonsterforrock-boulder. The scene imports that module, so the room, which loads no model file, cuts the same capsule every page does.spawnite add assetwrites the module for a game that has none, and prints the line that imports it into the scene. - A
CharacterCapsuleTraitwhoseradiusorheightthe game leaves out takes the registered capsule. A size the game sets wins, field by field. A radius over half the height would give the capsule a negative length, so the engine cuts the radius to half the height, writes that into theCharacterCapsuleTrait, and warns once in a dev world.
A walker whose model has no measured size, one registered by a bare url or not at all, gets a player’s character’s 0.35 m by 1.4 m, and a dev world warns once for its name. Each game’s models target bakes the manifest before dev, build, test and room, and the dev server rebakes it when a model file appears, changes or goes. The manifest check compares a fresh bake with the manifest as committed, not the working copy that test’s own bake has just rewritten. So in a repository a commit that changes a model without its manifest fails the test with the command to run. Outside git the check reads the working copy. The bake records what the file draws: the kit’s duck and red panda are drawn in centimetres and measure hundreds of metres, and the bake warns about each, as Models says. Unity, Unreal and Godot measure a model when it is imported and store the result beside the asset, where the server reads it; the manifest is that stored measurement.
A placed model’s collider
Section titled “A placed model’s collider”The bake measures each model’s collider from its solid triangles, and a map’s prop and an InstancedModel in a Landscape stand the model as it:
- Cut-out and see-through triangles, whose material’s alpha mode is mask or blend, never collide, so leaves, needles and grass cards are walked through.
- A model taller than it is wide whose solid sections near its foot are, at the median, under a quarter of its widest side is a trunk: a tree, a snag or a post. It stands as an upright cylinder through its narrowest section there, from its foot to its top, so its crown is walked under. The bake reads the band from 10 cm to 2 m up, or the same shares of a model under 6.7 m tall, so a one-metre tree a game scales up reads as a tree.
- Any other model stands as the convex hull of its solid triangles: a rock, a log, a stump or a house.
- A model with no solid triangle, such as a fern, stands as nothing, written
false.
A hull collider wraps at most 32 of the hull’s corners, because Rapier holds about 270 bytes for each corner in every room that stands the model. The bake keeps the corners at the hull’s extremes and its farthest reach, then each corner that leaves the least of the whole hull outside, and writes them as the collider’s own points. The kept hull lies inside the whole one, as Jolt and Godot reduce a hull. At 32 corners the example’s largest boulder loses up to 11 cm of its 3.3 m, and a log up to 2 cm. The entry’s hullPoints stay whole, so a rotated copy is seated as before. To keep more of a model’s hull, such as a rock a game places at four times its size, set maxHullPoints in the models field of the game’s package.json:
{ "models": { "maxHullPoints": { "default": 32, "boulder-large-moss": 128 } } }A single number caps every model. A count is an integer of 10 or more, and the bake refuses an id with no model file.
A registration’s own collider replaces the manifest’s for every prop and batch of that model, such as registerModel("oak", { ...models.oak, collider: false }). It takes the manifest’s shapes: { shape: { type: "cylinder", radius, height }, offset }, { shape: { type: "convex-hull" } } for the entry’s hull, or the same with its own points.
A model may be Draco-compressed: every GLB the engine loads, a VRM included, decodes Draco with three’s glTF decoder. A texture may be KTX2: useKtx2(url) loads one inside the Canvas, transcoded by Basis into a format the device’s GPU reads, for a material’s map. It suspends while it loads, and the texture is shared by URL, so its wrapping and repeat change for every material that uses it. The decoder and the transcoder come from the three package, and the game’s build copies them beside its bundle, so a player’s device fetches them from the game’s own site, and only once a file needs them. The game’s build encodes each model’s geometry with meshopt, as Game says; compress images before they are committed. An image several models share, named as a file beside them or carried inside each, such as a bark texture a whole stand of trees uses, is fetched and decoded once for the page. Three uploads it once wherever the models’ samplers and colour spaces agree.
import { Entity, registerModel, useKtx2, Views } from "@spawnite/engine";import rock from "./rock-draco.glb?url";import snow from "./snow.ktx2?url";
registerModel("rock", rock);
// A view: it reads a texture, which only a page loads.function Snow() { const map = useKtx2(snow); return ( <mesh rotation-x={-Math.PI / 2}> <planeGeometry args={[20, 20]} /> <meshStandardMaterial map={map} /> </mesh> );}
export function Slope() { return ( <> <Views> <Snow /> </Views> <Entity model="rock" position={[0, 0, -4]} /> </> );}Materials
Section titled “Materials”material changes what an entity’s model wears: a function handed each of the file’s materials, which returns the one the model wears in its place. A team’s colour, a hit’s flash, a stone curse or a hologram is a function of this kind. The original is the loaded file’s, which every other draw of the file wears, so return a new material, such as a clone, rather than the original changed.
The engine asks the function once for each of the file’s materials and keeps what it returns. Every Entity handed the same function wears the same materials, and the animated ones draw in one skinned batch: one draw for each mesh, however many stand. A second function draws in a batch of its own, so give each look one function and define it once, outside the component. A function made anew in each render makes new materials in each render.
To change the look of one entity for a while, such as a hit’s flash, hand it another function for as long as the look lasts, and undefined to go back to the registered material or the file’s own. The entity moves to that function’s batch and keeps its skeleton, its mixer and its clips. A batch whose last entity leaves waits 30 seconds for the next before it is freed, so a flash that comes back draws in a batch whose first draw is done. Looks do not stack: each function is handed the file’s materials, never another function’s result, so a red team’s flash is a function of its own. A look under the engine’s tone mapping reads darker than its colour, so a flash that should read white sets an emissiveIntensity above one. A value that changes for each entity over time, such as a flash that fades out or how far one enemy has dissolved, is not a material. Draw that entity with a view of the game’s own, whose skinned batch holds a value for each copy.
The following rules hold for every model the engine draws:
- When the function returns a see-through material, one with
transparent: true, the entities wearing it leave the batch, and each draws on its own, sorted back to front with the scene’s other see-through draws. - A mesh drawn with several materials asks the function for each of them.
- A shader patch, an
onBeforeCompileon what the function returns, draws in the batch too: the batch never copies the material, since three.js leaves the hook out of a copy, and each hook compiles a program of its own. - A new load of the file asks the function again for the new file’s materials, and a change of quality level leaves them as they are.
- What the function returns is the game’s to dispose: the engine never disposes it, so one material can dress many models.
registerModel(name, { path, material }), or a manifest’s entry with material beside it, gives the model a material wherever the engine draws it by that name. That covers an <Entity> with no material of its own, an InstancedModel, a map’s model prop, and an entity a system spawns or a room streams. A function cannot travel to another page, and a name can, so the registration is how every page in a room dresses the entities the room spawns. Every page registers its models from the same module, so each holds the same function. A collider’s material is unrelated: it is the body’s friction and bounce.
These ducks walk in their team’s colour, the red team in one draw and the blue team in another. The engine’s tests mount this file:
import { Entity, type ModelMaterial, type Position } from "@spawnite/engine";import { MeshStandardMaterial } from "three";
// Ducks in their team's colour: each wears its file's texture tinted red// or blue, and walks on its own skeleton.
export enum Team { Red = "red", Blue = "blue",}
/** The file's material tinted `color`, which multiplies the file's * texture: a copy, since the original is the loaded file's, which every * other draw of the file wears. */function tint(color: string): ModelMaterial { return (original) => { const tinted = original.clone(); if (tinted instanceof MeshStandardMaterial) tinted.color.set(color); return tinted; };}
// Made once, outside the component: each function is asked once for each// of the file's materials, so every duck of a team wears the same ones and// the team draws in one draw per mesh.const colors: Record<Team, ModelMaterial> = { [Team.Red]: tint("#d04a3a"), [Team.Blue]: tint("#3a6ad0"),};
interface TeamDuckProps { team: Team; position: Position;}
export function TeamDuck({ team, position }: TeamDuckProps) { return ( <Entity model="duck" animation="walk" position={position} material={colors[team]} /> );}Unity gives a renderer its own material instance, or a property block for a value per renderer that keeps it in its batch. Unreal makes a dynamic material instance per mesh. Godot sets material_override on a mesh instance. Roblox sets a part’s material and colour, or a MaterialVariant. PlayCanvas sets a material, or a shader parameter, on each mesh instance. material takes Godot’s override and Unity’s shared material: one function stands for one look, so the engine can draw every entity of a look together, and a game writes no per-instance bookkeeping. <Entity> has no equivalent of Unity’s property block yet: a value for each entity is a view of the game’s own, as the paragraph above says.
Display name
Section titled “Display name”<DisplayName name="Wolf" /> inside an Entity gives it the name a player reads: a target frame’s title, a plate over its head. It writes DisplayNameTrait, which a room streams with the entity. Every plate and frame reads a name through one reader, useDisplayName(entity) in a component and readDisplayName(entity) elsewhere. That reader takes the first of: the display name, the name a player joined a room as, an NPC’s own name, and the model’s name in words, so red-panda reads Red panda. Roblox’s DisplayName stands over a character’s name the same way; Unity, Unreal and Godot leave names to each game.
Authority
Section titled “Authority”Every entity says which end steers it. In a room, the room runs the game and has the final say over every entity, each player’s own character included. The player’s page also runs the character, ahead of the room, so a key press moves it at once on a phone. The room runs the same move from the player’s input, and where the two disagree, the player’s page takes the room’s position. Multiplayer says what that keeps a modified page from doing.
An Entity carries an AuthorityTrait trait, RunContext.Server unless the authority prop says RunContext.Client. Client means this page steers the entity ahead of the room and keeps its own movement over what the room streams; the room never takes the page’s word for where it is. The one entity that says Client is the local player’s character, and the <CharacterSpawn> component sets that itself. A single-player game runs the whole simulation on the page, writes no authority prop, and the default costs it nothing. The defaults in a room:
| Entity kind | Steered by | Note |
|---|---|---|
| A player’s own character | The player’s page, ahead of the room | The room runs each move from the player’s input and corrects the player’s page |
| Other players’ characters | The room | Drawn from the room’s stream, smoothed between its snapshots |
| Pickups, spawners, enemies and AI | The room | The page draws what the room streams |
| Physics props | The room | Drawn from the stream; the page’s own body for it can drift |
| Score, wallet, inventory, progress | The room | The page reads, never writes |
| Timers, matches, match state | The room | |
| Cosmetic effects, local UI | Each page | Changes only what that page draws |
The trust boundary cites this section for the room authority contract.
Bodies and colliders
Section titled “Bodies and colliders”An Entity without a collider has no body: a coin is walked through, and a ball placed in the air stays there. Two keys give it one, on <Entity>, on definePrefab and through spawn alike:
collideris its shape, one collider or a list of them, each with anoffsetand arotationin the entity’s own axes, amaterial, atriggerflag and, where one part differs from the rest, its owncollisionLayerandcollisionMask. AoneWaycollider is a platform a character jumps up through. A collider’s index in the list names it.bodyis how it moves:bodyTypeisRigidBodyType.Fixed,KinematicorDynamic, Rapier’s names with one kinematic kind. Each kind takes only the settings that mean something for it, so a kinematic body’smassor a dynamic body’spushesfails to typecheck. A collider with no body is a fixed body.
An entity whose body is fixed stands still, so its model casts into the sun’s far shadow map past the cascades: a hut a player builds shades the ground far off. static on the Entity says otherwise: static={false} for a fixed body the game moves by its pose, and static for a model with no body that never moves.
The physics world builds the body on the step after the entity spawns and takes it out in the same tick the entity is destroyed, so a cast later in that tick misses it, and what rested on it wakes and falls.
import { box, definePrefab, HealthTrait, RigidBodyType, spawn, type AuthoritativeStep,} from "@spawnite/engine";
export const crate = definePrefab("crate", { traits: [HealthTrait({ current: 20, maximum: 20 })], model: "crate", body: { bodyType: RigidBodyType.Dynamic }, collider: { shape: box({ size: [1, 1, 1] }) },});
export function dropCrates(step: AuthoritativeStep) { spawn(step, crate, { position: [0, 4, 0] });}Shapes
Section titled “Shapes”A helper makes each shape from named sizes, since Rapier takes half extents where three.js takes full ones:
| Helper | Size | Bodies |
|---|---|---|
box({ size }) |
Full extents, [width, height, depth] |
Any |
sphere({ radius }) |
Radius | Any |
capsule({ radius, height }) |
Height from tip to tip, as Unity’s and Godot’s capsules take it | Any |
cylinder({ radius, height }), cone({ radius, height }) |
Full height, centred halfway up | Any |
convexHull({ points }) |
The points’ hull; with no points, the hull of the entity’s model, which it then names |
Any |
triangleMesh({ vertices, indices }) |
A concave mesh, three indices per triangle | Fixed and kinematic |
heightfield({ heights, rows, columns, size }) |
rows samples along z by columns along x, row by row, over size, [width, depth], centred on the entity |
Fixed |
heightfield({ grid, size }) |
A two-dimensional grid field’s heights, its x along world x and its y along world z, over size |
Fixed |
voxels({ cellSize, cells }) |
Boxes cellSize metres on a side, or [x, y, z] metres; the cell [x, y, z] is the box from those numbers times the size |
Fixed |
voxels({ cellSize, grid, empty }) |
One box of cellSize for each cell of a three-dimensional grid field whose value empty does not list, [0] by default |
Fixed |
voxels({ cellSize, columns }) |
A two-dimensional grid field of columns: the cell [x, z] stacks as many boxes of cellSize as its value from the entity up, none at 0 |
Fixed |
The body’s type refuses a shape its kind cannot take: a triangle mesh, a heightfield or voxels on a dynamic body has no inside to weigh.
Shapes built from a grid
Section titled “Shapes built from a grid”A voxel or tile world is chunk entities, each with a grid field and a collider built from it. voxels({ cellSize, grid }) and heightfield({ grid, size }) name the field rather than carry its cells, so the collider streams a small record. The room and every page build it from the grid and follow each edit: a placed block costs one cell on the wire and one voxel on each end. A change from one solid value to another touches no collider. A heightfield rebuilds once before the next step or query, however many heights changed. A grid of columns sets only the boxes between a column’s old and new heights, as a block map’s chunk does.
The field belongs to a trait on the same entity, and a world that builds the collider without it throws in development, naming the field. Two voxel grids side by side on one lattice are joined at their seam, so a character crossing from one chunk to the next catches on no inside face. Other general engines leave a streamed, editable voxel collider to the game; Rust and Minecraft build theirs in their own code.
import { defineTrait, definePrefab, editGrid, grid, spawn, voxels, type Authority, type Entity,} from "@spawnite/engine";
/** What each cell of a chunk holds. */export enum Block { Air = 0, Stone = 1, Water = 2,}
/** One chunk of a block world: 16 cells a side, each a block. */export const ChunkTrait = defineTrait("chunk", { blocks: grid(Uint16Array, [16, 16, 16]),});
/** A chunk whose collider is its solid blocks: air and water are not. */export const chunk = definePrefab("chunk", { traits: [ChunkTrait], collider: { shape: voxels({ cellSize: 1, grid: ChunkTrait.fields.blocks, empty: [Block.Air, Block.Water], }), },});
/** A chunk at `position`, stone from its floor up to its fourth layer, * spawned from a room system's step or any other authority. */export function spawnChunk( writer: Authority, position: [number, number, number],) { const made = spawn(writer, chunk, { position }); editGrid(writer, made, ChunkTrait.fields.blocks).fill( Block.Stone, [0, 0, 0], [15, 3, 15], ); return made;}
/** Puts `block` in the cell at `x, y, z`: one cell on the wire, and one * voxel in the collider on every end. */export function placeBlock( writer: Authority, target: Entity, cell: readonly [x: number, y: number, z: number], block: Block,) { editGrid(writer, target, ChunkTrait.fields.blocks).set( cell[0], cell[1], cell[2], block, );}A shape a game generates from a seed is a builder: defineShapeBuilder("island", ({ seed }) => triangleMesh(generateIsland(seed))) returns a function, and collider: { shape: islandShape({ seed: 7 }) } streams the builder’s name and the record alone. Both ends run the builder on the record, rounded as the stream rounds numbers, so a builder reads its record and nothing else. It returns a triangleMesh, a heightfield or voxels({ cellSize, cells }). The room sends a hash of what it built, and a development page that builds another shape throws, naming the builder: math such as Math.sin can differ between browsers in its last digits, which the rounding absorbs in most cases.
Colliders turn and scale with the entity, offsets included, so a box tilted on x is a ramp a walker climbs, and a box of size [1, 1, 1] at scale [4, 1, 8] is a 4 by 1 by 8 box. A sphere takes one scale on every axis, and a capsule, a cylinder and a cone the same scale across x and z. A collider turned in its entity takes one scale on every axis, since a turned box would shear. Any other scale throws when the body is built, naming the shape.
A model’s hull wraps the corners its manifest entry holds, its collider’s own where it has them, so its body stands before the model loads, and in a room, which loads no model. A model registered by a bare url, or baked with hullPoints: false, has no corners, so the Entity throws into the game’s boundary, naming the model. A hull thin in one direction, such as a rug’s or a post’s, gets a body a centimetre past its points across that direction. A hull Rapier refuses, such as a slender pole of many sides, falls back to the box around its points, which every world warns about once. Give such a model a box or a capsule collider.
Layers
Section titled “Layers”A body stands in one collisionLayer and meets the layers its collisionMask lists. Two bodies touch only when each one’s mask holds the other’s layer, the rule Rapier and PlayCanvas use; Godot passes a pair when either mask holds the other’s. A mask is a list of layers, { except: [...] } for every layer but those, or every layer when left out.
A plugin declares its own layers by name, definePlugin(() => ({ name: "pitch", collisionLayers: ["karts", "ball"] })), and a body names each by its handle, pitch.collisionLayers.ball. The core reserves CoreLayers.default, where every body stands that names none, and CoreLayers.ground, where the terrain, its edge walls and its scatter stand. characters() declares characters.collisionLayers.players and npcs, which every world numbers. That leaves 12 of Rapier’s 16 for a game’s plugins, numbered in list order, and a world whose plugins declare more refuses to be made, naming each plugin and its count. A page and its room compare the numbering at the welcome.
pushes, on a kinematic body, lists the dynamic layers it pushes, every layer of its mask when left out. A kart that leaves the ball out still meets it and passes through, so the game’s own system decides the kick.ignore: [entity]skips the pairs between this body and the entities named, such as a rider and the rider’s own dragon, without spending a layer.membersOnly, a prop of the Entity and a spawn option, keeps it to its match. It meets its match’s members and entities and every fixed body and platform, and passes characters and moving bodies outside the match, such as a court’s net a passer-by walks through.- A
triggercollider touches nothing and weighs nothing unless its material says so; its entry and exit events arrive with the contacts step.
Mass, damping and materials
Section titled “Mass, damping and materials”A dynamic body’s mass is its colliders’ density times their volume, at Rapier’s density 1, so a 1 m crate weighs 1 kg. mass sets the total in kilograms over the densities, and centerOfMass, in the entity’s axes, moves the centre, so a kart sits low. linearDamping, angularDamping, gravityScale, canSleep, enabledRotations and enabledTranslations take Rapier’s and Unity’s meanings. continuousCollision: true stops a fast body at a thin wall; without it, a development world warns once for each body that moves farther in one step than its thinnest collider is thick. A collider’s material takes friction, 0.5 by default, restitution, 0, density, and frictionCombine and restitutionCombine from CombineRule.
Changing a body while it lives
Section titled “Changing a body while it lives”BodyTrait and ColliderTrait hold what the entity declared. A game reads them with readTrait(entity, BodyTrait), never koota’s get, which refuses them by type as it refuses writing them. A game changes them through three verbs on its authoritative step, which edit the body in place, so it keeps its velocity, its sleep and the pairs it holds, and each change streams:
setBody(step, entity, changes)changes its kind, layer, mask,pushes,ignore, mass and the rest:setBody(step, crate, { bodyType: RigidBodyType.Kinematic })picks a crate up.setCollider(step, entity, changes, { index })changes one collider’s shape, place, material, trigger flag, layer or mask: a door turned trigger is walked through, and the crate resting on it falls.collisionLayer: nullandcollisionMask: nullgive a collider’s own layer and mask back to its body’s.
A change of an Entity’s own body or collider prop does the same, and a change of its position or rotation prop places its body there, as a teleport does. A dynamic or kinematic body writes its pose back onto the entity every step, so what the children draw falls, rolls and rides with it. The player’s own character has no collider: its capsule is CharacterCapsuleTrait, which the player page describes.
Moving a body
Section titled “Moving a body”A body moves only through the physics: the solver, a force, its next pose or a teleport. Every verb takes the authority first, as setBody does, so a view and a page’s step, which decide nothing, fail to typecheck, and a predicted system narrows with if (step.authoritative) first. Every read takes the world and works anywhere. Vectors are three.js Vector3s or anything with x, y and z; a verb copies what it is given.
applyImpulse(step, ball, kick, { at })changes a dynamic body’s velocity at once, in newton-seconds;at, a point in world space, adds the spin an off-centre kick gives.applyTorqueImpulsedoes the same for its spin.applyForce(step, boat, thrust, { at })andapplyTorque(step, wheel, drive)push for the next physics step alone, as Unity’sAddForcedoes, so a system that stops calling them stops pushing.setLinearVelocityandsetAngularVelocityset a dynamic body’s velocity and spin, in metres and radians a second.setNextPose(step, lift, { position, rotation })sets where a kinematic body stands after the next physics step, as Unity’sMovePositiondoes. The step moves it there with the velocity of the move, so a lift carries the crate on it and a door that swings pushes one aside. A query before the step meets it where it stood. A second call in one tick replaces the position or the rotation it names, so a spin and a bob land together.<Spin>,<Bob>, aVelocityTraitand a track mover move a kinematic body this way, each onto wherereadNextPose(world, entity, into)says an earlier system sent it this tick, so their moves add up. A game’s own mover does the same.movePose(step, entity, { position, rotation })moves an entity that may or may not have a body: a body throughsetNextPose, and an entity with none by its transform, at once. It moves nothing the step has no authority over, such as an entity the room streams to a page.<Spin>,<Bob>and a track mover use it.teleport(step, entity, { position, rotation, keepVelocity? })places a body of any kind at once, with no sweep, keeping its velocity and waking it, as Unity, Godot and Roblox keep a body’s velocity when a script sets its position.keepVelocity: falsestops it, as a respawn wants. A kinematic body arrives without pushing, and every page draws it there with no glide. It answers{ isClear }: false where the body overlaps a fixed or kinematic body there, which marks itStuckTraituntil its next move recovers it. A dynamic body teleported inside a fixed one is pushed out over the next steps, and a development world warns once, naming both. A character takes the same call, as the player page says.moveAndSlide(step, entity, { velocity, rotation?, floorSnapDistance? })moves a kinematic body by a velocity for one tick, sliding along what it meets, as Godot’smove_and_slide()does. It pushes the shape out of anything it starts inside, slides along one surface, follows the crease of two and stops against three. It turns in place and is pushed out of what the turned shape overlaps, and snaps down onto a floor withinfloorSnapDistance. It answers what the move did,slideVelocity,isGrounded,hitsand the rest, as scratch its next call overwrites. On the room the physics step pushes each dynamic body the tick’s move reaches along its net displacement. It refuses a dynamic body and a character, whichmoveCharactermoves.commitPose(step, entity, { position, rotation })moves the step’s own entity to a pose a game computed, with no recovery, push out or slide, as a continuous move rather than a teleport: what a game’s own movement policy commits its result through.wakeUp(step, crate)andsleep(step, crate)wake a dynamic body or put it to sleep. A force, an impulse, a velocity and a teleport each wake it too.readLinearVelocity(world, ball),readAngularVelocity(world, ball)andisSleeping(world, ball)read a body anywhere. On a page, a body the room simulates reads the room’s velocity and sleep from the stream, which sends each awake body’s every send and a sleeping body’s once. The two reads write one vector each that the next call reuses, so copy one to keep it.
A force, a velocity and sleep act on a dynamic body, and setNextPose on a kinematic one. A prefab’s kind refuses the wrong verb by type: applyImpulse on a kart spawn made from a kinematic prefab fails to typecheck. A plain Entity’s kind is read when the verb runs: a development world throws, naming the system and the fix, and a deployed one refuses with a BodyRefusal, "not-dynamic" or "not-kinematic", which the verb returns, logs once and keeps running. So does a write to a body’s transform, which the body does not follow: the next physics step throws in development, naming the entity, and puts the transform back where the body stands deployed ("use-set-next-pose"). A verb on a body spawned in the same tick builds the body at once and acts on it, and a force on a body destroyed in the same tick goes with it.
A prefab that declares its body hands its kind to every entity spawn makes of it: spawn(step, crate) returns a BodyEntity<RigidBodyType.Dynamic>, which a verb for one kind of body reads.
In a room, the room simulates every shared body, and a page holds each one it streams as a stand-in: of its declared kind to every filter, placed at the newest streamed pose and never stepped, so it never drifts. A character on a streamed kinematic body is carried by the room’s velocity for it. A fixed or kinematic body stops a shot in the room and on the page, and so does a dynamic one.
The following file is a pitch on a map with no terrain: layers its plugin declares, a ball, and two karts of two colliders each, one of which leaves the ball out of what it pushes. outsidePitch.test.ts, in the room’s tests, runs it in a real room.
import { box, CoreLayers, createQuery, definePlugin, definePrefab, defineTrait, readEach, RigidBodyType, setNextPose, spawn, sphere, TransformTrait, type AuthoritativeStep, defineSystem, Phase,} from "@spawnite/engine/core";import { Vector3 } from "three";
// A pitch on a map with no terrain, built as a creator's plugin is, from// the engine's public entry alone: a fixed floor, two balls on a layer// the plugin declares, and two karts of two colliders each, a chassis and// a trigger at the nose that meets the ball alone. The room drives both// karts up the pitch; one pushes its ball, and the other, whose `pushes`// leaves the ball out, passes through its own, as a ball kit that applies// its own kick would want.
export const pitch = definePlugin(() => ({ name: "pitch", collisionLayers: ["karts", "ball"], systems: [ defineSystem({ name: "drive", phase: Phase.Rules, run: driveKarts, }), ],}));
/** Metres a second the room drives each kart up the pitch, along +z. */export const kartSpeed = 3;
/** Marks a kart, so the drive finds it. */export const KartTrait = defineTrait("pitchKart");
/** A ball, by the lane it starts in. */export const BallTrait = defineTrait("pitchBall", { lane: 0 });
export const floor = definePrefab("pitchFloor", { collider: { shape: box({ size: [40, 1, 40] }) },});
export const ball = definePrefab("pitchBall", { body: { bodyType: RigidBodyType.Dynamic, mass: 0.45, collisionLayer: pitch.collisionLayers.ball, collisionMask: [CoreLayers.default, pitch.collisionLayers.karts], continuousCollision: true, }, collider: { shape: sphere({ radius: 0.4 }), material: { friction: 0.6, restitution: 0.3 }, },});
/** A kart: its chassis, and a trigger at its nose that meets the ball * alone, its own layer and mask over the body's. */function declareKart(name: string, pushesBall: boolean) { return definePrefab(name, { traits: [KartTrait], body: { bodyType: RigidBodyType.Kinematic, collisionLayer: pitch.collisionLayers.karts, pushes: pushesBall ? [pitch.collisionLayers.ball] : [], }, collider: [ { shape: box({ size: [1.4, 0.5, 2.2] }), offset: [0, 0.35, 0] }, { shape: box({ size: [1.6, 0.8, 0.4] }), offset: [0, 0.6, 1.3], trigger: true, collisionMask: [pitch.collisionLayers.ball], }, ], });}
export const kart = declareKart("pitchKart", true);export const ghostKart = declareKart("pitchGhostKart", false);
const karts = createQuery(KartTrait, TransformTrait);
function driveKarts(step: AuthoritativeStep) { const world = step.world; if (step.tick === 1) { spawn(step, floor, { position: [0, -0.5, 0] }); spawn(step, ball, { position: [-4, 0.4, 0], traits: [BallTrait({ lane: -4 })], }); spawn(step, ball, { position: [4, 0.4, 0], traits: [BallTrait({ lane: 4 })], }); spawn(step, kart, { position: [-4, 0, -4] }); spawn(step, ghostKart, { position: [4, 0, -4] }); return; } readEach(world, karts, (_traits, each) => { const at = each.get(TransformTrait)?.position; if (!at) return; next.set(at.x, at.y, at.z + kartSpeed * step.deltaSeconds); setNextPose(step, each, { position: next }); });}
// Where a kart drives to this tick, written in place for each.const next = new Vector3();The following file kicks a ball the room alone simulates, on the player’s command: the room applies the impulse, and the player’s page reads the ball’s velocity and its sleep from the stream. outsideKick.test.ts, in the room’s tests, runs it in a real room.
import { applyImpulse, box, createQuery, defineCommand, definePlugin, definePrefab, defineTrait, findEntity, readCommands, RigidBodyType, spawn, sphere, type AuthoritativeStep, type PredictedStep, defineSystem, Phase,} from "@spawnite/engine/core";import { Vector3 } from "three";
// A ball a player kicks, on a map with no terrain, built as a creator's// plugin is, from the engine's public entry alone: the room spawns a// fixed floor and a ball only it simulates, and a kick by the player// sends the ball up the pitch with an impulse. The player's page holds// the ball as a stand-in, and reads its velocity and its sleep// from the stream.
/** The kick, in newton-seconds along +z: 2.4 m/s on a 0.45 kg ball. */export const kickImpulse = new Vector3(0, 0, 1.08);
/** Marks the ball, so the kick finds it. */export const KickBallTrait = defineTrait("kickBall");const kickBalls = createQuery(KickBallTrait);
export const kicks = definePlugin(() => ({ name: "kicks", commands: { kick: defineCommand({}, { predicted: true, entity: true }) }, systems: [ defineSystem({ name: "kick", phase: Phase.Input, predicted: true, answers: ["kick"], run: kickBall, }), defineSystem({ name: "setUp", phase: Phase.Rules, run: setUpPitch, }), ],}));
const floor = definePrefab("kickFloor", { collider: { shape: box({ size: [40, 1, 40] }) },});
const ball = definePrefab("kickBall", { traits: [KickBallTrait], body: { bodyType: RigidBodyType.Dynamic, mass: 0.45, linearDamping: 1, angularDamping: 1, }, collider: { shape: sphere({ radius: 0.4 }) },});
/** The room's pitch, on its first tick: a floor at height 0 and the ball * resting on it, away from where the player's character stands. */function setUpPitch(step: AuthoritativeStep) { if (step.tick !== 1) return; spawn(step, floor, { position: [0, -0.5, 0] }); spawn(step, ball, { position: [6, 0.4, 0] });}
/** Kicks the ball on each of the player's kicks, on the room alone: the * player's page, whose step is no authority, takes the command and leaves * the ball to the stream. */function kickBall(step: PredictedStep) { const world = step.world; const kicked = findEntity(world, kickBalls); for (const command of readCommands(step, kicks.commands.kick)) { if (step.authoritative && kicked) applyImpulse(step, kicked, kickImpulse); command.accept(); }}A body driven by the tick
Section titled “A body driven by the tick”A ball that flies from each hit, a volleyball or a thrown ball, is a kinematic body whose motion is a flight({...}): its path between two launches is a function of the tick and its last launch. The room and every page compute it to the bit from + - * / and Math.sqrt, a re-run included, so the stream carries one record a launch rather than a pose each send. Its settings and each launch are held at the stream’s precision, a tenth of a millimetre, so every world flies the same numbers. As Unreal’s projectile movement, narrowed to boxes so every world agrees.
flight({ gravityScale, drag, restitution, bounceOff, landOn })declares it.gravityScaletakes the scene’s gravity, read at each launch, so a later change never bends a ball in the air.dragis quadratic, per metre, as the track mover’s.restitutionis the share of its speed into a surface a bounce keeps.bounceOffandlandOnlist boxes in world space,{ shape: box({ size }), position, rotation? }. It bounces off the first, edges and corners included, and stops on the second. It passes through every other collider, so a wall it should meet goes in a list. It takes four contacts a tick, then stops for the tick;contactsPerTickraises it for a fast ball in a narrow space.- Its collider is one sphere at the body’s origin, which it sweeps. Queries meet it, as Unreal’s Query Only; it pushes nothing, reports no contacts of its own, and a character walks through it.
launchFlight(step, ball, velocity, { position? })launches it from where it stands at the step’s tick, or fromposition. A query later in the same tick meets it there.holdFlight(step, ball, { position? })holds it still, as a ball in a server’s hands;teleportholds it at the new spot, or relaunches it from there withkeepVelocity.readFlight(step, ball)answers itsposition,velocity,landedTickandisHeldat the step’s tick, andreadFlight(world, ball, { tick })at any tick outside a step. Each answer is written in place, so copy what you keep.setNextPoserefuses it with"use-launch-flight"andmoveAndSlidewith"flight-mover", and a transform written directly throws in development, as for any body.FlightLaunchedEventreaches every page that holds the ball with each launch, hold and teleport and its record, in order, though a send carries the last record alone: a hit’s sound reads it.- A page draws the ball at its own tick.
display: Display.NearestPlayerbesidemotiondraws a shared ball on the nearer player’s clock instead, as Draw the ball on the nearer player’s clock describes.
The engine’s exact sine, cosine, arcCosine and exponential aim a launch the same way on every world, where Math.sin can differ in the last digit, and a game’s lint warns of Math.sin in its .ts files.
A ball game’s aim assist solves by flight time rather than by angle, so it needs no trigonometry. solveFlight(from, to, { seconds, gravity, deltaSeconds }) answers the launch velocity that puts the ball’s centre on to once seconds has passed, rounded up to whole ticks. It uses + - * / alone, and its answer is written in place, so copy what you keep. Give it step.deltaSeconds, so it matches the way a flight steps, and the flight’s gravity, the scene’s times its gravityScale.
solveFlightSeconds(from, to, { gravity, clearance: { distance, height }, minimumSeconds, deltaSeconds }) answers the shortest time whose arc clears a height at a distance along the path, such as a net’s top plus the ball’s radius. It never answers less than minimumSeconds, such as a reaction floor. It answers the fewest whole ticks whose launched path clears the height, the straight line between ticks included. Both are pure, so a predicted command’s reader, the room and a bot solve the same numbers to the same bits. Unity and Godot ship no such solver, and Unreal’s SuggestProjectileVelocity solves by speed and answers an angle.
The following file serves a ball over a net onto a court, and serves again a second after each landing. outsideRally.test.ts, in the room’s tests, runs it in a real room:
import { box, createQuery, definePlugin, definePrefab, defineSystem, defineTrait, flight, launchFlight, Phase, readEach, readFlight, RigidBodyType, spawn, sphere, type AuthoritativeStep,} from "@spawnite/engine/core";import { Vector3 } from "three";
// A rally on a court with no terrain, built as a creator's plugin is, from// the engine's public entry alone: a volleyball that flies from each// serve, off the net and onto the court, and a room rule that serves it// again a second after it lands. Every page computes each flight from its// record, so the stream carries one record a serve.
export const rally = definePlugin(() => ({ name: "rally", systems: [defineSystem({ name: "serve", phase: Phase.Rules, run: serve })],}));
/** Marks the ball, so the serve finds it. */export const BallTrait = defineTrait("rallyBall");
/** The net, 9 m wide and 1 m tall, its top at 2.43 m, and the court. */const net = { shape: box({ size: [9, 1, 0.1] }), position: [0, 1.93, 0] as const,};const court = { shape: box({ size: [9, 0.2, 18] }), position: [0, -0.1, 0] as const,};
export const volleyball = definePrefab("rallyBall", { traits: [BallTrait], body: { bodyType: RigidBodyType.Kinematic, motion: flight({ drag: 0.02, restitution: 0.4, bounceOff: [net], landOn: [court], }), }, collider: { shape: sphere({ radius: 0.105 }) },});
/** Where each serve leaves from, behind the back line, and how fast. */export const serveSpot = new Vector3(0, 2, -8);export const serveVelocity = new Vector3(0, 6, 9);
/** Ticks the ball rests after it lands before the next serve. */export const restTicks = 60;
const balls = createQuery(BallTrait);
function serve(step: AuthoritativeStep) { if (step.tick === 1) { spawn(step, volleyball, { position: [serveSpot.x, serveSpot.y, serveSpot.z], }); return; } readEach(step.world, balls, (_traits, ball) => { const flown = readFlight(step, ball); if (!flown) return; const rested = flown.landedTick !== null && step.tick >= flown.landedTick + restTicks; if (flown.isHeld || rested) launchFlight(step, ball, serveVelocity, { position: serveSpot }); });}Joints
Section titled “Joints”A joint holds two bodies together on every physics step, or one body to the world, so they move as one machine: a gate on its post, a trailer behind a kart, a fence panel that breaks off. Each joint is an entity of its own, which createJoint(step, body, options) makes and returns, and <Joint> makes inside an <Entity> while it is mounted. No prefab field declares a joint. Both take the following options:
typeisJointType.Fixed,Hinge,Slider,BallAndSocket,SpringorRope, the words Unity, Godot and Roblox use, where Rapier says revolute, prismatic and spherical.tonames the other body’s entity; left out, the joint holds its body to the world.anchoris where it holds, in its body’s own axes, andconnectedAnchorwhere it holds on the other body; left out, it is whereveranchorlies on the other body when the joint is made, as Unity’sautoConfigureConnectedAnchordoes. A spring or a rope spans to the other body’s origin instead.- A hinge turns about its
axisand a slider moves along it, in its body’s axes,[0, 1, 0]for a hinge and[1, 0, 0]for a slider when left out.limits: { min, max }stop it, in radians or metres from the pose the two bodies had when the joint was made, signed by the right-hand rule about the axis.motor: { targetPosition, targetVelocity, stiffness, damping, maxForce }drives it, so a gate closes itself. - A ball-and-socket turns freely about its anchor, within
limits: { swingRadians, twist }.swingRadiansis the half-angle of the cone itsaxisleans within, andtwistis the{ min, max }in radians it turns about that axis. Leave either out to leave that motion free. Both are hard stops, with no give. - A ball-and-socket’s
axis, in its body’s axes, is[0, 1, 0]when left out. It rests alongconnectedAxis, the cone’s centre, in the other body’s axes or the world’s for a joint to the world. Name the same line of the body in both: a reversed one turns the rest half a turn. - Left out,
connectedAxisis where the axis lay when the joint was made, so give it for a ragdoll made in a bind pose. Given, the twist’s zero stays as near the made pose as it can. motor: { targetRotation, targetAngularVelocity, stiffness, damping, maxForce }turns a ball-and-socket toward a rotation by the shortest arc. The rotation is from its rest, in its body’s own axes, as Euler angles in radians or a quaternion.maxForcecaps each of the joint’s three axes, so a push on a diagonal can reach √3 times it.- A motor’s
stiffnessanddampingare 0 and itsmaxForcehas no cap when left out, so a motor given only a target does nothing. Both scale with the body’s inertia: √stiffnessis about the rate it swings at, in radians a second. - A motor pulls with its body’s inertia about its centre, so an arm held out against its weight rests a little short of its target, less as
stiffnessrises. A long thin limb swings past its target more than a round body at the same tuning; raisedampingfor it. - A spring takes
restLength,stiffnessanddamping, and a ropelength, each the bodies’ distance when left out. breakForce, in newtons, andbreakTorque, in newton-metres, break it. On the step the force or the torque it holds with passes its threshold, the joint goes andJointBrokenEventlands on its entity with the force, the torque and both bodies. The entity is destroyed the next tick.readJointReaction(world, joint)reads the same force and torque for any joint.collideConnected: truelets the two bodies collide, which a joint stops by default.
setJoint(step, joint, changes) changes a live joint’s motor, limits, lengths and break thresholds, each where its type has one: a crane’s arm follows its lever. New limits replace all of the joint’s limits, and a motor change keeps each field it leaves out. It refuses a motor on a rope, a hinge’s { min, max } on a ball-and-socket, or a range the solver cannot hold, such as a twist of a full turn: a throw in development and a JointRefusal deployed, the joint left as it was. createJoint throws for the same ranges, in a built game too, where <Joint> logs it and makes no joint.
A joint’s anchors move with its bodies’ scales. A body that attach holds to another leaves its joints until detach lets it go. A joint goes with either body, in the same tick, with no JointBrokenEvent, and destroy(step, joint) unhitches it. Both bodies must be simulated by the same world: the room’s two, or two a page holds alone. In a room the room simulates every shared joint, and each page holds its entity, whose JointTrait names both bodies, to draw a rope or a chain between them.
The following file hitches a trailer behind a kart the room drives. outsideTrailer.test.ts, in the room’s tests, runs it in a real room.
import { box, createJoint, createQuery, definePlugin, definePrefab, defineTrait, JointType, readEach, RigidBodyType, setNextPose, spawn, TransformTrait, type AuthoritativeStep, defineSystem, Phase,} from "@spawnite/engine/core";import { Vector3 } from "three";
// A trailer behind a kart, on a map with no terrain, built as a creator's// plugin is, from the engine's public entry alone. The room spawns a// fixed floor, a kinematic kart it drives up the pitch and a dynamic// trailer hitched to it on a ball joint, and the kart drags the trailer.// The player's page holds both as stand-ins and the hitch as the joint's// entity, which names both bodies, to draw it between them.
/** Metres a second the room drives the kart, along +z. */export const towSpeed = 2;
/** Marks the kart and the trailer. */export const TowKartTrait = defineTrait("towKart");export const TowTrailerTrait = defineTrait("towTrailer");
export const towing = definePlugin(() => ({ name: "towing", systems: [ defineSystem({ name: "tow", phase: Phase.Rules, run: towTrailer, }), ],}));
const floor = definePrefab("towFloor", { collider: { shape: box({ size: [40, 1, 40] }) },});
const kart = definePrefab("towKart", { traits: [TowKartTrait], body: { bodyType: RigidBodyType.Kinematic }, collider: { shape: box({ size: [1.4, 0.5, 2] }) },});
const trailer = definePrefab("towTrailer", { traits: [TowTrailerTrait], body: { bodyType: RigidBodyType.Dynamic, mass: 40 }, collider: { shape: box({ size: [1.2, 0.5, 1.6] }) },});
const karts = createQuery(TowKartTrait, TransformTrait);// Where the kart drives to this tick, written in place.const next = new Vector3();
/** The pitch on the room's first tick, the trailer hitched behind the * kart, then the kart driven up it each tick after. */function towTrailer(step: AuthoritativeStep) { const world = step.world; if (step.tick === 1) { spawn(step, floor, { position: [0, -0.5, 0] }); const towing = spawn(step, kart, { position: [6, 0.3, 0] }); const towed = spawn(step, trailer, { position: [6, 0.3, -2.2] }); createJoint(step, towed, { type: JointType.BallAndSocket, to: towing, anchor: [0, 0, 1.1], }); return; } readEach(world, karts, (_traits, each) => { const at = each.get(TransformTrait)?.position; if (!at) return; next.set(at.x, at.y, at.z + towSpeed * step.deltaSeconds); setNextPose(step, each, { position: next }); });}The following file hangs a ragdoll’s arm on a ball-and-socket, shoves it against its cone, then drives it back with the joint’s motor. outsideRagdoll.test.ts, in the room’s tests, runs it in a real room.
import { applyImpulse, box, createJoint, createQuery, definePlugin, definePrefab, defineSystem, defineTrait, JointTrait, JointType, Phase, readEach, readTrait, RigidBodyType, setJoint, spawn, TransformTrait, type AuthoritativeStep,} from "@spawnite/engine/core";import { Vector3 } from "three";
// A ragdoll's arm on a shoulder, on a map with no terrain, built as a// creator's plugin is, from the engine's public entry alone: the room// hangs the arm on a ball-and-socket whose cone points out and down from// the shoulder, shoves it hard for a second, which the cone stops, then// turns on the joint's motor, which lifts the arm back to the cone's// centre and turns it a little about its own length.
/** The cone's half-angle: the arm leans at most this far from its centre. */export const armSwingRadians = Math.PI / 4;/** The motor's target: the arm turned 0.3 rad about its own y, at rest. */export const armTarget: [number, number, number] = [0, 0.3, 0];/** The tick the room stops shoving the arm and starts its motor. */export const motorTick = 60;
/** Marks the shoulder and the arm. */export const ShoulderTrait = defineTrait("ragdollShoulder");export const ArmTrait = defineTrait("ragdollArm");
export const ragdolls = definePlugin(() => ({ name: "ragdolls", systems: [ defineSystem({ name: "swingArm", phase: Phase.Rules, run: swingArm, }), ],}));
const shoulder = definePrefab("ragdollShoulder", { traits: [ShoulderTrait], body: { bodyType: RigidBodyType.Fixed }, collider: { shape: box({ size: [0.3, 0.3, 0.3] }) },});
const arm = definePrefab("ragdollArm", { traits: [ArmTrait], body: { bodyType: RigidBodyType.Dynamic, mass: 3 }, collider: { shape: box({ size: [0.12, 1, 0.12] }) },});
const arms = createQuery(ArmTrait, TransformTrait);const joints = createQuery(JointTrait);// The hand, where the room shoves the arm, written in place.const hand = new Vector3();const handBelow = new Vector3(0, -0.5, 0);const shove = new Vector3();
/** The shoulder and its arm on the room's first tick, the arm shoved * sideways each tick until `motorTick`, then the joint's motor on. */function swingArm(step: AuthoritativeStep) { if (step.tick === 1) { const body = spawn(step, shoulder, { position: [0, 3, 0] }); const limb = spawn(step, arm, { position: [0, 2.35, 0] }); createJoint(step, limb, { type: JointType.BallAndSocket, to: body, anchor: [0, 0.5, 0], // the arm's top axis: [0, -1, 0], // down the arm, toward the hand connectedAxis: [1, -1, 0], // the cone points out and down limits: { swingRadians: armSwingRadians, twist: { min: -0.5, max: 0.5 }, }, }); return; } if (step.tick === motorTick) { // Its rest is the cone's centre: the motor lifts the arm there, // turned by the target, stiff enough to hold up its own weight. // Only the arm's joints: the game's other joints are not its. readEach(step.world, joints, (_traits, joint) => { if (!readTrait(joint, JointTrait)?.body?.has(ArmTrait)) return; setJoint(step, joint, { motor: { targetRotation: armTarget, stiffness: 2000, damping: 60, }, }); }); return; } if (step.tick > motorTick) return; readEach(step.world, arms, (_traits, each) => { const transform = each.get(TransformTrait); if (!transform) return; hand.copy(handBelow) .applyQuaternion(transform.rotation) .add(transform.position); applyImpulse(step, each, shove.set(0, 0, 40 * step.deltaSeconds), { at: hand, }); });}Queries
Section titled “Queries”A query asks the scene what is there and names the entity it meets: the crate, the ground for a hit on terrain, its edge walls or its scatter, and the character for a hit on its capsule. Five calls cover what Unity’s Physics.Raycast, RaycastAll, SphereCast, OverlapBox and CheckSphere do:
castRay(step, { from, direction, maxDistance })returns the nearest hit, or null. A hit holds itsentity, itspointand the surface’snormalin world space, itsdistancealong the direction, andcolliderIndex, the place of the collider it met in its entity’scolliderlist. A ray that starts inside a collider meets it at distance 0.directiontakes any length but zero, andmaxDistancereaches without end when left out.castRayAllreturns every collider the ray meets, nearest first, one hit per collider.castShape(step, { shape, from, rotation, direction, maxDistance })sweeps a shape and returns the nearest hit, withwitness, the point of the shape that touched. A shape that starts inside a collider meets it at distance 0 where its move leads further in, and passes out of it where the move leads out.overlapShape(step, { shape, position, rotation })returns each entity the shape overlaps where it stands, once however many of its colliders it overlaps. It samples one pose: a swing that must hit all it passes through overlaps at several poses along it, as the file below does, or casts its blade withcastShape.isTouching(step, entity, options)answers whether any of the entity’s colliders overlaps or lies within 2 cm of what the filter meets, or of the one entityothernames, even a trigger. A predicted system asks it, since a re-run hears no event: a character standing on lava touches it, though its capsule floats a centimetre above.
A query’s shape is box, sphere, capsule, cylinder, cone or convexHull({ points }), by type: a triangle mesh, a heightfield, voxels and a model’s hull are a body’s alone. Every query takes the same filter:
collisionMask, the layers it meets, every layer when left out.collisionLayer, the layer it stands in, so it meets only colliders whose own mask holds it, as a body there would. Left out, it stands in every layer, which a collider whose mask is empty never meets.ignore, entities it passes through, such as the caster’s own, where one destroyed since passes silently.includeTriggers: trueto meet trigger colliders, which a query passes through by default, as Unity’sQueryTriggerInteractiondoes.bodyTypes, the kinds it meets, read as each body declares its kind, so a page’s stand-in for a ball the room rolls counts as dynamic.asEntity, the entity the query is asked for, or an instigator, so it passes themembersOnlyentities of matches that entity is outside of. Left out, it meets every body, and a development world warns once when it meets amembersOnlyone;nullasks room-wide.
castRay, castRayAll, castShape and overlapShape also take rewind, which meets every other moving body the stream draws where one player’s screen showed it. rewind: command judges a shot the player sent as a command where the player saw their target, as the weapon page shows. It moves no body and steps nothing, so a query with it costs a recording, a re-run or a continue nothing. In a game played alone it meets the present.
Two hits as near as each other come in order of entity id, and so do an overlap’s entities.
A query takes the step in a system and the world in a view. Through the step it meets the tick as its systems wrote it: a body spawned earlier in the tick, built at once; one destroyed, gone; one teleported, where it now stands. A kinematic body’s setNextPose takes effect at the physics step, so a query before it meets the body where it stood. Through the world it reads the scene as the last physics step left it, so a frame’s queries never vary the work a world does. On a page, a stand-in stands where the newest delta put it, a send ahead of where the view draws it; a view that picks what it draws under a cursor keeps three.js’s raycaster on drawn meshes. Before the scene’s first body, and while Rapier loads for it, a query meets nothing.
A result is pooled, as a readEvents list is, so a query allocates nothing as it runs each tick: it holds until the system that asked returns, and in a view until the next query. Copy a field to keep it. A direction that points nowhere, a negative maxDistance and a hull whose points wrap no body throw in development, naming the system, and meet nothing deployed, logged once.
The following file swings a sword on the player’s command: the room overlaps the blade’s box at three poses of an arc in front of the player’s character, on a layer its plugin declares, and strikes each training post it meets once a swing. outsideSword.test.ts, in the room’s tests, runs it in a real room.
import type { Entity } from "@spawnite/engine/core";import { box, cylinder, defineCommand, definePlugin, definePrefab, defineTrait, overlapShape, readCommands, RigidBodyType, setTrait, spawn, TransformTrait, type AuthoritativeStep, type PredictedStep, defineSystem, Phase,} from "@spawnite/engine/core";import { Quaternion, Vector3 } from "three";
// A sword a player swings with a command, built as a creator's plugin is,// from the engine's public entry alone. The room spawns training posts on// a layer the plugin declares. A swing by the player sweeps the blade's// box through three poses of an arc in front of the character,// overlapping each, so a post the arc passes through is struck once a// swing, however many of the poses overlap it. A crate in the arc stands// in no layer the blade meets. The player's page reads each post's count// from the stream.
/** Marks a training post, and counts the swings that struck it. */export const PostTrait = defineTrait("swordPost", { hits: 0 });
export const swords = definePlugin(() => ({ name: "swords", collisionLayers: ["posts"], commands: { swing: defineCommand({}, { predicted: true, entity: true }) }, systems: [ defineSystem({ name: "swing", phase: Phase.Input, predicted: true, answers: ["swing"], run: swingSwords, }), defineSystem({ name: "setUp", phase: Phase.Rules, run: setUpYard, }), ],}));
const post = definePrefab("swordPost", { traits: [PostTrait], body: { bodyType: RigidBodyType.Fixed, collisionLayer: swords.collisionLayers.posts, }, collider: { shape: cylinder({ radius: 0.2, height: 2 }) },});
const crate = definePrefab("swordCrate", { collider: { shape: box({ size: [0.6, 0.6, 0.6] }) },});
/** The yard on the room's first tick: two posts before where the * player's character stands, facing down -z, one behind the * character, and a crate. */function setUpYard(step: AuthoritativeStep) { if (step.tick !== 1) return; spawn(step, post, { position: [-0.75, 1, -0.75] }); spawn(step, post, { position: [0.75, 1, -0.75] }); spawn(step, post, { position: [0, 1, 2] }); spawn(step, crate, { position: [0, 1, -1] });}
/** The blade: a box a metre and a half long, held out from * the character's middle. */const blade = box({ size: [0.1, 0.1, 1.5] });/** Radians either side of the character's facing the * arc runs through. */const arc = Math.PI / 4;const struck = new Set<Entity>();const turn = new Quaternion();const facing = new Quaternion();const up = new Vector3(0, 1, 0);const tip = new Vector3();
/** Sweeps one swing of `character`'s blade, on the room alone: three * overlaps along the arc, each post struck once. */function swing(step: AuthoritativeStep, character: Entity) { const pose = character.get(TransformTrait); if (!pose) return; struck.clear(); for (const share of [-1, 0, 1]) { turn.setFromAxisAngle(up, share * arc).premultiply( facing.copy(pose.rotation), ); // A body faces down -z at rest: the blade's middle 0.9 m ahead. tip.set(0, 1, -0.9).applyQuaternion(turn).add(pose.position); const poses = overlapShape(step, { shape: blade, position: tip, rotation: turn, collisionMask: [swords.collisionLayers.posts], }); for (const { entity } of poses) struck.add(entity); } for (const hit of struck) setTrait(step, hit, PostTrait, { hits: (hit.get(PostTrait)?.hits ?? 0) + 1, });}
/** Swings on each of the player's swings, on the room alone: the player's * page, whose step is no authority, takes the command and leaves the posts * to the stream. */function swingSwords(step: PredictedStep) { for (const command of readCommands(step, swords.commands.swing)) { if (step.authoritative) swing(step, command.entity); command.accept(); }}Contacts and triggers
Section titled “Contacts and triggers”A contact and a trigger are events in the log, read with readEvents as any other, one per pair of entities however many of their colliders touch:
CollisionEnteredEventlands on each entity of a pair that declaresreportContacts: trueon its body, the step the two first touch, andCollisionExitedEventthe step their last touching colliders part or one of them is destroyed. The entry’s record names theotherentity and itsotherDumpKey, which outlives it, thepointand thenormalfrom this entity to the other, and therelativeVelocity. TherelativeVelocityis the other’s velocity at the point less this one’s before the step’s solve, so a box dropped at 5 m/s reads about 5 m/s. The record also names the solver’simpulse, and which collider of each touched,colliderIndexandotherColliderIndex. Reporting is opt-in, as Rapier’s active events and Godot’scontact_monitorare, so a pile of crates nobody watches costs nothing. A collision event stays on the world that emits it: a system that wants pages to hear a touch emits its own event.TriggerEnteredEventlands on a trigger, an entity with a collider oftrigger: true, the step an entity first overlaps any of its colliders, andTriggerExitedEventthe step it overlaps none, or either is destroyed. Each event comes withother,otherDumpKeyand, on the entry, the trigger’scolliderIndex. A trigger reports always, and its events reach every page that holds it. A kinematic body, a character’s capsule among them, enters a fixed trigger, and two kinematic bodies report a touch when either asks.readTriggerOccupants(world, trigger)lists who stands inside a trigger now, the state its events report, so a reader added after an entry finds who is inside. It answers where the trigger is simulated: on a page, a trigger the room streams throws in development, and a page asksisTouching(step, character, { other: trigger })for the local player’s own character.- The engine’s behaviours Trigger, Pickup, Interact and Loot sit on volumes of their own: a sphere of their
radiusthat meets theirtargetsby their bodies, as a trigger collider does, with no collider on the entity. Trigger raises the same two events for each target,readTriggerOccupantsreads its occupants, andisTouchingmeets its sphere.
A trigger samples what overlaps it at each physics step. An entity inside it at spawn enters at the first step, and a teleport into it enters and one out of it exits at the next step. A teleport from one side to the other in one tick raises nothing, as a ball faster than the trigger is deep can cross it unseen. A destroy ends every pair its entity held in the same tick, with the exits, and other reads null to a reader once that entity is gone. A body asleep in a trigger stays inside it with no second entry. Whether two entities still touch on a later step is isTouching; there is no event per step a pair stays in touch, as Unity’s OnCollisionStay raises, since a system that asks reads the state. A page raises events only for the bodies it holds alone, never for two stand-ins, and a re-run steps no world, so it raises none. In development, a step that emits more than 1,024 contact and trigger events warns, naming the entity with the most.
The following file scores a ball on a goal trigger. outsideGoal.test.ts, in the room’s tests, runs it in a real room.
import { applyImpulse, box, CollisionEnteredEvent, createQuery, defineCommand, definePlugin, definePrefab, defineTrait, findEntity, readCommands, readEvents, RigidBodyType, setLinearVelocity, setTrait, spawn, sphere, teleport, TriggerEnteredEvent, type AuthoritativeStep, type PredictedStep, defineSystem, Phase,} from "@spawnite/engine/core";import { Vector3 } from "three";
// A goal that scores a ball, on a map with no terrain, built as a// creator's plugin is, from the engine's public entry alone: the room// spawns a floor, a ball that reports its contacts and a goal trigger// down the pitch. A kick by the player sends the ball at the goal; the// room scores on the trigger's entry, puts the ball back on its spot,// and counts each time the ball touches something. The player's page// reads the score from the stream; the contact events stay on the room.
/** The score and the ball's knocks, on the goal, which streams. */export const GoalTrait = defineTrait("goalCount", { goals: 0, knocks: 0 });/** Marks the ball. */export const GoalBallTrait = defineTrait("goalBall");
/** Where the ball rests before each kick. */export const ballSpot = new Vector3(0, 0.4, 0);/** The kick, in newton-seconds along -z: about 5 m/s on a 0.45 kg ball. */const kick = new Vector3(0, 0, -2.25);
export const goals = definePlugin(() => ({ name: "goals", commands: { kick: defineCommand({}, { predicted: true, entity: true }) }, systems: [ defineSystem({ name: "kick", phase: Phase.Input, predicted: true, answers: ["kick"], run: kickBall, }), defineSystem({ name: "score", phase: Phase.Rules, run: scoreGoals, }), ],}));
const floor = definePrefab("goalFloor", { collider: { shape: box({ size: [20, 1, 40] }) },});
const ball = definePrefab("goalBall", { traits: [GoalBallTrait], body: { bodyType: RigidBodyType.Dynamic, mass: 0.45, reportContacts: true, }, collider: { shape: sphere({ radius: 0.4 }) },});
const goal = definePrefab("goalMouth", { traits: [GoalTrait], collider: { shape: box({ size: [4, 2, 1] }), trigger: true },});
const balls = createQuery(GoalBallTrait);const mouths = createQuery(GoalTrait);
/** The pitch on the room's first tick, then each goal scored and each * knock of the ball counted on the goal. */function scoreGoals(step: AuthoritativeStep) { const world = step.world; if (step.tick === 1) { spawn(step, floor, { position: [0, -0.5, 0] }); spawn(step, ball, { position: ballSpot.toArray() }); spawn(step, goal, { position: [0, 1, -12] }); return; } const mouth = findEntity(world, mouths); const count = mouth?.get(GoalTrait); if (!mouth || !count) return; let { goals: scored, knocks } = count; for (const entered of readEvents(step, TriggerEnteredEvent)) { const scorer = entered.record.other; if (entered.entity !== mouth || !scorer?.has(GoalBallTrait)) continue; scored++; teleport(step, scorer, { position: ballSpot }); setLinearVelocity(step, scorer, new Vector3()); } knocks += readEvents(step, CollisionEnteredEvent).length; if (scored !== count.goals || knocks !== count.knocks) setTrait(step, mouth, GoalTrait, { goals: scored, knocks });}
/** Kicks the ball at the goal on each of the player's kicks, on * the room alone. */function kickBall(step: PredictedStep) { const world = step.world; const kicked = findEntity(world, balls); for (const command of readCommands(step, goals.commands.kick)) { if (step.authoritative && kicked) applyImpulse(step, kicked, kick); command.accept(); }}Behaviours
Section titled “Behaviours”A behaviour is a child component of an Entity, never a prop. Spin, Bob, Pickup, Interact, Trigger, Health, Chase and TrackMover compose on any Entity. Each is a trait, a system and a component; the component adds the trait on mount, sets it on prop change and removes it on unmount. A trait is koota’s word for one piece of state on an entity, and the name of a trait a file exports ends in Trait, as SpinTrait below does, so it never takes the name of the component that adds it.
Each behaviour also declares, as runsOn on the behaviour defineBehaviour makes, where a consequence of it is trusted. This is not where its system runs: the system’s entry in its plugin says that, as Where a system runs shows. The engine’s Spin declares RunContext.Client, and its system’s entry runs on the room and on each page.
RunContext.Client, the default: a page may hear the behaviour and answer it, so its component may take a callback for the page’s own UI. Spin, Bob, Interact and Trigger declare it, which is how Interact’sonInteractand Trigger’sonEnterandonExittake a function.RunContext.ServerorRunContext.Both: the room decides the behaviour’s consequence, so its component takes no function prop. Pickup, Health, Chase and Lock declareServer, and the character’s movement declaresBoth.
Every behaviour component is one call to useBehaviour(behaviour, value), which adds, sets and removes the trait on the nearest Entity. A game tags an entity with a trait of its own the same way, such as a boss’s BossTrait or a gate’s keys: defineBehaviour for the trait, and a component inside the <Entity> that calls useBehaviour. An entity.add in a useEffect leaves the trait out of the devtools’ Add behaviour and the Wiki tab, and writes it on a page’s copy of an entity that a room streams, where useBehaviour leaves the room’s copy to say. A game’s lint reports a trait added or removed in a useEffect, engine/effect-trait, and a trait written from any other part of a component or a hook, engine/view-outcome. A system may destroy the entity mid-frame, a pickup being the usual case. The children unmount on React’s next commit, so the rest of that frame still runs: a frame callback that reads its entity checks isAlive() first, as the hook and Entity’s own cleanup do.
defineBehaviour runs once, when its file is imported, and returns the behaviour typed by its trait, so useBehaviour checks the props a component passes. Its name is the name the devtools’ Add behaviour offers it by, and the name the dump writes its trait under unless defineTrait made the trait, which keeps its own name. Each name belongs to one behaviour, and a behaviour whose trait has no name of its own shares the dump’s names with traits: a second definition under a name already taken throws and names both. A module that hot reload runs again defines its own anew, and each new definition takes its name. So does every module after beginDefinitionReload(), which a host that runs a game’s modules again in one process calls first, as a watched room does on an edit. One module defining one name twice is refused like any other pair.
import { defineTrait } from "@spawnite/engine/core";import { defineBehaviour, RunContext, useBehaviour } from "@spawnite/engine";
const SpinTrait = defineTrait("spin", { speed: 1 });
const SpinBehaviour = defineBehaviour({ name: "spin", trait: SpinTrait, runsOn: RunContext.Client,});
export function Spin({ speed }: { speed: number }) { useBehaviour(SpinBehaviour, { speed });
return null;}A view reads its entity with useEntity(), and its position and speed with readTrait(entity, TransformTrait) and readTrait(entity, VelocityTrait). The records are read-only. A system changes movement through its step.
useFrame from @react-three/fiber runs the view’s callback. Its seconds follow the world’s time: none while a modal or the devtools pause, fewer under slow motion, and at most a quarter of a second in a long frame, as the steps cap it, so a hitch never jumps a tween. Use useUnscaledFrame for the wall clock.
import { readTrait, TransformTrait, VelocityTrait, useEntity,} from "@spawnite/engine";import { useFrame } from "@react-three/fiber";
function LogSpeed() { const entity = useEntity();
useFrame(() => { if (!entity.isAlive()) return; const position = readTrait(entity, TransformTrait)?.position; const velocity = readTrait(entity, VelocityTrait); console.log(position, velocity?.length()); });
return null;}Lists and grids
Section titled “Lists and grids”Two kinds of field send their changes rather than their whole value, so a long list or a block world costs what changed:
list(item, maxLength)holds up tomaxLengthitems, at most 10,000, read as an array.itemis the value a new slot holds, a primitive or a factory as any trait field is, and its type is the item’s:list((): Slot | null => null, 40). An item is plain data, with no entity, vector or other class; a list of entities stays a plain array field.grid(Type, size, { fill })holds a typed array of one, two or three dimensions, at most 1,048,576 cells:grid(Uint16Array, [16, 16, 16]). The type sets each value’s range; aFloat64Arraygrid rounds its values to four places as they are written. A cellx, y, zhas the indexx + size[0] * (y + size[1] * z).
A trait whose schema holds either gives a handle for each under fields, ChunkTrait.fields.blocks, and changes it only through an editor taken with what may write the trait. editList hands push, insert, set, remove, clear, resize and copyFrom, and editGrid hands set(x, y, z, value), setAt(index, value), fill(value, from, to), fillAt and copyFrom. Each change is checked: a value outside the type’s range, a cell outside the grid or a push past maxLength throws in development, naming the field, and is refused with one log line in a deployed room.
An editor writes within the system that took it, as editTrait’s record does: take it again in each system, since a development world throws for a write after its system returned. Each write reads the field as it stands, so two editors of one list keep both their writes.
A send compares each changed list or grid with what the pages hold and carries what differs. For a grid, that is each changed cell, and each run of neighbouring cells in index order that took one value. For a list, it is a set for each changed item, a push for each item added at the end, and a remove for each one cut from the end. Where that weighs more than the field whole, the send carries it whole: past the numbers of the grid’s whole form, or past half of the list’s items. An insert or a remove near a list’s front moves every item after it, so such a list goes whole; a list whose slots stay in place, as a bag’s do, sends one item a change.
An editor’s first write gives a list a new array, and its later writes change that array, so a view’s memo sees each editor’s changes as one new array. A grid reads with read(x, y, z), readAt(index), version and forEachChange(since, visit), which a mesher reads to redraw only the cells that changed. A predicted trait holds neither, since a correction would replay its changes on a restored copy.
import { defineTrait, editList, list, type Authority, type Entity, Reach,} from "@spawnite/engine";
/** One slot of a satchel: an item and how many, or null for an empty slot. */export interface SatchelSlot { item: string; count: number;}
/** A satchel of up to 40 slots, streamed to its owner alone. */export const SatchelTrait = defineTrait( "satchel", { slots: list((): SatchelSlot | null => null, 40) }, { reach: Reach.Owner },);
/** Adds `count` of `item` to the first slot that holds it, or to a new * slot: one change on the wire either way. */export function addToSatchel( writer: Authority, satchel: Entity, item: string, count: number,) { const slots = editList(writer, satchel, SatchelTrait.fields.slots); const index = slots.items.findIndex((slot) => slot?.item === item); if (index < 0) { slots.push({ item, count }); return; } const held = slots.items[index]; slots.set(index, { item, count: (held?.count ?? 0) + count });}
/** Grows the satchel to `size` empty slots, or cuts it to `size`. */export function resizeSatchel( writer: Authority, satchel: Entity, size: number,) { editList(writer, satchel, SatchelTrait.fields.slots).resize(size);}An entity or a cell
Section titled “An entity or a cell”An entity is a thing with an identity and traits of its own, such as a house, a chest or an NPC. A world’s save with each keeps one record for each, and the room holds every entity in memory, as A world’s size measures. A grid is one entity holding cells that have no identity: terrain, voxel blocks, tile maps, heightfields, fog and soil.
A chunk of 16 × 16 × 16 blocks shows the difference:
- As 4,096 entities, it is 4,096 records and about 3.4 MiB of the room’s memory (derived from the measurement), and each block’s change is an entity’s change on the wire and in the save.
- As one entity with
grid(Uint16Array, [16, 16, 16]), it is one record and 8 KiB of cells. Fifty players placing a block each between sends over 64 such chunks cost 623 bytes a send, against 132,226 bytes when each chunk was one plain array field, measured on the engine’s grid bench.
A cell that becomes a thing becomes an entity beside its grid. A chest placed on a block is an entity at that block’s place, with its own traits and its own record, and the cell under it stays a cell.
Events
Section titled “Events”An event is something that happened: a hit, a pickup, a match’s end. Every emit is one event, read once by each system and heard once by each view that listens, in the order emitted, and two emits are never merged. A game makes an event with defineEvent(name, record), at module scope in a module the room and the page both import; its name ends in Event, in the past tense, and it is no trait, so no query finds it. DamagedEvent is emitted on an entity each time it takes damage, one event per hit, and a trigger’s TriggerEnteredEvent and TriggerExitedEvent as a player’s character comes in or leaves.
- Emit with
emitEvent(authority, event, record, { entity }). An event is an outcome, so it takes an authority: the step insideif (step.authoritative)or in a system with norunsOn, the authorityuseAuthorityEffecthands a logic component, orfindAuthority(writer, entity)for an entity only this page holds. The record is copied as it is emitted, each field left out at its default. - Read in a system with
readEvents(step, event): every event emitted since the system last read it, oldest first, so a system reads each event once whether it runs before or after the emitter, and a system that skips ticks reads what it missed.{ entity }reads the events on one entity, which matches once that entity is destroyed too. A predicted system reads no events, which its step’s type holds, since a replay would read them again. - Hear in a view with
useEvent(event, (event) => ...): the frame loop hands each event to the views once a frame, after the frame’s steps, so a view hears each once however many steps the frame ran. - Read the entity as
event.entity, which is null once the entity is destroyed. The record carries what a reader needs after its entity is gone, asDamagedEventcarries where the hit landed. - Send to chosen players with
{ to }:emitEvent(step, CardDealtEvent, { card }, { to: player })reaches that player’s page and no other, and a list, such as a team’s players, reaches each of theirs. Every system of the world that emitted it still reads it, the room’s included. A player in the list who left before the emit receives nothing, an empty list reaches no page, and a player whose join lands in the step of the emit receives it in the player’s welcome.totakes aPlayerEntity, whichreadPlayers, a join hook’splayer, a command’scause.playerandreadLocalPlayerreturn.isPlayer(entity)narrows any other, such asfindController’s, since a room controller drives entities too. A prop or a character passed there fails to typecheck. An authority-only or a local event takes noto. In a game played alone, its views, and its systems that run on the client alone, hear only what reaches its own player. - Say what a page without an entity receives. Each field that holds an entity declares it in
entities:WhenAbsent.Nullsends the event with null there, and leaves the entity out of a list. A victim’s page then hearsDamagedEventwith nosourcewhere it does not hold the attacker, though the hit’sinstigatorPlayerstill names the player behind it, since every page holds every player.WhenAbsent.Withholdsends no such event to that page, so a pressure plate gives away nobody it cannot see. An event on a living entity a page does not hold never reaches it. Once the entity is destroyed, the field reads null under either choice, on every world, even after a new entity takes its slot, so both are typed with| null.
A private deal pairs an owner-only trait with { to }. The hand reaches the owner’s page alone, so does the card’s event, and the draw, an event on the owner’s player entity with no to, reaches every page: an owner-only trait chooses who receives the trait, and to who receives the event. With { cause } beside to, the owner’s page reads the event’s cause only where to sends the owner the event, so a cause never tells a page of an event it does not receive. Roblox’s FireClient and a loop of it, Unreal’s client RPC, Unity’s ClientRpcParams target ids and Godot’s rpc_id each send to chosen players too. Here the event stays in the log, so the room’s systems, the dump and a replay read it as they read every event.
import { addTrait, defineCommand, defineEvent, definePlugin, defineTrait, emitEvent, EventScope, readCommands, setTrait, type AuthoritativeStep, defineSystem, Phase, Reach,} from "@spawnite/engine/core";
// A card dealt to one player, built as a creator's plugin is, from the// engine's public entry alone. The player asks for a card, and the room// puts it in the player's hand, which reaches only the owning page, and// tells that page alone which card it was. Every page hears that the// player drew, never what.
/** The player's hand, on the player entity: an owner-only trait, which * the room streams to the player's page alone. */export const HandTrait = defineTrait( "dealtHand", (): { cards: string[] } => ({ cards: [] }), { reach: Reach.Owner },);
/** The card dealt to the player, which the player's page alone * receives: what that page turns face up. */export const CardDealtEvent = defineEvent( "cardDealt", { card: "" }, { scope: EventScope.Global },);
/** On the player entity as the player draws, which every page hears: * what the table shows as a card leaving the deck. */export const CardDrawnEvent = defineEvent("cardDrawn");
const deck = ["QH", "7S", "2D", "KC", "9H", "AS"];let dealt = 0;
/** Starts the deck over, for a test that plays it again. */export function shuffleDeck() { dealt = 0;}
/** Deals each player who drew the deck's next card. */function deal(step: AuthoritativeStep) { for (const command of readCommands(step, cards.commands.draw)) { const { player } = command; const card = deck[dealt++ % deck.length]; const hand = player.get(HandTrait)?.cards ?? []; setTrait(step, player, HandTrait, { cards: [...hand, card] }); // To the player's page alone, as the // player's command's outcome. emitEvent( step, CardDealtEvent, { card }, { to: player, cause: command.cause }, ); // To every page, which learns the player drew // and not what. emitEvent(step, CardDrawnEvent, { entity: player }); command.accept(); }}
export const cards = definePlugin(() => ({ name: "cards", commands: { draw: defineCommand({}) }, // A command's reader runs on the room alone, which holds the deck. systems: [ defineSystem({ name: "deal", phase: Phase.Rules, answers: ["draw"], run: deal, }), ], onPlayerJoin: ({ step, player }) => { addTrait(step, player, HandTrait); },}));replication says where an event goes:
EventReplication.Reliable, the default, reaches every page that holds its entity.EventReplication.Cosmeticmay be dropped by a page that falls behind or hides its tab.EventReplication.AuthorityOnlystays on the world that emitted it, anduseEventrefuses it by type.EventReplication.Localis the drawing world’s own, emitted with the world outside any step, as an animation’s clip mark is, andreadEventsrefuses it by type.
scope: EventScope.Global makes a global event, about the game as a whole, with no entity. An event is this engine’s version of Bevy’s buffered message, read by each system from where it last read, not Bevy’s observer; Unity’s and Unreal’s delegates call each listener inside the emit, which in a room would run only on the room.
A behaviour lists the events its system reads or its view hears in handles. The Wiki links the behaviour to each of them, and each event back to the behaviours that handle it, so the map follows a hit to what it sets off. Trigger handles its own two events: its component fires onEnter and onExit as each is heard.
import { defineTrait } from "@spawnite/engine/core";import { DamagedEvent, defineBehaviour, defineEvent, RunContext,} from "@spawnite/engine";
const FlinchTrait = defineTrait("flinch", { seconds: 0.2 });const HitEvent = defineEvent("hit", { amount: 0 });
export const FlinchBehaviour = defineBehaviour({ name: "flinch", trait: FlinchTrait, handles: [DamagedEvent, HitEvent], runsOn: RunContext.Client,});Consequences are data
Section titled “Consequences are data”A consequence is data on a trait handled by a system, never a callback prop. <Pickup reward={1} /> puts the reward on the trait, and the pickup system credits the wallet where it runs. In the engine’s source, a function prop on a behaviour declared Server or Both is a lint error: a closure lives in the browser’s React tree and the server can never run it. A behaviour declared Client may take a callback for local UI, which is how Interact’s onInteract opens a modal.
A consequence the engine has no behaviour for is written by the game the way the engine writes its own: a trait, a system and a component. The behaviour is declared Server, and its system’s entry leaves runsOn out, so the system runs on the room alone. Write your own behaviour builds one end to end, with its tests.
stateDiagram-v2
[*] --> Trait: mount adds
Trait --> Trait: prop change sets
Trait --> [*]: unmount removes
note right of Trait
the system reads it every step
end note
Samples
Section titled “Samples”Three game components, each one Entity with behaviours as children:
import { Bob, box, Entity, Pickup, type Position, RigidBodyType, sounds, Spin,} from "@spawnite/engine";
/** One coin: it turns, bobs, and goes into the wallet of whoever reaches it, * with a chime. * Its body follows the bob, so the ball bounces off it where it is drawn. */export interface CoinProps { position: Position;}
export function Coin({ position }: CoinProps) { return ( <Entity position={position} body={{ bodyType: RigidBodyType.Kinematic }} collider={{ shape: box({ size: [0.8, 0.1, 0.8] }) }} view={CoinView} > <Spin speed={2} /> <Bob height={0.2} /> <Pickup reward={1} sound={sounds.pickup} /> </Entity> );}
/** How a coin is drawn on a page: a gold disc. A room never mounts it. */function CoinView() { return ( <mesh> <cylinderGeometry args={[0.4, 0.4, 0.1, 24]} /> <meshStandardMaterial color="gold" /> </mesh> );}The coin is the example template’s. Its body and collider are there so the example’s ball bounces off it; Pickup needs neither.
export interface DoorProps { position: Position; /** The tags a key must carry, space-separated: "key gold". */ accepts: string;}
/** A door 3 m wide that stops characters until a key it accepts opens * its lock. Its origin stands on the ground, in the doorway's middle. */export function Door({ position, accepts }: DoorProps) { return ( <Entity position={position} collider={{ shape: box({ size: [3, 2.5, 0.3] }), offset: [0, 1.25, 0], }} view={DoorView} > <Lock accepts={accepts} /> <DoorPrompt /> </Entity> );}
/** The prompt the player sees, gone once the door opens. */function DoorPrompt() { const door = useEntity(); const character = useCharacter(); const isOpen = useTrait(door, LockTrait)?.open ?? false; if (isOpen) return null; return ( <Interact prompt="Unlock" onInteract={() => { if (character) tryKeys(character, door); }} /> );}
/** The panel the player sees, gone once the door opens. */function DoorView({ entity }: EntityViewProps) { const isOpen = useTrait(entity, LockTrait)?.open ?? false; if (isOpen) return null; return ( <mesh position={[0, 1.25, 0]}> <boxGeometry args={[3, 2.5, 0.3]} /> <meshStandardMaterial color="saddlebrown" /> </mesh> );}The door carries its lock as data: <Lock> says which key opens it, and the room decides when one does. Interact’s prompt and onInteract are client behaviour: the press asks the room to use the player’s keys on the door. The rest of the file, the keys, the press and the system that clears the doorway, is on Locks and keys.
import { Anchor, BarSize, Entity, Health, Panel, PanelVariant, useEntity, type EntityViewProps,} from "@spawnite/engine";import { healthResource, ResourceBar } from "@spawnite/engine/resources";
function BossHealthBar() { const boss = useEntity(); return ( <Panel anchor={Anchor.Above} maxDistance={60} variant={PanelVariant.Glass} > <ResourceBar entity={boss} resource={healthResource} label="Yeti king health" size={BarSize.Large} /> </Panel> );}
function YetiKingView(_: EntityViewProps) { return ( <mesh> <boxGeometry args={[2, 3, 2]} /> <meshStandardMaterial color="#dfe8f0" /> </mesh> );}
export function YetiKing() { return ( <Entity position={[0, 0, -30]} view={YetiKingView}> <Health maximum={500} /> <BossHealthBar /> </Entity> );}The health bar reads its own entity through useEntity() and follows it in the world through anchor.
Each behaviour has its own page: Spin, Bob, Pickup, Interact, Trigger, Health, Chase and TrackMover.