rayzee 11.16.0 → 11.17.0

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.
Files changed (107) hide show
  1. package/README.md +1 -1
  2. package/dist/ArchiveFormats-_WrBUn7t.js +2796 -0
  3. package/dist/{ArchiveImporter-CEv5EDgg.js → ArchiveImporter-CdtFzb0f.js} +1345 -1305
  4. package/dist/BidirectionalIntegrator-BH-c324Z.js +960 -0
  5. package/dist/{BufferLayout-ny3WneEc.js → BufferLayout-QzWWnb3A.js} +3 -0
  6. package/dist/{CameraRay-CdVb2LnS.js → CameraRay-gszl6gQ8.js} +20 -12
  7. package/dist/{ColorManagement-B6SgefNi.js → ColorManagement-D7Vcr71o.js} +36 -37
  8. package/dist/Common-jRX6P1vs.js +683 -0
  9. package/dist/CompactKernel-cuEVr6Jy.js +21025 -0
  10. package/dist/DepthPass-BAXPCPq-.js +69 -0
  11. package/dist/{LocalExposure-CMO6fd8G.js → LocalExposure-DUUpAbvu.js} +1 -1
  12. package/dist/{NeuralRetouch-CYRGwe9E.js → NeuralRetouch-RRRAJJZw.js} +3 -3
  13. package/dist/{NeuralSuperRes-p0A3_wjO.js → NeuralSuperRes-BXu9pHRi.js} +4 -4
  14. package/dist/{OpenStorage-CjlOYQyW.js → OpenStorage-PsDTuAHF.js} +2 -2
  15. package/dist/{PhysicalSky-qHATDBbB.js → PhysicalSky-Cbf04lJr.js} +310 -310
  16. package/dist/{PictureView-6y4XsUf0.js → PictureView-CqcqmjYy.js} +29 -29
  17. package/dist/{RayzeeRenderer-ClGfovbz.js → RayzeeRenderer-y85Ubgr_.js} +2539 -3702
  18. package/dist/{TextureBuckets-CcOI4Bdg.js → TextureBuckets-BfkUIWK6.js} +2 -0
  19. package/dist/{TextureSampling-CQMmzhCp.js → TextureSampling-Cmd2X04v.js} +129 -126
  20. package/dist/{ToneMapGPU-tJZo_-7S.js → ToneMapGPU-CVKz1Wun.js} +1 -1
  21. package/dist/{ViewTransforms-Bh7hSjSb.js → ViewTransforms-BjMXpgR2.js} +95 -66
  22. package/dist/addons/archives.es.js +2 -2
  23. package/dist/addons/bidirectional.es.js +1 -1
  24. package/dist/addons/color.es.js +1 -1
  25. package/dist/addons/physical-sky.es.js +1 -1
  26. package/dist/addons/storage.es.js +1 -1
  27. package/dist/rayzee-core.es.js +9 -10
  28. package/dist/rayzee.es.js +772 -788
  29. package/dist/rayzee.umd.js +110 -110
  30. package/package.json +2 -2
  31. package/src/EngineDefaults.js +2 -0
  32. package/src/RayzeeRenderer.js +92 -51
  33. package/src/RenderSettings.js +8 -0
  34. package/src/addons/archives/ArchiveImporter.js +67 -20
  35. package/src/addons/archives/ArchiveReader.js +4 -1
  36. package/src/addons/archives/pbrt/PBRTSceneBuilder.js +42 -12
  37. package/src/addons/archives/pbrt/index.js +12 -2
  38. package/src/addons/archives/usd/USDScene.js +25 -3
  39. package/src/addons/bidirectional/Bidirectional.js +1 -0
  40. package/src/addons/bidirectional/BidirectionalIntegrator.js +6 -6
  41. package/src/addons/color/ColorSpaces.js +2 -1
  42. package/src/addons/color/OcioViews.js +3 -3
  43. package/src/addons/physical-sky/PhysicalSky.js +2 -3
  44. package/src/addons/storage/OpenStorage.js +2 -0
  45. package/src/bvh/ReinsertionOptimizer.js +3 -2
  46. package/src/environment/EnvironmentManager.js +2 -2
  47. package/src/lights/LightManager.js +3 -2
  48. package/src/lights/LightSerializer.js +5 -4
  49. package/src/loaders/AssetLoader.js +3 -2
  50. package/src/loaders/PlatformImageLoader.js +180 -12
  51. package/src/loaders/SceneLoading.js +2 -0
  52. package/src/materials/MaterialDataManager.js +19 -7
  53. package/src/materials/MaterialPacking.js +5 -1
  54. package/src/materials/TextureCreator.js +137 -22
  55. package/src/output/Pictures.js +0 -1
  56. package/src/output/TextureReadback.js +2 -1
  57. package/src/pathtracer/KernelManager.js +21 -4
  58. package/src/pathtracer/PackedRayBuffer.js +3 -14
  59. package/src/pathtracer/PathTracer.js +24 -26
  60. package/src/pathtracer/PathTracerStage.js +5 -0
  61. package/src/pathtracer/QueueManager.js +9 -11
  62. package/src/pathtracer/StorageTexturePool.js +24 -35
  63. package/src/pathtracer/UniformManager.js +2 -0
  64. package/src/pipeline/Compositor.js +2 -2
  65. package/src/scene/BufferLayout.js +5 -3
  66. package/src/scene/GeometryExtractor.js +22 -2
  67. package/src/scene/SceneEdits.js +5 -1
  68. package/src/scene/SceneProcessor.js +2 -0
  69. package/src/scene/ViewCamera.js +2 -1
  70. package/src/shaders/Common.js +9 -1
  71. package/src/shaders/DFGTable.js +16 -16
  72. package/src/shaders/EmissiveSampling.js +56 -7
  73. package/src/shaders/Fog.js +238 -90
  74. package/src/shaders/LightBVHSampling.js +28 -9
  75. package/src/shaders/LightsDirect.js +32 -20
  76. package/src/shaders/LightsIndirect.js +6 -8
  77. package/src/shaders/LightsSampling.js +5 -4
  78. package/src/shaders/MaterialProperties.js +22 -3
  79. package/src/shaders/MaterialTransmission.js +125 -152
  80. package/src/shaders/Random.js +4 -1
  81. package/src/shaders/SceneResources.js +9 -1
  82. package/src/shaders/Struct.js +2 -0
  83. package/src/shaders/TextureSampling.js +18 -7
  84. package/src/shaders/ThreePatches.js +3 -33
  85. package/src/shaders/kernels/DepthPass.js +1 -2
  86. package/src/shaders/kernels/ShadeKernel.js +44 -19
  87. package/src/viewer/PathTracerApp.js +2 -1
  88. package/src/viewer/animation/VideoRenderManager.js +2 -0
  89. package/src/viewer/camera/CameraManager.js +1 -1
  90. package/src/viewer/denoise/DenoisingManager.js +2 -2
  91. package/src/viewer/denoise/MotionVector.js +6 -26
  92. package/src/viewer/denoise/NRD.js +25 -40
  93. package/src/viewer/denoise/NormalDepth.js +14 -46
  94. package/src/viewer/denoise/OIDNDenoiser.js +13 -15
  95. package/src/viewer/overlays/ViewOverlayRenderer.js +2 -1
  96. package/src/viewer/picture/AIUpscaler.js +8 -0
  97. package/src/viewer/picture/PictureView.js +5 -2
  98. package/dist/ArchiveFormats-CWi6IbSp.js +0 -1401
  99. package/dist/AssetConfig-C8BsprCp.js +0 -30
  100. package/dist/BidirectionalIntegrator-KWRQrMXX.js +0 -960
  101. package/dist/CompactKernel-C6TCBB6i.js +0 -19759
  102. package/dist/DepthPass-BMnBuepB.js +0 -69
  103. package/dist/PackedRayBuffer-BhqeNEaL.js +0 -802
  104. /package/dist/{EngineEvents-oQGofgRf.js → EngineEvents-Cdhzr9Bq.js} +0 -0
  105. /package/dist/{EngineIssues-DHAU18xh.js → EngineIssues-pnvWClTX.js} +0 -0
  106. /package/dist/{SolarLimb-IayvafJP.js → SolarLimb-BiVdxxmL.js} +0 -0
  107. /package/dist/{ZipReader-D6LbMsfZ.js → ZipReader-CEcslQJR.js} +0 -0
@@ -0,0 +1,2796 @@
1
+ import { a as e, i as t, r as n } from "./Logger-D7hic8LA.js";
2
+ import { a as r, i, l as a, n as o, r as s, t as c } from "./TextureBuckets-BfkUIWK6.js";
3
+ import { _ as l, f as u, h as d, l as f, m as p, r as m, v as h, y as g } from "./BufferLayout-QzWWnb3A.js";
4
+ import { n as _, t as v } from "./EngineIssues-pnvWClTX.js";
5
+ import { d as y, s as b } from "./FileIdentity-BXmPNvJP.js";
6
+ import { r as x } from "./ActiveColor-DakLCifA.js";
7
+ import { a as S, p as C, u as w, y as T } from "./ViewTransforms-BjMXpgR2.js";
8
+ import { BackSide as ee, Box3 as E, BufferAttribute as D, Color as O, DataArrayTexture as k, DataTexture as te, DataUtils as ne, DoubleSide as re, FloatType as ie, FrontSide as ae, HalfFloatType as oe, LinearFilter as A, LinearSRGBColorSpace as se, LoaderUtils as ce, Matrix3 as le, Matrix4 as ue, NoToneMapping as de, RGBAFormat as j, RGFormat as fe, RedFormat as pe, RepeatWrapping as me, SRGBColorSpace as M, Texture as he, UnsignedByteType as ge, UnsignedShortType as _e, Vector2 as ve, Vector3 as ye } from "three";
9
+ //#region src/materials/MaterialPacking.js
10
+ var be = [
11
+ 1,
12
+ 0,
13
+ 0,
14
+ 0,
15
+ 1,
16
+ 0,
17
+ 0,
18
+ 0
19
+ ], xe = [
20
+ ["mapMatrix", f.ALBEDO_TRANSFORM],
21
+ ["normalMapMatrices", f.NORMAL_TRANSFORM],
22
+ ["roughnessMapMatrices", f.ROUGHNESS_TRANSFORM],
23
+ ["metalnessMapMatrices", f.METALNESS_TRANSFORM],
24
+ ["emissiveMapMatrices", f.EMISSIVE_TRANSFORM],
25
+ ["bumpMapMatrices", f.BUMP_TRANSFORM],
26
+ ["displacementMapMatrices", f.DISPLACEMENT_TRANSFORM]
27
+ ], Se = Object.freeze(new Set([
28
+ "metalness",
29
+ "roughness",
30
+ "transmission",
31
+ "opacity",
32
+ "clearcoat",
33
+ "clearcoatRoughness",
34
+ "sheen",
35
+ "sheenRoughness",
36
+ "specularIntensity",
37
+ "iridescence",
38
+ "subsurface",
39
+ "anisotropy",
40
+ "diffuseTransmission",
41
+ "diffuseRoughness"
42
+ ])), Ce = (e) => Math.min(Math.max(e, 0), 1);
43
+ function N(e, t) {
44
+ let n = typeof e == "boolean" ? +e : e;
45
+ return Number.isFinite(n) ? n : t;
46
+ }
47
+ function P(e) {
48
+ return Number.isInteger(e) ? e : -1;
49
+ }
50
+ function F(e, t, n, r) {
51
+ let i = n?.r ?? n?.[0] ?? n?.x, a = n?.g ?? n?.[1] ?? n?.y, o = n?.b ?? n?.[2] ?? n?.z;
52
+ e[t] = N(i, r[0]), e[t + 1] = N(a, r[1]), e[t + 2] = N(o, r[2]);
53
+ }
54
+ function we(e, t, n) {
55
+ let r = (n, r, i) => {
56
+ e[t + n] = N(r, i);
57
+ }, i = (n, r, i) => {
58
+ e[t + n] = Ce(N(r, i));
59
+ };
60
+ r(f.IOR, n.ior, a.ior), i(f.TRANSMISSION, n.transmission, a.transmission), r(f.THICKNESS, n.thickness, a.thickness), r(f.EMISSIVE_INTENSITY, n.emissiveIntensity, a.emissiveIntensity), F(e, t + f.ATTENUATION_COLOR, n.attenuationColor, a.attenuationColor), e[t + f.ATTENUATION_DISTANCE] = l(n.attenuationDistance ?? a.attenuationDistance), i(f.OPACITY, n.opacity, a.opacity), r(f.SIDE, n.side, a.side), r(f.TRANSPARENT, n.transparent, a.transparent), r(f.ALPHA_TEST, n.alphaTest, a.alphaTest), r(f.ALPHA_MODE, n.alphaMode, a.alphaMode), r(f.DEPTH_WRITE, n.depthWrite, a.depthWrite);
61
+ let o = n.normalScale, s = typeof o == "number" ? o : void 0;
62
+ r(f.NORMAL_SCALE, s ?? o?.x ?? o?.[0], a.normalScale[0]), F(e, t + f.COLOR, n.color, a.color), i(f.METALNESS, n.metalness, a.metalness), F(e, t + f.EMISSIVE, n.emissive, a.emissive), i(f.ROUGHNESS, n.roughness, a.roughness), e[t + f.ALBEDO_MAP_INDEX] = P(n.map), e[t + f.NORMAL_MAP_INDEX] = P(n.normalMap), e[t + f.ROUGHNESS_MAP_INDEX] = P(n.roughnessMap), e[t + f.METALNESS_MAP_INDEX] = P(n.metalnessMap), e[t + f.EMISSIVE_MAP_INDEX] = P(n.emissiveMap), e[t + f.BUMP_MAP_INDEX] = P(n.bumpMap), e[t + f.DIFFUSE_ROUGHNESS_MAP_INDEX] = P(n.diffuseRoughnessMap), i(f.CLEARCOAT, n.clearcoat, a.clearcoat), i(f.CLEARCOAT_ROUGHNESS, n.clearcoatRoughness, a.clearcoatRoughness), r(f.DISPERSION, n.dispersion, a.dispersion), i(f.DIFFUSE_ROUGHNESS, n.diffuseRoughness, a.diffuseRoughness), i(f.SHEEN, n.sheen, a.sheen), i(f.SHEEN_ROUGHNESS, n.sheenRoughness, a.sheenRoughness), F(e, t + f.SHEEN_COLOR, n.sheenColor, a.sheenColor), i(f.DIFFUSE_TRANSMISSION, n.diffuseTransmission, a.diffuseTransmission), i(f.SPECULAR_INTENSITY, n.specularIntensity, a.specularIntensity), F(e, t + f.SPECULAR_COLOR, n.specularColor, a.specularColor), i(f.IRIDESCENCE, n.iridescence, a.iridescence), r(f.IRIDESCENCE_IOR, n.iridescenceIOR, a.iridescenceIOR), r(f.IRIDESCENCE_THICKNESS_RANGE, n.iridescenceThicknessRange?.[0], a.iridescenceThicknessRange[0]), r(f.IRIDESCENCE_THICKNESS_RANGE + 1, n.iridescenceThicknessRange?.[1], a.iridescenceThicknessRange[1]), r(f.BUMP_SCALE, n.bumpScale, a.bumpScale), r(f.DISPLACEMENT_SCALE, n.displacementScale, a.displacementScale), e[t + f.DISPLACEMENT_MAP_INDEX] = P(n.displacementMap), r(f.DISPLACEMENT_BIAS, n.displacementBias, a.displacementBias);
63
+ for (let [r, i] of xe) {
64
+ let a = n[r];
65
+ for (let n = 0; n < 8; n++) e[t + i + n] = N(a?.[n], be[n]);
66
+ }
67
+ e[t + f.BUMP_MAP_WIDTH] = N(n.bumpMapSize?.[0], 0), e[t + f.BUMP_MAP_HEIGHT] = N(n.bumpMapSize?.[1], 0), F(e, t + f.SUBSURFACE_COLOR, n.subsurfaceColor, a.subsurfaceColor), i(f.SUBSURFACE, n.subsurface, a.subsurface), F(e, t + f.SUBSURFACE_RADIUS, n.subsurfaceRadius, a.subsurfaceRadius), r(f.SUBSURFACE_RADIUS_SCALE, n.subsurfaceRadiusScale, a.subsurfaceRadiusScale), r(f.SUBSURFACE_ANISOTROPY, n.subsurfaceAnisotropy, a.subsurfaceAnisotropy), i(f.ANISOTROPY, n.anisotropy, a.anisotropy), r(f.ANISOTROPY_ROTATION, n.anisotropyRotation, a.anisotropyRotation), e[t + f.ANISOTROPY_MAP_INDEX] = P(n.anisotropyMap), e[t + f.TRANSMISSION_MAP_INDEX] = P(n.transmissionMap), e[t + f.CLEARCOAT_MAP_INDEX] = P(n.clearcoatMap), e[t + f.CLEARCOAT_ROUGHNESS_MAP_INDEX] = P(n.clearcoatRoughnessMap), e[t + f.SHEEN_COLOR_MAP_INDEX] = P(n.sheenColorMap), e[t + f.SHEEN_ROUGHNESS_MAP_INDEX] = P(n.sheenRoughnessMap), e[t + f.IRIDESCENCE_MAP_INDEX] = P(n.iridescenceMap), e[t + f.IRIDESCENCE_THICKNESS_MAP_INDEX] = P(n.iridescenceThicknessMap), e[t + f.SPECULAR_INTENSITY_MAP_INDEX] = P(n.specularIntensityMap), e[t + f.SPECULAR_COLOR_MAP_INDEX] = P(n.specularColorMap), F(e, t + f.DIFFUSE_TRANSMISSION_COLOR, n.diffuseTransmissionColor, a.diffuseTransmissionColor), e[t + f.DIFFUSE_TRANSMISSION_MAP_INDEX] = P(n.diffuseTransmissionMap), e[t + f.DIFFUSE_TRANSMISSION_COLOR_MAP_INDEX] = P(n.diffuseTransmissionColorMap), e[t + f.CLEARCOAT_NORMAL_MAP_INDEX] = P(n.clearcoatNormalMap);
68
+ let c = n.clearcoatNormalScale;
69
+ r(f.CLEARCOAT_NORMAL_SCALE, typeof c == "number" ? c : c?.x ?? c?.[0], a.clearcoatNormalScale[0]);
70
+ }
71
+ //#endregion
72
+ //#region src/memory/ChunkedRecords.js
73
+ var I = 64 * 1024 * 1024, Te = typeof SharedArrayBuffer < "u", Ee = null;
74
+ function De(e) {
75
+ Ee = e;
76
+ }
77
+ function L(e, t, n) {
78
+ let r = n ? new e(new SharedArrayBuffer(t * e.BYTES_PER_ELEMENT)) : new e(t);
79
+ return Ee && r.byteLength > 0 && Ee(r.byteLength, n), r;
80
+ }
81
+ var Oe = class e {
82
+ constructor(e, t, n, r = I, i = !1) {
83
+ let a = t * n.BYTES_PER_ELEMENT, o = Math.max(1, Math.floor(r / a));
84
+ this.recordCount = e, this.lanesPerRecord = t, this.LaneType = n, this.recordsPerChunk = e <= o ? Math.max(e, 1) : o, this.shared = i, this.chunks = [];
85
+ let s = e;
86
+ for (; s > 0;) {
87
+ let e = Math.min(s, this.recordsPerChunk);
88
+ this.chunks.push(L(n, e * t, i)), s -= e;
89
+ }
90
+ this.chunks.length === 0 && this.chunks.push(L(n, 0, i));
91
+ }
92
+ static adopt(t, n, r, i) {
93
+ let a = Object.create(e.prototype);
94
+ return a.recordCount = n, a.lanesPerRecord = r, a.LaneType = t[0]?.constructor ?? null, a.recordsPerChunk = i, a.chunks = t, a.shared = typeof SharedArrayBuffer < "u" && t[0]?.buffer instanceof SharedArrayBuffer, a;
95
+ }
96
+ static lazy(t, n, r, i = I, a = !1) {
97
+ let o = Math.max(1, Math.floor(i / (n * r.BYTES_PER_ELEMENT))), s = Object.create(e.prototype);
98
+ return s.recordCount = t, s.lanesPerRecord = n, s.LaneType = r, s.recordsPerChunk = t <= o ? Math.max(t, 1) : o, s.shared = a, s.chunks = Array(Math.max(1, Math.ceil(t / s.recordsPerChunk))), s._views = [], s;
99
+ }
100
+ _materialize(e) {
101
+ if (this._owner) return this._owner._materialize(e), this.chunks[e];
102
+ let t = e * this.recordsPerChunk, n = Math.min(this.recordsPerChunk, this.recordCount - t) * this.lanesPerRecord, r = this.chunks[e] = L(this.LaneType, n, this.shared);
103
+ for (let t of this._liveViews()) t.chunks[e] = new t.LaneType(r.buffer, r.byteOffset, r.byteLength / t.LaneType.BYTES_PER_ELEMENT);
104
+ return r;
105
+ }
106
+ materializeAll() {
107
+ for (let e = 0; e < this.chunks.length; e++) !this.chunks[e] && !this._spilled?.has(e) && this._materialize(e);
108
+ return this;
109
+ }
110
+ get chunkCount() {
111
+ return this.chunks.length;
112
+ }
113
+ get single() {
114
+ return this.chunks.length === 1 ? this.chunks[0] : null;
115
+ }
116
+ get byteLength() {
117
+ let e = 0;
118
+ for (let t of this.chunks) t && (e += t.byteLength);
119
+ return e;
120
+ }
121
+ chunkFor(e) {
122
+ let t = e / this.recordsPerChunk | 0, n = this.chunks[t];
123
+ if (n) return n;
124
+ if (this._spilled?.has(t)) throw Error(`ChunkedRecords: chunk ${t} is on disk — await ensureResident() before touching record ${e}`);
125
+ return this._materialize(t);
126
+ }
127
+ async spill(e, { keep: t = () => !1 } = {}) {
128
+ if (this._owner) throw Error("ChunkedRecords: spill the storage, not a view of it");
129
+ this._store = e, this._spilled ??= /* @__PURE__ */ new Set();
130
+ let n = 0;
131
+ for (let r = 0; r < this.chunks.length; r++) {
132
+ let i = this.chunks[r];
133
+ if (!(!i || t(r))) {
134
+ await e.write(r, i), this.chunks[r] = null;
135
+ for (let e of this._liveViews()) e.chunks[r] = null;
136
+ this._spilled.add(r), n += i.byteLength;
137
+ }
138
+ }
139
+ return n;
140
+ }
141
+ async spillChunk(e, t) {
142
+ let n = this.chunks[e];
143
+ if (!n) return 0;
144
+ this._store = t, this._spilled ??= /* @__PURE__ */ new Set(), await t.write(e, n), this.chunks[e] = null;
145
+ for (let t of this._liveViews()) t.chunks[e] = null;
146
+ return this._spilled.add(e), n.byteLength;
147
+ }
148
+ async ensureResident(e = 0, t = this.recordCount) {
149
+ if (!this._spilled?.size || t <= 0) return;
150
+ let n = e / this.recordsPerChunk | 0, r = (e + t - 1) / this.recordsPerChunk | 0;
151
+ for (let e = n; e <= r; e++) {
152
+ if (!this._spilled.has(e)) continue;
153
+ let t = Math.min(this.recordsPerChunk, this.recordCount - e * this.recordsPerChunk) * this.lanesPerRecord, n = L(this.LaneType, t, this.shared), r = new Uint8Array(n.buffer, n.byteOffset, n.byteLength);
154
+ this._store.readInto ? await this._store.readInto(e, r) : r.set(new Uint8Array(await this._store.read(e, r.byteLength))), this.chunks[e] = n;
155
+ for (let t of this._liveViews()) t.chunks[e] = new t.LaneType(n.buffer, n.byteOffset, n.byteLength / t.LaneType.BYTES_PER_ELEMENT);
156
+ this._spilled.delete(e);
157
+ }
158
+ }
159
+ _liveViews() {
160
+ return this._weakViews &&= this._weakViews.filter((e) => e.deref()), [...this._views ?? [], ...(this._weakViews ?? []).map((e) => e.deref())];
161
+ }
162
+ isResident(e = 0, t = this.recordCount) {
163
+ if (!this._spilled?.size || t <= 0) return !0;
164
+ let n = e / this.recordsPerChunk | 0, r = (e + t - 1) / this.recordsPerChunk | 0;
165
+ for (let e = n; e <= r; e++) if (this._spilled.has(e)) return !1;
166
+ return !0;
167
+ }
168
+ get spilledChunks() {
169
+ return this._spilled?.size ?? 0;
170
+ }
171
+ baseOf(e) {
172
+ return e % this.recordsPerChunk * this.lanesPerRecord;
173
+ }
174
+ isContiguous(e, t) {
175
+ return t <= 0 ? !0 : (e / this.recordsPerChunk | 0) == ((e + t - 1) / this.recordsPerChunk | 0);
176
+ }
177
+ slice(e, t) {
178
+ let n = this.baseOf(e), r = t * this.lanesPerRecord;
179
+ if (this.isContiguous(e, t)) return this.chunkFor(e).subarray(n, n + r);
180
+ let i = new this.LaneType(r);
181
+ return this.readRecords(e, t, i), i;
182
+ }
183
+ readRecords(e, t, n) {
184
+ let r = 0;
185
+ for (; r < t;) {
186
+ let i = e + r, a = this.chunkFor(i), o = this.baseOf(i), s = this.recordsPerChunk - i % this.recordsPerChunk, c = Math.min(s, t - r);
187
+ n.set(a.subarray(o, o + c * this.lanesPerRecord), r * this.lanesPerRecord), r += c;
188
+ }
189
+ return n;
190
+ }
191
+ setRecords(e, t) {
192
+ let n = t.length / this.lanesPerRecord, r = 0;
193
+ for (; r < n;) {
194
+ let i = e + r, a = this.chunkFor(i), o = this.baseOf(i), s = this.recordsPerChunk - i % this.recordsPerChunk, c = Math.min(s, n - r);
195
+ a.set(t.subarray(r * this.lanesPerRecord, (r + c) * this.lanesPerRecord), o), r += c;
196
+ }
197
+ }
198
+ copyOf(e, t) {
199
+ return this.readRecords(e, t, new this.LaneType(t * this.lanesPerRecord));
200
+ }
201
+ trimTo(t) {
202
+ let n = Math.max(1, Math.ceil(t / this.recordsPerChunk)), r = this.chunks.slice(0, n), i = (t - (n - 1) * this.recordsPerChunk) * this.lanesPerRecord, a = r[n - 1];
203
+ return a.length > i && (r[n - 1] = a.subarray(0, Math.max(0, i))), e.adopt(r, t, this.lanesPerRecord, this.recordsPerChunk);
204
+ }
205
+ grow(e) {
206
+ if (e <= this.recordCount) return;
207
+ let t = this.chunks.length - 1, n = (e, t) => Math.min(this.recordsPerChunk, t - e * this.recordsPerChunk) * this.lanesPerRecord, r = this.chunks[t];
208
+ this.recordCount = e;
209
+ for (let t of this._liveViews()) t.recordCount = e;
210
+ if (this.chunks.length * this.recordsPerChunk < e) {
211
+ this.chunks.length = Math.ceil(e / this.recordsPerChunk);
212
+ for (let e of this._liveViews()) e.chunks.length = this.chunks.length;
213
+ }
214
+ if (r && r.length < n(t, e)) {
215
+ let i = L(this.LaneType, n(t, e), this.shared);
216
+ i.set(r), this.chunks[t] = i;
217
+ for (let e of this._liveViews()) e.chunks[t] = new e.LaneType(i.buffer, i.byteOffset, i.byteLength / e.LaneType.BYTES_PER_ELEMENT);
218
+ } else if (!r && this._spilled?.has(t)) throw Error(`ChunkedRecords: cannot grow past chunk ${t}, which is on disk`);
219
+ }
220
+ release(e, t) {
221
+ let n = this.recordsPerChunk, r = Math.ceil(e / n), i = Math.floor((e + t) / n), a = 0;
222
+ for (let e = r; e < i; e++) {
223
+ let t = this.chunks[e];
224
+ if (t) {
225
+ a += t.byteLength, this.chunks[e] = void 0;
226
+ for (let t of this._liveViews()) t.chunks[e] = void 0;
227
+ }
228
+ }
229
+ return a;
230
+ }
231
+ trimInPlace(e) {
232
+ let t = Math.max(1, Math.ceil(e / this.recordsPerChunk)), n = Math.max(0, (e - (t - 1) * this.recordsPerChunk) * this.lanesPerRecord), r = [this, ...this._liveViews()];
233
+ for (let i of r) {
234
+ i.chunks.length = t;
235
+ let r = i.chunks[t - 1];
236
+ r && r.length > n && (i.chunks[t - 1] = r.subarray(0, n)), i.recordCount = e;
237
+ }
238
+ if (this._spilled) for (let e of this._spilled) e >= t && this._spilled.delete(e);
239
+ return this;
240
+ }
241
+ viewAs(t) {
242
+ let n = (e) => new t(e.buffer, e.byteOffset, e.byteLength / t.BYTES_PER_ELEMENT), r = e.adopt(this.chunks.map((e) => e ? n(e) : void 0), this.recordCount, this.lanesPerRecord, this.recordsPerChunk);
243
+ return r.LaneType = t, r._owner = this, this._views ? this._views.push(r) : (this._weakViews ??= []).push(new WeakRef(r)), r._spilled = this._spilled ??= /* @__PURE__ */ new Set(), r;
244
+ }
245
+ }, ke = 32 * 1024 * 1024, Ae = "chunks.bin", je = class e {
246
+ static async create(t, n, r, { label: i = "", expectedBytes: a = 0 } = {}) {
247
+ let o = t?.area(b.SPILL), s = await o?.create(n, {
248
+ label: i,
249
+ expectedBytes: a,
250
+ growable: [Ae]
251
+ });
252
+ return s ? new e(o, n, r, s) : null;
253
+ }
254
+ constructor(e, t, n, r) {
255
+ this._area = e, this._key = t, this._chunkBytes = n, this._writer = r, this._entry = null, this._file = null;
256
+ }
257
+ write(e, t) {
258
+ return this.writeAt(e * this._chunkBytes, t);
259
+ }
260
+ async writeAt(e, t) {
261
+ if (!this._writer && (this._entry?.release(), this._entry = this._file = null, this._writer = await this._area.edit(this._key), !this._writer)) throw Error("spill: its storage entry is gone");
262
+ let n = new Uint8Array(t.buffer, t.byteOffset, t.byteLength), r = 0;
263
+ do
264
+ await this._writer.write(Ae, n.subarray(r, Math.min(n.length, r + ke)), { at: e + r }), r += ke;
265
+ while (r < n.length);
266
+ }
267
+ async flush() {
268
+ if (this._writer &&= (await this._writer.commit(), null), !this._entry && (this._entry = await this._area.open(this._key, { wait: !0 }), this._file = await this._entry?.file(Ae), !this._file)) throw Error("spill: its storage entry is gone");
269
+ }
270
+ read(e, t) {
271
+ return this.readAt(e * this._chunkBytes, t);
272
+ }
273
+ async readAt(e, t) {
274
+ return await this.flush(), await this._file.slice(e, e + t).arrayBuffer();
275
+ }
276
+ async readInto(e, t) {
277
+ let n = await this.read(e, t.byteLength);
278
+ t.set(new Uint8Array(n)), n.transfer?.(0);
279
+ }
280
+ async dispose() {
281
+ this._writer && await this._writer.abort(), this._writer = null, this._entry?.release(), this._entry = this._file = null, await this._area.remove(this._key);
282
+ }
283
+ }, R = 32 * 1024 * 1024, Me = R / 4, Ne = 64 * 1024 * 1024, Pe = /* @__PURE__ */ new Map(), z = /* @__PURE__ */ new WeakSet();
284
+ function B(e) {
285
+ z.delete(e), e.transfer?.(0);
286
+ }
287
+ function Fe(e) {
288
+ let t = Pe.get(e);
289
+ return t || Pe.set(e, t = new e(0)), t;
290
+ }
291
+ var Ie = class e {
292
+ static async create(t, n, r = 0) {
293
+ let i = await je.create(t, n, 0, {
294
+ label: "Scene geometry (while building)",
295
+ expectedBytes: r
296
+ });
297
+ return i ? new e(i) : null;
298
+ }
299
+ static canTake(e) {
300
+ if (Object.keys(e.morphAttributes ?? {}).length) return !1;
301
+ for (let t in e.attributes) if (!e.attributes[t].isBufferAttribute) return !1;
302
+ return !e.index || e.index.isBufferAttribute === !0;
303
+ }
304
+ constructor(e) {
305
+ this._store = e, this._records = [], this._geometries = [], this._end = 0, this._pack = null, this._packAt = 0, this._packUsed = 0, this._packRecords = [], this._chain = Promise.resolve(), this._queued = 0, this.bytes = 0, this.error = null;
306
+ }
307
+ get queuedBytes() {
308
+ return this._queued;
309
+ }
310
+ add(e) {
311
+ e.boundingBox || e.computeBoundingBox(), e.boundingSphere || e.computeBoundingSphere();
312
+ let t = Object.values(e.attributes);
313
+ e.index && t.push(e.index), this.addAttributes(t), this._geometries.push({
314
+ geometry: e,
315
+ box: e.boundingBox.clone(),
316
+ sphere: e.boundingSphere.clone()
317
+ });
318
+ }
319
+ addAttributes(e) {
320
+ let t = /* @__PURE__ */ new Map();
321
+ for (let n of e) {
322
+ let e = n.array;
323
+ if (!e?.byteLength) continue;
324
+ let r = t.get(e);
325
+ r || t.set(e, r = this._write(e)), r.attributes.push(n), n.array = Fe(e.constructor);
326
+ }
327
+ }
328
+ _write(e) {
329
+ let t = new Uint8Array(e.buffer, e.byteOffset, e.byteLength), n = {
330
+ at: 0,
331
+ byteLength: t.byteLength,
332
+ Type: e.constructor,
333
+ attributes: [],
334
+ array: null,
335
+ pack: null,
336
+ offset: 0
337
+ };
338
+ return this._records.push(n), this.bytes += t.byteLength, t.byteLength >= Me ? (n.at = this._end, n.array = e, this._end += t.byteLength, this._queue(n.at, t, [n]), n) : (this._pack && this._packUsed + t.byteLength > R && this._flushPack(), this._pack || (this._pack = new Uint8Array(R), this._packAt = this._end, this._packUsed = 0, this._end += R), this._pack.set(t, this._packUsed), n.at = this._packAt + this._packUsed, n.pack = this._pack, n.offset = this._packUsed, this._packUsed += n.byteLength, this._packRecords.push(n), z.has(e.buffer) && B(e.buffer), n);
339
+ }
340
+ _flushPack() {
341
+ this._pack && (this._queue(this._packAt, this._pack.subarray(0, this._packUsed), this._packRecords, !0), this._pack = null, this._packRecords = []);
342
+ }
343
+ _queue(e, t, n, r = !1) {
344
+ let i = t.byteLength;
345
+ this._queued += i, this._chain = this._chain.then(async () => {
346
+ if (!this.error) {
347
+ await this._store.writeAt(e, t);
348
+ for (let e of n) {
349
+ let t = e.array?.buffer;
350
+ e.array = e.pack = null, z.has(t) && B(t);
351
+ }
352
+ r && t.buffer.transfer?.(0);
353
+ }
354
+ }).catch((e) => void (this.error ??= e)).finally(() => void (this._queued -= i));
355
+ }
356
+ written() {
357
+ return this._flushPack(), this._chain;
358
+ }
359
+ async restore() {
360
+ await this.written();
361
+ let e = this._records.sort((e, t) => e.at - t.at);
362
+ e.some((e) => !e.array && !e.pack) && await this._store.flush();
363
+ let t = null, n = 0;
364
+ for (let r of e) {
365
+ let e;
366
+ if (r.array ? e = r.array : r.pack ? e = new r.Type(r.pack.slice(r.offset, r.offset + r.byteLength).buffer) : r.byteLength > Ne ? e = new r.Type(await this._store.readAt(r.at, r.byteLength)) : ((!t || r.at + r.byteLength > n + t.byteLength) && (t && B(t), n = r.at, t = await this._store.readAt(r.at, Ne)), e = new r.Type(t.slice(r.at - n, r.at - n + r.byteLength))), e.byteLength !== r.byteLength) throw Error("geometry spill: an array came back short");
367
+ e !== r.array && z.add(e.buffer);
368
+ for (let t of r.attributes) t.array = e;
369
+ }
370
+ t && B(t);
371
+ for (let { geometry: e, box: t, sphere: n } of this._geometries) e.boundingBox = t, e.boundingSphere = n;
372
+ this._records = [], this._geometries = [], this.bytes = 0;
373
+ }
374
+ async dispose() {
375
+ await this._chain, this._records = [], this._geometries = [], this._pack = null, this._packRecords = [], await this._store.dispose();
376
+ }
377
+ }, Le = n("geometry");
378
+ function Re(e) {
379
+ e.traverse((e) => {
380
+ if (!e.isInstancedMesh || e.boundingBox !== null) return;
381
+ let t = e.geometry;
382
+ t.boundingBox === null && t.computeBoundingBox();
383
+ let n = e.boundingBox = new E(), r = t.boundingBox;
384
+ if (r.isEmpty()) return;
385
+ let i = [r.min.x, r.max.x], a = [r.min.y, r.max.y], o = [r.min.z, r.max.z], s = e.instanceMatrix.array, c = Infinity, l = Infinity, u = Infinity, d = -Infinity, f = -Infinity, p = -Infinity;
386
+ for (let t = 0, n = 0; t < e.count; t++, n += 16) {
387
+ let e = s[n], t = s[n + 1], r = s[n + 2], m = s[n + 3], h = s[n + 4], g = s[n + 5], _ = s[n + 6], v = s[n + 7], y = s[n + 8], b = s[n + 9], x = s[n + 10], S = s[n + 11], C = s[n + 12], w = s[n + 13], T = s[n + 14], ee = s[n + 15];
388
+ for (let n = 0; n < 8; n++) {
389
+ let s = i[n >> 2], E = a[n >> 1 & 1], D = o[n & 1], O = 1 / (m * s + v * E + S * D + ee), k = (e * s + h * E + y * D + C) * O, te = (t * s + g * E + b * D + w) * O, ne = (r * s + _ * E + x * D + T) * O;
390
+ c = Math.min(c, k), l = Math.min(l, te), u = Math.min(u, ne), d = Math.max(d, k), f = Math.max(f, te), p = Math.max(p, ne);
391
+ }
392
+ }
393
+ n.min.set(c, l, u), n.max.set(d, f, p);
394
+ });
395
+ }
396
+ var ze = c.MAX_TEXTURES_LIMIT, Be = new Set([
397
+ "color",
398
+ "emissive",
399
+ "attenuationColor",
400
+ "sheenColor",
401
+ "specularColor",
402
+ "subsurfaceColor",
403
+ "diffuseTransmissionColor"
404
+ ]), V = Object.freeze({
405
+ MATERIAL: "material",
406
+ MAPPED: "mapped",
407
+ DEFAULT: "default",
408
+ HOST: "host"
409
+ }), Ve = [
410
+ 1,
411
+ 0,
412
+ 0,
413
+ 0,
414
+ 0,
415
+ 1,
416
+ 0,
417
+ 0,
418
+ 0,
419
+ 0,
420
+ 1,
421
+ 0,
422
+ 0,
423
+ 0,
424
+ 0,
425
+ 1
426
+ ];
427
+ function He(e) {
428
+ for (let t = 0; t < 16; t++) if (e[t] !== Ve[t]) return !1;
429
+ return !0;
430
+ }
431
+ function Ue(e) {
432
+ let t = e?.image, n = t?.width || t?.naturalWidth, r = t?.height || t?.naturalHeight;
433
+ return n > 0 && r > 0 ? [n, r] : null;
434
+ }
435
+ function We(e) {
436
+ return {
437
+ map: e.map,
438
+ normalMap: e.normalMap,
439
+ bumpMap: e.bumpMap,
440
+ roughnessMap: e.roughnessMap,
441
+ metalnessMap: e.metalnessMap,
442
+ emissiveMap: e.emissiveMap ?? (e.isMeshBasicMaterial ? e.map : void 0),
443
+ displacementMap: e.displacementMap,
444
+ anisotropyMap: e.anisotropyMap,
445
+ clearcoatMap: e.clearcoatMap,
446
+ clearcoatRoughnessMap: e.clearcoatRoughnessMap,
447
+ clearcoatNormalMap: e.clearcoatNormalMap,
448
+ transmissionMap: e.transmissionMap,
449
+ sheenColorMap: e.sheenColorMap,
450
+ sheenRoughnessMap: e.sheenRoughnessMap,
451
+ specularIntensityMap: e.specularIntensityMap,
452
+ specularColorMap: e.specularColorMap,
453
+ diffuseTransmissionMap: e.diffuseTransmissionMap,
454
+ diffuseTransmissionColorMap: e.diffuseTransmissionColorMap,
455
+ iridescenceMap: e.iridescenceMap,
456
+ iridescenceThicknessMap: e.iridescenceThicknessMap,
457
+ diffuseRoughnessMap: e.diffuseRoughnessMap
458
+ };
459
+ }
460
+ function Ge(e) {
461
+ if (e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode) {
462
+ let t = e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;
463
+ return t === "BLEND" ? 2 : +(t === "MASK");
464
+ }
465
+ return e.alphaTest > 0 ? 1 : e.transparent && e.opacity < 1 || e.map && e.map.format === j && e.transparent ? 2 : 0;
466
+ }
467
+ function Ke(e) {
468
+ let t = 0, n = /* @__PURE__ */ new Set(), r = (e) => {
469
+ let i = e.isMesh && e.material ? e.geometry : null;
470
+ if (i && !n.has(i.uuid)) {
471
+ n.add(i.uuid);
472
+ for (let e in i.attributes) t += i.attributes[e].array?.byteLength ?? 0;
473
+ t += i.index?.array?.byteLength ?? 0;
474
+ }
475
+ if (e.children) for (let t of e.children) r(t);
476
+ };
477
+ return r(e), t;
478
+ }
479
+ function qe(e) {
480
+ let t = 0, n = /* @__PURE__ */ new Set();
481
+ return e.traverse?.((e) => {
482
+ let r = e.isInstancedMesh ? e.instanceMatrix?.array : null;
483
+ r && !n.has(r) && (n.add(r), t += r.byteLength);
484
+ }), t;
485
+ }
486
+ function Je(e, t) {
487
+ let n = e.x, r = e.y, i = e.z;
488
+ e.x = t[0] * n + t[4] * r + t[8] * i + t[12], e.y = t[1] * n + t[5] * r + t[9] * i + t[13], e.z = t[2] * n + t[6] * r + t[10] * i + t[14];
489
+ }
490
+ function Ye(e, t) {
491
+ let n = e.x, r = e.y, i = e.z;
492
+ e.x = t[0] * n + t[3] * r + t[6] * i, e.y = t[1] * n + t[4] * r + t[7] * i, e.z = t[2] * n + t[5] * r + t[8] * i;
493
+ }
494
+ var Xe = 1 << 21;
495
+ function H(e) {
496
+ return !!(e.isSkinnedMesh || Object.keys(e.geometry?.morphAttributes ?? {}).length);
497
+ }
498
+ function Ze(e) {
499
+ return e[0] * (e[5] * e[10] - e[9] * e[6]) - e[4] * (e[1] * e[10] - e[9] * e[2]) + e[8] * (e[1] * e[6] - e[5] * e[2]);
500
+ }
501
+ function Qe(e) {
502
+ let t = !1, n = /* @__PURE__ */ new Set();
503
+ return e.traverse((e) => {
504
+ if (!(t || !e.isMesh || !e.material)) {
505
+ for (let r of Array.isArray(e.material) ? e.material : [e.material]) if (!n.has(r)) {
506
+ n.add(r);
507
+ for (let e in r) r[e]?.isTexture && (t = !0);
508
+ }
509
+ }
510
+ }), t;
511
+ }
512
+ function $e(e, t) {
513
+ let n = e.getAttribute(t);
514
+ if (!n || n.normalized || !(n.array instanceof Float32Array) || e.morphAttributes?.[t]?.length) return;
515
+ let r = n.array;
516
+ for (let e = 0; e < r.length; e++) {
517
+ let t = r[e];
518
+ if (!(t >= -1.0001 && t <= 1.0001)) return;
519
+ }
520
+ let i = new Int16Array(r.length);
521
+ for (let e = 0; e < r.length; e++) i[e] = Math.round(Math.max(-1, Math.min(1, r[e])) * 32767);
522
+ e.setAttribute(t, new D(i, n.itemSize, !0));
523
+ }
524
+ var et = class {
525
+ constructor({ issues: e = null } = {}) {
526
+ this._issues = e, this._droppedTextures = 0, this._vectorPool = {
527
+ vec3: Array(9).fill().map(() => new ye()),
528
+ vec2: [
529
+ ,
530
+ ,
531
+ ,
532
+ ,
533
+ ,
534
+ ,
535
+ ].fill().map(() => new ve())
536
+ }, this._geometryRanges = /* @__PURE__ */ new Map(), this.expandedTriangleCount = 0, this._allocatePlacements(0), this._matrixPool = {
537
+ mat3: new le(),
538
+ mat4: new ue()
539
+ }, this.resetArrays(), this.triangleCount = 0, this.currentTriangleIndex = 0;
540
+ }
541
+ _getVec3(e = 0) {
542
+ return this._vectorPool.vec3[e % this._vectorPool.vec3.length];
543
+ }
544
+ _getVec2(e = 0) {
545
+ return this._vectorPool.vec2[e % this._vectorPool.vec2.length];
546
+ }
547
+ extract(e) {
548
+ this.resetArrays();
549
+ let t = this._countTriangles(e);
550
+ return this._triangleCapacity = Math.max(1024, t), this._allocateTriangles(this._triangleCapacity), this.currentTriangleIndex = 0, this._allocatePlacements(this._countPlacements(e)), this._geometryUses = this._countGeometryUses(e), this.bakeInverse = /* @__PURE__ */ new Map(), this.traverseObject(e), this._compressAttributes(e), this.logStats(), this.getExtractedData();
551
+ }
552
+ async extractStreaming(e, { onStore: t, onRange: n, pause: r, yieldEvery: i = 1 << 20, releaseGeometry: a = null }) {
553
+ this.resetArrays(), this._triangleCapacity = Math.max(1, this._countStoredTriangles(e)), this._allocateTriangles(this._triangleCapacity, !0), t?.(this.triangles), this.currentTriangleIndex = 0, this._allocatePlacements(this._countPlacements(e)), this._geometryUses = this._countGeometryUses(e), this.bakeInverse = /* @__PURE__ */ new Map(), this._onRange = n, this._releaseAfterRead = a ? this._geometryReleaser(e, a) : null;
554
+ try {
555
+ let t = [e], n = 0;
556
+ for (; t.length;) {
557
+ let e = t.pop();
558
+ if (this._visit(e), e.children) for (let n = e.children.length - 1; n >= 0; n--) t.push(e.children[n]);
559
+ this.currentTriangleIndex - n >= i && (n = this.currentTriangleIndex, await r(this.currentTriangleIndex));
560
+ }
561
+ } finally {
562
+ this._onRange = null, this._releaseAfterRead = null;
563
+ }
564
+ return this._compressAttributes(e), this.triangles.trimInPlace(this.currentTriangleIndex), this._streamedStore = !0, this.logStats(), this.getExtractedData();
565
+ }
566
+ _countStoredTriangles(e) {
567
+ let t = /* @__PURE__ */ new Set(), n = 0, r = (e) => {
568
+ if (e.isMesh && e.geometry && e.material) {
569
+ let r = e.geometry, i = Math.ceil((r.index ? r.index.count : r.attributes.position?.count ?? 0) / 3), a = Array.isArray(e.material) ? e.material[0] : e.material, o = a?.emissive, s = a?.emissiveIntensity > 0 && !!o && (o.r > 0 || o.g > 0 || o.b > 0), c = e.isInstancedMesh ? e.count ?? 0 : 1;
570
+ if (s && e.isInstancedMesh && !H(e) && i * c <= Xe) n += i * c;
571
+ else if (s || H(e)) n += i;
572
+ else {
573
+ let e = `${r.uuid}|${a?.uuid}`;
574
+ t.has(e) || (t.add(e), n += i);
575
+ }
576
+ }
577
+ if (e.children) for (let t of e.children) r(t);
578
+ };
579
+ return r(e), n;
580
+ }
581
+ _geometryReleaser(e, t) {
582
+ let n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set(), a = (e, t) => {
583
+ t ||= !!e.userData?.__rayzeeExternal;
584
+ let o = e.isMesh && e.material ? e.geometry : null;
585
+ if (o) {
586
+ if (!n.has(o)) {
587
+ Ie.canTake(o) || i.add(o);
588
+ for (let e of [...Object.values(o.attributes), o.index]) {
589
+ let t = e?.array;
590
+ if (!t) continue;
591
+ let n = r.get(t);
592
+ n && n !== o ? i.add(o).add(n) : r.set(t, o);
593
+ }
594
+ }
595
+ n.set(o, (n.get(o) ?? 0) + 1), (t || H(e)) && i.add(o);
596
+ }
597
+ if (e.children) for (let n of e.children) a(n, t);
598
+ };
599
+ return a(e, !1), (e) => {
600
+ let r = e.material ? e.geometry : null;
601
+ if (!r || !n.has(r)) return;
602
+ let a = n.get(r) - 1;
603
+ if (a > 0) return void n.set(r, a);
604
+ n.delete(r), !i.has(r) && (this._compressGeometry(r), t(r));
605
+ };
606
+ }
607
+ surveyScene(e) {
608
+ let t = 0, n = (e) => {
609
+ if (e.isMesh && e.geometry && e.material && t++, e.children) for (let t of e.children) n(t);
610
+ };
611
+ return n(e), {
612
+ triangles: this._countTriangles(e),
613
+ placements: this._countPlacements(e),
614
+ meshes: t,
615
+ geometryBytes: Ke(e),
616
+ instanceBytes: qe(e)
617
+ };
618
+ }
619
+ _countGeometryUses(e) {
620
+ let t = /* @__PURE__ */ new Map();
621
+ return e.traverse((e) => {
622
+ if (!e.isMesh || !e.geometry || !e.material) return;
623
+ let n = `${e.geometry.uuid}|${e.material.uuid}`;
624
+ t.set(n, (t.get(n) ?? 0) + 1);
625
+ }), t;
626
+ }
627
+ _countPlacements(e) {
628
+ let t = 0;
629
+ if (e.isMesh && e.geometry && e.material && (t += e.isInstancedMesh && e.instanceMatrix ? e.count ?? e.instanceMatrix.array.length / 16 : 1), e.children) for (let n of e.children) t += this._countPlacements(n);
630
+ return t;
631
+ }
632
+ _allocatePlacements(e) {
633
+ this.instanceCount = 0, this.instanceCapacity = e, this.instanceSource = new Int32Array(e), this._runs = {
634
+ first: [],
635
+ arrays: [],
636
+ arrayOf: [],
637
+ base: [],
638
+ owned: []
639
+ }, this._runArrayIndex = /* @__PURE__ */ new Map(), this._singles = null, this._singlesUsed = 0, this._singlesRun = null, this._compressed = /* @__PURE__ */ new Set(), this._matrixLists = /* @__PURE__ */ new Map();
640
+ }
641
+ _beginRun(e, t, n) {
642
+ let r = this._runs, i = this._runArrayIndex.get(e);
643
+ i === void 0 && this._runArrayIndex.set(e, i = r.arrays.push(e) - 1), r.first.push(this.instanceCount), r.arrayOf.push(i), r.base.push(t), r.owned.push(n);
644
+ }
645
+ _singleRow() {
646
+ let e = this._runs;
647
+ if (this._singles || (this._singles = new Float32Array(1024 * 16), this._singlesIndex = e.arrays.push(this._singles) - 1), this._singlesUsed + 16 > this._singles.length) {
648
+ let t = new Float32Array(this._singles.length * 2);
649
+ t.set(this._singles), this._singles = e.arrays[this._singlesIndex] = t;
650
+ }
651
+ this._singlesRun !== e.first.length - 1 && (e.first.push(this.instanceCount), e.arrayOf.push(this._singlesIndex), e.base.push(this._singlesUsed), e.owned.push(1), this._singlesRun = e.first.length - 1);
652
+ let t = this._singlesUsed;
653
+ return this._singlesUsed += 16, t;
654
+ }
655
+ _matrixRuns() {
656
+ let e = this._runs;
657
+ return {
658
+ first: [...e.first, this.instanceCount],
659
+ arrays: e.arrays,
660
+ arrayOf: e.arrayOf,
661
+ base: e.base,
662
+ owned: e.owned
663
+ };
664
+ }
665
+ _compressAttributes(e) {
666
+ let t = (e, n) => {
667
+ if (!e.userData?.__rayzeeExternal) {
668
+ n(e);
669
+ for (let r of e.children) t(r, n);
670
+ }
671
+ };
672
+ t(e, (e) => {
673
+ e.isMesh && e.geometry && this._compressGeometry(e.geometry);
674
+ });
675
+ }
676
+ _compressGeometry(e) {
677
+ if (!this._compressed.has(e.uuid)) {
678
+ this._compressed.add(e.uuid);
679
+ for (let t of [
680
+ "normal",
681
+ "tangent",
682
+ "color"
683
+ ]) $e(e, t);
684
+ }
685
+ }
686
+ _countTriangles(e) {
687
+ let t = 0;
688
+ if (e.isMesh && e.geometry && e.material) {
689
+ let n = e.geometry.index, r = e.geometry.attributes.position;
690
+ n ? t += Math.ceil(n.count / 3) : r && (t += Math.ceil(r.count / 3));
691
+ }
692
+ if (e.children) for (let n of e.children) t += this._countTriangles(n);
693
+ return t;
694
+ }
695
+ _ensureCapacity(e) {
696
+ if (e <= this._triangleCapacity) return;
697
+ if (this._onRange) {
698
+ this.triangles.grow(e), this._triangleCapacity = e;
699
+ return;
700
+ }
701
+ let t = this.triangles, n = this.currentTriangleIndex;
702
+ this._allocateTriangles(e);
703
+ for (let e = 0; e < n; e++) this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e), t.baseOf(e) + t.lanesPerRecord), this.triangles.baseOf(e));
704
+ this._triangleCapacity = e;
705
+ }
706
+ _allocateTriangles(e, t = !1) {
707
+ this.triangles = (t ? Oe.lazy : (...e) => new Oe(...e))(e, u.FLOATS_PER_TRIANGLE, Uint32Array, void 0, Te), this.triangleFloatChunks = this.triangles.viewAs(Float32Array), this.triangleData = this.triangles.single, this.triangleFloats = this.triangleFloatChunks.single;
708
+ }
709
+ traverseObject(e) {
710
+ if (this._visit(e), e.children) for (let t of e.children) this.traverseObject(t);
711
+ }
712
+ _visit(e) {
713
+ e.isMesh ? (this.processMesh(e), this._releaseAfterRead?.(e)) : e.isDirectionalLight ? this.directionalLights.push(e) : e.isCamera && this.cameras.push(e);
714
+ }
715
+ processMesh(e) {
716
+ if (!e.geometry || !e.material) {
717
+ console.warn("Skipping mesh with missing geometry or material:", e);
718
+ return;
719
+ }
720
+ let t = this.processMaterial(e.material);
721
+ e.userData.materialIndex = t;
722
+ let n = this.meshes.length;
723
+ this.meshes.push(e), e.userData.meshIndex = n;
724
+ let r = `${e.geometry.uuid}|${t}`, i = H(e), a = !this._emissiveMaterial(t) && !i, o = a ? this._geometryRanges.get(r) : null;
725
+ if (o) {
726
+ let t = {
727
+ start: o.start,
728
+ count: o.count,
729
+ expandedStart: this.expandedTriangleCount,
730
+ sharedFrom: o.meshIndex
731
+ };
732
+ this.expandedTriangleCount += o.count, this.meshTriangleRanges.push(t), this._recordPlacements(e, n, !1, !1, o.count > 0);
733
+ return;
734
+ }
735
+ let s = this.currentTriangleIndex, c = e.isInstancedMesh && !i && this._emissiveMaterial(t) && this._canExpand(e), l = c || !e.isInstancedMesh && !i && (this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`) === 1 || this._emissiveMaterial(t));
736
+ this.extractGeometry(e, t, n, l, c);
737
+ let u = {
738
+ start: s,
739
+ count: this.currentTriangleIndex - s,
740
+ expandedStart: this.expandedTriangleCount
741
+ };
742
+ this.expandedTriangleCount += u.count, this.meshTriangleRanges.push(u), u.count > 0 && !l && a && this._geometryRanges.set(r, {
743
+ ...u,
744
+ meshIndex: n
745
+ }), u.count > 0 && (this._recordPlacements(e, n, l, c, a), this._onRange?.(n, u));
746
+ }
747
+ _recordPlacements(e, t, n = !1, r = !1, i = !1) {
748
+ let a = e.matrixWorld.elements, o = this.instanceSource;
749
+ if (!e.isInstancedMesh || !e.instanceMatrix || r) {
750
+ let r = this._singleRow(), i = this._singles, s = this._nextPlacement();
751
+ if (o[s] = t, n) {
752
+ for (let e = 0; e < 16; e++) i[r + e] = +(e % 5 == 0);
753
+ this.bakeInverse.set(t, Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements));
754
+ } else for (let e = 0; e < 16; e++) i[r + e] = a[e];
755
+ return;
756
+ }
757
+ let s = e.instanceMatrix.array, c = e.count ?? s.length / 16;
758
+ if (i && c > 0) {
759
+ let n = this._matrixLists.get(e.instanceMatrix);
760
+ n || this._matrixLists.set(e.instanceMatrix, n = []), n.push({
761
+ meshIndex: t,
762
+ start: this.instanceCount,
763
+ count: c,
764
+ world: Float32Array.from(a)
765
+ });
766
+ }
767
+ if (c <= 0) return;
768
+ let l = He(a) && s.length >= c * 16, u = l ? s : new Float32Array(c * 16);
769
+ this._beginRun(l ? e.instanceMatrix : u, 0, +!l);
770
+ for (let e = 0; e < c; e++) {
771
+ let n = e * 16, r = this._nextPlacement(), i = e * 16;
772
+ if (o[r] = t, !l) for (let e = 0; e < 4; e++) for (let t = 0; t < 4; t++) u[i + e * 4 + t] = a[t] * s[n + e * 4] + a[4 + t] * s[n + e * 4 + 1] + a[8 + t] * s[n + e * 4 + 2] + a[12 + t] * s[n + e * 4 + 3];
773
+ }
774
+ }
775
+ _instanceGroups() {
776
+ let e = [];
777
+ for (let t of this._matrixLists.values()) {
778
+ let n = [];
779
+ for (let e of t) {
780
+ let t = n.find((t) => t.count === e.count && t.world.every((t, n) => t === e.world[n]));
781
+ t ? (t.members.push(e.meshIndex), t.starts.push(e.start)) : n.push({
782
+ world: e.world,
783
+ count: e.count,
784
+ members: [e.meshIndex],
785
+ starts: [e.start]
786
+ });
787
+ }
788
+ for (let t of n) t.members.length >= 2 && e.push({
789
+ members: t.members,
790
+ starts: t.starts,
791
+ count: t.count
792
+ });
793
+ }
794
+ return this._matrixLists.clear(), e;
795
+ }
796
+ _nextPlacement() {
797
+ if (this.instanceCount >= this.instanceCapacity) {
798
+ let e = Math.max(16, this.instanceCapacity * 2), t = new Int32Array(e);
799
+ t.set(this.instanceSource), this.instanceSource = t, this.instanceCapacity = e;
800
+ }
801
+ return this.instanceCount++;
802
+ }
803
+ _canExpand(e) {
804
+ let t = e.geometry, n = (t.index ? t.index.count : t.attributes.position.count) / 3, r = e.count ?? (e.instanceMatrix?.array.length ?? 0) / 16;
805
+ return n * r <= Xe ? !0 : (this._issues?.record(_.EMISSIVE_INSTANCES_COLLAPSED, `"${e.name || "instanced mesh"}" would need ${Math.round(n * r).toLocaleString()} triangles to light every instance; lighting the first one only`, {
806
+ instances: r,
807
+ trianglesPerInstance: n,
808
+ limit: Xe
809
+ }), !1);
810
+ }
811
+ _emissiveMaterial(e) {
812
+ let t = this.materials[e];
813
+ if (!t || !(t.emissiveIntensity > 0)) return !1;
814
+ let n = t.emissive;
815
+ return !!n && (n.r > 0 || n.g > 0 || n.b > 0);
816
+ }
817
+ processMaterial(t) {
818
+ let n = this._materialUuidMap.get(t.uuid) ?? -1;
819
+ if (n === -1) {
820
+ t.depthWrite === !1 && (t.depthWrite = !0, e(Le, "depthWrite", "material had depthWrite disabled — enabled for rastered rendering"));
821
+ let r = this.createMaterialObject(t);
822
+ this.materials.push(r), n = this.materials.length - 1, this._materialUuidMap.set(t.uuid, n);
823
+ }
824
+ return n;
825
+ }
826
+ getMaterialType(e) {
827
+ return e.isMeshPhysicalMaterial ? "physical" : e.isMeshStandardMaterial ? "standard" : e.isMeshPhongMaterial ? "phong" : e.isMeshLambertMaterial ? "lambert" : e.isMeshBasicMaterial ? "basic" : e.isMeshToonMaterial ? "toon" : "unknown";
828
+ }
829
+ getPhysicalDefaults() {
830
+ let e = {};
831
+ for (let [t, n] of Object.entries(a)) e[t] = Be.has(t) ? new O().fromArray(n) : Array.isArray(n) ? [...n] : n;
832
+ return e.normalScale = {
833
+ x: a.normalScale[0],
834
+ y: a.normalScale[1]
835
+ }, e;
836
+ }
837
+ mapLegacyMaterialToPhysical(e, t) {
838
+ let n = {};
839
+ switch (t) {
840
+ case "basic":
841
+ n.emissive = e.color.clone(), n.emissiveIntensity = 1, n.color = new O(0), n.roughness = 1, n.metalness = 0, n.specularIntensity = 0;
842
+ break;
843
+ case "lambert":
844
+ n.roughness = 1, n.metalness = 0, n.specularIntensity = 0;
845
+ break;
846
+ case "phong":
847
+ {
848
+ let t = e.shininess || 30;
849
+ n.roughness = Math.sqrt(2 / (t + 2)), n.metalness = 0;
850
+ }
851
+ if (e.specular) {
852
+ let t = e.specular, r = t.r * .299 + t.g * .587 + t.b * .114, i = Math.max(t.r, t.g, t.b);
853
+ n.specularIntensity = Math.min(r * 2, 1), n.specularColor = i > 0 ? t.clone().multiplyScalar(1 / i) : new O(1, 1, 1);
854
+ }
855
+ break;
856
+ case "toon":
857
+ n.roughness = .9, n.metalness = 0;
858
+ break;
859
+ case "standard":
860
+ case "physical": break;
861
+ }
862
+ return n;
863
+ }
864
+ createMaterialObject(e) {
865
+ let t = this.getPhysicalDefaults(), n = this.getMaterialType(e), r = this.mapLegacyMaterialToPhysical(e, n), i = We(e), a = {}, o = (t) => t === "iridescenceThicknessRange" && e.iridescenceThicknessMinimum !== void 0 ? [e.iridescenceThicknessMinimum, e.iridescenceThicknessMaximum] : e[t], s = (e) => {
866
+ if (r[e] !== void 0) return a[e] = V.MAPPED, r[e];
867
+ let n = o(e);
868
+ return n == null ? (a[e] = V.DEFAULT, t[e]) : (a[e] = V.MATERIAL, n);
869
+ };
870
+ for (let e of [
871
+ "transparent",
872
+ "alphaMode",
873
+ "side",
874
+ "depthWrite"
875
+ ]) a[e] = V.MATERIAL;
876
+ return {
877
+ uuid: e.uuid,
878
+ color: s("color"),
879
+ emissive: s("emissive"),
880
+ emissiveIntensity: s("emissiveIntensity"),
881
+ roughness: Math.max(.02, s("roughness")),
882
+ metalness: s("metalness"),
883
+ ior: s("ior"),
884
+ opacity: s("opacity"),
885
+ transmission: s("transmission"),
886
+ thickness: s("thickness"),
887
+ attenuationColor: s("attenuationColor"),
888
+ attenuationDistance: s("attenuationDistance"),
889
+ dispersion: s("dispersion"),
890
+ sheen: s("sheen"),
891
+ sheenRoughness: s("sheenRoughness"),
892
+ sheenColor: s("sheenColor"),
893
+ clearcoat: s("clearcoat"),
894
+ clearcoatRoughness: s("clearcoatRoughness"),
895
+ clearcoatNormalScale: s("clearcoatNormalScale"),
896
+ iridescence: s("iridescence"),
897
+ iridescenceIOR: s("iridescenceIOR"),
898
+ iridescenceThicknessRange: s("iridescenceThicknessRange"),
899
+ subsurface: s("subsurface"),
900
+ subsurfaceColor: s("subsurfaceColor"),
901
+ subsurfaceRadius: s("subsurfaceRadius"),
902
+ subsurfaceRadiusScale: s("subsurfaceRadiusScale"),
903
+ subsurfaceAnisotropy: s("subsurfaceAnisotropy"),
904
+ anisotropy: s("anisotropy"),
905
+ anisotropyRotation: s("anisotropyRotation"),
906
+ specularIntensity: s("specularIntensity"),
907
+ specularColor: s("specularColor"),
908
+ diffuseTransmission: s("diffuseTransmission"),
909
+ diffuseTransmissionColor: s("diffuseTransmissionColor"),
910
+ diffuseRoughness: s("diffuseRoughness"),
911
+ normalScale: s("normalScale"),
912
+ bumpScale: s("bumpScale"),
913
+ displacementScale: s("displacementScale"),
914
+ displacementBias: s("displacementBias"),
915
+ transparent: +!!e.transparent,
916
+ alphaTest: s("alphaTest"),
917
+ alphaMode: Ge(e),
918
+ side: this.getMaterialSide(e),
919
+ depthWrite: e.depthWrite ?? !0 ? 1 : 0,
920
+ map: this.processTexture(i.map, this.maps),
921
+ normalMap: this.processTexture(i.normalMap, this.normalMaps),
922
+ bumpMap: this.processTexture(i.bumpMap, this.bumpMaps),
923
+ roughnessMap: this.processTexture(i.roughnessMap, this.roughnessMaps),
924
+ metalnessMap: this.processTexture(i.metalnessMap, this.metalnessMaps),
925
+ emissiveMap: this.processTexture(i.emissiveMap, this.emissiveMaps),
926
+ displacementMap: this.processTexture(i.displacementMap, this.displacementMaps),
927
+ anisotropyMap: this.processTexture(i.anisotropyMap, this.anisotropyMaps),
928
+ clearcoatMap: this.processTexture(i.clearcoatMap, this.clearcoatMaps),
929
+ clearcoatRoughnessMap: this.processTexture(i.clearcoatRoughnessMap, this.clearcoatRoughnessMaps),
930
+ clearcoatNormalMap: this.processTexture(i.clearcoatNormalMap, this.clearcoatNormalMaps),
931
+ transmissionMap: this.processTexture(i.transmissionMap, this.transmissionMaps),
932
+ thicknessMap: this.processTexture(e.thicknessMap, []),
933
+ sheenColorMap: this.processTexture(i.sheenColorMap, this.sheenColorMaps),
934
+ sheenRoughnessMap: this.processTexture(i.sheenRoughnessMap, this.sheenRoughnessMaps),
935
+ specularIntensityMap: this.processTexture(i.specularIntensityMap, this.specularIntensityMaps),
936
+ specularColorMap: this.processTexture(i.specularColorMap, this.specularColorMaps),
937
+ diffuseTransmissionMap: this.processTexture(i.diffuseTransmissionMap, this.diffuseTransmissionMaps),
938
+ diffuseTransmissionColorMap: this.processTexture(i.diffuseTransmissionColorMap, this.diffuseTransmissionColorMaps),
939
+ iridescenceMap: this.processTexture(i.iridescenceMap, this.iridescenceMaps),
940
+ iridescenceThicknessMap: this.processTexture(i.iridescenceThicknessMap, this.iridescenceThicknessMaps),
941
+ diffuseRoughnessMap: this.processTexture(i.diffuseRoughnessMap, this.diffuseRoughnessMaps),
942
+ mapMatrix: this.getTextureMatrix(i.map),
943
+ normalMapMatrices: this.getTextureMatrix(i.normalMap ?? i.clearcoatNormalMap),
944
+ bumpMapMatrices: this.getTextureMatrix(i.bumpMap),
945
+ bumpMapSize: Ue(i.bumpMap),
946
+ roughnessMapMatrices: this.getTextureMatrix(i.roughnessMap),
947
+ metalnessMapMatrices: this.getTextureMatrix(i.metalnessMap),
948
+ emissiveMapMatrices: this.getTextureMatrix(i.emissiveMap),
949
+ displacementMapMatrices: this.getTextureMatrix(i.displacementMap),
950
+ sources: a,
951
+ originalType: n
952
+ };
953
+ }
954
+ getTextureMatrix(e) {
955
+ return e ? (e.matrixAutoUpdate && e.updateMatrix(), e.matrix.elements) : new le().elements;
956
+ }
957
+ getMaterialSide(e) {
958
+ if (e.transmission > 0) return 2;
959
+ switch (e.side) {
960
+ case ae: return 0;
961
+ case ee: return 1;
962
+ case re: return 2;
963
+ default: return 0;
964
+ }
965
+ }
966
+ processTexture(e, t) {
967
+ if (!e) return -1;
968
+ let n = this._textureIndexCache.get(t);
969
+ n || (n = /* @__PURE__ */ new Map(), this._textureIndexCache.set(t, n));
970
+ let r = e.source.uuid, i = n.get(r);
971
+ if (i !== void 0) return i;
972
+ if (t.length < ze) {
973
+ t.push(e);
974
+ let i = t.length - 1;
975
+ return n.set(r, i), i;
976
+ }
977
+ return this._droppedTextures++, this._droppedTextures === 1 && this._issues?.record(_.TEXTURE_LIMIT_EXCEEDED, `scene needs more than ${ze} distinct textures for one map type; the rest render untextured`, {
978
+ limit: ze,
979
+ firstDropped: e.name || e.source?.uuid
980
+ }), -1;
981
+ }
982
+ extractGeometry(e, t, n, r = !1, i = !1) {
983
+ e.updateMatrix(), e.updateMatrixWorld();
984
+ let a = e.geometry, o = a.attributes.position;
985
+ if (!o) return;
986
+ a.attributes.normal || a.computeVertexNormals();
987
+ let s = a.attributes.normal, c = a.attributes.uv, l = a.index ? a.index.array : null, u = Math.floor((l ? l.length : o.count) / 3);
988
+ if (i) {
989
+ let r = e.count ?? e.instanceMatrix.array.length / 16, i = this._matrixPool.mat4, a = new ue();
990
+ for (let d = 0; d < r; d++) {
991
+ i.fromArray(e.instanceMatrix.array, d * 16), a.multiplyMatrices(e.matrixWorld, i);
992
+ let r = new le().getNormalMatrix(a);
993
+ this.extractTrianglesInBatch(o, s, c, l, u, t, n, a, r, Ze(a.elements) < 0);
994
+ }
995
+ return;
996
+ }
997
+ let d = r ? this._matrixPool.mat4.copy(e.matrixWorld) : null, f = r ? this._matrixPool.mat3.getNormalMatrix(e.matrixWorld) : null, p = r && Ze(d.elements) < 0;
998
+ this.extractTrianglesInBatch(o, s, c, l, u, t, n, d, f, p);
999
+ }
1000
+ extractTrianglesInBatch(e, t, n, r, i, a, o, s = null, c = null, l = !1) {
1001
+ for (; this.materialTriangleCounts.length <= a;) this.materialTriangleCounts.push(0);
1002
+ this.materialTriangleCounts[a] += i;
1003
+ let u = this._getVec3(0), d = this._getVec3(1), f = this._getVec3(2), p = this._getVec3(3), m = this._getVec3(4), h = this._getVec3(5), g = this._getVec2(0), _ = this._getVec2(1), v = this._getVec2(2);
1004
+ this._ensureCapacity(this.currentTriangleIndex + i);
1005
+ let y = s?.elements, b = c?.elements;
1006
+ for (let c = 0; c < i; c++) {
1007
+ let i = c * 3, x = r ? r[i + 0] : i + 0, S = l ? 2 : 1, C = l ? 1 : 2, w = r ? r[i + S] : i + S, T = r ? r[i + C] : i + C;
1008
+ this.getVertex(e, x, u), this.getVertex(e, w, d), this.getVertex(e, T, f), this.getVertex(t, x, p), this.getVertex(t, w, m), this.getVertex(t, T, h), n ? (this.getVertex(n, x, g), this.getVertex(n, w, _), this.getVertex(n, T, v)) : (g.set(0, 0), _.set(0, 0), v.set(0, 0)), s && (Je(u, y), Je(d, y), Je(f, y), Ye(p, b), Ye(m, b), Ye(h, b)), p.normalize(), m.normalize(), h.normalize(), this.packTriangleDataTextureFormat(this.currentTriangleIndex, u, d, f, p, m, h, g, _, v, a, o), this.currentTriangleIndex++;
1009
+ }
1010
+ }
1011
+ packTriangleDataTextureFormat(e, t, n, r, i, a, o, s, c, l, d, f) {
1012
+ let p = u, m = this.triangles.baseOf(e), _ = this.triangleFloatChunks.chunkFor(e), v = this.triangles.chunkFor(e);
1013
+ _[m + p.POSITION_A_OFFSET + 0] = t.x, _[m + p.POSITION_A_OFFSET + 1] = t.y, _[m + p.POSITION_A_OFFSET + 2] = t.z, v[m + p.NORMAL_A_PACKED_OFFSET] = h(i.x, i.y, i.z), _[m + p.POSITION_B_OFFSET + 0] = n.x, _[m + p.POSITION_B_OFFSET + 1] = n.y, _[m + p.POSITION_B_OFFSET + 2] = n.z, v[m + p.NORMAL_B_PACKED_OFFSET] = h(a.x, a.y, a.z), _[m + p.POSITION_C_OFFSET + 0] = r.x, _[m + p.POSITION_C_OFFSET + 1] = r.y, _[m + p.POSITION_C_OFFSET + 2] = r.z, v[m + p.NORMAL_C_PACKED_OFFSET] = h(o.x, o.y, o.z), _[m + p.UV_AB_OFFSET + 0] = s.x, _[m + p.UV_AB_OFFSET + 1] = s.y, _[m + p.UV_AB_OFFSET + 2] = c.x, _[m + p.UV_AB_OFFSET + 3] = c.y, _[m + p.UV_C_OFFSET + 0] = l.x, _[m + p.UV_C_OFFSET + 1] = l.y, v[m + p.MATERIAL_FLAGS_OFFSET] = g(d, this.materials[d]), v[m + p.MESH_INDEX_OFFSET] = f;
1014
+ }
1015
+ releaseTriangles() {
1016
+ this.triangles = null, this.triangleData = null, this.triangleFloatChunks = null, this.triangleFloats = null;
1017
+ }
1018
+ getTriangleData() {
1019
+ return this.triangles ? this._streamedStore ? this.triangles : this.triangles.trimTo(this.currentTriangleIndex) : null;
1020
+ }
1021
+ getTriangleCount() {
1022
+ return this.currentTriangleIndex;
1023
+ }
1024
+ getVertex(e, t, n) {
1025
+ return e.itemSize === 2 ? (n.x = e.getX(t), n.y = e.getY(t)) : e.itemSize >= 3 && (n.x = e.getX(t), n.y = e.getY(t), n.z = e.getZ(t)), n;
1026
+ }
1027
+ logStats() {
1028
+ let e = this.currentTriangleIndex * u.FLOATS_PER_TRIANGLE * 4;
1029
+ Le.debug(t.list([
1030
+ `${t.count(this.currentTriangleIndex, "tri")} (${t.mb(e)})`,
1031
+ t.count(this.materials.length, "material"),
1032
+ t.count(this.maps.length, "map")
1033
+ ]));
1034
+ }
1035
+ extractMaterialsOnly(e) {
1036
+ return this.resetArrays(), this._traverseMaterialsOnly(e), this.getExtractedData();
1037
+ }
1038
+ _traverseMaterialsOnly(e) {
1039
+ if (e.isMesh && e.geometry && e.material) {
1040
+ let t = this.processMaterial(e.material);
1041
+ e.userData.materialIndex = t;
1042
+ let n = this.meshes.length;
1043
+ this.meshes.push(e), e.userData.meshIndex = n;
1044
+ } else e.isDirectionalLight ? this.directionalLights.push(e) : e.isCamera && this.cameras.push(e);
1045
+ if (e.children) for (let t of e.children) this._traverseMaterialsOnly(t);
1046
+ }
1047
+ resetArrays() {
1048
+ this._droppedTextures = 0, this.triangles = null, this._streamedStore = !1, this.triangleData = null, this.triangleFloatChunks = null, this.triangleFloats = null, this.triangleCount = 0, this.currentTriangleIndex = 0, this.materials = [], this.materialTriangleCounts = [], this.meshes = [], this.meshTriangleRanges = [], this._geometryRanges = /* @__PURE__ */ new Map(), this.expandedTriangleCount = 0, this._allocatePlacements(0), this.maps = [], this.normalMaps = [], this.bumpMaps = [], this.metalnessMaps = [], this.emissiveMaps = [], this.roughnessMaps = [], this.displacementMaps = [], this.anisotropyMaps = [], this.transmissionMaps = [], this.clearcoatMaps = [], this.clearcoatRoughnessMaps = [], this.clearcoatNormalMaps = [], this.sheenColorMaps = [], this.sheenRoughnessMaps = [], this.iridescenceMaps = [], this.iridescenceThicknessMaps = [], this.specularIntensityMaps = [], this.specularColorMaps = [], this.diffuseTransmissionMaps = [], this.diffuseTransmissionColorMaps = [], this.diffuseRoughnessMaps = [], this.directionalLights = [], this.cameras = [], this._materialUuidMap = /* @__PURE__ */ new Map(), this._textureIndexCache = /* @__PURE__ */ new WeakMap();
1049
+ }
1050
+ getExtractedData() {
1051
+ return {
1052
+ triangleData: this.getTriangleData(),
1053
+ triangleCount: this.getTriangleCount(),
1054
+ materials: this.materials,
1055
+ materialTriangleCounts: this.materialTriangleCounts,
1056
+ meshes: this.meshes,
1057
+ meshTriangleRanges: this.meshTriangleRanges,
1058
+ expandedTriangleCount: this.expandedTriangleCount,
1059
+ instanceSource: this.instanceSource.subarray(0, this.instanceCount),
1060
+ matrixRuns: this._matrixRuns(),
1061
+ instanceCount: this.instanceCount,
1062
+ instanceGroups: this._instanceGroups(),
1063
+ bakeInverse: this.bakeInverse,
1064
+ maps: this.maps,
1065
+ normalMaps: this.normalMaps,
1066
+ bumpMaps: this.bumpMaps,
1067
+ metalnessMaps: this.metalnessMaps,
1068
+ emissiveMaps: this.emissiveMaps,
1069
+ roughnessMaps: this.roughnessMaps,
1070
+ displacementMaps: this.displacementMaps,
1071
+ anisotropyMaps: this.anisotropyMaps,
1072
+ transmissionMaps: this.transmissionMaps,
1073
+ clearcoatMaps: this.clearcoatMaps,
1074
+ clearcoatRoughnessMaps: this.clearcoatRoughnessMaps,
1075
+ clearcoatNormalMaps: this.clearcoatNormalMaps,
1076
+ sheenColorMaps: this.sheenColorMaps,
1077
+ sheenRoughnessMaps: this.sheenRoughnessMaps,
1078
+ iridescenceMaps: this.iridescenceMaps,
1079
+ iridescenceThicknessMaps: this.iridescenceThicknessMaps,
1080
+ specularIntensityMaps: this.specularIntensityMaps,
1081
+ specularColorMaps: this.specularColorMaps,
1082
+ diffuseTransmissionMaps: this.diffuseTransmissionMaps,
1083
+ diffuseTransmissionColorMaps: this.diffuseTransmissionColorMaps,
1084
+ diffuseRoughnessMaps: this.diffuseRoughnessMaps,
1085
+ directionalLights: this.directionalLights,
1086
+ cameras: this.cameras
1087
+ };
1088
+ }
1089
+ }, U = {
1090
+ Worker: null,
1091
+ decodeImage: null,
1092
+ readFile: null
1093
+ };
1094
+ function tt(e) {
1095
+ e && Object.assign(U, e);
1096
+ }
1097
+ function nt() {
1098
+ return U;
1099
+ }
1100
+ function rt() {
1101
+ return typeof navigator < "u" && navigator.hardwareConcurrency || 4;
1102
+ }
1103
+ function it() {
1104
+ return !!U.decodeImage || typeof self < "u" && (typeof createImageBitmap < "u" || typeof document < "u");
1105
+ }
1106
+ function at() {
1107
+ return !!U.Worker || typeof Worker < "u";
1108
+ }
1109
+ var ot = 0;
1110
+ async function st(e) {
1111
+ if (!U.Worker || ot === 0 && globalThis.Worker !== void 0) return e();
1112
+ ot++ === 0 && (globalThis.Worker = U.Worker);
1113
+ try {
1114
+ return await e();
1115
+ } finally {
1116
+ --ot === 0 && globalThis.Worker === U.Worker && delete globalThis.Worker;
1117
+ }
1118
+ }
1119
+ function W(e, t) {
1120
+ let n = U.Worker;
1121
+ if (!n) return new e(t);
1122
+ let r = Object.prototype.hasOwnProperty.call(globalThis, "Worker"), i = globalThis.Worker;
1123
+ globalThis.Worker = n;
1124
+ try {
1125
+ return new e(t);
1126
+ } finally {
1127
+ r ? globalThis.Worker = i : delete globalThis.Worker;
1128
+ }
1129
+ }
1130
+ function ct() {
1131
+ return typeof MessageChannel > "u" ? new Promise((e) => setTimeout(e, 0)) : new Promise((e) => {
1132
+ let { port1: t, port2: n } = new MessageChannel();
1133
+ t.onmessage = () => {
1134
+ t.close(), e();
1135
+ }, n.postMessage(null);
1136
+ });
1137
+ }
1138
+ function lt(e = 50) {
1139
+ let t = performance.now(), n = () => {
1140
+ t = performance.now();
1141
+ };
1142
+ return () => performance.now() - t < e ? null : ct().then(n);
1143
+ }
1144
+ //#endregion
1145
+ //#region src/storage/CDFCache.js
1146
+ var ut = 5;
1147
+ function dt(e, t) {
1148
+ e && t && (e.userData.__rayzeeSource = t);
1149
+ }
1150
+ function ft(e) {
1151
+ let t = e?.userData?.__rayzeeSource;
1152
+ if (!t) return null;
1153
+ let { width: n = 0, height: r = 0 } = e.image ?? {};
1154
+ return `cdf:${ut}:${t}|${n}x${r}|${e.userData.__rayzeeColorSpace ?? "native"}`;
1155
+ }
1156
+ var pt = () => y(T().cacheNamespace)?.area(b.CDF) ?? null, mt = [
1157
+ "exactConditional",
1158
+ "exactMarginal",
1159
+ "exactRowGuide",
1160
+ "exactMarginalGuide"
1161
+ ], ht = mt.map((e) => `${e}.f32`);
1162
+ async function gt(e) {
1163
+ let t = ft(e), n = t ? await pt()?.open(t) : null;
1164
+ if (!n) return null;
1165
+ try {
1166
+ let e = await Promise.all(ht.map((e) => n.file(e)));
1167
+ if (e.some((e) => !e)) return null;
1168
+ let t = await Promise.all(e.map(async (e) => new Float32Array(await e.arrayBuffer()))), { totalSum: r, width: i, height: a, exactWidth: o, exactHeight: s, radianceIntegral: c } = n.extra;
1169
+ return {
1170
+ ...Object.fromEntries(mt.map((e, n) => [e, t[n]])),
1171
+ totalSum: r,
1172
+ width: i,
1173
+ height: a,
1174
+ exactWidth: o,
1175
+ exactHeight: s,
1176
+ radianceIntegral: c
1177
+ };
1178
+ } finally {
1179
+ n.release();
1180
+ }
1181
+ }
1182
+ async function _t(e, t) {
1183
+ let { totalSum: n, width: r, height: i, exactWidth: a, exactHeight: o, radianceIntegral: s } = t, c = mt.map((e) => t[e]), l = ft(e), u = l ? pt() : null;
1184
+ if (!u || c.some((e) => !e)) return !1;
1185
+ let d = await u.create(l, {
1186
+ label: e.name || "environment",
1187
+ expectedBytes: c.reduce((e, t) => e + t.byteLength, 0)
1188
+ });
1189
+ if (!d) return !1;
1190
+ try {
1191
+ for (let e = 0; e < ht.length; e++) await d.write(ht[e], c[e]);
1192
+ return await d.commit({
1193
+ totalSum: n,
1194
+ width: r,
1195
+ height: i,
1196
+ exactWidth: a,
1197
+ exactHeight: o,
1198
+ radianceIntegral: s
1199
+ }), !0;
1200
+ } catch {
1201
+ return await d.abort(), !1;
1202
+ }
1203
+ }
1204
+ //#endregion
1205
+ //#region src/memory/HostMemory.js
1206
+ var vt = u.FLOATS_PER_TRIANGLE * 4, yt = 64, bt = .9, xt = 28, St = 45, Ct = 4, wt = 1536 * 1024 * 1024, Tt = 7040 * 1024 * 1024, Et = 9216 * 1024 * 1024, Dt = 12e7, Ot = 6e7, kt = 8192;
1207
+ function At(e) {
1208
+ if (e > 0) return {
1209
+ gb: e,
1210
+ assumed: !1
1211
+ };
1212
+ let t = typeof navigator < "u" ? navigator.deviceMemory : void 0;
1213
+ return t > 0 ? {
1214
+ gb: t,
1215
+ assumed: !1
1216
+ } : {
1217
+ gb: 4,
1218
+ assumed: !0
1219
+ };
1220
+ }
1221
+ var jt = 1.15, Mt = 12 * 1024 * 1024 * 1024;
1222
+ function Nt({ triangles: e, placements: t, geometryBytes: n = 0, instanceBytes: r = 0 }) {
1223
+ let i = {
1224
+ triangles: e * vt,
1225
+ bvh: Math.ceil(e * bt) * yt,
1226
+ geometry: n,
1227
+ instances: r,
1228
+ placements: t * xt,
1229
+ orderMaps: e * Ct
1230
+ };
1231
+ return i.total = i.triangles + i.bvh + i.geometry + i.instances + i.placements + i.orderMaps, i;
1232
+ }
1233
+ function Pt(e, t, n) {
1234
+ let r = e.geometry + e.instances + t * 4 + n, i = e.instances + e.placements + t * St + e.orderMaps;
1235
+ return Math.max(r, i);
1236
+ }
1237
+ function Ft(e, { chunkBytes: t = I, shared: n = !1, allocate: r = null } = {}) {
1238
+ let i = Math.min(e, Mt), a = r ?? (n ? (e) => new SharedArrayBuffer(e) : (e) => new ArrayBuffer(e)), o = [], s = 0;
1239
+ try {
1240
+ for (; s < i;) {
1241
+ let e = Math.min(t, i - s);
1242
+ o.push(a(e)), s += e;
1243
+ }
1244
+ } catch {}
1245
+ for (let e = o.length - 1; e >= 0; e--) o[e] = null;
1246
+ return o.length = 0, {
1247
+ placed: s,
1248
+ want: i,
1249
+ exhausted: s < i,
1250
+ capped: e > i
1251
+ };
1252
+ }
1253
+ var It = class {
1254
+ constructor() {
1255
+ this.reset();
1256
+ }
1257
+ reset() {
1258
+ this.phase = "idle", this.events = [], this.samples = [], this.allocatedBytes = 0, this.peakLiveBytes = 0, this.byPhase = Object.create(null);
1259
+ }
1260
+ mark(e) {
1261
+ return this.phase = e, this.byPhase[e] ??= {
1262
+ allocated: 0,
1263
+ chunks: 0
1264
+ }, this;
1265
+ }
1266
+ alloc(e, t = "chunk") {
1267
+ if (!(e > 0)) return;
1268
+ let n = this.byPhase[this.phase] ??= {
1269
+ allocated: 0,
1270
+ chunks: 0
1271
+ };
1272
+ n.allocated += e, n.chunks++, this.allocatedBytes += e, this.events.push({
1273
+ phase: this.phase,
1274
+ bytes: e,
1275
+ what: t,
1276
+ at: performance.now()
1277
+ });
1278
+ }
1279
+ sample(e, t) {
1280
+ let n = 0;
1281
+ for (let e in t) n += t[e] || 0;
1282
+ return n > this.peakLiveBytes && (this.peakLiveBytes = n), this.samples.push({
1283
+ label: e,
1284
+ phase: this.phase,
1285
+ total: n,
1286
+ parts: t,
1287
+ at: performance.now()
1288
+ }), n;
1289
+ }
1290
+ get report() {
1291
+ return {
1292
+ allocatedBytes: this.allocatedBytes,
1293
+ peakLiveBytes: this.peakLiveBytes,
1294
+ byPhase: { ...this.byPhase },
1295
+ samples: this.samples.slice()
1296
+ };
1297
+ }
1298
+ }, Lt = "const e={VEC4_PER_BVH_NODE:4,FLOATS_PER_VEC4:4,MIN_TEXTURE_WIDTH:4,MAX_CONCURRENT_WORKERS:Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),BUFFER_POOL_SIZE:20,CANVAS_POOL_SIZE:12,CACHE_SIZE_LIMIT:50,MAX_TEXTURE_SIZE:8192,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256};function t(t,n){let r=Math.ceil(Math.max(1,t)/64)*64;return Math.min(n,Math.max(e.MIN_TEXTURE_WIDTH,r))}let n,r;const i={CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};let a=null;function o(e){if(e.stream===`begin`){let{width:t,height:n,depth:r}=e;a={width:t,height:n,depth:r,context:new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0}),data:new Uint8Array(t*n*r*4)};return}let{width:t,height:n,depth:r,context:i,data:o}=a;if(e.stream===`layer`){i.clearRect(0,0,t,n),i.drawImage(e.bitmap,0,0),e.bitmap.close(),o.set(i.getImageData(0,0,t,n).data,t*n*4*e.index),self.postMessage({stream:`ack`,index:e.index});return}a=null,self.postMessage({data:o.buffer,width:t,height:n,depth:r},[o.buffer])}async function s({shared:e,width:t,height:i,layers:a}){(n.width!==t||n.height!==i)&&(n.width=t,n.height=i),r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let o=new Uint8Array(e),s=t*i*4;for(let{index:e,texture:n}of a)try{await p(n,o,e*s,t,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t),o.fill(0,e*s,(e+1)*s)}}self.onmessage=async function(e){if(e.data.shared){try{n||c(e.data.maxTextureSize),await s(e.data),self.postMessage({done:!0})}catch(e){self.postMessage({error:e.message})}return}if(e.data.stream){try{o(e.data)}catch(e){self.postMessage({error:e.message})}return}let{textures:t,maxTextureSize:r,method:i=`direct-transfer`,dims:a=null}=e.data;try{n||c(r);let e=await l(t,r,i,a);self.postMessage(e,[e.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function c(t){let i=Math.min(t,e.MAX_TEXTURE_SIZE);n=new OffscreenCanvas(i,i),r=n.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function l(e,t,n,r=null){switch(n){case`direct-transfer`:return await g(e,t,r);case`offscreen-optimized`:return await v(e,t);case`imageBitmap-batch`:return await y(e,t);default:return await g(e,t,r)}}async function u(e,t,n){let{maxWidth:r,maxHeight:i}=b(e,t),a=e.length,o=d(r,i,a),s=Math.ceil(a/o);console.log(`Processing ${a} textures in ${s} chunks of up to ${o} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*o*4/1024/1024).toFixed(2)}MB`);let c;try{c=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await _(e,x(e,t),n)}let l=r*i*o*4,u;try{u=new Uint8Array(l)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await _(e,x(e,t),n)}for(let t=0;t<s;t++){let n=t*o,s=Math.min(n+o,a),l=s-n,d=await f(e.slice(n,s),r,i,u.subarray(0,r*i*l*4)),p=n*r*i*4,m=l*r*i*4;c.set(new Uint8Array(d.data.slice(0,m)),p),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:c.buffer,width:r,height:i,depth:a}}function d(e,t,n){if(!i.ADAPTIVE_CHUNK_SIZE)return Math.min(i.CHUNK_SIZE,n);let r=e*t*4/(1024*1024),a;return a=r<=1?16:r<=4?8:r<=16?4:2,Math.min(a,n,i.CHUNK_SIZE*2)}async function f(e,t,i,a){(n.width!==t||n.height!==i)&&(n.width=t,n.height=i);let o=t*i*4;r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let n=0;n<e.length;n++){let r=e[n];try{await p(r,a,n*o,t,i)}catch(e){console.warn(`Failed to process texture ${n}:`,e);let t=n*o;a.fill(0,t,t+o)}}return{data:a.buffer,width:t,height:i,depth:e.length}}async function p(e,t,n,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);r.clearRect(0,0,i,a),r.drawImage(o,0,0,i,a);let s=r.getImageData(0,0,i,a);t.set(s.data,n),o.close()}async function m(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await m(e,i,a)}return await f(e,t,n,r)}async function h(e,t,n,r,i){await p(e,n,r*i*4*t,r,i)}async function g(e,t,i=null){let{maxWidth:a,maxHeight:o}=i??b(e,t);(n.width!==a||n.height!==o)&&(n.width=a,n.height=o);let s=e.length,c;try{c=new Uint8Array(a*o*s*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`direct-transfer`)}r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let t=0;t<e.length;t++){let n=e[t];try{await h(n,t,c,a,o)}catch(e){console.warn(`Failed to process texture ${t}:`,e);let n=a*o*4*t;c.fill(0,n,n+a*o*4)}}return{data:c.buffer,width:a,height:o,depth:s}}async function _(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await m(e,r,i,n)}async function v(e,t){let{maxWidth:i,maxHeight:a}=b(e,t);(n.width!==i||n.height!==a)&&(n.width=i,n.height=a);let o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`offscreen-optimized`)}r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;for(let t=0;t<e.length;t++){let n=e[t];try{let e;if(n.isBlob){let t=new Blob([n.data]);e=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let t=new ImageData(new Uint8ClampedArray(n.data),n.width,n.height);e=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}r.clearRect(0,0,i,a),r.drawImage(e,0,0);let o=r.getImageData(0,0,i,a),c=i*a*4*t;s.set(o.data,c),e.close()}catch(e){console.warn(`Failed to process texture ${t}:`,e);let n=i*a*4*t;s.fill(0,n,n+i*a*4)}}return{data:s.buffer,width:i,height:a,depth:o}}async function y(e,t){let{maxWidth:i,maxHeight:a}=b(e,t),o=e.length,s;try{s=new Uint8Array(i*a*o*4)}catch(n){return console.error(`Failed to allocate texture array:`,n),await u(e,t,`imageBitmap-batch`)}let c=Math.min(d(i,a,e.length),e.length);for(let t=0;t<e.length;t+=c){let o=Math.min(t+c,e.length),l=[];for(let n=t;n<o;n++){let t=e[n],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}l.push(r.then(e=>({bitmap:e,index:n})))}let u=await Promise.all(l);n.width=i,n.height=a,r.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of u){r.clearRect(0,0,i,a),r.drawImage(e,0,0);let n=r.getImageData(0,0,i,a),o=i*a*4*t;s.set(n.data,o),e.close()}}return{data:s.buffer,width:i,height:a,depth:o}}function b(n,r){let i=0,a=0;for(let e of n)i=Math.max(i,e.width||0),a=Math.max(a,e.height||0);let o=Math.min(r,e.MAX_TEXTURE_SIZE),s=Math.max(i,a);if(s>o){let e=o/s;i=Math.round(i*e),a=Math.round(a*e)}return i=t(i,o),{maxWidth:i,maxHeight:Math.max(1,a)}}function x(e,t){let n=b(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}", Rt = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", Lt], { type: "text/javascript;charset=utf-8" });
1299
+ function zt(e) {
1300
+ let t;
1301
+ try {
1302
+ if (t = Rt && (self.URL || self.webkitURL).createObjectURL(Rt), !t) throw "";
1303
+ let n = new Worker(t, {
1304
+ type: "module",
1305
+ name: e?.name
1306
+ });
1307
+ return n.addEventListener("error", () => {
1308
+ (self.URL || self.webkitURL).revokeObjectURL(t);
1309
+ }), n;
1310
+ } catch {
1311
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(Lt), {
1312
+ type: "module",
1313
+ name: e?.name
1314
+ });
1315
+ }
1316
+ }
1317
+ //#endregion
1318
+ //#region src/materials/PackWorker.js?worker&inline
1319
+ var Bt = "function e({data:e,width:t,height:n,flipY:r},i,a,o,s){let c=o*4;if(t===o&&n===s){if(!r){i.set(e.subarray(0,s*c),a);return}for(let t=0;t<s;t++)i.set(e.subarray(t*c,(t+1)*c),a+(s-1-t)*c);return}let l=new Int32Array(o),u=new Int32Array(o),d=new Float64Array(o);for(let e=0;e<o;e++){let n=Math.min(Math.max((e+.5)*t/o-.5,0),t-1),r=Math.floor(n);l[e]=r*4,u[e]=Math.min(r+1,t-1)*4,d[e]=n-r}if(s<=n){for(let f=0;f<s;f++){let p=Math.min(Math.max((f+.5)*n/s-.5,0),n-1),m=Math.floor(p),h=Math.min(m+1,n-1),g=p-m,_=m*t*4,v=h*t*4,y=a+(r?s-1-f:f)*c;for(let t=0;t<o;t++,y+=4){let n=_+l[t],r=_+u[t],a=v+l[t],o=v+u[t],s=d[t];for(let t=0;t<4;t++){let c=e[n+t]+(e[r+t]-e[n+t])*s,l=e[a+t]+(e[o+t]-e[a+t])*s;i[y+t]=Math.round(c+(l-c)*g)}}}return}let f=[{row:-1,data:new Float64Array(c)},{row:-1,data:new Float64Array(c)}],p=(n,r)=>{for(let e of f)if(e.row===n)return e.data;let i=f[0].row===r?f[1]:f[0],a=n*t*4,s=i.data;for(let t=0,n=0;t<o;t++,n+=4){let r=a+l[t],i=a+u[t],o=d[t];s[n]=e[r]+(e[i]-e[r])*o,s[n+1]=e[r+1]+(e[i+1]-e[r+1])*o,s[n+2]=e[r+2]+(e[i+2]-e[r+2])*o,s[n+3]=e[r+3]+(e[i+3]-e[r+3])*o}return i.row=n,s};for(let e=0;e<s;e++){let t=Math.min(Math.max((e+.5)*n/s-.5,0),n-1),o=Math.floor(t),l=Math.min(o+1,n-1),u=t-o,d=p(o,l),f=l===o?d:p(l,o),m=a+(r?s-1-e:e)*c;for(let e=0;e<c;e++)i[m+e]=Math.round(d[e]+(f[e]-d[e])*u)}}self.onmessage=function(t){let{layers:n,width:r,height:i}=t.data;try{let t=r*i*4,a=new Uint8Array(t*n.length);n.forEach((n,o)=>e(n,a,o*t,r,i)),self.postMessage({data:a},[a.buffer])}catch(e){self.postMessage({error:e.message})}};", Vt = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", Bt], { type: "text/javascript;charset=utf-8" });
1320
+ function Ht(e) {
1321
+ let t;
1322
+ try {
1323
+ if (t = Vt && (self.URL || self.webkitURL).createObjectURL(Vt), !t) throw "";
1324
+ let n = new Worker(t, {
1325
+ type: "module",
1326
+ name: e?.name
1327
+ });
1328
+ return n.addEventListener("error", () => {
1329
+ (self.URL || self.webkitURL).revokeObjectURL(t);
1330
+ }), n;
1331
+ } catch {
1332
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(Bt), {
1333
+ type: "module",
1334
+ name: e?.name
1335
+ });
1336
+ }
1337
+ }
1338
+ //#endregion
1339
+ //#region src/materials/ResampleRGBA8.js
1340
+ function Ut({ data: e, width: t, height: n, flipY: r }, i, a, o, s) {
1341
+ let c = o * 4;
1342
+ if (t === o && n === s) {
1343
+ if (!r) {
1344
+ i.set(e.subarray(0, s * c), a);
1345
+ return;
1346
+ }
1347
+ for (let t = 0; t < s; t++) i.set(e.subarray(t * c, (t + 1) * c), a + (s - 1 - t) * c);
1348
+ return;
1349
+ }
1350
+ let l = new Int32Array(o), u = new Int32Array(o), d = new Float64Array(o);
1351
+ for (let e = 0; e < o; e++) {
1352
+ let n = Math.min(Math.max((e + .5) * t / o - .5, 0), t - 1), r = Math.floor(n);
1353
+ l[e] = r * 4, u[e] = Math.min(r + 1, t - 1) * 4, d[e] = n - r;
1354
+ }
1355
+ if (s <= n) {
1356
+ for (let f = 0; f < s; f++) {
1357
+ let p = Math.min(Math.max((f + .5) * n / s - .5, 0), n - 1), m = Math.floor(p), h = Math.min(m + 1, n - 1), g = p - m, _ = m * t * 4, v = h * t * 4, y = a + (r ? s - 1 - f : f) * c;
1358
+ for (let t = 0; t < o; t++, y += 4) {
1359
+ let n = _ + l[t], r = _ + u[t], a = v + l[t], o = v + u[t], s = d[t];
1360
+ for (let t = 0; t < 4; t++) {
1361
+ let c = e[n + t] + (e[r + t] - e[n + t]) * s, l = e[a + t] + (e[o + t] - e[a + t]) * s;
1362
+ i[y + t] = Math.round(c + (l - c) * g);
1363
+ }
1364
+ }
1365
+ }
1366
+ return;
1367
+ }
1368
+ let f = [{
1369
+ row: -1,
1370
+ data: new Float64Array(c)
1371
+ }, {
1372
+ row: -1,
1373
+ data: new Float64Array(c)
1374
+ }], p = (n, r) => {
1375
+ for (let e of f) if (e.row === n) return e.data;
1376
+ let i = f[0].row === r ? f[1] : f[0], a = n * t * 4, s = i.data;
1377
+ for (let t = 0, n = 0; t < o; t++, n += 4) {
1378
+ let r = a + l[t], i = a + u[t], o = d[t];
1379
+ s[n] = e[r] + (e[i] - e[r]) * o, s[n + 1] = e[r + 1] + (e[i + 1] - e[r + 1]) * o, s[n + 2] = e[r + 2] + (e[i + 2] - e[r + 2]) * o, s[n + 3] = e[r + 3] + (e[i + 3] - e[r + 3]) * o;
1380
+ }
1381
+ return i.row = n, s;
1382
+ };
1383
+ for (let e = 0; e < s; e++) {
1384
+ let t = Math.min(Math.max((e + .5) * n / s - .5, 0), n - 1), o = Math.floor(t), l = Math.min(o + 1, n - 1), u = t - o, d = p(o, l), f = l === o ? d : p(l, o), m = a + (r ? s - 1 - e : e) * c;
1385
+ for (let e = 0; e < c; e++) i[m + e] = Math.round(d[e] + (f[e] - d[e]) * u);
1386
+ }
1387
+ }
1388
+ //#endregion
1389
+ //#region src/output/ToneMapCPU.js
1390
+ var Wt = (e) => (t, n, r, i, a) => e(t > 0 ? t : 0, n > 0 ? n : 0, r > 0 ? r : 0, i, a), G = /* @__PURE__ */ new Map();
1391
+ function Gt() {
1392
+ G.clear();
1393
+ for (let e of S.values()) G.set(e.id, Wt(e.cpu));
1394
+ }
1395
+ Gt(), C(Gt);
1396
+ function Kt(e) {
1397
+ return w(e)?.outputEncoded === !0;
1398
+ }
1399
+ function K(e) {
1400
+ return e <= .0031308 ? 12.92 * e : 1.055 * e ** (1 / 2.4) - .055;
1401
+ }
1402
+ function qt(e, t) {
1403
+ let n = w(t);
1404
+ return n ? n.appliesExposure ? e : 1 : t === de ? 1 : e;
1405
+ }
1406
+ function Jt(e, t, n) {
1407
+ return qt(e, n) / qt(t, n);
1408
+ }
1409
+ function Yt(e, t, n) {
1410
+ return e + (t - e) * (1 - Math.min(Math.max(n, 0), 1));
1411
+ }
1412
+ var Xt = .2126, Zt = .7152, Qt = .0722;
1413
+ function $t(e, t) {
1414
+ if (t === 1) return;
1415
+ let n = e[0] * Xt + e[1] * Zt + e[2] * Qt;
1416
+ e[0] = n + (e[0] - n) * t, e[1] = n + (e[1] - n) * t, e[2] = n + (e[2] - n) * t;
1417
+ }
1418
+ function en(e, t) {
1419
+ return on(new Uint8ClampedArray(e.length), e, t);
1420
+ }
1421
+ function tn(e, t) {
1422
+ return on(new Uint16Array(e.length), e, t);
1423
+ }
1424
+ function nn(e, t) {
1425
+ return on(new Float32Array(e.length), e, t);
1426
+ }
1427
+ var rn = (e) => e > 0 ? e < 1 ? e : 1 : 0, an = (e) => e <= .04045 ? e / 12.92 : ((e + .055) / 1.055) ** 2.4;
1428
+ function on(e, t, { exposure: n, toneMapping: r, saturation: i = 1, preserveAlpha: a = !1, pixelGain: o = null }) {
1429
+ let s = G.get(r) ?? G.get(de), c = qt(n, r), l = Kt(r), u = e instanceof Float32Array ? (e) => an(rn(e)) : e instanceof Uint16Array ? (e) => Math.round(rn(e) * 65535) : (e) => e * 255 + .5, d = e instanceof Float32Array ? 1 : e instanceof Uint16Array ? 65535 : 255, f = [
1430
+ 0,
1431
+ 0,
1432
+ 0
1433
+ ], p = Math.log2(n);
1434
+ for (let n = 0; n < t.length; n += 4) {
1435
+ let r = c;
1436
+ if (o) {
1437
+ let e = 1;
1438
+ if (o.fn) {
1439
+ let r = n >> 2, i = r % o.width, a = (r - i) / o.width, s = t[n] * .2126 + t[n + 1] * .7152 + t[n + 2] * .0722;
1440
+ e = o.fn((i + .5) / o.width, (a + .5) / o.height, s, p);
1441
+ }
1442
+ o.backdrop > 0 && (e = Yt(e, o.backdrop, t[n + 3])), r *= e;
1443
+ }
1444
+ f[0] = t[n] * r, f[1] = t[n + 1] * r, f[2] = t[n + 2] * r, $t(f, i), s(f[0], f[1], f[2], 1, f), l ? (e[n] = u(f[0]), e[n + 1] = u(f[1]), e[n + 2] = u(f[2])) : (e[n] = u(K(f[0])), e[n + 1] = u(K(f[1])), e[n + 2] = u(K(f[2]))), e[n + 3] = a ? e instanceof Float32Array ? rn(t[n + 3]) : u(t[n + 3]) : d;
1445
+ }
1446
+ return e;
1447
+ }
1448
+ //#endregion
1449
+ //#region src/materials/TextureCreator.js
1450
+ var q = n("textures"), J = {
1451
+ MAX_BUFFER_MEMORY: 1024 * 1024 * 1024,
1452
+ MAX_TEXTURE_MEMORY: 2048 * 1024 * 1024,
1453
+ CLEANUP_THRESHOLD: .8,
1454
+ STREAM_BATCH_SIZE: 4
1455
+ }, sn = 8 * 2 ** 20, cn = 16, ln = 4, un = 8192 * 8192, Y = {
1456
+ busy: 0,
1457
+ waiting: []
1458
+ };
1459
+ async function dn() {
1460
+ return Y.busy < Math.max(1, rt() - 1) ? Y.busy++ : await new Promise((e) => Y.waiting.push(e)), () => {
1461
+ let e = Y.waiting.shift();
1462
+ e ? e() : Y.busy--;
1463
+ };
1464
+ }
1465
+ var fn = 256 * 2 ** 20, pn = {
1466
+ toSRGB: null,
1467
+ toLinear: null
1468
+ };
1469
+ function mn(e) {
1470
+ if (!pn[e]) {
1471
+ let t = new Uint8Array(256);
1472
+ for (let n = 0; n < 256; n++) {
1473
+ let r = n / 255, i = e === "toSRGB" ? K(r) : r <= .04045 ? r / 12.92 : ((r + .055) / 1.055) ** 2.4;
1474
+ t[n] = Math.max(0, Math.min(255, Math.round(i * 255)));
1475
+ }
1476
+ pn[e] = t;
1477
+ }
1478
+ return pn[e];
1479
+ }
1480
+ var hn = class {
1481
+ constructor() {
1482
+ this.canvasContextPairs = [], this.maxPoolSize = c.CANVAS_POOL_SIZE;
1483
+ }
1484
+ getCanvasWithContext(e, t, n = !1, r = {}) {
1485
+ let i = {
1486
+ willReadFrequently: !0,
1487
+ alpha: !0,
1488
+ desynchronized: !0,
1489
+ ...r
1490
+ }, a = this.canvasContextPairs.pop();
1491
+ if (!a) {
1492
+ let r;
1493
+ r = n && typeof OffscreenCanvas < "u" ? new OffscreenCanvas(e, t) : document.createElement("canvas");
1494
+ let o = r.getContext("2d", i);
1495
+ a = {
1496
+ canvas: r,
1497
+ context: o
1498
+ };
1499
+ }
1500
+ return a.canvas.width = e, a.canvas.height = t, a;
1501
+ }
1502
+ releaseCanvasWithContext(e) {
1503
+ this.canvasContextPairs.length < this.maxPoolSize && (e.context.globalAlpha = 1, e.context.globalCompositeOperation = "source-over", e.context.imageSmoothingEnabled = !0, e.context.clearRect(0, 0, e.canvas.width, e.canvas.height), e.canvas.width = 1, e.canvas.height = 1, this.canvasContextPairs.push(e));
1504
+ }
1505
+ getCanvas(e, t, n = !1) {
1506
+ return this.getCanvasWithContext(e, t, n).canvas;
1507
+ }
1508
+ getContext(e, t = {}) {
1509
+ let n = this.canvasContextPairs.find((t) => t.canvas === e);
1510
+ return n ? n.context : e.getContext("2d", {
1511
+ willReadFrequently: !0,
1512
+ alpha: !0,
1513
+ desynchronized: !0,
1514
+ ...t
1515
+ });
1516
+ }
1517
+ dispose() {
1518
+ this.canvasContextPairs = [];
1519
+ }
1520
+ }, gn = class {
1521
+ constructor(e = {}) {
1522
+ this.pools = /* @__PURE__ */ new Map(), this.memoryUsage = 0, this.maxMemoryUsage = e.maxMemory || J.MAX_BUFFER_MEMORY, this.allocatedBuffers = /* @__PURE__ */ new WeakMap(), this.sizeStrategy = e.sizeStrategy || "adaptive";
1523
+ }
1524
+ getOptimalSize(e) {
1525
+ switch (this.sizeStrategy) {
1526
+ case "exact": return e;
1527
+ case "power2": return 2 ** Math.ceil(Math.log2(e));
1528
+ default: return e < 1024 ? e : e < 1024 * 1024 ? Math.ceil(e / 1024) * 1024 : e < 64 * 2 ** 20 ? 2 ** Math.ceil(Math.log2(e)) : Math.ceil(e / 2 ** 20) * 2 ** 20;
1529
+ }
1530
+ }
1531
+ getBuffer(e, t = Float32Array) {
1532
+ let n = this.getOptimalSize(e), r = `${t.name}-${n}`, i = (this.pools.get(r) || []).pop();
1533
+ if (!i) try {
1534
+ i = new t(n), this.memoryUsage += i.byteLength, this.allocatedBuffers.set(i, !0);
1535
+ } catch {
1536
+ this.cleanup();
1537
+ try {
1538
+ i = new t(n), this.memoryUsage += i.byteLength, this.allocatedBuffers.set(i, !0);
1539
+ } catch (e) {
1540
+ let r = n * t.BYTES_PER_ELEMENT / (1024 * 1024), i = this.memoryUsage / (1024 * 1024);
1541
+ throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage / (1024 * 1024)).toFixed(1)}MB. Original error: ${e.message}`);
1542
+ }
1543
+ }
1544
+ return this.memoryUsage > this.maxMemoryUsage * J.CLEANUP_THRESHOLD && this.cleanup(), this.checkMemoryHealth(), i.byteOffset + e * t.BYTES_PER_ELEMENT > i.buffer.byteLength && (i = new t(e), this.memoryUsage += i.byteLength), new t(i.buffer, i.byteOffset, e);
1545
+ }
1546
+ forget(e) {
1547
+ this.memoryUsage = Math.max(0, this.memoryUsage - e.buffer.byteLength);
1548
+ }
1549
+ releaseBuffer(e, t = Float32Array) {
1550
+ let n = (e.buffer.byteLength - e.byteOffset) / t.BYTES_PER_ELEMENT, r = this.getOptimalSize(n), i = `${t.name}-${r}`, a = this.pools.get(i) || [];
1551
+ a.length < c.BUFFER_POOL_SIZE ? (a.push(new t(e.buffer, e.byteOffset, n)), this.pools.set(i, a)) : this.allocatedBuffers.has(e) && (this.memoryUsage -= e.byteLength, this.allocatedBuffers.delete(e));
1552
+ }
1553
+ cleanup() {
1554
+ let e = Array.from(this.pools.entries());
1555
+ e.slice(0, Math.floor(e.length / 2)).forEach(([e, t]) => {
1556
+ t.forEach((e) => {
1557
+ this.allocatedBuffers.has(e) && (this.memoryUsage -= e.byteLength, this.allocatedBuffers.delete(e));
1558
+ }), this.pools.delete(e);
1559
+ });
1560
+ }
1561
+ dispose() {
1562
+ this.pools.forEach((e) => {
1563
+ e.forEach((e) => {
1564
+ this.allocatedBuffers.has(e) && this.allocatedBuffers.delete(e);
1565
+ });
1566
+ }), this.pools.clear(), this.memoryUsage = 0;
1567
+ }
1568
+ getMemoryStats() {
1569
+ return {
1570
+ currentUsage: this.memoryUsage,
1571
+ maxUsage: this.maxMemoryUsage,
1572
+ utilizationPercentage: this.memoryUsage / this.maxMemoryUsage * 100,
1573
+ poolCount: this.pools.size,
1574
+ allocatedBufferCount: this.allocatedBuffers && this.allocatedBuffers.size || 0
1575
+ };
1576
+ }
1577
+ checkMemoryHealth() {
1578
+ let e = this.getMemoryStats();
1579
+ return e.utilizationPercentage > 90 ? (console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage / (1024 * 1024)).toFixed(1)}MB / ${(e.maxUsage / (1024 * 1024)).toFixed(1)}MB)`), "critical") : e.utilizationPercentage > 70 ? (console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage / (1024 * 1024)).toFixed(1)}MB / ${(e.maxUsage / (1024 * 1024)).toFixed(1)}MB)`), "high") : "normal";
1580
+ }
1581
+ }, X = class {
1582
+ constructor(e = c.CACHE_SIZE_LIMIT) {
1583
+ this.cache = /* @__PURE__ */ new Map(), this.accessOrder = [], this.maxSize = e;
1584
+ }
1585
+ generateHash(e) {
1586
+ let t = "";
1587
+ for (let n of e) if (n?.image) {
1588
+ let e = n.image.width || 0, r = n.image.height || 0, i = n.image.src || n.uuid || "", a = n.flipY === !1 ? "n" : "f", o = `${n.colorSpace ?? ""}|${n.userData?.ocioColorSpace ?? ""}`;
1589
+ t += `${e}x${r}_${i.slice(-8)}_${a}_${o}_`;
1590
+ }
1591
+ return t + e.length;
1592
+ }
1593
+ get(e) {
1594
+ if (this.cache.has(e)) {
1595
+ let t = this.cache.get(e);
1596
+ if (t?.userData && t.userData.buffer === null) {
1597
+ this.cache.delete(e);
1598
+ let t = this.accessOrder.indexOf(e);
1599
+ return t > -1 && this.accessOrder.splice(t, 1), null;
1600
+ }
1601
+ let n = this.accessOrder.indexOf(e);
1602
+ return n > -1 && this.accessOrder.splice(n, 1), this.accessOrder.push(e), t;
1603
+ }
1604
+ return null;
1605
+ }
1606
+ set(e, t) {
1607
+ if (this.cache.has(e)) {
1608
+ let t = this.accessOrder.indexOf(e);
1609
+ t > -1 && this.accessOrder.splice(t, 1);
1610
+ } else this.cache.size >= this.maxSize && this.evictLRU();
1611
+ this.cache.set(e, t), this.accessOrder.push(e);
1612
+ }
1613
+ evictLRU() {
1614
+ if (this.accessOrder.length > 0) {
1615
+ let e = this.accessOrder.shift(), t = this.cache.get(e);
1616
+ t && t.dispose && t.dispose(), this.cache.delete(e);
1617
+ }
1618
+ }
1619
+ dispose() {
1620
+ this.cache.forEach((e) => {
1621
+ e && e.dispose && e.dispose();
1622
+ }), this.cache.clear(), this.accessOrder = [];
1623
+ }
1624
+ }, _n = class {
1625
+ constructor(e = {}) {
1626
+ this.useWorkers = typeof Worker < "u", this.maxConcurrentWorkers = c.MAX_CONCURRENT_WORKERS, this.activeWorkers = 0, this._issues = e.issues ?? null, this.layerSink = e.layerSink ?? null, this.groupBytes = e.groupBytes ?? fn, this.maxTextureSize = this._clampTextureSize(e.maxTextureSize ?? c.DEFAULT_MAX_TEXTURE_SIZE), this.canvasPool = new hn(), this.bufferPool = new gn({
1627
+ maxMemory: e.maxBufferMemory || J.MAX_BUFFER_MEMORY,
1628
+ sizeStrategy: e.bufferSizeStrategy || "adaptive"
1629
+ }), this.textureCache = new X(), this.capabilities = this.detectCapabilities(), this.optimalMethod = this.selectOptimalMethod();
1630
+ }
1631
+ _reportTextureFailure(e, t) {
1632
+ if (t instanceof v) throw t;
1633
+ this._issues?.record(_.TEXTURE_BUILD_FAILED, `${e} texture array failed to build — those surfaces render untextured`, {
1634
+ map: e,
1635
+ cause: String(t?.message ?? t)
1636
+ });
1637
+ }
1638
+ _reportTextureLayer(e, t) {
1639
+ this._issues?.record(_.TEXTURE_BUILD_FAILED, `texture ${e} could not be read — its surfaces show a white placeholder`, {
1640
+ layer: e,
1641
+ cause: String(t?.message ?? t)
1642
+ });
1643
+ }
1644
+ _clampTextureSize(e) {
1645
+ let t = Math.floor(Number(e) || c.DEFAULT_MAX_TEXTURE_SIZE);
1646
+ return Math.max(c.MIN_TEXTURE_WIDTH, Math.min(t, c.MAX_TEXTURE_SIZE));
1647
+ }
1648
+ setMaxTextureSize(e) {
1649
+ let t = this._clampTextureSize(e);
1650
+ return t === this.maxTextureSize ? t : (this.maxTextureSize = t, this.textureCache?.dispose(), this.textureCache = new X(), this.maxTextureSize);
1651
+ }
1652
+ detectCapabilities() {
1653
+ return {
1654
+ offscreenCanvas: typeof OffscreenCanvas < "u",
1655
+ imageBitmap: typeof createImageBitmap < "u",
1656
+ workers: typeof Worker < "u",
1657
+ hardwareConcurrency: rt()
1658
+ };
1659
+ }
1660
+ selectOptimalMethod() {
1661
+ return this.capabilities.workers && this.capabilities.offscreenCanvas ? "worker-offscreen" : this.capabilities.imageBitmap ? "imageBitmap" : "canvas";
1662
+ }
1663
+ _applyColorManagement(e, t, n, r = /* @__PURE__ */ new Set(), i = null) {
1664
+ let a = x();
1665
+ if (!a?.hasConfig) return;
1666
+ let o = e?.image?.data;
1667
+ if (!o || !n) return;
1668
+ let s = t.filter((e) => e?.image), c = e.image.width * e.image.height * 4, l = 0, u = 0, d = [];
1669
+ for (let e = 0; e < s.length; e++) {
1670
+ let t = e * c, n = Math.min(t + c, o.length);
1671
+ if (t >= o.length) break;
1672
+ let i = s[e], f = o.subarray(t, n), p = null;
1673
+ try {
1674
+ p = a.resolveTexture(i);
1675
+ } catch (t) {
1676
+ q.warn(`could not resolve the colour space of layer ${e}: ${t.message}`);
1677
+ }
1678
+ let m = p && p.via !== "three" ? p.colorSpace : null, h = i.type === ie || i.type === oe;
1679
+ m && (r.has(e) || h) && (d.push(`${i.name || `layer ${e}`} (${m})`), m = null);
1680
+ try {
1681
+ a.convertTextureBytes(f, {
1682
+ space: m,
1683
+ encoding: "srgb"
1684
+ }) && (m ? l++ : u++);
1685
+ } catch (t) {
1686
+ this._issues?.warn(_.TEXTURE_PROCESSING_FALLBACK, `colour conversion failed for layer ${e} — left in its original space`, {
1687
+ cause: String(t?.message ?? t),
1688
+ space: m
1689
+ });
1690
+ }
1691
+ }
1692
+ l + u > 0 && (e.needsUpdate = !0), i ? (i.named += l, i.primaries += u, i.refused.push(...d)) : this._reportColorManaged({
1693
+ named: l,
1694
+ primaries: u,
1695
+ refused: d
1696
+ }, s.length);
1697
+ }
1698
+ _reportColorManaged({ named: e, primaries: t, refused: n }, r) {
1699
+ n.length && this._issues?.warn(_.TEXTURE_PROCESSING_FALLBACK, `${n.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`, { textures: n.slice(0, 8) }), e + t !== 0 && q.info(`colour maps into ${x().workingSpace}: ${e} by named space, ${t} by primaries, of ${r}`);
1700
+ }
1701
+ _harmonizeTransfer(e, t, n, r = null) {
1702
+ let i = /* @__PURE__ */ new Set(), a = e?.image?.data;
1703
+ if (!a) return i;
1704
+ let o = t.filter((e) => e?.image), s = n ? M : se, c = e.image.width * e.image.height * 4, l = [];
1705
+ for (let e = 0; e < o.length; e++) {
1706
+ let t = o[e].colorSpace;
1707
+ if (t !== M && t !== se || t === s) continue;
1708
+ let r = mn(n ? "toSRGB" : "toLinear"), u = e * c, d = Math.min(u + c, a.length);
1709
+ for (let e = u; e < d; e += 4) a[e] = r[a[e]], a[e + 1] = r[a[e + 1]], a[e + 2] = r[a[e + 2]];
1710
+ l.push(o[e].name || o[e].source?.uuid?.slice(0, 8) || `layer ${e}`), i.add(e);
1711
+ }
1712
+ return l.length > 0 && (e.needsUpdate = !0), r ? r.converted.push(...l) : this._reportHarmonized(l, o.length, n), i;
1713
+ }
1714
+ _reportHarmonized(e, t, n) {
1715
+ if (e.length === 0) return;
1716
+ let r = e.slice(0, 4).join(", ") + (e.length > 4 ? `, +${e.length - 4} more` : "");
1717
+ n ? q.info(`re-encoded ${e.length}/${t} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${r}`) : q.warn(`decoded ${e.length}/${t} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${r}`);
1718
+ }
1719
+ async createTexturesToDataTexture(e, { srgbPool: t = !1 } = {}) {
1720
+ if (!e || e.length === 0) return null;
1721
+ let n = x()?.inputKey ?? "-", r = `${t ? "s" : "l"}:${n}:${this.textureCache.generateHash(e)}`, i = this.textureCache.get(r);
1722
+ if (i) return i;
1723
+ let a = e.filter((e) => e?.image), o = this.calculateOptimalDimensions(a);
1724
+ if (this.layerSink && o.maxWidth * o.maxHeight * a.length * 4 > this.groupBytes) return this._packInGroups(a, t, o);
1725
+ let s;
1726
+ try {
1727
+ await this._holdImages(e), s = await this._packTextures(e, t);
1728
+ } finally {
1729
+ Tn(e);
1730
+ }
1731
+ return s && this.textureCache.set(r, s), s;
1732
+ }
1733
+ _holdImages(e) {
1734
+ return wn(e, (e) => this._issues?.record(_.TEXTURE_BUILD_FAILED, "a material map could not be read again — its surfaces show a white placeholder", { cause: String(e?.message ?? e) }));
1735
+ }
1736
+ async _packInGroups(e, t, n) {
1737
+ let { maxWidth: r, maxHeight: i } = n, a = r * i * 4, o = Math.max(1, Math.floor(this.groupBytes / a)), s = typeof createImageBitmap > "u" ? null : this.selectProcessingStrategy(e), c = {
1738
+ converted: [],
1739
+ named: 0,
1740
+ primaries: 0,
1741
+ refused: []
1742
+ }, l = { shared: null }, u = this.createDataArrayTextureFromBuffer(null, r, i, e.length);
1743
+ u.source.dataReady = !1, t && (u.colorSpace = M), this.layerSink.allocate(u);
1744
+ try {
1745
+ for (let a = 0; a < e.length; a += o) {
1746
+ let d = e.slice(a, a + o), f;
1747
+ try {
1748
+ await this._holdImages(d), f = await this._packTextures(d, t, {
1749
+ dims: n,
1750
+ strategy: s,
1751
+ tally: c,
1752
+ scratch: l
1753
+ });
1754
+ } finally {
1755
+ Tn(d);
1756
+ }
1757
+ let { data: p } = f.image;
1758
+ if (f.image.width !== r || f.image.height !== i || f.image.depth !== d.length) throw Error(`texture group packed at ${f.image.width}x${f.image.height}x${f.image.depth}, not ${r}x${i}x${d.length}`);
1759
+ await this.layerSink.write(u, a, p, d.length), this.bufferPool.forget(p), p.byteLength === p.buffer.byteLength && p.buffer.transfer && p.buffer.transfer(0);
1760
+ }
1761
+ } catch (e) {
1762
+ throw u.dispose(), e;
1763
+ }
1764
+ return this._reportHarmonized(c.converted, e.length, t), this._reportColorManaged(c, e.length), u;
1765
+ }
1766
+ async _packTextures(e, t, { dims: n, strategy: r, tally: i, scratch: a } = {}) {
1767
+ if (typeof createImageBitmap > "u") {
1768
+ let r = await this.processOnCPU(e, n), a = this._harmonizeTransfer(r, e, t, i);
1769
+ return this._applyColorManagement(r, e, t, a, i), r;
1770
+ }
1771
+ let { normalized: o, bitmapsToClose: s } = await this._normalizeTexturesForProcessing(e);
1772
+ r ??= this.selectProcessingStrategy(o);
1773
+ let c;
1774
+ try {
1775
+ switch (r.method) {
1776
+ case "worker-direct":
1777
+ c = await this.processWithWorkerDirect(o, n, a);
1778
+ break;
1779
+ case "worker-streaming":
1780
+ c = await this.processInWorkerStreaming(o, n);
1781
+ break;
1782
+ case "main-batch":
1783
+ c = await this.processOnMainThreadBatch(o, r.batchSize, n);
1784
+ break;
1785
+ case "main-streaming":
1786
+ c = await this.processOnMainThreadStreaming(o, n);
1787
+ break;
1788
+ default: c = await this.processOnMainThreadSync(o, n);
1789
+ }
1790
+ if (n && c && (c.image.width !== n.maxWidth || c.image.height !== n.maxHeight)) throw Error(`packed at ${c.image.width}x${c.image.height}, not the bucket's ${n.maxWidth}x${n.maxHeight}`);
1791
+ if (c) {
1792
+ let n = this._harmonizeTransfer(c, e, t, i);
1793
+ this._applyColorManagement(c, e, t, n, i);
1794
+ }
1795
+ return c;
1796
+ } catch (r) {
1797
+ if (r instanceof v) throw r;
1798
+ this._issues?.warn(_.TEXTURE_PROCESSING_FALLBACK, "worker texture processing failed — retrying on the main thread", { cause: String(r?.message ?? r) });
1799
+ let a = await this.processOnMainThreadSync(o, n), s = this._harmonizeTransfer(a, e, t, i);
1800
+ return this._applyColorManagement(a, e, t, s, i), a;
1801
+ } finally {
1802
+ for (let e of s) e.close();
1803
+ }
1804
+ }
1805
+ selectProcessingStrategy(e) {
1806
+ let t = e.reduce((e, t) => e + (t.image?.width || 0) * (t.image?.height || 0), 0), n = t * 4;
1807
+ return this.capabilities.workers && n > J.MAX_TEXTURE_MEMORY ? { method: "worker-streaming" } : this.capabilities.workers && t > 2097152 ? { method: "worker-direct" } : t > 524288 ? {
1808
+ method: "main-batch",
1809
+ batchSize: Math.min(4, e.length)
1810
+ } : e.length > 8 ? { method: "main-streaming" } : { method: "main-sync" };
1811
+ }
1812
+ async processWithWorkerDirect(e, t = null, n = null) {
1813
+ for (; this.activeWorkers >= this.maxConcurrentWorkers;) await new Promise((e) => setTimeout(e, 10));
1814
+ this.activeWorkers++;
1815
+ let r = 1, i = null;
1816
+ try {
1817
+ let a = await this.prepareTexturesForWorkerDirect(e), o = this._sharedPackSlots(a);
1818
+ if (o > 0) return r += o, this.activeWorkers += o, this.createDataArrayTextureFromResult(await this._packAcrossWorkers(a, r, t, n));
1819
+ i = new zt();
1820
+ let s = await new Promise((e, n) => {
1821
+ i.onmessage = (t) => {
1822
+ t.data.error ? n(Error(t.data.error)) : e(t.data);
1823
+ }, i.onerror = n;
1824
+ let r = [];
1825
+ a.forEach((e) => {
1826
+ e.data instanceof ArrayBuffer ? r.push(e.data) : e.bitmap && r.push(e.bitmap);
1827
+ }), i.postMessage({
1828
+ textures: a,
1829
+ maxTextureSize: this.maxTextureSize,
1830
+ method: "direct-transfer",
1831
+ dims: t
1832
+ }, r);
1833
+ });
1834
+ return this.createDataArrayTextureFromResult(s);
1835
+ } finally {
1836
+ i?.terminate(), this.activeWorkers -= r;
1837
+ }
1838
+ }
1839
+ _sharedPackSlots(e) {
1840
+ if (typeof SharedArrayBuffer > "u" || !globalThis.crossOriginIsolated || e.reduce((e, t) => e + t.width * t.height, 0) < un) return 0;
1841
+ let t = this.maxConcurrentWorkers - this.activeWorkers;
1842
+ return Math.max(0, Math.min(e.length, ln, t + 1) - 1);
1843
+ }
1844
+ async _packAcrossWorkers(e, t, n = null, r = null) {
1845
+ let { maxWidth: i, maxHeight: a } = n ?? this.calculateOptimalDimensions(e.map((e) => ({ image: e }))), o = e.length, s = i * a * o * 4, c = r?.shared?.byteLength >= s ? r.shared : new SharedArrayBuffer(s);
1846
+ r && (r.shared = c);
1847
+ let l = Array.from({ length: t }, () => ({
1848
+ cost: 0,
1849
+ layers: [],
1850
+ transfer: []
1851
+ })), u = e.map((e, t) => t), d = (t) => e[t].width * e[t].height;
1852
+ u.sort((e, t) => d(t) - d(e));
1853
+ for (let t of u) {
1854
+ let n = l.reduce((e, t) => t.cost < e.cost ? t : e), r = e[t];
1855
+ n.layers.push({
1856
+ index: t,
1857
+ texture: r
1858
+ }), n.cost += d(t), r.data instanceof ArrayBuffer ? n.transfer.push(r.data) : r.bitmap && n.transfer.push(r.bitmap);
1859
+ }
1860
+ let f = [];
1861
+ try {
1862
+ await Promise.all(l.filter((e) => e.layers.length).map((e) => new Promise((t, n) => {
1863
+ let r = W(zt);
1864
+ f.push(r), r.onmessage = ({ data: e }) => e.error ? n(Error(e.error)) : t(), r.onerror = (e) => n(Error(e.message || "texture worker failed")), r.postMessage({
1865
+ shared: c,
1866
+ width: i,
1867
+ height: a,
1868
+ layers: e.layers,
1869
+ maxTextureSize: this.maxTextureSize
1870
+ }, e.transfer);
1871
+ })));
1872
+ } finally {
1873
+ for (let e of f) e.terminate();
1874
+ }
1875
+ return {
1876
+ data: new Uint8Array(c, 0, s),
1877
+ width: i,
1878
+ height: a,
1879
+ depth: o
1880
+ };
1881
+ }
1882
+ async processInWorkerStreaming(e, t = null) {
1883
+ let n = e.filter((e) => e?.image);
1884
+ if (n.length === 0) return this.createFallbackTexture();
1885
+ let { maxWidth: r, maxHeight: i } = t ?? this.calculateOptimalDimensions(n), a = n.length;
1886
+ for (; this.activeWorkers >= this.maxConcurrentWorkers;) await new Promise((e) => setTimeout(e, 10));
1887
+ this.activeWorkers++;
1888
+ let o = W(zt);
1889
+ try {
1890
+ let e = 0, t = null, s, c = new Promise((e, t) => s = {
1891
+ resolve: e,
1892
+ reject: t
1893
+ });
1894
+ c.catch(() => {}), o.onmessage = ({ data: n }) => {
1895
+ n.error ? s.reject(Error(n.error)) : n.stream === "ack" ? e++ : s.resolve(n), t?.();
1896
+ }, o.onerror = (e) => {
1897
+ s.reject(Error(e.message || "texture worker failed")), t?.();
1898
+ }, o.postMessage({
1899
+ stream: "begin",
1900
+ width: r,
1901
+ height: i,
1902
+ depth: a
1903
+ });
1904
+ let l = performance.now();
1905
+ for (let s = 0; s < a; s++) {
1906
+ for (; s - e >= J.STREAM_BATCH_SIZE;) await Promise.race([new Promise((e) => t = e), c]), l = performance.now();
1907
+ let a = n[s], u = await createImageBitmap(a.image, {
1908
+ resizeWidth: r,
1909
+ resizeHeight: i,
1910
+ resizeQuality: "high",
1911
+ imageOrientation: a.flipY === !1 ? "none" : "flipY"
1912
+ });
1913
+ o.postMessage({
1914
+ stream: "layer",
1915
+ index: s,
1916
+ bitmap: u
1917
+ }, [u]), performance.now() - l > cn && (await new Promise((e) => setTimeout(e, 0)), l = performance.now());
1918
+ }
1919
+ return o.postMessage({ stream: "end" }), this.createDataArrayTextureFromResult(await c);
1920
+ } finally {
1921
+ o.terminate(), this.activeWorkers--;
1922
+ }
1923
+ }
1924
+ async prepareTexturesForWorkerDirect(e) {
1925
+ let t = [], n = () => ({
1926
+ data: new Uint8ClampedArray([
1927
+ 255,
1928
+ 255,
1929
+ 255,
1930
+ 255
1931
+ ]).buffer,
1932
+ width: 1,
1933
+ height: 1,
1934
+ isImageData: !0
1935
+ });
1936
+ for (let r = 0; r < e.length; r++) {
1937
+ let i = e[r];
1938
+ if (!i?.image) {
1939
+ this._reportTextureLayer(r, "no image"), t.push(n());
1940
+ continue;
1941
+ }
1942
+ let a = i.flipY !== !1;
1943
+ try {
1944
+ let e = i.image;
1945
+ if (typeof createImageBitmap < "u" && (typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof OffscreenCanvas < "u" && e instanceof OffscreenCanvas)) {
1946
+ let e = await createImageBitmap(i.image, { imageOrientation: a ? "flipY" : "none" });
1947
+ t.push({
1948
+ bitmap: e,
1949
+ width: i.image.width,
1950
+ height: i.image.height,
1951
+ isDirect: !0
1952
+ });
1953
+ } else {
1954
+ let e = i.image.width, n = i.image.height, r = await createImageBitmap(i.image, { imageOrientation: a ? "flipY" : "none" }), o = this.canvasPool.getCanvasWithContext(e, n);
1955
+ o.context.drawImage(r, 0, 0), r.close();
1956
+ let s = o.context.getImageData(0, 0, e, n);
1957
+ t.push({
1958
+ data: s.data.buffer,
1959
+ width: e,
1960
+ height: n,
1961
+ isImageData: !0
1962
+ }), this.canvasPool.releaseCanvasWithContext(o);
1963
+ }
1964
+ } catch (e) {
1965
+ this._reportTextureLayer(r, e), t.push(n());
1966
+ }
1967
+ }
1968
+ return t;
1969
+ }
1970
+ async processOnCPU(e, t = null) {
1971
+ let n = e.map((e, t) => {
1972
+ let n = e?.image, r = e?.isCompressedTexture ? e.mipmaps?.[0] : n, i = e?.isCompressedTexture ? r?.data : yn(e);
1973
+ return i && r.width > 0 && r.height > 0 && i.byteLength >= r.width * r.height * 4 ? {
1974
+ data: new Uint8Array(i.buffer, i.byteOffset, r.width * r.height * 4),
1975
+ width: r.width,
1976
+ height: r.height,
1977
+ flipY: e.flipY !== !1
1978
+ } : (this._reportTextureLayer(t, n ? "not decoded to pixels, and there is no browser to decode it" : "no image"), {
1979
+ data: new Uint8Array([
1980
+ 255,
1981
+ 255,
1982
+ 255,
1983
+ 255
1984
+ ]),
1985
+ width: 1,
1986
+ height: 1,
1987
+ flipY: !1
1988
+ });
1989
+ }), { maxWidth: r, maxHeight: i } = t ?? this.calculateOptimalDimensions(n.map((e) => ({ image: e }))), a = r * i * 4, o = at() && a * n.length >= sn ? await this._packInWorker(n, r, i) : null;
1990
+ if (o) return this.createDataArrayTextureFromBuffer(o, r, i, n.length);
1991
+ let s = this.bufferPool.getBuffer(a * n.length, Uint8Array);
1992
+ return n.forEach((e, t) => Ut(e, s, t * a, r, i)), this.createDataArrayTextureFromBuffer(s, r, i, n.length);
1993
+ }
1994
+ async _packInWorker(e, t, n) {
1995
+ let r = await dn(), i = null;
1996
+ try {
1997
+ let r = [], a = e.map((e) => {
1998
+ if (typeof SharedArrayBuffer < "u" && e.data.buffer instanceof SharedArrayBuffer) return e;
1999
+ let t = e.data.slice();
2000
+ return r.push(t.buffer), {
2001
+ ...e,
2002
+ data: t
2003
+ };
2004
+ });
2005
+ return i = W(Ht), await new Promise((e, o) => {
2006
+ i.onmessage = (t) => t.data.error ? o(Error(t.data.error)) : e(t.data.data), i.onerror = (e) => o(e.error ?? Error(e.message ?? "texture pack worker failed")), i.postMessage({
2007
+ layers: a,
2008
+ width: t,
2009
+ height: n
2010
+ }, r);
2011
+ });
2012
+ } catch (e) {
2013
+ return this._issues?.warn(_.TEXTURE_PROCESSING_FALLBACK, "worker texture packing failed — packing on the main thread", { cause: String(e?.message ?? e) }), null;
2014
+ } finally {
2015
+ i?.terminate(), r();
2016
+ }
2017
+ }
2018
+ async processOnMainThreadBatch(e, t, n = null) {
2019
+ let r = e.filter((e) => e?.image);
2020
+ if (r.length === 0) return this.createFallbackTexture();
2021
+ let { maxWidth: i, maxHeight: a } = n ?? this.calculateOptimalDimensions(r), o = r.length, s = this.bufferPool.getBuffer(i * a * o * 4, Uint8Array);
2022
+ for (let e = 0; e < r.length; e += t) {
2023
+ let n = Math.min(e + t, r.length), o = [];
2024
+ for (let t = e; t < n; t++) {
2025
+ let e = r[t], n = e.flipY !== !1, s = createImageBitmap(e.image, {
2026
+ resizeWidth: i,
2027
+ resizeHeight: a,
2028
+ resizeQuality: "high",
2029
+ imageOrientation: n ? "flipY" : "none"
2030
+ });
2031
+ o.push(s.then((e) => ({
2032
+ bitmap: e,
2033
+ index: t
2034
+ })));
2035
+ }
2036
+ let c = await Promise.all(o), l = this.canvasPool.getCanvasWithContext(i, a);
2037
+ l.context.imageSmoothingEnabled = !1;
2038
+ for (let { bitmap: e, index: t } of c) {
2039
+ l.context.clearRect(0, 0, i, a), l.context.drawImage(e, 0, 0);
2040
+ let n = l.context.getImageData(0, 0, i, a), r = i * a * 4 * t;
2041
+ s.set(n.data, r), e.close();
2042
+ }
2043
+ this.canvasPool.releaseCanvasWithContext(l);
2044
+ }
2045
+ return this.createDataArrayTextureFromBuffer(s, i, a, o);
2046
+ }
2047
+ async processOnMainThreadStreaming(e, t = null) {
2048
+ let n = e.filter((e) => e?.image);
2049
+ if (n.length === 0) return this.createFallbackTexture();
2050
+ let { maxWidth: r, maxHeight: i } = t ?? this.calculateOptimalDimensions(n), a = n.length, o = this.bufferPool.getBuffer(r * i * a * 4, Uint8Array), s = this.canvasPool.getCanvasWithContext(r, i);
2051
+ s.context.imageSmoothingEnabled = !0, s.context.imageSmoothingQuality = "high";
2052
+ for (let e = 0; e < n.length; e++) {
2053
+ let t = n[e], a = await createImageBitmap(t.image, {
2054
+ resizeWidth: r,
2055
+ resizeHeight: i,
2056
+ resizeQuality: "high",
2057
+ imageOrientation: t.flipY === !1 ? "none" : "flipY"
2058
+ });
2059
+ s.context.clearRect(0, 0, r, i), s.context.drawImage(a, 0, 0), a.close();
2060
+ let c = s.context.getImageData(0, 0, r, i), l = r * i * 4 * e;
2061
+ o.set(c.data, l), e % J.STREAM_BATCH_SIZE === 0 && await new Promise((e) => setTimeout(e, 0));
2062
+ }
2063
+ return this.canvasPool.releaseCanvasWithContext(s), this.createDataArrayTextureFromBuffer(o, r, i, a);
2064
+ }
2065
+ async processOnMainThreadSync(e, t = null) {
2066
+ let n = e.filter((e) => e?.image);
2067
+ if (n.length === 0) return this.createFallbackTexture();
2068
+ let { maxWidth: r, maxHeight: i } = t ?? this.calculateOptimalDimensions(n), a = n.length, o = this.bufferPool.getBuffer(r * i * a * 4, Uint8Array), s = this.canvasPool.getCanvasWithContext(r, i);
2069
+ s.context.imageSmoothingEnabled = !0, s.context.imageSmoothingQuality = "high";
2070
+ for (let e = 0; e < n.length; e++) {
2071
+ let t = n[e], a = await createImageBitmap(t.image, {
2072
+ resizeWidth: r,
2073
+ resizeHeight: i,
2074
+ resizeQuality: "high",
2075
+ imageOrientation: t.flipY === !1 ? "none" : "flipY"
2076
+ });
2077
+ s.context.clearRect(0, 0, r, i), s.context.drawImage(a, 0, 0), a.close();
2078
+ let c = s.context.getImageData(0, 0, r, i), l = r * i * 4 * e;
2079
+ o.set(c.data, l);
2080
+ }
2081
+ return this.canvasPool.releaseCanvasWithContext(s), this.createDataArrayTextureFromBuffer(o, r, i, a);
2082
+ }
2083
+ createMaterialRawData(e) {
2084
+ let t = f.FLOATS_PER_MATERIAL, n = new Float32Array(e.length * t);
2085
+ for (let r = 0; r < e.length; r++) we(n, r * t, e[r]);
2086
+ return n;
2087
+ }
2088
+ createBVHRawData(e) {
2089
+ let t = [], n = (e) => {
2090
+ let r = t.length;
2091
+ if (t.push(e), e.leftChild) {
2092
+ let t = n(e.leftChild), r = n(e.rightChild);
2093
+ e.leftChild = t, e.rightChild = r;
2094
+ }
2095
+ return r;
2096
+ };
2097
+ n(e);
2098
+ let r = c.VEC4_PER_BVH_NODE * c.FLOATS_PER_VEC4;
2099
+ p(t.length, "BVH node count");
2100
+ let i = t.length * r, a = new Float32Array(i), o = d(a);
2101
+ for (let e = 0; e < t.length; e++) {
2102
+ let n = e * r, i = t[e];
2103
+ if (i.leftChild !== null) {
2104
+ let e = i.leftChild, r = i.rightChild, s = t[e], c = t[r];
2105
+ a[n] = s.boundsMin.x, a[n + 1] = s.boundsMin.y, a[n + 2] = s.boundsMin.z, o[n + 3] = e, a[n + 4] = s.boundsMax.x, a[n + 5] = s.boundsMax.y, a[n + 6] = s.boundsMax.z, o[n + 7] = r, a[n + 8] = c.boundsMin.x, a[n + 9] = c.boundsMin.y, a[n + 10] = c.boundsMin.z, a[n + 12] = c.boundsMax.x, a[n + 13] = c.boundsMax.y, a[n + 14] = c.boundsMax.z;
2106
+ } else o[n] = i.triangleOffset, o[n + 1] = i.triangleCount, o[n + 3] = m.TRIANGLE_LEAF;
2107
+ }
2108
+ return a;
2109
+ }
2110
+ async createMaterialTextures(e) {
2111
+ let { materials: t, maps: n, normalMaps: r, bumpMaps: i, roughnessMaps: a, metalnessMaps: o, emissiveMaps: s, displacementMaps: c } = e;
2112
+ console.log("[TextureCreator] Creating material textures only");
2113
+ let l = performance.now();
2114
+ try {
2115
+ if (!t || t.length === 0) throw Error("No materials provided for texture creation");
2116
+ this.textureCache.dispose(), this.textureCache = new X();
2117
+ let e = [];
2118
+ for (let [t, l] of [
2119
+ ["albedo", n],
2120
+ ["normal", r],
2121
+ ["bump", i],
2122
+ ["roughness", a],
2123
+ ["metalness", o],
2124
+ ["emissive", s],
2125
+ ["displacement", c]
2126
+ ]) !l || l.length === 0 || e.push(this.createTexturesToDataTexture(l).then((e) => ({
2127
+ type: t,
2128
+ texture: e
2129
+ })).catch((e) => (this._reportTextureFailure(t, e), {
2130
+ type: t,
2131
+ texture: null
2132
+ })));
2133
+ let u = await Promise.allSettled(e), d = u.find((e) => e.status === "rejected");
2134
+ if (d) throw d.reason;
2135
+ let f = {};
2136
+ u.forEach((e) => {
2137
+ if (e.status === "fulfilled" && e.value) {
2138
+ let { type: t, texture: n } = e.value;
2139
+ if (n) switch (t) {
2140
+ case "albedo":
2141
+ n.colorSpace = M, f.albedoTexture = n;
2142
+ break;
2143
+ case "normal":
2144
+ f.normalTexture = n;
2145
+ break;
2146
+ case "bump":
2147
+ f.bumpTexture = n;
2148
+ break;
2149
+ case "roughness":
2150
+ f.roughnessTexture = n;
2151
+ break;
2152
+ case "metalness":
2153
+ f.metalnessTexture = n;
2154
+ break;
2155
+ case "emissive":
2156
+ n.colorSpace = M, f.emissiveTexture = n;
2157
+ break;
2158
+ case "displacement":
2159
+ f.displacementTexture = n;
2160
+ break;
2161
+ }
2162
+ }
2163
+ });
2164
+ let p = performance.now() - l;
2165
+ return console.log(`[TextureCreator] Material texture creation complete (${p.toFixed(2)}ms)`), f;
2166
+ } catch (e) {
2167
+ throw console.error("[TextureCreator] Material texture creation error:", e), Error(`Material texture creation failed: ${e.message}`);
2168
+ }
2169
+ }
2170
+ calculateOptimalDimensions(e) {
2171
+ let t = 0, n = 0;
2172
+ for (let r of e) t = Math.max(t, r.image.width), n = Math.max(n, r.image.height);
2173
+ let r = Math.max(t, n);
2174
+ if (r > this.maxTextureSize) {
2175
+ let e = this.maxTextureSize / r;
2176
+ t = Math.round(t * e), n = Math.round(n * e);
2177
+ }
2178
+ return {
2179
+ maxWidth: o(t, this.maxTextureSize),
2180
+ maxHeight: Math.max(1, n)
2181
+ };
2182
+ }
2183
+ createDataArrayTextureFromResult(e) {
2184
+ let t = ArrayBuffer.isView(e.data) ? e.data : new Uint8Array(e.data);
2185
+ return this.createDataArrayTextureFromBuffer(t, e.width, e.height, e.depth);
2186
+ }
2187
+ createDataArrayTextureFromBuffer(e, t, n, r) {
2188
+ let i = new k(e, t, n, r);
2189
+ i.minFilter = A, i.magFilter = A, i.wrapS = me, i.wrapT = me, i.format = j, i.type = ge, i.needsUpdate = !0, i.generateMipmaps = !1, i.userData = {
2190
+ buffer: e,
2191
+ bufferType: Uint8Array
2192
+ }, i.onUpdate = () => {
2193
+ let e = i.userData.buffer;
2194
+ e && (this.bufferPool.forget(e), i.userData.buffer = null, i.image.data = null);
2195
+ };
2196
+ let a = i.dispose.bind(i);
2197
+ return i.dispose = () => {
2198
+ i.userData.buffer && (this.bufferPool.releaseBuffer(i.userData.buffer, i.userData.bufferType), i.userData.buffer = null), a();
2199
+ }, i;
2200
+ }
2201
+ async _normalizeTexturesForProcessing(e) {
2202
+ let t = [], n = [], r = [];
2203
+ for (let n of e) {
2204
+ if (!n?.image) {
2205
+ this._reportTextureLayer(t.length, "no image"), t.push(null);
2206
+ continue;
2207
+ }
2208
+ if (n.isCompressedTexture && n.format === j && n.mipmaps?.[0]?.data) {
2209
+ let e = n.mipmaps[0], i = t.length;
2210
+ t.push(null), r.push({
2211
+ index: i,
2212
+ flipY: n.flipY,
2213
+ promise: vn(e.data, e.width, e.height)
2214
+ });
2215
+ continue;
2216
+ }
2217
+ if (n.isCompressedTexture) {
2218
+ console.warn("[TextureCreator] GPU-compressed texture in mixed group — using placeholder"), t.push(null);
2219
+ continue;
2220
+ }
2221
+ if (n.image.data && !(typeof HTMLImageElement < "u" && n.image instanceof HTMLImageElement) && !(typeof HTMLCanvasElement < "u" && n.image instanceof HTMLCanvasElement) && !(typeof ImageBitmap < "u" && n.image instanceof ImageBitmap)) {
2222
+ let e = t.length;
2223
+ t.push(null);
2224
+ let i = yn(n);
2225
+ r.push({
2226
+ index: e,
2227
+ flipY: n.flipY,
2228
+ promise: i ? vn(i, n.image.width, n.image.height) : Promise.reject(/* @__PURE__ */ Error("pixels in a layout the texture arrays cannot take"))
2229
+ });
2230
+ continue;
2231
+ }
2232
+ t.push(n);
2233
+ }
2234
+ if (r.length > 0) {
2235
+ let e = await Promise.allSettled(r.map((e) => e.promise));
2236
+ for (let i = 0; i < r.length; i++) {
2237
+ let { index: a, flipY: o } = r[i], s = e[i];
2238
+ if (s.status === "fulfilled") {
2239
+ let e = s.value;
2240
+ n.push(e), t[a] = {
2241
+ image: e,
2242
+ flipY: o
2243
+ };
2244
+ } else this._reportTextureLayer(a, s.reason);
2245
+ }
2246
+ }
2247
+ for (let e = 0; e < t.length; e++) if (t[e] === null) {
2248
+ let r = new Uint8ClampedArray([
2249
+ 255,
2250
+ 255,
2251
+ 255,
2252
+ 255
2253
+ ]), i = await createImageBitmap(new ImageData(r, 1, 1));
2254
+ n.push(i), t[e] = {
2255
+ image: i,
2256
+ flipY: !1
2257
+ };
2258
+ }
2259
+ return {
2260
+ normalized: t,
2261
+ bitmapsToClose: n
2262
+ };
2263
+ }
2264
+ createFallbackTexture() {
2265
+ let e = new k(new Uint8Array([
2266
+ 255,
2267
+ 255,
2268
+ 255,
2269
+ 255
2270
+ ]), 1, 1, 1);
2271
+ return e.minFilter = A, e.magFilter = A, e.format = j, e.type = ge, e.needsUpdate = !0, e.generateMipmaps = !1, e;
2272
+ }
2273
+ dispose() {
2274
+ this.canvasPool.dispose(), this.bufferPool.dispose(), this.textureCache.dispose();
2275
+ }
2276
+ };
2277
+ async function vn(e, t, n) {
2278
+ let r = new Uint8ClampedArray(e.buffer, e.byteOffset, e.byteLength);
2279
+ return createImageBitmap(new ImageData(r, t, n));
2280
+ }
2281
+ function yn(e) {
2282
+ let t = e?.image, n = t?.data;
2283
+ if (!n || !(t.width > 0) || !(t.height > 0)) return null;
2284
+ let r = t.width * t.height;
2285
+ if (n instanceof Uint8Array || n instanceof Uint8ClampedArray) return n.byteLength >= r * 4 ? new Uint8Array(n.buffer, n.byteOffset, r * 4) : null;
2286
+ let i = {
2287
+ [j]: 4,
2288
+ [fe]: 2,
2289
+ [pe]: 1
2290
+ }[e.format] ?? Math.round(n.length / r);
2291
+ if (!(i >= 1 && i <= 4) || n.length < r * i) return null;
2292
+ let a = e.type === oe, o = e.type === _e ? 1 / 65535 : 1, s = new Uint8Array(r * 4);
2293
+ for (let e = 0; e < r; e++) for (let t = 0; t < 4; t++) {
2294
+ let r = t < i ? n[e * i + t] : null, c = r === null ? t === 3 ? 1 : s[e * 4] / 255 : a ? ne.fromHalfFloat(r) : r * o;
2295
+ s[e * 4 + t] = Math.max(0, Math.min(255, Math.round(c * 255)));
2296
+ }
2297
+ return s;
2298
+ }
2299
+ var bn = /* @__PURE__ */ new WeakMap(), xn = 128;
2300
+ function Sn(e, t, { resident: n = !0 } = {}) {
2301
+ let r = e?.source, i = r?.data;
2302
+ i?.width > 0 && i?.height > 0 && bn.set(r, {
2303
+ read: t,
2304
+ users: 0,
2305
+ loading: null,
2306
+ stub: n ? null : Object.assign(i, { thumbnail: null })
2307
+ });
2308
+ }
2309
+ function Cn(e) {
2310
+ let t = /* @__PURE__ */ new Map();
2311
+ for (let n of e) {
2312
+ let e = n?.source && bn.get(n.source);
2313
+ e && t.set(n.source, e);
2314
+ }
2315
+ return t;
2316
+ }
2317
+ async function wn(e, t = null) {
2318
+ await Promise.all([...Cn(e)].map(async ([e, n]) => {
2319
+ n.users++, e.data === n.stub && (n.loading ??= n.read().catch((e) => (t?.(e), {
2320
+ data: new Uint8Array([
2321
+ 255,
2322
+ 255,
2323
+ 255,
2324
+ 255
2325
+ ]),
2326
+ width: 1,
2327
+ height: 1
2328
+ })).then((t) => {
2329
+ e.data = t;
2330
+ }).finally(() => {
2331
+ n.loading = null;
2332
+ }), await n.loading);
2333
+ }));
2334
+ }
2335
+ function Tn(e) {
2336
+ for (let [t, n] of Cn(e)) {
2337
+ if (n.users = Math.max(0, n.users - 1), n.users > 0 || t.data === n.stub) continue;
2338
+ let e = t.data, r = n.stub ??= {
2339
+ width: e.width,
2340
+ height: e.height,
2341
+ data: null,
2342
+ thumbnail: null
2343
+ };
2344
+ if (t.data = r, typeof e?.close != "function") continue;
2345
+ if (r.thumbnail || typeof createImageBitmap != "function") {
2346
+ e.close();
2347
+ continue;
2348
+ }
2349
+ let i = Math.min(1, xn / Math.max(e.width, e.height));
2350
+ createImageBitmap(e, {
2351
+ resizeWidth: Math.max(1, Math.round(e.width * i)),
2352
+ resizeHeight: Math.max(1, Math.round(e.height * i)),
2353
+ resizeQuality: "medium"
2354
+ }).then((e) => {
2355
+ r.thumbnail = e;
2356
+ }, () => {}).finally(() => e.close());
2357
+ }
2358
+ }
2359
+ var Z = n("scene"), En = Object.freeze([
2360
+ "maps",
2361
+ "normalMaps",
2362
+ "bumpMaps",
2363
+ "roughnessMaps",
2364
+ "metalnessMaps",
2365
+ "emissiveMaps",
2366
+ "displacementMaps",
2367
+ "anisotropyMaps",
2368
+ "transmissionMaps",
2369
+ "clearcoatMaps",
2370
+ "clearcoatRoughnessMaps",
2371
+ "clearcoatNormalMaps",
2372
+ "sheenColorMaps",
2373
+ "sheenRoughnessMaps",
2374
+ "iridescenceMaps",
2375
+ "iridescenceThicknessMaps",
2376
+ "specularIntensityMaps",
2377
+ "specularColorMaps",
2378
+ "diffuseTransmissionMaps",
2379
+ "diffuseTransmissionColorMaps",
2380
+ "diffuseRoughnessMaps"
2381
+ ]);
2382
+ function Dn(e, t) {
2383
+ return e.config.maxTextureSize = t, e.textureCreator?.setMaxTextureSize(t);
2384
+ }
2385
+ async function On(e) {
2386
+ e._log("Creating material textures (parallel with BVH)");
2387
+ try {
2388
+ let { srgbLists: t, linearLists: n, remap: r } = e._bucketTextures();
2389
+ An(e, r), e.materials?.length && (e.materialData = e.textureCreator.createMaterialRawData(e.materials));
2390
+ let i = (t, n) => t.length === 0 ? Promise.resolve(null) : e.textureCreator.createTexturesToDataTexture(t, { srgbPool: n }).then((e) => (e && n && (e.colorSpace = M), e)), [a, o] = await Promise.all([Promise.all(t.map((e) => i(e, !0))), Promise.all(n.map((e) => i(e, !1)))]);
2391
+ e.srgbBucketTextures = a, e.linearBucketTextures = o, e._log("Material textures complete", {
2392
+ materialData: !!e.materialData,
2393
+ srgbBuckets: a.map((e) => e ? `${e.image.width}x${e.image.height}x${e.image.depth}` : "-").join(","),
2394
+ linearBuckets: o.map((e) => e ? `${e.image.width}x${e.image.height}x${e.image.depth}` : "-").join(",")
2395
+ });
2396
+ } catch (e) {
2397
+ throw Z.error("texture creation failed:", e), e;
2398
+ }
2399
+ }
2400
+ function kn(e) {
2401
+ let t = e.config.maxTextureSize, n = c.MATERIAL_BUCKET_COUNT, a = c.BUCKET_LAYER_STRIDE, o = (e) => {
2402
+ let t = /* @__PURE__ */ new Set(), n = [];
2403
+ for (let r of e) for (let e of r || []) {
2404
+ if (!e?.image) continue;
2405
+ let r = e.source?.uuid ?? e.uuid;
2406
+ t.has(r) || (t.add(r), n.push({
2407
+ width: e.image.width,
2408
+ height: e.image.height
2409
+ }));
2410
+ }
2411
+ return n;
2412
+ }, l = [
2413
+ e.maps,
2414
+ e.emissiveMaps,
2415
+ e.sheenColorMaps,
2416
+ e.specularColorMaps,
2417
+ e.diffuseTransmissionColorMaps
2418
+ ], u = [
2419
+ e.normalMaps,
2420
+ e.bumpMaps,
2421
+ e.roughnessMaps,
2422
+ e.metalnessMaps,
2423
+ e.displacementMaps,
2424
+ e.anisotropyMaps,
2425
+ e.transmissionMaps,
2426
+ e.clearcoatMaps,
2427
+ e.clearcoatRoughnessMaps,
2428
+ e.clearcoatNormalMaps,
2429
+ e.sheenRoughnessMaps,
2430
+ e.iridescenceMaps,
2431
+ e.iridescenceThicknessMaps,
2432
+ e.specularIntensityMaps,
2433
+ e.diffuseTransmissionMaps,
2434
+ e.diffuseRoughnessMaps
2435
+ ], d = r(o(l), t, n), f = r(o(u), t, n);
2436
+ e._srgbBucketShapes = d, e._linearBucketShapes = f;
2437
+ let p = Array.from({ length: n }, () => []), m = Array.from({ length: n }, () => []), h = Array.from({ length: n }, () => /* @__PURE__ */ new Map()), g = Array.from({ length: n }, () => /* @__PURE__ */ new Map());
2438
+ e._srgbTexPacked = /* @__PURE__ */ new Map(), e._linearTexPacked = /* @__PURE__ */ new Map();
2439
+ let v = !1, y = !1, b = (t, n, r, o, c) => {
2440
+ if (!t) return -1;
2441
+ if (!t.image) return y || e.config.issues?.record(_.TEXTURE_BUILD_FAILED, "a material map had not finished decoding when the scene was packed; it renders untextured", { texture: t.name || t.source?.uuid || t.uuid }), y = !0, -1;
2442
+ let l = s(t.image.width, t.image.height, c), u = t.source?.uuid ?? t.uuid, d = r[l].get(u);
2443
+ if (d !== void 0) return i(l, d);
2444
+ if (n[l].length >= a) return Z.warn(`texture bucket ${l} full (${a}); dropping a map`), v || e.config.issues?.record(_.TEXTURE_LIMIT_EXCEEDED, `texture bucket ${l} full (${a} layers); the rest render untextured`, {
2445
+ bucket: l,
2446
+ limit: a
2447
+ }), v = !0, -1;
2448
+ n[l].push(t);
2449
+ let f = n[l].length - 1;
2450
+ r[l].set(u, f);
2451
+ let p = i(l, f);
2452
+ return o.set(u, p), p;
2453
+ }, x = (e, t, n, r, i) => (e || []).map((e) => b(e, t, n, r, i));
2454
+ return {
2455
+ srgbLists: p,
2456
+ linearLists: m,
2457
+ remap: {
2458
+ albedo: x(e.maps, p, h, e._srgbTexPacked, d),
2459
+ emissive: x(e.emissiveMaps, p, h, e._srgbTexPacked, d),
2460
+ normal: x(e.normalMaps, m, g, e._linearTexPacked, f),
2461
+ bump: x(e.bumpMaps, m, g, e._linearTexPacked, f),
2462
+ roughness: x(e.roughnessMaps, m, g, e._linearTexPacked, f),
2463
+ metalness: x(e.metalnessMaps, m, g, e._linearTexPacked, f),
2464
+ displacement: x(e.displacementMaps, m, g, e._linearTexPacked, f),
2465
+ anisotropy: x(e.anisotropyMaps, m, g, e._linearTexPacked, f),
2466
+ transmission: x(e.transmissionMaps, m, g, e._linearTexPacked, f),
2467
+ clearcoat: x(e.clearcoatMaps, m, g, e._linearTexPacked, f),
2468
+ clearcoatRoughness: x(e.clearcoatRoughnessMaps, m, g, e._linearTexPacked, f),
2469
+ clearcoatNormal: x(e.clearcoatNormalMaps, m, g, e._linearTexPacked, f),
2470
+ sheenColor: x(e.sheenColorMaps, p, h, e._srgbTexPacked, d),
2471
+ sheenRoughness: x(e.sheenRoughnessMaps, m, g, e._linearTexPacked, f),
2472
+ iridescence: x(e.iridescenceMaps, m, g, e._linearTexPacked, f),
2473
+ iridescenceThickness: x(e.iridescenceThicknessMaps, m, g, e._linearTexPacked, f),
2474
+ specularIntensity: x(e.specularIntensityMaps, m, g, e._linearTexPacked, f),
2475
+ specularColor: x(e.specularColorMaps, p, h, e._srgbTexPacked, d),
2476
+ diffuseTransmission: x(e.diffuseTransmissionMaps, m, g, e._linearTexPacked, f),
2477
+ diffuseTransmissionColor: x(e.diffuseTransmissionColorMaps, p, h, e._srgbTexPacked, d),
2478
+ diffuseRoughness: x(e.diffuseRoughnessMaps, m, g, e._linearTexPacked, f)
2479
+ }
2480
+ };
2481
+ }
2482
+ function An(e, t) {
2483
+ let n = (e, t) => e >= 0 && e < t.length ? t[e] : -1;
2484
+ for (let r of e.materials) r.map = n(r.map, t.albedo), r.emissiveMap = n(r.emissiveMap, t.emissive), r.normalMap = n(r.normalMap, t.normal), r.bumpMap = n(r.bumpMap, t.bump), r.roughnessMap = n(r.roughnessMap, t.roughness), r.metalnessMap = n(r.metalnessMap, t.metalness), r.displacementMap = n(r.displacementMap, t.displacement), r.anisotropyMap = n(r.anisotropyMap, t.anisotropy), r.transmissionMap = n(r.transmissionMap, t.transmission), r.clearcoatMap = n(r.clearcoatMap, t.clearcoat), r.clearcoatRoughnessMap = n(r.clearcoatRoughnessMap, t.clearcoatRoughness), r.clearcoatNormalMap = n(r.clearcoatNormalMap, t.clearcoatNormal), r.sheenColorMap = n(r.sheenColorMap, t.sheenColor), r.sheenRoughnessMap = n(r.sheenRoughnessMap, t.sheenRoughness), r.iridescenceMap = n(r.iridescenceMap, t.iridescence), r.iridescenceThicknessMap = n(r.iridescenceThicknessMap, t.iridescenceThickness), r.specularIntensityMap = n(r.specularIntensityMap, t.specularIntensity), r.specularColorMap = n(r.specularColorMap, t.specularColor), r.diffuseTransmissionMap = n(r.diffuseTransmissionMap, t.diffuseTransmission), r.diffuseTransmissionColorMap = n(r.diffuseTransmissionColorMap, t.diffuseTransmissionColor), r.diffuseRoughnessMap = n(r.diffuseRoughnessMap, t.diffuseRoughness);
2485
+ }
2486
+ function jn(e) {
2487
+ e._disposeBucketTextures();
2488
+ }
2489
+ function Mn(e) {
2490
+ for (let t of ["srgbBucketTextures", "linearBucketTextures"]) {
2491
+ let n = e[t];
2492
+ if (n) {
2493
+ for (let e of n) if (e && typeof e.dispose == "function") try {
2494
+ e.dispose();
2495
+ } catch (e) {
2496
+ Z.warn(`error disposing ${t}:`, e);
2497
+ }
2498
+ e[t] = null;
2499
+ }
2500
+ }
2501
+ }
2502
+ async function Nn(e, t) {
2503
+ if (e.isProcessing) throw Error("Already processing. Cannot rebuild materials during processing.");
2504
+ e._log("Rebuilding materials and textures");
2505
+ let n = performance.now();
2506
+ try {
2507
+ e.isProcessing = !0;
2508
+ let r = e.geometryExtractor.extractMaterialsOnly(t);
2509
+ e.srgbBucketTextures = e.linearBucketTextures = null, e.textureCreator.textureCache = new X(), e.materials = r.materials, e.meshes = r.meshes, e._adoptTextureLists(r), await e._createMaterialTextures();
2510
+ let i = performance.now() - n;
2511
+ return e._log(`Material rebuild complete (${i.toFixed(2)}ms)`, {
2512
+ materials: e.materials.length,
2513
+ textures: e.maps.length
2514
+ }), e;
2515
+ } catch (e) {
2516
+ throw Z.error("material rebuild failed:", e), e;
2517
+ } finally {
2518
+ e.isProcessing = !1;
2519
+ }
2520
+ }
2521
+ function Pn(e, t) {
2522
+ for (let n of En) e[n] = t[n] ?? [];
2523
+ }
2524
+ //#endregion
2525
+ //#region src/Version.js
2526
+ var Fn = "11.17.0", In = 256 * 1024, Ln = [
2527
+ [/\.jpe?g(\?|#|$)/i, "image/jpeg"],
2528
+ [/\.webp(\?|#|$)/i, "image/webp"],
2529
+ [/\.avif(\?|#|$)/i, "image/avif"]
2530
+ ];
2531
+ function Q(e) {
2532
+ return e.mimeType ? e.mimeType : e.uri?.startsWith("data:") ? e.uri.slice(5, e.uri.indexOf(";")) : Ln.find(([t]) => t.test(e.uri ?? ""))?.[1] ?? "image/png";
2533
+ }
2534
+ function Rn(e) {
2535
+ for (let t = 8; t + 12 <= e.length;) {
2536
+ let n = (e[t] << 24 | e[t + 1] << 16 | e[t + 2] << 8 | e[t + 3]) >>> 0, r = t + 12 + n;
2537
+ if (e[t + 4] === 73 && e[t + 5] === 69 && e[t + 6] === 78 && e[t + 7] === 68) return e.subarray(0, r);
2538
+ t = r;
2539
+ }
2540
+ return e;
2541
+ }
2542
+ function zn(e) {
2543
+ let t = (t) => (e[t] << 24 | e[t + 1] << 16 | e[t + 2] << 8 | e[t + 3]) >>> 0, n = (t) => e[t] << 8 | e[t + 1], r = (t, n) => String.fromCharCode(e[t], e[t + 1], e[t + 2], e[t + 3]) === n;
2544
+ if (e.length >= 24 && t(0) === 2303741511 && r(12, "IHDR")) {
2545
+ for (let n = 8; n + 8 <= e.length; n += 12 + t(n)) {
2546
+ if (r(n + 4, "eXIf")) return null;
2547
+ if (r(n + 4, "IDAT")) return {
2548
+ width: t(16),
2549
+ height: t(20)
2550
+ };
2551
+ }
2552
+ return null;
2553
+ }
2554
+ if (e.length < 4 || n(0) !== 65496) return null;
2555
+ for (let t = 2; t + 4 <= e.length;) {
2556
+ if (e[t] !== 255) return null;
2557
+ let i = e[t + 1];
2558
+ if (i === 255) {
2559
+ t++;
2560
+ continue;
2561
+ }
2562
+ if (i === 1 || i >= 208 && i <= 215) {
2563
+ t += 2;
2564
+ continue;
2565
+ }
2566
+ if (i === 225 && t + 10 <= e.length && r(t + 4, "Exif")) return null;
2567
+ if (i >= 192 && i <= 207 && i !== 196 && i !== 200 && i !== 204) return t + 9 <= e.length ? {
2568
+ width: n(t + 7),
2569
+ height: n(t + 5)
2570
+ } : null;
2571
+ if (i === 218 || i === 217) return null;
2572
+ t += 2 + n(t + 2);
2573
+ }
2574
+ return null;
2575
+ }
2576
+ function Bn({ data: e, width: t, height: n }, { shared: r = !1 } = {}) {
2577
+ let i = new Uint8Array(e.buffer, e.byteOffset, t * n * 4), a = i;
2578
+ return r && typeof SharedArrayBuffer < "u" && !(i.buffer instanceof SharedArrayBuffer) && (a = new Uint8Array(new SharedArrayBuffer(i.byteLength)), a.set(i)), {
2579
+ data: a,
2580
+ width: t,
2581
+ height: n
2582
+ };
2583
+ }
2584
+ function $(e, { width: t = e.width, height: n = e.height } = {}) {
2585
+ let r = new te(e?.data ?? null, t, n, j, ge);
2586
+ return r.needsUpdate = !0, r;
2587
+ }
2588
+ function Vn(e, t) {
2589
+ return nt().decodeImage(t === "image/png" ? Rn(e) : e, t);
2590
+ }
2591
+ async function Hn(e) {
2592
+ let t = await fetch(e);
2593
+ if (!t.ok) throw Error(`HTTP ${t.status}`);
2594
+ return new Uint8Array(await t.arrayBuffer());
2595
+ }
2596
+ function Un(e, t) {
2597
+ return e.options.manager.resolveURL(ce.resolveURL(t.uri, e.options.path));
2598
+ }
2599
+ function Wn(e, t) {
2600
+ return t.bufferView === void 0 ? Hn(Un(e, t)) : e.getDependency("bufferView", t.bufferView).then((e) => new Uint8Array(e));
2601
+ }
2602
+ function Gn(e, t, n) {
2603
+ if (t.bufferView !== void 0) return e.getDependency("bufferView", t.bufferView).then((e) => new Blob([e], { type: t.mimeType }));
2604
+ let { manager: r } = e.options, i = Un(e, t);
2605
+ return r.itemStart(i), fetch(i, {
2606
+ credentials: n.crossOrigin === "anonymous" ? "same-origin" : "include",
2607
+ headers: n.requestHeader,
2608
+ signal: r.abortController?.signal
2609
+ }).then((e) => {
2610
+ if (!e.ok) throw Error(`HTTP ${e.status}`);
2611
+ return e.blob();
2612
+ }).catch((e) => {
2613
+ throw r.itemError(i), e;
2614
+ }).finally(() => r.itemEnd(i));
2615
+ }
2616
+ var Kn = (e, t) => !!t && t !== e.textureLoader && typeof t.parse == "function";
2617
+ function qn(e, t, n) {
2618
+ if (e.sourceCache[t] !== void 0) return e.sourceCache[t].then((e) => e.clone());
2619
+ let r = Wn(e, e.json.images[t]).then((e) => new Promise((t, r) => {
2620
+ n.parse(e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), t, r);
2621
+ }));
2622
+ return e.sourceCache[t] = r, r;
2623
+ }
2624
+ async function Jn(e, t = Q({ uri: e })) {
2625
+ let n = $(Bn(await Vn(await Hn(e), t)));
2626
+ return n.flipY = !0, n;
2627
+ }
2628
+ async function Yn(e, t) {
2629
+ let n = $(Bn(await Vn(e, Q({ uri: t })), { shared: !0 }));
2630
+ return n.flipY = !0, n;
2631
+ }
2632
+ function Xn(e, t) {
2633
+ let n = $(null, {
2634
+ width: e,
2635
+ height: t
2636
+ });
2637
+ return n.flipY = !0, n;
2638
+ }
2639
+ async function Zn(e, t, n, r) {
2640
+ let i = zn(e.subarray(0, In)), a;
2641
+ try {
2642
+ a = await t(i);
2643
+ } catch (e) {
2644
+ throw r?.(n.uri ?? `bufferView ${n.bufferView}`, e), e;
2645
+ }
2646
+ return Sn(a, () => t(null).then((e) => e.image), { resident: !i }), n.extras && typeof n.extras == "object" && Object.assign(a.userData, n.extras), a.userData.mimeType = Q(n), a;
2647
+ }
2648
+ function Qn(e, t = null) {
2649
+ let n = e.loadImageSource;
2650
+ return e.loadImageSource = function(e, r) {
2651
+ let i = this.json.images[e];
2652
+ if (this.sourceCache[e] !== void 0 || i.bufferView === void 0 && i.uri === void 0 || !r?.isImageBitmapLoader) return n.call(this, e, r);
2653
+ let a = Gn(this, i, r).then(async (e) => Zn(new Uint8Array(await e.slice(0, In).arrayBuffer()), async (t) => {
2654
+ let n = new he(t ? {
2655
+ ...t,
2656
+ data: null
2657
+ } : await createImageBitmap(e, {
2658
+ ...r.options,
2659
+ colorSpaceConversion: "none"
2660
+ }));
2661
+ return n.needsUpdate = !0, n;
2662
+ }, i, t));
2663
+ return this.sourceCache[e] = a, a;
2664
+ }, { name: "RAYZEE_browser_images" };
2665
+ }
2666
+ function $n(e, t = null) {
2667
+ return e.loadImageSource = function(e, n) {
2668
+ if (Kn(this, n)) return qn(this, e, n);
2669
+ let r = this.json.images[e], i = /* @__PURE__ */ Error("no image decoder in this runtime: configurePlatform( nodePlatform( { decodeImage } ) ) — see \"Running in Node\"");
2670
+ return t?.(r.uri ?? `bufferView ${r.bufferView}`, i), Promise.reject(i);
2671
+ }, { name: "RAYZEE_missing_image_decoder" };
2672
+ }
2673
+ function er(e, t = null) {
2674
+ return e.loadImageSource = function(e, n) {
2675
+ if (Kn(this, n)) return qn(this, e, n);
2676
+ if (this.sourceCache[e] !== void 0) return this.sourceCache[e].then((e) => e.clone());
2677
+ let r = this.json.images[e], i = Q(r), a = r.uri ?? `bufferView ${r.bufferView}`, o = Wn(this, r).then((e) => {
2678
+ let n = new Blob([e]);
2679
+ return Zn(e, async (e) => $(e ? null : Bn(await Vn(new Uint8Array(await n.arrayBuffer()), i), { shared: !0 }), e ?? {}), r, t);
2680
+ }, (e) => {
2681
+ throw t?.(a, e), e;
2682
+ });
2683
+ return this.sourceCache[e] = o, o;
2684
+ }, { name: "RAYZEE_platform_images" };
2685
+ }
2686
+ //#endregion
2687
+ //#region src/loaders/SceneMetadata.js
2688
+ var tr = [
2689
+ "sourceFile",
2690
+ "url",
2691
+ "file"
2692
+ ];
2693
+ function nr(e) {
2694
+ if (typeof e == "string") try {
2695
+ let t = JSON.parse(e);
2696
+ return t && typeof t == "object" ? t : null;
2697
+ } catch {
2698
+ return null;
2699
+ }
2700
+ return e && typeof e == "object" ? e : null;
2701
+ }
2702
+ function rr(e) {
2703
+ let t = typeof e == "string" ? parseFloat(e) : e;
2704
+ return Number.isFinite(t) ? t : void 0;
2705
+ }
2706
+ function ir(e) {
2707
+ let t = nr(e);
2708
+ if (!t) return null;
2709
+ let n = (e) => e && (e.environment !== void 0 || e.render !== void 0), r = nr(t.rayzee);
2710
+ return n(r) ? r : n(t) ? t : null;
2711
+ }
2712
+ function ar(e) {
2713
+ let t = nr(e);
2714
+ if (!t) return null;
2715
+ let n = tr.map((e) => t[e]).find((e) => typeof e == "string" && e.trim());
2716
+ if (!n) return null;
2717
+ let r = rr(t.rotation), i = rr(t.intensity), a = { sourceFile: n.trim() };
2718
+ return r !== void 0 && (a.rotation = r), i !== void 0 && (a.intensity = Math.max(0, i)), a;
2719
+ }
2720
+ var or = [
2721
+ "maxBounces",
2722
+ "samples",
2723
+ "width",
2724
+ "height"
2725
+ ];
2726
+ function sr(e) {
2727
+ let t = nr(e);
2728
+ if (!t) return null;
2729
+ let n = {};
2730
+ for (let e of or) {
2731
+ let r = rr(t[e]);
2732
+ r !== void 0 && r > 0 && (n[e] = Math.round(r));
2733
+ }
2734
+ return Object.keys(n).length ? n : null;
2735
+ }
2736
+ function cr(e) {
2737
+ let t = ir(e);
2738
+ if (!t) return null;
2739
+ let n = ar(t.environment), r = sr(t.render);
2740
+ return !n && !r ? null : {
2741
+ ...n ? { environment: n } : {},
2742
+ ...r ? { render: r } : {}
2743
+ };
2744
+ }
2745
+ function lr(e) {
2746
+ if (!e) return null;
2747
+ let t = [
2748
+ e.userData,
2749
+ e.asset?.extras,
2750
+ e.scene?.userData
2751
+ ];
2752
+ Array.isArray(e.scenes) && t.push(...e.scenes.map((e) => e?.userData));
2753
+ for (let e of t) {
2754
+ let t = cr(e);
2755
+ if (t) return t;
2756
+ }
2757
+ return null;
2758
+ }
2759
+ //#endregion
2760
+ //#region src/loaders/ArchiveFormats.js
2761
+ var ur = Object.freeze({
2762
+ zip: {
2763
+ type: "archive",
2764
+ name: "ZIP Archive"
2765
+ },
2766
+ gz: {
2767
+ type: "archive",
2768
+ name: "Gzipped TAR Archive"
2769
+ },
2770
+ tgz: {
2771
+ type: "archive",
2772
+ name: "Gzipped TAR Archive"
2773
+ },
2774
+ tar: {
2775
+ type: "archive",
2776
+ name: "TAR Archive"
2777
+ }
2778
+ }), dr = (e) => typeof Blob < "u" && e instanceof Blob, fr = (e) => !!e && typeof e == "object" && !dr(e) && e.files != null, pr = (e) => e.startsWith(".") || e === "__MACOSX";
2779
+ function mr({ name: e = null, files: t }, { isModel: n = () => !1 } = {}) {
2780
+ let r = /* @__PURE__ */ new Map();
2781
+ for (let e of t) {
2782
+ let t = dr(e) ? e : e.file, n = dr(e) ? e.webkitRelativePath || e.name : e.path, i = String(n ?? "").replace(/\\/g, "/").split("/").filter((e) => e && e !== ".").join("/");
2783
+ !i || !t || i.split("/").some(pr) || r.set(i, {
2784
+ path: i,
2785
+ file: t
2786
+ });
2787
+ }
2788
+ let i = [...r.values()].sort((e, t) => e.path < t.path ? -1 : +(e.path > t.path)), a = i[0]?.path.split("/")[0], o = i.length > 0 && i.every((e) => e.path.startsWith(a + "/")) ? a : null;
2789
+ return {
2790
+ name: e ?? o ?? (i.find((e) => n(e.path)) ?? i[0])?.path.split("/").pop() ?? "Folder",
2791
+ files: i,
2792
+ flat: o === null && i.every((e) => !e.path.includes("/"))
2793
+ };
2794
+ }
2795
+ //#endregion
2796
+ export { et as $, Et as A, Ft as B, Tn as C, nn as D, Jt as E, kt as F, tt as G, gt as H, Ot as I, rt as J, W as K, Dt as L, wt as M, jt as N, tn as O, Tt as P, st as Q, At as R, Nn as S, Dn as T, _t as U, Pt as V, dt as W, at as X, it as Y, lt as Z, kn as _, cr as a, We as at, jn as b, zn as c, je as ct, Yn as d, Te as dt, V as et, Xn as f, De as ft, Pn as g, _n as h, we as ht, lr as i, $e as it, It as j, en as k, Jn as l, Oe as lt, Fn as m, Ce as mt, fr as n, Ge as nt, In as o, Qe as ot, er as p, Se as pt, nt as q, mr as r, Ke as rt, Qn as s, Ie as st, ur as t, Re as tt, $n as u, I as ut, On as v, Sn as w, wn as x, Mn as y, Nt as z };