@bendyline/molen-client 0.0.9 → 0.0.11

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.
@@ -8,8 +8,12 @@ interface AdmissionOptions {
8
8
  bytes?: number;
9
9
  signal?: AbortSignal;
10
10
  label?: string;
11
- /** Background jobs run only in frame budget that no normal job is waiting for. */
12
- priority?: "normal" | "background";
11
+ /**
12
+ * Background jobs run only in frame budget that no normal job is waiting for. Urgent jobs run
13
+ * before normal ones, in their own order: small work the view is visibly waiting on, such as
14
+ * terrain ground, which otherwise queued behind every building cell's upload.
15
+ */
16
+ priority?: "urgent" | "normal" | "background";
13
17
  }
14
18
  interface AdmissionSample {
15
19
  label: string;
@@ -40,18 +44,31 @@ declare class FrameAdmissionQueue implements SceneAdmission {
40
44
  private disposed;
41
45
  private readonly clock;
42
46
  private readonly schedule;
43
- private readonly maxMs;
44
- private readonly maxBytes;
45
- private readonly maxJobs;
47
+ private maxMs;
48
+ private maxBytes;
49
+ private maxJobs;
50
+ /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
51
+ private readonly expected;
46
52
  constructor(options?: FrameAdmissionOptions);
53
+ /**
54
+ * Change the per-frame budget from the next frame on; omitted limits keep their values. A host
55
+ * can admit more when frames have time to spare (an adaptive quality tier, say).
56
+ */
57
+ setLimits(limits: Pick<FrameAdmissionOptions, "maxMilliseconds" | "maxBytes" | "maxJobs">): void;
47
58
  run<T>(task: () => T, options?: AdmissionOptions): Promise<T>;
48
59
  /**
49
60
  * Callers keep the promise (preparation caches do, keyed by long-lived resources); the job holds
50
61
  * the task and everything it captured. Only a queued job may stay reachable from its promise.
51
62
  */
52
63
  private forget;
53
- /** Move a still-queued background job to the normal lane, behind the jobs already there. */
54
- promote(promise: Promise<unknown>): void;
64
+ /**
65
+ * Move a still-queued background job to the normal lane, behind the jobs already there, or with
66
+ * `front` ahead of them: for work a frame is waiting on, such as a material an object holds off
67
+ * switching to until it is prepared.
68
+ */
69
+ promote(promise: Promise<unknown>, options?: {
70
+ front?: boolean;
71
+ }): void;
55
72
  get pending(): number;
56
73
  private request;
57
74
  /** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
@@ -182,6 +199,13 @@ declare class SkyVisual {
182
199
  private catalog;
183
200
  private readonly palette;
184
201
  private lastTime;
202
+ /**
203
+ * What the dome's colors and the stars were last written for. The sun and the sky turn a
204
+ * quarter of a degree a minute: rewriting the dome and every star each second cost a frame
205
+ * 3-5 ms for changes far below a pixel, so they are rewritten once those changes could show.
206
+ */
207
+ private drawnDome;
208
+ private drawnStars;
185
209
  private cloudAttenuation;
186
210
  private currentFrame;
187
211
  private currentReflections;
@@ -285,6 +309,19 @@ interface ShadowFocus {
285
309
  radius: number;
286
310
  }
287
311
  //#endregion
312
+ //#region src/three/webgpu-ambient-occlusion.d.ts
313
+ interface AmbientOcclusionOptions {
314
+ /** World-space sampling radius, meters: about a wall-to-ground crease. */
315
+ radius?: number;
316
+ /** Share of the occlusion applied, 0–1. Sunlit faces keep most of their direct light. */
317
+ strength?: number;
318
+ /**
319
+ * View distance, meters, past which no occlusion is computed; it fades out over the last
320
+ * third. Farther creases are under a pixel, and skipping them is most of an aerial view.
321
+ */
322
+ reach?: number;
323
+ }
324
+ //#endregion
288
325
  //#region src/three/webgpu-scene-optimizer.d.ts
289
326
  /**
290
327
  * Uses Three render bundles and a pinned, version-aware instance upload adapter.
@@ -306,6 +343,8 @@ declare class WebGpuSceneOptimizer {
306
343
  private readonly matrixSamples;
307
344
  private readonly restoreRefresh;
308
345
  private materialSamples;
346
+ /** The render each material last refreshed a replayed object in; see the constructor. */
347
+ private readonly refreshed;
309
348
  private readonly videoMaterials;
310
349
  private readonly materialStates;
311
350
  constructor(renderer: WebGPURenderer);
@@ -427,6 +466,16 @@ declare class Renderer {
427
466
  private warmupMaterial;
428
467
  private readonly warmedPrograms;
429
468
  private readonly warmedMeshes;
469
+ /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
470
+ private readonly materialMeshes;
471
+ /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
472
+ private preparationLights;
473
+ /**
474
+ * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
475
+ * `prepareVariants`.
476
+ */
477
+ private readonly warmedVariants;
478
+ private readonly variantInterests;
430
479
  private readonly warmups;
431
480
  /** Deferred meshes whose preparation has not settled, with the interest that can promote it. */
432
481
  private readonly deferredMeshes;
@@ -461,8 +510,16 @@ declare class Renderer {
461
510
  private readonly optimizer;
462
511
  private activeSky;
463
512
  private readonly reflections;
464
- /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
465
- private readonly webgpuShadowLights;
513
+ private occlusionOptions;
514
+ private occlusion;
515
+ private occlusionLoad;
516
+ private occlusionSuspended;
517
+ /** Sun lights that have cast shadows: 'off' parks their maps; see setShadowQuality. */
518
+ private readonly shadowLights;
519
+ /** Kinds of shadow caster prepared so far (WebGL); see noteShadowCaster. */
520
+ private readonly casterVariants;
521
+ /** Whether the shadow pass has drawn shadowCasterWarmup's casters (WebGL). */
522
+ private shadowCastersWarmed;
466
523
  private readonly reflectionClearColor;
467
524
  private starCatalog;
468
525
  private activeWeather;
@@ -484,7 +541,12 @@ declare class Renderer {
484
541
  * moves: an orbit target, a walker, a car. Shadows must be on (`setShadowQuality`).
485
542
  */
486
543
  setShadowFocus(focus: ShadowFocus | undefined): void;
487
- /** Turn sun shadows on at a map resolution, or off, without rebuilding the environment. */
544
+ /**
545
+ * Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a
546
+ * light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader
547
+ * keeps the shadow inputs it was built with: a host that turns shadows on once before its first
548
+ * frame can then switch them freely (adaptive quality tiers do) without rebuilding a shader.
549
+ */
488
550
  setShadowQuality(quality: ShadowQuality): void;
489
551
  /** WebGL PCF shadow lookups against a reversed depth buffer; see focusDirectionalShadow. */
490
552
  private webglReversedPcfShadows;
@@ -544,10 +606,34 @@ declare class Renderer {
544
606
  * other levels afterwards in the background, so publication waits only for what can be seen.
545
607
  * Queued work is cancelled once every caller waiting for it has aborted, and background work
546
608
  * once its mesh or geometry is disposed.
609
+ *
610
+ * `root.userData.admissionPriority` admits the root's own work as `'urgent'` (ahead of normal
611
+ * work) or `'background'` (only in budget normal work leaves: content nobody waits on yet).
547
612
  */
548
613
  prepareObject(root: THREE.Object3D, signal?: AbortSignal, parent?: THREE.Object3D): Promise<void>;
614
+ /**
615
+ * Build `next`'s shaders for every kind of prepared mesh that draws `current`, before the caller
616
+ * copies `next` into `current`: a progressive material upgrading its placeholder in place once a
617
+ * texture bake lands. Three shares a program between materials built alike, so the upgraded
618
+ * placeholder draws with it at once. Otherwise every mesh showing the placeholder built its new
619
+ * shaders in the next frame, together: seconds of frozen flight shortly after loading. The work
620
+ * runs in the background lane. Keep `next` alive while `current` uses the shared program.
621
+ */
622
+ prepareMaterialChange(current: THREE.Material, next: THREE.Material): Promise<void>;
549
623
  private prepareMesh;
550
624
  private flushWebGlBatches;
625
+ /**
626
+ * A mesh that swaps its own material, as an instanced detail switch swaps in an opaque twin for
627
+ * its coarser levels, lists every material in `userData.materialVariants`. Each needs its own
628
+ * shader build, which the first frame to draw it would otherwise make mid-frame: in flight a whole
629
+ * view of trees changed level at once and built their twins in one frame, for most of a second.
630
+ * `userData.materialReady(material)` tells the mesh's owner whether one is ready. Until it is, the
631
+ * owner keeps what it shows; asking queues its build ahead of other work. Most batches never
632
+ * change level, so a variant is built only once its mesh asks for it.
633
+ */
634
+ private prepareVariants;
635
+ /** Whether `mesh` can draw `material` without building it mid-frame; builds it first if not. */
636
+ private variantReady;
551
637
  /** Queue one cancellable warm-up job in the lane's admission priority. */
552
638
  private warmup;
553
639
  /**
@@ -564,7 +650,34 @@ declare class Renderer {
564
650
  /** Nobody waits any longer: drop the job from every cache first, then from the queue. */
565
651
  private cancelWarmup;
566
652
  private rememberPreparation;
653
+ /**
654
+ * While WebGL shadows are parked the shadow pass never runs, so no depth program is built for
655
+ * the casters arriving meanwhile, and the first frame with shadows back built every one of them
656
+ * at once (an adaptive tier change, mid-flight). A caster of a kind the map has not drawn yet
657
+ * asks the parked map for one render, which builds its depth program as it streams in. The
658
+ * kinds follow three's shadow pass: one depth material, cloned for alpha-tested maps,
659
+ * displacement or clipping, built per mesh kind and side.
660
+ */
661
+ private noteShadowCaster;
662
+ /** Build `mesh` for the frame's draw target, drawn with `material` when given. */
567
663
  private compileMesh;
664
+ /**
665
+ * Three's compileAsync, but waiting for the programs built for this mesh. Three polls each
666
+ * material's current program, which the next frame resets for whatever it drew last: a
667
+ * material shared with drawn meshes (every building's wall) reported its ready program while
668
+ * the instanced variant was still linking, and that variant's first draw waited for the link
669
+ * mid-frame (130 ms in flight).
670
+ */
671
+ private compileWebGl;
672
+ /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
673
+ private sceneLights;
674
+ /**
675
+ * What a lit program is built for besides its material and mesh: the scene's lights and which
676
+ * cast shadows, the shadow map, fog, environment and output. Warm-ups are remembered under it.
677
+ * Without it a material built before the sky's sun, its shadows or its reflections existed
678
+ * counted as prepared, and the next tile drawing it built the real program mid-frame.
679
+ */
680
+ private programState;
568
681
  private prepareWebGlGeometries;
569
682
  render(): void;
570
683
  /**
@@ -579,6 +692,30 @@ declare class Renderer {
579
692
  */
580
693
  private hideReflectedAmbient;
581
694
  private renderScene;
695
+ /**
696
+ * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
697
+ * per side): the shadow pass builds a depth program for each kind of caster the first time it
698
+ * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
699
+ * shadow pass keeps its depth materials, so the programs stay built; three keys them by the
700
+ * scene's light counts too, so a light the renderer shows or hides warms them again.
701
+ */
702
+ private shadowCasterWarmup;
703
+ private optimized;
704
+ /**
705
+ * Screen-space ambient occlusion on the WebGPU backend (a no-op on WebGL): creases, corners and
706
+ * the ground around buildings and trees darken a little, as indirect light cannot reach them.
707
+ * The frame then renders through a node pipeline; frames draw directly while it compiles.
708
+ */
709
+ setAmbientOcclusion(enabled: boolean, options?: AmbientOcclusionOptions): void;
710
+ /**
711
+ * Skip the occlusion computation while keeping ambient occlusion set up: the frame still draws
712
+ * into its target, and the image is copied out unshaded. Each object's shaders are built for
713
+ * one draw target, so turning occlusion off and on again (`setAmbientOcclusion`) built every
714
+ * object in view again, mid-frame, when the target changed; suspending changes nothing there.
715
+ */
716
+ suspendAmbientOcclusion(suspended: boolean): void;
717
+ /** The occlusion pass for the current camera, building one in the background when needed. */
718
+ private currentOcclusion;
582
719
  /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
583
720
  createRenderGroup(): THREE.Group;
584
721
  /** Last completed visible frame, excluding offscreen resource preparation. */
@@ -0,0 +1,24 @@
1
+ import * as THREE from "three";
2
+ import { FontLibrary, FontLibrary as FontLibrary$1, TextLayoutOptions, TextLayoutOptions as TextLayoutOptions$1, TextMeshData, VectorFont, VectorFont as VectorFont$1, VectorGlyph, buildTextMesh, loadFontLibrary, vectorFontSchema } from "@bendyline/molen-materials/text";
3
+ import { FontData } from "three/addons/loaders/FontLoader.js";
4
+
5
+ //#region src/text.d.ts
6
+ interface CompileVectorFontOptions {
7
+ id: string;
8
+ /** Explicit subset, including ? and space. Default: every character in the typeface. */
9
+ characters?: string;
10
+ weight?: number;
11
+ style?: "normal" | "italic";
12
+ /** Segments per outline curve, 2–32; default 6 for medium-fi signage. */
13
+ curveSegments?: number;
14
+ /** Optional pair adjustments in em units from the source font's kerning tables. */
15
+ kerning?: Record<string, number>;
16
+ }
17
+ /** Compile typeface JSON (including TTFLoader output) once, then store the result in a pack.
18
+ * Node and browser compatible; no canvas or OS font dependency. Does not fetch a font.
19
+ */
20
+ declare function compileVectorFont(data: FontData, options: CompileVectorFontOptions): VectorFont$1;
21
+ /** Caller owns/disposes the geometry and chooses its material, color, transform and batching. */
22
+ declare function createTextGeometry(text: string, fonts: FontLibrary$1, options?: TextLayoutOptions$1): THREE.BufferGeometry;
23
+ //#endregion
24
+ export { CompileVectorFontOptions, type FontLibrary, type TextLayoutOptions, type TextMeshData, type VectorFont, type VectorGlyph, buildTextMesh, compileVectorFont, createTextGeometry, loadFontLibrary, vectorFontSchema };
package/dist/text.mjs ADDED
@@ -0,0 +1,62 @@
1
+ import * as THREE from "three";
2
+ import { buildTextMesh, buildTextMesh as buildTextMesh$1, loadFontLibrary, vectorFontSchema, vectorFontSchema as vectorFontSchema$1 } from "@bendyline/molen-materials/text";
3
+ import { Font } from "three/addons/loaders/FontLoader.js";
4
+ //#region src/text.ts
5
+ /** Three.js adapter and offline outline compiler for the shared font engine. */
6
+ /** Compile typeface JSON (including TTFLoader output) once, then store the result in a pack.
7
+ * Node and browser compatible; no canvas or OS font dependency. Does not fetch a font.
8
+ */
9
+ function compileVectorFont(data, options) {
10
+ const segments = options.curveSegments ?? 6;
11
+ if (!Number.isInteger(segments) || segments < 2 || segments > 32) throw new Error("curveSegments must be 2–32");
12
+ const font = new Font(data);
13
+ const glyphs = {};
14
+ const round = (value) => Math.round(value * 1e6) / 1e6;
15
+ for (const char of new Set(Array.from(options.characters ?? Object.keys(data.glyphs).join("")))) {
16
+ const glyph = data.glyphs[char];
17
+ if (!glyph) continue;
18
+ const geometry = new THREE.ShapeGeometry(font.generateShapes(char, 1), segments);
19
+ const position = geometry.getAttribute("position");
20
+ const points = [];
21
+ for (let i = 0; i < position.count; i++) points.push(round(position.getX(i)), round(position.getY(i)));
22
+ glyphs[char] = {
23
+ advance: round(glyph.ha / data.resolution),
24
+ positions: points,
25
+ indices: Array.from(geometry.index?.array ?? [])
26
+ };
27
+ geometry.dispose();
28
+ }
29
+ const metrics = data;
30
+ return vectorFontSchema$1.parse({
31
+ format: "molen/vector-font@1",
32
+ id: options.id,
33
+ family: data.familyName,
34
+ weight: options.weight ?? 400,
35
+ style: options.style ?? "normal",
36
+ ascent: round((metrics.ascender ?? data.boundingBox.yMax) / data.resolution),
37
+ descent: round((metrics.descender ?? data.boundingBox.yMin) / data.resolution),
38
+ lineHeight: round(((metrics.ascender ?? data.boundingBox.yMax) - (metrics.descender ?? data.boundingBox.yMin)) / data.resolution),
39
+ glyphs,
40
+ kerning: options.kerning ?? {}
41
+ });
42
+ }
43
+ /** Caller owns/disposes the geometry and chooses its material, color, transform and batching. */
44
+ function createTextGeometry(text, fonts, options = {}) {
45
+ const data = buildTextMesh$1(text, fonts, options);
46
+ const geometry = new THREE.BufferGeometry();
47
+ geometry.setAttribute("position", new THREE.BufferAttribute(data.positions, 3));
48
+ geometry.setIndex(new THREE.BufferAttribute(data.indices, 1));
49
+ geometry.computeVertexNormals();
50
+ geometry.computeBoundingBox();
51
+ geometry.computeBoundingSphere();
52
+ geometry.userData.textLayout = {
53
+ text: data.text,
54
+ width: data.width,
55
+ height: data.height,
56
+ missingGlyphs: data.missingGlyphs,
57
+ truncated: data.truncated
58
+ };
59
+ return geometry;
60
+ }
61
+ //#endregion
62
+ export { buildTextMesh, compileVectorFont, createTextGeometry, loadFontLibrary, vectorFontSchema };
@@ -1,4 +1,4 @@
1
- import { n as ModelSignals, t as ModelSignalVisual } from "./model-signals-DVlLyP-w.mjs";
1
+ import { n as ModelSignals, t as ModelSignalVisual } from "./model-signals-BpeXhsim.mjs";
2
2
  import { VehicleInteriorSpec, VehicleSpec } from "@bendyline/molen-schema";
3
3
  import { Object3D } from "three";
4
4
 
@@ -1,10 +1,13 @@
1
- import { t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.mjs";
1
+ import { t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
2
2
  //#region src/vehicle-interior.ts
3
3
  /** Vehicle convenience wrapper around the platform's model-signal binding system. */
4
4
  function createVehicleInteriorVisual(model, spec) {
5
5
  const visual = createModelSignalVisual(model, spec);
6
6
  return {
7
7
  ...visual,
8
+ get missingSignals() {
9
+ return visual.missingSignals;
10
+ },
8
11
  missingNodes: [...new Set([...spec.nodes.filter((name) => !model.getObjectByName(name)), ...visual.missingNodes])]
9
12
  };
10
13
  }
@@ -1,15 +1,16 @@
1
- import { t as ModelSignalVisual } from "./model-signals-DVlLyP-w.mjs";
2
- import { a as VehicleCameraPose, i as VehicleCameraOptions, n as VehicleInteriorVisual, o as vehicleCameraPose, r as createVehicleInteriorVisual, t as VehicleInteriorSignals } from "./vehicle-interior-GWcXnvXS.mjs";
3
- import { VehicleData, VehiclePlacement } from "@bendyline/molen-schema";
1
+ import { t as ModelSignalVisual } from "./model-signals-BpeXhsim.mjs";
2
+ import { a as VehicleCameraPose, i as VehicleCameraOptions, n as VehicleInteriorVisual, o as vehicleCameraPose, r as createVehicleInteriorVisual, t as VehicleInteriorSignals } from "./vehicle-interior-BgcC750p.mjs";
3
+ import { LiveryData, VehicleData, VehiclePlacement } from "@bendyline/molen-schema";
4
4
  import * as THREE from "three";
5
5
 
6
6
  //#region src/vehicles.d.ts
7
7
  interface VehicleVisual {
8
+ setLivery(data: LiveryData | undefined): void;
8
9
  object: THREE.Object3D;
9
10
  interior?: VehicleInteriorVisual;
10
11
  /** The visual's exterior `animation` bindings, posed from the same signals as the interior. */
11
12
  animation?: ModelSignalVisual;
12
- update(steer: number, wheelAngle: number, signals?: VehicleInteriorSignals): void;
13
+ update(steer: number, wheelAngle: number, signals?: VehicleInteriorSignals, timeSeconds?: number): void;
13
14
  dispose(): void;
14
15
  }
15
16
  /**
@@ -26,7 +27,7 @@ declare function createVehicleVisual(model: THREE.Object3D, vehicle: Pick<Vehicl
26
27
  length: number;
27
28
  cycle?: unknown;
28
29
  };
29
- }): VehicleVisual;
30
+ }, livery?: LiveryData): VehicleVisual;
30
31
  /** The dimensions a vehicle proxy is built from (a `VehicleSpec` satisfies it). */
31
32
  interface VehicleProxyDimensions {
32
33
  width: number;
package/dist/vehicles.mjs CHANGED
@@ -1,5 +1,6 @@
1
- import { t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.mjs";
2
- import { t as createVehicleInteriorVisual } from "./vehicle-interior-vJQsRLQy.mjs";
1
+ import { t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
2
+ import { t as applyLivery } from "./livery-C0abgthY.mjs";
3
+ import { t as createVehicleInteriorVisual } from "./vehicle-interior-DfpZwWEh.mjs";
3
4
  import * as THREE from "three";
4
5
  import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
5
6
  //#region src/vehicle-camera.ts
@@ -42,14 +43,14 @@ const travel = new THREE.Vector3();
42
43
  * each moves along the body's up axis to keep its centre at its resting height, so the outside
43
44
  * wheels stay on the road in a turn rather than sinking into it.
44
45
  */
45
- function createVehicleVisual(model, vehicle) {
46
+ function createVehicleVisual(model, vehicle, livery) {
46
47
  const interior = vehicle.visual.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, vehicle.visual.interior);
47
48
  const animation = vehicle.visual.animation === void 0 ? void 0 : createModelSignalVisual(model, vehicle.visual.animation);
48
49
  const nodes = /* @__PURE__ */ new Map();
49
50
  const frontWheels = new Set(vehicle.visual.frontWheelNodes);
50
51
  const wheels = [];
51
52
  let steeringWheel;
52
- const color = vehicle.color !== void 0 ? new THREE.Color(vehicle.color) : void 0;
53
+ const color = livery === void 0 && vehicle.color !== void 0 ? new THREE.Color(vehicle.color) : void 0;
53
54
  model.traverse((object) => {
54
55
  object.userData.vehicleGeometry = true;
55
56
  const named = nodes.get(object.name) ?? [];
@@ -80,11 +81,16 @@ function createVehicleVisual(model, vehicle) {
80
81
  });
81
82
  }
82
83
  if (vehicle.visual.steeringWheelNode !== void 0) steeringWheel = nodes.get(vehicle.visual.steeringWheelNode)?.[0];
84
+ let appearance = livery === void 0 ? void 0 : applyLivery(model, livery);
83
85
  return {
86
+ setLivery(data) {
87
+ appearance?.dispose();
88
+ appearance = data === void 0 ? void 0 : applyLivery(model, data);
89
+ },
84
90
  object: model,
85
91
  interior,
86
92
  animation,
87
- update(steer, angle, signals) {
93
+ update(steer, angle, signals, timeSeconds) {
88
94
  const roll = signals?.bodyRoll ?? 0;
89
95
  const pitch = signals?.bodyPitch ?? 0;
90
96
  const lean = Number.isFinite(roll) && Number.isFinite(pitch) && (roll !== 0 || pitch !== 0);
@@ -105,10 +111,11 @@ function createVehicleVisual(model, vehicle) {
105
111
  wheelAngle: angle,
106
112
  ...signals
107
113
  };
108
- interior?.update(telemetry);
109
- animation?.update(telemetry);
114
+ interior?.update(telemetry, timeSeconds);
115
+ animation?.update(telemetry, timeSeconds);
110
116
  },
111
117
  dispose() {
118
+ appearance?.dispose();
112
119
  const geometries = /* @__PURE__ */ new Set();
113
120
  const materials = /* @__PURE__ */ new Set();
114
121
  model.traverse((object) => {
@@ -128,6 +135,7 @@ const parkedMaterial = new THREE.MeshStandardMaterial({
128
135
  metalness: .12
129
136
  });
130
137
  const parkedTemplates = /* @__PURE__ */ new Map();
138
+ const paints = /* @__PURE__ */ new Map();
131
139
  function coloredBox(x, y, z, width, height, length, color) {
132
140
  const geometry = new THREE.BoxGeometry(width, height, length).translate(x, y, z).toNonIndexed();
133
141
  geometry.deleteAttribute("uv");
@@ -147,16 +155,22 @@ function coloredBox(x, y, z, width, height, length, color) {
147
155
  * Cached by dimensions; never dispose the returned geometry.
148
156
  */
149
157
  function vehicleProxyGeometry(dimensions) {
150
- return parkedTemplate(dimensions, "#ffffff");
158
+ return parkedTemplate(dimensions);
151
159
  }
152
160
  /** The shared vertex-coloured material of parked and proxy vehicles. */
153
161
  const vehicleProxyMaterial = parkedMaterial;
154
- /** Generic dimension-driven proxy used only for large dormant parking batches. */
155
- function parkedTemplate(spec, color) {
156
- const key = `${spec.width}:${spec.length}:${spec.height}:${spec.wheelbase}:${color}`;
162
+ /**
163
+ * Generic dimension-driven proxy used only for large dormant parking batches, its body white:
164
+ * the body is its first `userData.bodyVertices` vertices, painted as a batch bakes it. A template
165
+ * per paint as well was dozens built for a tile's first cars, 7 ms of one frame.
166
+ */
167
+ function parkedTemplate(spec) {
168
+ const key = `${spec.width}:${spec.length}:${spec.height}:${spec.wheelbase}`;
157
169
  const cached = parkedTemplates.get(key);
158
170
  if (cached !== void 0) return cached;
159
- const parts = [coloredBox(0, spec.height * .34, 0, spec.width, spec.height * .48, spec.length, color), coloredBox(0, spec.height * .72, -spec.length * .06, spec.width * .82, spec.height * .42, spec.length * .52, "#526b78")];
171
+ const body = coloredBox(0, spec.height * .34, 0, spec.width, spec.height * .48, spec.length, "#ffffff");
172
+ const bodyVertices = body.getAttribute("position").count;
173
+ const parts = [body, coloredBox(0, spec.height * .72, -spec.length * .06, spec.width * .82, spec.height * .42, spec.length * .52, "#526b78")];
160
174
  for (const x of [-spec.wheelTrack / 2, spec.wheelTrack / 2]) for (const z of [-spec.wheelbase / 2, spec.wheelbase / 2]) {
161
175
  const wheel = new THREE.CylinderGeometry(spec.wheelRadius, spec.wheelRadius, spec.width * .1, 8);
162
176
  wheel.rotateZ(Math.PI / 2);
@@ -178,6 +192,7 @@ function parkedTemplate(spec, color) {
178
192
  for (const part of parts) part.dispose();
179
193
  geometry.computeBoundingBox();
180
194
  geometry.computeBoundingSphere();
195
+ geometry.userData.bodyVertices = bodyVertices;
181
196
  parkedTemplates.set(key, geometry);
182
197
  return geometry;
183
198
  }
@@ -191,33 +206,60 @@ function createParkedVehicleBatch(placements, origin = [0, 0]) {
191
206
  const group = new THREE.Group();
192
207
  group.name = "surface:parked-cars";
193
208
  if (placements.length === 0) return group;
194
- const templates = placements.map((placement) => parkedTemplate(placement.spec, placement.color));
209
+ const templates = placements.map((placement) => parkedTemplate(placement.spec));
195
210
  const vertices = templates.reduce((sum, template) => sum + template.getAttribute("position").count, 0);
196
211
  const positions = new Float32Array(vertices * 3);
197
212
  const normals = new Float32Array(vertices * 3);
198
213
  const colors = new Float32Array(vertices * 3);
199
214
  const ranges = new Uint32Array(placements.length * 2);
200
215
  const matrix = new THREE.Matrix4();
201
- const normalMatrix = new THREE.Matrix3();
202
216
  const rotation = new THREE.Quaternion();
203
217
  const position = new THREE.Vector3();
204
218
  const scale = new THREE.Vector3(1, 1, 1);
205
- const vertex = new THREE.Vector3();
219
+ const min = new THREE.Vector3(Infinity, Infinity, Infinity);
220
+ const max = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
206
221
  let offset = 0;
207
222
  placements.forEach((placement, index) => {
208
223
  const template = templates[index];
209
224
  position.set(placement.position[0] - origin[0], placement.position[1], placement.position[2] - origin[1]);
210
225
  rotation.setFromEuler(new THREE.Euler(placement.pitch ?? 0, placement.yaw, placement.roll ?? 0, "YXZ"));
211
226
  matrix.compose(position, rotation, scale);
212
- normalMatrix.getNormalMatrix(matrix);
213
- const source = template.getAttribute("position");
214
- const sourceNormals = template.getAttribute("normal");
215
- const sourceColors = template.getAttribute("color");
216
- for (let i = 0; i < source.count; i++) {
217
- vertex.fromBufferAttribute(source, i).applyMatrix4(matrix).toArray(positions, (offset + i) * 3);
218
- vertex.fromBufferAttribute(sourceNormals, i).applyMatrix3(normalMatrix).normalize().toArray(normals, (offset + i) * 3);
219
- vertex.fromBufferAttribute(sourceColors, i).toArray(colors, (offset + i) * 3);
227
+ const e = matrix.elements;
228
+ const points = template.getAttribute("position").array;
229
+ const sourceNormals = template.getAttribute("normal").array;
230
+ const base = offset * 3;
231
+ for (let i = 0; i < points.length; i += 3) {
232
+ const x = points[i], y = points[i + 1], z = points[i + 2];
233
+ const px = Math.fround(e[0] * x + e[4] * y + e[8] * z + e[12]);
234
+ const py = Math.fround(e[1] * x + e[5] * y + e[9] * z + e[13]);
235
+ const pz = Math.fround(e[2] * x + e[6] * y + e[10] * z + e[14]);
236
+ positions[base + i] = px;
237
+ positions[base + i + 1] = py;
238
+ positions[base + i + 2] = pz;
239
+ if (px < min.x) min.x = px;
240
+ if (px > max.x) max.x = px;
241
+ if (py < min.y) min.y = py;
242
+ if (py > max.y) max.y = py;
243
+ if (pz < min.z) min.z = pz;
244
+ if (pz > max.z) max.z = pz;
245
+ const nx = sourceNormals[i], ny = sourceNormals[i + 1], nz = sourceNormals[i + 2];
246
+ normals[base + i] = e[0] * nx + e[4] * ny + e[8] * nz;
247
+ normals[base + i + 1] = e[1] * nx + e[5] * ny + e[9] * nz;
248
+ normals[base + i + 2] = e[2] * nx + e[6] * ny + e[10] * nz;
249
+ }
250
+ colors.set(template.getAttribute("color").array, base);
251
+ let paint = paints.get(placement.color);
252
+ if (paint === void 0) {
253
+ paint = new THREE.Color(placement.color);
254
+ paints.set(placement.color, paint);
220
255
  }
256
+ const body = base + template.userData.bodyVertices * 3;
257
+ for (let i = base; i < body; i += 3) {
258
+ colors[i] = paint.r;
259
+ colors[i + 1] = paint.g;
260
+ colors[i + 2] = paint.b;
261
+ }
262
+ const source = template.getAttribute("position");
221
263
  ranges[index * 2] = offset;
222
264
  ranges[index * 2 + 1] = source.count;
223
265
  offset += source.count;
@@ -226,8 +268,8 @@ function createParkedVehicleBatch(placements, origin = [0, 0]) {
226
268
  geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
227
269
  geometry.setAttribute("normal", new THREE.BufferAttribute(normals, 3));
228
270
  geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
229
- geometry.computeBoundingBox();
230
- geometry.computeBoundingSphere();
271
+ geometry.boundingBox = new THREE.Box3(min, max);
272
+ geometry.boundingSphere = geometry.boundingBox.getBoundingSphere(new THREE.Sphere());
231
273
  const mesh = new THREE.Mesh(geometry, parkedMaterial);
232
274
  mesh.name = "vehicle:parked";
233
275
  mesh.userData.vehicleIds = placements.map((placement) => placement.id);