@bendyline/molen-tooling 0.0.3 → 0.0.4

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 (46) hide show
  1. package/README.md +4 -4
  2. package/dist/capture/harness.js +222 -222
  3. package/dist/capture/worldgen-preview.js +205 -205
  4. package/dist/cli.mjs +54 -2
  5. package/dist/docs-src/guide/aircraft.md +12 -0
  6. package/dist/docs-src/guide/ambient-life.md +389 -0
  7. package/dist/docs-src/guide/browser-mount.md +5 -0
  8. package/dist/docs-src/guide/capability-authoring.md +5 -0
  9. package/dist/docs-src/guide/determinism.md +24 -16
  10. package/dist/docs-src/guide/earth-view.md +60 -12
  11. package/dist/docs-src/guide/entities.md +8 -0
  12. package/dist/docs-src/guide/examples.md +4 -1
  13. package/dist/docs-src/guide/figures.md +3 -0
  14. package/dist/docs-src/guide/game-samples.md +1 -1
  15. package/dist/docs-src/guide/markers.md +4 -1
  16. package/dist/docs-src/guide/navigation.md +6 -0
  17. package/dist/docs-src/guide/surface-rendering.md +4 -3
  18. package/dist/docs-src/guide/terrain.md +7 -0
  19. package/dist/docs-src/guide/vehicles.md +14 -1
  20. package/dist/docs-src/llms.txt +7 -4
  21. package/dist/docs-src/schemas/README.md +1 -0
  22. package/dist/docs-src/schemas/components.md +530 -1
  23. package/dist/docs-src/schemas/scene.md +105 -0
  24. package/dist/docs-src/schemas/transport-network.md +351 -0
  25. package/dist/index.d.mts +44 -1
  26. package/dist/index.mjs +81 -4
  27. package/dist/{mcp-BTVwVKFb.mjs → mcp-BtuworIW.mjs} +22 -1
  28. package/dist/{ops-BPdHodFR.mjs → ops-DMGcWoL2.mjs} +290 -65
  29. package/dist/templates/city-courier/README.md +1 -1
  30. package/dist/templates/city-courier/delivery-run.replay.json +151 -151
  31. package/dist/templates/city-courier/gen/molen-types.ts +82 -2
  32. package/dist/templates/city-courier/package.json +1 -0
  33. package/dist/templates/city-courier/scene.json +99 -282
  34. package/dist/templates/city-courier/scripts/game.ts +2 -14
  35. package/dist/templates/city-courier/scripts/molen-scripts.d.ts +86 -13
  36. package/dist/templates/city-courier/src/worker.ts +3 -1
  37. package/dist/templates/city-courier/test/headless.test.ts +3 -2
  38. package/dist/templates/data-viz/README.md +1 -1
  39. package/dist/templates/index.json +19 -1
  40. package/dist/templates/skybound/gen/molen-types.ts +82 -2
  41. package/dist/templates/skybound/scripts/molen-scripts.d.ts +81 -1
  42. package/dist/templates/terrain-flyover/README.md +2 -2
  43. package/dist/templates/top-down-arena/README.md +1 -1
  44. package/dist/templates/top-down-arena/scripts/molen-scripts.d.ts +81 -1
  45. package/dist/templates/top-down-arena/src/gen/molen-types.ts +82 -2
  46. package/package.json +13 -12
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as packAsset, A as inspectContentPack, B as OPS_CATALOG, C as checkTypesOp, D as buildContentPack, E as reserveNamespace, F as listFigurePresets, G as planAudio, H as formatOp, I as exportFrames, K as importSound, L as driveScene, M as generateTypes, O as extractContentPack, P as previewFigure, Q as formatPacked, S as rasterizeMaterial, T as projectInfo, U as checkScripts, V as describeOps, X as screenshotAsset, Y as stageAssets, Z as formatBytes, _ as loadComponentRegistry, b as diffSnapshots, c as validateAsset, d as runSimulation, et as inspectAsset, f as screenshotScene, g as listSchemasOp, h as listComponentsOp, i as bakeWorldgen, j as verifyContentPack, k as fetchContentPack, l as applyUvPaintOp, m as getSchemaOp, n as worldgenStats, p as getComponentOp, q as checkSoundbank, r as previewWorldgen, rt as importAsset, s as simWatch, t as formatWorldgenStats, tt as listAssets, u as testTypes, ut as playExperience, v as scaffoldExperience, w as listTypes, x as runReplayFile, y as listTemplates, z as searchDocs } from "./ops-BPdHodFR.mjs";
2
+ import { $ as formatPacked, A as inspectContentPack, B as searchDocs, C as checkTypesOp, D as buildContentPack, E as reserveNamespace, F as previewFigure, H as describeOps, I as listFigurePresets, J as checkSoundbank, K as planAudio, L as exportFrames, M as bakeNetwork, N as generateTypes, O as extractContentPack, Q as formatBytes, R as driveScene, S as rasterizeMaterial, T as projectInfo, U as formatOp, V as OPS_CATALOG, W as checkScripts, X as stageAssets, Z as screenshotAsset, _ as loadComponentRegistry, b as diffSnapshots, c as validateAsset, d as runSimulation, dt as playExperience, et as packAsset, f as screenshotScene, g as listSchemasOp, h as listComponentsOp, i as bakeWorldgen, it as importAsset, j as verifyContentPack, k as fetchContentPack, l as applyUvPaintOp, m as getSchemaOp, n as worldgenStats, nt as listAssets, p as getComponentOp, q as importSound, r as previewWorldgen, s as simWatch, t as formatWorldgenStats, tt as inspectAsset, u as testTypes, v as scaffoldExperience, w as listTypes, x as runReplayFile, y as listTemplates } from "./ops-DMGcWoL2.mjs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { formatIssues } from "@bendyline/molen-schema";
@@ -234,6 +234,7 @@ async function cmdSim(args) {
234
234
  for (const [domain, entry] of Object.entries(result.content ?? {})) out(`content: ${domain} ${entry.hash}${entry.packs ? ` (${entry.packs.join(", ")})` : ""}`);
235
235
  }
236
236
  out(`events: ${result.eventCount}`);
237
+ if (result.ambient !== void 0) out(`ambient: ${Object.entries(result.ambient.agents).filter(([, n]) => n > 0).map(([kind, n]) => `${n} ${kind}`).join(", ") || "no agents"} on ${result.ambient.lanes} lanes (${result.ambient.spawned} spawned, ${result.ambient.despawned} removed)`);
237
238
  if (result.physics !== void 0 && result.physics !== "none") out(result.physics === "rapier" ? "physics: rapier (deterministic same-build/same-platform only)" : `physics: ${result.physics} (cross-platform deterministic)`);
238
239
  if (result.assertionsFormatted !== void 0) out(result.assertionsFormatted);
239
240
  return result.ok ? 0 : 1;
@@ -1253,7 +1254,7 @@ async function cmdWorldgen(args) {
1253
1254
  return 2;
1254
1255
  }
1255
1256
  async function cmdMcp() {
1256
- const { startMcpServer } = await import("./mcp-BTVwVKFb.mjs");
1257
+ const { startMcpServer } = await import("./mcp-BtuworIW.mjs");
1257
1258
  await startMcpServer();
1258
1259
  return 0;
1259
1260
  }
@@ -1358,6 +1359,56 @@ async function runCli(argv) {
1358
1359
  * server, and this table are cross-checked by test/catalog.test.ts — a new op must land on all
1359
1360
  * three surfaces or that test fails.
1360
1361
  */
1362
+ async function cmdNetwork(args) {
1363
+ const sub = args.positionals[0];
1364
+ const usage = "usage: molen network bake <terrain-package.json> (--tile z/x/y [--radius n] | --bbox w,s,e,n) --out network.json [--classes road,rail,path] [--heights] [--json]";
1365
+ if (sub !== "bake") {
1366
+ err(usage);
1367
+ return 2;
1368
+ }
1369
+ const packagePath = args.positionals[1];
1370
+ const outPath = str(args.flags.out);
1371
+ if (packagePath === void 0 || outPath === void 0) {
1372
+ err(usage);
1373
+ return 2;
1374
+ }
1375
+ const bbox = str(args.flags.bbox)?.split(",").map(Number);
1376
+ if (bbox !== void 0 && (bbox.length !== 4 || bbox.some((v) => !Number.isFinite(v)))) {
1377
+ err("--bbox must be west,south,east,north in degrees");
1378
+ return 2;
1379
+ }
1380
+ const classes = str(args.flags.classes)?.split(",");
1381
+ if (classes?.some((c) => ![
1382
+ "road",
1383
+ "rail",
1384
+ "path"
1385
+ ].includes(c))) {
1386
+ err("--classes takes road, rail and/or path");
1387
+ return 2;
1388
+ }
1389
+ const radius = str(args.flags.radius);
1390
+ const r = await bakeNetwork({
1391
+ packagePath,
1392
+ outPath,
1393
+ ...str(args.flags.tile) !== void 0 ? { tile: str(args.flags.tile) } : {},
1394
+ ...radius !== void 0 ? { radius: Number(radius) } : {},
1395
+ ...bbox !== void 0 ? { bbox } : {},
1396
+ ...classes !== void 0 ? { classes } : {},
1397
+ heights: args.flags.heights === true
1398
+ });
1399
+ if (!r.ok) {
1400
+ err(r.error ?? "network bake failed");
1401
+ return 1;
1402
+ }
1403
+ if (args.flags.json === true) out(JSON.stringify(r, null, 2));
1404
+ else {
1405
+ const counts = Object.entries(r.classes ?? {}).map(([cls, n]) => `${n} ${cls}`).join(", ");
1406
+ out(`wrote ${r.path}: ${r.ways} ways (${counts}) from ${r.tiles} tiles`);
1407
+ if (r.origin !== void 0) out(`origin ${r.origin.latitude}, ${r.origin.longitude}`);
1408
+ for (const w of r.warnings ?? []) out(` ! ${w}`);
1409
+ }
1410
+ return 0;
1411
+ }
1361
1412
  const CLI_COMMANDS = {
1362
1413
  validate: cmdValidate,
1363
1414
  sim: cmdSim,
@@ -1384,6 +1435,7 @@ const CLI_COMMANDS = {
1384
1435
  templates: cmdTemplates,
1385
1436
  figure: cmdFigure,
1386
1437
  worldgen: cmdWorldgen,
1438
+ network: cmdNetwork,
1387
1439
  mcp: cmdMcp
1388
1440
  };
1389
1441
  //#endregion
@@ -107,6 +107,18 @@ and `airplane.yawStability` sets sideslip restoring response (1/s at reference a
107
107
  The authored engine thrust axis is respected. Engine positions relative to the center of mass
108
108
  produce thrust-induced yaw; wing position remains metadata rather than a distributed lift model.
109
109
 
110
+ ## In an Earth view
111
+
112
+ `mountEarthView` flies the same aircraft without a practice airfield: `view.setMode('fly')` puts the
113
+ viewer in a P-51D already airborne over the current view, and `{ aircraft:
114
+ 'molen.entities.aircraft.oh6' }` picks the helicopter. `view.vehicleStatus()` reports airspeed,
115
+ altitude, vertical speed, attitude, power and engine/gear/flap state for a HUD, and
116
+ `view.recover()` restarts the flight above an impact. See [Earth view](earth-view.md#modes).
117
+ Hosts composing their own view use `EarthAircraft` from `@bendyline/molen-earth/client`: it
118
+ spawns any aircraft type into the vehicles' ECS world, on the ground or with
119
+ `airborne: { speed, power }`, boards and releases the pilot, applies `EarthPilotControls` and
120
+ draws the models.
121
+
110
122
  ## Engine sound
111
123
 
112
124
  The P-51D carries an `audioSource` that plays `aircraft.engine.piston`, a Rolls-Royce Merlin
@@ -0,0 +1,389 @@
1
+ # Ambient life: traffic, pedestrians, trains and aircraft
2
+
3
+ `@bendyline/molen-ambient` fills a world with background life: cars that keep to their lanes and
4
+ stop at signals, pedestrians on footways, trains that dwell at stations, and aircraft crossing
5
+ overhead. Agents spawn in a ring around an observer, out of its line of sight, and are removed
6
+ once it moves away. The same simulation runs in a scene with a hand-drawn street grid and in the
7
+ [Earth view](earth-view.md) on mapped roads.
8
+
9
+ The package has a **kernel half** (`/kernel`: the transport network, the spawner and the agents,
10
+ all deterministic) and a **client half** (`/client`: instanced vehicle proxies, pooled full models
11
+ near the camera, and animated figures for pedestrians). There is no root export.
12
+
13
+ ## Quick start
14
+
15
+ Add an `ambient` block to a scene. This one draws a crossroads with a signal and a footway, and
16
+ spawns traffic around the `camera-rig` entity:
17
+
18
+ ```json
19
+ {
20
+ "format": "molen/scene@3",
21
+ "name": "crossroads",
22
+ "tickRate": 60,
23
+ "ambient": {
24
+ "network": {
25
+ "format": "molen/transport-network@1",
26
+ "ways": [
27
+ { "id": "main", "class": "road", "subclass": "primary", "points": [[-300, 0], [300, 0]], "lanes": 4 },
28
+ { "id": "cross", "class": "road", "subclass": "residential", "points": [[0, -300], [0, 300]] },
29
+ { "id": "walk", "class": "path", "subclass": "footway", "points": [[-300, 12], [300, 12]] }
30
+ ],
31
+ "signals": [{ "at": [0, 0], "kind": "light" }]
32
+ },
33
+ "observer": "camera-rig",
34
+ "classes": ["car", "pedestrian"],
35
+ "density": { "car": 16 }
36
+ },
37
+ "entities": [
38
+ { "id": "camera-rig", "components": { "transform": { "pos": [30, 0, 30], "rot": [0, 0, 0, 1] } } }
39
+ ]
40
+ }
41
+ ```
42
+
43
+ ```sh
44
+ npx molen validate scene.json
45
+ npx molen sim run scene.json --ticks 600
46
+ npx molen shot scene.json --ticks 600 --camera 40,25,45 --look 0,0,0 --out crossroads.png
47
+ ```
48
+
49
+ `sim run` reports what the block produced:
50
+
51
+ ```text
52
+ tick: 600
53
+ events: 0
54
+ ambient: 58 car, 17 pedestrian on 14 lanes (75 spawned, 0 removed)
55
+ ```
56
+
57
+ Tooling installs the capability for any scene with the block, and the capture page draws the
58
+ agents, so `validate`, `sim`, `replay` and `shot` need nothing else. A scene without the block
59
+ pays nothing and has no `molen.ambient` namespace.
60
+
61
+ ## The transport network
62
+
63
+ Agents move on a `molen/transport-network@1` document: polylines called ways, plus optional
64
+ stations, signals and aerodromes. Coordinates are scene metres, `[x, z]` or `[x, y, z]` where `y`
65
+ is the road surface height.
66
+
67
+ | Field | What it holds |
68
+ |---|---|
69
+ | `ways[]` | `class` (`road`, `rail`, `path`, `air`), `subclass` (the OSM kind, for example `primary`, `residential`, `service`, `footway`, `tram`), `points`, and optionally `oneway`, `lanes`, `width`, `speed` (m/s), `layer`, `bridge`, `tunnel` |
70
+ | `stations[]` | `id`, `at: [x, z]`, `kind` (`rail` or `bus`), `dwell` in seconds. Trains stop at the rail station nearest their track |
71
+ | `signals[]` | `at: [x, z]` and `kind`. A `light` signalises the junction nearest the point. A `stop` or `yield` sign makes the arm it stands on give way |
72
+ | `aerodromes[]` | `id`, `at: [x, z]`, `heading`, `length`. Some aircraft fly its approach and departure |
73
+ | `drivingSide` | `right` (default) or `left` |
74
+ | `sidewalks` | Infer walk lanes along streets that have no mapped path nearby (default false) |
75
+
76
+ The network is built into a lane graph when it is added:
77
+
78
+ - **Lanes.** A way carries `lanes` in total, split between directions (all forward when `oneway`).
79
+ Without `lanes`, the count follows the width. Lanes sit to the right of travel for right-hand
80
+ traffic.
81
+ - **Junctions.** Ways that share a point, cross, or end on another way at the same `layer` are
82
+ joined. Different layers, and bridges over roads, never connect mid-way. Each lane gets a curved
83
+ connector to every exit it may take, and movements that cross each other take turns.
84
+ - **Control.** A junction is signalised when a `light` is near it, or when four or more arms meet
85
+ and one is a major road. An arm with a `stop` or `yield` sign gives way, and so does a service
86
+ road or a link where it joins a street. Elsewhere cars take the junction in arrival order, one
87
+ conflicting movement at a time.
88
+ - **Tunnels** keep their traffic: agents inside are simulated but flagged `hidden`, so they are
89
+ not drawn.
90
+
91
+ ### Baking a network from map data
92
+
93
+ For a scene on real terrain, bake the roads, railways and paths of a terrain package into a
94
+ document:
95
+
96
+ ```sh
97
+ npx molen network bake terrain/terrain-package.json --tile 15/5247/11439 --radius 1 --out network.json
98
+ npx molen validate network.json
99
+ ```
100
+
101
+ `--bbox west,south,east,north` takes an area in degrees instead of a tile. `--classes road,rail`
102
+ keeps only some classes, and `--heights` adds surface heights from the package's elevation. The
103
+ document's `origin` records the latitude and longitude it was baked at. The MCP tool
104
+ `network_bake` does the same.
105
+
106
+ Reference the file from the scene by path, relative to the scene:
107
+
108
+ ```json
109
+ { "ambient": { "network": "network.json", "observer": "player" } }
110
+ ```
111
+
112
+ ## The scene block
113
+
114
+ Every field is optional. [`molen/scene@3`](../schemas/scene.md) lists them with the rest of the scene.
115
+
116
+ | Field | Meaning |
117
+ |---|---|
118
+ | `network` | A path to a transport-network document, or the document inline |
119
+ | `observer` | The entity the spawn ring follows |
120
+ | `classes` | Which classes run: `car`, `pedestrian`, `train`, `aircraft` (default `["car"]`) |
121
+ | `density` | Target agents per kilometre of lane near the observer, per class. For `aircraft` it is the number in the sky |
122
+ | `drivingSide` | `right` (default) or `left`, when the network does not say |
123
+ | `radius` | Outer spawn radius for cars in metres (default 350) |
124
+ | `despawnRadius` | Distance beyond which cars are removed (default 1.3 × `radius`) |
125
+ | `templates` | A prefab name per class. Every spawned agent of that class receives its components |
126
+ | `seedSalt` | Mixed into the scene seed, to vary the traffic without reseeding the scene |
127
+
128
+ Templates are how agents join the rest of the game. The
129
+ [City Courier](https://molen.dev/play/city-courier/) sample gives its traffic a prefab with a box
130
+ `renderable`, a `collider` and an engine `audioSource`, so the courier can bump into cars and hear
131
+ them pass:
132
+
133
+ ```json
134
+ {
135
+ "prefabs": {
136
+ "npc-car": {
137
+ "extends": "box",
138
+ "components": {
139
+ "renderable": { "primitive": { "size": [1.45, 0.7, 2.6] }, "materialRef": "palette:#df735e" },
140
+ "collider": { "shape": "circle", "radius": 1.3, "layer": 1, "mask": 2 },
141
+ "audioSource": { "sound": "vehicle.engine.car", "gain": 0.6 }
142
+ }
143
+ }
144
+ },
145
+ "ambient": { "templates": { "car": "npc-car" } }
146
+ }
147
+ ```
148
+
149
+ Without a template, vehicles get the `ambient-vehicle` renderable and pedestrians a procedural
150
+ `figure`.
151
+
152
+ ## Components
153
+
154
+ | Component | Where | What it holds |
155
+ |---|---|---|
156
+ | `ambientAgent` | Every agent | Class, content type, colour, lane, distance along it, speed, state and seed. The kernel owns it: read it, never write it |
157
+ | `ambientObserver` | Optional, on the observer | Per-observer `radius`, `despawnRadius` and a `density` multiplier |
158
+ | `ambientRole` | Entity types in a content pack | Which pool a vehicle type joins and how it drives. See [NPC content](#npc-content-and-ambientrole) |
159
+
160
+ Agents also carry a `transform` that the kernel writes every tick, so scripts, audio and physics
161
+ see them like any other entity. `molen component ambientAgent` prints the full field list.
162
+
163
+ ## The observer and the spawn ring
164
+
165
+ The spawner follows one observer. It takes, in order:
166
+
167
+ 1. the scene's `observer` entity, or an entity carrying `ambientObserver`;
168
+ 2. the last `ambient.observer` command, `{ "pos": [x, y, z], "forward": [x, z] }` or
169
+ `{ "entity": id }`;
170
+ 3. a host's `setObserver` call.
171
+
172
+ With no observer, nothing spawns and existing agents keep moving.
173
+
174
+ Each class has three radii around the observer. Agents spawn between `near` and `far`, weighted
175
+ by lane length, and never inside the view cone within 150 m ahead, so traffic appears out of sight
176
+ and fades in beyond that. Anything past `keep` is removed, as is an agent whose road left the
177
+ network or one stuck for 90 s out of sight.
178
+
179
+ | Class | `near` | `far` | `keep` | Density | Cap |
180
+ |---|---|---|---|---|---|
181
+ | `car` | 60 | 350 | 450 | 12 per lane-km | 200 |
182
+ | `pedestrian` | 25 | 140 | 180 | 25 per lane-km | 60 |
183
+ | `train` | 150 | 1200 | 1500 | 0.4 per lane-km | 2 consists |
184
+ | `aircraft` | 800 | 5000 | 6000 | — | 4 |
185
+
186
+ The spawner runs every 6 ticks and places at most 4 agents per run, so a busy street fills over a
187
+ few seconds instead of in one frame.
188
+
189
+ ## What agents do
190
+
191
+ - **Cars** follow the car ahead with the Intelligent Driver Model, slow for curves, stop at red
192
+ lights and for crossing traffic, and pick a turn at each junction from a seeded draw. They also
193
+ stop for a vehicle someone is driving and for pedestrians on a crossing.
194
+ - **Pedestrians** walk `path` ways and inferred sidewalks at 1.15 to 1.65 m/s, pause now and then,
195
+ and cross roads only on a pedestrian phase or when no car is close.
196
+ - **Trains** run `rail` ways as consists, two cars by default, that follow the lead around
197
+ curves. They dwell at stations for the station's `dwell` or 20 to 40 s, and reverse at the end
198
+ of the line.
199
+ - **Aircraft** fly straight corridors a few hundred metres up, or the approach and departure of an
200
+ aerodrome within 6 km.
201
+
202
+ ## Scripts: `molen.ambient.*`
203
+
204
+ | Call | What it does |
205
+ |---|---|
206
+ | `stats()` | Agent counts per class, lanes, spawned and removed totals |
207
+ | `setObserver(entity \| { pos, forward? } \| null)` | Move the spawn ring |
208
+ | `setPolicy(patch)` | Override radii, densities, caps or driver parameters. Recorded in world state |
209
+ | `laneAt(x, z, { class?, radius? })` | The nearest lane, the distance along it, and how far away it is |
210
+ | `laneSample(lane, s)` | Position, direction and grade at a distance along a lane |
211
+ | `agentsNear(x, z, radius, kind?)` | Agent ids within a radius |
212
+ | `addRoad(points, opts?)`, `addPolyline(line)` | Extend the network at run time |
213
+ | `despawnAll(kind?)` | Remove every agent, or every agent of a class |
214
+
215
+ ```ts
216
+ molen.on('tick', () => {
217
+ if (molen.tick % 60 !== 0) return;
218
+ const player = molen.get('player', 'transform');
219
+ if (player === undefined) return;
220
+ const cars = molen.ambient.agentsNear(player.pos[0], player.pos[2], 30, 'car');
221
+ molen.patchState({ carsNearby: cars.length });
222
+ });
223
+ molen.on('rush-hour', () => molen.ambient.setPolicy({ car: { perLaneKm: 24 } }));
224
+ ```
225
+
226
+ Scripts cannot register map tiles: that belongs to the host.
227
+
228
+ ## Browser hosts
229
+
230
+ A Worker-hosted scene adds the capability in the worker and the renderable kinds on the page:
231
+
232
+ ```ts
233
+ // worker.ts
234
+ import { ambientCapability } from '@bendyline/molen-ambient/kernel';
235
+ import { figuresScriptApi, installFigures } from '@bendyline/molen-figures/kernel';
236
+ import { startKernelWorker } from '@bendyline/molen-kernel';
237
+
238
+ startKernelWorker({
239
+ scene: scene(),
240
+ capabilities: [
241
+ ambientCapability(),
242
+ (world) => ({ figures: figuresScriptApi(installFigures(world)) }), // animates pedestrians
243
+ ],
244
+ });
245
+
246
+ // main.ts
247
+ import { ambientVehicleKind } from '@bendyline/molen-ambient/client';
248
+ import { mountExperience } from '@bendyline/molen-client';
249
+ import { figureKind } from '@bendyline/molen-figures/client';
250
+
251
+ await mountExperience({ link: worker, scene: scene(), canvas, kinds: [ambientVehicleKind(), figureKind()] });
252
+ ```
253
+
254
+ A scene whose `network` is a path needs the document handed over, because the worker cannot read
255
+ files. Pass it keyed by the path as written in the scene:
256
+
257
+ ```ts
258
+ ambientCapability({ networks: { 'network.json': await (await fetch('/network.json')).json() } });
259
+ ```
260
+
261
+ A host that steps its own `World` on the main thread installs the kernel directly and draws with
262
+ `createAmbientRenderer`, which instances every vehicle of a shape into one draw call:
263
+
264
+ ```ts
265
+ import { createAmbientRenderer } from '@bendyline/molen-ambient/client';
266
+ import { installAmbient } from '@bendyline/molen-ambient/kernel';
267
+
268
+ const ambient = installAmbient(world, { classes: ['car', 'pedestrian'] });
269
+ ambient.addDocument(network);
270
+ const renderer = createAmbientRenderer({ world, parent: scene });
271
+
272
+ function frame(dt: number) {
273
+ ambient.setObserver({ pos: camera.position.toArray(), forward: [viewX, viewZ] });
274
+ world.step();
275
+ renderer.update(camera.position.toArray(), dt);
276
+ }
277
+ ```
278
+
279
+ `installAmbient` takes `traffic`, `classes`, `policy`, `types`, `templates`, `ground` and `seed`.
280
+ For streamed maps, `registerTile` and `unregisterTile` add and drop one tile's transportation
281
+ features. Changes queue until the next tick, so a tile never changes the network mid-step.
282
+ `blocks(box)` answers whether an ambient car overlaps a box, for a vehicle solver's obstacle test.
283
+
284
+ ## In the Earth view
285
+
286
+ `mountEarthView` runs ambient life by default on the roads, footways and railways of the streamed
287
+ map:
288
+
289
+ ```ts
290
+ const view = await mountEarthView({
291
+ canvas,
292
+ terrain,
293
+ content,
294
+ camera,
295
+ ambient: { density: 0.6, pedestrians: true, rail: true, aircraft: true },
296
+ });
297
+ trafficButton.onclick = () => view.setAmbientEnabled(!view.ambientEnabled);
298
+ ```
299
+
300
+ `density` scales how busy the streets are, from 0 to 1. `cars`, `pedestrians`, `rail` and
301
+ `aircraft` switch classes, and `drivingSide` sets the side of the road. `ambient: false` turns the
302
+ layer off entirely. `stats().ambient` reports the counts on screen and the tiles in use.
303
+
304
+ The quality tier caps the numbers:
305
+
306
+ | Tier | Cars | Pedestrians | Trains | Aircraft | Full-model cars | Activity radius |
307
+ |---|---|---|---|---|---|---|
308
+ | Minimum | 24 | 8 | 0 | 0 | 2 | 250 m |
309
+ | Low | 48 | 16 | 0 | 1 | 4 | 350 m |
310
+ | Medium | 96 | 32 | 1 | 1 | 6 | 450 m |
311
+ | Balanced | 160 | 48 | 1 | 2 | 8 | 600 m |
312
+ | High | 240 | 80 | 2 | 3 | 12 | 800 m |
313
+ | Ultra | 320 | 120 | 2 | 4 | 16 | 1000 m |
314
+
315
+ Ambient cars share the view's vehicle world, so the car you drive stops against them and traffic
316
+ waits for you. They follow the rendered ground and bridge decks, and they rebuild when the view
317
+ re-anchors after a long trip.
318
+
319
+ ## NPC content and `ambientRole`
320
+
321
+ An entity type joins the ambient pools with an `ambientRole`:
322
+
323
+ ```json
324
+ {
325
+ "format": "molen/types@1",
326
+ "namespace": "my.pack",
327
+ "types": {
328
+ "my.pack.transit.tram": {
329
+ "components": {
330
+ "transform": { "pos": [0, 0, 0], "rot": [0, 0, 0, 1] },
331
+ "renderable": { "kind": "gltf", "ref": "my.pack.transit.tram" },
332
+ "ambientRole": {
333
+ "role": "rail",
334
+ "length": 30,
335
+ "width": 2.65,
336
+ "height": 3.6,
337
+ "cruise": 14,
338
+ "cars": 3,
339
+ "colors": ["#c8102e"],
340
+ "visual": { "paintMaterial": "tram-livery" }
341
+ }
342
+ }
343
+ }
344
+ }
345
+ }
346
+ ```
347
+
348
+ `role` is `car`, `bus` (drives with cars), `rail` or `aircraft`. A type with a `vehicle`
349
+ component takes its dimensions and wheels from the vehicle spec, so its role can be as short as
350
+ `{ "role": "car" }`. Other types give `length`, `width` and `height`, and `visual` names their
351
+ wheel, paint, rotor and landing-gear nodes. `weight` sets how often a type spawns within its pool,
352
+ and `cars` how many cars a train has.
353
+
354
+ The `molen.entities` pack gives roles to its five cars, a city bus, a light-rail car, an airliner
355
+ and the P-51 and OH-6 aircraft. See [Reusable entities](entities.md). Near the camera the Earth
356
+ view draws those cars and trains with their full models, painted in the agent's colour. Further
357
+ out, and without content, every vehicle is a proxy shape built from its dimensions.
358
+
359
+ ## Determinism and cost
360
+
361
+ Agent state lives in components: lane, distance along it, speed, and the seed behind every choice.
362
+ It is hashed, keyframed and replayed like the rest of the world. The network itself is derived
363
+ data outside the state hash, so a restored world needs the same network added back. Occupancy,
364
+ junction grants and signal phases are recomputed from components each tick, and a signal's colour
365
+ is a pure function of the junction and the tick.
366
+
367
+ `ambient.observer` and `ambient.policy` are commands, so replays reproduce where the ring was and
368
+ how busy it was. A host's `setBudget` caps are not recorded; hosts reapply them after a restore.
369
+
370
+ The simulation is kinematic: agents follow lanes instead of running the vehicle solver. On a
371
+ laptop, 300 cars, 60 pedestrians, four trains and four aircraft step in 1 to 2 ms per tick.
372
+ Building the lane graph for a dense downtown map tile takes about 10 ms, and the Earth view adds at
373
+ most one tile every 200 ms. In the engine repository,
374
+ `node packages/ambient/bench/agents.bench.mjs` measures both.
375
+
376
+ ## Limits
377
+
378
+ - Map data has no turn restrictions or speed limits. Speeds follow the road class, and lane
379
+ counts follow the width when OSM does not give them.
380
+ - Aircraft fly straight lines. They do not taxi, circle or land beyond the approach.
381
+ - Pedestrians keep to their lane and follow the walker ahead. They do not step around each other.
382
+ - Agents do not open doors, board, or park. A parked car in the Earth view is a separate entity.
383
+
384
+ ## Read next
385
+
386
+ - [Earth view](earth-view.md)
387
+ - [Figures: humans, bipeds and quadrupeds](figures.md)
388
+ - [Mountable vehicles and driving](vehicles.md)
389
+ - [Authoring a capability package](capability-authoring.md)
@@ -81,6 +81,11 @@ top-down-ortho / follow), wires the `input` block (bindings + `emit` rules: `pre
81
81
  to `client.command`, and keeps the renderer sized to the canvas (ortho framing refits on resize).
82
82
  It returns `{ client, input, dispose }`.
83
83
 
84
+ Capability packages that draw their own entities add renderable kinds on the page and their
85
+ kernel half in the worker's `capabilities`. People are `kinds: [figureKind()]` from
86
+ [figures](figures.md), and background traffic is `ambientVehicleKind()` from
87
+ [ambient life](ambient-life.md).
88
+
84
89
  The call is asynchronous because it picks a graphics backend: `backend` defaults to `'auto'`,
85
90
  which probes WebGPU and falls back to the existing Three.js WebGL renderer, so this page gets
86
91
  WebGPU wherever the browser has it. Pass `backend: 'webgl'` to skip the probe — pinning a
@@ -51,6 +51,11 @@ templates:
51
51
  Tooling wires the built-in capabilities in `prepareSceneBuilder`; your own host does the same
52
52
  with `buildWorld(manifest, setup, { scriptExtensions: { mine: myScriptApi(handle) } })`.
53
53
 
54
+ A capability that a scene opts into through its own manifest block is a `capabilities` hook,
55
+ `(world, manifest) => ({ mine: api })`, that returns `undefined` when the block is absent, so
56
+ scenes without it pay nothing. `ambientCapability()` from `@bendyline/molen-ambient/kernel`
57
+ is one: it reads the scene's `ambient` block (see [ambient life](ambient-life.md)).
58
+
54
59
  7. **Ground and reads.** A capability that owns a height source registers it with
55
60
  `installTerrain(world, field)` (any object with `sampleHeight` + `normalAt`) so the character
56
61
  controller and kinematics find it. Component reads are frozen stored objects: compare
@@ -47,6 +47,7 @@ subsystem's contribution to the state hash reproduces.
47
47
  | Quaternion helpers that use angles — `quatSlerp`, `lookRotation`, `quatFromYaw`, `quatFromEuler`, `yawOf` | Same JS engine | `kernel/src/math3d.ts` routes these through `dmath.sin/cos/acos/atan2`, and `dmath` is currently a thin re-export of native `Math` |
48
48
  | Vehicles and aircraft | Same JS engine | `kernel/src/vehicles.ts` and `aircraft.ts` use `dmath.sin/cos/tan/atan2/exp` |
49
49
  | Figures (`@bendyline/molen-figures/kernel`) | Same JS engine | its locomotion system writes `figureState` and `transform.rot` into the world and registers a `figures` snapshot provider, so it **is** hashed; it reaches `dmath.atan2` and `quatFromYaw`, and `gait.ts` reaches `dmath.pow`/`sin`/`cos` |
50
+ | Ambient life (`@bendyline/molen-ambient/kernel`) | Same JS engine | agent state (`ambientAgent`, the `$ambient` bookkeeping entity) and transforms are written into the world, so it **is** hashed; occupancy, junction grants and signal phases are rebuilt from components every tick, so a keyframe restores exactly into a world whose transport network was built from the same inputs. It reaches `dmath.acos/sin/cos` and `lookRotation`. The network itself is a `WeakMap` side channel like worldgen's |
50
51
  | `physics.engine: "rapier"` (3D rigid bodies) | Same build + platform | `@dimforge/rapier3d-compat` WASM; the plugin hashes an opaque `takeSnapshot()` blob plus its id→handle maps |
51
52
  | Worldgen geometry and prop placement | Not hashed | `installWorldgen` registers the index on a `WeakMap` side channel with no snapshot provider; a test asserts installing it leaves `stateHash` unchanged. Its own content hashes (`hashWorldgenOutput`) are **same JS engine**: its kernel half calls `Math.hypot` in ~33 places, which `dmath.hypot` deliberately avoids because `Math.hypot`'s intermediate scaling is engine-defined |
52
53
  | Terrain **streaming, projection, surface rendering** | Not hashed | outside `check-dmath`'s two guarded files on purpose; `geospatial.ts` reaches `Math.cos/log/tan/atan/exp` |
@@ -93,9 +94,11 @@ The script Compartment enforces the first three. The rest are yours to keep.
93
94
  and its hash.
94
95
  - **Kernel and capability code uses `dmath`, never transcendental `Math.*`.** `scripts/check-dmath.mjs`
95
96
  enforces it. It takes explicit roots, so coverage is per-package and deliberate: `kernel` guards
96
- all of `src`; `figures`, `worldgen` and `worldgen-earth` guard `src/kernel`; `terrain` guards
97
- exactly `src/heightfield.ts` and `src/gen.ts`, because a `Heightfield` is the kernel's structural
98
- `GroundField` and the rest of that package is projection and streaming. The lint is lexical — it
97
+ all of `src`; `figures`, `ambient`, `worldgen` and `worldgen-earth` guard `src/kernel`; `terrain`
98
+ guards `src/heightfield.ts` and `src/gen.ts`, because a `Heightfield` is the kernel's structural
99
+ `GroundField`, plus the three-free line-path, transport-feature, bridge-profile and
100
+ rendered-ground modules the ambient transport graph builds on. The rest of that package is
101
+ projection and streaming. The lint is lexical — it
99
102
  cannot see a transcendental reached through an import, which is why
100
103
  `worldgen-earth` carries its own `dmath`-based `projection.ts` instead of importing terrain's.
101
104
  - **Systems never read a content library at tick time.** Entity types, landmark models and
@@ -132,10 +135,10 @@ Two constants live in `packages/kernel/src/version.ts` and they do different job
132
135
 
133
136
  | Constant | Today | Role |
134
137
  |---|---|---|
135
- | `ENGINE_VERSION` | `0.0.3` | metadata. Written into a keyframe's `engine` field so a save says which build wrote it. **Never compared on load, never hashed.** |
138
+ | `ENGINE_VERSION` | `0.0.4` | metadata. Written into a keyframe's `engine` field so a save says which build wrote it. **Never compared on load, never hashed.** |
136
139
  | `STATE_FORMAT` | `1` | the gate. Written into a keyframe under the reserved `plugins.$format` key, compared by `applyKeyframeTo`, and folded into `stateHash` as `stateFormat`. |
137
140
 
138
- So a release — even one that moves every package on the fixed version line — keeps your keyframes
141
+ So a release — even one that moves every package — keeps your keyframes
139
142
  loadable and your recorded `*.replay.json` fixtures valid, as long as it did not change simulation
140
143
  semantics or the snapshot layout. `STATE_FORMAT` is bumped only when it did. A keyframe written
141
144
  before the key existed is read as format 1, the layout in use when it was introduced.
@@ -248,14 +251,18 @@ two snapshots, including continuation differences under the reserved `$world` ps
248
251
  `molen sim watch scene.json --ticks N` reruns on every file change and reports hash flips, event
249
252
  deltas and assertion transitions.
250
253
 
251
- **Golden images** are a different mechanism with a different guarantee. `compareGolden` from
252
- `@bendyline/molen-tooling` compares a render (from `molen shot`, or `screenshotScene` in a test)
253
- against a committed PNG with a perceptual tolerance (per-pixel threshold 0.1, at most 0.3%
254
- differing pixels by default). A missing golden **fails** rather than adopting the candidate.
255
- Record with `UPDATE_GOLDENS=1`. The engine's own golden suites (`pnpm -r test:golden` in the
256
- engine repository) render in a pinned headless Chromium on a software rasterizer, and their
257
- authoritative refresh is the `update-goldens` workflow, which records on the same Ubuntu 24.04
258
- runner as the CI golden job. Record your own goldens on one pinned machine for the same reason.
254
+ **Render tests** are a different mechanism with a different guarantee. A render (from
255
+ `molen shot`, or `screenshotScene` in a test) is deterministic for one Chromium build on one
256
+ machine, so the engine's own render suites (`pnpm -r test:golden` in the engine repository)
257
+ compare no committed reference images. They check what holds on any machine: the same input
258
+ renders the same frame twice (`diffImages` with a zero tolerance), a different input renders a
259
+ different frame, and `frameStats` from `@bendyline/molen-tooling` measures a frame or a region of
260
+ it — coverage against the backdrop, distinct colors, mean color — so a test can say the model
261
+ covers the middle of the view or the sky is above the island. `compareGolden` remains for a test
262
+ that needs a reference image: it compares against a committed PNG with a perceptual tolerance
263
+ (per-pixel threshold 0.1, at most 0.3% differing pixels by default), fails when the reference is
264
+ missing rather than adopting the candidate, and records with `UPDATE_GOLDENS=1`. Record and
265
+ compare on the same pinned machine.
259
266
 
260
267
  ## What is not promised
261
268
 
@@ -263,8 +270,9 @@ Read this list before you build something that depends on a guarantee it does no
263
270
 
264
271
  - **Golden images are deterministic per build, not across machines.** The software rasterizer
265
272
  agrees with itself for a given Chromium build; it does not agree across Chromium versions or
266
- operating systems. That is why goldens are recorded in one pinned container and compared with a
267
- tolerance, and why DOM text overlays are kept out of captured frames.
273
+ operating systems. That is why the engine's render tests compare a frame with itself and
274
+ measure it rather than matching a committed reference, and why DOM text overlays are kept out
275
+ of captured frames.
268
276
  - **Rapier is not cross-platform.** Same build, same platform. Measured run-to-run in its own
269
277
  tests; not claimed beyond that.
270
278
  - **Transcendentals are not proven across JS engines.** `dmath` exists so that the swap to
@@ -272,7 +280,7 @@ Read this list before you build something that depends on a guarantee it does no
272
280
  native `Math`, so every "same JS engine" row above stays same-JS-engine until that swap happens.
273
281
  Routing through `dmath` buys you the swap point, not the result.
274
282
  - **There is no cross-JS-engine CI.** Every environment Molen tests in — Node, headless Chromium,
275
- the browser goldens, the materials cross-environment test — runs V8. No claim in this repo has
283
+ the browser render tests, the materials cross-environment test — runs V8. No claim in this repo has
276
284
  been checked against JavaScriptCore or SpiderMonkey.
277
285
  - **Worldgen's content hashes are same-engine.** They are cache keys and regression signals, and
278
286
  its kernel half reaches `Math.hypot`, whose intermediate scaling is engine-defined.