@bendyline/molen-tooling 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +15 -0
  3. package/README.md +91 -0
  4. package/dist/capture/THIRD-PARTY-NOTICES.md +223 -0
  5. package/dist/capture/basis/LICENSE.txt +55 -0
  6. package/dist/capture/basis/basis_transcoder.js +19 -0
  7. package/dist/capture/basis/basis_transcoder.wasm +0 -0
  8. package/dist/capture/capture.html +15 -0
  9. package/dist/capture/harness.js +4671 -0
  10. package/dist/capture/worldgen-preview.html +15 -0
  11. package/dist/capture/worldgen-preview.js +4617 -0
  12. package/dist/cli.d.mts +1 -0
  13. package/dist/cli.mjs +1276 -0
  14. package/dist/docs-src/guide/3d-art-guidelines.md +157 -0
  15. package/dist/docs-src/guide/3d-model-assets.md +286 -0
  16. package/dist/docs-src/guide/adaptive-performance.md +89 -0
  17. package/dist/docs-src/guide/agent-loop.md +156 -0
  18. package/dist/docs-src/guide/aircraft.md +225 -0
  19. package/dist/docs-src/guide/browser-mount.md +185 -0
  20. package/dist/docs-src/guide/building-interiors.md +175 -0
  21. package/dist/docs-src/guide/capability-authoring.md +69 -0
  22. package/dist/docs-src/guide/determinism.md +285 -0
  23. package/dist/docs-src/guide/entities.md +47 -0
  24. package/dist/docs-src/guide/examples.md +58 -0
  25. package/dist/docs-src/guide/experience-playback.md +57 -0
  26. package/dist/docs-src/guide/figures.md +164 -0
  27. package/dist/docs-src/guide/game-samples.md +100 -0
  28. package/dist/docs-src/guide/graphics-performance.md +167 -0
  29. package/dist/docs-src/guide/input.md +205 -0
  30. package/dist/docs-src/guide/materials.md +125 -0
  31. package/dist/docs-src/guide/project.md +157 -0
  32. package/dist/docs-src/guide/quickstart.md +63 -0
  33. package/dist/docs-src/guide/recognizable-places.md +158 -0
  34. package/dist/docs-src/guide/rendering-backends.md +231 -0
  35. package/dist/docs-src/guide/scripting.md +330 -0
  36. package/dist/docs-src/guide/sky.md +192 -0
  37. package/dist/docs-src/guide/source-bundles.md +42 -0
  38. package/dist/docs-src/guide/structure-library.md +114 -0
  39. package/dist/docs-src/guide/surface-rendering.md +203 -0
  40. package/dist/docs-src/guide/terrain.md +389 -0
  41. package/dist/docs-src/guide/three-surface.md +70 -0
  42. package/dist/docs-src/guide/vehicle-interiors.md +126 -0
  43. package/dist/docs-src/guide/vehicles.md +110 -0
  44. package/dist/docs-src/guide/weather.md +123 -0
  45. package/dist/docs-src/guide/worldgen.md +434 -0
  46. package/dist/docs-src/llms.txt +129 -0
  47. package/dist/docs-src/schemas/README.md +36 -0
  48. package/dist/docs-src/schemas/archstyle.md +2340 -0
  49. package/dist/docs-src/schemas/assert.md +169 -0
  50. package/dist/docs-src/schemas/asset.md +543 -0
  51. package/dist/docs-src/schemas/business-catalog.md +162 -0
  52. package/dist/docs-src/schemas/cameratrack.md +132 -0
  53. package/dist/docs-src/schemas/command.md +112 -0
  54. package/dist/docs-src/schemas/components.md +5826 -0
  55. package/dist/docs-src/schemas/delta.md +204 -0
  56. package/dist/docs-src/schemas/experience-play.md +452 -0
  57. package/dist/docs-src/schemas/figure.md +290 -0
  58. package/dist/docs-src/schemas/interior-catalog.md +230 -0
  59. package/dist/docs-src/schemas/keyframe.md +314 -0
  60. package/dist/docs-src/schemas/landmark-catalog.md +56 -0
  61. package/dist/docs-src/schemas/landmark.md +293 -0
  62. package/dist/docs-src/schemas/matgraph.md +1163 -0
  63. package/dist/docs-src/schemas/pack-index.md +82 -0
  64. package/dist/docs-src/schemas/pack-source.md +139 -0
  65. package/dist/docs-src/schemas/pack.md +225 -0
  66. package/dist/docs-src/schemas/pixelgrid.md +108 -0
  67. package/dist/docs-src/schemas/prefab.md +106 -0
  68. package/dist/docs-src/schemas/project.md +271 -0
  69. package/dist/docs-src/schemas/region-atlas.md +612 -0
  70. package/dist/docs-src/schemas/replay.md +807 -0
  71. package/dist/docs-src/schemas/scatter.md +541 -0
  72. package/dist/docs-src/schemas/scene.md +1152 -0
  73. package/dist/docs-src/schemas/source-bundle.md +266 -0
  74. package/dist/docs-src/schemas/stylepack.md +420 -0
  75. package/dist/docs-src/schemas/terrain-package.md +731 -0
  76. package/dist/docs-src/schemas/terrain.md +313 -0
  77. package/dist/docs-src/schemas/types.md +218 -0
  78. package/dist/docs-src/schemas/uvpaint.md +149 -0
  79. package/dist/docs-src/schemas/worldgen-batch.md +743 -0
  80. package/dist/index.d.mts +1271 -0
  81. package/dist/index.mjs +78 -0
  82. package/dist/mcp-BFnCWrg0.mjs +796 -0
  83. package/dist/ops-BGxhSP6w.mjs +7246 -0
  84. package/package.json +96 -0
@@ -0,0 +1,57 @@
1
+ # Playing browser experiences
2
+
3
+ `molen play` is the browser counterpart to deterministic scene `drive`: it hosts a built web
4
+ experience, performs player-like inputs, and leaves screenshots plus diagnostics an agent can
5
+ inspect.
6
+
7
+ ```sh
8
+ molen play examples/world-explorer/dist \
9
+ --scenario examples/world-explorer/test/visual/navigation.play.json \
10
+ --out-dir .artifacts/world-explorer
11
+ ```
12
+
13
+ The host uses an ephemeral localhost port and supports HTTP byte ranges, so PMTiles and other
14
+ streamable archives exercise the same request path used in production. Each run writes the named
15
+ PNG frames and `experience-run.json`, containing probe text and browser console, page, and failed
16
+ request diagnostics. Failed plays also keep their partial frames and run manifest, including the
17
+ failing action and last observed stable-text probe, so a timeout remains inspectable.
18
+
19
+ ## Scenario format
20
+
21
+ An `molen/experience-play@1` document declares its viewport, initial URL, optional DOM text probes,
22
+ and ordered actions:
23
+
24
+ ```json
25
+ {
26
+ "format": "molen/experience-play@1",
27
+ "name": "walkthrough",
28
+ "path": "/?quality=high",
29
+ "viewport": [1280, 720],
30
+ "probes": [{ "name": "status", "selector": "#status" }],
31
+ "actions": [
32
+ { "type": "wait-for-stable", "selector": "#status", "text": "0 loading" },
33
+ { "type": "screenshot", "name": "start" },
34
+ { "type": "keys", "keys": ["w", "Shift"], "durationMs": 1500 },
35
+ { "type": "drag", "selector": "canvas", "from": [0.5, 0.5], "to": [0.75, 0.5] },
36
+ { "type": "screenshot", "name": "after" }
37
+ ]
38
+ }
39
+ ```
40
+
41
+ Supported actions are `wait`, `wait-for`, `wait-for-stable`, `keys`, `key-down`, `key-up`, `drag`,
42
+ `click`, `select`, `navigate`, and `screenshot`. Use `key-down`/`key-up` around timed captures to
43
+ inspect an experience while it is moving. Drag coordinates are normalized within the target
44
+ element, so a scenario remains meaningful at different viewport sizes. `keys` holds all declared
45
+ keys for the duration, which makes continuous movement deterministic enough for visual regression
46
+ work.
47
+
48
+ Use `wait-for-stable` on an experience's status or loading indicator before capture. This avoids
49
+ blessing transient tiles as a golden image while still exposing stalls: the action times out when
50
+ the required text never appears or the probe keeps changing. Stability is measured in rendered
51
+ frames: each read waits for the page to draw a frame, and `stableMs` counts frame time. So a status
52
+ written from the render loop cannot pass while one slow frame keeps it stale, as happens under a
53
+ software rasterizer on a busy machine.
54
+
55
+ The same operation is exported as `playExperience()` from `@bendyline/molen-tooling` and as the
56
+ `play_experience` MCP tool. MCP results include the captured frames as images so an agent can run
57
+ the complete edit → play → look → improve loop without a manual browser.
@@ -0,0 +1,164 @@
1
+ # Figures: humans, bipeds and quadrupeds
2
+
3
+ `@bendyline/molen-figures` renders stylized people and animals and moves them: a **kernel half**
4
+ (`/kernel`: descriptors and presets, canonical rigs and sockets, deterministic gait and pose
5
+ evaluation, locomotion state, attachments) and a **client half** (`/client`: the `figure`
6
+ renderable kind that generates a skinned body from the descriptor and poses it every frame).
7
+ The look is deliberately left of the uncanny valley: readable silhouettes, color blocks for
8
+ clothing, disc eyes, no mouths or fingers, gently faceted surfaces (see the figure rules in
9
+ [3D art guidelines](3d-art-guidelines.md)).
10
+
11
+ Naming note: this is **not** `@bendyline/molen-kernel/kinematics` (the 2.5D collision layer) and
12
+ not `/character` (the gravity/jump mover). Figures sit on top of whatever moves an entity.
13
+
14
+ ## Quick start
15
+
16
+ A human with a hat, walking under the character controller:
17
+
18
+ ```json
19
+ {
20
+ "format": "molen/scene@3",
21
+ "name": "hello-figures",
22
+ "tickRate": 60,
23
+ "physics": { "engine": "kinematics", "character": true },
24
+ "entities": [
25
+ {
26
+ "id": "npc-1",
27
+ "components": {
28
+ "transform": { "pos": [0, 0, 0], "rot": [0, 0, 0, 1] },
29
+ "renderable": { "kind": "figure", "ref": "procedural" },
30
+ "figure": { "preset": "human.adult", "height": 1.7, "palette": { "top": "#3b6ea5" } },
31
+ "character": { "speed": 1.4, "jumpSpeed": 6, "gravity": 20, "vy": 0, "grounded": true },
32
+ "moveIntent": { "dir": [1, 0], "jump": false },
33
+ "collider": { "shape": "circle", "radius": 0.35, "layer": 1, "mask": 1 },
34
+ "kinematicBody": { "vel": [0, 0, 0], "slide": true }
35
+ }
36
+ },
37
+ {
38
+ "id": "npc-1-hat",
39
+ "components": {
40
+ "transform": { "pos": [0, 0, 0], "rot": [0, 0, 0, 1] },
41
+ "renderable": { "kind": "primitive", "ref": "cylinder", "materialRef": "palette:#39747d", "primitive": { "size": [0.3, 0.12, 0.3] } },
42
+ "parent": { "id": "npc-1" },
43
+ "figureAttachment": { "socket": "head.top", "offset": { "pos": [0, 0.06, 0] } }
44
+ }
45
+ }
46
+ ]
47
+ }
48
+ ```
49
+
50
+ `molen validate`, `molen sim run --ticks 120 --hash`, and `molen shot` work unchanged: tooling
51
+ installs the figures systems on every world, and the capture page renders the `figure` kind. In a
52
+ browser host, pass the kind to the client and the systems to the world:
53
+
54
+ ```ts
55
+ import { mountExperience } from '@bendyline/molen-client';
56
+ import { figureKind } from '@bendyline/molen-figures/client';
57
+ await mountExperience({ link: worker, scene, canvas, kinds: [figureKind()] });
58
+
59
+ // worker.ts
60
+ import { buildWorld } from '@bendyline/molen-kernel';
61
+ import { figuresScriptApi, installFigures } from '@bendyline/molen-figures/kernel';
62
+ const world = buildWorld(scene, setup, {
63
+ capabilities: [(w) => ({ figures: figuresScriptApi(installFigures(w)) })],
64
+ });
65
+ ```
66
+
67
+ ## Components
68
+
69
+ | Component | Owner | Purpose |
70
+ |---|---|---|
71
+ | `figure` | you | What the figure is: `preset` plus descriptor overrides, and how it faces (`facing`, `turnRate`, `speedSource`, `blendTicks`). |
72
+ | `figureIntent` | you (optional) | Control: a forced `mode`, a `lookAt` target, joint `overrides`, `ik` goals. |
73
+ | `figureState` | kernel | Locomotion state: `mode`, quantized `speed`, `strideRate`, tick-anchored `phaseAt`/`phaseAtTick`, `modeAtTick`, `prevMode`. Read it; never write it. |
74
+ | `figureAttachment` | you | On a child entity with `parent`: which `socket` to follow, an `offset`, and which `anchor` of the child sits on the socket. |
75
+
76
+ The renderable is `{ "kind": "figure", "ref": "procedural", "lod"?: "auto" | 0 | 1 | 2 }`.
77
+ `materialRef` is ignored for figures; colors come from the descriptor palette.
78
+
79
+ ## Descriptor and presets
80
+
81
+ A descriptor is a preset plus overrides. `molen figure presets` lists them; `molen schema get
82
+ figure` prints the full shape (the `molen/figure@1` file format wraps the same fields with a
83
+ `format` envelope for `molen validate` and `molen figure preview`).
84
+
85
+ | Field | Meaning |
86
+ |---|---|
87
+ | `preset` | `human.adult`, `human.child`, `human.elder`, `dog`, `cat`, `horse`, `deer`, `cow`, `sheep` |
88
+ | `height` | meters; bipeds to the head top, quadrupeds to the withers |
89
+ | `build` | -1 (slight) to 1 (heavy): limb and torso radii, shoulder width |
90
+ | `age` | `child`, `adult`, `elder` (elder adds a stoop) |
91
+ | `proportions` | multipliers: `legRatio`, `armRatio`, `torsoRatio`, `headScale`, `neckLength`, `neckPitch`, `shoulderWidth`, `hipWidth`, `bodyLength`, `tailLength`, `earSize`, `snoutLength` |
92
+ | `features` | `hair` (none/cap/bob/long), `hands`, `sleeves`, `legs`, `tail`, `ears`, `horns`, `feet`, `mane` |
93
+ | `palette` | `#rrggbb`: `skin` (fur/hide for animals), `hair`, `eyes`, `top`, `bottom`, `shoes`, `accent`, `markings` |
94
+ | `seed` | detail jitter only (symmetry-safe) |
95
+
96
+ Every rig stands with its feet at y = 0 and its reference point exactly at `height`, whatever
97
+ the overrides. Bodies come in three detail tiers (near about 1,000 to 1,500 triangles, medium,
98
+ and a rigid distant tier); the client picks a tier by camera distance unless `lod` pins one.
99
+
100
+ ## Locomotion
101
+
102
+ The `figures-locomotion` system (late phase, before the hierarchy) reads whatever moves the
103
+ entity: `kinematicBody.vel`, then `character` + `moveIntent`, `platformBody`, a rapier
104
+ `velocity`, else transform deltas (`speedSource: 'transform'` forces the last; `'none'` freezes
105
+ it). It picks a mode (`idle`, `walk`, `run`, `jump`, `fall`; `sit` when `mounted`), a
106
+ quadruped gait (walk, trot, gallop by Froude number), a stride rate from the leg length, and
107
+ turns the figure toward its velocity (`facing: 'velocity'`, the default) at `turnRate` rad/s.
108
+ `facing: 'manual'` leaves `transform.rot` to you (rapier-driven bodies, strafing).
109
+
110
+ State is written only when something changes: speed is quantized to 0.05 m/s, the gait phase is
111
+ anchored to a tick, so a steadily walking figure sends no deltas. `figureIntent.mode` forces a
112
+ mode; `lookAt` aims the head at a point or an entity.
113
+
114
+ ## Sockets and attachments
115
+
116
+ Sockets are named points on the rig, evaluated under the current pose. An entity with
117
+ `parent: { id: <figure> }` and `figureAttachment: { socket }` gets its `localTransform` from the
118
+ socket each tick (the kernel hierarchy composes the world transform, and destroying the figure
119
+ cascades). Anything renders there: a glTF hat, a primitive, another figure.
120
+
121
+ | Biped sockets | Quadruped sockets |
122
+ |---|---|
123
+ | `head.top`, `face`, `eyes`, `eye`, `ear.l`, `ear.r`, `neck`, `chest`, `back`, `hip.l`, `hip.r`, `hand.l`, `hand.r`, `foot.l`, `foot.r`, `pelvis` | `head.top`, `face`, `eyes`, `eye`, `mouth`, `neck`, `withers`, `saddle`, `back`, `tail.tip`, `foot.fl`, `foot.fr`, `foot.hl`, `foot.hr`, `pelvis` |
124
+
125
+ `anchor` chooses which point of the attached entity sits on the socket: `origin` (default),
126
+ `pelvis`, or `eye` (for figures seated on saddles and vehicle seats). Riders use the vehicle
127
+ mount contract: `molen.figures.mount(rider, horse)` adds a `mountable` with a `saddle` seat and
128
+ seats the rider; the `figures-riders` system keeps the rider on the animated saddle.
129
+
130
+ ## Scripting: `molen.figures.*`
131
+
132
+ `setMode(id, mode | null)`, `lookAt(id, { pos } | { entity } | null)`, `pose(id, overrides | null)`,
133
+ `ik(id, goals | null)`, `attach(itemId, figureId, socket, offset?, anchor?)`, `detach(itemId)`,
134
+ `mount(riderId, figureId, seat?)`, `dismount(riderId)`, `socket(figureId, name)` (world pose),
135
+ `setDescriptor(id, patch)`, `joints(id)`, `sockets(id)`, `presets()`.
136
+
137
+ ## Previews
138
+
139
+ ```sh
140
+ molen figure presets
141
+ molen figure preview --lineup all --angles review --mode walk --out review.png
142
+ molen figure preview my.figure.json --angles 4 --out turntable.png
143
+ ```
144
+
145
+ The MCP tools `figure_preview` (returns images) and `list_figure_presets` mirror these. The
146
+ `review` view set is the art-guideline review: front, three-quarter, rear, and a gameplay-distance
147
+ view.
148
+
149
+ ## Determinism
150
+
151
+ The pose is a pure function `evaluatePose(rig, figureState, tick)` shared by both halves: the
152
+ kernel evaluates it only where it needs a socket (attachments, riders, `molen.figures.socket`), the
153
+ client at every frame. `figureState` and the attachment `localTransform`s are ordinary hashed
154
+ components; rigs, meshes and poses are derived. The client keeps the previous state until the
155
+ interpolated render tick reaches the tick a state changed on, so poses and transforms agree.
156
+
157
+ ## Limits
158
+
159
+ - Hands are mittens (a thumb on the near tier with `hands: 'fingers'`); no faces beyond eyes and
160
+ brows.
161
+ - Foot planting on uneven ground and quadruped IK are not evaluated yet.
162
+ - Imported skinned glTF figures and `molen figure bake` (skinned GLB export) are later phases.
163
+ - Accessories follow kernel-evaluated sockets at tick rate; fast hand swings can lag a few
164
+ centimeters between ticks.
@@ -0,0 +1,100 @@
1
+ # Three complete games, one authoring path
2
+
3
+ The new samples exercise the same scene → `buildWorld` → Worker → `mountExperience` path as the
4
+ CLI. Each is JSON data + scene scripts, with declared command/component schemas, input
5
+ bindings, semantic prefabs, durable state, a HUD, restart, and a tested win condition.
6
+
7
+ | Sample | Play from repo root | Loop | Engine services |
8
+ |---|---|---|---|
9
+ | City Courier | `pnpm dev:driving` | Five deliveries, traffic, damage and a time limit | XZ kinematics, hierarchy, follow camera |
10
+ | The Lantern Vault | `pnpm dev:dungeon` | Key, melee combat, healing, gate and relic | XZ kinematics/raycast, seeded RNG, hierarchy, tween, local follow camera |
11
+ | Skybound | `pnpm dev:platformer` | Islands, seeds, stomps, hazards, checkpoint and finish | XY platform controller, hierarchy, world follow camera |
12
+
13
+ Install with `pnpm install`; each launch command builds its engine dependencies automatically.
14
+ The games use checked-in runtime assets and need no art-generation tools to play. Each README documents
15
+ controls and exact validate/simulate/assert/screenshot commands. `test/playthrough.test.js`
16
+ in each sample proves its objective is reachable using player commands alone. Headless tests
17
+ also verify checkpoint continuation; browser tests exercise the actual Worker and DOM inputs.
18
+
19
+ ## Follow cameras
20
+
21
+ Camera tracking is part of scene data, so no example needs a custom Three.js camera loop:
22
+
23
+ ```json
24
+ "camera": {
25
+ "mode": "follow", "entity": "player",
26
+ "offset": [0, 24, 18], "lookOffset": [0, 0, -3], "fov": 52
27
+ }
28
+ ```
29
+
30
+ Offsets are world-axis meters by default. Set `"space": "local"` to rotate both offsets by the
31
+ entity quaternion. First person uses `offset: [0,1.6,0]`, `lookOffset: [0,1.6,-1]` and local
32
+ space. The target may be invisible; Skybound uses a separate camera-target entity to clamp
33
+ horizontal framing and keep the horizon steady while the player jumps.
34
+
35
+ Live tracking samples the same interpolation buffer as rendered objects. A missing target
36
+ holds the previous camera pose until it appears. `createClient` and `createSnapshotViewer`
37
+ accept `sceneCamera`; `mountExperience` supplies it automatically. `molen shot`, `drive`, and `frames`
38
+ resolve tracking against the captured keyframe. Explicit capture camera overrides still win.
39
+ `client.setCamera(pose)` overrides tracking for hosts that take over the camera.
40
+ Offsets do not inherit visual scale, and follow cameras do not perform obstacle avoidance.
41
+
42
+ ## Lightweight platform physics
43
+
44
+ Choose `physics: { "engine": "platformer" }` for a deterministic, headless XY platform game.
45
+ It installs automatically in every `buildWorld` host, without WASM or a setup module:
46
+
47
+ ```json
48
+ {
49
+ "transform": { "pos": [0, 2, 0], "rot": [0, 0, 0, 1] },
50
+ "platformBody": { "halfExtents": [0.35, 0.65], "speed": 7, "jumpSpeed": 12 },
51
+ "platformIntent": { "move": 0, "jumpHeld": false }
52
+ }
53
+ ```
54
+
55
+ Static platforms carry `platformSolid: { "halfExtents": [4,0.5] }`; add `oneWay: true` for
56
+ ledges the player can jump through from below. Dimensions are world-space meters, independent
57
+ of visual scale/rotation. The collision plane is XY; Z is preserved. Author non-overlapping
58
+ spawn positions. Motion sweeps X then Y to the nearest face, so fast bodies cannot tunnel
59
+ through thin walls, ceilings or floors along either sweep.
60
+
61
+ Translate commands to `platformIntent.move` (-1..1), a one-shot `jump: true`, and `jumpHeld`.
62
+ The service consumes the jump request, applies acceleration/gravity, handles coyote grace and
63
+ buffered presses, and exposes `platformBody.grounded` and `vel`. Releasing jump early reduces
64
+ upward velocity. Jump grace/buffer counters are component state, so checkpoints continue
65
+ without hidden closure state. Collision events publish after the resolved state is installed.
66
+
67
+ This service intentionally supports static axis-aligned solids and independent controlled
68
+ bodies. It has no body/body pushing, moving-platform carry, slopes, or rotation response; use
69
+ Rapier when a game needs those. It cannot be combined with `physics.character: true`.
70
+ Programmatic hosts can import the typed handles and `installPlatformer` from
71
+ `@bendyline/molen-kernel/platformer`.
72
+
73
+ ## What these examples demonstrate
74
+
75
+ The game scripts have no renderer imports and no DOM access. Browser code never modifies the
76
+ simulation. Validation, headless play, replay/checkpoints, browser play, and screenshots consume
77
+ the same scene and scripts. The new camera and platform services remove duplicated host logic
78
+ and sample-specific collision solvers from ordinary game authoring.
79
+
80
+ These are compact single-player examples, not demonstrations of authoritative remote servers,
81
+ network prediction, vehicle suspension, full tabletop rules, or large-world streaming. The
82
+ world-explorer and terrain-flyover samples remain the terrain starting points.
83
+
84
+ ## Lantern Vault asset collection
85
+
86
+ The dungeon ships 28 original GLB models: six creatures, eight architectural pieces and fourteen
87
+ props/items. Its textured stone, held equipment and tick-driven glTF clips use the same public
88
+ asset/component APIs as the headless tools. Three creatures participate in combat; three are
89
+ ambient dressing. The project index maps every model to a sidecar under `public/assets/`, so Vite
90
+ serves the same files that CLI captures verify.
91
+
92
+ See the [illustrated catalog](../../examples/lantern-dungeon/asset-src/CATALOG.md) and
93
+ [editable sources and regeneration guide](../../examples/lantern-dungeon/asset-src/README.md).
94
+ Run `pnpm --filter @bendyline/molen-examples-lantern-dungeon assets:check` to verify byte-for-byte
95
+ regeneration, and `assets:shot` to capture four angles of every model.
96
+
97
+ The [example asset contract](../../examples/ASSETS.md) preserves editable masters and optimized
98
+ runtime copies separately. The dungeon supports hand-edited GLBs, protects them from accidental
99
+ regeneration, and checks source/runtime freshness with `assets:verify` (Node only). All three
100
+ game builds use relative URLs and have browser coverage under a hosting subdirectory.
@@ -0,0 +1,167 @@
1
+ # Graphics performance controls
2
+
3
+ The client and terrain packages reduce work on both Three.js backends. Backend selection is
4
+ covered in [WebGPU and WebGL](rendering-backends.md). These controls affect presentation;
5
+ headless simulation, entity IDs and authored geometry remain authoritative.
6
+
7
+ ## Static scenes and sparse motion
8
+
9
+ Client delta ingestion stores only changed transforms in a short interpolation history. The
10
+ frame loop samples active interpolations, applies the final pose once, and then retires them.
11
+ Static entities retain their last pose. Keyframes, binding replacement, teleports and resync
12
+ still restore presentation state; full keyframes necessarily visit the full scene.
13
+
14
+ Opaque primitive and static GLB meshes sharing geometry, material identities, shadow flags and
15
+ render layers are instanced within spatial cells. Animated, skinned, morph-target, transparent,
16
+ custom shader/node-material and custom render-callback meshes remain ordinary meshes. An
17
+ entity that subsequently moves leaves its static batch. The original entity objects retain
18
+ identity; `client.entityForIntersection(hit)` (also available on `ThreeSceneBackend`) maps ray hits to entity IDs.
19
+ `getObject(id)` opts that entity out and restores mutable Three transforms for the escape hatch.
20
+
21
+ ```ts
22
+ const client = await createClient(worker, {
23
+ canvas,
24
+ sceneOptimization: {
25
+ staticInstancing: { cellSize: 32, minInstances: 2 }, // defaults; false disables
26
+ shaderWarmup: true,
27
+ animation: { distantDistance: 80, distantHz: 15, hiddenHz: 5 },
28
+ // maxLocalLights: 16, // optional quality tradeoff; no count cap by default
29
+ },
30
+ });
31
+ await client.ready();
32
+ ```
33
+
34
+ Smaller instance cells improve culling and larger cells reduce draws. A batch can submit
35
+ triangles belonging to individually offscreen members, so fewer draws do not guarantee less
36
+ GPU work. Static local matrices are frozen; floating-origin motion still updates world matrices.
37
+
38
+ Live animations use the simulation tick at every sampled pose, without clock accumulation.
39
+ Visible nearby meshes and visible shadow casters retain full-rate sampling. Distant meshes
40
+ sample at 15 Hz and hidden meshes at 5 Hz by default; returning nearby updates immediately.
41
+ Use `animation: false` for full-rate sampling everywhere. Snapshot/capture poses remain exact.
42
+ Finite local lights whose entire influence sphere lies outside the camera frustum are omitted.
43
+ An explicit light-count cap ranks remaining lights by intensity/distance and can change images.
44
+
45
+ ## Staged preparation and admission
46
+
47
+ Each `Renderer` owns a `FrameAdmissionQueue`, configurable with the `admission` option:
48
+
49
+ Renderer defaults are 2 ms on WebGL and 8 ms on WebGPU, with 2 MiB and 32 jobs per frame.
50
+ WebGPU's individual Three node-builder steps commonly exceed 2 ms; the larger budget avoids
51
+ admitting only one mesh per frame in large worlds. Explicit budgets override these defaults.
52
+
53
+ ```ts
54
+ const viewer = await createViewer({
55
+ canvas,
56
+ admission: {
57
+ maxMilliseconds: 2, // explicit low-latency budget; WebGPU default is 8
58
+ maxBytes: 2 * 1024 * 1024,
59
+ maxJobs: 32,
60
+ onSample(sample) { /* label, workMs, queueMs, bytes, overBudget */ },
61
+ },
62
+ });
63
+ ```
64
+
65
+ The queue limits synchronous work started per animation frame. One oversized indivisible job
66
+ runs alone and is reported as over budget. This is not a hard GPU/driver time bound. Texture
67
+ initialization, geometry preparation and async shader compilation use public Three facilities;
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.
71
+ 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).
74
+
75
+ For custom streamed geometry, call `await renderer.prepareObject(object, signal)` before
76
+ publication. Connect the same queue to terrain:
77
+
78
+ ```ts
79
+ const terrain = await createTerrainPackagePyramidStream(packageDescriptor, {
80
+ admission: viewer.renderer.admission,
81
+ prepareObject: (object, signal) => viewer.renderer.prepareObject(object, signal),
82
+ elevationWorker: new Worker(new URL('./elevation-worker.ts', import.meta.url), { type: 'module' }),
83
+ onElevationTiming: sample => { /* decode, resample, mesh; milliseconds */ },
84
+ });
85
+ ```
86
+
87
+ The worker entry calls `installTerrainElevationWorker(self)`, exported from
88
+ `@bendyline/molen-terrain/client` (use the worker-scope type cast shown by World Explorer when
89
+ compiling with DOM rather than WebWorker types). The host reads archive bytes; the worker
90
+ owns PNG decoding, its decoded tile cache, ancestor resampling and surface meshing. Worker
91
+ buffers transfer without detaching archive caches or reusable topology. Omitting the worker
92
+ retains the in-thread path. Worker errors are surfaced; they do not silently trigger duplicate work.
93
+
94
+ Procedural texture baking can use `createMaterialBakeWorkerPool(workers)` from
95
+ `@bendyline/molen-materials`. Each worker entry calls `installMaterialBakeWorker(self)`. Pass
96
+ this caller-owned pool as `ClientOptions.materialBaker` or the second `MaterialResolver`
97
+ constructor argument, and dispose the pool when finished. Pixel grids and material graphs
98
+ return the synchronous baker's exact pixels through transferables. World Explorer uses two
99
+ startup workers and releases them when its style pack is baked; `materialWorker=0` retains
100
+ synchronous baking for comparisons. Its `material-bake` timing reports worker CPU time.
101
+
102
+ World-generation workers also prepare building spatial cells and full/structural LOD indices.
103
+ The renderer requests `renderCellsOnly` when using cell LODs so it does not retain a redundant
104
+ canonical building mesh. Per-cell Three object assembly is a separate queue job. Generation
105
+ and cell-preparation timings are reported separately. Compatible opaque groups are merged
106
+ by the resolved Three material, including groups with different authored references that resolve
107
+ to the same material. Transparent group order is preserved.
108
+
109
+ World prop cells start at 512 metres and grow with coarser terrain levels, capped at 8192 metres.
110
+ This retains fine nearby culling without creating thousands of tiny distant batches. Every prop
111
+ placement remains intact; larger cells trade some culling precision for fewer submissions.
112
+
113
+ Terrain palettes compile once per mesh. Terrain index topology is immutable and shared in a
114
+ bounded CPU cache; use a copy before editing or transferring it. Grids and building cells use
115
+ 16-bit indices when eligible. Terrain index arrays can be shared in CPU memory; separate Three
116
+ attributes can still allocate separate GPU index buffers. Building LODs share their attribute
117
+ objects and full-detail index where material grouping permits. Three r184 currently promotes
118
+ unnormalized 16-bit attributes (including indices) to 32-bit storage on its WebGPU path, so the
119
+ compact-index GPU saving applies to WebGL; worker/cache buffers remain compact on both paths.
120
+
121
+ ## Terrain selection and transitions
122
+
123
+ Terrain selection refines the highest projected-error candidate within the leaf budget, instead
124
+ of retrying complete traversals with progressively relaxed thresholds. A 15% coarsening
125
+ hysteresis band retains detail near boundaries. Pass `previousTiles` when using the standalone
126
+ selector; the stream supplies its previous selection automatically. Pitched views use a
127
+ conservative field of view to retain ground beneath the camera.
128
+
129
+ Terrain requests preserve parent-first coverage and prioritize the camera view before the
130
+ 12-degree turn margin at each level. Distance is measured to tile bounds rather than tile
131
+ centers, so large tiles do not push nearby ground behind more distant requests. Semantic layers
132
+ use the same view priority and prepare resident selected leaves before the terrain handoff,
133
+ even while a slow sibling still holds the parent surface on screen. Selected leaves take
134
+ precedence over temporary fallback detail. The existing layer concurrency and residency limits
135
+ also bound this preparation. The previous terrain surface and its layers remain visible until
136
+ all enabled, level-eligible layers of the replacement tiles have finished construction and GPU
137
+ preparation. Surfaces, land use, roads and buildings then switch together; new terrain cannot
138
+ occlude the previous detail while its own detail is still loading. This applies to refinement and
139
+ coarsening, including intermediate fallback tiles. Cached LODs reuse their prepared geometry.
140
+
141
+ Previously unvisited ground can show its base surface immediately; its enabled layers appear
142
+ together once settled. Empty layer results count as ready. Failed replacement layers preserve
143
+ the old tiles until `retryFailed()` succeeds or the layer is disabled; on cold ground, successful
144
+ layers can still appear after another layer fails. Hidden layers do not delay a handoff. This
145
+ stages scene geometry rather than rendering a second full-screen image, and retains old visual
146
+ coverage under residency pressure until its replacement can safely take over.
147
+
148
+ `morphMilliseconds` enables refinement height morphs for bare surfaces; call
149
+ `stream.updateTransitions(nowMs)` in the frame loop. Vertices start on the actual parent
150
+ triangles and finish at their exact target positions with fixed horizontal coordinates. Grounded
151
+ semantic layers use coverage-preserving atomic replacement and hysteresis instead. Enabling
152
+ one finishes any surface morph before layer publication. Coarsening does not height-morph.
153
+ World Explorer uses 180 ms for bare terrain; deterministic `freeze` captures disable morphing.
154
+
155
+ ## Measurement
156
+
157
+ World Explorer enables elevation workers, shared admission and shader warmup by default.
158
+ For controlled comparisons, query flags `elevationWorker=0`, `materialWorker=0`, `admission=0` and `warmup=0`
159
+ disable those individual paths (`worker=0` disables all generation workers). The performance
160
+ HUD's `data-graphics` JSON contains bounded distributions of decode/resample/mesh,
161
+ world-generation/preparation, assembly/upload/publication and frame CPU timing, plus admission
162
+ overrun counts. Queue delay is reported separately from work. Frame CPU does not include
163
+ all GPU execution; use the backend GPU timer and browser frame intervals as separate metrics.
164
+
165
+ Measure time to coverage, cold/loading and moving p95/p99, steady frame cost, draws, triangles,
166
+ retained bytes and image parity. Staging trades some time to full detail for smaller individual
167
+ publication stalls; compiled shaders and GPU buffers must be tested on a cold traversal too.