@bendyline/molen-tooling 0.0.2 → 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 (86) hide show
  1. package/README.md +4 -4
  2. package/dist/capture/harness.js +222 -222
  3. package/dist/capture/worldgen-preview.js +288 -288
  4. package/dist/cli.mjs +162 -10
  5. package/dist/docs-src/guide/3d-model-assets.md +35 -3
  6. package/dist/docs-src/guide/adaptive-performance.md +4 -0
  7. package/dist/docs-src/guide/agent-loop.md +6 -6
  8. package/dist/docs-src/guide/aircraft.md +28 -7
  9. package/dist/docs-src/guide/ambient-life.md +389 -0
  10. package/dist/docs-src/guide/audio.md +247 -0
  11. package/dist/docs-src/guide/browser-mount.md +8 -1
  12. package/dist/docs-src/guide/building-interiors.md +5 -4
  13. package/dist/docs-src/guide/capability-authoring.md +5 -0
  14. package/dist/docs-src/guide/determinism.md +35 -27
  15. package/dist/docs-src/guide/earth-view.md +492 -0
  16. package/dist/docs-src/guide/entities.md +9 -1
  17. package/dist/docs-src/guide/examples.md +6 -2
  18. package/dist/docs-src/guide/figures.md +3 -0
  19. package/dist/docs-src/guide/game-samples.md +22 -5
  20. package/dist/docs-src/guide/graphics-performance.md +40 -8
  21. package/dist/docs-src/guide/input.md +9 -0
  22. package/dist/docs-src/guide/markers.md +55 -0
  23. package/dist/docs-src/guide/materials.md +10 -3
  24. package/dist/docs-src/guide/navigation.md +150 -0
  25. package/dist/docs-src/guide/project.md +1 -1
  26. package/dist/docs-src/guide/quickstart.md +2 -2
  27. package/dist/docs-src/guide/recognizable-places.md +3 -2
  28. package/dist/docs-src/guide/scripting.md +4 -2
  29. package/dist/docs-src/guide/sky.md +16 -0
  30. package/dist/docs-src/guide/source-bundles.md +0 -1
  31. package/dist/docs-src/guide/structure-library.md +2 -2
  32. package/dist/docs-src/guide/surface-rendering.md +4 -3
  33. package/dist/docs-src/guide/terrain.md +52 -2
  34. package/dist/docs-src/guide/vehicles.md +32 -10
  35. package/dist/docs-src/guide/worldgen.md +3 -3
  36. package/dist/docs-src/llms.txt +14 -5
  37. package/dist/docs-src/schemas/README.md +4 -0
  38. package/dist/docs-src/schemas/archive-set.md +175 -0
  39. package/dist/docs-src/schemas/components.md +1634 -2
  40. package/dist/docs-src/schemas/matgraph.md +6 -0
  41. package/dist/docs-src/schemas/scene.md +105 -0
  42. package/dist/docs-src/schemas/soundbank.md +251 -0
  43. package/dist/docs-src/schemas/structure-placements.md +496 -0
  44. package/dist/docs-src/schemas/terrain-package.md +120 -0
  45. package/dist/docs-src/schemas/transport-network.md +351 -0
  46. package/dist/index.d.mts +49 -2
  47. package/dist/index.mjs +81 -4
  48. package/dist/{mcp-AOfIp89b.mjs → mcp-BtuworIW.mjs} +88 -3
  49. package/dist/{ops-C4BvDgP-.mjs → ops-DMGcWoL2.mjs} +1204 -93
  50. package/dist/templates/city-courier/README.md +14 -1
  51. package/dist/templates/city-courier/delivery-run.replay.json +151 -151
  52. package/dist/templates/city-courier/gen/molen-types.ts +223 -5
  53. package/dist/templates/city-courier/package.json +2 -0
  54. package/dist/templates/city-courier/scene.json +142 -246
  55. package/dist/templates/city-courier/scripts/game.ts +7 -15
  56. package/dist/templates/city-courier/scripts/molen-scripts.d.ts +252 -16
  57. package/dist/templates/city-courier/src/audio.ts +96 -0
  58. package/dist/templates/city-courier/src/game-shell.css +8 -0
  59. package/dist/templates/city-courier/src/main.ts +3 -0
  60. package/dist/templates/city-courier/src/worker.ts +3 -1
  61. package/dist/templates/city-courier/test/headless.test.ts +3 -2
  62. package/dist/templates/data-viz/README.md +1 -1
  63. package/dist/templates/index.json +22 -1
  64. package/dist/templates/skybound/README.md +13 -0
  65. package/dist/templates/skybound/first-leap.replay.json +152 -152
  66. package/dist/templates/skybound/gen/molen-types.ts +223 -5
  67. package/dist/templates/skybound/package.json +1 -0
  68. package/dist/templates/skybound/scene.json +40 -0
  69. package/dist/templates/skybound/scripts/game.ts +8 -5
  70. package/dist/templates/skybound/scripts/molen-scripts.d.ts +248 -5
  71. package/dist/templates/skybound/src/audio.ts +96 -0
  72. package/dist/templates/skybound/src/game-shell.css +8 -0
  73. package/dist/templates/skybound/src/main.ts +3 -0
  74. package/dist/templates/skybound/test/headless.test.ts +1 -1
  75. package/dist/templates/terrain-flyover/README.md +2 -2
  76. package/dist/templates/top-down-arena/README.md +15 -2
  77. package/dist/templates/top-down-arena/arena-skirmish.replay.json +152 -152
  78. package/dist/templates/top-down-arena/package.json +1 -0
  79. package/dist/templates/top-down-arena/scene.json +20 -0
  80. package/dist/templates/top-down-arena/scripts/combat.ts +1 -0
  81. package/dist/templates/top-down-arena/scripts/molen-scripts.d.ts +248 -5
  82. package/dist/templates/top-down-arena/src/audio.ts +96 -0
  83. package/dist/templates/top-down-arena/src/gen/molen-types.ts +223 -5
  84. package/dist/templates/top-down-arena/src/main.ts +3 -0
  85. package/dist/templates/top-down-arena/test/headless.test.ts +1 -1
  86. package/package.json +13 -12
@@ -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)
@@ -0,0 +1,247 @@
1
+ # Sound and music
2
+
3
+ Sound in Molen is data. A sound bank names the clips, three components say when and where they
4
+ play, and scripts can fire one-shots with `molen.audio.play`. The client's audio director reads
5
+ all of it every frame and plays the result through Web Audio. Nothing about playback touches the
6
+ simulation, so sound never changes a state hash, and `molen audio plan` shows what a scene would
7
+ play without opening a browser.
8
+
9
+ ## The pieces
10
+
11
+ | Piece | Where it lives | What it does |
12
+ | --- | --- | --- |
13
+ | `molen/soundbank@1` | a content pack (`provides.soundbank`) or a file beside the scene | Sound ids → clip files, loop points, gain, pitch range, bus, spatial defaults and provenance |
14
+ | `audioEnvironment` | one entity in the scene | Ambience layers, music playlist, event → sound mappings, footsteps, bus gains |
15
+ | `audioSource` | any entity | An emitter: loops follow the entity, pitch and gain follow signals, one-shots fire on triggers |
16
+ | `audioZone` | any entity | Area ambience that fades in as the listener approaches a sphere or box |
17
+ | `molen.audio.*` | scene scripts | `play`, `stop` and `music`, emitted as `audio.*` events |
18
+ | `@bendyline/molen-client/audio` | the page | `createAudioLayer` loads banks and plays what the rules ask for |
19
+
20
+ The `molen.sounds` content pack carries 63 CC0 sounds (ambience, vehicles, footsteps, impacts,
21
+ foley, UI, stings and six music tracks). Fetch it into a project with:
22
+
23
+ ```sh
24
+ npx molen pack fetch https://molen.dev/packs/index.json molen.sounds --out-dir public/packs
25
+ ```
26
+
27
+ That writes `public/packs/index.json` and pins the pack in `project.json`, so CLI ops such as
28
+ `molen audio plan` find the bank without flags.
29
+
30
+ ## Annotate a scene
31
+
32
+ Add one entity with an `audioEnvironment`. This one plays rain while it rains, birds on sunny
33
+ days, music throughout, and a crash sound on the `crash` event your script emits:
34
+
35
+ ```json
36
+ {
37
+ "id": "audio",
38
+ "components": {
39
+ "audioEnvironment": {
40
+ "buses": { "music": 0.5 },
41
+ "ambience": [
42
+ {
43
+ "sound": "ambience.rain",
44
+ "when": { "weather.precipitation.kind": "rain" },
45
+ "gainFrom": { "signal": "weather.precipitation.intensity", "curve": [[0, 0], [1, 1]] }
46
+ },
47
+ { "sound": "ambience.birds", "when": { "sky.daylight": { "min": 0.35 } }, "fadeS": 4 }
48
+ ],
49
+ "music": { "playlist": ["music.ambient.first-light", "music.ambient.lifewave"], "mode": "shuffle" },
50
+ "events": { "crash": { "sound": "impact.metal.heavy" } }
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ Give a moving thing its own voice with `audioSource`. The engine below follows the car, and its
57
+ pitch and loudness follow the car's state:
58
+
59
+ ```json
60
+ {
61
+ "id": "player",
62
+ "components": {
63
+ "transform": { "pos": [0, 0.5, 0] },
64
+ "audioSource": {
65
+ "sound": "vehicle.engine.car",
66
+ "pitchFrom": { "signal": "vehicleState.speed", "curve": [[0, 0.8], [30, 1.7]] },
67
+ "gainFrom": { "signal": "vehicleInput.throttle", "curve": [[0, 0.5], [1, 1]] }
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ Put the `audioSource` on an entity type and every instance gets it. The `molen.entities` vehicles
74
+ and aircraft carry their engines this way: cars run `vehicle.engine.car` or
75
+ `vehicle.engine.diesel` only while someone drives them (`"when": { "self.occupied": true }`), with
76
+ pitch from `vehicleState.speed` and gain from `vehicleInput.throttle`. The P-51 (a Merlin) and the
77
+ OH-6 take pitch and gain from `aircraftState.rpm`, so they are silent until the engine starts and
78
+ spool up and down with it. A loop whose gain is zero holds no voice.
79
+
80
+ Fire one-shots from a script when something happens that no component describes:
81
+
82
+ ```ts
83
+ molen.onCommand('attack', () => {
84
+ molen.audio.play('weapon.slash');
85
+ });
86
+ if (delivered === total) molen.audio.play('sting.win');
87
+ const alarm = molen.audio.play('ui.error', { entity: 'door', loop: true });
88
+ molen.audio.stop(alarm, 0.5);
89
+ molen.audio.music('music.dungeon');
90
+ ```
91
+
92
+ `molen.emit` works too: any event type listed under `audioEnvironment.events` plays its sound, at
93
+ the entity or position the payload names (`payload.entity`, `payload.position`, or `payload.a` for
94
+ collisions), or at the listener.
95
+
96
+ ## Rules
97
+
98
+ Every rule is a small piece of data the director re-evaluates each frame.
99
+
100
+ | Field | Meaning |
101
+ | --- | --- |
102
+ | `when` | All conditions must hold. A value means equality, a list means any of, `{ "min", "max" }` is an inclusive range, `{ "exists": true }` tests presence |
103
+ | `gainFrom`, `pitchFrom` | `{ signal, curve, smoothS? }`: a piecewise-linear curve of `[input, output]` points, clamped at both ends. A list of them multiplies, so a sound can fade with height and with distance at once |
104
+ | `triggerFrom` | `{ signal, every?, onChange?, sound? }`: a one-shot each time the signal advances by `every` (footsteps by distance) or changes |
105
+ | `startTick` | Play once at that tick; changing it plays again |
106
+ | `fadeS` | Fade time for ambience layers (default 1.5 s) |
107
+
108
+ Sounds that come from the ground, such as birds in the trees or traffic on the roads, should get
109
+ quieter as the listener rises. List one curve for height and another for distance to the source:
110
+
111
+ ```json
112
+ {
113
+ "sound": "ambience.city.traffic",
114
+ "gainFrom": [
115
+ { "signal": "listener.heightAboveGround", "curve": [[3, 1], [30, 0.7], [100, 0.3], [300, 0.08], [500, 0]] },
116
+ { "signal": "host.streetDistance", "curve": [[0, 1], [40, 0.55], [120, 0.2], [250, 0]] }
117
+ ]
118
+ }
119
+ ```
120
+
121
+ A layer turns on after its condition has held for 0.25 s and off after it has failed for 1 s, and
122
+ numeric ranges widen by 5% while a layer plays. A signal hovering at a threshold therefore never
123
+ makes a sound flicker.
124
+
125
+ ## Signals
126
+
127
+ | Signal | Value |
128
+ | --- | --- |
129
+ | `<component>.<field>` | A field of a component on the source's entity, e.g. `vehicleState.speed`, `aircraftState.rpm`, `transform.pos.1`. In `audioEnvironment` rules it reads the `listenerEntity` |
130
+ | `self.speed`, `self.distance`, `self.x/y/z` | The source entity's measured speed (m/s), distance travelled (m) and position |
131
+ | `self.occupied` | true while someone rides the source entity (an entity's `mounted` component names it) |
132
+ | `listener.speed`, `listener.distance`, `listener.x/y/z`, `listener.altitude` | The listener's speed, odometer and position |
133
+ | `listener.heightAboveGround` | What the host reports as the listener's height above the terrain (m); 0 when it reports nothing |
134
+ | `listener.mode`, `listener.grounded`, `listener.surface`, `listener.indoors` | What the host reports: walk, drive, fly, pilot or orbit; on the ground; the surface underfoot; inside a building |
135
+ | `weather.precipitation.kind`, `weather.precipitation.intensity`, `weather.windSpeed`, `weather.visibility`, `weather.clouds.coverage` | The scene's weather; a scene without weather reads as clear and calm |
136
+ | `sky.daylight`, `sky.starVisibility`, `sky.sunElevation` | The sky; a scene without a sky reads as day |
137
+ | `time.seconds` | Seconds since the audio layer started |
138
+ | `host.<name>` | Anything the page passes in, e.g. `host.urban` |
139
+
140
+ An unknown built-in signal is reported with a did-you-mean suggestion by `molen audio plan` and
141
+ in the browser console.
142
+
143
+ ## Check it headlessly
144
+
145
+ `molen audio plan` runs the scene for N ticks, feeds the director, and prints what would play:
146
+
147
+ ```sh
148
+ npx molen audio plan scene.json --ticks 300 --commands commands.json
149
+ ```
150
+
151
+ ```text
152
+ 300 ticks at 30 Hz, banks: molen.sounds@1.0.0:sounds.soundbank.json
153
+ loops:
154
+ [0 → end] music.racing bus music peak 0.80 pitch 1.00
155
+ [0 → end] vehicle.engine.car @player bus sfx peak 0.61 pitch 0.75–1.36
156
+ one-shots (1):
157
+ t=115 impact.metal.heavy (sfx)
158
+ ```
159
+
160
+ It reports unknown sound ids with a suggestion, and exits non-zero when it finds one. Pass
161
+ `--weather rain`, `--daylight 0.1`, `--mode walk` or `--listener <entity>` to hear other
162
+ conditions. `--json` prints the full report, and the `plan_audio` MCP tool returns the same.
163
+ Script sounds are ordinary events, so assertions work on them too:
164
+
165
+ ```json
166
+ { "format": "molen/assert@1", "assertions": [{ "event": "audio.play", "op": "occurred" }] }
167
+ ```
168
+
169
+ ## Play it in the browser
170
+
171
+ A page with a Worker kernel creates one layer, attaches it to the client, and updates it each
172
+ frame. Sound starts on the first click or key press, as browsers require.
173
+
174
+ ```ts
175
+ import { mountExperience } from '@bendyline/molen-client';
176
+ import {
177
+ attachAutoplayUnlock,
178
+ createAudioLayer,
179
+ loadPackSoundbanks,
180
+ } from '@bendyline/molen-client/audio';
181
+ import { createPackSet, openPack } from '@bendyline/molen-pack';
182
+
183
+ const { client } = await mountExperience({ link: worker, scene, canvas });
184
+ const index = await (await fetch('packs/index.json')).json();
185
+ const entry = index.packs['molen.sounds'];
186
+ const packs = createPackSet([await openPack(new URL(entry.file, new URL('packs/', location.href)).href)]);
187
+ const audio = createAudioLayer({
188
+ banks: await loadPackSoundbanks(packs),
189
+ provider: packs.assetProvider(),
190
+ renderer: client.renderer, // the camera is the listener; weather and sky come from here too
191
+ });
192
+ audio.attachClient(client);
193
+ attachAutoplayUnlock(audio);
194
+ requestAnimationFrame(function frame(now) {
195
+ audio.update(now);
196
+ requestAnimationFrame(frame);
197
+ });
198
+ ```
199
+
200
+ Every game sample does exactly this in its `src/audio.ts`. Hosts without a Worker kernel use
201
+ `audio.attachWorld(world)` for a main-thread `World`, or no source at all and pass the listener to
202
+ `update(now, { position, forward, mode, grounded, heightAboveGround })`. `setVolume`, `setMuted` and
203
+ `setBusGain('music', 0)` drive a settings menu.
204
+
205
+ `mountEarthView` plays the Earth soundscape on its own when its content includes the
206
+ `molen.sounds` pack: weather and time-of-day ambience, footsteps in walk mode, traffic near
207
+ streets, and engines on the cars and aircraft you board. Birds, crickets and traffic fade with
208
+ height above the terrain, and traffic also fades with distance from the nearest street. Pass `audio: false` to turn it off, and
209
+ use `view.audio` for volume. See [Earth view](earth-view.md).
210
+
211
+ ## Make your own sounds
212
+
213
+ A sound bank is a JSON file beside its clips. Add clips with `molen audio import`, which copies the
214
+ file, hashes it, reads its duration, and records where it came from:
215
+
216
+ ```sh
217
+ npx molen audio import rain.mp3 --id ambience.rain --bank sounds/sounds.soundbank.json \
218
+ --license CC0-1.0 --source https://freesound.org/s/000000/ --loop \
219
+ --description "Steady rain on leaves"
220
+ npx molen audio import step-2.mp3 --id footstep.wood --bank sounds/sounds.soundbank.json \
221
+ --license CC0-1.0 --append
222
+ npx molen audio check sounds/sounds.soundbank.json
223
+ ```
224
+
225
+ A bank with a later position in `banks` overrides sounds with the same id, so a project can
226
+ re-skin `molen.sounds` by shipping only the sounds it changes. Every entry records its license.
227
+ A bank with `"license": "CC0-1.0"` rejects anything else, which is how `molen.sounds` stays public
228
+ domain.
229
+
230
+ > [!TIP]
231
+ > MP3 plays in every browser. Ogg Vorbis does not decode in older Safari. Keep one-shots mono so
232
+ > they pan cleanly, and set `loopStart`/`loopEnd` a few milliseconds inside a loop so encoder
233
+ > padding never plays.
234
+
235
+ Good places to find sounds:
236
+
237
+ - **[Freesound](https://freesound.org)** — the largest library; filter to Creative Commons 0.
238
+ - **[Kenney](https://kenney.nl/assets/category:Audio)** — CC0 packs of UI, impacts, footsteps and
239
+ jingles.
240
+ - **[OpenGameArt](https://opengameart.org/art-search-advanced)** — filter by license, then check
241
+ each page, since many items are CC-BY or GPL.
242
+ - **Generated clips** (ElevenLabs sound effects, Stable Audio Open) — record the prompt and the
243
+ generator in the entry's `source`, and check the service's terms for your use.
244
+
245
+ CC-BY sounds and music (Kevin MacLeod's, for example) are fine in your own bank if you show the
246
+ credit they require. Avoid the BBC Sound Effects archive (non-commercial licence) and libraries
247
+ that forbid redistribution.
@@ -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
@@ -101,7 +106,9 @@ and every sample template already carry the setting.
101
106
 
102
107
  ## Feedback from the simulation
103
108
 
104
- The client exposes what a HUD, sound, or win screen needs — no wire-protocol parsing:
109
+ The client exposes what a HUD, sound, or win screen needs — no wire-protocol parsing. For sound,
110
+ `createAudioLayer(...).attachClient(client)` from `@bendyline/molen-client/audio` plays a scene's
111
+ audio rules and `molen.audio.*` events; see [Sound and music](audio.md).
105
112
 
106
113
  ```ts
107
114
  client.onEvent('collision', (e, tick) => flash());
@@ -1,9 +1,10 @@
1
1
  # Inferred building interiors
2
2
 
3
- World explorer enables lazy interiors in the styled **Human** layer. Choose
4
- **Walk**, approach a building, and walk through its framed entrance. Near the entrance, the
5
- windows become transparent and reveal the same interior you can enter. `?interiors=0`
6
- disables this capability. `?synthetic=1&stores=1` provides a repeatable block of recognizable
3
+ World explorer enables lazy interiors in the styled **Human** layer: choose **Walk**, approach
4
+ a building, and walk through its framed entrance. Near the entrance, the windows become
5
+ transparent and reveal the same interior you can enter.
6
+
7
+ `?interiors=0` disables this capability. `?synthetic=1&stores=1` provides a repeatable block of recognizable
7
8
  stores; `test/visual/interiors.play.json` walks into and out of its fast-food restaurant and grocery store.
8
9
  Use `?synthetic=1&houses=1` for a residential block with two-storey houses and a bungalow.
9
10
  `test/visual/houses.play.json` walks through its entrance, climbs the stairs, and enters a bedroom.