@bendyline/molen-tooling 0.0.12 → 0.0.13

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 (41) hide show
  1. package/dist/capture/harness.js +386 -318
  2. package/dist/capture/worldgen-preview.js +254 -254
  3. package/dist/docs-src/guide/adaptive-performance.md +30 -3
  4. package/dist/docs-src/guide/aircraft.md +125 -3
  5. package/dist/docs-src/guide/ambient-life.md +15 -1
  6. package/dist/docs-src/guide/boats.md +9 -4
  7. package/dist/docs-src/guide/boost-mode.md +64 -0
  8. package/dist/docs-src/guide/determinism.md +1 -1
  9. package/dist/docs-src/guide/dioramas.md +11 -4
  10. package/dist/docs-src/guide/earth-view.md +104 -4
  11. package/dist/docs-src/guide/entities.md +3 -0
  12. package/dist/docs-src/guide/graphics-performance.md +177 -13
  13. package/dist/docs-src/guide/input.md +34 -1
  14. package/dist/docs-src/guide/liveries.md +167 -0
  15. package/dist/docs-src/guide/livery-catalog.md +2659 -0
  16. package/dist/docs-src/guide/livery-gallery.md +2684 -0
  17. package/dist/docs-src/guide/medium-fi.md +13 -5
  18. package/dist/docs-src/guide/night-lighting.md +96 -0
  19. package/dist/docs-src/guide/project.md +1 -1
  20. package/dist/docs-src/guide/regional-world.md +3 -1
  21. package/dist/docs-src/guide/rendering-backends.md +6 -2
  22. package/dist/docs-src/guide/surface-rendering.md +12 -0
  23. package/dist/docs-src/guide/terrain.md +38 -0
  24. package/dist/docs-src/guide/vehicles.md +13 -1
  25. package/dist/docs-src/guide/worldgen.md +20 -5
  26. package/dist/docs-src/llms.txt +6 -1
  27. package/dist/docs-src/schemas/archstyle.md +29 -0
  28. package/dist/docs-src/schemas/components.md +776 -1
  29. package/dist/docs-src/schemas/regional-catalog.md +39 -0
  30. package/dist/docs-src/schemas/scatter.md +36 -0
  31. package/dist/docs-src/schemas/structure-placement-data.md +91 -0
  32. package/dist/docs-src/schemas/structure-placements.md +91 -0
  33. package/dist/docs-src/schemas/worldgen-batch.md +105 -0
  34. package/dist/templates/city-courier/gen/molen-types.ts +103 -1
  35. package/dist/templates/city-courier/scripts/molen-scripts.d.ts +102 -0
  36. package/dist/templates/index.json +17 -17
  37. package/dist/templates/skybound/gen/molen-types.ts +103 -1
  38. package/dist/templates/skybound/scripts/molen-scripts.d.ts +102 -0
  39. package/dist/templates/top-down-arena/scripts/molen-scripts.d.ts +102 -0
  40. package/dist/templates/top-down-arena/src/gen/molen-types.ts +103 -1
  41. package/package.json +12 -12
@@ -71,7 +71,59 @@ const viewer = await createViewer({
71
71
  ```
72
72
 
73
73
  The queue limits synchronous work started per animation frame. One oversized indivisible job
74
- runs alone and is reported as over budget. This is not a hard GPU/driver time bound. Texture
74
+ runs alone and is reported as over budget. `setLimits` changes the budget from the next frame on.
75
+ A job's `priority` is `'normal'`, `'background'` (only in budget normal jobs leave) or `'urgent'`
76
+ (ahead of normal jobs, in its own order): the terrain stream admits ground that way, and marks a
77
+ tile group `userData.admissionPriority = 'urgent'` so `prepareObject` queues its upload the same
78
+ way, because a tile's residency otherwise waited behind every building cell's upload. A root
79
+ marked `'background'` prepares only in budget normal jobs leave: World Explorer's practice
80
+ aircraft load with the world that way, as in the normal lane their ~200 jobs held terrain and
81
+ buildings back by most of a minute on a software renderer.
82
+
83
+ Main-thread work that runs as a tile's sources resolve is admitted too, because several tiles
84
+ arriving together stacked it into one late frame: decoding vector tiles (the package semantic
85
+ layers' `admission` option), a worldgen request's own preparation, prop batches, surface results
86
+ from a worker (their meshes and parked cars), and ambient aircraft models (`admission` on
87
+ `createAmbientRenderer` and `EarthAmbient`). A worldgen request is three jobs: the tile's content
88
+ hash, the generator's optional `prepare` step (its ground grid, sampled once for both of a tile's
89
+ passes) and the message to a worker; in one piece a dense town tile's took 8-16 ms. A job runs
90
+ first in a frame however long it takes, but after other work the queue starts a job only when the
91
+ recent time of its `label` fits the budget left, so two long jobs never share a frame.
92
+ Street surfaces (roads, markings, parked cars) are generated by `createTerrainSurfaceWorkerPool`,
93
+ which spreads them over the workers it is given. Earth hosts size the world generation pool with
94
+ `generationWorkers()` (a quarter of the logical cores, at most two) and the land cover and surface
95
+ pools with `surfaceWorkers()` (one each). Four per kind took the cores the frame needs, and a jet's
96
+ frames drew the same scene up to twice as slowly while a town streamed in; two land cover and two
97
+ surface workers beside generation still slowed some frames threefold over a dense city, while one
98
+ of each streamed a low flight just as fast and loaded the first view about a fifth later. New kinds of ambient proxy batch stay hidden until
99
+ their shaders are built, as figures and aircraft do.
100
+
101
+ A tile observer (`observeSemanticTiles`) is handed each decoded tile, and what it keeps stays on
102
+ the main heap that every garbage collection walks, in pauses that land on frames. Keep the fields
103
+ you read, not the tile: `EarthAmbient` keeps a tile's roads and places, `EarthAudioTerrain` only
104
+ the water of a tile too coarse to choose the ground underfoot, and wildlife compiles its habitat
105
+ into a few typed arrays and lets the tile go. A renderer that may rebuild a tile later keeps
106
+ `keepTerrainSemanticTile(tile)` instead: a call that answers the tile while it lives and otherwise
107
+ decodes it again from the packet it arrived as. Kept whole, these held 95 decoded tiles over
108
+ Kyoto, some 1.4 million of the objects each collection walks.
109
+
110
+ Three updates every object's world matrix each frame, hidden ones included. Hidden terrain tiles,
111
+ pooled ambient figures (each with its skeleton) and the explorer's parked-aircraft cockpits skip
112
+ that walk until they show again. Far detail stops drawing: a surface tile's signs, fixtures,
113
+ signal lenses, markings and parked cars past their draw distance (`updateDetail`, see
114
+ [surface rendering](surface-rendering.md)) and street props below 1.5 px (`vanishPixels`, see
115
+ [worldgen](worldgen.md)); at High over a town that cut a fifth of the draws. A visibility pass makes
116
+ its first ground cut whatever it costs, but only 4 ms more (`TerrainGroundCutoutController.update`'s
117
+ budget); the rest keep their current cut until the next stream update, so tiles arriving together
118
+ no longer hold one frame for every cut they need.
119
+
120
+ Earth hosts admit more while frames have time to spare: `createEarthAdmissionGovernor(backend)`
121
+ smooths each frame's main-thread work and, through `earthAdmission`, switches the queue to 8 MiB
122
+ of uploads a frame (and 4 ms of work on WebGL) below 10 ms of work, back to the renderer's
123
+ defaults above 13 ms. Each terrain tile and layer passes several admission jobs; at 2 MiB a frame
124
+ everything behind a building cell's upload waited 30 ms a job, and ground and buildings beneath a
125
+ jet appeared a second late. A render-bound frame (High detail over a town) loses a sixth of its
126
+ rate to the larger budget, so it keeps the defaults. This is not a hard GPU/driver time bound. Texture
75
127
  initialization, geometry preparation and async shader compilation use public Three facilities;
76
128
  shared resources share pending preparation promises. A cancelled tile cannot cancel another
77
129
  tile waiting on the same resource; queued work is dropped once every tile waiting for it has
@@ -80,7 +132,10 @@ are discarded.
80
132
  When `prepareObject` receives the parent the object will join, it evaluates LODs for the current
81
133
  camera and waits only for the selected levels. The other levels prepare in the queue's background
82
134
  lane (`priority: 'background'`), which runs only in budget that normal jobs leave, and are dropped
83
- if their mesh or geometry is disposed first. A mesh that swaps its own material (an instanced
135
+ if their mesh or geometry is disposed first. This includes geometry-switch LODs whose current
136
+ level is empty: invisible ground cover does not delay an aerial tile, and a later approach waits
137
+ for its preparation before revealing it. WebGPU preparation shares the visible-light list between
138
+ rendered frames instead of walking the whole scene for each mesh. A mesh that swaps its own material (an instanced
84
139
  detail switch's opaque and shadow-free twins) lists every material in `userData.materialVariants`,
85
140
  and the renderer sets `userData.materialReady(material)`, which the mesh's owner asks before
86
141
  switching. Until it returns true the owner keeps what it shows; the first question queues that
@@ -90,6 +145,38 @@ before preparing (the terrain stream marks layers and surfaces first). Resident
90
145
  quality replacements use the same preparation/publication path when supplied with
91
146
  `WorldgenRendererOptions.prepareObject` (enabled in World Explorer).
92
147
 
148
+ Preparation remembers each material's builds under what a program is built for besides the
149
+ material: the mesh's instancing, instance colors, skinning, attributes and morph targets, and the
150
+ scene's lights (which cast shadows), shadow map, fog, environment and output. A material built
151
+ before the sky's sun or its shadows existed is built again for the next mesh that draws it,
152
+ instead of counting as prepared and building mid-frame. A material changed in place needs its new
153
+ program first: `await renderer.prepareMaterialChange(current, next)` builds `next` for every kind
154
+ of prepared mesh that draws `current`, in the background lane, after which `current.copy(next)`
155
+ reuses the shared program. Progressive building materials do this through
156
+ `ResolvedMaterialSetOptions.prepareChange` (Earth hosts pass `prepareMaterialChange` to
157
+ `createEarthWorldgen`); upgrading a placeholder as its texture bake landed rebuilt every visible
158
+ building's shaders in one frame, seconds into a session.
159
+
160
+ On WebGL a warm-up waits for the programs its own compile built. three.js's `compileAsync` checks
161
+ each material's current program, which the next frame resets for whatever it drew last: a material
162
+ shared with drawn meshes (every building's wall) reported its ready program while the instanced
163
+ variant was still linking, and that variant's first draw waited for the link, 130 ms in flight.
164
+ Content that appears beside the viewer is prepared before it shows as well: building interiors
165
+ (`InteriorStreamingOptions.prepare`, which the Earth renderers pass their `prepareObject`; the
166
+ entrance covers stay until it settles), ambient pedestrians and ambient aircraft stay hidden until
167
+ their shaders are built.
168
+
169
+ Main-thread work that runs as tiles stream in beneath a fast aircraft is kept small. Ambient
170
+ aircraft parse and merge each type once into a template, in 3 ms slices, without the cabin (its
171
+ animated instruments stayed hundreds of moving nodes on every copy). Storefront lettering shares
172
+ its glyph vertices (`MeshBufferBuilder.addFlatMesh`). The worldgen tile cache keys a semantic tile
173
+ by a fast hash of its JSON (the cache never leaves the session) rather than SHA-256, which spent up
174
+ to 20 ms on a dense town tile. Ground cutouts read positions straight from their arrays and pass
175
+ over triangles whose corners share a side outside every opening, or that one of a convex opening's
176
+ edges separates from it. Parked cars bake from their template arrays, and
177
+ `EarthAudioTerrain.sample` skips map features whose bounds cannot come nearer than the nearest
178
+ found.
179
+
93
180
  For custom streamed geometry, call `await renderer.prepareObject(object, signal, parent)` before
94
181
  publication. Connect the same queue to terrain, which passes each layer's tile group as `parent`:
95
182
 
@@ -129,8 +216,19 @@ unless `materialCache=0`.
129
216
  Terrain and content bytes persist the same way through a `BlockCache` from
130
217
  `@bendyline/molen-pack/cache`, passed to `mountEarthView` as `byteCache` (see
131
218
  [the Earth view](earth-view.md)). It saves network and decompression time, not frame time: decoding
132
- and meshing still run for every tile the stream loads. Prefetching reads bytes only, so it never
133
- competes with tile construction on the main thread.
219
+ and meshing still run for every tile the stream loads. Long-horizon byte prefetch reads bytes only.
220
+ The Earth view also prepares nearby future tiles through the normal construction and GPU queues,
221
+ so aircraft can arrive over already prepared terrain and layers even without persistent caching.
222
+
223
+ A generation worker runs one tile at a time, in the order requested (the stream asks for what the
224
+ view needs most first); interleaved, every tile in flight finished late, the nearest with the
225
+ rest. It yields to its event loop every 8 ms of work, through a message channel, so a
226
+ `cancel` message gets through. It used to yield after every step with a zero `setTimeout`, which a
227
+ browser holds for at least 4 ms once timers nest: a dense tile took a second of wall time for a
228
+ fifth of a second of work. Streaming generators also pass `hashOutput: false`: the SHA-256 over
229
+ every output array (`WorldgenBatchOutput.hash`, for tooling and determinism checks) was a fifth
230
+ of a dense tile's generation, and nothing reads it there; compare outputs with
231
+ `hashWorldgenOutput`.
134
232
 
135
233
  World-generation workers also prepare building spatial cells and full/structural LOD indices.
136
234
  The renderer requests `renderCellsOnly` when using cell LODs so it does not retain a redundant
@@ -169,17 +267,26 @@ hysteresis band retains detail near boundaries. Pass `previousTiles` when using
169
267
  selector; the stream supplies its previous selection automatically. Pitched views use a
170
268
  conservative field of view to retain ground beneath the camera.
171
269
 
172
- Terrain requests preserve parent-first coverage and prioritize the camera view before the
173
- 12-degree turn margin at each level. Distance is measured to tile bounds rather than tile
174
- centers, so large tiles do not push nearby ground behind more distant requests. Semantic layers
270
+ Terrain requests establish coarse coverage first, then prioritize nearby visible ground before
271
+ distant refinement and the 12-degree turn margin. Ancestors precede equally distant descendants.
272
+ Distance is measured to tile bounds rather than tile centers, so large tiles do not push nearby
273
+ ground behind more distant requests. Semantic layers
175
274
  use the same view priority and prepare resident selected leaves before the terrain handoff,
176
- even while a slow sibling still holds the parent surface on screen. Selected leaves take
177
- precedence over temporary fallback detail. The existing layer concurrency and residency limits
178
- also bound this preparation. The previous terrain surface and its layers remain visible until
179
- all enabled, level-eligible layers of the replacement tiles have finished construction and GPU
180
- preparation. Surfaces, land use, roads and buildings then switch together; new terrain cannot
275
+ even while a slow sibling still holds the parent surface on screen. A replacement family shares
276
+ its displayed parent's view and distance priority: finishing its siblings releases prepared
277
+ nearby detail instead of leaving it hidden behind the old parent. Within that priority, the
278
+ replacement family finishes before finer leaves that it would keep hidden. The existing layer concurrency and residency limits
279
+ also bound this preparation. Layers that release the existing parent take priority over newly
280
+ eligible layers, so slow building work cannot occupy all slots ahead of a sibling's ground cover.
281
+ Multi-level refinements advance the whole replacement family together; one already prepared fine
282
+ leaf does not skip that intermediate handoff while its siblings still need it.
283
+ The previous terrain surface and its layers remain visible until
284
+ the layers they already display have finished construction and GPU preparation on their
285
+ replacements. Surfaces and inherited detail then switch together; new terrain cannot
181
286
  occlude the previous detail while its own detail is still loading. This applies to refinement and
182
- coarsening, including intermediate fallback tiles. Cached LODs reuse their prepared geometry.
287
+ coarsening, including intermediate fallback tiles. Newly eligible detail, such as buildings
288
+ absent from a coarse parent, arrives when prepared without holding other tiles' completed detail
289
+ behind that parent. Cached LODs reuse their prepared geometry.
183
290
 
184
291
  Previously unvisited ground can show its base surface immediately; its enabled layers appear
185
292
  together once settled. Empty layer results count as ready. Failed replacement layers preserve
@@ -188,6 +295,49 @@ layers can still appear after another layer fails. Hidden layers do not delay a
188
295
  stages scene geometry rather than rendering a second full-screen image, and retains old visual
189
296
  coverage under residency pressure until its replacement can safely take over.
190
297
 
298
+ `stream.update(view, futureViews)` additionally prepares the nearest refinement family at each
299
+ future position at the same selection quality, including semantic layers and GPU resources.
300
+ Future views are ordered by time; speculative preparation is capped at the larger of 16 tiles
301
+ or a quarter of `maxSelectedTiles`, and by spare residency. The 16-tile allowance keeps all four
302
+ approaching families possible even at the lowest render tier.
303
+ Earth predicts 2, 4, 8 and 12 seconds ahead, following a smoothed ground-track turn rate through
304
+ banks. Extrapolated turns stop at 90 degrees and travel at 4 km; teleports and entry animations
305
+ reset the predictor.
306
+ With at least three concurrent slots, up to half of each queue's existing capacity keeps future
307
+ preparation progressing while visible work remains queued. Upcoming tiles already in the normal
308
+ selection also receive this forward capacity; they need not be new speculative requests.
309
+ The remaining slots prioritize current coverage, and unused capacity can prepare more of the route.
310
+ Obsolete surface requests are cancelled on route changes. Redundant hidden ancestors become
311
+ reclaimable cache once finer terrain is resident; intermediates still needed for the current
312
+ replacement stay protected. Speculative tiles yield to displayed
313
+ coverage under memory pressure; oversized speculative tiles back off instead of rebuilding on
314
+ every update. `preloading` and `preloaded` in stream stats distinguish requested and ready leaves.
315
+
316
+ Earth's automatic render tiers retain at least four height and eight layer jobs, including at
317
+ Minimum: serializing landcover, water and buildings behind one job could never keep up with a
318
+ jet. Eight layer slots let a four-tile approach family prepare while current coverage advances.
319
+ Main-thread publication still uses the shared frame admission budget. Both Earth hosts use
320
+ `earthTerrainCacheBudget` to retain the device-sized terrain cache across quality changes.
321
+ `AdaptiveQualityController` can recover during continuous streaming when sustained frame cadence
322
+ and measured CPU **and** GPU work show headroom; loading without those measurements still blocks
323
+ upgrades. A moving world need not become completely idle before recovering from a costly startup.
324
+
325
+ Publications share one visibility pass: the tiles and layers admitted in a frame request it, and
326
+ it runs once after the admission flush, together with eviction. Reads that depend on what is
327
+ displayed (`displayedTiles`, `sampleHeight`, `isAreaReady`, `stats`, `pressure`) run a pending
328
+ pass first. A fast flight publishes dozens of tiles and layers per frame, and each had run the
329
+ whole handoff, layer, cutout and byte pass. The warm cache keeps most resident tiles hidden; a
330
+ hidden tile's subtree is left out of the scene's per-frame world-matrix walk (three walks hidden
331
+ objects too), and a rebase above it is applied when it shows again. `stats()` walks every resident
332
+ tile's objects for exact byte totals; a live panel passes `{ geometry: 'tracked' }` for the
333
+ retained estimate and visible-only counts. Ground cutouts stay on hidden tiles while their
334
+ openings remain, keep the source grid's indices for triangles away from every opening, and
335
+ re-count only the tiles whose ground they changed.
336
+
337
+ Height queries prefer displayed terrain and fall back to resident heights outside the visible
338
+ cut. An aircraft's center can pass behind its cockpit camera at a tile boundary; it must not wait
339
+ indefinitely for already cached ground to become visible before moving again.
340
+
191
341
  `morphMilliseconds` enables refinement height morphs for bare surfaces; call
192
342
  `stream.updateTransitions(nowMs)` in the frame loop. Vertices start on the actual parent
193
343
  triangles and finish at their exact target positions with fixed horizontal coordinates. Grounded
@@ -206,6 +356,13 @@ of 4096 triangles or more are walked through a per-geometry XZ index, built on f
206
356
  with the geometry, so a terrain tile or building cell contributes only the triangles that can reach
207
357
  the neighborhood instead of every triangle it holds.
208
358
 
359
+ A scan brings world matrices up to date only for what it visits (the root's chain, then each object
360
+ as the scan reaches it), and skips any group that declares an X/Z rectangle of its own frame as
361
+ `userData.walkFootprint` when the rectangle is out of reach: terrain tiles declare theirs, so a jet
362
+ that scans many times a second visits the few tiles beneath it rather than everything on screen.
363
+ Aircraft cabins (the spec's interior nodes) are `walkIgnore`: nobody walks into a cockpit, and
364
+ their parts made a walker's tree beside a parked aircraft take a third of a second to build.
365
+
209
366
  A subject that moves tens of meters a second would otherwise recenter the tree every few frames.
210
367
  Vehicles and aircraft use a wider `radius` with a larger `rebuildDistance`, and a `verticalRadius`
211
368
  with `update(root, x, z, y)` so the ground far below an airframe never enters the tree; while it
@@ -228,6 +385,13 @@ world-generation/preparation, assembly/upload/publication and frame CPU timing,
228
385
  overrun counts. Queue delay is reported separately from work. Frame CPU does not include
229
386
  all GPU execution; use the backend GPU timer and browser frame intervals as separate metrics.
230
387
 
388
+ On a laptop with two GPUs, check which one the browser renders with (the WebGL renderer string,
389
+ `WEBGL_debug_renderer_info`). Chrome on Windows may use the integrated GPU whatever a page asks
390
+ for; on one AMD Radeon 880M it froze presentation for about 200 ms every ten seconds, on an empty
391
+ page too, while the same machine's discrete GPU drew without a pause. Chrome's
392
+ `#force-high-performance-gpu` flag, or the browser's entry in Windows' graphics settings, selects
393
+ the discrete GPU.
394
+
231
395
  Measure time to coverage, cold/loading and moving p95/p99, steady frame cost, draws, triangles,
232
396
  retained bytes and image parity. Staging trades some time to full detail for smaller individual
233
397
  publication stalls; compiled shaders and GPU buffers must be tested on a cold traversal too.
@@ -22,7 +22,10 @@ See the [Gamepad specification](https://www.w3.org/TR/gamepad/) and
22
22
 
23
23
  `input.update()` obtains fresh snapshots; `input.devices()` returns detached copies with `id`,
24
24
  `index`, `mapping`, raw `axes`, and raw `buttons` (`pressed` and `value`). Poll every animation
25
- frame in a custom host. `mountExperience`/`applyInputRules` poll automatically (default 50 ms;
25
+ frame in a custom host. With the default adapter and an event `target`, `update()` calls
26
+ `navigator.getGamepads()` only once the target has reported `gamepadconnected` (or a poll found a
27
+ device), and otherwise every 120th update: the call blocked Chrome's main thread for several
28
+ milliseconds a frame on Windows with no gamepad attached. `mountExperience`/`applyInputRules` poll automatically (default 50 ms;
26
29
  use `pollMs: 16` for more responsive controls). `gamepadStatus` reports `available`, `unavailable`,
27
30
  or `blocked`. An available API can still have no detected devices.
28
31
 
@@ -212,3 +215,33 @@ Style fieldsets and `[data-binding="key"|"button"|"axis"]` rows under `className
212
215
  includes `src/` so a host can copy/modify the component. A completely custom editor can use
213
216
  `getProfile`, `defineProfile`, `devices`, `suspend`, and the exported `InputProfile` types with no
214
217
  React dependency. No storage writes or permission prompts occur unless the host supplies them.
218
+
219
+ ## Navigation controller settings
220
+
221
+ World Explorer and the Earth view sample expose **Controllers (N)** beside their navigation
222
+ buttons. Open it, press a controller button if no device is listed, then move the stick and read
223
+ the numbered axes. Choose the relevant profile (`pilot` for an aircraft), assign axes and buttons,
224
+ and use **Reverse axis** or **Dead zone** as needed. Assign a throttle slider to
225
+ **Throttle / collective (absolute lever)**; its position sets power directly. **Done** resumes
226
+ gameplay; **Save** remembers all profiles in this browser. **Reset profile** restores the default
227
+ gamepad layout; save again to retain the reset. Keyboard controls remain available.
228
+
229
+ Custom navigation hosts can mount the same framework-free editor:
230
+
231
+ ```ts
232
+ import { createNavigationControls } from '@bendyline/molen-client/navigation';
233
+
234
+ const controls = createNavigationControls(input, {
235
+ container: toolbar,
236
+ focusTarget: canvas,
237
+ storageKey: 'my-app:controls:v1', // optional; enables Save and restores saved profiles
238
+ });
239
+ // On host disposal: controls.dispose();
240
+ ```
241
+
242
+ Here `input` is the host's `NavigationInputSource`. Continue calling `input.read(dt)` every frame.
243
+ The modal editor suspends gameplay while polling devices, then restores canvas focus on close.
244
+ Mappings are saved by browser device ID; identical devices can share an ID. The selected editor
245
+ profile does not change the gameplay mode. `nav-power` uses a `unit` axis; the optional
246
+ `NavigationInput.pilot.power` is absent while that axis is disconnected or input is suspended,
247
+ so hosts can retain the existing throttle setting. Zero is a valid connected lever reading.
@@ -0,0 +1,167 @@
1
+ # Vehicle liveries
2
+
3
+ Liveries combine reusable paint regions and surface markings on one model. Cars, aircraft,
4
+ RVs, boats, cycles and transit use the same `livery` component. The `molen.entities` content
5
+ pack includes two or three photo-based choices for each of its 192 vehicle types.
6
+
7
+ Browse the [visual livery gallery](livery-gallery.md) for comparisons and evidence coverage,
8
+ or the [complete livery catalog](livery-catalog.md) for every vehicle, choice and source link.
9
+
10
+ ## Choose a livery
11
+
12
+ Fetch and bind the entities pack as described in [reusable entities](entities.md). Read the
13
+ type's `livery.variants` for its ids, labels, paint recipes and provenance. Override only
14
+ `selected` when instantiating the type:
15
+
16
+ ```json
17
+ {
18
+ "id": "aircraft",
19
+ "type": "molen.entities.aircraft.f_16b",
20
+ "components": {
21
+ "transform": { "pos": [0, 0, 0] },
22
+ "livery": { "selected": "danish-et-612" }
23
+ }
24
+ }
25
+ ```
26
+
27
+ The F-16B choices are `danish-et-612`, `usaf-mc-gray` and `nsawc-07-blue-camouflage`.
28
+ The Danish scheme places roundels behind the canopy, the ET-612 serial aft of them, and small
29
+ flags high on the fin, using photographs of both sides. The other choices adapt photographed
30
+ USAF and NSAWC F-16 finishes to the two-seat model. Each recipe records its approximations
31
+ and omitted details. There is no F-4 model in this pack.
32
+
33
+ Change a scene entity from a script with `molen.patch('aircraft', 'livery',
34
+ { selected: 'danish-et-612' })`. The client retains the model and replaces its appearance;
35
+ instances sharing a GLB keep independent liveries. Removing the component restores the
36
+ original materials. Selection is serializable and replays with the rest of the entity data;
37
+ it does not change vehicle physics.
38
+
39
+ Earth hosts can use the same choices:
40
+
41
+ ```ts
42
+ const id = view.vehicles.spawn({
43
+ type: 'molen.entities.vehicle.winnebago_view_2022',
44
+ latitude: 47.61, longitude: -122.33, heading: 0,
45
+ livery: 'bay-mist-ii-study',
46
+ });
47
+ const choices = view.vehicles.liveries(id);
48
+ view.vehicles.setLivery(id, 'silver-and-charcoal-study');
49
+ ```
50
+
51
+ Earth preserves the selection across model unloading and terrain frame changes. Its lower-level
52
+ `EarthVehicles` and `EarthAircraft` APIs also accept a `livery` spawn option and expose
53
+ `setLivery(id, selected)`. A custom car `color` overrides the selected recipe's `body` paint;
54
+ choosing another livery replaces that override. Distant dimension-only traffic proxies continue
55
+ to show their ordinary body color; detailed markings appear on loaded models.
56
+
57
+ ## Author model bindings once
58
+
59
+ A component owns three layers:
60
+
61
+ | Layer | Responsibility |
62
+ | --- | --- |
63
+ | `slots` | Model-owned semantic names such as `body`, `accent`, `roof`; exact GLB material names and an optional named subtree |
64
+ | `anchors` | Model-owned sticker projectors, attached to a slot's bounds in the model's rest pose |
65
+ | `variants` | Livery-owned colors, camouflage, artwork and provenance referencing those names |
66
+
67
+ Keep glass, lights, tires, cabin surfaces and paint in separate materials. Do not put a paint
68
+ slot on a material shared with the cockpit. A model revision can rename or split meshes,
69
+ change topology or replace its UV layout without rewriting the recipes. Preserve material
70
+ names, or update the slot binding once. If the shape changes substantially, review and adjust
71
+ its anchors once. The renderer reports missing surfaces and projectors that miss the model.
72
+
73
+ ```json
74
+ {
75
+ "selected": "blue",
76
+ "slots": { "body": { "materials": ["body-paint"] } },
77
+ "anchors": {
78
+ "left-door": {
79
+ "slot": "body",
80
+ "position": [1, 0.5, 0.5],
81
+ "size": [0.2, 0.08, 0.06],
82
+ "rotation": [0, 1.5707963267948966, 0]
83
+ }
84
+ },
85
+ "variants": [{
86
+ "id": "blue",
87
+ "label": "Blue with ivory stripe",
88
+ "provenance": { "kind": "original", "note": "Original design.", "references": [] },
89
+ "paints": { "body": { "color": "#557990", "roughness": 0.4, "metalness": 0.2 } },
90
+ "markings": [{
91
+ "anchor": "left-door",
92
+ "graphic": {
93
+ "label": "Ivory stripe",
94
+ "shapes": [{ "color": "#e8e5d9", "points": [[0, 0.3], [1, 0.3], [1, 0.7], [0, 0.7]] }]
95
+ }
96
+ }]
97
+ }]
98
+ }
99
+ ```
100
+
101
+ Anchor positions are fractions of the selected surface bounds, measured from the minimum
102
+ corner. Size is width, height and depth as fractions of the bounds' longest dimension.
103
+ Rotation is XYZ Euler radians; the projector's +Z points out of the surface. A +X-side
104
+ projector uses `[0, PI/2, 0]`, a -X-side projector `[0, -PI/2, 0]`, and a top projector
105
+ `[-PI/2, 0, 0]`. Author each side separately so lettering reads correctly. Bind a slot to a
106
+ named subtree when a wing, mirror or other protrusion would make whole-body bounds unsuitable.
107
+
108
+ Markings clip to matching materials, follow the actual geometry, and remain attached to moving
109
+ rigid parts. Projection depth should reach only the intended panel. Thin two-sided panels are
110
+ supported. Skinned and morph-deformed surfaces are reported as unsupported. Livery updates use
111
+ the original bind pose even if a door or control surface has moved since loading.
112
+
113
+ ## Paint and artwork
114
+
115
+ Paint replaces the base color map and material tint; vertex colors and original normal,
116
+ metalness, roughness and AO maps survive. This retains trim masks on older vehicles that share
117
+ a paint material with their tires. An empty `paints` object preserves the original finish. Camouflage adds a seeded,
118
+ low-frequency pattern using a private model-space UV channel:
119
+
120
+ ```json
121
+ {
122
+ "color": "#ffffff",
123
+ "camouflage": { "colors": ["#4f5e49", "#79815a", "#ac9973"], "scale": 1, "seed": 17 }
124
+ }
125
+ ```
126
+
127
+ This is box projection with seams at changes in dominant face direction, not a reproduction
128
+ of an aircraft's official paint masking diagram. The pattern ignores authored UVs and stays
129
+ fixed on animated parts. Preserve separate upper/lower paint slots for precise two-tone work.
130
+ The renderer chooses a UV channel unused by the model's textures. If all four channels are
131
+ occupied, it reports a warning and uses the base paint color to preserve those texture bindings.
132
+
133
+ Graphics are ordered colored polygons in a 0–1 square, Y up. They are rasterized to a small
134
+ sRGB texture, with no font or network dependency at runtime. Roundels, stars, bars, stripes,
135
+ swoops and labels use this same format. For labels, outline text using `buildTextMesh` from
136
+ `@bendyline/molen-materials/text` and a font library; normalize its triangles into the square
137
+ while preserving the intended aspect ratio. See [fonts and lettering](typography.md).
138
+ The `graphic.label` field describes artwork for tools; it does not itself draw text.
139
+
140
+ Custom three.js hosts call `applyLivery(modelInstance, data)` from `@bendyline/molen-client`.
141
+ Read its `warnings`, then call the returned `dispose()` before selecting another recipe or
142
+ disposing the model. It restores original materials and geometry and frees only its own
143
+ resources. `createVehicleVisual` and `createAircraftVisual` accept the component as a third
144
+ argument and expose `setLivery(data)` to manage this lifetime for you.
145
+ An explicit livery takes precedence over the legacy `vehicle.color`; put custom colors in its
146
+ paint recipe. Earth handles that conversion for its `color` and `setColor` APIs and restores
147
+ the type's original recipe when a named livery is selected again.
148
+
149
+ ## Reference evidence and the fleet
150
+
151
+ Every variant records `provenance.kind` (`photo`, `inspired` or `original`), an honest scope
152
+ note and source URLs. `photo` and `inspired` require references. Do not label a proposed
153
+ palette as a real unit or factory option without supporting evidence. Source photographs
154
+ are references for original artwork; they are not shipped as textures.
155
+
156
+ All 385 fleet choices link real-world photographs. The [gallery](livery-gallery.md) compares
157
+ every choice and records its scope, while the [catalog](livery-catalog.md#source-index) lists
158
+ source attribution. They use `inspired` provenance because paint values, model variants,
159
+ camouflage masks and simplified artwork are adaptations rather than exact replicas.
160
+
161
+ In the engine repository, `content/entities/source/liveries.json` is the editable catalog.
162
+ `generate-models.mjs` validates and merges it into the runtime type libraries; the individual
163
+ base-model definitions stay independent. Copy the `livery` component along with a source
164
+ bundle when extracting a standalone vehicle. `generate-liveries.mjs` validates photo references,
165
+ coverage and model bindings, then propagates the authored catalog. It does not invent fallback
166
+ palettes or overwrite recipes. Ordinary model builds only consume the catalog, so geometry work
167
+ cannot erase livery edits. The shared `scenes/liveries.scene.json` provides a small scene for inspection.