@bendyline/molen-client 0.0.10 → 0.0.12

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,9 @@
1
1
  import { n as nlerp4, t as lerp3 } from "./math-ev_jEkRe.mjs";
2
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-BVZjf4T-.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-BliZYUY1.mjs";
4
+ import { createGlassVisual } from "./glass.mjs";
5
+ import { n as liveryGraphicTexture, t as applyLivery } from "./livery-qcDLzbU9.mjs";
6
+ import { a as cloudShellGeometry, i as cloudQualitySettings, n as CloudUniforms, o as createWebGlCloudMaterial, r as cloudDeckGeometry, s as cloudNoise, t as CloudTextures } from "./clouds-DmASLVoe.mjs";
4
7
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
5
8
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
6
9
  import * as THREE from "three";
@@ -154,10 +157,11 @@ var AdaptiveQualityController = class {
154
157
  const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
155
158
  const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
156
159
  const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
160
+ const measuredBoth = this.cpuSamples > 0 && this.gpuSamples > 0;
157
161
  const loading = this.loading;
158
162
  this.resetWindow();
159
163
  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;
164
+ const headroom = (!loading || measuredBoth) && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
161
165
  const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
162
166
  this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
163
167
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
@@ -576,6 +580,10 @@ function readTransform(components) {
576
580
  }
577
581
  function readRenderable(components) {
578
582
  const r = components.renderable;
583
+ if (r === void 0 && components.glass !== void 0) return {
584
+ kind: "glass",
585
+ ref: "glass"
586
+ };
579
587
  if (r?.kind === void 0 || r.ref === void 0) return void 0;
580
588
  return r;
581
589
  }
@@ -678,6 +686,8 @@ var SceneMirror = class {
678
686
  backend.updateRenderable(id, renderable);
679
687
  this.bound.set(id, key);
680
688
  }
689
+ backend.setLivery?.(id, comps?.livery);
690
+ backend.setGlass?.(id, comps?.glass, comps?.glassState);
681
691
  if (backend.setModelSignals) {
682
692
  const spec = comps?.["model.signals"];
683
693
  backend.setModelSignals(id, spec, readModelSignals(spec?.sources, (name) => comps?.[name]));
@@ -800,6 +810,7 @@ function createClientCore(opts) {
800
810
  let bufferTickRate;
801
811
  let awaitingKeyframe = false;
802
812
  let playbackPaused;
813
+ let active = true;
803
814
  const delayTicks = opts.interpolationDelayTicks;
804
815
  const nowMs = opts.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
805
816
  const eventHandlers = /* @__PURE__ */ new Map();
@@ -933,6 +944,10 @@ function createClientCore(opts) {
933
944
  sendCommand,
934
945
  command: (type, payload = {}) => sendCommand(localCommand(seq++, type, payload)),
935
946
  control: (action) => {
947
+ if (action.action === "set-active") {
948
+ if (action.active && !active) buffer?.resumeClock(nowMs());
949
+ active = action.active;
950
+ }
936
951
  if (action.action === "resume") {
937
952
  if (playbackPaused !== false) buffer?.resumeClock(nowMs());
938
953
  playbackPaused = false;
@@ -966,6 +981,49 @@ function describeLinkFailure(kind, ev) {
966
981
  return "kernel link error (no detail; the worker may have failed to load)";
967
982
  }
968
983
  //#endregion
984
+ //#region src/page-activity.ts
985
+ /** Observe whether the page is both visible and focused; reports the initial state immediately. */
986
+ function observePageActivity(onChange) {
987
+ if (typeof document === "undefined") return () => {};
988
+ const doc = document;
989
+ const win = doc.defaultView ?? (typeof window !== "undefined" ? window : void 0);
990
+ let focused = doc.hasFocus?.() ?? true;
991
+ let previous;
992
+ const update = () => {
993
+ const active = !doc.hidden && focused;
994
+ if (active === previous) return;
995
+ previous = active;
996
+ onChange(active);
997
+ };
998
+ const focus = () => {
999
+ focused = true;
1000
+ update();
1001
+ };
1002
+ const blur = () => {
1003
+ focused = false;
1004
+ update();
1005
+ };
1006
+ const visibility = () => {
1007
+ focused = doc.hasFocus?.() ?? focused;
1008
+ update();
1009
+ };
1010
+ win?.addEventListener?.("focus", focus);
1011
+ win?.addEventListener?.("blur", blur);
1012
+ doc.addEventListener("visibilitychange", visibility);
1013
+ const dispose = () => {
1014
+ win?.removeEventListener?.("focus", focus);
1015
+ win?.removeEventListener?.("blur", blur);
1016
+ doc.removeEventListener("visibilitychange", visibility);
1017
+ };
1018
+ try {
1019
+ update();
1020
+ } catch (error) {
1021
+ dispose();
1022
+ throw error;
1023
+ }
1024
+ return dispose;
1025
+ }
1026
+ //#endregion
969
1027
  //#region src/scene-bindings.ts
970
1028
  /**
971
1029
  * Apply a scene's `camera` block. `fixed` and `free-fly` pose the perspective camera (free-fly
@@ -1361,6 +1419,84 @@ var MaterialResolver = class {
1361
1419
  }
1362
1420
  };
1363
1421
  //#endregion
1422
+ //#region src/weather/cloud-shadows.ts
1423
+ function createCloudShadowUniforms(map) {
1424
+ return {
1425
+ molenCloudMap: { value: map },
1426
+ molenCloudShadow: { value: new THREE.Vector4(0, 0, 1, 0) },
1427
+ molenCloudField: { value: new THREE.Vector4() },
1428
+ molenCloudMix: { value: new THREE.Vector4() },
1429
+ molenCloudFit: { value: new THREE.Vector4(.15, 0, .35, 0) }
1430
+ };
1431
+ }
1432
+ const GLSL = `
1433
+ uniform sampler2D molenCloudMap;
1434
+ uniform vec4 molenCloudShadow;
1435
+ uniform vec4 molenCloudField;
1436
+ uniform vec4 molenCloudMix;
1437
+ uniform vec4 molenCloudFit;
1438
+ // Sunlight let through the cloud deck to a view-space point, toward a view-space light.
1439
+ float molenCloudShadowAt(vec3 viewPosition, vec3 viewLight) {
1440
+ if (molenCloudShadow.x <= 0.0) return 1.0;
1441
+ vec3 world = cameraPosition + (vec4(viewPosition, 0.0) * viewMatrix).xyz;
1442
+ vec3 light = (vec4(viewLight, 0.0) * viewMatrix).xyz;
1443
+ if (light.y <= 0.0) return 1.0;
1444
+ float base = molenCloudShadow.y;
1445
+ float top = molenCloudShadow.z;
1446
+ float castFrom = mix(base, top, molenCloudFit.z);
1447
+ vec2 xz = world.xz + light.xz * (max(castFrom - world.y, 0.0) / max(light.y, 0.05));
1448
+ vec4 w = textureLod(molenCloudMap, xz * molenCloudField.x + molenCloudField.yz, 0.0);
1449
+ float soft = molenCloudFit.x;
1450
+ float field = dot(w, molenCloudMix);
1451
+ float cover = clamp((field + molenCloudField.w * (1.0 + soft) - 1.0) / soft, 0.0, 1.0);
1452
+ cover *= 1.0 - molenCloudFit.w * (1.0 - field);
1453
+ // Above the layer there is nothing left to cast it.
1454
+ float below = 1.0 - smoothstep(base, top, world.y);
1455
+ return mix(1.0, exp(-cover * molenCloudFit.y), molenCloudShadow.x * below);
1456
+ }
1457
+ `;
1458
+ const TARGET = "getDirectionalLightInfo( directionalLight, directLight );";
1459
+ /** Add cloud shadows to a WebGL shader built from three's lighting chunks; false if none. */
1460
+ function injectCloudShadows(shader, uniforms) {
1461
+ const include = "#include <lights_fragment_begin>";
1462
+ const chunk = THREE.ShaderChunk.lights_fragment_begin;
1463
+ if (!shader.fragmentShader.includes(include) || !chunk.includes(TARGET)) return false;
1464
+ shader.fragmentShader = `${GLSL}\n${shader.fragmentShader.replace(include, chunk.replace(TARGET, `${TARGET}\n\t\tdirectLight.color *= molenCloudShadowAt( geometryPosition, directionalLight.direction );`))}`;
1465
+ Object.assign(shader.uniforms, uniforms);
1466
+ return true;
1467
+ }
1468
+ const registered = /* @__PURE__ */ new WeakMap();
1469
+ let original;
1470
+ /**
1471
+ * Give every lit shader `renderer` builds from now on the cloud shadow. Call before its first
1472
+ * frame. Returns a function that unregisters it.
1473
+ */
1474
+ function installWebGlCloudShadows(renderer, uniforms) {
1475
+ if (original === void 0) {
1476
+ const previous = THREE.Material.prototype.onBeforeCompile;
1477
+ original = previous;
1478
+ const hook = function(shader, target) {
1479
+ previous.call(this, shader, target);
1480
+ const own = registered.get(target);
1481
+ if (own !== void 0) injectCloudShadows(shader, own);
1482
+ };
1483
+ hook.toString = () => previous.toString();
1484
+ THREE.Material.prototype.onBeforeCompile = hook;
1485
+ }
1486
+ registered.set(renderer, uniforms);
1487
+ return () => {
1488
+ registered.delete(renderer);
1489
+ };
1490
+ }
1491
+ /**
1492
+ * Whether a material builds its own shader variations, beyond the renderer-wide cloud-shadow
1493
+ * hook every lit material shares.
1494
+ */
1495
+ function hasShaderHook(material) {
1496
+ const hook = material.onBeforeCompile;
1497
+ return hook !== THREE.Material.prototype.onBeforeCompile && hook !== original;
1498
+ }
1499
+ //#endregion
1364
1500
  //#region src/three/static-batches.ts
1365
1501
  /** Only renderer-owned, opaque, nonanimated meshes are admitted. Originals retain entity identity. */
1366
1502
  var StaticMeshBatches = class {
@@ -1388,9 +1524,9 @@ var StaticMeshBatches = class {
1388
1524
  const entries = [];
1389
1525
  object.traverseVisible((child) => {
1390
1526
  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;
1527
+ 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
1528
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
1393
- if (materials.some((m) => m.transparent || !m.depthWrite || !m.depthTest || m.transmission > 0 || m.isShaderMaterial || m.isNodeMaterial || m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile)) return;
1529
+ if (materials.some((m) => m.transparent || !m.depthWrite || !m.depthTest || m.transmission > 0 || m.isShaderMaterial || m.isNodeMaterial || hasShaderHook(m))) return;
1394
1530
  const matrix = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld);
1395
1531
  if (matrix.determinant() <= 0) return;
1396
1532
  const e = matrix.elements;
@@ -1574,7 +1710,9 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1574
1710
  animationTickRate = 30;
1575
1711
  objects = /* @__PURE__ */ new Map();
1576
1712
  gltf = /* @__PURE__ */ new Map();
1713
+ liveries = /* @__PURE__ */ new Map();
1577
1714
  modelSignals = /* @__PURE__ */ new Map();
1715
+ glass = /* @__PURE__ */ new Map();
1578
1716
  identities = /* @__PURE__ */ new Map();
1579
1717
  lights = /* @__PURE__ */ new Map();
1580
1718
  pointLightSlots = [];
@@ -1743,6 +1881,14 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1743
1881
  }
1744
1882
  create(id, renderable) {
1745
1883
  this.identities.set(id, this.identityOf(renderable));
1884
+ if (renderable.kind === "glass") {
1885
+ const group = new THREE.Group();
1886
+ group.name = id;
1887
+ group.visible = renderable.visible !== false;
1888
+ this.scene.add(group);
1889
+ this.objects.set(id, group);
1890
+ return;
1891
+ }
1746
1892
  if (renderable.kind !== "gltf" && renderable.kind !== "primitive") {
1747
1893
  this.createKind(id, renderable);
1748
1894
  return;
@@ -1803,10 +1949,12 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1803
1949
  return;
1804
1950
  }
1805
1951
  group.add(instance);
1952
+ this.bindLivery(id, instance);
1806
1953
  binding.clips = clips;
1807
1954
  this.bindModelSignals(id, instance);
1808
1955
  this.applyAnimation(id, binding, instance);
1809
1956
  this.applyModelSignals(id);
1957
+ this.bindGlass(id);
1810
1958
  this.batchDirty.add(id);
1811
1959
  }).catch((e) => {
1812
1960
  console.warn(`[molen] gltf "${renderable.ref}" failed to load: ${e.message}`);
@@ -1871,6 +2019,30 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1871
2019
  this.create(id, renderable);
1872
2020
  }
1873
2021
  /** Latest mirrored values are retained while the model loads. No simulation state is changed. */
2022
+ setLivery(id, data) {
2023
+ const previous = this.liveries.get(id);
2024
+ const key = data === void 0 ? void 0 : JSON.stringify(data);
2025
+ if (previous?.key === key) return;
2026
+ this.batches?.remove(id);
2027
+ this.batchDirty.add(id);
2028
+ previous?.visual?.dispose();
2029
+ this.liveries.delete(id);
2030
+ if (data !== void 0) {
2031
+ this.liveries.set(id, {
2032
+ key,
2033
+ data
2034
+ });
2035
+ const instance = this.gltf.has(id) ? this.objects.get(id)?.children[0] : void 0;
2036
+ if (instance) this.bindLivery(id, instance);
2037
+ }
2038
+ }
2039
+ bindLivery(id, instance) {
2040
+ const state = this.liveries.get(id);
2041
+ if (!state) return;
2042
+ state.visual = applyLivery(instance, state.data);
2043
+ for (const warning of state.visual.warnings) console.warn(`[molen] entity "${id}": livery ${warning}`);
2044
+ }
2045
+ /** Latest mirrored values are retained while the model loads. No simulation state is changed. */
1874
2046
  setModelSignals(id, spec, signals) {
1875
2047
  const previous = this.modelSignals.get(id);
1876
2048
  const key = spec === void 0 ? void 0 : JSON.stringify(spec);
@@ -1915,7 +2087,44 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1915
2087
  const state = this.modelSignals.get(id);
1916
2088
  state?.visual?.update(state.signals, this.animationTick / this.animationTickRate);
1917
2089
  }
2090
+ setGlass(id, data, state) {
2091
+ const key = data === void 0 ? void 0 : JSON.stringify(data);
2092
+ const previous = this.glass.get(id);
2093
+ if (key === previous?.key) {
2094
+ if (previous) previous.state = state;
2095
+ } else {
2096
+ previous?.visual?.dispose();
2097
+ this.glass.delete(id);
2098
+ this.batches?.remove(id);
2099
+ this.batchDirty.add(id);
2100
+ if (data) {
2101
+ this.glass.set(id, {
2102
+ key,
2103
+ data,
2104
+ state
2105
+ });
2106
+ if (!this.gltf.has(id) || this.objects.get(id)?.children.length) this.bindGlass(id);
2107
+ }
2108
+ }
2109
+ this.applyGlass(id);
2110
+ }
2111
+ bindGlass(id) {
2112
+ const binding = this.glass.get(id), object = this.objects.get(id);
2113
+ if (!binding || !object) return;
2114
+ binding.visual?.dispose();
2115
+ binding.visual = createGlassVisual(object, binding.data);
2116
+ if (binding.visual.missingNodes.length) console.warn(`[molen] entity "${id}": glass missing nodes: ${binding.visual.missingNodes.join(", ")}`);
2117
+ this.applyGlass(id);
2118
+ }
2119
+ applyGlass(id) {
2120
+ const binding = this.glass.get(id);
2121
+ binding?.visual?.update(binding.state, this.animationTick / this.animationTickRate);
2122
+ }
1918
2123
  destroy(id) {
2124
+ this.glass.get(id)?.visual?.dispose();
2125
+ this.glass.delete(id);
2126
+ this.liveries.get(id)?.visual?.dispose();
2127
+ this.liveries.delete(id);
1919
2128
  this.modelSignals.delete(id);
1920
2129
  this.batches?.remove(id);
1921
2130
  this.batchDirty.delete(id);
@@ -1968,6 +2177,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
1968
2177
  else obj.scale.set(1, 1, 1);
1969
2178
  if (changed || obj.matrixAutoUpdate) obj.updateMatrix();
1970
2179
  obj.matrixAutoUpdate = this.escaped.has(id);
2180
+ this.applyGlass(id);
1971
2181
  }
1972
2182
  const light = this.lights.get(id);
1973
2183
  if (light !== void 0) {
@@ -2036,6 +2246,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2036
2246
  if (binding) this.poseAnimation(binding);
2037
2247
  }
2038
2248
  for (const id of this.modelSignals.keys()) this.applyModelSignals(id);
2249
+ for (const id of this.glass.keys()) this.applyGlass(id);
2039
2250
  for (const handle of this.handles.values()) handle.setTick?.(tick, tickRate, void 0);
2040
2251
  if (this.pointLightSlots.length > 0 && this.renderer) this.updateLocalLights(this.renderer.camera);
2041
2252
  }
@@ -2044,11 +2255,11 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2044
2255
  for (const id of this.batchDirty) {
2045
2256
  const object = this.objects.get(id);
2046
2257
  if (!object || this.escaped.has(id) || this.handles.has(id)) continue;
2047
- if (!this.animations.has(id) && !this.modelSignals.has(id)) object.traverse((child) => {
2258
+ if (!this.animations.has(id) && !this.modelSignals.has(id) && !this.glass.has(id)) object.traverse((child) => {
2048
2259
  child.updateMatrix();
2049
2260
  child.matrixAutoUpdate = false;
2050
2261
  });
2051
- if (!this.dynamic.has(id) && !this.animations.has(id) && !this.modelSignals.has(id)) this.batches?.add(id, object);
2262
+ if (!this.dynamic.has(id) && !this.animations.has(id) && !this.modelSignals.has(id) && !this.glass.has(id)) this.batches?.add(id, object);
2052
2263
  }
2053
2264
  this.batchDirty.clear();
2054
2265
  this.batches?.flush();
@@ -2087,6 +2298,7 @@ var ThreeSceneBackend = class ThreeSceneBackend {
2087
2298
  this.lastPoseTick.set(id, tick);
2088
2299
  }
2089
2300
  for (const id of this.modelSignals.keys()) if (!this.animations.has(id)) this.applyModelSignals(id);
2301
+ for (const id of this.glass.keys()) this.applyGlass(id);
2090
2302
  for (const [id, handle] of this.handles) {
2091
2303
  if (handle.setTick === void 0) continue;
2092
2304
  const object = handle.object;
@@ -2233,11 +2445,16 @@ var FrameAdmissionQueue = class {
2233
2445
  queuedBackground = /* @__PURE__ */ new WeakMap();
2234
2446
  scheduled = false;
2235
2447
  disposed = false;
2448
+ paused = false;
2236
2449
  clock;
2237
2450
  schedule;
2238
2451
  maxMs;
2239
2452
  maxBytes;
2240
2453
  maxJobs;
2454
+ urgentStreak = 0;
2455
+ orderedStreak = 0;
2456
+ /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
2457
+ expected = /* @__PURE__ */ new Map();
2241
2458
  constructor(options = {}) {
2242
2459
  this.options = options;
2243
2460
  this.clock = options.now ?? (() => performance.now());
@@ -2248,11 +2465,20 @@ var FrameAdmissionQueue = class {
2248
2465
  this.maxMs = options.maxMilliseconds ?? 2;
2249
2466
  this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
2250
2467
  this.maxJobs = options.maxJobs ?? 32;
2251
- if (![
2252
- this.maxMs,
2253
- this.maxBytes,
2254
- this.maxJobs
2255
- ].every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2468
+ this.setLimits({});
2469
+ }
2470
+ /**
2471
+ * Change the per-frame budget from the next frame on; omitted limits keep their values. A host
2472
+ * can admit more when frames have time to spare (an adaptive quality tier, say).
2473
+ */
2474
+ setLimits(limits) {
2475
+ const next = [
2476
+ limits.maxMilliseconds ?? this.maxMs,
2477
+ limits.maxBytes ?? this.maxBytes,
2478
+ limits.maxJobs ?? this.maxJobs
2479
+ ];
2480
+ if (!next.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2481
+ [this.maxMs, this.maxBytes, this.maxJobs] = next;
2256
2482
  }
2257
2483
  run(task, options = {}) {
2258
2484
  if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
@@ -2276,7 +2502,11 @@ var FrameAdmissionQueue = class {
2276
2502
  }
2277
2503
  };
2278
2504
  options.signal?.addEventListener("abort", job.abort, { once: true });
2279
- (options.priority === "background" ? this.background : this.jobs).push(job);
2505
+ if (options.priority === "background") this.background.push(job);
2506
+ else if (options.priority === "urgent") {
2507
+ const after = this.jobs.findIndex((queued) => queued.options.priority !== "urgent");
2508
+ this.jobs.splice(after < 0 ? this.jobs.length : after, 0, job);
2509
+ } else this.jobs.push(job);
2280
2510
  this.request();
2281
2511
  });
2282
2512
  if (options.priority === "background") {
@@ -2316,8 +2546,13 @@ var FrameAdmissionQueue = class {
2316
2546
  get pending() {
2317
2547
  return this.jobs.length + this.background.length;
2318
2548
  }
2549
+ /** Hold queued uploads/preparation while the view is inactive; keep resources for resume. */
2550
+ setPaused(paused) {
2551
+ this.paused = paused;
2552
+ if (!paused) this.request();
2553
+ }
2319
2554
  request() {
2320
- if (this.scheduled || this.disposed || this.pending === 0) return;
2555
+ if (this.scheduled || this.disposed || this.paused || this.pending === 0) return;
2321
2556
  this.scheduled = true;
2322
2557
  this.schedule(() => {
2323
2558
  this.scheduled = false;
@@ -2326,22 +2561,37 @@ var FrameAdmissionQueue = class {
2326
2561
  }
2327
2562
  /** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
2328
2563
  flush() {
2329
- if (this.disposed) return;
2564
+ if (this.disposed || this.paused) return;
2330
2565
  const start = this.clock();
2331
2566
  let bytes = 0, count = 0;
2332
2567
  for (;;) {
2333
2568
  const lane = this.jobs.length > 0 ? this.jobs : this.background;
2334
- const next = lane[0];
2569
+ const waitingNormal = lane === this.jobs && this.urgentStreak >= 2 ? lane.findIndex((job) => job.options.priority !== "urgent") : -1;
2570
+ let index = waitingNormal >= 0 && this.clock() - lane[waitingNormal].queued >= 50 ? waitingNormal : 0;
2571
+ if (lane === this.jobs && lane[index]?.options.priority !== "urgent" && this.orderedStreak < 3) {
2572
+ let best = Number.POSITIVE_INFINITY;
2573
+ for (let i = index; i < lane.length; i++) {
2574
+ const order = lane[i]?.options.order?.() ?? Number.POSITIVE_INFINITY;
2575
+ if (order < best) {
2576
+ best = order;
2577
+ index = i;
2578
+ }
2579
+ }
2580
+ }
2581
+ const next = lane[index];
2335
2582
  if (next === void 0) break;
2336
2583
  const cost = next.options.bytes ?? 0;
2337
- if (count > 0 && (count >= this.maxJobs || this.clock() - start >= this.maxMs || bytes + cost > this.maxBytes)) break;
2338
- lane.shift();
2584
+ const label = next.options.label ?? "admission";
2585
+ if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > this.maxMs || bytes + cost > this.maxBytes)) break;
2586
+ lane.splice(index, 1);
2339
2587
  this.forget(next);
2340
2588
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
2341
2589
  if (next.options.signal?.aborted) {
2342
2590
  next.reject(new DOMException("Admission cancelled", "AbortError"));
2343
2591
  continue;
2344
2592
  }
2593
+ this.urgentStreak = next.options.priority === "urgent" ? this.urgentStreak + 1 : 0;
2594
+ if (next.options.priority !== "urgent") this.orderedStreak = next.options.order !== void 0 && this.orderedStreak < 3 ? this.orderedStreak + 1 : 0;
2345
2595
  const began = this.clock();
2346
2596
  try {
2347
2597
  next.resolve(next.run());
@@ -2349,10 +2599,12 @@ var FrameAdmissionQueue = class {
2349
2599
  next.reject(error);
2350
2600
  }
2351
2601
  const workMs = this.clock() - began;
2602
+ const previous = this.expected.get(label);
2603
+ this.expected.set(label, previous === void 0 ? workMs : previous + (workMs - previous) * .25);
2352
2604
  count++;
2353
2605
  bytes += cost;
2354
2606
  this.options.onSample?.({
2355
- label: next.options.label ?? "admission",
2607
+ label,
2356
2608
  queueMs: began - next.queued,
2357
2609
  workMs,
2358
2610
  bytes: cost,
@@ -2575,6 +2827,8 @@ function starDirection(rightAscensionDeg, declinationDeg, state) {
2575
2827
  //#endregion
2576
2828
  //#region src/sky/visual.ts
2577
2829
  const RAD$1 = Math.PI / 180;
2830
+ /** Sky motion (radians) before the dome and stars redraw: about half a pixel at 70 degrees. */
2831
+ const SKY_REDRAW_ANGLE = 4e-4;
2578
2832
  const clamp$3 = (x) => Math.max(0, Math.min(1, x));
2579
2833
  const rgb$1 = (color) => [
2580
2834
  color.r,
@@ -2642,7 +2896,15 @@ var SkyVisual = class {
2642
2896
  catalog;
2643
2897
  palette;
2644
2898
  lastTime;
2899
+ /**
2900
+ * What the dome's colors and the stars were last written for. The sun and the sky turn a
2901
+ * quarter of a degree a minute: rewriting the dome and every star each second cost a frame
2902
+ * 3-5 ms for changes far below a pixel, so they are rewritten once those changes could show.
2903
+ */
2904
+ drawnDome;
2905
+ drawnStars;
2645
2906
  cloudAttenuation = 0;
2907
+ directCloudAttenuation = 0;
2646
2908
  currentFrame;
2647
2909
  currentReflections;
2648
2910
  disposed = false;
@@ -2695,11 +2957,17 @@ var SkyVisual = class {
2695
2957
  get reflectionState() {
2696
2958
  return this.currentReflections;
2697
2959
  }
2698
- /** Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry. */
2699
- setCloudAttenuation(value) {
2960
+ /**
2961
+ * Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry.
2962
+ * `direct` dims the sun and moon (default `value`); with spatial cloud shadows it is 0, since
2963
+ * the shadows themselves take light away where clouds cover the sun.
2964
+ */
2965
+ setCloudAttenuation(value, direct = value) {
2700
2966
  const next = clamp$3(value);
2701
- if (next === this.cloudAttenuation) return;
2967
+ const nextDirect = clamp$3(direct);
2968
+ if (next === this.cloudAttenuation && nextDirect === this.directCloudAttenuation) return;
2702
2969
  this.cloudAttenuation = next;
2970
+ this.directCloudAttenuation = nextDirect;
2703
2971
  this.lastTime = void 0;
2704
2972
  }
2705
2973
  /** Move an Earth observer without rebuilding the dome, bodies or star catalog. */
@@ -2720,6 +2988,10 @@ var SkyVisual = class {
2720
2988
  const data = this.data;
2721
2989
  const time = data.mode === "earth" ? Math.floor(skyTimeMs(data.time, simulationSeconds) / 1e3) * 1e3 : 0;
2722
2990
  if (time === this.lastTime) return this.currentFrame;
2991
+ if (this.lastTime === void 0) {
2992
+ this.drawnDome = void 0;
2993
+ this.drawnStars = void 0;
2994
+ }
2723
2995
  this.lastTime = time;
2724
2996
  const earth = data.mode === "earth" ? evaluateEarthSky(time, data.observer) : void 0;
2725
2997
  const sunDirection = earth?.sun.direction ?? skyDirection(data.mode === "custom" ? data.sunBody.direction : [
@@ -2767,8 +3039,15 @@ var SkyVisual = class {
2767
3039
  this.ambientLight.color.copy(this.palette.nightHorizon).lerp(this.palette.dayHorizon, daylight);
2768
3040
  this.ambientLight.groundColor.copy(this.palette.ground);
2769
3041
  this.ambientLight.intensity = (light?.nightAmbient ?? .025) * (1 - daylight) + (light?.dayAmbient ?? .6) * daylight;
2770
- this.sunLight.intensity *= 1 - this.cloudAttenuation * .92;
2771
- this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
3042
+ const reference = light?.referenceElevation;
3043
+ if (reference !== void 0 && altitude > reference) {
3044
+ const level = (degrees) => this.ambientLight.intensity + this.sunLight.intensity * Math.sin(degrees * RAD$1);
3045
+ const scale = level(reference) / level(altitude);
3046
+ this.sunLight.intensity *= scale;
3047
+ this.ambientLight.intensity *= scale;
3048
+ }
3049
+ this.sunLight.intensity *= 1 - this.directCloudAttenuation * .92;
3050
+ this.moonLight.intensity *= 1 - this.directCloudAttenuation * .9;
2772
3051
  this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
2773
3052
  this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
2774
3053
  const radiance = this.ambientLight.intensity / Math.PI;
@@ -2823,6 +3102,12 @@ var SkyVisual = class {
2823
3102
  ]), 200);
2824
3103
  }
2825
3104
  updateDome(altitude, sun, daylight) {
3105
+ const drawn = this.drawnDome;
3106
+ if (drawn !== void 0 && drawn.sun.distanceToSquared(sun) < SKY_REDRAW_ANGLE ** 2 && Math.abs(drawn.daylight - daylight) < .001) return;
3107
+ this.drawnDome = {
3108
+ sun: sun.clone(),
3109
+ daylight
3110
+ };
2826
3111
  const colors = this.dome.geometry.getAttribute("color");
2827
3112
  const positions = this.dome.geometry.getAttribute("position");
2828
3113
  const horizon = this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight);
@@ -2890,6 +3175,13 @@ var SkyVisual = class {
2890
3175
  updateStars(rotation, visibility, moon, moonDiameter) {
2891
3176
  this.stars.visible = visibility > 0 && this.catalog.length > 0;
2892
3177
  if (!this.stars.visible) return;
3178
+ const drawn = this.drawnStars;
3179
+ 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;
3180
+ this.drawnStars = {
3181
+ rotation: rotation.clone(),
3182
+ visibility,
3183
+ moon: moon?.clone()
3184
+ };
2893
3185
  const positions = this.stars.geometry.getAttribute("position");
2894
3186
  const colors = this.stars.geometry.getAttribute("color");
2895
3187
  const d = new THREE.Vector3(), right = new THREE.Vector3(), up = new THREE.Vector3(), p = new THREE.Vector3();
@@ -2946,32 +3238,36 @@ function hash(x, y, seed) {
2946
3238
  h = Math.imul(h ^ h >>> 13, 1274126177);
2947
3239
  return ((h ^ h >>> 16) >>> 0) / 4294967296;
2948
3240
  }
2949
- function noise(x, y, period, seed) {
2950
- const ix = Math.floor(x), iy = Math.floor(y);
2951
- const fx = smooth$1(0, 1, x - ix), fy = smooth$1(0, 1, y - iy);
2952
- const a = hash(wrap(ix, period), wrap(iy, period), seed);
2953
- const b = hash(wrap(ix + 1, period), wrap(iy, period), seed);
2954
- const c = hash(wrap(ix, period), wrap(iy + 1, period), seed);
2955
- const d = hash(wrap(ix + 1, period), wrap(iy + 1, period), seed);
2956
- return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
2957
- }
2958
- /** Cloud texture texels per side: about 47 m each at the explorer's 24 km cloud scale. */
2959
- const CLOUD_RESOLUTION = 512;
2960
3241
  const PARTICLE_LIMIT = 1400;
3242
+ /** Visibility below which murk veils the sky as well as the ground, meters. */
3243
+ const VEIL_VISIBILITY = 2e4;
3244
+ /** Depth of the hazy air a view looking straight up crosses, meters. */
3245
+ const HAZE_DEPTH = 1500;
2961
3246
  /**
2962
- * Lightweight layered clouds and local precipitation with standard materials on both graphics
2963
- * backends. Patterns are seeded and sampled at absolute simulation time, not integrated frames.
2964
- * Cloud layers use absolute world altitudes; particles are visual and do not accumulate or collide.
3247
+ * Volumetric clouds, a high cirrus layer and local precipitation on both graphics backends.
3248
+ * Patterns are seeded and sampled at absolute simulation time, not integrated frames. Cloud
3249
+ * layers use absolute world altitudes; particles are visual and do not accumulate or collide.
2965
3250
  */
2966
3251
  var WeatherVisual = class {
2967
3252
  object = new THREE.Group();
2968
3253
  fog = new THREE.Fog("#c1c9cd", 0, 5e4);
2969
3254
  state;
2970
- cloudNoise;
2971
- cloudTexture;
2972
- cloudLayers = [];
2973
- cloudKey = "";
2974
- noiseSeed;
3255
+ textures;
3256
+ ownsTextures;
3257
+ createCloudMaterial;
3258
+ noiseBudgetMs;
3259
+ uniforms = new CloudUniforms();
3260
+ quality;
3261
+ cloudMaterial;
3262
+ deck;
3263
+ shells;
3264
+ deckReady = false;
3265
+ cirrus;
3266
+ cirrusCoverage;
3267
+ backend;
3268
+ /** Murk over the sky in poor visibility; see updateVeil. */
3269
+ veil;
3270
+ veilVisibility;
2975
3271
  particles;
2976
3272
  particleTexture;
2977
3273
  cameraPosition = new THREE.Vector3();
@@ -2979,9 +3275,15 @@ var WeatherVisual = class {
2979
3275
  up = new THREE.Vector3();
2980
3276
  color = new THREE.Color();
2981
3277
  disposed = false;
2982
- constructor(data) {
3278
+ constructor(data, options = {}) {
2983
3279
  this.state = resolveWeather$1(weatherSchema.parse(data));
2984
3280
  this.object.name = "molen:weather";
3281
+ this.ownsTextures = options.textures === void 0;
3282
+ this.textures = options.textures ?? new CloudTextures(cloudNoise());
3283
+ this.createCloudMaterial = options.createCloudMaterial;
3284
+ this.quality = options.quality ?? "medium";
3285
+ this.noiseBudgetMs = options.noiseBudgetMs ?? 3;
3286
+ this.backend = options.backend ?? "webgl";
2985
3287
  }
2986
3288
  /** Resolved copy; editing it does not change the visual. */
2987
3289
  get data() {
@@ -2995,9 +3297,32 @@ var WeatherVisual = class {
2995
3297
  get cloudAttenuation() {
2996
3298
  return this.state.clouds.coverage * this.state.clouds.density;
2997
3299
  }
3300
+ /** Per-pixel cloud work. Uniform-driven: changing it rebuilds nothing. */
3301
+ setCloudQuality(quality) {
3302
+ this.quality = quality;
3303
+ }
3304
+ get cloudQuality() {
3305
+ return this.quality;
3306
+ }
3307
+ /**
3308
+ * Whether lit surfaces get spatial cloud shadows this frame: from 'high' quality, once the
3309
+ * clouds have appeared. While they do, direct light needs no uniform cloud dimming.
3310
+ */
3311
+ get shadowsActive() {
3312
+ return cloudQualitySettings(this.quality).shadows && this.deckVisible() && this.deckReady;
3313
+ }
3314
+ /** Write this frame's cloud shadow into a renderer's lit-shader uniforms. */
3315
+ writeShadows(uniforms, active = this.shadowsActive) {
3316
+ const u = this.uniforms;
3317
+ uniforms.molenCloudShadow.value.set(active ? 1 : 0, u.slab.x, u.slab.y, 0);
3318
+ uniforms.molenCloudField.value.copy(u.field);
3319
+ uniforms.molenCloudMix.value.copy(u.mix);
3320
+ uniforms.molenCloudFit.value.set(u.erode.z, u.shadowDepth, .35, u.relief.x);
3321
+ }
3322
+ /** Cloud layers drawn (the volumetric layer and cirrus) and precipitation particles. */
2998
3323
  get stats() {
2999
3324
  return {
3000
- cloudLayers: this.cloudLayers.filter((layer) => layer.visible).length,
3325
+ cloudLayers: Number(this.deck?.visible === true || this.shells?.visible === true) + Number(this.cirrus?.visible === true),
3001
3326
  particles: this.particles?.visible ? this.particles.geometry.drawRange.count / 6 : 0
3002
3327
  };
3003
3328
  }
@@ -3010,16 +3335,21 @@ var WeatherVisual = class {
3010
3335
  this.right.setFromMatrixColumn(camera.matrixWorld, 0).normalize();
3011
3336
  this.up.setFromMatrixColumn(camera.matrixWorld, 1).normalize();
3012
3337
  const daylight = sky?.daylight ?? 1;
3013
- this.updateClouds(seconds, camera, origin, daylight, sky?.sunDirection ?? [
3014
- .3,
3015
- .8,
3016
- .2
3017
- ]);
3338
+ this.updateClouds(seconds, camera, origin, daylight, sky);
3018
3339
  this.updateParticles(seconds, origin, daylight);
3019
3340
  this.object.updateMatrixWorld(true);
3020
3341
  }
3021
- /** Combine weather visibility with an authored/streaming fog limit without mutating it. */
3342
+ /**
3343
+ * Combine weather visibility with an authored/streaming fog limit without mutating it. The
3344
+ * clouds are fogged with the result (see CloudUniforms.setFog).
3345
+ */
3022
3346
  fogFor(base, sky) {
3347
+ const fog = this.limitFog(base, sky);
3348
+ this.veil?.material.color.copy(fog.color);
3349
+ this.uniforms.setFog(fog, 1 - smooth$1(.5, .9, this.cloudAttenuation));
3350
+ return fog;
3351
+ }
3352
+ limitFog(base, sky) {
3023
3353
  const visibility = this.state.visibility;
3024
3354
  if (base instanceof THREE.Fog && base.far <= visibility) return base;
3025
3355
  if (base instanceof THREE.FogExp2 && base.density >= 2 / visibility) return base;
@@ -3028,19 +3358,115 @@ var WeatherVisual = class {
3028
3358
  this.fog.near = Math.min(this.fog.near, this.fog.far * .1);
3029
3359
  if (base) this.fog.color.copy(base.color);
3030
3360
  else this.fog.color.set("#0b1220").lerp(this.color.set("#c1c9cd"), sky?.daylight ?? 1);
3361
+ const overcast = smooth$1(.5, .9, this.cloudAttenuation);
3362
+ if (overcast > 0) {
3363
+ const { r, g, b } = this.fog.color;
3364
+ const grey = (r * .2126 + g * .7152 + b * .0722) * .85;
3365
+ this.fog.color.lerp(this.color.setRGB(grey, grey, grey), overcast * .8);
3366
+ }
3031
3367
  return this.fog;
3032
3368
  }
3033
- buildClouds() {
3034
- const texture = new THREE.DataTexture(new Uint8Array(CLOUD_RESOLUTION ** 2 * 4), CLOUD_RESOLUTION, CLOUD_RESOLUTION);
3035
- texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
3036
- texture.magFilter = THREE.LinearFilter;
3037
- texture.minFilter = THREE.LinearMipmapLinearFilter;
3038
- texture.anisotropy = 16;
3039
- texture.generateMipmaps = true;
3040
- texture.colorSpace = THREE.LinearSRGBColorSpace;
3041
- this.cloudTexture = texture;
3042
- for (let i = 0; i < 2; i++) {
3043
- const geometry = new THREE.PlaneGeometry(1, 1, 24, 24);
3369
+ deckVisible() {
3370
+ const { coverage, density } = this.state.clouds;
3371
+ return coverage > 0 && density > 0;
3372
+ }
3373
+ buildDeck() {
3374
+ const material = this.createCloudMaterial?.(this.uniforms, this.textures) ?? createWebGlCloudMaterial(this.uniforms, this.textures);
3375
+ this.cloudMaterial = material;
3376
+ this.deck = new THREE.Mesh(cloudDeckGeometry(), material);
3377
+ this.deck.name = "molen:cloud-deck";
3378
+ this.shells = new THREE.Mesh(cloudShellGeometry(), material);
3379
+ this.shells.name = "molen:cloud-shells";
3380
+ for (const mesh of [this.deck, this.shells]) {
3381
+ mesh.frustumCulled = false;
3382
+ mesh.visible = false;
3383
+ this.object.add(mesh);
3384
+ }
3385
+ }
3386
+ updateClouds(seconds, camera, origin, daylight, sky) {
3387
+ const { clouds } = this.state;
3388
+ const deck = this.deckVisible();
3389
+ const wanted = [...deck ? [
3390
+ "weather",
3391
+ "shape",
3392
+ "detail"
3393
+ ] : [], ...clouds.cirrus > 0 ? ["cirrus"] : []];
3394
+ if (wanted.length > 0) this.textures.noise.build(wanted, this.noiseBudgetMs);
3395
+ this.deckReady = this.textures.sync();
3396
+ const far = camera instanceof THREE.PerspectiveCamera || camera instanceof THREE.OrthographicCamera ? camera.far : 5e4;
3397
+ this.uniforms.update(this.state, seconds, origin, far, this.quality, sky);
3398
+ if (deck && this.deckReady && !this.deck) this.buildDeck();
3399
+ if (this.deck && this.shells) {
3400
+ const shown = deck && this.deckReady;
3401
+ const altitude = this.cameraPosition.y + origin[1];
3402
+ const top = clouds.baseAltitude + clouds.thickness;
3403
+ const inside = altitude > clouds.baseAltitude && altitude < top;
3404
+ this.deck.visible = shown && !inside;
3405
+ this.shells.visible = shown && inside;
3406
+ const slab = this.uniforms.slab;
3407
+ this.deck.position.set(this.cameraPosition.x, altitude <= clouds.baseAltitude ? slab.x : slab.y, this.cameraPosition.z);
3408
+ this.deck.scale.set(2 * slab.w, 1, 2 * slab.w);
3409
+ this.shells.position.copy(this.cameraPosition);
3410
+ }
3411
+ this.updateCirrus(seconds, origin, far, daylight, sky?.sunDirection ?? [
3412
+ .3,
3413
+ .8,
3414
+ .2
3415
+ ]);
3416
+ this.updateVeil(far);
3417
+ }
3418
+ /**
3419
+ * In fog, rain or snow the murk hides the sky too, not only the ground: a camera-centred
3420
+ * dome in the fog color, behind everything nearer, opaque toward the horizon and thinner
3421
+ * overhead, where a view crosses less hazy air. Clouds draw over it, and a fully hazed cloud
3422
+ * shows it. Absent in clear air (visibility from 20 km).
3423
+ */
3424
+ updateVeil(far) {
3425
+ const visibility = this.state.visibility;
3426
+ const shown = visibility < VEIL_VISIBILITY;
3427
+ if (this.veil) this.veil.visible = shown;
3428
+ if (!shown) return;
3429
+ if (!this.veil) {
3430
+ const geometry = new THREE.SphereGeometry(1, 32, 16);
3431
+ geometry.setAttribute("color", new THREE.BufferAttribute(new Float32Array(geometry.getAttribute("position").count * 4), 4));
3432
+ this.veil = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
3433
+ vertexColors: true,
3434
+ transparent: true,
3435
+ depthWrite: false,
3436
+ side: THREE.BackSide,
3437
+ fog: false,
3438
+ toneMapped: this.backend === "webgpu"
3439
+ }));
3440
+ this.veil.name = "molen:visibility-veil";
3441
+ this.veil.renderOrder = -1;
3442
+ this.veil.frustumCulled = false;
3443
+ this.object.add(this.veil);
3444
+ }
3445
+ if (visibility !== this.veilVisibility) {
3446
+ this.veilVisibility = visibility;
3447
+ const positions = this.veil.geometry.getAttribute("position");
3448
+ const colors = this.veil.geometry.getAttribute("color");
3449
+ const strength = smooth$1(VEIL_VISIBILITY, VEIL_VISIBILITY * .4, visibility);
3450
+ for (let i = 0; i < positions.count; i++) {
3451
+ const path = HAZE_DEPTH / Math.max(Math.abs(positions.getY(i)), .03);
3452
+ colors.setXYZW(i, 1, 1, 1, (1 - Math.exp(-3 * path / visibility)) * strength);
3453
+ }
3454
+ colors.needsUpdate = true;
3455
+ }
3456
+ this.veil.scale.setScalar(Math.min(far * .9, Math.max(1500, visibility * 2)));
3457
+ this.veil.position.copy(this.cameraPosition);
3458
+ }
3459
+ /**
3460
+ * Cirrus are thin ice streaks combed out by the jet stream, so this layer is a flat sheet: a
3461
+ * stretched texture turned to lie along the wind, at the cirrus altitude.
3462
+ */
3463
+ updateCirrus(seconds, origin, far, daylight, sun) {
3464
+ const { clouds, atmosphere } = this.state;
3465
+ const ready = clouds.cirrus > 0 && this.textures.noise.has("cirrus");
3466
+ if (this.cirrus) this.cirrus.visible = ready;
3467
+ if (!ready) return;
3468
+ if (!this.cirrus) {
3469
+ const geometry = new THREE.PlaneGeometry(1, 1, 16, 16);
3044
3470
  geometry.rotateX(-Math.PI / 2);
3045
3471
  const positions = geometry.getAttribute("position");
3046
3472
  const colors = new Float32Array(positions.count * 4);
@@ -3050,83 +3476,52 @@ var WeatherVisual = class {
3050
3476
  1,
3051
3477
  1,
3052
3478
  1,
3053
- 1 - smooth$1(.6, 1, r)
3479
+ 1 - smooth$1(.55, 1, r)
3054
3480
  ], j * 4);
3055
3481
  }
3056
3482
  geometry.setAttribute("color", new THREE.BufferAttribute(colors, 4));
3057
- const map = i === 0 ? texture : texture.clone();
3058
- const material = new THREE.MeshBasicMaterial({
3059
- map,
3483
+ this.cirrus = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
3484
+ map: this.textures.cirrus,
3060
3485
  vertexColors: true,
3061
3486
  transparent: true,
3062
3487
  side: THREE.DoubleSide,
3063
- depthWrite: false,
3064
- fog: false
3065
- });
3066
- const layer = new THREE.Mesh(geometry, material);
3067
- layer.name = `molen:cloud-layer-${i}`;
3068
- layer.frustumCulled = false;
3069
- this.cloudLayers.push(layer);
3070
- this.object.add(layer);
3071
- }
3072
- }
3073
- updateClouds(seconds, camera, origin, daylight, sun) {
3074
- const { clouds, seed, atmosphere } = this.state;
3075
- const visible = clouds.coverage > 0 && clouds.density > 0;
3076
- if (visible && !this.cloudTexture) this.buildClouds();
3077
- for (const layer of this.cloudLayers) layer.visible = visible;
3078
- if (!visible) return;
3079
- if (seed !== this.noiseSeed) {
3080
- this.noiseSeed = seed;
3081
- this.cloudKey = "";
3082
- this.cloudNoise = new Float32Array(CLOUD_RESOLUTION ** 2);
3083
- for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
3084
- let value = 0, weight = 0;
3085
- for (let octave = 0; octave < 5; octave++) {
3086
- const frequency = 8 * 2 ** octave, amplitude = .52 ** octave;
3087
- value += noise(x / CLOUD_RESOLUTION * frequency, y / CLOUD_RESOLUTION * frequency, frequency, seed + octave) * amplitude;
3088
- weight += amplitude;
3089
- }
3090
- this.cloudNoise[y * CLOUD_RESOLUTION + x] = value / weight;
3091
- }
3488
+ depthWrite: false
3489
+ }));
3490
+ this.cirrus.name = "molen:cirrus";
3491
+ this.cirrus.frustumCulled = false;
3492
+ this.object.add(this.cirrus);
3092
3493
  }
3093
- const key = `${clouds.coverage},${clouds.density},${sun.map((v) => Math.round(v * 20)).join(",")}`;
3094
- if (key !== this.cloudKey && this.cloudTexture && this.cloudNoise) {
3095
- this.cloudKey = key;
3096
- const pixels = this.cloudTexture.image.data;
3097
- const field = this.cloudNoise;
3098
- const threshold = .78 - clouds.coverage * .62;
3099
- for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
3100
- const i = y * CLOUD_RESOLUTION + x, n = field[i] ?? 0;
3101
- const dx = (field[y * CLOUD_RESOLUTION + (x + 1) % CLOUD_RESOLUTION] ?? n) - n;
3102
- const dz = (field[(y + 1) % CLOUD_RESOLUTION * CLOUD_RESOLUTION + x] ?? n) - n;
3103
- const shade = clamp$2(.56 + (1 - smooth$1(threshold, threshold + .25, n)) * .3 + (dx * sun[0] + dz * sun[2]) * 4 - clouds.density * .15);
3104
- const alpha = smooth$1(threshold - .075, threshold + .075, n) * (1 - Math.exp(-clouds.density * 6));
3105
- pixels.set([
3106
- shade * 255,
3107
- shade * 255,
3108
- shade * 255,
3109
- alpha * 255
3110
- ], i * 4);
3494
+ if (clouds.cirrus !== this.cirrusCoverage) {
3495
+ this.cirrusCoverage = clouds.cirrus;
3496
+ const noise = this.textures.noise.cirrus;
3497
+ const pixels = this.textures.cirrus.image.data;
3498
+ const threshold = 1 - clouds.cirrus;
3499
+ for (let i = 0; i < 256 ** 2; i++) {
3500
+ const alpha = smooth$1(threshold - .1, threshold + .35, (noise[i] ?? 0) / 255);
3501
+ pixels[i * 4] = pixels[i * 4 + 1] = pixels[i * 4 + 2] = 255;
3502
+ pixels[i * 4 + 3] = Math.round(alpha * 200);
3111
3503
  }
3112
- for (const layer of this.cloudLayers) if (layer.material.map) layer.material.map.needsUpdate = true;
3504
+ this.textures.cirrus.needsUpdate = true;
3113
3505
  }
3114
- const far = camera instanceof THREE.PerspectiveCamera || camera instanceof THREE.OrthographicCamera ? camera.far : 5e4;
3506
+ const layer = this.cirrus;
3115
3507
  const size = Math.max(2e3, Math.min(16e4, far * 1.4));
3116
- const absoluteX = this.cameraPosition.x + origin[0], absoluteZ = this.cameraPosition.z + origin[2];
3117
- this.color.set("#101829").lerp(new THREE.Color("#e4e9ee"), daylight);
3118
- const sunset = (1 - smooth$1(0, .3, Math.abs(sun[1]))) * smooth$1(-.15, .05, sun[1]);
3119
- this.color.lerp(new THREE.Color("#f6b88d"), sunset * .55);
3120
- this.color.multiplyScalar(1 + daylight * 1.8);
3121
- for (const [i, layer] of this.cloudLayers.entries()) {
3122
- layer.position.set(this.cameraPosition.x, clouds.baseAltitude + i * clouds.thickness - origin[1], this.cameraPosition.z);
3123
- layer.scale.set(size, 1, size);
3124
- layer.material.color.copy(this.color);
3125
- const map = layer.material.map;
3126
- const scale = clouds.scale * (1 + i * .35);
3127
- map.repeat.set(size / scale, size / scale);
3128
- map.offset.set(wrap((absoluteX - atmosphere.windVelocity[0] * seconds) / scale - size / scale / 2 + i * .31, 1), wrap(-(absoluteZ - atmosphere.windVelocity[2] * seconds) / scale - size / scale / 2 + i * .47, 1));
3129
- }
3508
+ const wind = atmosphere.windVelocity;
3509
+ const angle = Math.hypot(wind[0], wind[2]) > .01 ? Math.atan2(-wind[2], wind[0]) : 0;
3510
+ layer.rotation.y = angle;
3511
+ layer.position.set(this.cameraPosition.x, clouds.cirrusAltitude - origin[1], this.cameraPosition.z);
3512
+ layer.scale.set(size, 1, size);
3513
+ const cos = Math.cos(angle), sin = Math.sin(angle);
3514
+ const ax = this.cameraPosition.x + origin[0] - wind[0] * 2.5 * seconds;
3515
+ const az = this.cameraPosition.z + origin[2] - wind[2] * 2.5 * seconds;
3516
+ const scale = clouds.scale * 1.6;
3517
+ const map = layer.material.map;
3518
+ map.repeat.set(size / scale, size / scale);
3519
+ map.offset.set(wrap((ax * cos - az * sin) / scale - size / scale / 2, 1), wrap((-ax * sin - az * cos) / scale - size / scale / 2, 1));
3520
+ this.color.set("#101829").lerp(new THREE.Color("#eef2f6"), daylight);
3521
+ const sunset = (1 - smooth$1(0, .3, Math.abs(sun[1]))) * smooth$1(-.2, .05, sun[1]);
3522
+ this.color.lerp(new THREE.Color("#ffb48f"), sunset * .7);
3523
+ this.color.multiplyScalar(1 + daylight * 1.6);
3524
+ layer.material.color.copy(this.color);
3130
3525
  }
3131
3526
  buildParticles() {
3132
3527
  const geometry = new THREE.BufferGeometry();
@@ -3216,11 +3611,14 @@ var WeatherVisual = class {
3216
3611
  dispose() {
3217
3612
  if (this.disposed) return;
3218
3613
  this.disposed = true;
3219
- for (const layer of this.cloudLayers) {
3220
- layer.geometry.dispose();
3221
- layer.material.map?.dispose();
3222
- layer.material.dispose();
3223
- }
3614
+ this.deck?.geometry.dispose();
3615
+ this.shells?.geometry.dispose();
3616
+ this.cloudMaterial?.dispose();
3617
+ this.cirrus?.geometry.dispose();
3618
+ this.cirrus?.material.dispose();
3619
+ this.veil?.geometry.dispose();
3620
+ this.veil?.material.dispose();
3621
+ if (this.ownsTextures) this.textures.dispose();
3224
3622
  this.particles?.geometry.dispose();
3225
3623
  this.particles?.material.dispose();
3226
3624
  this.particleTexture?.dispose();
@@ -3352,33 +3750,56 @@ const SHADOW_MAP_SIZE = {
3352
3750
  high: 4096
3353
3751
  };
3354
3752
  const UP = new THREE.Vector3(0, 1, 0);
3753
+ const VERTICAL_UP = new THREE.Vector3(1, 0, 0);
3754
+ const shadowRadii = /* @__PURE__ */ new WeakMap();
3355
3755
  const scratchCenter = new THREE.Vector3();
3356
3756
  const scratchRight = new THREE.Vector3();
3357
3757
  const scratchUp = new THREE.Vector3();
3358
3758
  const scratchForward = new THREE.Vector3();
3759
+ /** Keep the projection fixed through small altitude/zoom changes, including at a bucket edge. */
3760
+ function stableRadius(light, requested) {
3761
+ const previous = shadowRadii.get(light);
3762
+ if (previous !== void 0 && requested <= previous && requested >= previous * .8) return previous;
3763
+ const step = 2 ** Math.floor(Math.log2(requested)) / 8;
3764
+ const radius = Math.ceil(requested / step) * step;
3765
+ shadowRadii.set(light, radius);
3766
+ return radius;
3767
+ }
3359
3768
  /**
3360
3769
  * Aim `light`'s shadow at `center` (scene coordinates, after rebasing) from `direction` (a unit
3361
- * vector toward the sun), covering ±`radius`. The light and its target move; the direction of
3770
+ * vector toward the sun), covering at least ±`radius`. The light and its target move; the direction of
3362
3771
  * the light is unchanged.
3363
3772
  */
3364
- function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false) {
3773
+ function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false, worldOrigin = [
3774
+ 0,
3775
+ 0,
3776
+ 0
3777
+ ]) {
3778
+ radius = stableRadius(light, radius);
3365
3779
  const toSun = scratchForward.copy(direction).normalize();
3366
3780
  const size = light.shadow.mapSize.x || 2048;
3367
3781
  const texel = 2 * radius / size;
3368
- const right = scratchRight.crossVectors(Math.abs(toSun.y) > .999 ? new THREE.Vector3(1, 0, 0) : UP, toSun);
3782
+ const camera = light.shadow.camera;
3783
+ camera.up.copy(Math.abs(toSun.y) > .999 ? VERTICAL_UP : UP);
3784
+ const right = scratchRight.crossVectors(camera.up, toSun);
3369
3785
  right.normalize();
3370
3786
  const up = scratchUp.crossVectors(toSun, right).normalize();
3371
3787
  const snapped = scratchCenter.copy(center);
3788
+ snapped.x += worldOrigin[0];
3789
+ snapped.y += worldOrigin[1];
3790
+ snapped.z += worldOrigin[2];
3372
3791
  const along = snapped.dot(toSun);
3373
3792
  const x = Math.round(snapped.dot(right) / texel) * texel;
3374
3793
  const y = Math.round(snapped.dot(up) / texel) * texel;
3375
3794
  snapped.copy(right).multiplyScalar(x).addScaledVector(up, y).addScaledVector(toSun, along);
3795
+ snapped.x -= worldOrigin[0];
3796
+ snapped.y -= worldOrigin[1];
3797
+ snapped.z -= worldOrigin[2];
3376
3798
  const distance = radius * 2 + 1e3;
3377
3799
  light.target.position.copy(snapped);
3378
3800
  light.position.copy(snapped).addScaledVector(toSun, distance);
3379
3801
  light.target.updateMatrixWorld();
3380
3802
  light.updateMatrixWorld();
3381
- const camera = light.shadow.camera;
3382
3803
  if (camera.left !== -radius || camera.top !== radius || camera.far !== distance + radius * 2 + 1e3) {
3383
3804
  camera.left = -radius;
3384
3805
  camera.right = radius;
@@ -3388,8 +3809,10 @@ function focusDirectionalShadow(light, direction, center, radius, biasAddsToward
3388
3809
  camera.far = distance + radius * 2 + 1e3;
3389
3810
  camera.updateProjectionMatrix();
3390
3811
  }
3391
- light.shadow.bias = biasAddsTowardLight ? 4e-4 : -4e-4;
3812
+ const bias = texel * .25 / (camera.far - camera.near);
3813
+ light.shadow.bias = biasAddsTowardLight ? bias : -bias;
3392
3814
  light.shadow.normalBias = texel * 1.2;
3815
+ light.shadow.radius = .5;
3393
3816
  }
3394
3817
  //#endregion
3395
3818
  //#region src/three/sky-reflections.ts
@@ -3601,6 +4024,10 @@ var Renderer = class Renderer {
3601
4024
  warmupMaterial;
3602
4025
  warmedPrograms = /* @__PURE__ */ new WeakMap();
3603
4026
  warmedMeshes = /* @__PURE__ */ new WeakMap();
4027
+ /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
4028
+ materialMeshes = /* @__PURE__ */ new WeakMap();
4029
+ /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
4030
+ preparationLights;
3604
4031
  /**
3605
4032
  * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
3606
4033
  * `prepareVariants`.
@@ -3651,12 +4078,23 @@ var Renderer = class Renderer {
3651
4078
  occlusion;
3652
4079
  occlusionLoad;
3653
4080
  occlusionSuspended = false;
3654
- /** Sun lights whose WebGPU shadow map exists and must not be torn down; see setShadowQuality. */
3655
- webgpuShadowLights = /* @__PURE__ */ new WeakSet();
4081
+ /** Sun lights that have cast shadows: 'off' parks their maps; see setShadowQuality. */
4082
+ shadowLights = /* @__PURE__ */ new WeakSet();
4083
+ /** Kinds of shadow caster prepared so far (WebGL); see noteShadowCaster. */
4084
+ casterVariants = /* @__PURE__ */ new Set();
4085
+ /** Whether the shadow pass has drawn shadowCasterWarmup's casters (WebGL). */
4086
+ shadowCastersWarmed = false;
3656
4087
  reflectionClearColor = Object.assign(new THREE.Color(), { a: 1 });
3657
4088
  starCatalog;
3658
4089
  activeWeather;
3659
4090
  weatherTimeOverride;
4091
+ /** Cloud textures and the cloud-shadow uniforms every lit shader reads, for the renderer's life. */
4092
+ cloudTextures = new CloudTextures(cloudNoise());
4093
+ cloudShadows = createCloudShadowUniforms(this.cloudTextures.shadow);
4094
+ cloudBackend;
4095
+ releaseCloudShadows;
4096
+ cloudQualityLevel = "medium";
4097
+ cloudShadowMapVersion = -1;
3660
4098
  weatherLightIntensities = /* @__PURE__ */ new WeakMap();
3661
4099
  /** The hemisphere the sky reflection map stands in for, and its authored visibility. */
3662
4100
  hiddenAmbient;
@@ -3674,7 +4112,7 @@ var Renderer = class Renderer {
3674
4112
  return this.activeSky;
3675
4113
  }
3676
4114
  /**
3677
- * Aim the sun's shadow at a focus (absolute world coordinates) covering ±`radius` meters, or
4115
+ * Aim the sun's shadow at a focus (absolute world coordinates) covering at least ±`radius` meters, or
3678
4116
  * `undefined` for the environment's own fixed box. Call whenever what the camera frames
3679
4117
  * moves: an orbit target, a walker, a car. Shadows must be on (`setShadowQuality`).
3680
4118
  */
@@ -3685,17 +4123,34 @@ var Renderer = class Renderer {
3685
4123
  radius: focus.radius
3686
4124
  };
3687
4125
  }
3688
- /** Turn sun shadows on at a map resolution, or off, without rebuilding the environment. */
4126
+ /**
4127
+ * Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a
4128
+ * light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader
4129
+ * keeps the shadow inputs it was built with: a host that turns shadows on once before its first
4130
+ * frame can then switch them freely (adaptive quality tiers do) without rebuilding a shader.
4131
+ */
3689
4132
  setShadowQuality(quality) {
3690
4133
  const enabled = quality !== "off";
4134
+ let parked = false;
3691
4135
  for (const light of this.sunLights()) {
3692
- if (this.backend === "webgpu" && this.webgpuShadowLights.has(light)) {
4136
+ if (this.backend === "webgpu" && this.shadowLights.has(light) && light.shadow.map !== null) {
3693
4137
  light.shadow.autoUpdate = enabled;
3694
4138
  light.shadow.intensity = enabled ? 1 : 0;
3695
4139
  continue;
3696
4140
  }
3697
- light.castShadow = enabled;
3698
- if (!enabled) continue;
4141
+ if (!enabled) {
4142
+ if (this.shadowLights.has(light)) {
4143
+ light.shadow.autoUpdate = false;
4144
+ light.shadow.intensity = 0;
4145
+ parked = true;
4146
+ } else light.castShadow = false;
4147
+ continue;
4148
+ }
4149
+ if (!light.castShadow) this.shadowCastersWarmed = false;
4150
+ light.castShadow = true;
4151
+ light.shadow.autoUpdate = true;
4152
+ light.shadow.intensity = 1;
4153
+ if (light.shadow.map === null) light.shadow.needsUpdate = true;
3699
4154
  const size = SHADOW_MAP_SIZE[quality];
3700
4155
  if (light.shadow.mapSize.x !== size) {
3701
4156
  light.shadow.mapSize.set(size, size);
@@ -3704,9 +4159,10 @@ var Renderer = class Renderer {
3704
4159
  light.shadow.map = null;
3705
4160
  }
3706
4161
  }
3707
- if (this.backend === "webgpu") this.webgpuShadowLights.add(light);
4162
+ this.shadowLights.add(light);
3708
4163
  }
3709
4164
  if (this.backend === "webgpu" && this.three.shadowMap.enabled) return;
4165
+ if (parked && this.three.shadowMap.enabled) return;
3710
4166
  this.three.shadowMap.enabled = enabled;
3711
4167
  this.three.shadowMap.type = quality === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
3712
4168
  }
@@ -3730,18 +4186,35 @@ var Renderer = class Renderer {
3730
4186
  const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
3731
4187
  for (const light of this.sunLights()) {
3732
4188
  if (!light.castShadow) continue;
3733
- focusDirectionalShadow(light, light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection), center, focus.radius, this.backend === "webgl" && this.webglReversedPcfShadows());
4189
+ focusDirectionalShadow(light, light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection), center, focus.radius, this.backend === "webgl" && this.webglReversedPcfShadows(), this.worldOrigin);
3734
4190
  }
3735
4191
  }
3736
4192
  /** Active weather effects; physical weather data is also available in the simulation component. */
3737
4193
  get weather() {
3738
4194
  return this.activeWeather;
3739
4195
  }
4196
+ /**
4197
+ * Per-pixel cloud work, default 'medium': ray-march steps and light samples, erosion detail
4198
+ * from 'high', and from 'high' also cloud shadows on every lit surface. Takes effect on the
4199
+ * next frame without rebuilding any shader, so adaptive quality tiers may change it freely.
4200
+ */
4201
+ setCloudQuality(quality) {
4202
+ this.cloudQualityLevel = quality;
4203
+ this.activeWeather?.setCloudQuality(quality);
4204
+ }
4205
+ get cloudQuality() {
4206
+ return this.cloudQualityLevel;
4207
+ }
3740
4208
  /** Apply the singleton weather component without rebuilding the sky or moving the camera. */
3741
4209
  setWeather(data) {
3742
4210
  if (data && this.activeWeather) this.activeWeather.setData(data);
3743
4211
  else {
3744
- const next = data ? new WeatherVisual(data) : void 0;
4212
+ const next = data ? new WeatherVisual(data, {
4213
+ textures: this.cloudTextures,
4214
+ quality: this.cloudQualityLevel,
4215
+ backend: this.backend,
4216
+ ...this.cloudBackend ? { createCloudMaterial: this.cloudBackend.material } : {}
4217
+ }) : void 0;
3745
4218
  this.activeWeather?.dispose();
3746
4219
  this.activeWeather = next;
3747
4220
  if (next) this.scene.add(next.object);
@@ -3802,9 +4275,14 @@ var Renderer = class Renderer {
3802
4275
  });
3803
4276
  try {
3804
4277
  const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-Cup4Yvzs.mjs"))).WebGpuSceneOptimizer(three);
4278
+ const clouds = await import("./webgpu-clouds-H03g7ID1.mjs");
3805
4279
  return new Renderer(opts, {
3806
4280
  three,
3807
4281
  backend: "webgpu",
4282
+ clouds: {
4283
+ material: clouds.createWebGpuCloudMaterial,
4284
+ installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms)
4285
+ },
3808
4286
  ...optimizer ? { optimizer } : {},
3809
4287
  ...opts.reflections === true ? { reflectionFilter: (await import("./webgpu-sky-reflections-CymGEes-.mjs")).createWebGpuSkyReflectionFilter(three) } : {}
3810
4288
  });
@@ -3846,6 +4324,7 @@ var Renderer = class Renderer {
3846
4324
  this.pixelRatio = pixelRatio;
3847
4325
  this.backend = initialized?.backend ?? "webgl";
3848
4326
  this.optimizer = initialized?.optimizer;
4327
+ this.cloudBackend = initialized?.clouds;
3849
4328
  this.three = initialized?.three ?? createWebGlRenderer({
3850
4329
  canvas: opts.canvas,
3851
4330
  antialias: opts.antialias ?? false,
@@ -3855,6 +4334,8 @@ var Renderer = class Renderer {
3855
4334
  logarithmicDepthBuffer: opts.logarithmicDepthBuffer ?? false
3856
4335
  });
3857
4336
  this.three.setPixelRatio(pixelRatio);
4337
+ if (this.cloudBackend) this.cloudBackend.installShadows(this.cloudShadows);
4338
+ else this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows);
3858
4339
  if (this.backend === "webgpu") this.three.onDeviceLost = (info) => {
3859
4340
  if (this.disposed) return;
3860
4341
  this.deviceLossReason = info.message;
@@ -4011,28 +4492,36 @@ var Renderer = class Renderer {
4011
4492
  * other levels afterwards in the background, so publication waits only for what can be seen.
4012
4493
  * Queued work is cancelled once every caller waiting for it has aborted, and background work
4013
4494
  * once its mesh or geometry is disposed.
4495
+ *
4496
+ * `root.userData.admissionPriority` admits the root's own work as `'urgent'` (ahead of normal
4497
+ * work) or `'background'` (only in budget normal work leaves: content nobody waits on yet).
4498
+ * `root.userData.admissionOrder` supplies live normal-lane order (lower first).
4014
4499
  */
4015
4500
  async prepareObject(root, signal, parent) {
4016
4501
  if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
4017
4502
  updateDetachedWorldMatrix(root, parent);
4018
4503
  const lods = parent === void 0 ? void 0 : unselectedLodLevels(root, this.camera);
4019
4504
  const deferredLevels = lods === void 0 ? void 0 : new Set([...lods.values()].flat());
4020
- const foreground = createLane(false);
4505
+ const priority = root.userData.admissionPriority;
4506
+ const foreground = createLane(priority === "background", priority === "urgent");
4507
+ if (typeof root.userData.admissionOrder === "function") foreground.order = root.userData.admissionOrder;
4021
4508
  const background = createLane(true);
4509
+ const state = this.programState();
4022
4510
  const interest = signal === void 0 ? "pinned" : new WarmupInterest(this.cancel);
4023
4511
  const deferred = [];
4024
4512
  const switching = [];
4025
4513
  root.traverse((object) => {
4026
4514
  const mesh = object;
4027
4515
  if (!mesh.isMesh) return;
4516
+ this.noteShadowCaster(mesh);
4028
4517
  if (mesh.userData.materialVariants !== void 0) switching.push(mesh);
4029
4518
  if (deferredLevels !== void 0 && withinAny(mesh, root, deferredLevels)) deferred.push(mesh);
4030
- else this.prepareMesh(mesh, foreground, interest);
4519
+ else this.prepareMesh(mesh, foreground, interest, state);
4031
4520
  });
4032
4521
  this.flushWebGlBatches(foreground);
4033
4522
  const deferredInterests = deferred.map((mesh) => {
4034
4523
  const meshInterest = new WarmupInterest(this.cancel);
4035
- this.prepareMesh(mesh, background, meshInterest);
4524
+ this.prepareMesh(mesh, background, meshInterest, state);
4036
4525
  return meshInterest;
4037
4526
  });
4038
4527
  this.flushWebGlBatches(background);
@@ -4060,7 +4549,30 @@ var Renderer = class Renderer {
4060
4549
  const failure = results.find((result) => result.status === "rejected");
4061
4550
  if (failure?.status === "rejected") throw failure.reason;
4062
4551
  }
4063
- prepareMesh(mesh, lane, interest) {
4552
+ /**
4553
+ * Build `next`'s shaders for every kind of prepared mesh that draws `current`, before the caller
4554
+ * copies `next` into `current`: a progressive material upgrading its placeholder in place once a
4555
+ * texture bake lands. Three shares a program between materials built alike, so the upgraded
4556
+ * placeholder draws with it at once. Otherwise every mesh showing the placeholder built its new
4557
+ * shaders in the next frame, together: seconds of frozen flight shortly after loading. The work
4558
+ * runs in the background lane. Keep `next` alive while `current` uses the shared program.
4559
+ */
4560
+ async prepareMaterialChange(current, next) {
4561
+ if (this.disposed) return;
4562
+ const builds = [];
4563
+ for (const ref of this.materialMeshes.get(current)?.values() ?? []) {
4564
+ const mesh = ref.deref();
4565
+ if (mesh === void 0) continue;
4566
+ const warmup = this.warmup(() => this.compileMesh(mesh, next), createLane(true), {
4567
+ label: "shader-upgrade",
4568
+ bytes: 0
4569
+ });
4570
+ warmup.pinned = true;
4571
+ builds.push(warmup.promise);
4572
+ }
4573
+ await Promise.allSettled(builds);
4574
+ }
4575
+ prepareMesh(mesh, lane, interest, state) {
4064
4576
  const need = (promise) => {
4065
4577
  lane.jobs.add(promise);
4066
4578
  const warmup = this.warmups.get(promise);
@@ -4070,7 +4582,7 @@ var Renderer = class Renderer {
4070
4582
  if (!lane.background) this.admission.promote(promise);
4071
4583
  };
4072
4584
  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
4073
- const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}`;
4585
+ 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(",")}`;
4074
4586
  const variants = [];
4075
4587
  for (const material of materials) {
4076
4588
  for (const value of Object.values(material)) {
@@ -4087,12 +4599,18 @@ var Renderer = class Renderer {
4087
4599
  this.rememberPreparation([value], upload);
4088
4600
  need(upload.promise);
4089
4601
  }
4602
+ let meshes = this.materialMeshes.get(material);
4603
+ if (!meshes) {
4604
+ meshes = /* @__PURE__ */ new Map();
4605
+ this.materialMeshes.set(material, meshes);
4606
+ }
4607
+ if (meshes.get(key)?.deref() === void 0) meshes.set(key, new WeakRef(mesh));
4090
4608
  let map = this.warmedPrograms.get(material);
4091
4609
  if (!map) {
4092
4610
  map = /* @__PURE__ */ new Map();
4093
4611
  this.warmedPrograms.set(material, map);
4094
4612
  }
4095
- const variantKey = `${material.version}/${key}`;
4613
+ const variantKey = `${material.version}/${key}/${state}`;
4096
4614
  const existing = map.get(variantKey);
4097
4615
  if (existing) need(existing);
4098
4616
  else variants.push({
@@ -4232,7 +4750,8 @@ var Renderer = class Renderer {
4232
4750
  const promise = this.admission.run(task, {
4233
4751
  ...options,
4234
4752
  signal: controller.signal,
4235
- priority: lane.background ? "background" : "normal"
4753
+ priority: lane.background ? "background" : lane.urgent ? "urgent" : "normal",
4754
+ ...lane.order ? { order: lane.order } : {}
4236
4755
  });
4237
4756
  const warmup = {
4238
4757
  promise,
@@ -4272,6 +4791,15 @@ var Renderer = class Renderer {
4272
4791
  }
4273
4792
  /** Returns whether any level is still being prepared. */
4274
4793
  holdUnpreparedLevel(lod, shown) {
4794
+ if (lod.levels.length === 0) {
4795
+ let pending = false;
4796
+ for (const child of lod.children) {
4797
+ if (!this.pendingWithin(child, child.visible)) continue;
4798
+ pending = true;
4799
+ child.visible = false;
4800
+ }
4801
+ return pending;
4802
+ }
4275
4803
  const ready = lod.levels.map((level) => !this.pendingWithin(level.object, false));
4276
4804
  if (ready.every(Boolean)) return false;
4277
4805
  const wanted = lod.getCurrentLevel();
@@ -4314,6 +4842,35 @@ var Renderer = class Renderer {
4314
4842
  warmup.forget.push(forget);
4315
4843
  promise.catch(forget);
4316
4844
  }
4845
+ /**
4846
+ * While WebGL shadows are parked the shadow pass never runs, so no depth program is built for
4847
+ * the casters arriving meanwhile, and the first frame with shadows back built every one of them
4848
+ * at once (an adaptive tier change, mid-flight). A caster of a kind the map has not drawn yet
4849
+ * asks the parked map for one render, which builds its depth program as it streams in. The
4850
+ * kinds follow three's shadow pass: one depth material, cloned for alpha-tested maps,
4851
+ * displacement or clipping, built per mesh kind and side.
4852
+ */
4853
+ noteShadowCaster(mesh) {
4854
+ if (this.backend !== "webgl" || !mesh.castShadow) return;
4855
+ const kind = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.morphAttributes).sort().join(",")}`;
4856
+ let fresh = false;
4857
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
4858
+ const textured = material;
4859
+ const variant = mesh.customDepthMaterial !== void 0 ? `custom:${mesh.customDepthMaterial.uuid}` : [
4860
+ kind,
4861
+ material.alphaTest > 0 && (textured.map != null || textured.alphaMap != null),
4862
+ textured.displacementMap != null && textured.displacementScale !== 0,
4863
+ material.alphaToCoverage,
4864
+ material.clipShadows && (material.clippingPlanes?.length ?? 0) > 0,
4865
+ material.shadowSide ?? material.side
4866
+ ].join("/");
4867
+ if (this.casterVariants.has(variant)) continue;
4868
+ this.casterVariants.add(variant);
4869
+ fresh = true;
4870
+ }
4871
+ if (!fresh) return;
4872
+ for (const light of this.sunLights()) if (this.shadowLights.has(light) && !light.shadow.autoUpdate) light.shadow.needsUpdate = true;
4873
+ }
4317
4874
  /** Build `mesh` for the frame's draw target, drawn with `material` when given. */
4318
4875
  compileMesh(mesh, material) {
4319
4876
  const load = this.occlusionOptions !== void 0 ? this.occlusionLoad : void 0;
@@ -4326,14 +4883,85 @@ var Renderer = class Renderer {
4326
4883
  mesh.visible = true;
4327
4884
  mesh.frustumCulled = false;
4328
4885
  if (material !== void 0) mesh.material = material;
4886
+ const traverse = this.scene.traverseVisible;
4887
+ const ownTraverse = Object.hasOwn(this.scene, "traverseVisible");
4329
4888
  try {
4330
- return occlusion !== void 0 ? occlusion.compile(mesh) : this.three.compileAsync(mesh, this.camera, this.scene);
4889
+ if (this.scene.onBeforeRender === THREE.Object3D.prototype.onBeforeRender) {
4890
+ const lights = this.sceneLights();
4891
+ this.scene.traverseVisible = (visit) => {
4892
+ for (const light of lights) visit(light);
4893
+ };
4894
+ }
4895
+ if (occlusion !== void 0) return occlusion.compile(mesh);
4896
+ if (this.backend === "webgl") return this.compileWebGl(mesh);
4897
+ return this.three.compileAsync(mesh, this.camera, this.scene);
4331
4898
  } finally {
4899
+ if (ownTraverse) this.scene.traverseVisible = traverse;
4900
+ else delete this.scene.traverseVisible;
4332
4901
  mesh.visible = visible;
4333
4902
  mesh.frustumCulled = culled;
4334
4903
  mesh.material = shown;
4335
4904
  }
4336
4905
  }
4906
+ /**
4907
+ * Three's compileAsync, but waiting for the programs built for this mesh. Three polls each
4908
+ * material's current program, which the next frame resets for whatever it drew last: a
4909
+ * material shared with drawn meshes (every building's wall) reported its ready program while
4910
+ * the instanced variant was still linking, and that variant's first draw waited for the link
4911
+ * mid-frame (130 ms in flight).
4912
+ */
4913
+ compileWebGl(mesh) {
4914
+ const renderer = this.three;
4915
+ const all = () => renderer.info.programs ?? [];
4916
+ const known = new Set(all());
4917
+ const programs = /* @__PURE__ */ new Set();
4918
+ for (const material of renderer.compile(mesh, this.camera, this.scene)) {
4919
+ const program = renderer.properties.get(material).currentProgram;
4920
+ if (program !== void 0) programs.add(program);
4921
+ }
4922
+ for (const program of all()) if (!known.has(program)) programs.add(program);
4923
+ return new Promise((resolve) => {
4924
+ const check = () => {
4925
+ for (const program of programs) if (program.program === void 0 || program.isReady()) programs.delete(program);
4926
+ if (programs.size === 0) resolve();
4927
+ else setTimeout(check, 10);
4928
+ };
4929
+ check();
4930
+ });
4931
+ }
4932
+ /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
4933
+ sceneLights() {
4934
+ this.preparationLights ??= (() => {
4935
+ const lights = [];
4936
+ THREE.Object3D.prototype.traverseVisible.call(this.scene, (object) => {
4937
+ if (object.isLight) lights.push(object);
4938
+ });
4939
+ return lights;
4940
+ })();
4941
+ return this.preparationLights;
4942
+ }
4943
+ /**
4944
+ * What a lit program is built for besides its material and mesh: the scene's lights and which
4945
+ * cast shadows, the shadow map, fog, environment and output. Warm-ups are remembered under it.
4946
+ * Without it a material built before the sky's sun, its shadows or its reflections existed
4947
+ * counted as prepared, and the next tile drawing it built the real program mid-frame.
4948
+ */
4949
+ programState() {
4950
+ let lights = "";
4951
+ for (const light of this.sceneLights()) lights += `${light.type}${light.castShadow ? "*" : ""},`;
4952
+ const fog = this.scene.fog;
4953
+ const environment = this.scene.environment;
4954
+ const image = environment?.image;
4955
+ return [
4956
+ lights,
4957
+ this.three.shadowMap.enabled,
4958
+ this.three.shadowMap.type,
4959
+ fog === null ? "" : fog.isFogExp2 ? "exp2" : "linear",
4960
+ environment === null ? "" : `${environment.mapping}:${image?.height ?? ""}`,
4961
+ this.three.toneMapping,
4962
+ this.three.outputColorSpace
4963
+ ].join("/");
4964
+ }
4337
4965
  prepareWebGlGeometries(meshes) {
4338
4966
  const renderer = this.three;
4339
4967
  this.warmupTarget ??= new THREE.WebGLRenderTarget(1, 1);
@@ -4367,12 +4995,16 @@ var Renderer = class Renderer {
4367
4995
  }
4368
4996
  }
4369
4997
  render() {
4998
+ this.preparationLights = void 0;
4370
4999
  if (this.disposed) throw new Error("Renderer has been disposed");
4371
5000
  if (this.deviceLossReason !== void 0) throw new Error(`WebGPU device lost: ${this.deviceLossReason}. Recreate the viewer, or reload with WebGL.`);
4372
5001
  if (this.backend === "webgpu") this.three.info.reset();
4373
5002
  const sky = this.activeSky;
4374
5003
  const weather = this.activeWeather;
4375
- sky?.setCloudAttenuation(weather?.cloudAttenuation ?? 0);
5004
+ const cloudAttenuation = weather?.cloudAttenuation ?? 0;
5005
+ const cloudShadowed = weather?.shadowsActive ?? false;
5006
+ const directAttenuation = cloudShadowed ? 0 : cloudAttenuation;
5007
+ sky?.setCloudAttenuation(cloudAttenuation, directAttenuation);
4376
5008
  sky?.update(this.environmentTimeOverride ?? this.environmentSeconds);
4377
5009
  findEnvironmentRig(this.scene)?.traverse((object) => {
4378
5010
  if (!(object instanceof THREE.Light)) return;
@@ -4388,9 +5020,16 @@ var Renderer = class Renderer {
4388
5020
  base = object.intensity;
4389
5021
  this.weatherLightIntensities.set(object, base);
4390
5022
  }
4391
- object.intensity = base * (1 - (weather?.cloudAttenuation ?? 0) * (object instanceof THREE.DirectionalLight ? .92 : .2));
5023
+ object.intensity = base * (object instanceof THREE.DirectionalLight ? 1 - directAttenuation * .92 : 1 - cloudAttenuation * .2);
4392
5024
  });
4393
5025
  weather?.update(this.weatherTimeOverride ?? this.environmentSeconds, this.camera, this.worldOrigin, sky?.frame);
5026
+ if (weather) weather.writeShadows(this.cloudShadows, cloudShadowed);
5027
+ else this.cloudShadows.molenCloudShadow.value.x = 0;
5028
+ const shadowMap = this.cloudShadows.molenCloudMap.value;
5029
+ if (weather && shadowMap.version !== this.cloudShadowMapVersion) {
5030
+ this.cloudShadowMapVersion = shadowMap.version;
5031
+ this.three.initTexture(shadowMap);
5032
+ }
4394
5033
  let reflectedAmbient;
4395
5034
  if (this.reflections) {
4396
5035
  const rig = findEnvironmentRig(this.scene);
@@ -4438,6 +5077,7 @@ var Renderer = class Renderer {
4438
5077
  this.applyShadowFocus();
4439
5078
  this.renderScene();
4440
5079
  }
5080
+ if (this.backend === "webgl") opaqueDrawingBuffer(this.three);
4441
5081
  const info = this.three.info.render;
4442
5082
  this.lastRenderStats.drawCalls = "drawCalls" in info ? info.drawCalls : info.calls;
4443
5083
  this.lastRenderStats.triangles = info.triangles;
@@ -4458,6 +5098,7 @@ var Renderer = class Renderer {
4458
5098
  hideReflectedAmbient(light) {
4459
5099
  const hidden = this.hiddenAmbient;
4460
5100
  if (hidden !== void 0 && hidden.light !== light) {
5101
+ if (hidden.light.visible !== hidden.visible) this.shadowCastersWarmed = false;
4461
5102
  hidden.light.visible = hidden.visible;
4462
5103
  this.hiddenAmbient = void 0;
4463
5104
  }
@@ -4466,10 +5107,67 @@ var Renderer = class Renderer {
4466
5107
  light,
4467
5108
  visible: light.visible
4468
5109
  };
5110
+ if (light.visible) this.shadowCastersWarmed = false;
4469
5111
  light.visible = false;
4470
5112
  }
4471
5113
  renderScene() {
4472
- this.optimized(() => this.three.render(this.scene, this.camera));
5114
+ const warmup = this.shadowCasterWarmup();
5115
+ if (warmup !== void 0) this.scene.add(warmup);
5116
+ try {
5117
+ this.optimized(() => this.three.render(this.scene, this.camera));
5118
+ } finally {
5119
+ if (warmup !== void 0) {
5120
+ warmup.removeFromParent();
5121
+ for (const child of warmup.children) {
5122
+ const mesh = child;
5123
+ mesh.geometry.dispose();
5124
+ mesh.material.dispose();
5125
+ }
5126
+ }
5127
+ }
5128
+ }
5129
+ /**
5130
+ * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
5131
+ * per side): the shadow pass builds a depth program for each kind of caster the first time it
5132
+ * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
5133
+ * shadow pass keeps its depth materials, so the programs stay built; three keys them by the
5134
+ * scene's light counts too, so a light the renderer shows or hides warms them again.
5135
+ */
5136
+ shadowCasterWarmup() {
5137
+ if (this.shadowCastersWarmed || this.backend !== "webgl" || !this.three.shadowMap.enabled) return void 0;
5138
+ if (!this.sunLights().some((light) => light.castShadow && light.shadow.intensity > 0)) return void 0;
5139
+ this.shadowCastersWarmed = true;
5140
+ const group = new THREE.Group();
5141
+ group.name = "molen:shadow-caster-warmup";
5142
+ for (const side of [
5143
+ THREE.FrontSide,
5144
+ THREE.BackSide,
5145
+ THREE.DoubleSide
5146
+ ]) for (const instanced of [false, true]) {
5147
+ const geometry = new THREE.BufferGeometry();
5148
+ geometry.setAttribute("position", new THREE.Float32BufferAttribute(new Array(9).fill(0), 3));
5149
+ geometry.setAttribute("normal", new THREE.Float32BufferAttribute([
5150
+ 0,
5151
+ 1,
5152
+ 0,
5153
+ 0,
5154
+ 1,
5155
+ 0,
5156
+ 0,
5157
+ 1,
5158
+ 0
5159
+ ], 3));
5160
+ const material = new THREE.MeshBasicMaterial({
5161
+ side,
5162
+ colorWrite: false,
5163
+ depthWrite: false
5164
+ });
5165
+ const mesh = instanced ? new THREE.InstancedMesh(geometry, material, 1) : new THREE.Mesh(geometry, material);
5166
+ mesh.castShadow = true;
5167
+ mesh.frustumCulled = false;
5168
+ group.add(mesh);
5169
+ }
5170
+ return group;
4473
5171
  }
4474
5172
  optimized(draw) {
4475
5173
  if (this.optimizer === void 0) {
@@ -4565,6 +5263,8 @@ var Renderer = class Renderer {
4565
5263
  this.activeSky = void 0;
4566
5264
  this.activeWeather?.dispose();
4567
5265
  this.activeWeather = void 0;
5266
+ this.releaseCloudShadows?.();
5267
+ this.cloudTextures.dispose();
4568
5268
  this.reflections?.dispose();
4569
5269
  this.hideReflectedAmbient(void 0);
4570
5270
  findEnvironmentRig(this.scene)?.traverse((object) => {
@@ -4610,9 +5310,10 @@ var WarmupInterest = class {
4610
5310
  return [...this.joined].map((warmup) => warmup.promise);
4611
5311
  }
4612
5312
  };
4613
- function createLane(background) {
5313
+ function createLane(background, urgent = false) {
4614
5314
  return {
4615
5315
  background,
5316
+ urgent,
4616
5317
  jobs: /* @__PURE__ */ new Set(),
4617
5318
  glAttributes: /* @__PURE__ */ new Set(),
4618
5319
  glBatches: []
@@ -4639,6 +5340,11 @@ function unselectedLodLevels(root, camera) {
4639
5340
  const lod = object;
4640
5341
  if (!lod.isLOD || !lod.autoUpdate) return;
4641
5342
  lod.update(camera);
5343
+ if (lod.levels.length === 0) {
5344
+ const hidden = lod.children.filter((child) => !child.visible);
5345
+ if (hidden.length > 0) unselected.set(lod, hidden);
5346
+ return;
5347
+ }
4642
5348
  if (lod.levels.length < 2) return;
4643
5349
  const selected = lod.getCurrentLevel();
4644
5350
  unselected.set(lod, lod.levels.filter((_, index) => index !== selected).map((level) => level.object));
@@ -4680,6 +5386,23 @@ function createWebGlRenderer(options) {
4680
5386
  }
4681
5387
  return renderer;
4682
5388
  }
5389
+ /**
5390
+ * Three r184 always asks for an alpha drawing buffer and keeps the canvas opaque by having opaque
5391
+ * materials write alpha 1. Alpha-to-coverage materials (frayed pavement edges, leaf cards) write
5392
+ * their coverage as alpha instead, so pixels they only partly covered left the canvas translucent
5393
+ * and the page behind it showed through: pale speckle along curbs and in canopies, plainest at
5394
+ * night. A clear of the alpha channel alone makes the finished frame opaque again.
5395
+ */
5396
+ function opaqueDrawingBuffer(renderer) {
5397
+ if (renderer.getRenderTarget() !== null) return;
5398
+ const gl = renderer.getContext();
5399
+ const color = renderer.state.buffers.color;
5400
+ color.setMask(true);
5401
+ color.setClear(0, 0, 0, 1, false);
5402
+ gl.colorMask(false, false, false, true);
5403
+ gl.clear(gl.COLOR_BUFFER_BIT);
5404
+ gl.colorMask(true, true, true, true);
5405
+ }
4683
5406
  function textureBytes(texture) {
4684
5407
  const image = texture.image;
4685
5408
  return image?.data?.byteLength ?? Math.ceil((image?.width ?? 1) * (image?.height ?? 1) * 4 * 4 / 3);
@@ -4760,6 +5483,7 @@ function createClientWithRenderer(link, opts, renderer) {
4760
5483
  const backend = new ThreeSceneBackend(renderer.worldRoot, assets, renderer, materials, opts.sceneOptimization);
4761
5484
  for (const kind of opts.kinds ?? []) backend.registerKind(kind);
4762
5485
  let disposeCore;
5486
+ let removeActivity;
4763
5487
  let raf;
4764
5488
  try {
4765
5489
  const core = createClientCore({
@@ -4785,11 +5509,15 @@ function createClientWithRenderer(link, opts, renderer) {
4785
5509
  renderer.render();
4786
5510
  }
4787
5511
  let disposed = false;
5512
+ let inactive = false;
5513
+ let activityKnown = false;
5514
+ let stopped = false;
5515
+ let requestFrame = () => {};
4788
5516
  if (opts.frameLoop !== "manual") {
4789
5517
  let consecutiveFailures = 0;
4790
5518
  const loop = () => {
4791
5519
  raf = void 0;
4792
- if (disposed) return;
5520
+ if (disposed || inactive || stopped) return;
4793
5521
  let stop = false;
4794
5522
  try {
4795
5523
  renderFrame();
@@ -4797,17 +5525,35 @@ function createClientWithRenderer(link, opts, renderer) {
4797
5525
  } catch (error) {
4798
5526
  consecutiveFailures++;
4799
5527
  stop = renderer.deviceLost !== void 0 || consecutiveFailures >= MAX_CONSECUTIVE_FRAME_FAILURES;
5528
+ stopped = stop;
4800
5529
  core.reportError({
4801
5530
  source: "frame",
4802
5531
  message: stop ? `frame loop stopped after ${consecutiveFailures} failed frame(s): ${describeError(error)}` : `render frame failed: ${describeError(error)}`,
4803
5532
  cause: error
4804
5533
  });
4805
5534
  } finally {
4806
- if (!stop && !disposed && renderer.deviceLost === void 0) raf = requestAnimationFrame(loop);
5535
+ if (!stop) requestFrame();
4807
5536
  }
4808
5537
  };
4809
- raf = requestAnimationFrame(loop);
5538
+ requestFrame = () => {
5539
+ if (raf === void 0 && !disposed && !inactive && !stopped && renderer.deviceLost === void 0) raf = requestAnimationFrame(loop);
5540
+ };
4810
5541
  }
5542
+ if (opts.pauseWhenInactive ?? opts.frameLoop !== "manual") removeActivity = observePageActivity((active) => {
5543
+ if (activityKnown && inactive === !active) return;
5544
+ activityKnown = true;
5545
+ inactive = !active;
5546
+ core.control({
5547
+ action: "set-active",
5548
+ active
5549
+ });
5550
+ renderer.admission.setPaused(inactive);
5551
+ if (inactive) {
5552
+ if (raf !== void 0) cancelAnimationFrame(raf);
5553
+ raf = void 0;
5554
+ } else requestFrame();
5555
+ });
5556
+ requestFrame();
4811
5557
  link.postMessage({
4812
5558
  type: "control",
4813
5559
  control: { action: "request-keyframe" }
@@ -4841,6 +5587,7 @@ function createClientWithRenderer(link, opts, renderer) {
4841
5587
  dispose: () => {
4842
5588
  if (disposed) return;
4843
5589
  disposed = true;
5590
+ removeActivity?.();
4844
5591
  if (raf !== void 0) cancelAnimationFrame(raf);
4845
5592
  core.dispose();
4846
5593
  backend.dispose();
@@ -4849,6 +5596,7 @@ function createClientWithRenderer(link, opts, renderer) {
4849
5596
  }
4850
5597
  };
4851
5598
  } catch (error) {
5599
+ removeActivity?.();
4852
5600
  if (raf !== void 0) cancelAnimationFrame(raf);
4853
5601
  disposeCore?.();
4854
5602
  backend.dispose();
@@ -5014,19 +5762,17 @@ function mountClient(opts, client) {
5014
5762
  });
5015
5763
  const map = input;
5016
5764
  disposers.push(() => map.dispose());
5017
- if (typeof document !== "undefined") {
5765
+ if (opts.pauseWhenInactive ?? opts.frameLoop !== "manual") {
5018
5766
  let resume;
5019
- const visibility = () => {
5020
- if (document.hidden) resume ??= map.suspend();
5767
+ const removeActivity = observePageActivity((active) => {
5768
+ if (!active) resume ??= map.suspend();
5021
5769
  else {
5022
5770
  resume?.();
5023
5771
  resume = void 0;
5024
5772
  }
5025
- };
5026
- document.addEventListener("visibilitychange", visibility);
5027
- visibility();
5773
+ });
5028
5774
  disposers.push(() => {
5029
- document.removeEventListener("visibilitychange", visibility);
5775
+ removeActivity();
5030
5776
  resume?.();
5031
5777
  });
5032
5778
  }
@@ -5193,4 +5939,4 @@ function decodeStarCatalog(input) {
5193
5939
  }));
5194
5940
  }
5195
5941
  //#endregion
5196
- 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 };
5942
+ 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, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };