@bendyline/molen-client 0.0.1
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/LICENSE +21 -0
- package/NOTICE.md +11 -0
- package/README.md +95 -0
- package/dist/aircraft.d.mts +23 -0
- package/dist/aircraft.mjs +99 -0
- package/dist/camera-track.d.mts +20 -0
- package/dist/camera-track.mjs +102 -0
- package/dist/index.d.mts +1000 -0
- package/dist/index.mjs +4579 -0
- package/dist/math-ev_jEkRe.mjs +42 -0
- package/dist/model-signals-DVlLyP-w.d.mts +17 -0
- package/dist/model-signals-Gw1COJfo.mjs +53 -0
- package/dist/renderer-B3pd4N-J.d.mts +446 -0
- package/dist/vehicle-interior-0o-8QV_-.d.mts +31 -0
- package/dist/vehicle-interior-DZT0HmWC.mjs +12 -0
- package/dist/vehicles.d.mts +17 -0
- package/dist/vehicles.mjs +174 -0
- package/dist/vite.d.mts +24 -0
- package/dist/vite.mjs +57 -0
- package/dist/webgpu-driver-DXsRuz8j.mjs +75 -0
- package/dist/webgpu-frame-timer-Xnuq1Hld.mjs +97 -0
- package/dist/webgpu-scene-optimizer-D6e9ZJQM.mjs +319 -0
- package/package.json +85 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,4579 @@
|
|
|
1
|
+
import { n as nlerp4, t as lerp3 } from "./math-ev_jEkRe.mjs";
|
|
2
|
+
import { n as readModelSignals, t as createModelSignalVisual } from "./model-signals-Gw1COJfo.mjs";
|
|
3
|
+
import { t as createWebGpuFrameTimer } from "./webgpu-frame-timer-Xnuq1Hld.mjs";
|
|
4
|
+
import { inputProfileIssues, inputProfileSchema, resolveWeather, resolveWeather as resolveWeather$1, skySchema, validateByKind, weatherProfile, weatherSchema } from "@bendyline/molen-schema";
|
|
5
|
+
import * as THREE from "three";
|
|
6
|
+
import * as SkeletonUtils from "three/addons/utils/SkeletonUtils.js";
|
|
7
|
+
import { bakeMatGraph, bakePixelGrid, registerMaterialSchemas } from "@bendyline/molen-materials";
|
|
8
|
+
import { MeshoptDecoder } from "three/addons/libs/meshopt_decoder.module.js";
|
|
9
|
+
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
|
|
10
|
+
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
|
|
11
|
+
import { KTX2Loader } from "three/addons/loaders/KTX2Loader.js";
|
|
12
|
+
//#region src/adaptive-quality.ts
|
|
13
|
+
function positive(value, name, allowZero = false) {
|
|
14
|
+
if (!Number.isFinite(value) || (allowZero ? value < 0 : value <= 0)) throw new RangeError(`${name} must be a finite ${allowZero ? "nonnegative" : "positive"} number`);
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
function levelBounds(min, max) {
|
|
18
|
+
if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < min) throw new RangeError("Quality levels must be nonnegative integers with minLevel <= maxLevel");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Rendering-only feedback controller; does not change simulation state or depend on a browser.
|
|
22
|
+
* Lower quickly, recover slowly, and probe with backoff instead of oscillating between tiers.
|
|
23
|
+
* Hosts should apply a change atomically to resolution, screen-space error, and residency.
|
|
24
|
+
*/
|
|
25
|
+
var AdaptiveQualityController = class {
|
|
26
|
+
minLevel;
|
|
27
|
+
maxLevel;
|
|
28
|
+
level;
|
|
29
|
+
targetFrameMs;
|
|
30
|
+
evaluationIntervalMs;
|
|
31
|
+
warmupMs;
|
|
32
|
+
decreaseDelayMs;
|
|
33
|
+
increaseDelayMs;
|
|
34
|
+
cooldownMs;
|
|
35
|
+
pauseFrameMs;
|
|
36
|
+
frames = [];
|
|
37
|
+
frameCursor = 0;
|
|
38
|
+
clockMs = 0;
|
|
39
|
+
windowMs = 0;
|
|
40
|
+
warmupElapsedMs = 0;
|
|
41
|
+
lastChangeMs = Number.NEGATIVE_INFINITY;
|
|
42
|
+
overloadMs = 0;
|
|
43
|
+
headroomMs = 0;
|
|
44
|
+
loading = false;
|
|
45
|
+
cpuTotalMs = 0;
|
|
46
|
+
cpuSamples = 0;
|
|
47
|
+
gpuTotalMs = 0;
|
|
48
|
+
gpuSamples = 0;
|
|
49
|
+
memoryTotal = 0;
|
|
50
|
+
memorySamples = 0;
|
|
51
|
+
previousPause = false;
|
|
52
|
+
smoothedFrameMs;
|
|
53
|
+
p90FrameMs;
|
|
54
|
+
slowFrameRatio = 0;
|
|
55
|
+
samples = 0;
|
|
56
|
+
changes = 0;
|
|
57
|
+
reason;
|
|
58
|
+
recoveryMultiplier = 1;
|
|
59
|
+
lastUpgradeMs = Number.NEGATIVE_INFINITY;
|
|
60
|
+
constructor(options = {}) {
|
|
61
|
+
this.minLevel = options.minLevel ?? 0;
|
|
62
|
+
this.maxLevel = options.maxLevel ?? 5;
|
|
63
|
+
levelBounds(this.minLevel, this.maxLevel);
|
|
64
|
+
const initial = options.initialLevel ?? Math.min(3, this.maxLevel);
|
|
65
|
+
if (!Number.isSafeInteger(initial)) throw new RangeError("initialLevel must be an integer");
|
|
66
|
+
this.level = Math.max(this.minLevel, Math.min(this.maxLevel, initial));
|
|
67
|
+
this.targetFrameMs = positive(options.targetFrameMs ?? 1e3 / 60, "targetFrameMs");
|
|
68
|
+
this.evaluationIntervalMs = positive(options.evaluationIntervalMs ?? 1e3, "evaluationIntervalMs");
|
|
69
|
+
this.warmupMs = positive(options.warmupMs ?? 1500, "warmupMs", true);
|
|
70
|
+
this.decreaseDelayMs = positive(options.decreaseDelayMs ?? 1e3, "decreaseDelayMs", true);
|
|
71
|
+
this.increaseDelayMs = positive(options.increaseDelayMs ?? 1e4, "increaseDelayMs");
|
|
72
|
+
this.cooldownMs = positive(options.cooldownMs ?? 2e3, "cooldownMs", true);
|
|
73
|
+
this.pauseFrameMs = positive(options.pauseFrameMs ?? 1e3, "pauseFrameMs");
|
|
74
|
+
}
|
|
75
|
+
/** No allocation in the usual per-frame path. A change object is returned only on a step. */
|
|
76
|
+
sample(frameMs, sample = {}) {
|
|
77
|
+
if (sample.active === false) {
|
|
78
|
+
this.resetMeasurements();
|
|
79
|
+
this.previousPause = false;
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (!Number.isFinite(frameMs) || frameMs <= 0) return;
|
|
83
|
+
if (frameMs > this.pauseFrameMs && !this.previousPause) {
|
|
84
|
+
this.resetMeasurements();
|
|
85
|
+
this.previousPause = true;
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
this.previousPause = frameMs > this.pauseFrameMs;
|
|
89
|
+
const elapsed = Math.min(frameMs, this.pauseFrameMs);
|
|
90
|
+
this.clockMs += elapsed;
|
|
91
|
+
this.windowMs += elapsed;
|
|
92
|
+
this.warmupElapsedMs += elapsed;
|
|
93
|
+
if (this.frames.length < 512) this.frames.push(elapsed);
|
|
94
|
+
else this.frames[this.frameCursor++ % 512] = elapsed;
|
|
95
|
+
this.loading ||= sample.loading === true;
|
|
96
|
+
if (Number.isFinite(sample.cpuFrameMs) && (sample.cpuFrameMs ?? 0) > 0) {
|
|
97
|
+
this.cpuTotalMs += sample.cpuFrameMs ?? 0;
|
|
98
|
+
this.cpuSamples++;
|
|
99
|
+
}
|
|
100
|
+
if (Number.isFinite(sample.gpuFrameMs) && (sample.gpuFrameMs ?? 0) > 0) {
|
|
101
|
+
this.gpuTotalMs += sample.gpuFrameMs ?? 0;
|
|
102
|
+
this.gpuSamples++;
|
|
103
|
+
}
|
|
104
|
+
if (Number.isFinite(sample.memoryPressure) && (sample.memoryPressure ?? -1) >= 0) {
|
|
105
|
+
this.memoryTotal += sample.memoryPressure ?? 0;
|
|
106
|
+
this.memorySamples++;
|
|
107
|
+
}
|
|
108
|
+
if (this.windowMs < this.evaluationIntervalMs || this.frames.length < 8) return;
|
|
109
|
+
return this.evaluate();
|
|
110
|
+
}
|
|
111
|
+
getStats() {
|
|
112
|
+
return {
|
|
113
|
+
level: this.level,
|
|
114
|
+
targetFrameMs: this.targetFrameMs,
|
|
115
|
+
smoothedFrameMs: this.smoothedFrameMs,
|
|
116
|
+
p90FrameMs: this.p90FrameMs,
|
|
117
|
+
slowFrameRatio: this.slowFrameRatio,
|
|
118
|
+
samples: this.samples,
|
|
119
|
+
changes: this.changes,
|
|
120
|
+
recoveryDelayMs: this.increaseDelayMs * this.recoveryMultiplier,
|
|
121
|
+
reason: this.reason
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/** Set a manual tier or restart automatic adaptation without carrying stale timing samples. */
|
|
125
|
+
setLevel(level) {
|
|
126
|
+
if (!Number.isSafeInteger(level)) throw new RangeError("level must be an integer");
|
|
127
|
+
const clamped = Math.max(this.minLevel, Math.min(this.maxLevel, level));
|
|
128
|
+
const change = clamped === this.level ? void 0 : this.change(clamped, "manual");
|
|
129
|
+
this.recoveryMultiplier = 1;
|
|
130
|
+
this.lastUpgradeMs = Number.NEGATIVE_INFINITY;
|
|
131
|
+
this.resetMeasurements();
|
|
132
|
+
this.previousPause = false;
|
|
133
|
+
return change;
|
|
134
|
+
}
|
|
135
|
+
/** Change a user/device ceiling and floor; an out-of-bounds current level is clamped. */
|
|
136
|
+
setBounds(minLevel, maxLevel) {
|
|
137
|
+
levelBounds(minLevel, maxLevel);
|
|
138
|
+
this.minLevel = minLevel;
|
|
139
|
+
this.maxLevel = maxLevel;
|
|
140
|
+
return this.setLevel(this.level);
|
|
141
|
+
}
|
|
142
|
+
evaluate() {
|
|
143
|
+
const ordered = this.frames.slice().sort((a, b) => a - b);
|
|
144
|
+
const trim = Math.floor(ordered.length * .1);
|
|
145
|
+
const middle = ordered.slice(trim, ordered.length - trim);
|
|
146
|
+
const mean = middle.reduce((total, value) => total + value, 0) / middle.length;
|
|
147
|
+
const elapsed = this.windowMs;
|
|
148
|
+
const alpha = 1 - Math.exp(-elapsed / 1500);
|
|
149
|
+
this.smoothedFrameMs = this.smoothedFrameMs === void 0 ? mean : this.smoothedFrameMs + alpha * (mean - this.smoothedFrameMs);
|
|
150
|
+
this.p90FrameMs = ordered[Math.ceil(ordered.length * .9) - 1] ?? mean;
|
|
151
|
+
this.slowFrameRatio = ordered.filter((value) => value > this.targetFrameMs * 1.25).length / ordered.length;
|
|
152
|
+
this.samples = ordered.length;
|
|
153
|
+
const memory = this.memorySamples > 0 ? this.memoryTotal / this.memorySamples : 0;
|
|
154
|
+
const work = Math.max(this.cpuSamples > 0 ? this.cpuTotalMs / this.cpuSamples : 0, this.gpuSamples > 0 ? this.gpuTotalMs / this.gpuSamples : 0);
|
|
155
|
+
const loading = this.loading;
|
|
156
|
+
this.resetWindow();
|
|
157
|
+
const overloaded = mean > this.targetFrameMs * 1.18 || this.p90FrameMs > this.targetFrameMs * 1.5 && this.slowFrameRatio >= .25;
|
|
158
|
+
const headroom = !loading && memory < .85 && mean <= this.targetFrameMs * 1.05 && this.p90FrameMs <= this.targetFrameMs * 1.15 && work < this.targetFrameMs * .9;
|
|
159
|
+
this.overloadMs = overloaded ? this.overloadMs + elapsed : 0;
|
|
160
|
+
this.headroomMs = headroom ? this.headroomMs + elapsed : 0;
|
|
161
|
+
if (this.warmupElapsedMs < this.warmupMs) return;
|
|
162
|
+
if (memory > 1 && this.level > this.minLevel) return this.change(this.level - 1, "memory-pressure");
|
|
163
|
+
if (this.clockMs - this.lastChangeMs < this.cooldownMs) return;
|
|
164
|
+
if (overloaded && this.overloadMs >= this.decreaseDelayMs && this.level > this.minLevel) return this.change(this.level - 1, "frame-time");
|
|
165
|
+
if (headroom && this.headroomMs >= this.increaseDelayMs * this.recoveryMultiplier && this.level < this.maxLevel) return this.change(this.level + 1, "headroom");
|
|
166
|
+
}
|
|
167
|
+
change(level, reason) {
|
|
168
|
+
const previousLevel = this.level;
|
|
169
|
+
if (reason === "headroom") this.lastUpgradeMs = this.clockMs;
|
|
170
|
+
else if (reason !== "manual" && this.clockMs - this.lastUpgradeMs < Math.max(15e3, this.cooldownMs * 3)) {
|
|
171
|
+
this.recoveryMultiplier = Math.min(6, this.recoveryMultiplier * 2);
|
|
172
|
+
this.lastUpgradeMs = Number.NEGATIVE_INFINITY;
|
|
173
|
+
}
|
|
174
|
+
this.level = level;
|
|
175
|
+
this.reason = reason;
|
|
176
|
+
this.changes++;
|
|
177
|
+
this.lastChangeMs = this.clockMs;
|
|
178
|
+
this.overloadMs = 0;
|
|
179
|
+
this.headroomMs = 0;
|
|
180
|
+
return {
|
|
181
|
+
previousLevel,
|
|
182
|
+
level,
|
|
183
|
+
reason
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
resetWindow() {
|
|
187
|
+
this.frames.length = 0;
|
|
188
|
+
this.frameCursor = 0;
|
|
189
|
+
this.windowMs = 0;
|
|
190
|
+
this.loading = false;
|
|
191
|
+
this.cpuTotalMs = 0;
|
|
192
|
+
this.cpuSamples = 0;
|
|
193
|
+
this.gpuTotalMs = 0;
|
|
194
|
+
this.gpuSamples = 0;
|
|
195
|
+
this.memoryTotal = 0;
|
|
196
|
+
this.memorySamples = 0;
|
|
197
|
+
}
|
|
198
|
+
resetMeasurements() {
|
|
199
|
+
this.resetWindow();
|
|
200
|
+
this.warmupElapsedMs = 0;
|
|
201
|
+
this.overloadMs = 0;
|
|
202
|
+
this.headroomMs = 0;
|
|
203
|
+
this.smoothedFrameMs = void 0;
|
|
204
|
+
this.p90FrameMs = void 0;
|
|
205
|
+
this.slowFrameRatio = 0;
|
|
206
|
+
this.samples = 0;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
//#endregion
|
|
210
|
+
//#region src/assets.ts
|
|
211
|
+
function isUrlish(ref) {
|
|
212
|
+
return ref.includes("/") || ref.startsWith("./") || /^https?:/.test(ref);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* URL-backed provider: asset ids resolve through an id -> URL index (from the project manifest's
|
|
216
|
+
* assets record, mapped to served model URLs); URL-ish refs resolve against baseUrl.
|
|
217
|
+
*/
|
|
218
|
+
function createUrlAssetProvider(baseUrl, index, options = {}) {
|
|
219
|
+
const candidates = (ref) => {
|
|
220
|
+
const mapped = index?.[ref];
|
|
221
|
+
if (mapped !== void 0) return [new URL(mapped, baseUrl).href];
|
|
222
|
+
if (isUrlish(ref)) return [new URL(ref, baseUrl).href];
|
|
223
|
+
const dir = `assets/${ref.replaceAll(".", "/")}`;
|
|
224
|
+
const urls = [new URL(`${dir}/model.glb`, baseUrl).href];
|
|
225
|
+
if (options.variant !== void 0) urls.unshift(new URL(`${dir}/model.${options.variant}.glb`, baseUrl).href);
|
|
226
|
+
return urls;
|
|
227
|
+
};
|
|
228
|
+
const fetchFirst = async (ref) => {
|
|
229
|
+
const urls = candidates(ref);
|
|
230
|
+
for (let i = 0; i < urls.length; i++) {
|
|
231
|
+
const url = urls[i];
|
|
232
|
+
const res = await fetch(url);
|
|
233
|
+
if (res.ok) return res;
|
|
234
|
+
if (res.status !== 404 || i === urls.length - 1) throw new Error(`asset "${ref}": HTTP ${res.status} for ${url}`);
|
|
235
|
+
}
|
|
236
|
+
throw new Error(`asset "${ref}": no candidate URL`);
|
|
237
|
+
};
|
|
238
|
+
return {
|
|
239
|
+
async load(ref) {
|
|
240
|
+
return (await fetchFirst(ref)).arrayBuffer();
|
|
241
|
+
},
|
|
242
|
+
async loadText(ref) {
|
|
243
|
+
return (await fetchFirst(ref)).text();
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Parse each glTF ref once; hand out per-entity instances (SkeletonUtils.clone so skinned
|
|
249
|
+
* meshes work while geometry/textures stay shared). `whenIdle()` resolves when no loads are
|
|
250
|
+
* pending — the capture path awaits it before its single deterministic frame.
|
|
251
|
+
*/
|
|
252
|
+
var AssetCache = class {
|
|
253
|
+
provider;
|
|
254
|
+
loader;
|
|
255
|
+
loads = /* @__PURE__ */ new Map();
|
|
256
|
+
bases = /* @__PURE__ */ new Set();
|
|
257
|
+
disposedGeometries = /* @__PURE__ */ new Set();
|
|
258
|
+
disposedMaterials = /* @__PURE__ */ new Set();
|
|
259
|
+
pending = 0;
|
|
260
|
+
idleResolvers = [];
|
|
261
|
+
disposed = false;
|
|
262
|
+
constructor(provider, loader) {
|
|
263
|
+
this.provider = provider;
|
|
264
|
+
this.loader = loader;
|
|
265
|
+
}
|
|
266
|
+
/** Register an external async task (e.g. a material bake) so whenIdle() waits for it. */
|
|
267
|
+
track(p) {
|
|
268
|
+
this.pending++;
|
|
269
|
+
const done = () => {
|
|
270
|
+
this.pending--;
|
|
271
|
+
if (this.pending === 0) for (const resolve of this.idleResolvers.splice(0)) resolve();
|
|
272
|
+
};
|
|
273
|
+
p.then(done, done);
|
|
274
|
+
return p;
|
|
275
|
+
}
|
|
276
|
+
base(ref) {
|
|
277
|
+
let load = this.loads.get(ref);
|
|
278
|
+
if (load === void 0) {
|
|
279
|
+
load = this.track(this.provider.load(ref).then((bytes) => new Promise((resolve, reject) => {
|
|
280
|
+
this.loader.parse(bytes, "", (gltf) => resolve({
|
|
281
|
+
scene: gltf.scene,
|
|
282
|
+
clips: gltf.animations
|
|
283
|
+
}), (e) => reject(e instanceof Error ? e : new Error(String(e))));
|
|
284
|
+
})).then((loaded) => {
|
|
285
|
+
if (this.disposed) this.disposeLoaded(loaded);
|
|
286
|
+
else this.bases.add(loaded);
|
|
287
|
+
return loaded;
|
|
288
|
+
}));
|
|
289
|
+
this.loads.set(ref, load);
|
|
290
|
+
}
|
|
291
|
+
return load;
|
|
292
|
+
}
|
|
293
|
+
/** A fresh instance of the (sub-)scene for one entity. */
|
|
294
|
+
async instance(ref, node) {
|
|
295
|
+
if (this.disposed) throw new Error("asset cache is disposed");
|
|
296
|
+
const { scene, clips } = await this.base(ref);
|
|
297
|
+
if (this.disposed) throw new Error("asset cache is disposed");
|
|
298
|
+
const source = node !== void 0 ? scene.getObjectByName(node) ?? scene : scene;
|
|
299
|
+
return {
|
|
300
|
+
scene: SkeletonUtils.clone(source),
|
|
301
|
+
clips
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/** Resolves once every load kicked off so far has settled. */
|
|
305
|
+
whenIdle() {
|
|
306
|
+
if (this.pending === 0) return Promise.resolve();
|
|
307
|
+
return new Promise((resolve) => {
|
|
308
|
+
this.idleResolvers.push(resolve);
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
clear() {
|
|
312
|
+
for (const loaded of this.bases) this.disposeLoaded(loaded);
|
|
313
|
+
this.bases.clear();
|
|
314
|
+
this.loads.clear();
|
|
315
|
+
}
|
|
316
|
+
dispose() {
|
|
317
|
+
if (this.disposed) return;
|
|
318
|
+
this.disposed = true;
|
|
319
|
+
this.clear();
|
|
320
|
+
this.loader.dracoLoader?.dispose();
|
|
321
|
+
this.loader.ktx2Loader?.dispose();
|
|
322
|
+
}
|
|
323
|
+
disposeLoaded(loaded) {
|
|
324
|
+
loaded.scene.traverse((child) => {
|
|
325
|
+
const mesh = child;
|
|
326
|
+
if (!mesh.isMesh) return;
|
|
327
|
+
if (!this.disposedGeometries.has(mesh.geometry)) {
|
|
328
|
+
this.disposedGeometries.add(mesh.geometry);
|
|
329
|
+
mesh.geometry.dispose();
|
|
330
|
+
}
|
|
331
|
+
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
|
|
332
|
+
for (const material of materials) {
|
|
333
|
+
if (this.disposedMaterials.has(material)) continue;
|
|
334
|
+
this.disposedMaterials.add(material);
|
|
335
|
+
for (const value of Object.values(material)) if (value instanceof THREE.Texture) value.dispose();
|
|
336
|
+
material.dispose();
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
//#endregion
|
|
342
|
+
//#region src/interpolation.ts
|
|
343
|
+
const DEFAULT_BUFFER = 4;
|
|
344
|
+
const DEFAULT_DELAY_TICKS = 1.5;
|
|
345
|
+
/**
|
|
346
|
+
* How fast the clock offset follows a *later* arrival. Lateness is one-sided noise (a tick is
|
|
347
|
+
* never delivered early by the network, only late by a stall), so the offset drops to a new
|
|
348
|
+
* earliest arrival at once and drifts toward a persistently later one slowly: one 12 ms hitch
|
|
349
|
+
* moves the render clock by a quarter of a millisecond instead of re-anchoring on it.
|
|
350
|
+
*/
|
|
351
|
+
const CLOCK_DRIFT = .02;
|
|
352
|
+
/**
|
|
353
|
+
* Holds a small ring of recent per-tick transform snapshots and samples interpolated
|
|
354
|
+
* transforms ~delayTicks behind the latest tick. Never extrapolates: clamps to the latest
|
|
355
|
+
* known transform when ahead of the buffer.
|
|
356
|
+
*/
|
|
357
|
+
var InterpolationBuffer = class {
|
|
358
|
+
tickRate;
|
|
359
|
+
snaps = [];
|
|
360
|
+
baseline = /* @__PURE__ */ new Map();
|
|
361
|
+
current = /* @__PURE__ */ new Map();
|
|
362
|
+
active = /* @__PURE__ */ new Map();
|
|
363
|
+
visited = 0;
|
|
364
|
+
capacity;
|
|
365
|
+
delayTicks;
|
|
366
|
+
tickMs;
|
|
367
|
+
/** Smoothed local time (ms) that tick 0 would have arrived at — the render clock's anchor. */
|
|
368
|
+
clockOffsetMs;
|
|
369
|
+
/** The last tick handed out, so a frame sequence never steps backwards. */
|
|
370
|
+
lastRenderTick;
|
|
371
|
+
constructor(tickRate, opts) {
|
|
372
|
+
this.tickRate = tickRate;
|
|
373
|
+
this.tickMs = 1e3 / tickRate;
|
|
374
|
+
this.capacity = opts?.capacity ?? DEFAULT_BUFFER;
|
|
375
|
+
this.delayTicks = opts?.delayTicks ?? DEFAULT_DELAY_TICKS;
|
|
376
|
+
}
|
|
377
|
+
/** Record the transforms present at a kernel tick. recvMs is the local receive time. */
|
|
378
|
+
push(tick, transforms, recvMs) {
|
|
379
|
+
const changes = /* @__PURE__ */ new Map();
|
|
380
|
+
for (const [id, transform] of transforms) if (!sameTransform(this.current.get(id), transform)) changes.set(id, transform);
|
|
381
|
+
for (const id of this.current.keys()) if (!transforms.has(id)) changes.set(id, void 0);
|
|
382
|
+
this.pushDelta(tick, changes, recvMs);
|
|
383
|
+
}
|
|
384
|
+
/** Record a contiguous sparse update. Unmentioned entities keep their previous transform. */
|
|
385
|
+
pushDelta(tick, changes, recvMs) {
|
|
386
|
+
if (this.latestTick !== void 0 && tick <= this.latestTick) throw new RangeError("Interpolation ticks must increase; clear the buffer on resync");
|
|
387
|
+
const owned = /* @__PURE__ */ new Map();
|
|
388
|
+
for (const [id, transform] of changes) {
|
|
389
|
+
if (sameTransform(this.current.get(id), transform)) continue;
|
|
390
|
+
const copy = transform === void 0 ? void 0 : structuredClone(transform);
|
|
391
|
+
owned.set(id, copy);
|
|
392
|
+
if (copy === void 0) {
|
|
393
|
+
this.current.delete(id);
|
|
394
|
+
this.active.delete(id);
|
|
395
|
+
} else {
|
|
396
|
+
this.current.set(id, copy);
|
|
397
|
+
this.active.set(id, tick);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
this.trackClock(tick, recvMs);
|
|
401
|
+
this.snaps.push({
|
|
402
|
+
tick,
|
|
403
|
+
recvMs,
|
|
404
|
+
transforms: owned
|
|
405
|
+
});
|
|
406
|
+
while (this.snaps.length > this.capacity) {
|
|
407
|
+
const retired = this.snaps.shift();
|
|
408
|
+
for (const [id, transform] of retired.transforms) if (transform === void 0) this.baseline.delete(id);
|
|
409
|
+
else this.baseline.set(id, transform);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
at(tick, id) {
|
|
413
|
+
for (let i = this.snaps.length - 1; i >= 0; i--) {
|
|
414
|
+
const snapshot = this.snaps[i];
|
|
415
|
+
if (snapshot.tick <= tick && snapshot.transforms.has(id)) return snapshot.transforms.get(id);
|
|
416
|
+
}
|
|
417
|
+
return this.baseline.get(id);
|
|
418
|
+
}
|
|
419
|
+
/** Visit only changed/interpolating entities; send the final pose once before retiring it. */
|
|
420
|
+
sampleActive(nowMs, apply) {
|
|
421
|
+
this.visited = 0;
|
|
422
|
+
const tick = this.estimateRenderTick(nowMs);
|
|
423
|
+
if (tick === void 0) return;
|
|
424
|
+
for (const [id, changedTick] of this.active) {
|
|
425
|
+
this.visited++;
|
|
426
|
+
const transform = this.sampleAt(tick, id);
|
|
427
|
+
if (transform !== void 0) apply(id, transform);
|
|
428
|
+
if (tick >= changedTick) this.active.delete(id);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
/** Reapply a static pose after a render/light binding changes without a transform delta. */
|
|
432
|
+
activate(id) {
|
|
433
|
+
if (this.current.has(id)) this.active.set(id, this.latestTick ?? 0);
|
|
434
|
+
}
|
|
435
|
+
get lastSampleVisited() {
|
|
436
|
+
return this.visited;
|
|
437
|
+
}
|
|
438
|
+
get latestTick() {
|
|
439
|
+
return this.snaps.length === 0 ? void 0 : this.snaps[this.snaps.length - 1].tick;
|
|
440
|
+
}
|
|
441
|
+
/** Number of snapshots currently held (≤ capacity). */
|
|
442
|
+
get size() {
|
|
443
|
+
return this.snaps.length;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Fold one arrival into the smoothed clock offset. Anchoring on the newest arrival instead (the
|
|
447
|
+
* old `latest.tick + (now - latest.recvMs)`) makes every stall a visible rewind: a delta that
|
|
448
|
+
* lands 12 ms late moves the render tick ~0.3 ticks *backwards* and every moving entity reverses.
|
|
449
|
+
*/
|
|
450
|
+
trackClock(tick, recvMs) {
|
|
451
|
+
const sample = recvMs - tick * this.tickMs;
|
|
452
|
+
if (!Number.isFinite(sample)) return;
|
|
453
|
+
if (this.clockOffsetMs === void 0 || sample < this.clockOffsetMs) {
|
|
454
|
+
this.clockOffsetMs = sample;
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
this.clockOffsetMs += (sample - this.clockOffsetMs) * CLOCK_DRIFT;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Estimate the render tick for a wall-clock time from the smoothed clock, minus the delay.
|
|
461
|
+
* Never runs ahead of the newest tick held (sampling clamps there anyway) and never steps
|
|
462
|
+
* backwards between calls, so a late delta cannot reverse motion mid-flight.
|
|
463
|
+
*/
|
|
464
|
+
estimateRenderTick(nowMs) {
|
|
465
|
+
const latest = this.snaps[this.snaps.length - 1];
|
|
466
|
+
if (latest === void 0) return void 0;
|
|
467
|
+
const est = (nowMs - (this.clockOffsetMs ?? latest.recvMs - latest.tick * this.tickMs)) / this.tickMs - this.delayTicks;
|
|
468
|
+
const capped = Math.min(est, latest.tick);
|
|
469
|
+
const floor = this.lastRenderTick === void 0 ? capped : Math.max(capped, Math.min(this.lastRenderTick, latest.tick));
|
|
470
|
+
if (Number.isFinite(floor)) this.lastRenderTick = floor;
|
|
471
|
+
return floor;
|
|
472
|
+
}
|
|
473
|
+
/** Sample an entity's interpolated transform at an explicit render tick (the tested core). */
|
|
474
|
+
sampleAt(renderTick, id) {
|
|
475
|
+
if (this.snaps.length === 0) return void 0;
|
|
476
|
+
let a;
|
|
477
|
+
let b;
|
|
478
|
+
for (const s of this.snaps) {
|
|
479
|
+
if (s.tick <= renderTick) a = s;
|
|
480
|
+
if (s.tick >= renderTick && b === void 0) b = s;
|
|
481
|
+
}
|
|
482
|
+
if (a === void 0) {
|
|
483
|
+
const earliest = this.snaps[0];
|
|
484
|
+
return this.at(earliest.tick, id);
|
|
485
|
+
}
|
|
486
|
+
if (b === void 0 || a.tick === b.tick) return this.at(a.tick, id);
|
|
487
|
+
const ta = this.at(a.tick, id);
|
|
488
|
+
const tb = this.at(b.tick, id);
|
|
489
|
+
if (ta === void 0) return tb;
|
|
490
|
+
if (tb === void 0) return ta;
|
|
491
|
+
if (tb.teleport === true) return tb;
|
|
492
|
+
if (ta === tb) return ta;
|
|
493
|
+
const t = (renderTick - a.tick) / (b.tick - a.tick);
|
|
494
|
+
const scaleA = ta.scale ?? [
|
|
495
|
+
1,
|
|
496
|
+
1,
|
|
497
|
+
1
|
|
498
|
+
];
|
|
499
|
+
const scaleB = tb.scale ?? [
|
|
500
|
+
1,
|
|
501
|
+
1,
|
|
502
|
+
1
|
|
503
|
+
];
|
|
504
|
+
return {
|
|
505
|
+
pos: lerp3(ta.pos, tb.pos, t),
|
|
506
|
+
rot: nlerp4(ta.rot, tb.rot, t),
|
|
507
|
+
scale: lerp3(scaleA, scaleB, t)
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
/** Sample for a wall-clock time using the estimated render tick. */
|
|
511
|
+
sample(nowMs, id) {
|
|
512
|
+
const renderTick = this.estimateRenderTick(nowMs);
|
|
513
|
+
if (renderTick === void 0) return void 0;
|
|
514
|
+
return this.sampleAt(renderTick, id);
|
|
515
|
+
}
|
|
516
|
+
/** Ids present in the most recent snapshot. */
|
|
517
|
+
latestIds() {
|
|
518
|
+
return [...this.current.keys()];
|
|
519
|
+
}
|
|
520
|
+
clear() {
|
|
521
|
+
this.snaps = [];
|
|
522
|
+
this.baseline.clear();
|
|
523
|
+
this.current.clear();
|
|
524
|
+
this.active.clear();
|
|
525
|
+
this.clockOffsetMs = void 0;
|
|
526
|
+
this.lastRenderTick = void 0;
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
function sameTransform(a, b) {
|
|
530
|
+
if (a === b) return true;
|
|
531
|
+
if (a === void 0 || b === void 0 || a.teleport !== b.teleport) return false;
|
|
532
|
+
return a.pos.every((v, i) => v === b.pos[i]) && a.rot.every((v, i) => v === b.rot[i]) && [
|
|
533
|
+
0,
|
|
534
|
+
1,
|
|
535
|
+
2
|
|
536
|
+
].every((i) => (a.scale?.[i] ?? 1) === (b.scale?.[i] ?? 1));
|
|
537
|
+
}
|
|
538
|
+
//#endregion
|
|
539
|
+
//#region src/sync.ts
|
|
540
|
+
function applyDeltaToMirror(mirror, delta) {
|
|
541
|
+
for (const [id, comps] of Object.entries(delta.spawned)) mirror.set(id, structuredClone(comps));
|
|
542
|
+
for (const [id, comps] of Object.entries(delta.changed)) {
|
|
543
|
+
const bucket = mirror.get(id) ?? {};
|
|
544
|
+
for (const [name, data] of Object.entries(comps)) if (data !== void 0) bucket[name] = data;
|
|
545
|
+
mirror.set(id, bucket);
|
|
546
|
+
}
|
|
547
|
+
for (const [id, names] of Object.entries(delta.removedComponents)) {
|
|
548
|
+
const bucket = mirror.get(id);
|
|
549
|
+
if (bucket !== void 0) for (const n of names) delete bucket[n];
|
|
550
|
+
}
|
|
551
|
+
for (const id of delta.destroyed) mirror.delete(id);
|
|
552
|
+
}
|
|
553
|
+
function readTransform(components) {
|
|
554
|
+
const t = components.transform;
|
|
555
|
+
if (t?.pos === void 0) return void 0;
|
|
556
|
+
return {
|
|
557
|
+
pos: t.pos,
|
|
558
|
+
rot: t.rot ?? [
|
|
559
|
+
0,
|
|
560
|
+
0,
|
|
561
|
+
0,
|
|
562
|
+
1
|
|
563
|
+
],
|
|
564
|
+
...t.scale ? { scale: t.scale } : {},
|
|
565
|
+
...t.teleport === true ? { teleport: true } : {}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function readRenderable(components) {
|
|
569
|
+
const r = components.renderable;
|
|
570
|
+
if (r?.kind === void 0 || r.ref === void 0) return void 0;
|
|
571
|
+
return r;
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Maintains a client-side mirror of kernel entities and reconciles renderable bindings against
|
|
575
|
+
* a SceneBackend (create / updateRenderable / destroy). Pure aside from the backend calls, so
|
|
576
|
+
* it is unit-testable with a mock backend.
|
|
577
|
+
*
|
|
578
|
+
* Reconciliation is incremental: a delta marks the ids it touched dirty and `reconcile` visits
|
|
579
|
+
* only those (a keyframe forces a full pass), so a 1000-entity scene with one moving entity
|
|
580
|
+
* serializes one renderable per message, not a thousand.
|
|
581
|
+
*/
|
|
582
|
+
var SceneMirror = class {
|
|
583
|
+
mirror = /* @__PURE__ */ new Map();
|
|
584
|
+
bound = /* @__PURE__ */ new Map();
|
|
585
|
+
boundLights = /* @__PURE__ */ new Map();
|
|
586
|
+
boundEnvironment;
|
|
587
|
+
environmentOwner;
|
|
588
|
+
boundWeather;
|
|
589
|
+
weatherOwner;
|
|
590
|
+
currentTick;
|
|
591
|
+
/** Ids touched since the last reconcile (spawned/changed/removedComponents/destroyed). */
|
|
592
|
+
dirty = /* @__PURE__ */ new Set();
|
|
593
|
+
/** Set by a keyframe: the next reconcile must visit everything. */
|
|
594
|
+
full = false;
|
|
595
|
+
visited = 0;
|
|
596
|
+
applyKeyframe(keyframe) {
|
|
597
|
+
this.mirror.clear();
|
|
598
|
+
for (const [id, comps] of Object.entries(keyframe.entities)) this.mirror.set(id, structuredClone(comps));
|
|
599
|
+
this.currentTick = keyframe.tick;
|
|
600
|
+
this.full = true;
|
|
601
|
+
this.dirty.clear();
|
|
602
|
+
}
|
|
603
|
+
/** Apply only a contiguous delta; false means the caller must request a fresh keyframe. */
|
|
604
|
+
applyDelta(delta) {
|
|
605
|
+
if (this.currentTick === void 0 || delta.baseTick !== this.currentTick) return false;
|
|
606
|
+
applyDeltaToMirror(this.mirror, delta);
|
|
607
|
+
for (const id of Object.keys(delta.spawned)) this.dirty.add(id);
|
|
608
|
+
for (const id of Object.keys(delta.changed)) this.dirty.add(id);
|
|
609
|
+
for (const id of Object.keys(delta.removedComponents)) this.dirty.add(id);
|
|
610
|
+
for (const id of delta.destroyed) this.dirty.add(id);
|
|
611
|
+
this.currentTick = delta.tick;
|
|
612
|
+
return true;
|
|
613
|
+
}
|
|
614
|
+
/** Extract the transforms present in the mirror (for the interpolation buffer). */
|
|
615
|
+
transforms() {
|
|
616
|
+
const out = /* @__PURE__ */ new Map();
|
|
617
|
+
for (const [id, comps] of this.mirror) {
|
|
618
|
+
const t = readTransform(comps);
|
|
619
|
+
if (t !== void 0) out.set(id, t);
|
|
620
|
+
}
|
|
621
|
+
return out;
|
|
622
|
+
}
|
|
623
|
+
/** Extract only transform changes (including removals), before reconciliation clears dirty ids. */
|
|
624
|
+
transformChanges(delta) {
|
|
625
|
+
const ids = new Set(Object.keys(delta.spawned));
|
|
626
|
+
for (const [id, components] of Object.entries(delta.changed)) if (components.transform !== void 0) ids.add(id);
|
|
627
|
+
for (const [id, names] of Object.entries(delta.removedComponents)) if (names.includes("transform")) ids.add(id);
|
|
628
|
+
for (const id of delta.destroyed) ids.add(id);
|
|
629
|
+
return new Map([...ids].map((id) => [id, readTransform(this.mirror.get(id) ?? {})]));
|
|
630
|
+
}
|
|
631
|
+
/** How many entity ids the last `reconcile` examined (all of them after a keyframe). */
|
|
632
|
+
get lastReconcileVisited() {
|
|
633
|
+
return this.visited;
|
|
634
|
+
}
|
|
635
|
+
/** Create/update/destroy backend objects so they match the mirror's renderables. */
|
|
636
|
+
reconcile(backend) {
|
|
637
|
+
const full = this.full;
|
|
638
|
+
if (full) {
|
|
639
|
+
this.visited = this.mirror.size;
|
|
640
|
+
for (const id of this.mirror.keys()) this.reconcileRenderable(backend, id);
|
|
641
|
+
for (const id of [...this.bound.keys()]) if (!this.mirror.has(id)) this.reconcileRenderable(backend, id);
|
|
642
|
+
} else {
|
|
643
|
+
this.visited = this.dirty.size;
|
|
644
|
+
for (const id of this.dirty) this.reconcileRenderable(backend, id);
|
|
645
|
+
}
|
|
646
|
+
this.reconcileLights(backend, full);
|
|
647
|
+
this.reconcileEnvironment(backend, full);
|
|
648
|
+
this.reconcileWeather(backend, full);
|
|
649
|
+
this.dirty.clear();
|
|
650
|
+
this.full = false;
|
|
651
|
+
}
|
|
652
|
+
/** Bring one id's renderable binding in line with the mirror (absent entity -> destroy). */
|
|
653
|
+
reconcileRenderable(backend, id) {
|
|
654
|
+
const comps = this.mirror.get(id);
|
|
655
|
+
const renderable = comps === void 0 ? void 0 : readRenderable(comps);
|
|
656
|
+
if (renderable === void 0) {
|
|
657
|
+
if (this.bound.has(id)) {
|
|
658
|
+
backend.destroy(id);
|
|
659
|
+
this.bound.delete(id);
|
|
660
|
+
}
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
const key = JSON.stringify(renderable);
|
|
664
|
+
const prev = this.bound.get(id);
|
|
665
|
+
if (prev === void 0) {
|
|
666
|
+
backend.create(id, renderable);
|
|
667
|
+
this.bound.set(id, key);
|
|
668
|
+
} else if (prev !== key) {
|
|
669
|
+
backend.updateRenderable(id, renderable);
|
|
670
|
+
this.bound.set(id, key);
|
|
671
|
+
}
|
|
672
|
+
if (backend.setModelSignals) {
|
|
673
|
+
const spec = comps?.["model.signals"];
|
|
674
|
+
backend.setModelSignals(id, spec, readModelSignals(spec?.sources, (name) => comps?.[name]));
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
reconcileLights(backend, full) {
|
|
678
|
+
if (backend.createLight === void 0) return;
|
|
679
|
+
if (full) {
|
|
680
|
+
for (const id of this.mirror.keys()) this.reconcileLight(backend, id);
|
|
681
|
+
for (const id of [...this.boundLights.keys()]) if (!this.mirror.has(id)) this.reconcileLight(backend, id);
|
|
682
|
+
} else for (const id of this.dirty) this.reconcileLight(backend, id);
|
|
683
|
+
}
|
|
684
|
+
reconcileLight(backend, id) {
|
|
685
|
+
const light = this.mirror.get(id)?.light;
|
|
686
|
+
if (light?.type === void 0) {
|
|
687
|
+
if (this.boundLights.has(id)) {
|
|
688
|
+
backend.destroyLight?.(id);
|
|
689
|
+
this.boundLights.delete(id);
|
|
690
|
+
}
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const key = JSON.stringify(light);
|
|
694
|
+
const prev = this.boundLights.get(id);
|
|
695
|
+
if (prev === void 0) {
|
|
696
|
+
backend.createLight?.(id, light);
|
|
697
|
+
this.boundLights.set(id, key);
|
|
698
|
+
} else if (prev !== key) {
|
|
699
|
+
backend.updateLight?.(id, light);
|
|
700
|
+
this.boundLights.set(id, key);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
reconcileEnvironment(backend, full) {
|
|
704
|
+
if (backend.setEnvironment === void 0) return;
|
|
705
|
+
if (!full && !this.environmentTouched()) return;
|
|
706
|
+
let env;
|
|
707
|
+
let owner;
|
|
708
|
+
for (const [id, comps] of this.mirror) if (comps.environment !== void 0) {
|
|
709
|
+
env = comps.environment;
|
|
710
|
+
owner = id;
|
|
711
|
+
break;
|
|
712
|
+
}
|
|
713
|
+
this.environmentOwner = owner;
|
|
714
|
+
const key = env !== void 0 ? JSON.stringify(env) : void 0;
|
|
715
|
+
if (key !== this.boundEnvironment) {
|
|
716
|
+
backend.setEnvironment(env);
|
|
717
|
+
this.boundEnvironment = key;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
reconcileWeather(backend, full) {
|
|
721
|
+
if (!backend.setWeather) return;
|
|
722
|
+
if (!full && !(this.weatherOwner !== void 0 && this.dirty.has(this.weatherOwner)) && ![...this.dirty].some((id) => this.mirror.get(id)?.weather !== void 0)) return;
|
|
723
|
+
let weather;
|
|
724
|
+
this.weatherOwner = void 0;
|
|
725
|
+
for (const [id, components] of this.mirror) {
|
|
726
|
+
if (components.weather === void 0) continue;
|
|
727
|
+
weather = components.weather;
|
|
728
|
+
this.weatherOwner = id;
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
const key = weather === void 0 ? void 0 : JSON.stringify(weather);
|
|
732
|
+
if (key !== this.boundWeather) {
|
|
733
|
+
backend.setWeather(weather);
|
|
734
|
+
this.boundWeather = key;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
/** Did this batch of dirty ids touch the current owner, or introduce another `environment`? */
|
|
738
|
+
environmentTouched() {
|
|
739
|
+
if (this.environmentOwner !== void 0 && this.dirty.has(this.environmentOwner)) return true;
|
|
740
|
+
for (const id of this.dirty) if (this.mirror.get(id)?.environment !== void 0) return true;
|
|
741
|
+
return false;
|
|
742
|
+
}
|
|
743
|
+
boundIds() {
|
|
744
|
+
return [...this.bound.keys()];
|
|
745
|
+
}
|
|
746
|
+
get tick() {
|
|
747
|
+
return this.currentTick;
|
|
748
|
+
}
|
|
749
|
+
has(id) {
|
|
750
|
+
return this.mirror.has(id);
|
|
751
|
+
}
|
|
752
|
+
/** A detached copy of one component of a mirrored entity (undefined when absent). */
|
|
753
|
+
get(id, component) {
|
|
754
|
+
const data = this.mirror.get(id)?.[component];
|
|
755
|
+
return data === void 0 ? void 0 : structuredClone(data);
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* The stored component object (no copy) for renderers that sample every frame: treat it as
|
|
759
|
+
* frozen. Its identity changes exactly when a delta or keyframe replaced it.
|
|
760
|
+
*/
|
|
761
|
+
peek(id, component) {
|
|
762
|
+
return this.mirror.get(id)?.[component];
|
|
763
|
+
}
|
|
764
|
+
/** Every mirrored entity id, in creation order. */
|
|
765
|
+
entities() {
|
|
766
|
+
return [...this.mirror.keys()];
|
|
767
|
+
}
|
|
768
|
+
/** The component names an entity currently carries. */
|
|
769
|
+
components(id) {
|
|
770
|
+
const bucket = this.mirror.get(id);
|
|
771
|
+
return bucket === void 0 ? [] : Object.keys(bucket);
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
//#endregion
|
|
775
|
+
//#region src/client-core.ts
|
|
776
|
+
/** The envelope `command()` fills: local source, kernel re-stamps tick 0 to next tick. */
|
|
777
|
+
function localCommand(seq, type, payload) {
|
|
778
|
+
return {
|
|
779
|
+
kind: "command",
|
|
780
|
+
seq,
|
|
781
|
+
source: "local",
|
|
782
|
+
tick: 0,
|
|
783
|
+
type,
|
|
784
|
+
payload
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
function createClientCore(opts) {
|
|
788
|
+
const { link, backend } = opts;
|
|
789
|
+
const mirror = new SceneMirror();
|
|
790
|
+
let buffer;
|
|
791
|
+
let bufferTickRate;
|
|
792
|
+
let awaitingKeyframe = false;
|
|
793
|
+
const delayTicks = opts.interpolationDelayTicks;
|
|
794
|
+
const nowMs = opts.now ?? (() => typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
795
|
+
const eventHandlers = /* @__PURE__ */ new Map();
|
|
796
|
+
const diagHandlers = /* @__PURE__ */ new Set();
|
|
797
|
+
const errorHandlers = /* @__PURE__ */ new Set();
|
|
798
|
+
function dispatchDiag(diag) {
|
|
799
|
+
for (const handler of [...diagHandlers]) handler(diag);
|
|
800
|
+
}
|
|
801
|
+
function reportError(error) {
|
|
802
|
+
for (const handler of [...errorHandlers]) handler(error);
|
|
803
|
+
dispatchDiag({
|
|
804
|
+
type: "diag",
|
|
805
|
+
code: error.source === "link" ? "link-error" : "frame-error",
|
|
806
|
+
detail: error.message
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
function ensureBuffer(tickRate) {
|
|
810
|
+
if (buffer === void 0 || bufferTickRate !== tickRate) {
|
|
811
|
+
buffer = new InterpolationBuffer(tickRate, delayTicks !== void 0 ? { delayTicks } : void 0);
|
|
812
|
+
bufferTickRate = tickRate;
|
|
813
|
+
}
|
|
814
|
+
return buffer;
|
|
815
|
+
}
|
|
816
|
+
function dispatchEvents(events, tick) {
|
|
817
|
+
for (const event of events) {
|
|
818
|
+
for (const handler of [...eventHandlers.get(event.type) ?? []]) handler(event, tick);
|
|
819
|
+
for (const handler of [...eventHandlers.get("*") ?? []]) handler(event, tick);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
function onMessage(msg) {
|
|
823
|
+
switch (msg.type) {
|
|
824
|
+
case "ready":
|
|
825
|
+
ensureBuffer(msg.tickRate);
|
|
826
|
+
break;
|
|
827
|
+
case "keyframe": {
|
|
828
|
+
const buf = ensureBuffer(msg.keyframe.tickRate);
|
|
829
|
+
if (!(buf.latestTick !== void 0 && msg.keyframe.tick === buf.latestTick + 1)) buf.clear();
|
|
830
|
+
awaitingKeyframe = false;
|
|
831
|
+
mirror.applyKeyframe(msg.keyframe);
|
|
832
|
+
mirror.reconcile(backend);
|
|
833
|
+
buf.push(msg.keyframe.tick, mirror.transforms(), nowMs());
|
|
834
|
+
for (const id of mirror.entities()) buf.activate(id);
|
|
835
|
+
dispatchEvents(msg.events ?? [], msg.keyframe.tick);
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
case "delta":
|
|
839
|
+
if (buffer === void 0) break;
|
|
840
|
+
if (!mirror.applyDelta(msg.delta)) {
|
|
841
|
+
buffer.clear();
|
|
842
|
+
if (!awaitingKeyframe) {
|
|
843
|
+
awaitingKeyframe = true;
|
|
844
|
+
link.postMessage({
|
|
845
|
+
type: "control",
|
|
846
|
+
control: { action: "request-keyframe" }
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
break;
|
|
850
|
+
}
|
|
851
|
+
buffer.pushDelta(msg.delta.tick, mirror.transformChanges(msg.delta), nowMs());
|
|
852
|
+
mirror.reconcile(backend);
|
|
853
|
+
for (const [id, components] of Object.entries(msg.delta.changed)) if (components.renderable !== void 0 || components.light !== void 0) buffer.activate(id);
|
|
854
|
+
dispatchEvents(msg.delta.events ?? [], msg.delta.tick);
|
|
855
|
+
break;
|
|
856
|
+
case "diag":
|
|
857
|
+
dispatchDiag(msg);
|
|
858
|
+
break;
|
|
859
|
+
default: break;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
const handler = (ev) => onMessage(ev.data);
|
|
863
|
+
const listeningWithEventTarget = typeof link.addEventListener === "function";
|
|
864
|
+
const linkEvents = link;
|
|
865
|
+
const onLinkError = (ev) => reportError({
|
|
866
|
+
source: "link",
|
|
867
|
+
message: describeLinkFailure("error", ev),
|
|
868
|
+
cause: ev
|
|
869
|
+
});
|
|
870
|
+
const onLinkMessageError = (ev) => reportError({
|
|
871
|
+
source: "link",
|
|
872
|
+
message: describeLinkFailure("messageerror", ev),
|
|
873
|
+
cause: ev
|
|
874
|
+
});
|
|
875
|
+
if (listeningWithEventTarget) {
|
|
876
|
+
link.addEventListener?.("message", handler);
|
|
877
|
+
linkEvents.addEventListener("error", onLinkError);
|
|
878
|
+
linkEvents.addEventListener("messageerror", onLinkMessageError);
|
|
879
|
+
} else link.onmessage = handler;
|
|
880
|
+
const sendCommand = (command) => link.postMessage({
|
|
881
|
+
type: "command",
|
|
882
|
+
command
|
|
883
|
+
});
|
|
884
|
+
let seq = 0;
|
|
885
|
+
return {
|
|
886
|
+
mirror,
|
|
887
|
+
get buffer() {
|
|
888
|
+
return buffer;
|
|
889
|
+
},
|
|
890
|
+
get tick() {
|
|
891
|
+
return mirror.tick;
|
|
892
|
+
},
|
|
893
|
+
onEvent(type, cb) {
|
|
894
|
+
let set = eventHandlers.get(type);
|
|
895
|
+
if (set === void 0) {
|
|
896
|
+
set = /* @__PURE__ */ new Set();
|
|
897
|
+
eventHandlers.set(type, set);
|
|
898
|
+
}
|
|
899
|
+
set.add(cb);
|
|
900
|
+
return () => {
|
|
901
|
+
set.delete(cb);
|
|
902
|
+
};
|
|
903
|
+
},
|
|
904
|
+
onDiag(cb) {
|
|
905
|
+
diagHandlers.add(cb);
|
|
906
|
+
return () => {
|
|
907
|
+
diagHandlers.delete(cb);
|
|
908
|
+
};
|
|
909
|
+
},
|
|
910
|
+
onError(cb) {
|
|
911
|
+
errorHandlers.add(cb);
|
|
912
|
+
return () => {
|
|
913
|
+
errorHandlers.delete(cb);
|
|
914
|
+
};
|
|
915
|
+
},
|
|
916
|
+
reportError,
|
|
917
|
+
get: (id, component) => mirror.get(id, component),
|
|
918
|
+
entities: () => mirror.entities(),
|
|
919
|
+
sampleTransforms(t, apply) {
|
|
920
|
+
if (buffer === void 0) return;
|
|
921
|
+
buffer.sampleActive(t, apply);
|
|
922
|
+
},
|
|
923
|
+
sendCommand,
|
|
924
|
+
command: (type, payload = {}) => sendCommand(localCommand(seq++, type, payload)),
|
|
925
|
+
control: (action) => link.postMessage({
|
|
926
|
+
type: "control",
|
|
927
|
+
control: action
|
|
928
|
+
}),
|
|
929
|
+
dispose: () => {
|
|
930
|
+
if (listeningWithEventTarget) {
|
|
931
|
+
link.removeEventListener?.("message", handler);
|
|
932
|
+
linkEvents.removeEventListener("error", onLinkError);
|
|
933
|
+
linkEvents.removeEventListener("messageerror", onLinkMessageError);
|
|
934
|
+
} else if (link.onmessage === handler) link.onmessage = null;
|
|
935
|
+
buffer?.clear();
|
|
936
|
+
eventHandlers.clear();
|
|
937
|
+
diagHandlers.clear();
|
|
938
|
+
errorHandlers.clear();
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
/** Readable summary of a link failure event; a bare `error` event carries no detail at all. */
|
|
943
|
+
function describeLinkFailure(kind, ev) {
|
|
944
|
+
if (kind === "messageerror") return "kernel link could not deserialize a message";
|
|
945
|
+
const detail = ev;
|
|
946
|
+
if (detail !== null && typeof detail === "object" && typeof detail.message === "string") {
|
|
947
|
+
const where = typeof detail.filename === "string" && detail.filename !== "" ? ` (${detail.filename}${typeof detail.lineno === "number" ? `:${detail.lineno}` : ""})` : "";
|
|
948
|
+
return `kernel link error: ${detail.message}${where}`;
|
|
949
|
+
}
|
|
950
|
+
return "kernel link error (no detail; the worker may have failed to load)";
|
|
951
|
+
}
|
|
952
|
+
//#endregion
|
|
953
|
+
//#region src/input.ts
|
|
954
|
+
/** Resolve a key or Mouse<button> code to its bound action. */
|
|
955
|
+
function resolveAction(bindings, code) {
|
|
956
|
+
return Object.hasOwn(bindings, code) ? bindings[code] : void 0;
|
|
957
|
+
}
|
|
958
|
+
function copyProfile(profile) {
|
|
959
|
+
const result = inputProfileSchema.parse(profile);
|
|
960
|
+
const issues = inputProfileIssues(result);
|
|
961
|
+
if (issues.length) throw new Error(issues[0]?.message);
|
|
962
|
+
return result;
|
|
963
|
+
}
|
|
964
|
+
function matches(device, pad) {
|
|
965
|
+
return (device?.id === void 0 || device.id === pad.id) && (device?.index === void 0 || device.index === pad.index);
|
|
966
|
+
}
|
|
967
|
+
/** Calibrate and shape a raw axis. Invalid/non-finite hardware readings are neutral. */
|
|
968
|
+
function normalizeInputAxis(raw, binding) {
|
|
969
|
+
if (!Number.isFinite(raw)) return 0;
|
|
970
|
+
const min = binding.min ?? -1;
|
|
971
|
+
const max = binding.max ?? 1;
|
|
972
|
+
const center = binding.center ?? 0;
|
|
973
|
+
let value = binding.mode === "unit" ? (raw - min) / (max - min) : raw >= center ? (raw - center) / (max - center) : (raw - center) / (center - min);
|
|
974
|
+
value = Math.max(binding.mode === "unit" ? 0 : -1, Math.min(1, value));
|
|
975
|
+
if (binding.invert) value = binding.mode === "unit" ? 1 - value : -value;
|
|
976
|
+
if (binding.mode === "positive") value = Math.max(0, value);
|
|
977
|
+
if (binding.mode === "negative") value = Math.max(0, -value);
|
|
978
|
+
const zone = binding.deadZone ?? (binding.mode === "unit" ? 0 : .12);
|
|
979
|
+
const magnitude = Math.max(0, (Math.abs(value) - zone) / (1 - zone));
|
|
980
|
+
return Math.sign(value) * magnitude ** (binding.curve ?? 1);
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Keyboard/mouse + browser controllers mapped to numeric named actions. Call update() each
|
|
984
|
+
* frame (applyInputRules does this on its poller). Profiles are complete replacements.
|
|
985
|
+
*/
|
|
986
|
+
var InputMap = class {
|
|
987
|
+
base;
|
|
988
|
+
profiles = /* @__PURE__ */ new Map();
|
|
989
|
+
current;
|
|
990
|
+
keys = /* @__PURE__ */ new Set();
|
|
991
|
+
blockedKeys = /* @__PURE__ */ new Set();
|
|
992
|
+
blockedButtons = /* @__PURE__ */ new Set();
|
|
993
|
+
baselineButtons = false;
|
|
994
|
+
values = /* @__PURE__ */ new Map();
|
|
995
|
+
padValues = /* @__PURE__ */ new Map();
|
|
996
|
+
pads = [];
|
|
997
|
+
enabled = true;
|
|
998
|
+
disposed = false;
|
|
999
|
+
focused = true;
|
|
1000
|
+
suspensions = 0;
|
|
1001
|
+
revision = 0;
|
|
1002
|
+
pressHandlers = /* @__PURE__ */ new Map();
|
|
1003
|
+
releaseHandlers = /* @__PURE__ */ new Map();
|
|
1004
|
+
changeHandlers = /* @__PURE__ */ new Set();
|
|
1005
|
+
resetHandlers = /* @__PURE__ */ new Set();
|
|
1006
|
+
profileHandlers = /* @__PURE__ */ new Set();
|
|
1007
|
+
target;
|
|
1008
|
+
provider;
|
|
1009
|
+
listeners = [];
|
|
1010
|
+
status = "unavailable";
|
|
1011
|
+
constructor(opts) {
|
|
1012
|
+
this.base = copyProfile({
|
|
1013
|
+
bindings: opts.bindings,
|
|
1014
|
+
axes: opts.axes,
|
|
1015
|
+
buttons: opts.buttons
|
|
1016
|
+
});
|
|
1017
|
+
for (const [name, profile] of Object.entries(opts.profiles ?? {})) this.profiles.set(name, copyProfile(profile));
|
|
1018
|
+
if (opts.profile !== void 0 && !this.profiles.has(opts.profile)) throw new Error(`Unknown input profile "${opts.profile}".`);
|
|
1019
|
+
this.current = opts.profile;
|
|
1020
|
+
this.target = opts.target;
|
|
1021
|
+
this.provider = opts.getGamepads ?? (() => typeof navigator !== "undefined" && typeof navigator.getGamepads === "function" ? navigator.getGamepads() : []);
|
|
1022
|
+
if (opts.getGamepads || typeof navigator !== "undefined" && typeof navigator.getGamepads === "function") this.status = "available";
|
|
1023
|
+
if (this.target) this.attach(this.target);
|
|
1024
|
+
}
|
|
1025
|
+
get accepting() {
|
|
1026
|
+
return this.enabled && this.focused && this.suspensions === 0;
|
|
1027
|
+
}
|
|
1028
|
+
get profile() {
|
|
1029
|
+
return this.current === void 0 ? this.base : this.profiles.get(this.current);
|
|
1030
|
+
}
|
|
1031
|
+
get activeProfile() {
|
|
1032
|
+
return this.current;
|
|
1033
|
+
}
|
|
1034
|
+
get gamepadStatus() {
|
|
1035
|
+
return this.status;
|
|
1036
|
+
}
|
|
1037
|
+
profileNames() {
|
|
1038
|
+
return [...this.profiles.keys()];
|
|
1039
|
+
}
|
|
1040
|
+
/** Detached, serializable copy for custom editors and host-managed persistence. */
|
|
1041
|
+
getProfile(...selection) {
|
|
1042
|
+
const name = selection.length === 0 ? this.current : selection[0];
|
|
1043
|
+
const profile = name === void 0 ? this.base : this.profiles.get(name);
|
|
1044
|
+
if (!profile) throw new Error(`Unknown input profile "${name}".`);
|
|
1045
|
+
return copyProfile(profile);
|
|
1046
|
+
}
|
|
1047
|
+
/** Atomically validate and replace bindings; no held button becomes a new action. */
|
|
1048
|
+
defineProfile(name, profile) {
|
|
1049
|
+
const next = copyProfile(profile);
|
|
1050
|
+
if (name === "") throw new Error("Profile names must not be empty.");
|
|
1051
|
+
if (name === void 0) this.base = next;
|
|
1052
|
+
else this.profiles.set(name, next);
|
|
1053
|
+
if (name === this.current) this.reset();
|
|
1054
|
+
for (const fn of this.profileHandlers) fn();
|
|
1055
|
+
}
|
|
1056
|
+
/** Undefined selects the root bindings. Held keys/buttons must be released before reuse. */
|
|
1057
|
+
setProfile(name) {
|
|
1058
|
+
if (name !== void 0 && !this.profiles.has(name)) throw new Error(`Unknown input profile "${name}".`);
|
|
1059
|
+
if (name === this.current) return;
|
|
1060
|
+
this.current = name;
|
|
1061
|
+
this.reset();
|
|
1062
|
+
for (const fn of this.profileHandlers) fn();
|
|
1063
|
+
}
|
|
1064
|
+
/** Snapshot of all detected devices and raw values, suitable for an axis/button inspector. */
|
|
1065
|
+
devices() {
|
|
1066
|
+
return this.pads.map((pad) => ({
|
|
1067
|
+
...pad,
|
|
1068
|
+
axes: [...pad.axes],
|
|
1069
|
+
buttons: pad.buttons.map((button) => ({ ...button }))
|
|
1070
|
+
}));
|
|
1071
|
+
}
|
|
1072
|
+
/** Poll fresh browser objects; unplugging or losing permission releases affected controls. */
|
|
1073
|
+
update() {
|
|
1074
|
+
if (this.disposed) return;
|
|
1075
|
+
try {
|
|
1076
|
+
this.pads = this.provider().filter((pad) => pad?.connected === true).map((pad) => ({
|
|
1077
|
+
id: pad.id,
|
|
1078
|
+
index: pad.index,
|
|
1079
|
+
connected: pad.connected,
|
|
1080
|
+
mapping: pad.mapping,
|
|
1081
|
+
axes: Array.from(pad.axes),
|
|
1082
|
+
buttons: Array.from(pad.buttons, (button) => ({
|
|
1083
|
+
pressed: button.pressed,
|
|
1084
|
+
value: button.value
|
|
1085
|
+
}))
|
|
1086
|
+
}));
|
|
1087
|
+
if (this.status === "blocked") this.status = "available";
|
|
1088
|
+
} catch {
|
|
1089
|
+
this.pads = [];
|
|
1090
|
+
this.status = "blocked";
|
|
1091
|
+
}
|
|
1092
|
+
const down = /* @__PURE__ */ new Set();
|
|
1093
|
+
for (const pad of this.pads) pad.buttons.forEach((button, index) => {
|
|
1094
|
+
if (button.pressed || button.value > 0) down.add(JSON.stringify([
|
|
1095
|
+
pad.id,
|
|
1096
|
+
pad.index,
|
|
1097
|
+
index
|
|
1098
|
+
]));
|
|
1099
|
+
});
|
|
1100
|
+
if (this.baselineButtons || !this.accepting) for (const key of down) this.blockedButtons.add(key);
|
|
1101
|
+
for (const key of this.blockedButtons) if (!down.has(key)) this.blockedButtons.delete(key);
|
|
1102
|
+
this.baselineButtons = false;
|
|
1103
|
+
this.padValues.clear();
|
|
1104
|
+
if (this.accepting) for (const pad of this.pads) {
|
|
1105
|
+
for (const binding of this.profile.axes ?? []) {
|
|
1106
|
+
const raw = pad.axes[binding.axis];
|
|
1107
|
+
if (matches(binding.device, pad) && raw !== void 0) this.contribute(this.padValues, binding.action, normalizeInputAxis(raw, binding));
|
|
1108
|
+
}
|
|
1109
|
+
for (const binding of this.profile.buttons ?? []) {
|
|
1110
|
+
const button = pad.buttons[binding.button];
|
|
1111
|
+
const key = JSON.stringify([
|
|
1112
|
+
pad.id,
|
|
1113
|
+
pad.index,
|
|
1114
|
+
binding.button
|
|
1115
|
+
]);
|
|
1116
|
+
if (matches(binding.device, pad) && button && !this.blockedButtons.has(key) && (button.value >= (binding.threshold ?? .5) || binding.threshold === void 0 && button.pressed)) this.contribute(this.padValues, binding.action, 1);
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
this.recompute();
|
|
1120
|
+
}
|
|
1121
|
+
/** Suspend while editing a form/menu; device discovery continues during update(). */
|
|
1122
|
+
setEnabled(enabled) {
|
|
1123
|
+
if (this.enabled === enabled) return;
|
|
1124
|
+
this.enabled = enabled;
|
|
1125
|
+
this.reset();
|
|
1126
|
+
}
|
|
1127
|
+
/** Temporarily suppress gameplay while a remapping UI is open; returned release is idempotent. */
|
|
1128
|
+
suspend() {
|
|
1129
|
+
this.suspensions++;
|
|
1130
|
+
this.reset();
|
|
1131
|
+
let released = false;
|
|
1132
|
+
return () => {
|
|
1133
|
+
if (released) return;
|
|
1134
|
+
released = true;
|
|
1135
|
+
this.suspensions--;
|
|
1136
|
+
this.reset();
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
attach(target) {
|
|
1140
|
+
const editable = (ev) => {
|
|
1141
|
+
return !!ev.target?.closest?.("input, textarea, select, button, [contenteditable]:not([contenteditable=\"false\"]), [data-molen-input-editor]");
|
|
1142
|
+
};
|
|
1143
|
+
const add = (type, fn) => {
|
|
1144
|
+
target.addEventListener(type, fn);
|
|
1145
|
+
this.listeners.push([type, fn]);
|
|
1146
|
+
};
|
|
1147
|
+
add("keydown", (ev) => {
|
|
1148
|
+
if (!editable(ev)) this.press(ev.code);
|
|
1149
|
+
});
|
|
1150
|
+
add("keyup", (ev) => this.release(ev.code));
|
|
1151
|
+
add("mousedown", (ev) => {
|
|
1152
|
+
if (!editable(ev)) this.press(`Mouse${ev.button}`);
|
|
1153
|
+
});
|
|
1154
|
+
add("mouseup", (ev) => this.release(`Mouse${ev.button}`));
|
|
1155
|
+
add("blur", () => {
|
|
1156
|
+
this.focused = false;
|
|
1157
|
+
this.reset();
|
|
1158
|
+
});
|
|
1159
|
+
add("focus", () => {
|
|
1160
|
+
this.focused = true;
|
|
1161
|
+
this.blockedKeys.clear();
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
press(code) {
|
|
1165
|
+
if (this.disposed || !this.accepting || this.blockedKeys.has(code) || this.keys.has(code)) return;
|
|
1166
|
+
this.keys.add(code);
|
|
1167
|
+
this.recompute();
|
|
1168
|
+
}
|
|
1169
|
+
release(code) {
|
|
1170
|
+
this.blockedKeys.delete(code);
|
|
1171
|
+
if (this.keys.delete(code)) this.recompute();
|
|
1172
|
+
}
|
|
1173
|
+
/** Numeric action value; strongest absolute contribution wins, keyboard wins ties. */
|
|
1174
|
+
value(action) {
|
|
1175
|
+
return this.values.get(action) ?? 0;
|
|
1176
|
+
}
|
|
1177
|
+
isActive(action) {
|
|
1178
|
+
return this.value(action) !== 0;
|
|
1179
|
+
}
|
|
1180
|
+
activeActions() {
|
|
1181
|
+
return new Set(this.values.keys());
|
|
1182
|
+
}
|
|
1183
|
+
contribute(values, action, value) {
|
|
1184
|
+
if (Number.isFinite(value) && Math.abs(value) > Math.abs(values.get(action) ?? 0)) values.set(action, value);
|
|
1185
|
+
}
|
|
1186
|
+
recompute() {
|
|
1187
|
+
const next = /* @__PURE__ */ new Map();
|
|
1188
|
+
if (this.accepting) {
|
|
1189
|
+
for (const code of this.keys) {
|
|
1190
|
+
const action = resolveAction(this.profile.bindings, code);
|
|
1191
|
+
if (action !== void 0) this.contribute(next, action, 1);
|
|
1192
|
+
}
|
|
1193
|
+
for (const [action, value] of this.padValues) this.contribute(next, action, value);
|
|
1194
|
+
}
|
|
1195
|
+
this.commit(next);
|
|
1196
|
+
}
|
|
1197
|
+
commit(next) {
|
|
1198
|
+
const prev = this.values;
|
|
1199
|
+
this.values = next;
|
|
1200
|
+
const revision = ++this.revision;
|
|
1201
|
+
for (const action of new Set([...prev.keys(), ...next.keys()])) {
|
|
1202
|
+
const before = prev.get(action) ?? 0;
|
|
1203
|
+
const after = next.get(action) ?? 0;
|
|
1204
|
+
const handlers = before === 0 && after !== 0 ? this.pressHandlers : before !== 0 && after === 0 ? this.releaseHandlers : void 0;
|
|
1205
|
+
for (const fn of handlers?.get(action) ?? []) {
|
|
1206
|
+
if (this.revision !== revision) return;
|
|
1207
|
+
fn(action);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
if (this.revision !== revision) return;
|
|
1211
|
+
if ([...new Set([...prev.keys(), ...next.keys()])].some((action) => prev.get(action) !== next.get(action))) for (const fn of this.changeHandlers) fn();
|
|
1212
|
+
}
|
|
1213
|
+
/** Release actions immediately; suppress held physical buttons until released. */
|
|
1214
|
+
reset() {
|
|
1215
|
+
for (const key of this.keys) this.blockedKeys.add(key);
|
|
1216
|
+
this.keys.clear();
|
|
1217
|
+
this.padValues.clear();
|
|
1218
|
+
this.baselineButtons = true;
|
|
1219
|
+
this.commit(/* @__PURE__ */ new Map());
|
|
1220
|
+
for (const fn of this.resetHandlers) fn();
|
|
1221
|
+
}
|
|
1222
|
+
subscribe(map, action, handler) {
|
|
1223
|
+
let set = map.get(action);
|
|
1224
|
+
if (!set) {
|
|
1225
|
+
set = /* @__PURE__ */ new Set();
|
|
1226
|
+
map.set(action, set);
|
|
1227
|
+
}
|
|
1228
|
+
set.add(handler);
|
|
1229
|
+
return () => {
|
|
1230
|
+
set.delete(handler);
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
onPress(action, handler) {
|
|
1234
|
+
return this.subscribe(this.pressHandlers, action, handler);
|
|
1235
|
+
}
|
|
1236
|
+
onRelease(action, handler) {
|
|
1237
|
+
return this.subscribe(this.releaseHandlers, action, handler);
|
|
1238
|
+
}
|
|
1239
|
+
/** Action values changed (including neutralization on reset/profile switch). */
|
|
1240
|
+
onChange(handler) {
|
|
1241
|
+
this.changeHandlers.add(handler);
|
|
1242
|
+
return () => {
|
|
1243
|
+
this.changeHandlers.delete(handler);
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
/** Explicit neutralization on reset, focus loss, suspension or profile replacement. */
|
|
1247
|
+
onReset(handler) {
|
|
1248
|
+
this.resetHandlers.add(handler);
|
|
1249
|
+
return () => {
|
|
1250
|
+
this.resetHandlers.delete(handler);
|
|
1251
|
+
};
|
|
1252
|
+
}
|
|
1253
|
+
/** Profile selection or definitions changed. */
|
|
1254
|
+
onProfilesChanged(handler) {
|
|
1255
|
+
this.profileHandlers.add(handler);
|
|
1256
|
+
return () => {
|
|
1257
|
+
this.profileHandlers.delete(handler);
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
dispose() {
|
|
1261
|
+
if (this.disposed) return;
|
|
1262
|
+
this.disposed = true;
|
|
1263
|
+
if (this.target) for (const [type, fn] of this.listeners) this.target.removeEventListener(type, fn);
|
|
1264
|
+
this.listeners.length = 0;
|
|
1265
|
+
this.reset();
|
|
1266
|
+
this.pressHandlers.clear();
|
|
1267
|
+
this.releaseHandlers.clear();
|
|
1268
|
+
this.changeHandlers.clear();
|
|
1269
|
+
this.resetHandlers.clear();
|
|
1270
|
+
this.profileHandlers.clear();
|
|
1271
|
+
this.pads = [];
|
|
1272
|
+
}
|
|
1273
|
+
};
|
|
1274
|
+
//#endregion
|
|
1275
|
+
//#region src/scene-bindings.ts
|
|
1276
|
+
/**
|
|
1277
|
+
* Apply a scene's `camera` block. `fixed` and `free-fly` pose the perspective camera (free-fly
|
|
1278
|
+
* applies its initial pose only; movement controls are the host's); `top-down-ortho` switches to
|
|
1279
|
+
* the orthographic framing. Re-run after a resize to keep ortho framing (the Renderer already
|
|
1280
|
+
* refits on setSize; callers with their own renderer may call this again).
|
|
1281
|
+
*/
|
|
1282
|
+
function applySceneCamera(camera, renderer, target) {
|
|
1283
|
+
switch (camera.mode) {
|
|
1284
|
+
case "follow":
|
|
1285
|
+
if (target === void 0) return;
|
|
1286
|
+
renderer.setCamera(followCameraPose(camera, target));
|
|
1287
|
+
if (camera.fov !== void 0) renderer.setFov(camera.fov);
|
|
1288
|
+
return;
|
|
1289
|
+
case "fixed":
|
|
1290
|
+
case "free-fly":
|
|
1291
|
+
renderer.setCamera({
|
|
1292
|
+
position: camera.position,
|
|
1293
|
+
...camera.lookAt !== void 0 ? { lookAt: camera.lookAt } : {}
|
|
1294
|
+
});
|
|
1295
|
+
if (camera.fov !== void 0) renderer.setFov(camera.fov);
|
|
1296
|
+
return;
|
|
1297
|
+
case "top-down-ortho":
|
|
1298
|
+
renderer.setTopDownOrtho({
|
|
1299
|
+
center: camera.center,
|
|
1300
|
+
viewHeight: camera.viewHeight,
|
|
1301
|
+
...camera.cameraHeight !== void 0 ? { cameraHeight: camera.cameraHeight } : {}
|
|
1302
|
+
});
|
|
1303
|
+
return;
|
|
1304
|
+
default: return;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Run a scene's `input.emit` rules against an InputMap: `press`/`release` rules emit on action
|
|
1309
|
+
* edges; numeric rules share one controller poller that emits a scalar or [x, y] vector only
|
|
1310
|
+
* when its value changes. Returns a disposer.
|
|
1311
|
+
*/
|
|
1312
|
+
function applyInputRules(input, inputMap, emit, opts) {
|
|
1313
|
+
const unsubs = [];
|
|
1314
|
+
const axisRules = [];
|
|
1315
|
+
for (const rule of input.emit) switch (rule.kind) {
|
|
1316
|
+
case "press":
|
|
1317
|
+
unsubs.push(inputMap.onPress(rule.action, () => emit(rule.command, rule.payload)));
|
|
1318
|
+
break;
|
|
1319
|
+
case "release":
|
|
1320
|
+
unsubs.push(inputMap.onRelease(rule.action, () => emit(rule.command, rule.payload)));
|
|
1321
|
+
break;
|
|
1322
|
+
case "axis":
|
|
1323
|
+
case "axis2d":
|
|
1324
|
+
axisRules.push({
|
|
1325
|
+
rule,
|
|
1326
|
+
last: void 0
|
|
1327
|
+
});
|
|
1328
|
+
break;
|
|
1329
|
+
default: break;
|
|
1330
|
+
}
|
|
1331
|
+
const timer = opts?.timer ?? {
|
|
1332
|
+
set: (fn, ms) => setInterval(fn, ms),
|
|
1333
|
+
clear: (h) => clearInterval(h)
|
|
1334
|
+
};
|
|
1335
|
+
const sample = () => {
|
|
1336
|
+
const clamp = (n) => Math.max(-1, Math.min(1, n));
|
|
1337
|
+
for (const entry of axisRules) {
|
|
1338
|
+
const { rule } = entry;
|
|
1339
|
+
const value = rule.kind === "axis" ? clamp(inputMap.value(rule.action) - (rule.negative ? inputMap.value(rule.negative) : 0)) : [clamp(inputMap.value(rule.xPos) - inputMap.value(rule.xNeg)), clamp(inputMap.value(rule.yPos) - inputMap.value(rule.yNeg))];
|
|
1340
|
+
const serialized = JSON.stringify(value);
|
|
1341
|
+
if (entry.last === serialized) continue;
|
|
1342
|
+
entry.last = serialized;
|
|
1343
|
+
emit(rule.command, { [rule.field]: value });
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
unsubs.push(inputMap.onReset(sample));
|
|
1347
|
+
const handle = timer.set(() => {
|
|
1348
|
+
inputMap.update();
|
|
1349
|
+
sample();
|
|
1350
|
+
}, opts?.pollMs ?? 50);
|
|
1351
|
+
unsubs.push(() => timer.clear(handle));
|
|
1352
|
+
return () => {
|
|
1353
|
+
for (const off of unsubs) off();
|
|
1354
|
+
unsubs.length = 0;
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
/** Pure camera composition shared by live interpolation and deterministic snapshot viewers. */
|
|
1358
|
+
function followCameraPose(camera, target) {
|
|
1359
|
+
const point = (offset) => {
|
|
1360
|
+
let [x, y, z] = offset;
|
|
1361
|
+
if (camera.space === "local") {
|
|
1362
|
+
const [qx, qy, qz, qw] = target.rot;
|
|
1363
|
+
const tx = 2 * (qy * z - qz * y);
|
|
1364
|
+
const ty = 2 * (qz * x - qx * z);
|
|
1365
|
+
const tz = 2 * (qx * y - qy * x);
|
|
1366
|
+
x += qw * tx + qy * tz - qz * ty;
|
|
1367
|
+
y += qw * ty + qz * tx - qx * tz;
|
|
1368
|
+
z += qw * tz + qx * ty - qy * tx;
|
|
1369
|
+
}
|
|
1370
|
+
return [
|
|
1371
|
+
target.pos[0] + x,
|
|
1372
|
+
target.pos[1] + y,
|
|
1373
|
+
target.pos[2] + z
|
|
1374
|
+
];
|
|
1375
|
+
};
|
|
1376
|
+
return {
|
|
1377
|
+
position: point(camera.offset),
|
|
1378
|
+
lookAt: point(camera.lookOffset)
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
//#endregion
|
|
1382
|
+
//#region src/three/environment.ts
|
|
1383
|
+
/** Exactly the rig the renderer always shipped — existing scenes render byte-identical. */
|
|
1384
|
+
const defaultEnvironment = {
|
|
1385
|
+
ambient: {
|
|
1386
|
+
sky: "#ffffff",
|
|
1387
|
+
ground: "#444455",
|
|
1388
|
+
intensity: 1.1
|
|
1389
|
+
},
|
|
1390
|
+
sun: {
|
|
1391
|
+
direction: [
|
|
1392
|
+
5,
|
|
1393
|
+
10,
|
|
1394
|
+
7
|
|
1395
|
+
],
|
|
1396
|
+
color: "#ffffff",
|
|
1397
|
+
intensity: 1.4
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
const RIG_NAME = "$environment";
|
|
1401
|
+
const SHADOW_MAP_SIZE = {
|
|
1402
|
+
low: 1024,
|
|
1403
|
+
medium: 2048,
|
|
1404
|
+
high: 4096
|
|
1405
|
+
};
|
|
1406
|
+
/**
|
|
1407
|
+
* Apply an environment onto the renderer + scene: replaces the ambient/sun rig, background,
|
|
1408
|
+
* fog, tone mapping, exposure, and the shadow quality tier. Passing `defaultEnvironment`
|
|
1409
|
+
* restores the stock rig; omitted fields fall back to it.
|
|
1410
|
+
*/
|
|
1411
|
+
function applyEnvironment(renderer, env) {
|
|
1412
|
+
renderer.setSky(env.sky, env.shadows ?? "off");
|
|
1413
|
+
const scene = renderer.scene;
|
|
1414
|
+
const existing = scene.getObjectByName(RIG_NAME);
|
|
1415
|
+
if (existing !== void 0) {
|
|
1416
|
+
existing.traverse((object) => {
|
|
1417
|
+
if (object.isLight) object.dispose();
|
|
1418
|
+
});
|
|
1419
|
+
scene.remove(existing);
|
|
1420
|
+
}
|
|
1421
|
+
const rig = new THREE.Group();
|
|
1422
|
+
rig.name = RIG_NAME;
|
|
1423
|
+
const ambient = env.ambient ?? defaultEnvironment.ambient;
|
|
1424
|
+
if (ambient !== void 0 && env.sky === void 0) rig.add(new THREE.HemisphereLight(new THREE.Color(ambient.sky ?? "#ffffff"), new THREE.Color(ambient.ground ?? "#444455"), ambient.intensity ?? 1.1));
|
|
1425
|
+
const shadows = env.shadows ?? "off";
|
|
1426
|
+
const sun = env.sun ?? defaultEnvironment.sun;
|
|
1427
|
+
if (sun !== void 0 && env.sky === void 0) {
|
|
1428
|
+
const dir = new THREE.DirectionalLight(new THREE.Color(sun.color ?? "#ffffff"), sun.intensity ?? 1.4);
|
|
1429
|
+
const d = sun.direction ?? [
|
|
1430
|
+
5,
|
|
1431
|
+
10,
|
|
1432
|
+
7
|
|
1433
|
+
];
|
|
1434
|
+
dir.position.set(d[0], d[1], d[2]);
|
|
1435
|
+
if (shadows !== "off" && sun.castShadow === true) {
|
|
1436
|
+
dir.castShadow = true;
|
|
1437
|
+
const size = SHADOW_MAP_SIZE[shadows];
|
|
1438
|
+
dir.shadow.mapSize.set(size, size);
|
|
1439
|
+
dir.shadow.camera.near = .5;
|
|
1440
|
+
dir.shadow.camera.far = 500;
|
|
1441
|
+
const extent = 50;
|
|
1442
|
+
dir.shadow.camera.left = -50;
|
|
1443
|
+
dir.shadow.camera.right = extent;
|
|
1444
|
+
dir.shadow.camera.top = extent;
|
|
1445
|
+
dir.shadow.camera.bottom = -50;
|
|
1446
|
+
}
|
|
1447
|
+
rig.add(dir);
|
|
1448
|
+
}
|
|
1449
|
+
scene.add(rig);
|
|
1450
|
+
renderer.three.shadowMap.enabled = shadows !== "off";
|
|
1451
|
+
renderer.three.shadowMap.type = shadows === "low" ? THREE.PCFShadowMap : THREE.PCFSoftShadowMap;
|
|
1452
|
+
renderer.three.setClearColor(env.background !== void 0 ? new THREE.Color(env.background) : renderer.defaultClearColor, 1);
|
|
1453
|
+
scene.fog = env.fog !== void 0 ? new THREE.Fog(new THREE.Color(env.fog.color), env.fog.near ?? 1, env.fog.far ?? 1e3) : null;
|
|
1454
|
+
renderer.three.toneMapping = env.toneMapping === "aces" ? THREE.ACESFilmicToneMapping : env.toneMapping === "agx" ? THREE.AgXToneMapping : THREE.NoToneMapping;
|
|
1455
|
+
renderer.three.toneMappingExposure = env.exposure ?? 1;
|
|
1456
|
+
}
|
|
1457
|
+
//#endregion
|
|
1458
|
+
//#region src/three/materials.ts
|
|
1459
|
+
registerMaterialSchemas();
|
|
1460
|
+
function textureFrom(image, filter, srgb) {
|
|
1461
|
+
const tex = new THREE.DataTexture(new Uint8Array(image.data.buffer.slice(0)), image.width, image.height, THREE.RGBAFormat);
|
|
1462
|
+
tex.flipY = false;
|
|
1463
|
+
if (srgb) tex.colorSpace = THREE.SRGBColorSpace;
|
|
1464
|
+
tex.magFilter = filter === "nearest" ? THREE.NearestFilter : THREE.LinearFilter;
|
|
1465
|
+
tex.minFilter = filter === "nearest" ? THREE.NearestFilter : THREE.LinearFilter;
|
|
1466
|
+
tex.needsUpdate = true;
|
|
1467
|
+
return tex;
|
|
1468
|
+
}
|
|
1469
|
+
/** Upload a BakedMaterial's slots onto a MeshStandardMaterial. */
|
|
1470
|
+
function materialFromBaked(baked) {
|
|
1471
|
+
const material = new THREE.MeshStandardMaterial({
|
|
1472
|
+
roughness: 1,
|
|
1473
|
+
metalness: 1
|
|
1474
|
+
});
|
|
1475
|
+
const filter = baked.meta.filter;
|
|
1476
|
+
if (baked.slots.baseColor !== void 0) material.map = textureFrom(baked.slots.baseColor, filter, true);
|
|
1477
|
+
else {
|
|
1478
|
+
material.roughness = .6;
|
|
1479
|
+
material.metalness = 0;
|
|
1480
|
+
}
|
|
1481
|
+
if (baked.slots.roughness !== void 0) material.roughnessMap = textureFrom(baked.slots.roughness, filter, false);
|
|
1482
|
+
if (baked.slots.metalness !== void 0) material.metalnessMap = textureFrom(baked.slots.metalness, filter, false);
|
|
1483
|
+
else if (baked.slots.baseColor !== void 0) material.metalness = 0;
|
|
1484
|
+
if (baked.slots.normal !== void 0) material.normalMap = textureFrom(baked.slots.normal, filter, false);
|
|
1485
|
+
if (baked.slots.emissive !== void 0) {
|
|
1486
|
+
material.emissiveMap = textureFrom(baked.slots.emissive, filter, true);
|
|
1487
|
+
material.emissive = new THREE.Color("#ffffff");
|
|
1488
|
+
}
|
|
1489
|
+
if (baked.slots.ao !== void 0) material.aoMap = textureFrom(baked.slots.ao, filter, false);
|
|
1490
|
+
if (baked.meta.alphaTest !== void 0) {
|
|
1491
|
+
material.alphaTest = baked.meta.alphaTest;
|
|
1492
|
+
material.transparent = false;
|
|
1493
|
+
}
|
|
1494
|
+
return material;
|
|
1495
|
+
}
|
|
1496
|
+
const GREY = "#cccccc";
|
|
1497
|
+
/** Cache key of the shared grey fallback (unknown/absent refs and async placeholders). */
|
|
1498
|
+
const GREY_KEY = "__grey";
|
|
1499
|
+
function flatMaterial(color) {
|
|
1500
|
+
return new THREE.MeshStandardMaterial({
|
|
1501
|
+
color: new THREE.Color(color),
|
|
1502
|
+
roughness: .6
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* Resolves materialRef strings to three.js materials. Sync for `palette:`; doc-backed refs
|
|
1507
|
+
* (`matgraph:`/`pixelgrid:`) load + bake asynchronously. Every ref string maps to ONE cached
|
|
1508
|
+
* material shared by all entities using it; `acquire*`/`release` refcount those so a material
|
|
1509
|
+
* (and its textures) is disposed exactly when its last user lets go.
|
|
1510
|
+
*/
|
|
1511
|
+
var MaterialResolver = class {
|
|
1512
|
+
provider;
|
|
1513
|
+
baker;
|
|
1514
|
+
cache = /* @__PURE__ */ new Map();
|
|
1515
|
+
/** Reverse map: cached material -> its cache key (for release). */
|
|
1516
|
+
keyOf = /* @__PURE__ */ new Map();
|
|
1517
|
+
refs = /* @__PURE__ */ new Map();
|
|
1518
|
+
disposed = false;
|
|
1519
|
+
disposedMaterials = /* @__PURE__ */ new WeakSet();
|
|
1520
|
+
/** An optional caller-owned worker baker keeps procedural rasterization off the UI thread. */
|
|
1521
|
+
constructor(provider = void 0, baker = void 0) {
|
|
1522
|
+
this.provider = provider;
|
|
1523
|
+
this.baker = baker;
|
|
1524
|
+
}
|
|
1525
|
+
/** Sync resolution: palette refs (and the shared grey fallback for unknown/absent refs). */
|
|
1526
|
+
resolveSync(materialRef) {
|
|
1527
|
+
const key = materialRef?.startsWith("palette:") === true ? materialRef : GREY_KEY;
|
|
1528
|
+
const cached = this.cache.get(key);
|
|
1529
|
+
if (cached instanceof THREE.Material) return cached;
|
|
1530
|
+
const material = flatMaterial(key === GREY_KEY ? GREY : key.slice(8));
|
|
1531
|
+
if (!this.disposed) this.remember(key, material);
|
|
1532
|
+
return material;
|
|
1533
|
+
}
|
|
1534
|
+
/** Is this a doc-backed ref that resolves asynchronously? */
|
|
1535
|
+
isAsync(materialRef) {
|
|
1536
|
+
return materialRef !== void 0 && (materialRef.startsWith("matgraph:") || materialRef.startsWith("pixelgrid:"));
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Async resolution for doc-backed refs; falls back to grey (with one warning) when the doc
|
|
1540
|
+
* is missing/invalid so a bad ref never blanks the scene.
|
|
1541
|
+
*/
|
|
1542
|
+
async resolve(materialRef) {
|
|
1543
|
+
if (this.disposed) throw new Error("material resolver is disposed");
|
|
1544
|
+
const cached = this.cache.get(materialRef);
|
|
1545
|
+
if (cached !== void 0) return cached;
|
|
1546
|
+
const promise = this.bake(materialRef).catch((e) => {
|
|
1547
|
+
console.warn(`[molen] materialRef "${materialRef}": ${e.message}`);
|
|
1548
|
+
return flatMaterial(GREY);
|
|
1549
|
+
}).then((material) => {
|
|
1550
|
+
if (this.disposed || this.cache.get(materialRef) !== promise) this.disposeMaterial(material);
|
|
1551
|
+
else this.remember(materialRef, material);
|
|
1552
|
+
return material;
|
|
1553
|
+
});
|
|
1554
|
+
this.cache.set(materialRef, promise);
|
|
1555
|
+
return promise;
|
|
1556
|
+
}
|
|
1557
|
+
/** `resolveSync` plus one reference; pair with `release`. */
|
|
1558
|
+
acquireSync(materialRef) {
|
|
1559
|
+
return this.retain(this.resolveSync(materialRef));
|
|
1560
|
+
}
|
|
1561
|
+
/** `resolve` plus one reference; pair with `release`. */
|
|
1562
|
+
async acquire(materialRef) {
|
|
1563
|
+
return this.retain(await this.resolve(materialRef));
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Drop one reference; at zero the material (and its textures) is disposed and evicted from
|
|
1567
|
+
* the cache. Materials not handed out by `acquire*` are ignored.
|
|
1568
|
+
*/
|
|
1569
|
+
release(material) {
|
|
1570
|
+
const count = this.refs.get(material);
|
|
1571
|
+
if (count === void 0) return;
|
|
1572
|
+
if (count > 1) {
|
|
1573
|
+
this.refs.set(material, count - 1);
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
this.refs.delete(material);
|
|
1577
|
+
const key = this.keyOf.get(material);
|
|
1578
|
+
if (key !== void 0) {
|
|
1579
|
+
this.keyOf.delete(material);
|
|
1580
|
+
if (this.cache.get(key) === material) this.cache.delete(key);
|
|
1581
|
+
}
|
|
1582
|
+
this.disposeMaterial(material);
|
|
1583
|
+
}
|
|
1584
|
+
retain(material) {
|
|
1585
|
+
if (!this.disposed) this.refs.set(material, (this.refs.get(material) ?? 0) + 1);
|
|
1586
|
+
return material;
|
|
1587
|
+
}
|
|
1588
|
+
remember(key, material) {
|
|
1589
|
+
this.cache.set(key, material);
|
|
1590
|
+
this.keyOf.set(material, key);
|
|
1591
|
+
}
|
|
1592
|
+
async bake(materialRef) {
|
|
1593
|
+
if (this.provider === void 0) throw new Error("no asset provider configured (ClientOptions.assets)");
|
|
1594
|
+
const sep = materialRef.indexOf(":");
|
|
1595
|
+
const kind = materialRef.slice(0, sep);
|
|
1596
|
+
const ref = materialRef.slice(sep + 1);
|
|
1597
|
+
const doc = JSON.parse(await this.provider.loadText(ref));
|
|
1598
|
+
if (kind === "matgraph") {
|
|
1599
|
+
const parsed = validateByKind("matgraph", doc);
|
|
1600
|
+
if (!parsed.ok) throw new Error(parsed.formatted);
|
|
1601
|
+
return materialFromBaked(this.baker ? await this.baker.bake("matgraph", parsed.value) : bakeMatGraph(parsed.value));
|
|
1602
|
+
}
|
|
1603
|
+
const parsed = validateByKind("pixelgrid", doc);
|
|
1604
|
+
if (!parsed.ok) throw new Error(parsed.formatted);
|
|
1605
|
+
return materialFromBaked(this.baker ? await this.baker.bake("pixelgrid", parsed.value) : bakePixelGrid(parsed.value));
|
|
1606
|
+
}
|
|
1607
|
+
dispose() {
|
|
1608
|
+
if (this.disposed) return;
|
|
1609
|
+
this.disposed = true;
|
|
1610
|
+
for (const entry of this.cache.values()) if (entry instanceof THREE.Material) this.disposeMaterial(entry);
|
|
1611
|
+
else entry.then((material) => this.disposeMaterial(material));
|
|
1612
|
+
this.cache.clear();
|
|
1613
|
+
this.keyOf.clear();
|
|
1614
|
+
this.refs.clear();
|
|
1615
|
+
}
|
|
1616
|
+
disposeMaterial(material) {
|
|
1617
|
+
if (this.disposedMaterials.has(material)) return;
|
|
1618
|
+
this.disposedMaterials.add(material);
|
|
1619
|
+
for (const value of Object.values(material)) if (value instanceof THREE.Texture) value.dispose();
|
|
1620
|
+
material.dispose();
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
//#endregion
|
|
1624
|
+
//#region src/three/static-batches.ts
|
|
1625
|
+
/** Only renderer-owned, opaque, nonanimated meshes are admitted. Originals retain entity identity. */
|
|
1626
|
+
var StaticMeshBatches = class {
|
|
1627
|
+
root;
|
|
1628
|
+
prepare;
|
|
1629
|
+
pending = /* @__PURE__ */ new Set();
|
|
1630
|
+
entities = /* @__PURE__ */ new Map();
|
|
1631
|
+
batches = /* @__PURE__ */ new Map();
|
|
1632
|
+
dirty = /* @__PURE__ */ new Set();
|
|
1633
|
+
cellSize;
|
|
1634
|
+
minimum;
|
|
1635
|
+
constructor(root, options = {}, prepare) {
|
|
1636
|
+
this.root = root;
|
|
1637
|
+
this.prepare = prepare;
|
|
1638
|
+
this.cellSize = options.cellSize ?? 32;
|
|
1639
|
+
this.minimum = options.minInstances ?? 2;
|
|
1640
|
+
if (!Number.isFinite(this.cellSize) || this.cellSize <= 0 || !Number.isInteger(this.minimum) || this.minimum < 2) throw new RangeError("Static batching requires a positive cell size and at least two instances");
|
|
1641
|
+
}
|
|
1642
|
+
add(id, object) {
|
|
1643
|
+
this.remove(id);
|
|
1644
|
+
if (!object.visible) return;
|
|
1645
|
+
this.root.updateWorldMatrix(true, false);
|
|
1646
|
+
object.updateWorldMatrix(true, true);
|
|
1647
|
+
const inverse = this.root.matrixWorld.clone().invert();
|
|
1648
|
+
const entries = [];
|
|
1649
|
+
object.traverseVisible((child) => {
|
|
1650
|
+
const mesh = child;
|
|
1651
|
+
if (!mesh.isMesh || mesh.isSkinnedMesh || mesh.isInstancedMesh || mesh.morphTargetInfluences || mesh.onBeforeRender !== THREE.Object3D.prototype.onBeforeRender || mesh.onAfterRender !== THREE.Object3D.prototype.onAfterRender) return;
|
|
1652
|
+
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
|
|
1653
|
+
if (materials.some((m) => m.transparent || !m.depthWrite || !m.depthTest || m.transmission > 0 || m.isShaderMaterial || m.isNodeMaterial || m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile)) return;
|
|
1654
|
+
const matrix = new THREE.Matrix4().multiplyMatrices(inverse, mesh.matrixWorld);
|
|
1655
|
+
if (matrix.determinant() <= 0) return;
|
|
1656
|
+
const e = matrix.elements;
|
|
1657
|
+
const key = `${[
|
|
1658
|
+
Math.floor(e[12] / this.cellSize),
|
|
1659
|
+
Math.floor(e[13] / this.cellSize),
|
|
1660
|
+
Math.floor(e[14] / this.cellSize)
|
|
1661
|
+
].join("/")}|${mesh.geometry.uuid}|${materials.map((m) => m.uuid).join(",")}|${mesh.castShadow}/${mesh.receiveShadow}/${mesh.layers.mask}/${mesh.renderOrder}`;
|
|
1662
|
+
const entry = {
|
|
1663
|
+
id,
|
|
1664
|
+
mesh,
|
|
1665
|
+
matrix,
|
|
1666
|
+
visible: mesh.visible,
|
|
1667
|
+
key
|
|
1668
|
+
};
|
|
1669
|
+
let batch = this.batches.get(key);
|
|
1670
|
+
if (!batch) {
|
|
1671
|
+
batch = { members: /* @__PURE__ */ new Set() };
|
|
1672
|
+
this.batches.set(key, batch);
|
|
1673
|
+
}
|
|
1674
|
+
batch.members.add(entry);
|
|
1675
|
+
entries.push(entry);
|
|
1676
|
+
this.dirty.add(key);
|
|
1677
|
+
});
|
|
1678
|
+
this.entities.set(id, entries);
|
|
1679
|
+
}
|
|
1680
|
+
remove(id) {
|
|
1681
|
+
for (const entry of this.entities.get(id) ?? []) {
|
|
1682
|
+
entry.mesh.visible = entry.visible;
|
|
1683
|
+
this.batches.get(entry.key)?.members.delete(entry);
|
|
1684
|
+
this.dirty.add(entry.key);
|
|
1685
|
+
}
|
|
1686
|
+
this.entities.delete(id);
|
|
1687
|
+
}
|
|
1688
|
+
flush() {
|
|
1689
|
+
for (const key of this.dirty) {
|
|
1690
|
+
const batch = this.batches.get(key);
|
|
1691
|
+
if (!batch) continue;
|
|
1692
|
+
const revision = (batch.revision ?? 0) + 1;
|
|
1693
|
+
batch.revision = revision;
|
|
1694
|
+
batch.object?.removeFromParent();
|
|
1695
|
+
batch.object?.dispose();
|
|
1696
|
+
delete batch.object;
|
|
1697
|
+
const entries = [...batch.members];
|
|
1698
|
+
for (const entry of entries) entry.mesh.visible = entry.visible;
|
|
1699
|
+
if (entries.length === 0) {
|
|
1700
|
+
this.batches.delete(key);
|
|
1701
|
+
continue;
|
|
1702
|
+
}
|
|
1703
|
+
if (entries.length < this.minimum) {
|
|
1704
|
+
for (const e of entries) e.mesh.visible = e.visible;
|
|
1705
|
+
continue;
|
|
1706
|
+
}
|
|
1707
|
+
const first = entries[0];
|
|
1708
|
+
const object = new THREE.InstancedMesh(first.mesh.geometry, first.mesh.material, entries.length);
|
|
1709
|
+
object.name = `molen:static:${key}`;
|
|
1710
|
+
object.castShadow = first.mesh.castShadow;
|
|
1711
|
+
object.receiveShadow = first.mesh.receiveShadow;
|
|
1712
|
+
object.layers.mask = first.mesh.layers.mask;
|
|
1713
|
+
object.renderOrder = first.mesh.renderOrder;
|
|
1714
|
+
const cell = key.split("|")[0]?.split("/").map(Number);
|
|
1715
|
+
object.position.set(cell[0] * this.cellSize, cell[1] * this.cellSize, cell[2] * this.cellSize);
|
|
1716
|
+
const offset = new THREE.Matrix4().makeTranslation(-object.position.x, -object.position.y, -object.position.z);
|
|
1717
|
+
const matrix = new THREE.Matrix4();
|
|
1718
|
+
const ids = [];
|
|
1719
|
+
entries.forEach((entry, i) => {
|
|
1720
|
+
object.setMatrixAt(i, matrix.multiplyMatrices(offset, entry.matrix));
|
|
1721
|
+
ids.push(entry.id);
|
|
1722
|
+
});
|
|
1723
|
+
object.userData.molenEntityIds = ids;
|
|
1724
|
+
object.updateMatrix();
|
|
1725
|
+
object.matrixAutoUpdate = false;
|
|
1726
|
+
object.instanceMatrix.needsUpdate = true;
|
|
1727
|
+
object.computeBoundingBox();
|
|
1728
|
+
object.computeBoundingSphere();
|
|
1729
|
+
const publish = () => {
|
|
1730
|
+
if (this.batches.get(key) !== batch || batch.revision !== revision) {
|
|
1731
|
+
object.dispose();
|
|
1732
|
+
return;
|
|
1733
|
+
}
|
|
1734
|
+
for (const entry of entries) entry.mesh.visible = false;
|
|
1735
|
+
batch.object = object;
|
|
1736
|
+
this.root.add(object);
|
|
1737
|
+
};
|
|
1738
|
+
if (this.prepare) {
|
|
1739
|
+
const pending = this.prepare(object).then(publish).catch((error) => {
|
|
1740
|
+
object.dispose();
|
|
1741
|
+
if (this.batches.get(key) === batch && batch.revision === revision) console.warn("[molen] static batch preparation failed; retaining ordinary meshes:", error);
|
|
1742
|
+
}).finally(() => this.pending.delete(pending));
|
|
1743
|
+
this.pending.add(pending);
|
|
1744
|
+
} else publish();
|
|
1745
|
+
}
|
|
1746
|
+
this.dirty.clear();
|
|
1747
|
+
}
|
|
1748
|
+
async whenIdle() {
|
|
1749
|
+
while (this.pending.size > 0) await Promise.all(this.pending);
|
|
1750
|
+
}
|
|
1751
|
+
dispose() {
|
|
1752
|
+
for (const id of this.entities.keys()) this.remove(id);
|
|
1753
|
+
this.flush();
|
|
1754
|
+
}
|
|
1755
|
+
};
|
|
1756
|
+
//#endregion
|
|
1757
|
+
//#region src/three/backend.ts
|
|
1758
|
+
/** Validate before allocating client resources. */
|
|
1759
|
+
function validateSceneOptimizationOptions(optimization = {}) {
|
|
1760
|
+
const animation = optimization.animation;
|
|
1761
|
+
if (animation && [animation.distantHz, animation.hiddenHz].some((value) => value !== void 0 && (!Number.isFinite(value) || value <= 0))) throw new RangeError("Animation sample rates must be finite and positive");
|
|
1762
|
+
if (animation && animation.distantDistance !== void 0 && (!Number.isFinite(animation.distantDistance) || animation.distantDistance < 0)) throw new RangeError("Animation distance must be finite and nonnegative");
|
|
1763
|
+
if (optimization.maxLocalLights !== void 0 && (!Number.isSafeInteger(optimization.maxLocalLights) || optimization.maxLocalLights < 0)) throw new RangeError("Local light limit must be a nonnegative integer");
|
|
1764
|
+
}
|
|
1765
|
+
/** Cache key of a primitive's geometry: every entity with the same key shares one buffer. */
|
|
1766
|
+
function geometryKey(r) {
|
|
1767
|
+
return `${r.ref}|${JSON.stringify(r.primitive?.size ?? null)}`;
|
|
1768
|
+
}
|
|
1769
|
+
/** Cache-miss factory for primitive geometry (see `ThreeSceneBackend.acquireGeometry`). */
|
|
1770
|
+
function buildGeometry(renderable) {
|
|
1771
|
+
const size = renderable.primitive?.size ?? [
|
|
1772
|
+
1,
|
|
1773
|
+
1,
|
|
1774
|
+
1
|
|
1775
|
+
];
|
|
1776
|
+
switch (renderable.ref) {
|
|
1777
|
+
case "box": return new THREE.BoxGeometry(size[0], size[1], size[2]);
|
|
1778
|
+
case "sphere": return new THREE.SphereGeometry(size[0] / 2, 24, 16);
|
|
1779
|
+
case "plane": return new THREE.PlaneGeometry(size[0], size[2]);
|
|
1780
|
+
case "cylinder": return new THREE.CylinderGeometry(size[0] / 2, size[0] / 2, size[1], 24);
|
|
1781
|
+
default: return new THREE.BoxGeometry(size[0], size[1], size[2]);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
/** Deterministic clip time from kernel tick (the capture path's animation contract). */
|
|
1785
|
+
function computeClipTime(anim, tick, tickRate, durationSec) {
|
|
1786
|
+
const speed = anim.speed ?? 1;
|
|
1787
|
+
const at = anim.paused === true ? anim.pausedAtTick ?? anim.startTick ?? 0 : tick;
|
|
1788
|
+
const raw = Math.max(0, (at - (anim.startTick ?? 0)) / tickRate) * speed;
|
|
1789
|
+
if (durationSec <= 0) return 0;
|
|
1790
|
+
switch (anim.loop ?? "repeat") {
|
|
1791
|
+
case "once": return Math.max(0, Math.min(raw, durationSec));
|
|
1792
|
+
case "pingpong": {
|
|
1793
|
+
const phase = (raw % (durationSec * 2) + durationSec * 2) % (durationSec * 2);
|
|
1794
|
+
return phase <= durationSec ? phase : durationSec * 2 - phase;
|
|
1795
|
+
}
|
|
1796
|
+
default: return (raw % durationSec + durationSec) % durationSec;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* The identity part of a renderable: same identity -> in-place update, no reload. A primitive's
|
|
1801
|
+
* material is NOT part of its identity (it swaps in place); a glTF's is, because the instance's
|
|
1802
|
+
* original materials cannot be restored once dressed.
|
|
1803
|
+
*/
|
|
1804
|
+
function renderableIdentity(r) {
|
|
1805
|
+
if (r.kind === "gltf") return `gltf|${r.ref}|${r.node ?? ""}|${r.materialRef ?? ""}`;
|
|
1806
|
+
return `primitive|${geometryKey(r)}`;
|
|
1807
|
+
}
|
|
1808
|
+
function buildLight(light) {
|
|
1809
|
+
const color = new THREE.Color(light.color ?? "#ffffff");
|
|
1810
|
+
const intensity = light.intensity ?? 1;
|
|
1811
|
+
switch (light.type) {
|
|
1812
|
+
case "point": return new THREE.PointLight(color, intensity, light.range ?? 0);
|
|
1813
|
+
case "spot": return new THREE.SpotLight(color, intensity, light.range ?? 0, (light.angleDeg ?? 45) * Math.PI / 180, light.penumbra ?? 0);
|
|
1814
|
+
default: return new THREE.DirectionalLight(color, intensity);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
/** three.js implementation of the SceneBackend: primitives + async glTF instances + lights. */
|
|
1818
|
+
var ThreeSceneBackend = class ThreeSceneBackend {
|
|
1819
|
+
scene;
|
|
1820
|
+
assets;
|
|
1821
|
+
renderer;
|
|
1822
|
+
materials;
|
|
1823
|
+
optimization;
|
|
1824
|
+
batches;
|
|
1825
|
+
batchDirty = /* @__PURE__ */ new Set();
|
|
1826
|
+
dynamic = /* @__PURE__ */ new Set();
|
|
1827
|
+
escaped = /* @__PURE__ */ new Set();
|
|
1828
|
+
transformed = /* @__PURE__ */ new Set();
|
|
1829
|
+
animations = /* @__PURE__ */ new Set();
|
|
1830
|
+
lastPoseTick = /* @__PURE__ */ new Map();
|
|
1831
|
+
frustum = new THREE.Frustum();
|
|
1832
|
+
viewProjection = new THREE.Matrix4();
|
|
1833
|
+
animationTick = 0;
|
|
1834
|
+
animationTickRate = 30;
|
|
1835
|
+
objects = /* @__PURE__ */ new Map();
|
|
1836
|
+
gltf = /* @__PURE__ */ new Map();
|
|
1837
|
+
modelSignals = /* @__PURE__ */ new Map();
|
|
1838
|
+
identities = /* @__PURE__ */ new Map();
|
|
1839
|
+
lights = /* @__PURE__ */ new Map();
|
|
1840
|
+
/** Refcounted primitive geometry, keyed by `geometryKey`; disposed when the count hits 0. */
|
|
1841
|
+
geometries = /* @__PURE__ */ new Map();
|
|
1842
|
+
entityGeometry = /* @__PURE__ */ new Map();
|
|
1843
|
+
/** The one resolver-owned material each entity currently holds a reference on. */
|
|
1844
|
+
entityMaterial = /* @__PURE__ */ new Map();
|
|
1845
|
+
entityMaterialRef = /* @__PURE__ */ new Map();
|
|
1846
|
+
/** Bumps on every material assignment/destroy so a late bake never overwrites a newer one. */
|
|
1847
|
+
materialEpoch = /* @__PURE__ */ new Map();
|
|
1848
|
+
epochSeq = 0;
|
|
1849
|
+
warnedNoAssets = false;
|
|
1850
|
+
/** Custom renderable kinds and the per-entity handles they created. */
|
|
1851
|
+
kinds = /* @__PURE__ */ new Map();
|
|
1852
|
+
handles = /* @__PURE__ */ new Map();
|
|
1853
|
+
warnedKinds = /* @__PURE__ */ new Set();
|
|
1854
|
+
mirror;
|
|
1855
|
+
/** Async work registered by kinds that the capture barrier waits for. */
|
|
1856
|
+
pending = /* @__PURE__ */ new Set();
|
|
1857
|
+
constructor(scene, assets = void 0, renderer = void 0, materials = new MaterialResolver(), optimization = {}) {
|
|
1858
|
+
this.scene = scene;
|
|
1859
|
+
this.assets = assets;
|
|
1860
|
+
this.renderer = renderer;
|
|
1861
|
+
this.materials = materials;
|
|
1862
|
+
this.optimization = optimization;
|
|
1863
|
+
validateSceneOptimizationOptions(optimization);
|
|
1864
|
+
if (optimization.staticInstancing !== false) this.batches = new StaticMeshBatches(scene, typeof optimization.staticInstancing === "object" ? optimization.staticInstancing : {}, renderer && optimization.shaderWarmup !== false ? (object) => renderer.prepareObject(object) : void 0);
|
|
1865
|
+
}
|
|
1866
|
+
/** Register a custom renderable kind (capability client halves). Core kinds cannot be replaced. */
|
|
1867
|
+
registerKind(kind) {
|
|
1868
|
+
if (kind.kind === "primitive" || kind.kind === "gltf") throw new Error(`renderable kind "${kind.kind}" is built in`);
|
|
1869
|
+
if (this.kinds.has(kind.kind)) throw new Error(`renderable kind "${kind.kind}" is already registered`);
|
|
1870
|
+
this.kinds.set(kind.kind, kind);
|
|
1871
|
+
}
|
|
1872
|
+
/** Give custom kinds read access to the mirrored components (no per-frame cloning). */
|
|
1873
|
+
bindMirror(reader) {
|
|
1874
|
+
this.mirror = reader;
|
|
1875
|
+
}
|
|
1876
|
+
identityOf(r) {
|
|
1877
|
+
const kind = this.kinds.get(r.kind);
|
|
1878
|
+
if (kind !== void 0) return `${r.kind}|${kind.identity(r)}`;
|
|
1879
|
+
return renderableIdentity(r);
|
|
1880
|
+
}
|
|
1881
|
+
kindContext() {
|
|
1882
|
+
const backend = this;
|
|
1883
|
+
return {
|
|
1884
|
+
scene: this.scene,
|
|
1885
|
+
renderer: this.renderer,
|
|
1886
|
+
assets: this.assets,
|
|
1887
|
+
materials: this.materials,
|
|
1888
|
+
get mirror() {
|
|
1889
|
+
return backend.mirror;
|
|
1890
|
+
},
|
|
1891
|
+
track: (promise) => {
|
|
1892
|
+
const tracked = promise.then((value) => {
|
|
1893
|
+
this.pending.delete(tracked);
|
|
1894
|
+
return value;
|
|
1895
|
+
}, (error) => {
|
|
1896
|
+
this.pending.delete(tracked);
|
|
1897
|
+
throw error;
|
|
1898
|
+
});
|
|
1899
|
+
this.pending.add(tracked);
|
|
1900
|
+
this.assets?.track(tracked);
|
|
1901
|
+
return tracked;
|
|
1902
|
+
},
|
|
1903
|
+
warn: (message) => console.warn(`[molen] ${message}`)
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
createKind(id, renderable) {
|
|
1907
|
+
const kind = this.kinds.get(renderable.kind);
|
|
1908
|
+
if (kind === void 0) {
|
|
1909
|
+
if (!this.warnedKinds.has(renderable.kind)) {
|
|
1910
|
+
this.warnedKinds.add(renderable.kind);
|
|
1911
|
+
console.warn(`[molen] renderable kind "${renderable.kind}" has no registered renderer (ClientOptions.kinds); entities of this kind render nothing`);
|
|
1912
|
+
}
|
|
1913
|
+
const group = new THREE.Group();
|
|
1914
|
+
group.name = id;
|
|
1915
|
+
group.visible = renderable.visible !== false;
|
|
1916
|
+
this.scene.add(group);
|
|
1917
|
+
this.objects.set(id, group);
|
|
1918
|
+
return;
|
|
1919
|
+
}
|
|
1920
|
+
const handle = kind.create(id, renderable, this.kindContext());
|
|
1921
|
+
const object = handle.object;
|
|
1922
|
+
object.name = id;
|
|
1923
|
+
object.visible = renderable.visible !== false;
|
|
1924
|
+
ThreeSceneBackend.applyShadows(object, renderable);
|
|
1925
|
+
this.scene.add(object);
|
|
1926
|
+
this.objects.set(id, object);
|
|
1927
|
+
this.handles.set(id, handle);
|
|
1928
|
+
}
|
|
1929
|
+
/** Apply a resolved material to every mesh under an object. */
|
|
1930
|
+
static dressMeshes(root, material) {
|
|
1931
|
+
root.traverse((obj) => {
|
|
1932
|
+
if (obj.isMesh) obj.material = material;
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
acquireGeometry(id, renderable) {
|
|
1936
|
+
const key = geometryKey(renderable);
|
|
1937
|
+
let entry = this.geometries.get(key);
|
|
1938
|
+
if (entry === void 0) {
|
|
1939
|
+
entry = {
|
|
1940
|
+
geometry: buildGeometry(renderable),
|
|
1941
|
+
refs: 0
|
|
1942
|
+
};
|
|
1943
|
+
this.geometries.set(key, entry);
|
|
1944
|
+
}
|
|
1945
|
+
entry.refs++;
|
|
1946
|
+
this.entityGeometry.set(id, key);
|
|
1947
|
+
return entry.geometry;
|
|
1948
|
+
}
|
|
1949
|
+
releaseGeometry(id) {
|
|
1950
|
+
const key = this.entityGeometry.get(id);
|
|
1951
|
+
if (key === void 0) return;
|
|
1952
|
+
this.entityGeometry.delete(id);
|
|
1953
|
+
const entry = this.geometries.get(key);
|
|
1954
|
+
if (entry === void 0) return;
|
|
1955
|
+
entry.refs--;
|
|
1956
|
+
if (entry.refs <= 0) {
|
|
1957
|
+
entry.geometry.dispose();
|
|
1958
|
+
this.geometries.delete(key);
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
/** Hand an already-acquired material to an entity, releasing whatever it held before. */
|
|
1962
|
+
assignMaterial(id, target, material) {
|
|
1963
|
+
this.batches?.remove(id);
|
|
1964
|
+
const previous = this.entityMaterial.get(id);
|
|
1965
|
+
if (previous !== void 0) this.materials.release(previous);
|
|
1966
|
+
this.entityMaterial.set(id, material);
|
|
1967
|
+
this.materialEpoch.set(id, ++this.epochSeq);
|
|
1968
|
+
ThreeSceneBackend.dressMeshes(target, material);
|
|
1969
|
+
this.batchDirty.add(id);
|
|
1970
|
+
}
|
|
1971
|
+
releaseMaterial(id) {
|
|
1972
|
+
const material = this.entityMaterial.get(id);
|
|
1973
|
+
if (material !== void 0) this.materials.release(material);
|
|
1974
|
+
this.entityMaterial.delete(id);
|
|
1975
|
+
this.entityMaterialRef.delete(id);
|
|
1976
|
+
this.materialEpoch.delete(id);
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* Resolve `materialRef` onto `target`: the sync material (palette, or the shared grey
|
|
1980
|
+
* placeholder) immediately, then the baked one once an async ref finishes. Refcounts are
|
|
1981
|
+
* balanced at every step so shared placeholders are never disposed out from under others.
|
|
1982
|
+
*/
|
|
1983
|
+
bindMaterial(id, target, materialRef) {
|
|
1984
|
+
this.entityMaterialRef.set(id, materialRef);
|
|
1985
|
+
this.assignMaterial(id, target, this.materials.acquireSync(materialRef));
|
|
1986
|
+
if (!this.materials.isAsync(materialRef)) return;
|
|
1987
|
+
const epoch = this.materialEpoch.get(id);
|
|
1988
|
+
const swap = this.materials.acquire(materialRef).then((material) => {
|
|
1989
|
+
if (this.materialEpoch.get(id) === epoch) this.assignMaterial(id, target, material);
|
|
1990
|
+
else this.materials.release(material);
|
|
1991
|
+
});
|
|
1992
|
+
this.assets?.track(swap);
|
|
1993
|
+
}
|
|
1994
|
+
static applyShadows(root, renderable) {
|
|
1995
|
+
const cast = renderable.shadows?.cast;
|
|
1996
|
+
const receive = renderable.shadows?.receive;
|
|
1997
|
+
root.traverse((obj) => {
|
|
1998
|
+
if (!obj.isMesh) return;
|
|
1999
|
+
obj.castShadow = cast ?? false;
|
|
2000
|
+
obj.receiveShadow = receive ?? false;
|
|
2001
|
+
});
|
|
2002
|
+
}
|
|
2003
|
+
create(id, renderable) {
|
|
2004
|
+
this.identities.set(id, this.identityOf(renderable));
|
|
2005
|
+
if (renderable.kind !== "gltf" && renderable.kind !== "primitive") {
|
|
2006
|
+
this.createKind(id, renderable);
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
if (renderable.kind === "gltf") {
|
|
2010
|
+
this.createGltf(id, renderable);
|
|
2011
|
+
return;
|
|
2012
|
+
}
|
|
2013
|
+
const mesh = new THREE.Mesh(this.acquireGeometry(id, renderable));
|
|
2014
|
+
this.bindMaterial(id, mesh, renderable.materialRef);
|
|
2015
|
+
mesh.visible = renderable.visible !== false;
|
|
2016
|
+
mesh.name = id;
|
|
2017
|
+
ThreeSceneBackend.applyShadows(mesh, renderable);
|
|
2018
|
+
this.scene.add(mesh);
|
|
2019
|
+
this.objects.set(id, mesh);
|
|
2020
|
+
this.batchDirty.add(id);
|
|
2021
|
+
}
|
|
2022
|
+
createGltf(id, renderable) {
|
|
2023
|
+
const group = new THREE.Group();
|
|
2024
|
+
group.name = id;
|
|
2025
|
+
group.visible = renderable.visible !== false;
|
|
2026
|
+
this.scene.add(group);
|
|
2027
|
+
this.objects.set(id, group);
|
|
2028
|
+
if (this.assets === void 0) {
|
|
2029
|
+
if (!this.warnedNoAssets) {
|
|
2030
|
+
this.warnedNoAssets = true;
|
|
2031
|
+
console.warn(`[molen] renderable kind "gltf" needs an asset provider (ClientOptions.assets) — "${renderable.ref}" renders nothing`);
|
|
2032
|
+
}
|
|
2033
|
+
return;
|
|
2034
|
+
}
|
|
2035
|
+
const binding = {
|
|
2036
|
+
token: 0,
|
|
2037
|
+
clips: [],
|
|
2038
|
+
clipDuration: 0,
|
|
2039
|
+
animation: renderable.animation
|
|
2040
|
+
};
|
|
2041
|
+
this.gltf.set(id, binding);
|
|
2042
|
+
const token = binding.token;
|
|
2043
|
+
const attach = this.assets.instance(renderable.ref, renderable.node).then(async ({ scene: instance, clips }) => {
|
|
2044
|
+
const current = this.gltf.get(id);
|
|
2045
|
+
const disposeSkeletons = () => instance.traverse((child) => {
|
|
2046
|
+
if (child.isSkinnedMesh) child.skeleton.dispose();
|
|
2047
|
+
});
|
|
2048
|
+
if (current !== binding || binding.token !== token) {
|
|
2049
|
+
disposeSkeletons();
|
|
2050
|
+
return;
|
|
2051
|
+
}
|
|
2052
|
+
if (renderable.materialRef !== void 0) this.bindMaterial(id, instance, renderable.materialRef);
|
|
2053
|
+
ThreeSceneBackend.applyShadows(instance, renderable);
|
|
2054
|
+
if (this.renderer && this.optimization.shaderWarmup !== false) try {
|
|
2055
|
+
await this.renderer.prepareObject(instance);
|
|
2056
|
+
} catch (error) {
|
|
2057
|
+
disposeSkeletons();
|
|
2058
|
+
throw error;
|
|
2059
|
+
}
|
|
2060
|
+
if (this.gltf.get(id) !== binding || binding.token !== token) {
|
|
2061
|
+
disposeSkeletons();
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
2064
|
+
group.add(instance);
|
|
2065
|
+
binding.clips = clips;
|
|
2066
|
+
this.bindModelSignals(id, instance);
|
|
2067
|
+
this.applyAnimation(id, binding, instance);
|
|
2068
|
+
this.applyModelSignals(id);
|
|
2069
|
+
this.batchDirty.add(id);
|
|
2070
|
+
}).catch((e) => {
|
|
2071
|
+
console.warn(`[molen] gltf "${renderable.ref}" failed to load: ${e.message}`);
|
|
2072
|
+
});
|
|
2073
|
+
this.assets.track(attach);
|
|
2074
|
+
}
|
|
2075
|
+
applyAnimation(id, binding, instance) {
|
|
2076
|
+
this.batches?.remove(id);
|
|
2077
|
+
this.animations.delete(id);
|
|
2078
|
+
this.lastPoseTick.delete(id);
|
|
2079
|
+
instance.traverse((object) => {
|
|
2080
|
+
object.matrixAutoUpdate = true;
|
|
2081
|
+
});
|
|
2082
|
+
const anim = binding.animation;
|
|
2083
|
+
binding.action?.stop();
|
|
2084
|
+
binding.action = void 0;
|
|
2085
|
+
binding.mixer = void 0;
|
|
2086
|
+
binding.clipDuration = 0;
|
|
2087
|
+
if (anim === void 0) return;
|
|
2088
|
+
const clip = binding.clips.find((c) => c.name === anim.clip);
|
|
2089
|
+
if (clip === void 0) {
|
|
2090
|
+
console.warn(`[molen] entity "${id}": gltf has no clip "${anim.clip}"`);
|
|
2091
|
+
return;
|
|
2092
|
+
}
|
|
2093
|
+
const mixer = new THREE.AnimationMixer(instance);
|
|
2094
|
+
const action = mixer.clipAction(clip);
|
|
2095
|
+
action.setLoop(THREE.LoopOnce, 1);
|
|
2096
|
+
action.clampWhenFinished = true;
|
|
2097
|
+
action.timeScale = 1;
|
|
2098
|
+
action.play();
|
|
2099
|
+
binding.mixer = mixer;
|
|
2100
|
+
binding.action = action;
|
|
2101
|
+
binding.clipDuration = clip.duration;
|
|
2102
|
+
this.animations.add(id);
|
|
2103
|
+
this.poseAnimation(binding);
|
|
2104
|
+
}
|
|
2105
|
+
updateRenderable(id, renderable) {
|
|
2106
|
+
this.batches?.remove(id);
|
|
2107
|
+
this.batchDirty.add(id);
|
|
2108
|
+
const identity = this.identityOf(renderable);
|
|
2109
|
+
if (this.identities.get(id) === identity) {
|
|
2110
|
+
const obj = this.objects.get(id);
|
|
2111
|
+
if (obj !== void 0) {
|
|
2112
|
+
obj.visible = renderable.visible !== false;
|
|
2113
|
+
ThreeSceneBackend.applyShadows(obj, renderable);
|
|
2114
|
+
this.handles.get(id)?.update(renderable);
|
|
2115
|
+
if (renderable.kind === "primitive" && this.entityMaterialRef.get(id) !== renderable.materialRef) this.bindMaterial(id, obj, renderable.materialRef);
|
|
2116
|
+
}
|
|
2117
|
+
const binding = this.gltf.get(id);
|
|
2118
|
+
if (binding !== void 0 && JSON.stringify(binding.animation) !== JSON.stringify(renderable.animation)) {
|
|
2119
|
+
binding.animation = renderable.animation;
|
|
2120
|
+
const instance = this.objects.get(id)?.children[0];
|
|
2121
|
+
if (instance !== void 0) {
|
|
2122
|
+
this.modelSignals.get(id)?.visual?.reset();
|
|
2123
|
+
this.applyAnimation(id, binding, instance);
|
|
2124
|
+
this.applyModelSignals(id);
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
return;
|
|
2128
|
+
}
|
|
2129
|
+
this.destroy(id);
|
|
2130
|
+
this.create(id, renderable);
|
|
2131
|
+
}
|
|
2132
|
+
/** Latest mirrored values are retained while the model loads. No simulation state is changed. */
|
|
2133
|
+
setModelSignals(id, spec, signals) {
|
|
2134
|
+
const previous = this.modelSignals.get(id);
|
|
2135
|
+
const key = spec === void 0 ? void 0 : JSON.stringify(spec);
|
|
2136
|
+
if (previous?.key === key) {
|
|
2137
|
+
if (previous) {
|
|
2138
|
+
previous.signals = signals;
|
|
2139
|
+
this.applyModelSignals(id);
|
|
2140
|
+
}
|
|
2141
|
+
return;
|
|
2142
|
+
}
|
|
2143
|
+
previous?.visual?.reset();
|
|
2144
|
+
this.modelSignals.delete(id);
|
|
2145
|
+
this.batches?.remove(id);
|
|
2146
|
+
this.batchDirty.add(id);
|
|
2147
|
+
if (spec !== void 0) {
|
|
2148
|
+
this.modelSignals.set(id, {
|
|
2149
|
+
key,
|
|
2150
|
+
spec,
|
|
2151
|
+
signals
|
|
2152
|
+
});
|
|
2153
|
+
const instance = this.gltf.has(id) ? this.objects.get(id)?.children[0] : void 0;
|
|
2154
|
+
if (instance) this.bindModelSignals(id, instance);
|
|
2155
|
+
} else {
|
|
2156
|
+
const animation = this.gltf.get(id);
|
|
2157
|
+
if (animation) {
|
|
2158
|
+
animation.action?.stop();
|
|
2159
|
+
this.poseAnimation(animation);
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
this.applyModelSignals(id);
|
|
2163
|
+
}
|
|
2164
|
+
bindModelSignals(id, instance) {
|
|
2165
|
+
const state = this.modelSignals.get(id);
|
|
2166
|
+
if (!state) return;
|
|
2167
|
+
const animation = this.gltf.get(id);
|
|
2168
|
+
animation?.action?.stop();
|
|
2169
|
+
state.visual = createModelSignalVisual(instance, state.spec);
|
|
2170
|
+
if (animation) this.poseAnimation(animation);
|
|
2171
|
+
if (state.visual.missingNodes.length) console.warn(`[molen] entity "${id}": model.signals missing nodes: ${state.visual.missingNodes.join(", ")}`);
|
|
2172
|
+
}
|
|
2173
|
+
applyModelSignals(id) {
|
|
2174
|
+
const state = this.modelSignals.get(id);
|
|
2175
|
+
state?.visual?.update(state.signals);
|
|
2176
|
+
}
|
|
2177
|
+
destroy(id) {
|
|
2178
|
+
this.modelSignals.delete(id);
|
|
2179
|
+
this.batches?.remove(id);
|
|
2180
|
+
this.batchDirty.delete(id);
|
|
2181
|
+
this.dynamic.delete(id);
|
|
2182
|
+
this.escaped.delete(id);
|
|
2183
|
+
this.transformed.delete(id);
|
|
2184
|
+
this.animations.delete(id);
|
|
2185
|
+
this.lastPoseTick.delete(id);
|
|
2186
|
+
const obj = this.objects.get(id);
|
|
2187
|
+
if (obj === void 0) return;
|
|
2188
|
+
this.scene.remove(obj);
|
|
2189
|
+
const handle = this.handles.get(id);
|
|
2190
|
+
if (handle !== void 0) {
|
|
2191
|
+
handle.dispose();
|
|
2192
|
+
this.handles.delete(id);
|
|
2193
|
+
}
|
|
2194
|
+
this.releaseGeometry(id);
|
|
2195
|
+
this.releaseMaterial(id);
|
|
2196
|
+
const binding = this.gltf.get(id);
|
|
2197
|
+
if (binding !== void 0) {
|
|
2198
|
+
binding.token++;
|
|
2199
|
+
binding.action?.stop();
|
|
2200
|
+
binding.mixer?.stopAllAction();
|
|
2201
|
+
obj.traverse((child) => {
|
|
2202
|
+
if (child.isSkinnedMesh) child.skeleton.dispose();
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
this.gltf.delete(id);
|
|
2206
|
+
this.objects.delete(id);
|
|
2207
|
+
this.identities.delete(id);
|
|
2208
|
+
}
|
|
2209
|
+
setTransform(id, t) {
|
|
2210
|
+
const obj = this.objects.get(id);
|
|
2211
|
+
if (obj !== void 0) {
|
|
2212
|
+
const scale = t.scale ?? [
|
|
2213
|
+
1,
|
|
2214
|
+
1,
|
|
2215
|
+
1
|
|
2216
|
+
];
|
|
2217
|
+
const changed = !obj.position.equals(new THREE.Vector3(...t.pos)) || !obj.quaternion.equals(new THREE.Quaternion(...t.rot)) || !obj.scale.equals(new THREE.Vector3(...scale));
|
|
2218
|
+
if (changed && this.transformed.has(id)) {
|
|
2219
|
+
this.dynamic.add(id);
|
|
2220
|
+
this.batches?.remove(id);
|
|
2221
|
+
}
|
|
2222
|
+
if (!this.transformed.has(id)) this.batchDirty.add(id);
|
|
2223
|
+
this.transformed.add(id);
|
|
2224
|
+
obj.position.set(t.pos[0], t.pos[1], t.pos[2]);
|
|
2225
|
+
obj.quaternion.set(t.rot[0], t.rot[1], t.rot[2], t.rot[3]);
|
|
2226
|
+
if (t.scale !== void 0) obj.scale.set(t.scale[0], t.scale[1], t.scale[2]);
|
|
2227
|
+
else obj.scale.set(1, 1, 1);
|
|
2228
|
+
if (changed || obj.matrixAutoUpdate) obj.updateMatrix();
|
|
2229
|
+
obj.matrixAutoUpdate = this.escaped.has(id);
|
|
2230
|
+
}
|
|
2231
|
+
const light = this.lights.get(id);
|
|
2232
|
+
if (light !== void 0) {
|
|
2233
|
+
light.position.set(t.pos[0], t.pos[1], t.pos[2]);
|
|
2234
|
+
light.updateMatrix();
|
|
2235
|
+
light.matrixAutoUpdate = false;
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
/** Per-entity `light` components (directional/spot aim at the origin by default). */
|
|
2239
|
+
createLight(id, data) {
|
|
2240
|
+
const light = buildLight(data);
|
|
2241
|
+
light.name = `${id}$light`;
|
|
2242
|
+
light.castShadow = data.castShadow === true;
|
|
2243
|
+
this.scene.add(light);
|
|
2244
|
+
this.lights.set(id, light);
|
|
2245
|
+
}
|
|
2246
|
+
updateLight(id, data) {
|
|
2247
|
+
this.destroyLight(id);
|
|
2248
|
+
this.createLight(id, data);
|
|
2249
|
+
}
|
|
2250
|
+
destroyLight(id) {
|
|
2251
|
+
const light = this.lights.get(id);
|
|
2252
|
+
if (light === void 0) return;
|
|
2253
|
+
this.scene.remove(light);
|
|
2254
|
+
light.dispose();
|
|
2255
|
+
this.lights.delete(id);
|
|
2256
|
+
}
|
|
2257
|
+
/** The singleton `environment` component; undefined restores the default rig. */
|
|
2258
|
+
setEnvironment(env) {
|
|
2259
|
+
if (this.renderer === void 0) return;
|
|
2260
|
+
applyEnvironment(this.renderer, env ?? defaultEnvironment);
|
|
2261
|
+
}
|
|
2262
|
+
setWeather(weather) {
|
|
2263
|
+
this.renderer?.setWeather(weather);
|
|
2264
|
+
}
|
|
2265
|
+
/** Standalone preview clock; connected clients use setAnimationTick with the kernel clock. */
|
|
2266
|
+
tickAnimations(dtSec) {
|
|
2267
|
+
this.setAnimationTick(this.animationTick + dtSec * this.animationTickRate, this.animationTickRate);
|
|
2268
|
+
}
|
|
2269
|
+
poseAnimation(binding) {
|
|
2270
|
+
if (binding.mixer === void 0 || binding.action === void 0 || binding.animation === void 0) return;
|
|
2271
|
+
binding.action.reset().play();
|
|
2272
|
+
binding.action.time = computeClipTime(binding.animation, this.animationTick, this.animationTickRate, binding.clipDuration);
|
|
2273
|
+
binding.mixer.update(0);
|
|
2274
|
+
}
|
|
2275
|
+
/** Live and capture poses use the same simulation tick and no wall-clock accumulation. */
|
|
2276
|
+
setAnimationTick(tick, tickRate) {
|
|
2277
|
+
this.renderer?.setEnvironmentTime(tick / tickRate);
|
|
2278
|
+
this.animationTick = tick;
|
|
2279
|
+
this.animationTickRate = tickRate;
|
|
2280
|
+
for (const id of this.animations) {
|
|
2281
|
+
const binding = this.gltf.get(id);
|
|
2282
|
+
if (binding) this.poseAnimation(binding);
|
|
2283
|
+
this.applyModelSignals(id);
|
|
2284
|
+
}
|
|
2285
|
+
for (const handle of this.handles.values()) handle.setTick?.(tick, tickRate, void 0);
|
|
2286
|
+
}
|
|
2287
|
+
/** Flush static membership only when bindings change; world-origin shifts move the common root. */
|
|
2288
|
+
prepareFrame() {
|
|
2289
|
+
for (const id of this.batchDirty) {
|
|
2290
|
+
const object = this.objects.get(id);
|
|
2291
|
+
if (!object || this.escaped.has(id) || this.handles.has(id)) continue;
|
|
2292
|
+
if (!this.animations.has(id) && !this.modelSignals.has(id)) object.traverse((child) => {
|
|
2293
|
+
child.updateMatrix();
|
|
2294
|
+
child.matrixAutoUpdate = false;
|
|
2295
|
+
});
|
|
2296
|
+
if (!this.dynamic.has(id) && !this.animations.has(id) && !this.modelSignals.has(id)) this.batches?.add(id, object);
|
|
2297
|
+
}
|
|
2298
|
+
this.batchDirty.clear();
|
|
2299
|
+
this.batches?.flush();
|
|
2300
|
+
}
|
|
2301
|
+
async whenReady() {
|
|
2302
|
+
this.prepareFrame();
|
|
2303
|
+
await this.batches?.whenIdle();
|
|
2304
|
+
await Promise.all([...this.pending]);
|
|
2305
|
+
}
|
|
2306
|
+
/** Exact tick-derived poses on return to view; invisible shadow casters are never skipped. */
|
|
2307
|
+
updateLiveAnimations(tick, tickRate, camera) {
|
|
2308
|
+
this.renderer?.setEnvironmentTime(tick / tickRate);
|
|
2309
|
+
this.animationTick = tick;
|
|
2310
|
+
this.animationTickRate = tickRate;
|
|
2311
|
+
camera.updateMatrixWorld();
|
|
2312
|
+
this.frustum.setFromProjectionMatrix(this.viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse), camera.coordinateSystem, camera.reversedDepth);
|
|
2313
|
+
const config = this.optimization.animation;
|
|
2314
|
+
for (const id of this.animations) {
|
|
2315
|
+
const binding = this.gltf.get(id), object = this.objects.get(id);
|
|
2316
|
+
if (!binding || !object) continue;
|
|
2317
|
+
let inView = false, shadows = false;
|
|
2318
|
+
object.updateWorldMatrix(true, true);
|
|
2319
|
+
object.traverseVisible((child) => {
|
|
2320
|
+
const mesh = child;
|
|
2321
|
+
if (mesh.isMesh) {
|
|
2322
|
+
shadows ||= mesh.castShadow;
|
|
2323
|
+
inView ||= this.frustum.intersectsObject(mesh);
|
|
2324
|
+
}
|
|
2325
|
+
});
|
|
2326
|
+
const distance = object.getWorldPosition(new THREE.Vector3()).distanceTo(camera.getWorldPosition(new THREE.Vector3()));
|
|
2327
|
+
const hz = config === false || shadows || inView && distance < (config?.distantDistance ?? 80) ? Infinity : inView ? config?.distantHz ?? 15 : config?.hiddenHz ?? 5;
|
|
2328
|
+
const previous = this.lastPoseTick.get(id);
|
|
2329
|
+
if (previous !== void 0 && tick >= previous && (tick - previous) / tickRate < 1 / hz) continue;
|
|
2330
|
+
this.poseAnimation(binding);
|
|
2331
|
+
this.applyModelSignals(id);
|
|
2332
|
+
this.lastPoseTick.set(id, tick);
|
|
2333
|
+
}
|
|
2334
|
+
for (const [id, handle] of this.handles) {
|
|
2335
|
+
if (handle.setTick === void 0) continue;
|
|
2336
|
+
const object = handle.object;
|
|
2337
|
+
let inView = false;
|
|
2338
|
+
let shadows = false;
|
|
2339
|
+
object.updateWorldMatrix(true, true);
|
|
2340
|
+
object.traverseVisible((child) => {
|
|
2341
|
+
const mesh = child;
|
|
2342
|
+
if (mesh.isMesh) {
|
|
2343
|
+
shadows ||= mesh.castShadow;
|
|
2344
|
+
inView ||= this.frustum.intersectsObject(mesh);
|
|
2345
|
+
}
|
|
2346
|
+
});
|
|
2347
|
+
const distance = object.getWorldPosition(new THREE.Vector3()).distanceTo(camera.getWorldPosition(new THREE.Vector3()));
|
|
2348
|
+
const distantDistance = config === false ? Infinity : config?.distantDistance ?? 80;
|
|
2349
|
+
const hz = config === false || shadows || inView && distance < distantDistance ? Infinity : inView ? config?.distantHz ?? 15 : config?.hiddenHz ?? 5;
|
|
2350
|
+
const previous = this.lastPoseTick.get(id);
|
|
2351
|
+
if (previous !== void 0 && tick >= previous && (tick - previous) / tickRate < 1 / hz) continue;
|
|
2352
|
+
handle.setTick(tick, tickRate, {
|
|
2353
|
+
distance,
|
|
2354
|
+
inView,
|
|
2355
|
+
shadows,
|
|
2356
|
+
distantDistance
|
|
2357
|
+
});
|
|
2358
|
+
this.lastPoseTick.set(id, tick);
|
|
2359
|
+
}
|
|
2360
|
+
this.updateLocalLights(camera);
|
|
2361
|
+
}
|
|
2362
|
+
updateLocalLights(camera) {
|
|
2363
|
+
const local = [];
|
|
2364
|
+
const cameraPosition = camera.getWorldPosition(new THREE.Vector3());
|
|
2365
|
+
for (const light of this.lights.values()) {
|
|
2366
|
+
if (!(light instanceof THREE.PointLight || light instanceof THREE.SpotLight)) continue;
|
|
2367
|
+
light.updateWorldMatrix(true, false);
|
|
2368
|
+
const center = light.getWorldPosition(new THREE.Vector3());
|
|
2369
|
+
const overlaps = light.distance === 0 || this.frustum.intersectsSphere(new THREE.Sphere(center, light.distance));
|
|
2370
|
+
light.visible = overlaps;
|
|
2371
|
+
if (overlaps) local.push({
|
|
2372
|
+
light,
|
|
2373
|
+
score: light.intensity / Math.max(1, center.distanceToSquared(cameraPosition))
|
|
2374
|
+
});
|
|
2375
|
+
}
|
|
2376
|
+
const cap = this.optimization.maxLocalLights;
|
|
2377
|
+
if (cap !== void 0) {
|
|
2378
|
+
local.sort((a, b) => b.score - a.score || a.light.id - b.light.id);
|
|
2379
|
+
for (let i = Math.max(0, Math.floor(cap)); i < local.length; i++) local[i].light.visible = false;
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
entityForIntersection(hit) {
|
|
2383
|
+
const ids = hit.object.userData.molenEntityIds;
|
|
2384
|
+
if (hit.instanceId !== void 0 && ids) return ids[hit.instanceId];
|
|
2385
|
+
for (let object = hit.object; object && object !== this.scene; object = object.parent) if (this.objects.get(object.name) === object) return object.name;
|
|
2386
|
+
}
|
|
2387
|
+
count() {
|
|
2388
|
+
return this.objects.size;
|
|
2389
|
+
}
|
|
2390
|
+
dispose() {
|
|
2391
|
+
this.batches?.dispose();
|
|
2392
|
+
for (const id of [...this.objects.keys()]) this.destroy(id);
|
|
2393
|
+
for (const id of [...this.lights.keys()]) this.destroyLight(id);
|
|
2394
|
+
for (const kind of this.kinds.values()) kind.dispose?.();
|
|
2395
|
+
this.kinds.clear();
|
|
2396
|
+
for (const entry of this.geometries.values()) entry.geometry.dispose();
|
|
2397
|
+
this.geometries.clear();
|
|
2398
|
+
this.entityGeometry.clear();
|
|
2399
|
+
this.materials.dispose();
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Escape hatch: the raw three.js object for an entity (undefined if not created), for advanced
|
|
2403
|
+
* effects the wrapper doesn't cover. Unstable — you own whatever you mutate, and the backend may
|
|
2404
|
+
* recreate the object when the renderable changes.
|
|
2405
|
+
*/
|
|
2406
|
+
getObject(id) {
|
|
2407
|
+
this.escaped.add(id);
|
|
2408
|
+
this.batches?.remove(id);
|
|
2409
|
+
this.batches?.flush();
|
|
2410
|
+
const object = this.objects.get(id);
|
|
2411
|
+
object?.traverse((child) => {
|
|
2412
|
+
child.matrixAutoUpdate = true;
|
|
2413
|
+
});
|
|
2414
|
+
return object;
|
|
2415
|
+
}
|
|
2416
|
+
/** The three.js world root this backend writes into (escape hatch for custom objects/lights). */
|
|
2417
|
+
get threeScene() {
|
|
2418
|
+
return this.scene;
|
|
2419
|
+
}
|
|
2420
|
+
};
|
|
2421
|
+
//#endregion
|
|
2422
|
+
//#region src/three/loaders.ts
|
|
2423
|
+
/**
|
|
2424
|
+
* A GLTFLoader with the meshopt decoder always attached (its WASM is inlined — zero hosting),
|
|
2425
|
+
* plus optional Draco/KTX2 support when decoder paths are configured. Canonical GLBs from
|
|
2426
|
+
* `molen asset import` are quantize+meshopt only, so most apps never configure paths.
|
|
2427
|
+
*/
|
|
2428
|
+
function createGltfLoader(renderer, config = {}) {
|
|
2429
|
+
const loader = new GLTFLoader();
|
|
2430
|
+
loader.setMeshoptDecoder(MeshoptDecoder);
|
|
2431
|
+
if (config.dracoDecoderPath !== void 0) {
|
|
2432
|
+
const draco = new DRACOLoader();
|
|
2433
|
+
draco.setDecoderPath(config.dracoDecoderPath);
|
|
2434
|
+
loader.setDRACOLoader(draco);
|
|
2435
|
+
}
|
|
2436
|
+
if (config.ktx2TranscoderPath !== void 0 && renderer !== void 0) {
|
|
2437
|
+
const ktx2 = new KTX2Loader();
|
|
2438
|
+
ktx2.setTranscoderPath(config.ktx2TranscoderPath);
|
|
2439
|
+
ktx2.detectSupport(renderer);
|
|
2440
|
+
loader.setKTX2Loader(ktx2);
|
|
2441
|
+
}
|
|
2442
|
+
return loader;
|
|
2443
|
+
}
|
|
2444
|
+
//#endregion
|
|
2445
|
+
//#region src/frame-admission.ts
|
|
2446
|
+
var FrameAdmissionQueue = class {
|
|
2447
|
+
options;
|
|
2448
|
+
jobs = [];
|
|
2449
|
+
scheduled = false;
|
|
2450
|
+
disposed = false;
|
|
2451
|
+
clock;
|
|
2452
|
+
schedule;
|
|
2453
|
+
maxMs;
|
|
2454
|
+
maxBytes;
|
|
2455
|
+
maxJobs;
|
|
2456
|
+
constructor(options = {}) {
|
|
2457
|
+
this.options = options;
|
|
2458
|
+
this.clock = options.now ?? (() => performance.now());
|
|
2459
|
+
this.schedule = options.schedule ?? ((callback) => {
|
|
2460
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(callback);
|
|
2461
|
+
else setTimeout(callback, 0);
|
|
2462
|
+
});
|
|
2463
|
+
this.maxMs = options.maxMilliseconds ?? 2;
|
|
2464
|
+
this.maxBytes = options.maxBytes ?? 2 * 1024 * 1024;
|
|
2465
|
+
this.maxJobs = options.maxJobs ?? 32;
|
|
2466
|
+
if (![
|
|
2467
|
+
this.maxMs,
|
|
2468
|
+
this.maxBytes,
|
|
2469
|
+
this.maxJobs
|
|
2470
|
+
].every((v) => Number.isFinite(v) && v > 0)) throw new RangeError("Admission budgets must be finite and positive");
|
|
2471
|
+
}
|
|
2472
|
+
run(task, options = {}) {
|
|
2473
|
+
if (this.disposed || options.signal?.aborted) return Promise.reject(new DOMException("Admission cancelled", "AbortError"));
|
|
2474
|
+
if (!Number.isFinite(options.bytes ?? 0) || (options.bytes ?? 0) < 0) return Promise.reject(/* @__PURE__ */ new RangeError("Admission bytes must be finite and nonnegative"));
|
|
2475
|
+
return new Promise((resolve, reject) => {
|
|
2476
|
+
const job = {
|
|
2477
|
+
run: task,
|
|
2478
|
+
resolve: (value) => resolve(value),
|
|
2479
|
+
reject,
|
|
2480
|
+
options,
|
|
2481
|
+
queued: this.clock()
|
|
2482
|
+
};
|
|
2483
|
+
job.abort = () => {
|
|
2484
|
+
const index = this.jobs.indexOf(job);
|
|
2485
|
+
if (index >= 0) {
|
|
2486
|
+
this.jobs.splice(index, 1);
|
|
2487
|
+
reject(new DOMException("Admission cancelled", "AbortError"));
|
|
2488
|
+
}
|
|
2489
|
+
};
|
|
2490
|
+
options.signal?.addEventListener("abort", job.abort, { once: true });
|
|
2491
|
+
this.jobs.push(job);
|
|
2492
|
+
this.request();
|
|
2493
|
+
});
|
|
2494
|
+
}
|
|
2495
|
+
get pending() {
|
|
2496
|
+
return this.jobs.length;
|
|
2497
|
+
}
|
|
2498
|
+
request() {
|
|
2499
|
+
if (this.scheduled || this.disposed || this.jobs.length === 0) return;
|
|
2500
|
+
this.scheduled = true;
|
|
2501
|
+
this.schedule(() => {
|
|
2502
|
+
this.scheduled = false;
|
|
2503
|
+
this.flush();
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
/** One frame's budget. Exposed for hosts with a manual frame loop and deterministic tests. */
|
|
2507
|
+
flush() {
|
|
2508
|
+
if (this.disposed) return;
|
|
2509
|
+
const start = this.clock();
|
|
2510
|
+
let bytes = 0, count = 0;
|
|
2511
|
+
while (this.jobs.length > 0) {
|
|
2512
|
+
const next = this.jobs[0];
|
|
2513
|
+
const cost = next.options.bytes ?? 0;
|
|
2514
|
+
if (count > 0 && (count >= this.maxJobs || this.clock() - start >= this.maxMs || bytes + cost > this.maxBytes)) break;
|
|
2515
|
+
this.jobs.shift();
|
|
2516
|
+
if (next.abort) next.options.signal?.removeEventListener("abort", next.abort);
|
|
2517
|
+
if (next.options.signal?.aborted) {
|
|
2518
|
+
next.reject(new DOMException("Admission cancelled", "AbortError"));
|
|
2519
|
+
continue;
|
|
2520
|
+
}
|
|
2521
|
+
const began = this.clock();
|
|
2522
|
+
try {
|
|
2523
|
+
next.resolve(next.run());
|
|
2524
|
+
} catch (error) {
|
|
2525
|
+
next.reject(error);
|
|
2526
|
+
}
|
|
2527
|
+
const workMs = this.clock() - began;
|
|
2528
|
+
count++;
|
|
2529
|
+
bytes += cost;
|
|
2530
|
+
this.options.onSample?.({
|
|
2531
|
+
label: next.options.label ?? "admission",
|
|
2532
|
+
queueMs: began - next.queued,
|
|
2533
|
+
workMs,
|
|
2534
|
+
bytes: cost,
|
|
2535
|
+
overBudget: workMs > this.maxMs || cost > this.maxBytes
|
|
2536
|
+
});
|
|
2537
|
+
}
|
|
2538
|
+
this.request();
|
|
2539
|
+
}
|
|
2540
|
+
dispose() {
|
|
2541
|
+
this.disposed = true;
|
|
2542
|
+
for (const job of this.jobs) {
|
|
2543
|
+
if (job.abort) job.options.signal?.removeEventListener("abort", job.abort);
|
|
2544
|
+
job.reject(new DOMException("Admission queue disposed", "AbortError"));
|
|
2545
|
+
}
|
|
2546
|
+
this.jobs = [];
|
|
2547
|
+
}
|
|
2548
|
+
};
|
|
2549
|
+
//#endregion
|
|
2550
|
+
//#region src/sky/astronomy.ts
|
|
2551
|
+
const RAD$2 = Math.PI / 180;
|
|
2552
|
+
const DAY_MS = 864e5;
|
|
2553
|
+
const EARTH_KM = 6378.137;
|
|
2554
|
+
const AU_KM = 149597870.7;
|
|
2555
|
+
const sin = (degrees) => Math.sin(degrees * RAD$2);
|
|
2556
|
+
const cos = (degrees) => Math.cos(degrees * RAD$2);
|
|
2557
|
+
const atan2 = (y, x) => Math.atan2(y, x) / RAD$2;
|
|
2558
|
+
const wrap$1 = (degrees) => (degrees % 360 + 360) % 360;
|
|
2559
|
+
/** Explicit, seekable simulation clock; no implicit Date.now or browser timezone. */
|
|
2560
|
+
function skyTimeMs(time, simulationSeconds = 0) {
|
|
2561
|
+
const utcMs = time.epochMs + simulationSeconds * (time.scale ?? 1) * 1e3;
|
|
2562
|
+
if (![
|
|
2563
|
+
time.epochMs,
|
|
2564
|
+
time.scale ?? 1,
|
|
2565
|
+
simulationSeconds,
|
|
2566
|
+
utcMs
|
|
2567
|
+
].every(Number.isFinite)) throw new Error("Sky time must be finite");
|
|
2568
|
+
if (utcMs < -22089888e5 || utcMs > 4133980799999) throw new Error("Earth sky supports UTC dates from 1900 through 2100");
|
|
2569
|
+
return utcMs;
|
|
2570
|
+
}
|
|
2571
|
+
/** Normalize without accepting zero or nonfinite vectors at the public rendering boundary. */
|
|
2572
|
+
function skyDirection(value) {
|
|
2573
|
+
const length = Math.hypot(...value);
|
|
2574
|
+
if (!Number.isFinite(length) || length === 0) throw new Error("Sky direction must be finite and nonzero");
|
|
2575
|
+
return [
|
|
2576
|
+
value[0] / length,
|
|
2577
|
+
value[1] / length,
|
|
2578
|
+
value[2] / length
|
|
2579
|
+
];
|
|
2580
|
+
}
|
|
2581
|
+
function orbit(anomaly, eccentricity, radius) {
|
|
2582
|
+
const mean = wrap$1(anomaly) * RAD$2;
|
|
2583
|
+
let eccentric = mean + eccentricity * Math.sin(mean);
|
|
2584
|
+
for (let i = 0; i < 5; i++) eccentric -= (eccentric - eccentricity * Math.sin(eccentric) - mean) / (1 - eccentricity * Math.cos(eccentric));
|
|
2585
|
+
const x = Math.cos(eccentric) - eccentricity;
|
|
2586
|
+
const y = Math.sqrt(1 - eccentricity * eccentricity) * Math.sin(eccentric);
|
|
2587
|
+
return {
|
|
2588
|
+
angle: atan2(y, x),
|
|
2589
|
+
radius: radius * Math.hypot(x, y)
|
|
2590
|
+
};
|
|
2591
|
+
}
|
|
2592
|
+
function ecliptic(longitude, latitude, radius, obliquity) {
|
|
2593
|
+
const x = radius * cos(longitude) * cos(latitude);
|
|
2594
|
+
const y = radius * sin(longitude) * cos(latitude);
|
|
2595
|
+
const z = radius * sin(latitude);
|
|
2596
|
+
return [
|
|
2597
|
+
x,
|
|
2598
|
+
y * cos(obliquity) - z * sin(obliquity),
|
|
2599
|
+
y * sin(obliquity) + z * cos(obliquity)
|
|
2600
|
+
];
|
|
2601
|
+
}
|
|
2602
|
+
function horizontal(vector, latitude, sidereal, northOffset) {
|
|
2603
|
+
const meridian = cos(sidereal) * vector[0] + sin(sidereal) * vector[1];
|
|
2604
|
+
const east = -sin(sidereal) * vector[0] + cos(sidereal) * vector[1];
|
|
2605
|
+
const north = -sin(latitude) * meridian + cos(latitude) * vector[2];
|
|
2606
|
+
const up = cos(latitude) * meridian + sin(latitude) * vector[2];
|
|
2607
|
+
return [
|
|
2608
|
+
east * cos(northOffset) + north * sin(northOffset),
|
|
2609
|
+
up,
|
|
2610
|
+
east * sin(northOffset) - north * cos(northOffset)
|
|
2611
|
+
];
|
|
2612
|
+
}
|
|
2613
|
+
function precess(vector, centuries) {
|
|
2614
|
+
const t = centuries;
|
|
2615
|
+
const zeta = (2306.2181 * t + .30188 * t * t + .017998 * t ** 3) / 3600;
|
|
2616
|
+
const z = (2306.2181 * t + 1.09468 * t * t + .018203 * t ** 3) / 3600;
|
|
2617
|
+
const theta = (2004.3109 * t - .42665 * t * t - .041833 * t ** 3) / 3600;
|
|
2618
|
+
const x = vector[0] * cos(zeta) - vector[1] * sin(zeta);
|
|
2619
|
+
const y = vector[0] * sin(zeta) + vector[1] * cos(zeta);
|
|
2620
|
+
const b = x * cos(theta) - vector[2] * sin(theta);
|
|
2621
|
+
return [
|
|
2622
|
+
b * cos(z) - y * sin(z),
|
|
2623
|
+
b * sin(z) + y * cos(z),
|
|
2624
|
+
x * sin(theta) + vector[2] * cos(theta)
|
|
2625
|
+
];
|
|
2626
|
+
}
|
|
2627
|
+
/**
|
|
2628
|
+
* Compact Earth ephemeris: Keplerian Sun + Moon with the major lunar perturbations,
|
|
2629
|
+
* ellipsoidal observer parallax, sidereal rotation and stellar precession.
|
|
2630
|
+
* Formula reference: https://www.stjarnhimlen.se/comp/ppcomp.html (Paul Schlyter).
|
|
2631
|
+
* Intended for visual skies, not navigation: no refraction, nutation, eclipses, or light time.
|
|
2632
|
+
*/
|
|
2633
|
+
function evaluateEarthSky(utcMs, observer) {
|
|
2634
|
+
skyTimeMs({ epochMs: utcMs });
|
|
2635
|
+
const { latitude, longitude } = observer;
|
|
2636
|
+
const elevation = observer.elevation ?? 0;
|
|
2637
|
+
const offset = observer.northOffsetDeg ?? 0;
|
|
2638
|
+
if (![
|
|
2639
|
+
latitude,
|
|
2640
|
+
longitude,
|
|
2641
|
+
elevation,
|
|
2642
|
+
offset
|
|
2643
|
+
].every(Number.isFinite) || Math.abs(latitude) > 90 || Math.abs(longitude) > 180 || elevation < -500 || elevation > 1e5) throw new Error("Invalid Earth sky observer");
|
|
2644
|
+
const julianDate = utcMs / DAY_MS + 2440587.5;
|
|
2645
|
+
const d = julianDate - 2451543.5;
|
|
2646
|
+
const t = (julianDate - 2451545) / 36525;
|
|
2647
|
+
const sidereal = wrap$1(280.46061837 + 360.98564736629 * (julianDate - 2451545) + 387933e-9 * t * t - t ** 3 / 3871e4 + longitude);
|
|
2648
|
+
const obliquity = 23.4393 - 3.563e-7 * d;
|
|
2649
|
+
const solarMean = wrap$1(356.047 + .9856002585 * d);
|
|
2650
|
+
const solarPerihelion = 282.9404 + 470935e-10 * d;
|
|
2651
|
+
const solarOrbit = orbit(solarMean, .016709 - 1.151e-9 * d, 1);
|
|
2652
|
+
const solarLongitude = solarOrbit.angle + solarPerihelion;
|
|
2653
|
+
const sunVector = ecliptic(solarLongitude, 0, solarOrbit.radius * AU_KM, obliquity);
|
|
2654
|
+
const node = wrap$1(125.1228 - .0529538083 * d);
|
|
2655
|
+
const perihelion = wrap$1(318.0634 + .1643573223 * d);
|
|
2656
|
+
const lunarMean = wrap$1(115.3654 + 13.0649929509 * d);
|
|
2657
|
+
const lunarOrbit = orbit(lunarMean, .0549, 60.2666);
|
|
2658
|
+
const argument = lunarOrbit.angle + perihelion;
|
|
2659
|
+
const x = cos(node) * cos(argument) - sin(node) * sin(argument) * cos(5.1454);
|
|
2660
|
+
const y = sin(node) * cos(argument) + cos(node) * sin(argument) * cos(5.1454);
|
|
2661
|
+
const z = sin(argument) * sin(5.1454);
|
|
2662
|
+
const elongation = lunarMean + perihelion + node - solarMean - solarPerihelion;
|
|
2663
|
+
const f = lunarMean + perihelion;
|
|
2664
|
+
const m = lunarMean;
|
|
2665
|
+
const s = solarMean;
|
|
2666
|
+
const e = elongation;
|
|
2667
|
+
const lunarLongitude = atan2(y, x) - 1.274 * sin(m - 2 * e) + .658 * sin(2 * e) - .186 * sin(s) - .059 * sin(2 * m - 2 * e) - .057 * sin(m - 2 * e + s) + .053 * sin(m + 2 * e) + .046 * sin(2 * e - s) + .041 * sin(m - s) - .035 * sin(e) - .031 * sin(m + s) - .015 * sin(2 * f - 2 * e) + .011 * sin(m - 4 * e);
|
|
2668
|
+
const moonVector = ecliptic(lunarLongitude, atan2(z, Math.hypot(x, y)) - .173 * sin(f - 2 * e) - .055 * sin(m - f - 2 * e) - .046 * sin(m + f - 2 * e) + .033 * sin(f + 2 * e) + .017 * sin(2 * m + f), (lunarOrbit.radius - .58 * cos(m - 2 * e) - .46 * cos(2 * e)) * EARTH_KM, obliquity);
|
|
2669
|
+
const n = EARTH_KM / Math.sqrt(1 - .00669437999014 * sin(latitude) ** 2);
|
|
2670
|
+
const rho = (n + elevation / 1e3) * cos(latitude);
|
|
2671
|
+
const observerVector = [
|
|
2672
|
+
rho * cos(sidereal),
|
|
2673
|
+
rho * sin(sidereal),
|
|
2674
|
+
(n * .99330562000986 + elevation / 1e3) * sin(latitude)
|
|
2675
|
+
];
|
|
2676
|
+
const position = (vector, radius) => {
|
|
2677
|
+
const local = horizontal([
|
|
2678
|
+
vector[0] - observerVector[0],
|
|
2679
|
+
vector[1] - observerVector[1],
|
|
2680
|
+
vector[2] - observerVector[2]
|
|
2681
|
+
], latitude, sidereal, 0);
|
|
2682
|
+
const distanceKm = Math.hypot(...local);
|
|
2683
|
+
return {
|
|
2684
|
+
direction: skyDirection(horizontal([
|
|
2685
|
+
vector[0] - observerVector[0],
|
|
2686
|
+
vector[1] - observerVector[1],
|
|
2687
|
+
vector[2] - observerVector[2]
|
|
2688
|
+
], latitude, sidereal, offset)),
|
|
2689
|
+
altitudeDeg: atan2(local[1], Math.hypot(local[0], local[2])),
|
|
2690
|
+
azimuthDeg: wrap$1(atan2(local[0], -local[2])),
|
|
2691
|
+
distanceKm,
|
|
2692
|
+
angularDiameterDeg: 2 * Math.asin(radius / distanceKm) / RAD$2
|
|
2693
|
+
};
|
|
2694
|
+
};
|
|
2695
|
+
const moonToSun = skyDirection([
|
|
2696
|
+
sunVector[0] - moonVector[0],
|
|
2697
|
+
sunVector[1] - moonVector[1],
|
|
2698
|
+
sunVector[2] - moonVector[2]
|
|
2699
|
+
]);
|
|
2700
|
+
const moonToObserver = skyDirection([
|
|
2701
|
+
observerVector[0] - moonVector[0],
|
|
2702
|
+
observerVector[1] - moonVector[1],
|
|
2703
|
+
observerVector[2] - moonVector[2]
|
|
2704
|
+
]);
|
|
2705
|
+
const illuminatedFraction = (1 + moonToSun.reduce((sum, value, i) => sum + value * (moonToObserver[i] ?? 0), 0)) / 2;
|
|
2706
|
+
const basis = (v) => horizontal(precess(v, t), latitude, sidereal, offset);
|
|
2707
|
+
return {
|
|
2708
|
+
utcMs,
|
|
2709
|
+
julianDate,
|
|
2710
|
+
sun: position(sunVector, 695700),
|
|
2711
|
+
moon: {
|
|
2712
|
+
...position(moonVector, 1737.4),
|
|
2713
|
+
illuminatedFraction,
|
|
2714
|
+
phase: wrap$1(lunarLongitude - solarLongitude) / 360
|
|
2715
|
+
},
|
|
2716
|
+
starBasis: [
|
|
2717
|
+
basis([
|
|
2718
|
+
1,
|
|
2719
|
+
0,
|
|
2720
|
+
0
|
|
2721
|
+
]),
|
|
2722
|
+
basis([
|
|
2723
|
+
0,
|
|
2724
|
+
1,
|
|
2725
|
+
0
|
|
2726
|
+
]),
|
|
2727
|
+
basis([
|
|
2728
|
+
0,
|
|
2729
|
+
0,
|
|
2730
|
+
1
|
|
2731
|
+
])
|
|
2732
|
+
]
|
|
2733
|
+
};
|
|
2734
|
+
}
|
|
2735
|
+
/** Map a catalog J2000 position (degrees) through a sampled Earth's star basis. */
|
|
2736
|
+
function starDirection(rightAscensionDeg, declinationDeg, state) {
|
|
2737
|
+
if (!Number.isFinite(rightAscensionDeg) || !Number.isFinite(declinationDeg) || Math.abs(declinationDeg) > 90) throw new Error("Invalid stellar coordinates");
|
|
2738
|
+
const equatorial = [
|
|
2739
|
+
cos(rightAscensionDeg) * cos(declinationDeg),
|
|
2740
|
+
sin(rightAscensionDeg) * cos(declinationDeg),
|
|
2741
|
+
sin(declinationDeg)
|
|
2742
|
+
];
|
|
2743
|
+
return [
|
|
2744
|
+
0,
|
|
2745
|
+
1,
|
|
2746
|
+
2
|
|
2747
|
+
].map((axis) => state.starBasis.reduce((sum, basis, i) => sum + (basis[axis] ?? 0) * (equatorial[i] ?? 0), 0));
|
|
2748
|
+
}
|
|
2749
|
+
//#endregion
|
|
2750
|
+
//#region src/sky/visual.ts
|
|
2751
|
+
const RAD$1 = Math.PI / 180;
|
|
2752
|
+
const clamp$2 = (x) => Math.max(0, Math.min(1, x));
|
|
2753
|
+
function smooth$1(a, b, x) {
|
|
2754
|
+
const t = clamp$2((x - a) / (b - a));
|
|
2755
|
+
return t * t * (3 - 2 * t);
|
|
2756
|
+
}
|
|
2757
|
+
const defaultSkyPalette = {
|
|
2758
|
+
dayZenith: "#2374c5",
|
|
2759
|
+
dayHorizon: "#b8d7eb",
|
|
2760
|
+
twilight: "#f78753",
|
|
2761
|
+
nightZenith: "#020510",
|
|
2762
|
+
nightHorizon: "#121c32",
|
|
2763
|
+
ground: "#18212c",
|
|
2764
|
+
sun: "#fff4dc",
|
|
2765
|
+
moon: "#dae5f5"
|
|
2766
|
+
};
|
|
2767
|
+
function mesh(geometry, order, transparent = false) {
|
|
2768
|
+
geometry.setAttribute("color", new THREE.Float32BufferAttribute(new Float32Array(geometry.getAttribute("position").count * 4), 4));
|
|
2769
|
+
const result = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
|
|
2770
|
+
vertexColors: true,
|
|
2771
|
+
side: THREE.DoubleSide,
|
|
2772
|
+
depthTest: false,
|
|
2773
|
+
depthWrite: false,
|
|
2774
|
+
fog: false,
|
|
2775
|
+
transparent
|
|
2776
|
+
}));
|
|
2777
|
+
result.renderOrder = order;
|
|
2778
|
+
result.frustumCulled = false;
|
|
2779
|
+
return result;
|
|
2780
|
+
}
|
|
2781
|
+
/** Seven vertices per star (a centre and six rim points), fanned into six triangles. */
|
|
2782
|
+
function starGeometry(count) {
|
|
2783
|
+
const geometry = new THREE.BufferGeometry();
|
|
2784
|
+
geometry.setAttribute("position", new THREE.Float32BufferAttribute(new Float32Array(count * 7 * 3), 3));
|
|
2785
|
+
const indices = [];
|
|
2786
|
+
for (let i = 0; i < count; i++) for (let j = 0; j < 6; j++) indices.push(i * 7, i * 7 + j + 1, i * 7 + (j + 1) % 6 + 1);
|
|
2787
|
+
geometry.setIndex(indices);
|
|
2788
|
+
return geometry;
|
|
2789
|
+
}
|
|
2790
|
+
/** Star colour from its B−V colour index. */
|
|
2791
|
+
function starColor(bv) {
|
|
2792
|
+
return new THREE.Color("#b6d1ff").lerp(new THREE.Color("#fff4e8"), smooth$1(-.3, .5, bv)).lerp(new THREE.Color("#ffb46c"), smooth$1(.5, 1.8, bv));
|
|
2793
|
+
}
|
|
2794
|
+
/**
|
|
2795
|
+
* Generic clear-sky dome, celestial spheres, batched stars and lighting, using standard
|
|
2796
|
+
* materials on WebGL and WebGPU. A separate background scene avoids far-plane, reverse-depth,
|
|
2797
|
+
* logarithmic-depth and floating-origin coupling. No textures, shaders or network requests.
|
|
2798
|
+
*/
|
|
2799
|
+
var SkyVisual = class {
|
|
2800
|
+
scene = new THREE.Scene();
|
|
2801
|
+
camera = new THREE.PerspectiveCamera(60, 1, .01, 10);
|
|
2802
|
+
lights = new THREE.Group();
|
|
2803
|
+
sunLight = new THREE.DirectionalLight();
|
|
2804
|
+
moonLight = new THREE.DirectionalLight();
|
|
2805
|
+
ambientLight = new THREE.HemisphereLight();
|
|
2806
|
+
data;
|
|
2807
|
+
dome = mesh(new THREE.SphereGeometry(2, 96, 48), -100);
|
|
2808
|
+
sun = mesh(new THREE.SphereGeometry(1, 32, 16), -70, true);
|
|
2809
|
+
moon = mesh(new THREE.SphereGeometry(1, 64, 32), -60, true);
|
|
2810
|
+
stars;
|
|
2811
|
+
catalog;
|
|
2812
|
+
palette;
|
|
2813
|
+
lastTime;
|
|
2814
|
+
cloudAttenuation = 0;
|
|
2815
|
+
currentFrame;
|
|
2816
|
+
disposed = false;
|
|
2817
|
+
constructor(data, options = {}) {
|
|
2818
|
+
this.data = skySchema.parse(data);
|
|
2819
|
+
if (this.data.mode === "custom") {
|
|
2820
|
+
skyDirection(this.data.sunBody.direction);
|
|
2821
|
+
if (this.data.moonBody) skyDirection(this.data.moonBody.direction);
|
|
2822
|
+
}
|
|
2823
|
+
this.palette = Object.fromEntries(Object.entries({
|
|
2824
|
+
...defaultSkyPalette,
|
|
2825
|
+
...data.palette
|
|
2826
|
+
}).map(([key, value]) => [key, new THREE.Color(value)]));
|
|
2827
|
+
this.scene.name = "molen:sky";
|
|
2828
|
+
this.lights.name = "molen:sky-lights";
|
|
2829
|
+
this.dome.name = "molen:sky-dome";
|
|
2830
|
+
this.sun.name = "molen:sky-sun";
|
|
2831
|
+
this.moon.name = "molen:sky-moon";
|
|
2832
|
+
this.catalog = this.catalogFrom(options.stars);
|
|
2833
|
+
this.stars = mesh(starGeometry(this.catalog.length), -80, true);
|
|
2834
|
+
this.stars.material.blending = THREE.AdditiveBlending;
|
|
2835
|
+
this.stars.name = "molen:sky-stars";
|
|
2836
|
+
this.scene.add(this.dome, this.stars, this.sun, this.moon);
|
|
2837
|
+
this.lights.add(this.ambientLight, this.sunLight, this.sunLight.target, this.moonLight, this.moonLight.target);
|
|
2838
|
+
const shadows = options.shadows ?? "off";
|
|
2839
|
+
if (shadows !== "off" && data.lighting?.castShadow !== false) {
|
|
2840
|
+
this.sunLight.castShadow = true;
|
|
2841
|
+
const size = {
|
|
2842
|
+
low: 1024,
|
|
2843
|
+
medium: 2048,
|
|
2844
|
+
high: 4096
|
|
2845
|
+
}[shadows];
|
|
2846
|
+
this.sunLight.shadow.mapSize.set(size, size);
|
|
2847
|
+
Object.assign(this.sunLight.shadow.camera, {
|
|
2848
|
+
near: .5,
|
|
2849
|
+
far: 500,
|
|
2850
|
+
left: -50,
|
|
2851
|
+
right: 50,
|
|
2852
|
+
top: 50,
|
|
2853
|
+
bottom: -50
|
|
2854
|
+
});
|
|
2855
|
+
this.sunLight.shadow.camera.updateProjectionMatrix();
|
|
2856
|
+
}
|
|
2857
|
+
this.update(0);
|
|
2858
|
+
}
|
|
2859
|
+
get frame() {
|
|
2860
|
+
return this.currentFrame;
|
|
2861
|
+
}
|
|
2862
|
+
/** Diffuse cloud lighting; actual celestial occlusion comes from the cloud layer geometry. */
|
|
2863
|
+
setCloudAttenuation(value) {
|
|
2864
|
+
const next = clamp$2(value);
|
|
2865
|
+
if (next === this.cloudAttenuation) return;
|
|
2866
|
+
this.cloudAttenuation = next;
|
|
2867
|
+
this.lastTime = void 0;
|
|
2868
|
+
}
|
|
2869
|
+
/** Move an Earth observer without rebuilding the dome, bodies or star catalog. */
|
|
2870
|
+
setObserver(observer) {
|
|
2871
|
+
if (this.disposed) throw new Error("SkyVisual has been disposed");
|
|
2872
|
+
if (this.data.mode !== "earth") throw new Error("Only Earth skies have an observer");
|
|
2873
|
+
const next = skySchema.parse({
|
|
2874
|
+
...this.data,
|
|
2875
|
+
observer
|
|
2876
|
+
});
|
|
2877
|
+
if (next.mode === "earth") this.data.observer = next.observer;
|
|
2878
|
+
this.lastTime = void 0;
|
|
2879
|
+
}
|
|
2880
|
+
/** Seek in simulation seconds. Earth render samples use a stable one-second UTC grid. */
|
|
2881
|
+
update(simulationSeconds) {
|
|
2882
|
+
if (this.disposed) throw new Error("SkyVisual has been disposed");
|
|
2883
|
+
if (!Number.isFinite(simulationSeconds)) throw new Error("Sky simulation time must be finite");
|
|
2884
|
+
const data = this.data;
|
|
2885
|
+
const time = data.mode === "earth" ? Math.floor(skyTimeMs(data.time, simulationSeconds) / 1e3) * 1e3 : 0;
|
|
2886
|
+
if (time === this.lastTime) return this.currentFrame;
|
|
2887
|
+
this.lastTime = time;
|
|
2888
|
+
const earth = data.mode === "earth" ? evaluateEarthSky(time, data.observer) : void 0;
|
|
2889
|
+
const sunDirection = earth?.sun.direction ?? skyDirection(data.mode === "custom" ? data.sunBody.direction : [
|
|
2890
|
+
0,
|
|
2891
|
+
1,
|
|
2892
|
+
0
|
|
2893
|
+
]);
|
|
2894
|
+
const moonDirection = earth?.moon.direction ?? (data.mode === "custom" && data.moonBody ? skyDirection(data.moonBody.direction) : void 0);
|
|
2895
|
+
const sunVector = new THREE.Vector3(...sunDirection);
|
|
2896
|
+
const moonVector = moonDirection ? new THREE.Vector3(...moonDirection) : void 0;
|
|
2897
|
+
const moonIllumination = earth?.moon.illuminatedFraction ?? (moonVector ? (1 - moonVector.dot(sunVector)) / 2 : 0);
|
|
2898
|
+
const altitude = Math.asin(sunDirection[1]) / RAD$1;
|
|
2899
|
+
const daylight = smooth$1(-12, 8, altitude);
|
|
2900
|
+
const starVisibility = (1 - smooth$1(-18, -4, altitude)) * (1 - .65 * moonIllumination * smooth$1(0, .5, moonDirection?.[1] ?? -1));
|
|
2901
|
+
const sunDiameterDeg = earth?.sun.angularDiameterDeg ?? (data.mode === "custom" ? data.sunBody.angularDiameterDeg ?? .53 : .53);
|
|
2902
|
+
const moonDiameterDeg = earth?.moon.angularDiameterDeg ?? (data.mode === "custom" ? data.moonBody?.angularDiameterDeg ?? .53 : .53);
|
|
2903
|
+
this.currentFrame = {
|
|
2904
|
+
sunDirection,
|
|
2905
|
+
...moonDirection ? { moonDirection } : {},
|
|
2906
|
+
sunDiameterDeg,
|
|
2907
|
+
moonDiameterDeg,
|
|
2908
|
+
moonIllumination,
|
|
2909
|
+
daylight,
|
|
2910
|
+
starVisibility,
|
|
2911
|
+
...earth ? { earth } : {}
|
|
2912
|
+
};
|
|
2913
|
+
this.updateDome(altitude, sunVector, daylight);
|
|
2914
|
+
this.updateBody(this.sun, sunVector, sunDiameterDeg * (data.sun?.size ?? 1), sunVector, false);
|
|
2915
|
+
this.sun.visible = data.sun?.visible !== false && this.sun.visible;
|
|
2916
|
+
this.moon.visible = false;
|
|
2917
|
+
if (moonVector && data.moon?.visible !== false) this.updateBody(this.moon, moonVector, moonDiameterDeg * (data.moon?.size ?? 1), sunVector, true);
|
|
2918
|
+
const rotation = new THREE.Matrix4();
|
|
2919
|
+
if (earth) rotation.makeBasis(...earth.starBasis.map((v) => new THREE.Vector3(...v)));
|
|
2920
|
+
else if (data.mode === "custom") rotation.makeRotationFromEuler(new THREE.Euler(...(data.starRotationDeg ?? [
|
|
2921
|
+
0,
|
|
2922
|
+
0,
|
|
2923
|
+
0
|
|
2924
|
+
]).map((v) => v * RAD$1)));
|
|
2925
|
+
this.updateStars(rotation, starVisibility, moonVector, moonDiameterDeg * (data.moon?.size ?? 1));
|
|
2926
|
+
const light = data.lighting;
|
|
2927
|
+
this.sunLight.color.copy(this.palette.sun).lerp(this.palette.twilight, 1 - smooth$1(0, 18, altitude));
|
|
2928
|
+
this.sunLight.intensity = (light?.sunIntensity ?? 3) * smooth$1(-.8, 8, altitude);
|
|
2929
|
+
this.moonLight.color.copy(this.palette.moon);
|
|
2930
|
+
this.moonLight.intensity = (light?.moonIntensity ?? .12) * moonIllumination * smooth$1(0, .2, moonDirection?.[1] ?? -1) * (1 - daylight);
|
|
2931
|
+
this.ambientLight.color.copy(this.palette.nightHorizon).lerp(this.palette.dayHorizon, daylight);
|
|
2932
|
+
this.ambientLight.groundColor.copy(this.palette.ground);
|
|
2933
|
+
this.ambientLight.intensity = (light?.nightAmbient ?? .025) * (1 - daylight) + (light?.dayAmbient ?? .6) * daylight;
|
|
2934
|
+
this.sunLight.intensity *= 1 - this.cloudAttenuation * .92;
|
|
2935
|
+
this.moonLight.intensity *= 1 - this.cloudAttenuation * .9;
|
|
2936
|
+
this.ambientLight.intensity *= 1 - this.cloudAttenuation * .2;
|
|
2937
|
+
this.ambientLight.color.lerp(new THREE.Color("#b9c2cb"), this.cloudAttenuation * daylight * .6);
|
|
2938
|
+
return this.currentFrame;
|
|
2939
|
+
}
|
|
2940
|
+
/** Copy view orientation/projection only; celestial bodies never translate with the camera. */
|
|
2941
|
+
prepareCamera(camera) {
|
|
2942
|
+
camera.updateWorldMatrix(true, false);
|
|
2943
|
+
camera.getWorldQuaternion(this.camera.quaternion);
|
|
2944
|
+
if (camera instanceof THREE.PerspectiveCamera) {
|
|
2945
|
+
this.camera.projectionMatrix.copy(camera.projectionMatrix);
|
|
2946
|
+
this.camera.fov = camera.fov;
|
|
2947
|
+
this.camera.aspect = camera.aspect;
|
|
2948
|
+
this.camera.zoom = camera.zoom;
|
|
2949
|
+
this.camera.filmGauge = camera.filmGauge;
|
|
2950
|
+
this.camera.filmOffset = camera.filmOffset;
|
|
2951
|
+
this.camera.view = camera.view ? { ...camera.view } : null;
|
|
2952
|
+
} else if (camera instanceof THREE.OrthographicCamera) {
|
|
2953
|
+
this.camera.fov = 60;
|
|
2954
|
+
this.camera.aspect = (camera.right - camera.left) / (camera.top - camera.bottom);
|
|
2955
|
+
this.camera.zoom = 1;
|
|
2956
|
+
this.camera.filmOffset = 0;
|
|
2957
|
+
this.camera.view = null;
|
|
2958
|
+
}
|
|
2959
|
+
this.camera.coordinateSystem = camera.coordinateSystem;
|
|
2960
|
+
this.camera.updateProjectionMatrix();
|
|
2961
|
+
this.camera.updateMatrixWorld();
|
|
2962
|
+
const center = camera.getWorldPosition(new THREE.Vector3());
|
|
2963
|
+
this.sunLight.target.position.copy(center);
|
|
2964
|
+
this.sunLight.position.copy(center).addScaledVector(new THREE.Vector3(...this.frame.sunDirection), 200);
|
|
2965
|
+
this.moonLight.target.position.copy(center);
|
|
2966
|
+
this.moonLight.position.copy(center).addScaledVector(new THREE.Vector3(...this.frame.moonDirection ?? [
|
|
2967
|
+
0,
|
|
2968
|
+
-1,
|
|
2969
|
+
0
|
|
2970
|
+
]), 200);
|
|
2971
|
+
}
|
|
2972
|
+
updateDome(altitude, sun, daylight) {
|
|
2973
|
+
const colors = this.dome.geometry.getAttribute("color");
|
|
2974
|
+
const positions = this.dome.geometry.getAttribute("position");
|
|
2975
|
+
const horizon = this.palette.nightHorizon.clone().lerp(this.palette.dayHorizon, daylight);
|
|
2976
|
+
const zenith = this.palette.nightZenith.clone().lerp(this.palette.dayZenith, daylight);
|
|
2977
|
+
const twilight = smooth$1(-18, -4, altitude) * (1 - smooth$1(0, 16, altitude));
|
|
2978
|
+
const color = new THREE.Color();
|
|
2979
|
+
const dir = new THREE.Vector3();
|
|
2980
|
+
for (let i = 0; i < positions.count; i++) {
|
|
2981
|
+
dir.fromBufferAttribute(positions, i).normalize();
|
|
2982
|
+
color.copy(horizon).lerp(zenith, clamp$2(dir.y) ** .45);
|
|
2983
|
+
const nearSun = clamp$2((dir.dot(sun) + 1) / 2) ** 8;
|
|
2984
|
+
color.lerp(this.palette.twilight, twilight * Math.exp(-Math.abs(dir.y) * 7) * (.25 + .7 * nearSun));
|
|
2985
|
+
if (dir.y < 0) color.lerp(this.palette.ground.clone().multiplyScalar(.08 + daylight * .92), smooth$1(0, .2, -dir.y));
|
|
2986
|
+
const glow = clamp$2(dir.dot(sun)) ** 96 * smooth$1(-2, 5, altitude) * .22;
|
|
2987
|
+
color.lerp(this.palette.sun, glow);
|
|
2988
|
+
colors.setXYZW(i, color.r, color.g, color.b, 1);
|
|
2989
|
+
}
|
|
2990
|
+
colors.needsUpdate = true;
|
|
2991
|
+
}
|
|
2992
|
+
updateBody(body, direction, diameter, sun, lunar) {
|
|
2993
|
+
const radius = Math.sin(Math.min(170, diameter) * RAD$1 / 2);
|
|
2994
|
+
body.position.copy(direction);
|
|
2995
|
+
body.scale.setScalar(radius);
|
|
2996
|
+
body.visible = direction.y + radius > 0;
|
|
2997
|
+
const positions = body.geometry.getAttribute("position");
|
|
2998
|
+
const colors = body.geometry.getAttribute("color");
|
|
2999
|
+
const base = lunar ? this.palette.moon : this.palette.sun.clone().lerp(this.palette.twilight, 1 - smooth$1(0, .2, direction.y));
|
|
3000
|
+
const normal = new THREE.Vector3();
|
|
3001
|
+
for (let i = 0; i < positions.count; i++) {
|
|
3002
|
+
normal.fromBufferAttribute(positions, i).normalize();
|
|
3003
|
+
const illumination = lunar ? (this.data.moon?.earthshine ?? .025) + Math.max(0, normal.dot(sun)) * .975 : 2.5;
|
|
3004
|
+
const albedo = lunar ? .85 + .15 * Math.sin(normal.x * 27 + Math.sin(normal.y * 19) * 2) * Math.sin(normal.z * 21) : 1;
|
|
3005
|
+
colors.setXYZW(i, base.r * illumination * albedo, base.g * illumination * albedo, base.b * illumination * albedo, smooth$1(-3e-4, 3e-4, direction.y + normal.y * radius));
|
|
3006
|
+
}
|
|
3007
|
+
colors.needsUpdate = true;
|
|
3008
|
+
body.material.side = THREE.FrontSide;
|
|
3009
|
+
}
|
|
3010
|
+
/**
|
|
3011
|
+
* Replace the star catalog, e.g. once a catalog loaded from a content pack arrives. `undefined`
|
|
3012
|
+
* removes the stars. Takes effect on the next update.
|
|
3013
|
+
*/
|
|
3014
|
+
setStars(stars) {
|
|
3015
|
+
if (this.disposed) throw new Error("SkyVisual has been disposed");
|
|
3016
|
+
this.catalog = this.catalogFrom(stars);
|
|
3017
|
+
const previous = this.stars.geometry;
|
|
3018
|
+
this.stars.geometry = starGeometry(this.catalog.length);
|
|
3019
|
+
const colors = this.stars.geometry.getAttribute("position").count * 4;
|
|
3020
|
+
this.stars.geometry.setAttribute("color", new THREE.Float32BufferAttribute(new Float32Array(colors), 4));
|
|
3021
|
+
previous.dispose();
|
|
3022
|
+
this.lastTime = void 0;
|
|
3023
|
+
}
|
|
3024
|
+
catalogFrom(stars) {
|
|
3025
|
+
const limit = this.data.stars?.magnitudeLimit ?? 6;
|
|
3026
|
+
if (this.data.stars?.enabled === false || stars === void 0) return [];
|
|
3027
|
+
return stars.filter((s) => s.magnitude <= limit).map((s) => {
|
|
3028
|
+
if (!Number.isFinite(s.magnitude)) throw new Error("Star magnitude must be finite");
|
|
3029
|
+
return {
|
|
3030
|
+
direction: new THREE.Vector3(...skyDirection(s.direction)),
|
|
3031
|
+
color: new THREE.Color(s.color ?? "#ffffff"),
|
|
3032
|
+
magnitude: s.magnitude
|
|
3033
|
+
};
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
3036
|
+
updateStars(rotation, visibility, moon, moonDiameter) {
|
|
3037
|
+
this.stars.visible = visibility > 0 && this.catalog.length > 0;
|
|
3038
|
+
if (!this.stars.visible) return;
|
|
3039
|
+
const positions = this.stars.geometry.getAttribute("position");
|
|
3040
|
+
const colors = this.stars.geometry.getAttribute("color");
|
|
3041
|
+
const d = new THREE.Vector3(), right = new THREE.Vector3(), up = new THREE.Vector3(), p = new THREE.Vector3();
|
|
3042
|
+
const pole = new THREE.Vector3(0, 1, 0);
|
|
3043
|
+
for (const [i, star] of this.catalog.entries()) {
|
|
3044
|
+
d.copy(star.direction).applyMatrix4(rotation).normalize();
|
|
3045
|
+
right.crossVectors(Math.abs(d.y) > .99 ? new THREE.Vector3(1, 0, 0) : pole, d).normalize();
|
|
3046
|
+
up.crossVectors(d, right);
|
|
3047
|
+
const size = (8e-4 + 45e-5 * Math.max(0, 6 - star.magnitude)) * (this.data.stars?.size ?? 1);
|
|
3048
|
+
const alpha = moon && this.data.moon?.visible !== false && d.dot(moon) > Math.cos(Math.min(170, moonDiameter) * RAD$1 / 2) ? 0 : visibility * smooth$1(0, .06, d.y) * (this.data.stars?.intensity ?? 1);
|
|
3049
|
+
const brightness = Math.min(3, 10 ** (-.2 * (star.magnitude - 2)));
|
|
3050
|
+
for (let j = 0; j < 7; j++) {
|
|
3051
|
+
p.copy(d);
|
|
3052
|
+
if (j > 0) p.addScaledVector(right, size * Math.cos((j - 1) * Math.PI / 3)).addScaledVector(up, size * Math.sin((j - 1) * Math.PI / 3));
|
|
3053
|
+
positions.setXYZ(i * 7 + j, p.x, p.y, p.z);
|
|
3054
|
+
colors.setXYZW(i * 7 + j, star.color.r * brightness, star.color.g * brightness, star.color.b * brightness, j === 0 ? alpha : 0);
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
positions.needsUpdate = true;
|
|
3058
|
+
colors.needsUpdate = true;
|
|
3059
|
+
}
|
|
3060
|
+
dispose() {
|
|
3061
|
+
if (this.disposed) return;
|
|
3062
|
+
this.disposed = true;
|
|
3063
|
+
for (const object of [
|
|
3064
|
+
this.dome,
|
|
3065
|
+
this.sun,
|
|
3066
|
+
this.moon,
|
|
3067
|
+
this.stars
|
|
3068
|
+
]) {
|
|
3069
|
+
object.geometry.dispose();
|
|
3070
|
+
object.material.dispose();
|
|
3071
|
+
}
|
|
3072
|
+
for (const light of [
|
|
3073
|
+
this.sunLight,
|
|
3074
|
+
this.moonLight,
|
|
3075
|
+
this.ambientLight
|
|
3076
|
+
]) light.dispose();
|
|
3077
|
+
this.lights.removeFromParent();
|
|
3078
|
+
this.lights.clear();
|
|
3079
|
+
this.scene.clear();
|
|
3080
|
+
}
|
|
3081
|
+
};
|
|
3082
|
+
//#endregion
|
|
3083
|
+
//#region src/weather/visual.ts
|
|
3084
|
+
const clamp$1 = (x) => Math.max(0, Math.min(1, x));
|
|
3085
|
+
const wrap = (x, size) => (x % size + size) % size;
|
|
3086
|
+
function smooth(a, b, x) {
|
|
3087
|
+
const t = clamp$1((x - a) / (b - a));
|
|
3088
|
+
return t * t * (3 - 2 * t);
|
|
3089
|
+
}
|
|
3090
|
+
function hash(x, y, seed) {
|
|
3091
|
+
let h = Math.imul(x ^ seed, 374761393) ^ Math.imul(y, 668265263);
|
|
3092
|
+
h = Math.imul(h ^ h >>> 13, 1274126177);
|
|
3093
|
+
return ((h ^ h >>> 16) >>> 0) / 4294967296;
|
|
3094
|
+
}
|
|
3095
|
+
function noise(x, y, period, seed) {
|
|
3096
|
+
const ix = Math.floor(x), iy = Math.floor(y);
|
|
3097
|
+
const fx = smooth(0, 1, x - ix), fy = smooth(0, 1, y - iy);
|
|
3098
|
+
const a = hash(wrap(ix, period), wrap(iy, period), seed);
|
|
3099
|
+
const b = hash(wrap(ix + 1, period), wrap(iy, period), seed);
|
|
3100
|
+
const c = hash(wrap(ix, period), wrap(iy + 1, period), seed);
|
|
3101
|
+
const d = hash(wrap(ix + 1, period), wrap(iy + 1, period), seed);
|
|
3102
|
+
return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
|
|
3103
|
+
}
|
|
3104
|
+
const CLOUD_RESOLUTION = 256;
|
|
3105
|
+
const PARTICLE_LIMIT = 1400;
|
|
3106
|
+
/**
|
|
3107
|
+
* Lightweight layered clouds and local precipitation with standard materials on both graphics
|
|
3108
|
+
* backends. Patterns are seeded and sampled at absolute simulation time, not integrated frames.
|
|
3109
|
+
* Cloud layers use absolute world altitudes; particles are visual and do not accumulate or collide.
|
|
3110
|
+
*/
|
|
3111
|
+
var WeatherVisual = class {
|
|
3112
|
+
object = new THREE.Group();
|
|
3113
|
+
fog = new THREE.Fog("#c1c9cd", 0, 5e4);
|
|
3114
|
+
state;
|
|
3115
|
+
cloudNoise;
|
|
3116
|
+
cloudTexture;
|
|
3117
|
+
cloudLayers = [];
|
|
3118
|
+
cloudKey = "";
|
|
3119
|
+
noiseSeed;
|
|
3120
|
+
particles;
|
|
3121
|
+
particleTexture;
|
|
3122
|
+
cameraPosition = new THREE.Vector3();
|
|
3123
|
+
right = new THREE.Vector3();
|
|
3124
|
+
up = new THREE.Vector3();
|
|
3125
|
+
color = new THREE.Color();
|
|
3126
|
+
disposed = false;
|
|
3127
|
+
constructor(data) {
|
|
3128
|
+
this.state = resolveWeather$1(weatherSchema.parse(data));
|
|
3129
|
+
this.object.name = "molen:weather";
|
|
3130
|
+
}
|
|
3131
|
+
/** Resolved copy; editing it does not change the visual. */
|
|
3132
|
+
get data() {
|
|
3133
|
+
return resolveWeather$1(this.state);
|
|
3134
|
+
}
|
|
3135
|
+
/** Replace weather while retaining geometry, particles and cached noise. */
|
|
3136
|
+
setData(data) {
|
|
3137
|
+
if (this.disposed) throw new Error("WeatherVisual has been disposed");
|
|
3138
|
+
this.state = resolveWeather$1(weatherSchema.parse(data));
|
|
3139
|
+
}
|
|
3140
|
+
get cloudAttenuation() {
|
|
3141
|
+
return this.state.clouds.coverage * this.state.clouds.density;
|
|
3142
|
+
}
|
|
3143
|
+
get stats() {
|
|
3144
|
+
return {
|
|
3145
|
+
cloudLayers: this.cloudLayers.filter((layer) => layer.visible).length,
|
|
3146
|
+
particles: this.particles?.visible ? this.particles.geometry.drawRange.count / 6 : 0
|
|
3147
|
+
};
|
|
3148
|
+
}
|
|
3149
|
+
/** Update camera-relative geometry using the renderer's absolute floating origin. */
|
|
3150
|
+
update(seconds, camera, origin, sky) {
|
|
3151
|
+
if (this.disposed) throw new Error("WeatherVisual has been disposed");
|
|
3152
|
+
if (!Number.isFinite(seconds)) throw new Error("Weather time must be finite");
|
|
3153
|
+
camera.updateWorldMatrix(true, false);
|
|
3154
|
+
camera.getWorldPosition(this.cameraPosition);
|
|
3155
|
+
this.right.setFromMatrixColumn(camera.matrixWorld, 0).normalize();
|
|
3156
|
+
this.up.setFromMatrixColumn(camera.matrixWorld, 1).normalize();
|
|
3157
|
+
const daylight = sky?.daylight ?? 1;
|
|
3158
|
+
this.updateClouds(seconds, camera, origin, daylight, sky?.sunDirection ?? [
|
|
3159
|
+
.3,
|
|
3160
|
+
.8,
|
|
3161
|
+
.2
|
|
3162
|
+
]);
|
|
3163
|
+
this.updateParticles(seconds, origin, daylight);
|
|
3164
|
+
this.object.updateMatrixWorld(true);
|
|
3165
|
+
}
|
|
3166
|
+
/** Combine weather visibility with an authored/streaming fog limit without mutating it. */
|
|
3167
|
+
fogFor(base, sky) {
|
|
3168
|
+
const visibility = this.state.visibility;
|
|
3169
|
+
if (base instanceof THREE.Fog && base.far <= visibility) return base;
|
|
3170
|
+
if (base instanceof THREE.FogExp2 && base.density >= 2 / visibility) return base;
|
|
3171
|
+
this.fog.near = Math.min(visibility * .035, base instanceof THREE.Fog ? base.near : 400);
|
|
3172
|
+
this.fog.far = Math.min(visibility, base instanceof THREE.Fog ? base.far : Infinity);
|
|
3173
|
+
this.fog.near = Math.min(this.fog.near, this.fog.far * .1);
|
|
3174
|
+
if (base) this.fog.color.copy(base.color);
|
|
3175
|
+
else this.fog.color.set("#0b1220").lerp(this.color.set("#c1c9cd"), sky?.daylight ?? 1);
|
|
3176
|
+
return this.fog;
|
|
3177
|
+
}
|
|
3178
|
+
buildClouds() {
|
|
3179
|
+
const texture = new THREE.DataTexture(new Uint8Array(CLOUD_RESOLUTION ** 2 * 4), CLOUD_RESOLUTION, CLOUD_RESOLUTION);
|
|
3180
|
+
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
|
|
3181
|
+
texture.magFilter = THREE.LinearFilter;
|
|
3182
|
+
texture.minFilter = THREE.LinearMipmapLinearFilter;
|
|
3183
|
+
texture.generateMipmaps = true;
|
|
3184
|
+
texture.colorSpace = THREE.LinearSRGBColorSpace;
|
|
3185
|
+
this.cloudTexture = texture;
|
|
3186
|
+
for (let i = 0; i < 2; i++) {
|
|
3187
|
+
const geometry = new THREE.PlaneGeometry(1, 1, 24, 24);
|
|
3188
|
+
geometry.rotateX(-Math.PI / 2);
|
|
3189
|
+
const positions = geometry.getAttribute("position");
|
|
3190
|
+
const colors = new Float32Array(positions.count * 4);
|
|
3191
|
+
for (let j = 0; j < positions.count; j++) {
|
|
3192
|
+
const r = Math.max(Math.abs(positions.getX(j)), Math.abs(positions.getZ(j))) * 2;
|
|
3193
|
+
colors.set([
|
|
3194
|
+
1,
|
|
3195
|
+
1,
|
|
3196
|
+
1,
|
|
3197
|
+
1 - smooth(.6, 1, r)
|
|
3198
|
+
], j * 4);
|
|
3199
|
+
}
|
|
3200
|
+
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 4));
|
|
3201
|
+
const map = i === 0 ? texture : texture.clone();
|
|
3202
|
+
const material = new THREE.MeshBasicMaterial({
|
|
3203
|
+
map,
|
|
3204
|
+
vertexColors: true,
|
|
3205
|
+
transparent: true,
|
|
3206
|
+
side: THREE.DoubleSide,
|
|
3207
|
+
depthWrite: false,
|
|
3208
|
+
fog: false
|
|
3209
|
+
});
|
|
3210
|
+
const layer = new THREE.Mesh(geometry, material);
|
|
3211
|
+
layer.name = `molen:cloud-layer-${i}`;
|
|
3212
|
+
layer.frustumCulled = false;
|
|
3213
|
+
this.cloudLayers.push(layer);
|
|
3214
|
+
this.object.add(layer);
|
|
3215
|
+
}
|
|
3216
|
+
}
|
|
3217
|
+
updateClouds(seconds, camera, origin, daylight, sun) {
|
|
3218
|
+
const { clouds, seed, atmosphere } = this.state;
|
|
3219
|
+
const visible = clouds.coverage > 0 && clouds.density > 0;
|
|
3220
|
+
if (visible && !this.cloudTexture) this.buildClouds();
|
|
3221
|
+
for (const layer of this.cloudLayers) layer.visible = visible;
|
|
3222
|
+
if (!visible) return;
|
|
3223
|
+
if (seed !== this.noiseSeed) {
|
|
3224
|
+
this.noiseSeed = seed;
|
|
3225
|
+
this.cloudKey = "";
|
|
3226
|
+
this.cloudNoise = new Float32Array(CLOUD_RESOLUTION ** 2);
|
|
3227
|
+
for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
|
|
3228
|
+
let value = 0, weight = 0;
|
|
3229
|
+
for (let octave = 0; octave < 5; octave++) {
|
|
3230
|
+
const frequency = 8 * 2 ** octave, amplitude = .5 ** octave;
|
|
3231
|
+
value += noise(x / CLOUD_RESOLUTION * frequency, y / CLOUD_RESOLUTION * frequency, frequency, seed + octave) * amplitude;
|
|
3232
|
+
weight += amplitude;
|
|
3233
|
+
}
|
|
3234
|
+
this.cloudNoise[y * CLOUD_RESOLUTION + x] = value / weight;
|
|
3235
|
+
}
|
|
3236
|
+
}
|
|
3237
|
+
const key = `${clouds.coverage},${clouds.density},${sun.map((v) => Math.round(v * 20)).join(",")}`;
|
|
3238
|
+
if (key !== this.cloudKey && this.cloudTexture && this.cloudNoise) {
|
|
3239
|
+
this.cloudKey = key;
|
|
3240
|
+
const pixels = this.cloudTexture.image.data;
|
|
3241
|
+
const field = this.cloudNoise;
|
|
3242
|
+
const threshold = .78 - clouds.coverage * .62;
|
|
3243
|
+
for (let y = 0; y < CLOUD_RESOLUTION; y++) for (let x = 0; x < CLOUD_RESOLUTION; x++) {
|
|
3244
|
+
const i = y * CLOUD_RESOLUTION + x, n = field[i] ?? 0;
|
|
3245
|
+
const dx = (field[y * CLOUD_RESOLUTION + (x + 1) % CLOUD_RESOLUTION] ?? n) - n;
|
|
3246
|
+
const dz = (field[(y + 1) % CLOUD_RESOLUTION * CLOUD_RESOLUTION + x] ?? n) - n;
|
|
3247
|
+
const shade = clamp$1(.56 + (1 - smooth(threshold, threshold + .25, n)) * .3 + (dx * sun[0] + dz * sun[2]) * 4 - clouds.density * .15);
|
|
3248
|
+
const alpha = smooth(threshold - .075, threshold + .075, n) * (1 - Math.exp(-clouds.density * 6));
|
|
3249
|
+
pixels.set([
|
|
3250
|
+
shade * 255,
|
|
3251
|
+
shade * 255,
|
|
3252
|
+
shade * 255,
|
|
3253
|
+
alpha * 255
|
|
3254
|
+
], i * 4);
|
|
3255
|
+
}
|
|
3256
|
+
for (const layer of this.cloudLayers) if (layer.material.map) layer.material.map.needsUpdate = true;
|
|
3257
|
+
}
|
|
3258
|
+
const far = camera instanceof THREE.PerspectiveCamera || camera instanceof THREE.OrthographicCamera ? camera.far : 5e4;
|
|
3259
|
+
const size = Math.max(2e3, Math.min(16e4, far * 1.4));
|
|
3260
|
+
const absoluteX = this.cameraPosition.x + origin[0], absoluteZ = this.cameraPosition.z + origin[2];
|
|
3261
|
+
this.color.set("#101829").lerp(new THREE.Color("#e4e9ee"), daylight);
|
|
3262
|
+
const sunset = (1 - smooth(0, .3, Math.abs(sun[1]))) * smooth(-.15, .05, sun[1]);
|
|
3263
|
+
this.color.lerp(new THREE.Color("#f6b88d"), sunset * .55);
|
|
3264
|
+
this.color.multiplyScalar(1 + daylight * 1.8);
|
|
3265
|
+
for (const [i, layer] of this.cloudLayers.entries()) {
|
|
3266
|
+
layer.position.set(this.cameraPosition.x, clouds.baseAltitude + i * clouds.thickness - origin[1], this.cameraPosition.z);
|
|
3267
|
+
layer.scale.set(size, 1, size);
|
|
3268
|
+
layer.material.color.copy(this.color);
|
|
3269
|
+
const map = layer.material.map;
|
|
3270
|
+
const scale = clouds.scale * (1 + i * .35);
|
|
3271
|
+
map.repeat.set(size / scale, size / scale);
|
|
3272
|
+
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));
|
|
3273
|
+
}
|
|
3274
|
+
}
|
|
3275
|
+
buildParticles() {
|
|
3276
|
+
const geometry = new THREE.BufferGeometry();
|
|
3277
|
+
geometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(PARTICLE_LIMIT * 4 * 3), 3).setUsage(THREE.DynamicDrawUsage));
|
|
3278
|
+
const uv = new Float32Array(PARTICLE_LIMIT * 4 * 2);
|
|
3279
|
+
const indices = [];
|
|
3280
|
+
for (let i = 0; i < PARTICLE_LIMIT; i++) {
|
|
3281
|
+
uv.set([
|
|
3282
|
+
0,
|
|
3283
|
+
0,
|
|
3284
|
+
1,
|
|
3285
|
+
0,
|
|
3286
|
+
1,
|
|
3287
|
+
1,
|
|
3288
|
+
0,
|
|
3289
|
+
1
|
|
3290
|
+
], i * 8);
|
|
3291
|
+
const n = i * 4;
|
|
3292
|
+
indices.push(n, n + 1, n + 2, n, n + 2, n + 3);
|
|
3293
|
+
}
|
|
3294
|
+
geometry.setAttribute("uv", new THREE.BufferAttribute(uv, 2));
|
|
3295
|
+
geometry.setIndex(indices);
|
|
3296
|
+
const pixels = new Uint8Array(1024 * 4);
|
|
3297
|
+
for (let y = 0; y < 32; y++) for (let x = 0; x < 32; x++) {
|
|
3298
|
+
const r = Math.hypot((x - 15.5) / 15.5, (y - 15.5) / 15.5);
|
|
3299
|
+
pixels.set([
|
|
3300
|
+
255,
|
|
3301
|
+
255,
|
|
3302
|
+
255,
|
|
3303
|
+
(1 - smooth(.15, 1, r)) * 255
|
|
3304
|
+
], (y * 32 + x) * 4);
|
|
3305
|
+
}
|
|
3306
|
+
this.particleTexture = new THREE.DataTexture(pixels, 32, 32);
|
|
3307
|
+
this.particleTexture.magFilter = THREE.LinearFilter;
|
|
3308
|
+
this.particleTexture.needsUpdate = true;
|
|
3309
|
+
this.particles = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
|
|
3310
|
+
map: this.particleTexture,
|
|
3311
|
+
transparent: true,
|
|
3312
|
+
depthWrite: false,
|
|
3313
|
+
side: THREE.DoubleSide,
|
|
3314
|
+
opacity: .65
|
|
3315
|
+
}));
|
|
3316
|
+
this.particles.name = "molen:precipitation";
|
|
3317
|
+
this.particles.frustumCulled = false;
|
|
3318
|
+
this.object.add(this.particles);
|
|
3319
|
+
}
|
|
3320
|
+
updateParticles(seconds, origin, daylight) {
|
|
3321
|
+
const { precipitation: p, seed, atmosphere: a } = this.state;
|
|
3322
|
+
const count = p.kind === "none" ? 0 : Math.round(PARTICLE_LIMIT * p.intensity);
|
|
3323
|
+
if (count > 0 && !this.particles) this.buildParticles();
|
|
3324
|
+
if (!this.particles) return;
|
|
3325
|
+
this.particles.visible = count > 0;
|
|
3326
|
+
this.particles.geometry.setDrawRange(0, count * 6);
|
|
3327
|
+
if (!count) return;
|
|
3328
|
+
const rain = p.kind === "rain";
|
|
3329
|
+
this.particles.material.color.set("#6c809c").lerp(this.color.set("#f2f6ff"), daylight);
|
|
3330
|
+
this.particles.material.color.multiplyScalar(1 + daylight * 2);
|
|
3331
|
+
this.particles.material.opacity = rain ? .42 : .85;
|
|
3332
|
+
const positions = this.particles.geometry.getAttribute("position");
|
|
3333
|
+
const c = this.cameraPosition;
|
|
3334
|
+
const width = 52, height = 34;
|
|
3335
|
+
const absolute = [
|
|
3336
|
+
c.x + origin[0],
|
|
3337
|
+
c.y + origin[1],
|
|
3338
|
+
c.z + origin[2]
|
|
3339
|
+
];
|
|
3340
|
+
for (let i = 0; i < count; i++) {
|
|
3341
|
+
const r = hash(i, 0, seed), s = hash(i, 1, seed), t = hash(i, 2, seed);
|
|
3342
|
+
const fall = rain ? 13 + r * 7 : .8 + r * .8;
|
|
3343
|
+
const x = c.x + wrap(r * width + a.windVelocity[0] * seconds - (absolute[0] ?? 0) + width / 2, width) - width / 2;
|
|
3344
|
+
const y = c.y + wrap(t * height + (a.windVelocity[1] - fall) * seconds - (absolute[1] ?? 0) + height / 2, height) - height / 2;
|
|
3345
|
+
const z = c.z + wrap(s * width + a.windVelocity[2] * seconds - (absolute[2] ?? 0) + width / 2, width) - width / 2;
|
|
3346
|
+
const halfWidth = rain ? .009 + r * .009 : .035 + r * .055;
|
|
3347
|
+
const halfLength = rain ? .35 + r * .25 : halfWidth;
|
|
3348
|
+
const ux = rain ? -a.windVelocity[0] / fall : this.up.x;
|
|
3349
|
+
const uy = rain ? 1 : this.up.y;
|
|
3350
|
+
const uz = rain ? -a.windVelocity[2] / fall : this.up.z;
|
|
3351
|
+
const flutterX = rain ? 0 : Math.sin(seconds * 1.2 + r * 30) * .7;
|
|
3352
|
+
const flutterZ = rain ? 0 : Math.cos(seconds * .8 + s * 30) * .6;
|
|
3353
|
+
for (let j = 0; j < 4; j++) {
|
|
3354
|
+
const side = j === 0 || j === 3 ? -1 : 1, top = j < 2 ? -1 : 1;
|
|
3355
|
+
positions.setXYZ(i * 4 + j, x + flutterX + this.right.x * halfWidth * side + ux * halfLength * top, y + this.right.y * halfWidth * side + uy * halfLength * top, z + flutterZ + this.right.z * halfWidth * side + uz * halfLength * top);
|
|
3356
|
+
}
|
|
3357
|
+
}
|
|
3358
|
+
positions.needsUpdate = true;
|
|
3359
|
+
}
|
|
3360
|
+
dispose() {
|
|
3361
|
+
if (this.disposed) return;
|
|
3362
|
+
this.disposed = true;
|
|
3363
|
+
for (const layer of this.cloudLayers) {
|
|
3364
|
+
layer.geometry.dispose();
|
|
3365
|
+
layer.material.map?.dispose();
|
|
3366
|
+
layer.material.dispose();
|
|
3367
|
+
}
|
|
3368
|
+
this.particles?.geometry.dispose();
|
|
3369
|
+
this.particles?.material.dispose();
|
|
3370
|
+
this.particleTexture?.dispose();
|
|
3371
|
+
this.object.removeFromParent();
|
|
3372
|
+
this.object.clear();
|
|
3373
|
+
}
|
|
3374
|
+
};
|
|
3375
|
+
//#endregion
|
|
3376
|
+
//#region src/three/gpu-frame-timer.ts
|
|
3377
|
+
/**
|
|
3378
|
+
* Optional WebGL2 timing. Reads a result only after QUERY_RESULT_AVAILABLE; never waits,
|
|
3379
|
+
* flushes, finishes, or schedules polling. Unavailable extensions return undefined.
|
|
3380
|
+
* Context restoration reacquires the extension and starts with fresh query objects.
|
|
3381
|
+
*/
|
|
3382
|
+
function createGpuFrameTimer(context, options = {}) {
|
|
3383
|
+
const capacity = options.maxPendingQueries ?? 4;
|
|
3384
|
+
const interval = options.sampleEveryFrames ?? 4;
|
|
3385
|
+
for (const [name, value] of [["maxPendingQueries", capacity], ["sampleEveryFrames", interval]]) if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive integer`);
|
|
3386
|
+
if (!("createQuery" in context)) return;
|
|
3387
|
+
const gl = context;
|
|
3388
|
+
const acquireExtension = () => {
|
|
3389
|
+
if (gl.isContextLost()) return;
|
|
3390
|
+
const ext = gl.getExtension("EXT_disjoint_timer_query_webgl2");
|
|
3391
|
+
if (!ext) return;
|
|
3392
|
+
const bits = gl.getQuery(ext.TIME_ELAPSED_EXT, ext.QUERY_COUNTER_BITS_EXT);
|
|
3393
|
+
if (typeof bits !== "number" || !Number.isFinite(bits) || bits <= 0) return;
|
|
3394
|
+
return ext;
|
|
3395
|
+
};
|
|
3396
|
+
let extension = acquireExtension();
|
|
3397
|
+
if (!extension) return;
|
|
3398
|
+
let disposed = false;
|
|
3399
|
+
let lost = false;
|
|
3400
|
+
let untilSample = 0;
|
|
3401
|
+
let active;
|
|
3402
|
+
const pending = [];
|
|
3403
|
+
const abandon = (contextLost) => {
|
|
3404
|
+
if (active) {
|
|
3405
|
+
if (!contextLost && extension) {
|
|
3406
|
+
if (gl.getQuery(extension.TIME_ELAPSED_EXT, gl.CURRENT_QUERY) === active) gl.endQuery(extension.TIME_ELAPSED_EXT);
|
|
3407
|
+
gl.deleteQuery(active);
|
|
3408
|
+
}
|
|
3409
|
+
active = void 0;
|
|
3410
|
+
}
|
|
3411
|
+
if (!contextLost) for (const query of pending) gl.deleteQuery(query);
|
|
3412
|
+
pending.length = 0;
|
|
3413
|
+
untilSample = 0;
|
|
3414
|
+
};
|
|
3415
|
+
const onContextLost = () => {
|
|
3416
|
+
lost = true;
|
|
3417
|
+
abandon(true);
|
|
3418
|
+
extension = void 0;
|
|
3419
|
+
};
|
|
3420
|
+
const onContextRestored = () => {
|
|
3421
|
+
if (disposed) return;
|
|
3422
|
+
lost = false;
|
|
3423
|
+
extension = acquireExtension();
|
|
3424
|
+
};
|
|
3425
|
+
const usable = () => {
|
|
3426
|
+
if (disposed || lost) return false;
|
|
3427
|
+
if (gl.isContextLost()) {
|
|
3428
|
+
onContextLost();
|
|
3429
|
+
return false;
|
|
3430
|
+
}
|
|
3431
|
+
return extension !== void 0;
|
|
3432
|
+
};
|
|
3433
|
+
const discardDisjoint = () => {
|
|
3434
|
+
if (!extension || !gl.getParameter(extension.GPU_DISJOINT_EXT)) return false;
|
|
3435
|
+
abandon(false);
|
|
3436
|
+
return true;
|
|
3437
|
+
};
|
|
3438
|
+
gl.canvas.addEventListener("webglcontextlost", onContextLost);
|
|
3439
|
+
gl.canvas.addEventListener("webglcontextrestored", onContextRestored);
|
|
3440
|
+
return {
|
|
3441
|
+
begin() {
|
|
3442
|
+
if (!usable() || !extension || active) return false;
|
|
3443
|
+
if (untilSample > 0) {
|
|
3444
|
+
untilSample--;
|
|
3445
|
+
return false;
|
|
3446
|
+
}
|
|
3447
|
+
if (pending.length >= capacity || discardDisjoint()) return false;
|
|
3448
|
+
if (gl.getQuery(extension.TIME_ELAPSED_EXT, gl.CURRENT_QUERY) !== null) return false;
|
|
3449
|
+
const query = gl.createQuery();
|
|
3450
|
+
if (!query) return false;
|
|
3451
|
+
active = query;
|
|
3452
|
+
gl.beginQuery(extension.TIME_ELAPSED_EXT, query);
|
|
3453
|
+
untilSample = interval - 1;
|
|
3454
|
+
return true;
|
|
3455
|
+
},
|
|
3456
|
+
end() {
|
|
3457
|
+
if (!usable() || !extension || !active) return;
|
|
3458
|
+
const query = active;
|
|
3459
|
+
active = void 0;
|
|
3460
|
+
if (gl.getQuery(extension.TIME_ELAPSED_EXT, gl.CURRENT_QUERY) !== query) {
|
|
3461
|
+
gl.deleteQuery(query);
|
|
3462
|
+
return;
|
|
3463
|
+
}
|
|
3464
|
+
gl.endQuery(extension.TIME_ELAPSED_EXT);
|
|
3465
|
+
pending.push(query);
|
|
3466
|
+
},
|
|
3467
|
+
poll() {
|
|
3468
|
+
if (!usable() || !extension || pending.length === 0 && !active) return;
|
|
3469
|
+
if (discardDisjoint()) return;
|
|
3470
|
+
let latest;
|
|
3471
|
+
while (pending.length > 0) {
|
|
3472
|
+
const query = pending[0];
|
|
3473
|
+
if (!query || !gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE)) break;
|
|
3474
|
+
const nanos = gl.getQueryParameter(query, gl.QUERY_RESULT);
|
|
3475
|
+
gl.deleteQuery(query);
|
|
3476
|
+
pending.shift();
|
|
3477
|
+
if (typeof nanos === "number" && Number.isFinite(nanos) && nanos >= 0) latest = nanos / 1e6;
|
|
3478
|
+
}
|
|
3479
|
+
return latest;
|
|
3480
|
+
},
|
|
3481
|
+
dispose() {
|
|
3482
|
+
if (disposed) return;
|
|
3483
|
+
disposed = true;
|
|
3484
|
+
abandon(lost || gl.isContextLost());
|
|
3485
|
+
gl.canvas.removeEventListener("webglcontextlost", onContextLost);
|
|
3486
|
+
gl.canvas.removeEventListener("webglcontextrestored", onContextRestored);
|
|
3487
|
+
extension = void 0;
|
|
3488
|
+
}
|
|
3489
|
+
};
|
|
3490
|
+
}
|
|
3491
|
+
//#endregion
|
|
3492
|
+
//#region src/three/renderer.ts
|
|
3493
|
+
/** Orthographic half-extents for a vertical view extent at an aspect ratio (pure; testable). */
|
|
3494
|
+
function orthoFrustum(viewHeight, aspect) {
|
|
3495
|
+
if (!Number.isFinite(viewHeight) || viewHeight <= 0) throw new Error("viewHeight must be finite and positive");
|
|
3496
|
+
if (!Number.isFinite(aspect) || aspect <= 0) throw new Error("aspect must be finite and positive");
|
|
3497
|
+
const halfH = viewHeight / 2;
|
|
3498
|
+
return {
|
|
3499
|
+
halfW: halfH * aspect,
|
|
3500
|
+
halfH
|
|
3501
|
+
};
|
|
3502
|
+
}
|
|
3503
|
+
/** Pure automatic-origin policy, exported so hosts can predict and test rebases without WebGL. */
|
|
3504
|
+
function nextWorldOrigin(current, cameraPosition, options) {
|
|
3505
|
+
if (!Number.isFinite(options.threshold) || options.threshold <= 0) throw new Error("automatic world-origin threshold must be finite and positive");
|
|
3506
|
+
if (options.gridSize !== void 0 && (!Number.isFinite(options.gridSize) || options.gridSize <= 0)) throw new Error("automatic world-origin gridSize must be finite and positive");
|
|
3507
|
+
if (!current.every(Number.isFinite) || !cameraPosition.every(Number.isFinite)) throw new Error("automatic world-origin positions must contain finite numbers");
|
|
3508
|
+
const dx = cameraPosition[0] - current[0];
|
|
3509
|
+
const dy = options.includeY === true ? cameraPosition[1] - current[1] : 0;
|
|
3510
|
+
const dz = cameraPosition[2] - current[2];
|
|
3511
|
+
if (Math.hypot(dx, dy, dz) <= options.threshold) return void 0;
|
|
3512
|
+
const snap = (value) => options.gridSize === void 0 ? value : Math.round(value / options.gridSize) * options.gridSize;
|
|
3513
|
+
return [
|
|
3514
|
+
snap(cameraPosition[0]),
|
|
3515
|
+
options.includeY === true ? snap(cameraPosition[1]) : current[1],
|
|
3516
|
+
snap(cameraPosition[2])
|
|
3517
|
+
];
|
|
3518
|
+
}
|
|
3519
|
+
/**
|
|
3520
|
+
* Bound one step of the WebGPU probe. A step that never settles is not hypothetical: a headless
|
|
3521
|
+
* context can advertise `navigator.gpu`, hand back no adapter, and leave three's init pending
|
|
3522
|
+
* forever, which shows up as a page that renders nothing and reports nothing. `disposeLate`
|
|
3523
|
+
* releases a result that arrives after we gave up, so a slow success cannot leak a GPU device.
|
|
3524
|
+
*/
|
|
3525
|
+
async function withProbeTimeout(pending, ms, step, disposeLate) {
|
|
3526
|
+
if (!Number.isFinite(ms) || ms <= 0) return pending;
|
|
3527
|
+
let timer;
|
|
3528
|
+
const expiry = new Promise((_resolve, reject) => {
|
|
3529
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`WebGPU ${step} did not settle within ${ms}ms`)), ms);
|
|
3530
|
+
});
|
|
3531
|
+
try {
|
|
3532
|
+
return await Promise.race([pending, expiry]);
|
|
3533
|
+
} catch (error) {
|
|
3534
|
+
pending.then((value) => disposeLate?.(value), () => {});
|
|
3535
|
+
throw error;
|
|
3536
|
+
} finally {
|
|
3537
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
3538
|
+
}
|
|
3539
|
+
}
|
|
3540
|
+
/**
|
|
3541
|
+
* Thin wrapper over the three.js renderer + scene + camera. The engine owns the single
|
|
3542
|
+
* construction path so capture settings (pixel ratio, AA, tone mapping) are deterministic.
|
|
3543
|
+
* The `backend` option selects WebGPU or WebGL — see docs-src/guide/rendering-backends.md.
|
|
3544
|
+
*/
|
|
3545
|
+
var Renderer = class Renderer {
|
|
3546
|
+
admission;
|
|
3547
|
+
preparedResources = /* @__PURE__ */ new WeakMap();
|
|
3548
|
+
warmupTarget;
|
|
3549
|
+
warmupMaterial;
|
|
3550
|
+
warmedPrograms = /* @__PURE__ */ new WeakMap();
|
|
3551
|
+
warmedMeshes = /* @__PURE__ */ new WeakMap();
|
|
3552
|
+
three;
|
|
3553
|
+
backend;
|
|
3554
|
+
fallback;
|
|
3555
|
+
get fallbackReason() {
|
|
3556
|
+
return this.fallback;
|
|
3557
|
+
}
|
|
3558
|
+
scene;
|
|
3559
|
+
/** World-space objects live here so the renderer can rebase them near the camera. */
|
|
3560
|
+
worldRoot;
|
|
3561
|
+
camera;
|
|
3562
|
+
defaultClearColor;
|
|
3563
|
+
aspect;
|
|
3564
|
+
viewportWidth;
|
|
3565
|
+
viewportHeight;
|
|
3566
|
+
pixelRatio;
|
|
3567
|
+
uploadBatchBytes;
|
|
3568
|
+
worldOrigin = [
|
|
3569
|
+
0,
|
|
3570
|
+
0,
|
|
3571
|
+
0
|
|
3572
|
+
];
|
|
3573
|
+
cameraPose;
|
|
3574
|
+
/** The active top-down framing, so a resize can refit the orthographic bounds. */
|
|
3575
|
+
ortho;
|
|
3576
|
+
cameraNear;
|
|
3577
|
+
cameraFar;
|
|
3578
|
+
autoWorldOrigin;
|
|
3579
|
+
timers = /* @__PURE__ */ new Set();
|
|
3580
|
+
disposed = false;
|
|
3581
|
+
deviceLossReason;
|
|
3582
|
+
optimizer;
|
|
3583
|
+
activeSky;
|
|
3584
|
+
starCatalog;
|
|
3585
|
+
activeWeather;
|
|
3586
|
+
weatherTimeOverride;
|
|
3587
|
+
weatherLightIntensities = /* @__PURE__ */ new WeakMap();
|
|
3588
|
+
environmentSeconds = 0;
|
|
3589
|
+
environmentTimeOverride;
|
|
3590
|
+
/** Active clear-sky visual and sampled ephemeris, when environment.sky is configured. */
|
|
3591
|
+
get sky() {
|
|
3592
|
+
return this.activeSky;
|
|
3593
|
+
}
|
|
3594
|
+
/** Active weather effects; physical weather data is also available in the simulation component. */
|
|
3595
|
+
get weather() {
|
|
3596
|
+
return this.activeWeather;
|
|
3597
|
+
}
|
|
3598
|
+
/** Apply the singleton weather component without rebuilding the sky or moving the camera. */
|
|
3599
|
+
setWeather(data) {
|
|
3600
|
+
if (data && this.activeWeather) this.activeWeather.setData(data);
|
|
3601
|
+
else {
|
|
3602
|
+
const next = data ? new WeatherVisual(data) : void 0;
|
|
3603
|
+
this.activeWeather?.dispose();
|
|
3604
|
+
this.activeWeather = next;
|
|
3605
|
+
if (next) this.scene.add(next.object);
|
|
3606
|
+
}
|
|
3607
|
+
}
|
|
3608
|
+
/** Standalone weather preview clock. Undefined follows simulation time, independently of sky seeks. */
|
|
3609
|
+
setWeatherTimeOverride(seconds) {
|
|
3610
|
+
if (seconds !== void 0 && !Number.isFinite(seconds)) throw new Error("Weather time must be finite");
|
|
3611
|
+
this.weatherTimeOverride = seconds;
|
|
3612
|
+
}
|
|
3613
|
+
/** @internal Environment binding hook; hosts use applyEnvironment to replace the complete lighting rig. */
|
|
3614
|
+
setSky(data, shadows = "off") {
|
|
3615
|
+
const next = data ? new SkyVisual(data, {
|
|
3616
|
+
shadows,
|
|
3617
|
+
...this.starCatalog !== void 0 ? { stars: this.starCatalog } : {}
|
|
3618
|
+
}) : void 0;
|
|
3619
|
+
try {
|
|
3620
|
+
next?.update(this.environmentTimeOverride ?? this.environmentSeconds);
|
|
3621
|
+
} catch (error) {
|
|
3622
|
+
next?.dispose();
|
|
3623
|
+
throw error;
|
|
3624
|
+
}
|
|
3625
|
+
this.activeSky?.dispose();
|
|
3626
|
+
this.activeSky = next;
|
|
3627
|
+
if (next) this.scene.add(next.lights);
|
|
3628
|
+
}
|
|
3629
|
+
/**
|
|
3630
|
+
* Stars for every sky this renderer shows, e.g. `decodeStarCatalog` of a content pack's
|
|
3631
|
+
* molen/stars@1 file. Applies to the current sky at once and survives sky changes;
|
|
3632
|
+
* `undefined` removes the stars.
|
|
3633
|
+
*/
|
|
3634
|
+
setStarCatalog(stars) {
|
|
3635
|
+
this.starCatalog = stars;
|
|
3636
|
+
this.activeSky?.setStars(stars);
|
|
3637
|
+
}
|
|
3638
|
+
/** Absolute simulation seconds, shared by live playback, paused snapshots and captures. */
|
|
3639
|
+
setEnvironmentTime(seconds) {
|
|
3640
|
+
if (!Number.isFinite(seconds)) throw new Error("Environment time must be finite");
|
|
3641
|
+
this.environmentSeconds = seconds;
|
|
3642
|
+
}
|
|
3643
|
+
/** Preview a sky at absolute simulation seconds without seeking the world; undefined resumes its clock. */
|
|
3644
|
+
setEnvironmentTimeOverride(seconds) {
|
|
3645
|
+
if (seconds !== void 0 && !Number.isFinite(seconds)) throw new Error("Environment time override must be finite");
|
|
3646
|
+
this.environmentTimeOverride = seconds;
|
|
3647
|
+
}
|
|
3648
|
+
/** Prefer WebGPU when available; explicit webgpu is strict and never silently falls back. */
|
|
3649
|
+
static async create(opts = {}) {
|
|
3650
|
+
validateRendererOptions(opts);
|
|
3651
|
+
const preference = opts.backend ?? "auto";
|
|
3652
|
+
if (preference === "webgl") return new Renderer(opts);
|
|
3653
|
+
const probeMs = opts.backendProbeTimeoutMs ?? 5e3;
|
|
3654
|
+
try {
|
|
3655
|
+
if (typeof navigator === "undefined" || !("gpu" in navigator) || !navigator.gpu) throw new Error("WebGPU is unavailable in this browser or context");
|
|
3656
|
+
if (await withProbeTimeout(navigator.gpu.requestAdapter(), probeMs, "adapter request") === null) throw new Error("WebGPU reported no adapter for this device");
|
|
3657
|
+
const { createWebGpuDriver } = await import("./webgpu-driver-DXsRuz8j.mjs");
|
|
3658
|
+
const three = await withProbeTimeout(createWebGpuDriver(opts), probeMs, "initialization", (late) => {
|
|
3659
|
+
late.dispose();
|
|
3660
|
+
});
|
|
3661
|
+
try {
|
|
3662
|
+
const optimizer = opts.optimizeWebGpu === false ? void 0 : new (await (import("./webgpu-scene-optimizer-D6e9ZJQM.mjs"))).WebGpuSceneOptimizer(three);
|
|
3663
|
+
return new Renderer(opts, {
|
|
3664
|
+
three,
|
|
3665
|
+
backend: "webgpu",
|
|
3666
|
+
...optimizer ? { optimizer } : {}
|
|
3667
|
+
});
|
|
3668
|
+
} catch (error) {
|
|
3669
|
+
three.dispose();
|
|
3670
|
+
throw error;
|
|
3671
|
+
}
|
|
3672
|
+
} catch (error) {
|
|
3673
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
3674
|
+
if (preference === "webgpu") throw new Error(`WebGPU initialization failed: ${reason}`, { cause: error });
|
|
3675
|
+
const renderer = new Renderer({
|
|
3676
|
+
...opts,
|
|
3677
|
+
backend: "webgl"
|
|
3678
|
+
});
|
|
3679
|
+
renderer.fallback = reason;
|
|
3680
|
+
return renderer;
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
constructor(opts = {}, initialized) {
|
|
3684
|
+
validateRendererOptions(opts);
|
|
3685
|
+
this.starCatalog = opts.stars;
|
|
3686
|
+
this.admission = new FrameAdmissionQueue({
|
|
3687
|
+
maxMilliseconds: initialized?.backend === "webgpu" ? 8 : 2,
|
|
3688
|
+
...opts.admission
|
|
3689
|
+
});
|
|
3690
|
+
this.uploadBatchBytes = opts.admission?.maxBytes ?? 2 * 1024 * 1024;
|
|
3691
|
+
if (initialized === void 0 && opts.backend !== void 0 && opts.backend !== "webgl") throw new Error("Use await Renderer.create() for auto or webgpu backends");
|
|
3692
|
+
const width = opts.width ?? 1280;
|
|
3693
|
+
const height = opts.height ?? 720;
|
|
3694
|
+
const pixelRatio = opts.pixelRatio ?? 1;
|
|
3695
|
+
const cameraNear = opts.cameraNear ?? .1;
|
|
3696
|
+
const cameraFar = opts.cameraFar ?? 5e3;
|
|
3697
|
+
this.autoWorldOrigin = opts.autoWorldOrigin;
|
|
3698
|
+
this.cameraNear = cameraNear;
|
|
3699
|
+
this.cameraFar = cameraFar;
|
|
3700
|
+
this.viewportWidth = width;
|
|
3701
|
+
this.viewportHeight = height;
|
|
3702
|
+
this.pixelRatio = pixelRatio;
|
|
3703
|
+
this.backend = initialized?.backend ?? "webgl";
|
|
3704
|
+
this.optimizer = initialized?.optimizer;
|
|
3705
|
+
this.three = initialized?.three ?? new THREE.WebGLRenderer({
|
|
3706
|
+
canvas: opts.canvas,
|
|
3707
|
+
antialias: opts.antialias ?? false,
|
|
3708
|
+
preserveDrawingBuffer: opts.preserveDrawingBuffer ?? true,
|
|
3709
|
+
powerPreference: opts.powerPreference ?? "default",
|
|
3710
|
+
reversedDepthBuffer: opts.reverseDepthBuffer ?? false,
|
|
3711
|
+
logarithmicDepthBuffer: opts.logarithmicDepthBuffer ?? false
|
|
3712
|
+
});
|
|
3713
|
+
this.three.setPixelRatio(pixelRatio);
|
|
3714
|
+
if (this.backend === "webgpu") this.three.onDeviceLost = (info) => {
|
|
3715
|
+
if (this.disposed) return;
|
|
3716
|
+
this.deviceLossReason = info.message;
|
|
3717
|
+
for (const timer of this.timers) timer.dispose();
|
|
3718
|
+
this.timers.clear();
|
|
3719
|
+
opts.onDeviceLost?.(info.message);
|
|
3720
|
+
};
|
|
3721
|
+
this.three.setSize(width, height, false);
|
|
3722
|
+
this.defaultClearColor = new THREE.Color(opts.clearColor ?? "#1a1a20");
|
|
3723
|
+
this.three.setClearColor(this.defaultClearColor, 1);
|
|
3724
|
+
this.scene = new THREE.Scene();
|
|
3725
|
+
this.worldRoot = new THREE.Group();
|
|
3726
|
+
this.worldRoot.name = "molen:world-root";
|
|
3727
|
+
this.scene.add(this.worldRoot);
|
|
3728
|
+
this.aspect = width / height;
|
|
3729
|
+
this.camera = new THREE.PerspectiveCamera(60, this.aspect, cameraNear, cameraFar);
|
|
3730
|
+
this.camera.position.set(0, 0, 10);
|
|
3731
|
+
applyEnvironment(this, defaultEnvironment);
|
|
3732
|
+
}
|
|
3733
|
+
/** Pose the perspective camera (leaving top-down ortho mode if it was active). */
|
|
3734
|
+
setCamera(pose) {
|
|
3735
|
+
if (this.camera instanceof THREE.OrthographicCamera) {
|
|
3736
|
+
this.camera = new THREE.PerspectiveCamera(60, this.aspect, this.cameraNear, this.cameraFar);
|
|
3737
|
+
this.ortho = void 0;
|
|
3738
|
+
}
|
|
3739
|
+
this.cameraPose = {
|
|
3740
|
+
position: [...pose.position],
|
|
3741
|
+
...pose.lookAt !== void 0 ? { lookAt: [...pose.lookAt] } : {},
|
|
3742
|
+
...pose.rotation !== void 0 ? { rotation: [...pose.rotation] } : {}
|
|
3743
|
+
};
|
|
3744
|
+
this.maybeRebase(pose.position);
|
|
3745
|
+
this.applyCameraPose(this.cameraPose);
|
|
3746
|
+
}
|
|
3747
|
+
/** Vertical field of view in degrees (perspective camera only; a no-op for ortho). */
|
|
3748
|
+
setFov(fovDeg) {
|
|
3749
|
+
if (!Number.isFinite(fovDeg) || fovDeg <= 0 || fovDeg >= 180) throw new Error("fov must be in (0, 180) degrees");
|
|
3750
|
+
if (this.camera instanceof THREE.PerspectiveCamera) {
|
|
3751
|
+
this.camera.fov = fovDeg;
|
|
3752
|
+
this.camera.updateProjectionMatrix();
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3755
|
+
/** Shift all engine-owned world objects near the local origin without changing world poses. */
|
|
3756
|
+
setWorldOrigin(origin) {
|
|
3757
|
+
if (!origin.every(Number.isFinite)) throw new Error("world origin must contain finite numbers");
|
|
3758
|
+
this.applyWorldOrigin(origin);
|
|
3759
|
+
if (this.cameraPose !== void 0) this.applyCameraPose(this.cameraPose);
|
|
3760
|
+
else if (this.ortho !== void 0) this.setTopDownOrtho(this.ortho);
|
|
3761
|
+
}
|
|
3762
|
+
getWorldOrigin() {
|
|
3763
|
+
return [...this.worldOrigin];
|
|
3764
|
+
}
|
|
3765
|
+
setCameraClip(near, far) {
|
|
3766
|
+
if (!Number.isFinite(near) || near <= 0 || !Number.isFinite(far) || far <= near) throw new Error("camera clip range requires finite 0 < near < far");
|
|
3767
|
+
this.camera.near = near;
|
|
3768
|
+
this.camera.far = far;
|
|
3769
|
+
this.camera.updateProjectionMatrix();
|
|
3770
|
+
}
|
|
3771
|
+
applyCameraPose(pose) {
|
|
3772
|
+
this.camera.position.set(pose.position[0] - this.worldOrigin[0], pose.position[1] - this.worldOrigin[1], pose.position[2] - this.worldOrigin[2]);
|
|
3773
|
+
if (pose.lookAt !== void 0) this.camera.lookAt(pose.lookAt[0] - this.worldOrigin[0], pose.lookAt[1] - this.worldOrigin[1], pose.lookAt[2] - this.worldOrigin[2]);
|
|
3774
|
+
else if (pose.rotation !== void 0) {
|
|
3775
|
+
const r = pose.rotation;
|
|
3776
|
+
this.camera.quaternion.set(r[0], r[1], r[2], r[3]);
|
|
3777
|
+
}
|
|
3778
|
+
}
|
|
3779
|
+
maybeRebase(position) {
|
|
3780
|
+
if (this.autoWorldOrigin === void 0) return;
|
|
3781
|
+
const next = nextWorldOrigin(this.worldOrigin, position, this.autoWorldOrigin);
|
|
3782
|
+
if (next !== void 0) this.applyWorldOrigin(next);
|
|
3783
|
+
}
|
|
3784
|
+
applyWorldOrigin(origin) {
|
|
3785
|
+
this.worldOrigin = [...origin];
|
|
3786
|
+
this.worldRoot.position.set(-origin[0], -origin[1], -origin[2]);
|
|
3787
|
+
}
|
|
3788
|
+
/** Switch to a top-down orthographic camera looking straight down at a world point. */
|
|
3789
|
+
setTopDownOrtho(opts) {
|
|
3790
|
+
const { halfW, halfH } = orthoFrustum(opts.viewHeight, this.aspect);
|
|
3791
|
+
const camH = opts.cameraHeight ?? 200;
|
|
3792
|
+
this.ortho = {
|
|
3793
|
+
...opts,
|
|
3794
|
+
center: [opts.center[0], opts.center[1]]
|
|
3795
|
+
};
|
|
3796
|
+
this.cameraPose = void 0;
|
|
3797
|
+
this.maybeRebase([
|
|
3798
|
+
opts.center[0],
|
|
3799
|
+
camH,
|
|
3800
|
+
opts.center[1]
|
|
3801
|
+
]);
|
|
3802
|
+
let ortho;
|
|
3803
|
+
if (this.camera instanceof THREE.OrthographicCamera) {
|
|
3804
|
+
ortho = this.camera;
|
|
3805
|
+
ortho.left = -halfW;
|
|
3806
|
+
ortho.right = halfW;
|
|
3807
|
+
ortho.top = halfH;
|
|
3808
|
+
ortho.bottom = -halfH;
|
|
3809
|
+
} else {
|
|
3810
|
+
ortho = new THREE.OrthographicCamera(-halfW, halfW, halfH, -halfH, .1, camH * 4);
|
|
3811
|
+
this.camera = ortho;
|
|
3812
|
+
}
|
|
3813
|
+
const centerX = opts.center[0] - this.worldOrigin[0];
|
|
3814
|
+
const centerZ = opts.center[1] - this.worldOrigin[2];
|
|
3815
|
+
ortho.position.set(centerX, camH - this.worldOrigin[1], centerZ);
|
|
3816
|
+
ortho.up.set(0, 0, -1);
|
|
3817
|
+
ortho.lookAt(centerX, -this.worldOrigin[1], centerZ);
|
|
3818
|
+
if (opts.rotationDeg !== void 0) ortho.rotateZ(opts.rotationDeg * Math.PI / 180);
|
|
3819
|
+
ortho.updateProjectionMatrix();
|
|
3820
|
+
}
|
|
3821
|
+
/**
|
|
3822
|
+
* The WebGPU device-loss reason once the device is gone (undefined while it is live). Every
|
|
3823
|
+
* later `render()` throws, so a frame loop stops here instead of failing once per frame.
|
|
3824
|
+
*/
|
|
3825
|
+
get deviceLost() {
|
|
3826
|
+
return this.deviceLossReason;
|
|
3827
|
+
}
|
|
3828
|
+
/**
|
|
3829
|
+
* Update the device pixel ratio after a display change. Three applies the ratio on the next
|
|
3830
|
+
* `setSize`, so callers pair the two (the mount's resize handler does).
|
|
3831
|
+
*/
|
|
3832
|
+
setPixelRatio(ratio) {
|
|
3833
|
+
if (!Number.isFinite(ratio) || ratio <= 0) throw new Error("pixelRatio must be finite and positive");
|
|
3834
|
+
if (ratio === this.pixelRatio) return;
|
|
3835
|
+
this.pixelRatio = ratio;
|
|
3836
|
+
this.three.setPixelRatio(ratio);
|
|
3837
|
+
}
|
|
3838
|
+
setSize(width, height) {
|
|
3839
|
+
const w = Number.isFinite(width) && width > 0 ? width : 1;
|
|
3840
|
+
const h = Number.isFinite(height) && height > 0 ? height : 1;
|
|
3841
|
+
const sizeChanged = w !== this.viewportWidth || h !== this.viewportHeight;
|
|
3842
|
+
this.viewportWidth = w;
|
|
3843
|
+
this.viewportHeight = h;
|
|
3844
|
+
if (sizeChanged) this.three.setSize(w, h, false);
|
|
3845
|
+
this.aspect = w / h;
|
|
3846
|
+
if (this.camera instanceof THREE.PerspectiveCamera) {
|
|
3847
|
+
this.camera.aspect = this.aspect;
|
|
3848
|
+
this.camera.updateProjectionMatrix();
|
|
3849
|
+
return;
|
|
3850
|
+
}
|
|
3851
|
+
if (this.ortho !== void 0) this.setTopDownOrtho(this.ortho);
|
|
3852
|
+
else this.camera.updateProjectionMatrix();
|
|
3853
|
+
}
|
|
3854
|
+
/** Prepare shared resources once; all dependants await the same admission jobs. */
|
|
3855
|
+
async prepareObject(root, signal) {
|
|
3856
|
+
const jobs = /* @__PURE__ */ new Set();
|
|
3857
|
+
const glAttributes = /* @__PURE__ */ new Set();
|
|
3858
|
+
const glBatches = [];
|
|
3859
|
+
root.updateWorldMatrix(true, true);
|
|
3860
|
+
root.traverse((object) => {
|
|
3861
|
+
const mesh = object;
|
|
3862
|
+
if (!mesh.isMesh) return;
|
|
3863
|
+
const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
|
|
3864
|
+
const key = `${Boolean(mesh.isInstancedMesh)}/${Boolean(mesh.isSkinnedMesh)}/${Object.keys(mesh.geometry.attributes).sort().join(",")}`;
|
|
3865
|
+
const variants = [];
|
|
3866
|
+
for (const material of materials) {
|
|
3867
|
+
for (const value of Object.values(material)) {
|
|
3868
|
+
if (!(value instanceof THREE.Texture)) continue;
|
|
3869
|
+
const existing = this.preparedResources.get(value);
|
|
3870
|
+
if (existing?.version === value.version) {
|
|
3871
|
+
jobs.add(existing.promise);
|
|
3872
|
+
continue;
|
|
3873
|
+
}
|
|
3874
|
+
const promise = this.admission.run(() => this.three.initTexture(value), {
|
|
3875
|
+
label: "texture-upload",
|
|
3876
|
+
bytes: textureBytes(value)
|
|
3877
|
+
});
|
|
3878
|
+
this.rememberPreparation([value], promise);
|
|
3879
|
+
jobs.add(promise);
|
|
3880
|
+
}
|
|
3881
|
+
let map = this.warmedPrograms.get(material);
|
|
3882
|
+
if (!map) {
|
|
3883
|
+
map = /* @__PURE__ */ new Map();
|
|
3884
|
+
this.warmedPrograms.set(material, map);
|
|
3885
|
+
}
|
|
3886
|
+
const variantKey = `${material.version}/${key}`;
|
|
3887
|
+
const existing = map.get(variantKey);
|
|
3888
|
+
if (existing) jobs.add(existing);
|
|
3889
|
+
else variants.push({
|
|
3890
|
+
map,
|
|
3891
|
+
key: variantKey
|
|
3892
|
+
});
|
|
3893
|
+
}
|
|
3894
|
+
const instanced = mesh;
|
|
3895
|
+
const fresh = [
|
|
3896
|
+
...Object.values(mesh.geometry.attributes).map((a) => a instanceof THREE.InterleavedBufferAttribute ? a.data : a),
|
|
3897
|
+
...mesh.geometry.index ? [mesh.geometry.index] : [],
|
|
3898
|
+
...instanced.isInstancedMesh ? [instanced.instanceMatrix, ...instanced.instanceColor ? [instanced.instanceColor] : []] : []
|
|
3899
|
+
].filter((attribute) => {
|
|
3900
|
+
if (glAttributes.has(attribute)) return false;
|
|
3901
|
+
const existing = this.preparedResources.get(attribute);
|
|
3902
|
+
if (existing?.version === attribute.version) {
|
|
3903
|
+
jobs.add(existing.promise);
|
|
3904
|
+
return false;
|
|
3905
|
+
}
|
|
3906
|
+
return true;
|
|
3907
|
+
});
|
|
3908
|
+
let compilation;
|
|
3909
|
+
const objectSpecific = instanced.isInstancedMesh || mesh.isSkinnedMesh || mesh.morphTargetInfluences !== void 0;
|
|
3910
|
+
const previousMesh = this.warmedMeshes.get(mesh);
|
|
3911
|
+
if (previousMesh) jobs.add(previousMesh);
|
|
3912
|
+
if (variants.length > 0 || this.backend === "webgpu" && (fresh.length > 0 || objectSpecific && !previousMesh)) {
|
|
3913
|
+
compilation = this.admission.run(() => this.compileMesh(mesh), {
|
|
3914
|
+
label: this.backend === "webgpu" && fresh.length > 0 ? "geometry-upload-and-shader" : "shader-warmup",
|
|
3915
|
+
bytes: this.backend === "webgpu" ? fresh.reduce((sum, a) => sum + a.array.byteLength, 0) : 0
|
|
3916
|
+
});
|
|
3917
|
+
jobs.add(compilation);
|
|
3918
|
+
if (this.backend === "webgpu") {
|
|
3919
|
+
this.warmedMeshes.set(mesh, compilation);
|
|
3920
|
+
compilation.catch(() => {
|
|
3921
|
+
if (this.warmedMeshes.get(mesh) === compilation) this.warmedMeshes.delete(mesh);
|
|
3922
|
+
});
|
|
3923
|
+
}
|
|
3924
|
+
for (const variant of variants) {
|
|
3925
|
+
variant.map.set(variant.key, compilation);
|
|
3926
|
+
compilation.catch(() => {
|
|
3927
|
+
if (variant.map.get(variant.key) === compilation) variant.map.delete(variant.key);
|
|
3928
|
+
});
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
if (fresh.length > 0) if (this.backend === "webgpu") {
|
|
3932
|
+
const upload = compilation;
|
|
3933
|
+
this.rememberPreparation(fresh, upload);
|
|
3934
|
+
jobs.add(upload);
|
|
3935
|
+
} else {
|
|
3936
|
+
const bytes = fresh.reduce((sum, a) => sum + a.array.byteLength, 0);
|
|
3937
|
+
let batch = glBatches.at(-1);
|
|
3938
|
+
if (!batch || batch.meshes.length >= 16 || batch.bytes + bytes > this.uploadBatchBytes) {
|
|
3939
|
+
batch = {
|
|
3940
|
+
meshes: [],
|
|
3941
|
+
attributes: [],
|
|
3942
|
+
bytes: 0
|
|
3943
|
+
};
|
|
3944
|
+
glBatches.push(batch);
|
|
3945
|
+
}
|
|
3946
|
+
batch.meshes.push(mesh);
|
|
3947
|
+
batch.attributes.push(...fresh);
|
|
3948
|
+
batch.bytes += bytes;
|
|
3949
|
+
for (const attribute of fresh) glAttributes.add(attribute);
|
|
3950
|
+
}
|
|
3951
|
+
});
|
|
3952
|
+
for (const batch of glBatches) {
|
|
3953
|
+
const upload = this.admission.run(() => this.prepareWebGlGeometries(batch.meshes), {
|
|
3954
|
+
label: "geometry-upload",
|
|
3955
|
+
bytes: batch.bytes
|
|
3956
|
+
});
|
|
3957
|
+
this.rememberPreparation(batch.attributes, upload);
|
|
3958
|
+
jobs.add(upload);
|
|
3959
|
+
}
|
|
3960
|
+
const results = await Promise.allSettled(jobs);
|
|
3961
|
+
if (signal?.aborted) throw new DOMException("Preparation cancelled", "AbortError");
|
|
3962
|
+
const failure = results.find((result) => result.status === "rejected");
|
|
3963
|
+
if (failure?.status === "rejected") throw failure.reason;
|
|
3964
|
+
}
|
|
3965
|
+
rememberPreparation(resources, promise) {
|
|
3966
|
+
for (const resource of resources) this.preparedResources.set(resource, {
|
|
3967
|
+
version: resource.version,
|
|
3968
|
+
promise
|
|
3969
|
+
});
|
|
3970
|
+
promise.catch(() => {
|
|
3971
|
+
for (const resource of resources) if (this.preparedResources.get(resource)?.promise === promise) this.preparedResources.delete(resource);
|
|
3972
|
+
});
|
|
3973
|
+
}
|
|
3974
|
+
compileMesh(mesh) {
|
|
3975
|
+
const visible = mesh.visible, culled = mesh.frustumCulled;
|
|
3976
|
+
mesh.visible = true;
|
|
3977
|
+
mesh.frustumCulled = false;
|
|
3978
|
+
try {
|
|
3979
|
+
return this.three.compileAsync(mesh, this.camera, this.scene);
|
|
3980
|
+
} finally {
|
|
3981
|
+
mesh.visible = visible;
|
|
3982
|
+
mesh.frustumCulled = culled;
|
|
3983
|
+
}
|
|
3984
|
+
}
|
|
3985
|
+
prepareWebGlGeometries(meshes) {
|
|
3986
|
+
const renderer = this.three;
|
|
3987
|
+
this.warmupTarget ??= new THREE.WebGLRenderTarget(1, 1);
|
|
3988
|
+
this.warmupMaterial ??= new THREE.MeshBasicMaterial({
|
|
3989
|
+
colorWrite: false,
|
|
3990
|
+
depthWrite: false
|
|
3991
|
+
});
|
|
3992
|
+
const scene = new THREE.Scene();
|
|
3993
|
+
const ranges = /* @__PURE__ */ new Map();
|
|
3994
|
+
for (const mesh of meshes) {
|
|
3995
|
+
const geometry = mesh.geometry;
|
|
3996
|
+
if (!ranges.has(geometry)) ranges.set(geometry, { ...geometry.drawRange });
|
|
3997
|
+
const instanced = mesh;
|
|
3998
|
+
const proxy = instanced.isInstancedMesh ? new THREE.InstancedMesh(geometry, this.warmupMaterial, 0) : new THREE.Mesh(geometry, this.warmupMaterial);
|
|
3999
|
+
if (proxy instanceof THREE.InstancedMesh) {
|
|
4000
|
+
proxy.instanceMatrix = instanced.instanceMatrix;
|
|
4001
|
+
proxy.instanceColor = instanced.instanceColor;
|
|
4002
|
+
}
|
|
4003
|
+
proxy.frustumCulled = false;
|
|
4004
|
+
scene.add(proxy);
|
|
4005
|
+
}
|
|
4006
|
+
const target = renderer.getRenderTarget();
|
|
4007
|
+
try {
|
|
4008
|
+
for (const geometry of ranges.keys()) geometry.setDrawRange(0, 0);
|
|
4009
|
+
renderer.setRenderTarget(this.warmupTarget);
|
|
4010
|
+
renderer.render(scene, this.camera);
|
|
4011
|
+
} finally {
|
|
4012
|
+
for (const [geometry, range] of ranges) geometry.setDrawRange(range.start, range.count);
|
|
4013
|
+
renderer.setRenderTarget(target);
|
|
4014
|
+
scene.clear();
|
|
4015
|
+
}
|
|
4016
|
+
}
|
|
4017
|
+
render() {
|
|
4018
|
+
if (this.disposed) throw new Error("Renderer has been disposed");
|
|
4019
|
+
if (this.deviceLossReason !== void 0) throw new Error(`WebGPU device lost: ${this.deviceLossReason}. Recreate the viewer, or reload with WebGL.`);
|
|
4020
|
+
if (this.backend === "webgpu") this.three.info.reset();
|
|
4021
|
+
const sky = this.activeSky;
|
|
4022
|
+
const weather = this.activeWeather;
|
|
4023
|
+
sky?.setCloudAttenuation(weather?.cloudAttenuation ?? 0);
|
|
4024
|
+
sky?.update(this.environmentTimeOverride ?? this.environmentSeconds);
|
|
4025
|
+
this.scene.getObjectByName("$environment")?.traverse((object) => {
|
|
4026
|
+
if (!(object instanceof THREE.Light)) return;
|
|
4027
|
+
let base = this.weatherLightIntensities.get(object);
|
|
4028
|
+
if (!weather) {
|
|
4029
|
+
if (base !== void 0) {
|
|
4030
|
+
object.intensity = base;
|
|
4031
|
+
this.weatherLightIntensities.delete(object);
|
|
4032
|
+
}
|
|
4033
|
+
return;
|
|
4034
|
+
}
|
|
4035
|
+
if (base === void 0) {
|
|
4036
|
+
base = object.intensity;
|
|
4037
|
+
this.weatherLightIntensities.set(object, base);
|
|
4038
|
+
}
|
|
4039
|
+
object.intensity = base * (1 - (weather?.cloudAttenuation ?? 0) * (object instanceof THREE.DirectionalLight ? .92 : .2));
|
|
4040
|
+
});
|
|
4041
|
+
weather?.update(this.weatherTimeOverride ?? this.environmentSeconds, this.camera, this.worldOrigin, sky?.frame);
|
|
4042
|
+
const baseFog = this.scene.fog;
|
|
4043
|
+
if (weather) this.scene.fog = weather.fogFor(baseFog, sky?.frame);
|
|
4044
|
+
try {
|
|
4045
|
+
if (sky) {
|
|
4046
|
+
sky.update(this.environmentTimeOverride ?? this.environmentSeconds);
|
|
4047
|
+
sky.prepareCamera(this.camera);
|
|
4048
|
+
const autoClear = this.three.autoClear;
|
|
4049
|
+
const autoReset = this.three.info.autoReset;
|
|
4050
|
+
this.three.info.reset();
|
|
4051
|
+
this.three.info.autoReset = false;
|
|
4052
|
+
try {
|
|
4053
|
+
this.three.render(sky.scene, sky.camera);
|
|
4054
|
+
this.three.autoClear = false;
|
|
4055
|
+
this.renderScene();
|
|
4056
|
+
} finally {
|
|
4057
|
+
this.three.autoClear = autoClear;
|
|
4058
|
+
this.three.info.autoReset = autoReset;
|
|
4059
|
+
}
|
|
4060
|
+
return;
|
|
4061
|
+
}
|
|
4062
|
+
this.renderScene();
|
|
4063
|
+
} finally {
|
|
4064
|
+
this.scene.fog = baseFog;
|
|
4065
|
+
}
|
|
4066
|
+
}
|
|
4067
|
+
renderScene() {
|
|
4068
|
+
if (this.optimizer === void 0) {
|
|
4069
|
+
this.three.render(this.scene, this.camera);
|
|
4070
|
+
return;
|
|
4071
|
+
}
|
|
4072
|
+
this.optimizer.prepare(this.scene, this.camera);
|
|
4073
|
+
const autoUpdate = this.scene.matrixWorldAutoUpdate;
|
|
4074
|
+
this.scene.matrixWorldAutoUpdate = false;
|
|
4075
|
+
try {
|
|
4076
|
+
this.three.render(this.scene, this.camera);
|
|
4077
|
+
this.optimizer.finish();
|
|
4078
|
+
} finally {
|
|
4079
|
+
this.scene.matrixWorldAutoUpdate = autoUpdate;
|
|
4080
|
+
}
|
|
4081
|
+
}
|
|
4082
|
+
/** Use for independent terrain/content chunks. WebGPU caches eligible opaque draw commands. */
|
|
4083
|
+
createRenderGroup() {
|
|
4084
|
+
return this.optimizer?.createGroup() ?? new THREE.Group();
|
|
4085
|
+
}
|
|
4086
|
+
/** Render stats for the screenshot stats block. */
|
|
4087
|
+
stats() {
|
|
4088
|
+
const info = this.three.info.render;
|
|
4089
|
+
return {
|
|
4090
|
+
drawCalls: "drawCalls" in info ? info.drawCalls : info.calls,
|
|
4091
|
+
triangles: info.triangles
|
|
4092
|
+
};
|
|
4093
|
+
}
|
|
4094
|
+
/** Optional backend-specific GPU timing with the same nonblocking polling interface. */
|
|
4095
|
+
createGpuTimer(options = {}) {
|
|
4096
|
+
if (this.disposed) throw new Error("Renderer has been disposed");
|
|
4097
|
+
const timer = this.backend === "webgpu" ? createWebGpuFrameTimer(this.three, options) : createGpuFrameTimer(this.three.getContext(), options);
|
|
4098
|
+
if (timer !== void 0) {
|
|
4099
|
+
const dispose = timer.dispose.bind(timer);
|
|
4100
|
+
timer.dispose = () => {
|
|
4101
|
+
this.timers.delete(timer);
|
|
4102
|
+
dispose();
|
|
4103
|
+
};
|
|
4104
|
+
this.timers.add(timer);
|
|
4105
|
+
}
|
|
4106
|
+
return timer;
|
|
4107
|
+
}
|
|
4108
|
+
dispose() {
|
|
4109
|
+
if (this.disposed) return;
|
|
4110
|
+
this.disposed = true;
|
|
4111
|
+
this.activeSky?.dispose();
|
|
4112
|
+
this.activeSky = void 0;
|
|
4113
|
+
this.activeWeather?.dispose();
|
|
4114
|
+
this.activeWeather = void 0;
|
|
4115
|
+
this.scene.getObjectByName("$environment")?.traverse((object) => {
|
|
4116
|
+
if (object instanceof THREE.Light) object.dispose();
|
|
4117
|
+
});
|
|
4118
|
+
this.admission.dispose();
|
|
4119
|
+
this.warmupTarget?.dispose();
|
|
4120
|
+
this.warmupMaterial?.dispose();
|
|
4121
|
+
for (const timer of this.timers) timer.dispose();
|
|
4122
|
+
this.timers.clear();
|
|
4123
|
+
this.optimizer?.dispose();
|
|
4124
|
+
this.worldRoot.clear();
|
|
4125
|
+
this.three.dispose();
|
|
4126
|
+
}
|
|
4127
|
+
};
|
|
4128
|
+
function textureBytes(texture) {
|
|
4129
|
+
const image = texture.image;
|
|
4130
|
+
return image?.data?.byteLength ?? Math.ceil((image?.width ?? 1) * (image?.height ?? 1) * 4 * 4 / 3);
|
|
4131
|
+
}
|
|
4132
|
+
function validateRendererOptions(opts) {
|
|
4133
|
+
if (opts.backend !== void 0 && ![
|
|
4134
|
+
"auto",
|
|
4135
|
+
"webgl",
|
|
4136
|
+
"webgpu"
|
|
4137
|
+
].includes(opts.backend)) throw new Error("backend must be auto, webgl, or webgpu");
|
|
4138
|
+
const near = opts.cameraNear ?? .1;
|
|
4139
|
+
const far = opts.cameraFar ?? 5e3;
|
|
4140
|
+
if (!Number.isFinite(near) || near <= 0) throw new Error("cameraNear must be finite and positive");
|
|
4141
|
+
if (!Number.isFinite(far) || far <= near) throw new Error("cameraFar must be finite and greater than cameraNear");
|
|
4142
|
+
if (opts.reverseDepthBuffer && opts.logarithmicDepthBuffer) throw new Error("reverseDepthBuffer and logarithmicDepthBuffer are mutually exclusive");
|
|
4143
|
+
if (opts.autoWorldOrigin !== void 0) nextWorldOrigin([
|
|
4144
|
+
0,
|
|
4145
|
+
0,
|
|
4146
|
+
0
|
|
4147
|
+
], [
|
|
4148
|
+
0,
|
|
4149
|
+
0,
|
|
4150
|
+
0
|
|
4151
|
+
], opts.autoWorldOrigin);
|
|
4152
|
+
}
|
|
4153
|
+
//#endregion
|
|
4154
|
+
//#region src/client.ts
|
|
4155
|
+
function buildAssetStack(renderer, opts) {
|
|
4156
|
+
if (opts.assets === void 0) return {
|
|
4157
|
+
cache: void 0,
|
|
4158
|
+
materials: new MaterialResolver()
|
|
4159
|
+
};
|
|
4160
|
+
const provider = opts.assets.provider ?? createUrlAssetProvider(opts.assets.baseUrl ?? (typeof location !== "undefined" ? location.href : "http://localhost/"), opts.assets.index, { ...opts.assets.variant !== void 0 ? { variant: opts.assets.variant } : {} });
|
|
4161
|
+
return {
|
|
4162
|
+
cache: new AssetCache(provider, createGltfLoader(renderer.three, opts.decoders ?? {})),
|
|
4163
|
+
materials: new MaterialResolver(provider, opts.materialBaker)
|
|
4164
|
+
};
|
|
4165
|
+
}
|
|
4166
|
+
const NO_UNSUB = () => {};
|
|
4167
|
+
/** Consecutive throwing frames before the automatic loop gives up (and says so on `onError`). */
|
|
4168
|
+
const MAX_CONSECUTIVE_FRAME_FAILURES = 5;
|
|
4169
|
+
function describeError(error) {
|
|
4170
|
+
return error instanceof Error ? error.message : String(error);
|
|
4171
|
+
}
|
|
4172
|
+
/**
|
|
4173
|
+
* Create a client bound to a kernel message link (Worker/MessagePort). The renderer-free core
|
|
4174
|
+
* (`createClientCore`) applies keyframes/deltas into a scene mirror + interpolation buffer and
|
|
4175
|
+
* dispatches events; this wraps it with the three.js backend and a frame loop.
|
|
4176
|
+
*
|
|
4177
|
+
* Asynchronous because selecting a graphics backend is: `backend` defaults to `'auto'`, which
|
|
4178
|
+
* probes WebGPU and falls back to WebGL. Pass `backend: 'webgl'` to skip the probe — capture and
|
|
4179
|
+
* golden paths do, because a pinned backend is what makes a frame byte-stable.
|
|
4180
|
+
*/
|
|
4181
|
+
async function createClient(link, opts = {}) {
|
|
4182
|
+
throwIfAborted(opts.signal);
|
|
4183
|
+
const renderer = await Renderer.create(opts);
|
|
4184
|
+
let client;
|
|
4185
|
+
try {
|
|
4186
|
+
throwIfAborted(opts.signal);
|
|
4187
|
+
client = createClientWithRenderer(link, opts, renderer);
|
|
4188
|
+
throwIfAborted(opts.signal);
|
|
4189
|
+
return client;
|
|
4190
|
+
} catch (error) {
|
|
4191
|
+
if (client !== void 0) client.dispose();
|
|
4192
|
+
else renderer.dispose();
|
|
4193
|
+
throw error;
|
|
4194
|
+
}
|
|
4195
|
+
}
|
|
4196
|
+
/** Reject an aborted mount the standard way (`AbortError`), before anything is wired. */
|
|
4197
|
+
function throwIfAborted(signal) {
|
|
4198
|
+
if (signal === void 0 || !signal.aborted) return;
|
|
4199
|
+
if (typeof signal.throwIfAborted === "function") signal.throwIfAborted();
|
|
4200
|
+
throw new DOMException("The client mount was aborted", "AbortError");
|
|
4201
|
+
}
|
|
4202
|
+
function createClientWithRenderer(link, opts, renderer) {
|
|
4203
|
+
validateSceneOptimizationOptions(opts.sceneOptimization);
|
|
4204
|
+
const { cache: assets, materials } = buildAssetStack(renderer, opts);
|
|
4205
|
+
const backend = new ThreeSceneBackend(renderer.worldRoot, assets, renderer, materials, opts.sceneOptimization);
|
|
4206
|
+
for (const kind of opts.kinds ?? []) backend.registerKind(kind);
|
|
4207
|
+
let disposeCore;
|
|
4208
|
+
let raf;
|
|
4209
|
+
try {
|
|
4210
|
+
const core = createClientCore({
|
|
4211
|
+
link,
|
|
4212
|
+
backend,
|
|
4213
|
+
...opts.interpolationDelayTicks !== void 0 ? { interpolationDelayTicks: opts.interpolationDelayTicks } : {}
|
|
4214
|
+
});
|
|
4215
|
+
disposeCore = core.dispose;
|
|
4216
|
+
backend.bindMirror(core.mirror);
|
|
4217
|
+
let sceneCamera = opts.sceneCamera;
|
|
4218
|
+
if (sceneCamera !== void 0) applySceneCamera(sceneCamera, renderer);
|
|
4219
|
+
const nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
4220
|
+
function renderFrame(at) {
|
|
4221
|
+
const t = at ?? nowMs();
|
|
4222
|
+
core.sampleTransforms(t, (id, transform) => {
|
|
4223
|
+
backend.setTransform(id, transform);
|
|
4224
|
+
if (sceneCamera?.mode === "follow" && id === sceneCamera.entity) applySceneCamera(sceneCamera, renderer, transform);
|
|
4225
|
+
});
|
|
4226
|
+
const buffer = core.buffer;
|
|
4227
|
+
const tick = buffer?.estimateRenderTick(t);
|
|
4228
|
+
if (buffer !== void 0 && tick !== void 0 && buffer.latestTick !== void 0) backend.updateLiveAnimations(Math.max(0, Math.min(tick, buffer.latestTick)), buffer.tickRate, renderer.camera);
|
|
4229
|
+
backend.prepareFrame();
|
|
4230
|
+
renderer.render();
|
|
4231
|
+
}
|
|
4232
|
+
let disposed = false;
|
|
4233
|
+
if (opts.frameLoop !== "manual") {
|
|
4234
|
+
let consecutiveFailures = 0;
|
|
4235
|
+
const loop = () => {
|
|
4236
|
+
raf = void 0;
|
|
4237
|
+
if (disposed) return;
|
|
4238
|
+
let stop = false;
|
|
4239
|
+
try {
|
|
4240
|
+
renderFrame();
|
|
4241
|
+
consecutiveFailures = 0;
|
|
4242
|
+
} catch (error) {
|
|
4243
|
+
consecutiveFailures++;
|
|
4244
|
+
stop = renderer.deviceLost !== void 0 || consecutiveFailures >= MAX_CONSECUTIVE_FRAME_FAILURES;
|
|
4245
|
+
core.reportError({
|
|
4246
|
+
source: "frame",
|
|
4247
|
+
message: stop ? `frame loop stopped after ${consecutiveFailures} failed frame(s): ${describeError(error)}` : `render frame failed: ${describeError(error)}`,
|
|
4248
|
+
cause: error
|
|
4249
|
+
});
|
|
4250
|
+
} finally {
|
|
4251
|
+
if (!stop && !disposed && renderer.deviceLost === void 0) raf = requestAnimationFrame(loop);
|
|
4252
|
+
}
|
|
4253
|
+
};
|
|
4254
|
+
raf = requestAnimationFrame(loop);
|
|
4255
|
+
}
|
|
4256
|
+
link.postMessage({
|
|
4257
|
+
type: "control",
|
|
4258
|
+
control: { action: "request-keyframe" }
|
|
4259
|
+
});
|
|
4260
|
+
return {
|
|
4261
|
+
renderer,
|
|
4262
|
+
backend,
|
|
4263
|
+
get tick() {
|
|
4264
|
+
return core.tick;
|
|
4265
|
+
},
|
|
4266
|
+
setCamera: (pose) => {
|
|
4267
|
+
sceneCamera = void 0;
|
|
4268
|
+
renderer.setCamera(pose);
|
|
4269
|
+
},
|
|
4270
|
+
sendCommand: core.sendCommand,
|
|
4271
|
+
command: core.command,
|
|
4272
|
+
control: core.control,
|
|
4273
|
+
onEvent: core.onEvent,
|
|
4274
|
+
onDiag: core.onDiag,
|
|
4275
|
+
onError: core.onError,
|
|
4276
|
+
get: core.get,
|
|
4277
|
+
entities: core.entities,
|
|
4278
|
+
renderFrame,
|
|
4279
|
+
ready: async () => {
|
|
4280
|
+
await assets?.whenIdle();
|
|
4281
|
+
await backend.whenReady();
|
|
4282
|
+
},
|
|
4283
|
+
objectCount: () => backend.count(),
|
|
4284
|
+
entityForIntersection: (hit) => backend.entityForIntersection(hit),
|
|
4285
|
+
getObject: (id) => backend.getObject(id),
|
|
4286
|
+
dispose: () => {
|
|
4287
|
+
if (disposed) return;
|
|
4288
|
+
disposed = true;
|
|
4289
|
+
if (raf !== void 0) cancelAnimationFrame(raf);
|
|
4290
|
+
core.dispose();
|
|
4291
|
+
backend.dispose();
|
|
4292
|
+
assets?.dispose();
|
|
4293
|
+
renderer.dispose();
|
|
4294
|
+
}
|
|
4295
|
+
};
|
|
4296
|
+
} catch (error) {
|
|
4297
|
+
if (raf !== void 0) cancelAnimationFrame(raf);
|
|
4298
|
+
disposeCore?.();
|
|
4299
|
+
backend.dispose();
|
|
4300
|
+
assets?.dispose();
|
|
4301
|
+
renderer.dispose();
|
|
4302
|
+
throw error;
|
|
4303
|
+
}
|
|
4304
|
+
}
|
|
4305
|
+
/**
|
|
4306
|
+
* Boot a client directly from a serialized keyframe with no live kernel — the capture page
|
|
4307
|
+
* and replay viewer use this (docs-src/guide/three-surface.md). With gltf renderables, await
|
|
4308
|
+
* `ready()` before the deterministic frame; clip poses derive from the keyframe tick.
|
|
4309
|
+
*
|
|
4310
|
+
* Like `createClient`, `backend` defaults to `'auto'`; pin `'webgl'` for a byte-stable frame.
|
|
4311
|
+
*/
|
|
4312
|
+
async function createSnapshotViewer(keyframe, opts = {}) {
|
|
4313
|
+
throwIfAborted(opts.signal);
|
|
4314
|
+
const renderer = await Renderer.create(opts);
|
|
4315
|
+
let viewer;
|
|
4316
|
+
try {
|
|
4317
|
+
throwIfAborted(opts.signal);
|
|
4318
|
+
viewer = createSnapshotViewerWithRenderer(keyframe, opts, renderer);
|
|
4319
|
+
throwIfAborted(opts.signal);
|
|
4320
|
+
return viewer;
|
|
4321
|
+
} catch (error) {
|
|
4322
|
+
if (viewer !== void 0) viewer.dispose();
|
|
4323
|
+
else renderer.dispose();
|
|
4324
|
+
throw error;
|
|
4325
|
+
}
|
|
4326
|
+
}
|
|
4327
|
+
function createSnapshotViewerWithRenderer(keyframe, opts, renderer) {
|
|
4328
|
+
validateSceneOptimizationOptions(opts.sceneOptimization);
|
|
4329
|
+
const { cache: assets, materials } = buildAssetStack(renderer, opts);
|
|
4330
|
+
const backend = new ThreeSceneBackend(renderer.worldRoot, assets, renderer, materials, opts.sceneOptimization);
|
|
4331
|
+
try {
|
|
4332
|
+
for (const kind of opts.kinds ?? []) backend.registerKind(kind);
|
|
4333
|
+
const mirror = new SceneMirror();
|
|
4334
|
+
backend.bindMirror(mirror);
|
|
4335
|
+
mirror.applyKeyframe(keyframe);
|
|
4336
|
+
mirror.reconcile(backend);
|
|
4337
|
+
const transforms = mirror.transforms();
|
|
4338
|
+
if (opts.sceneCamera !== void 0) applySceneCamera(opts.sceneCamera, renderer, opts.sceneCamera.mode === "follow" ? transforms.get(opts.sceneCamera.entity) : void 0);
|
|
4339
|
+
for (const [id, t] of transforms) backend.setTransform(id, t);
|
|
4340
|
+
let disposed = false;
|
|
4341
|
+
return {
|
|
4342
|
+
renderer,
|
|
4343
|
+
backend,
|
|
4344
|
+
get tick() {
|
|
4345
|
+
return mirror.tick;
|
|
4346
|
+
},
|
|
4347
|
+
setCamera: (pose) => renderer.setCamera(pose),
|
|
4348
|
+
sendCommand: () => {},
|
|
4349
|
+
command: () => {},
|
|
4350
|
+
control: () => {},
|
|
4351
|
+
onEvent: () => NO_UNSUB,
|
|
4352
|
+
onDiag: () => NO_UNSUB,
|
|
4353
|
+
onError: () => NO_UNSUB,
|
|
4354
|
+
get: (id, component) => mirror.get(id, component),
|
|
4355
|
+
entities: () => mirror.entities(),
|
|
4356
|
+
renderFrame: () => {
|
|
4357
|
+
backend.setAnimationTick(keyframe.tick, keyframe.tickRate);
|
|
4358
|
+
backend.prepareFrame();
|
|
4359
|
+
renderer.render();
|
|
4360
|
+
},
|
|
4361
|
+
ready: async () => {
|
|
4362
|
+
await assets?.whenIdle();
|
|
4363
|
+
await backend.whenReady();
|
|
4364
|
+
},
|
|
4365
|
+
objectCount: () => backend.count(),
|
|
4366
|
+
entityForIntersection: (hit) => backend.entityForIntersection(hit),
|
|
4367
|
+
getObject: (id) => backend.getObject(id),
|
|
4368
|
+
dispose: () => {
|
|
4369
|
+
if (disposed) return;
|
|
4370
|
+
disposed = true;
|
|
4371
|
+
backend.dispose();
|
|
4372
|
+
assets?.dispose();
|
|
4373
|
+
renderer.dispose();
|
|
4374
|
+
}
|
|
4375
|
+
};
|
|
4376
|
+
} catch (error) {
|
|
4377
|
+
backend.dispose();
|
|
4378
|
+
assets?.dispose();
|
|
4379
|
+
renderer.dispose();
|
|
4380
|
+
throw error;
|
|
4381
|
+
}
|
|
4382
|
+
}
|
|
4383
|
+
/**
|
|
4384
|
+
* Create a viewer with no kernel and no snapshot — just a renderer + camera over an empty
|
|
4385
|
+
* scene. For client-side capabilities (terrain, custom three.js objects via `renderer.scene`).
|
|
4386
|
+
*/
|
|
4387
|
+
function createViewer(opts = {}) {
|
|
4388
|
+
return createSnapshotViewer(emptyKeyframe(), opts);
|
|
4389
|
+
}
|
|
4390
|
+
function emptyKeyframe() {
|
|
4391
|
+
return {
|
|
4392
|
+
kind: "keyframe",
|
|
4393
|
+
v: 1,
|
|
4394
|
+
engine: "",
|
|
4395
|
+
tick: 0,
|
|
4396
|
+
tickRate: 30,
|
|
4397
|
+
seed: "",
|
|
4398
|
+
nextEntitySeq: 0,
|
|
4399
|
+
rng: {
|
|
4400
|
+
algo: "sfc32",
|
|
4401
|
+
state: [
|
|
4402
|
+
0,
|
|
4403
|
+
0,
|
|
4404
|
+
0,
|
|
4405
|
+
0
|
|
4406
|
+
]
|
|
4407
|
+
},
|
|
4408
|
+
entities: {},
|
|
4409
|
+
plugins: {}
|
|
4410
|
+
};
|
|
4411
|
+
}
|
|
4412
|
+
/**
|
|
4413
|
+
* The one-call browser mount: create the client on the link, apply the scene's `camera`, wire
|
|
4414
|
+
* its `input` bindings + emit rules to `client.command`, and keep the renderer sized to the
|
|
4415
|
+
* canvas. The kernel side is the host's `KernelHost` in a Worker built with `buildWorld` (which
|
|
4416
|
+
* installs the same scene's scripts). Returns the client plus a disposer.
|
|
4417
|
+
*
|
|
4418
|
+
* This is the one entry point a page needs. It is asynchronous because `backend` defaults to
|
|
4419
|
+
* `'auto'`, which probes WebGPU and falls back to WebGL; pass `backend: 'webgl'` to skip the probe.
|
|
4420
|
+
*/
|
|
4421
|
+
async function mountExperience(opts) {
|
|
4422
|
+
const client = await createClient(opts.link, mountClientOptions(opts));
|
|
4423
|
+
if (opts.signal?.aborted === true) {
|
|
4424
|
+
client.dispose();
|
|
4425
|
+
throwIfAborted(opts.signal);
|
|
4426
|
+
}
|
|
4427
|
+
return mountClient(opts, client);
|
|
4428
|
+
}
|
|
4429
|
+
/** The device pixel ratio a live page renders at, capped so a 3x phone does not cost 9x the fill. */
|
|
4430
|
+
function livePixelRatio() {
|
|
4431
|
+
return Math.min(typeof devicePixelRatio === "number" && devicePixelRatio > 0 ? devicePixelRatio : 1, 2);
|
|
4432
|
+
}
|
|
4433
|
+
function mountClientOptions(opts) {
|
|
4434
|
+
const { link: _link, scene, canvas, inputTarget: _target, pollMs: _poll, autoResize: _resize, ...clientOpts } = opts;
|
|
4435
|
+
const width = clientOpts.width ?? (canvas.clientWidth || 1280);
|
|
4436
|
+
const height = clientOpts.height ?? (canvas.clientHeight || 720);
|
|
4437
|
+
return {
|
|
4438
|
+
pixelRatio: livePixelRatio(),
|
|
4439
|
+
antialias: true,
|
|
4440
|
+
preserveDrawingBuffer: false,
|
|
4441
|
+
...clientOpts,
|
|
4442
|
+
sceneCamera: scene.camera,
|
|
4443
|
+
canvas,
|
|
4444
|
+
width,
|
|
4445
|
+
height
|
|
4446
|
+
};
|
|
4447
|
+
}
|
|
4448
|
+
function mountClient(opts, client) {
|
|
4449
|
+
const { scene, canvas, inputTarget, pollMs, autoResize } = opts;
|
|
4450
|
+
const disposers = [];
|
|
4451
|
+
try {
|
|
4452
|
+
if (scene.camera !== void 0) applySceneCamera(scene.camera, client.renderer);
|
|
4453
|
+
let input;
|
|
4454
|
+
if (scene.input !== void 0) {
|
|
4455
|
+
const target = inputTarget ?? (typeof window !== "undefined" ? window : void 0);
|
|
4456
|
+
input = new InputMap({
|
|
4457
|
+
...scene.input,
|
|
4458
|
+
...target ? { target } : {}
|
|
4459
|
+
});
|
|
4460
|
+
const map = input;
|
|
4461
|
+
disposers.push(() => map.dispose());
|
|
4462
|
+
if (typeof document !== "undefined") {
|
|
4463
|
+
let resume;
|
|
4464
|
+
const visibility = () => {
|
|
4465
|
+
if (document.hidden) resume ??= map.suspend();
|
|
4466
|
+
else {
|
|
4467
|
+
resume?.();
|
|
4468
|
+
resume = void 0;
|
|
4469
|
+
}
|
|
4470
|
+
};
|
|
4471
|
+
document.addEventListener("visibilitychange", visibility);
|
|
4472
|
+
visibility();
|
|
4473
|
+
disposers.push(() => {
|
|
4474
|
+
document.removeEventListener("visibilitychange", visibility);
|
|
4475
|
+
resume?.();
|
|
4476
|
+
});
|
|
4477
|
+
}
|
|
4478
|
+
disposers.push(applyInputRules(scene.input, map, (type, payload) => client.command(type, payload), pollMs !== void 0 ? { pollMs } : void 0));
|
|
4479
|
+
}
|
|
4480
|
+
if (autoResize ?? typeof window !== "undefined") {
|
|
4481
|
+
const onResize = () => {
|
|
4482
|
+
const width = canvas.clientWidth || (typeof window !== "undefined" ? window.innerWidth : 0);
|
|
4483
|
+
const height = canvas.clientHeight || (typeof window !== "undefined" ? window.innerHeight : 0);
|
|
4484
|
+
if (width <= 0 || height <= 0) return;
|
|
4485
|
+
if (opts.pixelRatio === void 0) client.renderer.setPixelRatio(livePixelRatio());
|
|
4486
|
+
client.renderer.setSize(width, height);
|
|
4487
|
+
};
|
|
4488
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
4489
|
+
const observer = new ResizeObserver(() => onResize());
|
|
4490
|
+
observer.observe(canvas);
|
|
4491
|
+
disposers.push(() => observer.disconnect());
|
|
4492
|
+
} else if (typeof window !== "undefined") {
|
|
4493
|
+
window.addEventListener("resize", onResize);
|
|
4494
|
+
disposers.push(() => window.removeEventListener("resize", onResize));
|
|
4495
|
+
}
|
|
4496
|
+
}
|
|
4497
|
+
return {
|
|
4498
|
+
client,
|
|
4499
|
+
input,
|
|
4500
|
+
dispose: () => {
|
|
4501
|
+
for (const off of disposers) off();
|
|
4502
|
+
client.dispose();
|
|
4503
|
+
}
|
|
4504
|
+
};
|
|
4505
|
+
} catch (error) {
|
|
4506
|
+
for (const off of disposers) off();
|
|
4507
|
+
client.dispose();
|
|
4508
|
+
throw error;
|
|
4509
|
+
}
|
|
4510
|
+
}
|
|
4511
|
+
//#endregion
|
|
4512
|
+
//#region src/sky/star-catalog.ts
|
|
4513
|
+
const MAGIC = 1381258061;
|
|
4514
|
+
const VERSION = 1;
|
|
4515
|
+
const HEADER_BYTES = 16;
|
|
4516
|
+
const RAD = Math.PI / 180;
|
|
4517
|
+
function clamp(value, min, max) {
|
|
4518
|
+
return Math.min(max, Math.max(min, value));
|
|
4519
|
+
}
|
|
4520
|
+
/** Encode catalog rows as molen/stars@1 bytes. */
|
|
4521
|
+
function encodeStarCatalog(rows) {
|
|
4522
|
+
const count = rows.length;
|
|
4523
|
+
const bytes = new Uint8Array(HEADER_BYTES + count * 6);
|
|
4524
|
+
const view = new DataView(bytes.buffer);
|
|
4525
|
+
view.setUint32(0, MAGIC, true);
|
|
4526
|
+
view.setUint16(4, VERSION, true);
|
|
4527
|
+
view.setUint32(8, count, true);
|
|
4528
|
+
const ra = HEADER_BYTES;
|
|
4529
|
+
const dec = ra + count * 2;
|
|
4530
|
+
const mag = dec + count * 2;
|
|
4531
|
+
const bv = mag + count;
|
|
4532
|
+
rows.forEach(([r, d, m, b], i) => {
|
|
4533
|
+
const wrapped = (r % 360 + 360) % 360;
|
|
4534
|
+
view.setUint16(ra + i * 2, Math.round(wrapped / 360 * 65536) % 65536, true);
|
|
4535
|
+
view.setInt16(dec + i * 2, Math.round(clamp(d, -90, 90) / 90 * 32767), true);
|
|
4536
|
+
view.setUint8(mag + i, Math.round(clamp((m + 2) * 25, 0, 255)));
|
|
4537
|
+
view.setUint8(bv + i, Math.round(clamp((b + 1) * 50, 0, 255)));
|
|
4538
|
+
});
|
|
4539
|
+
return bytes;
|
|
4540
|
+
}
|
|
4541
|
+
/** Decode molen/stars@1 bytes to catalog rows. */
|
|
4542
|
+
function decodeStarCatalogRows(input) {
|
|
4543
|
+
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
|
|
4544
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
4545
|
+
if (bytes.byteLength < HEADER_BYTES || view.getUint32(0, true) !== MAGIC) throw new Error("not a molen/stars@1 catalog");
|
|
4546
|
+
const version = view.getUint16(4, true);
|
|
4547
|
+
if (version !== VERSION) throw new Error(`unsupported star catalog version ${version}`);
|
|
4548
|
+
const count = view.getUint32(8, true);
|
|
4549
|
+
if (bytes.byteLength !== HEADER_BYTES + count * 6) throw new Error(`star catalog is ${bytes.byteLength} bytes; ${count} stars need ${HEADER_BYTES + count * 6}`);
|
|
4550
|
+
const ra = HEADER_BYTES;
|
|
4551
|
+
const dec = ra + count * 2;
|
|
4552
|
+
const mag = dec + count * 2;
|
|
4553
|
+
const bv = mag + count;
|
|
4554
|
+
const rows = [];
|
|
4555
|
+
for (let i = 0; i < count; i++) rows.push([
|
|
4556
|
+
view.getUint16(ra + i * 2, true) / 65536 * 360,
|
|
4557
|
+
view.getInt16(dec + i * 2, true) / 32767 * 90,
|
|
4558
|
+
view.getUint8(mag + i) / 25 - 2,
|
|
4559
|
+
view.getUint8(bv + i) / 50 - 1
|
|
4560
|
+
]);
|
|
4561
|
+
return rows;
|
|
4562
|
+
}
|
|
4563
|
+
/**
|
|
4564
|
+
* Decode a molen/stars@1 catalog into sky stars (J2000 equatorial directions, the same frame the
|
|
4565
|
+
* bundled catalog uses) for `SkyVisual.setStars` or `Renderer.setStarCatalog`.
|
|
4566
|
+
*/
|
|
4567
|
+
function decodeStarCatalog(input) {
|
|
4568
|
+
return decodeStarCatalogRows(input).map(([ra, dec, magnitude, bv]) => ({
|
|
4569
|
+
direction: [
|
|
4570
|
+
Math.cos(ra * RAD) * Math.cos(dec * RAD),
|
|
4571
|
+
Math.sin(ra * RAD) * Math.cos(dec * RAD),
|
|
4572
|
+
Math.sin(dec * RAD)
|
|
4573
|
+
],
|
|
4574
|
+
magnitude,
|
|
4575
|
+
color: `#${starColor(bv).getHexString()}`
|
|
4576
|
+
}));
|
|
4577
|
+
}
|
|
4578
|
+
//#endregion
|
|
4579
|
+
export { AdaptiveQualityController, AssetCache, FrameAdmissionQueue, InputMap, InterpolationBuffer, MaterialResolver, Renderer, SceneMirror, SkyVisual, THREE, ThreeSceneBackend, WeatherVisual, applyEnvironment, applyInputRules, applySceneCamera, computeClipTime, createClient, createClientCore, createGltfLoader, createGpuFrameTimer, createModelSignalVisual, createSnapshotViewer, createUrlAssetProvider, createViewer, decodeStarCatalog, decodeStarCatalogRows, defaultEnvironment, defaultSkyPalette, encodeStarCatalog, evaluateEarthSky, followCameraPose, lerp3, localCommand, materialFromBaked, mountExperience, nextWorldOrigin, nlerp4, normalizeInputAxis, orthoFrustum, readModelSignals, resolveAction, resolveWeather, skyTimeMs, starDirection, weatherProfile };
|