@miris-inc/core 0.0.8-b1f8bb4 → 0.0.8-b408cae

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js ADDED
@@ -0,0 +1,2402 @@
1
+ class LodStore {
2
+ #keyMap = /* @__PURE__ */ new Map();
3
+ #idMap = /* @__PURE__ */ new Map();
4
+ forKey(key) {
5
+ return this.#keyMap.get(key);
6
+ }
7
+ forId(id) {
8
+ return this.#idMap.get(id);
9
+ }
10
+ setKey(key, lod) {
11
+ this.#keyMap.set(key, lod);
12
+ }
13
+ setId(id, lod) {
14
+ return this.#idMap.set(id, lod);
15
+ }
16
+ delete(lod) {
17
+ this.#keyMap.delete(lod.key);
18
+ this.#idMap.delete(lod.id);
19
+ }
20
+ deleteKey(key) {
21
+ this.#keyMap.delete(key);
22
+ }
23
+ deleteId(id) {
24
+ this.#idMap.delete(id);
25
+ }
26
+ }
27
+ class Lod {
28
+ /// three/Lod object that this core/Lod object represents. We use unknown to avoid a circular dependency.
29
+ #key;
30
+ /// flag that tells us whether this Lod uses the original spark packedsplats data format (false) or uses the newer extsplats format (true)
31
+ useExtSplats = false;
32
+ /// if useExtSplats is false, this contains the PackedSplats data. if that flag is true, then this contains bytes 0 - 15 of ExtSplats
33
+ #splats = null;
34
+ /// is useExtSplats is false, this is null. if that flag is true, this contains bytes 16 - 31
35
+ splatsExtendedData = null;
36
+ /// Bounds of this lod in world space, retrieved when the lod is first created and never updated
37
+ /// @deprecated Use the local bounds and transform whenever possible
38
+ #cachedWorldBounds = null;
39
+ /// bounds of this lod chunk, relative to the stream. used to calculate the stream's total bounds
40
+ #localBounds = null;
41
+ #transform = null;
42
+ #lodIndex = null;
43
+ #paddingCount = 0;
44
+ sh1Data = null;
45
+ sh1Max = 1;
46
+ sh2Data = null;
47
+ sh2Max = 1;
48
+ sh3Data = null;
49
+ sh3Max = 1;
50
+ sh3ExtendedData = null;
51
+ get key() {
52
+ return this.#key ?? null;
53
+ }
54
+ set key(key) {
55
+ this.store.deleteKey(this.key);
56
+ if (key || 0 === key) {
57
+ this.store.setKey(key, this);
58
+ }
59
+ this.#key = key;
60
+ }
61
+ set splats(splats) {
62
+ this.#splats = splats;
63
+ }
64
+ get splats() {
65
+ return this.#splats;
66
+ }
67
+ /**
68
+ * Sets the cached world bounds of this object
69
+ *
70
+ * @deprecated set the local bounds and transform as needed
71
+ */
72
+ set bounds(bounds) {
73
+ this.#cachedWorldBounds = bounds;
74
+ }
75
+ /**
76
+ * Retrieves the cached world bounds of this object
77
+ *
78
+ * @deprecated Retrieve the local bounds and transform as needed
79
+ */
80
+ get bounds() {
81
+ console.warn("`bounds` is deprecated, use `localBounds` instead");
82
+ return this.#cachedWorldBounds;
83
+ }
84
+ /**
85
+ * Sets the local bounds of this lod
86
+ */
87
+ set localBounds(bounds) {
88
+ this.#localBounds = bounds;
89
+ }
90
+ /**
91
+ * Retrieves the local bounds of this lod
92
+ */
93
+ get localBounds() {
94
+ return this.#localBounds;
95
+ }
96
+ set lodIndex(index) {
97
+ this.#lodIndex = index;
98
+ }
99
+ get lodIndex() {
100
+ return this.#lodIndex;
101
+ }
102
+ set paddingCount(count) {
103
+ this.#paddingCount = count;
104
+ }
105
+ get paddingCount() {
106
+ return this.#paddingCount;
107
+ }
108
+ set transform(transform) {
109
+ this.#transform = transform;
110
+ }
111
+ get transform() {
112
+ return this.#transform;
113
+ }
114
+ setSh1(sh1Data, sh1Max) {
115
+ this.sh1Data = sh1Data;
116
+ this.sh1Max = sh1Max;
117
+ }
118
+ setSh2(sh2Data, sh2Max) {
119
+ this.sh2Data = sh2Data;
120
+ this.sh2Max = sh2Max;
121
+ }
122
+ setSh3(sh3Data, sh3Max) {
123
+ this.sh3Data = sh3Data;
124
+ this.sh3Max = sh3Max;
125
+ }
126
+ dispose() {
127
+ const key = this.#key;
128
+ key?.dispose?.();
129
+ this.store.delete(this);
130
+ this.#key = null;
131
+ key?.dispose?.();
132
+ this.#splats = null;
133
+ this.splatsExtendedData = null;
134
+ this.#cachedWorldBounds = null;
135
+ this.#transform = null;
136
+ this.sh1Data = null;
137
+ this.sh2Data = null;
138
+ this.sh3Data = null;
139
+ this.sh3ExtendedData = null;
140
+ this.modelRoot?.lods?.delete(this);
141
+ }
142
+ constructor({ id, modelRoot, lodStore }) {
143
+ Object.defineProperties(this, {
144
+ id: { value: id },
145
+ modelRoot: { value: modelRoot },
146
+ store: { value: lodStore }
147
+ });
148
+ lodStore.setId(id, this);
149
+ modelRoot.add(this);
150
+ }
151
+ }
152
+ class Change {
153
+ constructor({ type, lod }) {
154
+ Object.defineProperties(this, {
155
+ type: { value: type },
156
+ lod: { value: lod }
157
+ });
158
+ }
159
+ }
160
+ class ModelRoot {
161
+ static #keyMap = /* @__PURE__ */ new Map();
162
+ static #idMap = /* @__PURE__ */ new Map();
163
+ static forKey(key) {
164
+ return this.#keyMap.get(key);
165
+ }
166
+ static forId(id) {
167
+ return this.#idMap.get(id);
168
+ }
169
+ #key;
170
+ get key() {
171
+ return this.#key ?? null;
172
+ }
173
+ set key(key) {
174
+ ModelRoot.#keyMap.delete(this.key);
175
+ if (key || 0 === key) {
176
+ ModelRoot.#keyMap.set(key, this);
177
+ }
178
+ this.#key = key;
179
+ }
180
+ #lods = /* @__PURE__ */ new Set();
181
+ get lods() {
182
+ return this.#lods;
183
+ }
184
+ #transform;
185
+ set transform(transform) {
186
+ this.#transform = transform;
187
+ }
188
+ get transform() {
189
+ return this.#transform;
190
+ }
191
+ constructor({ id, stream }) {
192
+ Object.defineProperties(this, {
193
+ id: { value: id },
194
+ stream: { value: stream }
195
+ });
196
+ ModelRoot.#idMap.set(id, this);
197
+ stream.add(this);
198
+ }
199
+ add(lod) {
200
+ this.#lods.add(lod);
201
+ }
202
+ dispose() {
203
+ const lods = [...this.#lods];
204
+ this.#lods.clear();
205
+ for (const lod of lods) {
206
+ lod.dispose();
207
+ }
208
+ ModelRoot.#keyMap.delete(this.key);
209
+ ModelRoot.#idMap.delete(this.id);
210
+ this.#key = null;
211
+ }
212
+ }
213
+ class AttributeCache {
214
+ static #cache = /* @__PURE__ */ new Map();
215
+ static #nextId = 1;
216
+ // checkSum is important for early detection of critical regressions
217
+ // in lifetime management of cache entries. Note that such regressions
218
+ // cause OOM kills (crashes) on iOS
219
+ // Do not remove, especially not in response to checksum mismatch errors.
220
+ static #checkSum = 0;
221
+ static #checkSumModulo = 2 ** 32;
222
+ static #lastReportedCheckSumDifference = 0;
223
+ static #addCheckSum(id) {
224
+ this.#checkSum = (this.#checkSum + id) % this.#checkSumModulo;
225
+ }
226
+ static #removeCheckSum(id) {
227
+ this.#checkSum = (this.#checkSum - id) % this.#checkSumModulo;
228
+ if (this.#checkSum < 0) this.#checkSum += this.#checkSumModulo;
229
+ }
230
+ static getCheckSum() {
231
+ return this.#checkSum;
232
+ }
233
+ static getConsecutiveIds(howMany) {
234
+ const result = this.#nextId;
235
+ this.#nextId += howMany;
236
+ return result;
237
+ }
238
+ static addWithId(data, id) {
239
+ this.#addCheckSum(id);
240
+ this.#cache.set(id, data);
241
+ }
242
+ static add(data) {
243
+ const id = this.#nextId++;
244
+ this.addWithId(data, id);
245
+ return id;
246
+ }
247
+ static get(id) {
248
+ const data = this.#cache.get(id);
249
+ if (data === void 0) {
250
+ throw new Error(`Attribute with id ${id} not found in cache`);
251
+ }
252
+ return data;
253
+ }
254
+ static remove(idOrIds) {
255
+ if (Array.isArray(idOrIds)) {
256
+ for (const id of idOrIds) {
257
+ this.#cache.delete(id);
258
+ this.#removeCheckSum(id);
259
+ }
260
+ } else {
261
+ this.#cache.delete(idOrIds);
262
+ this.#removeCheckSum(idOrIds);
263
+ }
264
+ }
265
+ static validateCheckSum(checkSumWasm) {
266
+ if (checkSumWasm != this.getCheckSum()) {
267
+ let difference = checkSumWasm - this.getCheckSum();
268
+ if (difference < 0) difference += this.#checkSumModulo;
269
+ if (difference != this.#lastReportedCheckSumDifference) {
270
+ console.error(
271
+ `ID checksum mismatch between WASM and TypeScript sides! ${checkSumWasm} ${this.getCheckSum()}`
272
+ );
273
+ this.#lastReportedCheckSumDifference = difference;
274
+ }
275
+ }
276
+ }
277
+ }
278
+ class Stream extends EventTarget {
279
+ static _idMap = /* @__PURE__ */ new Map();
280
+ static _keyMap = /* @__PURE__ */ new Map();
281
+ static forId(id) {
282
+ if (!id) return;
283
+ return this._idMap.get(id);
284
+ }
285
+ static forKey(key) {
286
+ return this._keyMap.get(key);
287
+ }
288
+ #key;
289
+ #loadedRenderableData = false;
290
+ #variantHierarchies = {};
291
+ #prefetchOnly = false;
292
+ /**
293
+ * @internal
294
+ */
295
+ _addVariantCollection(hierarchyId) {
296
+ if (!this.#variantHierarchies[hierarchyId]) {
297
+ this.#variantHierarchies[hierarchyId] = { id: hierarchyId, children: [] };
298
+ }
299
+ }
300
+ /**
301
+ * @internal
302
+ */
303
+ _findAndAddToVariantSet(parentId, variant) {
304
+ const addToNode = (node) => {
305
+ if (!node) return false;
306
+ if (node.id === parentId) {
307
+ if (node.children) {
308
+ node.children.push(variant);
309
+ } else if (variant.type === "option") {
310
+ if (!node.options) node.options = [];
311
+ node.options.push(variant);
312
+ } else {
313
+ if (!node.nestedSets) node.nestedSets = [];
314
+ node.nestedSets.push(variant);
315
+ }
316
+ return true;
317
+ }
318
+ if (Array.isArray(node.children)) {
319
+ for (const child of node.children) {
320
+ if (addToNode(child)) return true;
321
+ }
322
+ }
323
+ if (Array.isArray(node.nestedSets)) {
324
+ for (const nested of node.nestedSets) {
325
+ if (addToNode(nested)) return true;
326
+ }
327
+ }
328
+ if (Array.isArray(node.options)) {
329
+ for (const option of node.options) {
330
+ if (addToNode(option)) return true;
331
+ }
332
+ }
333
+ return false;
334
+ };
335
+ for (const hierarchy of Object.values(this.#variantHierarchies)) {
336
+ if (addToNode(hierarchy)) return;
337
+ }
338
+ }
339
+ /**
340
+ * @internal
341
+ */
342
+ _addVariant(parentId, variant) {
343
+ this._findAndAddToVariantSet(parentId, variant);
344
+ }
345
+ /**
346
+ * @internal
347
+ */
348
+ _exportVariantHierarchies() {
349
+ return Object.entries(this.#variantHierarchies).map(
350
+ ([hierarchyId, hierarchy]) => ({
351
+ hierarchyId: Number(hierarchyId),
352
+ hierarchy
353
+ })
354
+ );
355
+ }
356
+ /**
357
+ * @internal
358
+ */
359
+ _setVariantSelection(variantId) {
360
+ this.client.setVariantSelection(variantId);
361
+ }
362
+ get key() {
363
+ return this.#key ?? null;
364
+ }
365
+ set key(key) {
366
+ if (this.#prefetchOnly) {
367
+ console.log(`[junk] Not setting key ${key} for prefetch-only stream`);
368
+ return;
369
+ }
370
+ Stream._keyMap.delete(this.key);
371
+ if (key || 0 === key) {
372
+ Stream._keyMap.set(key, this);
373
+ }
374
+ this.#key = key;
375
+ }
376
+ // prettier-ignore
377
+ #matrix = [
378
+ 1,
379
+ 0,
380
+ 0,
381
+ 0,
382
+ 0,
383
+ 1,
384
+ 0,
385
+ 0,
386
+ 0,
387
+ 0,
388
+ 1,
389
+ 0,
390
+ 0,
391
+ 0,
392
+ 0,
393
+ 1
394
+ ];
395
+ get matrix() {
396
+ return this.#matrix;
397
+ }
398
+ set matrix(matrix) {
399
+ this.#matrix = matrix;
400
+ const { engine, client } = this;
401
+ const matrixBuffer = engine.malloc(this.#matrix.length * 4);
402
+ engine.heapF32.set(Float32Array.from(this.#matrix), matrixBuffer / 4);
403
+ client.setSceneObjectTransform(this.id, matrixBuffer);
404
+ engine.free(matrixBuffer);
405
+ }
406
+ get boundingBox() {
407
+ const { engine, client } = this;
408
+ const boxBuffer = engine.malloc(6 * 4);
409
+ client.getWorldBoundingBox(this.id, boxBuffer);
410
+ const [cX, cY, cZ, dX, dY, dZ] = Float32Array.from(
411
+ engine.heapF32.subarray(boxBuffer / 4, boxBuffer / 4 + 6)
412
+ );
413
+ if (cX === void 0 || cY === void 0 || cZ === void 0 || dX === void 0 || dY === void 0 || dZ === void 0) return;
414
+ const box = {
415
+ min: {
416
+ x: cX - dX / 2,
417
+ y: cY - dY / 2,
418
+ z: cZ - dZ / 2
419
+ },
420
+ max: {
421
+ x: cX + dX / 2,
422
+ y: cY + dY / 2,
423
+ z: cZ + dZ / 2
424
+ },
425
+ size: {
426
+ x: dX,
427
+ y: dY,
428
+ z: dZ
429
+ },
430
+ center: {
431
+ x: cX,
432
+ y: cY,
433
+ z: cZ
434
+ }
435
+ };
436
+ Object.freeze(box);
437
+ return box;
438
+ }
439
+ #modelRoots = /* @__PURE__ */ new Set();
440
+ get modelRoots() {
441
+ return new Set(this.#modelRoots);
442
+ }
443
+ /**
444
+ * @deprecated Use `modelRoots` instead.
445
+ */
446
+ get chunks() {
447
+ return this.modelRoots;
448
+ }
449
+ constructor(options) {
450
+ super();
451
+ const { scene, uuid } = options;
452
+ Object.defineProperties(this, {
453
+ uuid: { value: uuid, enumerable: true },
454
+ scene: { value: scene, enumerable: true },
455
+ client: { value: scene.client, enumerable: true },
456
+ miris: { value: scene.miris, enumerable: true },
457
+ engine: { value: scene.miris.engine, enumerable: true }
458
+ });
459
+ this._initStream(options);
460
+ Stream._idMap.set(this.id, this);
461
+ scene.add(this);
462
+ }
463
+ _initStream({ uuid, prefetch = false, prefetchMaxDepth = 3, keepPrefetch = false }) {
464
+ this.#prefetchOnly = prefetch;
465
+ const id = prefetch ? this.client.addPrefetchStreamById(uuid, uuid, prefetchMaxDepth, keepPrefetch) : this.client.addStreamById(uuid, uuid, false);
466
+ Object.defineProperty(this, "id", { value: id });
467
+ }
468
+ /**
469
+ * @internal
470
+ */
471
+ async _onStreamLoaded() {
472
+ if (this.#loadedRenderableData) return;
473
+ this.dispatchEvent(new Event("streamloaded"));
474
+ this.scene._onSceneLoaded();
475
+ this.#loadedRenderableData = true;
476
+ }
477
+ /**
478
+ * @internal
479
+ */
480
+ _onRootLoaded() {
481
+ this.dispatchEvent(new Event("rootloaded"));
482
+ }
483
+ add(modelRoot) {
484
+ this.#modelRoots.add(modelRoot);
485
+ }
486
+ end() {
487
+ console.log("ending the stream");
488
+ this.client.removeStream(this.id);
489
+ for (const modelRoot of this.#modelRoots) {
490
+ modelRoot.dispose();
491
+ }
492
+ this.#modelRoots.clear();
493
+ Stream._idMap.delete(this.id);
494
+ Stream._keyMap.delete(this.key);
495
+ if (this.scene.streams.has(this)) {
496
+ this.scene.delete(this);
497
+ }
498
+ }
499
+ }
500
+ let _jsPromise, _wasmPromise;
501
+ const _wasmUrl = ((u) => u.includes("/.vite/") ? u.replace(/\.vite\/[^?#]*/, () => "node_modules/@miris-inc/core/dist/AquaApi.wasm") : u)(new URL("AquaApi.wasm", import.meta.url).href);
502
+ function _getExport(m) {
503
+ return m.default || m;
504
+ }
505
+ function _loadModule(url) {
506
+ return import(/* @vite-ignore */ /* webpackIgnore: true */ /* turbopackIgnore: true */ url).then((m) => {
507
+ const f = _getExport(m);
508
+ if (typeof f === "function") return f;
509
+ throw new Error("bad module");
510
+ }).catch(() => fetch(url).then((r) => {
511
+ if (!r.ok) throw new Error(r.status + " " + url);
512
+ return r.text();
513
+ }).then((text) => {
514
+ const blobUrl = URL.createObjectURL(new Blob([text], { type: "text/javascript" }));
515
+ return import(/* @vite-ignore */ /* webpackIgnore: true */ /* turbopackIgnore: true */ blobUrl).then((m) => {
516
+ URL.revokeObjectURL(blobUrl);
517
+ return _getExport(m);
518
+ });
519
+ }));
520
+ }
521
+ function _factory(...args) {
522
+ if (!_jsPromise) {
523
+ _wasmPromise = fetch(_wasmUrl).then((r) => {
524
+ if (!r.ok || (r.headers.get("content-type") || "").includes("text/html")) return null;
525
+ return r.arrayBuffer();
526
+ }).catch(() => null);
527
+ _jsPromise = _loadModule(((u) => u.includes("/.vite/") ? new URL("/node_modules/@miris-inc/core/dist/AquaApi.js", u).href : u)(new URL("./AquaApi.js", import.meta.url).href)).catch((e) => {
528
+ _jsPromise = _wasmPromise = void 0;
529
+ throw e;
530
+ });
531
+ }
532
+ return Promise.all([_jsPromise, _wasmPromise]).then(([factory, wasmBinary]) => {
533
+ if (wasmBinary) {
534
+ const [opts = {}, ...rest] = args;
535
+ return factory({ ...opts, wasmBinary }, ...rest);
536
+ }
537
+ return factory(...args);
538
+ });
539
+ }
540
+ class Thread {
541
+ static name = "thread";
542
+ static get Worker() {
543
+ throw new Error(
544
+ "Thread could not be initialized because no Worker was supplied. Do you forget to set `static Worker = Worker` on the child class?"
545
+ );
546
+ }
547
+ constructor({ engine }) {
548
+ Object.defineProperty(this, "engine", { value: engine, enumerable: true });
549
+ Object.defineProperty(this, "ready", {
550
+ enumerable: true,
551
+ value: new Promise((resolve) => {
552
+ this.#resolvers.set(0, async () => {
553
+ this.#pending = false;
554
+ this.#resolvers.delete(0);
555
+ resolve(this);
556
+ });
557
+ })
558
+ });
559
+ this.#worker = new this.constructor.Worker({
560
+ name: `decoder-${Thread.#nextWorkerId()}`
561
+ });
562
+ this.#worker.addEventListener("message", this.#message.bind(this));
563
+ }
564
+ static #latestWorkerId = 0;
565
+ static #nextWorkerId() {
566
+ return this.#latestWorkerId += 1;
567
+ }
568
+ #pending = true;
569
+ get pending() {
570
+ return this.#pending;
571
+ }
572
+ #worker;
573
+ #resolvers = /* @__PURE__ */ new Map();
574
+ get pendingRequests() {
575
+ return this.#resolvers.size;
576
+ }
577
+ get terminated() {
578
+ return !this.#worker;
579
+ }
580
+ #latestProcessId = 0;
581
+ #nextProcessId() {
582
+ return this.#latestProcessId += 1;
583
+ }
584
+ async _execute(action, ...args) {
585
+ if (this.pending) {
586
+ throw new Error(
587
+ `Unable to execute ${action} because decoder has not yet been initialized`
588
+ );
589
+ }
590
+ if (!this.#worker) {
591
+ throw new Error(
592
+ `Unable to execute ${action} because decoder has already been terminated`
593
+ );
594
+ }
595
+ return new Promise((resolve) => {
596
+ if (!this.#worker) {
597
+ throw new Error(
598
+ `Unable to execute ${action} because decoder has already been terminated`
599
+ );
600
+ }
601
+ const id = this.#nextProcessId();
602
+ this.#resolvers.set(id, async (result) => {
603
+ this.#resolvers.delete(id);
604
+ resolve(result);
605
+ });
606
+ const transfer = args.filter(
607
+ (arg) => arg instanceof ArrayBuffer
608
+ );
609
+ this.#worker.postMessage({ id, action, args }, transfer);
610
+ });
611
+ }
612
+ #message({
613
+ data
614
+ }) {
615
+ if ("ready" === data) data = { id: 0, result: void 0 };
616
+ const { id, result } = data;
617
+ this.#resolvers.get(id)?.(result);
618
+ }
619
+ _postToWorker(data, transfer) {
620
+ this.#worker?.postMessage(data, transfer ?? []);
621
+ }
622
+ terminate() {
623
+ if (!this.#worker) return;
624
+ this.#worker.terminate();
625
+ this.#worker.removeEventListener("message", this.#message);
626
+ this.#worker = null;
627
+ }
628
+ }
629
+ const jsContent = 'const defineActions = (actions) => {\n self.postMessage("ready");\n self.addEventListener("message", async ({ data }) => {\n if ("ready" === data) return;\n const { id, action, args } = data;\n const [result, ...postMessageArgs] = await Reflect.apply(\n actions[action],\n void 0,\n [...args, id]\n );\n self.postMessage({ id, result }, ...postMessageArgs);\n });\n return actions;\n};\nconst sparkMinSplats = 2048;\nconst sparkAttributeList = {\n sparkPackedSplat: { elementsPerSplat: 4, discard: false },\n extendedPackedSplatLow: { elementsPerSplat: 4, discard: false },\n extendedPackedSplatHigh: { elementsPerSplat: 4, discard: false },\n packedSh1: { elementsPerSplat: 2, discard: false },\n packedSh2: { elementsPerSplat: 4, discard: false },\n packedSh3: { elementsPerSplat: 4, discard: false },\n sh1Extended: { elementsPerSplat: 4, discard: false },\n sh2Extended: { elementsPerSplat: 4, discard: false },\n sh3Extended_0: { elementsPerSplat: 4, discard: false },\n sh3Extended_1: { elementsPerSplat: 4, discard: false },\n // Splatter renderer format: pre-decoded ellipsoid + spherical harmonic\n // Will not be present unless the c++ was compiled with --enable-feature splatter\n splatterEllipsoids: { elementsPerSplat: 12, discard: false },\n splatterSphericalHarmonics: { elementsPerSplat: 16, discard: false }\n};\nfunction roundUpToMultipleOf(a, multiple) {\n return Math.ceil(a / multiple) * multiple;\n}\nfunction sparkAttributeFromRaw(name, id, wasmView) {\n const attrib = sparkAttributeList[name];\n if (attrib === void 0)\n throw new Error("attribute name" + name + " is unknown");\n const originalSize = wasmView.length;\n const paddedSize = roundUpToMultipleOf(\n originalSize,\n attrib.elementsPerSplat * sparkMinSplats\n );\n const paddedData = new Uint32Array(paddedSize);\n paddedData.set(wasmView);\n return { paddedData, originalSize, id };\n}\nasync function Li(Le = {}) {\n var $r, l = Le, Lr = "./this.program", zr = (e, r) => {\n throw r;\n }, Ne = import.meta.url, wr = "";\n function Ge(e) {\n return l.locateFile ? l.locateFile(e, wr) : wr + e;\n }\n var Yr, Tr;\n {\n try {\n wr = new URL(".", Ne).href;\n } catch {\n }\n Tr = (e) => {\n var r = new XMLHttpRequest();\n return r.open("GET", e, false), r.responseType = "arraybuffer", r.send(null), new Uint8Array(r.response);\n }, Yr = async (e) => {\n var r = await fetch(e, { credentials: "same-origin" });\n if (r.ok) return r.arrayBuffer();\n throw new Error(r.status + " : " + r.url);\n };\n }\n var Nr = console.log.bind(console), B = console.error.bind(console), G, Q = false, rr;\n var Gr, qr, er, k, A, U, L, T, w, tr, nr, V, Xr, Jr = false;\n function Kr() {\n var e = er.buffer;\n l.HEAP8 = k = new Int8Array(e), U = new Int16Array(e), l.HEAPU8 = A = new Uint8Array(e), L = new Uint16Array(e), l.HEAP32 = T = new Int32Array(e), l.HEAPU32 = w = new Uint32Array(e), l.HEAPF32 = tr = new Float32Array(e), l.HEAPF64 = nr = new Float64Array(e), V = new BigInt64Array(e), Xr = new BigUint64Array(e);\n }\n function qe() {\n if (l.preRun) for (typeof l.preRun == "function" && (l.preRun = [l.preRun]); l.preRun.length; ) at(l.preRun.shift());\n Qr(ee);\n }\n function Xe() {\n Jr = true, H.__wasm_call_ctors();\n }\n function Je() {\n if (l.postRun) for (typeof l.postRun == "function" && (l.postRun = [l.postRun]); l.postRun.length; ) it(l.postRun.shift());\n Qr(re);\n }\n function z(e) {\n l.onAbort?.(e), e = "Aborted(" + e + ")", B(e), Q = true, e += ". Build with -sASSERTIONS for more info.";\n var r = new WebAssembly.RuntimeError(e);\n throw qr?.(r), r;\n }\n var Fr;\n function Ke() {\n return l.locateFile ? Ge("aqua-parser.wasm") : "";\n }\n function Ze(e) {\n if (e == Fr && G) return new Uint8Array(G);\n if (Tr) return Tr(e);\n throw "both async and sync fetching of the wasm failed";\n }\n async function Qe(e) {\n if (!G) try {\n var r = await Yr(e);\n return new Uint8Array(r);\n } catch {\n }\n return Ze(e);\n }\n async function rt(e, r) {\n try {\n var t = await Qe(e), n = await WebAssembly.instantiate(t, r);\n return n;\n } catch (i) {\n B(`failed to asynchronously prepare wasm: ${i}`), z(i);\n }\n }\n async function et(e, r, t) {\n if (!e) try {\n var n = fetch(r, { credentials: "same-origin" }), i = await WebAssembly.instantiateStreaming(n, t);\n return i;\n } catch (a) {\n B(`wasm streaming compile failed: ${a}`), B("falling back to ArrayBuffer instantiation");\n }\n return rt(r, t);\n }\n function tt() {\n return { env: Ie, wasi_snapshot_preview1: Ie };\n }\n async function nt() {\n function e(a, s) {\n return H = a.exports, er = H.memory, Kr(), fe = H.__indirect_function_table, si(H), H;\n }\n function r(a) {\n return e(a.instance);\n }\n var t = tt();\n if (l.instantiateWasm) return new Promise((a, s) => {\n l.instantiateWasm(t, (o, u) => {\n a(e(o));\n });\n });\n Fr ??= Ke();\n var n = await et(G, Fr, t), i = r(n);\n return i;\n }\n class Zr {\n name = "ExitStatus";\n constructor(r) {\n this.message = `Program terminated with exit(${r})`, this.status = r;\n }\n }\n var Qr = (e) => {\n for (; e.length > 0; ) e.shift()(l);\n }, re = [], it = (e) => re.push(e), ee = [], at = (e) => ee.push(e);\n var Cr = true;\n var y = (e) => De(e), m = () => xe(), ir = [], ar = 0, st = (e) => {\n var r = new Pr(e);\n return r.get_caught() || (r.set_caught(true), ar--), r.set_rethrown(false), ir.push(r), Ue(e), je(e);\n }, x = 0, ot = () => {\n g(0, 0);\n var e = ir.pop();\n Oe(e.excPtr), x = 0;\n };\n class Pr {\n constructor(r) {\n this.excPtr = r, this.ptr = r - 24;\n }\n set_type(r) {\n w[this.ptr + 4 >> 2] = r;\n }\n get_type() {\n return w[this.ptr + 4 >> 2];\n }\n set_destructor(r) {\n w[this.ptr + 8 >> 2] = r;\n }\n get_destructor() {\n return w[this.ptr + 8 >> 2];\n }\n set_caught(r) {\n r = r ? 1 : 0, k[this.ptr + 12] = r;\n }\n get_caught() {\n return k[this.ptr + 12] != 0;\n }\n set_rethrown(r) {\n r = r ? 1 : 0, k[this.ptr + 13] = r;\n }\n get_rethrown() {\n return k[this.ptr + 13] != 0;\n }\n init(r, t) {\n this.set_adjusted_ptr(0), this.set_type(r), this.set_destructor(t);\n }\n set_adjusted_ptr(r) {\n w[this.ptr + 16 >> 2] = r;\n }\n get_adjusted_ptr() {\n return w[this.ptr + 16 >> 2];\n }\n }\n var sr = (e) => Re(e), kr = (e) => {\n var r = x;\n if (!r) return sr(0), 0;\n var t = new Pr(r);\n t.set_adjusted_ptr(r);\n var n = t.get_type();\n if (!n) return sr(0), r;\n for (var i of e) {\n if (i === 0 || i === n) break;\n var a = t.ptr + 16;\n if (Ve(i, n, a)) return sr(i), r;\n }\n return sr(n), r;\n }, ut = () => kr([]), ct = (e) => kr([e]), ft = (e, r) => kr([e, r]), lt = () => {\n var e = ir.pop();\n e || z("no exception to throw");\n var r = e.excPtr;\n throw e.get_rethrown() || (ir.push(e), e.set_rethrown(true), e.set_caught(false), ar++), x = r, x;\n }, vt = (e, r, t) => {\n var n = new Pr(e);\n throw n.init(r, t), x = e, ar++, x;\n }, _t = () => ar, dt = (e) => {\n throw x || (x = e), x;\n }, pt = () => z(""), C = (e) => {\n for (var r = ""; ; ) {\n var t = A[e++];\n if (!t) return r;\n r += String.fromCharCode(t);\n }\n }, Y = {}, j = {}, or = {}, q = class extends Error {\n constructor(r) {\n super(r), this.name = "BindingError";\n }\n }, h = (e) => {\n throw new q(e);\n };\n function ht(e, r, t = {}) {\n var n = r.name;\n if (e || h(`type "${n}" must have a positive integer typeid pointer`), j.hasOwnProperty(e)) {\n if (t.ignoreDuplicateRegistrations) return;\n h(`Cannot register type \'${n}\' twice`);\n }\n if (j[e] = r, delete or[e], Y.hasOwnProperty(e)) {\n var i = Y[e];\n delete Y[e], i.forEach((a) => a());\n }\n }\n function E(e, r, t = {}) {\n return ht(e, r, t);\n }\n var te = (e, r, t) => {\n switch (r) {\n case 1:\n return t ? (n) => k[n] : (n) => A[n];\n case 2:\n return t ? (n) => U[n >> 1] : (n) => L[n >> 1];\n case 4:\n return t ? (n) => T[n >> 2] : (n) => w[n >> 2];\n case 8:\n return t ? (n) => V[n >> 3] : (n) => Xr[n >> 3];\n default:\n throw new TypeError(`invalid integer width (${r}): ${e}`);\n }\n }, gt = (e, r, t, n, i) => {\n r = C(r);\n const a = n === 0n;\n let s = (o) => o;\n if (a) {\n const o = t * 8;\n s = (u) => BigInt.asUintN(o, u), i = s(i);\n }\n E(e, { name: r, fromWireType: s, toWireType: (o, u) => (typeof u == "number" && (u = BigInt(u)), u), readValueFromPointer: te(r, t, !a), destructorFunction: null });\n }, yt = (e, r, t, n) => {\n r = C(r), E(e, { name: r, fromWireType: function(i) {\n return !!i;\n }, toWireType: function(i, a) {\n return a ? t : n;\n }, readValueFromPointer: function(i) {\n return this.fromWireType(A[i]);\n }, destructorFunction: null });\n }, mt = (e) => ({ count: e.count, deleteScheduled: e.deleteScheduled, preservePointerOnDelete: e.preservePointerOnDelete, ptr: e.ptr, ptrType: e.ptrType, smartPtr: e.smartPtr, smartPtrType: e.smartPtrType }), Sr = (e) => {\n function r(t) {\n return t.$$.ptrType.registeredClass.name;\n }\n h(r(e) + " instance already deleted");\n }, Ar = false, ne = (e) => {\n }, bt = (e) => {\n e.smartPtr ? e.smartPtrType.rawDestructor(e.smartPtr) : e.ptrType.registeredClass.rawDestructor(e.ptr);\n }, ie = (e) => {\n e.count.value -= 1;\n var r = e.count.value === 0;\n r && bt(e);\n }, X = (e) => typeof FinalizationRegistry > "u" ? (X = (r) => r, e) : (Ar = new FinalizationRegistry((r) => {\n ie(r.$$);\n }), X = (r) => {\n var t = r.$$, n = !!t.smartPtr;\n if (n) {\n var i = { $$: t };\n Ar.register(r, i, r);\n }\n return r;\n }, ne = (r) => Ar.unregister(r), X(e)), wt = () => {\n let e = cr.prototype;\n Object.assign(e, { isAliasOf(t) {\n if (!(this instanceof cr) || !(t instanceof cr)) return false;\n var n = this.$$.ptrType.registeredClass, i = this.$$.ptr;\n t.$$ = t.$$;\n for (var a = t.$$.ptrType.registeredClass, s = t.$$.ptr; n.baseClass; ) i = n.upcast(i), n = n.baseClass;\n for (; a.baseClass; ) s = a.upcast(s), a = a.baseClass;\n return n === a && i === s;\n }, clone() {\n if (this.$$.ptr || Sr(this), this.$$.preservePointerOnDelete) return this.$$.count.value += 1, this;\n var t = X(Object.create(Object.getPrototypeOf(this), { $$: { value: mt(this.$$) } }));\n return t.$$.count.value += 1, t.$$.deleteScheduled = false, t;\n }, delete() {\n this.$$.ptr || Sr(this), this.$$.deleteScheduled && !this.$$.preservePointerOnDelete && h("Object already scheduled for deletion"), ne(this), ie(this.$$), this.$$.preservePointerOnDelete || (this.$$.smartPtr = void 0, this.$$.ptr = void 0);\n }, isDeleted() {\n return !this.$$.ptr;\n }, deleteLater() {\n return this.$$.ptr || Sr(this), this.$$.deleteScheduled && !this.$$.preservePointerOnDelete && h("Object already scheduled for deletion"), this.$$.deleteScheduled = true, this;\n } });\n const r = Symbol.dispose;\n r && (e[r] = e.delete);\n };\n function cr() {\n }\n var fr = (e, r) => Object.defineProperty(r, "name", { value: e }), se = {}, Er = (e, r, t) => {\n if (e[r].overloadTable === void 0) {\n var n = e[r];\n e[r] = function(...i) {\n return e[r].overloadTable.hasOwnProperty(i.length) || h(`Function \'${t}\' called with an invalid number of arguments (${i.length}) - expects one of (${e[r].overloadTable})!`), e[r].overloadTable[i.length].apply(this, i);\n }, e[r].overloadTable = [], e[r].overloadTable[n.argCount] = n;\n }\n }, Rr = (e, r, t) => {\n l.hasOwnProperty(e) ? ((t === void 0 || l[e].overloadTable !== void 0 && l[e].overloadTable[t] !== void 0) && h(`Cannot register public name \'${e}\' twice`), Er(l, e, e), l[e].overloadTable.hasOwnProperty(t) && h(`Cannot register multiple overloads of a function with the same number of arguments (${t})!`), l[e].overloadTable[t] = r) : (l[e] = r, l[e].argCount = t);\n }, Tt = 48, Ft = 57, Ct = (e) => {\n e = e.replace(/[^a-zA-Z0-9_]/g, "$");\n var r = e.charCodeAt(0);\n return r >= Tt && r <= Ft ? `_${e}` : e;\n };\n function Pt(e, r, t, n, i, a, s, o) {\n this.name = e, this.constructor = r, this.instancePrototype = t, this.rawDestructor = n, this.baseClass = i, this.getActualType = a, this.upcast = s, this.downcast = o, this.pureVirtualFunctions = [];\n }\n var lr = (e, r, t) => {\n for (; r !== t; ) r.upcast || h(`Expected null or instance of ${t.name}, got an instance of ${r.name}`), e = r.upcast(e), r = r.baseClass;\n return e;\n }, Dr = (e) => {\n if (e === null) return "null";\n var r = typeof e;\n return r === "object" || r === "array" || r === "function" ? e.toString() : "" + e;\n };\n function kt(e, r) {\n if (r === null) return this.isReference && h(`null is not a valid ${this.name}`), 0;\n r.$$ || h(`Cannot pass "${Dr(r)}" as a ${this.name}`), r.$$.ptr || h(`Cannot pass deleted object as a pointer of type ${this.name}`);\n var t = r.$$.ptrType.registeredClass, n = lr(r.$$.ptr, t, this.registeredClass);\n return n;\n }\n function St(e, r) {\n var t;\n if (r === null) return this.isReference && h(`null is not a valid ${this.name}`), this.isSmartPointer ? (t = this.rawConstructor(), e !== null && e.push(this.rawDestructor, t), t) : 0;\n (!r || !r.$$) && h(`Cannot pass "${Dr(r)}" as a ${this.name}`), r.$$.ptr || h(`Cannot pass deleted object as a pointer of type ${this.name}`), !this.isConst && r.$$.ptrType.isConst && h(`Cannot convert argument of type ${r.$$.smartPtrType ? r.$$.smartPtrType.name : r.$$.ptrType.name} to parameter type ${this.name}`);\n var n = r.$$.ptrType.registeredClass;\n if (t = lr(r.$$.ptr, n, this.registeredClass), this.isSmartPointer) switch (r.$$.smartPtr === void 0 && h("Passing raw pointer to smart pointer is illegal"), this.sharingPolicy) {\n case 0:\n r.$$.smartPtrType === this ? t = r.$$.smartPtr : h(`Cannot convert argument of type ${r.$$.smartPtrType ? r.$$.smartPtrType.name : r.$$.ptrType.name} to parameter type ${this.name}`);\n break;\n case 1:\n t = r.$$.smartPtr;\n break;\n case 2:\n if (r.$$.smartPtrType === this) t = r.$$.smartPtr;\n else {\n var i = r.clone();\n t = this.rawShare(t, W.toHandle(() => i.delete())), e !== null && e.push(this.rawDestructor, t);\n }\n break;\n default:\n h("Unsupporting sharing policy");\n }\n return t;\n }\n function At(e, r) {\n if (r === null) return this.isReference && h(`null is not a valid ${this.name}`), 0;\n r.$$ || h(`Cannot pass "${Dr(r)}" as a ${this.name}`), r.$$.ptr || h(`Cannot pass deleted object as a pointer of type ${this.name}`), r.$$.ptrType.isConst && h(`Cannot convert argument of type ${r.$$.ptrType.name} to parameter type ${this.name}`);\n var t = r.$$.ptrType.registeredClass, n = lr(r.$$.ptr, t, this.registeredClass);\n return n;\n }\n function vr(e) {\n return this.fromWireType(w[e >> 2]);\n }\n var oe = (e, r, t) => {\n if (r === t) return e;\n if (t.baseClass === void 0) return null;\n var n = oe(e, r, t.baseClass);\n return n === null ? null : t.downcast(n);\n }, Et = {}, Rt = (e, r) => {\n for (r === void 0 && h("ptr should not be undefined"); e.baseClass; ) r = e.upcast(r), e = e.baseClass;\n return r;\n }, Dt = (e, r) => (r = Rt(e, r), Et[r]), Wt = class extends Error {\n constructor(r) {\n super(r), this.name = "InternalError";\n }\n }, _r = (e) => {\n throw new Wt(e);\n }, dr = (e, r) => {\n (!r.ptrType || !r.ptr) && _r("makeClassHandle requires ptr and ptrType");\n var t = !!r.smartPtrType, n = !!r.smartPtr;\n return t !== n && _r("Both smartPtrType and smartPtr must be specified"), r.count = { value: 1 }, X(Object.create(e, { $$: { value: r, writable: true } }));\n };\n function xt(e) {\n var r = this.getPointee(e);\n if (!r) return this.destructor(e), null;\n var t = Dt(this.registeredClass, r);\n if (t !== void 0) {\n if (t.$$.count.value === 0) return t.$$.ptr = r, t.$$.smartPtr = e, t.clone();\n var n = t.clone();\n return this.destructor(e), n;\n }\n function i() {\n return this.isSmartPointer ? dr(this.registeredClass.instancePrototype, { ptrType: this.pointeeType, ptr: r, smartPtrType: this, smartPtr: e }) : dr(this.registeredClass.instancePrototype, { ptrType: this, ptr: e });\n }\n var a = this.registeredClass.getActualType(r), s = se[a];\n if (!s) return i.call(this);\n var o;\n this.isConst ? o = s.constPointerType : o = s.pointerType;\n var u = oe(r, this.registeredClass, o.registeredClass);\n return u === null ? i.call(this) : this.isSmartPointer ? dr(o.registeredClass.instancePrototype, { ptrType: o, ptr: u, smartPtrType: this, smartPtr: e }) : dr(o.registeredClass.instancePrototype, { ptrType: o, ptr: u });\n }\n var Ot = () => {\n Object.assign(pr.prototype, { getPointee(e) {\n return this.rawGetPointee && (e = this.rawGetPointee(e)), e;\n }, destructor(e) {\n this.rawDestructor?.(e);\n }, readValueFromPointer: vr, fromWireType: xt });\n };\n function pr(e, r, t, n, i, a, s, o, u, c, f) {\n this.name = e, this.registeredClass = r, this.isReference = t, this.isConst = n, this.isSmartPointer = i, this.pointeeType = a, this.sharingPolicy = s, this.rawGetPointee = o, this.rawConstructor = u, this.rawShare = c, this.rawDestructor = f, !i && r.baseClass === void 0 ? n ? (this.toWireType = kt, this.destructorFunction = null) : (this.toWireType = At, this.destructorFunction = null) : this.toWireType = St;\n }\n var ue = (e, r, t) => {\n l.hasOwnProperty(e) || _r("Replacing nonexistent public symbol"), l[e].overloadTable !== void 0 && t !== void 0 ? l[e].overloadTable[t] = r : (l[e] = r, l[e].argCount = t);\n }, ce = [], fe, b = (e) => {\n var r = ce[e];\n return r || (ce[e] = r = fe.get(e)), r;\n }, R = (e, r, t = false) => {\n e = C(e);\n function n() {\n var a = b(r);\n return a;\n }\n var i = n();\n return typeof i != "function" && h(`unknown function pointer with signature ${e}: ${r}`), i;\n };\n class Ut extends Error {\n }\n var le = (e) => {\n var r = Ae(e), t = C(r);\n return O(r), t;\n }, I = (e, r) => {\n var t = [], n = {};\n function i(a) {\n if (!n[a] && !j[a]) {\n if (or[a]) {\n or[a].forEach(i);\n return;\n }\n t.push(a), n[a] = true;\n }\n }\n throw r.forEach(i), new Ut(`${e}: ` + t.map(le).join([", "]));\n }, D = (e, r, t) => {\n e.forEach((o) => or[o] = r);\n function n(o) {\n var u = t(o);\n u.length !== e.length && _r("Mismatched type converter count");\n for (var c = 0; c < e.length; ++c) E(e[c], u[c]);\n }\n var i = new Array(r.length), a = [], s = 0;\n r.forEach((o, u) => {\n j.hasOwnProperty(o) ? i[u] = j[o] : (a.push(o), Y.hasOwnProperty(o) || (Y[o] = []), Y[o].push(() => {\n i[u] = j[o], ++s, s === a.length && n(i);\n }));\n }), a.length === 0 && n(i);\n }, Vt = (e, r, t, n, i, a, s, o, u, c, f, _, d) => {\n f = C(f), a = R(i, a), o &&= R(s, o), c &&= R(u, c), d = R(_, d);\n var p = Ct(f);\n Rr(p, function() {\n I(`Cannot construct ${f} due to unbound types`, [n]);\n }), D([e, r, t], n ? [n] : [], (v) => {\n v = v[0];\n var $, P;\n n ? ($ = v.registeredClass, P = $.instancePrototype) : P = cr.prototype;\n var F = fr(f, function(...Hr) {\n if (Object.getPrototypeOf(this) !== Z) throw new q(`Use \'new\' to construct ${f}`);\n if (S.constructor_body === void 0) throw new q(`${f} has no accessible constructor`);\n var Be = S.constructor_body[Hr.length];\n if (Be === void 0) throw new q(`Tried to invoke ctor of ${f} with invalid number of parameters (${Hr.length}) - expected (${Object.keys(S.constructor_body).toString()}) parameters instead!`);\n return Be.apply(this, Hr);\n }), Z = Object.create(P, { constructor: { value: F } });\n F.prototype = Z;\n var S = new Pt(f, F, Z, d, $, a, o, c);\n S.baseClass && (S.baseClass.__derivedClasses ??= [], S.baseClass.__derivedClasses.push(S));\n var Bi = new pr(f, S, true, false, false), Me = new pr(f + "*", S, false, false, false), He = new pr(f + " const*", S, false, true, false);\n return se[e] = { pointerType: Me, constPointerType: He }, ue(p, F), [Bi, Me, He];\n });\n }, Wr = (e) => {\n for (; e.length; ) {\n var r = e.pop(), t = e.pop();\n t(r);\n }\n };\n function ve(e) {\n for (var r = 1; r < e.length; ++r) if (e[r] !== null && e[r].destructorFunction === void 0) return true;\n return false;\n }\n function jt(e, r, t, n) {\n var i = ve(e), a = e.length - 2, s = [], o = ["fn"];\n r && o.push("thisWired");\n for (var u = 0; u < a; ++u) s.push(`arg${u}`), o.push(`arg${u}Wired`);\n s = s.join(","), o = o.join(",");\n var c = `return function (${s}) {\n`;\n i && (c += `var destructors = [];\n`);\n var f = i ? "destructors" : "null", _ = ["humanName", "throwBindingError", "invoker", "fn", "runDestructors", "fromRetWire", "toClassParamWire"];\n r && (c += `var thisWired = toClassParamWire(${f}, this);\n`);\n for (var u = 0; u < a; ++u) {\n var d = `toArg${u}Wire`;\n c += `var arg${u}Wired = ${d}(${f}, arg${u});\n`, _.push(d);\n }\n c += (t || n ? "var rv = " : "") + `invoker(${o});\n`;\n if (i) c += `runDestructors(destructors);\n`;\n else for (var u = r ? 1 : 2; u < e.length; ++u) {\n var v = u === 1 ? "thisWired" : "arg" + (u - 2) + "Wired";\n e[u].destructorFunction !== null && (c += `${v}_dtor(${v});\n`, _.push(`${v}_dtor`));\n }\n return t && (c += `var ret = fromRetWire(rv);\nreturn ret;\n`), c += `}\n`, new Function(_, c);\n }\n function hr(e, r, t, n, i, a) {\n var s = r.length;\n s < 2 && h("argTypes array size mismatch! Must at least get return value and \'this\' types!");\n for (var o = r[1] !== null && t !== null, u = ve(r), c = !r[0].isVoid, f = s - 2, _ = r[0], d = r[1], p = [e, h, n, i, Wr, _.fromWireType.bind(_), d?.toWireType.bind(d)], v = 2; v < s; ++v) {\n var $ = r[v];\n p.push($.toWireType.bind($));\n }\n if (!u) for (var v = o ? 1 : 2; v < r.length; ++v) r[v].destructorFunction !== null && p.push(r[v].destructorFunction);\n var F = jt(r, o, c, a)(...p);\n return fr(e, F);\n }\n var gr = (e, r) => {\n for (var t = [], n = 0; n < e; n++) t.push(w[r + n * 4 >> 2]);\n return t;\n }, xr = (e) => {\n e = e.trim();\n const r = e.indexOf("(");\n return r === -1 ? e : e.slice(0, r);\n }, It = (e, r, t, n, i, a, s, o, u) => {\n var c = gr(t, n);\n r = C(r), r = xr(r), a = R(i, a, o), D([], [e], (f) => {\n f = f[0];\n var _ = `${f.name}.${r}`;\n function d() {\n I(`Cannot call ${_} due to unbound types`, c);\n }\n r.startsWith("@@") && (r = Symbol[r.substring(2)]);\n var p = f.registeredClass.constructor;\n return p[r] === void 0 ? (d.argCount = t - 1, p[r] = d) : (Er(p, r, _), p[r].overloadTable[t - 1] = d), D([], c, (v) => {\n var $ = [v[0], null].concat(v.slice(1)), P = hr(_, $, null, a, s, o);\n if (p[r].overloadTable === void 0 ? (P.argCount = t - 1, p[r] = P) : p[r].overloadTable[t - 1] = P, f.registeredClass.__derivedClasses) for (const F of f.registeredClass.__derivedClasses) F.constructor.hasOwnProperty(r) || (F.constructor[r] = P);\n return [];\n }), [];\n });\n }, Mt = (e, r, t, n, i, a) => {\n var s = gr(r, t);\n i = R(n, i);\n D([], [e], (c) => {\n c = c[0];\n var f = `constructor ${c.name}`;\n if (c.registeredClass.constructor_body === void 0 && (c.registeredClass.constructor_body = []), c.registeredClass.constructor_body[r - 1] !== void 0) throw new q(`Cannot register multiple constructors with identical number of parameters (${r - 1}) for class \'${c.name}\'! Overload resolution is currently only performed using the parameter count, not actual type info!`);\n return c.registeredClass.constructor_body[r - 1] = () => {\n I(`Cannot construct ${c.name} due to unbound types`, s);\n }, D([], s, (_) => (_.splice(1, 0, null), c.registeredClass.constructor_body[r - 1] = hr(f, _, null, i, a), [])), [];\n });\n }, Ht = (e, r, t, n, i, a, s, o, u, c) => {\n var f = gr(t, n);\n r = C(r), r = xr(r), a = R(i, a, u), D([], [e], (_) => {\n _ = _[0];\n var d = `${_.name}.${r}`;\n r.startsWith("@@") && (r = Symbol[r.substring(2)]), o && _.registeredClass.pureVirtualFunctions.push(r);\n function p() {\n I(`Cannot call ${d} due to unbound types`, f);\n }\n var v = _.registeredClass.instancePrototype, $ = v[r];\n return $ === void 0 || $.overloadTable === void 0 && $.className !== _.name && $.argCount === t - 2 ? (p.argCount = t - 2, p.className = _.name, v[r] = p) : (Er(v, r, d), v[r].overloadTable[t - 2] = p), D([], f, (P) => {\n var F = hr(d, P, _, a, s, u);\n return v[r].overloadTable === void 0 ? (F.argCount = t - 2, v[r] = F) : v[r].overloadTable[t - 2] = F, [];\n }), [];\n });\n }, _e = (e, r, t) => (e instanceof Object || h(`${t} with invalid "this": ${e}`), e instanceof r.registeredClass.constructor || h(`${t} incompatible with "this" of type ${e.constructor.name}`), e.$$.ptr || h(`cannot call emscripten binding method ${t} on deleted object`), lr(e.$$.ptr, e.$$.ptrType.registeredClass, r.registeredClass)), Bt = (e, r, t, n, i, a, s, o, u, c) => {\n r = C(r), i = R(n, i), D([], [e], (f) => {\n f = f[0];\n var _ = `${f.name}.${r}`, d = { get() {\n I(`Cannot access ${_} due to unbound types`, [t, s]);\n }, enumerable: true, configurable: true };\n return u ? d.set = () => I(`Cannot access ${_} due to unbound types`, [t, s]) : d.set = (p) => h(_ + " is a read-only property"), Object.defineProperty(f.registeredClass.instancePrototype, r, d), D([], u ? [t, s] : [t], (p) => {\n var v = p[0], $ = { get() {\n var F = _e(this, f, _ + " getter");\n return v.fromWireType(i(a, F));\n }, enumerable: true };\n if (u) {\n u = R(o, u);\n var P = p[1];\n $.set = function(F) {\n var Z = _e(this, f, _ + " setter"), S = [];\n u(c, Z, P.toWireType(S, F)), Wr(S);\n };\n }\n return Object.defineProperty(f.registeredClass.instancePrototype, r, $), [];\n }), [];\n });\n }, de = [], N = [0, 1, , 1, null, 1, true, 1, false, 1], Or = (e) => {\n e > 9 && --N[e + 1] === 0 && (N[e] = void 0, de.push(e));\n }, W = { toValue: (e) => (e || h(`Cannot use deleted val. handle = ${e}`), N[e]), toHandle: (e) => {\n switch (e) {\n case void 0:\n return 2;\n case null:\n return 4;\n case true:\n return 6;\n case false:\n return 8;\n default: {\n const r = de.pop() || N.length;\n return N[r] = e, N[r + 1] = 1, r;\n }\n }\n } }, Lt = { name: "emscripten::val", fromWireType: (e) => {\n var r = W.toValue(e);\n return Or(e), r;\n }, toWireType: (e, r) => W.toHandle(r), readValueFromPointer: vr, destructorFunction: null }, zt = (e) => E(e, Lt), Yt = (e, r, t) => {\n switch (r) {\n case 1:\n return t ? function(n) {\n return this.fromWireType(k[n]);\n } : function(n) {\n return this.fromWireType(A[n]);\n };\n case 2:\n return t ? function(n) {\n return this.fromWireType(U[n >> 1]);\n } : function(n) {\n return this.fromWireType(L[n >> 1]);\n };\n case 4:\n return t ? function(n) {\n return this.fromWireType(T[n >> 2]);\n } : function(n) {\n return this.fromWireType(w[n >> 2]);\n };\n default:\n throw new TypeError(`invalid integer width (${r}): ${e}`);\n }\n }, Nt = (e, r, t, n) => {\n r = C(r);\n function i() {\n }\n i.values = {}, E(e, { name: r, constructor: i, fromWireType: function(a) {\n return this.constructor.values[a];\n }, toWireType: (a, s) => s.value, readValueFromPointer: Yt(r, t, n), destructorFunction: null }), Rr(r, i);\n }, pe = (e, r) => {\n var t = j[e];\n return t === void 0 && h(`${r} has unknown type ${le(e)}`), t;\n }, Gt = (e, r, t) => {\n var n = pe(e, "enum");\n r = C(r);\n var i = n.constructor, a = Object.create(n.constructor.prototype, { value: { value: t }, constructor: { value: fr(`${n.name}_${r}`, function() {\n }) } });\n i.values[t] = a, i[r] = a;\n }, qt = (e, r) => {\n switch (r) {\n case 4:\n return function(t) {\n return this.fromWireType(tr[t >> 2]);\n };\n case 8:\n return function(t) {\n return this.fromWireType(nr[t >> 3]);\n };\n default:\n throw new TypeError(`invalid float width (${r}): ${e}`);\n }\n }, Xt = (e, r, t) => {\n r = C(r), E(e, { name: r, fromWireType: (n) => n, toWireType: (n, i) => i, readValueFromPointer: qt(r, t), destructorFunction: null });\n }, Jt = (e, r, t, n, i, a, s, o) => {\n var u = gr(r, t);\n e = C(e), e = xr(e), i = R(n, i, s), Rr(e, function() {\n I(`Cannot call ${e} due to unbound types`, u);\n }, r - 1), D([], u, (c) => {\n var f = [c[0], null].concat(c.slice(1));\n return ue(e, hr(e, f, null, i, a, s), r - 1), [];\n });\n }, Kt = (e, r, t, n, i) => {\n r = C(r);\n const a = n === 0;\n let s = (u) => u;\n if (a) {\n var o = 32 - 8 * t;\n s = (u) => u << o >>> o, i = s(i);\n }\n E(e, { name: r, fromWireType: s, toWireType: (u, c) => c, readValueFromPointer: te(r, t, n !== 0), destructorFunction: null });\n }, Zt = (e, r, t) => {\n var n = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array], i = n[r];\n function a(s) {\n var o = w[s >> 2], u = w[s + 4 >> 2];\n return new i(k.buffer, u, o);\n }\n t = C(t), E(e, { name: t, fromWireType: a, readValueFromPointer: a }, { ignoreDuplicateRegistrations: true });\n }, Qt = (e, r, t, n) => {\n if (!(n > 0)) return 0;\n for (var i = t, a = t + n - 1, s = 0; s < e.length; ++s) {\n var o = e.codePointAt(s);\n if (o <= 127) {\n if (t >= a) break;\n r[t++] = o;\n } else if (o <= 2047) {\n if (t + 1 >= a) break;\n r[t++] = 192 | o >> 6, r[t++] = 128 | o & 63;\n } else if (o <= 65535) {\n if (t + 2 >= a) break;\n r[t++] = 224 | o >> 12, r[t++] = 128 | o >> 6 & 63, r[t++] = 128 | o & 63;\n } else {\n if (t + 3 >= a) break;\n r[t++] = 240 | o >> 18, r[t++] = 128 | o >> 12 & 63, r[t++] = 128 | o >> 6 & 63, r[t++] = 128 | o & 63, s++;\n }\n }\n return r[t] = 0, t - i;\n }, M = (e, r, t) => Qt(e, A, r, t), Ur = (e) => {\n for (var r = 0, t = 0; t < e.length; ++t) {\n var n = e.charCodeAt(t);\n n <= 127 ? r++ : n <= 2047 ? r += 2 : n >= 55296 && n <= 57343 ? (r += 4, ++t) : r += 3;\n }\n return r;\n }, he = typeof TextDecoder < "u" ? new TextDecoder() : void 0, ge = (e, r, t, n) => {\n var i = r + t;\n if (n) return i;\n for (; e[r] && !(r >= i); ) ++r;\n return r;\n }, ye = (e, r = 0, t, n) => {\n var i = ge(e, r, t, n);\n if (i - r > 16 && e.buffer && he) return he.decode(e.subarray(r, i));\n for (var a = ""; r < i; ) {\n var s = e[r++];\n if (!(s & 128)) {\n a += String.fromCharCode(s);\n continue;\n }\n var o = e[r++] & 63;\n if ((s & 224) == 192) {\n a += String.fromCharCode((s & 31) << 6 | o);\n continue;\n }\n var u = e[r++] & 63;\n if ((s & 240) == 224 ? s = (s & 15) << 12 | o << 6 | u : s = (s & 7) << 18 | o << 12 | u << 6 | e[r++] & 63, s < 65536) a += String.fromCharCode(s);\n else {\n var c = s - 65536;\n a += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);\n }\n }\n return a;\n }, yr = (e, r, t) => e ? ye(A, e, r, t) : "", rn = (e, r) => {\n r = C(r);\n E(e, { name: r, fromWireType(n) {\n var i = w[n >> 2], a = n + 4, s;\n s = yr(a, i, true);\n return O(n), s;\n }, toWireType(n, i) {\n i instanceof ArrayBuffer && (i = new Uint8Array(i));\n var a, s = typeof i == "string";\n s || ArrayBuffer.isView(i) && i.BYTES_PER_ELEMENT == 1 || h("Cannot pass non-string to std::string"), s ? a = Ur(i) : a = i.length;\n var o = Mr(4 + a + 1), u = o + 4;\n if (w[o >> 2] = a, s) M(i, u, a + 1);\n else A.set(i, u);\n return n !== null && n.push(O, o), o;\n }, readValueFromPointer: vr, destructorFunction(n) {\n O(n);\n } });\n }, me = typeof TextDecoder < "u" ? new TextDecoder("utf-16le") : void 0, en = (e, r, t) => {\n var n = e >> 1, i = ge(L, n, r / 2, t);\n if (i - n > 16 && me) return me.decode(L.subarray(n, i));\n for (var a = "", s = n; s < i; ++s) {\n var o = L[s];\n a += String.fromCharCode(o);\n }\n return a;\n }, tn = (e, r, t) => {\n if (t ??= 2147483647, t < 2) return 0;\n t -= 2;\n for (var n = r, i = t < e.length * 2 ? t / 2 : e.length, a = 0; a < i; ++a) {\n var s = e.charCodeAt(a);\n U[r >> 1] = s, r += 2;\n }\n return U[r >> 1] = 0, r - n;\n }, nn = (e) => e.length * 2, an = (e, r, t) => {\n for (var n = "", i = e >> 2, a = 0; !(a >= r / 4); a++) {\n var s = w[i + a];\n if (!s && !t) break;\n n += String.fromCodePoint(s);\n }\n return n;\n }, sn = (e, r, t) => {\n if (t ??= 2147483647, t < 4) return 0;\n for (var n = r, i = n + t - 4, a = 0; a < e.length; ++a) {\n var s = e.codePointAt(a);\n if (s > 65535 && a++, T[r >> 2] = s, r += 4, r + 4 > i) break;\n }\n return T[r >> 2] = 0, r - n;\n }, on = (e) => {\n for (var r = 0, t = 0; t < e.length; ++t) {\n var n = e.codePointAt(t);\n n > 65535 && t++, r += 4;\n }\n return r;\n }, un = (e, r, t) => {\n t = C(t);\n var n, i, a;\n r === 2 ? (n = en, i = tn, a = nn) : (n = an, i = sn, a = on), E(e, { name: t, fromWireType: (s) => {\n var o = w[s >> 2], u = n(s + 4, o * r, true);\n return O(s), u;\n }, toWireType: (s, o) => {\n typeof o != "string" && h(`Cannot pass non-string to C++ string type ${t}`);\n var u = a(o), c = Mr(4 + u + r);\n return w[c >> 2] = u / r, i(o, c + 4, u + r), s !== null && s.push(O, c), c;\n }, readValueFromPointer: vr, destructorFunction(s) {\n O(s);\n } });\n }, cn = (e, r) => {\n r = C(r), E(e, { isVoid: true, name: r, fromWireType: () => {\n }, toWireType: (t, n) => {\n } });\n }, be = 0, fn = () => {\n Cr = false, be = 0;\n }, Vr = [], ln = (e) => {\n var r = Vr.length;\n return Vr.push(e), r;\n }, vn = (e, r) => {\n for (var t = new Array(e), n = 0; n < e; ++n) t[n] = pe(w[r + n * 4 >> 2], `parameter ${n}`);\n return t;\n }, _n = (e, r, t) => {\n var n = [], i = e(n, t);\n return n.length && (w[r >> 2] = W.toHandle(n)), i;\n }, dn = {}, pn = (e) => {\n var r = dn[e];\n return r === void 0 ? C(e) : r;\n }, hn = (e, r, t) => {\n var n = 8, [i, ...a] = vn(e, r), s = i.toWireType.bind(i), o = a.map((p) => p.readValueFromPointer.bind(p));\n e--;\n var u = { toValue: W.toValue }, c = o.map((p, v) => {\n var $ = `argFromPtr${v}`;\n return u[$] = p, `${$}(args${v ? "+" + v * n : ""})`;\n }), f;\n switch (t) {\n case 0:\n f = "toValue(handle)";\n break;\n case 2:\n f = "new (toValue(handle))";\n break;\n case 3:\n f = "";\n break;\n case 1:\n u.getStringOrSymbol = pn, f = "toValue(handle)[getStringOrSymbol(methodName)]";\n break;\n }\n f += `(${c})`, i.isVoid || (u.toReturnWire = s, u.emval_returnValue = _n, f = `return emval_returnValue(toReturnWire, destructorsRef, ${f})`), f = `return function (handle, methodName, destructorsRef, args) {\n ${f}\n }`;\n var _ = new Function(Object.keys(u), f)(...Object.values(u)), d = `methodCaller<(${a.map((p) => p.name)}) => ${i.name}>`;\n return ln(fr(d, _));\n }, gn = (e, r, t, n, i) => Vr[e](r, t, n, i), yn = () => W.toHandle({}), mn = (e) => {\n var r = W.toValue(e);\n Wr(r), Or(e);\n }, bn = (e, r, t) => {\n e = W.toValue(e), r = W.toValue(r), t = W.toValue(t), e[r] = t;\n }, $n = 9007199254740992, wn = -9007199254740992, mr = (e) => e < wn || e > $n ? NaN : Number(e);\n function Tn(e, r) {\n e = mr(e);\n var t = new Date(e * 1e3);\n T[r >> 2] = t.getUTCSeconds(), T[r + 4 >> 2] = t.getUTCMinutes(), T[r + 8 >> 2] = t.getUTCHours(), T[r + 12 >> 2] = t.getUTCDate(), T[r + 16 >> 2] = t.getUTCMonth(), T[r + 20 >> 2] = t.getUTCFullYear() - 1900, T[r + 24 >> 2] = t.getUTCDay();\n var n = Date.UTC(t.getUTCFullYear(), 0, 1, 0, 0, 0, 0), i = (t.getTime() - n) / (1e3 * 60 * 60 * 24) | 0;\n T[r + 28 >> 2] = i;\n }\n var Fn = (e) => e % 4 === 0 && (e % 100 !== 0 || e % 400 === 0), Cn = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], Pn = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], kn = (e) => {\n var r = Fn(e.getFullYear()), t = r ? Cn : Pn, n = t[e.getMonth()] + e.getDate() - 1;\n return n;\n };\n function Sn(e, r) {\n e = mr(e);\n var t = new Date(e * 1e3);\n T[r >> 2] = t.getSeconds(), T[r + 4 >> 2] = t.getMinutes(), T[r + 8 >> 2] = t.getHours(), T[r + 12 >> 2] = t.getDate(), T[r + 16 >> 2] = t.getMonth(), T[r + 20 >> 2] = t.getFullYear() - 1900, T[r + 24 >> 2] = t.getDay();\n var n = kn(t) | 0;\n T[r + 28 >> 2] = n, T[r + 36 >> 2] = -(t.getTimezoneOffset() * 60);\n var i = new Date(t.getFullYear(), 0, 1), a = new Date(t.getFullYear(), 6, 1).getTimezoneOffset(), s = i.getTimezoneOffset(), o = (a != s && t.getTimezoneOffset() == Math.min(s, a)) | 0;\n T[r + 32 >> 2] = o;\n }\n var J = {}, $e = (e) => {\n if (e instanceof Zr || e == "unwind") return rr;\n zr(1, e);\n }, we = () => Cr || be > 0, Te = (e) => {\n rr = e, we() || (l.onExit?.(e), Q = true), zr(e, new Zr(e));\n }, An = (e, r) => {\n rr = e, Te(e);\n }, En = An, Rn = () => {\n if (!we()) try {\n En(rr);\n } catch (e) {\n $e(e);\n }\n }, Dn = (e) => {\n if (!Q) try {\n e(), Rn();\n } catch (r) {\n $e(r);\n }\n }, Fe = () => performance.now(), Wn = (e, r) => {\n if (J[e] && (clearTimeout(J[e].id), delete J[e]), !r) return 0;\n var t = setTimeout(() => {\n delete J[e], Dn(() => Ee(e, Fe()));\n }, r);\n return J[e] = { id: t, timeout_ms: r }, 0;\n }, xn = (e, r, t, n) => {\n var i = (/* @__PURE__ */ new Date()).getFullYear(), a = new Date(i, 0, 1), s = new Date(i, 6, 1), o = a.getTimezoneOffset(), u = s.getTimezoneOffset(), c = Math.max(o, u);\n w[e >> 2] = c * 60, T[r >> 2] = +(o != u);\n var f = (p) => {\n var v = p >= 0 ? "-" : "+", $ = Math.abs(p), P = String(Math.floor($ / 60)).padStart(2, "0"), F = String($ % 60).padStart(2, "0");\n return `UTC${v}${P}${F}`;\n }, _ = f(o), d = f(u);\n u < o ? (M(_, t, 17), M(d, n, 17)) : (M(_, n, 17), M(d, t, 17));\n }, On = () => Date.now(), Vn = (e) => e >= 0 && e <= 3;\n function jn(e, r, t) {\n if (!Vn(e)) return 28;\n var n;\n if (e === 0) n = On();\n else n = Fe();\n var i = Math.round(n * 1e3 * 1e3);\n return V[t >> 3] = BigInt(i), 0;\n }\n var Ce = () => 2147483648, In = () => Ce(), Mn = (e, r) => Math.ceil(e / r) * r, Hn = (e) => {\n var r = er.buffer.byteLength, t = (e - r + 65535) / 65536 | 0;\n try {\n return er.grow(t), Kr(), 1;\n } catch {\n }\n }, Bn = (e) => {\n var r = A.length;\n e >>>= 0;\n var t = Ce();\n if (e > t) return false;\n for (var n = 1; n <= 4; n *= 2) {\n var i = r * (1 + 0.2 / n);\n i = Math.min(i, e + 100663296);\n var a = Math.min(t, Mn(Math.max(e, i), 65536)), s = Hn(a);\n if (s) return true;\n }\n return false;\n }, br = {}, Ln = () => Lr || "./this.program", K = () => {\n if (!K.strings) {\n var e = (typeof navigator == "object" && navigator.language || "C").replace("-", "_") + ".UTF-8", r = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: e, _: Ln() };\n for (var t in br) br[t] === void 0 ? delete r[t] : r[t] = br[t];\n var n = [];\n for (var t in r) n.push(`${t}=${r[t]}`);\n K.strings = n;\n }\n return K.strings;\n }, zn = (e, r) => {\n var t = 0, n = 0;\n for (var i of K()) {\n var a = r + t;\n w[e + n >> 2] = a, t += M(i, a, 1 / 0) + 1, n += 4;\n }\n return 0;\n }, Yn = (e, r) => {\n var t = K();\n w[e >> 2] = t.length;\n var n = 0;\n for (var i of t) n += Ur(i) + 1;\n return w[r >> 2] = n, 0;\n }, Nn = (e) => 52, Gn = (e, r) => {\n var t = 0, n = 0, i = 0;\n {\n var a = 2;\n e == 0 ? t = 2 : (e == 1 || e == 2) && (t = 64), i = 1;\n }\n return k[r] = a, U[r + 2 >> 1] = i, V[r + 8 >> 3] = BigInt(t), V[r + 16 >> 3] = BigInt(n), 0;\n };\n function qn(e, r, t, n) {\n return 70;\n }\n var jr = [null, [], []], Ir = (e, r) => {\n var t = jr[e];\n r === 0 || r === 10 ? ((e === 1 ? Nr : B)(ye(t)), t.length = 0) : t.push(r);\n }, Xn = (e, r, t, n) => {\n for (var i = 0, a = 0; a < t; a++) {\n var s = w[r >> 2], o = w[r + 4 >> 2];\n r += 8;\n for (var u = 0; u < o; u++) Ir(e, A[s + u]);\n i += o;\n }\n return w[n >> 2] = i, 0;\n }, Jn = (e) => e, Pe = (e) => {\n var r = l["_" + e];\n return r;\n }, Kn = (e, r) => {\n k.set(e, r);\n }, ke = (e) => We(e), Zn = (e) => {\n var r = Ur(e) + 1, t = ke(r);\n return M(e, t, r), t;\n }, Se = (e, r, t, n, i) => {\n var a = { string: (v) => {\n var $ = 0;\n return v != null && v !== 0 && ($ = Zn(v)), $;\n }, array: (v) => {\n var $ = ke(v.length);\n return Kn(v, $), $;\n } };\n function s(v) {\n return r === "string" ? yr(v) : r === "boolean" ? !!v : v;\n }\n var o = Pe(e), u = [], c = 0;\n if (n) for (var f = 0; f < n.length; f++) {\n var _ = a[t[f]];\n _ ? (c === 0 && (c = m()), u[f] = _(n[f])) : u[f] = n[f];\n }\n var d = o(...u);\n function p(v) {\n return c !== 0 && y(c), s(v);\n }\n return d = p(d), d;\n }, Qn = (e, r, t, n) => {\n var i = !t || t.every((s) => s === "number" || s === "boolean"), a = r !== "string";\n return a && i && !n ? Pe(e) : (...s) => Se(e, r, t, s);\n };\n if (wt(), Ot(), l.noExitRuntime && (Cr = l.noExitRuntime), l.print && (Nr = l.print), l.printErr && (B = l.printErr), l.wasmBinary && (G = l.wasmBinary), l.arguments && l.arguments, l.thisProgram && (Lr = l.thisProgram), l.preInit) for (typeof l.preInit == "function" && (l.preInit = [l.preInit]); l.preInit.length > 0; ) l.preInit.shift()();\n l.ENV = br, l.ccall = Se, l.cwrap = Qn;\n var Ae, Mr, O, Ee, g, Re, De, We, xe, Oe, Ue, Ve, je;\n function si(e) {\n Ae = e.__getTypeName, l._malloc = Mr = e.malloc, l._parseDropFile = e.parseDropFile, l._getAttributeFromDropFile = e.getAttributeFromDropFile, l._takeAttributeFromDropFile = e.takeAttributeFromDropFile, l._flattenDropFile = e.flattenDropFile, l._destroyDropFileHandle = e.destroyDropFileHandle, e.__cxa_free_exception, l._free = O = e.free, Ee = e._emscripten_timeout, g = e.setThrew, Re = e._emscripten_tempret_set, De = e._emscripten_stack_restore, We = e._emscripten_stack_alloc, xe = e.emscripten_stack_get_current, Oe = e.__cxa_decrement_exception_refcount, Ue = e.__cxa_increment_exception_refcount, Ve = e.__cxa_can_catch, je = e.__cxa_get_exception_ptr;\n }\n var Ie = { __cxa_begin_catch: st, __cxa_end_catch: ot, __cxa_find_matching_catch_2: ut, __cxa_find_matching_catch_3: ct, __cxa_find_matching_catch_4: ft, __cxa_rethrow: lt, __cxa_throw: vt, __cxa_uncaught_exceptions: _t, __resumeException: dt, _abort_js: pt, _embind_register_bigint: gt, _embind_register_bool: yt, _embind_register_class: Vt, _embind_register_class_class_function: It, _embind_register_class_constructor: Mt, _embind_register_class_function: Ht, _embind_register_class_property: Bt, _embind_register_emval: zt, _embind_register_enum: Nt, _embind_register_enum_value: Gt, _embind_register_float: Xt, _embind_register_function: Jt, _embind_register_integer: Kt, _embind_register_memory_view: Zt, _embind_register_std_string: rn, _embind_register_std_wstring: un, _embind_register_void: cn, _emscripten_runtime_keepalive_clear: fn, _emval_create_invoker: hn, _emval_decref: Or, _emval_invoke: gn, _emval_new_object: yn, _emval_run_destructors: mn, _emval_set_property: bn, _gmtime_js: Tn, _localtime_js: Sn, _setitimer_js: Wn, _tzset_js: xn, clock_time_get: jn, emscripten_get_heap_max: In, emscripten_resize_heap: Bn, environ_get: zn, environ_sizes_get: Yn, fd_close: Nn, fd_fdstat_get: Gn, fd_seek: qn, fd_write: Xn, invoke_diii: Wi, invoke_fi: Ti, invoke_fiii: Di, invoke_i: Ci, invoke_ii: ui, invoke_iii: ci, invoke_iiii: mi, invoke_iiiid: Oi, invoke_iiiii: wi, invoke_iiiiid: Ai, invoke_iiiiii: hi, invoke_iiiiiii: Ui, invoke_iiiiiiii: Ei, invoke_iiiiiiiiii: yi, invoke_iiiiiiiiiii: _i, invoke_iiiiiiiiiiii: di, invoke_iiiiijj: Vi, invoke_iiiijj: ji, invoke_iiij: Pi, invoke_j: ki, invoke_jiiii: Ri, invoke_v: pi, invoke_vi: oi, invoke_vii: li, invoke_viii: fi, invoke_viiii: vi, invoke_viiiii: bi, invoke_viiiiii: gi, invoke_viiiiiii: xi, invoke_viiiiiiii: Fi, invoke_viiiiiiiiii: Ii, invoke_viiiiiiiiiiiiiii: Mi, invoke_viiji: Si, invoke_viijii: $i, llvm_eh_typeid_for: Jn, proc_exit: Te };\n function oi(e, r) {\n var t = m();\n try {\n b(e)(r);\n } catch (n) {\n if (y(t), n !== n + 0) throw n;\n g(1, 0);\n }\n }\n function ui(e, r) {\n var t = m();\n try {\n return b(e)(r);\n } catch (n) {\n if (y(t), n !== n + 0) throw n;\n g(1, 0);\n }\n }\n function ci(e, r, t) {\n var n = m();\n try {\n return b(e)(r, t);\n } catch (i) {\n if (y(n), i !== i + 0) throw i;\n g(1, 0);\n }\n }\n function fi(e, r, t, n) {\n var i = m();\n try {\n b(e)(r, t, n);\n } catch (a) {\n if (y(i), a !== a + 0) throw a;\n g(1, 0);\n }\n }\n function li(e, r, t) {\n var n = m();\n try {\n b(e)(r, t);\n } catch (i) {\n if (y(n), i !== i + 0) throw i;\n g(1, 0);\n }\n }\n function vi(e, r, t, n, i) {\n var a = m();\n try {\n b(e)(r, t, n, i);\n } catch (s) {\n if (y(a), s !== s + 0) throw s;\n g(1, 0);\n }\n }\n function _i(e, r, t, n, i, a, s, o, u, c, f) {\n var _ = m();\n try {\n return b(e)(r, t, n, i, a, s, o, u, c, f);\n } catch (d) {\n if (y(_), d !== d + 0) throw d;\n g(1, 0);\n }\n }\n function di(e, r, t, n, i, a, s, o, u, c, f, _) {\n var d = m();\n try {\n return b(e)(r, t, n, i, a, s, o, u, c, f, _);\n } catch (p) {\n if (y(d), p !== p + 0) throw p;\n g(1, 0);\n }\n }\n function pi(e) {\n var r = m();\n try {\n b(e)();\n } catch (t) {\n if (y(r), t !== t + 0) throw t;\n g(1, 0);\n }\n }\n function hi(e, r, t, n, i, a) {\n var s = m();\n try {\n return b(e)(r, t, n, i, a);\n } catch (o) {\n if (y(s), o !== o + 0) throw o;\n g(1, 0);\n }\n }\n function gi(e, r, t, n, i, a, s) {\n var o = m();\n try {\n b(e)(r, t, n, i, a, s);\n } catch (u) {\n if (y(o), u !== u + 0) throw u;\n g(1, 0);\n }\n }\n function yi(e, r, t, n, i, a, s, o, u, c) {\n var f = m();\n try {\n return b(e)(r, t, n, i, a, s, o, u, c);\n } catch (_) {\n if (y(f), _ !== _ + 0) throw _;\n g(1, 0);\n }\n }\n function mi(e, r, t, n) {\n var i = m();\n try {\n return b(e)(r, t, n);\n } catch (a) {\n if (y(i), a !== a + 0) throw a;\n g(1, 0);\n }\n }\n function bi(e, r, t, n, i, a) {\n var s = m();\n try {\n b(e)(r, t, n, i, a);\n } catch (o) {\n if (y(s), o !== o + 0) throw o;\n g(1, 0);\n }\n }\n function $i(e, r, t, n, i, a) {\n var s = m();\n try {\n b(e)(r, t, n, i, a);\n } catch (o) {\n if (y(s), o !== o + 0) throw o;\n g(1, 0);\n }\n }\n function wi(e, r, t, n, i) {\n var a = m();\n try {\n return b(e)(r, t, n, i);\n } catch (s) {\n if (y(a), s !== s + 0) throw s;\n g(1, 0);\n }\n }\n function Ti(e, r) {\n var t = m();\n try {\n return b(e)(r);\n } catch (n) {\n if (y(t), n !== n + 0) throw n;\n g(1, 0);\n }\n }\n function Fi(e, r, t, n, i, a, s, o, u) {\n var c = m();\n try {\n b(e)(r, t, n, i, a, s, o, u);\n } catch (f) {\n if (y(c), f !== f + 0) throw f;\n g(1, 0);\n }\n }\n function Ci(e) {\n var r = m();\n try {\n return b(e)();\n } catch (t) {\n if (y(r), t !== t + 0) throw t;\n g(1, 0);\n }\n }\n function Pi(e, r, t, n) {\n var i = m();\n try {\n return b(e)(r, t, n);\n } catch (a) {\n if (y(i), a !== a + 0) throw a;\n g(1, 0);\n }\n }\n function ki(e) {\n var r = m();\n try {\n return b(e)();\n } catch (t) {\n if (y(r), t !== t + 0) throw t;\n return g(1, 0), 0n;\n }\n }\n function Si(e, r, t, n, i) {\n var a = m();\n try {\n b(e)(r, t, n, i);\n } catch (s) {\n if (y(a), s !== s + 0) throw s;\n g(1, 0);\n }\n }\n function Ai(e, r, t, n, i, a) {\n var s = m();\n try {\n return b(e)(r, t, n, i, a);\n } catch (o) {\n if (y(s), o !== o + 0) throw o;\n g(1, 0);\n }\n }\n function Ei(e, r, t, n, i, a, s, o) {\n var u = m();\n try {\n return b(e)(r, t, n, i, a, s, o);\n } catch (c) {\n if (y(u), c !== c + 0) throw c;\n g(1, 0);\n }\n }\n function Ri(e, r, t, n, i) {\n var a = m();\n try {\n return b(e)(r, t, n, i);\n } catch (s) {\n if (y(a), s !== s + 0) throw s;\n return g(1, 0), 0n;\n }\n }\n function Di(e, r, t, n) {\n var i = m();\n try {\n return b(e)(r, t, n);\n } catch (a) {\n if (y(i), a !== a + 0) throw a;\n g(1, 0);\n }\n }\n function Wi(e, r, t, n) {\n var i = m();\n try {\n return b(e)(r, t, n);\n } catch (a) {\n if (y(i), a !== a + 0) throw a;\n g(1, 0);\n }\n }\n function xi(e, r, t, n, i, a, s, o) {\n var u = m();\n try {\n b(e)(r, t, n, i, a, s, o);\n } catch (c) {\n if (y(u), c !== c + 0) throw c;\n g(1, 0);\n }\n }\n function Oi(e, r, t, n, i) {\n var a = m();\n try {\n return b(e)(r, t, n, i);\n } catch (s) {\n if (y(a), s !== s + 0) throw s;\n g(1, 0);\n }\n }\n function Ui(e, r, t, n, i, a, s) {\n var o = m();\n try {\n return b(e)(r, t, n, i, a, s);\n } catch (u) {\n if (y(o), u !== u + 0) throw u;\n g(1, 0);\n }\n }\n function Vi(e, r, t, n, i, a, s) {\n var o = m();\n try {\n return b(e)(r, t, n, i, a, s);\n } catch (u) {\n if (y(o), u !== u + 0) throw u;\n g(1, 0);\n }\n }\n function ji(e, r, t, n, i, a) {\n var s = m();\n try {\n return b(e)(r, t, n, i, a);\n } catch (o) {\n if (y(s), o !== o + 0) throw o;\n g(1, 0);\n }\n }\n function Ii(e, r, t, n, i, a, s, o, u, c, f) {\n var _ = m();\n try {\n b(e)(r, t, n, i, a, s, o, u, c, f);\n } catch (d) {\n if (y(_), d !== d + 0) throw d;\n g(1, 0);\n }\n }\n function Mi(e, r, t, n, i, a, s, o, u, c, f, _, d, p, v, $) {\n var P = m();\n try {\n b(e)(r, t, n, i, a, s, o, u, c, f, _, d, p, v, $);\n } catch (F) {\n if (y(P), F !== F + 0) throw F;\n g(1, 0);\n }\n }\n function Hi() {\n qe();\n function e() {\n l.calledRun = true, !Q && (Xe(), Gr?.(l), l.onRuntimeInitialized?.(), Je());\n }\n l.setStatus ? (l.setStatus("Running..."), setTimeout(() => {\n setTimeout(() => l.setStatus(""), 1), e();\n }, 1)) : e();\n }\n var H;\n return H = await nt(), Hi(), Jr ? $r = l : $r = new Promise((e, r) => {\n Gr = e, qr = r;\n }), $r;\n}\nconst { wasmBinary } = await new Promise(\n (resolve) => {\n self.addEventListener("message", function onInit(e) {\n if (e.data?.type === "wasm-init") {\n self.removeEventListener("message", onInit);\n resolve(e.data);\n }\n });\n }\n);\nif (!wasmBinary) {\n throw new Error(\n "Decoder worker did not receive WASM binary. The main thread failed to fetch aqua-parser.wasm."\n );\n}\nconst module$1 = await Li({ wasmBinary });\nconst controllers = /* @__PURE__ */ new Map();\nconst decoder = {\n get AttributeInfo() {\n return module$1.AttributeInfo;\n },\n get AquaStatus() {\n return module$1.AquaStatus;\n },\n get heapU8() {\n return module$1.HEAPU8;\n },\n get heapU32() {\n return module$1.HEAPU32;\n },\n get SceneRequestDescriptor() {\n return module$1.SceneRequestDescriptor;\n },\n get WorkerDataType() {\n return module$1.WorkerDataType;\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n dataPtrView: (attributeInfo) => {\n return module$1.dataPtrView(attributeInfo);\n },\n free: (...args) => {\n return module$1.ccall("free", "number", ["number"], args);\n },\n malloc: (...args) => {\n return module$1.ccall("malloc", "number", ["number"], args);\n },\n parseDropFile: (bufferPtr, bufferSize) => {\n return module$1.parseDropFile(bufferPtr, bufferSize);\n },\n getAttributeFromDropFile: (handle, attributeName, attributeInfo) => {\n return module$1.getAttributeFromDropFile(\n handle,\n attributeName,\n attributeInfo\n );\n },\n takeAttributeFromDropFile: (handle, attributeName, clientSideId) => {\n return module$1.takeAttributeFromDropFile(\n handle,\n attributeName,\n clientSideId\n );\n },\n flattenDropFile: (handle, outPtr, outSize) => {\n return module$1.flattenDropFile(handle, outPtr, outSize);\n },\n destroyDropFileHandle: (handle) => {\n return module$1.destroyDropFileHandle(handle);\n }\n};\ndefineActions({\n // eslint-disable-line @typescript-eslint/no-unused-vars\n async cancel(requestIdLow, requestIdHigh) {\n const key = `${requestIdHigh}-${requestIdLow}`;\n const controller = controllers.get(key);\n if (controller) {\n controller.abort();\n controllers.delete(key);\n }\n return [{ cancelled: !!controller }];\n },\n async heapSnapshot(topN) {\n if (typeof module$1.TakeHeapSnapshot !== "function") {\n return [{ snapshotJson: null }];\n }\n const snapshotJson = module$1.TakeHeapSnapshot(topN);\n return [{ snapshotJson }];\n },\n async heapTrackingControl(enabled) {\n if (typeof module$1.SetHeapTrackingEnabled !== "function") {\n return [{ success: false }];\n }\n module$1.SetHeapTrackingEnabled(enabled);\n return [{ success: true }];\n },\n async heapTrackingReset() {\n if (typeof module$1.ResetHeapTracking !== "function") {\n return [{ success: false }];\n }\n module$1.ResetHeapTracking();\n return [{ success: true }];\n },\n async decode(requestIdLow, requestIdHigh, descriptorBuffer, contextPtr, consecutiveIdsStart, noJwt) {\n const key = `${requestIdHigh}-${requestIdLow}`;\n const controller = new AbortController();\n controllers.set(key, controller);\n try {\n const {\n free,\n malloc,\n parseDropFile,\n getAttributeFromDropFile,\n takeAttributeFromDropFile,\n flattenDropFile,\n destroyDropFileHandle\n } = decoder;\n const descriptorSize = descriptorBuffer.byteLength;\n const descriptorPointer = malloc(descriptorSize);\n decoder.heapU8.set(new Uint8Array(descriptorBuffer), descriptorPointer);\n const descriptor = module$1.SceneRequestDescriptor.deserializeFromBinary(\n descriptorPointer,\n descriptorSize\n );\n free(descriptorPointer);\n let url = descriptor.getUrl();\n if (noJwt) {\n const url_class = new URL(url);\n url_class.searchParams.delete("jwt");\n url = url_class.toString();\n }\n const body = descriptor.getBody() || null;\n const method = body ? "POST" : "GET";\n const headers = descriptor.getHeaders();\n descriptor.delete();\n const startTime = performance.now();\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal\n });\n const responseHeadersJson = JSON.stringify({\n "x-cache": response.headers.get("x-cache") ?? ""\n });\n if (!response.ok) {\n const duration2 = performance.now() - startTime;\n return [\n {\n requestIdLow,\n requestIdHigh,\n resultBuffer: new ArrayBuffer(0),\n success: false,\n parsed: false,\n error: `HTTP error! status: ${response.status}`,\n dataType: module$1.WorkerDataType.Raw.value,\n contextPtr,\n attributes: [],\n duration: duration2,\n ttfb: duration2,\n httpStatus: response.status,\n responseHeadersJson\n },\n { transfer: [] }\n ];\n }\n const rtt = performance.now() - startTime;\n const responseBuffer = await response.arrayBuffer();\n const endTime = performance.now();\n const duration = endTime - startTime;\n const attributes = [];\n const path = url.split(/[?#]/, 1)[0];\n if (!path.endsWith(".drop")) {\n return [\n {\n requestIdLow,\n requestIdHigh,\n resultBuffer: responseBuffer,\n success: true,\n parsed: false,\n error: void 0,\n dataType: module$1.WorkerDataType.Raw.value,\n contextPtr,\n attributes,\n duration,\n ttfb: rtt,\n httpStatus: response.status,\n responseHeadersJson\n },\n { transfer: [responseBuffer] }\n ];\n }\n const responseSize = responseBuffer.byteLength;\n const responsePointer = malloc(responseSize);\n decoder.heapU8.set(new Uint8Array(responseBuffer), responsePointer);\n const outputPointerPointer = malloc(4);\n const outputSizePointer = malloc(4);\n decoder.heapU32[outputPointerPointer / 4] = 0;\n decoder.heapU32[outputSizePointer / 4] = 0;\n let handle = 0;\n let outputPointer = 0;\n const attributeInfo = new decoder.AttributeInfo();\n try {\n handle = parseDropFile(responsePointer, responseSize);\n if (handle === 0) {\n throw new Error("parseDropFile failed");\n }\n let index = consecutiveIdsStart;\n for (const [name, info] of Object.entries(sparkAttributeList)) {\n if (info.discard) {\n takeAttributeFromDropFile(handle, name, index);\n } else {\n const status2 = getAttributeFromDropFile(\n handle,\n name,\n attributeInfo\n );\n if (status2 === decoder.AquaStatus.Success) {\n const wasmView = decoder.dataPtrView(attributeInfo);\n const splatData = sparkAttributeFromRaw(name, index, wasmView);\n const takeStatus = takeAttributeFromDropFile(handle, name, index);\n if (takeStatus === decoder.AquaStatus.Success) {\n attributes.push(splatData);\n }\n }\n }\n index++;\n }\n const status = flattenDropFile(\n handle,\n outputPointerPointer,\n outputSizePointer\n );\n if (status !== decoder.AquaStatus.Success) {\n throw new Error("flattenDropFile failed");\n }\n outputPointer = decoder.heapU32[outputPointerPointer / 4];\n const outputSize = decoder.heapU32[outputSizePointer / 4];\n if (outputPointer === 0) {\n throw new Error("flattenDropFile gave nullptr");\n }\n const resultBuffer = decoder.heapU8.buffer.slice(\n outputPointer,\n outputPointer + outputSize\n );\n const transferList = attributes.map((attr) => attr.paddedData.buffer);\n return [\n {\n requestIdLow,\n requestIdHigh,\n resultBuffer,\n success: true,\n parsed: true,\n error: void 0,\n dataType: module$1.WorkerDataType.Drop.value,\n contextPtr,\n attributes,\n duration,\n ttfb: rtt,\n httpStatus: response.status,\n responseHeadersJson\n },\n { transfer: [resultBuffer, ...transferList] }\n ];\n } catch (error) {\n console.error("Exception when parsing dropfile", error);\n const errorMessage = error instanceof Error ? error.stack ?? error.message : String(error);\n const empty = new Uint8Array();\n const resultBuffer = empty.buffer;\n return [\n {\n requestIdLow,\n requestIdHigh,\n resultBuffer,\n success: false,\n parsed: false,\n error: errorMessage,\n dataType: module$1.WorkerDataType.Drop.value,\n contextPtr,\n attributes: void 0,\n // Important: the main thread must not cache attributes if there\'s a failure here\n duration,\n ttfb: rtt,\n httpStatus: response.status,\n responseHeadersJson\n },\n { transfer: [resultBuffer] }\n ];\n } finally {\n destroyDropFileHandle(handle);\n free(responsePointer);\n free(outputPointerPointer);\n free(outputSizePointer);\n if (outputPointer !== 0) {\n free(outputPointer);\n }\n attributeInfo.delete();\n }\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n const isCancelled = error instanceof Error && error.name === "AbortError";\n return [\n {\n requestIdLow,\n requestIdHigh,\n resultBuffer: new ArrayBuffer(0),\n success: false,\n parsed: false,\n error: isCancelled ? "Cancelled" : errorMsg,\n dataType: module$1.WorkerDataType.Raw.value,\n contextPtr,\n attributes: [],\n duration: 0,\n ttfb: 0,\n httpStatus: 0,\n responseHeadersJson: "{}"\n },\n { transfer: [] }\n ];\n } finally {\n controllers.delete(key);\n }\n }\n});\n';
630
+ const blob = typeof self !== "undefined" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", jsContent], { type: "text/javascript;charset=utf-8" });
631
+ function WorkerWrapper(options) {
632
+ let objURL;
633
+ try {
634
+ objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
635
+ if (!objURL) throw "";
636
+ const worker = new Worker(objURL, {
637
+ type: "module",
638
+ name: options?.name
639
+ });
640
+ worker.addEventListener("error", () => {
641
+ (self.URL || self.webkitURL).revokeObjectURL(objURL);
642
+ });
643
+ return worker;
644
+ } catch (e) {
645
+ return new Worker(
646
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(jsContent),
647
+ {
648
+ type: "module",
649
+ name: options?.name
650
+ }
651
+ );
652
+ }
653
+ }
654
+ const parserWasmUrl = ((u) => u.includes("/.vite/") ? u.replace(/\.vite\/[^?#]*/, () => "@miris-inc/core/dist/aqua-parser.wasm") : u)(new URL("aqua-parser.wasm", import.meta.url).href);
655
+ class Decoder extends Thread {
656
+ static name = "decoder";
657
+ static Worker = WorkerWrapper;
658
+ constructor(init) {
659
+ super(init);
660
+ this.#sendParserWasm();
661
+ }
662
+ async #sendParserWasm() {
663
+ try {
664
+ const response = await fetch(parserWasmUrl);
665
+ if (!response.ok) {
666
+ throw new Error(`HTTP ${response.status} fetching aqua-parser.wasm`);
667
+ }
668
+ const wasmBinary = await response.arrayBuffer();
669
+ this._postToWorker({ type: "wasm-init", wasmBinary }, [wasmBinary]);
670
+ } catch (e) {
671
+ console.error("Failed to load aqua-parser.wasm for decoder worker", e);
672
+ this._postToWorker({ type: "wasm-init" });
673
+ }
674
+ }
675
+ get AttributeInfo() {
676
+ return this.module.AttributeInfo;
677
+ }
678
+ async heapSnapshot(topN) {
679
+ return this._execute("heapSnapshot", topN);
680
+ }
681
+ async heapTrackingControl(enabled) {
682
+ return this._execute("heapTrackingControl", enabled);
683
+ }
684
+ async heapTrackingReset() {
685
+ return this._execute("heapTrackingReset");
686
+ }
687
+ async cancel(requestIdLow, requestIdHigh) {
688
+ await this.ready;
689
+ this._execute("cancel", requestIdLow, requestIdHigh).catch(() => {
690
+ });
691
+ }
692
+ async decode(...args) {
693
+ const {
694
+ requestIdLow,
695
+ requestIdHigh,
696
+ resultBuffer,
697
+ success,
698
+ dataType,
699
+ contextPtr,
700
+ attributes,
701
+ duration,
702
+ ttfb,
703
+ httpStatus,
704
+ responseHeadersJson
705
+ } = await this._execute("decode", ...args);
706
+ if (attributes !== void 0) {
707
+ for (const { paddedData, originalSize, id } of attributes) {
708
+ AttributeCache.addWithId({ paddedData, originalSize }, id);
709
+ }
710
+ }
711
+ const { engine } = this;
712
+ const bufferSize = resultBuffer.byteLength;
713
+ const bufferPointer = engine.malloc(bufferSize);
714
+ engine.heapU8.set(new Uint8Array(resultBuffer), bufferPointer);
715
+ engine.onWorkerResult(
716
+ requestIdLow,
717
+ requestIdHigh,
718
+ bufferPointer,
719
+ bufferSize,
720
+ httpStatus,
721
+ duration,
722
+ ttfb,
723
+ success,
724
+ dataType,
725
+ "",
726
+ responseHeadersJson,
727
+ contextPtr
728
+ );
729
+ }
730
+ }
731
+ const sparkMinSplats = 2048;
732
+ const sparkAttributeList = {
733
+ sparkPackedSplat: { elementsPerSplat: 4, discard: false },
734
+ extendedPackedSplatLow: { elementsPerSplat: 4, discard: false },
735
+ extendedPackedSplatHigh: { elementsPerSplat: 4, discard: false },
736
+ packedSh1: { elementsPerSplat: 2, discard: false },
737
+ packedSh2: { elementsPerSplat: 4, discard: false },
738
+ packedSh3: { elementsPerSplat: 4, discard: false },
739
+ sh1Extended: { elementsPerSplat: 4, discard: false },
740
+ sh2Extended: { elementsPerSplat: 4, discard: false },
741
+ sh3Extended_0: { elementsPerSplat: 4, discard: false },
742
+ sh3Extended_1: { elementsPerSplat: 4, discard: false },
743
+ // Splatter renderer format: pre-decoded ellipsoid + spherical harmonic
744
+ // Will not be present unless the c++ was compiled with --enable-feature splatter
745
+ splatterEllipsoids: { elementsPerSplat: 12, discard: false },
746
+ splatterSphericalHarmonics: { elementsPerSplat: 16, discard: false }
747
+ };
748
+ function roundUpToMultipleOf(a, multiple) {
749
+ return Math.ceil(a / multiple) * multiple;
750
+ }
751
+ function sparkAttributeFromRaw(name, id, wasmView) {
752
+ const attrib = sparkAttributeList[name];
753
+ if (attrib === void 0)
754
+ throw new Error("attribute name" + name + " is unknown");
755
+ const originalSize = wasmView.length;
756
+ const paddedSize = roundUpToMultipleOf(
757
+ originalSize,
758
+ attrib.elementsPerSplat * sparkMinSplats
759
+ );
760
+ const paddedData = new Uint32Array(paddedSize);
761
+ paddedData.set(wasmView);
762
+ return { paddedData, originalSize, id };
763
+ }
764
+ class AttributeNames {
765
+ static SPARK_PACKED_SPLAT = "sparkPackedSplat";
766
+ static SPARK_EXTENDED_SPLAT_LOW = "extendedPackedSplatLow";
767
+ static SPARK_EXTENDED_SPLAT_HIGH = "extendedPackedSplatHigh";
768
+ static SPARK_PACKED_SH1 = "packedSh1";
769
+ static SPARK_PACKED_SH2 = "packedSh2";
770
+ static SPARK_PACKED_SH3 = "packedSh3";
771
+ static SPARK_EXTENDED_SH1 = "sh1Extended";
772
+ static SPARK_EXTENDED_SH2 = "sh2Extended";
773
+ static SPARK_EXTENDED_SH3_A = "sh3Extended_0";
774
+ static SPARK_EXTENDED_SH3_B = "sh3Extended_1";
775
+ static UNUSED = "unused";
776
+ static SPLATTER_ELLIPSOIDS = "splatterEllipsoids";
777
+ static SPLATTER_SPHERICAL_HARMONICS = "splatterSphericalHarmonics";
778
+ }
779
+ class Engine {
780
+ static AquaStatus = {
781
+ Success: 0,
782
+ Failure: 1
783
+ };
784
+ static SceneObjectType = {
785
+ ModelRoot: 0,
786
+ SceneObject: 1,
787
+ StreamObject: 2,
788
+ GaussianSplats: 3,
789
+ PointsObject: 4,
790
+ Camera: 5,
791
+ LodOctree: 6,
792
+ VariantSetCollection: 7,
793
+ VariantSet: 8,
794
+ VariantSetOption: 9
795
+ };
796
+ static Feature = {
797
+ DrMap: 0,
798
+ ReflMesh: 1,
799
+ GlassMesh: 2
800
+ };
801
+ static FeatureState = {
802
+ NotLoaded: 0,
803
+ Pending: 1,
804
+ Loaded: 2,
805
+ Failed: 3
806
+ };
807
+ #module;
808
+ get module() {
809
+ if (!this.#module) {
810
+ throw new Error(
811
+ "Engine has not yet been initialized. Did you forget to `await engine.ready()?`"
812
+ );
813
+ }
814
+ return this.#module;
815
+ }
816
+ #decoders = /* @__PURE__ */ new Set();
817
+ #requestMap = /* @__PURE__ */ new Map();
818
+ // TODO: rework JWT handling
819
+ #noJwt = new URL(location.href).searchParams.has("nojwt");
820
+ constructor(moduleOptions = {}) {
821
+ Object.defineProperty(this, "pending", {
822
+ value: true,
823
+ configurable: true,
824
+ enumerable: true
825
+ });
826
+ Object.defineProperty(this, "ready", {
827
+ enumerable: true,
828
+ value: this.#initialize(moduleOptions)
829
+ });
830
+ }
831
+ async #initialize(moduleOptions) {
832
+ this.#module = await _factory({
833
+ createDeserializeWorker: this.createDeserializeWorker.bind(this),
834
+ submitToWorker: this.submitToWorker.bind(this),
835
+ cancelRequest: this.cancelRequest.bind(this),
836
+ terminateWorker: this.terminateWorker.bind(this),
837
+ // TODO: remove this possibly
838
+ workerUrl: "aqua-parser",
839
+ ...moduleOptions,
840
+ // preRun fires after Emscripten replaces Module.ENV with its internal
841
+ // ENV object, but before initRuntime() caches getEnvStrings(). This is
842
+ // the only window where mutations to Module.ENV reach C getenv().
843
+ preRun: [(mod) => Object.assign(mod.ENV, Engine.#env())]
844
+ });
845
+ Object.defineProperty(this, "pending", {
846
+ value: false,
847
+ configurable: false
848
+ });
849
+ return this;
850
+ }
851
+ /*
852
+ |----------------------------------------------------------------------------
853
+ | Wasm Exports
854
+ |----------------------------------------------------------------------------
855
+ |
856
+ | All exported Wasm functions should be wrapped here. A wrapper is just a
857
+ | getter property for classes, or a wrapper method for functions. Some
858
+ | methods call module exports directly and others exports use cwap.
859
+ |
860
+ */
861
+ get AttributeInfo() {
862
+ return this.module.AttributeInfo;
863
+ }
864
+ get Handedness() {
865
+ return this.module.Handedness;
866
+ }
867
+ get heapF32() {
868
+ return this.module.HEAPF32;
869
+ }
870
+ get heapU8() {
871
+ return this.module.HEAPU8;
872
+ }
873
+ get MatrixOrder() {
874
+ return this.module.MatrixOrder;
875
+ }
876
+ get SceneChangeIds() {
877
+ return this.module.SceneChangeIds;
878
+ }
879
+ get SceneMetadata() {
880
+ return this.module.SceneMetadata;
881
+ }
882
+ get RuntimeSettings() {
883
+ return this.module.RuntimeSettings;
884
+ }
885
+ get SpatialFormat() {
886
+ return this.module.SpatialFormat;
887
+ }
888
+ get StringVector() {
889
+ return this.module.StringVector;
890
+ }
891
+ get UpAxis() {
892
+ return this.module.UpAxis;
893
+ }
894
+ activatedObjectIdsView(...args) {
895
+ return this.module.activatedObjectIdsView(...args);
896
+ }
897
+ addStreamById(...args) {
898
+ return this.module.ccall(
899
+ "AddStreamById",
900
+ "number",
901
+ ["number", "string", "string", "number"],
902
+ args
903
+ );
904
+ }
905
+ addPrefetchStreamById(...args) {
906
+ return this.module.ccall(
907
+ "AddPrefetchStreamById",
908
+ "number",
909
+ ["number", "string", "string", "number", "boolean"],
910
+ args
911
+ );
912
+ }
913
+ allocateSceneChangesArrays(...args) {
914
+ return this.module.AllocateSceneChangesArrays(...args);
915
+ }
916
+ createContext(...args) {
917
+ return this.module.ccall("CreateAquaContext", "number", [], args);
918
+ }
919
+ destroyContext(...args) {
920
+ return this.module.ccall("DestroyAquaContext", "number", ["number"], args);
921
+ }
922
+ createClient(context, ...args) {
923
+ if (context) {
924
+ return this.module.ccall("CreateClientForContext", "number", ["number"], [context, ...args]);
925
+ }
926
+ return this.module.ccall("CreateClient", "number", [], args);
927
+ }
928
+ createdObjectIdsView(...args) {
929
+ return this.module.createdObjectIdsView(...args);
930
+ }
931
+ deletedObjectIdsView(...args) {
932
+ return this.module.deletedObjectIdsView(...args);
933
+ }
934
+ dataPtrView(...args) {
935
+ return this.module.dataPtrView(...args);
936
+ }
937
+ deactivatedObjectIdsView(...args) {
938
+ return this.module.deactivatedObjectIdsView(...args);
939
+ }
940
+ destroyClient(...args) {
941
+ return this.module.ccall("DestroyClient", "number", ["number"], args);
942
+ }
943
+ free(...args) {
944
+ return this.module.ccall("free", "number", ["number"], args);
945
+ }
946
+ getAssetsAsync(...args) {
947
+ return this.module.GetAssetsAsync(...args);
948
+ }
949
+ getAttribute(...args) {
950
+ return this.module.ccall(
951
+ "GetAttribute",
952
+ "number",
953
+ ["number", "number", "string", "number"],
954
+ args
955
+ );
956
+ }
957
+ getDefaultCameraId(...args) {
958
+ return this.module.ccall("GetDefaultCameraId", "number", ["number"], args);
959
+ }
960
+ getLocalBoundingBox(...args) {
961
+ return this.module.ccall(
962
+ "GetLocalBoundingBox",
963
+ "number",
964
+ ["number", "number", "number"],
965
+ args
966
+ );
967
+ }
968
+ getWorldBoundingBox(...args) {
969
+ return this.module.ccall(
970
+ "GetWorldBoundingBox",
971
+ "number",
972
+ ["number", "number", "number"],
973
+ args
974
+ );
975
+ }
976
+ getLodIndex(...args) {
977
+ return this.module.ccall(
978
+ "GetLodIndex",
979
+ "number",
980
+ ["number", "number"],
981
+ args
982
+ );
983
+ }
984
+ getSceneChanges(...args) {
985
+ return this.module.GetSceneChanges(...args);
986
+ }
987
+ getSceneChangesCounts(...args) {
988
+ return this.module.GetSceneChangesCounts(...args);
989
+ }
990
+ getSceneMetadata(...args) {
991
+ return this.module.GetSceneMetadata(...args).value;
992
+ }
993
+ getSceneObjectParent(...args) {
994
+ return this.module.ccall(
995
+ "GetSceneObjectParent",
996
+ "number",
997
+ ["number", "number"],
998
+ args
999
+ );
1000
+ }
1001
+ getSceneObjectType(...args) {
1002
+ return this.module.ccall(
1003
+ "GetSceneObjectType",
1004
+ "number",
1005
+ ["number", "number"],
1006
+ args
1007
+ );
1008
+ }
1009
+ getLocalTransform(...args) {
1010
+ return this.module.ccall(
1011
+ "MirisGetLocalTransform",
1012
+ "number",
1013
+ ["number", "number", "number"],
1014
+ args
1015
+ );
1016
+ }
1017
+ getWorldTransform(...args) {
1018
+ return this.module.ccall(
1019
+ "MirisGetWorldTransform",
1020
+ "number",
1021
+ ["number", "number", "number"],
1022
+ args
1023
+ );
1024
+ }
1025
+ hasAttribute(...args) {
1026
+ return this.module.ccall(
1027
+ "HasAttribute",
1028
+ "boolean",
1029
+ ["number", "number", "string"],
1030
+ args
1031
+ );
1032
+ }
1033
+ isSceneObjectAncestorOf(...args) {
1034
+ return this.module.ccall(
1035
+ "IsSceneObjectAncestorOf",
1036
+ "boolean",
1037
+ ["number", "number", "number"],
1038
+ args
1039
+ );
1040
+ }
1041
+ lockScene(...args) {
1042
+ return this.module.ccall("LockScene", "number", ["number"], args);
1043
+ }
1044
+ malloc(...args) {
1045
+ return this.module.ccall("malloc", "number", ["number"], args);
1046
+ }
1047
+ modifiedObjectIdsView(...args) {
1048
+ return this.module.modifiedObjectIdsView(...args);
1049
+ }
1050
+ onWorkerResult(...args) {
1051
+ const requestKey = `${args[1]}-${args[0]}`;
1052
+ this.#requestMap.delete(requestKey);
1053
+ return this.module.ccall(
1054
+ "onWorkerResult",
1055
+ null,
1056
+ [
1057
+ "number",
1058
+ // requestIdLow
1059
+ "number",
1060
+ // requestIdHigh
1061
+ "number",
1062
+ // bufferPtr
1063
+ "number",
1064
+ // bufferSize
1065
+ "number",
1066
+ // httpStatus
1067
+ "number",
1068
+ // durationMs (C++ arg 6)
1069
+ "number",
1070
+ // ttfbMs (C++ arg 7)
1071
+ "number",
1072
+ // success (C++ arg 8)
1073
+ "number",
1074
+ // dataType (C++ arg 9)
1075
+ "string",
1076
+ // errorPtr (C++ arg 10)
1077
+ "string",
1078
+ // responseHeadersJson (C++ arg 11)
1079
+ "number"
1080
+ // contextPtr (C++ arg 12)
1081
+ ],
1082
+ args
1083
+ );
1084
+ }
1085
+ removeStream(...args) {
1086
+ return this.module.ccall(
1087
+ "RemoveStream",
1088
+ "boolean",
1089
+ ["pointer", "number"],
1090
+ args
1091
+ );
1092
+ }
1093
+ setAssetViewerKey(...args) {
1094
+ return this.module.ccall(
1095
+ "SetAssetViewerKey",
1096
+ "number",
1097
+ ["number", "string"],
1098
+ args
1099
+ );
1100
+ }
1101
+ setClientSpatialFormat(...args) {
1102
+ return this.module.SetClientSpatialFormat(...args).value;
1103
+ }
1104
+ setRuntimeSettings(...args) {
1105
+ return this.module.SetRuntimeSettings(...args).value;
1106
+ }
1107
+ setMainCameraTransform(...args) {
1108
+ return this.module.ccall(
1109
+ "SetMainCameraTransform",
1110
+ "number",
1111
+ ["number", "number"],
1112
+ args
1113
+ );
1114
+ }
1115
+ setMainCameraViewFrustum(...args) {
1116
+ return this.module.ccall(
1117
+ "SetMainCameraViewFrustum",
1118
+ "number",
1119
+ ["number", "number", "number", "number", "number"],
1120
+ args
1121
+ );
1122
+ }
1123
+ setMaxCacheSize(...args) {
1124
+ return this.module.setMaxCacheSize(...args);
1125
+ }
1126
+ setSceneObjectTransform(...args) {
1127
+ return this.module.ccall(
1128
+ "SetSceneObjectTransform",
1129
+ "number",
1130
+ ["number", "number", "number"],
1131
+ args
1132
+ );
1133
+ }
1134
+ // Feature API
1135
+ hasFeature(...args) {
1136
+ return this.module.HasFeature(...args);
1137
+ }
1138
+ getFeatureVersion(...args) {
1139
+ return this.module.GetFeatureVersion(...args);
1140
+ }
1141
+ getFeatureState(...args) {
1142
+ return this.module.GetFeatureState(...args);
1143
+ }
1144
+ // Object Name API
1145
+ getName(...args) {
1146
+ return this.module.GetName(...args);
1147
+ }
1148
+ setVariantSelection(...args) {
1149
+ return this.module.ccall(
1150
+ "SetVariantSelection",
1151
+ "number",
1152
+ ["number", "number"],
1153
+ args
1154
+ );
1155
+ }
1156
+ takeAttribute(...args) {
1157
+ return this.module.ccall(
1158
+ "TakeAttribute",
1159
+ "number",
1160
+ ["number", "number", "string", "bigint"],
1161
+ args
1162
+ );
1163
+ }
1164
+ takeEvictedClientSideAttributeIds(...args) {
1165
+ return this.module.TakeEvictedClientSideAttributeIds(...args);
1166
+ }
1167
+ getActiveClientSideIdsCheckSum() {
1168
+ return this.module.GetActiveClientSideIdsCheckSum();
1169
+ }
1170
+ unlockScene(...args) {
1171
+ return this.module.ccall("UnlockScene", "number", ["number"], args);
1172
+ }
1173
+ updateSceneExecution(...args) {
1174
+ return this.module.ccall(
1175
+ "UpdateSceneExecution",
1176
+ "number",
1177
+ ["number"],
1178
+ args
1179
+ );
1180
+ }
1181
+ recordFrameTime(...args) {
1182
+ return this.module.ccall(
1183
+ "RecordFrameTime",
1184
+ "number",
1185
+ ["number", "number"],
1186
+ args
1187
+ );
1188
+ }
1189
+ takeRenderRequired(...args) {
1190
+ return this.module.TakeRenderRequired(...args);
1191
+ }
1192
+ /*
1193
+ |----------------------------------------------------------------------------
1194
+ | Decoder helpers
1195
+ |----------------------------------------------------------------------------
1196
+ */
1197
+ createDeserializeWorker(_url, _workerUrl, poolSize) {
1198
+ for (let index = 1; index < poolSize; index += 1) {
1199
+ this.#decoders.add(new Decoder({ engine: this }));
1200
+ }
1201
+ return true;
1202
+ }
1203
+ cancelRequest(requestIdLow, requestIdHigh) {
1204
+ const requestKey = `${requestIdHigh}-${requestIdLow}`;
1205
+ const decoder = this.#requestMap.get(requestKey);
1206
+ if (decoder) {
1207
+ decoder.cancel(requestIdLow, requestIdHigh);
1208
+ this.#requestMap.delete(requestKey);
1209
+ }
1210
+ return true;
1211
+ }
1212
+ submitToWorker(requestIdLow, requestIdHigh, descriptorBuffer, contextPtr) {
1213
+ const decoder = [...this.#decoders.values()].reduce((previous, current) => {
1214
+ if (!previous) return current;
1215
+ return current.pendingRequests < previous.pendingRequests ? current : previous;
1216
+ });
1217
+ const requestKey = `${requestIdHigh}-${requestIdLow}`;
1218
+ this.#requestMap.set(requestKey, decoder);
1219
+ const firstId = AttributeCache.getConsecutiveIds(
1220
+ Object.keys(sparkAttributeList).length
1221
+ );
1222
+ decoder.ready.then(
1223
+ () => decoder.decode(
1224
+ requestIdLow,
1225
+ requestIdHigh,
1226
+ descriptorBuffer,
1227
+ contextPtr,
1228
+ firstId,
1229
+ this.#noJwt
1230
+ )
1231
+ );
1232
+ return true;
1233
+ }
1234
+ terminateWorker() {
1235
+ for (const decoder of this.#decoders) {
1236
+ decoder.terminate();
1237
+ }
1238
+ this.#decoders.clear();
1239
+ }
1240
+ /*
1241
+ |----------------------------------------------------------------------------
1242
+ | Heap profiler helpers (fan-out to all decoder workers)
1243
+ |----------------------------------------------------------------------------
1244
+ */
1245
+ async requestWorkerHeapSnapshots(topN) {
1246
+ const decoders = [...this.#decoders];
1247
+ const results = await Promise.allSettled(
1248
+ decoders.map(
1249
+ (d) => d.ready.then(() => {
1250
+ let timer;
1251
+ const timeout = new Promise((resolve) => {
1252
+ timer = setTimeout(() => resolve(null), 5e3);
1253
+ });
1254
+ return Promise.race([
1255
+ d.heapSnapshot(topN).then((r) => r.snapshotJson),
1256
+ timeout
1257
+ ]).finally(() => clearTimeout(timer));
1258
+ })
1259
+ )
1260
+ );
1261
+ return results.map((r) => r.status === "fulfilled" ? r.value : null);
1262
+ }
1263
+ async setWorkerHeapTrackingEnabled(enabled) {
1264
+ await Promise.allSettled(
1265
+ [...this.#decoders].map(
1266
+ (d) => d.ready.then(() => d.heapTrackingControl(enabled))
1267
+ )
1268
+ );
1269
+ }
1270
+ async resetWorkerHeapTracking() {
1271
+ await Promise.allSettled(
1272
+ [...this.#decoders].map((d) => d.ready.then(() => d.heapTrackingReset()))
1273
+ );
1274
+ }
1275
+ static #env() {
1276
+ const url = "https://app.miris.com/viewer/v1";
1277
+ return {
1278
+ AQUA_USE_SINGLETON_NETWORK_TRANSPORT: "true",
1279
+ ...{ AQUA_SERVER_BASE_URL: url }
1280
+ };
1281
+ }
1282
+ }
1283
+ const RATES = [30, 60, 72, 90, 120, 144, 165, 240];
1284
+ function createRefreshRateDetector() {
1285
+ let samples = [], last = null, hz = 0;
1286
+ screen.addEventListener?.("change", () => {
1287
+ samples = [];
1288
+ hz = 0;
1289
+ last = null;
1290
+ });
1291
+ return {
1292
+ update(ts) {
1293
+ if (hz)
1294
+ return;
1295
+ if (last !== null) {
1296
+ samples.push(ts - last);
1297
+ if (samples.length > 60)
1298
+ samples.shift();
1299
+ if (!hz && samples.length === 60) {
1300
+ const avg = samples.reduce((a, b) => a + b, 0) / samples.length;
1301
+ const meanHz = 1e3 / avg;
1302
+ hz = RATES.reduce((a, b) => Math.abs(b - meanHz) < Math.abs(a - meanHz) ? b : a);
1303
+ }
1304
+ }
1305
+ last = ts;
1306
+ },
1307
+ get nativeHz() {
1308
+ return hz;
1309
+ }
1310
+ };
1311
+ }
1312
+ class Miris {
1313
+ static _instance;
1314
+ static async instance() {
1315
+ const miris = this._instance ??= new this();
1316
+ await miris.ready;
1317
+ return miris;
1318
+ }
1319
+ #sharedContext;
1320
+ get sharedContext() {
1321
+ return this.#sharedContext;
1322
+ }
1323
+ #viewerKey;
1324
+ get viewerKey() {
1325
+ return this.#viewerKey;
1326
+ }
1327
+ set viewerKey(viewerKey) {
1328
+ this.#viewerKey = viewerKey;
1329
+ }
1330
+ #scenes = /* @__PURE__ */ new Set();
1331
+ get scenes() {
1332
+ return new Set(this.#scenes);
1333
+ }
1334
+ #changes = [];
1335
+ #changeIds = null;
1336
+ #pendingActivations = /* @__PURE__ */ new Set();
1337
+ #pendingDeactivations = /* @__PURE__ */ new Map();
1338
+ #useSphericalHarmonics = true;
1339
+ get useSphericalHarmonics() {
1340
+ return this.#useSphericalHarmonics;
1341
+ }
1342
+ set useSphericalHarmonics(value) {
1343
+ this.#useSphericalHarmonics = value;
1344
+ }
1345
+ constructor() {
1346
+ if (!this.constructor.prototype._instance) {
1347
+ this.constructor.prototype._instance = this;
1348
+ }
1349
+ Object.defineProperties(this, {
1350
+ pending: { value: true, configurable: true, enumerable: true },
1351
+ engine: { value: new Engine(), enumerable: true }
1352
+ });
1353
+ Object.defineProperty(this, "ready", {
1354
+ enumerable: true,
1355
+ value: this.#initializeMiris()
1356
+ });
1357
+ console.assert(this._xrModeActive === false);
1358
+ this.#bindRequestAnimationFrame();
1359
+ }
1360
+ async #initializeMiris() {
1361
+ const { engine } = this;
1362
+ await engine.ready;
1363
+ this.#sharedContext = this.engine.createContext();
1364
+ const mb = 1024 * 1024;
1365
+ const urlParams = new URLSearchParams(window.location.search);
1366
+ const maxCacheSizeParam = urlParams.get("aquaMaxCacheSize");
1367
+ let maxCacheSizeMB = 0;
1368
+ if (maxCacheSizeParam) {
1369
+ const parsedSize = parseInt(maxCacheSizeParam, 10);
1370
+ if (!isNaN(parsedSize) && parsedSize > 0) {
1371
+ maxCacheSizeMB = parsedSize;
1372
+ }
1373
+ }
1374
+ if (maxCacheSizeMB > 0) {
1375
+ this.engine.setMaxCacheSize(maxCacheSizeMB * mb);
1376
+ } else if (navigator.userAgent.includes("iPhone")) {
1377
+ this.engine.setMaxCacheSize(128 * mb);
1378
+ } else if (navigator.userAgent.includes("Android")) {
1379
+ this.engine.setMaxCacheSize(256 * mb);
1380
+ }
1381
+ this.#browserUpdate();
1382
+ Object.defineProperty(this, "pending", {
1383
+ value: false,
1384
+ configurable: false
1385
+ });
1386
+ return this;
1387
+ }
1388
+ dispose() {
1389
+ if (this.#sharedContext) {
1390
+ if (this.engine.destroyContext(this.#sharedContext) !== Engine.AquaStatus.Success) {
1391
+ console.error(
1392
+ `Failed to destroy aqua context with handle '${this.#sharedContext}'`
1393
+ );
1394
+ }
1395
+ this.#sharedContext = 0;
1396
+ }
1397
+ }
1398
+ updateParentedTransform(_modelTransform, _parentTransform) {
1399
+ return void 0;
1400
+ }
1401
+ #detector = createRefreshRateDetector();
1402
+ #boundUpdate = this.#browserUpdate.bind(this);
1403
+ // Set once a host drives update() from its own render loop; the internal RAF loop then stops so
1404
+ // _update() runs exactly once per displayed frame (renderer-driven hosts otherwise tick twice).
1405
+ #hostDriven = false;
1406
+ // Timestamp of the previous _update() tick, for the per-frame render time fed to the
1407
+ // budget controller. null = no prior frame (first tick / post-stall).
1408
+ #lastFrameTimestamp = null;
1409
+ #lastUpdateTs = -1;
1410
+ #targetFramesPerSecond = 72;
1411
+ #splatCountBudgetOverride = null;
1412
+ _xrModeActive = false;
1413
+ _xrSession = null;
1414
+ _requestAnimationFrame = null;
1415
+ signalResumeFromIdle() {
1416
+ }
1417
+ #applyDisplaySettings() {
1418
+ const settings = new this.engine.RuntimeSettings();
1419
+ settings.targetFramesPerSecond = this.#targetFramesPerSecond;
1420
+ settings.xrModeActive = this._xrModeActive;
1421
+ if (this.#splatCountBudgetOverride !== null) {
1422
+ settings.splatCountBudget = this.#splatCountBudgetOverride;
1423
+ } else if (this._xrModeActive) {
1424
+ settings.splatCountBudget = 2e5;
1425
+ }
1426
+ for (const scene of this.#scenes) {
1427
+ scene.client.setRuntimeSettings(settings);
1428
+ }
1429
+ settings.delete();
1430
+ }
1431
+ /**
1432
+ * Why 43? Because the AVP throttles down to 45Hz :(
1433
+ */
1434
+ static _XR_TARGET_FRAME_RATE = 43;
1435
+ #bindRequestAnimationFrame() {
1436
+ this._requestAnimationFrame = this._xrModeActive ? (
1437
+ // _xrSession is always set whenever XR mode is active (see _setXRModeActive).
1438
+ this._xrSession.requestAnimationFrame.bind(this._xrSession)
1439
+ ) : window.requestAnimationFrame.bind(window);
1440
+ }
1441
+ /**
1442
+ * @internal
1443
+ */
1444
+ _setTargetFrameRate(frameRate) {
1445
+ this.#targetFramesPerSecond = frameRate;
1446
+ this.#detector = null;
1447
+ this.#applyDisplaySettings();
1448
+ }
1449
+ /**
1450
+ * @internal
1451
+ */
1452
+ _setXRModeActive(active, frameRate, xrSession) {
1453
+ this._xrModeActive = active;
1454
+ this._xrSession = xrSession ?? null;
1455
+ if (frameRate !== void 0) {
1456
+ this.#targetFramesPerSecond = frameRate;
1457
+ }
1458
+ this.#applyDisplaySettings();
1459
+ this.#bindRequestAnimationFrame();
1460
+ }
1461
+ /**
1462
+ * @internal
1463
+ */
1464
+ _setSplatCountBudgetOverride(budget) {
1465
+ this.#splatCountBudgetOverride = budget;
1466
+ this.#applyDisplaySettings();
1467
+ }
1468
+ #browserUpdate(ts = 0) {
1469
+ if (this.#hostDriven) return;
1470
+ this._update(ts);
1471
+ if (this._xrModeActive) {
1472
+ return;
1473
+ }
1474
+ requestAnimationFrame(this.#boundUpdate);
1475
+ }
1476
+ /**
1477
+ * @internal
1478
+ *
1479
+ * Shared update function being driven by browser's update loop or an XR session
1480
+ */
1481
+ _update(ts = 0) {
1482
+ if (ts !== 0 && ts === this.#lastUpdateTs) {
1483
+ return;
1484
+ }
1485
+ this.#lastUpdateTs = ts;
1486
+ if (this.#detector) {
1487
+ this.#detector.update(performance.now());
1488
+ if (this.#detector.nativeHz > 0) {
1489
+ const hz = this.#detector.nativeHz;
1490
+ this.#targetFramesPerSecond = hz <= 40 ? hz : 40;
1491
+ this.#applyDisplaySettings();
1492
+ this.#detector = null;
1493
+ }
1494
+ }
1495
+ const now = performance.now();
1496
+ const elapsed = this.#lastFrameTimestamp === null ? null : now - this.#lastFrameTimestamp;
1497
+ this.#lastFrameTimestamp = now;
1498
+ const MAX_PLAUSIBLE_FRAME_MS = 1e3;
1499
+ const frameTimeMs = elapsed !== null && elapsed <= MAX_PLAUSIBLE_FRAME_MS ? elapsed : null;
1500
+ for (const scene of this.#scenes) {
1501
+ const { client } = scene;
1502
+ if (frameTimeMs !== null) {
1503
+ client.recordFrameTime(frameTimeMs);
1504
+ }
1505
+ client.updateSceneExecution();
1506
+ const evicted = client.takeEvictedClientSideAttributeIds();
1507
+ try {
1508
+ const evictedSize = evicted.size();
1509
+ if (evictedSize > 0) {
1510
+ const evictedArray = [];
1511
+ for (let i = 0; i < evictedSize; i++) {
1512
+ evictedArray.push(Number(evicted.get(i)));
1513
+ }
1514
+ AttributeCache.remove(evictedArray);
1515
+ }
1516
+ } finally {
1517
+ evicted.delete();
1518
+ }
1519
+ const checkSumWasm = this.engine.getActiveClientSideIdsCheckSum();
1520
+ AttributeCache.validateCheckSum(checkSumWasm);
1521
+ const locked = client.lockScene();
1522
+ if (!locked) {
1523
+ return;
1524
+ }
1525
+ try {
1526
+ this.#updateScene(scene);
1527
+ } finally {
1528
+ client.unlockScene();
1529
+ }
1530
+ }
1531
+ if (this.#changes.length) {
1532
+ this.applyChanges(this.#changes);
1533
+ this.#changes.length = 0;
1534
+ }
1535
+ }
1536
+ #retrieveFloatArray(objectId, arraySize, fn) {
1537
+ const sizeOfFloat = 4;
1538
+ const arrayPtr = this.engine.malloc(arraySize * sizeOfFloat);
1539
+ fn(objectId, arrayPtr);
1540
+ const floatArray = this.engine.heapF32.subarray(arrayPtr >> 2, (arrayPtr >> 2) + arraySize).slice();
1541
+ this.engine.free(arrayPtr);
1542
+ return floatArray;
1543
+ }
1544
+ getLocalTransform(client, sceneObjectId) {
1545
+ if (Number.isInteger(sceneObjectId) && sceneObjectId >= 0) {
1546
+ return this.#retrieveFloatArray(
1547
+ sceneObjectId,
1548
+ 16,
1549
+ client.getLocalTransform.bind(client)
1550
+ );
1551
+ }
1552
+ }
1553
+ getWorldTransform(client, sceneObjectId) {
1554
+ if (Number.isInteger(sceneObjectId) && sceneObjectId >= 0) {
1555
+ return this.#retrieveFloatArray(
1556
+ sceneObjectId,
1557
+ 16,
1558
+ client.getWorldTransform.bind(client)
1559
+ );
1560
+ }
1561
+ }
1562
+ #shouldUpdateSceneChanges() {
1563
+ if (!this.#changeIds) {
1564
+ return false;
1565
+ }
1566
+ if (this.#changeIds.createdObjectsCount > 0) {
1567
+ return true;
1568
+ }
1569
+ if (this.#changeIds.activatedObjectsCount > 0) {
1570
+ return true;
1571
+ }
1572
+ if (this.#changeIds.deactivatedObjectsCount > 0) {
1573
+ return true;
1574
+ }
1575
+ if (this.#changeIds.modifiedObjectsCount > 0) {
1576
+ return true;
1577
+ }
1578
+ if (this.#changeIds.deletedObjectsCount > 0) {
1579
+ return true;
1580
+ }
1581
+ return false;
1582
+ }
1583
+ #getDataFromAttribute(client, sceneObjectId, attributeName, outAttributeInfo) {
1584
+ const { engine } = this;
1585
+ if (!client.hasAttribute(sceneObjectId, attributeName)) {
1586
+ return null;
1587
+ }
1588
+ const { ptr } = outAttributeInfo.$$;
1589
+ const status = client.getAttribute(sceneObjectId, attributeName, ptr);
1590
+ if (status !== Engine.AquaStatus.Success) {
1591
+ console.warn(
1592
+ `GetAttribute failed for object id ${sceneObjectId} and attribute name ${attributeName}: status ${status}`
1593
+ );
1594
+ return null;
1595
+ }
1596
+ let paddedData;
1597
+ let originalSize;
1598
+ if (outAttributeInfo.clientSideId != 0n) {
1599
+ ({ paddedData, originalSize } = AttributeCache.get(
1600
+ Number(outAttributeInfo.clientSideId)
1601
+ ));
1602
+ } else {
1603
+ const wasmView = engine.dataPtrView(outAttributeInfo);
1604
+ const result = sparkAttributeFromRaw(attributeName, 0, wasmView);
1605
+ paddedData = result.paddedData;
1606
+ originalSize = result.originalSize;
1607
+ const myCacheEntry = AttributeCache.add({
1608
+ paddedData: result.paddedData,
1609
+ originalSize: result.originalSize
1610
+ });
1611
+ const takeStatus = client.takeAttribute(
1612
+ sceneObjectId,
1613
+ attributeName,
1614
+ BigInt(myCacheEntry)
1615
+ );
1616
+ if (takeStatus !== Engine.AquaStatus.Success) {
1617
+ AttributeCache.remove(myCacheEntry);
1618
+ console.warn(
1619
+ `Failed to take attribute ${attributeName} for scene object ${sceneObjectId}: status ${takeStatus}`
1620
+ );
1621
+ return null;
1622
+ }
1623
+ }
1624
+ return { paddedData, originalSize };
1625
+ }
1626
+ #updateScene(scene) {
1627
+ const { engine } = this;
1628
+ const { client, camera, lods } = scene;
1629
+ if (camera) {
1630
+ camera.update();
1631
+ }
1632
+ if (this.#changeIds === null) {
1633
+ this.#changeIds = new engine.SceneChangeIds();
1634
+ }
1635
+ client.getSceneChangesCounts(this.#changeIds);
1636
+ if (!this.#shouldUpdateSceneChanges()) {
1637
+ return;
1638
+ }
1639
+ engine.allocateSceneChangesArrays(this.#changeIds);
1640
+ client.getSceneChanges(this.#changeIds);
1641
+ const createdLodIds = /* @__PURE__ */ new Set();
1642
+ for (const sceneObjectId of engine.createdObjectIdsView(this.#changeIds)) {
1643
+ const sceneObjectType = client.getSceneObjectType(sceneObjectId);
1644
+ if (sceneObjectType === Engine.SceneObjectType.StreamObject) {
1645
+ Stream.forId(sceneObjectId);
1646
+ continue;
1647
+ } else if (sceneObjectType === Engine.SceneObjectType.ModelRoot) {
1648
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1649
+ if (!stream) continue;
1650
+ const modelRoot = new ModelRoot({ id: sceneObjectId, stream });
1651
+ const modelRootTransform = this.getLocalTransform(
1652
+ client,
1653
+ sceneObjectId
1654
+ );
1655
+ if (!modelRootTransform) continue;
1656
+ const parentId = client.getSceneObjectParent(sceneObjectId);
1657
+ const parentTransform = this.getLocalTransform(client, parentId);
1658
+ if (!parentTransform) continue;
1659
+ const updatedTransform = this.updateParentedTransform(
1660
+ modelRootTransform,
1661
+ parentTransform
1662
+ );
1663
+ if (!updatedTransform) continue;
1664
+ modelRoot.transform = updatedTransform;
1665
+ } else if (sceneObjectType == Engine.SceneObjectType.GaussianSplats) {
1666
+ const modelRoot = scene.getModelRootForDescendentId(sceneObjectId);
1667
+ if (!modelRoot) continue;
1668
+ const lod = new Lod({ id: sceneObjectId, modelRoot, lodStore: lods });
1669
+ lod.transform = this.getLocalTransform(client, sceneObjectId);
1670
+ createdLodIds.add(sceneObjectId);
1671
+ const entry = new Change({ type: "created", lod });
1672
+ this.#changes.push(entry);
1673
+ } else if (sceneObjectType == Engine.SceneObjectType.VariantSetCollection) {
1674
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1675
+ stream?._addVariantCollection(sceneObjectId);
1676
+ } else if (sceneObjectType == Engine.SceneObjectType.VariantSet) {
1677
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1678
+ const name = client.getName(sceneObjectId);
1679
+ const parentId = client.getSceneObjectParent(sceneObjectId);
1680
+ stream?._addVariant(parentId, {
1681
+ id: sceneObjectId,
1682
+ name,
1683
+ options: [],
1684
+ nestedSets: []
1685
+ });
1686
+ } else if (sceneObjectType == Engine.SceneObjectType.VariantSetOption) {
1687
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1688
+ const name = client.getName(sceneObjectId);
1689
+ const parentId = client.getSceneObjectParent(sceneObjectId);
1690
+ stream?._addVariant(parentId, {
1691
+ id: sceneObjectId,
1692
+ name,
1693
+ type: "option"
1694
+ });
1695
+ }
1696
+ }
1697
+ for (const sceneObjectId of engine.deletedObjectIdsView(this.#changeIds)) {
1698
+ const lod = lods.forId(sceneObjectId);
1699
+ if (!lod) {
1700
+ continue;
1701
+ }
1702
+ const entry = new Change({ type: "deleted", lod });
1703
+ this.#changes.push(entry);
1704
+ }
1705
+ for (const sceneObjectId of engine.modifiedObjectIdsView(this.#changeIds)) {
1706
+ const sceneObjectType = client.getSceneObjectType(sceneObjectId);
1707
+ if (sceneObjectType === Engine.SceneObjectType.LodOctree) {
1708
+ scene._onFeatureData(sceneObjectId);
1709
+ } else if (sceneObjectType === Engine.SceneObjectType.GaussianSplats) {
1710
+ const lodIndex = client.getLodIndex(sceneObjectId);
1711
+ const attributeInfo = new engine.AttributeInfo();
1712
+ const attributeInfoHigh = new engine.AttributeInfo();
1713
+ try {
1714
+ let attribute = this.#getDataFromAttribute(
1715
+ client,
1716
+ sceneObjectId,
1717
+ AttributeNames.SPARK_EXTENDED_SPLAT_LOW,
1718
+ attributeInfo
1719
+ );
1720
+ let attributeHigh = null;
1721
+ let useExtSplats = true;
1722
+ if (attribute === null) {
1723
+ attribute = this.#getDataFromAttribute(
1724
+ client,
1725
+ sceneObjectId,
1726
+ AttributeNames.SPARK_PACKED_SPLAT,
1727
+ attributeInfo
1728
+ );
1729
+ useExtSplats = false;
1730
+ } else {
1731
+ attributeHigh = this.#getDataFromAttribute(
1732
+ client,
1733
+ sceneObjectId,
1734
+ AttributeNames.SPARK_EXTENDED_SPLAT_HIGH,
1735
+ attributeInfoHigh
1736
+ );
1737
+ }
1738
+ if (attribute === null) {
1739
+ console.error(
1740
+ `Could not retrieve primary splats attribute for scene object ${sceneObjectId}! skipping scene object`
1741
+ );
1742
+ continue;
1743
+ }
1744
+ const lod = lods.forId(sceneObjectId);
1745
+ if (!lod) {
1746
+ console.warn(
1747
+ `Received modified event for LOD ${sceneObjectId} which does not exist.`
1748
+ );
1749
+ continue;
1750
+ }
1751
+ const worldBounds = this.#retrieveFloatArray(
1752
+ lod.id,
1753
+ 6,
1754
+ client.getWorldBoundingBox.bind(client)
1755
+ );
1756
+ const localBounds = this.#retrieveFloatArray(
1757
+ lod.id,
1758
+ 6,
1759
+ client.getLocalBoundingBox.bind(client)
1760
+ );
1761
+ lod.splats = attribute?.paddedData;
1762
+ lod.splatsExtendedData = attributeHigh?.paddedData ?? null;
1763
+ lod.useExtSplats = useExtSplats;
1764
+ lod.bounds = worldBounds;
1765
+ lod.localBounds = localBounds;
1766
+ lod.lodIndex = lodIndex;
1767
+ lod.paddingCount = (attribute?.paddedData.length - attribute.originalSize) / 4;
1768
+ if (this.useSphericalHarmonics) {
1769
+ this.#addSphericalHarmonicsToLod(scene, sceneObjectId, lod);
1770
+ }
1771
+ const entry = new Change({ type: "modified", lod });
1772
+ this.#changes.push(entry);
1773
+ if (this.#pendingActivations.delete(sceneObjectId)) {
1774
+ this.#changes.push(new Change({ type: "activated", lod }));
1775
+ for (const [, deactLod] of this.#pendingDeactivations) {
1776
+ this.#changes.push(
1777
+ new Change({ type: "deactivated", lod: deactLod })
1778
+ );
1779
+ }
1780
+ this.#pendingDeactivations.clear();
1781
+ }
1782
+ } finally {
1783
+ attributeInfo.delete();
1784
+ attributeInfoHigh.delete();
1785
+ }
1786
+ }
1787
+ }
1788
+ if (this.#changes.some((c) => c.type === "created")) {
1789
+ try {
1790
+ const metadata = new engine.SceneMetadata();
1791
+ client.getSceneMetadata(metadata);
1792
+ this.onColorSpaceDetected(metadata.inputColorSpace === "linear");
1793
+ metadata.delete();
1794
+ } catch (e) {
1795
+ console.warn("Failed to read scene metadata:", e);
1796
+ }
1797
+ }
1798
+ let deferredActivationsThisFrame = false;
1799
+ for (const sceneObjectId of engine.activatedObjectIdsView(
1800
+ this.#changeIds
1801
+ )) {
1802
+ const sceneObjectType = client.getSceneObjectType(sceneObjectId);
1803
+ if (sceneObjectType == Engine.SceneObjectType.GaussianSplats) {
1804
+ const lod = lods.forId(sceneObjectId);
1805
+ if (lod && lod.splats) {
1806
+ const entry = new Change({ type: "activated", lod });
1807
+ this.#changes.push(entry);
1808
+ } else if (lod) {
1809
+ this.#pendingActivations.add(sceneObjectId);
1810
+ deferredActivationsThisFrame = true;
1811
+ }
1812
+ }
1813
+ }
1814
+ for (const sceneObjectId of engine.deactivatedObjectIdsView(
1815
+ this.#changeIds
1816
+ )) {
1817
+ const sceneObjectType = client.getSceneObjectType(sceneObjectId);
1818
+ if (sceneObjectType == Engine.SceneObjectType.GaussianSplats) {
1819
+ this.#pendingActivations.delete(sceneObjectId);
1820
+ if (!createdLodIds.has(sceneObjectId)) {
1821
+ const lod = lods.forId(sceneObjectId);
1822
+ if (lod && lod.splats) {
1823
+ if (deferredActivationsThisFrame) {
1824
+ this.#pendingDeactivations.set(sceneObjectId, lod);
1825
+ } else {
1826
+ const entry = new Change({ type: "deactivated", lod });
1827
+ this.#changes.push(entry);
1828
+ }
1829
+ }
1830
+ }
1831
+ }
1832
+ }
1833
+ }
1834
+ #addSphericalHarmonicsToLod(scene, sceneObjectId, outLod) {
1835
+ const { engine } = this;
1836
+ const { client } = scene;
1837
+ const getAndAssignSh = (packedName, extName, setter) => {
1838
+ const attributeName = outLod.useExtSplats ? extName : packedName;
1839
+ if (client.hasAttribute(sceneObjectId, attributeName)) {
1840
+ const attributeInfo = new engine.AttributeInfo();
1841
+ try {
1842
+ const attribute = this.#getDataFromAttribute(
1843
+ client,
1844
+ sceneObjectId,
1845
+ attributeName,
1846
+ attributeInfo
1847
+ );
1848
+ if (attribute !== null) {
1849
+ setter(attribute.paddedData, attributeInfo.maxValue.x);
1850
+ }
1851
+ } finally {
1852
+ attributeInfo.delete();
1853
+ }
1854
+ }
1855
+ };
1856
+ getAndAssignSh(
1857
+ AttributeNames.SPARK_PACKED_SH1,
1858
+ AttributeNames.SPARK_EXTENDED_SH1,
1859
+ (data, max) => outLod.setSh1(data, max)
1860
+ );
1861
+ getAndAssignSh(
1862
+ AttributeNames.SPARK_PACKED_SH2,
1863
+ AttributeNames.SPARK_EXTENDED_SH2,
1864
+ (data, max) => outLod.setSh2(data, max)
1865
+ );
1866
+ getAndAssignSh(
1867
+ AttributeNames.SPARK_PACKED_SH3,
1868
+ AttributeNames.SPARK_EXTENDED_SH3_A,
1869
+ (data, max) => outLod.setSh3(data, max)
1870
+ );
1871
+ getAndAssignSh(
1872
+ AttributeNames.UNUSED,
1873
+ AttributeNames.SPARK_EXTENDED_SH3_B,
1874
+ (data, _max) => outLod.sh3ExtendedData = data
1875
+ );
1876
+ }
1877
+ update() {
1878
+ this.#hostDriven = true;
1879
+ this._update();
1880
+ let needsRender = false;
1881
+ for (const scene of this.#scenes) {
1882
+ if (scene.client.takeRenderRequired()) {
1883
+ needsRender = true;
1884
+ }
1885
+ }
1886
+ return needsRender || this._computeAdditionalRenderNeeded();
1887
+ }
1888
+ applyChanges(_entries) {
1889
+ }
1890
+ _computeAdditionalRenderNeeded() {
1891
+ return false;
1892
+ }
1893
+ onColorSpaceDetected(_isLinear) {
1894
+ }
1895
+ // prettier-ignore
1896
+ add(scene) {
1897
+ this.#scenes.add(scene);
1898
+ }
1899
+ delete(scene) {
1900
+ this.#scenes.delete(scene);
1901
+ if (scene.miris) scene.close();
1902
+ if (this.#scenes.size === 0 && this.#changeIds !== null) {
1903
+ this.#changeIds.delete();
1904
+ this.#changeIds = null;
1905
+ }
1906
+ }
1907
+ }
1908
+ class Camera {
1909
+ update() {
1910
+ const { engine } = this;
1911
+ const { client } = this.scene;
1912
+ const matrixBuffer = engine.malloc(this.#matrix.length * 4);
1913
+ engine.heapF32.set(Float32Array.from(this.#matrix), matrixBuffer / 4);
1914
+ client.setMainCameraTransform(matrixBuffer);
1915
+ engine.free(matrixBuffer);
1916
+ client.setMainCameraViewFrustum(
1917
+ this.#aspect,
1918
+ this.#fov,
1919
+ this.#near,
1920
+ this.#far
1921
+ );
1922
+ }
1923
+ #aspect;
1924
+ get aspect() {
1925
+ return this.#aspect;
1926
+ }
1927
+ set aspect(aspect) {
1928
+ this.#aspect = aspect;
1929
+ }
1930
+ #fov;
1931
+ get fov() {
1932
+ return this.#fov;
1933
+ }
1934
+ set fov(fov) {
1935
+ this.#fov = fov;
1936
+ }
1937
+ #near;
1938
+ get near() {
1939
+ return this.#near;
1940
+ }
1941
+ set near(near) {
1942
+ this.#near = near;
1943
+ }
1944
+ #far;
1945
+ get far() {
1946
+ return this.#far;
1947
+ }
1948
+ set far(far) {
1949
+ this.#far = far;
1950
+ }
1951
+ #matrix;
1952
+ get matrix() {
1953
+ return this.#matrix;
1954
+ }
1955
+ set matrix(matrix) {
1956
+ this.#matrix = matrix;
1957
+ }
1958
+ constructor({ aspect, fov, near, far, matrix, scene }) {
1959
+ this.#aspect = aspect;
1960
+ this.#fov = fov;
1961
+ this.#near = near;
1962
+ this.#far = far;
1963
+ this.#matrix = matrix;
1964
+ Object.defineProperties(this, {
1965
+ scene: { value: scene },
1966
+ miris: { value: scene.miris },
1967
+ engine: { value: scene.miris.engine }
1968
+ });
1969
+ }
1970
+ }
1971
+ class Client {
1972
+ #viewerKey = null;
1973
+ get viewerKey() {
1974
+ return this.#viewerKey;
1975
+ }
1976
+ set viewerKey(key) {
1977
+ if (key) {
1978
+ this.setAssetViewerKey(key);
1979
+ }
1980
+ this.#viewerKey = key;
1981
+ }
1982
+ constructor({ engine, context }) {
1983
+ Object.defineProperties(this, {
1984
+ engine: { value: engine, enumerable: true },
1985
+ handle: { value: engine.createClient(context), enumerable: true }
1986
+ });
1987
+ }
1988
+ dispose() {
1989
+ if (this.engine.destroyClient(this.handle) !== Engine.AquaStatus.Success) {
1990
+ console.error(`Failed to destroy client with handle '${this.handle}'`);
1991
+ }
1992
+ }
1993
+ addStreamById(...args) {
1994
+ return this.engine.addStreamById(this.handle, ...args);
1995
+ }
1996
+ addPrefetchStreamById(...args) {
1997
+ return this.engine.addPrefetchStreamById(this.handle, ...args);
1998
+ }
1999
+ destroyClient(...args) {
2000
+ return this.engine.destroyClient(this.handle, ...args);
2001
+ }
2002
+ getAssetsAsync(...args) {
2003
+ return this.engine.getAssetsAsync(this.handle, ...args);
2004
+ }
2005
+ getAttribute(...args) {
2006
+ return this.engine.getAttribute(this.handle, ...args);
2007
+ }
2008
+ getDefaultCameraId(...args) {
2009
+ return this.engine.getDefaultCameraId(this.handle, ...args);
2010
+ }
2011
+ getLocalBoundingBox(...args) {
2012
+ return this.engine.getLocalBoundingBox(this.handle, ...args);
2013
+ }
2014
+ getWorldBoundingBox(...args) {
2015
+ return this.engine.getWorldBoundingBox(this.handle, ...args);
2016
+ }
2017
+ getLodIndex(...args) {
2018
+ return this.engine.getLodIndex(this.handle, ...args);
2019
+ }
2020
+ getSceneChanges(...args) {
2021
+ return this.engine.getSceneChanges(this.handle, ...args);
2022
+ }
2023
+ getSceneChangesCounts(...args) {
2024
+ return this.engine.getSceneChangesCounts(this.handle, ...args);
2025
+ }
2026
+ getSceneMetadata(...args) {
2027
+ return this.engine.getSceneMetadata(this.handle, ...args);
2028
+ }
2029
+ getSceneObjectParent(...args) {
2030
+ return this.engine.getSceneObjectParent(this.handle, ...args);
2031
+ }
2032
+ getSceneObjectType(...args) {
2033
+ return this.engine.getSceneObjectType(this.handle, ...args);
2034
+ }
2035
+ getLocalTransform(...args) {
2036
+ return this.engine.getLocalTransform(this.handle, ...args);
2037
+ }
2038
+ getWorldTransform(...args) {
2039
+ return this.engine.getWorldTransform(this.handle, ...args);
2040
+ }
2041
+ hasAttribute(...args) {
2042
+ return this.engine.hasAttribute(this.handle, ...args);
2043
+ }
2044
+ isSceneObjectAncestorOf(...args) {
2045
+ return this.engine.isSceneObjectAncestorOf(this.handle, ...args);
2046
+ }
2047
+ lockScene(...args) {
2048
+ return this.engine.lockScene(this.handle, ...args);
2049
+ }
2050
+ removeStream(...args) {
2051
+ return this.engine.removeStream(this.handle, ...args);
2052
+ }
2053
+ setAssetViewerKey(...args) {
2054
+ return this.engine.setAssetViewerKey(this.handle, ...args);
2055
+ }
2056
+ setClientSpatialFormat(...args) {
2057
+ return this.engine.setClientSpatialFormat(this.handle, ...args);
2058
+ }
2059
+ setRuntimeSettings(...args) {
2060
+ return this.engine.setRuntimeSettings(this.handle, ...args);
2061
+ }
2062
+ setMainCameraTransform(...args) {
2063
+ return this.engine.setMainCameraTransform(this.handle, ...args);
2064
+ }
2065
+ setMainCameraViewFrustum(...args) {
2066
+ return this.engine.setMainCameraViewFrustum(this.handle, ...args);
2067
+ }
2068
+ setSceneObjectTransform(...args) {
2069
+ return this.engine.setSceneObjectTransform(this.handle, ...args);
2070
+ }
2071
+ hasFeature(...args) {
2072
+ return this.engine.hasFeature(this.handle, ...args);
2073
+ }
2074
+ getFeatureVersion(...args) {
2075
+ return this.engine.getFeatureVersion(this.handle, ...args);
2076
+ }
2077
+ getFeatureState(...args) {
2078
+ return this.engine.getFeatureState(this.handle, ...args);
2079
+ }
2080
+ getName(...args) {
2081
+ return this.engine.getName(this.handle, ...args);
2082
+ }
2083
+ setVariantSelection(...args) {
2084
+ return this.engine.setVariantSelection(this.handle, ...args);
2085
+ }
2086
+ takeAttribute(...args) {
2087
+ return this.engine.takeAttribute(this.handle, ...args);
2088
+ }
2089
+ takeEvictedClientSideAttributeIds(...args) {
2090
+ return this.engine.takeEvictedClientSideAttributeIds(this.handle, ...args);
2091
+ }
2092
+ takeRenderRequired(...args) {
2093
+ return this.engine.takeRenderRequired(this.handle, ...args);
2094
+ }
2095
+ unlockScene(...args) {
2096
+ return this.engine.unlockScene(this.handle, ...args);
2097
+ }
2098
+ updateSceneExecution(...args) {
2099
+ return this.engine.updateSceneExecution(this.handle, ...args);
2100
+ }
2101
+ recordFrameTime(...args) {
2102
+ return this.engine.recordFrameTime(this.handle, ...args);
2103
+ }
2104
+ }
2105
+ class Scene extends EventTarget {
2106
+ static #idMap = /* @__PURE__ */ new Map();
2107
+ static #keyMap = /* @__PURE__ */ new Map();
2108
+ // Associated camera
2109
+ #camera = null;
2110
+ get camera() {
2111
+ return this.#camera;
2112
+ }
2113
+ set camera(camera) {
2114
+ this.#camera = camera;
2115
+ }
2116
+ #defaultCameraId = null;
2117
+ static forId(id) {
2118
+ return Scene.#idMap.get(id);
2119
+ }
2120
+ static forKey(key) {
2121
+ return Scene.#keyMap.get(key);
2122
+ }
2123
+ #key;
2124
+ get key() {
2125
+ return this.#key ?? null;
2126
+ }
2127
+ set key(key) {
2128
+ Scene.#keyMap.delete(this.key);
2129
+ if (key || 0 === key) Scene.#keyMap.set(key, this);
2130
+ this.#key = key;
2131
+ }
2132
+ #streams = /* @__PURE__ */ new Set();
2133
+ #streamObjectIdToStream = /* @__PURE__ */ new Map();
2134
+ get viewerKey() {
2135
+ return this.client.viewerKey;
2136
+ }
2137
+ set viewerKey(viewerKey) {
2138
+ if (viewerKey) this.client.viewerKey = viewerKey;
2139
+ }
2140
+ get streams() {
2141
+ return new Set(this.#streams);
2142
+ }
2143
+ #lods = new LodStore();
2144
+ get lods() {
2145
+ return this.#lods;
2146
+ }
2147
+ constructor({ miris, viewerKey }) {
2148
+ super();
2149
+ Object.defineProperties(this, {
2150
+ miris: { value: miris, enumerable: true },
2151
+ engine: { value: miris.engine, enumerable: true },
2152
+ client: {
2153
+ value: new Client({
2154
+ engine: miris.engine,
2155
+ context: miris.sharedContext
2156
+ })
2157
+ }
2158
+ });
2159
+ if (viewerKey) this.viewerKey = viewerKey;
2160
+ const spatialFormat = new this.engine.SpatialFormat();
2161
+ spatialFormat.metersPerUnit = 1;
2162
+ spatialFormat.upAxis = this.engine.UpAxis.Y;
2163
+ spatialFormat.matrixOrder = this.engine.MatrixOrder.ColumnMajor;
2164
+ spatialFormat.handedness = this.engine.Handedness.Right;
2165
+ this.client.setClientSpatialFormat(spatialFormat);
2166
+ spatialFormat.delete();
2167
+ Scene.#idMap.set(this.id, this);
2168
+ miris.add(this);
2169
+ }
2170
+ dispose() {
2171
+ this.close();
2172
+ this.client.dispose();
2173
+ }
2174
+ #updateSceneCameraData() {
2175
+ const defaultCameraId = this.client.getDefaultCameraId();
2176
+ this.#defaultCameraId = defaultCameraId >= 0 ? defaultCameraId : null;
2177
+ }
2178
+ async fetchAssets(tags) {
2179
+ if (!this.viewerKey) {
2180
+ throw new Error("Could not fetch assets because there is no viewer key");
2181
+ }
2182
+ const vector = new this.engine.StringVector();
2183
+ let _tags = [];
2184
+ if (typeof tags === "string") _tags = tags.split(",");
2185
+ else if (tags?.[Symbol.iterator]) _tags = [...tags];
2186
+ for (const tag of _tags) vector.push_back(tag);
2187
+ const _assets = await this.client.getAssetsAsync(vector);
2188
+ const assets = [];
2189
+ const decoder = new TextDecoder();
2190
+ for (const { name, tags: tags2, thumbnailUrl, uuid } of _assets) {
2191
+ const asset = {
2192
+ name,
2193
+ thumbnailUrl,
2194
+ uuid,
2195
+ tags: []
2196
+ };
2197
+ const size = tags2.size();
2198
+ for (let index = 0; index < size; index += 1) {
2199
+ let tag = tags2.get(index);
2200
+ if (tag) {
2201
+ if (typeof tag !== "string") tag = decoder.decode(tag);
2202
+ asset.tags.push(tag);
2203
+ }
2204
+ }
2205
+ assets.push(asset);
2206
+ }
2207
+ vector.delete();
2208
+ return assets;
2209
+ }
2210
+ getDefaultCameraTransform() {
2211
+ if (this.#defaultCameraId === null) return null;
2212
+ return this.miris.getWorldTransform(this.client, this.#defaultCameraId);
2213
+ }
2214
+ add(stream) {
2215
+ this.#streams.add(stream);
2216
+ this.#streamObjectIdToStream.set(stream.id, stream);
2217
+ }
2218
+ getStreamForId(streamObjectId) {
2219
+ return this.#streamObjectIdToStream.get(streamObjectId);
2220
+ }
2221
+ getStreamForDescendentId(descendentObjectId) {
2222
+ for (const [streamObjectId, stream] of this.#streamObjectIdToStream) {
2223
+ if (this.client.isSceneObjectAncestorOf(streamObjectId, descendentObjectId)) {
2224
+ return stream;
2225
+ }
2226
+ }
2227
+ return null;
2228
+ }
2229
+ getModelRootForDescendentId(descendentObjectId) {
2230
+ for (const [, stream] of this.#streamObjectIdToStream) {
2231
+ for (const modelRoot of stream.modelRoots) {
2232
+ if (this.client.isSceneObjectAncestorOf(modelRoot.id, descendentObjectId)) {
2233
+ return modelRoot;
2234
+ }
2235
+ }
2236
+ }
2237
+ return null;
2238
+ }
2239
+ /**
2240
+ * @internal
2241
+ */
2242
+ async _getFeatureMesh(sceneObjectId, feature, attrBase) {
2243
+ if (!this.client.hasFeature(sceneObjectId, feature)) return null;
2244
+ if (this.client.getFeatureState(sceneObjectId, feature) !== Engine.FeatureState.Loaded) return null;
2245
+ const version = this.client.getFeatureVersion(sceneObjectId, feature);
2246
+ if (version === 1) {
2247
+ const attrName = `${attrBase}_v${version}`;
2248
+ const attrInfo = new this.engine.AttributeInfo();
2249
+ try {
2250
+ const status = this.client.getAttribute(
2251
+ sceneObjectId,
2252
+ attrName,
2253
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2254
+ attrInfo.$$.ptr
2255
+ // embind $$.ptr — typed at build time by binding post-processor
2256
+ );
2257
+ if (status !== Engine.AquaStatus.Success) return null;
2258
+ if (attrInfo.clientSideId !== 0n) {
2259
+ return AttributeCache.get(Number(attrInfo.clientSideId));
2260
+ }
2261
+ const wasmView = this.engine.dataPtrView(attrInfo);
2262
+ const buffer = new Uint8Array(wasmView.buffer).subarray(
2263
+ wasmView.byteOffset,
2264
+ wasmView.byteOffset + wasmView.byteLength
2265
+ ).slice().buffer;
2266
+ const cacheId = AttributeCache.add(buffer);
2267
+ const takeStatus = this.client.takeAttribute(
2268
+ sceneObjectId,
2269
+ attrName,
2270
+ BigInt(cacheId)
2271
+ );
2272
+ if (takeStatus !== Engine.AquaStatus.Success) {
2273
+ AttributeCache.remove(cacheId);
2274
+ console.warn(
2275
+ `Failed to take attribute ${attrName} for scene object ${sceneObjectId}: status ${takeStatus}`
2276
+ );
2277
+ return null;
2278
+ }
2279
+ return buffer;
2280
+ } finally {
2281
+ attrInfo.delete();
2282
+ }
2283
+ }
2284
+ console.warn(`getFeatureMesh: unsupported version ${version} for feature ${feature}`);
2285
+ return null;
2286
+ }
2287
+ /**
2288
+ * @internal
2289
+ */
2290
+ async _getDrMap(sceneObjectId) {
2291
+ if (!this.client.hasFeature(sceneObjectId, Engine.Feature.DrMap)) return null;
2292
+ if (this.client.getFeatureState(sceneObjectId, Engine.Feature.DrMap) !== Engine.FeatureState.Loaded)
2293
+ return null;
2294
+ const version = this.client.getFeatureVersion(
2295
+ sceneObjectId,
2296
+ Engine.Feature.DrMap
2297
+ );
2298
+ if (version === 1 || version === 2) {
2299
+ const attrName = `drMap_v${version}`;
2300
+ const attrInfo = new this.engine.AttributeInfo();
2301
+ try {
2302
+ const status = this.client.getAttribute(
2303
+ sceneObjectId,
2304
+ attrName,
2305
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2306
+ attrInfo.$$.ptr
2307
+ // embind $$.ptr — typed at build time by binding post-processor
2308
+ );
2309
+ if (status !== Engine.AquaStatus.Success) return null;
2310
+ if (attrInfo.clientSideId !== 0n) {
2311
+ const cached = AttributeCache.get(Number(attrInfo.clientSideId));
2312
+ return cached !== void 0 ? { bytes: cached, version } : null;
2313
+ }
2314
+ const wasmView = this.engine.dataPtrView(attrInfo);
2315
+ const bytes = new Uint8Array(wasmView.buffer).subarray(
2316
+ wasmView.byteOffset,
2317
+ wasmView.byteOffset + wasmView.byteLength
2318
+ ).slice();
2319
+ const cacheId = AttributeCache.add(bytes);
2320
+ console.log(
2321
+ `_getDrMap is calling takeAttribute for ${attrName} with id ${cacheId}`
2322
+ );
2323
+ const takeStatus = this.client.takeAttribute(
2324
+ sceneObjectId,
2325
+ attrName,
2326
+ BigInt(cacheId)
2327
+ );
2328
+ if (takeStatus !== Engine.AquaStatus.Success) {
2329
+ AttributeCache.remove(cacheId);
2330
+ const status2 = this.client.getAttribute(
2331
+ sceneObjectId,
2332
+ attrName,
2333
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2334
+ attrInfo.$$.ptr
2335
+ // embind $$.ptr — typed at build time by binding post-processor
2336
+ );
2337
+ if (status2 === Engine.AquaStatus.Success && attrInfo.clientSideId !== 0n) {
2338
+ const cached = AttributeCache.get(Number(attrInfo.clientSideId));
2339
+ return cached !== void 0 ? { bytes: cached, version } : null;
2340
+ }
2341
+ console.warn(
2342
+ `getDrMap: failed to take attribute ${attrName} for scene object ${sceneObjectId}: status ${takeStatus}`
2343
+ );
2344
+ return null;
2345
+ }
2346
+ return { bytes, version };
2347
+ } finally {
2348
+ attrInfo.delete();
2349
+ }
2350
+ }
2351
+ console.warn(`getDrMap: unsupported DR map version ${version}`);
2352
+ return null;
2353
+ }
2354
+ /**
2355
+ * @internal
2356
+ */
2357
+ async _onFeatureData(sceneObjectId) {
2358
+ const drMapData = await this._getDrMap(sceneObjectId);
2359
+ if (drMapData !== null) {
2360
+ this.dispatchEvent(
2361
+ new CustomEvent("drmaploaded", { detail: { bytes: drMapData.bytes, version: drMapData.version, sceneObjectId } })
2362
+ );
2363
+ }
2364
+ const reflBuffer = await this._getFeatureMesh(sceneObjectId, Engine.Feature.ReflMesh, "reflMesh");
2365
+ if (reflBuffer !== null) {
2366
+ this.dispatchEvent(new CustomEvent("reflmeshloaded", { detail: { buffer: reflBuffer, sceneObjectId } }));
2367
+ }
2368
+ const glassBuffer = await this._getFeatureMesh(sceneObjectId, Engine.Feature.GlassMesh, "glassMesh");
2369
+ if (glassBuffer !== null) {
2370
+ this.dispatchEvent(new CustomEvent("glassmeshloaded", { detail: { buffer: glassBuffer, sceneObjectId } }));
2371
+ }
2372
+ }
2373
+ /**
2374
+ * @internal
2375
+ */
2376
+ _onSceneLoaded() {
2377
+ this.#updateSceneCameraData();
2378
+ this.dispatchEvent(new Event("sceneloaded"));
2379
+ }
2380
+ delete(stream) {
2381
+ this.#streams.delete(stream);
2382
+ this.#streamObjectIdToStream.delete(stream.id);
2383
+ if (Stream.forId(stream.id)) stream.end();
2384
+ }
2385
+ close() {
2386
+ for (const stream of this.streams) {
2387
+ stream.end();
2388
+ }
2389
+ Scene.#idMap.delete(this.id);
2390
+ Scene.#keyMap.delete(this.key);
2391
+ if (this.miris.scenes.has(this)) this.miris.delete(this);
2392
+ }
2393
+ }
2394
+ export {
2395
+ Camera,
2396
+ Lod,
2397
+ LodStore,
2398
+ Miris,
2399
+ ModelRoot,
2400
+ Scene,
2401
+ Stream
2402
+ };