@babylonjs/lite-compat 1.29.0-preview → 1.30.0-preview

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.
@@ -0,0 +1,3511 @@
1
+ import { addToScene, cloneTransformNode, computeAabb, createBox, createCylinder, createDashedLines, createDisc, createExtrudeShape, createGround, createGroundFromHeightMap, createLineMaterial, createLineSystem, createMeshFromData, createPbrMaterial, createPlane, createPolyhedron, createQuatFromRotationMat4, createRibbon, createSolidTexture2D, createSphere, createStandardMaterial, createTorus, createTorusKnot, createTransformNode, createTube, markMaterialUboDirty, maximizeMat4InPlace, normalizeVec2ToRef, projectPointToViewportToRef, rebuildMaterial, removeFromScene, resizeMeshGeometry, scaleBoundsFromCenterToRef, setLineMaterialColor, setMat4Translation, setMeshVisible, setParent, setPbrAnisotropy, setPbrClearCoat, setPbrEmissive, setPbrGammaAlbedo, setPbrIridescence, setPbrSheen, setStandardBumpTexture, setStandardEmissiveTexture, setThinInstanceColors, setThinInstances, updateDashedLines, updateLineSystem, updateMeshUvs, writeMat4FromQuatIntoBuffer } from "@babylonjs/lite";
2
+ //#region src/error.ts
3
+ /**
4
+ * Error thrown when Babylon.js code reaches an API surface that the Babylon Lite
5
+ * compatibility layer cannot (or does not yet) support.
6
+ *
7
+ * The compat layer intentionally favours a loud, discoverable failure over a
8
+ * silent wrong result: if a ported scene hits one of these, the porting gap is
9
+ * surfaced immediately with a pointer to the reason and (where relevant) the
10
+ * native Lite API to use instead.
11
+ */
12
+ var LiteCompatError = class extends Error {
13
+ constructor(api, detail) {
14
+ super(detail ? `'${api}' is not supported by the Babylon Lite compat layer. ${detail}` : `'${api}' is not supported by the Babylon Lite compat layer.`);
15
+ this.name = "LiteCompatError";
16
+ }
17
+ };
18
+ /** Throw a {@link LiteCompatError} for an unsupported API. */
19
+ function unsupported(api, detail) {
20
+ throw new LiteCompatError(api, detail);
21
+ }
22
+ //#endregion
23
+ //#region src/math/vector.ts
24
+ /**
25
+ * Babylon.js-compatible vector classes (`Vector2`, `Vector3`, `Vector4`).
26
+ *
27
+ * These are mutable classes backed by plain `x`/`y`/`z`/`w` fields. Because a
28
+ * `Vector3` is structurally `{ x, y, z }`, it can be passed directly anywhere
29
+ * the Babylon Lite API expects a `Vec3`. For APIs that want a tuple, use
30
+ * `asArray()`.
31
+ */
32
+ var Vector2 = class Vector2 {
33
+ x;
34
+ y;
35
+ constructor(x = 0, y = 0) {
36
+ this.x = x;
37
+ this.y = y;
38
+ }
39
+ set(x, y) {
40
+ this.x = x;
41
+ this.y = y;
42
+ return this;
43
+ }
44
+ copyFrom(source) {
45
+ this.x = source.x;
46
+ this.y = source.y;
47
+ return this;
48
+ }
49
+ copyFromFloats(x, y) {
50
+ this.x = x;
51
+ this.y = y;
52
+ return this;
53
+ }
54
+ add(other) {
55
+ return new Vector2(this.x + other.x, this.y + other.y);
56
+ }
57
+ addInPlace(other) {
58
+ this.x += other.x;
59
+ this.y += other.y;
60
+ return this;
61
+ }
62
+ subtract(other) {
63
+ return new Vector2(this.x - other.x, this.y - other.y);
64
+ }
65
+ scale(scale) {
66
+ return new Vector2(this.x * scale, this.y * scale);
67
+ }
68
+ scaleInPlace(scale) {
69
+ this.x *= scale;
70
+ this.y *= scale;
71
+ return this;
72
+ }
73
+ length() {
74
+ return Math.sqrt(this.x * this.x + this.y * this.y);
75
+ }
76
+ lengthSquared() {
77
+ return this.x * this.x + this.y * this.y;
78
+ }
79
+ normalize() {
80
+ return this.normalizeToRef(this);
81
+ }
82
+ normalizeToRef(result) {
83
+ return normalizeVec2ToRef(this, result);
84
+ }
85
+ clone() {
86
+ return new Vector2(this.x, this.y);
87
+ }
88
+ equals(other) {
89
+ return this.x === other.x && this.y === other.y;
90
+ }
91
+ asArray() {
92
+ return [this.x, this.y];
93
+ }
94
+ static Zero() {
95
+ return new Vector2(0, 0);
96
+ }
97
+ static One() {
98
+ return new Vector2(1, 1);
99
+ }
100
+ static Dot(a, b) {
101
+ return a.x * b.x + a.y * b.y;
102
+ }
103
+ };
104
+ var Vector3 = class Vector3 {
105
+ x;
106
+ y;
107
+ z;
108
+ constructor(x = 0, y = 0, z = 0) {
109
+ this.x = x;
110
+ this.y = y;
111
+ this.z = z;
112
+ }
113
+ set(x, y, z) {
114
+ this.x = x;
115
+ this.y = y;
116
+ this.z = z;
117
+ return this;
118
+ }
119
+ setAll(value) {
120
+ this.x = this.y = this.z = value;
121
+ return this;
122
+ }
123
+ copyFrom(source) {
124
+ this.x = source.x;
125
+ this.y = source.y;
126
+ this.z = source.z;
127
+ return this;
128
+ }
129
+ copyFromFloats(x, y, z) {
130
+ this.x = x;
131
+ this.y = y;
132
+ this.z = z;
133
+ return this;
134
+ }
135
+ add(other) {
136
+ return new Vector3(this.x + other.x, this.y + other.y, this.z + other.z);
137
+ }
138
+ addInPlace(other) {
139
+ this.x += other.x;
140
+ this.y += other.y;
141
+ this.z += other.z;
142
+ return this;
143
+ }
144
+ addInPlaceFromFloats(x, y, z) {
145
+ this.x += x;
146
+ this.y += y;
147
+ this.z += z;
148
+ return this;
149
+ }
150
+ subtract(other) {
151
+ return new Vector3(this.x - other.x, this.y - other.y, this.z - other.z);
152
+ }
153
+ subtractInPlace(other) {
154
+ this.x -= other.x;
155
+ this.y -= other.y;
156
+ this.z -= other.z;
157
+ return this;
158
+ }
159
+ multiply(other) {
160
+ return new Vector3(this.x * other.x, this.y * other.y, this.z * other.z);
161
+ }
162
+ scale(scale) {
163
+ return new Vector3(this.x * scale, this.y * scale, this.z * scale);
164
+ }
165
+ scaleInPlace(scale) {
166
+ this.x *= scale;
167
+ this.y *= scale;
168
+ this.z *= scale;
169
+ return this;
170
+ }
171
+ negate() {
172
+ return new Vector3(-this.x, -this.y, -this.z);
173
+ }
174
+ minimizeInPlace(other) {
175
+ return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
176
+ }
177
+ maximizeInPlace(other) {
178
+ return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
179
+ }
180
+ minimizeInPlaceFromFloats(x, y, z) {
181
+ if (x < this.x) this.x = x;
182
+ if (y < this.y) this.y = y;
183
+ if (z < this.z) this.z = z;
184
+ return this;
185
+ }
186
+ maximizeInPlaceFromFloats(x, y, z) {
187
+ if (x > this.x) this.x = x;
188
+ if (y > this.y) this.y = y;
189
+ if (z > this.z) this.z = z;
190
+ return this;
191
+ }
192
+ length() {
193
+ return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
194
+ }
195
+ lengthSquared() {
196
+ return this.x * this.x + this.y * this.y + this.z * this.z;
197
+ }
198
+ normalize() {
199
+ const len = this.length();
200
+ if (len !== 0) {
201
+ this.x /= len;
202
+ this.y /= len;
203
+ this.z /= len;
204
+ }
205
+ return this;
206
+ }
207
+ clone() {
208
+ return new Vector3(this.x, this.y, this.z);
209
+ }
210
+ equals(other) {
211
+ return this.x === other.x && this.y === other.y && this.z === other.z;
212
+ }
213
+ equalsWithEpsilon(other, epsilon = 1e-6) {
214
+ return Math.abs(this.x - other.x) <= epsilon && Math.abs(this.y - other.y) <= epsilon && Math.abs(this.z - other.z) <= epsilon;
215
+ }
216
+ asArray() {
217
+ return [
218
+ this.x,
219
+ this.y,
220
+ this.z
221
+ ];
222
+ }
223
+ toArray(array, index = 0) {
224
+ array[index] = this.x;
225
+ array[index + 1] = this.y;
226
+ array[index + 2] = this.z;
227
+ return this;
228
+ }
229
+ static Zero() {
230
+ return new Vector3(0, 0, 0);
231
+ }
232
+ static One() {
233
+ return new Vector3(1, 1, 1);
234
+ }
235
+ static Up() {
236
+ return new Vector3(0, 1, 0);
237
+ }
238
+ static Down() {
239
+ return new Vector3(0, -1, 0);
240
+ }
241
+ static Forward() {
242
+ return new Vector3(0, 0, 1);
243
+ }
244
+ static Backward() {
245
+ return new Vector3(0, 0, -1);
246
+ }
247
+ static Right() {
248
+ return new Vector3(1, 0, 0);
249
+ }
250
+ static Left() {
251
+ return new Vector3(-1, 0, 0);
252
+ }
253
+ static FromArray(array, offset = 0) {
254
+ return new Vector3(array[offset] ?? 0, array[offset + 1] ?? 0, array[offset + 2] ?? 0);
255
+ }
256
+ static FromArrayToRef(array, offset, result) {
257
+ result.set(array[offset] ?? 0, array[offset + 1] ?? 0, array[offset + 2] ?? 0);
258
+ return result;
259
+ }
260
+ static FromFloatsToRef(x, y, z, result) {
261
+ result.set(x, y, z);
262
+ return result;
263
+ }
264
+ static Dot(a, b) {
265
+ return a.x * b.x + a.y * b.y + a.z * b.z;
266
+ }
267
+ static Cross(a, b) {
268
+ return Vector3.CrossToRef(a, b, new Vector3());
269
+ }
270
+ static CrossToRef(a, b, result) {
271
+ result.set(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
272
+ return result;
273
+ }
274
+ static Distance(a, b) {
275
+ return Math.sqrt(Vector3.DistanceSquared(a, b));
276
+ }
277
+ static DistanceSquared(a, b) {
278
+ const dx = a.x - b.x;
279
+ const dy = a.y - b.y;
280
+ const dz = a.z - b.z;
281
+ return dx * dx + dy * dy + dz * dz;
282
+ }
283
+ static Lerp(start, end, amount) {
284
+ return Vector3.LerpToRef(start, end, amount, new Vector3());
285
+ }
286
+ static LerpToRef(start, end, amount, result) {
287
+ result.set(start.x + (end.x - start.x) * amount, start.y + (end.y - start.y) * amount, start.z + (end.z - start.z) * amount);
288
+ return result;
289
+ }
290
+ /** Midpoint between two vectors. */
291
+ static Center(a, b) {
292
+ return Vector3.CenterToRef(a, b, new Vector3());
293
+ }
294
+ /** Midpoint between two vectors, written into `ref`. */
295
+ static CenterToRef(a, b, ref) {
296
+ return ref.set((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2);
297
+ }
298
+ static Normalize(vector) {
299
+ return Vector3.NormalizeToRef(vector, new Vector3());
300
+ }
301
+ static NormalizeToRef(vector, result) {
302
+ const len = vector.length();
303
+ if (len === 0) result.set(0, 0, 0);
304
+ else result.set(vector.x / len, vector.y / len, vector.z / len);
305
+ return result;
306
+ }
307
+ static Minimize(a, b) {
308
+ return a.clone().minimizeInPlace(b);
309
+ }
310
+ static Maximize(a, b) {
311
+ return a.clone().maximizeInPlace(b);
312
+ }
313
+ /** Project a world-space point into a Babylon.js viewport. */
314
+ static Project(vector, world, transform, viewport) {
315
+ return Vector3.ProjectToRef(vector, world, transform, viewport, new Vector3());
316
+ }
317
+ /** Project a world-space point into a Babylon.js viewport, writing into `result`. */
318
+ static ProjectToRef(vector, world, transform, viewport, result) {
319
+ return projectPointToViewportToRef(vector, world.m, transform.m, viewport, result);
320
+ }
321
+ /** Transform a coordinate (point) by a matrix using the row-vector convention. */
322
+ static TransformCoordinates(vector, transformation) {
323
+ return Vector3.TransformCoordinatesToRef(vector, transformation, new Vector3());
324
+ }
325
+ /** Transform a coordinate (point) by a matrix using the row-vector convention. */
326
+ static TransformCoordinatesToRef(vector, transformation, result) {
327
+ const m = transformation.m;
328
+ const x = vector.x;
329
+ const y = vector.y;
330
+ const z = vector.z;
331
+ const rx = x * m[0] + y * m[4] + z * m[8] + m[12];
332
+ const ry = x * m[1] + y * m[5] + z * m[9] + m[13];
333
+ const rz = x * m[2] + y * m[6] + z * m[10] + m[14];
334
+ const rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
335
+ result.set(rx * rw, ry * rw, rz * rw);
336
+ return result;
337
+ }
338
+ /** Transform a direction (normal) by a matrix, ignoring translation. */
339
+ static TransformNormal(vector, transformation) {
340
+ return Vector3.TransformNormalToRef(vector, transformation, new Vector3());
341
+ }
342
+ /** Transform a direction (normal) by a matrix, ignoring translation. */
343
+ static TransformNormalToRef(vector, transformation, result) {
344
+ const m = transformation.m;
345
+ const x = vector.x;
346
+ const y = vector.y;
347
+ const z = vector.z;
348
+ result.set(x * m[0] + y * m[4] + z * m[8], x * m[1] + y * m[5] + z * m[9], x * m[2] + y * m[6] + z * m[10]);
349
+ return result;
350
+ }
351
+ };
352
+ /**
353
+ * @internal A `Vector3` whose `x`/`y`/`z` read and write **through** to a live
354
+ * Babylon Lite vector (`ObservableVec3`). This lets compat code expose
355
+ * `mesh.position` / `rotation` / `scaling` as a real `Vector3` — so inherited
356
+ * in-place methods (`scaleInPlace`, `addInPlace`, `set`, …) mutate the Lite node
357
+ * and trigger its dirty tracking, matching Babylon.js's live-transform semantics.
358
+ *
359
+ * The accessors are installed with `Object.defineProperty` **after** `super()`,
360
+ * which redefines the own `x`/`y`/`z` data properties the base constructor created
361
+ * (parameter properties). This is required under `useDefineForClassFields` (ES2022),
362
+ * where overriding the accessors via a subclass field/prototype alone would be
363
+ * shadowed by the base's own data properties.
364
+ */
365
+ var LiteBackedVector3 = class extends Vector3 {
366
+ constructor(lite) {
367
+ super(0, 0, 0);
368
+ Object.defineProperty(this, "x", {
369
+ enumerable: true,
370
+ configurable: true,
371
+ get: () => lite.x,
372
+ set: (v) => lite.x = v
373
+ });
374
+ Object.defineProperty(this, "y", {
375
+ enumerable: true,
376
+ configurable: true,
377
+ get: () => lite.y,
378
+ set: (v) => lite.y = v
379
+ });
380
+ Object.defineProperty(this, "z", {
381
+ enumerable: true,
382
+ configurable: true,
383
+ get: () => lite.z,
384
+ set: (v) => lite.z = v
385
+ });
386
+ }
387
+ };
388
+ /** One stable proxy per Lite vector, so `mesh.position === mesh.position` (Babylon.js identity parity). */
389
+ var _liteVec3Proxies = /* @__PURE__ */ new WeakMap();
390
+ /**
391
+ * @internal Return the cached write-through `Vector3` proxy over a Lite
392
+ * `ObservableVec3` (creating it on first use). Stable identity per Lite vector.
393
+ */
394
+ function liteBackedVector3(lite) {
395
+ let proxy = _liteVec3Proxies.get(lite);
396
+ if (!proxy) {
397
+ proxy = new LiteBackedVector3(lite);
398
+ _liteVec3Proxies.set(lite, proxy);
399
+ }
400
+ return proxy;
401
+ }
402
+ var Vector4 = class Vector4 {
403
+ x;
404
+ y;
405
+ z;
406
+ w;
407
+ constructor(x = 0, y = 0, z = 0, w = 0) {
408
+ this.x = x;
409
+ this.y = y;
410
+ this.z = z;
411
+ this.w = w;
412
+ }
413
+ set(x, y, z, w) {
414
+ this.x = x;
415
+ this.y = y;
416
+ this.z = z;
417
+ this.w = w;
418
+ return this;
419
+ }
420
+ copyFrom(source) {
421
+ this.x = source.x;
422
+ this.y = source.y;
423
+ this.z = source.z;
424
+ this.w = source.w;
425
+ return this;
426
+ }
427
+ add(other) {
428
+ return new Vector4(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
429
+ }
430
+ scale(scale) {
431
+ return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
432
+ }
433
+ length() {
434
+ return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
435
+ }
436
+ clone() {
437
+ return new Vector4(this.x, this.y, this.z, this.w);
438
+ }
439
+ equals(other) {
440
+ return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
441
+ }
442
+ asArray() {
443
+ return [
444
+ this.x,
445
+ this.y,
446
+ this.z,
447
+ this.w
448
+ ];
449
+ }
450
+ static Zero() {
451
+ return new Vector4(0, 0, 0, 0);
452
+ }
453
+ };
454
+ //#endregion
455
+ //#region src/math/color.ts
456
+ /**
457
+ * Babylon.js-compatible colour classes (`Color3`, `Color4`).
458
+ *
459
+ * Mutable, backed by `r`/`g`/`b`/`a` fields. `asArray()` yields the tuple shape
460
+ * (`[r, g, b]` / `[r, g, b, a]`) consumed by the Babylon Lite material and light
461
+ * APIs.
462
+ */
463
+ var Color3 = class Color3 {
464
+ r;
465
+ g;
466
+ b;
467
+ constructor(r = 0, g = 0, b = 0) {
468
+ this.r = r;
469
+ this.g = g;
470
+ this.b = b;
471
+ }
472
+ set(r, g, b) {
473
+ this.r = r;
474
+ this.g = g;
475
+ this.b = b;
476
+ return this;
477
+ }
478
+ copyFrom(source) {
479
+ this.r = source.r;
480
+ this.g = source.g;
481
+ this.b = source.b;
482
+ return this;
483
+ }
484
+ scale(scale) {
485
+ return new Color3(this.r * scale, this.g * scale, this.b * scale);
486
+ }
487
+ scaleInPlace(scale) {
488
+ this.r *= scale;
489
+ this.g *= scale;
490
+ this.b *= scale;
491
+ return this;
492
+ }
493
+ multiply(other) {
494
+ return new Color3(this.r * other.r, this.g * other.g, this.b * other.b);
495
+ }
496
+ add(other) {
497
+ return new Color3(this.r + other.r, this.g + other.g, this.b + other.b);
498
+ }
499
+ clone() {
500
+ return new Color3(this.r, this.g, this.b);
501
+ }
502
+ equals(other) {
503
+ return this.r === other.r && this.g === other.g && this.b === other.b;
504
+ }
505
+ asArray() {
506
+ return [
507
+ this.r,
508
+ this.g,
509
+ this.b
510
+ ];
511
+ }
512
+ toColor4(alpha = 1) {
513
+ return new Color4(this.r, this.g, this.b, alpha);
514
+ }
515
+ toHexString() {
516
+ const intR = Math.round(Math.min(Math.max(this.r, 0), 1) * 255);
517
+ const intG = Math.round(Math.min(Math.max(this.g, 0), 1) * 255);
518
+ const intB = Math.round(Math.min(Math.max(this.b, 0), 1) * 255);
519
+ return "#" + toHex(intR) + toHex(intG) + toHex(intB);
520
+ }
521
+ static Black() {
522
+ return new Color3(0, 0, 0);
523
+ }
524
+ static White() {
525
+ return new Color3(1, 1, 1);
526
+ }
527
+ static Red() {
528
+ return new Color3(1, 0, 0);
529
+ }
530
+ static Green() {
531
+ return new Color3(0, 1, 0);
532
+ }
533
+ static Blue() {
534
+ return new Color3(0, 0, 1);
535
+ }
536
+ static FromArray(array, offset = 0) {
537
+ return new Color3(array[offset] ?? 0, array[offset + 1] ?? 0, array[offset + 2] ?? 0);
538
+ }
539
+ static FromInts(r, g, b) {
540
+ return new Color3(r / 255, g / 255, b / 255);
541
+ }
542
+ static FromHexString(hex) {
543
+ if (hex.charAt(0) !== "#" || hex.length < 7) return new Color3(0, 0, 0);
544
+ const r = parseInt(hex.substring(1, 3), 16);
545
+ const g = parseInt(hex.substring(3, 5), 16);
546
+ const b = parseInt(hex.substring(5, 7), 16);
547
+ return Color3.FromInts(r, g, b);
548
+ }
549
+ static Lerp(start, end, amount) {
550
+ return new Color3(start.r + (end.r - start.r) * amount, start.g + (end.g - start.g) * amount, start.b + (end.b - start.b) * amount);
551
+ }
552
+ };
553
+ var Color4 = class Color4 {
554
+ r;
555
+ g;
556
+ b;
557
+ a;
558
+ constructor(r = 0, g = 0, b = 0, a = 1) {
559
+ this.r = r;
560
+ this.g = g;
561
+ this.b = b;
562
+ this.a = a;
563
+ }
564
+ set(r, g, b, a) {
565
+ this.r = r;
566
+ this.g = g;
567
+ this.b = b;
568
+ this.a = a;
569
+ return this;
570
+ }
571
+ copyFrom(source) {
572
+ this.r = source.r;
573
+ this.g = source.g;
574
+ this.b = source.b;
575
+ this.a = source.a;
576
+ return this;
577
+ }
578
+ scale(scale) {
579
+ return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
580
+ }
581
+ add(other) {
582
+ return new Color4(this.r + other.r, this.g + other.g, this.b + other.b, this.a + other.a);
583
+ }
584
+ clone() {
585
+ return new Color4(this.r, this.g, this.b, this.a);
586
+ }
587
+ equals(other) {
588
+ return this.r === other.r && this.g === other.g && this.b === other.b && this.a === other.a;
589
+ }
590
+ asArray() {
591
+ return [
592
+ this.r,
593
+ this.g,
594
+ this.b,
595
+ this.a
596
+ ];
597
+ }
598
+ static FromArray(array, offset = 0) {
599
+ return new Color4(array[offset] ?? 0, array[offset + 1] ?? 0, array[offset + 2] ?? 0, array[offset + 3] ?? 1);
600
+ }
601
+ static FromInts(r, g, b, a) {
602
+ return new Color4(r / 255, g / 255, b / 255, a / 255);
603
+ }
604
+ };
605
+ function toHex(value) {
606
+ const hex = value.toString(16).toUpperCase();
607
+ return hex.length === 1 ? "0" + hex : hex;
608
+ }
609
+ //#endregion
610
+ //#region src/math/quaternion.ts
611
+ /**
612
+ * Babylon.js-compatible `Quaternion`.
613
+ *
614
+ * Mutable, backed by `x`/`y`/`z`/`w` fields. Structurally compatible with the
615
+ * Babylon Lite `{ x, y, z, w }` quaternion shape used on transform nodes.
616
+ */
617
+ var Quaternion = class Quaternion {
618
+ x;
619
+ y;
620
+ z;
621
+ w;
622
+ constructor(x = 0, y = 0, z = 0, w = 1) {
623
+ this.x = x;
624
+ this.y = y;
625
+ this.z = z;
626
+ this.w = w;
627
+ }
628
+ set(x, y, z, w) {
629
+ this.x = x;
630
+ this.y = y;
631
+ this.z = z;
632
+ this.w = w;
633
+ return this;
634
+ }
635
+ copyFrom(source) {
636
+ this.x = source.x;
637
+ this.y = source.y;
638
+ this.z = source.z;
639
+ this.w = source.w;
640
+ return this;
641
+ }
642
+ multiply(other) {
643
+ return new Quaternion(other.w * this.x + other.x * this.w + other.y * this.z - other.z * this.y, other.w * this.y - other.x * this.z + other.y * this.w + other.z * this.x, other.w * this.z + other.x * this.y - other.y * this.x + other.z * this.w, other.w * this.w - other.x * this.x - other.y * this.y - other.z * this.z);
644
+ }
645
+ length() {
646
+ return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
647
+ }
648
+ normalize() {
649
+ const len = this.length();
650
+ if (len !== 0) {
651
+ const inv = 1 / len;
652
+ this.x *= inv;
653
+ this.y *= inv;
654
+ this.z *= inv;
655
+ this.w *= inv;
656
+ }
657
+ return this;
658
+ }
659
+ conjugate() {
660
+ return new Quaternion(-this.x, -this.y, -this.z, this.w);
661
+ }
662
+ /**
663
+ * Babylon.js `Quaternion.fromRotationMatrix` — update this quaternion in place
664
+ * from the rotation part of `matrix`. Backed by Lite's `createQuatFromRotationMat4`.
665
+ */
666
+ fromRotationMatrix(matrix) {
667
+ const q = createQuatFromRotationMat4(matrix.m);
668
+ this.x = q.x;
669
+ this.y = q.y;
670
+ this.z = q.z;
671
+ this.w = q.w;
672
+ return this;
673
+ }
674
+ /**
675
+ * Babylon.js `Quaternion.toRotationMatrix` — write this quaternion's rotation
676
+ * into `result`.
677
+ */
678
+ toRotationMatrix(result) {
679
+ writeMat4FromQuatIntoBuffer(result.m, this.x, this.y, this.z, this.w);
680
+ return result;
681
+ }
682
+ clone() {
683
+ return new Quaternion(this.x, this.y, this.z, this.w);
684
+ }
685
+ equals(other) {
686
+ return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
687
+ }
688
+ asArray() {
689
+ return [
690
+ this.x,
691
+ this.y,
692
+ this.z,
693
+ this.w
694
+ ];
695
+ }
696
+ toEulerAngles() {
697
+ const result = new Vector3();
698
+ const qz = this.z;
699
+ const qx = this.x;
700
+ const qy = this.y;
701
+ const qw = this.w;
702
+ const sqw = qw * qw;
703
+ const sqz = qz * qz;
704
+ const sqx = qx * qx;
705
+ const sqy = qy * qy;
706
+ const zAxisY = qy * qz - qx * qw;
707
+ const limit = .4999999;
708
+ if (zAxisY < -.4999999) {
709
+ result.y = 2 * Math.atan2(qy, qw);
710
+ result.x = Math.PI / 2;
711
+ result.z = 0;
712
+ } else if (zAxisY > limit) {
713
+ result.y = 2 * Math.atan2(qy, qw);
714
+ result.x = -Math.PI / 2;
715
+ result.z = 0;
716
+ } else {
717
+ result.z = Math.atan2(2 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw);
718
+ result.x = Math.asin(-2 * (qz * qy - qx * qw));
719
+ result.y = Math.atan2(2 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw);
720
+ }
721
+ return result;
722
+ }
723
+ static Identity() {
724
+ return new Quaternion(0, 0, 0, 1);
725
+ }
726
+ /**
727
+ * Babylon.js `Quaternion.FromRotationMatrix` — create a new quaternion from the
728
+ * rotation part of `matrix`. Backed by Lite's `createQuatFromRotationMat4`.
729
+ */
730
+ static FromRotationMatrix(matrix) {
731
+ const result = new Quaternion();
732
+ Quaternion.FromRotationMatrixToRef(matrix, result);
733
+ return result;
734
+ }
735
+ /**
736
+ * Babylon.js `Quaternion.FromRotationMatrixToRef` — write the rotation part of
737
+ * `matrix` into `result`. Backed by Lite's `createQuatFromRotationMat4`.
738
+ */
739
+ static FromRotationMatrixToRef(matrix, result) {
740
+ const q = createQuatFromRotationMat4(matrix.m);
741
+ result.x = q.x;
742
+ result.y = q.y;
743
+ result.z = q.z;
744
+ result.w = q.w;
745
+ return result;
746
+ }
747
+ static FromEulerAngles(x, y, z) {
748
+ return Quaternion.RotationYawPitchRoll(y, x, z);
749
+ }
750
+ static RotationYawPitchRoll(yaw, pitch, roll) {
751
+ const halfRoll = roll * .5;
752
+ const halfPitch = pitch * .5;
753
+ const halfYaw = yaw * .5;
754
+ const sinRoll = Math.sin(halfRoll);
755
+ const cosRoll = Math.cos(halfRoll);
756
+ const sinPitch = Math.sin(halfPitch);
757
+ const cosPitch = Math.cos(halfPitch);
758
+ const sinYaw = Math.sin(halfYaw);
759
+ const cosYaw = Math.cos(halfYaw);
760
+ return new Quaternion(cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll, sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll, cosYaw * cosPitch * sinRoll - sinYaw * sinPitch * cosRoll, cosYaw * cosPitch * cosRoll + sinYaw * sinPitch * sinRoll);
761
+ }
762
+ static RotationAxis(axis, angle) {
763
+ const sin = Math.sin(angle / 2);
764
+ const len = axis.length() || 1;
765
+ return new Quaternion(axis.x / len * sin, axis.y / len * sin, axis.z / len * sin, Math.cos(angle / 2));
766
+ }
767
+ static Slerp(left, right, amount) {
768
+ let num2;
769
+ let num3;
770
+ const num = amount;
771
+ let dot = left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
772
+ let flip = false;
773
+ if (dot < 0) {
774
+ flip = true;
775
+ dot = -dot;
776
+ }
777
+ if (dot > .999999) {
778
+ num3 = 1 - num;
779
+ num2 = flip ? -num : num;
780
+ } else {
781
+ const angle = Math.acos(dot);
782
+ const invSin = 1 / Math.sin(angle);
783
+ num3 = Math.sin((1 - num) * angle) * invSin;
784
+ num2 = flip ? -Math.sin(num * angle) * invSin : Math.sin(num * angle) * invSin;
785
+ }
786
+ return new Quaternion(num3 * left.x + num2 * right.x, num3 * left.y + num2 * right.y, num3 * left.z + num2 * right.z, num3 * left.w + num2 * right.w);
787
+ }
788
+ };
789
+ //#endregion
790
+ //#region src/math/matrix.ts
791
+ /**
792
+ * Babylon.js-compatible `Matrix` (4x4).
793
+ *
794
+ * Storage and conventions match Babylon.js: a 16-element row-major `Float32Array`
795
+ * with translation in elements 12/13/14, and the row-vector convention
796
+ * (`v' = v · M`). `multiply(other)` applies `this` first, then `other`.
797
+ */
798
+ var matrixMaximizeValues;
799
+ var Matrix = class Matrix {
800
+ m;
801
+ constructor() {
802
+ this.m = /* @__PURE__ */ new Float32Array(16);
803
+ }
804
+ set(index, value) {
805
+ this.m[index] = value;
806
+ return this;
807
+ }
808
+ copyFrom(source) {
809
+ this.m.set(source.m);
810
+ return this;
811
+ }
812
+ /** Set only this matrix's translation components. */
813
+ setTranslationFromFloats(x, y, z) {
814
+ setMat4Translation(this.m, x, y, z);
815
+ return this;
816
+ }
817
+ maximizeInPlace(other) {
818
+ maximizeMat4InPlace(this.m, other.m);
819
+ return this.markAsUpdated();
820
+ }
821
+ maximizeInPlaceFromFloats(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15) {
822
+ const values = matrixMaximizeValues ??= /* @__PURE__ */ new Float32Array(16);
823
+ values[0] = m0;
824
+ values[1] = m1;
825
+ values[2] = m2;
826
+ values[3] = m3;
827
+ values[4] = m4;
828
+ values[5] = m5;
829
+ values[6] = m6;
830
+ values[7] = m7;
831
+ values[8] = m8;
832
+ values[9] = m9;
833
+ values[10] = m10;
834
+ values[11] = m11;
835
+ values[12] = m12;
836
+ values[13] = m13;
837
+ values[14] = m14;
838
+ values[15] = m15;
839
+ maximizeMat4InPlace(this.m, values);
840
+ return this.markAsUpdated();
841
+ }
842
+ clone() {
843
+ const result = new Matrix();
844
+ result.m.set(this.m);
845
+ return result;
846
+ }
847
+ asArray() {
848
+ return this.m;
849
+ }
850
+ toArray() {
851
+ return Array.from(this.m);
852
+ }
853
+ /** Babylon.js `Matrix.copyToArray` — copy the 16 elements into `array` at `offset`. */
854
+ copyToArray(array, offset = 0) {
855
+ for (let i = 0; i < 16; i++) array[offset + i] = this.m[i];
856
+ return this;
857
+ }
858
+ equals(other) {
859
+ for (let i = 0; i < 16; i++) if (this.m[i] !== other.m[i]) return false;
860
+ return true;
861
+ }
862
+ multiply(other) {
863
+ return Matrix.FromValues(...multiplyValues(this.m, other.m));
864
+ }
865
+ multiplyToRef(other, result) {
866
+ const values = multiplyValues(this.m, other.m);
867
+ result.m.set(values);
868
+ return result;
869
+ }
870
+ transpose() {
871
+ const a = this.m;
872
+ return Matrix.FromValues(a[0], a[4], a[8], a[12], a[1], a[5], a[9], a[13], a[2], a[6], a[10], a[14], a[3], a[7], a[11], a[15]);
873
+ }
874
+ determinant() {
875
+ return determinant(this.m);
876
+ }
877
+ invert() {
878
+ const result = new Matrix();
879
+ this.invertToRef(result);
880
+ return result;
881
+ }
882
+ invertToRef(result) {
883
+ const inv = invertValues(this.m);
884
+ result.m.set(inv);
885
+ return result;
886
+ }
887
+ getTranslation() {
888
+ return new Vector3(this.m[12], this.m[13], this.m[14]);
889
+ }
890
+ /**
891
+ * Babylon.js `Matrix.decompose(scale?, rotation?, translation?)` — split this
892
+ * TRS matrix into its scale, rotation (quaternion), and translation parts,
893
+ * writing into any provided out-params. Returns `false` (matching BJS) when a
894
+ * scale axis is zero. The rotation extraction is backed by Lite's
895
+ * `createQuatFromRotationMat4` (via `Quaternion.FromRotationMatrixToRef`); the
896
+ * negative-determinant `scale.y` flip matches Babylon.js exactly.
897
+ */
898
+ decompose(scale, rotation, translation) {
899
+ const m = this.m;
900
+ if (translation) translation.copyFromFloats(m[12], m[13], m[14]);
901
+ const sc = scale ?? new Vector3();
902
+ sc.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
903
+ sc.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
904
+ sc.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
905
+ if (m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8]) + m[2] * (m[4] * m[9] - m[5] * m[8]) < 0) sc.y *= -1;
906
+ if (sc.x === 0 || sc.y === 0 || sc.z === 0) {
907
+ if (rotation) rotation.set(0, 0, 0, 1);
908
+ return false;
909
+ }
910
+ if (rotation) {
911
+ const sx = 1 / sc.x;
912
+ const sy = 1 / sc.y;
913
+ const sz = 1 / sc.z;
914
+ const r = (decomposeRotationScratch ??= new Matrix()).m;
915
+ r[0] = m[0] * sx;
916
+ r[1] = m[1] * sx;
917
+ r[2] = m[2] * sx;
918
+ r[3] = 0;
919
+ r[4] = m[4] * sy;
920
+ r[5] = m[5] * sy;
921
+ r[6] = m[6] * sy;
922
+ r[7] = 0;
923
+ r[8] = m[8] * sz;
924
+ r[9] = m[9] * sz;
925
+ r[10] = m[10] * sz;
926
+ r[11] = 0;
927
+ r[12] = 0;
928
+ r[13] = 0;
929
+ r[14] = 0;
930
+ r[15] = 1;
931
+ Quaternion.FromRotationMatrixToRef(decomposeRotationScratch, rotation);
932
+ }
933
+ return true;
934
+ }
935
+ static FromValues(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15) {
936
+ const result = new Matrix();
937
+ result.m.set([
938
+ m0,
939
+ m1,
940
+ m2,
941
+ m3,
942
+ m4,
943
+ m5,
944
+ m6,
945
+ m7,
946
+ m8,
947
+ m9,
948
+ m10,
949
+ m11,
950
+ m12,
951
+ m13,
952
+ m14,
953
+ m15
954
+ ]);
955
+ return result;
956
+ }
957
+ static FromArray(array, offset = 0) {
958
+ const result = new Matrix();
959
+ for (let i = 0; i < 16; i++) result.m[i] = array[offset + i] ?? 0;
960
+ return result;
961
+ }
962
+ static Identity() {
963
+ return Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
964
+ }
965
+ static Zero() {
966
+ return new Matrix();
967
+ }
968
+ static Translation(x, y, z) {
969
+ return Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1);
970
+ }
971
+ static Scaling(x, y, z) {
972
+ return Matrix.FromValues(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
973
+ }
974
+ static RotationX(angle) {
975
+ const s = Math.sin(angle);
976
+ const c = Math.cos(angle);
977
+ return Matrix.FromValues(1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1);
978
+ }
979
+ static RotationY(angle) {
980
+ const s = Math.sin(angle);
981
+ const c = Math.cos(angle);
982
+ return Matrix.FromValues(c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1);
983
+ }
984
+ static RotationZ(angle) {
985
+ const s = Math.sin(angle);
986
+ const c = Math.cos(angle);
987
+ return Matrix.FromValues(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
988
+ }
989
+ /** Babylon.js `Matrix.LookAtLH(eye, target, up)` — left-handed view matrix. */
990
+ static LookAtLH(eye, target, up) {
991
+ let zx = target.x - eye.x, zy = target.y - eye.y, zz = target.z - eye.z;
992
+ const zl = Math.hypot(zx, zy, zz) || 1;
993
+ zx /= zl;
994
+ zy /= zl;
995
+ zz /= zl;
996
+ let xx = up.y * zz - up.z * zy, xy = up.z * zx - up.x * zz, xz = up.x * zy - up.y * zx;
997
+ const xl = Math.hypot(xx, xy, xz) || 1;
998
+ xx /= xl;
999
+ xy /= xl;
1000
+ xz /= xl;
1001
+ const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx;
1002
+ const ex = -(xx * eye.x + xy * eye.y + xz * eye.z);
1003
+ const ey = -(yx * eye.x + yy * eye.y + yz * eye.z);
1004
+ const ez = -(zx * eye.x + zy * eye.y + zz * eye.z);
1005
+ return Matrix.FromValues(xx, yx, zx, 0, xy, yy, zy, 0, xz, yz, zz, 0, ex, ey, ez, 1);
1006
+ }
1007
+ /** Babylon.js `Matrix.OrthoOffCenterLH(left, right, bottom, top, znear, zfar, halfZRange?)` — LH ortho projection. */
1008
+ static OrthoOffCenterLH(left, right, bottom, top, znear, zfar, _halfZRange) {
1009
+ const a = 2 / (right - left);
1010
+ const b = 2 / (top - bottom);
1011
+ const c = 1 / (zfar - znear);
1012
+ const tx = (left + right) / (left - right);
1013
+ const ty = (top + bottom) / (bottom - top);
1014
+ const tz = -znear * c;
1015
+ return Matrix.FromValues(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, tx, ty, tz, 1);
1016
+ }
1017
+ /**
1018
+ * Babylon.js `Matrix.Compose(scale, rotation, translation)` — build a TRS matrix
1019
+ * from a scale vector, a rotation quaternion, and a translation vector (row-vector
1020
+ * convention, translation in elements 12/13/14).
1021
+ */
1022
+ static Compose(scale, rotation, translation) {
1023
+ const { x, y, z, w } = rotation;
1024
+ const x2 = x + x, y2 = y + y, z2 = z + z;
1025
+ const xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2;
1026
+ const sx = scale.x, sy = scale.y, sz = scale.z;
1027
+ return Matrix.FromValues((1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0, (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0, (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0, translation.x, translation.y, translation.z, 1);
1028
+ }
1029
+ /** Babylon.js `Matrix.markAsUpdated()` — Lite has no per-matrix dirty flag; no-op for parity. */
1030
+ markAsUpdated() {
1031
+ return this;
1032
+ }
1033
+ };
1034
+ var decomposeRotationScratch = null;
1035
+ function multiplyValues(a, b) {
1036
+ const result = new Array(16);
1037
+ for (let r = 0; r < 4; r++) for (let c = 0; c < 4; c++) result[r * 4 + c] = a[r * 4] * b[c] + a[r * 4 + 1] * b[4 + c] + a[r * 4 + 2] * b[8 + c] + a[r * 4 + 3] * b[12 + c];
1038
+ return result;
1039
+ }
1040
+ function determinant(m) {
1041
+ const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
1042
+ const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
1043
+ const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
1044
+ const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
1045
+ const b00 = m00 * m11 - m01 * m10;
1046
+ const b01 = m00 * m12 - m02 * m10;
1047
+ const b02 = m00 * m13 - m03 * m10;
1048
+ const b03 = m01 * m12 - m02 * m11;
1049
+ const b04 = m01 * m13 - m03 * m11;
1050
+ const b05 = m02 * m13 - m03 * m12;
1051
+ const b06 = m20 * m31 - m21 * m30;
1052
+ const b07 = m20 * m32 - m22 * m30;
1053
+ const b08 = m20 * m33 - m23 * m30;
1054
+ const b09 = m21 * m32 - m22 * m31;
1055
+ const b10 = m21 * m33 - m23 * m31;
1056
+ return b00 * (m22 * m33 - m23 * m32) - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
1057
+ }
1058
+ function invertValues(m) {
1059
+ const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3];
1060
+ const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7];
1061
+ const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11];
1062
+ const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15];
1063
+ const b00 = m00 * m11 - m01 * m10;
1064
+ const b01 = m00 * m12 - m02 * m10;
1065
+ const b02 = m00 * m13 - m03 * m10;
1066
+ const b03 = m01 * m12 - m02 * m11;
1067
+ const b04 = m01 * m13 - m03 * m11;
1068
+ const b05 = m02 * m13 - m03 * m12;
1069
+ const b06 = m20 * m31 - m21 * m30;
1070
+ const b07 = m20 * m32 - m22 * m30;
1071
+ const b08 = m20 * m33 - m23 * m30;
1072
+ const b09 = m21 * m32 - m22 * m31;
1073
+ const b10 = m21 * m33 - m23 * m31;
1074
+ const b11 = m22 * m33 - m23 * m32;
1075
+ const det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
1076
+ if (det === 0) return [
1077
+ 1,
1078
+ 0,
1079
+ 0,
1080
+ 0,
1081
+ 0,
1082
+ 1,
1083
+ 0,
1084
+ 0,
1085
+ 0,
1086
+ 0,
1087
+ 1,
1088
+ 0,
1089
+ 0,
1090
+ 0,
1091
+ 0,
1092
+ 1
1093
+ ];
1094
+ const invDet = 1 / det;
1095
+ return [
1096
+ (m11 * b11 - m12 * b10 + m13 * b09) * invDet,
1097
+ (m02 * b10 - m01 * b11 - m03 * b09) * invDet,
1098
+ (m31 * b05 - m32 * b04 + m33 * b03) * invDet,
1099
+ (m22 * b04 - m21 * b05 - m23 * b03) * invDet,
1100
+ (m12 * b08 - m10 * b11 - m13 * b07) * invDet,
1101
+ (m00 * b11 - m02 * b08 + m03 * b07) * invDet,
1102
+ (m32 * b02 - m30 * b05 - m33 * b01) * invDet,
1103
+ (m20 * b05 - m22 * b02 + m23 * b01) * invDet,
1104
+ (m10 * b10 - m11 * b08 + m13 * b06) * invDet,
1105
+ (m01 * b08 - m00 * b10 - m03 * b06) * invDet,
1106
+ (m30 * b04 - m31 * b02 + m33 * b00) * invDet,
1107
+ (m21 * b02 - m20 * b04 - m23 * b00) * invDet,
1108
+ (m11 * b07 - m10 * b09 - m12 * b06) * invDet,
1109
+ (m00 * b09 - m01 * b07 + m02 * b06) * invDet,
1110
+ (m31 * b01 - m30 * b03 - m32 * b00) * invDet,
1111
+ (m20 * b03 - m21 * b01 + m22 * b00) * invDet
1112
+ ];
1113
+ }
1114
+ /**
1115
+ * Babylon.js-compatible vector × matrix transforms (static helpers that live on
1116
+ * `Vector3` in Babylon.js). Kept here to avoid a circular import between the
1117
+ * vector and matrix modules.
1118
+ */
1119
+ function transformCoordinates(vector, transformation) {
1120
+ const m = transformation.m;
1121
+ const x = vector.x;
1122
+ const y = vector.y;
1123
+ const z = vector.z;
1124
+ const rx = x * m[0] + y * m[4] + z * m[8] + m[12];
1125
+ const ry = x * m[1] + y * m[5] + z * m[9] + m[13];
1126
+ const rz = x * m[2] + y * m[6] + z * m[10] + m[14];
1127
+ const rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]);
1128
+ return new Vector3(rx * rw, ry * rw, rz * rw);
1129
+ }
1130
+ function transformNormal(vector, transformation) {
1131
+ const m = transformation.m;
1132
+ const x = vector.x;
1133
+ const y = vector.y;
1134
+ const z = vector.z;
1135
+ return new Vector3(x * m[0] + y * m[4] + z * m[8], x * m[1] + y * m[5] + z * m[9], x * m[2] + y * m[6] + z * m[10]);
1136
+ }
1137
+ //#endregion
1138
+ //#region src/culling/bounding.ts
1139
+ /**
1140
+ * Babylon.js-compatible bounding volumes (`BoundingBox`, `BoundingSphere`,
1141
+ * `BoundingInfo`) — pure JS over the compat math types.
1142
+ *
1143
+ * World-space members (`minimumWorld`, `maximumWorld`, `centerWorld`,
1144
+ * `extendSizeWorld`, `vectorsWorld`, `radiusWorld`) are derived by transforming
1145
+ * the local geometry by the supplied world matrix, exactly as Babylon.js does:
1146
+ * all eight corners are transformed and the world AABB is fitted around them, so
1147
+ * the result is correct under rotation (transforming only min/max is not).
1148
+ */
1149
+ var boundingSphereScaleMinimum;
1150
+ var boundingSphereScaleMaximum;
1151
+ var BoundingSphere = class {
1152
+ center = new Vector3();
1153
+ radius;
1154
+ centerWorld = new Vector3();
1155
+ radiusWorld;
1156
+ minimum = new Vector3();
1157
+ maximum = new Vector3();
1158
+ _worldMatrix;
1159
+ constructor(min, max, worldMatrix) {
1160
+ this.radius = 0;
1161
+ this.radiusWorld = 0;
1162
+ this._worldMatrix = Matrix.Identity();
1163
+ this.reConstruct(min, max, worldMatrix);
1164
+ }
1165
+ reConstruct(min, max, worldMatrix) {
1166
+ this.minimum.copyFrom(min);
1167
+ this.maximum.copyFrom(max);
1168
+ this.center.copyFrom(Vector3.Lerp(min, max, .5));
1169
+ this.radius = max.subtract(min).length() * .5;
1170
+ this._update(worldMatrix ?? Matrix.Identity());
1171
+ }
1172
+ getWorldMatrix() {
1173
+ return this._worldMatrix;
1174
+ }
1175
+ scale(factor) {
1176
+ const minimum = boundingSphereScaleMinimum ??= new Vector3();
1177
+ const maximum = boundingSphereScaleMaximum ??= new Vector3();
1178
+ scaleBoundsFromCenterToRef(this.minimum, this.maximum, this.center, factor, minimum, maximum);
1179
+ this.reConstruct(minimum, maximum, this._worldMatrix);
1180
+ return this;
1181
+ }
1182
+ /** @internal */
1183
+ _update(worldMatrix) {
1184
+ Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
1185
+ const scaled = Vector3.TransformNormal(new Vector3(1, 1, 1), worldMatrix);
1186
+ this.radiusWorld = Math.max(Math.abs(scaled.x), Math.abs(scaled.y), Math.abs(scaled.z)) * this.radius;
1187
+ this._worldMatrix = worldMatrix;
1188
+ }
1189
+ intersectsPoint(point) {
1190
+ return Vector3.DistanceSquared(this.centerWorld, point) <= this.radiusWorld * this.radiusWorld;
1191
+ }
1192
+ static Intersects(a, b) {
1193
+ const r = a.radiusWorld + b.radiusWorld;
1194
+ return Vector3.DistanceSquared(a.centerWorld, b.centerWorld) <= r * r;
1195
+ }
1196
+ };
1197
+ var BoundingBox = class {
1198
+ minimum = new Vector3();
1199
+ maximum = new Vector3();
1200
+ center = new Vector3();
1201
+ extendSize = new Vector3();
1202
+ /** Center of the AABB in world space. */
1203
+ centerWorld = new Vector3();
1204
+ /** Half-size of the AABB in world space (multiply by 2 for the full size). */
1205
+ extendSizeWorld = new Vector3();
1206
+ /** Minimum corner of the world-space AABB. */
1207
+ minimumWorld = new Vector3();
1208
+ /** Maximum corner of the world-space AABB. */
1209
+ maximumWorld = new Vector3();
1210
+ /** The 8 corner points in local space (min/max combinations). */
1211
+ vectors = [];
1212
+ /** The 8 corner points transformed into world space. */
1213
+ vectorsWorld = [];
1214
+ /** The three world-space axis directions of the box (rows of the world matrix). */
1215
+ directions = [
1216
+ new Vector3(),
1217
+ new Vector3(),
1218
+ new Vector3()
1219
+ ];
1220
+ _worldMatrix;
1221
+ constructor(min, max, worldMatrix) {
1222
+ for (let i = 0; i < 8; i++) {
1223
+ this.vectors.push(new Vector3());
1224
+ this.vectorsWorld.push(new Vector3());
1225
+ }
1226
+ this._worldMatrix = Matrix.Identity();
1227
+ this.reConstruct(min, max, worldMatrix);
1228
+ }
1229
+ reConstruct(min, max, worldMatrix) {
1230
+ const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
1231
+ this.minimum.copyFromFloats(minX, minY, minZ);
1232
+ this.maximum.copyFromFloats(maxX, maxY, maxZ);
1233
+ this.vectors[0].copyFromFloats(minX, minY, minZ);
1234
+ this.vectors[1].copyFromFloats(maxX, maxY, maxZ);
1235
+ this.vectors[2].copyFromFloats(maxX, minY, minZ);
1236
+ this.vectors[3].copyFromFloats(minX, maxY, minZ);
1237
+ this.vectors[4].copyFromFloats(minX, minY, maxZ);
1238
+ this.vectors[5].copyFromFloats(maxX, maxY, minZ);
1239
+ this.vectors[6].copyFromFloats(minX, maxY, maxZ);
1240
+ this.vectors[7].copyFromFloats(maxX, minY, maxZ);
1241
+ this.center.copyFromFloats((minX + maxX) * .5, (minY + maxY) * .5, (minZ + maxZ) * .5);
1242
+ this.extendSize.copyFromFloats((maxX - minX) * .5, (maxY - minY) * .5, (maxZ - minZ) * .5);
1243
+ this._update(worldMatrix ?? Matrix.Identity());
1244
+ }
1245
+ getWorldMatrix() {
1246
+ return this._worldMatrix;
1247
+ }
1248
+ /** @internal */
1249
+ _update(world) {
1250
+ this.minimumWorld.setAll(Number.MAX_VALUE);
1251
+ this.maximumWorld.setAll(-Number.MAX_VALUE);
1252
+ for (let i = 0; i < 8; i++) {
1253
+ const v = this.vectorsWorld[i];
1254
+ Vector3.TransformCoordinatesToRef(this.vectors[i], world, v);
1255
+ this.minimumWorld.minimizeInPlace(v);
1256
+ this.maximumWorld.maximizeInPlace(v);
1257
+ }
1258
+ const minX = this.minimumWorld.x, minY = this.minimumWorld.y, minZ = this.minimumWorld.z, maxX = this.maximumWorld.x, maxY = this.maximumWorld.y, maxZ = this.maximumWorld.z;
1259
+ this.extendSizeWorld.copyFromFloats((maxX - minX) * .5, (maxY - minY) * .5, (maxZ - minZ) * .5);
1260
+ this.centerWorld.copyFromFloats((minX + maxX) * .5, (minY + maxY) * .5, (minZ + maxZ) * .5);
1261
+ const m = world.m;
1262
+ this.directions[0].copyFromFloats(m[0], m[1], m[2]);
1263
+ this.directions[1].copyFromFloats(m[4], m[5], m[6]);
1264
+ this.directions[2].copyFromFloats(m[8], m[9], m[10]);
1265
+ this._worldMatrix = world;
1266
+ }
1267
+ intersectsPoint(point) {
1268
+ return point.x >= this.minimumWorld.x && point.x <= this.maximumWorld.x && point.y >= this.minimumWorld.y && point.y <= this.maximumWorld.y && point.z >= this.minimumWorld.z && point.z <= this.maximumWorld.z;
1269
+ }
1270
+ static Intersects(a, b) {
1271
+ return a.minimumWorld.x <= b.maximumWorld.x && a.maximumWorld.x >= b.minimumWorld.x && a.minimumWorld.y <= b.maximumWorld.y && a.maximumWorld.y >= b.minimumWorld.y && a.minimumWorld.z <= b.maximumWorld.z && a.maximumWorld.z >= b.minimumWorld.z;
1272
+ }
1273
+ };
1274
+ var BoundingInfo = class {
1275
+ boundingBox;
1276
+ boundingSphere;
1277
+ constructor(min, max, worldMatrix) {
1278
+ this.boundingBox = new BoundingBox(min, max, worldMatrix);
1279
+ this.boundingSphere = new BoundingSphere(min, max, worldMatrix);
1280
+ }
1281
+ get minimum() {
1282
+ return this.boundingBox.minimum;
1283
+ }
1284
+ get maximum() {
1285
+ return this.boundingBox.maximum;
1286
+ }
1287
+ intersectsPoint(point) {
1288
+ return this.boundingSphere.intersectsPoint(point) && this.boundingBox.intersectsPoint(point);
1289
+ }
1290
+ /** Babylon.js `BoundingInfo.update` — re-derive the world-space bounds from the
1291
+ * local geometry and a new world matrix. */
1292
+ update(worldMatrix) {
1293
+ this.boundingBox._update(worldMatrix);
1294
+ this.boundingSphere._update(worldMatrix);
1295
+ }
1296
+ /** Rebuild the local bounds and (optionally) re-derive world-space bounds from
1297
+ * the supplied world matrix, transforming all eight corners. */
1298
+ reConstruct(min, max, worldMatrix) {
1299
+ this.boundingBox.reConstruct(min, max, worldMatrix);
1300
+ this.boundingSphere.reConstruct(min, max, worldMatrix);
1301
+ }
1302
+ };
1303
+ //#endregion
1304
+ //#region src/misc/observable.ts
1305
+ var Observable = class {
1306
+ _onObserverAdded;
1307
+ notifyIfTriggered;
1308
+ _observers = [];
1309
+ _hasNotified = false;
1310
+ _lastNotifiedValue;
1311
+ _lastNotifiedMask = -1;
1312
+ constructor(_onObserverAdded, notifyIfTriggered = false) {
1313
+ this._onObserverAdded = _onObserverAdded;
1314
+ this.notifyIfTriggered = notifyIfTriggered;
1315
+ }
1316
+ add(callback, mask = -1) {
1317
+ this._observers.push({
1318
+ callback,
1319
+ mask
1320
+ });
1321
+ this._onObserverAdded?.(callback);
1322
+ if (this._hasNotified && this.notifyIfTriggered && (mask & this._lastNotifiedMask) !== 0) callback(this._lastNotifiedValue);
1323
+ return callback;
1324
+ }
1325
+ addOnce(callback, mask = -1) {
1326
+ const wrapper = (eventData) => {
1327
+ this.removeCallback(wrapper);
1328
+ callback(eventData);
1329
+ };
1330
+ return this.add(wrapper, mask);
1331
+ }
1332
+ remove(callback) {
1333
+ return callback ? this.removeCallback(callback) : false;
1334
+ }
1335
+ removeCallback(callback) {
1336
+ const index = this._observers.findIndex((observer) => observer.callback === callback);
1337
+ if (index !== -1) {
1338
+ this._observers.splice(index, 1);
1339
+ return true;
1340
+ }
1341
+ return false;
1342
+ }
1343
+ notifyObservers(eventData, mask = -1) {
1344
+ if (this.notifyIfTriggered) {
1345
+ this._hasNotified = true;
1346
+ this._lastNotifiedValue = eventData;
1347
+ this._lastNotifiedMask = mask;
1348
+ }
1349
+ for (const observer of this._observers.slice()) if ((observer.mask & mask) !== 0) observer.callback(eventData);
1350
+ }
1351
+ hasObservers() {
1352
+ return this._observers.length > 0;
1353
+ }
1354
+ clear() {
1355
+ this._observers = [];
1356
+ this._onObserverAdded = void 0;
1357
+ this.cleanLastNotifiedState();
1358
+ }
1359
+ cleanLastNotifiedState() {
1360
+ this._hasNotified = false;
1361
+ this._lastNotifiedValue = void 0;
1362
+ this._lastNotifiedMask = -1;
1363
+ }
1364
+ };
1365
+ //#endregion
1366
+ //#region src/node/node.ts
1367
+ var _uniqueIdCounter = 0;
1368
+ var Node = class {
1369
+ name;
1370
+ /** String id. Defaults to the name (Babylon.js parity). */
1371
+ id;
1372
+ /** Process-unique numeric id, assigned at construction. */
1373
+ uniqueId;
1374
+ /** Free-form user data slot (Babylon.js `Node.metadata`). */
1375
+ metadata = null;
1376
+ onDisposeObservable = new Observable();
1377
+ /** @internal Owning compat scene, when constructed against one. */
1378
+ _scene;
1379
+ /** @internal */
1380
+ _parent = null;
1381
+ /** @internal Direct children, maintained as `parent` / `setParent` links change. */
1382
+ _children = [];
1383
+ /** @internal */
1384
+ _enabled = true;
1385
+ /** @internal Effective enabled state inherited from the parent chain. */
1386
+ _parentEnabled = true;
1387
+ /** @internal */
1388
+ _disposed = false;
1389
+ constructor(name, scene) {
1390
+ this.name = name;
1391
+ this.id = name;
1392
+ this.uniqueId = ++_uniqueIdCounter;
1393
+ this._scene = scene;
1394
+ }
1395
+ /** The runtime class name (overridden by each subclass). */
1396
+ getClassName() {
1397
+ return "Node";
1398
+ }
1399
+ /** The scene this node belongs to, if any. */
1400
+ getScene() {
1401
+ return this._scene;
1402
+ }
1403
+ /** The engine backing this node's scene, if any. */
1404
+ getEngine() {
1405
+ return this._scene?.getEngine();
1406
+ }
1407
+ get parent() {
1408
+ return this._parent;
1409
+ }
1410
+ set parent(value) {
1411
+ this._linkParent(value);
1412
+ this._applyParent(value);
1413
+ }
1414
+ /**
1415
+ * @internal Update the parent link and both nodes' child registries. Shared by
1416
+ * the `parent` setter and `TransformNode.setParent` (which differ only in how
1417
+ * the Lite-side transform is reparented, handled by their own callers).
1418
+ */
1419
+ _linkParent(value) {
1420
+ if (this._parent === value) return;
1421
+ if (this._parent) {
1422
+ const i = this._parent._children.indexOf(this);
1423
+ if (i !== -1) this._parent._children.splice(i, 1);
1424
+ }
1425
+ this._parent = value;
1426
+ if (value && !value._children.includes(this)) value._children.push(this);
1427
+ this._syncParentEnabledState();
1428
+ }
1429
+ /** @internal Whether this node is an `AbstractMesh` (overridden there) — drives `getChildMeshes`. */
1430
+ _isMeshNode() {
1431
+ return false;
1432
+ }
1433
+ /**
1434
+ * Babylon.js `node.getDescendants(directDescendantsOnly?, predicate?)` — the
1435
+ * nodes parented (directly or transitively) under this one, optionally filtered.
1436
+ */
1437
+ getDescendants(directDescendantsOnly = false, predicate) {
1438
+ const results = [];
1439
+ const collect = (node) => {
1440
+ for (const child of node._children) {
1441
+ if (!predicate || predicate(child)) results.push(child);
1442
+ if (!directDescendantsOnly) collect(child);
1443
+ }
1444
+ };
1445
+ collect(this);
1446
+ return results;
1447
+ }
1448
+ /**
1449
+ * Babylon.js `node.getChildren(predicate?, directDescendantsOnly?)` — descendant
1450
+ * nodes (direct children by default), optionally filtered by a predicate.
1451
+ */
1452
+ getChildren(predicate, directDescendantsOnly = true) {
1453
+ return this.getDescendants(directDescendantsOnly, predicate);
1454
+ }
1455
+ /**
1456
+ * Babylon.js `node.getChildMeshes(directDescendantsOnly?, predicate?)` — the
1457
+ * descendant nodes that are meshes (all descendants by default).
1458
+ */
1459
+ getChildMeshes(directDescendantsOnly = false, predicate) {
1460
+ return this.getDescendants(directDescendantsOnly, (node) => node._isMeshNode() && (!predicate || predicate(node)));
1461
+ }
1462
+ isEnabled(checkAncestors = true) {
1463
+ return this._enabled && (!checkAncestors || this._parentEnabled);
1464
+ }
1465
+ setEnabled(value) {
1466
+ if (this._enabled === value) return;
1467
+ this._enabled = value;
1468
+ this._syncParentEnabledState();
1469
+ }
1470
+ /** @internal Refresh this subtree after a local enabled or parent change. */
1471
+ _syncParentEnabledState() {
1472
+ this._parentEnabled = this._parent?.isEnabled() ?? true;
1473
+ this._onEffectiveEnabledStateChanged(this.isEnabled());
1474
+ for (const child of this._children) child._syncParentEnabledState();
1475
+ }
1476
+ /** @internal Hook for wrappers that must materialize effective enabled state in Lite. */
1477
+ _onEffectiveEnabledStateChanged(_enabled) {}
1478
+ isDisposed() {
1479
+ return this._disposed;
1480
+ }
1481
+ dispose(doNotRecurse = false) {
1482
+ this._disposeWrapperTree(doNotRecurse);
1483
+ }
1484
+ /** @internal Dispose this node's subclass-owned resources. */
1485
+ _disposeSelf(_doNotRecurse) {}
1486
+ /** @internal Dispose this compat wrapper tree in post-order. */
1487
+ _disposeWrapperTree(doNotRecurse = false) {
1488
+ if (this._disposed) return;
1489
+ if (doNotRecurse) for (const child of [...this._children]) child.parent = null;
1490
+ else for (const child of [...this._children]) child._disposeWrapperTree();
1491
+ this._disposeSelf(doNotRecurse);
1492
+ this._disposed = true;
1493
+ this.onDisposeObservable.notifyObservers(this);
1494
+ this.onDisposeObservable.clear();
1495
+ this._linkParent(null);
1496
+ this._scene?._unregisterNode(this);
1497
+ }
1498
+ /** @internal Hook for subclasses to wire the parent link into the Lite scene graph. */
1499
+ _applyParent(_parent) {}
1500
+ };
1501
+ //#endregion
1502
+ //#region src/materials/materials.ts
1503
+ /**
1504
+ * Babylon.js-compatible material classes over the Babylon Lite material
1505
+ * factories.
1506
+ *
1507
+ * The Lite material is plain-data props (`_lite`); assign it to a mesh via
1508
+ * `mesh.material = material`. Property setters mutate the props and mark the
1509
+ * material UBO dirty (matching Babylon.js's "mutate then it just works"
1510
+ * behaviour). Only the common property subset is mapped; rarely-used Babylon.js
1511
+ * material properties are intentionally omitted.
1512
+ */
1513
+ /** Babylon.js `Material` — base class for all materials. */
1514
+ var Material = class {
1515
+ name;
1516
+ /** Common transparency mode flag (Babylon.js `Material.transparencyMode`). */
1517
+ transparencyMode = null;
1518
+ /** Back-face culling toggle (Babylon.js `Material.backFaceCulling`). */
1519
+ _backFaceCulling = true;
1520
+ get backFaceCulling() {
1521
+ return this._backFaceCulling;
1522
+ }
1523
+ set backFaceCulling(value) {
1524
+ this._backFaceCulling = value;
1525
+ this._applyBackFaceCulling(value);
1526
+ this._markDirty();
1527
+ }
1528
+ /** @internal Per-material hook to push culling onto the Lite props (Standard vs PBR differ). */
1529
+ _applyBackFaceCulling(_value) {}
1530
+ /** Wireframe rendering toggle (not honoured by all Lite materials). */
1531
+ wireframe = false;
1532
+ /** @internal Owning compat scene, when constructed against one. */
1533
+ _scene;
1534
+ constructor(name, scene) {
1535
+ this.name = name;
1536
+ this._scene = scene;
1537
+ scene?._registerMaterial(this);
1538
+ }
1539
+ getClassName() {
1540
+ return "Material";
1541
+ }
1542
+ /**
1543
+ * @internal Copy the shared base + Lite data-property state onto a freshly
1544
+ * constructed clone. The clone keeps the `_buildGroup`/UBO its own factory
1545
+ * created (internal `_`-prefixed fields are never copied), so only the observable
1546
+ * data properties — colours, scalars, and shared texture references — carry over.
1547
+ */
1548
+ _cloneBaseInto(target) {
1549
+ copyLiteMaterialData(this._lite, target._lite);
1550
+ target.transparencyMode = this.transparencyMode;
1551
+ target.wireframe = this.wireframe;
1552
+ target.backFaceCulling = this._backFaceCulling;
1553
+ }
1554
+ /** The scene this material was constructed against (Babylon.js `Material.getScene`). */
1555
+ getScene() {
1556
+ return this._scene;
1557
+ }
1558
+ /**
1559
+ * The textures currently bound to this material (Babylon.js
1560
+ * `Material.getActiveTextures`). The base material owns no texture slots, so
1561
+ * this returns an empty array; each subclass overrides it to enumerate its own
1562
+ * slots and those of its extensions.
1563
+ */
1564
+ getActiveTextures() {
1565
+ return [];
1566
+ }
1567
+ _markDirty() {
1568
+ markMaterialUboDirty(this._lite);
1569
+ }
1570
+ /**
1571
+ * @internal Finalize GPU-facing resources before the mesh is registered.
1572
+ * Base materials need nothing; PBR overrides this to synthesize the solid
1573
+ * textures Babylon Lite's PBR pipeline requires from factor-only materials.
1574
+ */
1575
+ _ensureRenderable(_engine) {}
1576
+ /**
1577
+ * @internal Adopt an owning scene discovered when the material is first assigned
1578
+ * to a mesh (Babylon.js allows `new StandardMaterial(name)` with no scene, then
1579
+ * `mesh.material = mat`). Needed so the texture-readiness path can reconcile the
1580
+ * material into the running scene. Registers with the scene the first time.
1581
+ */
1582
+ _adoptScene(scene) {
1583
+ if (!this._scene) {
1584
+ this._scene = scene;
1585
+ scene._registerMaterial(this);
1586
+ }
1587
+ }
1588
+ /**
1589
+ * @internal Reconcile this material into its scene when the scene is already
1590
+ * live: finalize GPU-facing resources ({@link _ensureRenderable}) and rebuild
1591
+ * the renderables of every mesh using it. A no-op before engine start (the
1592
+ * boot-time build handles those meshes) or when the material has no scene.
1593
+ * Shared by the mesh `material` setter and the texture-readiness callback.
1594
+ */
1595
+ _refreshInScene() {
1596
+ const scene = this._scene;
1597
+ if (!scene?._hasStarted) return;
1598
+ this._ensureRenderable(scene.getEngine()._lite);
1599
+ rebuildMaterial(scene._lite, this._lite);
1600
+ }
1601
+ /**
1602
+ * @internal Rebind + rebuild this material once an asynchronously loaded texture
1603
+ * assigned to it becomes GPU-ready. Babylon.js `Texture`s load in the background,
1604
+ * so a texture assigned to a material (or a material assigned to a mesh) before
1605
+ * the load resolves must go back through the rebuild path once the handle exists.
1606
+ * Fires immediately when the texture is already ready (then gated by scene state).
1607
+ */
1608
+ _watchTexture(texture) {
1609
+ texture?._onReady?.(() => this._refreshInScene());
1610
+ }
1611
+ dispose() {
1612
+ this._scene?._unregisterMaterial(this);
1613
+ this._scene = void 0;
1614
+ }
1615
+ };
1616
+ /** Babylon.js `PushMaterial` — intermediate base; behaves like {@link Material} here. */
1617
+ var PushMaterial = class extends Material {
1618
+ getClassName() {
1619
+ return "PushMaterial";
1620
+ }
1621
+ };
1622
+ function readColor3(tuple) {
1623
+ return tuple ? new Color3(tuple[0], tuple[1], tuple[2]) : new Color3(0, 0, 0);
1624
+ }
1625
+ /**
1626
+ * Copy the observable Babylon Lite material data-properties from `src` onto `dst`.
1627
+ * `_`-prefixed internal fields (`_buildGroup`, `_uboVersion`, render-feature caches)
1628
+ * are skipped so the clone keeps its own renderable state. Arrays (colour/UV tuples)
1629
+ * are copied so mutating one material's colour does not alias the other; object
1630
+ * values (texture handles) are shared by reference, matching Babylon.js clone
1631
+ * semantics. Nested config objects (PBR clearcoat/sheen/…) are re-copied per-subclass.
1632
+ */
1633
+ function copyLiteMaterialData(src, dst) {
1634
+ const s = src;
1635
+ const d = dst;
1636
+ for (const key of Object.keys(s)) {
1637
+ if (key.startsWith("_")) continue;
1638
+ const value = s[key];
1639
+ d[key] = Array.isArray(value) ? value.slice() : value;
1640
+ }
1641
+ }
1642
+ var StandardMaterial = class StandardMaterial extends PushMaterial {
1643
+ /** @internal Underlying Babylon Lite standard-material props. */
1644
+ _lite;
1645
+ constructor(name, scene) {
1646
+ super(name, scene);
1647
+ this._lite = createStandardMaterial();
1648
+ }
1649
+ getClassName() {
1650
+ return "StandardMaterial";
1651
+ }
1652
+ get diffuseColor() {
1653
+ return readColor3(this._lite.diffuseColor);
1654
+ }
1655
+ set diffuseColor(value) {
1656
+ this._lite.diffuseColor = [
1657
+ value.r,
1658
+ value.g,
1659
+ value.b
1660
+ ];
1661
+ this._markDirty();
1662
+ }
1663
+ get specularColor() {
1664
+ return readColor3(this._lite.specularColor);
1665
+ }
1666
+ set specularColor(value) {
1667
+ this._lite.specularColor = [
1668
+ value.r,
1669
+ value.g,
1670
+ value.b
1671
+ ];
1672
+ this._markDirty();
1673
+ }
1674
+ get emissiveColor() {
1675
+ return readColor3(this._lite.emissiveColor);
1676
+ }
1677
+ set emissiveColor(value) {
1678
+ this._lite.emissiveColor = [
1679
+ value.r,
1680
+ value.g,
1681
+ value.b
1682
+ ];
1683
+ this._markDirty();
1684
+ }
1685
+ get ambientColor() {
1686
+ return readColor3(this._lite.ambientColor);
1687
+ }
1688
+ set ambientColor(value) {
1689
+ this._lite.ambientColor = [
1690
+ value.r,
1691
+ value.g,
1692
+ value.b
1693
+ ];
1694
+ this._markDirty();
1695
+ }
1696
+ get disableLighting() {
1697
+ return this._lite.disableLighting;
1698
+ }
1699
+ set disableLighting(value) {
1700
+ this._lite.disableLighting = value;
1701
+ this._markDirty();
1702
+ }
1703
+ _applyBackFaceCulling(value) {
1704
+ this._lite.backFaceCulling = value;
1705
+ }
1706
+ get alpha() {
1707
+ return this._lite.alpha;
1708
+ }
1709
+ set alpha(value) {
1710
+ this._lite.alpha = value;
1711
+ this._markDirty();
1712
+ }
1713
+ get diffuseTexture() {
1714
+ return this._diffuseTexture;
1715
+ }
1716
+ set diffuseTexture(texture) {
1717
+ this._diffuseTexture = texture;
1718
+ this._lite.diffuseTexture = texture?._lite ?? null;
1719
+ this._watchTexture(texture);
1720
+ this._markDirty();
1721
+ }
1722
+ /**
1723
+ * Babylon.js `StandardMaterial.alphaCutOff` — alpha-test threshold. Fragments
1724
+ * whose diffuse-texture alpha is below this value are discarded. Babylon Lite's
1725
+ * Standard pipeline alpha-tests against the diffuse texture's alpha when
1726
+ * `alphaCutOff > 0`, so this is wired directly.
1727
+ */
1728
+ get alphaCutOff() {
1729
+ return this._lite.alphaCutOff;
1730
+ }
1731
+ set alphaCutOff(value) {
1732
+ this._lite.alphaCutOff = value;
1733
+ this._markDirty();
1734
+ }
1735
+ /**
1736
+ * Babylon.js `StandardMaterial.useAlphaFromDiffuseTexture`. Babylon Lite's
1737
+ * alpha test already samples the diffuse texture's alpha (enabled via
1738
+ * `alphaCutOff`), so this is accepted for parity.
1739
+ */
1740
+ useAlphaFromDiffuseTexture = false;
1741
+ get bumpTexture() {
1742
+ return this._bumpTexture;
1743
+ }
1744
+ set bumpTexture(texture) {
1745
+ this._bumpTexture = texture;
1746
+ setStandardBumpTexture(this._lite, texture?._lite ?? null);
1747
+ this._watchTexture(texture);
1748
+ this._markDirty();
1749
+ }
1750
+ get emissiveTexture() {
1751
+ return this._emissiveTexture;
1752
+ }
1753
+ set emissiveTexture(texture) {
1754
+ this._emissiveTexture = texture;
1755
+ setStandardEmissiveTexture(this._lite, texture?._lite ?? null);
1756
+ this._watchTexture(texture);
1757
+ this._markDirty();
1758
+ }
1759
+ _diffuseTexture = null;
1760
+ _bumpTexture = null;
1761
+ _emissiveTexture = null;
1762
+ /** Enumerate the standard-material texture slots that are bound (Babylon.js `getActiveTextures`). */
1763
+ getActiveTextures() {
1764
+ const textures = [];
1765
+ if (this._diffuseTexture) textures.push(this._diffuseTexture);
1766
+ if (this._bumpTexture) textures.push(this._bumpTexture);
1767
+ if (this._emissiveTexture) textures.push(this._emissiveTexture);
1768
+ return textures;
1769
+ }
1770
+ /**
1771
+ * @internal Re-bind texture maps to the Lite material. Babylon.js `Texture`s
1772
+ * load asynchronously, so when `material.diffuseTexture = new Texture(url)` ran
1773
+ * the Lite handle was still undefined. By engine-start the scene has awaited the
1774
+ * loads, so copy the now-resolved handles (and UV tiling) onto the Lite props.
1775
+ */
1776
+ _ensureRenderable(_engine) {
1777
+ const diff = this._diffuseTexture;
1778
+ if (diff?._lite) {
1779
+ this._lite.diffuseTexture = diff._lite;
1780
+ if (diff.uScale !== void 0 && diff.vScale !== void 0) this._lite.uvScale = [diff.uScale, diff.vScale];
1781
+ }
1782
+ const bump = this._bumpTexture;
1783
+ if (bump?._lite) setStandardBumpTexture(this._lite, bump._lite);
1784
+ const emissive = this._emissiveTexture;
1785
+ if (emissive?._lite) setStandardEmissiveTexture(this._lite, emissive._lite);
1786
+ this._markDirty();
1787
+ }
1788
+ /**
1789
+ * Babylon.js `StandardMaterial.clone(name)`. Copies the diffuse/specular/emissive/
1790
+ * ambient colours and scalars, shares the diffuse/bump/emissive texture references,
1791
+ * and gives the clone its own Lite standard-material renderable.
1792
+ */
1793
+ clone(name) {
1794
+ const cloned = new StandardMaterial(name, this._scene);
1795
+ this._cloneBaseInto(cloned);
1796
+ cloned.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
1797
+ cloned._diffuseTexture = this._diffuseTexture;
1798
+ cloned._bumpTexture = this._bumpTexture;
1799
+ cloned._emissiveTexture = this._emissiveTexture;
1800
+ return cloned;
1801
+ }
1802
+ };
1803
+ /**
1804
+ * Babylon.js `PBRClearCoatConfiguration` — the `pbr.clearCoat` sub-object.
1805
+ * Proxies the common clearcoat fields onto a Babylon Lite `ClearCoatProps`.
1806
+ */
1807
+ var PBRClearCoatConfiguration = class {
1808
+ _props;
1809
+ _markDirty;
1810
+ constructor(_props, _markDirty) {
1811
+ this._props = _props;
1812
+ this._markDirty = _markDirty;
1813
+ }
1814
+ get isEnabled() {
1815
+ return this._props.isEnabled ?? false;
1816
+ }
1817
+ set isEnabled(value) {
1818
+ this._props.isEnabled = value;
1819
+ this._markDirty();
1820
+ }
1821
+ get intensity() {
1822
+ return this._props.intensity ?? 1;
1823
+ }
1824
+ set intensity(value) {
1825
+ this._props.intensity = value;
1826
+ this._markDirty();
1827
+ }
1828
+ get roughness() {
1829
+ return this._props.roughness ?? 0;
1830
+ }
1831
+ set roughness(value) {
1832
+ this._props.roughness = value;
1833
+ this._markDirty();
1834
+ }
1835
+ get indexOfRefraction() {
1836
+ return this._props.indexOfRefraction ?? 1.5;
1837
+ }
1838
+ set indexOfRefraction(value) {
1839
+ this._props.indexOfRefraction = value;
1840
+ this._markDirty();
1841
+ }
1842
+ };
1843
+ /** Babylon.js `PBRSheenConfiguration` — the `pbr.sheen` sub-object over Lite `SheenProps`. */
1844
+ var PBRSheenConfiguration = class {
1845
+ _props;
1846
+ _markDirty;
1847
+ constructor(_props, _markDirty) {
1848
+ this._props = _props;
1849
+ this._markDirty = _markDirty;
1850
+ }
1851
+ get isEnabled() {
1852
+ return this._props.isEnabled;
1853
+ }
1854
+ set isEnabled(value) {
1855
+ this._props.isEnabled = value;
1856
+ this._markDirty();
1857
+ }
1858
+ get intensity() {
1859
+ return this._props.intensity ?? 1;
1860
+ }
1861
+ set intensity(value) {
1862
+ this._props.intensity = value;
1863
+ this._markDirty();
1864
+ }
1865
+ get roughness() {
1866
+ return this._props.roughness ?? 0;
1867
+ }
1868
+ set roughness(value) {
1869
+ this._props.roughness = value;
1870
+ this._markDirty();
1871
+ }
1872
+ get color() {
1873
+ const c = this._props.color ?? [
1874
+ 1,
1875
+ 1,
1876
+ 1
1877
+ ];
1878
+ return new Color3(c[0], c[1], c[2]);
1879
+ }
1880
+ set color(value) {
1881
+ this._props.color = [
1882
+ value.r,
1883
+ value.g,
1884
+ value.b
1885
+ ];
1886
+ this._markDirty();
1887
+ }
1888
+ /** Babylon.js `sheen.texture`. Retains the wrapper and binds the Lite handle if the texture has resolved. */
1889
+ get texture() {
1890
+ return this._texture;
1891
+ }
1892
+ set texture(value) {
1893
+ this._texture = value;
1894
+ if (value?._lite) this._props.texture = value._lite;
1895
+ else delete this._props.texture;
1896
+ this._markDirty();
1897
+ }
1898
+ _texture = null;
1899
+ /** Enumerate the sheen texture slot for `Material.getActiveTextures`. */
1900
+ getActiveTextures() {
1901
+ return this._texture ? [this._texture] : [];
1902
+ }
1903
+ };
1904
+ /** Babylon.js `PBRAnisotropicConfiguration` — the `pbr.anisotropy` sub-object over Lite `AnisotropyProps`. */
1905
+ var PBRAnisotropicConfiguration = class {
1906
+ _props;
1907
+ _markDirty;
1908
+ constructor(_props, _markDirty) {
1909
+ this._props = _props;
1910
+ this._markDirty = _markDirty;
1911
+ }
1912
+ get isEnabled() {
1913
+ return this._props.isEnabled;
1914
+ }
1915
+ set isEnabled(value) {
1916
+ this._props.isEnabled = value;
1917
+ this._markDirty();
1918
+ }
1919
+ get intensity() {
1920
+ return this._props.intensity ?? 1;
1921
+ }
1922
+ set intensity(value) {
1923
+ this._props.intensity = value;
1924
+ this._markDirty();
1925
+ }
1926
+ get direction() {
1927
+ const d = this._props.direction ?? [1, 0];
1928
+ return {
1929
+ x: d[0],
1930
+ y: d[1]
1931
+ };
1932
+ }
1933
+ set direction(value) {
1934
+ this._props.direction = [value.x, value.y];
1935
+ this._markDirty();
1936
+ }
1937
+ };
1938
+ /** Babylon.js `PBRIridescenceConfiguration` — the `pbr.iridescence` sub-object over Lite `IridescenceProps`. */
1939
+ var PBRIridescenceConfiguration = class {
1940
+ _props;
1941
+ _markDirty;
1942
+ constructor(_props, _markDirty) {
1943
+ this._props = _props;
1944
+ this._markDirty = _markDirty;
1945
+ }
1946
+ get isEnabled() {
1947
+ return this._props.isEnabled ?? false;
1948
+ }
1949
+ set isEnabled(value) {
1950
+ this._props.isEnabled = value;
1951
+ this._markDirty();
1952
+ }
1953
+ get intensity() {
1954
+ return this._props.intensity ?? 1;
1955
+ }
1956
+ set intensity(value) {
1957
+ this._props.intensity = value;
1958
+ this._markDirty();
1959
+ }
1960
+ get indexOfRefraction() {
1961
+ return this._props.indexOfRefraction ?? 1.3;
1962
+ }
1963
+ set indexOfRefraction(value) {
1964
+ this._props.indexOfRefraction = value;
1965
+ this._markDirty();
1966
+ }
1967
+ get minimumThickness() {
1968
+ return this._props.minimumThickness ?? 100;
1969
+ }
1970
+ set minimumThickness(value) {
1971
+ this._props.minimumThickness = value;
1972
+ this._markDirty();
1973
+ }
1974
+ get maximumThickness() {
1975
+ return this._props.maximumThickness ?? 400;
1976
+ }
1977
+ set maximumThickness(value) {
1978
+ this._props.maximumThickness = value;
1979
+ this._markDirty();
1980
+ }
1981
+ };
1982
+ var PBRMaterial = class PBRMaterial extends PushMaterial {
1983
+ /** @internal Underlying Babylon Lite PBR-material props. */
1984
+ _lite;
1985
+ _albedoFactor = [
1986
+ 1,
1987
+ 1,
1988
+ 1,
1989
+ 1
1990
+ ];
1991
+ constructor(name, scene) {
1992
+ super(name, scene);
1993
+ this._lite = createPbrMaterial();
1994
+ if (!this._lite.baseColorFactor) this._lite.baseColorFactor = [
1995
+ 1,
1996
+ 1,
1997
+ 1,
1998
+ 1
1999
+ ];
2000
+ }
2001
+ getClassName() {
2002
+ return "PBRMaterial";
2003
+ }
2004
+ get albedoColor() {
2005
+ return new Color3(this._albedoFactor[0], this._albedoFactor[1], this._albedoFactor[2]);
2006
+ }
2007
+ set albedoColor(value) {
2008
+ this._albedoFactor = [
2009
+ value.r,
2010
+ value.g,
2011
+ value.b,
2012
+ this._albedoFactor[3]
2013
+ ];
2014
+ this._lite.baseColorFactor = [...this._albedoFactor];
2015
+ this._markDirty();
2016
+ }
2017
+ /**
2018
+ * Babylon.js `pbr.albedoTexture` (glTF base-color map). The texture loads
2019
+ * asynchronously, so the resolved Lite handle (+ sRGB flag) is bound in
2020
+ * {@link _ensureRenderable} at engine start rather than here.
2021
+ */
2022
+ get albedoTexture() {
2023
+ return this._albedoTexture;
2024
+ }
2025
+ set albedoTexture(texture) {
2026
+ this._albedoTexture = texture;
2027
+ this._watchTexture(texture);
2028
+ this._markDirty();
2029
+ }
2030
+ _albedoTexture = null;
2031
+ /**
2032
+ * Enumerate every bound PBR texture slot, including extension sub-configurations
2033
+ * (Babylon.js `PBRMaterial.getActiveTextures`).
2034
+ */
2035
+ getActiveTextures() {
2036
+ const textures = [];
2037
+ if (this._albedoTexture) textures.push(this._albedoTexture);
2038
+ const environmentTexture = this.environmentTexture;
2039
+ if (environmentTexture) textures.push(environmentTexture);
2040
+ if (this._sheen) textures.push(...this._sheen.getActiveTextures());
2041
+ return textures;
2042
+ }
2043
+ get metallic() {
2044
+ return this._lite.metallicFactor ?? 1;
2045
+ }
2046
+ set metallic(value) {
2047
+ this._lite.metallicFactor = value;
2048
+ this._markDirty();
2049
+ }
2050
+ get roughness() {
2051
+ return this._lite.roughnessFactor ?? 1;
2052
+ }
2053
+ set roughness(value) {
2054
+ this._lite.roughnessFactor = value;
2055
+ this._markDirty();
2056
+ }
2057
+ get emissiveColor() {
2058
+ return readColor3(this._lite._emissiveColor);
2059
+ }
2060
+ set emissiveColor(value) {
2061
+ setPbrEmissive(this._lite, [
2062
+ value.r,
2063
+ value.g,
2064
+ value.b
2065
+ ]);
2066
+ this._markDirty();
2067
+ }
2068
+ /**
2069
+ * Babylon.js `pbr.usePhysicalLightFalloff`. When false, point/spot lights use
2070
+ * Standard-style linear range falloff instead of physical inverse-square.
2071
+ * Default true (matches Babylon.js PBRMaterial).
2072
+ */
2073
+ get usePhysicalLightFalloff() {
2074
+ return this._lite.usePhysicalLightFalloff ?? true;
2075
+ }
2076
+ set usePhysicalLightFalloff(value) {
2077
+ this._lite.usePhysicalLightFalloff = value;
2078
+ this._markDirty();
2079
+ }
2080
+ get alpha() {
2081
+ return this._lite.alpha ?? 1;
2082
+ }
2083
+ set alpha(value) {
2084
+ this._lite.alpha = value;
2085
+ this._markDirty();
2086
+ }
2087
+ /**
2088
+ * Babylon.js `material.forceIrradianceInFragment`. Babylon Lite computes
2089
+ * irradiance in the fragment stage already, so this is accepted for parity.
2090
+ */
2091
+ forceIrradianceInFragment = false;
2092
+ _applyBackFaceCulling(value) {
2093
+ this._lite.doubleSided = !value;
2094
+ }
2095
+ /**
2096
+ * Babylon.js `pbr.clearCoat` sub-configuration. Lazily allocates the Lite
2097
+ * `clearCoat` props on first access and proxies the common fields
2098
+ * (`isEnabled`, `intensity`, `roughness`, `indexOfRefraction`) onto them.
2099
+ */
2100
+ get clearCoat() {
2101
+ if (!this._clearCoat) {
2102
+ setPbrClearCoat(this._lite, this._lite._clearCoat ?? { isEnabled: false });
2103
+ this._clearCoat = new PBRClearCoatConfiguration(this._lite._clearCoat, () => this._markDirty());
2104
+ }
2105
+ return this._clearCoat;
2106
+ }
2107
+ _clearCoat;
2108
+ /** Babylon.js `pbr.sheen` sub-configuration (Lite `SheenProps`). */
2109
+ get sheen() {
2110
+ if (!this._sheen) {
2111
+ setPbrSheen(this._lite, this._lite._sheen ?? { isEnabled: false });
2112
+ this._sheen = new PBRSheenConfiguration(this._lite._sheen, () => this._markDirty());
2113
+ }
2114
+ return this._sheen;
2115
+ }
2116
+ _sheen;
2117
+ /** Babylon.js `pbr.anisotropy` sub-configuration (Lite `AnisotropyProps`). */
2118
+ get anisotropy() {
2119
+ if (!this._anisotropy) {
2120
+ setPbrAnisotropy(this._lite, this._lite._anisotropy ?? { isEnabled: false });
2121
+ this._anisotropy = new PBRAnisotropicConfiguration(this._lite._anisotropy, () => this._markDirty());
2122
+ }
2123
+ return this._anisotropy;
2124
+ }
2125
+ _anisotropy;
2126
+ /** Babylon.js `pbr.iridescence` sub-configuration (Lite `IridescenceProps`). */
2127
+ get iridescence() {
2128
+ if (!this._iridescence) {
2129
+ setPbrIridescence(this._lite, this._lite._iridescence ?? { isEnabled: false });
2130
+ this._iridescence = new PBRIridescenceConfiguration(this._lite._iridescence, () => this._markDirty());
2131
+ }
2132
+ return this._iridescence;
2133
+ }
2134
+ _iridescence;
2135
+ /**
2136
+ * Babylon.js `material.environmentTexture` / `reflectionTexture`. Babylon Lite
2137
+ * applies image-based lighting scene-wide rather than per-material, so a cube
2138
+ * environment assigned to a material is routed to the owning scene's
2139
+ * environment (the dominant single-IBL case Babylon.js scenes use).
2140
+ */
2141
+ get environmentTexture() {
2142
+ return this._environmentTexture ?? this._scene?.environmentTexture ?? null;
2143
+ }
2144
+ set environmentTexture(value) {
2145
+ this._environmentTexture = value;
2146
+ if (this._scene) this._scene.environmentTexture = value;
2147
+ }
2148
+ _environmentTexture = null;
2149
+ get reflectionTexture() {
2150
+ return this.environmentTexture;
2151
+ }
2152
+ set reflectionTexture(value) {
2153
+ this.environmentTexture = value;
2154
+ }
2155
+ /** @internal Bind resolved textures and synthesize the solid textures Babylon Lite's PBR pipeline requires from a factor-only material. */
2156
+ _ensureRenderable(engine) {
2157
+ const lite = this._lite;
2158
+ const albedo = this._albedoTexture;
2159
+ if (albedo?._lite) {
2160
+ lite.baseColorTexture = albedo._lite;
2161
+ lite.baseColorFactor = [...this._albedoFactor];
2162
+ if (albedo.gammaSpace ?? true) setPbrGammaAlbedo(lite);
2163
+ else lite._gammaAlbedo = false;
2164
+ }
2165
+ if (!lite.baseColorTexture) {
2166
+ const f = this._albedoFactor;
2167
+ lite.baseColorTexture = createSolidTexture2D(engine, f[0], f[1], f[2], f[3]);
2168
+ lite.baseColorFactor = [
2169
+ 1,
2170
+ 1,
2171
+ 1,
2172
+ 1
2173
+ ];
2174
+ }
2175
+ if (!lite.ormTexture) {
2176
+ const rough = lite.roughnessFactor ?? 1;
2177
+ const metal = lite.metallicFactor ?? 1;
2178
+ lite.ormTexture = createSolidTexture2D(engine, 1, rough, metal);
2179
+ lite.roughnessFactor = 1;
2180
+ lite.metallicFactor = 1;
2181
+ }
2182
+ }
2183
+ /**
2184
+ * Babylon.js `PBRMaterial.clone(name)`. Copies the albedo/metallic/roughness/
2185
+ * emissive state, shares the albedo texture reference, gives the clone independent
2186
+ * clearcoat/sheen/anisotropy/iridescence sub-configurations (sharing any nested
2187
+ * texture), and a fresh Lite PBR renderable.
2188
+ */
2189
+ clone(name) {
2190
+ const cloned = new PBRMaterial(name, this._scene);
2191
+ this._clonePbrInto(cloned);
2192
+ return cloned;
2193
+ }
2194
+ /**
2195
+ * @internal Copy PBR-specific compat + Lite state onto a freshly constructed PBR
2196
+ * clone (used by every `PBRMaterial` subclass so each returns its own concrete
2197
+ * type). The base `_cloneBaseInto` shares the sub-config objects by reference; this
2198
+ * re-copies them so the clone's `clearCoat`/`sheen`/… mutate independently while
2199
+ * still sharing any nested texture handle.
2200
+ */
2201
+ _clonePbrInto(target) {
2202
+ this._cloneBaseInto(target);
2203
+ target.forceIrradianceInFragment = this.forceIrradianceInFragment;
2204
+ target._albedoFactor = [...this._albedoFactor];
2205
+ target._albedoTexture = this._albedoTexture;
2206
+ const src = this._lite;
2207
+ const dst = target._lite;
2208
+ if (src._emissiveColor) setPbrEmissive(dst, [...src._emissiveColor]);
2209
+ if (src._clearCoat) setPbrClearCoat(dst, { ...src._clearCoat });
2210
+ if (src._sheen) setPbrSheen(dst, { ...src._sheen });
2211
+ if (src._anisotropy) setPbrAnisotropy(dst, { ...src._anisotropy });
2212
+ if (src._iridescence) setPbrIridescence(dst, { ...src._iridescence });
2213
+ }
2214
+ };
2215
+ /**
2216
+ * Babylon.js `PBRMetallicRoughnessMaterial` — a simplified façade over
2217
+ * {@link PBRMaterial} exposing the metallic-roughness workflow directly.
2218
+ */
2219
+ var PBRMetallicRoughnessMaterial = class PBRMetallicRoughnessMaterial extends PBRMaterial {
2220
+ getClassName() {
2221
+ return "PBRMetallicRoughnessMaterial";
2222
+ }
2223
+ /** Alias of `albedoColor` (glTF "base color"). */
2224
+ get baseColor() {
2225
+ return this.albedoColor;
2226
+ }
2227
+ set baseColor(value) {
2228
+ this.albedoColor = value;
2229
+ }
2230
+ clone(name) {
2231
+ const cloned = new PBRMetallicRoughnessMaterial(name, this._scene);
2232
+ this._clonePbrInto(cloned);
2233
+ return cloned;
2234
+ }
2235
+ };
2236
+ /**
2237
+ * Babylon.js `PBRSpecularGlossinessMaterial` — the spec/gloss workflow is
2238
+ * supported when loaded from glTF (`KHR_materials_pbrSpecularGlossiness`), but a
2239
+ * standalone manual spec/gloss material is not mapped onto Lite's metallic-roughness
2240
+ * PBR. The constructor builds a metallic-roughness PBR material and exposes a
2241
+ * `diffuseColor`/`glossiness` façade; results will not match BJS spec/gloss exactly.
2242
+ */
2243
+ var PBRSpecularGlossinessMaterial = class PBRSpecularGlossinessMaterial extends PBRMaterial {
2244
+ getClassName() {
2245
+ return "PBRSpecularGlossinessMaterial";
2246
+ }
2247
+ get diffuseColor() {
2248
+ return this.albedoColor;
2249
+ }
2250
+ set diffuseColor(value) {
2251
+ this.albedoColor = value;
2252
+ }
2253
+ /** Maps glossiness → (1 - roughness). */
2254
+ get glossiness() {
2255
+ return 1 - this.roughness;
2256
+ }
2257
+ set glossiness(value) {
2258
+ this.roughness = 1 - value;
2259
+ }
2260
+ clone(name) {
2261
+ const cloned = new PBRSpecularGlossinessMaterial(name, this._scene);
2262
+ this._clonePbrInto(cloned);
2263
+ return cloned;
2264
+ }
2265
+ };
2266
+ //#endregion
2267
+ //#region src/meshes/merge-mesh-geometry.ts
2268
+ function fillFlatNormals(positions, indices, indexOffset, indexCount, vertexBase, out) {
2269
+ for (let i = 0; i < indexCount; i += 3) {
2270
+ const a = (indices[indexOffset + i] + vertexBase) * 3;
2271
+ const b = (indices[indexOffset + i + 1] + vertexBase) * 3;
2272
+ const c = (indices[indexOffset + i + 2] + vertexBase) * 3;
2273
+ const ux = positions[b] - positions[a];
2274
+ const uy = positions[b + 1] - positions[a + 1];
2275
+ const uz = positions[b + 2] - positions[a + 2];
2276
+ const vx = positions[c] - positions[a];
2277
+ const vy = positions[c + 1] - positions[a + 1];
2278
+ const vz = positions[c + 2] - positions[a + 2];
2279
+ let nx = uy * vz - uz * vy;
2280
+ let ny = uz * vx - ux * vz;
2281
+ let nz = ux * vy - uy * vx;
2282
+ const len = Math.hypot(nx, ny, nz) || 1;
2283
+ nx /= len;
2284
+ ny /= len;
2285
+ nz /= len;
2286
+ for (const vi of [
2287
+ a,
2288
+ b,
2289
+ c
2290
+ ]) {
2291
+ out[vi] = nx;
2292
+ out[vi + 1] = ny;
2293
+ out[vi + 2] = nz;
2294
+ }
2295
+ }
2296
+ }
2297
+ function mergeMeshGeometry(engine, name, meshes) {
2298
+ if (meshes.length === 0) throw new Error("mergeMeshGeometry requires at least one mesh");
2299
+ let totalVerts = 0;
2300
+ let totalIdx = 0;
2301
+ let anyUvs = false;
2302
+ for (const mesh of meshes) {
2303
+ if (!mesh._cpuPositions || !mesh._cpuIndices) throw new Error(`mergeMeshGeometry: mesh "${mesh.name}" is missing CPU geometry`);
2304
+ totalVerts += mesh._cpuPositions.length / 3;
2305
+ totalIdx += mesh._cpuIndices.length;
2306
+ if (mesh._cpuUvs?.length) anyUvs = true;
2307
+ }
2308
+ const positions = new Float32Array(totalVerts * 3);
2309
+ const normals = new Float32Array(totalVerts * 3);
2310
+ const uvs = anyUvs ? new Float32Array(totalVerts * 2) : void 0;
2311
+ const indices = new Uint32Array(totalIdx);
2312
+ let pOff = 0;
2313
+ let iOff = 0;
2314
+ let vertBase = 0;
2315
+ for (const mesh of meshes) {
2316
+ const src = mesh._cpuPositions;
2317
+ const srcNormals = mesh._cpuNormals;
2318
+ const srcUvs = mesh._cpuUvs;
2319
+ const wm = mesh.worldMatrix;
2320
+ const vertexCount = src.length / 3;
2321
+ const a = wm[0], b = wm[4], c = wm[8], d = wm[1], e = wm[5], f = wm[9], g = wm[2], h = wm[6], i = wm[10];
2322
+ const c00 = e * i - f * h, c01 = f * g - d * i, c02 = d * h - e * g, c10 = c * h - b * i, c11 = a * i - c * g, c12 = b * g - a * h, c20 = b * f - c * e, c21 = c * d - a * f, c22 = a * e - b * d;
2323
+ const normalSign = a * c00 + b * c01 + c * c02 < 0 ? -1 : 1;
2324
+ const reverseWinding = normalSign !== (mesh._authoredSign ?? 1);
2325
+ const meshVertexStart = pOff / 3;
2326
+ for (let v = 0; v < src.length; v += 3) {
2327
+ const x = src[v], y = src[v + 1], z = src[v + 2];
2328
+ positions[pOff] = x * a + y * b + z * c + wm[12];
2329
+ positions[pOff + 1] = x * d + y * e + z * f + wm[13];
2330
+ positions[pOff + 2] = x * g + y * h + z * i + wm[14];
2331
+ if (srcNormals) {
2332
+ const nx = srcNormals[v], ny = srcNormals[v + 1], nz = srcNormals[v + 2];
2333
+ let tx = (nx * c00 + ny * c01 + nz * c02) * normalSign;
2334
+ let ty = (nx * c10 + ny * c11 + nz * c12) * normalSign;
2335
+ let tz = (nx * c20 + ny * c21 + nz * c22) * normalSign;
2336
+ const len = Math.hypot(tx, ty, tz) || 1;
2337
+ tx /= len;
2338
+ ty /= len;
2339
+ tz /= len;
2340
+ normals[pOff] = tx;
2341
+ normals[pOff + 1] = ty;
2342
+ normals[pOff + 2] = tz;
2343
+ }
2344
+ pOff += 3;
2345
+ }
2346
+ if (uvs && srcUvs?.length) uvs.set(srcUvs.subarray(0, vertexCount * 2), meshVertexStart * 2);
2347
+ const meshIdx = mesh._cpuIndices;
2348
+ const indexCount = meshIdx.length;
2349
+ const indexStart = iOff;
2350
+ for (let k = 0; k < indexCount; k += 3) {
2351
+ indices[iOff++] = meshIdx[k] + vertBase;
2352
+ indices[iOff++] = meshIdx[k + (reverseWinding ? 2 : 1)] + vertBase;
2353
+ indices[iOff++] = meshIdx[k + (reverseWinding ? 1 : 2)] + vertBase;
2354
+ }
2355
+ if (!srcNormals) fillFlatNormals(positions, indices, indexStart, indexCount, 0, normals);
2356
+ vertBase += vertexCount;
2357
+ }
2358
+ return createMeshFromData(engine, name, positions, normals, indices, uvs);
2359
+ }
2360
+ //#endregion
2361
+ //#region src/meshes/meshes.ts
2362
+ /**
2363
+ * Babylon.js-compatible mesh hierarchy and `MeshBuilder`.
2364
+ *
2365
+ * Mirrors the Babylon.js inheritance chain:
2366
+ * `Mesh → AbstractMesh → TransformNode → Node`. Geometry is built through the
2367
+ * Babylon Lite mesh factories (which take the engine, not the scene) and
2368
+ * registered with `addToScene`. Transform properties (`position`, `rotation`,
2369
+ * `scaling`) are live views over Lite's observable vectors, so
2370
+ * `mesh.position.x = 1` and `mesh.rotation.y += 0.01` propagate; reassignment
2371
+ * (`mesh.position = new Vector3(...)`) also works.
2372
+ */
2373
+ var LinesMaterial = class LinesMaterial extends Material {
2374
+ _lite;
2375
+ constructor(name, lite, scene) {
2376
+ super(name, scene);
2377
+ this._lite = lite;
2378
+ }
2379
+ getClassName() {
2380
+ return "ShaderMaterial";
2381
+ }
2382
+ clone(name) {
2383
+ return new LinesMaterial(name, createLineMaterial({
2384
+ name,
2385
+ color: this._lite.color,
2386
+ useVertexColor: this._lite.useVertexColor,
2387
+ useVertexAlpha: this._lite.useVertexAlpha,
2388
+ useThinInstances: this._lite.useThinInstances,
2389
+ useThinInstanceColors: this._lite.useThinInstanceColors,
2390
+ depthWrite: this._lite.depthWrite,
2391
+ depthCompare: this._lite.depthCompare
2392
+ }), this.getScene());
2393
+ }
2394
+ };
2395
+ /**
2396
+ * @internal Runtime discriminator for the `Mesh` constructor's two call shapes:
2397
+ * `new Mesh(name, scene)` (empty mesh, Babylon.js) vs the internal
2398
+ * `new Mesh(name, liteMesh, scene)` (geometry-backed). A compat `Scene` exposes
2399
+ * `getEngine()`; a Lite mesh does not.
2400
+ */
2401
+ function isCompatScene(value) {
2402
+ return typeof value.getEngine === "function";
2403
+ }
2404
+ /**
2405
+ * @internal Resolve the backing Lite scene node for a compat node. Mesh/light/
2406
+ * camera wrappers store it as `_lite`; a plain `TransformNode` stores it as
2407
+ * `_node`. (Declared as optionals because the base `Node` exposes neither.)
2408
+ */
2409
+ function liteNodeOf(node) {
2410
+ if (!node) return null;
2411
+ const n = node;
2412
+ return n._node ?? n._lite ?? null;
2413
+ }
2414
+ var PLACEHOLDER_POSITIONS = new Float32Array([
2415
+ 0,
2416
+ 0,
2417
+ 0,
2418
+ 0,
2419
+ 0,
2420
+ 0,
2421
+ 0,
2422
+ 0,
2423
+ 0
2424
+ ]);
2425
+ var PLACEHOLDER_NORMALS = new Float32Array([
2426
+ 0,
2427
+ 0,
2428
+ 1,
2429
+ 0,
2430
+ 0,
2431
+ 1,
2432
+ 0,
2433
+ 0,
2434
+ 1
2435
+ ]);
2436
+ var PLACEHOLDER_UVS = new Float32Array([
2437
+ 0,
2438
+ 0,
2439
+ 0,
2440
+ 0,
2441
+ 0,
2442
+ 0
2443
+ ]);
2444
+ var PLACEHOLDER_INDICES = new Uint32Array([
2445
+ 0,
2446
+ 1,
2447
+ 2
2448
+ ]);
2449
+ /** @internal Coerce a number list / typed array to a `Float32Array` (reusing the buffer when possible). */
2450
+ function toF32(data) {
2451
+ return data instanceof Float32Array ? data : Float32Array.from(data);
2452
+ }
2453
+ /** @internal Coerce an index list / typed array to a `Uint32Array`. */
2454
+ function toU32(data) {
2455
+ return data instanceof Uint32Array ? data : Uint32Array.from(data);
2456
+ }
2457
+ /** @internal Flat per-face normals for vertex data that omits them (Lite requires a normals buffer). */
2458
+ function computeFlatNormals(positions, indices) {
2459
+ const normals = new Float32Array(positions.length);
2460
+ for (let i = 0; i < indices.length; i += 3) {
2461
+ const a = indices[i] * 3;
2462
+ const b = indices[i + 1] * 3;
2463
+ const c = indices[i + 2] * 3;
2464
+ const ux = positions[b] - positions[a];
2465
+ const uy = positions[b + 1] - positions[a + 1];
2466
+ const uz = positions[b + 2] - positions[a + 2];
2467
+ const vx = positions[c] - positions[a];
2468
+ const vy = positions[c + 1] - positions[a + 1];
2469
+ const vz = positions[c + 2] - positions[a + 2];
2470
+ let nx = uy * vz - uz * vy;
2471
+ let ny = uz * vx - ux * vz;
2472
+ let nz = ux * vy - uy * vx;
2473
+ const len = Math.hypot(nx, ny, nz) || 1;
2474
+ nx /= len;
2475
+ ny /= len;
2476
+ nz /= len;
2477
+ for (const vi of [
2478
+ a,
2479
+ b,
2480
+ c
2481
+ ]) {
2482
+ normals[vi] = nx;
2483
+ normals[vi + 1] = ny;
2484
+ normals[vi + 2] = nz;
2485
+ }
2486
+ }
2487
+ return normals;
2488
+ }
2489
+ /** @internal Return an attribute only when it has exactly one value tuple per vertex. */
2490
+ function matchingVertexAttribute(data, vertexCount, components) {
2491
+ return data?.length === vertexCount * components ? data : void 0;
2492
+ }
2493
+ /**
2494
+ * Babylon.js `TransformNode` — a positioned, rotated, scaled scene-graph node.
2495
+ * Wraps a Lite scene node (`_node`): either a standalone Lite transform node, or
2496
+ * (for meshes) the Lite mesh itself, which also carries the transform.
2497
+ */
2498
+ var TransformNode = class extends Node {
2499
+ /** @internal The Lite scene node that carries this transform. */
2500
+ _node;
2501
+ physicsBody = null;
2502
+ /**
2503
+ * @internal The Lite asset container this node was loaded from, when produced
2504
+ * by a loader. Used by the `KHR_materials_variants` helpers (which key off the
2505
+ * loaded root node) and to keep loaded meshes tied to their source asset.
2506
+ */
2507
+ _container;
2508
+ /**
2509
+ * @internal Bind a loader-produced wrapper to the scene the container was added
2510
+ * to. The loader already inserted the underlying Lite node (via
2511
+ * `addToScene(container)`), so this only wires the compat-side scene reference
2512
+ * and lists the wrapper in `scene.meshes` — it never re-inserts into Lite.
2513
+ */
2514
+ _bindLoadedScene(scene) {
2515
+ if (this._scene === scene) return;
2516
+ this._scene = scene;
2517
+ scene._registerMesh(this, this._node);
2518
+ }
2519
+ /** @internal Link an already-parented Lite node without mutating its Lite hierarchy. */
2520
+ _adoptLoadedParent(parent) {
2521
+ this._linkParent(parent);
2522
+ }
2523
+ constructor(name, scene, liteNode) {
2524
+ super(name, scene);
2525
+ if (liteNode) this._node = liteNode;
2526
+ else {
2527
+ this._node = createTransformNode(name);
2528
+ if (scene) addToScene(scene._lite, this._node);
2529
+ }
2530
+ }
2531
+ getClassName() {
2532
+ return "TransformNode";
2533
+ }
2534
+ get position() {
2535
+ return liteBackedVector3(this._node.position);
2536
+ }
2537
+ set position(value) {
2538
+ this._node.position.set(value.x, value.y, value.z);
2539
+ }
2540
+ get rotation() {
2541
+ return liteBackedVector3(this._node.rotation);
2542
+ }
2543
+ set rotation(value) {
2544
+ this._node.rotation.set(value.x, value.y, value.z);
2545
+ }
2546
+ get scaling() {
2547
+ return liteBackedVector3(this._node.scaling);
2548
+ }
2549
+ set scaling(value) {
2550
+ this._node.scaling.set(value.x, value.y, value.z);
2551
+ }
2552
+ /** @internal Whether `rotationQuaternion` was explicitly set (Babylon.js returns null otherwise). */
2553
+ _useQuat = false;
2554
+ /**
2555
+ * Babylon.js `rotationQuaternion`. Babylon Lite always drives a node's world
2556
+ * matrix from a quaternion (its euler `rotation` is a proxy over the same
2557
+ * quaternion), so this reads/writes that quaternion. Returns `null` until
2558
+ * explicitly assigned, matching Babylon.js's euler-by-default convention.
2559
+ */
2560
+ get rotationQuaternion() {
2561
+ if (!this._useQuat) return null;
2562
+ const q = this._node.rotationQuaternion;
2563
+ return new Quaternion(q.x, q.y, q.z, q.w);
2564
+ }
2565
+ set rotationQuaternion(value) {
2566
+ if (value) {
2567
+ this._useQuat = true;
2568
+ this._node.rotationQuaternion.set(value.x, value.y, value.z, value.w);
2569
+ } else this._useQuat = false;
2570
+ }
2571
+ /**
2572
+ * Babylon.js `setParent(node)` — reparent while **preserving world position**
2573
+ * (the child's local transform is recomputed). Distinct from the `parent`
2574
+ * setter, which keeps the local transform and lets the world move.
2575
+ */
2576
+ setParent(parent) {
2577
+ this._linkParent(parent);
2578
+ setParent(this._node, liteNodeOf(parent));
2579
+ return this;
2580
+ }
2581
+ _applyParent(parent) {
2582
+ this._node.parent = liteNodeOf(parent);
2583
+ }
2584
+ /** @internal Remove this wrapper's node without letting Lite recurse for `dispose(true)`. */
2585
+ _disposeSelf(doNotRecurse) {
2586
+ if (!this._scene) return;
2587
+ if (!doNotRecurse) {
2588
+ removeFromScene(this._scene._lite, this._node);
2589
+ return;
2590
+ }
2591
+ for (const child of this._node.children) child.parent = null;
2592
+ this._node.children.length = 0;
2593
+ removeFromScene(this._scene._lite, this._node);
2594
+ }
2595
+ };
2596
+ /**
2597
+ * Babylon.js `AbstractMesh` — a renderable transform node with a material,
2598
+ * visibility, and shadow-receipt. Concrete meshes derive from this.
2599
+ */
2600
+ var AbstractMesh = class extends TransformNode {
2601
+ /** @internal Underlying Babylon Lite mesh. */
2602
+ _lite;
2603
+ _material = null;
2604
+ _visible = true;
2605
+ constructor(name, lite, scene) {
2606
+ super(name, scene, lite);
2607
+ this._lite = lite;
2608
+ this._lite.name = name;
2609
+ if (scene) {
2610
+ this.material = scene.defaultMaterial;
2611
+ scene._registerMesh(this, this._lite);
2612
+ }
2613
+ }
2614
+ getClassName() {
2615
+ return "AbstractMesh";
2616
+ }
2617
+ /** @internal An `AbstractMesh` counts as a mesh node for `getChildMeshes`. */
2618
+ _isMeshNode() {
2619
+ return true;
2620
+ }
2621
+ get material() {
2622
+ return this._material;
2623
+ }
2624
+ set material(value) {
2625
+ this._material = value;
2626
+ const scene = this._scene;
2627
+ const renderMaterial = value ?? scene?.defaultMaterial;
2628
+ if (renderMaterial && scene?._hasStarted) {
2629
+ renderMaterial._adoptScene?.(scene);
2630
+ renderMaterial._ensureRenderable(engineOf(scene));
2631
+ }
2632
+ if (renderMaterial?._lite) this._lite.material = renderMaterial._lite;
2633
+ if (value && "_bindMesh" in value) value._bindMesh(this._lite, () => this._material === value);
2634
+ }
2635
+ get isVisible() {
2636
+ return this._visible;
2637
+ }
2638
+ set isVisible(value) {
2639
+ this._visible = value;
2640
+ this._syncVisibility(this.isEnabled());
2641
+ }
2642
+ get isPickable() {
2643
+ return this._lite.pickable !== false;
2644
+ }
2645
+ set isPickable(value) {
2646
+ this._lite.pickable = value;
2647
+ }
2648
+ get receiveShadows() {
2649
+ return this._lite.receiveShadows;
2650
+ }
2651
+ set receiveShadows(value) {
2652
+ this._lite.receiveShadows = value;
2653
+ }
2654
+ _onEffectiveEnabledStateChanged(enabled) {
2655
+ this._syncVisibility(enabled);
2656
+ }
2657
+ /** @internal Apply local visibility and effective enabled state to Lite. */
2658
+ _syncVisibility(enabled) {
2659
+ const visible = this._visible && enabled;
2660
+ if (this._lite.visible !== visible) setMeshVisible(this._lite, visible);
2661
+ }
2662
+ /**
2663
+ * Babylon.js `mesh.getBoundingInfo()` — the mesh's AABB. `minimum`/`maximum`
2664
+ * are the local-space bounds; the returned `BoundingInfo`'s world members
2665
+ * (`minimumWorld`/`maximumWorld`/`centerWorld`/…) are derived by transforming
2666
+ * the eight local corners by the mesh's world matrix, so a mesh at (1,2,3)
2667
+ * reports correctly-offset world bounds. Babylon Lite stores `boundMin`/
2668
+ * `boundMax` (local space) on factory- and loader-built meshes; when absent
2669
+ * (e.g. a placeholder mesh whose bounds were never computed) we fold the
2670
+ * retained CPU positions through Lite's `computeAabb`. A mesh with no geometry
2671
+ * returns a degenerate zero-size box.
2672
+ */
2673
+ getBoundingInfo() {
2674
+ const world = this._worldMatrixForBounds();
2675
+ const lo = this._lite.boundMin;
2676
+ const hi = this._lite.boundMax;
2677
+ if (lo && hi) return new BoundingInfo(new Vector3(lo[0], lo[1], lo[2]), new Vector3(hi[0], hi[1], hi[2]), world);
2678
+ const positions = this._lite._cpuPositions;
2679
+ if (positions && positions.length >= 3 && positions.length % 3 === 0) {
2680
+ const [min, max] = computeAabb(positions);
2681
+ if (Number.isFinite(min[0]) && Number.isFinite(min[1]) && Number.isFinite(min[2]) && Number.isFinite(max[0]) && Number.isFinite(max[1]) && Number.isFinite(max[2])) return new BoundingInfo(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2]), world);
2682
+ }
2683
+ return new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0), world);
2684
+ }
2685
+ /** Compat handle over Babylon Lite's world matrix for bounds derivation. Returns
2686
+ * `undefined` when the Lite node hasn't computed one (world bounds fall back to
2687
+ * local). */
2688
+ _worldMatrixForBounds() {
2689
+ const wm = this._lite.worldMatrix;
2690
+ return wm ? Matrix.FromArray(wm) : void 0;
2691
+ }
2692
+ /**
2693
+ * Babylon.js `mesh.getVerticesData(kind)` — read back the CPU geometry buffer.
2694
+ * `position` / `normal` / `uv` come from the buffers Babylon Lite retains on the
2695
+ * mesh (for picking + device-loss recovery). Prefer the last compat-side value
2696
+ * for `uv2` / `tangent` / `color`, falling back to attributes retained by Lite
2697
+ * for loader- and factory-created meshes.
2698
+ */
2699
+ getVerticesData(kind) {
2700
+ switch (kind) {
2701
+ case "position": return this._lite._cpuPositions ?? null;
2702
+ case "normal": return this._lite._cpuNormals ?? null;
2703
+ case "uv": return this._lite._cpuUvs ?? null;
2704
+ case "uv2": return this._lastUv2 ?? this._lite._cpuUv2s ?? null;
2705
+ case "tangent": return this._lastTangents ?? this._lite._cpuTangents ?? null;
2706
+ case "color": return this._lastColors ?? this._lite._cpuColors ?? null;
2707
+ default: return null;
2708
+ }
2709
+ }
2710
+ /**
2711
+ * Babylon.js `mesh.setVerticesData(kind, data)` — replace a vertex attribute.
2712
+ * `position` / `normal` / `uv` / `color` / `tangent` re-upload the geometry in
2713
+ * place; the last-set `color`/`tangent` buffers are retained so successive calls
2714
+ * (e.g. set tangent then set color) keep both. Skinning/morph attributes
2715
+ * (`matricesIndices`, etc.) are accepted but not applied (Babylon Lite drives
2716
+ * skinning through its own loaded-skeleton path).
2717
+ */
2718
+ setVerticesData(kind, data, _updatable) {
2719
+ const engine = this._scene?.getEngine()._lite;
2720
+ const lite = this._lite;
2721
+ if (!engine || !lite._cpuPositions || !lite._cpuIndices) return;
2722
+ if (kind !== "position" && kind !== "normal" && kind !== "uv" && kind !== "uv2" && kind !== "color" && kind !== "tangent") return;
2723
+ const f32 = data instanceof Float32Array ? data : Float32Array.from(data);
2724
+ if (kind === "uv2") this._lastUv2 = f32;
2725
+ if (kind === "color") this._lastColors = f32;
2726
+ if (kind === "tangent") this._lastTangents = f32;
2727
+ const positions = kind === "position" ? f32 : lite._cpuPositions;
2728
+ const vertexCount = positions.length / 3;
2729
+ const existingNormals = matchingVertexAttribute(lite._cpuNormals, vertexCount, 3);
2730
+ const normals = kind === "normal" ? f32 : existingNormals ?? computeFlatNormals(positions, lite._cpuIndices);
2731
+ if (kind === "position") this._normalsFollowIndices = !existingNormals;
2732
+ else if (kind === "normal") this._normalsFollowIndices = false;
2733
+ const existingUvs = matchingVertexAttribute(lite._cpuUvs, vertexCount, 2);
2734
+ const uvs = kind === "uv" ? f32 : existingUvs ?? (kind === "position" ? new Float32Array(vertexCount * 2) : void 0);
2735
+ const uvs2 = kind === "uv2" ? f32 : matchingVertexAttribute(this._lastUv2 ?? lite._cpuUv2s, vertexCount, 2);
2736
+ const tangents = matchingVertexAttribute(this._lastTangents ?? lite._cpuTangents, vertexCount, 4);
2737
+ const colors = matchingVertexAttribute(this._lastColors ?? lite._cpuColors, vertexCount, 4);
2738
+ resizeMeshGeometry(engine, this._lite, positions, normals, lite._cpuIndices, uvs, uvs2, tangents, colors);
2739
+ }
2740
+ /**
2741
+ * Babylon.js `mesh.getIndices()` — read back the mesh's index (topology) buffer.
2742
+ * Babylon Lite retains the indices on the mesh as a `Uint32Array` (for picking +
2743
+ * device-loss recovery), so we return that directly; a mesh with no geometry
2744
+ * returns `null`.
2745
+ */
2746
+ getIndices(_copyWhenShared, forceCopy) {
2747
+ const indices = this._lite._cpuIndices;
2748
+ return indices ? forceCopy ? indices.slice() : indices : null;
2749
+ }
2750
+ /**
2751
+ * Babylon.js `mesh.setIndices(indices)` — replace the mesh's index (topology)
2752
+ * buffer. Babylon Lite re-uploads the geometry in place via `resizeMeshGeometry`,
2753
+ * keeping the existing position/normal/uv/tangent/color attributes and swapping
2754
+ * only the indices. Returns the mesh for chaining.
2755
+ */
2756
+ setIndices(indices, _totalVertices, _updatable) {
2757
+ const engine = this._scene?.getEngine()._lite;
2758
+ const lite = this._lite;
2759
+ if (!engine || !lite._cpuPositions) return this;
2760
+ const u32 = indices instanceof Uint32Array ? indices : Uint32Array.from(indices);
2761
+ const positions = lite._cpuPositions;
2762
+ const vertexCount = positions.length / 3;
2763
+ const normals = this._normalsFollowIndices ? computeFlatNormals(positions, u32) : matchingVertexAttribute(lite._cpuNormals, vertexCount, 3) ?? computeFlatNormals(positions, u32);
2764
+ resizeMeshGeometry(engine, this._lite, positions, normals, u32, matchingVertexAttribute(lite._cpuUvs, vertexCount, 2), matchingVertexAttribute(this._lastUv2 ?? lite._cpuUv2s, vertexCount, 2), matchingVertexAttribute(this._lastTangents ?? lite._cpuTangents, vertexCount, 4), matchingVertexAttribute(this._lastColors ?? lite._cpuColors, vertexCount, 4));
2765
+ return this;
2766
+ }
2767
+ /** @internal Retained uv2/tangent/color buffers so successive `setVerticesData` (and a bake) keep them all. */
2768
+ _lastUv2;
2769
+ _lastTangents;
2770
+ _lastColors;
2771
+ /** @internal Position resizing generated normals from the old topology; regenerate after the next index update. */
2772
+ _normalsFollowIndices = false;
2773
+ /** Babylon.js `mesh.getTotalVertices()` — vertex count from the position buffer. */
2774
+ getTotalVertices() {
2775
+ const positions = this._lite._cpuPositions;
2776
+ return positions ? positions.length / 3 : 0;
2777
+ }
2778
+ /**
2779
+ * Babylon.js `mesh.refreshBoundingInfo()` — Babylon Lite recomputes a mesh's
2780
+ * bounds from its CPU geometry on demand (and on geometry upload), so this is a
2781
+ * no-op that returns the mesh for chaining. The deformed-pick options
2782
+ * (`applySkeleton` / `applyMorph`) are accepted for parity but not used.
2783
+ */
2784
+ refreshBoundingInfo(_options) {
2785
+ return this;
2786
+ }
2787
+ /**
2788
+ * @internal Shared bake: fold `matrix` into the retained CPU geometry and
2789
+ * re-upload it. Positions transform by the full matrix; **normals by the
2790
+ * inverse-transpose of the upper 3×3** (so they stay perpendicular to the baked
2791
+ * surface under non-uniform / sheared transforms, unlike a raw 3×3 multiply) and
2792
+ * are renormalized. The retained `uv` / `uv2` / `tangent` / `color` attributes are
2793
+ * forwarded unchanged so they survive the geometry reupload rather than being
2794
+ * dropped. Returns `false` when there is no geometry to bake.
2795
+ */
2796
+ _bakeMatrix(matrix) {
2797
+ const engine = this._scene?.getEngine()._lite;
2798
+ const lite = this._lite;
2799
+ const positions = lite._cpuPositions;
2800
+ const indices = lite._cpuIndices;
2801
+ if (!engine || !positions || !indices) return false;
2802
+ const m = matrix.m;
2803
+ const newPositions = new Float32Array(positions.length);
2804
+ for (let i = 0; i < positions.length; i += 3) {
2805
+ const x = positions[i], y = positions[i + 1], z = positions[i + 2];
2806
+ newPositions[i] = x * m[0] + y * m[4] + z * m[8] + m[12];
2807
+ newPositions[i + 1] = x * m[1] + y * m[5] + z * m[9] + m[13];
2808
+ newPositions[i + 2] = x * m[2] + y * m[6] + z * m[10] + m[14];
2809
+ }
2810
+ let bakedIndices = indices;
2811
+ if (matrix.determinant() < 0) {
2812
+ bakedIndices = new Uint32Array(indices);
2813
+ for (let i = 0; i + 2 < bakedIndices.length; i += 3) {
2814
+ const second = bakedIndices[i + 1];
2815
+ bakedIndices[i + 1] = bakedIndices[i + 2];
2816
+ bakedIndices[i + 2] = second;
2817
+ }
2818
+ }
2819
+ let newNormals;
2820
+ const normals = lite._cpuNormals;
2821
+ if (normals) {
2822
+ const nm = matrix.invert().transpose().m;
2823
+ newNormals = new Float32Array(normals.length);
2824
+ for (let i = 0; i < normals.length; i += 3) {
2825
+ const x = normals[i], y = normals[i + 1], z = normals[i + 2];
2826
+ let nx = x * nm[0] + y * nm[4] + z * nm[8];
2827
+ let ny = x * nm[1] + y * nm[5] + z * nm[9];
2828
+ let nz = x * nm[2] + y * nm[6] + z * nm[10];
2829
+ const len = Math.hypot(nx, ny, nz) || 1;
2830
+ nx /= len;
2831
+ ny /= len;
2832
+ nz /= len;
2833
+ newNormals[i] = nx;
2834
+ newNormals[i + 1] = ny;
2835
+ newNormals[i + 2] = nz;
2836
+ }
2837
+ } else newNormals = computeFlatNormals(newPositions, bakedIndices);
2838
+ const tangents = this._lastTangents ?? lite._cpuTangents ?? void 0;
2839
+ let newTangents;
2840
+ if (tangents) {
2841
+ newTangents = new Float32Array(tangents.length);
2842
+ for (let i = 0; i < tangents.length; i += 4) {
2843
+ const x = tangents[i], y = tangents[i + 1], z = tangents[i + 2];
2844
+ let tx = x * m[0] + y * m[4] + z * m[8];
2845
+ let ty = x * m[1] + y * m[5] + z * m[9];
2846
+ let tz = x * m[2] + y * m[6] + z * m[10];
2847
+ const len = Math.hypot(tx, ty, tz) || 1;
2848
+ tx /= len;
2849
+ ty /= len;
2850
+ tz /= len;
2851
+ newTangents[i] = tx;
2852
+ newTangents[i + 1] = ty;
2853
+ newTangents[i + 2] = tz;
2854
+ newTangents[i + 3] = tangents[i + 3];
2855
+ }
2856
+ }
2857
+ resizeMeshGeometry(engine, this._lite, newPositions, newNormals, bakedIndices, lite._cpuUvs, this._lastUv2 ?? lite._cpuUv2s ?? void 0, newTangents, this._lastColors ?? lite._cpuColors ?? void 0);
2858
+ return true;
2859
+ }
2860
+ /**
2861
+ * Babylon.js `mesh.bakeCurrentTransformIntoVertices()` — fold the node's local
2862
+ * transform (position / rotation / scaling) into the CPU geometry via the shared
2863
+ * {@link _bakeMatrix} helper, then reset the node transform to identity (the
2864
+ * geometry now carries it).
2865
+ */
2866
+ bakeCurrentTransformIntoVertices() {
2867
+ const node = this._node;
2868
+ const q = node.rotationQuaternion;
2869
+ const matrix = Matrix.Compose(liteBackedVector3(node.scaling), {
2870
+ x: q.x,
2871
+ y: q.y,
2872
+ z: q.z,
2873
+ w: q.w
2874
+ }, liteBackedVector3(node.position));
2875
+ if (!this._bakeMatrix(matrix)) return this;
2876
+ node.position.set(0, 0, 0);
2877
+ node.rotation.set(0, 0, 0);
2878
+ node.scaling.set(1, 1, 1);
2879
+ return this;
2880
+ }
2881
+ /**
2882
+ * Babylon.js `mesh.bakeTransformIntoVertices(transform)` — fold an **arbitrary**
2883
+ * matrix into the CPU geometry via the shared {@link _bakeMatrix} helper. Unlike
2884
+ * {@link bakeCurrentTransformIntoVertices}, the node's own transform is **not**
2885
+ * reset: the supplied matrix is independent of the node transform.
2886
+ */
2887
+ bakeTransformIntoVertices(transform) {
2888
+ this._bakeMatrix(transform);
2889
+ return this;
2890
+ }
2891
+ };
2892
+ /** Babylon.js `Mesh` — a concrete renderable mesh with geometry. */
2893
+ var Mesh = class Mesh extends AbstractMesh {
2894
+ constructor(name, sceneOrLite, scene) {
2895
+ if (sceneOrLite !== void 0 && isCompatScene(sceneOrLite)) {
2896
+ const realScene = sceneOrLite;
2897
+ const lite = createMeshFromData(realScene.getEngine()._lite, name, PLACEHOLDER_POSITIONS, PLACEHOLDER_NORMALS, PLACEHOLDER_INDICES, PLACEHOLDER_UVS);
2898
+ super(name, lite, realScene);
2899
+ addPrimitive(this, realScene);
2900
+ } else super(name, sceneOrLite, scene);
2901
+ }
2902
+ getClassName() {
2903
+ return "Mesh";
2904
+ }
2905
+ /**
2906
+ * @internal Wrap an already-loaded Lite mesh (or the loader's synthetic root
2907
+ * node) as a canonical compat `Mesh`. Unlike the public constructor it does
2908
+ * **not** re-insert the node into the scene (the loader already added the whole
2909
+ * container) and does **not** override the natively-loaded material — it only
2910
+ * adopts the existing Lite node. Used by the loader to give
2911
+ * `AssetContainer.meshes` real, stable-identity mesh handles.
2912
+ */
2913
+ static _fromLite(lite, container, scene) {
2914
+ const mesh = new Mesh(lite.name ?? "", lite);
2915
+ mesh._container = container;
2916
+ mesh._visible = lite.visible !== false;
2917
+ if (scene) mesh._bindLoadedScene(scene);
2918
+ return mesh;
2919
+ }
2920
+ /** @internal Wrap and link a complete Lite hierarchy, registering every wrapper. */
2921
+ static _fromLiteHierarchy(lite, container, scene, registry = /* @__PURE__ */ new Map(), parent = null) {
2922
+ let wrapper = registry.get(lite);
2923
+ if (!wrapper) {
2924
+ wrapper = Mesh._fromLite(lite, container, scene);
2925
+ registry.set(lite, wrapper);
2926
+ } else if (scene) wrapper._bindLoadedScene(scene);
2927
+ wrapper._adoptLoadedParent(parent);
2928
+ const children = lite.children;
2929
+ if (children) for (const child of children) Mesh._fromLiteHierarchy(child, container, scene, registry, wrapper);
2930
+ return wrapper;
2931
+ }
2932
+ _morphTargetManager = null;
2933
+ /**
2934
+ * Babylon.js `mesh.morphTargetManager`. Babylon Lite builds morph GPU data via
2935
+ * `createMorphTargets` and stores it on the Lite mesh; the compat manager is
2936
+ * registered with the scene so the engine builds it at start (once the base
2937
+ * CPU geometry exists) and assigns it onto the Lite mesh before registration.
2938
+ */
2939
+ get morphTargetManager() {
2940
+ return this._morphTargetManager;
2941
+ }
2942
+ set morphTargetManager(value) {
2943
+ this._morphTargetManager = value;
2944
+ if (value && this._scene) this._scene._registerMorphTargetManager(this, value);
2945
+ }
2946
+ /** Legacy `Mesh.CreateSphere(name, segments, diameter, scene)`. */
2947
+ static CreateSphere(name, segments, diameter, scene) {
2948
+ return MeshBuilder.CreateSphere(name, {
2949
+ segments,
2950
+ diameter
2951
+ }, scene);
2952
+ }
2953
+ /** Legacy `Mesh.CreateBox(name, size, scene)`. */
2954
+ static CreateBox(name, size, scene) {
2955
+ return MeshBuilder.CreateBox(name, { size }, scene);
2956
+ }
2957
+ /** Legacy `Mesh.CreateGround(name, width, height, subdivisions, scene)`. */
2958
+ static CreateGround(name, width, height, subdivisions, scene) {
2959
+ return MeshBuilder.CreateGround(name, {
2960
+ width,
2961
+ height,
2962
+ subdivisions
2963
+ }, scene);
2964
+ }
2965
+ /** Legacy `Mesh.CreatePlane(name, size, scene)`. */
2966
+ static CreatePlane(name, size, scene) {
2967
+ return MeshBuilder.CreatePlane(name, { size }, scene);
2968
+ }
2969
+ /** Legacy `Mesh.CreateCylinder(name, height, diameterTop, diameterBottom, tessellation, _subdivisions, scene)`. */
2970
+ static CreateCylinder(name, height, diameterTop, diameterBottom, tessellation, _subdivisions, scene) {
2971
+ const diameter = Math.max(diameterTop, diameterBottom);
2972
+ return MeshBuilder.CreateCylinder(name, {
2973
+ height,
2974
+ diameter,
2975
+ tessellation
2976
+ }, scene);
2977
+ }
2978
+ /** Legacy `Mesh.CreateTorus(name, diameter, thickness, tessellation, scene)`. */
2979
+ static CreateTorus(name, diameter, thickness, tessellation, scene) {
2980
+ return MeshBuilder.CreateTorus(name, {
2981
+ diameter,
2982
+ thickness,
2983
+ tessellation
2984
+ }, scene);
2985
+ }
2986
+ /** Hardware-instanced copy — unsupported. Use native thin instances instead. */
2987
+ createInstance() {
2988
+ return unsupported("Mesh.createInstance", "Babylon Lite has no hardware-instance object. Use the native thin-instance API (`setThinInstances`).");
2989
+ }
2990
+ /**
2991
+ * Babylon.js `mesh.thinInstanceSetBuffer(kind, buffer, stride)`. Maps the
2992
+ * `"matrix"` and `"color"` instance buffers onto Babylon Lite's thin-instance
2993
+ * API. Applied immediately to the Lite mesh (before the scene builds).
2994
+ */
2995
+ thinInstanceSetBuffer(kind, buffer, _stride = 16) {
2996
+ if (!buffer) return;
2997
+ if (kind === "matrix") setThinInstances(this._lite, buffer, buffer.length / 16);
2998
+ else if (kind === "color") setThinInstanceColors(this._lite, buffer);
2999
+ }
3000
+ /**
3001
+ * Babylon.js `mesh.clone(name, newParent?, doNotCloneChildren?)` — a new mesh
3002
+ * that shares this mesh's geometry. Forwards to Lite's `cloneTransformNode`,
3003
+ * which shares the `_gpu`/skeleton/morph/thin-instance resources with the clone
3004
+ * under ref-counting (so both meshes own the buffers and they survive until the
3005
+ * last is disposed). Babylon.js uses the requested name verbatim, derives clone
3006
+ * IDs from that name plus the source ID, and prefixes descendant names with the
3007
+ * root clone name. The source material is kept (BJS shares it by reference), and
3008
+ * the clone is registered with the same compat scene through its own wrapper.
3009
+ * An omitted or `null` `newParent` keeps the source parent.
3010
+ * `doNotCloneChildren` drops the descendants Lite always clones.
3011
+ */
3012
+ clone(name = "", newParent = null, doNotCloneChildren) {
3013
+ const scene = this._scene;
3014
+ const liteClone = cloneTransformNode(this._lite);
3015
+ const wrappedClone = Mesh._wrapCloneHierarchy(this, liteClone, scene, null, doNotCloneChildren === true, name);
3016
+ if (!(wrappedClone instanceof Mesh)) throw new Error("Mesh.clone produced a non-mesh root.");
3017
+ const clone = wrappedClone;
3018
+ if (scene) addPrimitive(clone, scene, doNotCloneChildren ? () => pruneClonedDescendants(scene, liteClone) : void 0);
3019
+ const parent = newParent ?? this.parent;
3020
+ if (parent) clone.parent = parent;
3021
+ return clone;
3022
+ }
3023
+ static _wrapCloneHierarchy(source, lite, scene, parent, skipChildren, cloneName) {
3024
+ if (cloneName !== void 0) lite.name = cloneName;
3025
+ const wrapper = source instanceof Mesh || "_gpu" in lite && "material" in lite ? new Mesh(lite.name ?? "", lite) : new TransformNode(lite.name ?? "", scene, lite);
3026
+ wrapper._container = source?._container;
3027
+ if (wrapper instanceof Mesh) {
3028
+ wrapper._scene = scene;
3029
+ if (scene) scene._registerMesh(wrapper, lite);
3030
+ }
3031
+ wrapper.parent = parent;
3032
+ if (source) {
3033
+ wrapper.id = wrapper instanceof Mesh ? `${wrapper.name}.${source.id}` : wrapper.name;
3034
+ wrapper.metadata = source.metadata;
3035
+ wrapper.setEnabled(source.isEnabled(false));
3036
+ if (wrapper instanceof Mesh && source instanceof Mesh) {
3037
+ wrapper.material = source.material;
3038
+ wrapper.isVisible = source.isVisible;
3039
+ }
3040
+ }
3041
+ if (!skipChildren) {
3042
+ const sourceLiteChildren = liteNodeOf(source ?? null)?.children ?? [];
3043
+ const sourceChildren = source?.getChildren(void 0, true) ?? [];
3044
+ for (let i = 0; i < lite.children.length; i++) {
3045
+ const sourceLiteChild = sourceLiteChildren[i];
3046
+ const sourceChild = sourceChildren.find((child) => liteNodeOf(child) === sourceLiteChild);
3047
+ const childName = sourceChild ? `${wrapper.name}.${sourceChild.name}` : void 0;
3048
+ Mesh._wrapCloneHierarchy(sourceChild, lite.children[i], scene, wrapper, false, childName);
3049
+ }
3050
+ }
3051
+ return wrapper;
3052
+ }
3053
+ /** Level-of-detail — unsupported (no LOD system in Babylon Lite). */
3054
+ addLODLevel() {
3055
+ return unsupported("Mesh.addLODLevel", "Level-of-detail is not implemented in Babylon Lite.");
3056
+ }
3057
+ /**
3058
+ * Babylon.js `Mesh.MergeMeshes` — bake several meshes into one, transforming
3059
+ * each source's geometry by its world matrix. Signature:
3060
+ * `MergeMeshes(meshes, disposeSource?, allow32BitsIndices?, meshSubclass?, subdivideWithSubMeshes?, multiMultiMaterials?)`.
3061
+ * Uses the compat-local `mergeMeshGeometry`; the merged mesh lives at
3062
+ * identity (world transforms are baked in) and takes the first mesh's material.
3063
+ *
3064
+ * **Supported semantics** (everything else is rejected, never silently dropped):
3065
+ * - `disposeSource` (default `true`) — source meshes are disposed after merge.
3066
+ * - `allow32BitsIndices` — Lite indices are always uint32, so 32-bit is always
3067
+ * available. When `allow32BitsIndices` is falsy and the merged vertex count
3068
+ * reaches 65536, this returns `null`, exactly like Babylon.js.
3069
+ * - Positions, normals (world-transformed) and one UV set are carried.
3070
+ *
3071
+ * **Rejected** (throws `LiteCompatError`): `multiMultiMaterials` /
3072
+ * `subdivideWithSubMeshes` (Lite has no submesh / multi-material partitioning),
3073
+ * a supplied `meshSubclass` target, and sources carrying vertex colours,
3074
+ * tangents or a second UV set, or sources carrying skeleton, morph-target, or
3075
+ * vertex-animation data (Lite would have to drop them).
3076
+ */
3077
+ static MergeMeshes(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) {
3078
+ const sources = meshes.filter((m) => !!m);
3079
+ if (sources.length === 0) return null;
3080
+ if (multiMultiMaterials || subdivideWithSubMeshes) return unsupported("Mesh.MergeMeshes(multiMultiMaterials/subdivideWithSubMeshes)", "Babylon Lite renders one material per mesh with no submesh partitioning, so multi-material / subdivided merges cannot be produced. Merge per-material groups into separate meshes instead.");
3081
+ if (meshSubclass) return unsupported("Mesh.MergeMeshes(meshSubclass)", "Merging into an existing target mesh is not wrapped; the merge always returns a fresh mesh. Merge without a meshSubclass and use the result.");
3082
+ if (!allow32BitsIndices) {
3083
+ let totalVertices = 0;
3084
+ for (const mesh of sources) {
3085
+ totalVertices += mesh.getTotalVertices();
3086
+ if (totalVertices >= 65536) return null;
3087
+ }
3088
+ }
3089
+ for (const mesh of sources) {
3090
+ const lite = mesh._lite;
3091
+ if (lite._cpuColors || lite._cpuTangents || lite._cpuUv2s) return unsupported("Mesh.MergeMeshes(colors/tangents/uv2)", `Mesh "${mesh.name}" carries vertex colours, tangents or a second UV set, which the merge does not carry. Strip those attributes before merging, or keep the meshes separate.`);
3092
+ if (lite.skeleton || lite.morphTargets || lite.vat) return unsupported("Mesh.MergeMeshes(animation)", `Mesh "${mesh.name}" carries skeleton, morph-target, or vertex-animation data, which the merge does not carry. Bake the deformation before merging, or keep the meshes separate.`);
3093
+ }
3094
+ const scene = sources[0].getScene();
3095
+ if (!scene) return null;
3096
+ const lite = mergeMeshGeometry(scene.getEngine()._lite, sources[0].name, sources.map((m) => m._lite));
3097
+ const merged = new Mesh(sources[0].name, lite, scene);
3098
+ merged.material = sources[0].material;
3099
+ addPrimitive(merged, scene);
3100
+ if (disposeSource) for (const mesh of sources) mesh.dispose();
3101
+ return merged;
3102
+ }
3103
+ };
3104
+ function createObservableLineColor(onChange) {
3105
+ const color = new Color3(1, 1, 1);
3106
+ let r = color.r;
3107
+ let g = color.g;
3108
+ let b = color.b;
3109
+ Object.defineProperties(color, {
3110
+ r: {
3111
+ get: () => r,
3112
+ set: (value) => {
3113
+ r = value;
3114
+ onChange(color);
3115
+ },
3116
+ enumerable: true,
3117
+ configurable: true
3118
+ },
3119
+ g: {
3120
+ get: () => g,
3121
+ set: (value) => {
3122
+ g = value;
3123
+ onChange(color);
3124
+ },
3125
+ enumerable: true,
3126
+ configurable: true
3127
+ },
3128
+ b: {
3129
+ get: () => b,
3130
+ set: (value) => {
3131
+ b = value;
3132
+ onChange(color);
3133
+ },
3134
+ enumerable: true,
3135
+ configurable: true
3136
+ }
3137
+ });
3138
+ return color;
3139
+ }
3140
+ /** Babylon.js `LinesMesh` backed by a Babylon Lite line-system mesh. */
3141
+ var LinesMesh = class extends Mesh {
3142
+ useVertexColor;
3143
+ useVertexAlpha;
3144
+ intersectionThreshold = .1;
3145
+ _lineMaterial;
3146
+ _color;
3147
+ _alpha = 1;
3148
+ _suspendLineColorSync = false;
3149
+ constructor(name, sceneOrLite, scene, useVertexColor = false, useVertexAlpha = true) {
3150
+ const realScene = isCompatScene(sceneOrLite) ? sceneOrLite : scene;
3151
+ const lite = isCompatScene(sceneOrLite) ? createLineSystem(engineOf(sceneOrLite), {
3152
+ name,
3153
+ lines: [[new Vector3(0, 0, 0)]],
3154
+ ...useVertexColor ? { colors: [[new Color4(1, 1, 1, 1)]] } : {},
3155
+ useVertexAlpha
3156
+ }) : sceneOrLite;
3157
+ const lineMaterial = lite.material;
3158
+ super(name, lite, realScene);
3159
+ this.useVertexColor = useVertexColor;
3160
+ this.useVertexAlpha = useVertexAlpha;
3161
+ this._lineMaterial = new LinesMaterial("colorShader", lineMaterial, realScene);
3162
+ this.material = this._lineMaterial;
3163
+ this._color = createObservableLineColor(() => {
3164
+ if (!this._suspendLineColorSync) this._syncLineColor();
3165
+ });
3166
+ if (isCompatScene(sceneOrLite)) addPrimitive(this, sceneOrLite);
3167
+ }
3168
+ getClassName() {
3169
+ return "LinesMesh";
3170
+ }
3171
+ get color() {
3172
+ return this._color;
3173
+ }
3174
+ set color(value) {
3175
+ this._suspendLineColorSync = true;
3176
+ try {
3177
+ this._color.copyFrom(value);
3178
+ } finally {
3179
+ this._suspendLineColorSync = false;
3180
+ }
3181
+ this._syncLineColor();
3182
+ }
3183
+ get alpha() {
3184
+ return this._alpha;
3185
+ }
3186
+ set alpha(value) {
3187
+ this._alpha = value;
3188
+ this._syncLineColor();
3189
+ }
3190
+ thinInstanceSetBuffer(kind, buffer, stride = 16) {
3191
+ super.thinInstanceSetBuffer(kind, buffer, stride);
3192
+ if (buffer && (kind === "matrix" || kind === "color")) this._enableThinLineMaterial(kind === "color" || this._lineMaterial._lite.useThinInstanceColors);
3193
+ }
3194
+ _enableThinLineMaterial(useThinInstanceColors) {
3195
+ if (this._lineMaterial._lite.useThinInstances && this._lineMaterial._lite.useThinInstanceColors === useThinInstanceColors) return;
3196
+ const lite = createLineMaterial({
3197
+ name: this._lineMaterial.name,
3198
+ color: {
3199
+ r: this._color.r,
3200
+ g: this._color.g,
3201
+ b: this._color.b,
3202
+ a: this._alpha
3203
+ },
3204
+ useVertexColor: this.useVertexColor,
3205
+ useVertexAlpha: this.useVertexAlpha,
3206
+ useThinInstances: true,
3207
+ useThinInstanceColors,
3208
+ depthWrite: this._lineMaterial._lite.depthWrite,
3209
+ depthCompare: this._lineMaterial._lite.depthCompare
3210
+ });
3211
+ this._lineMaterial = new LinesMaterial(this._lineMaterial.name, lite, this.getScene());
3212
+ this.material = this._lineMaterial;
3213
+ }
3214
+ _syncLineColor() {
3215
+ setLineMaterialColor(this._lineMaterial._lite, {
3216
+ r: this._color.r,
3217
+ g: this._color.g,
3218
+ b: this._color.b,
3219
+ a: this._alpha
3220
+ });
3221
+ }
3222
+ };
3223
+ /** Babylon.js `GroundMesh` — a ground plane mesh. CPU height queries are not modelled. */
3224
+ var GroundMesh = class extends Mesh {
3225
+ getClassName() {
3226
+ return "GroundMesh";
3227
+ }
3228
+ /** CPU height-at-coordinates query — needs a CPU heightmap accessor not present in Babylon Lite. */
3229
+ getHeightAtCoordinates() {
3230
+ return unsupported("GroundMesh.getHeightAtCoordinates", "CPU height queries are not implemented in Babylon Lite.");
3231
+ }
3232
+ };
3233
+ /** Babylon.js `InstancedMesh` — hardware instances are not modelled; use thin instances. */
3234
+ var InstancedMesh = class {
3235
+ constructor() {
3236
+ unsupported("InstancedMesh", "Babylon Lite has no hardware-instance object. Use the native thin-instance API (`setThinInstances`).");
3237
+ }
3238
+ };
3239
+ /**
3240
+ * Babylon.js `VertexBuffer` — the per-attribute geometry buffer. Only the `kind`
3241
+ * string constants are surfaced (used with `mesh.getVerticesData` /
3242
+ * `setVerticesData`); the buffer-object API itself is not wrapped.
3243
+ */
3244
+ var VertexBuffer = {
3245
+ PositionKind: "position",
3246
+ NormalKind: "normal",
3247
+ TangentKind: "tangent",
3248
+ UVKind: "uv",
3249
+ UV2Kind: "uv2",
3250
+ ColorKind: "color",
3251
+ MatricesIndicesKind: "matricesIndices",
3252
+ MatricesWeightsKind: "matricesWeights"
3253
+ };
3254
+ /**
3255
+ * Babylon.js `VertexData` — CPU vertex attribute container. Pure data; apply it
3256
+ * to a Lite mesh via the native geometry-update APIs when needed.
3257
+ */
3258
+ var VertexData = class {
3259
+ positions = null;
3260
+ normals = null;
3261
+ uvs = null;
3262
+ colors = null;
3263
+ indices = null;
3264
+ /**
3265
+ * Babylon.js `VertexData.applyToMesh(mesh)` — upload this CPU geometry onto a
3266
+ * mesh (typically one created via `new Mesh(name, scene)`). Replaces the Lite
3267
+ * mesh's geometry in place via `resizeMeshGeometry`. Normals are computed flat
3268
+ * if omitted (Babylon Lite requires a normals buffer).
3269
+ */
3270
+ applyToMesh(mesh) {
3271
+ if (!this.positions || !this.indices) return;
3272
+ const scene = mesh.getScene();
3273
+ if (!scene) return;
3274
+ const engine = scene.getEngine()._lite;
3275
+ const positions = toF32(this.positions);
3276
+ const indices = toU32(this.indices);
3277
+ const normals = this.normals ? toF32(this.normals) : computeFlatNormals(positions, indices);
3278
+ const uvs = this.uvs ? toF32(this.uvs) : void 0;
3279
+ const colors = this.colors ? toF32(this.colors) : void 0;
3280
+ resizeMeshGeometry(engine, mesh._lite, positions, normals, indices, uvs, void 0, void 0, colors);
3281
+ }
3282
+ /** Merge another `VertexData` into this one (concatenating attributes + reindexing). */
3283
+ merge(other) {
3284
+ const baseVertexCount = this.positions ? this.positions.length / 3 : 0;
3285
+ this.positions = concat(this.positions, other.positions);
3286
+ this.normals = concat(this.normals, other.normals);
3287
+ this.uvs = concat(this.uvs, other.uvs);
3288
+ this.colors = concat(this.colors, other.colors);
3289
+ if (other.indices) {
3290
+ const shifted = Array.from(other.indices, (i) => i + baseVertexCount);
3291
+ this.indices = this.indices ? [...Array.from(this.indices), ...shifted] : shifted;
3292
+ }
3293
+ return this;
3294
+ }
3295
+ };
3296
+ function concat(a, b) {
3297
+ if (!a && !b) return null;
3298
+ return [...a ? Array.from(a) : [], ...b ? Array.from(b) : []];
3299
+ }
3300
+ function engineOf(scene) {
3301
+ return scene.getEngine()._lite;
3302
+ }
3303
+ /**
3304
+ * Add a freshly-constructed mesh to its Lite scene. The wrapper constructor has
3305
+ * already assigned the mesh's material (a real one or `scene.defaultMaterial`),
3306
+ * but Babylon.js code commonly reassigns `mesh.material` a line later. Lite locks
3307
+ * a mesh into a render group at add time, so we defer the add until engine start
3308
+ * (via `scene._deferAdd`) to let those assignments settle.
3309
+ */
3310
+ function addPrimitive(mesh, scene, afterAdd) {
3311
+ scene._deferAdd(() => {
3312
+ if (mesh.isDisposed()) return;
3313
+ const mat = mesh.material;
3314
+ mat?._ensureRenderable(engineOf(scene));
3315
+ if (mat?._lite) mesh._lite.material = mat._lite;
3316
+ addToScene(scene._lite, mesh._lite);
3317
+ afterAdd?.();
3318
+ });
3319
+ return mesh;
3320
+ }
3321
+ /**
3322
+ * Drop the descendants Lite's `cloneTransformNode` always clones, for
3323
+ * `mesh.clone(..., doNotCloneChildren = true)`. `addToScene` already registered
3324
+ * them (it recurses into `children`), so `removeFromScene` here releases their
3325
+ * shared, ref-counted GPU claims — the source keeps its buffers — and detaches
3326
+ * them, leaving the clone a lone node with no leak.
3327
+ */
3328
+ function pruneClonedDescendants(scene, liteClone) {
3329
+ for (const child of [...liteClone.children]) removeFromScene(scene._lite, child);
3330
+ liteClone.children.length = 0;
3331
+ }
3332
+ /** Babylon.js `MeshBuilder` — factory namespace for primitive meshes. */
3333
+ var MeshBuilder = {
3334
+ CreateBox(name, options, scene) {
3335
+ return addPrimitive(new Mesh(name, createBox(engineOf(scene), options), scene), scene);
3336
+ },
3337
+ CreateSphere(name, options, scene) {
3338
+ return addPrimitive(new Mesh(name, createSphere(engineOf(scene), options), scene), scene);
3339
+ },
3340
+ CreateGround(name, options, scene) {
3341
+ return addPrimitive(new Mesh(name, createGround(engineOf(scene), options), scene), scene);
3342
+ },
3343
+ /**
3344
+ * Babylon.js `MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene)`.
3345
+ * Babylon.js returns the mesh synchronously and fills its geometry once the
3346
+ * heightmap image loads; we mirror that by returning a placeholder `GroundMesh`
3347
+ * immediately and swapping in the real geometry (via `resizeMeshGeometry`) when
3348
+ * the async Lite `createGroundFromHeightMap` resolves. The load is tracked so
3349
+ * the engine awaits it before the scene is registered.
3350
+ */
3351
+ CreateGroundFromHeightMap(name, url, options, scene) {
3352
+ const engine = engineOf(scene);
3353
+ const mesh = new GroundMesh(name, scene);
3354
+ scene._trackTextureLoad(createGroundFromHeightMap(engine, url, options).then((lite) => {
3355
+ resizeMeshGeometry(engine, mesh._lite, lite._cpuPositions, lite._cpuNormals, lite._cpuIndices, lite._cpuUvs);
3356
+ const baseUvs = lite._cpuUvs;
3357
+ if (baseUvs) scene._registerGroundUvBake(() => {
3358
+ const albedo = mesh.material?.albedoTexture ?? null;
3359
+ const uScale = albedo?.uScale ?? 1;
3360
+ const vScale = albedo?.vScale ?? 1;
3361
+ if (uScale === 1 && vScale === 1) return;
3362
+ const scaled = new Float32Array(baseUvs.length);
3363
+ for (let i = 0; i < baseUvs.length; i += 2) {
3364
+ scaled[i] = baseUvs[i] * uScale;
3365
+ scaled[i + 1] = baseUvs[i + 1] * vScale;
3366
+ }
3367
+ updateMeshUvs(engine, mesh._lite, scaled);
3368
+ mesh._lite._cpuUvs = scaled;
3369
+ });
3370
+ }));
3371
+ return mesh;
3372
+ },
3373
+ CreatePlane(name, options, scene) {
3374
+ return addPrimitive(new Mesh(name, createPlane(engineOf(scene), options), scene), scene);
3375
+ },
3376
+ CreateCylinder(name, options, scene) {
3377
+ return addPrimitive(new Mesh(name, createCylinder(engineOf(scene), options), scene), scene);
3378
+ },
3379
+ CreateTorus(name, options, scene) {
3380
+ return addPrimitive(new Mesh(name, createTorus(engineOf(scene), options), scene), scene);
3381
+ },
3382
+ CreateTorusKnot(name, options, scene) {
3383
+ return addPrimitive(new Mesh(name, createTorusKnot(engineOf(scene), options), scene), scene);
3384
+ },
3385
+ CreateDisc(name, options, scene) {
3386
+ return addPrimitive(new Mesh(name, createDisc(engineOf(scene), options), scene), scene);
3387
+ },
3388
+ CreatePolyhedron(name, options, scene) {
3389
+ return addPrimitive(new Mesh(name, createPolyhedron(engineOf(scene), options), scene), scene);
3390
+ },
3391
+ CreateRibbon(name, options, scene) {
3392
+ return addPrimitive(new Mesh(name, createRibbon(engineOf(scene), options), scene), scene);
3393
+ },
3394
+ CreateTube(name, options, scene) {
3395
+ return addPrimitive(new Mesh(name, createTube(engineOf(scene), options), scene), scene);
3396
+ },
3397
+ ExtrudeShape(name, options, scene) {
3398
+ return addPrimitive(new Mesh(name, createExtrudeShape(engineOf(scene), options), scene), scene);
3399
+ },
3400
+ CreateLines(name, options, scene) {
3401
+ return CreateLineSystem(name, {
3402
+ lines: [options.points],
3403
+ updatable: options.updatable,
3404
+ instance: options.instance,
3405
+ colors: options.colors ? [options.colors] : void 0,
3406
+ useVertexAlpha: options.useVertexAlpha,
3407
+ material: options.material
3408
+ }, scene);
3409
+ },
3410
+ CreateLineSystem(name, options, scene) {
3411
+ if (options.instance) {
3412
+ const instanceScene = options.instance.getScene() ?? scene;
3413
+ if (!instanceScene) throw new Error("MeshBuilder.CreateLineSystem requires the instance to belong to a scene");
3414
+ updateLineSystem(engineOf(instanceScene), options.instance._lite, {
3415
+ lines: options.lines,
3416
+ ...options.colors ? { colors: options.colors } : {}
3417
+ });
3418
+ return options.instance;
3419
+ }
3420
+ if (options.material) return unsupported("MeshBuilder.CreateLineSystem.material", "Custom line materials are not implemented in Babylon Lite compatibility mode.");
3421
+ if (!scene) throw new Error("MeshBuilder.CreateLineSystem requires a scene when creating a line system");
3422
+ return addPrimitive(new LinesMesh(name, createLineSystem(engineOf(scene), {
3423
+ name,
3424
+ lines: options.lines,
3425
+ ...options.colors ? { colors: options.colors } : {},
3426
+ useVertexAlpha: options.useVertexAlpha
3427
+ }), scene, !!options.colors, options.useVertexAlpha ?? true), scene);
3428
+ },
3429
+ CreateDashedLines(name, options, scene) {
3430
+ if (options.instance) {
3431
+ const instanceScene = options.instance.getScene() ?? scene;
3432
+ if (!instanceScene) throw new Error("MeshBuilder.CreateDashedLines requires the instance to belong to a scene");
3433
+ updateDashedLines(engineOf(instanceScene), options.instance._lite, { points: options.points });
3434
+ return options.instance;
3435
+ }
3436
+ if (options.material) return unsupported("MeshBuilder.CreateDashedLines.material", "Custom line materials are not implemented in Babylon Lite compatibility mode.");
3437
+ if (!scene) throw new Error("MeshBuilder.CreateDashedLines requires a scene");
3438
+ return addPrimitive(new LinesMesh(name, createDashedLines(engineOf(scene), {
3439
+ name,
3440
+ points: options.points,
3441
+ ...options.dashSize !== void 0 ? { dashSize: options.dashSize } : {},
3442
+ ...options.gapSize !== void 0 ? { gapSize: options.gapSize } : {},
3443
+ ...options.dashNb !== void 0 ? { dashNb: options.dashNb } : {},
3444
+ useVertexAlpha: options.useVertexAlpha
3445
+ }), scene, false, options.useVertexAlpha ?? true), scene);
3446
+ },
3447
+ CreateDecal() {
3448
+ return unsupported("MeshBuilder.CreateDecal", "Decal projection is not implemented in Babylon Lite.");
3449
+ },
3450
+ CreateText() {
3451
+ return unsupported("MeshBuilder.CreateText", "Extruded font meshes are not implemented in Babylon Lite. For 2D/SDF text use the native `createTextRenderable` API.");
3452
+ },
3453
+ CreateTiledBox(_name, _options, _scene) {
3454
+ return unsupported("MeshBuilder.CreateTiledBox", "Tiled box geometry is not implemented in Babylon Lite. Its per-face tile-pattern UV layout (tile size, alignment, per-tile flip/rotate patterns) is a non-trivial vertex-data generator with pattern design choices — not a mechanical addition — so it needs a Lite core mesh-builder decision.");
3455
+ },
3456
+ CreateTiledPlane(_name, _options, _scene) {
3457
+ return unsupported("MeshBuilder.CreateTiledPlane", "Tiled plane geometry is not implemented in Babylon Lite. Its per-tile UV layout (tile size, alignment, per-tile flip/rotate patterns) is a non-trivial vertex-data generator with pattern design choices — not a mechanical addition — so it needs a Lite core mesh-builder decision.");
3458
+ }
3459
+ };
3460
+ /** Babylon.js `CreateBox(name, options, scene)` (boxBuilder). */
3461
+ function CreateBox(name, options, scene) {
3462
+ return MeshBuilder.CreateBox(name, options, scene);
3463
+ }
3464
+ /** Babylon.js `CreateSphere(name, options, scene)` (sphereBuilder). */
3465
+ function CreateSphere(name, options, scene) {
3466
+ return MeshBuilder.CreateSphere(name, options, scene);
3467
+ }
3468
+ /** Babylon.js `CreateGround(name, options, scene)` (groundBuilder). */
3469
+ function CreateGround(name, options, scene) {
3470
+ return MeshBuilder.CreateGround(name, options, scene);
3471
+ }
3472
+ /** Babylon.js `CreatePlane(name, options, scene)` (planeBuilder). */
3473
+ function CreatePlane(name, options, scene) {
3474
+ return MeshBuilder.CreatePlane(name, options, scene);
3475
+ }
3476
+ /** Babylon.js `CreateCylinder(name, options, scene)` (cylinderBuilder). */
3477
+ function CreateCylinder(name, options, scene) {
3478
+ return MeshBuilder.CreateCylinder(name, options, scene);
3479
+ }
3480
+ /** Babylon.js `CreateTorus(name, options, scene)` (torusBuilder). */
3481
+ function CreateTorus(name, options, scene) {
3482
+ return MeshBuilder.CreateTorus(name, options, scene);
3483
+ }
3484
+ /** Babylon.js `CreateDisc(name, options, scene)` (discBuilder). */
3485
+ function CreateDisc(name, options, scene) {
3486
+ return MeshBuilder.CreateDisc(name, options, scene);
3487
+ }
3488
+ /** Babylon.js `CreateLines(name, options, scene)` (linesBuilder). */
3489
+ function CreateLines(name, options, scene) {
3490
+ return MeshBuilder.CreateLines(name, options, scene);
3491
+ }
3492
+ /** Babylon.js `CreateLineSystem(name, options, scene)` (linesBuilder). */
3493
+ function CreateLineSystem(name, options, scene) {
3494
+ return MeshBuilder.CreateLineSystem(name, options, scene);
3495
+ }
3496
+ /** Babylon.js `CreateDashedLines(name, options, scene)` (linesBuilder). */
3497
+ function CreateDashedLines(name, options, scene) {
3498
+ return MeshBuilder.CreateDashedLines(name, options, scene);
3499
+ }
3500
+ /** Babylon.js `CreateTiledBox(name, options, scene)` (tiledBoxBuilder) — throwing stub (see `MeshBuilder.CreateTiledBox`). */
3501
+ function CreateTiledBox(name, options, scene) {
3502
+ return MeshBuilder.CreateTiledBox(name, options, scene);
3503
+ }
3504
+ /** Babylon.js `CreateTiledPlane(name, options, scene)` (tiledPlaneBuilder) — throwing stub (see `MeshBuilder.CreateTiledPlane`). */
3505
+ function CreateTiledPlane(name, options, scene) {
3506
+ return MeshBuilder.CreateTiledPlane(name, options, scene);
3507
+ }
3508
+ //#endregion
3509
+ export { PushMaterial as A, Quaternion as B, PBRAnisotropicConfiguration as C, PBRMetallicRoughnessMaterial as D, PBRMaterial as E, BoundingInfo as F, Vector4 as G, Color4 as H, BoundingSphere as I, unsupported as J, liteBackedVector3 as K, Matrix as L, Node as M, Observable as N, PBRSheenConfiguration as O, BoundingBox as P, transformCoordinates as R, Material as S, PBRIridescenceConfiguration as T, Vector2 as U, Color3 as V, Vector3 as W, Mesh as _, CreateDisc as a, VertexBuffer as b, CreateLines as c, CreateTiledBox as d, CreateTiledPlane as f, LinesMesh as g, InstancedMesh as h, CreateDashedLines as i, StandardMaterial as j, PBRSpecularGlossinessMaterial as k, CreatePlane as l, GroundMesh as m, CreateBox as n, CreateGround as o, CreateTorus as p, LiteCompatError as q, CreateCylinder as r, CreateLineSystem as s, AbstractMesh as t, CreateSphere as u, MeshBuilder as v, PBRClearCoatConfiguration as w, VertexData as x, TransformNode as y, transformNormal as z };
3510
+
3511
+ //# sourceMappingURL=meshes-DJ46g22_.js.map