@speridlabs/visus 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.es.js DELETED
@@ -1,1292 +0,0 @@
1
- var lt = Object.defineProperty;
2
- var ht = (A, t, n) => t in A ? lt(A, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : A[t] = n;
3
- var f = (A, t, n) => ht(A, typeof t != "symbol" ? t + "" : t, n);
4
- import * as i from "three";
5
- class et {
6
- constructor() {
7
- f(this, "min", new i.Vector3(1 / 0, 1 / 0, 1 / 0));
8
- f(this, "max", new i.Vector3(-1 / 0, -1 / 0, -1 / 0));
9
- f(this, "center", new i.Vector3());
10
- /** Half extents (size/2) */
11
- f(this, "halfExtents", new i.Vector3());
12
- }
13
- /**
14
- * Reset the bounding box to its initial state
15
- */
16
- reset() {
17
- this.min.set(1 / 0, 1 / 0, 1 / 0), this.max.set(-1 / 0, -1 / 0, -1 / 0), this.center.set(0, 0, 0), this.halfExtents.set(0, 0, 0);
18
- }
19
- /**
20
- * Expand the bounding box to include the given point
21
- * @param point Point to include in the bounding box
22
- */
23
- expandByPoint(t) {
24
- this.min.x = Math.min(this.min.x, t.x), this.min.y = Math.min(this.min.y, t.y), this.min.z = Math.min(this.min.z, t.z), this.max.x = Math.max(this.max.x, t.x), this.max.y = Math.max(this.max.y, t.y), this.max.z = Math.max(this.max.z, t.z), this.updateDerived();
25
- }
26
- /**
27
- * Expand this bounding box to include another bounding box
28
- * @param box Bounding box to include
29
- */
30
- expandByBox(t) {
31
- this.min.x = Math.min(this.min.x, t.min.x), this.min.y = Math.min(this.min.y, t.min.y), this.min.z = Math.min(this.min.z, t.min.z), this.max.x = Math.max(this.max.x, t.max.x), this.max.y = Math.max(this.max.y, t.max.y), this.max.z = Math.max(this.max.z, t.max.z), this.updateDerived();
32
- }
33
- /**
34
- * Update the center and half extents based on min/max
35
- */
36
- updateDerived() {
37
- this.center.addVectors(this.min, this.max).multiplyScalar(0.5), this.halfExtents.subVectors(this.max, this.min).multiplyScalar(0.5);
38
- }
39
- /**
40
- * Check if this box contains a point
41
- * @param point Point to check
42
- * @returns True if the point is inside the box
43
- */
44
- containsPoint(t) {
45
- return t.x >= this.min.x && t.x <= this.max.x && t.y >= this.min.y && t.y <= this.max.y && t.z >= this.min.z && t.z <= this.max.z;
46
- }
47
- /**
48
- * Create a Three.js Box3 from this bounding box
49
- * @returns THREE.Box3 representation
50
- */
51
- toBox3() {
52
- return new i.Box3().set(this.min, this.max);
53
- }
54
- /**
55
- * Create a clone of this bounding box
56
- * @returns New bounding box with the same values
57
- */
58
- clone() {
59
- const t = new et();
60
- return t.min.copy(this.min), t.max.copy(this.max), t.center.copy(this.center), t.halfExtents.copy(this.halfExtents), t;
61
- }
62
- }
63
- class ut {
64
- // TODO: there is no sh spherical harmonics
65
- constructor(t = 0) {
66
- f(this, "numSplats", 0);
67
- f(this, "positions");
68
- f(this, "rotations");
69
- f(this, "scales");
70
- f(this, "colors");
71
- f(this, "opacities");
72
- f(this, "centers");
73
- f(this, "boundingBox", new et());
74
- this.numSplats = t, this.allocateBuffers(t);
75
- }
76
- allocateBuffers(t) {
77
- this.positions = new Float32Array(t * 3), this.rotations = new Float32Array(t * 4), this.scales = new Float32Array(t * 3), this.colors = new Float32Array(t * 3), this.opacities = new Float32Array(t), this.centers = new Float32Array(t * 3);
78
- }
79
- /**
80
- * Set data for a specific splat
81
- * @param index Splat index
82
- * @param position Position vector
83
- * @param rotation Quaternion
84
- * @param scale Scale vector (expects LOG SCALE)
85
- * @param color Color
86
- * @param opacity Opacity value
87
- */
88
- setSplat(t, n, e, r, s, o) {
89
- if (t >= this.numSplats)
90
- throw new Error(
91
- `Splat index out of bounds: ${t} >= ${this.numSplats}`
92
- );
93
- const a = t * 3, c = t * 4, h = t * 3, v = t * 3;
94
- this.positions[a] = n.x, this.positions[a + 1] = n.y, this.positions[a + 2] = n.z, this.rotations[c] = e.x, this.rotations[c + 1] = e.y, this.rotations[c + 2] = e.z, this.rotations[c + 3] = e.w, this.scales[h] = r.x, this.scales[h + 1] = r.y, this.scales[h + 2] = r.z, this.colors[v] = s.r, this.colors[v + 1] = s.g, this.colors[v + 2] = s.b, this.opacities[t] = o, this.centers[a] = n.x, this.centers[a + 1] = n.y, this.centers[a + 2] = n.z;
95
- }
96
- /**
97
- * Get a splat's data
98
- * @param index Splat index
99
- * @returns Object containing splat data (linear scale)
100
- */
101
- getSplat(t) {
102
- if (t >= this.numSplats)
103
- throw new Error(
104
- `Splat index out of bounds: ${t} >= ${this.numSplats}`
105
- );
106
- const n = t * 3, e = t * 4, r = t * 3, s = t * 3;
107
- return {
108
- position: new i.Vector3(
109
- this.positions[n],
110
- this.positions[n + 1],
111
- this.positions[n + 2]
112
- ),
113
- rotation: new i.Quaternion(
114
- this.rotations[e],
115
- this.rotations[e + 1],
116
- this.rotations[e + 2],
117
- this.rotations[e + 3]
118
- ),
119
- // Convert log scale back to linear scale for external use
120
- scale: new i.Vector3(
121
- Math.exp(this.scales[r]),
122
- Math.exp(this.scales[r + 1]),
123
- Math.exp(this.scales[r + 2])
124
- ),
125
- color: new i.Color(
126
- this.colors[s],
127
- this.colors[s + 1],
128
- this.colors[s + 2]
129
- ),
130
- opacity: this.opacities[t]
131
- };
132
- }
133
- /**
134
- * Calculate the bounding box for all splats
135
- * NOTE: Currently it only uses positions, not the actual splat bounds
136
- */
137
- calculateBoundingBox() {
138
- this.boundingBox.reset();
139
- const t = new i.Vector3();
140
- for (let n = 0; n < this.numSplats; n++) {
141
- const e = n * 3;
142
- t.set(
143
- this.positions[e],
144
- this.positions[e + 1],
145
- this.positions[e + 2]
146
- ), this.boundingBox.expandByPoint(t);
147
- }
148
- return this.boundingBox;
149
- }
150
- /**
151
- * Create a Three.js BufferGeometry from this splat data
152
- * This is for visualization/debugging purposes only, not for rendering
153
- */
154
- createDebugGeometry() {
155
- const t = new i.BufferGeometry();
156
- t.setAttribute(
157
- "position",
158
- new i.BufferAttribute(this.positions, 3)
159
- );
160
- const n = new Float32Array(this.numSplats * 3), e = new i.Quaternion(), r = new i.Euler();
161
- for (let s = 0; s < this.numSplats; s++) {
162
- const o = s * 4, a = s * 3;
163
- e.set(
164
- this.rotations[o],
165
- this.rotations[o + 1],
166
- this.rotations[o + 2],
167
- this.rotations[o + 3]
168
- ), r.setFromQuaternion(e), n[a] = r.x, n[a + 1] = r.y, n[a + 2] = r.z;
169
- }
170
- return t.setAttribute(
171
- "rotation",
172
- new i.BufferAttribute(n, 3)
173
- ), t.setAttribute(
174
- "scale",
175
- new i.BufferAttribute(this.scales, 3)
176
- ), t.setAttribute(
177
- "color",
178
- new i.BufferAttribute(this.colors, 3)
179
- ), t.setAttribute(
180
- "opacity",
181
- new i.BufferAttribute(this.opacities, 1)
182
- ), t;
183
- }
184
- }
185
- class dt extends i.EventDispatcher {
186
- constructor() {
187
- super();
188
- f(this, "worker");
189
- f(this, "centers", null);
190
- f(this, "orderTexture", null);
191
- /** Bounding box data for optimization */
192
- f(this, "chunks", null);
193
- f(this, "lastCameraPosition", new i.Vector3());
194
- f(this, "lastCameraDirection", new i.Vector3());
195
- const n = this.createWorkerCode(), e = new Blob([n], { type: "application/javascript" });
196
- this.worker = new Worker(URL.createObjectURL(e)), this.worker.onmessage = this.onWorkerMessage.bind(this);
197
- }
198
- /**
199
- * Handles messages received from the sorting worker.
200
- * @param event The message event from the worker.
201
- */
202
- onWorkerMessage(n) {
203
- if (!this.orderTexture || !this.orderTexture.image)
204
- return console.error("SplatSorter: Order texture not initialized!");
205
- const { order: e, count: r } = n.data, s = this.orderTexture.image.data;
206
- if (!(s instanceof Uint32Array))
207
- return console.error(
208
- "SplatSorter: Order texture data is not a Uint32Array!"
209
- );
210
- s.set(new Uint32Array(e)), this.orderTexture.needsUpdate = !0;
211
- const o = s.buffer.slice(0), a = { order: o };
212
- this.worker.postMessage(a, [o]), this.dispatchEvent({ type: "updated", count: r });
213
- }
214
- /**
215
- * Initializes the sorter with necessary data and textures.
216
- * @param orderTexture The THREE.DataTexture (R32UI) to store the sorted splat indices.
217
- * @param centers A Float32Array containing the center position (x, y, z) for each splat.
218
- * @param chunks Optional: A Float32Array containing bounding box chunk data [minX, minY, minZ, maxX, maxY, maxZ, ...] for optimization.
219
- */
220
- init(n, e, r) {
221
- if (!n || !(n.image.data instanceof Uint32Array))
222
- throw new Error("SplatSorter: Invalid orderTexture provided. Must be DataTexture with Uint32Array data.");
223
- if (!e || e.length % 3 !== 0)
224
- throw new Error("SplatSorter: Invalid centers array provided. Length must be multiple of 3.");
225
- if (n.image.data.length < e.length / 3)
226
- throw new Error("SplatSorter: orderTexture data buffer is smaller than the number of splats.");
227
- const s = e.length / 3;
228
- this.orderTexture = n, this.centers = e.slice();
229
- const o = this.orderTexture.image.data;
230
- for (let y = 0; y < s; y++) o[y] = y;
231
- this.orderTexture.needsUpdate = !0;
232
- const a = o.buffer.slice(0), c = this.centers.buffer.slice(0), h = {
233
- order: a,
234
- centers: c
235
- }, v = [
236
- a,
237
- c
238
- ];
239
- if (r) {
240
- this.chunks = r.slice();
241
- const y = this.chunks.buffer.slice(0);
242
- h.chunks = y, v.push(y);
243
- }
244
- this.worker.postMessage(h, v);
245
- }
246
- /**
247
- * Applies an optional mapping to filter or reorder splats before sorting.
248
- * The sorter will only consider splats whose original indices are present in the mapping.
249
- * @param mapping A Uint32Array where each element is the *original* index of a splat to include, or null to reset mapping.
250
- */
251
- setMapping(n) {
252
- if (!this.centers)
253
- return console.warn(
254
- "SplatSorter: Cannot set mapping before initialization."
255
- );
256
- let e;
257
- const r = [];
258
- if (!n) {
259
- const c = this.centers.buffer.slice(0);
260
- return e = {
261
- centers: c,
262
- mapping: null
263
- }, r.push(c), this.worker.postMessage(e, r);
264
- }
265
- const s = new Float32Array(n.length * 3);
266
- for (let c = 0; c < n.length; c++) {
267
- const h = n[c];
268
- if (h * 3 + 2 >= this.centers.length) {
269
- console.warn(
270
- `SplatSorter: Mapping index ${h} out of bounds.`
271
- );
272
- continue;
273
- }
274
- const v = h * 3, y = c * 3;
275
- s[y + 0] = this.centers[v + 0], s[y + 1] = this.centers[v + 1], s[y + 2] = this.centers[v + 2];
276
- }
277
- const o = s.buffer.slice(0), a = n.buffer.slice(0);
278
- e = {
279
- centers: o,
280
- mapping: a
281
- }, r.push(o, a), this.worker.postMessage(e, r);
282
- }
283
- /**
284
- * Updates the camera parameters used for sorting.
285
- * @param position The camera's position in the sorter's local coordinate space.
286
- * @param direction The camera's forward direction in the sorter's local coordinate space.
287
- */
288
- setCamera(n, e) {
289
- const r = this.lastCameraPosition.distanceToSquared(n) > 1e-7, s = this.lastCameraDirection.dot(e) < 0.9999;
290
- if (!r && !s)
291
- return;
292
- this.lastCameraPosition.copy(n), this.lastCameraDirection.copy(e);
293
- const o = {
294
- cameraPosition: { x: n.x, y: n.y, z: n.z },
295
- cameraDirection: { x: e.x, y: e.y, z: e.z }
296
- };
297
- this.worker.postMessage(o);
298
- }
299
- /**
300
- * Terminates the Web Worker and cleans up resources.
301
- */
302
- dispose() {
303
- this.worker && this.worker.terminate(), this.orderTexture = null, this.centers = null, this.chunks = null;
304
- }
305
- /**
306
- * Creates the self-contained code for the sorting Web Worker.
307
- * @returns A string containing the JavaScript code for the worker.
308
- */
309
- createWorkerCode() {
310
- return `(${(function() {
311
- let e = null, r = null, s = null, o = null, a = null, c = null, h = !1;
312
- const v = { x: 0, y: 0, z: 0 }, y = { x: 0, y: 0, z: 0 }, p = { x: 0, y: 0, z: 0 }, u = { x: 0, y: 0, z: 0 };
313
- let l = null, b = null;
314
- const B = 32, O = new Array(B).fill(0), q = new Array(B).fill(0), E = new Array(B).fill(0), R = (F, S, D) => {
315
- for (; F <= S; ) {
316
- const M = S + F >> 1, m = D(M);
317
- if (m > 0) F = M + 1;
318
- else if (m < 0) S = M - 1;
319
- else return M;
320
- }
321
- return ~F;
322
- }, W = () => {
323
- if (!e || !r || !a || !c)
324
- return;
325
- if (r.length === 0) {
326
- const g = {
327
- order: e.buffer,
328
- count: 0
329
- };
330
- self.postMessage(g, [e.buffer]), e = null;
331
- return;
332
- }
333
- const F = a.x, S = a.y, D = a.z, M = c.x, m = c.y, C = c.z, _ = 1e-4, V = Math.abs(F - v.x) > _ || Math.abs(S - v.y) > _ || Math.abs(D - v.z) > _, x = Math.abs(M - y.x) > _ || Math.abs(m - y.y) > _ || Math.abs(C - y.z) > _;
334
- if (!h && !V && !x)
335
- return;
336
- h = !1, v.x = F, v.y = S, v.z = D, y.x = M, y.y = m, y.z = C;
337
- let d = 1 / 0, z = -1 / 0;
338
- for (let g = 0; g < 8; ++g) {
339
- const k = g & 1 ? p.x : u.x, U = g & 2 ? p.y : u.y, w = g & 4 ? p.z : u.z, P = k * M + U * m + w * C;
340
- d = Math.min(d, P), z = Math.max(z, P);
341
- }
342
- const T = r.length / 3, L = z - d, I = (1 << Math.max(
343
- 10,
344
- Math.min(20, Math.ceil(Math.log2(T / 4)))
345
- )) + 1;
346
- if ((!l || l.length !== T) && (l = new Uint32Array(T)), !b || b.length !== I ? b = new Uint32Array(I) : b.fill(0), L < 1e-7) {
347
- for (let g = 0; g < T; ++g) l[g] = 0;
348
- b[0] = T;
349
- } else if (s && s.length > 0) {
350
- const g = s.length / 6;
351
- O.fill(0);
352
- for (let w = 0; w < g; ++w) {
353
- const P = w * 6, Z = s[P + 0], G = s[P + 1], $ = s[P + 2], H = s[P + 3], Y = Z * M + G * m + $ * C - d, J = Y - H, X = Y + H, Q = Math.max(
354
- 0,
355
- Math.floor(J * B / L)
356
- ), tt = Math.min(
357
- B,
358
- Math.ceil(X * B / L)
359
- );
360
- for (let N = Q; N < tt; ++N)
361
- O[N]++;
362
- }
363
- let k = 0;
364
- for (let w = 0; w < B; ++w) k += O[w];
365
- E[0] = 0, q[0] = 0;
366
- for (let w = 1; w < B; ++w)
367
- E[w - 1] = O[w - 1] / k * I >>> 0, q[w] = q[w - 1] + E[w - 1];
368
- E[B - 1] = O[B - 1] / k * I >>> 0;
369
- const U = L / B;
370
- for (let w = 0; w < T; ++w) {
371
- const P = w * 3, Z = r[P + 0], G = r[P + 1], $ = r[P + 2], H = Z * M + G * m + $ * C, J = (z - H) / U, X = Math.max(
372
- 0,
373
- Math.min(
374
- B - 1,
375
- Math.floor(J)
376
- )
377
- ), Q = J - X, tt = q[X] + E[X] * Q >>> 0, N = Math.min(tt, I - 1);
378
- l[w] = N, b[N]++;
379
- }
380
- } else {
381
- const g = (I - 1) / L;
382
- for (let k = 0; k < T; ++k) {
383
- const U = k * 3, w = r[U + 0], P = r[U + 1], Z = r[U + 2], G = w * M + P * m + Z * C, H = (z - G) * g >>> 0, Y = Math.min(H, I - 1);
384
- l[k] = Y, b[Y]++;
385
- }
386
- }
387
- for (let g = 1; g < I; g++)
388
- b[g] += b[g - 1];
389
- for (let g = T - 1; g >= 0; g--) {
390
- const k = l[g], U = --b[k];
391
- e[U] = o ? o[g] : g;
392
- }
393
- const at = F * M + S * m + D * C, rt = (g) => {
394
- if (!e) return -1 / 0;
395
- const k = e[g], U = k;
396
- if (!r || U * 3 + 2 >= r.length)
397
- return -1 / 0;
398
- const w = U * 3;
399
- return r[w] * M + r[w + 1] * m + r[w + 2] * C - at;
400
- };
401
- let st = T;
402
- if (T > 0 && rt(T - 1) < 0) {
403
- const g = R(
404
- 0,
405
- T - 1,
406
- rt
407
- );
408
- st = g < 0 ? ~g : g;
409
- }
410
- const ct = {
411
- order: e.buffer,
412
- count: st
413
- };
414
- self.postMessage(ct, [e.buffer]), e = null;
415
- };
416
- self.onmessage = (F) => {
417
- const S = F.data;
418
- S.order && (e = new Uint32Array(S.order));
419
- let D = !1;
420
- if (S.centers && (r = new Float32Array(S.centers), D = !0, h = !0), Object.prototype.hasOwnProperty.call(S, "mapping") && (o = S.mapping ? new Uint32Array(S.mapping) : null, h = !0), S.chunks) {
421
- if (s = new Float32Array(S.chunks), s.length > 0 && s[3] > 0)
422
- for (let M = 0; M < s.length / 6; ++M) {
423
- const m = M * 6, C = s[m + 0], _ = s[m + 1], V = s[m + 2], x = s[m + 3], d = s[m + 4], z = s[m + 5];
424
- s[m + 0] = (C + x) * 0.5, s[m + 1] = (_ + d) * 0.5, s[m + 2] = (V + z) * 0.5, s[m + 3] = Math.sqrt(
425
- (x - C) ** 2 + (d - _) ** 2 + (z - V) ** 2
426
- ) * 0.5;
427
- }
428
- h = !0;
429
- }
430
- if (D && r && r.length > 0) {
431
- p.x = u.x = r[0], p.y = u.y = r[1], p.z = u.z = r[2];
432
- for (let M = 1; M < r.length / 3; M++) {
433
- const m = M * 3;
434
- p.x = Math.min(p.x, r[m + 0]), u.x = Math.max(u.x, r[m + 0]), p.y = Math.min(p.y, r[m + 1]), u.y = Math.max(u.y, r[m + 1]), p.z = Math.min(p.z, r[m + 2]), u.z = Math.max(u.z, r[m + 2]);
435
- }
436
- } else D && r && r.length === 0 && (p.x = u.x = p.y = u.y = p.z = u.z = 0);
437
- S.cameraPosition && (a = S.cameraPosition), S.cameraDirection && (c = S.cameraDirection), W();
438
- };
439
- }).toString()})();`;
440
- }
441
- }
442
- const ft = (A, t) => {
443
- const n = nt(A), e = nt(t);
444
- return n | e << 16;
445
- };
446
- function nt(A) {
447
- const t = new Float32Array([A]), e = new Int32Array(t.buffer)[0];
448
- let r = e >> 16 & 32768, s = e >> 12 & 2047;
449
- const o = e >> 23 & 255;
450
- return o < 103 ? r : o > 142 ? (r |= 31744, r |= (o === 255 ? 0 : 1) && e & 8388607, r) : o < 113 ? (s |= 2048, r |= (s >> 114 - o) + (s >> 113 - o & 1), r) : (r |= o - 112 << 10 | s >> 1, r += s & 1, r);
451
- }
452
- const pt = new ArrayBuffer(4), ot = new DataView(pt), mt = (A) => (ot.setUint32(0, A, !0), ot.getFloat32(0, !0));
453
- class xt {
454
- /**
455
- * Create a new TextureManager for a set of splats
456
- * @param splatData The splat data to manage textures for
457
- */
458
- constructor(t) {
459
- f(this, "transformA");
460
- // position xyz and rotation quaternion y,z components
461
- f(this, "transformB");
462
- // rotation quaternion x and scale xyz
463
- f(this, "colorTexture");
464
- // color an opacity
465
- f(this, "orderTexture");
466
- f(this, "textureWidth");
467
- f(this, "textureHeight");
468
- const n = t.numSplats;
469
- this.textureWidth = Math.ceil(Math.sqrt(n)), this.textureHeight = Math.ceil(n / this.textureWidth), this.transformA = this.createTransformATexture(t), this.transformB = this.createTransformBTexture(t), this.colorTexture = this.createColorTexture(t), this.orderTexture = this.createOrderTexture(n);
470
- }
471
- /**
472
- * Create the transform A texture (positions and quaternion w component)
473
- * @param splatData The splat data
474
- * @returns DataTexture containing position data
475
- */
476
- createTransformATexture(t) {
477
- const n = t.numSplats, e = new Float32Array(
478
- this.textureWidth * this.textureHeight * 4
479
- );
480
- for (let s = 0; s < n; s++) {
481
- const o = s * 4, a = s * 3, c = s * 4;
482
- e[o] = t.positions[a], e[o + 1] = t.positions[a + 1], e[o + 2] = t.positions[a + 2];
483
- const h = t.rotations[c + 0], v = t.rotations[c + 1], y = ft(h, v);
484
- e[o + 3] = mt(y);
485
- }
486
- const r = new i.DataTexture(
487
- e,
488
- this.textureWidth,
489
- this.textureHeight,
490
- i.RGBAFormat,
491
- i.FloatType
492
- // Store as Float32, shader will reinterpret bits
493
- );
494
- return r.needsUpdate = !0, r.magFilter = i.NearestFilter, r.minFilter = i.NearestFilter, r;
495
- }
496
- /**
497
- * Create the transform B texture (scale and rotation xyz)
498
- * @param splatData The splat data
499
- * @returns DataTexture containing scale and rotation data
500
- */
501
- createTransformBTexture(t) {
502
- const n = t.numSplats, e = new Float32Array(
503
- this.textureWidth * this.textureHeight * 4
504
- );
505
- for (let s = 0; s < n; s++) {
506
- const o = s * 4, a = s * 3, c = s * 4;
507
- e[o] = t.scales[a], e[o + 1] = t.scales[a + 1], e[o + 2] = t.scales[a + 2], e[o + 3] = t.rotations[c + 2];
508
- }
509
- const r = new i.DataTexture(
510
- e,
511
- this.textureWidth,
512
- this.textureHeight,
513
- i.RGBAFormat,
514
- i.FloatType
515
- );
516
- return r.needsUpdate = !0, r.magFilter = i.NearestFilter, r.minFilter = i.NearestFilter, r;
517
- }
518
- /**
519
- * Create the color texture (RGB and opacity)
520
- * @param splatData The splat data
521
- * @returns DataTexture containing color data
522
- */
523
- createColorTexture(t) {
524
- const n = t.numSplats, e = new Float32Array(
525
- this.textureWidth * this.textureHeight * 4
526
- );
527
- for (let s = 0; s < n; s++) {
528
- const o = s * 4, a = s * 3;
529
- e[o] = t.colors[a], e[o + 1] = t.colors[a + 1], e[o + 2] = t.colors[a + 2], e[o + 3] = t.opacities[s];
530
- }
531
- const r = new i.DataTexture(
532
- e,
533
- this.textureWidth,
534
- this.textureHeight,
535
- i.RGBAFormat,
536
- i.FloatType
537
- );
538
- return r.needsUpdate = !0, r;
539
- }
540
- /**
541
- * Create the order texture for sorting
542
- * @param numSplats Number of splats
543
- * @returns DataTexture for storing order indices
544
- */
545
- createOrderTexture(t) {
546
- const n = new Uint32Array(this.textureWidth * this.textureHeight);
547
- for (let r = 0; r < t; r++)
548
- n[r] = r;
549
- const e = new i.DataTexture(
550
- n,
551
- this.textureWidth,
552
- this.textureHeight,
553
- i.RedIntegerFormat,
554
- i.UnsignedIntType
555
- );
556
- return e.needsUpdate = !0, e;
557
- }
558
- dispose() {
559
- this.transformA.dispose(), this.transformB.dispose(), this.colorTexture.dispose(), this.orderTexture.dispose();
560
- }
561
- }
562
- const gt = (
563
- /* glsl */
564
- `
565
- precision highp float;
566
- precision highp int;
567
- precision highp usampler2D;
568
- precision highp sampler2D;
569
-
570
- // --- Uniforms (Provided by Three.js) ---
571
- // uniform mat4 modelViewMatrix; // Don't redeclare
572
- // uniform mat4 projectionMatrix; // Don't redeclare
573
- uniform vec2 viewport; // Viewport dimensions (width, height)
574
- uniform uint numSplats; // Total number of splats potentially renderable by sorter
575
-
576
- // Textures
577
- uniform highp sampler2D transformA; // vec4: pos.xyz, packed_rot.yz
578
- uniform highp sampler2D transformB; // vec4: log_scale.xyz, rot.x
579
- uniform highp sampler2D splatColor; // vec4: color.rgb, opacity
580
- uniform highp usampler2D splatOrder; // uint: original splat index
581
-
582
- // --- Attributes ---
583
- // Instancing attribute: base index for this block of splats
584
- attribute uint splatInstanceIndex;
585
-
586
- // Per-vertex attribute of the quad (Built-in, don't redeclare 'position')
587
- // attribute vec3 position; // Use the built-in 'position'
588
- // position.xy: corner coords (-1..1)
589
- // position.z: index within the instance block (0..INSTANCE_BUFFER_SIZE-1)
590
-
591
- // --- Varyings ---
592
- varying vec4 vColor;
593
- varying vec2 vUv; // For gaussian calculation in fragment shader
594
-
595
- // --- Constants ---
596
- #define INSTANCE_BUFFER_SIZE 128.0 // Must match the size in SplatMesh
597
-
598
- // --- Helper Functions ---
599
-
600
- // Use GLSL built-in unpackHalf2x16 for proper half-float unpacking
601
-
602
- // Reconstruct quaternion from packed components (xy_packed, z)
603
- // Returns (w,x,y,z) format for quatToMat3 compatibility
604
- vec4 unpackRotation(float xy_packed, float z) {
605
- vec2 xy = unpackHalf2x16(floatBitsToUint(xy_packed));
606
- float x = xy.x;
607
- float y = xy.y;
608
- float w_squared = 1.0 - x*x - y*y - z*z;
609
- float w = (w_squared < 0.0) ? 0.0 : sqrt(w_squared);
610
- return vec4(w, x, y, z); // Return (w,x,y,z)
611
- }
612
-
613
- // Convert quaternion to 3x3 rotation matrix
614
- mat3 quatToMat3(vec4 R) {
615
- vec4 R2 = R + R;
616
- float X = R2.x * R.w;
617
- vec4 Y = R2.y * R;
618
- vec4 Z = R2.z * R;
619
- float W = R2.w * R.w;
620
-
621
- return mat3(
622
- 1.0 - Z.z - W,
623
- Y.z + X,
624
- Y.w - Z.x,
625
- Y.z - X,
626
- 1.0 - Y.y - W,
627
- Z.w + Y.x,
628
- Y.w + Z.x,
629
- Z.w - Y.x,
630
- 1.0 - Y.y - Z.z
631
- );
632
- }
633
-
634
- // Calculate model-space covariance components
635
- void getModelCovariance(vec3 scale, vec4 rotation, out vec3 covA, out vec3 covB) {
636
- mat3 rot = quatToMat3(rotation);
637
-
638
- // M = S * R (scale COLUMNS, then transpose)
639
- mat3 M = transpose(mat3(
640
- scale.x * rot[0], // scale.x * column 0
641
- scale.y * rot[1], // scale.y * column 1
642
- scale.z * rot[2] // scale.z * column 2
643
- ));
644
-
645
- covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2]));
646
- covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2]));
647
- }
648
-
649
- // --- Main Function ---
650
- void main(void) {
651
- // Calculate the final splat index for this vertex
652
- uint instanceOffset = uint(position.z); // Read index within instance from Z
653
- uint orderedSplatIndex = splatInstanceIndex + instanceOffset;
654
-
655
- // Discard if this splat index is beyond the sorted count
656
- if (orderedSplatIndex >= numSplats) {
657
- gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // Off-screen
658
- return;
659
- }
660
-
661
- // --- Source Data Lookup ---
662
- uint texWidth = uint(textureSize(splatOrder, 0).x);
663
- ivec2 orderUV = ivec2(orderedSplatIndex % texWidth, orderedSplatIndex / texWidth);
664
- uint originalSplatIndex = texelFetch(splatOrder, orderUV, 0).r;
665
-
666
- ivec2 dataUV = ivec2(originalSplatIndex % texWidth, originalSplatIndex / texWidth);
667
-
668
- // Fetch data from textures
669
- vec4 texTransformA = texelFetch(transformA, dataUV, 0);
670
- vec4 texTransformB = texelFetch(transformB, dataUV, 0);
671
- vec4 texColor = texelFetch(splatColor, dataUV, 0);
672
-
673
- vec3 splatPosition = texTransformA.xyz;
674
- vec3 splatLogScale = texTransformB.xyz; // Assume stored as log scale
675
- vec4 splatRotation = unpackRotation(texTransformA.w, texTransformB.w); // Unpack rot xy, z
676
- vec3 splatColor = texColor.rgb;
677
- float splatOpacity = texColor.a;
678
-
679
- vec3 splatScale = exp(splatLogScale); // Convert log scale to actual scale
680
-
681
- // --- Center Projection ---
682
-
683
- // Compute normalized view-space center
684
- vec4 centerClipRaw = modelViewMatrix * vec4(splatPosition, 1.0);
685
- vec3 centerView = centerClipRaw.xyz / centerClipRaw.w;
686
-
687
- // Early out if splat is behind the camera
688
- if (centerView.z > -0.2) { // Use small epsilon
689
- gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
690
- return;
691
- }
692
-
693
- // Project to clip space
694
- vec4 centerClip = projectionMatrix * centerClipRaw;
695
-
696
- // --- Covariance Calculation & Projection ---
697
-
698
- // Calculating model space covariance (Vrk)
699
- vec3 covA, covB;
700
- getModelCovariance(splatScale, splatRotation, covA, covB);
701
- mat3 Vrk = mat3(
702
- covA.x, covA.y, covA.z,
703
- covA.y, covB.x, covB.y, // covB.x is Vrk[1][1]
704
- covA.z, covB.y, covB.z // covB.y is Vrk[1][2], covB.z is Vrk[2][2]
705
- );
706
-
707
- // Calculate Jacobian J (screen space change wrt view space change)
708
- // Requres focal lenghts and view-space center depth (tz)
709
- float focalX = viewport.x * projectionMatrix[0][0];
710
- float focalY = viewport.y * projectionMatrix[1][1];
711
- float tz = centerView.z;
712
- float tz2 = tz * tz;
713
-
714
- // Jacobian J = [fx/tz, 0, -fx*tx/tz^2]
715
- // [0, fy/tz, -fy*ty/tz^2]
716
- mat3 J = mat3(
717
- focalX / tz, 0.0, -focalX * centerView.x / tz2,
718
- 0.0, focalY / tz, -focalY * centerView.y / tz2,
719
- 0.0, 0.0, 0.0
720
- );
721
-
722
- // Calculate W
723
- mat3 W = transpose(mat3(modelViewMatrix));
724
- // Calculate T = W * J
725
- mat3 T = W * J;
726
- // Calculate Projected 2D Covariance: SigmaProj = transpose(T) * Vrk * T
727
- mat3 SigmaProj = transpose(T) * Vrk * T;
728
-
729
- // Extract 2D components and add bias
730
- float cov2D_11 = SigmaProj[0][0] + 0.3;
731
- float cov2D_12 = SigmaProj[0][1];
732
- float cov2D_22 = SigmaProj[1][1] + 0.3;
733
-
734
- // --- Calculate 2D Screen Space Rotation & Scale ---
735
-
736
- float det = cov2D_11 * cov2D_22 - cov2D_12 * cov2D_12;
737
- // Ensure determinant is non-negative before sqrt
738
- if (det <= 0.0) {
739
- gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // Discard degenerated
740
- return;
741
- }
742
-
743
- float trace = cov2D_11 + cov2D_22;
744
- float traceOver2 = 0.5 * trace;
745
- float discriminantSqrt = sqrt(max(traceOver2 * traceOver2 - det, 0.0)); // Avoid sqrt(negative)
746
-
747
- float lambda1 = traceOver2 + discriminantSqrt; // Larger eigenvalue
748
- float lambda2 = max(0.1, traceOver2 - discriminantSqrt); // Smaller eigenvalue, clamped
749
-
750
- // Compute eigenvectors
751
-
752
- vec2 v1_eigen, v2_eigen;
753
-
754
- // Handle diagonal case
755
- if(abs(cov2D_12) < 1e-16) {
756
- v1_eigen = vec2(1.0, 0.0);
757
- } else {
758
- v1_eigen = normalize(vec2(cov2D_12, lambda1 - cov2D_11)); // diagonal choice
759
- }
760
-
761
- v2_eigen = vec2(-v1_eigen.y, v1_eigen.x); // Perpendicular eigenvector
762
-
763
- // Calculate SCALED vectors (l1, l2, incorparate factor)
764
- float scaleFactor = 2.0 * sqrt(2.0); // ~2.8284
765
- float l1 = sqrt(lambda1) * scaleFactor; // scaleX
766
- float l2 = sqrt(lambda2) * scaleFactor; // scaleY
767
-
768
- // Early out tiny splats
769
- if (l1 < 2.0 && l2 < 2.0) { // Check if smaller than ~2 pixel
770
- gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
771
- return;
772
- }
773
-
774
- // Scaled eigenvectors for offset calculation
775
- vec2 v1_scaled = l1 * v1_eigen;
776
- vec2 v2_scaled = l2 * v2_eigen;
777
-
778
- // --- FRUSTUM CHECK ---
779
-
780
- vec2 clipRadius = vec2(max(l1, l2)) * (centerClip.w / viewport);
781
-
782
- // Check if the bounding circle's edge is outside the [-w, w] range in clip space for x or y
783
- if (any(greaterThan(abs(centerClip.xy) + clipRadius, vec2(abs(centerClip.w))))) {
784
- gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // Off-screen
785
- return;
786
- }
787
-
788
- // --- END FRUSTUM CHECK ---
789
-
790
- // --- Final Vertex Position ---
791
-
792
- vec2 cornerOffset = position.xy; // (-1,-1) to (1,1)
793
-
794
- // Clip the quad so only high-alpha core is visible
795
- float alpha = max(splatOpacity, 1e-6); // avoid log(0)
796
- float clip = min(1.0, sqrt(-log(1.0 / 255.0 / alpha)) / 2.0);
797
-
798
- // Apply clip to the corner offset *before* calculating screen space offset
799
- vec2 clippedCornerOffset = cornerOffset * clip;
800
- vec2 screenOffsetPixels = clippedCornerOffset.x * v1_scaled + clippedCornerOffset.y * v2_scaled;
801
-
802
- // Convert pixel offset to clip space offset
803
- vec2 clipOffset = screenOffsetPixels * (centerClip.w / viewport);
804
-
805
-
806
- // Apply offset to center clip position
807
- gl_Position = centerClip + vec4(clipOffset, 0.0, 0.0);
808
-
809
- // --- Pass data to Fragment Shader ---
810
-
811
- vColor = vec4(splatColor, splatOpacity);
812
- vUv = clippedCornerOffset;
813
- }
814
- `
815
- ), yt = (
816
- /* glsl */
817
- `
818
- precision highp float;
819
-
820
- varying vec4 vColor; // Color and opacity passed from vertex shader
821
- varying vec2 vUv; // Quad UV coordinates (-1 to 1) passed from vertex shader
822
-
823
- void main(void) {
824
-
825
- float distSq = dot(vUv, vUv); // Calculate squared distance from center (in the quad's coordinate system)
826
- if (distSq > 1.0) discard; // Discard fragments outside the circle inscribed in the quad
827
-
828
- // Calculate Gaussian function: alpha = opacity * exp(-distSq * factor)
829
- // The factor 4.0 corresponds to the original implementation's scaling.
830
- // factor = 1 / (2 * sigma^2), where sigma controls the spread.
831
- // Using 4.0 implies sigma^2 = 1/8.
832
- float alpha = exp(-distSq * 4.0) * vColor.a;
833
-
834
- if (alpha < 1.0 / 255.0) discard; // Discard fragments with very low alpha
835
-
836
- // Premultiply color by alpha (required for correct blending)
837
- gl_FragColor = vec4(vColor.rgb * alpha, alpha);
838
- }
839
- `
840
- );
841
- class vt extends i.ShaderMaterial {
842
- constructor(t = {}) {
843
- const n = {
844
- // Textures (values set via methods)
845
- transformA: { value: null },
846
- transformB: { value: null },
847
- splatColor: { value: null },
848
- splatOrder: { value: null },
849
- // Other uniforms
850
- viewport: { value: new i.Vector2(1, 1) },
851
- // Will be updated
852
- numSplats: { value: 0 }
853
- // Max splats to render (updated by sorter)
854
- };
855
- super({
856
- vertexShader: gt,
857
- fragmentShader: yt,
858
- uniforms: n,
859
- transparent: !0,
860
- blending: i.CustomBlending,
861
- // Premultiplied alpha blending:
862
- // color = src_color * src_alpha + dst_color * (1 - src_alpha)
863
- // alpha = src_alpha * 1 + dst_alpha * (1 - src_alpha)
864
- blendSrc: i.OneFactor,
865
- // Using ONE because shader outputs premultiplied color (color * alpha)
866
- blendDst: i.OneMinusSrcAlphaFactor,
867
- blendSrcAlpha: i.OneFactor,
868
- // source alpha comes from shader
869
- blendDstAlpha: i.OneMinusSrcAlphaFactor,
870
- blendEquation: i.AddEquation,
871
- blendEquationAlpha: i.AddEquation,
872
- depthTest: !0,
873
- depthWrite: !1,
874
- // Disable depth write for transparency
875
- side: i.DoubleSide,
876
- // Render both sides (or CULLFACE_NONE equivalent)
877
- // Optional settings from constructor
878
- alphaTest: t.alphaTest !== void 0 ? t.alphaTest : 0,
879
- // Typically 0 for blending
880
- toneMapped: t.toneMapped !== void 0 ? t.toneMapped : !1
881
- // prettier-ignore
882
- }), t.alphaHash && (this.alphaHash = !0, this.depthWrite = !0, this.blending = i.NoBlending);
883
- }
884
- /**
885
- * Update the viewport size
886
- * @param width Viewport width
887
- * @param height Viewport height
888
- */
889
- updateViewport(t, n) {
890
- this.uniforms.viewport.value.set(t, n);
891
- }
892
- /**
893
- * Set transform texture A (positions)
894
- * @param texture Texture containing positions
895
- */
896
- setTransformA(t) {
897
- this.uniforms.transformA.value = t;
898
- }
899
- /**
900
- * Set transform texture B (rotation, scale)
901
- * @param texture Texture containing rotation and scale data
902
- */
903
- setTransformB(t) {
904
- this.uniforms.transformB.value = t;
905
- }
906
- /**
907
- * Set color texture
908
- * @param texture Texture containing colors
909
- */
910
- setColorTexture(t) {
911
- this.uniforms.splatColor.value = t;
912
- }
913
- /**
914
- * Set order texture
915
- * @param texture Texture containing sort order
916
- */
917
- setOrderTexture(t) {
918
- this.uniforms.splatOrder.value = t;
919
- }
920
- /**
921
- * Set number of splats to render
922
- * @param count Number of splats
923
- */
924
- setNumSplats(t) {
925
- this.uniforms.numSplats.value = t;
926
- }
927
- }
928
- const j = class j extends i.Mesh {
929
- // Match shader constant
930
- /**
931
- * Create a new SplatMesh for rendering Gaussian splats
932
- * @param splatData The splat data to render
933
- * @param options Rendering options
934
- */
935
- constructor(n, e = {}) {
936
- const r = new vt(e), s = j.createInstancedGeometry(n.numSplats, j.INSTANCE_SIZE);
937
- super(s, r);
938
- f(this, "sorter");
939
- f(this, "splatData");
940
- f(this, "options");
941
- f(this, "textureManager");
942
- f(this, "material");
943
- f(this, "geometry");
944
- f(this, "lastCameraPositionLocal", new i.Vector3());
945
- f(this, "lastCameraDirectionLocal", new i.Vector3());
946
- f(this, "invModelMatrix", new i.Matrix4());
947
- this.geometry = s, this.material = r, this.splatData = n, this.frustumCulled = !1, this.options = { autoSort: !0, ...e }, this.textureManager = new xt(n), this.sorter = new dt();
948
- let o = this.createChunks() || void 0;
949
- o === null && console.warn("Visus: Could not create sorter chunks, bounding box might be invalid."), o = void 0, this.sorter.init(
950
- this.textureManager.orderTexture,
951
- this.splatData.centers,
952
- o ?? void 0
953
- ), this.sorter.addEventListener(
954
- "updated",
955
- (a) => {
956
- const c = a.count;
957
- this.geometry.instanceCount = Math.ceil(c / j.INSTANCE_SIZE), this.material.setNumSplats(c);
958
- }
959
- ), this.material.setTransformA(this.textureManager.transformA), this.material.setTransformB(this.textureManager.transformB), this.material.setColorTexture(this.textureManager.colorTexture), this.material.setOrderTexture(this.textureManager.orderTexture), this.material.setNumSplats(0), this.geometry.boundingBox = n.boundingBox.toBox3(), this.geometry.boundingSphere = new i.Sphere(), this.geometry.boundingBox.getBoundingSphere(this.geometry.boundingSphere);
960
- }
961
- /**
962
- * Creates the instanced geometry for rendering splats.
963
- * @param totalSplats Total number of splats in the data.
964
- * @param instanceSize Number of splats per instance.
965
- * @returns InstancedBufferGeometry
966
- */
967
- static createInstancedGeometry(n, e) {
968
- const r = Math.ceil(n / e), s = new i.BufferGeometry(), o = new Float32Array([
969
- // x, y, splat_index_in_instance
970
- -1,
971
- -1,
972
- 0,
973
- 1,
974
- -1,
975
- 0,
976
- 1,
977
- 1,
978
- 0,
979
- -1,
980
- 1,
981
- 0
982
- ]), a = new Uint16Array([0, 1, 2, 0, 2, 3]), c = new Float32Array(4 * 3 * e);
983
- for (let p = 0; p < e; p++) {
984
- const u = p * 4 * 3;
985
- for (let l = 0; l < 4; l++)
986
- c[u + l * 3 + 0] = o[l * 3 + 0], c[u + l * 3 + 1] = o[l * 3 + 1], c[u + l * 3 + 2] = p;
987
- }
988
- const h = new Uint32Array(6 * e);
989
- for (let p = 0; p < e; p++) {
990
- const u = p * 6, l = p * 4;
991
- h[u + 0] = a[0] + l, h[u + 1] = a[1] + l, h[u + 2] = a[2] + l, h[u + 3] = a[3] + l, h[u + 4] = a[4] + l, h[u + 5] = a[5] + l;
992
- }
993
- s.setAttribute("position", new i.BufferAttribute(c, 3)), s.setIndex(new i.BufferAttribute(h, 1));
994
- const v = new i.InstancedBufferGeometry();
995
- v.index = s.index, v.setAttribute("position", s.getAttribute("position"));
996
- const y = new Uint32Array(r);
997
- for (let p = 0; p < r; p++)
998
- y[p] = p * e;
999
- return v.setAttribute("splatInstanceIndex", new i.InstancedBufferAttribute(y, 1, !1)), v.instanceCount = 0, v;
1000
- }
1001
- /**
1002
- * Create chunks data (bounding box min/max) for the sorter.
1003
- * @returns Float32Array containing chunk data [minX, minY, minZ, maxX, maxY, maxZ] or null.
1004
- */
1005
- createChunks() {
1006
- const n = this.splatData.boundingBox;
1007
- return n.min.x === 1 / 0 || n.max.x === -1 / 0 ? null : new Float32Array([
1008
- n.min.x,
1009
- n.min.y,
1010
- n.min.z,
1011
- n.max.x,
1012
- n.max.y,
1013
- n.max.z
1014
- ]);
1015
- }
1016
- /**
1017
- * Update the viewport size
1018
- * @param width Viewport width
1019
- * @param height Viewport height
1020
- */
1021
- updateViewport(n, e) {
1022
- this.material.updateViewport(n, e);
1023
- }
1024
- /**
1025
- * Sorts splats based on camera position and direction.
1026
- * @param camera The camera to sort against.
1027
- */
1028
- sort(n) {
1029
- const e = new i.Vector3(), r = new i.Vector3();
1030
- n.getWorldPosition(e), n.getWorldDirection(r), this.invModelMatrix.copy(this.matrixWorld).invert();
1031
- const s = e.applyMatrix4(this.invModelMatrix), o = r.transformDirection(this.invModelMatrix), a = this.lastCameraPositionLocal.distanceToSquared(s) > 1e-6, c = this.lastCameraDirectionLocal.dot(o) < 0.999;
1032
- this.options.autoSort && (a || c) && (this.lastCameraPositionLocal.copy(s), this.lastCameraDirectionLocal.copy(o), this.sorter.setCamera(s, o));
1033
- }
1034
- /**
1035
- * THREE.js hook called before rendering the object.
1036
- * Used here to trigger sorting and update viewport.
1037
- * @param renderer The renderer
1038
- * @param scene The scene
1039
- * @param camera The camera
1040
- */
1041
- // prettier-ignore
1042
- // @ts-expect-error scene is not used
1043
- onBeforeRender(n, e, r) {
1044
- this.sort(r);
1045
- const s = n.getSize(new i.Vector2());
1046
- let { width: o, height: a } = s;
1047
- const c = n.xr;
1048
- if (c.enabled && c.isPresenting) {
1049
- const h = c.getCamera().cameras[0].view;
1050
- h && (o = h.width, a = h.height);
1051
- }
1052
- this.updateViewport(o, a);
1053
- }
1054
- /**
1055
- * Dispose of resources
1056
- */
1057
- dispose() {
1058
- this.sorter.dispose(), this.geometry.dispose(), this.material.dispose(), this.textureManager.dispose();
1059
- }
1060
- };
1061
- // Cached inverse matrix
1062
- /** Number of splats combined into a single instanced draw call. */
1063
- f(j, "INSTANCE_SIZE", 128);
1064
- let it = j;
1065
- class bt extends i.Loader {
1066
- /**
1067
- * Load a PLY file with Gaussian Splat data
1068
- * @param url URL of the PLY file
1069
- * @param onLoad Optional callback when loading is complete
1070
- * @param onProgress Optional progress callback
1071
- * @param onError Optional error callback
1072
- */
1073
- load(t, n, e, r) {
1074
- const s = new i.FileLoader(this.manager);
1075
- s.setResponseType("arraybuffer"), s.setRequestHeader(this.requestHeader), s.setPath(this.path), s.setWithCredentials(this.withCredentials), s.load(
1076
- t,
1077
- (o) => {
1078
- try {
1079
- if (n) {
1080
- const a = this.parse(o);
1081
- n(a);
1082
- }
1083
- } catch (a) {
1084
- r ? r(a) : console.error(a), this.manager.itemError(t);
1085
- }
1086
- },
1087
- e,
1088
- r
1089
- );
1090
- }
1091
- /**
1092
- * Load a PLY file asynchronously and return a Promise
1093
- * @param url URL of the PLY file
1094
- * @param onProgress Optional progress callback
1095
- * @returns A Promise that resolves with the parsed SplatData
1096
- */
1097
- loadAsync(t, n) {
1098
- return new Promise((e, r) => {
1099
- const s = new i.FileLoader(this.manager);
1100
- s.setResponseType("arraybuffer"), s.setRequestHeader(this.requestHeader), s.setPath(this.path), s.setWithCredentials(this.withCredentials), s.load(
1101
- t,
1102
- (o) => {
1103
- try {
1104
- const a = this.parse(o);
1105
- e(a);
1106
- } catch (a) {
1107
- r(a), this.manager.itemError(t);
1108
- }
1109
- },
1110
- n,
1111
- (o) => {
1112
- r(o), this.manager.itemError(t);
1113
- }
1114
- );
1115
- });
1116
- }
1117
- /**
1118
- * Parse PLY buffer data into SplatData
1119
- * @param buffer ArrayBuffer containing PLY data
1120
- * @returns Parsed SplatData
1121
- */
1122
- parse(t) {
1123
- const n = new TextDecoder(), e = new Uint8Array(t), r = [112, 108, 121, 10], s = `
1124
- end_header
1125
- `;
1126
- for (let x = 0; x < r.length; x++)
1127
- if (e[x] !== r[x])
1128
- throw new Error("Invalid PLY file: Missing magic bytes");
1129
- let o = 0;
1130
- for (let x = 0; x < e.length - s.length; x++) {
1131
- let d = !0;
1132
- for (let z = 0; z < s.length; z++)
1133
- if (e[x + z] !== s.charCodeAt(z)) {
1134
- d = !1;
1135
- break;
1136
- }
1137
- if (d) {
1138
- o = x + s.length;
1139
- break;
1140
- }
1141
- }
1142
- if (o === 0)
1143
- throw new Error("Invalid PLY file: Could not find end of header");
1144
- const c = n.decode(
1145
- e.slice(0, o)
1146
- ).split(`
1147
- `), h = [];
1148
- let v = null;
1149
- for (let x = 1; x < c.length; x++) {
1150
- const d = c[x].trim();
1151
- if (d === "" || d === "end_header") continue;
1152
- const z = d.split(" ");
1153
- switch (z[0]) {
1154
- case "format":
1155
- v = z[1];
1156
- break;
1157
- case "element":
1158
- h.push({
1159
- name: z[1],
1160
- count: parseInt(z[2], 10),
1161
- properties: []
1162
- });
1163
- break;
1164
- case "property":
1165
- if (h.length === 0)
1166
- throw new Error(
1167
- "Invalid PLY file: Property without element"
1168
- );
1169
- h[h.length - 1].properties.push({
1170
- type: z[1],
1171
- name: z[2],
1172
- storage: null
1173
- });
1174
- break;
1175
- }
1176
- }
1177
- if (v !== "binary_little_endian")
1178
- throw new Error(`Unsupported PLY format: ${v}`);
1179
- const y = h.find((x) => x.name === "vertex");
1180
- if (!y)
1181
- throw new Error("Invalid PLY file: No vertex element found");
1182
- const p = new ut(y.count), u = new DataView(t);
1183
- let l = o;
1184
- const b = (x) => y.properties.findIndex((d) => d.name === x), B = b("x"), O = b("y"), q = b("z"), E = [
1185
- b("rot_0"),
1186
- b("rot_1"),
1187
- b("rot_2"),
1188
- b("rot_3")
1189
- ], R = [
1190
- b("scale_0"),
1191
- b("scale_1"),
1192
- b("scale_2")
1193
- ], W = [
1194
- b("f_dc_0"),
1195
- b("f_dc_1"),
1196
- b("f_dc_2")
1197
- ], F = b("opacity");
1198
- if ([
1199
- B,
1200
- O,
1201
- q,
1202
- ...E,
1203
- ...R,
1204
- ...W,
1205
- F
1206
- ].some((x) => x === -1))
1207
- throw new Error("Invalid PLY file: Missing required properties");
1208
- const D = 0.28209479177387814, M = (x) => {
1209
- if (x > 0) return 1 / (1 + Math.exp(-x));
1210
- const d = Math.exp(x);
1211
- return d / (1 + d);
1212
- }, m = new i.Vector3(), C = new i.Quaternion(), _ = new i.Vector3(), V = new i.Color();
1213
- for (let x = 0; x < y.count; x++) {
1214
- const d = [];
1215
- for (let T = 0; T < y.properties.length; T++) {
1216
- const K = y.properties[T].type;
1217
- let I;
1218
- switch (K) {
1219
- case "char":
1220
- I = u.getInt8(l), l += 1;
1221
- break;
1222
- case "uchar":
1223
- I = u.getUint8(l), l += 1;
1224
- break;
1225
- case "short":
1226
- I = u.getInt16(l, !0), l += 2;
1227
- break;
1228
- case "ushort":
1229
- I = u.getUint16(l, !0), l += 2;
1230
- break;
1231
- case "int":
1232
- I = u.getInt32(l, !0), l += 4;
1233
- break;
1234
- case "uint":
1235
- I = u.getUint32(l, !0), l += 4;
1236
- break;
1237
- case "float":
1238
- I = u.getFloat32(l, !0), l += 4;
1239
- break;
1240
- case "double":
1241
- I = u.getFloat64(l, !0), l += 8;
1242
- break;
1243
- default:
1244
- throw new Error(`Unsupported property type: ${K}`);
1245
- }
1246
- d.push(I);
1247
- }
1248
- m.set(
1249
- d[B],
1250
- d[O],
1251
- d[q]
1252
- ), C.set(
1253
- d[E[1]],
1254
- // PLY stores rot 1,2,3,0 (x,y,z,w)
1255
- d[E[2]],
1256
- d[E[3]],
1257
- d[E[0]]
1258
- ).normalize(), C.w < 0 && (C.x = -C.x, C.y = -C.y, C.z = -C.z, C.w = -C.w), _.set(
1259
- d[R[0]],
1260
- // Read directly assuming it's log scale
1261
- d[R[1]],
1262
- d[R[2]]
1263
- ), V.set(
1264
- 0.5 + d[W[0]] * D,
1265
- 0.5 + d[W[1]] * D,
1266
- 0.5 + d[W[2]] * D
1267
- ), V.r = Math.max(0, Math.min(1, V.r)), V.g = Math.max(0, Math.min(1, V.g)), V.b = Math.max(0, Math.min(1, V.b));
1268
- const z = M(d[F]);
1269
- p.setSplat(
1270
- x,
1271
- m,
1272
- C,
1273
- _,
1274
- // Pass log scale directly
1275
- V,
1276
- z
1277
- );
1278
- }
1279
- return p.calculateBoundingBox(), p;
1280
- }
1281
- }
1282
- const Mt = "0.3.0";
1283
- export {
1284
- et as BoundingBox,
1285
- bt as PlyLoader,
1286
- ut as SplatData,
1287
- vt as SplatMaterial,
1288
- it as SplatMesh,
1289
- dt as SplatSorter,
1290
- xt as TextureManager,
1291
- Mt as VERSION
1292
- };