@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.
package/dist/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { n as nlerp4, t as lerp3 } from "./math-ev_jEkRe.mjs";
2
- import { n as readModelSignals, t as createModelSignalVisual } from "./model-signals-Dp5OV-Y0.mjs";
3
- import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-BVZjf4T-.mjs";
2
+ import { r as readModelSignals, t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-BliZYUY1.mjs";
4
+ import { n as liveryGraphicTexture, t as applyLivery } from "./livery-C0abgthY.mjs";
4
5
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
5
6
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
6
7
  import * as THREE from "three";
@@ -154,10 +155,11 @@ var AdaptiveQualityController = class {
154
155
  const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
155
156
  const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
156
157
  const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
158
+ const measuredBoth = this.cpuSamples > 0 && this.gpuSamples > 0;
157
159
  const loading = this.loading;
158
160
  this.resetWindow();
159
161
  const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
160
- const headroom = !loading && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
162
+ const headroom = (!loading || measuredBoth) && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
161
163
  const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
162
164
  this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
163
165
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
@@ -678,6 +680,7 @@ var SceneMirror = class {
678
680
  backend.updateRenderable(id, renderable);
679
681
  this.bound.set(id, key);
680
682
  }
683
+ backend.setLivery?.(id, comps?.livery);
681
684
  if (backend.setModelSignals) {
682
685
  const spec = comps?.["model.signals"];
683
686
  backend.setModelSignals(id, spec, readModelSignals(spec?.sources, (name) => comps?.[name]));
@@ -1388,7 +1391,7 @@ var StaticMeshBatches = class {
1388
1391
  const entries = [];
1389
1392
  object.traverseVisible((child) => {
1390
1393
  const mesh = child;
1391
- if (!mesh.isMesh || mesh.isSkinnedMesh || mesh.isInstancedMesh || mesh.morphTargetInfluences || mesh.onBeforeRender !== THREE.Object3D.prototype.onBeforeRender || mesh.onAfterRender !== THREE.Object3D.prototype.onAfterRender) return;
1394
+ if (!mesh.isMesh || mesh.children.some((child) => child.userData.liveryMarking === true) || mesh.isSkinnedMesh || mesh.isInstancedMesh || mesh.morphTargetInfluences || mesh.onBeforeRender !== THREE.Object3D.prototype.onBeforeRender || mesh.onAfterRender !== THREE.Object3D.prototype.onAfterRender) return;
1392
1395
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
1393
1396
  if (materials.some((m) => m.transparent || !m.depthWrite || !m.depthTest || m.transmission > 0 || m.isShaderMaterial || m.isNodeMaterial || m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile)) return;
1394
1397
  const matrix = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld);
@@ -1574,6 +1577,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1574
1577
  animationTickRate = 30;
1575
1578
  objects = /* @__PURE__ */ new Map();
1576
1579
  gltf = /* @__PURE__ */ new Map();
1580
+ liveries = /* @__PURE__ */ new Map();
1577
1581
  modelSignals = /* @__PURE__ */ new Map();
1578
1582
  identities = /* @__PURE__ */ new Map();
1579
1583
  lights = /* @__PURE__ */ new Map();
@@ -1803,6 +1807,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1803
1807
  return;
1804
1808
  }
1805
1809
  group.add(instance);
1810
+ this.bindLivery(id, instance);
1806
1811
  binding.clips = clips;
1807
1812
  this.bindModelSignals(id, instance);
1808
1813
  this.applyAnimation(id, binding, instance);
@@ -1871,6 +1876,30 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1871
1876
  this.create(id, renderable);
1872
1877
  }
1873
1878
  /** Latest mirrored values are retained while the model loads. No simulation state is changed. */
1879
+ setLivery(id, data) {
1880
+ const previous = this.liveries.get(id);
1881
+ const key = data === void 0 ? void 0 : JSON.stringify(data);
1882
+ if (previous?.key === key) return;
1883
+ this.batches?.remove(id);
1884
+ this.batchDirty.add(id);
1885
+ previous?.visual?.dispose();
1886
+ this.liveries.delete(id);
1887
+ if (data !== void 0) {
1888
+ this.liveries.set(id, {
1889
+ key,
1890
+ data
1891
+ });
1892
+ const instance = this.gltf.has(id) ? this.objects.get(id)?.children[0] : void 0;
1893
+ if (instance) this.bindLivery(id, instance);
1894
+ }
1895
+ }
1896
+ bindLivery(id, instance) {
1897
+ const state = this.liveries.get(id);
1898
+ if (!state) return;
1899
+ state.visual = applyLivery(instance, state.data);
1900
+ for (const warning of state.visual.warnings) console.warn(`[molen] entity "${id}": livery ${warning}`);
1901
+ }
1902
+ /** Latest mirrored values are retained while the model loads. No simulation state is changed. */
1874
1903
  setModelSignals(id, spec, signals) {
1875
1904
  const previous = this.modelSignals.get(id);
1876
1905
  const key = spec === void 0 ? void 0 : JSON.stringify(spec);
@@ -1913,9 +1942,11 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1913
1942
  }
1914
1943
  applyModelSignals(id) {
1915
1944
  const state = this.modelSignals.get(id);
1916
- state?.visual?.update(state.signals);
1945
+ state?.visual?.update(state.signals, this.animationTick / this.animationTickRate);
1917
1946
  }
1918
1947
  destroy(id) {
1948
+ this.liveries.get(id)?.visual?.dispose();
1949
+ this.liveries.delete(id);
1919
1950
  this.modelSignals.delete(id);
1920
1951
  this.batches?.remove(id);
1921
1952
  this.batchDirty.delete(id);
@@ -2034,8 +2065,8 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2034
2065
  for (const id of this.animations) {
2035
2066
  const binding = this.gltf.get(id);
2036
2067
  if (binding) this.poseAnimation(binding);
2037
- this.applyModelSignals(id);
2038
2068
  }
2069
+ for (const id of this.modelSignals.keys()) this.applyModelSignals(id);
2039
2070
  for (const handle of this.handles.values()) handle.setTick?.(tick, tickRate, void 0);
2040
2071
  if (this.pointLightSlots.length > 0 && this.renderer) this.updateLocalLights(this.renderer.camera);
2041
2072
  }
@@ -2086,6 +2117,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2086
2117
  this.applyModelSignals(id);
2087
2118
  this.lastPoseTick.set(id, tick);
2088
2119
  }
2120
+ for (const id of this.modelSignals.keys()) if (!this.animations.has(id)) this.applyModelSignals(id);
2089
2121
  for (const [id, handle] of this.handles) {
2090
2122
  if (handle.setTick === void 0) continue;
2091
2123
  const object = handle.object;
@@ -2237,6 +2269,8 @@ var FrameAdmissionQueue = class {
2237
2269
  maxMs;
2238
2270
  maxBytes;
2239
2271
  maxJobs;
2272
+ /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
2273
+ expected = /* @__PURE__ */ new Map();
2240
2274
  constructor(options = {}) {
2241
2275
  this.options = options;
2242
2276
  this.clock = options.now ?? (() => performance.now());
@@ -2247,11 +2281,20 @@ var FrameAdmissionQueue = class {
2247
2281
  this.maxMs = options.maxMilliseconds ?? 2;
2248
2282
  this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
2249
2283
  this.maxJobs = options.maxJobs ?? 32;
2250
- if (![
2251
- this.maxMs,
2252
- this.maxBytes,
2253
- this.maxJobs
2254
- ].every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2284
+ this.setLimits({});
2285
+ }
2286
+ /**
2287
+ * Change the per-frame budget from the next frame on; omitted limits keep their values. A host
2288
+ * can admit more when frames have time to spare (an adaptive quality tier, say).
2289
+ */
2290
+ setLimits(limits) {
2291
+ const next = [
2292
+ limits.maxMilliseconds ?? this.maxMs,
2293
+ limits.maxBytes ?? this.maxBytes,
2294
+ limits.maxJobs ?? this.maxJobs
2295
+ ];
2296
+ if (!next.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2297
+ [this.maxMs, this.maxBytes, this.maxJobs] = next;
2255
2298
  }
2256
2299
  run(task, options = {}) {
2257
2300
  if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
@@ -2275,7 +2318,11 @@ var FrameAdmissionQueue = class {
2275
2318
  }
2276
2319
  };
2277
2320
  options.signal?.addEventListener("abort", job.abort, { once: true });
2278
- (options.priority === "background" ? this.background : this.jobs).push(job);
2321
+ if (options.priority === "background") this.background.push(job);
2322
+ else if (options.priority === "urgent") {
2323
+ const after = this.jobs.findIndex((queued) => queued.options.priority !== "urgent");
2324
+ this.jobs.splice(after < 0 ? this.jobs.length : after, 0, job);
2325
+ } else this.jobs.push(job);
2279
2326
  this.request();
2280
2327
  });
2281
2328
  if (options.priority === "background") {
@@ -2293,8 +2340,12 @@ var FrameAdmissionQueue = class {
2293
2340
  this.queuedBackground.delete(job.promise);
2294
2341
  job.promise = void 0;
2295
2342
  }
2296
- /** Move a still-queued background job to the normal lane, behind the jobs already there. */
2297
- promote(promise) {
2343
+ /**
2344
+ * Move a still-queued background job to the normal lane, behind the jobs already there, or with
2345
+ * `front` ahead of them: for work a frame is waiting on, such as a material an object holds off
2346
+ * switching to until it is prepared.
2347
+ */
2348
+ promote(promise, options = {}) {
2298
2349
  const job = this.queuedBackground.get(promise);
2299
2350
  const index = job === void 0 ? -1 : this.background.indexOf(job);
2300
2351
  if (job === void 0 || index < 0) return;
@@ -2304,7 +2355,8 @@ var FrameAdmissionQueue = class {
2304
2355
  ...job.options,
2305
2356
  priority: "normal"
2306
2357
  };
2307
- this.jobs.push(job);
2358
+ if (options.front === true) this.jobs.unshift(job);
2359
+ else this.jobs.push(job);
2308
2360
  this.request();
2309
2361
  }
2310
2362
  get pending() {
@@ -2328,7 +2380,8 @@ var FrameAdmissionQueue = class {
2328
2380
  const next = lane[0];
2329
2381
  if (next === void 0) break;
2330
2382
  const cost = next.options.bytes ?? 0;
2331
- if (count > 0 && (count >= this.maxJobs || this.clock() - start >= this.maxMs || bytes + cost > this.maxBytes)) break;
2383
+ const label = next.options.label ?? "admission";
2384
+ if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > this.maxMs || bytes + cost > this.maxBytes)) break;
2332
2385
  lane.shift();
2333
2386
  this.forget(next);
2334
2387
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
@@ -2343,10 +2396,12 @@ var FrameAdmissionQueue = class {
2343
2396
  next.reject(error);
2344
2397
  }
2345
2398
  const workMs = this.clock() - began;
2399
+ const previous = this.expected.get(label);
2400
+ this.expected.set(label, previous === void 0 ? workMs : previous + (workMs - previous) * .25);
2346
2401
  count++;
2347
2402
  bytes += cost;
2348
2403
  this.options.onSample?.({
2349
- label: next.options.label ?? "admission",
2404
+ label,
2350
2405
  queueMs: began - next.queued,
2351
2406
  workMs,
2352
2407
  bytes: cost,
@@ -2569,6 +2624,8 @@ function starDirection(rightAscensionDeg, declinationDeg, state) {
2569
2624
  //#endregion
2570
2625
  //#region src/sky/visual.ts
2571
2626
  const RAD$1 = Math.PI / 180;
2627
+ /** Sky motion (radians) before the dome and stars redraw: about half a pixel at 70 degrees. */
2628
+ const SKY_REDRAW_ANGLE = 4e-4;
2572
2629
  const clamp$3 = (x) => Math.max(0, Math.min(1, x));
2573
2630
  const rgb$1 = (color) => [
2574
2631
  color.r,
@@ -2636,6 +2693,13 @@ var SkyVisual = class {
2636
2693
  catalog;
2637
2694
  palette;
2638
2695
  lastTime;
2696
+ /**
2697
+ * What the dome's colors and the stars were last written for. The sun and the sky turn a
2698
+ * quarter of a degree a minute: rewriting the dome and every star each second cost a frame
2699
+ * 3-5 ms for changes far below a pixel, so they are rewritten once those changes could show.
2700
+ */
2701
+ drawnDome;
2702
+ drawnStars;
2639
2703
  cloudAttenuation = 0;
2640
2704
  currentFrame;
2641
2705
  currentReflections;
@@ -2714,6 +2778,10 @@ var SkyVisual = class {
2714
2778
  const data = this.data;
2715
2779
  const time = data.mode === "earth" ? Math.floor(skyTimeMs(data.time, simulationSeconds) / 1e3) * 1e3 : 0;
2716
2780
  if (time === this.lastTime) return this.currentFrame;
2781
+ if (this.lastTime === void 0) {
2782
+ this.drawnDome = void 0;
2783
+ this.drawnStars = void 0;
2784
+ }
2717
2785
  this.lastTime = time;
2718
2786
  const earth = data.mode === "earth" ? evaluateEarthSky(time, data.observer) : void 0;
2719
2787
  const sunDirection = earth?.sun.direction ?? skyDirection(data.mode === "custom" ? data.sunBody.direction : [
@@ -2761,14 +2829,26 @@ var SkyVisual = class {
2761
2829
  this.ambientLight.color.copy(this.palette.nightHorizon).lerp(this.palette.dayHorizon, daylight);
2762
2830
  this.ambientLight.groundColor.copy(this.palette.ground);
2763
2831
  this.ambientLight.intensity = (light?.nightAmbient ?? .025) * (1 - daylight) + (light?.dayAmbient ?? .6) * daylight;
2832
+ const reference = light?.referenceElevation;
2833
+ if (reference !== void 0 && altitude > reference) {
2834
+ const level = (degrees) => this.ambientLight.intensity + this.sunLight.intensity * Math.sin(degrees * RAD$1);
2835
+ const scale = level(reference) / level(altitude);
2836
+ this.sunLight.intensity *= scale;
2837
+ this.ambientLight.intensity *= scale;
2838
+ }
2764
2839
  this.sunLight.intensity *= 1 - this.cloudAttenuation * .92;
2765
2840
  this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
2766
2841
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
2767
2842
  this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
2768
2843
  const radiance = this.ambientLight.intensity / Math.PI;
2844
+ const saturation = Math.max(0, Math.min(1, light?.skyLightSaturation ?? 1));
2845
+ const cast = (color) => {
2846
+ const luminance = color.r * .2126 + color.g * .7152 + color.b * .0722;
2847
+ return color.setRGB(luminance + (color.r - luminance) * saturation, luminance + (color.g - luminance) * saturation, luminance + (color.b - luminance) * saturation);
2848
+ };
2769
2849
  this.currentReflections = {
2770
- zenith: rgb$1(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight).multiplyScalar(radiance)),
2771
- horizon: rgb$1(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight).multiplyScalar(radiance)),
2850
+ zenith: rgb$1(cast(this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight)).multiplyScalar(radiance)),
2851
+ horizon: rgb$1(cast(this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight)).multiplyScalar(radiance)),
2772
2852
  ground: rgb$1(this.palette.ground.clone().multiplyScalar((.08 + daylight * .92) * radiance)),
2773
2853
  twilight: rgb$1(this.palette.twilight.clone().multiplyScalar(radiance)),
2774
2854
  twilightStrength: smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude)),
@@ -2812,11 +2892,18 @@ var SkyVisual = class {
2812
2892
  ]), 200);
2813
2893
  }
2814
2894
  updateDome(altitude, sun, daylight) {
2895
+ const drawn = this.drawnDome;
2896
+ if (drawn !== void 0 && drawn.sun.distanceToSquared(sun) < SKY_REDRAW_ANGLE ** 2 && Math.abs(drawn.daylight - daylight) < .001) return;
2897
+ this.drawnDome = {
2898
+ sun: sun.clone(),
2899
+ daylight
2900
+ };
2815
2901
  const colors = this.dome.geometry.getAttribute("color");
2816
2902
  const positions = this.dome.geometry.getAttribute("position");
2817
2903
  const horizon = this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight);
2818
2904
  const zenith = this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight);
2819
2905
  const twilight = smooth$2(-18, -4, altitude) * (1 - smooth$2(0, 16, altitude));
2906
+ const brightness = this.data.dome?.brightness ?? 1;
2820
2907
  const color = new THREE.Color();
2821
2908
  const dir = new THREE.Vector3();
2822
2909
  for (let i = 0; i < positions.count; i++) {
@@ -2826,7 +2913,7 @@ var SkyVisual = class {
2826
2913
  color.lerp(this.palette.twilight, twilight * Math.exp(-Math.abs(dir.y) * 7) * (.25 + .7 * nearSun));
2827
2914
  if (dir.y < 0) color.lerp(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92), smooth$2(0, .2, -dir.y));
2828
2915
  const glow = clamp$3(dir.dot(sun)) ** 96 * smooth$2(-2, 5, altitude) * .22;
2829
- color.lerp(this.palette.sun, glow);
2916
+ color.lerp(this.palette.sun, glow).multiplyScalar(brightness);
2830
2917
  colors.setXYZW(i, color.r, color.g, color.b, 1);
2831
2918
  }
2832
2919
  colors.needsUpdate = true;
@@ -2878,6 +2965,13 @@ var SkyVisual = class {
2878
2965
  updateStars(rotation, visibility, moon, moonDiameter) {
2879
2966
  this.stars.visible = visibility > 0 && this.catalog.length > 0;
2880
2967
  if (!this.stars.visible) return;
2968
+ const drawn = this.drawnStars;
2969
+ if (drawn !== void 0 && Math.abs(drawn.visibility - visibility) < .001 && drawn.rotation.elements.every((value, i) => Math.abs(value - rotation.elements[i]) < SKY_REDRAW_ANGLE) && (moon === void 0 ? drawn.moon === void 0 : drawn.moon !== void 0 && drawn.moon.distanceToSquared(moon) < SKY_REDRAW_ANGLE ** 2)) return;
2970
+ this.drawnStars = {
2971
+ rotation: rotation.clone(),
2972
+ visibility,
2973
+ moon: moon?.clone()
2974
+ };
2881
2975
  const positions = this.stars.geometry.getAttribute("position");
2882
2976
  const colors = this.stars.geometry.getAttribute("color");
2883
2977
  const d = new THREE.Vector3(), right = new THREE.Vector3(), up = new THREE.Vector3(), p = new THREE.Vector3();
@@ -2943,7 +3037,8 @@ function noise(x, y, period, seed) {
2943
3037
  const d = hash(wrap(ix + 1, period), wrap(iy + 1, period), seed);
2944
3038
  return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
2945
3039
  }
2946
- const CLOUD_RESOLUTION = 256;
3040
+ /** Cloud texture texels per side: about 47 m each at the explorer's 24 km cloud scale. */
3041
+ const CLOUD_RESOLUTION = 512;
2947
3042
  const PARTICLE_LIMIT = 1400;
2948
3043
  /**
2949
3044
  * Lightweight layered clouds and local precipitation with standard materials on both graphics
@@ -3022,6 +3117,7 @@ var WeatherVisual = class {
3022
3117
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
3023
3118
  texture.magFilter = THREE.LinearFilter;
3024
3119
  texture.minFilter = THREE.LinearMipmapLinearFilter;
3120
+ texture.anisotropy = 16;
3025
3121
  texture.generateMipmaps = true;
3026
3122
  texture.colorSpace = THREE.LinearSRGBColorSpace;
3027
3123
  this.cloudTexture = texture;
@@ -3069,7 +3165,7 @@ var WeatherVisual = class {
3069
3165
  for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
3070
3166
  let value = 0, weight = 0;
3071
3167
  for (let octave = 0; octave < 5; octave++) {
3072
- const frequency = 8 * 2 ** octave, amplitude = .5 ** octave;
3168
+ const frequency = 8 * 2 ** octave, amplitude = .52 ** octave;
3073
3169
  value += noise(x / CLOUD_RESOLUTION * frequency, y / CLOUD_RESOLUTION * frequency, frequency, seed + octave) * amplitude;
3074
3170
  weight += amplitude;
3075
3171
  }
@@ -3587,6 +3683,16 @@ var Renderer = class Renderer {
3587
3683
  warmupMaterial;
3588
3684
  warmedPrograms = /* @__PURE__ */ new WeakMap();
3589
3685
  warmedMeshes = /* @__PURE__ */ new WeakMap();
3686
+ /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
3687
+ materialMeshes = /* @__PURE__ */ new WeakMap();
3688
+ /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
3689
+ preparationLights;
3690
+ /**
3691
+ * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
3692
+ * `prepareVariants`.
3693
+ */
3694
+ warmedVariants = /* @__PURE__ */ new WeakMap();
3695
+ variantInterests = /* @__PURE__ */ new WeakMap();
3590
3696
  warmups = /* @__PURE__ */ new WeakMap();
3591
3697
  /** Deferred meshes whose preparation has not settled, with the interest that can promote it. */
3592
3698
  deferredMeshes = /* @__PURE__ */ new WeakMap();
@@ -3627,8 +3733,16 @@ var Renderer = class Renderer {
3627
3733
  optimizer;
3628
3734
  activeSky;
3629
3735
  reflections;
3630
- /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
3631
- webgpuShadowLights = /* @__PURE__ */ new WeakSet();
3736
+ occlusionOptions;
3737
+ occlusion;
3738
+ occlusionLoad;
3739
+ occlusionSuspended = false;
3740
+ /** Sun lights that have cast shadows: 'off' parks their maps; see setShadowQuality. */
3741
+ shadowLights = /* @__PURE__ */ new WeakSet();
3742
+ /** Kinds of shadow caster prepared so far (WebGL); see noteShadowCaster. */
3743
+ casterVariants = /* @__PURE__ */ new Set();
3744
+ /** Whether the shadow pass has drawn shadowCasterWarmup's casters (WebGL). */
3745
+ shadowCastersWarmed = false;
3632
3746
  reflectionClearColor = Object.assign(new THREE.Color(), { a: 1 });
3633
3747
  starCatalog;
3634
3748
  activeWeather;
@@ -3661,17 +3775,33 @@ var Renderer = class Renderer {
3661
3775
  radius: focus.radius
3662
3776
  };
3663
3777
  }
3664
- /** Turn sun shadows on at a map resolution, or off, without rebuilding the environment. */
3778
+ /**
3779
+ * Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a
3780
+ * light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader
3781
+ * keeps the shadow inputs it was built with: a host that turns shadows on once before its first
3782
+ * frame can then switch them freely (adaptive quality tiers do) without rebuilding a shader.
3783
+ */
3665
3784
  setShadowQuality(quality) {
3666
3785
  const enabled = quality !== "off";
3786
+ let parked = false;
3667
3787
  for (const light of this.sunLights()) {
3668
- if (this.backend === "webgpu" && this.webgpuShadowLights.has(light)) {
3788
+ if (this.backend === "webgpu" && this.shadowLights.has(light)) {
3669
3789
  light.shadow.autoUpdate = enabled;
3670
3790
  light.shadow.intensity = enabled ? 1 : 0;
3671
3791
  continue;
3672
3792
  }
3673
- light.castShadow = enabled;
3674
- if (!enabled) continue;
3793
+ if (!enabled) {
3794
+ if (this.shadowLights.has(light)) {
3795
+ light.shadow.autoUpdate = false;
3796
+ light.shadow.intensity = 0;
3797
+ parked = true;
3798
+ } else light.castShadow = false;
3799
+ continue;
3800
+ }
3801
+ if (!light.castShadow) this.shadowCastersWarmed = false;
3802
+ light.castShadow = true;
3803
+ light.shadow.autoUpdate = true;
3804
+ light.shadow.intensity = 1;
3675
3805
  const size = SHADOW_MAP_SIZE[quality];
3676
3806
  if (light.shadow.mapSize.x !== size) {
3677
3807
  light.shadow.mapSize.set(size, size);
@@ -3680,9 +3810,10 @@ var Renderer = class Renderer {
3680
3810
  light.shadow.map = null;
3681
3811
  }
3682
3812
  }
3683
- if (this.backend === "webgpu") this.webgpuShadowLights.add(light);
3813
+ this.shadowLights.add(light);
3684
3814
  }
3685
3815
  if (this.backend === "webgpu" && this.three.shadowMap.enabled) return;
3816
+ if (parked && this.three.shadowMap.enabled) return;
3686
3817
  this.three.shadowMap.enabled = enabled;
3687
3818
  this.three.shadowMap.type = quality === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
3688
3819
  }
@@ -3772,12 +3903,12 @@ var Renderer = class Renderer {
3772
3903
  try {
3773
3904
  if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
3774
3905
  if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
3775
- const { createWebGpuDriver } = await import("./webgpu-driver-Bt2mvZk9.mjs");
3906
+ const { createWebGpuDriver } = await import("./webgpu-driver-BQnmPRqs.mjs");
3776
3907
  const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
3777
3908
  late.dispose();
3778
3909
  });
3779
3910
  try {
3780
- const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-DKRyHBRC.mjs"))).WebGpuSceneOptimizer(three);
3911
+ const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-Cup4Yvzs.mjs"))).WebGpuSceneOptimizer(three);
3781
3912
  return new Renderer(opts, {
3782
3913
  three,
3783
3914
  backend: "webgpu",
@@ -3987,26 +4118,34 @@ var Renderer = class Renderer {
3987
4118
  * other levels afterwards in the background, so publication waits only for what can be seen.
3988
4119
  * Queued work is cancelled once every caller waiting for it has aborted, and background work
3989
4120
  * once its mesh or geometry is disposed.
4121
+ *
4122
+ * `root.userData.admissionPriority` admits the root's own work as `'urgent'` (ahead of normal
4123
+ * work) or `'background'` (only in budget normal work leaves: content nobody waits on yet).
3990
4124
  */
3991
4125
  async prepareObject(root, signal, parent) {
3992
4126
  if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
3993
4127
  updateDetachedWorldMatrix(root, parent);
3994
4128
  const lods = parent === void 0 ? void 0 : unselectedLodLevels(root, this.camera);
3995
4129
  const deferredLevels = lods === void 0 ? void 0 : new Set([...lods.values()].flat());
3996
- const foreground = createLane(false);
4130
+ const priority = root.userData.admissionPriority;
4131
+ const foreground = createLane(priority === "background", priority === "urgent");
3997
4132
  const background = createLane(true);
4133
+ const state = this.programState();
3998
4134
  const interest = signal === void 0 ? "pinned" : new WarmupInterest(this.cancel);
3999
4135
  const deferred = [];
4136
+ const switching = [];
4000
4137
  root.traverse((object) => {
4001
4138
  const mesh = object;
4002
4139
  if (!mesh.isMesh) return;
4140
+ this.noteShadowCaster(mesh);
4141
+ if (mesh.userData.materialVariants !== void 0) switching.push(mesh);
4003
4142
  if (deferredLevels !== void 0 && withinAny(mesh, root, deferredLevels)) deferred.push(mesh);
4004
- else this.prepareMesh(mesh, foreground, interest);
4143
+ else this.prepareMesh(mesh, foreground, interest, state);
4005
4144
  });
4006
4145
  this.flushWebGlBatches(foreground);
4007
4146
  const deferredInterests = deferred.map((mesh) => {
4008
4147
  const meshInterest = new WarmupInterest(this.cancel);
4009
- this.prepareMesh(mesh, background, meshInterest);
4148
+ this.prepareMesh(mesh, background, meshInterest, state);
4010
4149
  return meshInterest;
4011
4150
  });
4012
4151
  this.flushWebGlBatches(background);
@@ -4018,6 +4157,7 @@ var Renderer = class Renderer {
4018
4157
  if (this.deferredMeshes.get(mesh) === meshInterest) this.deferredMeshes.delete(mesh);
4019
4158
  });
4020
4159
  });
4160
+ for (const mesh of switching) this.prepareVariants(mesh);
4021
4161
  for (const [lod, levels] of lods ?? []) if (levels.length > 0) this.guardLod(lod);
4022
4162
  const release = () => {
4023
4163
  if (interest !== "pinned") interest.release();
@@ -4033,7 +4173,30 @@ var Renderer = class Renderer {
4033
4173
  const failure = results.find((result) => result.status === "rejected");
4034
4174
  if (failure?.status === "rejected") throw failure.reason;
4035
4175
  }
4036
- prepareMesh(mesh, lane, interest) {
4176
+ /**
4177
+ * Build `next`'s shaders for every kind of prepared mesh that draws `current`, before the caller
4178
+ * copies `next` into `current`: a progressive material upgrading its placeholder in place once a
4179
+ * texture bake lands. Three shares a program between materials built alike, so the upgraded
4180
+ * placeholder draws with it at once. Otherwise every mesh showing the placeholder built its new
4181
+ * shaders in the next frame, together: seconds of frozen flight shortly after loading. The work
4182
+ * runs in the background lane. Keep `next` alive while `current` uses the shared program.
4183
+ */
4184
+ async prepareMaterialChange(current, next) {
4185
+ if (this.disposed) return;
4186
+ const builds = [];
4187
+ for (const ref of this.materialMeshes.get(current)?.values() ?? []) {
4188
+ const mesh = ref.deref();
4189
+ if (mesh === void 0) continue;
4190
+ const warmup = this.warmup(() => this.compileMesh(mesh, next), createLane(true), {
4191
+ label: "shader-upgrade",
4192
+ bytes: 0
4193
+ });
4194
+ warmup.pinned = true;
4195
+ builds.push(warmup.promise);
4196
+ }
4197
+ await Promise.allSettled(builds);
4198
+ }
4199
+ prepareMesh(mesh, lane, interest, state) {
4037
4200
  const need = (promise) => {
4038
4201
  lane.jobs.add(promise);
4039
4202
  const warmup = this.warmups.get(promise);
@@ -4043,7 +4206,7 @@ var Renderer = class Renderer {
4043
4206
  if (!lane.background) this.admission.promote(promise);
4044
4207
  };
4045
4208
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
4046
- const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}`;
4209
+ const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.instanceColor)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}/${Object.keys(mesh.geometry.morphAttributes).sort().join(",")}`;
4047
4210
  const variants = [];
4048
4211
  for (const material of materials) {
4049
4212
  for (const value of Object.values(material)) {
@@ -4060,12 +4223,18 @@ var Renderer = class Renderer {
4060
4223
  this.rememberPreparation([value], upload);
4061
4224
  need(upload.promise);
4062
4225
  }
4226
+ let meshes = this.materialMeshes.get(material);
4227
+ if (!meshes) {
4228
+ meshes = /* @__PURE__ */ new Map();
4229
+ this.materialMeshes.set(material, meshes);
4230
+ }
4231
+ if (meshes.get(key)?.deref() === void 0) meshes.set(key, new WeakRef(mesh));
4063
4232
  let map = this.warmedPrograms.get(material);
4064
4233
  if (!map) {
4065
4234
  map = /* @__PURE__ */ new Map();
4066
4235
  this.warmedPrograms.set(material, map);
4067
4236
  }
4068
- const variantKey = `${material.version}/${key}`;
4237
+ const variantKey = `${material.version}/${key}/${state}`;
4069
4238
  const existing = map.get(variantKey);
4070
4239
  if (existing) need(existing);
4071
4240
  else variants.push({
@@ -4150,13 +4319,62 @@ var Renderer = class Renderer {
4150
4319
  }
4151
4320
  lane.glBatches.length = 0;
4152
4321
  }
4322
+ /**
4323
+ * A mesh that swaps its own material, as an instanced detail switch swaps in an opaque twin for
4324
+ * its coarser levels, lists every material in `userData.materialVariants`. Each needs its own
4325
+ * shader build, which the first frame to draw it would otherwise make mid-frame: in flight a whole
4326
+ * view of trees changed level at once and built their twins in one frame, for most of a second.
4327
+ * `userData.materialReady(material)` tells the mesh's owner whether one is ready. Until it is, the
4328
+ * owner keeps what it shows; asking queues its build ahead of other work. Most batches never
4329
+ * change level, so a variant is built only once its mesh asks for it.
4330
+ */
4331
+ prepareVariants(mesh) {
4332
+ let builds = this.warmedVariants.get(mesh);
4333
+ if (builds === void 0) {
4334
+ builds = /* @__PURE__ */ new Map();
4335
+ this.warmedVariants.set(mesh, builds);
4336
+ }
4337
+ builds.set(mesh.material, null);
4338
+ mesh.userData.materialReady ??= (material) => this.variantReady(mesh, material);
4339
+ }
4340
+ /** Whether `mesh` can draw `material` without building it mid-frame; builds it first if not. */
4341
+ variantReady(mesh, material) {
4342
+ const builds = this.warmedVariants.get(mesh);
4343
+ const known = builds?.get(material);
4344
+ if (builds === void 0 || known === null) return true;
4345
+ let promise = known;
4346
+ if (promise === void 0) {
4347
+ let interest = this.variantInterests.get(mesh);
4348
+ if (interest === void 0) {
4349
+ interest = new WarmupInterest(this.cancel);
4350
+ releaseOnDispose(mesh, interest);
4351
+ this.variantInterests.set(mesh, interest);
4352
+ }
4353
+ const warmup = this.warmup(() => this.compileMesh(mesh, material), createLane(true), {
4354
+ label: "shader-variant",
4355
+ bytes: 0
4356
+ });
4357
+ interest.join(warmup);
4358
+ builds.set(material, warmup.promise);
4359
+ const forget = () => {
4360
+ if (builds.get(material) === warmup.promise) builds.delete(material);
4361
+ };
4362
+ warmup.forget.push(forget);
4363
+ warmup.promise.catch(forget);
4364
+ promise = warmup.promise;
4365
+ }
4366
+ const warmup = this.warmups.get(promise);
4367
+ if (warmup === void 0 || warmup.settled) return true;
4368
+ this.admission.promote(promise, { front: true });
4369
+ return false;
4370
+ }
4153
4371
  /** Queue one cancellable warm-up job in the lane's admission priority. */
4154
4372
  warmup(task, lane, options) {
4155
4373
  const controller = new AbortController();
4156
4374
  const promise = this.admission.run(task, {
4157
4375
  ...options,
4158
4376
  signal: controller.signal,
4159
- priority: lane.background ? "background" : "normal"
4377
+ priority: lane.background ? "background" : lane.urgent ? "urgent" : "normal"
4160
4378
  });
4161
4379
  const warmup = {
4162
4380
  promise,
@@ -4196,6 +4414,15 @@ var Renderer = class Renderer {
4196
4414
  }
4197
4415
  /** Returns whether any level is still being prepared. */
4198
4416
  holdUnpreparedLevel(lod, shown) {
4417
+ if (lod.levels.length === 0) {
4418
+ let pending = false;
4419
+ for (const child of lod.children) {
4420
+ if (!this.pendingWithin(child, child.visible)) continue;
4421
+ pending = true;
4422
+ child.visible = false;
4423
+ }
4424
+ return pending;
4425
+ }
4199
4426
  const ready = lod.levels.map((level) => !this.pendingWithin(level.object, false));
4200
4427
  if (ready.every(Boolean)) return false;
4201
4428
  const wanted = lod.getCurrentLevel();
@@ -4238,16 +4465,125 @@ var Renderer = class Renderer {
4238
4465
  warmup.forget.push(forget);
4239
4466
  promise.catch(forget);
4240
4467
  }
4241
- compileMesh(mesh) {
4242
- const visible = mesh.visible, culled = mesh.frustumCulled;
4468
+ /**
4469
+ * While WebGL shadows are parked the shadow pass never runs, so no depth program is built for
4470
+ * the casters arriving meanwhile, and the first frame with shadows back built every one of them
4471
+ * at once (an adaptive tier change, mid-flight). A caster of a kind the map has not drawn yet
4472
+ * asks the parked map for one render, which builds its depth program as it streams in. The
4473
+ * kinds follow three's shadow pass: one depth material, cloned for alpha-tested maps,
4474
+ * displacement or clipping, built per mesh kind and side.
4475
+ */
4476
+ noteShadowCaster(mesh) {
4477
+ if (this.backend !== "webgl" || !mesh.castShadow) return;
4478
+ const kind = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.morphAttributes).sort().join(",")}`;
4479
+ let fresh = false;
4480
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
4481
+ const textured = material;
4482
+ const variant = mesh.customDepthMaterial !== void 0 ? `custom:${mesh.customDepthMaterial.uuid}` : [
4483
+ kind,
4484
+ material.alphaTest > 0 && (textured.map != null || textured.alphaMap != null),
4485
+ textured.displacementMap != null && textured.displacementScale !== 0,
4486
+ material.alphaToCoverage,
4487
+ material.clipShadows && (material.clippingPlanes?.length ?? 0) > 0,
4488
+ material.shadowSide ?? material.side
4489
+ ].join("/");
4490
+ if (this.casterVariants.has(variant)) continue;
4491
+ this.casterVariants.add(variant);
4492
+ fresh = true;
4493
+ }
4494
+ if (!fresh) return;
4495
+ for (const light of this.sunLights()) if (this.shadowLights.has(light) && !light.shadow.autoUpdate) light.shadow.needsUpdate = true;
4496
+ }
4497
+ /** Build `mesh` for the frame's draw target, drawn with `material` when given. */
4498
+ compileMesh(mesh, material) {
4499
+ const load = this.occlusionOptions !== void 0 ? this.occlusionLoad : void 0;
4500
+ if (load !== void 0 && this.occlusion === void 0) {
4501
+ const retry = () => this.compileMesh(mesh, material);
4502
+ return load.then(retry, retry);
4503
+ }
4504
+ const occlusion = this.occlusionOptions !== void 0 && this.occlusion?.camera === this.camera ? this.occlusion.pass : void 0;
4505
+ const visible = mesh.visible, culled = mesh.frustumCulled, shown = mesh.material;
4243
4506
  mesh.visible = true;
4244
4507
  mesh.frustumCulled = false;
4508
+ if (material !== void 0) mesh.material = material;
4509
+ const traverse = this.scene.traverseVisible;
4510
+ const ownTraverse = Object.hasOwn(this.scene, "traverseVisible");
4245
4511
  try {
4512
+ if (this.scene.onBeforeRender === THREE.Object3D.prototype.onBeforeRender) {
4513
+ const lights = this.sceneLights();
4514
+ this.scene.traverseVisible = (visit) => {
4515
+ for (const light of lights) visit(light);
4516
+ };
4517
+ }
4518
+ if (occlusion !== void 0) return occlusion.compile(mesh);
4519
+ if (this.backend === "webgl") return this.compileWebGl(mesh);
4246
4520
  return this.three.compileAsync(mesh, this.camera, this.scene);
4247
4521
  } finally {
4522
+ if (ownTraverse) this.scene.traverseVisible = traverse;
4523
+ else delete this.scene.traverseVisible;
4248
4524
  mesh.visible = visible;
4249
4525
  mesh.frustumCulled = culled;
4526
+ mesh.material = shown;
4527
+ }
4528
+ }
4529
+ /**
4530
+ * Three's compileAsync, but waiting for the programs built for this mesh. Three polls each
4531
+ * material's current program, which the next frame resets for whatever it drew last: a
4532
+ * material shared with drawn meshes (every building's wall) reported its ready program while
4533
+ * the instanced variant was still linking, and that variant's first draw waited for the link
4534
+ * mid-frame (130 ms in flight).
4535
+ */
4536
+ compileWebGl(mesh) {
4537
+ const renderer = this.three;
4538
+ const all = () => renderer.info.programs ?? [];
4539
+ const known = new Set(all());
4540
+ const programs = /* @__PURE__ */ new Set();
4541
+ for (const material of renderer.compile(mesh, this.camera, this.scene)) {
4542
+ const program = renderer.properties.get(material).currentProgram;
4543
+ if (program !== void 0) programs.add(program);
4250
4544
  }
4545
+ for (const program of all()) if (!known.has(program)) programs.add(program);
4546
+ return new Promise((resolve) => {
4547
+ const check = () => {
4548
+ for (const program of programs) if (program.program === void 0 || program.isReady()) programs.delete(program);
4549
+ if (programs.size === 0) resolve();
4550
+ else setTimeout(check, 10);
4551
+ };
4552
+ check();
4553
+ });
4554
+ }
4555
+ /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
4556
+ sceneLights() {
4557
+ this.preparationLights ??= (() => {
4558
+ const lights = [];
4559
+ THREE.Object3D.prototype.traverseVisible.call(this.scene, (object) => {
4560
+ if (object.isLight) lights.push(object);
4561
+ });
4562
+ return lights;
4563
+ })();
4564
+ return this.preparationLights;
4565
+ }
4566
+ /**
4567
+ * What a lit program is built for besides its material and mesh: the scene's lights and which
4568
+ * cast shadows, the shadow map, fog, environment and output. Warm-ups are remembered under it.
4569
+ * Without it a material built before the sky's sun, its shadows or its reflections existed
4570
+ * counted as prepared, and the next tile drawing it built the real program mid-frame.
4571
+ */
4572
+ programState() {
4573
+ let lights = "";
4574
+ for (const light of this.sceneLights()) lights += `${light.type}${light.castShadow ? "*" : ""},`;
4575
+ const fog = this.scene.fog;
4576
+ const environment = this.scene.environment;
4577
+ const image = environment?.image;
4578
+ return [
4579
+ lights,
4580
+ this.three.shadowMap.enabled,
4581
+ this.three.shadowMap.type,
4582
+ fog === null ? "" : fog.isFogExp2 ? "exp2" : "linear",
4583
+ environment === null ? "" : `${environment.mapping}:${image?.height ?? ""}`,
4584
+ this.three.toneMapping,
4585
+ this.three.outputColorSpace
4586
+ ].join("/");
4251
4587
  }
4252
4588
  prepareWebGlGeometries(meshes) {
4253
4589
  const renderer = this.three;
@@ -4282,6 +4618,7 @@ var Renderer = class Renderer {
4282
4618
  }
4283
4619
  }
4284
4620
  render() {
4621
+ this.preparationLights = void 0;
4285
4622
  if (this.disposed) throw new Error("Renderer has been disposed");
4286
4623
  if (this.deviceLossReason !== void 0) throw new Error(`WebGPU device lost: ${this.deviceLossReason}. Recreate the viewer, or reload with WebGL.`);
4287
4624
  if (this.backend === "webgpu") this.three.info.reset();
@@ -4317,8 +4654,23 @@ var Renderer = class Renderer {
4317
4654
  this.hideReflectedAmbient(reflectedAmbient);
4318
4655
  const baseFog = this.scene.fog;
4319
4656
  if (weather) this.scene.fog = weather.fogFor(baseFog, sky?.frame);
4657
+ const occlusion = this.currentOcclusion();
4320
4658
  try {
4321
- if (sky) {
4659
+ if (occlusion) {
4660
+ if (sky) {
4661
+ sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4662
+ sky.prepareCamera(this.camera);
4663
+ }
4664
+ this.applyShadowFocus();
4665
+ const autoReset = this.three.info.autoReset;
4666
+ this.three.info.reset();
4667
+ this.three.info.autoReset = false;
4668
+ try {
4669
+ this.optimized(() => occlusion.render(sky, !this.occlusionSuspended));
4670
+ } finally {
4671
+ this.three.info.autoReset = autoReset;
4672
+ }
4673
+ } else if (sky) {
4322
4674
  sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
4323
4675
  sky.prepareCamera(this.camera);
4324
4676
  this.applyShadowFocus();
@@ -4358,6 +4710,7 @@ var Renderer = class Renderer {
4358
4710
  hideReflectedAmbient(light) {
4359
4711
  const hidden = this.hiddenAmbient;
4360
4712
  if (hidden !== void 0 && hidden.light !== light) {
4713
+ if (hidden.light.visible !== hidden.visible) this.shadowCastersWarmed = false;
4361
4714
  hidden.light.visible = hidden.visible;
4362
4715
  this.hiddenAmbient = void 0;
4363
4716
  }
@@ -4366,23 +4719,130 @@ var Renderer = class Renderer {
4366
4719
  light,
4367
4720
  visible: light.visible
4368
4721
  };
4722
+ if (light.visible) this.shadowCastersWarmed = false;
4369
4723
  light.visible = false;
4370
4724
  }
4371
4725
  renderScene() {
4726
+ const warmup = this.shadowCasterWarmup();
4727
+ if (warmup !== void 0) this.scene.add(warmup);
4728
+ try {
4729
+ this.optimized(() => this.three.render(this.scene, this.camera));
4730
+ } finally {
4731
+ if (warmup !== void 0) {
4732
+ warmup.removeFromParent();
4733
+ for (const child of warmup.children) {
4734
+ const mesh = child;
4735
+ mesh.geometry.dispose();
4736
+ mesh.material.dispose();
4737
+ }
4738
+ }
4739
+ }
4740
+ }
4741
+ /**
4742
+ * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
4743
+ * per side): the shadow pass builds a depth program for each kind of caster the first time it
4744
+ * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
4745
+ * shadow pass keeps its depth materials, so the programs stay built; three keys them by the
4746
+ * scene's light counts too, so a light the renderer shows or hides warms them again.
4747
+ */
4748
+ shadowCasterWarmup() {
4749
+ if (this.shadowCastersWarmed || this.backend !== "webgl" || !this.three.shadowMap.enabled) return void 0;
4750
+ if (!this.sunLights().some((light) => light.castShadow && light.shadow.intensity > 0)) return void 0;
4751
+ this.shadowCastersWarmed = true;
4752
+ const group = new THREE.Group();
4753
+ group.name = "molen:shadow-caster-warmup";
4754
+ for (const side of [
4755
+ THREE.FrontSide,
4756
+ THREE.BackSide,
4757
+ THREE.DoubleSide
4758
+ ]) for (const instanced of [false, true]) {
4759
+ const geometry = new THREE.BufferGeometry();
4760
+ geometry.setAttribute("position", new THREE.Float32BufferAttribute(new Array(9).fill(0), 3));
4761
+ geometry.setAttribute("normal", new THREE.Float32BufferAttribute([
4762
+ 0,
4763
+ 1,
4764
+ 0,
4765
+ 0,
4766
+ 1,
4767
+ 0,
4768
+ 0,
4769
+ 1,
4770
+ 0
4771
+ ], 3));
4772
+ const material = new THREE.MeshBasicMaterial({
4773
+ side,
4774
+ colorWrite: false,
4775
+ depthWrite: false
4776
+ });
4777
+ const mesh = instanced ? new THREE.InstancedMesh(geometry, material, 1) : new THREE.Mesh(geometry, material);
4778
+ mesh.castShadow = true;
4779
+ mesh.frustumCulled = false;
4780
+ group.add(mesh);
4781
+ }
4782
+ return group;
4783
+ }
4784
+ optimized(draw) {
4372
4785
  if (this.optimizer === void 0) {
4373
- this.three.render(this.scene, this.camera);
4786
+ draw();
4374
4787
  return;
4375
4788
  }
4376
4789
  this.optimizer.prepare(this.scene, this.camera);
4377
4790
  const autoUpdate = this.scene.matrixWorldAutoUpdate;
4378
4791
  this.scene.matrixWorldAutoUpdate = false;
4379
4792
  try {
4380
- this.three.render(this.scene, this.camera);
4793
+ draw();
4381
4794
  this.optimizer.finish();
4382
4795
  } finally {
4383
4796
  this.scene.matrixWorldAutoUpdate = autoUpdate;
4384
4797
  }
4385
4798
  }
4799
+ /**
4800
+ * Screen-space ambient occlusion on the WebGPU backend (a no-op on WebGL): creases, corners and
4801
+ * the ground around buildings and trees darken a little, as indirect light cannot reach them.
4802
+ * The frame then renders through a node pipeline; frames draw directly while it compiles.
4803
+ */
4804
+ setAmbientOcclusion(enabled, options = {}) {
4805
+ if (this.disposed) throw new Error("Renderer has been disposed");
4806
+ const next = enabled && this.backend === "webgpu" ? { ...options } : void 0;
4807
+ const current = this.occlusionOptions;
4808
+ if (next !== void 0 && current !== void 0 && next.radius === current.radius && next.strength === current.strength && next.reach === current.reach) return;
4809
+ this.occlusion?.pass.dispose();
4810
+ this.occlusion = void 0;
4811
+ this.occlusionOptions = next;
4812
+ this.currentOcclusion();
4813
+ }
4814
+ /**
4815
+ * Skip the occlusion computation while keeping ambient occlusion set up: the frame still draws
4816
+ * into its target, and the image is copied out unshaded. Each object's shaders are built for
4817
+ * one draw target, so turning occlusion off and on again (`setAmbientOcclusion`) built every
4818
+ * object in view again, mid-frame, when the target changed; suspending changes nothing there.
4819
+ */
4820
+ suspendAmbientOcclusion(suspended) {
4821
+ if (this.disposed) throw new Error("Renderer has been disposed");
4822
+ this.occlusionSuspended = suspended;
4823
+ }
4824
+ /** The occlusion pass for the current camera, building one in the background when needed. */
4825
+ currentOcclusion() {
4826
+ const options = this.occlusionOptions;
4827
+ if (options === void 0) return void 0;
4828
+ if (this.occlusion !== void 0 && this.occlusion.camera !== this.camera) {
4829
+ this.occlusion.pass.dispose();
4830
+ this.occlusion = void 0;
4831
+ }
4832
+ if (this.occlusion === void 0 && this.occlusionLoad === void 0) {
4833
+ const camera = this.camera;
4834
+ this.occlusionLoad = import("./webgpu-ambient-occlusion-9gnp3qOY.mjs").then(({ createWebGpuAmbientOcclusion }) => createWebGpuAmbientOcclusion(this.three, this.scene, camera, options)).then((pass) => {
4835
+ if (this.disposed || this.occlusionOptions !== options) pass.dispose();
4836
+ else this.occlusion = {
4837
+ camera,
4838
+ pass
4839
+ };
4840
+ }).finally(() => {
4841
+ this.occlusionLoad = void 0;
4842
+ });
4843
+ }
4844
+ return this.occlusion?.camera === this.camera ? this.occlusion.pass : void 0;
4845
+ }
4386
4846
  /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
4387
4847
  createRenderGroup() {
4388
4848
  return this.optimizer?.createGroup() ?? new THREE.Group();
@@ -4408,6 +4868,9 @@ var Renderer = class Renderer {
4408
4868
  dispose() {
4409
4869
  if (this.disposed) return;
4410
4870
  this.disposed = true;
4871
+ this.occlusionOptions = void 0;
4872
+ this.occlusion?.pass.dispose();
4873
+ this.occlusion = void 0;
4411
4874
  this.activeSky?.dispose();
4412
4875
  this.activeSky = void 0;
4413
4876
  this.activeWeather?.dispose();
@@ -4457,9 +4920,10 @@ var WarmupInterest = class {
4457
4920
  return [...this.joined].map((warmup) => warmup.promise);
4458
4921
  }
4459
4922
  };
4460
- function createLane(background) {
4923
+ function createLane(background, urgent = false) {
4461
4924
  return {
4462
4925
  background,
4926
+ urgent,
4463
4927
  jobs: /* @__PURE__ */ new Set(),
4464
4928
  glAttributes: /* @__PURE__ */ new Set(),
4465
4929
  glBatches: []
@@ -4484,8 +4948,14 @@ function unselectedLodLevels(root, camera) {
4484
4948
  const unselected = /* @__PURE__ */ new Map();
4485
4949
  root.traverse((object) => {
4486
4950
  const lod = object;
4487
- if (!lod.isLOD || !lod.autoUpdate || lod.levels.length < 2) return;
4951
+ if (!lod.isLOD || !lod.autoUpdate) return;
4488
4952
  lod.update(camera);
4953
+ if (lod.levels.length === 0) {
4954
+ const hidden = lod.children.filter((child) => !child.visible);
4955
+ if (hidden.length > 0) unselected.set(lod, hidden);
4956
+ return;
4957
+ }
4958
+ if (lod.levels.length < 2) return;
4489
4959
  const selected = lod.getCurrentLevel();
4490
4960
  unselected.set(lod, lod.levels.filter((_, index) => index !== selected).map((level) => level.object));
4491
4961
  });
@@ -5039,4 +5509,4 @@ function decodeStarCatalog(input) {
5039
5509
  }));
5040
5510
  }
5041
5511
  //#endregion
5042
- export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, lerp3, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };
5512
+ export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, lerp3, liveryGraphicTexture, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };