Skip to content

Latest commit

 

History

History
139 lines (105 loc) · 21.9 KB

CONTRACT.md

File metadata and controls

139 lines (105 loc) · 21.9 KB

The Runek Component Contract

This is the normative spec every Runek component must satisfy to be accepted into the registry. It's what PR reviewers check against. The friendly walkthrough lives in the docs (The component contract); this document is the checklist.

The keywords MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY are used as in RFC 2119.

Stability: the contract is pre-1.0 and MAY change on a minor (0.x.0) bump. It freezes at 1.0.0, after which changes follow semver.


1. Shape

  • A component MUST be a React function component with a named export in PascalCase (e.g. Bookshelf), and MUST export a typed props interface named <Name>Props.
  • It MUST accept the base props position, rotation, and seed (WorldComponentProps from @runek/core). It MAY add its own props.
  • A component with nothing to vary MUST still accept seed, and SHOULD document it as having no seeded variation; the generated prop schema marks it seeded: false, so tools skip seed controls for it.
  • Props SHOULD carry a one-line JSDoc: it becomes the description in the prop schema (props.json), the docs, the workshop inspector, and runek info.
  • Every prop SHOULD be JSON-serializable (numbers, strings, booleans, arrays, plain objects). Function/ref props break worlds-as-data and SHOULD NOT be required.
  • Each prop MUST have a sensible default, so <Name /> renders something.
  • A component MAY be interactive. If so, the data of the interaction (what is clickable, where a click leads) MUST stay JSON-serializable — e.g. a books array, a per-item href — and any event callback (e.g. onBookSelect) MUST be optional, so the component still renders and round-trips from data without it. See Bookshelf.

2. Determinism

  • A component MUST be a pure, deterministic function of its props: the same props (including seed) MUST produce the same output on every machine and every render.
  • All randomness MUST come from the seeded RNG (rng(seed) and the helpers from @runek/core). Components MUST NOT use Math.random(), Date, or any other ambient nondeterminism to generate geometry.
  • When composing child components, child seeds MUST be derived stably (e.g. sub(seed, n)), not shared verbatim.
  • Motion that is part of the world (a figure walking its route) SHOULD be a pure function of its props and the world's wall clock (useWorld().now(), falling back to Date.now() when a hand-rolled provider leaves it out), not state integrated frame by frame, so every viewer sees it in the same place. A component MUST NOT read Date.now() or new Date() directly for world motion or time of day, so an app that gives the world a shared clock (<World now>) gets every component on it. A one-off motion that starts on an event (a trip) SHOULD carry its start as data (an epoch-ms prop such as departAt), not start when the component mounts. Reactions to the viewer's own avatar (stepping aside, waiting) are the one per-viewer part, and SHOULD ride on top as an offset or a delay. See Person.

3. Geometry

  • Geometry MUST be generated inside useMemo, keyed on every geometry-affecting prop (including seed). Unrelated re-renders MUST NOT rebuild geometry.
  • Detail SHOULD scale with props and/or distance (parametric LOD) where it's meaningful.
  • A static component a world places by the hundred (furniture, props, street parts) SHOULD also export its geometry as data: Component.build = (props, ctx) => Built from @runek/core, returning its parts (primitive shapes or raw arrays, each with a material look), cuboid colliders and lights, and render that same Built from its React form with <BuiltView> / useBuilt. A build MUST be pure (§2): the same props and ctx (unit, palette) give the same result, with no React, no three objects other than raw arrays, and nothing that changes after mount. A streamed world mounts such components without React. See Crate, Bench.

4. No assets (the moat)

  • A component MUST NOT depend on binary assets: no .glb/.gltf, no image textures, no HDR environment maps.
  • A component MUST NOT fetch anything at runtime or require a CDN. Geometry, color, and materials come from code.
  • A texture a component draws in code at runtime is not a binary asset: a DataTexture filled by a seeded function, a CanvasTexture it paints (a glyph atlas from the world's fonts, an ad board it redraws), or a depth map it renders from the scene. Such a texture MUST be a pure function of props, seed, the world's fonts and clock (§2), ship no file and fetch nothing. It SHOULD be built once per distinct input and shared between instances that would draw the same one, SHOULD stay at or under 1024 px a side (2048 for one shared by a whole world), and a material that holds it is the component's own (§7). One that is redrawn after mount SHOULD redraw only while it is near enough to be seen, and no more often than it visibly changes.
  • A look MAY name a material slot (slot, from MATERIAL_SLOTS in @runek/core) that a world answers with a material of its own. The component still gives a complete look, which draws when the world doesn't answer; an app that answers a slot with textures owns those assets, as it does for any texture it passes a component.
  • Text is the one carve-out. A component that renders text uses a font drawn only from world.fonts (declared by the world) or the single default font bundled in @runek/core. It still MUST NOT ship its own font file or fetch a font from a CDN, including through its renderer's fallback for characters its fonts lack: troika-three-text's default font is set to lastResortFont() from @runek/core, which draws a box for anything the world's fonts don't have. Every other component stays asset-free.

5. Colliders

  • A component that presents a gameplay surface (something you stand on, bump into, or can't pass through) MUST register its own colliders via a Rapier RigidBody.
  • Collider count SHOULD be proportional to gameplay surface, not visual detail — one cuboid for a bookshelf, not one collider per book. Prefer cuboid/convex hull; use trimesh only when a shape genuinely needs arbitrary geometry (it's the most expensive).
  • Purely decorative or non-solid components (e.g. Sky, LightRig, Grass) MAY register no colliders.

6. Units & orientation

  • A component MUST read unit from useWorld() and scale its dimensions by it. 1 unit = 1 meter, Y is up, rotations are in radians.
  • Point-list props (a Person's patrol or route waypoints) SHOULD be node-local: relative to position and turned by rotation, like the component's own geometry, so moving or rotating the node in an editor carries them along.

7. Palette & performance

  • Color props SHOULD default to a slot of the world palette (useWorld().palette) so one palette swap re-themes a whole world. An explicit color prop MUST still override the palette. Fixed colors are acceptable only where no slot fits (e.g. seeded book spines).
  • A static part's material SHOULD come from useMaterial(look) / useMaterials(looks) in @runek/core, not an inline <meshStandardMaterial>: parts with the same look anywhere in the world then share one material instance (fewer state changes, and what lets the renderer batch them). Shared materials are read-only; a material whose properties change after mount (a flicker, a hover highlight, a texture drawn into) MUST stay the component's own. A look for a recognizable surface (a road deck, a pane of glass, a wooden top) SHOULD name its material slot, so a world can give every such surface a material of its own in one place.
  • <World> merges static parts that share a material into one mesh per material per cell (static batching). Parts a component moves, scales, hides or reshapes after mount (a clock's hands, a flag's cloth, a bobbing hull) SHOULD sit inside <Dynamic> from @runek/core, so they never join a batch. The batcher also leaves out parts it sees moving, but marking them avoids the churn.
  • Repeated geometry (books, branches, blades, …) SHOULD render as an InstancedMesh — draw calls scale with kinds of geometry, not instance counts. See Bookshelf, Trees, and Grass for the pattern.
  • A surface drawn as light (a screen, neon, a bulb, a flame) SHOULD take its brightness from a world luminance level (useLuminance() from @runek/core, with glowLook(color, level) for an unlit glow, or the level multiplying an emissive intensity), not a literal, so a world sets its exposure in one place. Indicators and effects that aren't a light source MAY stay at face value.
  • A component that gives off light MUST register it with useLight(look) from @runek/core and place the returned emitter's ref (and a spot's target), never mount a three.js light itself. The world lends a fixed pool of real lights (<World lightBudget>) to the emitters that matter most to the view, so a world full of lamps costs what a handful does (under WebGPURenderer, where point lights are shaded in tiles, every point emitter gets a light of its own). A flicker writes the emitter's intensity each frame.
  • Shadow casters SHOULD follow the collider rule: gameplay-sized parts cast, small detail doesn't (a shadow narrower than a few centimetres falls inside one texel of a world-sized sun shadow map). It matters most for parts that move or don't batch: each one is a draw in every shadow update. Static detail on shared materials is merged by the batcher and costs little either way.
  • Anything that makes the renderer draw the whole world again (a material with transmission, a render-to-texture view like Rift's, a reflection) multiplies the cost of every other component. A component MUST NOT use transmission; fake glass with opacity and gloss. A component that renders the scene itself MUST skip that render when it is culled or too small on screen to matter, and SHOULD render it below full resolution, inside scenePass() from @runek/core and never while inScenePass() is true, so passes don't nest. See Rift.
  • A reflective surface (a polished floor, a wet street, still water) MUST take its reflection from the world's mirror (useMirrorMaterial(look, strength) from @runek/core) and never render its own: every reflective surface at one height shares one reflection, drawn once a frame while one of them is in view, within the world's mirrors limit.
  • A component that writes a shader (a ShaderMaterial, an onBeforeCompile patch) SHOULD also provide a node (TSL) material for WebGPURenderer, chosen with useNodeRenderer() and loaded with lazyModule() from @runek/core so a WebGL world never downloads it, or MUST be documented as WebGLRenderer only.

8. Dependencies & boundaries

  • Shared utilities MUST be imported from @runek/core only.
  • A component MAY compose sibling components; each such sibling MUST be declared as a registryDependency (see CONTRIBUTING).
  • A component MUST NOT import from an app (apps/*). Dependency direction is one-way: app → components → core.
  • Third-party npm dependencies are derived automatically from imports — keep them minimal and justified.

9. World data (the envelope)

These govern the WorldData a component is placed into, not individual components. @runek/core handles them, but an author should know the shape round-trips losslessly.

  • WorldData MAY carry optional top-level fields the renderer reads (unit, gravity, palette, fog) plus meta, the world's identity (title, description, authors[], license, source). Every one is optional and additive.
  • A world MAY also declare runtime settings (the world's "rules") as top-level fields, resolved onto WorldContext for components to read via useWorld():
    • time ("HH:MM", 24h) pins a reproducible time-of-day; timezone (IANA) instead tracks a live clock. Both resolve to useWorld().time ({ hours, live, timezone? }). A day/night-aware component (e.g. Sky, LightRig) SHOULD read it, and MUST still render with the default (a pinned midday) when unset.
    • avatar ('first' | 'third' | 'overhead') is the world's default camera view, read as useWorld().avatar; Player uses it when its own view is unset. An explicit component prop MUST win over the world default (as with palette colors).
    • ground (a Y baseline, default 0) is the world's ground level, read as useWorld().ground (in a coastal world, this baseline is your sea level). Floor-sitting and water components SHOULD default their placement to it (open water at or below it, per §10); an explicit position wins.
    • luminance (screen, sign, tube, lamp, flame: numbers, scene-linear, default 1) sets how bright each kind of glowing surface is, read as useWorld().luminance or useLuminance() (§7).
    • stream (true or { radius, cell } in units) mounts only the top-level nodes near the viewer. Because a component is a pure function of its props (§2), unmounting and remounting one MUST bring it back as it was; anything it keeps over time comes from the world's clock, not from how long it has been mounted. A component that must stay mounted wherever the viewer is (the avatar, the sky, a surface that follows the camera) sets stream = false on itself.
    • controls (a partial action → KeyboardEvent.code[] map, merged over the defaults) remaps input bindings and MAY declare unknown action names, which become custom bindings any component can read via drei's useKeyboardControls. The resolved map is exposed as useWorld().controls — a component displaying or consuming bindings SHOULD read it rather than hardcode keys. The bindings are orthogonal to avatar: an action behaves the same in every view. <World keyboardMap> (JSX-only, verbatim) remains the low-level escape hatch and wins when given.
  • parseWorld MUST accept a world without meta, MUST pass meta, the settings above, and unknown fields through unchanged (light shape validation only), and a new optional field MUST NOT require a version bump.
  • A WorldNode MAY carry an optional stable id. The editor assigns ids to nodes that lack them and preserves existing ones; ids key React reconciliation and selection, with an array-index fallback. Hand-authored worlds need not write ids.
  • A WorldNode MAY carry an optional anchor ('ground' | 'surface'). Anchored, position[1] is an offset above the ground at the node's (x, z): ground counts terrain surfaces, surface also counts decks (§12). Absent means absolute. The renderer resolves it through the world's surfaces and hands the component an absolute position, so a component MUST NOT need to know it was anchored. serializeWorld MUST keep the authored offset, never the resolved Y. Under a parent tilted more than ~1°, an anchor is treated as absolute (with a dev warning).
  • serializeWorld MUST emit a canonical key order (each node type, id, anchor, props, children), so an unchanged node never churns the diff.

10. Water

  • An open water body (e.g. Lake) MUST read as filling a depression, never floating above the ground. Its local origin is the water surface, and a world MUST place that surface at or below the surrounding ground level, with the terrain forming the banks. A water sheet hovering over flat ground is a placement bug, not a valid world.
  • A water component SHOULD treat its origin as the surface plane (so sinking it is a single negative-Y placement) and MUST NOT assume it rests on top of the ground. It SHOULD default its surface to world.ground (§9), so <Lake /> complies without an explicit position.
  • Contained water held in a component's own vessel (e.g. Fountain, Well) is the exception: its surface sits inside the basin the component renders, because the vessel, not the terrain, holds it.
  • The rule is checkable: an open water component SHOULD publish a water surface with a rim (§12), and runek check-world flags water that stands above the ground at its rim.
  • Water a figure can get into (Ocean, Lake, Pool) SHOULD publish itself to the world with useWater (from @runek/core): its still surface at a world point, the swell on it right now, and how deep it goes when it has a floor of its own. The Player and every Person then wade, swim and dive in it with nothing wired per world. planeWater(object, size, { wave, depth, color, clarity }) builds that for a flat sheet. The swell MUST be the wave the surface draws (the same function of position and time), so a swimmer rides the water that is on screen. Such water SHOULD also say what it looks like from inside (color, and clarity, how far one sees through it in world units), which is what a camera under its surface is fogged with, and SHOULD draw its surface from below as well as from above, since a swimmer can go under it. Contained water (§10, Fountain, Well) publishes nothing.

11. Composites

A composite is a registry item whose payload is a data arrangement of component nodes (kind: "composite", a nodes: WorldNode[] array) rather than source code — house and room are the canonical examples. The renderer expands an instance eagerly into a group carrying the instance's position/rotation.

  • A composite's nodes MUST be plain, JSON-serializable WorldNodes. No callbacks, no template variables — a composite is one concrete arrangement; variation comes from the instance seed and from unpacking.
  • Every type a composite references MUST be a registry item (or the built-in Group), and each one MUST be declared as a registryDependency (derived automatically by the registry build from the node types).
  • Seeds follow §2's derivation rule at the data level: an instance seed gives each child that doesn't pin its own seed a stable sub(seed, index). A composite MUST NOT rely on all children sharing one seed.
  • Colliders, units, palette, and the no-assets rule (§4–§7) are satisfied by the referenced components; a composite adds no geometry of its own.
  • The optional bounds field ([w, h, d] in units) is the arrangement's footprint when a world streams (stream); a composite meant for dense, streamed worlds SHOULD declare it, or it streams as a point at its position.
  • A composite that stands on the ground SHOULD declare "groundSitting": true, so the world check flags a buried or floating instance (§12). Its parts' surfaces (a Floor inside a house) need nothing extra.

12. Surfaces

The ground is queryable: groundAt(x, z) (and useGround() inside a world) returns the highest walkable top at a point, computed from the same pure functions that build the meshes, with no raycasts. Components opt in by publishing what they are.

  • A component whose top is walkable ground or deck SHOULD publish a SurfaceDef as a static property, Component.surface = { kind, build }, where kind is terrain (ground proper), deck (a built top: dock, floor, slab), or water (open water, §10). build(props, { unit, ground }) returns the height of the top at local (x, z), or null off it.
  • build MUST be pure and MUST agree with the component's collider to within 1 cm. For a displaced mesh that means interpolating the rendered triangles (float32 vertices, the same diagonal), not the idealized field; the mesh and the query SHOULD share one height function.
  • The surface math MUST live in a plain-TS sibling module (surfaces/<name>.ts) with no React, three.js, or physics imports, shipped as one of the component's registry files. Node tooling (runek check-world) imports it directly.
  • A component that stands on the ground (people, trees, furniture, buildings) SHOULD declare Component.groundSitting = true, so the world check knows it may be neither buried nor floating. Things that fly, hover, or are placed in the air (Birds, Clouds, Sky, Sign) MUST NOT.
  • A component with a displaced collider SHOULD build it in the same render as its mesh (e.g. an explicit TrimeshCollider), not through automatic colliders, which arrive a commit later and let a spawning dynamic body fall through.

Conformance checklist

  • Named PascalCase export + exported <Name>Props interface
  • Accepts position, rotation, seed; all props default and are JSON-serializable
  • Pure & deterministic; randomness only via rng/sub from @runek/core
  • Geometry built in useMemo keyed on geometry props (incl. seed)
  • No binary assets, no runtime fetch / CDN; any texture is drawn in code, shared, and capped in size
  • Registers colliders proportional to gameplay surface (or none, if decorative)
  • Respects unit from useWorld() (meters, Y-up, radians)
  • Color props default to world-palette slots; explicit colors still win
  • Repeated geometry is instanced, not one mesh per piece
  • Static materials come from useMaterial / useMaterials; only materials that change after mount are the component's own
  • Parts animated after mount sit inside <Dynamic>
  • Light comes from useLight emitters, never a <pointLight> / <spotLight> of its own
  • No transmission; any extra scene render is skipped when culled or small, and runs below full resolution
  • Imports shared code from @runek/core; sibling deps declared; no app imports
  • Open water sits at/below ground (surface origin); contained water is in its vessel
  • A walkable top publishes Component.surface (pure, from surfaces/<name>.ts, within 1 cm of the collider); a ground-standing component sets Component.groundSitting = true
  • just check passes (lint, typecheck, test, build)