@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
@@ -57,7 +57,7 @@ const viewer = await createViewer({
57
57
  maxMilliseconds: 2, // explicit low-latency budget; WebGPU default is 8
58
58
  maxBytes: 2 * 1024 * 1024,
59
59
  maxJobs: 32,
60
- onSample(sample) { /* label, workMs, queueMs, bytes, overBudget */ },
60
+ onSample(sample) { /* label, workMs, queueMs, bytes, overBudget, background */ },
61
61
  },
62
62
  });
63
63
  ```
@@ -66,19 +66,25 @@ The queue limits synchronous work started per animation frame. One oversized ind
66
66
  runs alone and is reported as over budget. This is not a hard GPU/driver time bound. Texture
67
67
  initialization, geometry preparation and async shader compilation use public Three facilities;
68
68
  shared resources share pending preparation promises. A cancelled tile cannot cancel another
69
- tile waiting on the same resource. Prepared static batches replace ordinary meshes only when
70
- ready; stale batch results are discarded.
69
+ tile waiting on the same resource; queued work is dropped once every tile waiting for it has
70
+ cancelled. Prepared static batches replace ordinary meshes only when ready; stale batch results
71
+ are discarded.
71
72
  Instanced LOD meshes each prepare their own WebGPU node builder even when every buffer is
72
- shared. Resident world-generation quality replacements use the same preparation/publication
73
- path when supplied with `WorldgenRendererOptions.prepareObject` (enabled in World Explorer).
73
+ shared. When `prepareObject` receives the parent the object will join, it evaluates LODs for
74
+ the current camera and waits only for the selected levels. The other levels prepare in the
75
+ queue's background lane (`priority: 'background'`), which runs only in budget that normal jobs
76
+ leave, and are dropped if their mesh or geometry is disposed first. Resident world-generation
77
+ quality replacements use the same preparation/publication path when supplied with
78
+ `WorldgenRendererOptions.prepareObject` (enabled in World Explorer).
74
79
 
75
- For custom streamed geometry, call `await renderer.prepareObject(object, signal)` before
76
- publication. Connect the same queue to terrain:
80
+ For custom streamed geometry, call `await renderer.prepareObject(object, signal, parent)` before
81
+ publication. Connect the same queue to terrain, which passes each layer's tile group as `parent`:
77
82
 
78
83
  ```ts
79
84
  const terrain = await createTerrainPackagePyramidStream(packageDescriptor, {
80
85
  admission: viewer.renderer.admission,
81
- prepareObject: (object, signal) => viewer.renderer.prepareObject(object, signal),
86
+ prepareObject: (object, signal, parent) =>
87
+ viewer.renderer.prepareObject(object, signal, parent),
82
88
  elevationWorker: new Worker(new URL('./elevation-worker.ts', import.meta.url), { type: 'module' }),
83
89
  onElevationTiming: sample => { /* decode, resample, mesh; milliseconds */ },
84
90
  });
@@ -99,6 +105,14 @@ return the synchronous baker's exact pixels through transferables. World Explore
99
105
  startup workers and releases them when its style pack is baked; `materialWorker=0` retains
100
106
  synchronous baking for comparisons. Its `material-bake` timing reports worker CPU time.
101
107
 
108
+ `withBakedMaterialStore(baker, store)` serves bakes from a persistent `BakedMaterialStore`, such as
109
+ `createIndexedDbMaterialStore()` from `@bendyline/molen-client`, so a later visit reads textures
110
+ instead of rasterizing them. Keys combine the document's content with a fingerprint of the
111
+ rasterizers (a tiny bake that exercises every node type), so a changed baker never serves stale
112
+ pixels and its old entries are pruned. Store failures fall back to baking. `createEarthWorldgen`
113
+ and `mountEarthView` accept the store as `materialStore`; World Explorer passes the IndexedDB store
114
+ unless `materialCache=0`.
115
+
102
116
  World-generation workers also prepare building spatial cells and full/structural LOD indices.
103
117
  The renderer requests `renderCellsOnly` when using cell LODs so it does not retain a redundant
104
118
  canonical building mesh. Per-cell Three object assembly is a separate queue job. Generation
@@ -152,6 +166,24 @@ semantic layers use coverage-preserving atomic replacement and hysteresis instea
152
166
  one finishes any surface morph before layer publication. Coarsening does not height-morph.
153
167
  World Explorer uses 180 ms for bare terrain; deterministic `freeze` captures disable morphing.
154
168
 
169
+ ## Collision neighborhoods
170
+
171
+ `WalkCollision` from `@bendyline/molen-client/navigation` gives walkers, driven cars and piloted
172
+ aircraft a triangle tree of the visible geometry around them. Two costs matter. The **scan** visits
173
+ every visible mesh under the root to notice streamed changes; it runs on `update` only when the
174
+ subject has left the neighborhood, when `rescanIntervalMs` has passed (the Earth hosts use 200 ms)
175
+ or after `invalidate()`. The **rebuild** transforms the nearby triangles into the tree; geometries
176
+ of 4096 triangles or more are walked through a per-geometry XZ index, built on first use and kept
177
+ with the geometry, so a terrain tile or building cell contributes only the triangles that can reach
178
+ the neighborhood instead of every triangle it holds.
179
+
180
+ A subject that moves tens of meters a second would otherwise recenter the tree every few frames.
181
+ Vehicles and aircraft use a wider `radius` with a larger `rebuildDistance`, and a `verticalRadius`
182
+ with `update(root, x, z, y)` so the ground far below an airframe never enters the tree; while it
183
+ flies high the tree is empty and rebuilds are free. World Explorer's aircraft use 48 m / 24 m / 40 m,
184
+ its cars 32 m / 12 m / 24 m; walkers keep the 24 m / 6 m default and the whole column, which their
185
+ placement ray needs. The kernel's own ground contact (`groundHeight`) does not depend on this tree.
186
+
155
187
  ## Measurement
156
188
 
157
189
  World Explorer enables elevation workers, shared admission and shader warmup by default.
@@ -35,6 +35,15 @@ A custom `getGamepads` callback can supply the same structural snapshots, so a h
35
35
  another facility, such as a device-specific WebHID integration, without changing profiles or UI.
36
36
  Molen does not itself request WebHID permission or implement device-specific HID reports.
37
37
 
38
+ ## Software controls
39
+
40
+ On-screen controls feed the same actions as physical devices. `input.setVirtual(source, action,
41
+ value)` sets a named control's contribution, for example a touch stick pushing `move-forward` to
42
+ 0.6, and `input.clearVirtual(source)` releases everything it drives. As with other devices, the
43
+ strongest contribution to an action wins. Software values persist until changed, and a reset
44
+ (focus loss, suspension, profile switch) releases them. `createTouchJoystick` in
45
+ [`@bendyline/molen-client/navigation`](navigation.md) is a ready-made stick built on this.
46
+
38
47
  ## Define and switch profiles
39
48
 
40
49
  ```ts
@@ -0,0 +1,55 @@
1
+ # World markers
2
+
3
+ `@bendyline/molen-client/markers` draws screen-sized billboards pinned to world positions: photo
4
+ pins, labels you render to images, waypoints. A marker keeps a constant on-screen size. It sits on
5
+ the ground, re-snapping as finer terrain streams in, hides behind hills and buildings through the
6
+ depth test, and can fade with distance. With `declutter: true` a pin whose on-screen footprint
7
+ overlaps a more important one is hidden: higher `priority` first, then pins already on screen (so
8
+ they do not flicker as the camera moves), then the nearest. The Earth view declutters its markers. They ignore the scene's fog, so distance haze never washes a
9
+ pin into a blank card; the layer's own `fade` handles distance. Markers are budgeted so the nearest or most important ones
10
+ draw, and `pick(x, y)` resolves a click or tap to a marker id.
11
+
12
+ ```ts
13
+ import { composeMarkerImage, createMarkerLayer } from '@bendyline/molen-client/markers';
14
+ import { wgs84ToWorld } from '@bendyline/molen-terrain/kernel';
15
+
16
+ const markers = createMarkerLayer(viewer.renderer, {
17
+ groundHeight: (x, z) => stream.sampleHeight(x, z),
18
+ maxVisible: 200,
19
+ fade: { near: 15_000, far: 40_000 },
20
+ });
21
+
22
+ const photo = await createImageBitmap(await (await fetch(thumbnailUrl)).blob());
23
+ const [x, z] = wgs84ToWorld(metersPerUnit, longitude, latitude);
24
+ markers.set([
25
+ {
26
+ id: 'space-needle',
27
+ x,
28
+ z,
29
+ elevation: 2,
30
+ image: composeMarkerImage(photo, { borderColor: '#c4a265' }),
31
+ size: 64,
32
+ },
33
+ ]);
34
+
35
+ // each frame, after posing the camera:
36
+ markers.update(cameraPosition);
37
+
38
+ // on a tap (element-relative CSS pixels, e.g. NavigationInput.taps):
39
+ const id = markers.pick(tap.x, tap.y);
40
+ ```
41
+
42
+ - **Coordinates** are absolute world meters, the same ones you give `setCamera`. The layer lives
43
+ under `renderer.worldRoot`, so floating-origin rebasing moves it with everything else. Omit `y`
44
+ to sit on the ground (`groundHeight` + `elevation`). Ground-snapped markers stay hidden until
45
+ their ground height is known (`hideUntilGrounded`), so pins never jump from sea level.
46
+ - **Images** are canvases, bitmaps, image elements, or URLs. Markers that share an image share one
47
+ texture, and `set` matches markers by id, so re-calling it with the same list costs nothing.
48
+ `composeMarkerImage` cover-crops a photo into a rounded, bordered frame with a shadow and a
49
+ pointer tail. The canvas's bottom-center is the pin point, which suits the default
50
+ `anchor: 'bottom'`.
51
+ - **Budget:** `maxVisible` keeps the highest `priority`, then nearest, markers.
52
+ - `screenPosition(id)` places DOM callouts next to a marker. `projectWorldToScreen(renderer,
53
+ position)` projects any world point the same way.
54
+
55
+ The layer never fetches anything you did not pass it, and it adds no draw calls when it is empty.
@@ -39,7 +39,7 @@ every char is in the palette — with row/column pinpointed. Bake: `molen materi
39
39
 
40
40
  Author vector art and rasterize it deterministically (resvg, identical bytes in Node/browser/CI):
41
41
 
42
- ```
42
+ ```sh
43
43
  molen material bake badge.svg -o badge.png
44
44
  ```
45
45
 
@@ -83,10 +83,11 @@ evidence across environments rather than a proof across JS engines; see
83
83
  - Each node has an optional `input` (single upstream node) or `inputs` (named, e.g. blend's `b`).
84
84
  - `outputs` maps PBR slots (baseColor, roughness, metalness, normal, emissive, ao) to node ids.
85
85
  - Cycles are a validation error naming the path.
86
+ - Optional `alphaTest: 0.5` renders base-color RGBA alpha as cutout holes; ramps accept `#rrggbbaa`. Omitted graphs remain opaque. Cutouts write depth normally and do not use blended transparency.
86
87
 
87
88
  Bake and inspect:
88
89
 
89
- ```
90
+ ```sh
90
91
  molen material bake rock.matgraph.json -o rock.png
91
92
  ```
92
93
 
@@ -101,7 +102,7 @@ Full node vocabulary and per-field schema: [schemas/matgraph.md](../schemas/matg
101
102
  For textured models: a sidecar pairs a model with island annotations and a painted template, so a
102
103
  flat color/paint pass re-imports into the right UV islands (masked + gutter-dilated).
103
104
 
104
- ```
105
+ ```sh
105
106
  molen validate scout.uvpaint.json
106
107
  molen uvpaint apply scout-painted.png --islands scout-islands.png -o scout-tex.png
107
108
  # (same op over MCP: apply_uv_paint)
@@ -119,6 +120,12 @@ The client resolves materialRefs at load time:
119
120
  `MeshStandardMaterial`. Works in the live client and in `molen shot` (the capture server
120
121
  serves the doc). A bad ref falls back to grey with a warning — it never blanks the scene.
121
122
 
123
+ The client stores a constant roughness or metalness channel as an exact numeric factor
124
+ instead of allocating a map. It checks the sampled channel (roughness G, metalness B),
125
+ preserves its quantized `byte / 255` value and multiplies the existing factor. Other channels
126
+ keep their textures. A rendered material may therefore have a null `roughnessMap` or
127
+ `metalnessMap` even when the baked document contains that channel.
128
+
122
129
  `molen material bake` (or `rasterize_material`) still bakes to PNG when you want a static
123
130
  texture asset or a golden comparison. SVG (rung 3) runs anywhere once `initSvg` has its WASM;
124
131
  Node is simply the environment that finds it automatically.
@@ -0,0 +1,150 @@
1
+ # Camera navigation
2
+
3
+ `@bendyline/molen-client/navigation` moves a camera through a world you render yourself with
4
+ `createViewer`: an orbit camera for map-style views, free flight, first-person walking with
5
+ collision against whatever geometry you stream, and a chase camera for vehicles or avatars. Input
6
+ comes from one model that spans keyboard, gamepad, mouse and touch gestures, and an on-screen
7
+ stick. Nothing here attaches to `window`; every listener goes on the element you pass, so the
8
+ controls embed cleanly in a larger page.
9
+
10
+ Controllers are plain objects. Each frame you read an input, call `update(dt, input, environment)`
11
+ and render the returned pose:
12
+
13
+ ```ts
14
+ import { createViewer } from '@bendyline/molen-client';
15
+ import { NavigationInputSource, OrbitController } from '@bendyline/molen-client/navigation';
16
+
17
+ canvas.tabIndex = 0; // key events arrive once the canvas has focus; presses focus it
18
+ const viewer = await createViewer({ canvas, cameraFar: 500_000 });
19
+ const input = new NavigationInputSource({ element: canvas, profile: 'orbit' });
20
+ const orbit = new OrbitController({ target: [0, 0, 0], range: 3000, heading: 0, pitch: 0.6 });
21
+ const environment = { groundHeight: (x: number, z: number) => stream.sampleHeight(x, z) };
22
+
23
+ let last = performance.now();
24
+ function frame(now: number) {
25
+ const dt = (now - last) / 1000;
26
+ last = now;
27
+ const pose = orbit.update(dt, input.read(dt), environment);
28
+ stream.update({ position: pose.position, direction: pose.direction, verticalFov, viewportHeight });
29
+ viewer.setCamera({ position: pose.position, lookAt: pose.lookAt });
30
+ viewer.renderFrame();
31
+ requestAnimationFrame(frame);
32
+ }
33
+ requestAnimationFrame(frame);
34
+ ```
35
+
36
+ `environment.groundHeight(x, z)` returns the ground height at a world position, or `undefined`
37
+ while that terrain has not streamed in. Terrain streams provide it as `sampleHeight`. Controllers
38
+ use it to settle onto ground as it loads and to keep the camera above it.
39
+
40
+ ## Orbit
41
+
42
+ `OrbitController` frames a ground `target` from `range` meters away, looking along a compass
43
+ `heading` (0 north, `PI/2` east) and tilted `pitch` radians below the horizon. Drag to rotate and
44
+ tilt (the scene follows the pointer), use the wheel or a pinch to zoom, twist two fingers to
45
+ rotate, and pan with the secondary mouse button, shift-drag, two fingers, or WASD/arrow keys (Q/E
46
+ zoom). Motion eases toward a goal, so every change feels smooth.
47
+
48
+ `flyTo({ target, range, heading, pitch }, { durationMs })` animates to a framing. It rises
49
+ mid-flight on long hops so the camera clears the scenery, and any direct input cancels it.
50
+ `set(state)` jumps immediately, and `state` reads the current framing. The target settles onto the
51
+ ground as finer terrain arrives, and the camera never dips below `minClearance`.
52
+
53
+ ## Fly
54
+
55
+ `FlyController` moves along the view with WASD or the left stick, changes altitude with Q/E, and
56
+ looks by dragging or with the right stick. Its speed scales with height above ground, from
57
+ `minSpeed` near the surface to continental speeds high up, so one control scheme works at every
58
+ scale. Shift sprints.
59
+
60
+ ## Walk
61
+
62
+ `WalkController` is a 1.8 m capsule with gravity, jumping, wall sliding and a 50° walkable-slope
63
+ limit. It integrates at a fixed 120 Hz, so the same input produces the same path at any frame rate.
64
+ Its world position is `feet`; render the camera `WALK_EYE_HEIGHT` above it. Collision comes from
65
+ `WalkCollision`, which builds a small bounding-volume tree from the **visible** meshes under a root
66
+ (usually your terrain stream's object) within a neighborhood of the walker: 24 m by default,
67
+ rebuilt once the walker has moved 6 m from its center or the geometry inside it changed. It stays
68
+ correct across floating-origin rebasing.
69
+
70
+ ```ts
71
+ const walker = new WalkController();
72
+ // Each scan visits every visible mesh under the root; 5 Hz still catches streamed changes.
73
+ const collision = new WalkCollision({ rescanIntervalMs: 200 });
74
+ walker.reset(x, z);
75
+ // each frame:
76
+ if (!walker.ready) collision.invalidate(); // placement must see geometry published this frame
77
+ collision.update(stream.object, walker.feet.x, walker.feet.z);
78
+ if (!walker.ready) walker.place(collision, sampleHeight); // finds open ground, not a roof
79
+ walker.update(dt, { forward, right, yaw, sprint, jump }, collision, sampleHeight);
80
+ ```
81
+
82
+ `update` scans the scene when the subject leaves the neighborhood, when `rescanIntervalMs` has
83
+ passed (default 0: every call), or after `invalidate()`, and rebuilds the tree only when the nearby
84
+ meshes changed. Terrain tiles and building cells are walked through a per-geometry spatial index,
85
+ so a rebuild costs the triangles near the subject, not the whole tile. Faster subjects widen the
86
+ neighborhood and bound it vertically: `new WalkCollision({ radius: 48, rebuildDistance: 24,
87
+ verticalRadius: 40 })` with `update(root, x, z, y)` keeps ground far below an aircraft out of the
88
+ tree entirely. Queries reach at most `radius - rebuildDistance` from the subject. Leave
89
+ `verticalRadius` unset for a walker, whose placement ray scans the whole column.
90
+
91
+ Meshes opt out with `userData.walkIgnore = true`. Water materials and landcover overlays are never
92
+ solid. A missing terrain tile pauses movement until it arrives, rather than dropping the walker.
93
+
94
+ ## Follow
95
+
96
+ `FollowController` trails a subject, given its position and compass heading, at a set distance
97
+ and height. It eases after turns and bumps instead of welding to them. Look input swings the camera
98
+ around the subject, and it drifts back behind the subject after the input stops. Call `reset()`
99
+ after a teleport. For the cockpit and chase views of a mounted vehicle, see
100
+ [vehicles](vehicles.md) (`vehicleCameraPose`).
101
+
102
+ ## Input
103
+
104
+ `NavigationInputSource` combines an `InputMap` (keyboard, gamepad, software controls) with
105
+ `NavigationPointer` gestures into one `NavigationInput` per frame: `move` (forward/right/up,
106
+ -1..1), `look`, `pan`, `zoom`, `twist`, `sprint`, `jump`, edge-triggered `interact`/`view` press
107
+ counts, and element-relative `taps` for picking. You can also build a `NavigationInput` yourself,
108
+ which is useful in tests, replays and agent-driven cameras (`idleNavigationInput()` is the neutral
109
+ value).
110
+
111
+ Default profiles come from `navigationInputProfiles()`:
112
+
113
+ | Profile | Keys | Gamepad (standard mapping) |
114
+ |---|---|---|
115
+ | `orbit`, `fly` | WASD/arrows move, Q/E down/up, Shift sprint | left stick move, right stick look, bumpers up/down |
116
+ | `walk`, `drive` | WASD/arrows move, Space jump/brake, E or F interact, V view, Shift sprint | left stick move, right stick look, A jump, X interact, Y view |
117
+ | `pilot` | W/S or ↑/↓ nose down/up, A/D or ←/→ bank, Q/Z rudder, Shift/Ctrl (or +/−, Page Up/Down) power, I engine, G gear, F flaps, R recover, Space brake, V view, E exit | left stick pitch/bank, right stick look, triggers power, bumpers rudder, A brake, B engine, X exit, Y view |
118
+
119
+ In the `pilot` profile each `NavigationInput` also carries `pilot`: the held `throttle` and `yaw`
120
+ axes (-1..1) and edge-triggered `engine`, `gear`, `flaps` and `recover` presses. Pitch is
121
+ `-move.forward` and bank is `move.right`, so the touch stick flies too; hold-to-throttle buttons
122
+ can drive `NAVIGATION_ACTIONS.throttleUp`/`throttleDown` with `input.map.setVirtual(...)`.
123
+
124
+ Call `input.setProfile(mode)` when navigation changes. The walk profile also turns on pointer lock
125
+ for mouse-look, with drag-look as the fallback when pointer lock is declined. Replace any profile
126
+ with `input.map.defineProfile(name, profile)`. The action names are exported as
127
+ `NAVIGATION_ACTIONS`.
128
+
129
+ ### Touch
130
+
131
+ One finger drags to look, two fingers pinch, twist and pan, and a quick tap is reported in `taps`.
132
+ For movement on phones, add the on-screen stick:
133
+
134
+ ```ts
135
+ import { createTouchJoystick } from '@bendyline/molen-client/navigation';
136
+
137
+ const stick = createTouchJoystick(container, input.map); // bottom-left, style with className
138
+ stick.setVisible(matchMedia('(pointer: coarse)').matches);
139
+ ```
140
+
141
+ The stick drives the same `nav-forward`/`nav-back`/`nav-left`/`nav-right` actions through
142
+ `InputMap.setVirtual`, so a phone moves exactly like a keyboard or gamepad. `TouchStick` is its
143
+ DOM-free geometry, if you want to draw your own.
144
+
145
+ ## Streaming alongside the camera
146
+
147
+ Terrain selection is usually throttled (for example to 10 Hz). `viewNeedsImmediateUpdate(previous
148
+ position, previous direction, position, direction, moveThreshold, turnRadians)` reports when a
149
+ move or turn is large enough to outrun the selector's guard band, so you can update the stream
150
+ before rendering that frame.
@@ -99,7 +99,7 @@ recorded replay keeps that identity (see [determinism](determinism.md)). A proje
99
99
  namespace and everything under it on dot boundaries (`train` covers `train.car`, not
100
100
  `trainer.x`), for **both type ids and asset ids**. Reserve before you author:
101
101
 
102
- ```
102
+ ```sh
103
103
  molen types reserve train --owner agent:layout
104
104
  ```
105
105
 
@@ -12,7 +12,7 @@ install: three complete games, the capability demos and the small starters.
12
12
 
13
13
  Scaffold a project from npm and install it:
14
14
 
15
- ```
15
+ ```sh
16
16
  npx @bendyline/molen-tooling new my-experience
17
17
  cd my-experience
18
18
  npm install # the engine, the molen CLI, TypeScript and Vite
@@ -32,7 +32,7 @@ CLI the project installed. See the [agent loop](agent-loop.md) and
32
32
  The smaller samples ship inside `@bendyline/molen-tooling` as templates, locked to the engine
33
33
  version you install. `--template` copies one into a standalone npm project that you own:
34
34
 
35
- ```
35
+ ```sh
36
36
  npx @bendyline/molen-tooling templates # list them
37
37
  npx @bendyline/molen-tooling new my-game --template skybound
38
38
  cd my-game
@@ -109,8 +109,9 @@ catalogs are extended in the engine repository.
109
109
  title. Reserve other geometric marks for non-business category signs and props. A new silhouette
110
110
  needs a bounded generator implementation and schema update.
111
111
  4. Increment the edited document version to record the revision. Run `molen validate <file>`
112
- for structural validation, then `pnpm -r build` to validate catalog cross-references.
113
- Content hashes handle cache invalidation independently of manual version bumps.
112
+ for structural validation, then `pnpm -r build` in the engine repository to validate catalog
113
+ cross-references. Content hashes handle cache invalidation independently of manual version
114
+ bumps.
114
115
  5. For behavioral or visual changes, add positive and misleading-name cases, a standalone and
115
116
  shared-building example, and inspect near/distant captures. Follow the
116
117
  [3D art guidelines](3d-art-guidelines.md).
@@ -1,6 +1,6 @@
1
1
  # Game logic: scripts and setup
2
2
 
3
- A molen experience is **data plus scripts**. The scene manifest declares the world, the commands
3
+ A Molen experience is **data plus scripts**. The scene manifest declares the world, the commands
4
4
  it accepts, and its scripts; the scripts hold the logic. A code setup module exists for the rare
5
5
  things scripts cannot express, and for typed TypeScript authoring inside a project that installs
6
6
  the engine packages.
@@ -24,7 +24,8 @@ Erasure is whitespace-preserving, so the evaluated source keeps the exact line a
24
24
  of the file you wrote and `script "chase" tick handler at tick 12: …` still points at the right
25
25
  line. Nothing is emitted next to your source, and there is no build step to run by hand.
26
26
 
27
- > **Renamed:** the verb set was injected as `api` in earlier builds and is now `molen`. There is
27
+ > [!NOTE]
28
+ > **Renamed.** The verb set was injected as `api` in earlier builds and is now `molen`. There is
28
29
  > no alias — a script that references `api` throws at evaluation with the new name in the
29
30
  > message, so the fix is a find-and-replace of `api.` with `molen.`.
30
31
 
@@ -87,6 +88,7 @@ A script may also declare `function setup(molen, config) { … }` instead of top
87
88
  | `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 |
88
89
  | `query` | `(...componentNames)` | iterable result with `.ids()`, `.count()`, `.first()`, `.without(...names)` |
89
90
  | `emit` | `(type, payload)` | events reach other scripts, `molen.on` handlers, the client (`client.onEvent`), and `drive`/assert |
91
+ | `audio` | `molen.audio.play(sound, { entity?, position?, gain?, pitch?, bus?, loop? })` → handle / `stop(handle \| { entity?, sound? }, fadeS?)` / `music(playlist \| null)` | sound one-shots, loops and music; each call emits an `audio.*` event and never changes simulation state. See [audio.md](audio.md) |
90
92
  | `raycast` / `overlapCircle` | spatial queries (kinematics layer) | |
91
93
  | `after` / `every` | `(ticks, event, payload?)` | snapshot-safe world timers that EMIT (no callbacks); returns timer id. The handler receives `{ entity, timerId, payload }`. |
92
94
  | `cancelTimer` | `(timerId, entity?)` | |
@@ -92,6 +92,22 @@ scene geometry that casts/receives shadows; their local frustum follows the came
92
92
  light intensity to disable illumination. `sun.size` and `moon.size` are visual multipliers;
93
93
  the default 1 preserves real angular size. Larger values help stylized scenes and small displays.
94
94
 
95
+ ## Reflections
96
+
97
+ For metal and glass, pass `reflections: true` to `createViewer` or `mountExperience`.
98
+ The renderer shares one small procedural sky/ground environment across PBR materials on WebGL
99
+ and WebGPU. It follows the sky palette, solar direction and cloud cover, and refreshes only when
100
+ lighting changes visibly; moving the camera does not rebuild it. It is enabled by default in
101
+ `mountEarthView` and the world explorer. General viewers keep the legacy default (`false`).
102
+ The approximation provides sky reflections, not reflections of nearby buildings or trees.
103
+ Without `environment.sky`, it uses the ambient/sun rig and background color. Its filtered map
104
+ replaces the hemisphere's diffuse contribution during rendering to avoid lighting surfaces twice.
105
+ A host-supplied `renderer.scene.environment` takes precedence; the host retains ownership of that
106
+ texture and control of its light balance.
107
+ Custom host meshes should use `MeshStandardMaterial` or `MeshPhysicalMaterial` for this mode;
108
+ legacy Lambert/Phong materials do not receive the filtered sky's diffuse lighting. Unlit
109
+ materials remain unlit. Molen's built-in world surfaces and interiors use the PBR path.
110
+
95
111
  ## Other worlds
96
112
 
97
113
  The shared sky dome, twilight gradient, star sphere and celestial-body rendering can use authored
@@ -13,7 +13,6 @@ source/<category>/<thing>/
13
13
  models/
14
14
  source.glb
15
15
  generate.mjs
16
- baseline.json
17
16
  scripts/
18
17
  interactions.ts
19
18
  textures/
@@ -1,7 +1,7 @@
1
1
  # Default structure library
2
2
 
3
3
  Molen ships **120 procedural structures**: the original 16 styles and 104 additional interpretations
4
- of real-world buildings. They share 45 material graphs and the existing footprint-driven worldgen
4
+ of real-world buildings. They share 51 material graphs and the existing footprint-driven worldgen
5
5
  pipeline. Each entry has a stable style ID, taxonomy, country references, use, characteristic
6
6
  details, and a representative footprint and floor count. These are original stylized studies,
7
7
  not surveyed replicas or static meshes stretched to fit a parcel.
@@ -96,7 +96,7 @@ precedence. Dormers use `roof.features.dormers` on eligible pitched wings. Simpl
96
96
  representations omit ornament while retaining their footprint, primary roof and measured envelope.
97
97
 
98
98
  The [standard material catalog](https://github.com/bendyline/molen/blob/main/content/worldgen/materials/README.md)
99
- groups all 45 shared graphs by construction. It includes several brick bonds, cut/rubble stone,
99
+ groups all 51 shared graphs by construction. It includes several brick bonds, cut/rubble stone,
100
100
  clapboard and board-and-batten, shingles, clay tiles, slate, thatch, rammed earth and metal roofs.
101
101
  Physical repeat sizes live in `scripts/standard-materials.mjs`. Common textures are 256² and
102
102
  prepared once per shared material set. Window graphs use cell UVs; solid surfaces use meter UVs.
@@ -144,7 +144,8 @@ and explicit `width`. Properties absent from the source use class-based defaults
144
144
  omitted; bridges and differing layers do not form surface junctions. Bridge ribbons retain the
145
145
  existing approximate terrain-relative elevation; this renderer does not build engineered bridge
146
146
  decks. Crossing paint, inferred sidewalks, signal placement and parking occupancy are decorative,
147
- not traffic-control or navigation data.
147
+ not traffic-control or navigation data. [Ambient life](ambient-life.md) builds its own lane graph
148
+ from the same features for NPC traffic.
148
149
 
149
150
  Ground surfaces render at all available semantic levels. Fine markings and fixtures default to
150
151
  the finest pyramid level; `detailLevelsBelowMax` extends them to coarser levels. Fixture/car and
@@ -199,5 +200,5 @@ For a utility corridor, use narrow elevated bands and widely spaced pole repeate
199
200
  width across the route, height, and length along it. Band `dash: [length, gap]` and `phase` use
200
201
  world units along the path; callers can carry phase across tile fragments when their source
201
202
  provides route chainage. `terrainLinePath` and `sampleTerrainLine` are exported for custom
202
- attachment/model placement. Railway switches, wire sag, traffic simulation, and route-level
203
- cross-tile topology are separate consumers of this foundation.
203
+ attachment/model placement. Railway switches, wire sag and route-level cross-tile topology are
204
+ separate consumers of this foundation, and traffic simulation is [ambient life](ambient-life.md).
@@ -90,7 +90,16 @@ Earth packages use Web Mercator, which inflates horizontal distance by 1/cos(lat
90
90
  projected frame by `metersPerUnit = cos(center latitude)` (recorded on the descriptor), so tiles,
91
91
  meshes, semantic densities, character speeds, and entity XZ are all in ground meters. Convert
92
92
  between world and projected space with `projectedToWorld` / `worldToProjected`; `webMercatorToWgs84`
93
- takes projected coordinates (divide world XZ by `metersPerUnit` first).
93
+ takes projected coordinates (divide world XZ by `metersPerUnit` first). `wgs84ToWorld(metersPerUnit,
94
+ lon, lat)` and `worldToWgs84` do both steps for placing cameras, markers, and entities.
95
+
96
+ The scale is exact at one latitude, the **frame**. It defaults to the center of the package bounds,
97
+ which suits a regional package. A worldwide package centers on the equator, so pass the latitude you
98
+ are viewing: `createTerrainPackagePyramidStream(pkg, { frame: { latitude }, … })` (every package
99
+ open/descriptor helper accepts the same `frame`). `terrainPackageMetersPerUnit(pkg, frame)` returns the
100
+ matching scale for your own placement math and for worldgen's `metersPerUnit`. The error grows by
101
+ roughly 1–1.5% per degree of latitude away from the frame at mid-latitudes, so re-anchor — rebuild
102
+ the streams on a new frame — after moving more than about a degree north or south.
94
103
 
95
104
  ## 3. Render it (client side)
96
105
 
@@ -123,6 +132,10 @@ function frame(cameraPosition: [number, number, number]) {
123
132
  }
124
133
  ```
125
134
 
135
+ `reverseDepthBuffer` preserves depth precision across a large view range. On WebGL devices without
136
+ `EXT_clip_control`, Molen automatically uses logarithmic depth on the same canvas and context.
137
+ Logarithmic depth costs early-fragment performance; devices supporting reversed depth keep it.
138
+
126
139
  The source interface returns decoded height tiles, so archive readers, procedural worlds, and tests
127
140
  do not change residency behavior. HTTP 404 is a stable missing tile; call `retryFailed()` only after
128
141
  the backing data has changed. A *thrown* error is not: a dropped range request, a 503, or a CORS
@@ -167,7 +180,7 @@ calls, instances, loading/failure counts, and evictions for live quality diagnos
167
180
 
168
181
  ## 4. Screenshot it headlessly
169
182
 
170
- ```
183
+ ```sh
171
184
  molen shot scene.json --out island.png --camera 256,160,580 --look 256,20,256 --size 1280x720
172
185
  ```
173
186
 
@@ -215,6 +228,26 @@ Validate the manifest with `molen validate terrain-package.json`. A compiler/rel
215
228
  also run `molen validate terrain-package.json --verify-files`; that streams every declared file
216
229
  and checks directory containment, byte size, and SHA-256 without loading an archive into memory.
217
230
 
231
+ A source may also be a **split archive family**: `{ "kind": "pmtiles-set", "url": ".../archive-set.json" }`
232
+ (or a package-relative `path`) names a `molen/archive-set@1` document instead of one archive. Planet
233
+ data outgrows what CDNs cache as a single object, so producers cut it into a coarse `base` archive
234
+ plus detail archives, each owning a disjoint set of cells at `partitionLevel` (as run-length indices
235
+ `y * 2^partitionLevel + x`). The package adapter opens the document lazily and routes every tile to
236
+ the archive owning its ancestor cell, opening members on demand in a small LRU. Hosts with their own
237
+ transport call `createTerrainArchiveSetArchive(urlOrDocument, { openArchive })` from
238
+ `@bendyline/molen-terrain/client` and pass the result as `archive`, `landcoverArchive`, or
239
+ `featuresArchive`; `createTerrainArchiveSetRouter` in the kernel half is the pure routing function,
240
+ and `encodeTerrainArchiveSetPartitions` writes the run-length lists. Validate a set document with
241
+ `molen validate archive-set.json`.
242
+
243
+ Compilers write package archives with the portable PMTiles v3 writer in
244
+ `@bendyline/molen-terrain/kernel` (Node, Workers and browsers). `writePmtilesArchive(tiles,
245
+ { tileType: 'png', bounds })` builds a whole archive in memory; for archives too large for memory,
246
+ stream the tile payloads to disk in tile-id order (`pmtilesTileId(z, x, y)`) and write
247
+ `createPmtilesPrefix(records, dataLength, options)` in front of them. Official readers fetch only the
248
+ first 16 KiB to find the root directory, so the writer moves entries into gzip-compressed leaf
249
+ directories once one root would overflow that window; archives of any size stay readable.
250
+
218
251
  The optional `surface` block declares `seaLevel` and portable height/slope material bands. If it is
219
252
  omitted, the projected-Earth adapter supplies a conservative dirt/sand/grass/rock/snow palette.
220
253
 
@@ -312,6 +345,23 @@ they share one `features` PMTiles sidecar. When both sections reference one MVT
312
345
  renderer layers share one in-flight range read and full decode; decoded semantic documents are not
313
346
  retained as a second long-lived cache.
314
347
 
348
+ Polygonal water is flat: a lake's level is the lower quartile of the elevation inside it, so shore
349
+ samples cannot lift it onto its banks. For projected Earth, pass `seaLevel` in the mesh options
350
+ (the Earth view does): water whose floor reaches within 2 m of it is the sea, a harbor or a tidal
351
+ river, and draws at one level 1.5 m above sea level in every tile. Coastal elevation is noisy
352
+ around zero and bathymetry differs from tile to tile, so a sampled level would let the ground poke
353
+ through and step at tile seams.
354
+
355
+ The opposite split works too: when the terrain refines past a sidecar's last level (a zoom-13 vector
356
+ archive under zoom-14 elevation), the finer tiles overzoom the sidecar's finest tiles by default.
357
+ `overzoomTerrainSemanticTile` rescales an ancestor's normalized geometry onto the descendant, clips
358
+ roads, waterways and areas to it (plus a 1/64 buffer, like decoded tiles), and keeps each building
359
+ and point in exactly the one descendant that holds its center, so nothing is cut or drawn twice.
360
+ `createOverzoomTerrainSemanticSource` wraps any semantic source this way and keeps recently decoded
361
+ ancestors, since one ancestor serves up to four children at a time. Layers created by
362
+ `createTerrainPackageSemanticLayers` then reach the package's `maxLevel`; pass `overzoom: false`
363
+ to stop them at the sidecar's levels.
364
+
315
365
  The package elevation pyramid may be sparse. `createTerrainPackagePyramidHeightSource` walks to the
316
366
  nearest declared ancestor when an exact tile is absent, then crops and resamples that ancestor into
317
367
  the requested tile bounds. This supports broad coarse coverage plus a small regional detail window
@@ -1,15 +1,14 @@
1
1
  # Mountable vehicles and driving
2
2
 
3
- For the P-51D Mustang and OH-6, see [Aircraft](aircraft.md). They share the mount/seat
4
- foundation and add separate flight controls, physics, assets and cockpit cameras.
5
-
6
3
  World explorer's parking cars are external entity types with stable IDs, metric dimensions, and five
7
- models: compact, sedan, SUV, pickup and van. Each type owns its GLB reference, complete physics
8
- configuration, seats, named visual bindings, and optional deterministic scripts. Dormant cars use
9
- generic dimension-driven instance proxies; approaching or entering one loads its independent GLB
10
- with its own interior and controls. See [Vehicle interiors](vehicle-interiors.md).
11
- No concrete car model or handling catalog is compiled into schema,
12
- kernel, or client.
4
+ models: compact, sedan, SUV, pickup and van. You can walk up to one, get in and drive it.
5
+
6
+ Each type owns its GLB reference, complete physics configuration, seats, named visual bindings,
7
+ and optional deterministic scripts. Dormant cars use generic dimension-driven instance proxies;
8
+ approaching or entering one loads its independent GLB with its own interior and controls. See
9
+ [Vehicle interiors](vehicle-interiors.md). No concrete car model or handling catalog is compiled
10
+ into schema, kernel, or client. The P-51D Mustang and OH-6 share the same mount/seat foundation
11
+ and add separate flight controls, physics, assets and cockpit cameras; see [Aircraft](aircraft.md).
13
12
 
14
13
  In **Walk mode**, approach a car and press **E** to enter its driver seat. **W/S** accelerate or
15
14
  brake then reverse; **A/D** steer; **Space** brakes; **V** switches cockpit/chase views. Mouse look
@@ -78,7 +77,9 @@ fixtures and buildings. Terrain gaps pause motion; abrupt steps and slopes above
78
77
  the car. Cockpit views use the full chassis quaternion; chase views shorten at obstructions.
79
78
 
80
79
  This is a grounded driving foundation. It does not implement rigid-body rollovers, crash deformation,
81
- traffic AI, passenger animation, multiplayer ownership, or disk persistence. Without collision hooks,
80
+ passenger animation, multiplayer ownership, or disk persistence. Background traffic is a separate
81
+ package: [ambient life](ambient-life.md) moves NPC cars along lanes without this solver, and they
82
+ stop for a car someone is driving. Without collision hooks,
82
83
  the reusable kernel solver supplies terrain driving only. Do not attach a second physics body to the
83
84
  same vehicle; the vehicle solver owns its transform.
84
85
 
@@ -86,6 +87,27 @@ All durable simulation state and mount relationships live in ECS components and
86
87
  and replay. Install the same systems/environment when restoring. Host streaming and render resources
87
88
  are separate from those checkpoints.
88
89
 
90
+ ## In an Earth view
91
+
92
+ `mountEarthView` drives the parked cars its street surfaces place, and can add one:
93
+ `view.setMode('drive', { vehicle: true })` puts the viewer in a car in the nearest mapped road
94
+ lane. `EarthVehicles` exposes the pieces for hosts that compose their own view: `spawn(kind,
95
+ position, yaw)` at an exact spot, `spawnNear(kind, x, z, yaw, { avoid })` on the nearest open
96
+ ground (under open sky, never a roof or deck), `board(id)` without walking to the door, and
97
+ `release()` to step out at once. A standing spawned car settles onto finer terrain as it streams
98
+ in. The entity's `vehicle.color`, when set, paints the model's `paintMaterial`; without one the
99
+ authored paint stays.
100
+
101
+ ## Engine sound
102
+
103
+ Every `molen.entities` vehicle type carries an `audioSource`: the compact, sedan and SUV run
104
+ `vehicle.engine.car`, the pickup and van `vehicle.engine.diesel`, each with its own pitch. The
105
+ engine plays only while someone drives (`self.occupied`), rises in pitch with
106
+ `vehicleState.speed`, and grows louder with `vehicleInput.throttle`. Any host that plays audio from
107
+ the entity world, such as `mountEarthView` or a page with `createAudioLayer(...).attachWorld(world)`,
108
+ hears it with no extra code. Override the component on a type or entity to change the sound; see
109
+ [Sound and music](audio.md).
110
+
89
111
  ## Reusable views and parking data
90
112
 
91
113
  `@bendyline/molen-client/vehicles` exports `createVehicleVisual`, `createParkedVehicleBatch`,