@bendyline/molen-client 0.0.13 → 0.0.16

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,10 +1,13 @@
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-BliZYUY1.mjs";
3
+ import { n as normalizeInputAxis, r as resolveAction, t as InputMap } from "./input-CzlS1f2N.mjs";
4
4
  import { createGlassVisual } from "./glass.mjs";
5
5
  import { n as liveryGraphicTexture, t as applyLivery } from "./livery-qcDLzbU9.mjs";
6
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";
7
+ import { a as createSnowCoverUniforms, f as writeSnowCover, s as injectSnowCover } from "./snow-cover-Bh0woabf.mjs";
8
+ import { a as expandRenderBounds, i as boxOutsideView, n as RENDER_BOUNDS_STALE, o as markRenderBoundsChanged, r as RENDER_MATRICES_STALE, s as viewProjection, t as RENDER_BOUNDS } from "./render-bounds-uRp_yPp6.mjs";
7
9
  import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
10
+ import { a as isInstanceBatch, i as InstanceMatrixAttribute, n as INSTANCE_BATCH_MATRIX_COLUMNS, o as isInstanceBatchGeometry, r as InstanceBatch, t as INSTANCE_BATCH_COLOR } from "./instance-batch-Ds-oKQW4.mjs";
8
11
  import { resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
9
12
  import * as THREE from "three";
10
13
  import * as SkeletonUtils from "three/addons/utils/SkeletonUtils.js";
@@ -37,6 +40,12 @@ var AdaptiveQualityController = class {
37
40
  increaseDelayMs;
38
41
  cooldownMs;
39
42
  pauseFrameMs;
43
+ pauseRepeatMs;
44
+ upgradeWorkFraction;
45
+ strainDelayMs;
46
+ lastPauseMs = Number.NEGATIVE_INFINITY;
47
+ strained = false;
48
+ strainMs = 0;
40
49
  frames = [];
41
50
  frameCursor = 0;
42
51
  clockMs = 0;
@@ -46,6 +55,7 @@ var AdaptiveQualityController = class {
46
55
  overloadMs = 0;
47
56
  headroomMs = 0;
48
57
  loading = false;
58
+ settling = false;
49
59
  cpuTotalMs = 0;
50
60
  cpuSamples = 0;
51
61
  gpuTotalMs = 0;
@@ -75,6 +85,9 @@ var AdaptiveQualityController = class {
75
85
  this.increaseDelayMs = positive(options.increaseDelayMs ?? 1e4, "increaseDelayMs");
76
86
  this.cooldownMs = positive(options.cooldownMs ?? 2e3, "cooldownMs", true);
77
87
  this.pauseFrameMs = positive(options.pauseFrameMs ?? 1e3, "pauseFrameMs");
88
+ this.pauseRepeatMs = positive(options.pauseRepeatMs ?? 6e4, "pauseRepeatMs", true);
89
+ this.upgradeWorkFraction = positive(options.upgradeWorkFraction ?? .9, "upgradeWorkFraction");
90
+ this.strainDelayMs = positive(options.strainDelayMs ?? 1e4, "strainDelayMs", true);
78
91
  }
79
92
  /** No allocation in the usual per-frame path. A change object is returned only on a step. */
80
93
  sample(frameMs, sample = {}) {
@@ -85,8 +98,14 @@ var AdaptiveQualityController = class {
85
98
  }
86
99
  if (!Number.isFinite(frameMs) || frameMs <= 0) return;
87
100
  if (frameMs > this.pauseFrameMs && !this.previousPause) {
101
+ const repeated = this.clockMs - this.lastPauseMs < this.pauseRepeatMs;
102
+ this.lastPauseMs = this.clockMs;
88
103
  this.resetMeasurements();
89
104
  this.previousPause = true;
105
+ if (repeated && this.level > this.minLevel && sample.settling !== true) {
106
+ this.lastPauseMs = Number.NEGATIVE_INFINITY;
107
+ return this.change(this.level - 1, "frame-time");
108
+ }
90
109
  return;
91
110
  }
92
111
  this.previousPause = frameMs > this.pauseFrameMs;
@@ -97,6 +116,8 @@ var AdaptiveQualityController = class {
97
116
  if (this.frames.length < 512) this.frames.push(elapsed);
98
117
  else this.frames[this.frameCursor++ % 512] = elapsed;
99
118
  this.loading ||= sample.loading === true;
119
+ this.settling ||= sample.settling === true;
120
+ this.strained ||= sample.strained === true;
100
121
  if (Number.isFinite(sample.cpuFrameMs) && (sample.cpuFrameMs ?? 0) > 0) {
101
122
  this.cpuTotalMs += sample.cpuFrameMs ?? 0;
102
123
  this.cpuSamples++;
@@ -155,21 +176,27 @@ var AdaptiveQualityController = class {
155
176
  this.slowFrameRatio = ordered.filter((value) => value > this.targetFrameMs * 1.25).length / ordered.length;
156
177
  this.samples = ordered.length;
157
178
  const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
158
- const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
179
+ const gpuWork = this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0;
180
+ const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, gpuWork);
159
181
  const measured = this.cpuSamples > 0 || this.gpuSamples > 0;
160
182
  const measuredBoth = this.cpuSamples > 0 && this.gpuSamples > 0;
161
183
  const loading = this.loading;
184
+ const settling = this.settling;
185
+ const strained = this.strained;
162
186
  this.resetWindow();
163
187
  const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
164
- const headroom = (!loading || measuredBoth) && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
188
+ const headroom = !settling && (!loading || measuredBoth) && !strained && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * this.upgradeWorkFraction;
165
189
  const renderBound = !loading || !measured || work > this.targetFrameMs * .75;
166
- this.overloadMs = overloaded && renderBound ? this.overloadMs + elapsed : 0;
190
+ const gpuBound = gpuWork > this.targetFrameMs * 2;
191
+ this.overloadMs = overloaded && renderBound && (!settling || gpuBound) ? this.overloadMs + elapsed : 0;
167
192
  this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
193
+ this.strainMs = strained ? this.strainMs + elapsed : 0;
168
194
  if (this.warmupElapsedMs < this.warmupMs) return;
169
195
  const memorySettling = loading && this.reason === "memory-pressure" && this.clockMs - this.lastChangeMs < this.increaseDelayMs;
170
196
  if (memory > 1 && this.level > this.minLevel && !memorySettling) return this.change(this.level - 1, "memory-pressure");
171
197
  if (this.clockMs - this.lastChangeMs < this.cooldownMs) return;
172
198
  if (overloaded && this.overloadMs >= this.decreaseDelayMs && this.level > this.minLevel) return this.change(this.level - 1, "frame-time");
199
+ if (strained && this.strainMs >= this.strainDelayMs && this.level > this.minLevel) return this.change(this.level - 1, "streaming");
173
200
  if (headroom && this.headroomMs >= this.increaseDelayMs * this.recoveryMultiplier && this.level < this.maxLevel) return this.change(this.level + 1, "headroom");
174
201
  }
175
202
  change(level, reason) {
@@ -185,6 +212,7 @@ var AdaptiveQualityController = class {
185
212
  this.lastChangeMs = this.clockMs;
186
213
  this.overloadMs = 0;
187
214
  this.headroomMs = 0;
215
+ this.strainMs = 0;
188
216
  return {
189
217
  previousLevel,
190
218
  level,
@@ -196,6 +224,8 @@ var AdaptiveQualityController = class {
196
224
  this.frameCursor = 0;
197
225
  this.windowMs = 0;
198
226
  this.loading = false;
227
+ this.settling = false;
228
+ this.strained = false;
199
229
  this.cpuTotalMs = 0;
200
230
  this.cpuSamples = 0;
201
231
  this.gpuTotalMs = 0;
@@ -208,6 +238,7 @@ var AdaptiveQualityController = class {
208
238
  this.warmupElapsedMs = 0;
209
239
  this.overloadMs = 0;
210
240
  this.headroomMs = 0;
241
+ this.strainMs = 0;
211
242
  this.smoothedFrameMs = void 0;
212
243
  this.p90FrameMs = void 0;
213
244
  this.slowFrameRatio = 0;
@@ -1210,7 +1241,7 @@ function applyEnvironment(renderer, env) {
1210
1241
  }
1211
1242
  scene.add(rig);
1212
1243
  renderer.three.shadowMap.enabled = shadows !== "off";
1213
- renderer.three.shadowMap.type = shadows === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
1244
+ renderer.three.shadowMap.type = shadows === "low" || renderer.backend === "webgl" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
1214
1245
  renderer.three.setClearColor(env.background !== void 0 ? new THREE.Color(env.background) : renderer.defaultClearColor, 1);
1215
1246
  scene.fog = env.fog !== void 0 ? new THREE.Fog(new THREE.Color(env.fog.color), env.fog.near ?? 1, env.fog.far ?? 1e3) : null;
1216
1247
  renderer.three.toneMapping = env.toneMapping === "aces" ? THREE.ACESFilmicToneMapping : env.toneMapping === "agx" ? THREE.AgXToneMapping : env.toneMapping === "neutral" ? THREE.NeutralToneMapping : THREE.NoToneMapping;
@@ -1468,22 +1499,26 @@ function injectCloudShadows(shader, uniforms) {
1468
1499
  const registered = /* @__PURE__ */ new WeakMap();
1469
1500
  let original;
1470
1501
  /**
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.
1502
+ * Give every lit shader `renderer` builds from now on the cloud shadow, and then whatever `also`
1503
+ * adds to it for the material being built (the sun's far shadow map, three/far-shadow.ts, and
1504
+ * lying snow, weather/snow-cover.ts). Call before its first frame.
1505
+ * Returns a function that unregisters it.
1473
1506
  */
1474
- function installWebGlCloudShadows(renderer, uniforms) {
1507
+ function installWebGlCloudShadows(renderer, uniforms, also) {
1475
1508
  if (original === void 0) {
1476
1509
  const previous = THREE.Material.prototype.onBeforeCompile;
1477
1510
  original = previous;
1478
1511
  const hook = function(shader, target) {
1479
1512
  previous.call(this, shader, target);
1480
- const own = registered.get(target);
1481
- if (own !== void 0) injectCloudShadows(shader, own);
1513
+ registered.get(target)?.(shader, this);
1482
1514
  };
1483
1515
  hook.toString = () => previous.toString();
1484
1516
  THREE.Material.prototype.onBeforeCompile = hook;
1485
1517
  }
1486
- registered.set(renderer, uniforms);
1518
+ registered.set(renderer, (shader, material) => {
1519
+ injectCloudShadows(shader, uniforms);
1520
+ also?.(shader, material);
1521
+ });
1487
1522
  return () => {
1488
1523
  registered.delete(renderer);
1489
1524
  };
@@ -2438,6 +2473,17 @@ function createGltfLoader(renderer, config = {}) {
2438
2473
  }
2439
2474
  //#endregion
2440
2475
  //#region src/frame-admission.ts
2476
+ /** The frame length per-frame budgets are set for: 60 frames a second. */
2477
+ const NOMINAL_FRAME_MS = 1e3 / 60;
2478
+ /**
2479
+ * Frames at least this long, `SLOW_FRAMES` in a row while work waits, are software rendering
2480
+ * (200 ms to a second a frame), not a device to keep interactive: there the budget is the same
2481
+ * share of the frame as of one at 60 a second. Interactive rates keep the fixed budget, which a
2482
+ * busy frame cannot spare (see earthAdmission). A fixed 2 ms of a 450 ms frame left streaming
2483
+ * under half a percent of the time, and a town's layers spent their two-minute deadline queued.
2484
+ */
2485
+ const SLOW_FRAME_MS = 100;
2486
+ const SLOW_FRAMES = 3;
2441
2487
  var FrameAdmissionQueue = class {
2442
2488
  options;
2443
2489
  jobs = [];
@@ -2446,13 +2492,26 @@ var FrameAdmissionQueue = class {
2446
2492
  scheduled = false;
2447
2493
  disposed = false;
2448
2494
  paused = false;
2495
+ /** Milliseconds past its budget the last flush ran, repaid from the frames after it. */
2496
+ overrunMs = 0;
2497
+ /** When the last flush finished, so a repaying frame knows how long it was. */
2498
+ lastFlushEnd;
2499
+ /** The last flush left work waiting, so the time since it ended is a frame, not idle time. */
2500
+ continuing = false;
2501
+ /** Frame lengths outside the queue while work waited, newest last, at most SLOW_FRAMES. */
2502
+ recentFrames = [];
2449
2503
  clock;
2450
2504
  schedule;
2451
2505
  maxMs;
2452
2506
  maxBytes;
2453
2507
  maxJobs;
2508
+ backlog;
2454
2509
  urgentStreak = 0;
2455
2510
  orderedStreak = 0;
2511
+ /** Jobs from the other lanes since the background lane last ran one. */
2512
+ foregroundStreak = 0;
2513
+ backgroundWaitMs;
2514
+ backgroundShare;
2456
2515
  /** Recent work time per label (ms, smoothed): what the next job of that kind will likely take. */
2457
2516
  expected = /* @__PURE__ */ new Map();
2458
2517
  constructor(options = {}) {
@@ -2465,11 +2524,16 @@ var FrameAdmissionQueue = class {
2465
2524
  this.maxMs = options.maxMilliseconds ?? 2;
2466
2525
  this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
2467
2526
  this.maxJobs = options.maxJobs ?? 32;
2468
- this.setLimits({});
2527
+ this.backlog = void 0;
2528
+ this.backgroundWaitMs = options.backgroundWaitMs ?? 750;
2529
+ this.backgroundShare = options.backgroundShare ?? 8;
2530
+ if (!(this.backgroundWaitMs >= 0) || !(this.backgroundShare >= 1)) throw new RangeError("Background admission needs a nonnegative wait and a share of 1 or more");
2531
+ this.setLimits({ backlog: options.backlog });
2469
2532
  }
2470
2533
  /**
2471
2534
  * 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).
2535
+ * can admit more when frames have time to spare (an adaptive quality tier, say). `backlog` is
2536
+ * replaced when the key is present: `undefined` takes the backlog budget away.
2473
2537
  */
2474
2538
  setLimits(limits) {
2475
2539
  const next = [
@@ -2478,7 +2542,26 @@ var FrameAdmissionQueue = class {
2478
2542
  limits.maxJobs ?? this.maxJobs
2479
2543
  ];
2480
2544
  if (!next.every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
2545
+ const backlog = "backlog" in limits ? limits.backlog : this.backlog;
2546
+ if (backlog !== void 0 && (!(Number.isFinite(backlog.afterMs) && backlog.afterMs > 0) || ![backlog.maxMilliseconds, backlog.maxBytes].every((v) => v === void 0 || Number.isFinite(v) && v > 0))) throw new RangeError("A backlog budget needs a positive wait and positive limits");
2481
2547
  [this.maxMs, this.maxBytes, this.maxJobs] = next;
2548
+ this.backlog = backlog === void 0 ? void 0 : { ...backlog };
2549
+ }
2550
+ /**
2551
+ * How far into its backlog budget the queue is, 0 to 1: by how long the oldest job outside the
2552
+ * background lane has waited. Urgent jobs sit ahead of the others, each kind in arrival order
2553
+ * but for the ordered jobs taken from among them, so the oldest is the first of either kind.
2554
+ */
2555
+ pressure(now) {
2556
+ const backlog = this.backlog;
2557
+ const first = this.jobs[0];
2558
+ if (backlog === void 0 || first === void 0) return 0;
2559
+ let oldest = first.queued;
2560
+ if (first.options.priority === "urgent") {
2561
+ const normal = this.jobs.find((job) => job.options.priority !== "urgent");
2562
+ if (normal !== void 0 && normal.queued < oldest) oldest = normal.queued;
2563
+ }
2564
+ return Math.max(0, Math.min(1, (now - oldest - backlog.afterMs) / backlog.afterMs));
2482
2565
  }
2483
2566
  run(task, options = {}) {
2484
2567
  if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
@@ -2549,6 +2632,7 @@ var FrameAdmissionQueue = class {
2549
2632
  /** Hold queued uploads/preparation while the view is inactive; keep resources for resume. */
2550
2633
  setPaused(paused) {
2551
2634
  this.paused = paused;
2635
+ if (paused) this.continuing = false;
2552
2636
  if (!paused) this.request();
2553
2637
  }
2554
2638
  request() {
@@ -2559,13 +2643,41 @@ var FrameAdmissionQueue = class {
2559
2643
  this.flush();
2560
2644
  });
2561
2645
  }
2562
- /** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
2646
+ /**
2647
+ * One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests.
2648
+ *
2649
+ * A job cannot be split, so one can take several frames' budget by itself, and a queue of them
2650
+ * would hold every frame at that length however small the budget. A frame that overruns repays
2651
+ * the excess from the frames after it, so the budget holds on average: a 20 ms shader build
2652
+ * every third frame, rather than every frame at half the frame rate, for the same throughput.
2653
+ *
2654
+ * The budget is a share of a frame at 60 a second. A frame that comes later than that repays
2655
+ * the same share of its own length: under software rendering a frame takes 200 ms or more, and
2656
+ * a job that waits on the GPU once is charged for a whole such frame, so repaying 2 ms a frame
2657
+ * left the queue idle for minutes. At 60 frames a second and faster nothing changes. Sustained
2658
+ * frames that slow also run that share of themselves (see SLOW_FRAME_MS).
2659
+ */
2563
2660
  flush() {
2564
2661
  if (this.disposed || this.paused) return;
2662
+ const sinceLast = this.lastFlushEnd === void 0 ? 0 : this.clock() - this.lastFlushEnd;
2663
+ const pressure = this.pressure(this.clock());
2664
+ const grown = (base, most) => most !== void 0 && most > base ? base + (most - base) * pressure : base;
2665
+ const maxMs = grown(this.maxMs, this.backlog?.maxMilliseconds);
2666
+ const maxBytes = grown(this.maxBytes, this.backlog?.maxBytes);
2667
+ const budget = this.frameBudget(sinceLast, maxMs);
2668
+ if (this.overrunMs > 0) {
2669
+ const repaid = Math.max(maxMs, sinceLast * maxMs / NOMINAL_FRAME_MS);
2670
+ this.overrunMs = Math.max(0, this.overrunMs - repaid);
2671
+ this.lastFlushEnd = this.clock();
2672
+ this.continuing = this.pending > 0;
2673
+ this.request();
2674
+ return;
2675
+ }
2565
2676
  const start = this.clock();
2566
2677
  let bytes = 0, count = 0;
2567
2678
  for (;;) {
2568
- const lane = this.jobs.length > 0 ? this.jobs : this.background;
2679
+ const overdue = this.jobs.length > 0 && this.foregroundStreak >= this.backgroundShare && this.background.length > 0 && this.clock() - this.background[0].queued >= this.backgroundWaitMs;
2680
+ const lane = this.jobs.length > 0 && !overdue ? this.jobs : this.background;
2569
2681
  const waitingNormal = lane === this.jobs && this.urgentStreak >= 2 ? lane.findIndex((job) => job.options.priority !== "urgent") : -1;
2570
2682
  let index = waitingNormal >= 0 && this.clock() - lane[waitingNormal].queued >= 50 ? waitingNormal : 0;
2571
2683
  if (lane === this.jobs && lane[index]?.options.priority !== "urgent" && this.orderedStreak < 3) {
@@ -2582,7 +2694,7 @@ var FrameAdmissionQueue = class {
2582
2694
  if (next === void 0) break;
2583
2695
  const cost = next.options.bytes ?? 0;
2584
2696
  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;
2697
+ if (count > 0 && (count >= this.maxJobs || this.clock() - start + (this.expected.get(label) ?? 0) > budget || bytes + cost > maxBytes)) break;
2586
2698
  lane.splice(index, 1);
2587
2699
  this.forget(next);
2588
2700
  if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
@@ -2590,6 +2702,7 @@ var FrameAdmissionQueue = class {
2590
2702
  next.reject(new DOMException("Admission cancelled", "AbortError"));
2591
2703
  continue;
2592
2704
  }
2705
+ this.foregroundStreak = lane === this.background ? 0 : this.foregroundStreak + 1;
2593
2706
  this.urgentStreak = next.options.priority === "urgent" ? this.urgentStreak + 1 : 0;
2594
2707
  if (next.options.priority !== "urgent") this.orderedStreak = next.options.order !== void 0 && this.orderedStreak < 3 ? this.orderedStreak + 1 : 0;
2595
2708
  const began = this.clock();
@@ -2612,8 +2725,26 @@ var FrameAdmissionQueue = class {
2612
2725
  background: next.options.priority === "background"
2613
2726
  });
2614
2727
  }
2728
+ this.overrunMs = this.pending > 0 ? Math.max(0, this.clock() - start - budget) : 0;
2729
+ this.lastFlushEnd = this.clock();
2730
+ this.continuing = this.pending > 0;
2615
2731
  this.request();
2616
2732
  }
2733
+ /**
2734
+ * This frame's work allowance: the budget (`maxMs`, the ordinary one or what a backlog has grown
2735
+ * it to), or for sustained software-rendering frames the same share of the shortest recent one.
2736
+ * One long frame (a hitch) changes nothing.
2737
+ */
2738
+ frameBudget(sinceLast, maxMs) {
2739
+ if (!this.continuing) this.recentFrames.length = 0;
2740
+ else {
2741
+ this.recentFrames.push(sinceLast);
2742
+ if (this.recentFrames.length > SLOW_FRAMES) this.recentFrames.shift();
2743
+ }
2744
+ if (this.recentFrames.length < SLOW_FRAMES) return maxMs;
2745
+ const shortest = Math.min(...this.recentFrames);
2746
+ return shortest >= SLOW_FRAME_MS ? Math.max(maxMs, shortest * maxMs / NOMINAL_FRAME_MS) : maxMs;
2747
+ }
2617
2748
  dispose() {
2618
2749
  this.disposed = true;
2619
2750
  for (const job of [...this.jobs, ...this.background]) {
@@ -2829,6 +2960,16 @@ function starDirection(rightAscensionDeg, declinationDeg, state) {
2829
2960
  const RAD$1 = Math.PI / 180;
2830
2961
  /** Sky motion (radians) before the dome and stars redraw: about half a pixel at 70 degrees. */
2831
2962
  const SKY_REDRAW_ANGLE = 4e-4;
2963
+ /** The dome's vertex grid, which `domeColor` samples. */
2964
+ const DOME_COLUMNS = 96;
2965
+ const DOME_ROWS = 48;
2966
+ /** How far the Sun's glare reaches, in Sun disk radii. */
2967
+ const GLARE_SPREAD = 16;
2968
+ /**
2969
+ * The Sun's color multiplier, past what tone mapping can show. WebGPU blends before tone mapping,
2970
+ * so the glare needs it too: at plain Sun color it would top out grey around a white disk.
2971
+ */
2972
+ const SUN_RADIANCE = 2.5;
2832
2973
  const clamp$3 = (x) => Math.max(0, Math.min(1, x));
2833
2974
  const rgb$1 = (color) => [
2834
2975
  color.r,
@@ -2863,6 +3004,28 @@ function mesh(geometry, order, transparent = false) {
2863
3004
  result.frustumCulled = false;
2864
3005
  return result;
2865
3006
  }
3007
+ /**
3008
+ * The Sun's glare, which is what makes the real disk look far larger than its half degree: a unit
3009
+ * disk facing +Z whose vertex alpha falls with the inverse square of the angle, as veiling glare
3010
+ * does in the eye, windowed to reach zero at the rim. The material sets its color and strength.
3011
+ * It draws over the disk, which would otherwise tone map dimmer than the glare around it, and
3012
+ * under the Moon, which can cover it.
3013
+ */
3014
+ function sunGlare() {
3015
+ const glare = mesh(new THREE.RingGeometry(0, 1, 32, 16), -65, true);
3016
+ glare.material.blending = THREE.AdditiveBlending;
3017
+ const positions = glare.geometry.getAttribute("position");
3018
+ const colors = glare.geometry.getAttribute("color");
3019
+ for (let i = 0; i < positions.count; i++) {
3020
+ const x = positions.getX(i);
3021
+ const y = positions.getY(i);
3022
+ const ring = Math.hypot(x, y);
3023
+ const r = ring * ring;
3024
+ positions.setXY(i, x * ring, y * ring);
3025
+ colors.setXYZW(i, 1, 1, 1, (1 - r * r) ** 2 / (1 + (r / .12) ** 2));
3026
+ }
3027
+ return glare;
3028
+ }
2866
3029
  /** Seven vertices per star (a centre and six rim points), fanned into six triangles. */
2867
3030
  function starGeometry(count) {
2868
3031
  const geometry = new THREE.BufferGeometry();
@@ -2889,8 +3052,9 @@ var SkyVisual = class {
2889
3052
  moonLight = new THREE.DirectionalLight();
2890
3053
  ambientLight = new THREE.HemisphereLight();
2891
3054
  data;
2892
- dome = mesh(new THREE.SphereGeometry(2, 96, 48), -100);
3055
+ dome = mesh(new THREE.SphereGeometry(2, DOME_COLUMNS, DOME_ROWS), -100);
2893
3056
  sun = mesh(new THREE.SphereGeometry(1, 32, 16), -70, true);
3057
+ glare = sunGlare();
2894
3058
  moon = mesh(new THREE.SphereGeometry(1, 64, 32), -60, true);
2895
3059
  stars;
2896
3060
  catalog;
@@ -2921,13 +3085,14 @@ var SkyVisual = class {
2921
3085
  this.scene.name = "molen:sky";
2922
3086
  this.lights.name = "molen:sky-lights";
2923
3087
  this.dome.name = "molen:sky-dome";
3088
+ this.glare.name = "molen:sky-sun-glare";
2924
3089
  this.sun.name = "molen:sky-sun";
2925
3090
  this.moon.name = "molen:sky-moon";
2926
3091
  this.catalog = this.catalogFrom(options.stars);
2927
3092
  this.stars = mesh(starGeometry(this.catalog.length), -80, true);
2928
3093
  this.stars.material.blending = THREE.AdditiveBlending;
2929
3094
  this.stars.name = "molen:sky-stars";
2930
- this.scene.add(this.dome, this.stars, this.sun, this.moon);
3095
+ this.scene.add(this.dome, this.stars, this.sun, this.glare, this.moon);
2931
3096
  this.lights.add(this.ambientLight, this.sunLight, this.sunLight.target, this.moonLight, this.moonLight.target);
2932
3097
  const shadows = options.shadows ?? "off";
2933
3098
  if (shadows !== "off" && data.lighting?.castShadow !== false) {
@@ -3021,6 +3186,7 @@ var SkyVisual = class {
3021
3186
  this.updateDome(altitude, sunVector, daylight);
3022
3187
  this.updateBody(this.sun, sunVector, sunDiameterDeg * (data.sun?.size ?? 1), sunVector, false);
3023
3188
  this.sun.visible = data.sun?.visible !== false && this.sun.visible;
3189
+ this.updateGlare(sunVector, altitude);
3024
3190
  this.moon.visible = false;
3025
3191
  if (moonVector && data.moon?.visible !== false) this.updateBody(this.moon, moonVector, moonDiameterDeg * (data.moon?.size ?? 1), sunVector, true);
3026
3192
  const rotation = new THREE.Matrix4();
@@ -3135,17 +3301,73 @@ var SkyVisual = class {
3135
3301
  body.visible = direction.y + radius > 0;
3136
3302
  const positions = body.geometry.getAttribute("position");
3137
3303
  const colors = body.geometry.getAttribute("color");
3138
- const base = lunar ? this.palette.moon : this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$2(0, .2, direction.y));
3304
+ const base = lunar ? this.palette.moon : this.sunColor(direction);
3305
+ const earthshine = (this.data.moon?.earthshine ?? .025) * (1 - this.currentFrame.daylight);
3139
3306
  const normal = new THREE.Vector3();
3307
+ const toward = new THREE.Vector3();
3308
+ const behind = new THREE.Color(0, 0, 0);
3140
3309
  for (let i = 0; i < positions.count; i++) {
3141
3310
  normal.fromBufferAttribute(positions, i).normalize();
3142
- const illumination = lunar ? (this.data.moon?.earthshine ?? .025) + Math.max(0, normal.dot(sun)) * .975 : 2.5;
3311
+ const illumination = lunar ? earthshine + Math.max(0, normal.dot(sun)) * .975 : SUN_RADIANCE;
3143
3312
  const albedo = lunar ? .85 + .15 * Math.sin(normal.x * 27 + Math.sin(normal.y * 19) * 2) * Math.sin(normal.z * 21) : 1;
3144
- colors.setXYZW(i, base.r * illumination * albedo, base.g * illumination * albedo, base.b * illumination * albedo, smooth$2(-3e-4, 3e-4, direction.y + normal.y * radius));
3313
+ if (lunar) {
3314
+ toward.copy(direction).addScaledVector(normal, radius).normalize();
3315
+ this.domeColor(toward, behind);
3316
+ }
3317
+ colors.setXYZW(i, behind.r + base.r * illumination * albedo, behind.g + base.g * illumination * albedo, behind.b + base.b * illumination * albedo, smooth$2(-3e-4, 3e-4, direction.y + normal.y * radius));
3145
3318
  }
3146
3319
  colors.needsUpdate = true;
3147
3320
  body.material.side = THREE.FrontSide;
3148
3321
  }
3322
+ sunColor(direction) {
3323
+ return this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$2(0, .2, direction.y));
3324
+ }
3325
+ updateGlare(sun, altitude) {
3326
+ this.glare.visible = this.sun.visible;
3327
+ this.glare.position.copy(sun);
3328
+ this.glare.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), sun);
3329
+ this.glare.scale.setScalar(this.sun.scale.x * GLARE_SPREAD);
3330
+ this.glare.material.color.copy(this.sunColor(sun)).multiplyScalar(SUN_RADIANCE);
3331
+ this.glare.material.opacity = smooth$2(-2, 5, altitude);
3332
+ }
3333
+ /** The drawn dome's color toward a unit direction, interpolated across its vertex grid. */
3334
+ domeColor(direction, target) {
3335
+ const colors = this.dome.geometry.getAttribute("color");
3336
+ const across = (Math.atan2(direction.z, -direction.x) / (2 * Math.PI) + 1) % 1 * DOME_COLUMNS;
3337
+ const down = Math.acos(Math.max(-1, Math.min(1, direction.y))) / Math.PI * DOME_ROWS;
3338
+ const column = Math.floor(across);
3339
+ const row = Math.min(DOME_ROWS - 1, Math.floor(down));
3340
+ const right = across - column;
3341
+ const lower = down - row;
3342
+ target.setRGB(0, 0, 0);
3343
+ for (const [dx, dy, weight] of [
3344
+ [
3345
+ 0,
3346
+ 0,
3347
+ (1 - right) * (1 - lower)
3348
+ ],
3349
+ [
3350
+ 1,
3351
+ 0,
3352
+ right * (1 - lower)
3353
+ ],
3354
+ [
3355
+ 0,
3356
+ 1,
3357
+ (1 - right) * lower
3358
+ ],
3359
+ [
3360
+ 1,
3361
+ 1,
3362
+ right * lower
3363
+ ]
3364
+ ]) {
3365
+ const vertex = (row + dy) * 97 + column + dx;
3366
+ target.r += colors.getX(vertex) * weight;
3367
+ target.g += colors.getY(vertex) * weight;
3368
+ target.b += colors.getZ(vertex) * weight;
3369
+ }
3370
+ }
3149
3371
  /**
3150
3372
  * Replace the star catalog, e.g. once a catalog loaded from a content pack arrives. `undefined`
3151
3373
  * removes the stars. Takes effect on the next update.
@@ -3209,6 +3431,7 @@ var SkyVisual = class {
3209
3431
  for (const object of [
3210
3432
  this.dome,
3211
3433
  this.sun,
3434
+ this.glare,
3212
3435
  this.moon,
3213
3436
  this.stars
3214
3437
  ]) {
@@ -3627,6 +3850,294 @@ var WeatherVisual = class {
3627
3850
  }
3628
3851
  };
3629
3852
  //#endregion
3853
+ //#region src/three/shadow-focus.ts
3854
+ const SHADOW_MAP_SIZE = {
3855
+ low: 1024,
3856
+ medium: 2048,
3857
+ high: 4096
3858
+ };
3859
+ const UP = new THREE.Vector3(0, 1, 0);
3860
+ const VERTICAL_UP = new THREE.Vector3(1, 0, 0);
3861
+ const shadowRadii = /* @__PURE__ */ new WeakMap();
3862
+ const scratchCenter = new THREE.Vector3();
3863
+ const scratchRight = new THREE.Vector3();
3864
+ const scratchUp = new THREE.Vector3();
3865
+ const scratchForward = new THREE.Vector3();
3866
+ /** Keep the projection fixed through small altitude/zoom changes, including at a bucket edge. */
3867
+ function stableRadius(light, requested) {
3868
+ const previous = shadowRadii.get(light);
3869
+ if (previous !== void 0 && requested <= previous && requested >= previous * .8) return previous;
3870
+ const step = 2 ** Math.floor(Math.log2(requested)) / 8;
3871
+ const radius = Math.ceil(requested / step) * step;
3872
+ shadowRadii.set(light, radius);
3873
+ return radius;
3874
+ }
3875
+ /**
3876
+ * Aim `light`'s shadow at `center` (scene coordinates, after rebasing) from `direction` (a unit
3877
+ * vector toward the sun), covering at least ±`radius`. The light and its target move; the direction of
3878
+ * the light is unchanged.
3879
+ */
3880
+ function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false, worldOrigin = [
3881
+ 0,
3882
+ 0,
3883
+ 0
3884
+ ]) {
3885
+ radius = stableRadius(light, radius);
3886
+ const toSun = scratchForward.copy(direction).normalize();
3887
+ const size = light.shadow.mapSize.x || 2048;
3888
+ const texel = 2 * radius / size;
3889
+ const camera = light.shadow.camera;
3890
+ camera.up.copy(Math.abs(toSun.y) > .999 ? VERTICAL_UP : UP);
3891
+ const right = scratchRight.crossVectors(camera.up, toSun);
3892
+ right.normalize();
3893
+ const up = scratchUp.crossVectors(toSun, right).normalize();
3894
+ const snapped = scratchCenter.copy(center);
3895
+ snapped.x += worldOrigin[0];
3896
+ snapped.y += worldOrigin[1];
3897
+ snapped.z += worldOrigin[2];
3898
+ const along = snapped.dot(toSun);
3899
+ const x = Math.round(snapped.dot(right) / texel) * texel;
3900
+ const y = Math.round(snapped.dot(up) / texel) * texel;
3901
+ snapped.copy(right).multiplyScalar(x).addScaledVector(up, y).addScaledVector(toSun, along);
3902
+ snapped.x -= worldOrigin[0];
3903
+ snapped.y -= worldOrigin[1];
3904
+ snapped.z -= worldOrigin[2];
3905
+ const distance = radius * 2 + 1e3;
3906
+ light.target.position.copy(snapped);
3907
+ light.position.copy(snapped).addScaledVector(toSun, distance);
3908
+ light.target.updateMatrixWorld();
3909
+ light.updateMatrixWorld();
3910
+ if (camera.left !== -radius || camera.top !== radius || camera.far !== distance + radius * 2 + 1e3) {
3911
+ camera.left = -radius;
3912
+ camera.right = radius;
3913
+ camera.top = radius;
3914
+ camera.bottom = -radius;
3915
+ camera.near = 1;
3916
+ camera.far = distance + radius * 2 + 1e3;
3917
+ camera.updateProjectionMatrix();
3918
+ }
3919
+ const bias = texel * .25 / (camera.far - camera.near);
3920
+ light.shadow.bias = biasAddsTowardLight ? bias : -bias;
3921
+ light.shadow.normalBias = texel * 1.2;
3922
+ light.shadow.radius = .5;
3923
+ }
3924
+ //#endregion
3925
+ //#region src/three/far-shadow.ts
3926
+ /** Where the focused map starts handing over to the far one, as a share of its half-width. */
3927
+ const HANDOVER = .8;
3928
+ /** Redraw once the wanted center is this share of the radius from the drawn one. */
3929
+ const DRIFT = .125;
3930
+ /** Redraw for scenery that arrived since, ms. */
3931
+ const REFRESH_MS = 1e3;
3932
+ /** Redraw once the sun has moved this far, radians (0.2 degrees). */
3933
+ const SUN_TURN = .0035;
3934
+ const PARS_VERTEX = `
3935
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
3936
+ uniform mat4 molenFarShadowMatrix;
3937
+ uniform vec4 molenFarShadow;
3938
+ varying vec4 vMolenFarShadowCoord;
3939
+ #endif
3940
+ `;
3941
+ const VERTEX = `
3942
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
3943
+ vMolenFarShadowCoord = molenFarShadowMatrix * ( worldPosition + vec4( shadowWorldNormal * molenFarShadow.z, 0.0 ) );
3944
+ #endif
3945
+ `;
3946
+ const PARS_FRAGMENT = `
3947
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
3948
+ uniform vec4 molenFarShadow;
3949
+ varying vec4 vMolenFarShadowCoord;
3950
+ #if defined( SHADOWMAP_TYPE_PCF )
3951
+ uniform sampler2DShadow molenFarShadowMap;
3952
+ // Sunlight reaching this fragment by the far map: 1 outside it, fading in from its edge.
3953
+ float molenFarShadowAt() {
3954
+ vec3 coord = vMolenFarShadowCoord.xyz / vMolenFarShadowCoord.w;
3955
+ coord.z += molenFarShadow.y;
3956
+ vec2 fromCenter = abs( coord.xy - 0.5 ) * 2.0;
3957
+ float edge = max( fromCenter.x, fromCenter.y );
3958
+ if ( edge >= 1.0 || coord.z > 1.0 ) return 1.0;
3959
+ vec2 texel = vec2( 0.5 ) / vec2( textureSize( molenFarShadowMap, 0 ) );
3960
+ float lit = 0.25 * (
3961
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( - texel.x, - texel.y ), coord.z ) ) +
3962
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( texel.x, - texel.y ), coord.z ) ) +
3963
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( - texel.x, texel.y ), coord.z ) ) +
3964
+ texture( molenFarShadowMap, vec3( coord.xy + vec2( texel.x, texel.y ), coord.z ) )
3965
+ );
3966
+ return mix( 1.0, lit, molenFarShadow.x * ( 1.0 - smoothstep( 0.8, 1.0, edge ) ) );
3967
+ }
3968
+ #endif
3969
+ // The first directional light's shadow: the focused map's, handing over to the far map
3970
+ // toward the focused map's edge and beyond it.
3971
+ float molenSunShadow( int index, float near, vec4 nearCoord ) {
3972
+ #if defined( SHADOWMAP_TYPE_PCF )
3973
+ if ( index != 0 || molenFarShadow.x <= 0.0 ) return near;
3974
+ vec2 fromCenter = abs( nearCoord.xy / nearCoord.w - 0.5 ) * 2.0;
3975
+ float handover = smoothstep( molenFarShadow.w, 1.0, max( fromCenter.x, fromCenter.y ) );
3976
+ if ( handover <= 0.0 ) return near;
3977
+ return mix( near, molenFarShadowAt(), handover );
3978
+ #else
3979
+ return near;
3980
+ #endif
3981
+ }
3982
+ #endif
3983
+ `;
3984
+ const CALL = "getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] )";
3985
+ function createFarShadowUniforms() {
3986
+ const none = new THREE.DepthTexture(1, 1);
3987
+ none.name = "molen:far-shadow-none";
3988
+ none.compareFunction = THREE.LessEqualCompare;
3989
+ none.needsUpdate = true;
3990
+ return {
3991
+ molenFarShadowMap: { value: none },
3992
+ molenFarShadowMatrix: { value: new THREE.Matrix4() },
3993
+ molenFarShadow: { value: new THREE.Vector4(0, 0, 0, HANDOVER) }
3994
+ };
3995
+ }
3996
+ /**
3997
+ * Give a WebGL shader built from three's lighting chunks the far shadow map; false if it has
3998
+ * none of them (an unlit or hand-written shader), which is then left as it was.
3999
+ */
4000
+ function injectFarShadow(shader, uniforms) {
4001
+ const parsVertex = "#include <shadowmap_pars_vertex>";
4002
+ const vertex = "#include <shadowmap_vertex>";
4003
+ const parsFragment = "#include <shadowmap_pars_fragment>";
4004
+ const lights = "#include <lights_fragment_begin>";
4005
+ let fragment = shader.fragmentShader;
4006
+ if (fragment.includes(lights)) fragment = fragment.replace(lights, THREE.ShaderChunk.lights_fragment_begin);
4007
+ if (!shader.vertexShader.includes(parsVertex) || !shader.vertexShader.includes(vertex) || !fragment.includes(parsFragment) || !fragment.includes(CALL)) return false;
4008
+ shader.vertexShader = shader.vertexShader.replace(parsVertex, `${parsVertex}\n${PARS_VERTEX}`).replace(vertex, `${vertex}\n${VERTEX}`);
4009
+ shader.fragmentShader = fragment.replace(parsFragment, `${parsFragment}\n${PARS_FRAGMENT}`).replace(CALL, `molenSunShadow( UNROLLED_LOOP_INDEX, ${CALL}, vDirectionalShadowCoord[ i ] )`);
4010
+ Object.assign(shader.uniforms, uniforms);
4011
+ return true;
4012
+ }
4013
+ /** The far map of one WebGL renderer: when to draw it, and the uniforms every lit shader reads. */
4014
+ var FarShadow = class {
4015
+ uniforms = createFarShadowUniforms();
4016
+ none = this.uniforms.molenFarShadowMap.value;
4017
+ /** Never in the scene: three's shadow pass draws for it when asked to. */
4018
+ light = new THREE.DirectionalLight();
4019
+ casters;
4020
+ scene;
4021
+ pending = false;
4022
+ drawn = false;
4023
+ drawnAt = Number.NEGATIVE_INFINITY;
4024
+ drawnRadius = 0;
4025
+ /** Absolute world coordinates. */
4026
+ drawnCenter = new THREE.Vector3();
4027
+ drawnDirection = new THREE.Vector3();
4028
+ drawnOrigin = [
4029
+ 0,
4030
+ 0,
4031
+ 0
4032
+ ];
4033
+ drawnMatrix = new THREE.Matrix4();
4034
+ origin = [
4035
+ 0,
4036
+ 0,
4037
+ 0
4038
+ ];
4039
+ wanted = new THREE.Vector3();
4040
+ shift = new THREE.Matrix4();
4041
+ release;
4042
+ draws = 0;
4043
+ lastDrawMs = 0;
4044
+ constructor(renderer) {
4045
+ this.light.name = "molen:far-shadow";
4046
+ this.light.shadow.autoUpdate = false;
4047
+ const shadowMap = renderer.shadowMap;
4048
+ const render = shadowMap.render;
4049
+ if (typeof render !== "function") {
4050
+ this.release = () => {};
4051
+ return;
4052
+ }
4053
+ shadowMap.render = (lights, scene, camera) => {
4054
+ render.call(shadowMap, lights, scene, camera);
4055
+ if (!this.pending || scene !== this.scene || this.casters === void 0) return;
4056
+ this.pending = false;
4057
+ const started = performance.now();
4058
+ this.light.shadow.needsUpdate = true;
4059
+ render.call(shadowMap, [this.light], this.casters, camera);
4060
+ this.lastDrawMs = performance.now() - started;
4061
+ const map = this.light.shadow.map;
4062
+ const depth = map?.depthTexture;
4063
+ if (map === null || depth === null || depth === void 0) return;
4064
+ this.draws++;
4065
+ this.drawn = true;
4066
+ this.drawnMatrix.copy(this.light.shadow.matrix);
4067
+ this.drawnOrigin[0] = this.origin[0];
4068
+ this.drawnOrigin[1] = this.origin[1];
4069
+ this.drawnOrigin[2] = this.origin[2];
4070
+ this.uniforms.molenFarShadowMap.value = depth;
4071
+ this.uniforms.molenFarShadowMatrix.value.copy(this.drawnMatrix);
4072
+ this.uniforms.molenFarShadow.value.set(1, this.light.shadow.bias, this.light.shadow.normalBias, HANDOVER);
4073
+ };
4074
+ this.release = () => {
4075
+ shadowMap.render = render;
4076
+ };
4077
+ }
4078
+ /** The scene whose render draws the map, and the static root it is drawn from. */
4079
+ setCasters(scene, casters) {
4080
+ this.scene = scene;
4081
+ if (this.casters === casters) return;
4082
+ this.casters = casters;
4083
+ this.drawn = false;
4084
+ }
4085
+ get info() {
4086
+ return this.drawn ? {
4087
+ radius: this.drawnRadius,
4088
+ draws: this.draws,
4089
+ lastDrawMs: this.lastDrawMs
4090
+ } : void 0;
4091
+ }
4092
+ /** Before each frame: `view` while the sun casts shadows and a far radius is wanted. */
4093
+ update(view) {
4094
+ const state = this.uniforms.molenFarShadow.value;
4095
+ if (view === void 0 || this.casters === void 0) {
4096
+ state.x = 0;
4097
+ this.pending = false;
4098
+ this.drawn = false;
4099
+ return;
4100
+ }
4101
+ const shadow = this.light.shadow;
4102
+ if (shadow.mapSize.x !== view.mapSize) {
4103
+ shadow.mapSize.set(view.mapSize, view.mapSize);
4104
+ this.disposeMap();
4105
+ }
4106
+ this.origin = view.worldOrigin;
4107
+ const wanted = this.wanted.set(view.center.x + view.worldOrigin[0], view.center.y + view.worldOrigin[1], view.center.z + view.worldOrigin[2]);
4108
+ if (!this.drawn || view.now - this.drawnAt >= REFRESH_MS || view.radius > this.drawnRadius || view.radius < this.drawnRadius * .7 || wanted.distanceTo(this.drawnCenter) > this.drawnRadius * DRIFT || view.direction.angleTo(this.drawnDirection) > SUN_TURN) {
4109
+ focusDirectionalShadow(this.light, view.direction, view.center, view.radius, view.biasAddsTowardLight, view.worldOrigin);
4110
+ this.drawnAt = view.now;
4111
+ this.drawnRadius = shadow.camera.right;
4112
+ this.drawnCenter.copy(wanted);
4113
+ this.drawnDirection.copy(view.direction);
4114
+ this.pending = true;
4115
+ }
4116
+ if (!this.drawn) {
4117
+ state.x = 0;
4118
+ return;
4119
+ }
4120
+ state.x = 1;
4121
+ this.uniforms.molenFarShadowMatrix.value.multiplyMatrices(this.drawnMatrix, this.shift.makeTranslation(view.worldOrigin[0] - this.drawnOrigin[0], view.worldOrigin[1] - this.drawnOrigin[1], view.worldOrigin[2] - this.drawnOrigin[2]));
4122
+ }
4123
+ disposeMap() {
4124
+ const map = this.light.shadow.map;
4125
+ this.uniforms.molenFarShadowMap.value = this.none;
4126
+ this.uniforms.molenFarShadow.value.x = 0;
4127
+ this.drawn = false;
4128
+ if (map === null) return;
4129
+ map.depthTexture?.dispose();
4130
+ map.dispose();
4131
+ this.light.shadow.map = null;
4132
+ }
4133
+ dispose() {
4134
+ this.release();
4135
+ this.disposeMap();
4136
+ this.none.dispose();
4137
+ this.light.dispose();
4138
+ }
4139
+ };
4140
+ //#endregion
3630
4141
  //#region src/three/gpu-frame-timer.ts
3631
4142
  /**
3632
4143
  * Optional WebGL2 timing. Reads a result only after QUERY_RESULT_AVAILABLE; never waits,
@@ -3743,78 +4254,6 @@ function createGpuFrameTimer(context, options = {}) {
3743
4254
  };
3744
4255
  }
3745
4256
  //#endregion
3746
- //#region src/three/shadow-focus.ts
3747
- const SHADOW_MAP_SIZE = {
3748
- low: 1024,
3749
- medium: 2048,
3750
- high: 4096
3751
- };
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();
3755
- const scratchCenter = new THREE.Vector3();
3756
- const scratchRight = new THREE.Vector3();
3757
- const scratchUp = new THREE.Vector3();
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
- }
3768
- /**
3769
- * Aim `light`'s shadow at `center` (scene coordinates, after rebasing) from `direction` (a unit
3770
- * vector toward the sun), covering at least ±`radius`. The light and its target move; the direction of
3771
- * the light is unchanged.
3772
- */
3773
- function focusDirectionalShadow(light, direction, center, radius, biasAddsTowardLight = false, worldOrigin = [
3774
- 0,
3775
- 0,
3776
- 0
3777
- ]) {
3778
- radius = stableRadius(light, radius);
3779
- const toSun = scratchForward.copy(direction).normalize();
3780
- const size = light.shadow.mapSize.x || 2048;
3781
- const texel = 2 * radius / size;
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);
3785
- right.normalize();
3786
- const up = scratchUp.crossVectors(toSun, right).normalize();
3787
- const snapped = scratchCenter.copy(center);
3788
- snapped.x += worldOrigin[0];
3789
- snapped.y += worldOrigin[1];
3790
- snapped.z += worldOrigin[2];
3791
- const along = snapped.dot(toSun);
3792
- const x = Math.round(snapped.dot(right) / texel) * texel;
3793
- const y = Math.round(snapped.dot(up) / texel) * texel;
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];
3798
- const distance = radius * 2 + 1e3;
3799
- light.target.position.copy(snapped);
3800
- light.position.copy(snapped).addScaledVector(toSun, distance);
3801
- light.target.updateMatrixWorld();
3802
- light.updateMatrixWorld();
3803
- if (camera.left !== -radius || camera.top !== radius || camera.far !== distance + radius * 2 + 1e3) {
3804
- camera.left = -radius;
3805
- camera.right = radius;
3806
- camera.top = radius;
3807
- camera.bottom = -radius;
3808
- camera.near = 1;
3809
- camera.far = distance + radius * 2 + 1e3;
3810
- camera.updateProjectionMatrix();
3811
- }
3812
- const bias = texel * .25 / (camera.far - camera.near);
3813
- light.shadow.bias = biasAddsTowardLight ? bias : -bias;
3814
- light.shadow.normalBias = texel * 1.2;
3815
- light.shadow.radius = .5;
3816
- }
3817
- //#endregion
3818
4257
  //#region src/three/sky-reflections.ts
3819
4258
  const WIDTH = 256;
3820
4259
  const HEIGHT = 128;
@@ -3965,6 +4404,44 @@ function reflectionStateFromLights(ambient, sun, background, clouds) {
3965
4404
  }
3966
4405
  //#endregion
3967
4406
  //#region src/three/renderer.ts
4407
+ /** Renderer strings of the software rasterizers browsers fall back to (see softwareRasterizer). */
4408
+ const SOFTWARE_RASTERIZER = /swiftshader|llvmpipe|softpipe|lavapipe|basic render driver/i;
4409
+ /** How long the lights gathered for warm-up builds stand, ms (see `sceneLights`). */
4410
+ const LIGHTS_REFRESH_MS = 250;
4411
+ /** How often a group seen only by a shadow map has its levels of detail chosen again, ms. */
4412
+ const SHADOW_LOD_MS = 500;
4413
+ const cullMatrix = new THREE.Matrix4();
4414
+ const cullBox = new THREE.Box3();
4415
+ /** Frames (render groups' parents) whose world matrix a culling pass has brought up to date. */
4416
+ const cullFrames = /* @__PURE__ */ new WeakMap();
4417
+ let cullPass = 0;
4418
+ /** Whether `group` is under `scene`: a group its owner has detached keeps its parent. */
4419
+ function groupInScene(group, scene) {
4420
+ for (let cursor = group.parent; cursor !== null; cursor = cursor.parent) if (cursor === scene) return true;
4421
+ return false;
4422
+ }
4423
+ /** A WebGPU adapter that rasterizes on the CPU, by its own flag or its description. */
4424
+ function softwareAdapter(adapter) {
4425
+ const legacy = adapter;
4426
+ const info = adapter.info;
4427
+ const described = [
4428
+ info?.vendor,
4429
+ info?.architecture,
4430
+ info?.device,
4431
+ info?.description
4432
+ ].filter((part) => typeof part === "string").join(" ");
4433
+ return legacy.isFallbackAdapter === true || info?.isFallbackAdapter === true || SOFTWARE_RASTERIZER.test(described);
4434
+ }
4435
+ /** A WebGL context drawn by a software rasterizer, by its unmasked renderer string when exposed. */
4436
+ function softwareContext(gl) {
4437
+ try {
4438
+ const debug = gl.getExtension?.("WEBGL_debug_renderer_info");
4439
+ const name = gl.getParameter?.(debug ? debug.UNMASKED_RENDERER_WEBGL : gl.RENDERER);
4440
+ return typeof name === "string" && SOFTWARE_RASTERIZER.test(name);
4441
+ } catch {
4442
+ return false;
4443
+ }
4444
+ }
3968
4445
  /** Orthographic half-extents for a vertical view extent at an aspect ratio (pure; testable). */
3969
4446
  function orthoFrustum(viewHeight, aspect) {
3970
4447
  if (!Number.isFinite(viewHeight) || viewHeight <= 0) throw new Error("viewHeight must be finite and positive");
@@ -4027,7 +4504,21 @@ var Renderer = class Renderer {
4027
4504
  /** Per material, one prepared mesh of each kind it draws; see `prepareMaterialChange`. */
4028
4505
  materialMeshes = /* @__PURE__ */ new WeakMap();
4029
4506
  /** The scene's visible lights for warm-up builds, gathered once between rendered frames. */
4507
+ /**
4508
+ * WebGL render groups, for `cullRenderGroups`. Held weakly: a group is made before its owner
4509
+ * attaches it (a tile's, several frames before) and may never be, and one its owner has let
4510
+ * go of must not be kept alive here.
4511
+ */
4512
+ renderGroups = /* @__PURE__ */ new Set();
4513
+ /** Groups left out of the scene walk under way, to show again when it ends. */
4514
+ culledGroups = [];
4515
+ cullGroups = false;
4516
+ releaseShadowCulling;
4030
4517
  preparationLights;
4518
+ /** Every light the last walk of the scene found on show, and when it was (see `sceneLights`). */
4519
+ foundLights;
4520
+ foundLightsChildren = -1;
4521
+ foundLightsAt = Number.NEGATIVE_INFINITY;
4031
4522
  /**
4032
4523
  * Per mesh, builds of the materials it swaps to itself (`null`: prepared with the mesh); see
4033
4524
  * `prepareVariants`.
@@ -4046,6 +4537,18 @@ var Renderer = class Renderer {
4046
4537
  get fallbackReason() {
4047
4538
  return this.fallback;
4048
4539
  }
4540
+ software;
4541
+ /**
4542
+ * Whether this device draws through a software rasterizer: SwiftShader (headless and
4543
+ * blocklisted-GPU Chromium), Mesa's llvmpipe or lavapipe, Windows' Basic Render Driver, or a
4544
+ * WebGPU fallback adapter. Every pixel and vertex then costs CPU time, so a host that sizes its
4545
+ * work to the device starts at its lowest tier. Read once, from the WebGL context's unmasked
4546
+ * renderer string (false where the browser hides it) or the WebGPU adapter's fallback flag.
4547
+ */
4548
+ get softwareRasterizer() {
4549
+ this.software ??= this.backend === "webgl" && softwareContext(this.three.getContext());
4550
+ return this.software;
4551
+ }
4049
4552
  scene;
4050
4553
  /** World-space objects live here so the renderer can rebase them near the camera. */
4051
4554
  worldRoot;
@@ -4091,6 +4594,8 @@ var Renderer = class Renderer {
4091
4594
  /** Cloud textures and the cloud-shadow uniforms every lit shader reads, for the renderer's life. */
4092
4595
  cloudTextures = new CloudTextures(cloudNoise());
4093
4596
  cloudShadows = createCloudShadowUniforms(this.cloudTextures.shadow);
4597
+ /** The weather's lying snow, read by every material marked with `enableSnowCover`. */
4598
+ snowCover = createSnowCoverUniforms();
4094
4599
  cloudBackend;
4095
4600
  releaseCloudShadows;
4096
4601
  cloudQualityLevel = "medium";
@@ -4107,6 +4612,10 @@ var Renderer = class Renderer {
4107
4612
  shadowFocus;
4108
4613
  shadowCenter = new THREE.Vector3();
4109
4614
  shadowDirection = new THREE.Vector3();
4615
+ /** The sun's far shadow map (WebGL); see setFarShadowCasters. */
4616
+ farShadow;
4617
+ farShadowCenter = new THREE.Vector3();
4618
+ farShadowDirection = new THREE.Vector3();
4110
4619
  /** Active clear-sky visual and sampled ephemeris, when environment.sky is configured. */
4111
4620
  get sky() {
4112
4621
  return this.activeSky;
@@ -4118,12 +4627,47 @@ var Renderer = class Renderer {
4118
4627
  */
4119
4628
  setShadowFocus(focus) {
4120
4629
  if (focus !== void 0 && (!(focus.radius > 0) || !Number.isFinite(focus.radius))) throw new RangeError("Shadow focus radius must be a positive number of meters");
4630
+ const far = focus?.far;
4631
+ if (far !== void 0 && (!(far.radius > 0) || !Number.isFinite(far.radius))) throw new RangeError("Far shadow radius must be a positive number of meters");
4121
4632
  this.shadowFocus = focus === void 0 ? void 0 : {
4122
4633
  center: [...focus.center],
4123
- radius: focus.radius
4634
+ radius: focus.radius,
4635
+ ...far !== void 0 ? { far: {
4636
+ center: [...far.center],
4637
+ radius: far.radius
4638
+ } } : {}
4124
4639
  };
4125
4640
  }
4126
4641
  /**
4642
+ * The scenery that does not move (a terrain stream's object: ground, buildings, trees), for the
4643
+ * sun's far shadow map. With it and a focus that names a `far` square, surfaces past the
4644
+ * focused map are shadowed from a second, wider map instead of ending in sunlight: over a
4645
+ * city the focused map ends a few hundred meters out, and buildings gained their shadows as
4646
+ * it reached them. Only what is under `root` casts into it, and it is redrawn when the camera
4647
+ * has left its middle, when the sun has moved and about once a second for scenery that has
4648
+ * arrived, so a moving caster would leave its shadow behind. WebGL; `undefined` turns it off.
4649
+ */
4650
+ setFarShadowCasters(root) {
4651
+ this.farShadow?.setCasters(this.scene, root);
4652
+ }
4653
+ /** The far shadow map as last drawn, or `undefined` while there is none. */
4654
+ get farShadowInfo() {
4655
+ return this.farShadow?.info;
4656
+ }
4657
+ /**
4658
+ * Meters one texel of the sun's shadow map covers as of the last frame, or `undefined` while sun
4659
+ * shadows are off or parked. A focus over a wide view coarsens it: hosts use it to keep a subject
4660
+ * the map cannot resolve out of the shadow pass (`AircraftVisual.updateShadows`).
4661
+ */
4662
+ get shadowTexelSize() {
4663
+ if (!this.three.shadowMap.enabled) return void 0;
4664
+ for (const light of this.sunLights()) {
4665
+ if (!light.castShadow || light.shadow.intensity <= 0) continue;
4666
+ const camera = light.shadow.camera;
4667
+ return (camera.right - camera.left) / (light.shadow.mapSize.x || 1);
4668
+ }
4669
+ }
4670
+ /**
4127
4671
  * Turn sun shadows on at a map resolution, or off, without rebuilding the environment. Once a
4128
4672
  * light has cast shadows, 'off' stops redrawing its map and fades it out, so every lit shader
4129
4673
  * keeps the shadow inputs it was built with: a host that turns shadows on once before its first
@@ -4164,7 +4708,7 @@ var Renderer = class Renderer {
4164
4708
  if (this.backend === "webgpu" && this.three.shadowMap.enabled) return;
4165
4709
  if (parked && this.three.shadowMap.enabled) return;
4166
4710
  this.three.shadowMap.enabled = enabled;
4167
- this.three.shadowMap.type = quality === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
4711
+ this.three.shadowMap.type = quality === "low" || this.backend === "webgl" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
4168
4712
  }
4169
4713
  /** WebGL PCF shadow lookups against a reversed depth buffer; see focusDirectionalShadow. */
4170
4714
  webglReversedPcfShadows() {
@@ -4182,12 +4726,26 @@ var Renderer = class Renderer {
4182
4726
  }
4183
4727
  applyShadowFocus() {
4184
4728
  const focus = this.shadowFocus;
4185
- if (focus === void 0 || !this.three.shadowMap.enabled) return;
4186
- const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
4187
- for (const light of this.sunLights()) {
4188
- if (!light.castShadow) continue;
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);
4729
+ let far;
4730
+ if (focus !== void 0 && this.three.shadowMap.enabled) {
4731
+ const center = this.shadowCenter.set(focus.center[0] - this.worldOrigin[0], focus.center[1] - this.worldOrigin[1], focus.center[2] - this.worldOrigin[2]);
4732
+ const reversedPcf = this.backend === "webgl" && this.webglReversedPcfShadows();
4733
+ for (const light of this.sunLights()) {
4734
+ if (!light.castShadow) continue;
4735
+ const direction = light === this.activeSky?.sunLight ? this.shadowDirection.fromArray(this.activeSky.frame.sunDirection) : this.shadowDirection.copy(light.userData.molenSunDirection);
4736
+ focusDirectionalShadow(light, direction, center, focus.radius, reversedPcf, this.worldOrigin);
4737
+ if (far === void 0 && focus.far !== void 0 && light.shadow.autoUpdate && light.shadow.intensity > 0 && light.visible && direction.y > .02) far = {
4738
+ direction: this.farShadowDirection.copy(direction).normalize(),
4739
+ center: this.farShadowCenter.set(focus.far.center[0] - this.worldOrigin[0], focus.far.center[1] - this.worldOrigin[1], focus.far.center[2] - this.worldOrigin[2]),
4740
+ radius: focus.far.radius,
4741
+ mapSize: Math.min(2048, light.shadow.mapSize.x),
4742
+ biasAddsTowardLight: reversedPcf,
4743
+ worldOrigin: this.worldOrigin,
4744
+ now: performance.now()
4745
+ };
4746
+ }
4190
4747
  }
4748
+ this.farShadow?.update(far);
4191
4749
  }
4192
4750
  /** Active weather effects; physical weather data is also available in the simulation component. */
4193
4751
  get weather() {
@@ -4268,20 +4826,24 @@ var Renderer = class Renderer {
4268
4826
  const probeMs = opts.backendProbeTimeoutMs ?? 5e3;
4269
4827
  try {
4270
4828
  if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
4271
- if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
4272
- const { createWebGpuDriver } = await import("./webgpu-driver-BQnmPRqs.mjs");
4829
+ const adapter = await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request");
4830
+ if (adapter === null) throw new Error("WebGPU reported no adapter for this device");
4831
+ const { createWebGpuDriver } = await import("./webgpu-driver-YWVTLOY7.mjs");
4273
4832
  const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
4274
4833
  late.dispose();
4275
4834
  });
4276
4835
  try {
4277
4836
  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");
4837
+ const clouds = await import("./webgpu-clouds-DwSBoV8A.mjs");
4838
+ const snow = await import("./webgpu-snow-cover-CiqYhvPq.mjs");
4279
4839
  return new Renderer(opts, {
4280
4840
  three,
4281
4841
  backend: "webgpu",
4842
+ softwareAdapter: softwareAdapter(adapter),
4282
4843
  clouds: {
4283
4844
  material: clouds.createWebGpuCloudMaterial,
4284
- installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms)
4845
+ installShadows: (uniforms) => clouds.installWebGpuCloudShadows(three, uniforms),
4846
+ installSnowCover: (uniforms) => snow.installWebGpuSnowCover(three, uniforms)
4285
4847
  },
4286
4848
  ...optimizer ? { optimizer } : {},
4287
4849
  ...opts.reflections === true ? { reflectionFilter: (await import("./webgpu-sky-reflections-CymGEes-.mjs")).createWebGpuSkyReflectionFilter(three) } : {}
@@ -4323,6 +4885,7 @@ var Renderer = class Renderer {
4323
4885
  this.viewportHeight = height;
4324
4886
  this.pixelRatio = pixelRatio;
4325
4887
  this.backend = initialized?.backend ?? "webgl";
4888
+ if (this.backend === "webgpu") this.software = initialized?.softwareAdapter === true;
4326
4889
  this.optimizer = initialized?.optimizer;
4327
4890
  this.cloudBackend = initialized?.clouds;
4328
4891
  this.three = initialized?.three ?? createWebGlRenderer({
@@ -4334,8 +4897,19 @@ var Renderer = class Renderer {
4334
4897
  logarithmicDepthBuffer: opts.logarithmicDepthBuffer ?? false
4335
4898
  });
4336
4899
  this.three.setPixelRatio(pixelRatio);
4337
- if (this.cloudBackend) this.cloudBackend.installShadows(this.cloudShadows);
4338
- else this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows);
4900
+ if (this.cloudBackend) {
4901
+ this.cloudBackend.installShadows(this.cloudShadows);
4902
+ this.cloudBackend.installSnowCover(this.snowCover);
4903
+ } else {
4904
+ this.cullGroups = opts.cullRenderGroups !== false;
4905
+ if (this.cullGroups) this.installShadowCulling(this.three);
4906
+ const far = new FarShadow(this.three);
4907
+ this.farShadow = far;
4908
+ this.releaseCloudShadows = installWebGlCloudShadows(this.three, this.cloudShadows, (shader, material) => {
4909
+ injectFarShadow(shader, far.uniforms);
4910
+ injectSnowCover(shader, this.snowCover, material);
4911
+ });
4912
+ }
4339
4913
  if (this.backend === "webgpu") this.three.onDeviceLost = (info) => {
4340
4914
  if (this.disposed) return;
4341
4915
  this.deviceLossReason = info.message;
@@ -4619,11 +5193,11 @@ var Renderer = class Renderer {
4619
5193
  });
4620
5194
  }
4621
5195
  const instanced = mesh;
4622
- const fresh = [
4623
- ...Object.values(mesh.geometry.attributes).map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a),
5196
+ const fresh = [...new Set([
5197
+ ...Object.values(mesh.geometry.attributes),
4624
5198
  ...mesh.geometry.index ? [mesh.geometry.index] : [],
4625
5199
  ...instanced.isInstancedMesh ? [instanced.instanceMatrix, ...instanced.instanceColor ? [instanced.instanceColor] : []] : []
4626
- ].filter((attribute) => {
5200
+ ].map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a))].filter((attribute) => {
4627
5201
  if (lane.glAttributes.has(attribute)) return false;
4628
5202
  const existing = this.preparedResources.get(attribute);
4629
5203
  if (existing?.version === attribute.version) {
@@ -4929,15 +5503,37 @@ var Renderer = class Renderer {
4929
5503
  check();
4930
5504
  });
4931
5505
  }
4932
- /** The scene's visible lights, gathered once between rendered frames for warm-up builds. */
5506
+ /**
5507
+ * The scene's visible lights, for warm-up builds, as of this frame. Finding them is a walk of
5508
+ * the whole visible scene, and made once between rendered frames that was 1.2 ms of every frame
5509
+ * that prepared anything over a streamed city (two lights among nine thousand objects), which
5510
+ * in flight is all of them. So the lights found stand for `LIGHTS_REFRESH_MS`, or until the
5511
+ * scene's own children change, and each frame only checks which of them are still on show. A
5512
+ * light that appears deeper in the scene counts from the next walk: until then a warm-up is
5513
+ * built, and remembered, for the lights before it, so it is prepared again rather than taken
5514
+ * for ready.
5515
+ */
4933
5516
  sceneLights() {
4934
- this.preparationLights ??= (() => {
5517
+ if (this.preparationLights !== void 0) return this.preparationLights;
5518
+ const now = performance.now();
5519
+ const children = this.scene.children.length;
5520
+ if (this.foundLights === void 0 || children !== this.foundLightsChildren || now - this.foundLightsAt >= LIGHTS_REFRESH_MS) {
4935
5521
  const lights = [];
4936
5522
  THREE.Object3D.prototype.traverseVisible.call(this.scene, (object) => {
4937
5523
  if (object.isLight) lights.push(object);
4938
5524
  });
4939
- return lights;
4940
- })();
5525
+ this.foundLights = lights;
5526
+ this.foundLightsChildren = children;
5527
+ this.foundLightsAt = now;
5528
+ }
5529
+ const scene = this.scene;
5530
+ this.preparationLights = this.foundLights.filter((light) => {
5531
+ for (let cursor = light; cursor !== null; cursor = cursor.parent) {
5532
+ if (!cursor.visible) return false;
5533
+ if (cursor === scene) return true;
5534
+ }
5535
+ return false;
5536
+ });
4941
5537
  return this.preparationLights;
4942
5538
  }
4943
5539
  /**
@@ -5025,6 +5621,7 @@ var Renderer = class Renderer {
5025
5621
  weather?.update(this.weatherTimeOverride ?? this.environmentSeconds, this.camera, this.worldOrigin, sky?.frame);
5026
5622
  if (weather) weather.writeShadows(this.cloudShadows, cloudShadowed);
5027
5623
  else this.cloudShadows.molenCloudShadow.value.x = 0;
5624
+ writeSnowCover(this.snowCover, weather?.data.snowCover, this.worldOrigin);
5028
5625
  const shadowMap = this.cloudShadows.molenCloudMap.value;
5029
5626
  if (weather && shadowMap.version !== this.cloudShadowMapVersion) {
5030
5627
  this.cloudShadowMapVersion = shadowMap.version;
@@ -5101,6 +5698,7 @@ var Renderer = class Renderer {
5101
5698
  if (hidden.light.visible !== hidden.visible) this.shadowCastersWarmed = false;
5102
5699
  hidden.light.visible = hidden.visible;
5103
5700
  this.hiddenAmbient = void 0;
5701
+ this.foundLights = void 0;
5104
5702
  }
5105
5703
  if (light === void 0) return;
5106
5704
  this.hiddenAmbient ??= {
@@ -5114,8 +5712,11 @@ var Renderer = class Renderer {
5114
5712
  const warmup = this.shadowCasterWarmup();
5115
5713
  if (warmup !== void 0) this.scene.add(warmup);
5116
5714
  try {
5715
+ this.cullOutOfView();
5117
5716
  this.optimized(() => this.three.render(this.scene, this.camera));
5118
5717
  } finally {
5718
+ for (const group of this.culledGroups) group.visible = true;
5719
+ this.culledGroups.length = 0;
5119
5720
  if (warmup !== void 0) {
5120
5721
  warmup.removeFromParent();
5121
5722
  for (const child of warmup.children) {
@@ -5127,6 +5728,127 @@ var Renderer = class Renderer {
5127
5728
  }
5128
5729
  }
5129
5730
  /**
5731
+ * Hide, for the scene walk about to start, every render group whose bounds lie wholly outside
5732
+ * the camera's view: three then skips it and everything under it when it brings world matrices
5733
+ * up to date, updates levels of detail and gathers what to draw, none of which can draw
5734
+ * anything from it. Shown again when the render ends (see `renderScene`), so nothing outside the
5735
+ * render sees a group hidden. Shadow maps are walked on their own terms (`installShadowCulling`).
5736
+ */
5737
+ cullOutOfView() {
5738
+ if (!this.cullGroups || this.renderGroups.size === 0) return;
5739
+ const camera = this.camera;
5740
+ if (camera.parent === null && camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
5741
+ viewProjection(camera, cullMatrix);
5742
+ for (const ref of this.renderGroups) {
5743
+ const group = ref.deref();
5744
+ if (group === void 0) {
5745
+ this.renderGroups.delete(ref);
5746
+ continue;
5747
+ }
5748
+ const parent = group.parent;
5749
+ if (parent === null) continue;
5750
+ const bounds = group.userData[RENDER_BOUNDS];
5751
+ if (bounds === void 0 || !group.visible || bounds.isEmpty()) continue;
5752
+ if (group.userData["renderBoundsStale"] === true) continue;
5753
+ if (!groupInScene(group, this.scene)) continue;
5754
+ if (cullFrames.get(parent) !== cullPass) {
5755
+ cullFrames.set(parent, cullPass);
5756
+ parent.updateWorldMatrix(true, false);
5757
+ }
5758
+ cullBox.copy(bounds).applyMatrix4(parent.matrixWorld);
5759
+ if (!boxOutsideView(cullMatrix, cullBox.min, cullBox.max)) continue;
5760
+ group.visible = false;
5761
+ this.culledGroups.push(group);
5762
+ }
5763
+ cullPass++;
5764
+ }
5765
+ /**
5766
+ * Walk each shadow map's casters without the render groups that cannot cast into it. A map is
5767
+ * drawn from its light, so what counts is the light's own view, not the camera's: groups hidden
5768
+ * for the camera come back for a light that reaches them (with their world matrices and levels
5769
+ * of detail brought up to date, which the scene's walk skipped), and groups the camera sees stay
5770
+ * out of a map that ends short of them. The sun's focused map covers a few hundred meters of a
5771
+ * view tens of kilometers deep, and three walked every object of that view for it. Lights
5772
+ * other than directional ones keep every group, as before.
5773
+ */
5774
+ installShadowCulling(renderer) {
5775
+ const shadowMap = renderer.shadowMap;
5776
+ const render = shadowMap.render;
5777
+ if (typeof render !== "function") return;
5778
+ const matrices = [];
5779
+ const depths = [];
5780
+ /** When each group out of view last had its levels of detail chosen for a shadow map. */
5781
+ const shadowLods = /* @__PURE__ */ new WeakMap();
5782
+ shadowMap.render = (lights, scene, camera) => {
5783
+ if (!this.cullGroups || this.renderGroups.size === 0 || lights.length === 0 || !renderer.shadowMap.enabled) {
5784
+ render.call(shadowMap, lights, scene, camera);
5785
+ return;
5786
+ }
5787
+ const shadowOf = (light) => light.shadow;
5788
+ const drawn = lights.filter((light) => {
5789
+ const shadow = shadowOf(light);
5790
+ return shadow !== void 0 && (shadow.autoUpdate || shadow.needsUpdate);
5791
+ });
5792
+ const directional = drawn.every((light) => light.isDirectionalLight);
5793
+ let count = 0;
5794
+ if (directional) for (const light of drawn) {
5795
+ const shadow = shadowOf(light);
5796
+ shadow.updateMatrices(light);
5797
+ let matrix = matrices[count];
5798
+ if (matrix === void 0) {
5799
+ matrix = new THREE.Matrix4();
5800
+ matrices[count] = matrix;
5801
+ }
5802
+ viewProjection(shadow.camera, matrix);
5803
+ const lens = shadow.camera;
5804
+ depths[count] = {
5805
+ view: lens.matrixWorldInverse,
5806
+ near: lens.near,
5807
+ far: lens.far
5808
+ };
5809
+ count++;
5810
+ }
5811
+ const changed = [];
5812
+ const hidden = new Set(this.culledGroups);
5813
+ const now = performance.now();
5814
+ for (const ref of this.renderGroups) {
5815
+ const group = ref.deref();
5816
+ const parent = group?.parent;
5817
+ if (group === void 0 || parent === null || parent === void 0) continue;
5818
+ const culled = hidden.has(group);
5819
+ if (!culled && !group.visible) continue;
5820
+ const bounds = group.userData[RENDER_BOUNDS];
5821
+ let reached = !directional || bounds === void 0 || bounds.isEmpty() || group.userData["renderBoundsStale"] === true;
5822
+ if (!reached) {
5823
+ cullBox.copy(bounds).applyMatrix4(parent.matrixWorld);
5824
+ for (let i = 0; i < count && !reached; i++) reached = !boxOutsideView(matrices[i], cullBox.min, cullBox.max, depths[i]);
5825
+ }
5826
+ if (reached === !culled) continue;
5827
+ group.visible = reached;
5828
+ changed.push(group);
5829
+ if (!reached) continue;
5830
+ if (group.matrixWorldNeedsUpdate || group.userData["renderMatricesStale"] === true) {
5831
+ group.userData[RENDER_MATRICES_STALE] = false;
5832
+ group.updateMatrixWorld();
5833
+ }
5834
+ if (now - (shadowLods.get(group) ?? Number.NEGATIVE_INFINITY) < SHADOW_LOD_MS) continue;
5835
+ shadowLods.set(group, now);
5836
+ group.traverseVisible((object) => {
5837
+ const lod = object;
5838
+ if (lod.isLOD && lod.autoUpdate) lod.update(camera);
5839
+ });
5840
+ }
5841
+ try {
5842
+ render.call(shadowMap, lights, scene, camera);
5843
+ } finally {
5844
+ for (const group of changed) group.visible = !group.visible;
5845
+ }
5846
+ };
5847
+ this.releaseShadowCulling = () => {
5848
+ shadowMap.render = render;
5849
+ };
5850
+ }
5851
+ /**
5130
5852
  * Once WebGL sun shadows draw, a frame of degenerate casters (one plain and one instanced mesh
5131
5853
  * per side): the shadow pass builds a depth program for each kind of caster the first time it
5132
5854
  * draws one, and the first double-sided caster in view held a mid-flight frame 10 ms. The
@@ -5231,9 +5953,18 @@ var Renderer = class Renderer {
5231
5953
  }
5232
5954
  return this.occlusion?.camera === this.camera ? this.occlusion.pass : void 0;
5233
5955
  }
5234
- /** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
5956
+ /**
5957
+ * Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands.
5958
+ * WebGL leaves a group out of the scene walks it cannot be seen in, once its owner states its
5959
+ * bounds in `userData.renderBounds` (see `RENDER_BOUNDS`) and keeps them true as its content
5960
+ * changes (`expandRenderBounds`, `markRenderBoundsChanged`): see `cullRenderGroups`.
5961
+ */
5235
5962
  createRenderGroup() {
5236
- return this.optimizer?.createGroup() ?? new THREE.Group();
5963
+ const optimized = this.optimizer?.createGroup();
5964
+ if (optimized !== void 0) return optimized;
5965
+ const group = new THREE.Group();
5966
+ if (this.cullGroups) this.renderGroups.add(new WeakRef(group));
5967
+ return group;
5237
5968
  }
5238
5969
  /** Last completed visible frame, excluding offscreen resource preparation. */
5239
5970
  stats() {
@@ -5264,6 +5995,9 @@ var Renderer = class Renderer {
5264
5995
  this.activeWeather?.dispose();
5265
5996
  this.activeWeather = void 0;
5266
5997
  this.releaseCloudShadows?.();
5998
+ this.farShadow?.dispose();
5999
+ this.releaseShadowCulling?.();
6000
+ this.renderGroups.clear();
5267
6001
  this.cloudTextures.dispose();
5268
6002
  this.reflections?.dispose();
5269
6003
  this.hideReflectedAmbient(void 0);
@@ -5939,4 +6673,4 @@ function decodeStarCatalog(input) {
5939
6673
  }));
5940
6674
  }
5941
6675
  //#endregion
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 };
6676
+ export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, INSTANCE_BATCH_COLOR, INSTANCE_BATCH_MATRIX_COLUMNS, InputMap, InstanceBatch, InstanceMatrixAttribute, InterpolationBuffer, MaterialResolver, RENDER_BOUNDS, RENDER_BOUNDS_STALE, RENDER_MATRICES_STALE, Renderer, SceneMirror, SkyReflections, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applyLivery, applySceneCamera, boxOutsideView, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createIndexedDbMaterialStore, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, createWebGlSkyReflectionFilter, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, expandRenderBounds, followCameraPose, isInstanceBatch, isInstanceBatchGeometry, lerp3, liveryGraphicTexture, localCommand, markRenderBoundsChanged, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, observePageActivity, orthoFrustum, readModelSignals, reflectionStateFromLights, resolveAction, resolveWeather, skyTimeMs, starDirection, viewProjection, weatherProfile };