# Worlds as data

> Because every component is a pure function of props, a whole world serializes to plain JSON.

Every component is a deterministic function of its props, so an entire scene can be described as **data** — a list of `{ type, props }` — then rendered, saved, diffed, and edited like any file.

## The shape

```ts
interface WorldData {
  $schema?: string // editor hint: https://runek.nullorder.org/r/world.schema.json
  version: 1
  meta?: WorldMeta // the world's identity (title, authors, license, source)
  unit?: number
  gravity?: [number, number, number]
  ground?: number // baseline ground level (Y); floor + water default to it
  time?: string // pinned time-of-day "HH:MM" (reproducible day/night)
  timezone?: string // OR an IANA zone for a live, clock-driven day/night
  avatar?: 'first' | 'third' | 'overhead' // default player camera view
  controls?: Record<string, string[]> // input remap: action → KeyboardEvent.codes
  palette?: Partial<WorldPalette> // color-slot overrides for the whole world
  fonts?: Partial<WorldFonts> // fonts the world ships, by role (display, body), and a fallback
  luminance?: Partial<WorldLuminance> // glow levels: screen, sign, tube, lamp, flame
  stream?: boolean | { radius?: number; cell?: number; build?: boolean } // mount only what's near the viewer
  fog?: { color: string; near: number; far: number }
  nodes: WorldNode[]
}

interface WorldNode {
  type: string // a registry key, e.g. "Bookshelf"
  id?: string // stable identity; the editor fills this in (see below)
  anchor?: 'ground' | 'surface' // position[1] is an offset above the ground here
  props?: Record<string, JsonValue>
  children?: WorldNode[]
}
```

A small world:

```json
{
  "version": 1,
  "palette": { "wood": "#7a5a40" },
  "nodes": [
    { "type": "Terrain", "props": { "size": [40, 40] } },
    { "type": "Bookshelf", "props": { "position": [0, 1, 0], "seed": 42 } },
    { "type": "Player" }
  ]
}
```

The look of a world is data too: `palette` re-themes every component at once and `fog` sets the atmosphere — both diff as cleanly as any node.

## Validate it

Start a world file with a `$schema` line and editors check it and complete component names, props, and enum values as you type:

```json
{
  "$schema": "https://runek.nullorder.org/r/world.schema.json",
  "version": 1,
  "nodes": []
}
```

The [world schema](https://runek.nullorder.org/r/world.schema.json) is generated from the [prop schema](https://runek.nullorder.org/r/props.json): every prop of every component with its type, default, and doc, read from the TypeScript source. `npx @runek/cli validate world.json` runs the same checks from a terminal (see the [CLI reference](https://runek.nullorder.org/docs/cli.md)), and `serializeWorld` keeps the `$schema` line when it saves.

## World settings (the rules)

A handful of top-level fields are the world's **rules**: values components read through `useWorld()` to decide how the world looks and plays, not geometry. They resolve onto the world context the same way `unit`, `gravity`, and `palette` do — set once on the world, read everywhere.

```json
{
  "version": 1,
  "time": "21:30",
  "avatar": "third",
  "nodes": [{ "type": "Sky" }, { "type": "LightRig" }, { "type": "Player" }]
}
```

- **`time`** pins a fixed time-of-day (`"HH:MM"`, 24-hour), so the world is fully reproducible: the same file lights the same way every time. **`timezone`** (an IANA zone like `"Asia/Kolkata"`) makes the world *live* instead — the day/night state tracks the real clock, an explicit exception to determinism. A pin wins if both are set. Day/night-aware components read the resolved value as `useWorld().time`: `Sky` arcs the sun overhead by day and swaps to a dark, starlit dome at night, and `LightRig` follows it with golden-hour tints and dim moonlight.
- **`avatar`** (`"first"`, `"third"`, or `"overhead"`) is the default camera view. `Player` uses it unless its own `view` prop is set — an explicit prop always wins.
- **`controls`** remaps input bindings: a partial `action → KeyboardEvent.code[]` map merged over the defaults (WASD moves, arrow keys turn/look, C held swims down under water — in either view). Declare only what you change (`{ "forward": ["KeyW", "KeyZ"] }` for AZERTY), bind `[]` to disable an action, or add unknown action names as custom bindings your own components read via `useKeyboardControls`. Components see the resolved map at `useWorld().controls`. Controls are orthogonal to `avatar`: bindings behave the same in every view.
- **`ground`** is the baseline ground level (a `Y` value, default `0`): the datum that `Floor` and water like `Lake` default their placement to. In a coastal world it is effectively your **sea level**, the terrain rises from it and the water sits at it, so moving `ground` shifts a whole world's datum at once (a sunken basin, a plateau). Open water sits at or below it (a floating lake is a bug); an explicit `position` still wins.
- **`luminance`** sets how bright glowing surfaces are, per kind: `screen` (screens, monitors, TVs), `sign` (a `Sign` with `lit`), `tube` (neon), `lamp` (bulbs and the shades they light) and `flame` (fires), in scene-linear units where `1` is face value. Above 1 they feed bloom. Every level defaults to `1`, so `{ "luminance": { "lamp": 6, "screen": 1.5 } }` is a world's exposure in one line (see [the World provider](https://runek.nullorder.org/docs/the-world-provider.md#luminance)).
- **`stream`** is for dense worlds, a district of a few thousand nodes: only the nodes near the viewer are mounted, so the cost of a world follows what's around you, not its size. `true` mounts what's within 80 m, or give `{ "radius": 60, "cell": 20 }` in units. A node's place is its `position` and its footprint is its composite's `bounds` or its own `size`. Nodes stay mounted a little past the radius so standing on a boundary doesn't make them flicker, and a node streams back exactly as it left, since every component is a pure function of its props. Nodes with no position, `Group`s and the things that belong everywhere (`Player`, `Sky`, `Ocean`, `Clouds`, `LightRig`) are always mounted. Only top-level nodes stream; a composite comes and goes as a whole. Components that export a `build` (their geometry as data, see `Crate` and `Bench`) are mounted from it without a React component each, which roughly halves what it costs to bring a neighbourhood in as you move; `{ "build": false }` mounts them as React like everything else. Off by default.
- **`fonts`** are the typefaces the world ships, keyed by role (`display` for titles and signage, `body` for labels). They are the one exception to the no-assets moat: components hold no fonts, so the world declares them and `Sign` draws from them. An undeclared role falls back to the pixel font bundled in `@runek/core`, so `Sign` always renders even with no `fonts` set.
- **`fonts.fallback`** is a font URL, or a list of them in order of preference, for text a role's font can't fully draw: a CJK or symbol face under a Latin display font. A `Sign` whose text its role font can't draw is drawn in whichever declared face covers most of it (the text renderer draws one text from one face, so the whole sign switches, not single characters). Characters no declared face draws show as boxes, from a face built in code: text never fetches a font the world didn't declare. `runek validate` warns about a `Sign` whose text the bundled font can't draw.

Every setting is optional with a sensible default (a bright midday, first-person), so a world that declares none renders exactly as before.

## Render it

`<WorldRenderer>` maps each node's `type` through a registry of components:

```tsx
import { WorldRenderer, parseWorld } from '@runek/core'
import { registry } from './runek/registry'

const world = parseWorld(await (await fetch('/my.world.json')).text())

<WorldRenderer data={world} registry={registry} />
```

Two node types resolve without a component behind them:

- **Composites** — a registry entry can be a data arrangement instead of code (`House`, `Room`). The renderer expands the arrangement in place, inside a group carrying the node's `position`/`rotation`; an instance `seed` re-rolls unpinned children deterministically. See [the building kit](https://runek.nullorder.org/docs/building-kit.md).
- **`Group`** — a built-in transform container (`position`, `rotation`, `children`), what the editor's **Unpack** leaves behind when you break a composite instance open for per-instance edits.

## Save it

`serializeWorld(data)` returns pretty JSON. The runtime editor (`<WorldEditor>`) edits a `WorldData` live and exports it with the same call, so a world round-trips: render, edit, serialize, commit.

The editor has its own entry point, so an app that only renders worlds doesn't ship its props panel. It needs `leva` installed alongside `@runek/core`:

```tsx
import { WorldEditor } from '@runek/core/editor'

<WorldEditor data={world} registry={registry} onChange={setWorld} />
```

In the editor, drag to orbit, hold `W` `A` `S` `D` to pan across the ground (`Q` / `E` for down and up) and the arrow keys to orbit, with `⇧` to go faster. Click a node to select it: the gizmo moves or rotates it (`g` / `r`), the props panel edits its numbers, and `W` `A` `S` `D` `Q` `E` now step it 0.1 along the world axis nearest the camera (`⇧` for 1). `⌘D` duplicates, `⌫` deletes, `⌘Z` undoes, `Esc` deselects.

## Identity & contribution

A world is a creative work, so its identity travels *in the file* under `meta` (the way `package.json` carries a package's name, author, and `repository`):

```ts
interface WorldMeta {
  title?: string
  description?: string
  authors?: { name: string; url?: string }[]
  license?: string // a world is content, so a CC license often fits better than MIT
  source?: { url: string; path?: string; branch?: string } // the canonical repo
}
```

`meta` is optional, and so is every field within it. When present, both `<WorldRenderer>` (walk) and `<WorldEditor>` (edit) show a small **ⓘ** that opens an "About this world" panel with the title, authors, license, and a link to the source repo. A world with no `meta` still renders.

When `meta.source` points at a GitHub repo, the editor also gains a **Contribute** action with two paths. *Fork this world* opens GitHub's fork page for your own deployable copy. *Suggest changes upstream* downloads the edited JSON plus a PNG snapshot of the view and opens GitHub's edit-file URL, which auto-forks for non-collaborators, so your change becomes a normal pull request with no backend, account, or token. Non-GitHub hosts fall back to opening the repo.

## Anchored nodes

On uneven `Terrain`, a fixed Y is only right where the ground happens to be that high. An `anchor` makes `position[1]` an offset above the ground at the node's (x, z) instead: `"ground"` stands on terrain, `"surface"` on whatever is highest there (terrain, a dock, a floor).

```json
{ "type": "Person", "anchor": "ground", "props": { "position": [3.2, 0, 115.4], "seed": 123 } }
```

The file keeps the offset, so moving or reseeding the terrain re-seats everything anchored to it. See [Placing things on uneven ground](https://runek.nullorder.org/docs/placing-things-on-uneven-ground.md).

## Stable node ids

Each `WorldNode` can carry an optional `id`. You don't write these by hand: the editor assigns one to any node missing it on load and preserves the rest. Ids give nodes a durable identity across edits, and `serializeWorld` writes keys in a canonical order, so a pull request shows only what actually changed.
