@miris-inc/core 0.0.8-99f6922 → 0.0.8-9d53d06

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,2126 @@
1
+ //#region packages/core/attributeCache.ts
2
+ var AttributeCache = class {
3
+ static #cache = /* @__PURE__ */ new Map();
4
+ static #nextId = 1;
5
+ static #checkSum = 0;
6
+ static #checkSumModulo = 2 ** 32;
7
+ static #lastReportedCheckSumDifference = 0;
8
+ static #addCheckSum(id) {
9
+ this.#checkSum = (this.#checkSum + id) % this.#checkSumModulo;
10
+ }
11
+ static #removeCheckSum(id) {
12
+ this.#checkSum = (this.#checkSum - id) % this.#checkSumModulo;
13
+ if (this.#checkSum < 0) this.#checkSum += this.#checkSumModulo;
14
+ }
15
+ static getCheckSum() {
16
+ return this.#checkSum;
17
+ }
18
+ static getConsecutiveIds(howMany) {
19
+ const result = this.#nextId;
20
+ this.#nextId += howMany;
21
+ return result;
22
+ }
23
+ static addWithId(data, id) {
24
+ this.#addCheckSum(id);
25
+ this.#cache.set(id, data);
26
+ }
27
+ static add(data) {
28
+ const id = this.#nextId++;
29
+ this.addWithId(data, id);
30
+ return id;
31
+ }
32
+ static get(id) {
33
+ const data = this.#cache.get(id);
34
+ if (data === void 0) throw new Error(`Attribute with id ${id} not found in cache`);
35
+ return data;
36
+ }
37
+ static remove(idOrIds) {
38
+ if (Array.isArray(idOrIds)) for (const id of idOrIds) {
39
+ this.#cache.delete(id);
40
+ this.#removeCheckSum(id);
41
+ }
42
+ else {
43
+ this.#cache.delete(idOrIds);
44
+ this.#removeCheckSum(idOrIds);
45
+ }
46
+ }
47
+ static validateCheckSum(checkSumWasm) {
48
+ if (checkSumWasm != this.getCheckSum()) {
49
+ let difference = checkSumWasm - this.getCheckSum();
50
+ if (difference < 0) difference += this.#checkSumModulo;
51
+ if (difference != this.#lastReportedCheckSumDifference) {
52
+ console.error(`ID checksum mismatch between WASM and TypeScript sides! ${checkSumWasm} ${this.getCheckSum()}`);
53
+ this.#lastReportedCheckSumDifference = difference;
54
+ }
55
+ }
56
+ }
57
+ };
58
+ //#endregion
59
+ //#region \0emscripten-lazy:AquaApi
60
+ var _jsPromise;
61
+ var _wasmPromise;
62
+ var _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);
63
+ function _getExport(m) {
64
+ return m.default || m;
65
+ }
66
+ function _loadModule(url) {
67
+ return import(/* @vite-ignore */ /* webpackIgnore: true */ /* turbopackIgnore: true */ url).then((m) => {
68
+ const f = _getExport(m);
69
+ if (typeof f === "function") return f;
70
+ throw new Error("bad module");
71
+ }).catch(() => fetch(url).then((r) => {
72
+ if (!r.ok) throw new Error(r.status + " " + url);
73
+ return r.text();
74
+ }).then((text) => {
75
+ const blobUrl = URL.createObjectURL(new Blob([text], { type: "text/javascript" }));
76
+ return import(/* @vite-ignore */ /* webpackIgnore: true */ /* turbopackIgnore: true */ blobUrl).then((m) => {
77
+ URL.revokeObjectURL(blobUrl);
78
+ return _getExport(m);
79
+ });
80
+ }));
81
+ }
82
+ function _emscripten_lazy_AquaApi_default(...args) {
83
+ if (!_jsPromise) {
84
+ _wasmPromise = fetch(_wasmUrl).then((r) => {
85
+ if (!r.ok || (r.headers.get("content-type") || "").includes("text/html")) return null;
86
+ return r.arrayBuffer();
87
+ }).catch(() => null);
88
+ _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) => {
89
+ _jsPromise = _wasmPromise = void 0;
90
+ throw e;
91
+ });
92
+ }
93
+ return Promise.all([_jsPromise, _wasmPromise]).then(([factory, wasmBinary]) => {
94
+ if (wasmBinary) {
95
+ const [opts = {}, ...rest] = args;
96
+ return factory({
97
+ ...opts,
98
+ wasmBinary
99
+ }, ...rest);
100
+ }
101
+ return factory(...args);
102
+ });
103
+ }
104
+ //#endregion
105
+ //#region packages/core/engine/factory.ts
106
+ var factory_default = _emscripten_lazy_AquaApi_default;
107
+ //#endregion
108
+ //#region packages/core/engine/threads/thread.ts
109
+ var Thread = class Thread {
110
+ static name = "thread";
111
+ static get Worker() {
112
+ throw new Error("Thread could not be initialized because no Worker was supplied. Do you forget to set `static Worker = Worker` on the child class?");
113
+ }
114
+ constructor({ engine }) {
115
+ Object.defineProperty(this, "engine", {
116
+ value: engine,
117
+ enumerable: true
118
+ });
119
+ Object.defineProperty(this, "ready", {
120
+ enumerable: true,
121
+ value: new Promise((resolve) => {
122
+ this.#resolvers.set(0, async () => {
123
+ this.#pending = false;
124
+ this.#resolvers.delete(0);
125
+ resolve(this);
126
+ });
127
+ })
128
+ });
129
+ this.#worker = new this.constructor.Worker({ name: `decoder-${Thread.#nextWorkerId()}` });
130
+ this.#worker.addEventListener("message", this.#message.bind(this));
131
+ }
132
+ static #latestWorkerId = 0;
133
+ static #nextWorkerId() {
134
+ return this.#latestWorkerId += 1;
135
+ }
136
+ #pending = true;
137
+ get pending() {
138
+ return this.#pending;
139
+ }
140
+ #worker;
141
+ #resolvers = /* @__PURE__ */ new Map();
142
+ get pendingRequests() {
143
+ return this.#resolvers.size;
144
+ }
145
+ get terminated() {
146
+ return !this.#worker;
147
+ }
148
+ #latestProcessId = 0;
149
+ #nextProcessId() {
150
+ return this.#latestProcessId += 1;
151
+ }
152
+ async _execute(action, ...args) {
153
+ if (this.pending) throw new Error(`Unable to execute ${action} because decoder has not yet been initialized`);
154
+ if (!this.#worker) throw new Error(`Unable to execute ${action} because decoder has already been terminated`);
155
+ return new Promise((resolve) => {
156
+ if (!this.#worker) throw new Error(`Unable to execute ${action} because decoder has already been terminated`);
157
+ const id = this.#nextProcessId();
158
+ this.#resolvers.set(id, async (result) => {
159
+ this.#resolvers.delete(id);
160
+ resolve(result);
161
+ });
162
+ const transfer = args.filter((arg) => arg instanceof ArrayBuffer);
163
+ this.#worker.postMessage({
164
+ id,
165
+ action,
166
+ args
167
+ }, transfer);
168
+ });
169
+ }
170
+ #message({ data }) {
171
+ if ("ready" === data) data = {
172
+ id: 0,
173
+ result: void 0
174
+ };
175
+ const { id, result } = data;
176
+ this.#resolvers.get(id)?.(result);
177
+ }
178
+ _postToWorker(data, transfer) {
179
+ this.#worker?.postMessage(data, transfer ?? []);
180
+ }
181
+ terminate() {
182
+ if (!this.#worker) return;
183
+ this.#worker.terminate();
184
+ this.#worker.removeEventListener("message", this.#message);
185
+ this.#worker = null;
186
+ }
187
+ };
188
+ //#endregion
189
+ //#region packages/core/engine/threads/decoder/worker.ts?worker&inline
190
+ var jsContent = "//#region packages/core/engine/threads/utils.ts\nconst 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(actions[action], void 0, [...args, id]);\n self.postMessage({\n id,\n result\n }, ...postMessageArgs);\n });\n return actions;\n};\n//#endregion\n//#region packages/core/attribute.ts\nconst sparkMinSplats = 2048;\nconst sparkAttributeList = {\n sparkPackedSplat: {\n elementsPerSplat: 4,\n discard: false\n },\n extendedPackedSplatLow: {\n elementsPerSplat: 4,\n discard: false\n },\n extendedPackedSplatHigh: {\n elementsPerSplat: 4,\n discard: false\n },\n packedSh1: {\n elementsPerSplat: 2,\n discard: false\n },\n packedSh2: {\n elementsPerSplat: 4,\n discard: false\n },\n packedSh3: {\n elementsPerSplat: 4,\n discard: false\n },\n sh1Extended: {\n elementsPerSplat: 4,\n discard: false\n },\n sh2Extended: {\n elementsPerSplat: 4,\n discard: false\n },\n sh3Extended_0: {\n elementsPerSplat: 4,\n discard: false\n },\n sh3Extended_1: {\n elementsPerSplat: 4,\n discard: false\n },\n sharkEllipsoids: {\n elementsPerSplat: 12,\n discard: false\n },\n sharkSphericalHarmonics: {\n elementsPerSplat: 16,\n discard: false\n }\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) throw new Error(\"attribute name\" + name + \" is unknown\");\n const originalSize = wasmView.length;\n const paddedSize = roundUpToMultipleOf(originalSize, attrib.elementsPerSplat * sparkMinSplats);\n const paddedData = new Uint32Array(paddedSize);\n paddedData.set(wasmView);\n return {\n paddedData,\n originalSizeInUints: originalSize,\n id\n };\n}\n//#endregion\n//#region packages/core/aqua-parser.js\nasync function Li(Le = {}) {\n var $r, l = Le, ze = !1, Br = !0, 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 if (ze || Br) {\n try {\n wr = new URL(\".\", Ne).href;\n } catch {}\n Br && (Tr = (e) => {\n var r = new XMLHttpRequest();\n return r.open(\"GET\", e, !1), 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 = !1, rr, Gr, qr, er, k, A, U, L, T, w, tr, nr, V, Xr, Jr = !1;\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 = !0, 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 = !0, 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 return Ze(e);\n }\n async function rt(e, r) {\n try {\n var t = await Qe(e);\n return await WebAssembly.instantiate(t, r);\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\" });\n return await WebAssembly.instantiateStreaming(n, t);\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 {\n env: Ie,\n wasi_snapshot_preview1: Ie\n };\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, u));\n });\n });\n Fr ??= Ke();\n return r(await et(G, Fr, t));\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 = !0;\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(!0), ar--), r.set_rethrown(!1), 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(!0), e.set_caught(!1), ar++), x = r, x;\n }, vt = (e, r, t) => {\n throw new Pr(e).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: return t ? (n) => k[n] : (n) => A[n];\n case 2: return t ? (n) => U[n >> 1] : (n) => L[n >> 1];\n case 4: return t ? (n) => T[n >> 2] : (n) => w[n >> 2];\n case 8: return t ? (n) => V[n >> 3] : (n) => Xr[n >> 3];\n default: 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, {\n name: r,\n fromWireType: s,\n toWireType: (o, u) => (typeof u == \"number\" && (u = BigInt(u)), u),\n readValueFromPointer: te(r, t, !a),\n destructorFunction: null\n });\n }, yt = (e, r, t, n) => {\n r = C(r), E(e, {\n name: r,\n fromWireType: function(i) {\n return !!i;\n },\n toWireType: function(i, a) {\n return a ? t : n;\n },\n readValueFromPointer: function(i) {\n return this.fromWireType(A[i]);\n },\n destructorFunction: null\n });\n }, mt = (e) => ({\n count: e.count,\n deleteScheduled: e.deleteScheduled,\n preservePointerOnDelete: e.preservePointerOnDelete,\n ptr: e.ptr,\n ptrType: e.ptrType,\n smartPtr: e.smartPtr,\n smartPtrType: e.smartPtrType\n }), Sr = (e) => {\n function r(t) {\n return t.$$.ptrType.registeredClass.name;\n }\n h(r(e) + \" instance already deleted\");\n }, Ar = !1, ne = (e) => {}, 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 e.count.value === 0 && 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 if (!!t.smartPtr) {\n var i = { $$: t };\n Ar.register(r, i, r);\n }\n return r;\n }, ne = (r) => Ar.unregister(r), X(e)), ur = [], $t = () => {\n for (; ur.length;) {\n var e = ur.pop();\n e.$$.deleteScheduled = !1, e.delete();\n }\n }, ae, wt = () => {\n let e = cr.prototype;\n Object.assign(e, {\n isAliasOf(t) {\n if (!(this instanceof cr) || !(t instanceof cr)) return !1;\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 },\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 = !1, t;\n },\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 },\n isDeleted() {\n return !this.$$.ptr;\n },\n deleteLater() {\n return this.$$.ptr || Sr(this), this.$$.deleteScheduled && !this.$$.preservePointerOnDelete && h(\"Object already scheduled for deletion\"), ur.push(this), ur.length === 1 && ae && ae($t), this.$$.deleteScheduled = !0, this;\n }\n });\n const r = Symbol.dispose;\n r && (e[r] = e.delete);\n };\n function cr() {}\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 return lr(r.$$.ptr, t, this.registeredClass);\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: 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 return lr(r.$$.ptr, t, this.registeredClass);\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 return !!r.smartPtrType !== !!r.smartPtr && _r(\"Both smartPtrType and smartPtr must be specified\"), r.count = { value: 1 }, X(Object.create(e, { $$: {\n value: r,\n writable: !0\n } }));\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, {\n ptrType: this.pointeeType,\n ptr: r,\n smartPtrType: this,\n smartPtr: e\n }) : dr(this.registeredClass.instancePrototype, {\n ptrType: this,\n ptr: e\n });\n }\n var s = se[this.registeredClass.getActualType(r)];\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, {\n ptrType: o,\n ptr: u,\n smartPtrType: this,\n smartPtr: e\n }) : dr(o.registeredClass.instancePrototype, {\n ptrType: o,\n ptr: u\n });\n }\n var Ot = () => {\n Object.assign(pr.prototype, {\n getPointee(e) {\n return this.rawGetPointee && (e = this.rawGetPointee(e)), e;\n },\n destructor(e) {\n this.rawDestructor?.(e);\n },\n readValueFromPointer: vr,\n fromWireType: xt\n });\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 = !1) => {\n e = C(e);\n function n() {\n return b(r);\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 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] = !0;\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([\n e,\n r,\n t\n ], 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, !0, !1, !1), Me = new pr(f + \"*\", S, !1, !1, !1), He = new pr(f + \" const*\", S, !1, !0, !1);\n return se[e] = {\n pointerType: Me,\n constPointerType: He\n }, ue(p, F), [\n Bi,\n Me,\n He\n ];\n });\n }, Wr = (e) => {\n for (; e.length;) {\n var r = e.pop();\n e.pop()(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 !0;\n return !1;\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\", _ = [\n \"humanName\",\n \"throwBindingError\",\n \"invoker\",\n \"fn\",\n \"runDestructors\",\n \"fromRetWire\",\n \"toClassParamWire\"\n ];\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 = [\n e,\n h,\n n,\n i,\n Wr,\n _.fromWireType.bind(_),\n d?.toWireType.bind(d)\n ], 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 return fr(e, jt(r, o, c, a)(...p));\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 P = hr(_, [v[0], null].concat(v.slice(1)), 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 = {\n get() {\n I(`Cannot access ${_} due to unbound types`, [t, s]);\n },\n enumerable: !0,\n configurable: !0\n };\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], $ = {\n get() {\n var F = _e(this, f, _ + \" getter\");\n return v.fromWireType(i(a, F));\n },\n enumerable: !0\n };\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 = [\n 0,\n 1,\n ,\n 1,\n null,\n 1,\n !0,\n 1,\n !1,\n 1\n ], Or = (e) => {\n e > 9 && --N[e + 1] === 0 && (N[e] = void 0, de.push(e));\n }, W = {\n toValue: (e) => (e || h(`Cannot use deleted val. handle = ${e}`), N[e]),\n toHandle: (e) => {\n switch (e) {\n case void 0: return 2;\n case null: return 4;\n case !0: return 6;\n case !1: return 8;\n default: {\n const r = de.pop() || N.length;\n return N[r] = e, N[r + 1] = 1, r;\n }\n }\n }\n }, Lt = {\n name: \"emscripten::val\",\n fromWireType: (e) => {\n var r = W.toValue(e);\n return Or(e), r;\n },\n toWireType: (e, r) => W.toHandle(r),\n readValueFromPointer: vr,\n destructorFunction: null\n }, zt = (e) => E(e, Lt), Yt = (e, r, t) => {\n switch (r) {\n case 1: return t ? function(n) {\n return this.fromWireType(k[n]);\n } : function(n) {\n return this.fromWireType(A[n]);\n };\n case 2: 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: return t ? function(n) {\n return this.fromWireType(T[n >> 2]);\n } : function(n) {\n return this.fromWireType(w[n >> 2]);\n };\n default: throw new TypeError(`invalid integer width (${r}): ${e}`);\n }\n }, Nt = (e, r, t, n) => {\n r = C(r);\n function i() {}\n i.values = {}, E(e, {\n name: r,\n constructor: i,\n fromWireType: function(a) {\n return this.constructor.values[a];\n },\n toWireType: (a, s) => s.value,\n readValueFromPointer: Yt(r, t, n),\n destructorFunction: null\n }), 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, {\n value: { value: t },\n 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: return function(t) {\n return this.fromWireType(tr[t >> 2]);\n };\n case 8: return function(t) {\n return this.fromWireType(nr[t >> 3]);\n };\n default: throw new TypeError(`invalid float width (${r}): ${e}`);\n }\n }, Xt = (e, r, t) => {\n r = C(r), E(e, {\n name: r,\n fromWireType: (n) => n,\n toWireType: (n, i) => i,\n readValueFromPointer: qt(r, t),\n destructorFunction: null\n });\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, {\n name: r,\n fromWireType: s,\n toWireType: (u, c) => c,\n readValueFromPointer: te(r, t, n !== 0),\n destructorFunction: null\n });\n }, Zt = (e, r, t) => {\n var i = [\n Int8Array,\n Uint8Array,\n Int16Array,\n Uint16Array,\n Int32Array,\n Uint32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array\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, {\n name: t,\n fromWireType: a,\n readValueFromPointer: a\n }, { ignoreDuplicateRegistrations: !0 });\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 var t = !0;\n E(e, {\n name: r,\n fromWireType(n) {\n var i = w[n >> 2], a = n + 4, s;\n if (t) s = yr(a, i, !0);\n else {\n s = \"\";\n for (var o = 0; o < i; ++o) s += String.fromCharCode(A[a + o]);\n }\n return O(n), s;\n },\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\"), t && s ? a = Ur(i) : a = i.length;\n var o = Mr(4 + a + 1), u = o + 4;\n if (w[o >> 2] = a, s) if (t) M(i, u, a + 1);\n else for (var c = 0; c < a; ++c) {\n var f = i.charCodeAt(c);\n f > 255 && (O(o), h(\"String has UTF-16 code units that do not fit in 8 bits\")), A[u + c] = f;\n }\n else A.set(i, u);\n return n !== null && n.push(O, o), o;\n },\n readValueFromPointer: vr,\n destructorFunction(n) {\n O(n);\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) e.codePointAt(t) > 65535 && t++, r += 4;\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, {\n name: t,\n fromWireType: (s) => {\n var o = w[s >> 2], u = n(s + 4, o * r, !0);\n return O(s), u;\n },\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 },\n readValueFromPointer: vr,\n destructorFunction(s) {\n O(s);\n }\n });\n }, cn = (e, r) => {\n r = C(r), E(e, {\n isVoid: !0,\n name: r,\n fromWireType: () => {},\n toWireType: (t, n) => {}\n });\n }, be = 0, fn = () => {\n Cr = !1, 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: u.getStringOrSymbol = pn, f = \"toValue(handle)[getStringOrSymbol(methodName)]\";\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));\n return ln(fr(`methodCaller<(${a.map((p) => p.name)}) => ${i.name}>`, _));\n }, gn = (e, r, t, n, i) => Vr[e](r, t, n, i), yn = () => W.toHandle({}), mn = (e) => {\n Wr(W.toValue(e)), 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 = /* @__PURE__ */ 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) / 864e5 | 0;\n T[r + 28 >> 2] = i;\n }\n var Fn = (e) => e % 4 === 0 && (e % 100 !== 0 || e % 400 === 0), Cn = [\n 0,\n 31,\n 60,\n 91,\n 121,\n 152,\n 182,\n 213,\n 244,\n 274,\n 305,\n 335\n ], Pn = [\n 0,\n 31,\n 59,\n 90,\n 120,\n 151,\n 181,\n 212,\n 243,\n 273,\n 304,\n 334\n ], kn = (e) => {\n return (Fn(e.getFullYear()) ? Cn : Pn)[e.getMonth()] + e.getDate() - 1;\n };\n function Sn(e, r) {\n e = mr(e);\n var t = /* @__PURE__ */ 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 = !0), 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 return J[e] = {\n id: setTimeout(() => {\n delete J[e], Dn(() => Ee(e, Fe()));\n }, r),\n timeout_ms: r\n }, 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);\n return `UTC${v}${String(Math.floor($ / 60)).padStart(2, \"0\")}${String($ % 60).padStart(2, \"0\")}`;\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(), Un = 1, Vn = (e) => e >= 0 && e <= 3;\n function jn(e, r, t) {\n if (r = mr(r), !Vn(e)) return 28;\n var n;\n if (e === 0) n = On();\n else if (Un) n = Fe();\n else return 52;\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 t = (e - er.buffer.byteLength + 65535) / 65536 | 0;\n try {\n return er.grow(t), Kr(), 1;\n } catch {}\n }, Bn = (e) => {\n var r = A.length;\n e >>>= 0;\n var t = Ce();\n if (e > t) return !1;\n for (var n = 1; n <= 4; n *= 2) {\n var i = r * (1 + .2 / n);\n i = Math.min(i, e + 100663296);\n if (Hn(Math.min(t, Mn(Math.max(e, i), 65536)))) return !0;\n }\n return !1;\n }, br = {}, Ln = () => Lr || \"./this.program\", K = () => {\n if (!K.strings) {\n var r = {\n USER: \"web_user\",\n LOGNAME: \"web_user\",\n PATH: \"/\",\n PWD: \"/\",\n HOME: \"/home/web_user\",\n LANG: (typeof navigator == \"object\" && navigator.language || \"C\").replace(\"-\", \"_\") + \".UTF-8\",\n _: Ln()\n };\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 var a = 2;\n e == 0 ? t = 2 : (e == 1 || e == 2) && (t = 64), i = 1;\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 r = mr(r), 70;\n }\n var jr = [\n null,\n [],\n []\n ], 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 return l[\"_\" + e];\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 = {\n string: (v) => {\n var $ = 0;\n return v != null && v !== 0 && ($ = Zn(v)), $;\n },\n array: (v) => {\n var $ = ke(v.length);\n return Kn(v, $), $;\n }\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\");\n return r !== \"string\" && i && !n ? Pe(e) : (...s) => Se(e, r, t, s, n);\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 = {\n __cxa_begin_catch: st,\n __cxa_end_catch: ot,\n __cxa_find_matching_catch_2: ut,\n __cxa_find_matching_catch_3: ct,\n __cxa_find_matching_catch_4: ft,\n __cxa_rethrow: lt,\n __cxa_throw: vt,\n __cxa_uncaught_exceptions: _t,\n __resumeException: dt,\n _abort_js: pt,\n _embind_register_bigint: gt,\n _embind_register_bool: yt,\n _embind_register_class: Vt,\n _embind_register_class_class_function: It,\n _embind_register_class_constructor: Mt,\n _embind_register_class_function: Ht,\n _embind_register_class_property: Bt,\n _embind_register_emval: zt,\n _embind_register_enum: Nt,\n _embind_register_enum_value: Gt,\n _embind_register_float: Xt,\n _embind_register_function: Jt,\n _embind_register_integer: Kt,\n _embind_register_memory_view: Zt,\n _embind_register_std_string: rn,\n _embind_register_std_wstring: un,\n _embind_register_void: cn,\n _emscripten_runtime_keepalive_clear: fn,\n _emval_create_invoker: hn,\n _emval_decref: Or,\n _emval_invoke: gn,\n _emval_new_object: yn,\n _emval_run_destructors: mn,\n _emval_set_property: bn,\n _gmtime_js: Tn,\n _localtime_js: Sn,\n _setitimer_js: Wn,\n _tzset_js: xn,\n clock_time_get: jn,\n emscripten_get_heap_max: In,\n emscripten_resize_heap: Bn,\n environ_get: zn,\n environ_sizes_get: Yn,\n fd_close: Nn,\n fd_fdstat_get: Gn,\n fd_seek: qn,\n fd_write: Xn,\n invoke_diii: Wi,\n invoke_fi: Ti,\n invoke_fiii: Di,\n invoke_i: Ci,\n invoke_ii: ui,\n invoke_iii: ci,\n invoke_iiii: mi,\n invoke_iiiid: Oi,\n invoke_iiiii: wi,\n invoke_iiiiid: Ai,\n invoke_iiiiii: hi,\n invoke_iiiiiii: Ui,\n invoke_iiiiiiii: Ei,\n invoke_iiiiiiiiii: yi,\n invoke_iiiiiiiiiii: _i,\n invoke_iiiiiiiiiiii: di,\n invoke_iiiiijj: Vi,\n invoke_iiiijj: ji,\n invoke_iiij: Pi,\n invoke_j: ki,\n invoke_jiiii: Ri,\n invoke_v: pi,\n invoke_vi: oi,\n invoke_vii: li,\n invoke_viii: fi,\n invoke_viiii: vi,\n invoke_viiiii: bi,\n invoke_viiiiii: gi,\n invoke_viiiiiii: xi,\n invoke_viiiiiiii: Fi,\n invoke_viiiiiiiiii: Ii,\n invoke_viiiiiiiiiiiiiii: Mi,\n invoke_viiji: Si,\n invoke_viijii: $i,\n llvm_eh_typeid_for: Jn,\n proc_exit: Te\n };\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 = !0, !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}\n//#endregion\n//#region packages/core/engine/threads/decoder/worker.ts\nconst { wasmBinary } = await new Promise((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});\nif (!wasmBinary) throw new Error(\"Decoder worker did not receive WASM binary. The main thread failed to fetch aqua-parser.wasm.\");\nconst module = await Li({ wasmBinary });\nconst controllers = /* @__PURE__ */ new Map();\nconst decoder = {\n get AttributeInfo() {\n return module.AttributeInfo;\n },\n get AquaStatus() {\n return module.AquaStatus;\n },\n get heapU8() {\n return module.HEAPU8;\n },\n get heapU32() {\n return module.HEAPU32;\n },\n get SceneRequestDescriptor() {\n return module.SceneRequestDescriptor;\n },\n get WorkerDataType() {\n return module.WorkerDataType;\n },\n dataPtrView: (attributeInfo) => {\n return module.dataPtrView(attributeInfo);\n },\n free: (...args) => {\n return module.ccall(\"free\", \"number\", [\"number\"], args);\n },\n malloc: (...args) => {\n return module.ccall(\"malloc\", \"number\", [\"number\"], args);\n },\n parseDropFile: (bufferPtr, bufferSize) => {\n return module.parseDropFile(bufferPtr, bufferSize);\n },\n getAttributeFromDropFile: (handle, attributeName, attributeInfo) => {\n return module.getAttributeFromDropFile(handle, attributeName, attributeInfo);\n },\n takeAttributeFromDropFile: (handle, attributeName, clientSideId) => {\n return module.takeAttributeFromDropFile(handle, attributeName, clientSideId);\n },\n flattenDropFile: (handle, outPtr, outSize) => {\n return module.flattenDropFile(handle, outPtr, outSize);\n },\n destroyDropFileHandle: (handle) => {\n return module.destroyDropFileHandle(handle);\n }\n};\ndefineActions({\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.TakeHeapSnapshot !== \"function\") return [{ snapshotJson: null }];\n return [{ snapshotJson: module.TakeHeapSnapshot(topN) }];\n },\n async heapTrackingControl(enabled) {\n if (typeof module.SetHeapTrackingEnabled !== \"function\") return [{ success: false }];\n module.SetHeapTrackingEnabled(enabled);\n return [{ success: true }];\n },\n async heapTrackingReset() {\n if (typeof module.ResetHeapTracking !== \"function\") return [{ success: false }];\n module.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 { free, malloc, parseDropFile, getAttributeFromDropFile, takeAttributeFromDropFile, flattenDropFile, destroyDropFileHandle } = decoder;\n const descriptorSize = descriptorBuffer.byteLength;\n const descriptorPointer = malloc(descriptorSize);\n decoder.heapU8.set(new Uint8Array(descriptorBuffer), descriptorPointer);\n const descriptor = module.SceneRequestDescriptor.deserializeFromBinary(descriptorPointer, descriptorSize);\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({ \"x-cache\": response.headers.get(\"x-cache\") ?? \"\" });\n if (!response.ok) {\n const duration = performance.now() - startTime;\n return [{\n requestIdLow,\n requestIdHigh,\n resultBuffer: /* @__PURE__ */ new ArrayBuffer(0),\n success: false,\n parsed: false,\n error: `HTTP error! status: ${response.status}`,\n dataType: module.WorkerDataType.Raw.value,\n contextPtr,\n attributes: [],\n duration,\n ttfb: duration,\n httpStatus: response.status,\n responseHeadersJson\n }, { transfer: [] }];\n }\n const rtt = performance.now() - startTime;\n const responseBuffer = await response.arrayBuffer();\n const duration = performance.now() - startTime;\n const attributes = [];\n if (!url.split(/[?#]/, 1)[0].endsWith(\".drop\")) return [{\n requestIdLow,\n requestIdHigh,\n resultBuffer: responseBuffer,\n success: true,\n parsed: false,\n error: void 0,\n dataType: module.WorkerDataType.Raw.value,\n contextPtr,\n attributes,\n duration,\n ttfb: rtt,\n httpStatus: response.status,\n responseHeadersJson\n }, { transfer: [responseBuffer] }];\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) throw new Error(\"parseDropFile failed\");\n let index = consecutiveIdsStart;\n for (const [name, info] of Object.entries(sparkAttributeList)) {\n if (info.discard) takeAttributeFromDropFile(handle, name, index);\n else if (getAttributeFromDropFile(handle, name, attributeInfo) === decoder.AquaStatus.Success) {\n const wasmView = decoder.dataPtrView(attributeInfo);\n const splatData = sparkAttributeFromRaw(name, index, wasmView);\n if (takeAttributeFromDropFile(handle, name, index) === decoder.AquaStatus.Success) attributes.push(splatData);\n }\n index++;\n }\n if (flattenDropFile(handle, outputPointerPointer, outputSizePointer) !== decoder.AquaStatus.Success) throw new Error(\"flattenDropFile failed\");\n outputPointer = decoder.heapU32[outputPointerPointer / 4];\n const outputSize = decoder.heapU32[outputSizePointer / 4];\n if (outputPointer === 0) throw new Error(\"flattenDropFile gave nullptr\");\n const resultBuffer = decoder.heapU8.buffer.slice(outputPointer, outputPointer + outputSize);\n const transferList = attributes.map((attr) => attr.paddedData.buffer);\n return [{\n requestIdLow,\n requestIdHigh,\n resultBuffer,\n success: true,\n parsed: true,\n error: void 0,\n dataType: module.WorkerDataType.Drop.value,\n contextPtr,\n attributes,\n duration,\n ttfb: rtt,\n httpStatus: response.status,\n responseHeadersJson\n }, { transfer: [resultBuffer, ...transferList] }];\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 resultBuffer = (/* @__PURE__ */ new Uint8Array()).buffer;\n return [{\n requestIdLow,\n requestIdHigh,\n resultBuffer,\n success: false,\n parsed: false,\n error: errorMessage,\n dataType: module.WorkerDataType.Drop.value,\n contextPtr,\n attributes: void 0,\n duration,\n ttfb: rtt,\n httpStatus: response.status,\n responseHeadersJson\n }, { transfer: [resultBuffer] }];\n } finally {\n destroyDropFileHandle(handle);\n free(responsePointer);\n free(outputPointerPointer);\n free(outputSizePointer);\n if (outputPointer !== 0) free(outputPointer);\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 requestIdLow,\n requestIdHigh,\n resultBuffer: /* @__PURE__ */ new ArrayBuffer(0),\n success: false,\n parsed: false,\n error: isCancelled ? \"Cancelled\" : errorMsg,\n dataType: module.WorkerDataType.Raw.value,\n contextPtr,\n attributes: [],\n duration: 0,\n ttfb: 0,\n httpStatus: 0,\n responseHeadersJson: \"{}\"\n }, { transfer: [] }];\n } finally {\n controllers.delete(key);\n }\n }\n});\n//#endregion\n";
191
+ var blob = typeof self !== "undefined" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", jsContent], { type: "text/javascript;charset=utf-8" });
192
+ function WorkerWrapper(options) {
193
+ let objURL;
194
+ try {
195
+ objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
196
+ if (!objURL) throw "";
197
+ const worker = new Worker(objURL, {
198
+ type: "module",
199
+ name: options?.name
200
+ });
201
+ worker.addEventListener("error", () => {
202
+ (self.URL || self.webkitURL).revokeObjectURL(objURL);
203
+ });
204
+ return worker;
205
+ } catch (e) {
206
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(jsContent), {
207
+ type: "module",
208
+ name: options?.name
209
+ });
210
+ }
211
+ }
212
+ //#endregion
213
+ //#region packages/core/engine/threads/decoder/wasmFetch.ts
214
+ var createSharedWasmFetch = (url) => {
215
+ let cached;
216
+ return async () => {
217
+ cached ??= fetch(url).then((response) => {
218
+ if (!response.ok) throw new Error(`HTTP ${response.status} fetching ${url}`);
219
+ return response.arrayBuffer();
220
+ });
221
+ try {
222
+ return (await cached).slice(0);
223
+ } catch (error) {
224
+ cached = void 0;
225
+ throw error;
226
+ }
227
+ };
228
+ };
229
+ var fetchParserWasm = createSharedWasmFetch(((u) => u.includes("/.vite/") ? u.replace(/\.vite\/[^?#]*/, () => "@miris-inc/core/dist/aqua-parser.wasm") : u)(new URL("aqua-parser.wasm", import.meta.url).href));
230
+ var Decoder = class extends Thread {
231
+ static name = "decoder";
232
+ static Worker = WorkerWrapper;
233
+ constructor(init) {
234
+ super(init);
235
+ this.#sendParserWasm();
236
+ }
237
+ async #sendParserWasm() {
238
+ try {
239
+ const wasmBinary = await fetchParserWasm();
240
+ this._postToWorker({
241
+ type: "wasm-init",
242
+ wasmBinary
243
+ }, [wasmBinary]);
244
+ } catch (e) {
245
+ console.error("Failed to load aqua-parser.wasm for decoder worker", e);
246
+ this._postToWorker({ type: "wasm-init" });
247
+ }
248
+ }
249
+ get AttributeInfo() {
250
+ return this.module.AttributeInfo;
251
+ }
252
+ async heapSnapshot(topN) {
253
+ return this._execute("heapSnapshot", topN);
254
+ }
255
+ async heapTrackingControl(enabled) {
256
+ return this._execute("heapTrackingControl", enabled);
257
+ }
258
+ async heapTrackingReset() {
259
+ return this._execute("heapTrackingReset");
260
+ }
261
+ async cancel(requestIdLow, requestIdHigh) {
262
+ await this.ready;
263
+ this._execute("cancel", requestIdLow, requestIdHigh).catch(() => {});
264
+ }
265
+ async decode(...args) {
266
+ const { requestIdLow, requestIdHigh, resultBuffer, success, dataType, contextPtr, attributes, duration, ttfb, httpStatus, responseHeadersJson } = await this._execute("decode", ...args);
267
+ if (attributes !== void 0) for (const { paddedData, originalSizeInUints, id } of attributes) AttributeCache.addWithId({
268
+ paddedData,
269
+ originalSizeInUints
270
+ }, id);
271
+ const { engine } = this;
272
+ const bufferSize = resultBuffer.byteLength;
273
+ const bufferPointer = engine.malloc(bufferSize);
274
+ engine.heapU8.set(new Uint8Array(resultBuffer), bufferPointer);
275
+ engine.onWorkerResult(requestIdLow, requestIdHigh, bufferPointer, bufferSize, httpStatus, duration, ttfb, success, dataType, "", responseHeadersJson, contextPtr);
276
+ }
277
+ };
278
+ //#endregion
279
+ //#region packages/core/engine/index.ts
280
+ /**
281
+ * The main Aqua wrapper.
282
+ *
283
+ * @remarks
284
+ * The engine is asynchronously initialized, meaning synchronous operations may
285
+ * fail if is not ready. To ensure the engine is ready, await `engine.ready`
286
+ * or check `engine.pending`.
287
+ */
288
+ var Engine = class Engine {
289
+ static AquaStatus = {
290
+ Success: 0,
291
+ Failure: 1
292
+ };
293
+ static SceneObjectType = {
294
+ ModelRoot: 0,
295
+ SceneObject: 1,
296
+ StreamObject: 2,
297
+ GaussianSplats: 3,
298
+ PointsObject: 4,
299
+ Camera: 5,
300
+ LodOctree: 6,
301
+ VariantSetCollection: 7,
302
+ VariantSet: 8,
303
+ VariantSetOption: 9
304
+ };
305
+ static Feature = {
306
+ DrMap: 0,
307
+ ReflMesh: 1,
308
+ GlassMesh: 2
309
+ };
310
+ static FeatureState = {
311
+ NotLoaded: 0,
312
+ Pending: 1,
313
+ Loaded: 2,
314
+ Failed: 3
315
+ };
316
+ #module;
317
+ get module() {
318
+ if (!this.#module) throw new Error("Engine has not yet been initialized. Did you forget to `await engine.ready()?`");
319
+ return this.#module;
320
+ }
321
+ #decoders = /* @__PURE__ */ new Set();
322
+ #requestMap = /* @__PURE__ */ new Map();
323
+ #noJwt = new URL(location.href).searchParams.has("nojwt");
324
+ constructor(moduleOptions = {}) {
325
+ Object.defineProperty(this, "pending", {
326
+ value: true,
327
+ configurable: true,
328
+ enumerable: true
329
+ });
330
+ Object.defineProperty(this, "ready", {
331
+ enumerable: true,
332
+ value: this.#initialize(moduleOptions)
333
+ });
334
+ }
335
+ async #initialize(moduleOptions) {
336
+ this.#module = await factory_default({
337
+ createDeserializeWorker: this.createDeserializeWorker.bind(this),
338
+ submitToWorker: this.submitToWorker.bind(this),
339
+ cancelRequest: this.cancelRequest.bind(this),
340
+ terminateWorker: this.terminateWorker.bind(this),
341
+ workerUrl: "aqua-parser",
342
+ ...moduleOptions,
343
+ preRun: [(mod) => Object.assign(mod.ENV, Engine.#env())]
344
+ });
345
+ Object.defineProperty(this, "pending", {
346
+ value: false,
347
+ configurable: false
348
+ });
349
+ return this;
350
+ }
351
+ get AttributeInfo() {
352
+ return this.module.AttributeInfo;
353
+ }
354
+ get Handedness() {
355
+ return this.module.Handedness;
356
+ }
357
+ get heapF32() {
358
+ return this.module.HEAPF32;
359
+ }
360
+ get heapU8() {
361
+ return this.module.HEAPU8;
362
+ }
363
+ get MatrixOrder() {
364
+ return this.module.MatrixOrder;
365
+ }
366
+ get SceneChangeIds() {
367
+ return this.module.SceneChangeIds;
368
+ }
369
+ get SceneMetadata() {
370
+ return this.module.SceneMetadata;
371
+ }
372
+ get RuntimeSettings() {
373
+ return this.module.RuntimeSettings;
374
+ }
375
+ get SpatialFormat() {
376
+ return this.module.SpatialFormat;
377
+ }
378
+ get StringVector() {
379
+ return this.module.StringVector;
380
+ }
381
+ get UpAxis() {
382
+ return this.module.UpAxis;
383
+ }
384
+ activatedObjectIdsView(...args) {
385
+ return this.module.activatedObjectIdsView(...args);
386
+ }
387
+ addStreamById(...args) {
388
+ return this.module.ccall("AddStreamById", "number", [
389
+ "number",
390
+ "string",
391
+ "string",
392
+ "number"
393
+ ], args);
394
+ }
395
+ allocateSceneChangesArrays(...args) {
396
+ return this.module.AllocateSceneChangesArrays(...args);
397
+ }
398
+ createContext(...args) {
399
+ return this.module.ccall("CreateAquaContext", "number", [], args);
400
+ }
401
+ destroyContext(...args) {
402
+ return this.module.ccall("DestroyAquaContext", "number", ["number"], args);
403
+ }
404
+ createClient(context, ...args) {
405
+ if (context) return this.module.ccall("CreateClientForContext", "number", ["number"], [context, ...args]);
406
+ return this.module.ccall("CreateClient", "number", [], args);
407
+ }
408
+ createdObjectIdsView(...args) {
409
+ return this.module.createdObjectIdsView(...args);
410
+ }
411
+ deletedObjectIdsView(...args) {
412
+ return this.module.deletedObjectIdsView(...args);
413
+ }
414
+ dataPtrView(...args) {
415
+ return this.module.dataPtrView(...args);
416
+ }
417
+ deactivatedObjectIdsView(...args) {
418
+ return this.module.deactivatedObjectIdsView(...args);
419
+ }
420
+ remaskedObjectIdsView(...args) {
421
+ return this.module.remaskedObjectIdsView(...args);
422
+ }
423
+ getDrawnOctantMask(...args) {
424
+ return this.module.GetDrawnOctantMask(...args);
425
+ }
426
+ destroyClient(...args) {
427
+ return this.module.ccall("DestroyClient", "number", ["number"], args);
428
+ }
429
+ free(...args) {
430
+ return this.module.ccall("free", "number", ["number"], args);
431
+ }
432
+ getAssetsAsync(...args) {
433
+ return this.module.GetAssetsAsync(...args);
434
+ }
435
+ getAttribute(...args) {
436
+ return this.module.ccall("GetAttribute", "number", [
437
+ "number",
438
+ "number",
439
+ "string",
440
+ "number"
441
+ ], args);
442
+ }
443
+ getDefaultCameraId(...args) {
444
+ return this.module.ccall("GetDefaultCameraId", "number", ["number"], args);
445
+ }
446
+ getViewingVolumeId(...args) {
447
+ return this.module.ccall("GetViewingVolumeId", "number", ["number"], args);
448
+ }
449
+ getLocalBoundingBox(...args) {
450
+ return this.module.ccall("GetLocalBoundingBox", "number", [
451
+ "number",
452
+ "number",
453
+ "number"
454
+ ], args);
455
+ }
456
+ getWorldBoundingBox(...args) {
457
+ return this.module.ccall("GetWorldBoundingBox", "number", [
458
+ "number",
459
+ "number",
460
+ "number"
461
+ ], args);
462
+ }
463
+ getLodIndex(...args) {
464
+ return this.module.ccall("GetLodIndex", "number", ["number", "number"], args);
465
+ }
466
+ getSceneChanges(...args) {
467
+ return this.module.GetSceneChanges(...args);
468
+ }
469
+ getSceneChangesCounts(...args) {
470
+ return this.module.GetSceneChangesCounts(...args);
471
+ }
472
+ getSceneMetadata(...args) {
473
+ return this.module.GetSceneMetadata(...args).value;
474
+ }
475
+ getSceneObjectParent(...args) {
476
+ return this.module.ccall("GetSceneObjectParent", "number", ["number", "number"], args);
477
+ }
478
+ getSceneObjectType(...args) {
479
+ return this.module.ccall("GetSceneObjectType", "number", ["number", "number"], args);
480
+ }
481
+ getLocalTransform(...args) {
482
+ return this.module.ccall("MirisGetLocalTransform", "number", [
483
+ "number",
484
+ "number",
485
+ "number"
486
+ ], args);
487
+ }
488
+ getWorldTransform(...args) {
489
+ return this.module.ccall("MirisGetWorldTransform", "number", [
490
+ "number",
491
+ "number",
492
+ "number"
493
+ ], args);
494
+ }
495
+ hasAttribute(...args) {
496
+ return this.module.ccall("HasAttribute", "boolean", [
497
+ "number",
498
+ "number",
499
+ "string"
500
+ ], args);
501
+ }
502
+ isSceneObjectAncestorOf(...args) {
503
+ return this.module.ccall("IsSceneObjectAncestorOf", "boolean", [
504
+ "number",
505
+ "number",
506
+ "number"
507
+ ], args);
508
+ }
509
+ lockScene(...args) {
510
+ return this.module.ccall("LockScene", "number", ["number"], args);
511
+ }
512
+ malloc(...args) {
513
+ return this.module.ccall("malloc", "number", ["number"], args);
514
+ }
515
+ modifiedObjectIdsView(...args) {
516
+ return this.module.modifiedObjectIdsView(...args);
517
+ }
518
+ onWorkerResult(...args) {
519
+ const requestKey = `${args[1]}-${args[0]}`;
520
+ this.#requestMap.delete(requestKey);
521
+ return this.module.ccall("onWorkerResult", null, [
522
+ "number",
523
+ "number",
524
+ "number",
525
+ "number",
526
+ "number",
527
+ "number",
528
+ "number",
529
+ "number",
530
+ "number",
531
+ "string",
532
+ "string",
533
+ "number"
534
+ ], args);
535
+ }
536
+ removeStream(...args) {
537
+ return this.module.ccall("RemoveStream", "boolean", ["pointer", "number"], args);
538
+ }
539
+ setAssetViewerKey(...args) {
540
+ return this.module.ccall("SetAssetViewerKey", "number", ["number", "string"], args);
541
+ }
542
+ setClientSpatialFormat(...args) {
543
+ return this.module.SetClientSpatialFormat(...args).value;
544
+ }
545
+ setRuntimeSettings(...args) {
546
+ return this.module.SetRuntimeSettings(...args).value;
547
+ }
548
+ setMainCameraTransform(...args) {
549
+ return this.module.ccall("SetMainCameraTransform", "number", ["number", "number"], args);
550
+ }
551
+ setMainCameraViewFrustum(...args) {
552
+ return this.module.ccall("SetMainCameraViewFrustum", "number", [
553
+ "number",
554
+ "number",
555
+ "number",
556
+ "number",
557
+ "number"
558
+ ], args);
559
+ }
560
+ setMaxCacheSize(...args) {
561
+ return this.module.setMaxCacheSize(...args);
562
+ }
563
+ setSceneObjectTransform(...args) {
564
+ return this.module.ccall("SetSceneObjectTransform", "number", [
565
+ "number",
566
+ "number",
567
+ "number"
568
+ ], args);
569
+ }
570
+ hasFeature(...args) {
571
+ return this.module.HasFeature(...args);
572
+ }
573
+ getFeatureVersion(...args) {
574
+ return this.module.GetFeatureVersion(...args);
575
+ }
576
+ getFeatureState(...args) {
577
+ return this.module.GetFeatureState(...args);
578
+ }
579
+ getName(...args) {
580
+ return this.module.GetName(...args);
581
+ }
582
+ setVariantSelection(...args) {
583
+ return this.module.ccall("SetVariantSelection", "number", ["number", "number"], args);
584
+ }
585
+ takeAttribute(...args) {
586
+ return this.module.ccall("TakeAttribute", "number", [
587
+ "number",
588
+ "number",
589
+ "string",
590
+ "bigint"
591
+ ], args);
592
+ }
593
+ takeEvictedClientSideAttributeIds(...args) {
594
+ return this.module.TakeEvictedClientSideAttributeIds(...args);
595
+ }
596
+ getActiveClientSideIdsCheckSum() {
597
+ return this.module.GetActiveClientSideIdsCheckSum();
598
+ }
599
+ unlockScene(...args) {
600
+ return this.module.ccall("UnlockScene", "number", ["number"], args);
601
+ }
602
+ updateSceneExecution(...args) {
603
+ return this.module.ccall("UpdateSceneExecution", "number", ["number"], args);
604
+ }
605
+ recordFrameTime(...args) {
606
+ return this.module.ccall("RecordFrameTime", "number", ["number", "number"], args);
607
+ }
608
+ takeRenderRequired(...args) {
609
+ return this.module.TakeRenderRequired(...args);
610
+ }
611
+ createDeserializeWorker(_url, _workerUrl, poolSize) {
612
+ for (let index = 1; index < poolSize; index += 1) this.#decoders.add(new Decoder({ engine: this }));
613
+ return true;
614
+ }
615
+ cancelRequest(requestIdLow, requestIdHigh) {
616
+ const requestKey = `${requestIdHigh}-${requestIdLow}`;
617
+ const decoder = this.#requestMap.get(requestKey);
618
+ if (decoder) {
619
+ decoder.cancel(requestIdLow, requestIdHigh);
620
+ this.#requestMap.delete(requestKey);
621
+ }
622
+ return true;
623
+ }
624
+ submitToWorker(requestIdLow, requestIdHigh, descriptorBuffer, contextPtr) {
625
+ const decoder = [...this.#decoders.values()].reduce((previous, current) => {
626
+ if (!previous) return current;
627
+ return current.pendingRequests < previous.pendingRequests ? current : previous;
628
+ });
629
+ const requestKey = `${requestIdHigh}-${requestIdLow}`;
630
+ this.#requestMap.set(requestKey, decoder);
631
+ const firstId = AttributeCache.getConsecutiveIds(Object.keys(sparkAttributeList).length);
632
+ decoder.ready.then(() => decoder.decode(requestIdLow, requestIdHigh, descriptorBuffer, contextPtr, firstId, this.#noJwt));
633
+ return true;
634
+ }
635
+ terminateWorker() {
636
+ for (const decoder of this.#decoders) decoder.terminate();
637
+ this.#decoders.clear();
638
+ }
639
+ async requestWorkerHeapSnapshots(topN) {
640
+ const decoders = [...this.#decoders];
641
+ return (await Promise.allSettled(decoders.map((d) => d.ready.then(() => {
642
+ let timer;
643
+ const timeout = new Promise((resolve) => {
644
+ timer = setTimeout(() => resolve(null), 5e3);
645
+ });
646
+ return Promise.race([d.heapSnapshot(topN).then((r) => r.snapshotJson), timeout]).finally(() => clearTimeout(timer));
647
+ })))).map((r) => r.status === "fulfilled" ? r.value : null);
648
+ }
649
+ async setWorkerHeapTrackingEnabled(enabled) {
650
+ await Promise.allSettled([...this.#decoders].map((d) => d.ready.then(() => d.heapTrackingControl(enabled))));
651
+ }
652
+ async resetWorkerHeapTracking() {
653
+ await Promise.allSettled([...this.#decoders].map((d) => d.ready.then(() => d.heapTrackingReset())));
654
+ }
655
+ static #env() {
656
+ return {
657
+ AQUA_USE_SINGLETON_NETWORK_TRANSPORT: "true",
658
+ AQUA_SERVER_BASE_URL: "https://app.miris.com/viewer/v1"
659
+ };
660
+ }
661
+ };
662
+ //#endregion
663
+ //#region packages/core/attribute.ts
664
+ var sparkMinSplats = 2048;
665
+ var sparkAttributeList = {
666
+ sparkPackedSplat: {
667
+ elementsPerSplat: 4,
668
+ discard: false
669
+ },
670
+ extendedPackedSplatLow: {
671
+ elementsPerSplat: 4,
672
+ discard: false
673
+ },
674
+ extendedPackedSplatHigh: {
675
+ elementsPerSplat: 4,
676
+ discard: false
677
+ },
678
+ packedSh1: {
679
+ elementsPerSplat: 2,
680
+ discard: false
681
+ },
682
+ packedSh2: {
683
+ elementsPerSplat: 4,
684
+ discard: false
685
+ },
686
+ packedSh3: {
687
+ elementsPerSplat: 4,
688
+ discard: false
689
+ },
690
+ sh1Extended: {
691
+ elementsPerSplat: 4,
692
+ discard: false
693
+ },
694
+ sh2Extended: {
695
+ elementsPerSplat: 4,
696
+ discard: false
697
+ },
698
+ sh3Extended_0: {
699
+ elementsPerSplat: 4,
700
+ discard: false
701
+ },
702
+ sh3Extended_1: {
703
+ elementsPerSplat: 4,
704
+ discard: false
705
+ },
706
+ sharkEllipsoids: {
707
+ elementsPerSplat: 12,
708
+ discard: false
709
+ },
710
+ sharkSphericalHarmonics: {
711
+ elementsPerSplat: 16,
712
+ discard: false
713
+ }
714
+ };
715
+ function roundUpToMultipleOf(a, multiple) {
716
+ return Math.ceil(a / multiple) * multiple;
717
+ }
718
+ function sparkAttributeFromRaw(name, id, wasmView) {
719
+ const attrib = sparkAttributeList[name];
720
+ if (attrib === void 0) throw new Error("attribute name" + name + " is unknown");
721
+ const originalSize = wasmView.length;
722
+ const paddedSize = roundUpToMultipleOf(originalSize, attrib.elementsPerSplat * sparkMinSplats);
723
+ const paddedData = new Uint32Array(paddedSize);
724
+ paddedData.set(wasmView);
725
+ return {
726
+ paddedData,
727
+ originalSizeInUints: originalSize,
728
+ id
729
+ };
730
+ }
731
+ var AttributeNames = class {
732
+ static SPARK_PACKED_SPLAT = "sparkPackedSplat";
733
+ static SPARK_EXTENDED_SPLAT_LOW = "extendedPackedSplatLow";
734
+ static SPARK_EXTENDED_SPLAT_HIGH = "extendedPackedSplatHigh";
735
+ static SPARK_PACKED_SH1 = "packedSh1";
736
+ static SPARK_PACKED_SH2 = "packedSh2";
737
+ static SPARK_PACKED_SH3 = "packedSh3";
738
+ static SPARK_EXTENDED_SH1 = "sh1Extended";
739
+ static SPARK_EXTENDED_SH2 = "sh2Extended";
740
+ static SPARK_EXTENDED_SH3_A = "sh3Extended_0";
741
+ static SPARK_EXTENDED_SH3_B = "sh3Extended_1";
742
+ static UNUSED = "unused";
743
+ static SHARK_ELLIPSOIDS = "sharkEllipsoids";
744
+ static SHARK_SPHERICAL_HARMONICS = "sharkSphericalHarmonics";
745
+ static OCTANT_OFFSETS = "childOctantOffsets";
746
+ };
747
+ function retrieveFloatArray(engine, objectId, arraySize, fn) {
748
+ const arrayPtr = engine.malloc(arraySize * 4);
749
+ fn(objectId, arrayPtr);
750
+ const floatArray = engine.heapF32.subarray(arrayPtr >> 2, (arrayPtr >> 2) + arraySize).slice();
751
+ engine.free(arrayPtr);
752
+ return floatArray;
753
+ }
754
+ /**
755
+ * Reads a small raw uint32 attribute (e.g. sparse-octant childOctantOffsets) directly, without the
756
+ * spark per-splat padding applied by getDataFromAttribute. Returns a copy of the values, or null if
757
+ * the attribute is absent or empty. Ownership stays with the C++ client (no takeAttribute).
758
+ */
759
+ function getRawUint32Attribute(engine, client, sceneObjectId, attributeName) {
760
+ if (!client.hasAttribute(sceneObjectId, attributeName)) return null;
761
+ const attributeInfo = new engine.AttributeInfo();
762
+ try {
763
+ const { ptr } = attributeInfo.$$;
764
+ if (client.getAttribute(sceneObjectId, attributeName, ptr) !== Engine.AquaStatus.Success) return null;
765
+ const view = engine.dataPtrView(attributeInfo);
766
+ if (view.length === 0) return null;
767
+ return view.slice();
768
+ } finally {
769
+ attributeInfo.delete();
770
+ }
771
+ }
772
+ function getDataFromAttribute(engine, client, sceneObjectId, attributeName, outAttributeInfo) {
773
+ if (!client.hasAttribute(sceneObjectId, attributeName)) return null;
774
+ const { ptr } = outAttributeInfo.$$;
775
+ const status = client.getAttribute(sceneObjectId, attributeName, ptr);
776
+ if (status !== Engine.AquaStatus.Success) {
777
+ console.warn(`GetAttribute failed for object id ${sceneObjectId} and attribute name ${attributeName}: status ${status}`);
778
+ return null;
779
+ }
780
+ let paddedData;
781
+ let originalSizeInUints;
782
+ if (outAttributeInfo.clientSideId != 0n) ({paddedData: paddedData, originalSizeInUints: originalSizeInUints} = AttributeCache.get(Number(outAttributeInfo.clientSideId)));
783
+ else {
784
+ const result = sparkAttributeFromRaw(attributeName, 0, engine.dataPtrView(outAttributeInfo));
785
+ paddedData = result.paddedData;
786
+ originalSizeInUints = result.originalSizeInUints;
787
+ console.log(`retrieved a attribute ${attributeName} with size ${result.originalSizeInUints} for chunk ${sceneObjectId}`);
788
+ const myCacheEntry = AttributeCache.add({
789
+ paddedData: result.paddedData,
790
+ originalSizeInUints: result.originalSizeInUints
791
+ });
792
+ const takeStatus = client.takeAttribute(sceneObjectId, attributeName, BigInt(myCacheEntry));
793
+ if (takeStatus !== Engine.AquaStatus.Success) {
794
+ AttributeCache.remove(myCacheEntry);
795
+ console.warn(`Failed to take attribute ${attributeName} for scene object ${sceneObjectId}: status ${takeStatus}`);
796
+ return null;
797
+ }
798
+ }
799
+ return {
800
+ paddedData,
801
+ originalSizeInUints
802
+ };
803
+ }
804
+ //#endregion
805
+ //#region packages/core/lod.ts
806
+ var LodStore = class {
807
+ #keyMap = /* @__PURE__ */ new Map();
808
+ #idMap = /* @__PURE__ */ new Map();
809
+ forKey(key) {
810
+ return this.#keyMap.get(key);
811
+ }
812
+ forId(id) {
813
+ return this.#idMap.get(id);
814
+ }
815
+ setKey(key, lod) {
816
+ this.#keyMap.set(key, lod);
817
+ }
818
+ setId(id, lod) {
819
+ return this.#idMap.set(id, lod);
820
+ }
821
+ delete(lod) {
822
+ this.#keyMap.delete(lod.key);
823
+ this.#idMap.delete(lod.id);
824
+ }
825
+ deleteKey(key) {
826
+ this.#keyMap.delete(key);
827
+ }
828
+ deleteId(id) {
829
+ this.#idMap.delete(id);
830
+ }
831
+ };
832
+ var Lod = class {
833
+ #client;
834
+ #key;
835
+ #cachedWorldBounds = null;
836
+ #localBounds = null;
837
+ #transform = null;
838
+ #lodIndex = null;
839
+ #paddingSplatsCount = 0;
840
+ #drawnOctantMask = 255;
841
+ #octantOffsets = null;
842
+ #octantOffsetsRead = false;
843
+ get key() {
844
+ return this.#key ?? null;
845
+ }
846
+ set key(key) {
847
+ this.store.deleteKey(this.key);
848
+ if (key || 0 === key) this.store.setKey(key, this);
849
+ this.#key = key;
850
+ }
851
+ set bounds(bounds) {
852
+ this.#cachedWorldBounds = bounds;
853
+ }
854
+ /**
855
+ * Retrieves the cached world bounds of this object
856
+ *
857
+ * @deprecated Retrieve the local bounds and transform as needed
858
+ */
859
+ get bounds() {
860
+ console.warn("`bounds` is deprecated, use `localBounds` instead");
861
+ return this.#cachedWorldBounds;
862
+ }
863
+ /**
864
+ * Sets the local bounds of this lod
865
+ */
866
+ set localBounds(bounds) {
867
+ this.#localBounds = bounds;
868
+ }
869
+ /**
870
+ * Retrieves the local bounds of this lod
871
+ */
872
+ get localBounds() {
873
+ return this.#localBounds;
874
+ }
875
+ set lodIndex(index) {
876
+ this.#lodIndex = index;
877
+ }
878
+ get lodIndex() {
879
+ return this.#lodIndex;
880
+ }
881
+ set paddingSplatsCount(count) {
882
+ this.#paddingSplatsCount = count;
883
+ }
884
+ get paddingSplatsCount() {
885
+ return this.#paddingSplatsCount;
886
+ }
887
+ set transform(transform) {
888
+ this.#transform = transform;
889
+ }
890
+ get transform() {
891
+ return this.#transform;
892
+ }
893
+ get _drawnOctantMask() {
894
+ return this.#drawnOctantMask;
895
+ }
896
+ set _drawnOctantMask(mask) {
897
+ this.#drawnOctantMask = mask;
898
+ }
899
+ get _octantOffsets() {
900
+ return this.#octantOffsets;
901
+ }
902
+ get _hasOctantOffsets() {
903
+ return this.#octantOffsets !== null;
904
+ }
905
+ _readOctantOffsets(engine) {
906
+ if (this.#octantOffsetsRead) return;
907
+ this.#octantOffsetsRead = true;
908
+ const offsets = getRawUint32Attribute(engine, this.#client, this.id, AttributeNames.OCTANT_OFFSETS);
909
+ if (offsets && offsets.length === 7) this.#octantOffsets = offsets;
910
+ }
911
+ hasAttribute(attributeName) {
912
+ return this.#client.hasAttribute(this.id, attributeName);
913
+ }
914
+ getDataFromAttribute(engine, attributeName, attributeInfo) {
915
+ return getDataFromAttribute(engine, this.#client, this.id, attributeName, attributeInfo);
916
+ }
917
+ dispose() {
918
+ const key = this.#key;
919
+ key?.dispose?.();
920
+ this.store.delete(this);
921
+ this.#key = null;
922
+ key?.dispose?.();
923
+ this.#cachedWorldBounds = null;
924
+ this.#localBounds = null;
925
+ this.#transform = null;
926
+ this.modelRoot?.lods?.delete(this);
927
+ }
928
+ constructor({ id, modelRoot, lodStore, client }) {
929
+ Object.defineProperties(this, {
930
+ id: { value: id },
931
+ modelRoot: { value: modelRoot },
932
+ store: { value: lodStore }
933
+ });
934
+ this.#client = client;
935
+ lodStore.setId(id, this);
936
+ modelRoot.add(this);
937
+ }
938
+ };
939
+ //#endregion
940
+ //#region packages/core/change.ts
941
+ var Change = class {
942
+ constructor({ type, lod }) {
943
+ Object.defineProperties(this, {
944
+ type: { value: type },
945
+ lod: { value: lod }
946
+ });
947
+ }
948
+ };
949
+ //#endregion
950
+ //#region packages/core/modelRoot.ts
951
+ var ModelRoot = class ModelRoot {
952
+ static #keyMap = /* @__PURE__ */ new Map();
953
+ static #idMap = /* @__PURE__ */ new Map();
954
+ static forKey(key) {
955
+ return this.#keyMap.get(key);
956
+ }
957
+ static forId(id) {
958
+ return this.#idMap.get(id);
959
+ }
960
+ #key;
961
+ get key() {
962
+ return this.#key ?? null;
963
+ }
964
+ set key(key) {
965
+ ModelRoot.#keyMap.delete(this.key);
966
+ if (key || 0 === key) ModelRoot.#keyMap.set(key, this);
967
+ this.#key = key;
968
+ }
969
+ #lods = /* @__PURE__ */ new Set();
970
+ get lods() {
971
+ return this.#lods;
972
+ }
973
+ #transform;
974
+ set transform(transform) {
975
+ this.#transform = transform;
976
+ }
977
+ get transform() {
978
+ return this.#transform;
979
+ }
980
+ constructor({ id, stream }) {
981
+ Object.defineProperties(this, {
982
+ id: { value: id },
983
+ stream: { value: stream }
984
+ });
985
+ ModelRoot.#idMap.set(id, this);
986
+ stream.add(this);
987
+ }
988
+ add(lod) {
989
+ this.#lods.add(lod);
990
+ }
991
+ dispose() {
992
+ const lods = [...this.#lods];
993
+ this.#lods.clear();
994
+ for (const lod of lods) lod.dispose();
995
+ ModelRoot.#keyMap.delete(this.key);
996
+ ModelRoot.#idMap.delete(this.id);
997
+ this.#key = null;
998
+ }
999
+ };
1000
+ //#endregion
1001
+ //#region packages/core/stream.ts
1002
+ var Stream = class Stream extends EventTarget {
1003
+ static _idMap = /* @__PURE__ */ new Map();
1004
+ static _keyMap = /* @__PURE__ */ new Map();
1005
+ static forId(id) {
1006
+ if (!id) return;
1007
+ return this._idMap.get(id);
1008
+ }
1009
+ static forKey(key) {
1010
+ return this._keyMap.get(key);
1011
+ }
1012
+ #key;
1013
+ #loadedRenderableData = false;
1014
+ #variantHierarchies = {};
1015
+ /**
1016
+ * @internal
1017
+ */
1018
+ _addVariantCollection(hierarchyId) {
1019
+ if (!this.#variantHierarchies[hierarchyId]) this.#variantHierarchies[hierarchyId] = {
1020
+ id: hierarchyId,
1021
+ children: []
1022
+ };
1023
+ }
1024
+ /**
1025
+ * @internal
1026
+ */
1027
+ _findAndAddToVariantSet(parentId, variant) {
1028
+ const addToNode = (node) => {
1029
+ if (!node) return false;
1030
+ if (node.id === parentId) {
1031
+ if (node.children) node.children.push(variant);
1032
+ else if (variant.type === "option") {
1033
+ if (!node.options) node.options = [];
1034
+ node.options.push(variant);
1035
+ } else {
1036
+ if (!node.nestedSets) node.nestedSets = [];
1037
+ node.nestedSets.push(variant);
1038
+ }
1039
+ return true;
1040
+ }
1041
+ if (Array.isArray(node.children)) {
1042
+ for (const child of node.children) if (addToNode(child)) return true;
1043
+ }
1044
+ if (Array.isArray(node.nestedSets)) {
1045
+ for (const nested of node.nestedSets) if (addToNode(nested)) return true;
1046
+ }
1047
+ if (Array.isArray(node.options)) {
1048
+ for (const option of node.options) if (addToNode(option)) return true;
1049
+ }
1050
+ return false;
1051
+ };
1052
+ for (const hierarchy of Object.values(this.#variantHierarchies)) if (addToNode(hierarchy)) return;
1053
+ }
1054
+ /**
1055
+ * @internal
1056
+ */
1057
+ _addVariant(parentId, variant) {
1058
+ this._findAndAddToVariantSet(parentId, variant);
1059
+ }
1060
+ /**
1061
+ * @internal
1062
+ */
1063
+ _exportVariantHierarchies() {
1064
+ return Object.entries(this.#variantHierarchies).map(([hierarchyId, hierarchy]) => ({
1065
+ hierarchyId: Number(hierarchyId),
1066
+ hierarchy
1067
+ }));
1068
+ }
1069
+ /**
1070
+ * @internal
1071
+ */
1072
+ _setVariantSelection(variantId) {
1073
+ this.client.setVariantSelection(variantId);
1074
+ }
1075
+ get key() {
1076
+ return this.#key ?? null;
1077
+ }
1078
+ set key(key) {
1079
+ Stream._keyMap.delete(this.key);
1080
+ if (key || 0 === key) Stream._keyMap.set(key, this);
1081
+ this.#key = key;
1082
+ }
1083
+ #matrix = [
1084
+ 1,
1085
+ 0,
1086
+ 0,
1087
+ 0,
1088
+ 0,
1089
+ 1,
1090
+ 0,
1091
+ 0,
1092
+ 0,
1093
+ 0,
1094
+ 1,
1095
+ 0,
1096
+ 0,
1097
+ 0,
1098
+ 0,
1099
+ 1
1100
+ ];
1101
+ get matrix() {
1102
+ return this.#matrix;
1103
+ }
1104
+ set matrix(matrix) {
1105
+ this.#matrix = matrix;
1106
+ const { engine, client } = this;
1107
+ const matrixBuffer = engine.malloc(this.#matrix.length * 4);
1108
+ engine.heapF32.set(Float32Array.from(this.#matrix), matrixBuffer / 4);
1109
+ client.setSceneObjectTransform(this.id, matrixBuffer);
1110
+ engine.free(matrixBuffer);
1111
+ }
1112
+ #opacity = 1;
1113
+ get opacity() {
1114
+ return this.#opacity;
1115
+ }
1116
+ set opacity(opacity) {
1117
+ this.#opacity = Math.min(1, Math.max(0, opacity));
1118
+ }
1119
+ get boundingBox() {
1120
+ const { engine, client } = this;
1121
+ const boxBuffer = engine.malloc(24);
1122
+ client.getWorldBoundingBox(this.id, boxBuffer);
1123
+ const [cX, cY, cZ, dX, dY, dZ] = Float32Array.from(engine.heapF32.subarray(boxBuffer / 4, boxBuffer / 4 + 6));
1124
+ if (cX === void 0 || cY === void 0 || cZ === void 0 || dX === void 0 || dY === void 0 || dZ === void 0) return;
1125
+ const box = {
1126
+ min: {
1127
+ x: cX - dX / 2,
1128
+ y: cY - dY / 2,
1129
+ z: cZ - dZ / 2
1130
+ },
1131
+ max: {
1132
+ x: cX + dX / 2,
1133
+ y: cY + dY / 2,
1134
+ z: cZ + dZ / 2
1135
+ },
1136
+ size: {
1137
+ x: dX,
1138
+ y: dY,
1139
+ z: dZ
1140
+ },
1141
+ center: {
1142
+ x: cX,
1143
+ y: cY,
1144
+ z: cZ
1145
+ }
1146
+ };
1147
+ Object.freeze(box);
1148
+ return box;
1149
+ }
1150
+ #modelRoots = /* @__PURE__ */ new Set();
1151
+ get modelRoots() {
1152
+ return new Set(this.#modelRoots);
1153
+ }
1154
+ /**
1155
+ * @deprecated Use `modelRoots` instead.
1156
+ */
1157
+ get chunks() {
1158
+ return this.modelRoots;
1159
+ }
1160
+ constructor(options) {
1161
+ super();
1162
+ const { scene, uuid } = options;
1163
+ Object.defineProperties(this, {
1164
+ uuid: {
1165
+ value: uuid,
1166
+ enumerable: true
1167
+ },
1168
+ scene: {
1169
+ value: scene,
1170
+ enumerable: true
1171
+ },
1172
+ client: {
1173
+ value: scene.client,
1174
+ enumerable: true
1175
+ },
1176
+ miris: {
1177
+ value: scene.miris,
1178
+ enumerable: true
1179
+ },
1180
+ engine: {
1181
+ value: scene.miris.engine,
1182
+ enumerable: true
1183
+ }
1184
+ });
1185
+ this._initStream(options);
1186
+ Stream._idMap.set(this.id, this);
1187
+ scene.add(this);
1188
+ }
1189
+ _initStream({ uuid }) {
1190
+ const id = this.client.addStreamById(uuid, uuid, false);
1191
+ Object.defineProperty(this, "id", { value: id });
1192
+ }
1193
+ /**
1194
+ * @internal
1195
+ */
1196
+ async _onStreamLoaded() {
1197
+ if (this.#loadedRenderableData) return;
1198
+ this.dispatchEvent(new Event("streamloaded"));
1199
+ this.scene._onSceneLoaded();
1200
+ this.#loadedRenderableData = true;
1201
+ }
1202
+ /**
1203
+ * @internal
1204
+ */
1205
+ _onRootLoaded() {
1206
+ this.dispatchEvent(new Event("rootloaded"));
1207
+ }
1208
+ add(modelRoot) {
1209
+ this.#modelRoots.add(modelRoot);
1210
+ }
1211
+ end() {
1212
+ console.log("ending the stream");
1213
+ this.client.removeStream(this.id);
1214
+ for (const modelRoot of this.#modelRoots) modelRoot.dispose();
1215
+ this.#modelRoots.clear();
1216
+ Stream._idMap.delete(this.id);
1217
+ Stream._keyMap.delete(this.key);
1218
+ if (this.scene.streams.has(this)) this.scene.delete(this);
1219
+ }
1220
+ };
1221
+ //#endregion
1222
+ //#region packages/core/rate.ts
1223
+ var RATES = [
1224
+ 30,
1225
+ 60,
1226
+ 72,
1227
+ 90,
1228
+ 120,
1229
+ 144,
1230
+ 165,
1231
+ 240
1232
+ ];
1233
+ function createRefreshRateDetector() {
1234
+ let samples = [], last = null, hz = 0;
1235
+ screen.addEventListener?.("change", () => {
1236
+ samples = [];
1237
+ hz = 0;
1238
+ last = null;
1239
+ });
1240
+ return {
1241
+ update(ts) {
1242
+ if (hz) return;
1243
+ if (last !== null) {
1244
+ samples.push(ts - last);
1245
+ if (samples.length > 60) samples.shift();
1246
+ if (!hz && samples.length === 60) {
1247
+ const meanHz = 1e3 / (samples.reduce((a, b) => a + b, 0) / samples.length);
1248
+ hz = RATES.reduce((a, b) => Math.abs(b - meanHz) < Math.abs(a - meanHz) ? b : a);
1249
+ }
1250
+ }
1251
+ last = ts;
1252
+ },
1253
+ get nativeHz() {
1254
+ return hz;
1255
+ }
1256
+ };
1257
+ }
1258
+ //#endregion
1259
+ //#region packages/core/miris.ts
1260
+ /**
1261
+ * The main Miris application.
1262
+ *
1263
+ * @remarks
1264
+ * This class is initialized asynchronously, so synchronous operations may
1265
+ * fail if Miris is not ready. To ensure Miris is ready, await `miris.ready`
1266
+ * or get `miris.pending`.
1267
+ */
1268
+ var Miris = class {
1269
+ static tryUseShark = typeof window !== "undefined" && new URLSearchParams(window.location.search).get("shark") === "1";
1270
+ static _instance;
1271
+ static async instance() {
1272
+ const miris = this._instance ??= new this();
1273
+ await miris.ready;
1274
+ return miris;
1275
+ }
1276
+ #sharedContext;
1277
+ get sharedContext() {
1278
+ return this.#sharedContext;
1279
+ }
1280
+ #viewerKey;
1281
+ get viewerKey() {
1282
+ return this.#viewerKey;
1283
+ }
1284
+ set viewerKey(viewerKey) {
1285
+ this.#viewerKey = viewerKey;
1286
+ }
1287
+ #scenes = /* @__PURE__ */ new Set();
1288
+ get scenes() {
1289
+ return new Set(this.#scenes);
1290
+ }
1291
+ #changes = [];
1292
+ #changeIds = null;
1293
+ #pendingActivations = /* @__PURE__ */ new Set();
1294
+ #pendingDeactivations = /* @__PURE__ */ new Map();
1295
+ #useSphericalHarmonics = true;
1296
+ get useSphericalHarmonics() {
1297
+ return this.#useSphericalHarmonics;
1298
+ }
1299
+ set useSphericalHarmonics(value) {
1300
+ this.#useSphericalHarmonics = value;
1301
+ }
1302
+ constructor() {
1303
+ if (!this.constructor.prototype._instance) this.constructor.prototype._instance = this;
1304
+ Object.defineProperties(this, {
1305
+ pending: {
1306
+ value: true,
1307
+ configurable: true,
1308
+ enumerable: true
1309
+ },
1310
+ engine: {
1311
+ value: new Engine(),
1312
+ enumerable: true
1313
+ }
1314
+ });
1315
+ Object.defineProperty(this, "ready", {
1316
+ enumerable: true,
1317
+ value: this.#initializeMiris()
1318
+ });
1319
+ console.assert?.(this._xrModeActive === false);
1320
+ this.#bindRequestAnimationFrame();
1321
+ }
1322
+ async #initializeMiris() {
1323
+ const { engine } = this;
1324
+ await engine.ready;
1325
+ this.#sharedContext = this.engine.createContext();
1326
+ const mb = 1048576;
1327
+ const maxCacheSizeParam = new URLSearchParams(window.location.search).get("aquaMaxCacheSize");
1328
+ let maxCacheSizeMB = 0;
1329
+ if (maxCacheSizeParam) {
1330
+ const parsedSize = parseInt(maxCacheSizeParam, 10);
1331
+ if (!isNaN(parsedSize) && parsedSize > 0) maxCacheSizeMB = parsedSize;
1332
+ }
1333
+ if (maxCacheSizeMB > 0) this.engine.setMaxCacheSize(maxCacheSizeMB * mb);
1334
+ else if (navigator.userAgent.includes("iPhone")) this.engine.setMaxCacheSize(128 * mb);
1335
+ else if (navigator.userAgent.includes("Android")) this.engine.setMaxCacheSize(256 * mb);
1336
+ this.#browserUpdate();
1337
+ Object.defineProperty(this, "pending", {
1338
+ value: false,
1339
+ configurable: false
1340
+ });
1341
+ return this;
1342
+ }
1343
+ dispose() {
1344
+ if (this.#sharedContext) {
1345
+ if (this.engine.destroyContext(this.#sharedContext) !== Engine.AquaStatus.Success) console.error(`Failed to destroy aqua context with handle '${this.#sharedContext}'`);
1346
+ this.#sharedContext = 0;
1347
+ }
1348
+ }
1349
+ updateParentedTransform(_modelTransform, _parentTransform) {}
1350
+ #detector = createRefreshRateDetector();
1351
+ #boundUpdate = this.#browserUpdate.bind(this);
1352
+ #hostDriven = false;
1353
+ #lastFrameTimestamp = null;
1354
+ #lastUpdateTs = -1;
1355
+ #targetFramesPerSecond = 72;
1356
+ #splatCountBudgetOverride = null;
1357
+ _xrModeActive = false;
1358
+ _xrSession = null;
1359
+ _requestAnimationFrame = null;
1360
+ signalResumeFromIdle() {}
1361
+ #applyDisplaySettings() {
1362
+ const settings = new this.engine.RuntimeSettings();
1363
+ settings.targetFramesPerSecond = this.#targetFramesPerSecond;
1364
+ settings.xrModeActive = this._xrModeActive;
1365
+ if (this.#splatCountBudgetOverride !== null) settings.splatCountBudget = this.#splatCountBudgetOverride;
1366
+ else if (this._xrModeActive) settings.splatCountBudget = 2e5;
1367
+ for (const scene of this.#scenes) scene.client.setRuntimeSettings(settings);
1368
+ settings.delete();
1369
+ }
1370
+ /**
1371
+ * Why 43? Because the AVP throttles down to 45Hz :(
1372
+ */
1373
+ static _XR_TARGET_FRAME_RATE = 43;
1374
+ #bindRequestAnimationFrame() {
1375
+ this._requestAnimationFrame = this._xrModeActive ? this._xrSession.requestAnimationFrame.bind(this._xrSession) : window.requestAnimationFrame.bind(window);
1376
+ }
1377
+ /**
1378
+ * @internal
1379
+ */
1380
+ _setTargetFrameRate(frameRate) {
1381
+ this.#targetFramesPerSecond = frameRate;
1382
+ this.#detector = null;
1383
+ this.#applyDisplaySettings();
1384
+ }
1385
+ /**
1386
+ * @internal
1387
+ */
1388
+ _setXRModeActive(active, frameRate, xrSession) {
1389
+ this._xrModeActive = active;
1390
+ this._xrSession = xrSession ?? null;
1391
+ if (frameRate !== void 0) this.#targetFramesPerSecond = frameRate;
1392
+ this.#applyDisplaySettings();
1393
+ this.#bindRequestAnimationFrame();
1394
+ }
1395
+ /**
1396
+ * @internal
1397
+ */
1398
+ _setSplatCountBudgetOverride(budget) {
1399
+ this.#splatCountBudgetOverride = budget;
1400
+ this.#applyDisplaySettings();
1401
+ }
1402
+ #browserUpdate(ts = 0) {
1403
+ if (this.#hostDriven) return;
1404
+ this._update(ts);
1405
+ if (this._xrModeActive) return;
1406
+ requestAnimationFrame(this.#boundUpdate);
1407
+ }
1408
+ /**
1409
+ * @internal
1410
+ *
1411
+ * Shared update function being driven by browser's update loop or an XR session
1412
+ */
1413
+ _update(ts = 0) {
1414
+ if (ts !== 0 && ts === this.#lastUpdateTs) return;
1415
+ this.#lastUpdateTs = ts;
1416
+ if (this.#detector) {
1417
+ this.#detector.update(performance.now());
1418
+ if (this.#detector.nativeHz > 0) {
1419
+ const hz = this.#detector.nativeHz;
1420
+ this.#targetFramesPerSecond = hz <= 40 ? hz : 40;
1421
+ this.#applyDisplaySettings();
1422
+ this.#detector = null;
1423
+ }
1424
+ }
1425
+ const now = performance.now();
1426
+ const elapsed = this.#lastFrameTimestamp === null ? null : now - this.#lastFrameTimestamp;
1427
+ this.#lastFrameTimestamp = now;
1428
+ const frameTimeMs = elapsed !== null && elapsed <= 1e3 ? elapsed : null;
1429
+ for (const scene of this.#scenes) {
1430
+ const { client } = scene;
1431
+ if (frameTimeMs !== null) client.recordFrameTime(frameTimeMs);
1432
+ client.updateSceneExecution();
1433
+ const evicted = client.takeEvictedClientSideAttributeIds();
1434
+ try {
1435
+ const evictedSize = evicted.size();
1436
+ if (evictedSize > 0) {
1437
+ const evictedArray = [];
1438
+ for (let i = 0; i < evictedSize; i++) evictedArray.push(Number(evicted.get(i)));
1439
+ AttributeCache.remove(evictedArray);
1440
+ }
1441
+ } finally {
1442
+ evicted.delete();
1443
+ }
1444
+ const checkSumWasm = this.engine.getActiveClientSideIdsCheckSum();
1445
+ AttributeCache.validateCheckSum(checkSumWasm);
1446
+ if (!client.lockScene()) return;
1447
+ try {
1448
+ this.#updateScene(scene);
1449
+ } finally {
1450
+ client.unlockScene();
1451
+ }
1452
+ }
1453
+ if (this.#changes.length) {
1454
+ this.applyChanges(this.#changes);
1455
+ this.#changes.length = 0;
1456
+ }
1457
+ }
1458
+ getLocalTransform(client, sceneObjectId) {
1459
+ if (Number.isInteger(sceneObjectId) && sceneObjectId >= 0) return retrieveFloatArray(this.engine, sceneObjectId, 16, client.getLocalTransform.bind(client));
1460
+ }
1461
+ getWorldTransform(client, sceneObjectId) {
1462
+ if (Number.isInteger(sceneObjectId) && sceneObjectId >= 0) return retrieveFloatArray(this.engine, sceneObjectId, 16, client.getWorldTransform.bind(client));
1463
+ }
1464
+ #shouldUpdateSceneChanges() {
1465
+ if (!this.#changeIds) return false;
1466
+ if (this.#changeIds.createdObjectsCount > 0) return true;
1467
+ if (this.#changeIds.activatedObjectsCount > 0) return true;
1468
+ if (this.#changeIds.deactivatedObjectsCount > 0) return true;
1469
+ if (this.#changeIds.modifiedObjectsCount > 0) return true;
1470
+ if (this.#changeIds.deletedObjectsCount > 0) return true;
1471
+ if (this.#changeIds.remaskedObjectsCount > 0) return true;
1472
+ return false;
1473
+ }
1474
+ #updateScene(scene) {
1475
+ const { engine } = this;
1476
+ const { client, camera, lods } = scene;
1477
+ if (camera) camera.update();
1478
+ if (this.#changeIds === null) this.#changeIds = new engine.SceneChangeIds();
1479
+ client.getSceneChangesCounts(this.#changeIds);
1480
+ if (!this.#shouldUpdateSceneChanges()) return;
1481
+ engine.allocateSceneChangesArrays(this.#changeIds);
1482
+ client.getSceneChanges(this.#changeIds);
1483
+ const createdLodIds = /* @__PURE__ */ new Set();
1484
+ for (const sceneObjectId of engine.createdObjectIdsView(this.#changeIds)) {
1485
+ const sceneObjectType = client.getSceneObjectType(sceneObjectId);
1486
+ if (sceneObjectType === Engine.SceneObjectType.StreamObject) {
1487
+ Stream.forId(sceneObjectId);
1488
+ continue;
1489
+ } else if (sceneObjectType === Engine.SceneObjectType.ModelRoot) {
1490
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1491
+ if (!stream) continue;
1492
+ const modelRoot = new ModelRoot({
1493
+ id: sceneObjectId,
1494
+ stream
1495
+ });
1496
+ const modelRootTransform = this.getLocalTransform(client, sceneObjectId);
1497
+ if (!modelRootTransform) continue;
1498
+ const parentId = client.getSceneObjectParent(sceneObjectId);
1499
+ const parentTransform = this.getLocalTransform(client, parentId);
1500
+ if (!parentTransform) continue;
1501
+ const updatedTransform = this.updateParentedTransform(modelRootTransform, parentTransform);
1502
+ if (!updatedTransform) continue;
1503
+ modelRoot.transform = updatedTransform;
1504
+ } else if (sceneObjectType == Engine.SceneObjectType.GaussianSplats) {
1505
+ const modelRoot = scene.getModelRootForDescendentId(sceneObjectId);
1506
+ if (!modelRoot) continue;
1507
+ const lod = new Lod({
1508
+ id: sceneObjectId,
1509
+ modelRoot,
1510
+ lodStore: lods,
1511
+ client
1512
+ });
1513
+ lod.transform = this.getLocalTransform(client, sceneObjectId);
1514
+ createdLodIds.add(sceneObjectId);
1515
+ const entry = new Change({
1516
+ type: "created",
1517
+ lod
1518
+ });
1519
+ this.#changes.push(entry);
1520
+ } else if (sceneObjectType == Engine.SceneObjectType.VariantSetCollection) scene.getStreamForDescendentId(sceneObjectId)?._addVariantCollection(sceneObjectId);
1521
+ else if (sceneObjectType == Engine.SceneObjectType.VariantSet) {
1522
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1523
+ const name = client.getName(sceneObjectId);
1524
+ const parentId = client.getSceneObjectParent(sceneObjectId);
1525
+ stream?._addVariant(parentId, {
1526
+ id: sceneObjectId,
1527
+ name,
1528
+ options: [],
1529
+ nestedSets: []
1530
+ });
1531
+ } else if (sceneObjectType == Engine.SceneObjectType.VariantSetOption) {
1532
+ const stream = scene.getStreamForDescendentId(sceneObjectId);
1533
+ const name = client.getName(sceneObjectId);
1534
+ const parentId = client.getSceneObjectParent(sceneObjectId);
1535
+ stream?._addVariant(parentId, {
1536
+ id: sceneObjectId,
1537
+ name,
1538
+ type: "option"
1539
+ });
1540
+ }
1541
+ }
1542
+ for (const sceneObjectId of engine.deletedObjectIdsView(this.#changeIds)) {
1543
+ const lod = lods.forId(sceneObjectId);
1544
+ if (!lod) continue;
1545
+ const entry = new Change({
1546
+ type: "deleted",
1547
+ lod
1548
+ });
1549
+ this.#changes.push(entry);
1550
+ }
1551
+ for (const sceneObjectId of engine.modifiedObjectIdsView(this.#changeIds)) {
1552
+ const sceneObjectType = client.getSceneObjectType(sceneObjectId);
1553
+ if (sceneObjectType === Engine.SceneObjectType.LodOctree) scene._onFeatureData(sceneObjectId);
1554
+ else if (sceneObjectType === Engine.SceneObjectType.GaussianSplats) {
1555
+ const lodIndex = client.getLodIndex(sceneObjectId);
1556
+ const lod = lods.forId(sceneObjectId);
1557
+ if (!lod) {
1558
+ console.warn(`Received modified event for LOD ${sceneObjectId} which does not exist.`);
1559
+ continue;
1560
+ }
1561
+ const worldBounds = retrieveFloatArray(this.engine, lod.id, 6, client.getWorldBoundingBox.bind(client));
1562
+ const localBounds = retrieveFloatArray(this.engine, lod.id, 6, client.getLocalBoundingBox.bind(client));
1563
+ lod.bounds = worldBounds;
1564
+ lod.localBounds = localBounds;
1565
+ lod.lodIndex = lodIndex;
1566
+ const entry = new Change({
1567
+ type: "modified",
1568
+ lod
1569
+ });
1570
+ this.#changes.push(entry);
1571
+ if (this.#pendingActivations.delete(sceneObjectId)) {
1572
+ this.#changes.push(new Change({
1573
+ type: "activated",
1574
+ lod
1575
+ }));
1576
+ for (const [, deactLod] of this.#pendingDeactivations) this.#changes.push(new Change({
1577
+ type: "deactivated",
1578
+ lod: deactLod
1579
+ }));
1580
+ this.#pendingDeactivations.clear();
1581
+ }
1582
+ }
1583
+ }
1584
+ if (this.#changes.some((c) => c.type === "created")) try {
1585
+ const metadata = new engine.SceneMetadata();
1586
+ client.getSceneMetadata(metadata);
1587
+ this.onColorSpaceDetected(metadata.inputColorSpace === "linear");
1588
+ metadata.delete();
1589
+ } catch (e) {
1590
+ console.warn("Failed to read scene metadata:", e);
1591
+ }
1592
+ for (const sceneObjectId of engine.activatedObjectIdsView(this.#changeIds)) if (client.getSceneObjectType(sceneObjectId) == Engine.SceneObjectType.GaussianSplats) {
1593
+ const lod = lods.forId(sceneObjectId);
1594
+ if (lod) {
1595
+ const entry = new Change({
1596
+ type: "activated",
1597
+ lod
1598
+ });
1599
+ this.#changes.push(entry);
1600
+ }
1601
+ }
1602
+ for (const sceneObjectId of engine.deactivatedObjectIdsView(this.#changeIds)) if (client.getSceneObjectType(sceneObjectId) == Engine.SceneObjectType.GaussianSplats) {
1603
+ this.#pendingActivations.delete(sceneObjectId);
1604
+ if (!createdLodIds.has(sceneObjectId)) {
1605
+ const lod = lods.forId(sceneObjectId);
1606
+ if (lod) {
1607
+ const entry = new Change({
1608
+ type: "deactivated",
1609
+ lod
1610
+ });
1611
+ this.#changes.push(entry);
1612
+ }
1613
+ }
1614
+ }
1615
+ for (const sceneObjectId of engine.remaskedObjectIdsView(this.#changeIds)) if (client.getSceneObjectType(sceneObjectId) == Engine.SceneObjectType.GaussianSplats) {
1616
+ const lod = lods.forId(sceneObjectId);
1617
+ if (lod) {
1618
+ lod._drawnOctantMask = client.getDrawnOctantMask(sceneObjectId);
1619
+ this.#changes.push(new Change({
1620
+ type: "remasked",
1621
+ lod
1622
+ }));
1623
+ }
1624
+ }
1625
+ }
1626
+ update() {
1627
+ this.#hostDriven = true;
1628
+ this._update();
1629
+ let needsRender = false;
1630
+ for (const scene of this.#scenes) if (scene.client.takeRenderRequired()) needsRender = true;
1631
+ return needsRender || this._computeAdditionalRenderNeeded();
1632
+ }
1633
+ applyChanges(_entries) {}
1634
+ _computeAdditionalRenderNeeded() {
1635
+ return false;
1636
+ }
1637
+ onColorSpaceDetected(_isLinear) {}
1638
+ add(scene) {
1639
+ this.#scenes.add(scene);
1640
+ }
1641
+ delete(scene) {
1642
+ this.#scenes.delete(scene);
1643
+ if (scene.miris) scene.close();
1644
+ if (this.#scenes.size === 0 && this.#changeIds !== null) {
1645
+ this.#changeIds.delete();
1646
+ this.#changeIds = null;
1647
+ }
1648
+ }
1649
+ };
1650
+ //#endregion
1651
+ //#region packages/core/camera.ts
1652
+ var Camera = class {
1653
+ update() {
1654
+ const { engine } = this;
1655
+ const { client } = this.scene;
1656
+ const matrixBuffer = engine.malloc(this.#matrix.length * 4);
1657
+ engine.heapF32.set(Float32Array.from(this.#matrix), matrixBuffer / 4);
1658
+ client.setMainCameraTransform(matrixBuffer);
1659
+ engine.free(matrixBuffer);
1660
+ client.setMainCameraViewFrustum(this.#aspect, this.#fov, this.#near, this.#far);
1661
+ }
1662
+ #aspect;
1663
+ get aspect() {
1664
+ return this.#aspect;
1665
+ }
1666
+ set aspect(aspect) {
1667
+ this.#aspect = aspect;
1668
+ }
1669
+ #fov;
1670
+ get fov() {
1671
+ return this.#fov;
1672
+ }
1673
+ set fov(fov) {
1674
+ this.#fov = fov;
1675
+ }
1676
+ #near;
1677
+ get near() {
1678
+ return this.#near;
1679
+ }
1680
+ set near(near) {
1681
+ this.#near = near;
1682
+ }
1683
+ #far;
1684
+ get far() {
1685
+ return this.#far;
1686
+ }
1687
+ set far(far) {
1688
+ this.#far = far;
1689
+ }
1690
+ #matrix;
1691
+ get matrix() {
1692
+ return this.#matrix;
1693
+ }
1694
+ set matrix(matrix) {
1695
+ this.#matrix = matrix;
1696
+ }
1697
+ constructor({ aspect, fov, near, far, matrix, scene }) {
1698
+ this.#aspect = aspect;
1699
+ this.#fov = fov;
1700
+ this.#near = near;
1701
+ this.#far = far;
1702
+ this.#matrix = matrix;
1703
+ Object.defineProperties(this, {
1704
+ scene: { value: scene },
1705
+ miris: { value: scene.miris },
1706
+ engine: { value: scene.miris.engine }
1707
+ });
1708
+ }
1709
+ };
1710
+ //#endregion
1711
+ //#region packages/core/engine/client.ts
1712
+ var Client = class {
1713
+ #viewerKey = null;
1714
+ get viewerKey() {
1715
+ return this.#viewerKey;
1716
+ }
1717
+ set viewerKey(key) {
1718
+ if (key) this.setAssetViewerKey(key);
1719
+ this.#viewerKey = key;
1720
+ }
1721
+ constructor({ engine, context }) {
1722
+ Object.defineProperties(this, {
1723
+ engine: {
1724
+ value: engine,
1725
+ enumerable: true
1726
+ },
1727
+ handle: {
1728
+ value: engine.createClient(context),
1729
+ enumerable: true
1730
+ }
1731
+ });
1732
+ }
1733
+ dispose() {
1734
+ if (this.engine.destroyClient(this.handle) !== Engine.AquaStatus.Success) console.error(`Failed to destroy client with handle '${this.handle}'`);
1735
+ }
1736
+ addStreamById(...args) {
1737
+ return this.engine.addStreamById(this.handle, ...args);
1738
+ }
1739
+ destroyClient(...args) {
1740
+ return this.engine.destroyClient(this.handle, ...args);
1741
+ }
1742
+ getAssetsAsync(...args) {
1743
+ return this.engine.getAssetsAsync(this.handle, ...args);
1744
+ }
1745
+ getAttribute(...args) {
1746
+ return this.engine.getAttribute(this.handle, ...args);
1747
+ }
1748
+ getDefaultCameraId(...args) {
1749
+ return this.engine.getDefaultCameraId(this.handle, ...args);
1750
+ }
1751
+ getViewingVolumeId(...args) {
1752
+ return this.engine.getViewingVolumeId(this.handle, ...args);
1753
+ }
1754
+ getLocalBoundingBox(...args) {
1755
+ return this.engine.getLocalBoundingBox(this.handle, ...args);
1756
+ }
1757
+ getWorldBoundingBox(...args) {
1758
+ return this.engine.getWorldBoundingBox(this.handle, ...args);
1759
+ }
1760
+ getLodIndex(...args) {
1761
+ return this.engine.getLodIndex(this.handle, ...args);
1762
+ }
1763
+ getSceneChanges(...args) {
1764
+ return this.engine.getSceneChanges(this.handle, ...args);
1765
+ }
1766
+ getSceneChangesCounts(...args) {
1767
+ return this.engine.getSceneChangesCounts(this.handle, ...args);
1768
+ }
1769
+ getSceneMetadata(...args) {
1770
+ return this.engine.getSceneMetadata(this.handle, ...args);
1771
+ }
1772
+ getSceneObjectParent(...args) {
1773
+ return this.engine.getSceneObjectParent(this.handle, ...args);
1774
+ }
1775
+ getSceneObjectType(...args) {
1776
+ return this.engine.getSceneObjectType(this.handle, ...args);
1777
+ }
1778
+ getDrawnOctantMask(...args) {
1779
+ return this.engine.getDrawnOctantMask(this.handle, ...args);
1780
+ }
1781
+ getLocalTransform(...args) {
1782
+ return this.engine.getLocalTransform(this.handle, ...args);
1783
+ }
1784
+ getWorldTransform(...args) {
1785
+ return this.engine.getWorldTransform(this.handle, ...args);
1786
+ }
1787
+ hasAttribute(...args) {
1788
+ return this.engine.hasAttribute(this.handle, ...args);
1789
+ }
1790
+ isSceneObjectAncestorOf(...args) {
1791
+ return this.engine.isSceneObjectAncestorOf(this.handle, ...args);
1792
+ }
1793
+ lockScene(...args) {
1794
+ return this.engine.lockScene(this.handle, ...args);
1795
+ }
1796
+ removeStream(...args) {
1797
+ return this.engine.removeStream(this.handle, ...args);
1798
+ }
1799
+ setAssetViewerKey(...args) {
1800
+ return this.engine.setAssetViewerKey(this.handle, ...args);
1801
+ }
1802
+ setClientSpatialFormat(...args) {
1803
+ return this.engine.setClientSpatialFormat(this.handle, ...args);
1804
+ }
1805
+ setRuntimeSettings(...args) {
1806
+ return this.engine.setRuntimeSettings(this.handle, ...args);
1807
+ }
1808
+ setMainCameraTransform(...args) {
1809
+ return this.engine.setMainCameraTransform(this.handle, ...args);
1810
+ }
1811
+ setMainCameraViewFrustum(...args) {
1812
+ return this.engine.setMainCameraViewFrustum(this.handle, ...args);
1813
+ }
1814
+ setSceneObjectTransform(...args) {
1815
+ return this.engine.setSceneObjectTransform(this.handle, ...args);
1816
+ }
1817
+ hasFeature(...args) {
1818
+ return this.engine.hasFeature(this.handle, ...args);
1819
+ }
1820
+ getFeatureVersion(...args) {
1821
+ return this.engine.getFeatureVersion(this.handle, ...args);
1822
+ }
1823
+ getFeatureState(...args) {
1824
+ return this.engine.getFeatureState(this.handle, ...args);
1825
+ }
1826
+ getName(...args) {
1827
+ return this.engine.getName(this.handle, ...args);
1828
+ }
1829
+ setVariantSelection(...args) {
1830
+ return this.engine.setVariantSelection(this.handle, ...args);
1831
+ }
1832
+ takeAttribute(...args) {
1833
+ return this.engine.takeAttribute(this.handle, ...args);
1834
+ }
1835
+ takeEvictedClientSideAttributeIds(...args) {
1836
+ return this.engine.takeEvictedClientSideAttributeIds(this.handle, ...args);
1837
+ }
1838
+ takeRenderRequired(...args) {
1839
+ return this.engine.takeRenderRequired(this.handle, ...args);
1840
+ }
1841
+ unlockScene(...args) {
1842
+ return this.engine.unlockScene(this.handle, ...args);
1843
+ }
1844
+ updateSceneExecution(...args) {
1845
+ return this.engine.updateSceneExecution(this.handle, ...args);
1846
+ }
1847
+ recordFrameTime(...args) {
1848
+ return this.engine.recordFrameTime(this.handle, ...args);
1849
+ }
1850
+ };
1851
+ //#endregion
1852
+ //#region packages/core/scene.ts
1853
+ var Scene = class Scene extends EventTarget {
1854
+ static #idMap = /* @__PURE__ */ new Map();
1855
+ static #keyMap = /* @__PURE__ */ new Map();
1856
+ #camera = null;
1857
+ get camera() {
1858
+ return this.#camera;
1859
+ }
1860
+ set camera(camera) {
1861
+ this.#camera = camera;
1862
+ }
1863
+ #defaultCameraId = null;
1864
+ static forId(id) {
1865
+ return Scene.#idMap.get(id);
1866
+ }
1867
+ static forKey(key) {
1868
+ return Scene.#keyMap.get(key);
1869
+ }
1870
+ #key;
1871
+ get key() {
1872
+ return this.#key ?? null;
1873
+ }
1874
+ set key(key) {
1875
+ Scene.#keyMap.delete(this.key);
1876
+ if (key || 0 === key) Scene.#keyMap.set(key, this);
1877
+ this.#key = key;
1878
+ }
1879
+ #streams = /* @__PURE__ */ new Set();
1880
+ #streamObjectIdToStream = /* @__PURE__ */ new Map();
1881
+ get viewerKey() {
1882
+ return this.client.viewerKey;
1883
+ }
1884
+ set viewerKey(viewerKey) {
1885
+ if (viewerKey) this.client.viewerKey = viewerKey;
1886
+ }
1887
+ get streams() {
1888
+ return new Set(this.#streams);
1889
+ }
1890
+ #lods = new LodStore();
1891
+ get lods() {
1892
+ return this.#lods;
1893
+ }
1894
+ constructor({ miris, viewerKey }) {
1895
+ super();
1896
+ Object.defineProperties(this, {
1897
+ miris: {
1898
+ value: miris,
1899
+ enumerable: true
1900
+ },
1901
+ engine: {
1902
+ value: miris.engine,
1903
+ enumerable: true
1904
+ },
1905
+ client: { value: new Client({
1906
+ engine: miris.engine,
1907
+ context: miris.sharedContext
1908
+ }) }
1909
+ });
1910
+ if (viewerKey) this.viewerKey = viewerKey;
1911
+ const spatialFormat = new this.engine.SpatialFormat();
1912
+ spatialFormat.metersPerUnit = 1;
1913
+ spatialFormat.upAxis = this.engine.UpAxis.Y;
1914
+ spatialFormat.matrixOrder = this.engine.MatrixOrder.ColumnMajor;
1915
+ spatialFormat.handedness = this.engine.Handedness.Right;
1916
+ this.client.setClientSpatialFormat(spatialFormat);
1917
+ spatialFormat.delete();
1918
+ Scene.#idMap.set(this.id, this);
1919
+ miris.add(this);
1920
+ }
1921
+ dispose() {
1922
+ this.close();
1923
+ this.client.dispose();
1924
+ }
1925
+ #updateSceneCameraData() {
1926
+ const defaultCameraId = this.client.getDefaultCameraId();
1927
+ this.#defaultCameraId = defaultCameraId >= 0 ? defaultCameraId : null;
1928
+ }
1929
+ /**
1930
+ * Returns the world-space AABB of the authored /Miris/ViewingVolume prim,
1931
+ * or null if no viewing volume is present in the loaded structure.
1932
+ * @internal
1933
+ */
1934
+ _getViewingVolumeBounds() {
1935
+ const viewingVolumeId = this.client.getViewingVolumeId();
1936
+ if (viewingVolumeId < 0) return null;
1937
+ const { engine, client } = this;
1938
+ const boxBuffer = engine.malloc(24);
1939
+ try {
1940
+ client.getWorldBoundingBox(viewingVolumeId, boxBuffer);
1941
+ const [cX, cY, cZ, dX, dY, dZ] = Float32Array.from(engine.heapF32.subarray(boxBuffer / 4, boxBuffer / 4 + 6));
1942
+ if (cX === void 0 || cY === void 0 || cZ === void 0 || dX === void 0 || dY === void 0 || dZ === void 0) return null;
1943
+ return {
1944
+ min: [
1945
+ cX - dX / 2,
1946
+ cY - dY / 2,
1947
+ cZ - dZ / 2
1948
+ ],
1949
+ max: [
1950
+ cX + dX / 2,
1951
+ cY + dY / 2,
1952
+ cZ + dZ / 2
1953
+ ]
1954
+ };
1955
+ } finally {
1956
+ engine.free(boxBuffer);
1957
+ }
1958
+ }
1959
+ async fetchAssets(tags) {
1960
+ if (!this.viewerKey) throw new Error("Could not fetch assets because there is no viewer key");
1961
+ const vector = new this.engine.StringVector();
1962
+ let _tags = [];
1963
+ if (typeof tags === "string") _tags = tags.split(",");
1964
+ else if (tags?.[Symbol.iterator]) _tags = [...tags];
1965
+ for (const tag of _tags) vector.push_back(tag);
1966
+ const _assets = await this.client.getAssetsAsync(vector);
1967
+ const assets = [];
1968
+ const decoder = new TextDecoder();
1969
+ for (const { name, tags, thumbnailUrl, uuid } of _assets) {
1970
+ const asset = {
1971
+ name,
1972
+ thumbnailUrl,
1973
+ uuid,
1974
+ tags: []
1975
+ };
1976
+ const size = tags.size();
1977
+ for (let index = 0; index < size; index += 1) {
1978
+ let tag = tags.get(index);
1979
+ if (tag) {
1980
+ if (typeof tag !== "string") tag = decoder.decode(tag);
1981
+ asset.tags.push(tag);
1982
+ }
1983
+ }
1984
+ assets.push(asset);
1985
+ }
1986
+ vector.delete();
1987
+ return assets;
1988
+ }
1989
+ getDefaultCameraTransform() {
1990
+ if (this.#defaultCameraId === null) return null;
1991
+ return this.miris.getWorldTransform(this.client, this.#defaultCameraId);
1992
+ }
1993
+ add(stream) {
1994
+ this.#streams.add(stream);
1995
+ this.#streamObjectIdToStream.set(stream.id, stream);
1996
+ }
1997
+ getStreamForId(streamObjectId) {
1998
+ return this.#streamObjectIdToStream.get(streamObjectId);
1999
+ }
2000
+ getStreamForDescendentId(descendentObjectId) {
2001
+ for (const [streamObjectId, stream] of this.#streamObjectIdToStream) if (this.client.isSceneObjectAncestorOf(streamObjectId, descendentObjectId)) return stream;
2002
+ return null;
2003
+ }
2004
+ getModelRootForDescendentId(descendentObjectId) {
2005
+ for (const [, stream] of this.#streamObjectIdToStream) for (const modelRoot of stream.modelRoots) if (this.client.isSceneObjectAncestorOf(modelRoot.id, descendentObjectId)) return modelRoot;
2006
+ return null;
2007
+ }
2008
+ /**
2009
+ * @internal
2010
+ */
2011
+ async _getFeatureMesh(sceneObjectId, feature, attrBase) {
2012
+ if (!this.client.hasFeature(sceneObjectId, feature)) return null;
2013
+ if (this.client.getFeatureState(sceneObjectId, feature) !== Engine.FeatureState.Loaded) return null;
2014
+ const version = this.client.getFeatureVersion(sceneObjectId, feature);
2015
+ if (version === 1) {
2016
+ const attrName = `${attrBase}_v${version}`;
2017
+ const attrInfo = new this.engine.AttributeInfo();
2018
+ try {
2019
+ if (this.client.getAttribute(sceneObjectId, attrName, attrInfo.$$.ptr) !== Engine.AquaStatus.Success) return null;
2020
+ if (attrInfo.clientSideId !== 0n) return AttributeCache.get(Number(attrInfo.clientSideId));
2021
+ const wasmView = this.engine.dataPtrView(attrInfo);
2022
+ const buffer = new Uint8Array(wasmView.buffer).subarray(wasmView.byteOffset, wasmView.byteOffset + wasmView.byteLength).slice().buffer;
2023
+ const cacheId = AttributeCache.add(buffer);
2024
+ const takeStatus = this.client.takeAttribute(sceneObjectId, attrName, BigInt(cacheId));
2025
+ if (takeStatus !== Engine.AquaStatus.Success) {
2026
+ AttributeCache.remove(cacheId);
2027
+ console.warn(`Failed to take attribute ${attrName} for scene object ${sceneObjectId}: status ${takeStatus}`);
2028
+ return null;
2029
+ }
2030
+ return buffer;
2031
+ } finally {
2032
+ attrInfo.delete();
2033
+ }
2034
+ }
2035
+ console.warn(`getFeatureMesh: unsupported version ${version} for feature ${feature}`);
2036
+ return null;
2037
+ }
2038
+ /**
2039
+ * @internal
2040
+ */
2041
+ async _getDrMap(sceneObjectId) {
2042
+ if (!this.client.hasFeature(sceneObjectId, Engine.Feature.DrMap)) return null;
2043
+ if (this.client.getFeatureState(sceneObjectId, Engine.Feature.DrMap) !== Engine.FeatureState.Loaded) return null;
2044
+ const version = this.client.getFeatureVersion(sceneObjectId, Engine.Feature.DrMap);
2045
+ if (version === 1 || version === 2) {
2046
+ const attrName = `drMap_v${version}`;
2047
+ const attrInfo = new this.engine.AttributeInfo();
2048
+ try {
2049
+ if (this.client.getAttribute(sceneObjectId, attrName, attrInfo.$$.ptr) !== Engine.AquaStatus.Success) return null;
2050
+ if (attrInfo.clientSideId !== 0n) {
2051
+ const cached = AttributeCache.get(Number(attrInfo.clientSideId));
2052
+ return cached !== void 0 ? {
2053
+ bytes: cached,
2054
+ version
2055
+ } : null;
2056
+ }
2057
+ const wasmView = this.engine.dataPtrView(attrInfo);
2058
+ const bytes = new Uint8Array(wasmView.buffer).subarray(wasmView.byteOffset, wasmView.byteOffset + wasmView.byteLength).slice();
2059
+ const cacheId = AttributeCache.add(bytes);
2060
+ console.log(`_getDrMap is calling takeAttribute for ${attrName} with id ${cacheId}`);
2061
+ const takeStatus = this.client.takeAttribute(sceneObjectId, attrName, BigInt(cacheId));
2062
+ if (takeStatus !== Engine.AquaStatus.Success) {
2063
+ AttributeCache.remove(cacheId);
2064
+ if (this.client.getAttribute(sceneObjectId, attrName, attrInfo.$$.ptr) === Engine.AquaStatus.Success && attrInfo.clientSideId !== 0n) {
2065
+ const cached = AttributeCache.get(Number(attrInfo.clientSideId));
2066
+ return cached !== void 0 ? {
2067
+ bytes: cached,
2068
+ version
2069
+ } : null;
2070
+ }
2071
+ console.warn(`getDrMap: failed to take attribute ${attrName} for scene object ${sceneObjectId}: status ${takeStatus}`);
2072
+ return null;
2073
+ }
2074
+ return {
2075
+ bytes,
2076
+ version
2077
+ };
2078
+ } finally {
2079
+ attrInfo.delete();
2080
+ }
2081
+ }
2082
+ console.warn(`getDrMap: unsupported DR map version ${version}`);
2083
+ return null;
2084
+ }
2085
+ /**
2086
+ * @internal
2087
+ */
2088
+ async _onFeatureData(sceneObjectId) {
2089
+ const drMapData = await this._getDrMap(sceneObjectId);
2090
+ if (drMapData !== null) this.dispatchEvent(new CustomEvent("drmaploaded", { detail: {
2091
+ bytes: drMapData.bytes,
2092
+ version: drMapData.version,
2093
+ sceneObjectId
2094
+ } }));
2095
+ const reflBuffer = await this._getFeatureMesh(sceneObjectId, Engine.Feature.ReflMesh, "reflMesh");
2096
+ if (reflBuffer !== null) this.dispatchEvent(new CustomEvent("reflmeshloaded", { detail: {
2097
+ buffer: reflBuffer,
2098
+ sceneObjectId
2099
+ } }));
2100
+ const glassBuffer = await this._getFeatureMesh(sceneObjectId, Engine.Feature.GlassMesh, "glassMesh");
2101
+ if (glassBuffer !== null) this.dispatchEvent(new CustomEvent("glassmeshloaded", { detail: {
2102
+ buffer: glassBuffer,
2103
+ sceneObjectId
2104
+ } }));
2105
+ }
2106
+ /**
2107
+ * @internal
2108
+ */
2109
+ _onSceneLoaded() {
2110
+ this.#updateSceneCameraData();
2111
+ this.dispatchEvent(new Event("sceneloaded"));
2112
+ }
2113
+ delete(stream) {
2114
+ this.#streams.delete(stream);
2115
+ this.#streamObjectIdToStream.delete(stream.id);
2116
+ if (Stream.forId(stream.id)) stream.end();
2117
+ }
2118
+ close() {
2119
+ for (const stream of this.streams) stream.end();
2120
+ Scene.#idMap.delete(this.id);
2121
+ Scene.#keyMap.delete(this.key);
2122
+ if (this.miris.scenes.has(this)) this.miris.delete(this);
2123
+ }
2124
+ };
2125
+ //#endregion
2126
+ export { AttributeNames, Camera, Lod, LodStore, Miris, ModelRoot, Scene, Stream, sparkAttributeList };