@bendyline/molen-tooling 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +15 -0
  3. package/README.md +91 -0
  4. package/dist/capture/THIRD-PARTY-NOTICES.md +223 -0
  5. package/dist/capture/basis/LICENSE.txt +55 -0
  6. package/dist/capture/basis/basis_transcoder.js +19 -0
  7. package/dist/capture/basis/basis_transcoder.wasm +0 -0
  8. package/dist/capture/capture.html +15 -0
  9. package/dist/capture/harness.js +4671 -0
  10. package/dist/capture/worldgen-preview.html +15 -0
  11. package/dist/capture/worldgen-preview.js +4617 -0
  12. package/dist/cli.d.mts +1 -0
  13. package/dist/cli.mjs +1276 -0
  14. package/dist/docs-src/guide/3d-art-guidelines.md +157 -0
  15. package/dist/docs-src/guide/3d-model-assets.md +286 -0
  16. package/dist/docs-src/guide/adaptive-performance.md +89 -0
  17. package/dist/docs-src/guide/agent-loop.md +156 -0
  18. package/dist/docs-src/guide/aircraft.md +225 -0
  19. package/dist/docs-src/guide/browser-mount.md +185 -0
  20. package/dist/docs-src/guide/building-interiors.md +175 -0
  21. package/dist/docs-src/guide/capability-authoring.md +69 -0
  22. package/dist/docs-src/guide/determinism.md +285 -0
  23. package/dist/docs-src/guide/entities.md +47 -0
  24. package/dist/docs-src/guide/examples.md +58 -0
  25. package/dist/docs-src/guide/experience-playback.md +57 -0
  26. package/dist/docs-src/guide/figures.md +164 -0
  27. package/dist/docs-src/guide/game-samples.md +100 -0
  28. package/dist/docs-src/guide/graphics-performance.md +167 -0
  29. package/dist/docs-src/guide/input.md +205 -0
  30. package/dist/docs-src/guide/materials.md +125 -0
  31. package/dist/docs-src/guide/project.md +157 -0
  32. package/dist/docs-src/guide/quickstart.md +63 -0
  33. package/dist/docs-src/guide/recognizable-places.md +158 -0
  34. package/dist/docs-src/guide/rendering-backends.md +231 -0
  35. package/dist/docs-src/guide/scripting.md +330 -0
  36. package/dist/docs-src/guide/sky.md +192 -0
  37. package/dist/docs-src/guide/source-bundles.md +42 -0
  38. package/dist/docs-src/guide/structure-library.md +114 -0
  39. package/dist/docs-src/guide/surface-rendering.md +203 -0
  40. package/dist/docs-src/guide/terrain.md +389 -0
  41. package/dist/docs-src/guide/three-surface.md +70 -0
  42. package/dist/docs-src/guide/vehicle-interiors.md +126 -0
  43. package/dist/docs-src/guide/vehicles.md +110 -0
  44. package/dist/docs-src/guide/weather.md +123 -0
  45. package/dist/docs-src/guide/worldgen.md +434 -0
  46. package/dist/docs-src/llms.txt +129 -0
  47. package/dist/docs-src/schemas/README.md +36 -0
  48. package/dist/docs-src/schemas/archstyle.md +2340 -0
  49. package/dist/docs-src/schemas/assert.md +169 -0
  50. package/dist/docs-src/schemas/asset.md +543 -0
  51. package/dist/docs-src/schemas/business-catalog.md +162 -0
  52. package/dist/docs-src/schemas/cameratrack.md +132 -0
  53. package/dist/docs-src/schemas/command.md +112 -0
  54. package/dist/docs-src/schemas/components.md +5826 -0
  55. package/dist/docs-src/schemas/delta.md +204 -0
  56. package/dist/docs-src/schemas/experience-play.md +452 -0
  57. package/dist/docs-src/schemas/figure.md +290 -0
  58. package/dist/docs-src/schemas/interior-catalog.md +230 -0
  59. package/dist/docs-src/schemas/keyframe.md +314 -0
  60. package/dist/docs-src/schemas/landmark-catalog.md +56 -0
  61. package/dist/docs-src/schemas/landmark.md +293 -0
  62. package/dist/docs-src/schemas/matgraph.md +1163 -0
  63. package/dist/docs-src/schemas/pack-index.md +82 -0
  64. package/dist/docs-src/schemas/pack-source.md +139 -0
  65. package/dist/docs-src/schemas/pack.md +225 -0
  66. package/dist/docs-src/schemas/pixelgrid.md +108 -0
  67. package/dist/docs-src/schemas/prefab.md +106 -0
  68. package/dist/docs-src/schemas/project.md +271 -0
  69. package/dist/docs-src/schemas/region-atlas.md +612 -0
  70. package/dist/docs-src/schemas/replay.md +807 -0
  71. package/dist/docs-src/schemas/scatter.md +541 -0
  72. package/dist/docs-src/schemas/scene.md +1152 -0
  73. package/dist/docs-src/schemas/source-bundle.md +266 -0
  74. package/dist/docs-src/schemas/stylepack.md +420 -0
  75. package/dist/docs-src/schemas/terrain-package.md +731 -0
  76. package/dist/docs-src/schemas/terrain.md +313 -0
  77. package/dist/docs-src/schemas/types.md +218 -0
  78. package/dist/docs-src/schemas/uvpaint.md +149 -0
  79. package/dist/docs-src/schemas/worldgen-batch.md +743 -0
  80. package/dist/index.d.mts +1271 -0
  81. package/dist/index.mjs +78 -0
  82. package/dist/mcp-BFnCWrg0.mjs +796 -0
  83. package/dist/ops-BGxhSP6w.mjs +7246 -0
  84. package/package.json +96 -0
@@ -0,0 +1,330 @@
1
+ # Game logic: scripts and setup
2
+
3
+ A molen experience is **data plus scripts**. The scene manifest declares the world, the commands
4
+ it accepts, and its scripts; the scripts hold the logic. A code setup module exists for the rare
5
+ things scripts cannot express, and for typed TypeScript authoring inside a workspace package.
6
+
7
+ ## 1. Scene-data scripts (the default)
8
+
9
+ Put logic in the scene manifest's `scripts` array. Each script is evaluated in its own SES
10
+ `Compartment` with two injected globals: `molen` (the verb set below) and `config` (this script's
11
+ config object, frozen). Author it as a scene-file-relative `path` to a **`.ts`** file (the
12
+ default — see [Typed scripts](#typed-scripts-checked-before-the-first-tick)), a `.js` file, or
13
+ inline as `code` (exactly one of `code` or `path`).
14
+
15
+ The Compartment is a determinism harness, **not** a security boundary — a script runs with the
16
+ authority of the host process that evaluates it. Read
17
+ [Script trust](#script-trust-a-script-runs-as-the-host-process) before you run a manifest you did
18
+ not write.
19
+
20
+ Only JavaScript is ever evaluated: a `.ts` script has its **types erased where the
21
+ scene is loaded** — the tooling loader in Node, the `molenScripts()` Vite plugin in the browser.
22
+ Erasure is whitespace-preserving, so the evaluated source keeps the exact line and column numbers
23
+ of the file you wrote and `script "chase" tick handler at tick 12: …` still points at the right
24
+ line. Nothing is emitted next to your source, and there is no build step to run by hand.
25
+
26
+ > **Renamed:** the verb set was injected as `api` in earlier builds and is now `molen`. There is
27
+ > no alias — a script that references `api` throws at evaluation with the new name in the
28
+ > message, so the fix is a find-and-replace of `api.` with `molen.`.
29
+
30
+ ```json
31
+ {
32
+ "format": "molen/scene@3",
33
+ "name": "spinner",
34
+ "commands": {
35
+ "move": {
36
+ "doc": "Planar move direction [x, z], each in -1..1.",
37
+ "payload": {
38
+ "type": "object",
39
+ "properties": { "dir": { "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2 } },
40
+ "required": ["dir"],
41
+ "additionalProperties": false
42
+ }
43
+ }
44
+ },
45
+ "input": {
46
+ "bindings": { "KeyW": "up", "KeyS": "down", "KeyA": "left", "KeyD": "right" },
47
+ "emit": [{ "kind": "axis2d", "xNeg": "left", "xPos": "right", "yNeg": "up", "yPos": "down", "command": "move" }]
48
+ },
49
+ "physics": { "engine": "kinematics" },
50
+ "entities": [
51
+ { "id": "hero", "components": {
52
+ "transform": { "pos": [0, 0, 0], "rot": [0, 0, 0, 1] },
53
+ "collider": { "shape": "circle", "radius": 0.5, "layer": 1, "mask": 1 },
54
+ "kinematicBody": { "vel": [0, 0, 0], "slide": true },
55
+ "renderable": { "kind": "primitive", "ref": "box", "materialRef": "palette:#4363d8" }
56
+ } }
57
+ ],
58
+ "scripts": [
59
+ {
60
+ "id": "control",
61
+ "config": { "speed": 6 },
62
+ "code": "molen.onCommand('move', (p) => molen.patch('hero', 'kinematicBody', { vel: [p.dir[0] * config.speed, 0, p.dir[1] * config.speed] }));"
63
+ },
64
+ { "id": "spawner", "path": "scripts/spawner.ts" }
65
+ ]
66
+ }
67
+ ```
68
+
69
+ `molen sim run scene.json --ticks 60 --hash` runs it; `molen drive` plays it with commands;
70
+ `mountExperience` runs the same manifest in the browser, where the `input` block turns WASD into
71
+ `move` commands. No setup module, no build step. A script that registers no handler at all gets a
72
+ warning (`molen.on` / `molen.onCommand` was never called).
73
+
74
+ A script may also declare `function setup(molen, config) { … }` instead of top-level code.
75
+
76
+ ## The script verb set (`molen`)
77
+
78
+ | Verb | Signature | Notes |
79
+ |---|---|---|
80
+ | `onCommand` | `(type, handler(payload, ctx, command))` | **player/agent input.** The scene declares the type under `commands` (with an optional JSON Schema payload); undeclared types and bad payloads are rejected before any handler runs. Runs in the commands phase, before every system. |
81
+ | `on` | `('tick' \| eventType, handler(payload, ctx))` | tick handlers run in the update phase; event handlers run when the event is emitted (`collision`, `tween-complete`, your own `emit`s). Returns an unsubscribe. |
82
+ | `spawn` | `(components, id?)` or `(prefabName, components?, id?)` | prefab form needs a manifest (it has one when run via `buildWorld`); component data is validated. Spawns apply at the system boundary (all tick handlers share one system): `molen.exists(id)` is false until then. |
83
+ | `spawnType` | `(typeId, components?, id?)` | instantiate a project-registry type with overrides; pass `types` to `buildWorld` in browser hosts (the CLI resolves the project automatically) |
84
+ | `state` / `setState` / `patchState` | immutable JSON read / `(data)` / `(partial)` | script-owned persistent state, saved in checkpoints and preserved on hot reload; patches replace top-level fields |
85
+ | `destroy` / `exists` | `(id)` | |
86
+ | `get` / `set` / `patch` / `remove` / `has` | `(id, component, …)` | component is a **string name**; `set` and the final shallow-merged `patch` value are validated against this world's vocabulary |
87
+ | `query` | `(...componentNames)` | iterable result with `.ids()`, `.count()`, `.first()`, `.without(...names)` |
88
+ | `emit` | `(type, payload)` | events reach other scripts, `molen.on` handlers, the client (`client.onEvent`), and `drive`/assert |
89
+ | `raycast` / `overlapCircle` | spatial queries (kinematics layer) | |
90
+ | `after` / `every` | `(ticks, event, payload?)` | snapshot-safe world timers that EMIT (no callbacks); returns timer id. The handler receives `{ entity, timerId, payload }`. |
91
+ | `cancelTimer` | `(timerId, entity?)` | |
92
+ | `tween` / `cancelTween` | `(entity, { component, path, to, ticks, easing?, loop? })` | data-driven value animation; completion emits `tween-complete` |
93
+ | `parent` / `unparent` | `(id, parentId)` / `(id)` | keep-world reparenting; the hierarchy system composes transforms |
94
+ | `rng` | `() => number` | the **only** source of randomness — deterministic |
95
+ | `tick` / `dt` | current tick / seconds-per-tick | |
96
+ | `math` | `molen.math.sin/cos/tan/atan2/pow/exp/log/hypot/sqrt/clamp/...` | deterministic (`dmath`) |
97
+ | `physics` | `molen.physics.raycast(origin, dir, maxDist, { mask?, exclude? })` / `overlapSphere(center, radius, { mask?, exclude? })` / `velocityOf(id)` | present when the scene's `physics.engine` is `rapier`; hits carry `normal`; `collision` events carry `normal`/`point` |
98
+ | `terrain` | `molen.terrain.heightAt/normalAt/slopeAt/raycast` | present when the scene has a `terrain` block with a heightmap |
99
+
100
+ ### Reads are immutable snapshots
101
+
102
+ `molen.get` and query rows hand back the engine's stored object, frozen. Never mutate it — write
103
+ with `molen.set`/`molen.patch`, which install a new object. Mutating a read throws with a hint
104
+ naming the script, the handler, and the tick.
105
+
106
+ ### State that survives save/load and replay
107
+
108
+ Use `molen.state`, components, or a registered snapshot provider for **all durable state**.
109
+ JavaScript closure variables are not serialized. For example:
110
+
111
+ ```js
112
+ molen.on('tick', () => {
113
+ const rounds = (molen.state.rounds ?? 0) + 1;
114
+ molen.patchState({ rounds });
115
+ if (rounds % 30 === 0) molen.spawnType('game.enemy');
116
+ });
117
+ ```
118
+
119
+ Mark each script that follows this rule with `"checkpoint": "state"` in its scene entry
120
+ (or `checkpoint: 'state'` in `LoadedScript`). This is an authoring contract, not static analysis
121
+ of JavaScript: do not mark a script that keeps counters, cooldowns, or other durable values in
122
+ mutable closures. `molen.state` is isolated by script id; reads are immutable, and reload retains
123
+ it. Initialization should use existing state (`molen.state.value ?? initialValue`) rather than
124
+ unconditionally resetting it. Script ids must stay stable across save/load.
125
+
126
+ For scripts without this declaration, `ReplayPlayer` reconstructs from the beginning when
127
+ seeking. Restoring a nonzero checkpoint into their active script host throws an actionable
128
+ error instead of silently resetting closures. Cached seeking is available once every script
129
+ has opted in. Setup-module systems have the same durable-state obligation: store state
130
+ in components or use `world.registerSnapshotProvider`; the engine cannot serialize host closures.
131
+
132
+ Randomness during initialization, command/event handling, and ticks uses the same seeded world
133
+ RNG. Reload evaluation consumes fresh draws from the current world stream; restoring a
134
+ checkpoint restores its saved RNG state after the host has constructed the scripts. Timers and tweens commit their next state before dispatching completion events, so handlers
135
+ can cancel repeating work or schedule the next step. Events already due in that system pass
136
+ are dispatched once in their original order.
137
+
138
+ ### Script trust: a script runs as the host process
139
+
140
+ A script has the authority of the process that evaluates it. **Treat a scene manifest like source
141
+ code: only run manifests you would run as a program.** That matters most for the `molen` CLI and
142
+ the MCP server, which evaluate a manifest's scripts **in-process** on a developer's machine, so a
143
+ `scene.json` handed to you by an agent, a sample repo, or a bug report is a program you are about
144
+ to execute.
145
+
146
+ The `Compartment` and its tamed endowments are there to make the simulation **deterministic**, not
147
+ to contain hostile code. Concretely, un-hardened:
148
+
149
+ - **Intrinsics are shared and mutable.** The kernel does not call SES `lockdown()` — it is
150
+ process-global and would freeze the intrinsics of every host that links the kernel — so
151
+ `Object`, `Array` and friends inside a script are the host's own. `Array.prototype.x = 1` in a
152
+ script changes the array prototype the kernel itself runs on.
153
+ - **The host global is one expression away.** `(() => {}).constructor('return globalThis')()`
154
+ returns the host realm — in Node, `process` and all.
155
+ - **Taking `Math.random` away stops accidents, not attacks.** It removes the most common source
156
+ of accidental non-determinism; it does nothing to a script that is trying to get out, and was
157
+ never meant to.
158
+
159
+ What the Compartment does buy, reliably: each script gets a fresh global (and a fresh one per hot
160
+ reload), `config` and the shared `molen` verb set are frozen so one script cannot rewrite
161
+ another's verbs or the manifest, and `Date` / `Intl` / `Promise` / `Math.random` cannot be reached
162
+ by accident — the determinism rules below are enforced rather than merely documented.
163
+
164
+ #### Hardening a kernel-only host (`hardenScripts()`)
165
+
166
+ A host whose whole job is running the kernel *can* have the boundary. `hardenScripts()` from
167
+ `@bendyline/molen-kernel` runs SES `lockdown()` once for the process: intrinsics are frozen and
168
+ `Function.prototype.constructor` stops building functions in the host realm, so the escape above
169
+ throws instead of returning `globalThis`.
170
+
171
+ ```ts
172
+ import { buildWorld, hardenScripts } from '@bendyline/molen-kernel';
173
+
174
+ hardenScripts(); // once, at startup, BEFORE buildWorld
175
+ const world = buildWorld(manifest); // scripts installed here cannot reach the host realm
176
+ ```
177
+
178
+ - **Process-global and irreversible.** Call it at host startup, before building a world, and only
179
+ in a process dedicated to the kernel — a Worker, or a Node host that does nothing else. Do
180
+ **not** call it in a host that also runs bundlers, image/asset tooling, or a browser-automation
181
+ stack: frozen intrinsics break libraries that patch prototypes at runtime. That is why the CLI
182
+ and the MCP server do not call it for you.
183
+ - **Idempotent.** It returns `true` if this call performed the lockdown and `false` if the realm
184
+ was already hardened (by an earlier call or by the host's own `lockdown()`); `scriptsHardened()`
185
+ reports the current state.
186
+ - **Determinism is unaffected** — it never depended on lockdown. The kernel ticks, hashes and
187
+ replays identically before and after; Rapier's WASM initializes under lockdown too.
188
+ - `hardenScripts({ errorTaming: 'unsafe' })` keeps `error.stack` readable while you debug;
189
+ `overrideTaming` and `stackFiltering` are the other passthroughs. Defaults are SES's, except
190
+ `overrideTaming: 'severe'` (the most forgiving setting for ordinary JS).
191
+
192
+ `molen new` puts the call in the generated Worker as a commented-out one-liner: a starter you
193
+ author yourself does not need it, and uncommenting it is the whole change if that Worker will run
194
+ scenes you did not write.
195
+
196
+ ### Determinism rules (what every script must follow)
197
+
198
+ These are the rules an author follows to keep a run reproducible. They are determinism tooling —
199
+ see [Script trust](#script-trust-a-script-runs-as-the-host-process) for why that is not the same
200
+ as containment.
201
+
202
+ - No `Math.random` — the injected `Math` has no `random`; use `molen.rng()`.
203
+ - No `Date` or `Intl` — both are shadowed to `undefined`, so a reach for them fails at the use
204
+ site. Use `molen.tick` for time.
205
+ - No `Promise`: it is shadowed too, because a `.then()` callback would run after the tick's hash
206
+ was taken. Use `molen.after` / `molen.every` for "later".
207
+ - Math goes through `molen.math` (routed through `dmath`, the cross-platform swap point).
208
+ - Locale formatting (`toLocaleString`, `localeCompare`) lives on `Number`/`String` prototypes,
209
+ which the Compartment cannot take away — keep it out of component state and event payloads, and
210
+ format for display in the client instead.
211
+ - These keep replay hashes identical run-to-run; `molen replay <fixture>` will pinpoint the first
212
+ divergent tick (with a component diff) if you break them.
213
+
214
+ A script that sticks to IEEE-exact arithmetic reproduces on any JS engine; one that calls
215
+ `molen.math.sin` and friends reproduces on the same JS engine, because `dmath` is today a thin
216
+ re-export of native `Math` for transcendentals. [determinism.md](determinism.md) has the level for
217
+ every subsystem, what a host can break from outside, and what `STATE_FORMAT` means for save files.
218
+
219
+ ### Typed scripts: checked before the first tick
220
+
221
+ Scripts are TypeScript, and they are **checked** — not just at the edges. `molen types gen`
222
+ writes two generated files next to every directory of file-backed scripts:
223
+
224
+ | File | What it is |
225
+ |---|---|
226
+ | `molen-scripts.d.ts` | ambient declarations for `molen` and `config`, generated from the same facts the engine validates against |
227
+ | `tsconfig.json` | the project that checks `*.ts` (and any `*.js`) in that directory — editors pick it up automatically |
228
+
229
+ The declarations are derived, not hand-written: component names and their data shapes come from
230
+ the component registry (scene-declared custom components included), the entity id and prefab
231
+ unions from the scene, `spawnType` ids from the project type registry, and each command's payload
232
+ from the JSON Schema the scene declares under `commands`. `config` is typed from the `config`
233
+ blocks of the scripts in that directory, each key tagged with the script that declares it.
234
+
235
+ ```sh
236
+ molen types gen # regenerate after editing the scene, its commands, or the type registry
237
+ molen scripts check # type-check every script in the project
238
+ ```
239
+
240
+ So these are errors at author time rather than throws at tick 40:
241
+
242
+ ```js
243
+ molen.get('player', 'transfrom'); // TS2345: not assignable to keyof MolenComponentData
244
+ molen.patch('hero', 'transform', { pos: [1, 2] }); // TS2322: needs 3 elements
245
+ molen.onCommand('move', (p) => p.dir[2]); // TS2493: tuple has length 2
246
+ molen.spawnType('arena.enemey'); // TS2345: not a registered type id
247
+ ```
248
+
249
+ Two things the types insist on, both real:
250
+
251
+ - **`get` returns `T | undefined`.** An entity can be destroyed and a component removed, so guard
252
+ (`const g = molen.get('game', 'state'); if (!g) return;`) — the examples do.
253
+ - **Reads are `Readonly`.** Mutating one throws at runtime; now it also fails to compile.
254
+
255
+ Annotate where inference needs help — a fixed-length vector is the common case:
256
+
257
+ ```ts
258
+ const pos: [number, number, number] = onX ? [a, 0, b] : [b, 0, a];
259
+ ```
260
+
261
+ Because erasure is not compilation, a script may only use **erasable** syntax: no `enum`, no
262
+ `namespace`, no constructor parameter properties, and `import type` for any type-only import.
263
+ The generated tsconfig sets `erasableSyntaxOnly`, so `molen scripts check` reports that as an
264
+ error instead of letting the scene fail to load. A script still may not `import` anything at
265
+ runtime — the Compartment has no module loader, so its whole world is `molen` and `config`. That
266
+ is an authoring constraint, not containment (see
267
+ [Script trust](#script-trust-a-script-runs-as-the-host-process)).
268
+
269
+ `molen scripts check` refuses to run against stale declarations: if the scene changed and the
270
+ generated files no longer match, it says so and names `molen types gen` rather than reporting
271
+ errors against types the scene no longer describes. Scripts authored inline as `code` have no
272
+ file to check — another reason to prefer `path` refs.
273
+
274
+ ### What the script API cannot express
275
+
276
+ Shape of the verb set, not a containment claim (for that, see
277
+ [Script trust](#script-trust-a-script-runs-as-the-host-process)):
278
+
279
+ - Run in a phase other than `update` (all tick handlers run in one system; command handlers run
280
+ in the commands phase). Post-physics logic belongs in a setup-module system.
281
+ - Register a new command *type* — scenes declare types under `commands`; scripts attach handlers.
282
+ - `import` anything, or reach `Date` / `Intl` / `Promise` / `Math.random` by accident (the
283
+ determinism rules above).
284
+
285
+ Errors carry the script id: `script "chase" tick handler at tick 12: …`, or
286
+ `script "spawner" failed to evaluate: …` for syntax errors.
287
+
288
+ ## 2. Setup module (`setup.mjs`) — systems and typed authoring
289
+
290
+ Use a code module for ECS **systems** in any phase and for typed TypeScript authoring. Pass it
291
+ with `--setup ./setup.mjs`, or set `"setup": "setup.mjs"` in project.json and every scene op
292
+ picks it up. Within a phase, systems run by `priority` (lower first, default 0), then in
293
+ registration order; the character controller, for example, prepares at -100 and reconciles with
294
+ the ground at 100.
295
+
296
+ ```js
297
+ export function setup(world, manifest) {
298
+ world.addSystem((w, ctx) => { /* runs after physics */ }, { phase: 'late', name: 'cleanup' });
299
+ world.registerCommand('spawn_cube', (w) => {
300
+ w.spawnRaw({
301
+ transform: { pos: [0, 2, 0], rot: [0, 0, 0, 1] },
302
+ renderable: { kind: 'primitive', ref: 'box', materialRef: 'palette:#e6194b' },
303
+ });
304
+ });
305
+ }
306
+ export default setup;
307
+ ```
308
+
309
+ A setup module loaded from an arbitrary folder can't import the kernel (no `node_modules`
310
+ there), so it uses `world.spawnRaw(componentMap)`, `world.registerCommand`, `world.addSystem`,
311
+ and string-named component handles (`w.patch(id, { name: 'kinematicBody' }, …)`). Inside a
312
+ workspace package you can import handles from `@bendyline/molen-kernel` and use the typed
313
+ `world` API or `defineExperience({...})` (see [project.md](project.md)).
314
+
315
+ A command type may carry many handlers: a scene-declared `move` can be handled by a script and by
316
+ a setup module; handlers run in registration order (setup first, then scripts in manifest order).
317
+
318
+ ## Build order (one path for every host)
319
+
320
+ `buildWorld(manifest, setup?, opts?)` is how tooling ops, example workers, and tests all build a
321
+ world: data-declared systems (gameplay; kinematics + character controller when `physics` asks
322
+ for them) → declared `commands` → entities → physics plugin hook (rapier) → terrain hook →
323
+ `setup` → the manifest's scripts. Scripts install last so they see every command and every
324
+ capability extension.
325
+
326
+ ## Try it
327
+
328
+ `molen new my-experience` scaffolds a scene with a control script, an input block, and a
329
+ `setup.mjs`, plus `cmds.json` / `checks.json`, wired for the full loop in
330
+ [agent-loop.md](agent-loop.md).
@@ -0,0 +1,192 @@
1
+ # Earth and authored skies
2
+
3
+ Put `sky` on the singleton `environment` component to render a clear sky, Sun, Moon and
4
+ stars, with lighting that follows the Sun and lunar phase. It works in live clients, snapshot
5
+ viewers, `molen shot`, and `molen frames`, on WebGL and WebGPU. Scenes without `sky` retain
6
+ their existing environment behavior. No external texture or astronomy service is required.
7
+
8
+ ## Author an Earth sky
9
+
10
+ ```json
11
+ {
12
+ "id": "environment",
13
+ "components": {
14
+ "environment": {
15
+ "sky": {
16
+ "mode": "earth",
17
+ "observer": { "latitude": 47.6, "longitude": -122.3, "elevation": 50 },
18
+ "time": { "epochMs": 1718942400000, "scale": 60 },
19
+ "stars": { "magnitudeLimit": 6, "intensity": 1 },
20
+ "lighting": { "sunIntensity": 3, "moonIntensity": 0.12 }
21
+ },
22
+ "toneMapping": "agx",
23
+ "shadows": "medium"
24
+ }
25
+ }
26
+ }
27
+ ```
28
+
29
+ The clock is `epochMs + simulationSeconds × scale × 1000`, where simulation seconds are
30
+ `tick / tickRate`. `epochMs` is UTC Unix milliseconds at tick zero. `scale: 1` advances at
31
+ simulation speed, `60` advances a minute per simulation second, `0` freezes, and negative
32
+ values rewind. Captures seek directly to the requested tick; no accumulated browser frame
33
+ time is needed. Rendering samples a stable one-second UTC grid; the pure ephemeris API uses
34
+ the exact supplied time. Pausing or resynchronizing the simulation also pauses or seeks the sky.
35
+
36
+ Latitude is degrees north, longitude degrees east (west is negative), elevation is meters above
37
+ sea level. Molen uses +X east, +Y up and -Z north. `observer.northOffsetDeg` rotates geographic
38
+ north clockwise toward +X for worlds with another orientation. Location is explicit; the engine
39
+ does not request geolocation or infer it from arbitrary entity coordinates. For a large Earth
40
+ world, the host should update the observer when moving to a different geographic region.
41
+
42
+ To start at the current time, supply it once **in the host**, before loading the manifest:
43
+
44
+ ```ts
45
+ const sky = {
46
+ mode: 'earth' as const,
47
+ observer: { latitude: 47.6, longitude: -122.3 },
48
+ time: { epochMs: Date.now(), scale: 1 },
49
+ };
50
+ ```
51
+
52
+ Store that epoch with the scene to reproduce it later. Scene scripts cannot read `Date`;
53
+ they can patch the environment's sky data in response to commands. Changing speed without a
54
+ jump requires rebasing `epochMs` so that the new clock has the same UTC value at the current tick.
55
+ Timezone and daylight-saving conversion belongs in the host UI; the renderer only consumes UTC.
56
+
57
+ ## Renderer API and astronomical queries
58
+
59
+ ```ts
60
+ import { applyEnvironment, evaluateEarthSky, starDirection } from '@bendyline/molen-client';
61
+
62
+ applyEnvironment(viewer.renderer, { sky, toneMapping: 'agx' });
63
+ viewer.renderFrame(); // Live clients and snapshots supply their own simulation time.
64
+
65
+ const state = evaluateEarthSky(Date.parse('2024-03-25T05:00:00Z'), sky.observer);
66
+ console.log(state.sun.altitudeDeg, state.sun.azimuthDeg);
67
+ console.log(state.moon.illuminatedFraction, state.moon.phase);
68
+ const sirius = starDirection(101.287, -16.716, state);
69
+ ```
70
+
71
+ Standalone `Renderer` hosts call `renderer.setEnvironmentTime(simulationSeconds)` before
72
+ `renderer.render()` to drive the clock themselves.
73
+ For a time slider over a live or snapshot viewer, call
74
+ `renderer.setEnvironmentTimeOverride(simulationSeconds)` to preview the sky without seeking
75
+ the world. Pass `undefined` to resume the viewer's clock. The override uses the sky's configured
76
+ epoch and scale, just like simulation time. `renderer.sky?.setObserver(observer)` moves an Earth
77
+ observer without rebuilding geometry; the next render updates the ephemeris.
78
+
79
+ `evaluateEarthSky` is a pure CPU query; it needs neither DOM nor GPU. Directions point toward
80
+ each body. Azimuth runs clockwise from geographic north, regardless of `northOffsetDeg`.
81
+ The Moon's `phase` runs from 0 (new), through 0.25 (first quarter), 0.5 (full), to 0.75 (last
82
+ quarter). `illuminatedFraction` is 0–1. Returned diameters are apparent angular degrees.
83
+ `renderer.sky?.frame` exposes the current rendering sample, including daylight and star visibility.
84
+ These are client calculations using native floating-point math, outside the kernel state hash.
85
+
86
+ When enabled, sky lighting replaces `environment.ambient` and `environment.sun`. Configure
87
+ `sky.lighting.sunIntensity`, `moonIntensity`, `dayAmbient`, `nightAmbient` and `castShadow`
88
+ instead. Sunlight fades around the horizon; moonlight depends on altitude, phase and darkness.
89
+ Only the Sun casts a sky shadow in phase 1. Shadows also require `environment.shadows` and
90
+ scene geometry that casts/receives shadows; their local frustum follows the camera.
91
+ `sun.visible`/`moon.visible` control the disks independently of lighting. Use the corresponding
92
+ light intensity to disable illumination. `sun.size` and `moon.size` are visual multipliers;
93
+ the default 1 preserves real angular size. Larger values help stylized scenes and small displays.
94
+
95
+ ## Other worlds
96
+
97
+ The shared sky dome, twilight gradient, star sphere and celestial-body rendering can use authored
98
+ directions and colors without an Earth clock:
99
+
100
+ ```ts
101
+ applyEnvironment(renderer, {
102
+ sky: {
103
+ mode: 'custom',
104
+ sunBody: { direction: [-1, -0.12, -1], angularDiameterDeg: 1 },
105
+ moonBody: { direction: [0.6, 0.45, -1], angularDiameterDeg: 7 },
106
+ palette: {
107
+ dayZenith: '#5f36a3', dayHorizon: '#e394b5', twilight: '#e37893',
108
+ nightZenith: '#100720', nightHorizon: '#543156', moon: '#bee9d8'
109
+ },
110
+ starRotationDeg: [25, 40, 15]
111
+ }
112
+ });
113
+ ```
114
+
115
+ Directions must be nonzero; their length is ignored. The Moon's terminator follows the Sun's
116
+ direction. Omit `moonBody` for a moonless world. `starRotationDeg` is an XYZ Euler rotation in
117
+ degrees. A custom sky uses whatever star catalog the renderer has, rotated this way: the Earth
118
+ catalog's pattern, or an authored list. Low-level `new SkyVisual(data, { stars })` accepts an
119
+ authored star list with `direction`, `magnitude`, and optional hex `color`.
120
+ Attach its `lights` group to the world scene, call `update(seconds)` and `prepareCamera(camera)`,
121
+ and render its `scene`/`camera` as a background pass before your scene. Dispose it when removed.
122
+
123
+ `palette` also accepts `ground`, `sun`, and `moon`. `moon.earthshine` controls the dark side's
124
+ subtle visibility. Stars support `enabled`, `magnitudeLimit` (up to the catalog limit of 6.5),
125
+ `intensity` and visual angular `size`. Stars disappear below the horizon and fade through
126
+ twilight; a bright visible Moon reduces their contrast. Moon disks occlude stars behind them.
127
+
128
+ The clear-sky gradient is art directed, with a forward Sun glow. It is deliberately independent
129
+ of distance fog, haze, clouds and weather. Existing `environment.fog` still works on world
130
+ geometry; sky colors and lights do not configure it. The background has its own camera and clip
131
+ range, so it stays stable through floating-origin rebases, distant terrain and reversed depth.
132
+ Orthographic views use a 60° perspective sky oriented along the orthographic camera's view.
133
+
134
+ ## The star catalog is content
135
+
136
+ No package ships star data. The Earth catalog is the `molen.sky` content pack (source
137
+ `content/sky/`): `stars.bin`, 8,404 stars in the 50 KB `molen/stars@1` binary format. Load it
138
+ once and hand it to the renderer; until then skies have no stars.
139
+
140
+ ```ts
141
+ import { createClient, decodeStarCatalog } from '@bendyline/molen-client';
142
+ import { openPack } from '@bendyline/molen-pack';
143
+
144
+ const sky = await openPack('/packs/molen.sky.zip'); // wherever the app hosts it
145
+ const stars = decodeStarCatalog(await sky.readBytes('stars.bin'));
146
+ const client = await createClient(link, { stars }); // or later: client.renderer.setStarCatalog(stars)
147
+ ```
148
+
149
+ `setStarCatalog` applies to the current sky at once and to every later one.
150
+
151
+ ## Accuracy, sources and scope
152
+
153
+ The supported UTC date interval is 1900–2100. Sun and Moon positions use compact orbital
154
+ elements with the major lunar perturbations, ellipsoidal observer parallax and sidereal rotation.
155
+ The formula reference is Paul Schlyter's
156
+ [Computing planetary positions](https://www.stjarnhimlen.se/comp/ppcomp.html).
157
+ Regression fixtures independently compare geometric topocentric directions with
158
+ [Astronomy Engine](https://github.com/cosinekitty/astronomy): the included cases cover both
159
+ hemispheres, poles, solstices, equinox, phase changes, and the date-range endpoints. Their
160
+ tolerances are 0.03° for the Sun and 0.15° for the Moon; these are fixture tolerances, not a
161
+ guaranteed error bound over the entire interval.
162
+
163
+ The `molen.sky` pack's 8,404 stars through visual magnitude 6.5 are numerical position/photometry records
164
+ from **Hoffleit, D. & Warren, W. H. Jr. (1991), Bright Star Catalogue, 5th Revised Edition
165
+ (Preliminary Version)**, [CDS V/50](https://cdsarc.cds.unistra.fr/ftp/V/50/), also described by
166
+ [NASA HEASARC](https://heasarc.gsfc.nasa.gov/W3Browse/star-catalog/bsc5p.html).
167
+ The default magnitude cutoff is 6. Stellar colors approximate B−V; visual splat sizes are
168
+ exaggerated for visibility. J2000 coordinates receive precession and rotate with local sidereal
169
+ time. Proper motion, variability, stellar parallax and nutation are omitted. Positions are
170
+ quantized to about 0.005° and magnitudes to 0.04. Regenerate `content/sky/stars.bin` with
171
+ `node packages/client/scripts/generate-star-catalog.mjs /path/to/catalog.gz`; the pack's NOTICE
172
+ records the input checksum.
173
+
174
+ No atmospheric refraction, horizon dip, terrain horizon calculation, eclipses, planetary bodies,
175
+ Milky Way texture, lunar libration or photographic lunar map are modeled. The procedural lunar
176
+ surface is illustrative. Sunrise and sunset are geometric approximations; this is an experience
177
+ renderer, not a navigation or observational ephemeris. Layered clouds, precipitation, visibility
178
+ and physical atmospheric state live in the separate [weather component](weather.md).
179
+ Volumetric atmospheric scattering remains future work.
180
+
181
+ ## Try it
182
+
183
+ Run `pnpm --filter @bendyline/molen-examples-world-explorer dev` and open
184
+ `http://localhost:5225/sky.html`. Choose a location, UTC date, time speed,
185
+ or the authored Amethyst world; drag to look around and use **Face Sun** / **Face Moon**.
186
+ **Use current time** reads the host clock once and starts normal time flow.
187
+ `?backend=webgl` / `?backend=webgpu` select a backend; `?hud=0` hides controls for capture.
188
+ The terrain explorer at `/index.html` includes a 24-hour slider, date picker and Now button.
189
+ It starts at noon today and shows times in the browser's labeled local time zone. Scrubbing
190
+ keeps the camera fixed while the sky, celestial bodies and scene lighting follow the selected
191
+ instant and camera location. Use `?date=2024-03-25T05:00:00Z` for a repeatable instant or
192
+ `?sky=daylight` for the legacy fixed daylight terrain comparison rig.
@@ -0,0 +1,42 @@
1
+ # Logical source bundles
2
+
3
+ A logical thing is authored in one copyable directory. The directory contains a validated
4
+ `source.json` (`molen/source-bundle@1`) and every source file owned by that thing: definitions,
5
+ editable models or procedural recipes, authoring generators, behavior scripts, textures, sounds,
6
+ and provenance.
7
+
8
+ ```text
9
+ source/<category>/<thing>/
10
+ source.json
11
+ README.md
12
+ entity.types.json
13
+ models/
14
+ source.glb
15
+ generate.mjs
16
+ baseline.json
17
+ scripts/
18
+ interactions.ts
19
+ textures/
20
+ sounds/
21
+ ```
22
+
23
+ Only create a subdirectory when the thing has a file of that class; empty directories are not
24
+ required. A root-level entity type document can reference `scripts/` without escaping its own
25
+ directory. Paths in `source.json` are relative to the bundle and cannot escape it. A source bundle
26
+ must not depend on a sibling bundle for concrete entity values or owned behavior. It may depend on
27
+ documented engine capabilities such as the generic vehicle, airplane, helicopter, or procedural
28
+ building solvers, and on shared material libraries.
29
+
30
+ Imported assets remain build outputs. Their `molen/asset@1` sidecars and canonical models belong
31
+ under the owning project's runtime `assets/` tree, not inside the source bundle. Browser `public/`
32
+ and `dist/` copies are also outputs. This leaves one authority for authoring while preserving the
33
+ existing runtime contracts.
34
+
35
+ Validate a manifest directly:
36
+
37
+ ```sh
38
+ molen validate path/to/source.json
39
+ ```
40
+
41
+ Repository builds additionally verify that every path listed by a source bundle exists, that no
42
+ owned source file is omitted, and that pinned source-model hashes match.