rayzee 11.3.0 → 11.4.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 (35) hide show
  1. package/README.md +33 -5
  2. package/dist/{ArchiveImporter-D735xX-4.js → ArchiveImporter-Cgyx5AF7.js} +2 -2
  3. package/dist/{BidirectionalIntegrator-M89c0AlP.js → BidirectionalIntegrator-BKF-cwH2.js} +2 -2
  4. package/dist/{NeuralRetouch-DiBH63kz.js → NeuralRetouch-C3Q2XqbF.js} +4 -3
  5. package/dist/{NeuralSuperRes-CZNQP13W.js → NeuralSuperRes-DV5TtURP.js} +11 -5
  6. package/dist/{PathTracer-BXCCVrPK.js → PathTracer-D3MvEaZK.js} +19 -12
  7. package/dist/{PhysicalSky-DqmaS0lb.js → PhysicalSky-CY4jiz6a.js} +1 -1
  8. package/dist/{RayzeeRenderer-DUSMFhmc.js → RayzeeRenderer-D23m6NqG.js} +313 -281
  9. package/dist/{ToneMapGPU-BOjpul7A.js → ToneMapGPU-CTDBvmmS.js} +31 -22
  10. package/dist/addons/archives.es.js +1 -1
  11. package/dist/addons/bidirectional.es.js +1 -1
  12. package/dist/addons/physical-sky.es.js +1 -1
  13. package/dist/rayzee-core.es.js +3 -3
  14. package/dist/rayzee.es.js +1343 -858
  15. package/dist/rayzee.umd.js +124 -113
  16. package/dist/{sceneCachePolicy-BAib5fCp.js → sceneCachePolicy-AKOEu2lf.js} +1 -1
  17. package/package.json +1 -1
  18. package/src/EngineDefaults.js +2 -2
  19. package/src/Passes/AIUpscaler.js +2 -0
  20. package/src/PathTracerApp.js +122 -16
  21. package/src/Pipeline/CompletionTracker.js +7 -3
  22. package/src/Processor/ToneMapCPU.js +16 -4
  23. package/src/Processor/ToneMapGPU.js +30 -14
  24. package/src/RayzeeRenderer.js +54 -7
  25. package/src/RenderSettings.js +4 -2
  26. package/src/Stages/AutoExposure.js +484 -494
  27. package/src/Stages/Compositor.js +27 -6
  28. package/src/Stages/LocalExposure.js +546 -0
  29. package/src/Stages/PathTracer.js +6 -4
  30. package/src/Stages/PathTracerStage.js +9 -7
  31. package/src/index.js +1 -0
  32. package/src/managers/DenoisingManager.js +11 -15
  33. package/src/managers/VideoRenderManager.js +30 -4
  34. package/src/neural/NeuralRetouch.js +1 -0
  35. package/src/neural/NeuralSuperRes.js +6 -1
package/dist/rayzee.es.js CHANGED
@@ -1,33 +1,34 @@
1
- import { t as e } from "./BidirectionalIntegrator-M89c0AlP.js";
1
+ import { t as e } from "./BidirectionalIntegrator-BKF-cwH2.js";
2
2
  import { $t as t, Ft as n, Pt as r, Yt as i, en as a, jt as o, nn as s, rt as c, wt as l } from "./SolarLimb-bZE6y63S.js";
3
- import { _ as u, a as d, c as f, d as p, f as m, g as h, h as g, i as _, l as v, m as y, n as b, o as x, p as S, r as ee, s as C, t as te, u as w } from "./RayzeeRenderer-DUSMFhmc.js";
4
- import { $ as ne, B as re, Et as T, H as ie, K as ae, L as oe, N as se, Ot as E, P as D, Q as ce, R as O, Tt as k, X as le, Z as ue, _t as de, dt as A, et as fe, ft as pe, gt as me, ht as he, kt as ge, lt as _e, nt as ve, pt as ye, tt as be, ut as xe, wt as Se, z as Ce } from "./PathTracer-BXCCVrPK.js";
3
+ import { _ as u, a as d, c as f, d as p, f as m, g as h, h as g, i as _, l as v, m as y, n as b, o as x, p as S, r as ee, s as C, t as w, u as T } from "./RayzeeRenderer-D23m6NqG.js";
4
+ import { $ as E, B as te, Et as D, H as ne, K as re, L as ie, N as ae, Ot as O, P as k, Q as oe, R as se, Tt as A, X as ce, Z as le, _t as ue, dt as de, et as fe, ft as pe, gt as me, ht as he, kt as ge, lt as _e, nt as ve, pt as ye, tt as be, ut as xe, wt as Se, z as Ce } from "./PathTracer-D3MvEaZK.js";
5
5
  import { n as we, t as j } from "./EngineEvents-Ci8dVWCP.js";
6
- import { D as Te, G as Ee, J as De, K as Oe, O as ke, W as Ae, Y as je, a as Me, c as Ne, et as Pe, i as Fe, m as Ie, ot as Le, p as Re, q as ze, r as Be, tt as Ve, x as He, y as Ue } from "./sceneCachePolicy-BAib5fCp.js";
6
+ import { D as Te, G as Ee, J as De, K as Oe, O as ke, W as Ae, Y as je, a as Me, c as Ne, et as Pe, i as Fe, m as Ie, ot as Le, p as Re, q as ze, r as Be, tt as Ve, x as He, y as Ue } from "./sceneCachePolicy-AKOEu2lf.js";
7
7
  import { i as We, n as Ge, r as Ke, t as qe } from "./Logger-dDDGj9Av.js";
8
8
  import { f as Je, r as Ye } from "./BufferLayout-xPRH9jYD.js";
9
9
  import { i as Xe, n as Ze, r as Qe, t as $e } from "./EngineIssues-CIZnXHsF.js";
10
10
  import { i as et, r as tt } from "./shared-BGBcSxBQ.js";
11
- import { i as nt, r as rt, t as it } from "./ActiveColor-YvuQq44O.js";
12
- import { n as at, t as ot } from "./AssetConfig-DSEntE65.js";
13
- import { a as st, d as ct, g as lt, i as ut, l as dt, o as ft, p as pt, r as mt, s as ht, t as gt, u as _t } from "./ViewTransforms-CYN7bq2w.js";
14
- import { a as vt, i as yt, n as bt, r as xt } from "./identity-C1cLD1C0.js";
15
- import { a as St, n as Ct, r as wt, t as Tt } from "./SceneMetadata-D2Sh-0e-.js";
16
- import { t as Et } from "./ToneMapGPU-BOjpul7A.js";
17
- import { t as Dt } from "./FileFormats-sPGJeCRc.js";
18
- import { A as Ot, C as kt, D as At, E as jt, O as Mt, S as Nt, T as Pt, _ as Ft, a as It, b as Lt, c as Rt, d as zt, f as Bt, g as Vt, h as Ht, i as Ut, k as Wt, l as Gt, m as Kt, n as qt, o as Jt, p as Yt, r as Xt, s as Zt, t as Qt, u as $t, v as en, w as tn, x as nn, y as rn } from "./ColorManagement-oeEk7oSu.js";
19
- import { c as an, l as on, n as sn, o as cn, t as ln } from "./openStorage-Fe9BoS1_.js";
20
- import { n as un, t as dn } from "./ZipReader-gDSWr0I5.js";
21
- import { i as fn, n as pn, r as mn } from "./NeuralSuperRes-CZNQP13W.js";
22
- import { i as hn, n as gn, r as _n } from "./NeuralRetouch-DiBH63kz.js";
23
- import { ExternalTexture as vn, MeshBasicNodeMaterial as yn, QuadMesh as bn, ReadbackBuffer as xn, RenderTarget as Sn, StorageTexture as M, TextureNode as N, WebGPURenderer as Cn } from "three/webgpu";
24
- import { Fn as wn, If as P, Loop as Tn, Return as En, abs as Dn, atan as On, atomicAdd as kn, atomicLoad as An, atomicStore as jn, attributeArray as Mn, dot as Nn, exp as Pn, exp2 as Fn, float as F, floor as In, fract as Ln, int as I, ivec2 as L, localId as R, max as z, min as Rn, mix as B, normalize as zn, pow as Bn, round as Vn, saturate as V, select as H, smoothstep as Hn, sqrt as Un, storage as Wn, textureLoad as U, textureStore as W, uint as G, uniform as K, uvec2 as Gn, uvec4 as Kn, vec2 as qn, vec3 as q, vec4 as J, wgslFn as Jn, workgroupArray as Yn, workgroupBarrier as Xn, workgroupId as Y } from "three/tsl";
25
- import { ACESFilmicToneMapping as Zn, AddEquation as Qn, AnimationMixer as $n, Box2 as er, Box3 as tr, ClampToEdgeWrapping as nr, Color as rr, Controls as ir, CustomBlending as ar, DataArrayTexture as or, DataTexture as sr, EventDispatcher as cr, FloatType as lr, HalfFloatType as ur, InterpolateSmooth as dr, LinearFilter as X, LoopOnce as fr, LoopRepeat as pr, MathUtils as mr, Matrix4 as hr, Mesh as gr, MeshBasicMaterial as _r, NearestFilter as Z, NoColorSpace as vr, NumberKeyframeTrack as yr, OneFactor as br, OrthographicCamera as xr, PerspectiveCamera as Sr, PropertyBinding as Cr, Quaternion as wr, RGBAFormat as Q, Raycaster as Tr, RedIntegerFormat as Er, SRGBColorSpace as Dr, Scene as Or, SphereGeometry as kr, Timer as Ar, UnsignedByteType as jr, UnsignedIntType as Mr, Vector2 as Nr, Vector3 as $, Vector4 as Pr, VectorKeyframeTrack as Fr } from "three";
26
- import { OrbitControls as Ir } from "three/addons/controls/OrbitControls.js";
27
- import { outline as Lr } from "three/addons/tsl/display/OutlineNode.js";
28
- import { TransformControls as Rr } from "three/addons/controls/TransformControls.js";
11
+ import { r as nt } from "./WorkingMatrix-C6y233hT.js";
12
+ import { i as rt, r as it, t as at } from "./ActiveColor-YvuQq44O.js";
13
+ import { n as ot, t as st } from "./AssetConfig-DSEntE65.js";
14
+ import { a as ct, d as lt, g as ut, i as dt, l as ft, o as pt, p as mt, r as ht, s as gt, t as _t, u as vt } from "./ViewTransforms-CYN7bq2w.js";
15
+ import { a as yt, i as bt, n as xt, r as St } from "./identity-C1cLD1C0.js";
16
+ import { a as Ct, n as wt, r as Tt, t as Et } from "./SceneMetadata-D2Sh-0e-.js";
17
+ import { t as Dt } from "./ToneMapGPU-CTDBvmmS.js";
18
+ import { t as Ot } from "./FileFormats-sPGJeCRc.js";
19
+ import { A as kt, C as At, D as jt, E as Mt, O as Nt, S as Pt, T as Ft, _ as It, a as Lt, b as Rt, c as zt, d as Bt, f as Vt, g as Ht, h as Ut, i as Wt, k as Gt, l as Kt, m as qt, n as Jt, o as Yt, p as Xt, r as Zt, s as Qt, t as $t, u as en, v as tn, w as nn, x as rn, y as an } from "./ColorManagement-oeEk7oSu.js";
20
+ import { c as on, l as sn, n as cn, o as ln, t as un } from "./openStorage-Fe9BoS1_.js";
21
+ import { n as dn, t as fn } from "./ZipReader-gDSWr0I5.js";
22
+ import { i as pn, n as mn, r as hn } from "./NeuralSuperRes-DV5TtURP.js";
23
+ import { i as gn, n as _n, r as vn } from "./NeuralRetouch-C3Q2XqbF.js";
24
+ import { ExternalTexture as yn, MeshBasicNodeMaterial as bn, QuadMesh as xn, ReadbackBuffer as Sn, RenderTarget as Cn, StorageTexture as wn, TextureNode as M, WebGPURenderer as Tn } from "three/webgpu";
25
+ import { Fn as En, If as N, Loop as Dn, Return as On, abs as kn, atan as An, atomicAdd as jn, atomicLoad as Mn, atomicStore as Nn, attributeArray as Pn, dot as Fn, exp as In, exp2 as Ln, float as P, floatBitsToUint as Rn, floor as zn, fract as Bn, int as F, ivec2 as I, localId as L, log2 as Vn, max as R, min as Hn, mix as z, normalize as Un, pow as Wn, round as Gn, saturate as B, select as V, smoothstep as Kn, sqrt as qn, storage as Jn, textureLoad as H, textureStore as U, toneMappingExposure as Yn, uint as W, uniform as G, uvec2 as Xn, uvec4 as Zn, vec2 as K, vec3 as q, vec4 as J, wgslFn as Qn, workgroupArray as $n, workgroupBarrier as er, workgroupId as Y } from "three/tsl";
26
+ import { ACESFilmicToneMapping as tr, AddEquation as nr, AnimationMixer as rr, Box2 as ir, Box3 as ar, ClampToEdgeWrapping as or, Color as sr, Controls as cr, CustomBlending as lr, DataArrayTexture as ur, DataTexture as dr, EventDispatcher as fr, FloatType as pr, HalfFloatType as mr, InterpolateSmooth as hr, LinearFilter as X, LoopOnce as gr, LoopRepeat as _r, MathUtils as vr, Matrix3 as yr, Matrix4 as br, Mesh as xr, MeshBasicMaterial as Sr, NearestFilter as Z, NoColorSpace as Cr, NumberKeyframeTrack as wr, OneFactor as Tr, OrthographicCamera as Er, PerspectiveCamera as Dr, PropertyBinding as Or, Quaternion as kr, RGBAFormat as Q, Raycaster as Ar, RedIntegerFormat as jr, SRGBColorSpace as Mr, Scene as Nr, SphereGeometry as Pr, Timer as Fr, UnsignedByteType as Ir, UnsignedIntType as Lr, Vector2 as Rr, Vector3 as $, Vector4 as zr, VectorKeyframeTrack as Br } from "three";
27
+ import { OrbitControls as Vr } from "three/addons/controls/OrbitControls.js";
28
+ import { outline as Hr } from "three/addons/tsl/display/OutlineNode.js";
29
+ import { TransformControls as Ur } from "three/addons/controls/TransformControls.js";
29
30
  //#region src/Stages/DenoiserSettings.js
30
- var zr = 65504, Br = 6e4, Vr = .01, Hr = {
31
+ var Wr = 65504, Gr = 6e4, Kr = .01, qr = {
31
32
  low: {
32
33
  temporalAlpha: .1,
33
34
  gradientStrength: .8,
@@ -67,7 +68,7 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
67
68
  maxAccumFrames: 128,
68
69
  varianceBoost: 1.5
69
70
  }
70
- }, Ur = 3, Wr = .1, Gr = {
71
+ }, Jr = 3, Yr = .1, Xr = {
71
72
  maxAccumulatedFrameNum: 30,
72
73
  maxFastAccumulatedFrameNum: 6,
73
74
  maxStabilizedFrameNum: 63,
@@ -91,7 +92,7 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
91
92
  convergenceP: .8,
92
93
  lobeVolumePercent: .1,
93
94
  handoverFrames: 0
94
- }, Kr = [
95
+ }, Zr = [
95
96
  "maxAccumulatedFrameNum",
96
97
  "maxFastAccumulatedFrameNum",
97
98
  "maxStabilizedFrameNum",
@@ -99,7 +100,7 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
99
100
  "prepassBlurRadius",
100
101
  "maxBlurRadius",
101
102
  "enableAntiFirefly"
102
- ], qr = {
103
+ ], Qr = {
103
104
  low: {
104
105
  maxAccumulatedFrameNum: 16,
105
106
  maxFastAccumulatedFrameNum: 4,
@@ -117,7 +118,7 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
117
118
  prepassBlurRadius: 40,
118
119
  maxBlurRadius: 40
119
120
  }
120
- }, Jr = Hr.medium, Yr = {
121
+ }, $r = qr.medium, ei = {
121
122
  denoiserStrategy: "none",
122
123
  filterStrength: 1,
123
124
  edgeAtrousIterations: 5,
@@ -135,45 +136,45 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
135
136
  upscalerHdr: !0,
136
137
  enableASVGF: !1,
137
138
  asvgfQualityPreset: "medium",
138
- asvgfTemporalAlpha: Jr.temporalAlpha,
139
- asvgfAtrousIterations: Jr.atrousIterations,
140
- asvgfPhiColor: Jr.phiColor,
141
- asvgfPhiNormal: Jr.phiNormal,
142
- asvgfPhiDepth: Jr.phiDepth,
143
- asvgfPhiLuminance: Jr.phiLuminance,
144
- asvgfVarianceBoost: Jr.varianceBoost,
145
- asvgfMaxAccumFrames: Jr.maxAccumFrames,
146
- asvgfGradientStrength: Jr.gradientStrength,
147
- asvgfGradientSigmaScale: Jr.gradientSigmaScale,
148
- asvgfGradientNoiseFloor: Jr.gradientNoiseFloor,
139
+ asvgfTemporalAlpha: $r.temporalAlpha,
140
+ asvgfAtrousIterations: $r.atrousIterations,
141
+ asvgfPhiColor: $r.phiColor,
142
+ asvgfPhiNormal: $r.phiNormal,
143
+ asvgfPhiDepth: $r.phiDepth,
144
+ asvgfPhiLuminance: $r.phiLuminance,
145
+ asvgfVarianceBoost: $r.varianceBoost,
146
+ asvgfMaxAccumFrames: $r.maxAccumFrames,
147
+ asvgfGradientStrength: $r.gradientStrength,
148
+ asvgfGradientSigmaScale: $r.gradientSigmaScale,
149
+ asvgfGradientNoiseFloor: $r.gradientNoiseFloor,
149
150
  asvgfDebugMode: 0,
150
151
  showAsvgfHeatmap: !1,
151
152
  nrdQualityPreset: "medium",
152
153
  nrdDebugMode: 0
153
- }, Xr = class extends E {
154
+ }, ti = class extends O {
154
155
  constructor(e, t = {}) {
155
156
  super("NormalDepth", {
156
157
  ...t,
157
158
  executionMode: ge.ALWAYS
158
- }), this.renderer = e, this.pathTracer = t.pathTracer, this._dirty = !0, this.cameraWorldMatrix = K(new hr(), "mat4"), this.cameraProjectionMatrixInverse = K(new hr(), "mat4"), this.cameraRay = ce(), this.resolutionWidth = K(t.width || 1), this.resolutionHeight = K(t.height || 1);
159
+ }), this.renderer = e, this.pathTracer = t.pathTracer, this._dirty = !0, this.cameraWorldMatrix = G(new br(), "mat4"), this.cameraProjectionMatrixInverse = G(new br(), "mat4"), this.cameraRay = oe(), this.resolutionWidth = G(t.width || 1), this.resolutionHeight = G(t.height || 1);
159
160
  let n = t.width || 1, r = t.height || 1;
160
- this._outputStorageTex = new M(k, k), this._outputStorageTex.type = ur, this._outputStorageTex.format = Q, this._outputStorageTex.minFilter = Z, this._outputStorageTex.magFilter = Z, this._shadingStorageTex = new M(k, k), this._shadingStorageTex.type = ur, this._shadingStorageTex.format = Q, this._shadingStorageTex.minFilter = Z, this._shadingStorageTex.magFilter = Z, this._shadingRT = new Sn(n, r, {
161
- type: ur,
161
+ this._outputStorageTex = new wn(A, A), this._outputStorageTex.type = mr, this._outputStorageTex.format = Q, this._outputStorageTex.minFilter = Z, this._outputStorageTex.magFilter = Z, this._shadingStorageTex = new wn(A, A), this._shadingStorageTex.type = mr, this._shadingStorageTex.format = Q, this._shadingStorageTex.minFilter = Z, this._shadingStorageTex.magFilter = Z, this._shadingRT = new Cn(n, r, {
162
+ type: mr,
162
163
  format: Q,
163
164
  minFilter: Z,
164
165
  magFilter: Z,
165
166
  depthBuffer: !1,
166
167
  stencilBuffer: !1
167
- }), this._leafStorageTex = null, this._leafRT = null, this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0));
168
+ }), this._leafStorageTex = null, this._leafRT = null, this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0));
168
169
  let i = {
169
- type: ur,
170
+ type: mr,
170
171
  format: Q,
171
172
  minFilter: Z,
172
173
  magFilter: Z,
173
174
  depthBuffer: !1,
174
175
  stencilBuffer: !1
175
176
  };
176
- this._rtA = new Sn(n, r, i), this._rtB = new Sn(n, r, i), this._currentIdx = 0, this._hasHistory = !1, this._dispatchX = Math.ceil(n / 8), this._dispatchY = Math.ceil(r / 8), this._triStorageNode = null, this._bvhStorageNode = null, this._matStorageNode = null, this._lastTriAttr = null, this._lastBvhAttr = null, this._lastMatAttr = null, this._computeNode = null, this._computeBuilt = !1, this._linearBuckets = null;
177
+ this._rtA = new Cn(n, r, i), this._rtB = new Cn(n, r, i), this._currentIdx = 0, this._hasHistory = !1, this._dispatchX = Math.ceil(n / 8), this._dispatchY = Math.ceil(r / 8), this._triStorageNode = null, this._bvhStorageNode = null, this._matStorageNode = null, this._lastTriAttr = null, this._lastBvhAttr = null, this._lastMatAttr = null, this._computeNode = null, this._computeBuilt = !1, this._linearBuckets = null;
177
178
  }
178
179
  setupEventListeners() {
179
180
  this.on("camera:moved", () => {
@@ -190,35 +191,35 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
190
191
  let t = e.sceneStorageNodes?.();
191
192
  t && (this._triStorageNode = t.triangles, this._bvhStorageNode = t.bvh);
192
193
  }
193
- return t && !this._matStorageNode && (this._matStorageNode = Wn(t, "vec4", t.count).toReadOnly()), this._linearBuckets && re(this._linearBuckets, e.materialData?.linearBuckets), this._lastTriAttr = e.triangleGeoAttr || this._lastTriAttr, this._lastBvhAttr = e.bvhStorageAttr || this._lastBvhAttr, this._lastMatAttr = t || this._lastMatAttr, !!(this._triStorageNode && this._bvhStorageNode && this._matStorageNode);
194
+ return t && !this._matStorageNode && (this._matStorageNode = Jn(t, "vec4", t.count).toReadOnly()), this._linearBuckets && te(this._linearBuckets, e.materialData?.linearBuckets), this._lastTriAttr = e.triangleGeoAttr || this._lastTriAttr, this._lastBvhAttr = e.bvhStorageAttr || this._lastBvhAttr, this._lastMatAttr = t || this._lastMatAttr, !!(this._triStorageNode && this._bvhStorageNode && this._matStorageNode);
194
195
  }
195
196
  _buildCompute() {
196
197
  let e = this._triStorageNode, n = this._bvhStorageNode, r = this._matStorageNode;
197
- this._linearBuckets = se(this.pathTracer?.materialData?.linearBuckets);
198
+ this._linearBuckets = ae(this.pathTracer?.materialData?.linearBuckets);
198
199
  let o = {
199
- srgbBuckets: se(null),
200
+ srgbBuckets: ae(null),
200
201
  linearBuckets: this._linearBuckets,
201
202
  shadowAlbedoMaps: null,
202
203
  goboMaps: null,
203
204
  iesProfiles: null,
204
205
  alphaShadows: null
205
206
  }, c = this.cameraWorldMatrix, u = this.cameraProjectionMatrixInverse, d = this.resolutionWidth, f = this.resolutionHeight, p = this._outputStorageTex, m = this._shadingStorageTex, h = this._leafStorageTex;
206
- this._computeNode = he(wn(([o, c]) => {
207
- let u = I(Y.x).mul(8).add(I(R.x)), g = I(Y.y).mul(8).add(I(R.y));
208
- P(u.lessThan(I(d)).and(g.lessThan(I(f))), () => {
209
- let _ = t(le(qn(F(u).add(.5).div(d), F(g).add(.5).div(f)), o, c, this.cameraRay)), v = i.wrap(ae(_, n, e)), y = v.normal.mul(.5).add(.5), b = Rn(v.dst, F(65504)), x = v.didHit.select(J(y, b), J(0, 0, 0, F(zr)));
210
- W(p, Gn(G(u), G(g)), x).toWriteOnly(), h && W(h, Gn(G(u), G(g)), Kn(G(v.instanceLeaf.add(1)), 0, 0, 0)).toWriteOnly();
211
- let S = v.normal.toVar(), ee = F(1).toVar();
212
- P(v.didHit, () => {
213
- let t = a.wrap(l(v.materialIndex, r)).toVar(), i = s.wrap(D(v.uv, t)).toVar(), o = J(0).toVar();
214
- P(t.normalMapIndex.greaterThanEqual(I(0)), () => {
215
- o.assign(ie(e, v.triangleIndex, v.normal, t.normalTransform, n, v.instanceLeaf));
207
+ this._computeNode = he(En(([o, c]) => {
208
+ let u = F(Y.x).mul(8).add(F(L.x)), g = F(Y.y).mul(8).add(F(L.y));
209
+ N(u.lessThan(F(d)).and(g.lessThan(F(f))), () => {
210
+ let _ = t(ce(K(P(u).add(.5).div(d), P(g).add(.5).div(f)), o, c, this.cameraRay)), v = i.wrap(re(_, n, e)), y = v.normal.mul(.5).add(.5), b = Hn(v.dst, P(65504)), x = v.didHit.select(J(y, b), J(0, 0, 0, P(Wr)));
211
+ U(p, Xn(W(u), W(g)), x).toWriteOnly(), h && U(h, Xn(W(u), W(g)), Zn(W(v.instanceLeaf.add(1)), 0, 0, 0)).toWriteOnly();
212
+ let S = v.normal.toVar(), ee = P(1).toVar();
213
+ N(v.didHit, () => {
214
+ let t = a.wrap(l(v.materialIndex, r)).toVar(), i = s.wrap(k(v.uv, t)).toVar(), o = J(0).toVar();
215
+ N(t.normalMapIndex.greaterThanEqual(F(0)), () => {
216
+ o.assign(ne(e, v.triangleIndex, v.normal, t.normalTransform, n, v.instanceLeaf));
216
217
  });
217
218
  let c = Ce(v.normal, t, i, o).toVar();
218
- S.assign(oe(c, t, i)), ee.assign(O(t, i).y.clamp(.05, 1));
219
+ S.assign(ie(c, t, i)), ee.assign(se(t, i).y.clamp(.05, 1));
219
220
  });
220
221
  let C = v.didHit.select(J(S.mul(.5).add(.5), ee), J(0, 0, 0, 1));
221
- W(m, Gn(G(u), G(g)), C).toWriteOnly();
222
+ U(m, Xn(W(u), W(g)), C).toWriteOnly();
222
223
  });
223
224
  })(c, u), o).compute([
224
225
  this._dispatchX,
@@ -264,15 +265,15 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
264
265
  reallocateReservedStorage() {
265
266
  this._computeNode?.dispose(), this._computeNode = null, this._outputStorageTex?.dispose(), this._shadingStorageTex?.dispose();
266
267
  let e = () => {
267
- let e = new M(k, k);
268
- return e.type = ur, e.format = Q, e.minFilter = Z, e.magFilter = Z, e;
268
+ let e = new wn(A, A);
269
+ return e.type = mr, e.format = Q, e.minFilter = Z, e.magFilter = Z, e;
269
270
  };
270
271
  this._outputStorageTex = e(), this._shadingStorageTex = e(), this._leafStorageTex &&= (this._leafStorageTex.dispose(), this._makeLeafStorage()), this._computeBuilt = !1;
271
272
  }
272
273
  setInstanceLeafOutput(e) {
273
- e = !!e, e !== !!this._leafStorageTex && (this._computeNode?.dispose(), this._computeNode = null, this._computeBuilt = !1, this._dirty = !0, e ? (this._leafStorageTex = this._makeLeafStorage(), this._leafRT = new Sn(this._rtA.width, this._rtA.height, {
274
- type: Mr,
275
- format: Er,
274
+ e = !!e, e !== !!this._leafStorageTex && (this._computeNode?.dispose(), this._computeNode = null, this._computeBuilt = !1, this._dirty = !0, e ? (this._leafStorageTex = this._makeLeafStorage(), this._leafRT = new Cn(this._rtA.width, this._rtA.height, {
275
+ type: Lr,
276
+ format: jr,
276
277
  minFilter: Z,
277
278
  magFilter: Z,
278
279
  depthBuffer: !1,
@@ -283,40 +284,40 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
283
284
  this._leafRT ? e.setTexture("pathtracer:instanceLeaf", this._leafRT.texture) : e.getTexture("pathtracer:instanceLeaf") && e.removeTexture("pathtracer:instanceLeaf");
284
285
  }
285
286
  _makeLeafStorage() {
286
- let e = new M(k, k);
287
- return e.type = Mr, e.format = Er, e.minFilter = Z, e.magFilter = Z, e;
287
+ let e = new wn(A, A);
288
+ return e.type = Lr, e.format = jr, e.minFilter = Z, e.magFilter = Z, e;
288
289
  }
289
290
  dispose() {
290
291
  this._computeNode?.dispose(), this._outputStorageTex?.dispose(), this._shadingStorageTex?.dispose(), this._shadingRT?.dispose(), this._leafStorageTex?.dispose(), this._leafRT?.dispose(), this._rtA?.dispose(), this._rtB?.dispose();
291
292
  }
292
- }, Zr = class extends E {
293
+ }, ni = class extends O {
293
294
  constructor(e, t, n = {}) {
294
295
  super("MotionVector", {
295
296
  ...n,
296
297
  executionMode: ge.ALWAYS
297
298
  }), this.renderer = e, this.camera = t, this.pathTracer = n.pathTracer || null;
298
299
  let r = n.width || 1, i = n.height || 1;
299
- this.prevViewProjectionMatrix = new hr(), this.currentViewProjectionMatrix = new hr(), this.matricesInitialized = !1, this.isFirstFrame = !0, this.frameCount = 0, this.cameraWorldMatrix = K(new hr(), "mat4"), this.cameraProjectionMatrixInverse = K(new hr(), "mat4"), this.cameraRay = ce(), this.prevVP = K(new hr(), "mat4"), this.isFirstFrameU = K(1), this.deltaTime = K(1 / 60), this.velocityScale = K(1), this.resolutionWidth = K(r), this.resolutionHeight = K(i), this._normalDepthTexNode = new N(), this._screenSpaceStorageTex = new M(k, k), this._screenSpaceStorageTex.type = ur, this._screenSpaceStorageTex.format = Q, this._screenSpaceStorageTex.minFilter = Z, this._screenSpaceStorageTex.magFilter = Z, this._worldSpaceStorageTex = new M(k, k), this._worldSpaceStorageTex.type = ur, this._worldSpaceStorageTex.format = Q, this._worldSpaceStorageTex.minFilter = Z, this._worldSpaceStorageTex.magFilter = Z, this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0));
300
+ this.prevViewProjectionMatrix = new br(), this.currentViewProjectionMatrix = new br(), this.matricesInitialized = !1, this.isFirstFrame = !0, this.frameCount = 0, this.cameraWorldMatrix = G(new br(), "mat4"), this.cameraProjectionMatrixInverse = G(new br(), "mat4"), this.cameraRay = oe(), this.prevVP = G(new br(), "mat4"), this.isFirstFrameU = G(1), this.deltaTime = G(1 / 60), this.velocityScale = G(1), this.resolutionWidth = G(r), this.resolutionHeight = G(i), this._normalDepthTexNode = new M(), this._screenSpaceStorageTex = new wn(A, A), this._screenSpaceStorageTex.type = mr, this._screenSpaceStorageTex.format = Q, this._screenSpaceStorageTex.minFilter = Z, this._screenSpaceStorageTex.magFilter = Z, this._worldSpaceStorageTex = new wn(A, A), this._worldSpaceStorageTex.type = mr, this._worldSpaceStorageTex.format = Q, this._worldSpaceStorageTex.minFilter = Z, this._worldSpaceStorageTex.magFilter = Z, this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0));
300
301
  let a = {
301
- type: ur,
302
+ type: mr,
302
303
  format: Q,
303
304
  minFilter: Z,
304
305
  magFilter: Z,
305
306
  depthBuffer: !1,
306
307
  stencilBuffer: !1
307
308
  };
308
- this.screenSpaceTarget = new Sn(r, i, a), this.worldSpaceTarget = new Sn(r, i, a), this._dispatchX = Math.ceil(r / 16), this._dispatchY = Math.ceil(i / 16), this._buildScreenSpaceCompute(), this._buildWorldSpaceCompute();
309
+ this.screenSpaceTarget = new Cn(r, i, a), this.worldSpaceTarget = new Cn(r, i, a), this._dispatchX = Math.ceil(r / 16), this._dispatchY = Math.ceil(i / 16), this._buildScreenSpaceCompute(), this._buildWorldSpaceCompute();
309
310
  }
310
311
  _buildScreenSpaceCompute() {
311
312
  let e = this._normalDepthTexNode, t = this.cameraWorldMatrix, n = this.cameraProjectionMatrixInverse, r = this.prevVP, i = this.resolutionWidth, a = this.resolutionHeight, o = this._screenSpaceStorageTex;
312
- this._screenSpaceComputeNode = wn(([t, n]) => {
313
- let s = I(Y.x).mul(16).add(I(R.x)), c = I(Y.y).mul(16).add(I(R.y));
314
- P(s.lessThan(I(i)).and(c.lessThan(I(a))), () => {
315
- let l = U(e, L(s, c)).w, u = qn(F(s).add(.5).div(i), F(c).add(.5).div(a)), d = J(0, 0, l, 1).toVar();
316
- P(l.lessThan(F(6e4)), () => {
317
- let e = ue(u, l, t, n, this.cameraRay), i = r.mul(J(e, 1)), a = i.xy.div(i.w), o = qn(a.x.mul(.5).add(.5), a.y.mul(-.5).add(.5)), s = u.sub(o), c = o.x.greaterThanEqual(0).and(o.x.lessThanEqual(1)).and(o.y.greaterThanEqual(0)).and(o.y.lessThanEqual(1));
318
- d.assign(c.select(J(s, l, 1), J(F(1e3), F(1e3), l, 0)));
319
- }), W(o, Gn(G(s), G(c)), d).toWriteOnly();
313
+ this._screenSpaceComputeNode = En(([t, n]) => {
314
+ let s = F(Y.x).mul(16).add(F(L.x)), c = F(Y.y).mul(16).add(F(L.y));
315
+ N(s.lessThan(F(i)).and(c.lessThan(F(a))), () => {
316
+ let l = H(e, I(s, c)).w, u = K(P(s).add(.5).div(i), P(c).add(.5).div(a)), d = J(0, 0, l, 1).toVar();
317
+ N(l.lessThan(P(6e4)), () => {
318
+ let e = le(u, l, t, n, this.cameraRay), i = r.mul(J(e, 1)), a = i.xy.div(i.w), o = K(a.x.mul(.5).add(.5), a.y.mul(-.5).add(.5)), s = u.sub(o), c = o.x.greaterThanEqual(0).and(o.x.lessThanEqual(1)).and(o.y.greaterThanEqual(0)).and(o.y.lessThanEqual(1));
319
+ d.assign(c.select(J(s, l, 1), J(P(1e3), P(1e3), l, 0)));
320
+ }), U(o, Xn(W(s), W(c)), d).toWriteOnly();
320
321
  });
321
322
  })(t, n).compute([
322
323
  this._dispatchX,
@@ -330,14 +331,14 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
330
331
  }
331
332
  _buildWorldSpaceCompute() {
332
333
  let e = this._normalDepthTexNode, t = this.cameraWorldMatrix, n = this.cameraProjectionMatrixInverse, r = this.prevVP, i = this.isFirstFrameU, a = this.deltaTime, o = this.velocityScale, s = this.resolutionWidth, c = this.resolutionHeight, l = this._worldSpaceStorageTex;
333
- this._worldSpaceComputeNode = wn(([t, n]) => {
334
- let u = I(Y.x).mul(16).add(I(R.x)), d = I(Y.y).mul(16).add(I(R.y));
335
- P(u.lessThan(I(s)).and(d.lessThan(I(c))), () => {
336
- let f = U(e, L(u, d)).w, p = J(0, 0, 0, 0).toVar();
337
- P(i.lessThan(.5).and(f.lessThan(F(6e4))), () => {
338
- let e = qn(F(u).add(.5).div(s), F(d).add(.5).div(c)), i = ue(e, f, t, n, this.cameraRay), l = r.mul(J(i, 1)), m = l.xy.div(l.w), h = qn(m.x.mul(.5).add(.5), m.y.mul(-.5).add(.5)), g = h.x.greaterThanEqual(0).and(h.x.lessThanEqual(1)).and(h.y.greaterThanEqual(0)).and(h.y.lessThanEqual(1)), _ = e.sub(h), v = q(_.x.div(a).mul(o), _.y.div(a).mul(o), 0);
334
+ this._worldSpaceComputeNode = En(([t, n]) => {
335
+ let u = F(Y.x).mul(16).add(F(L.x)), d = F(Y.y).mul(16).add(F(L.y));
336
+ N(u.lessThan(F(s)).and(d.lessThan(F(c))), () => {
337
+ let f = H(e, I(u, d)).w, p = J(0, 0, 0, 0).toVar();
338
+ N(i.lessThan(.5).and(f.lessThan(P(6e4))), () => {
339
+ let e = K(P(u).add(.5).div(s), P(d).add(.5).div(c)), i = le(e, f, t, n, this.cameraRay), l = r.mul(J(i, 1)), m = l.xy.div(l.w), h = K(m.x.mul(.5).add(.5), m.y.mul(-.5).add(.5)), g = h.x.greaterThanEqual(0).and(h.x.lessThanEqual(1)).and(h.y.greaterThanEqual(0)).and(h.y.lessThanEqual(1)), _ = e.sub(h), v = q(_.x.div(a).mul(o), _.y.div(a).mul(o), 0);
339
340
  p.assign(g.select(J(v, 1), J(0, 0, 0, .5)));
340
- }), W(l, Gn(G(u), G(d)), p).toWriteOnly();
341
+ }), U(l, Xn(W(u), W(d)), p).toWriteOnly();
341
342
  });
342
343
  })(t, n).compute([
343
344
  this._dispatchX,
@@ -401,83 +402,83 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
401
402
  reallocateReservedStorage() {
402
403
  this._screenSpaceComputeNode?.dispose(), this._worldSpaceComputeNode?.dispose(), this._screenSpaceStorageTex?.dispose(), this._worldSpaceStorageTex?.dispose();
403
404
  let e = () => {
404
- let e = new M(k, k);
405
- return e.type = ur, e.format = Q, e.minFilter = Z, e.magFilter = Z, e;
405
+ let e = new wn(A, A);
406
+ return e.type = mr, e.format = Q, e.minFilter = Z, e.magFilter = Z, e;
406
407
  };
407
408
  this._screenSpaceStorageTex = e(), this._worldSpaceStorageTex = e(), this._buildScreenSpaceCompute(), this._buildWorldSpaceCompute();
408
409
  }
409
410
  dispose() {
410
411
  this._screenSpaceComputeNode?.dispose(), this._worldSpaceComputeNode?.dispose(), this._screenSpaceStorageTex?.dispose(), this._worldSpaceStorageTex?.dispose(), this.screenSpaceTarget?.dispose(), this.worldSpaceTarget?.dispose(), this._normalDepthTexNode?.dispose();
411
412
  }
412
- }, Qr = (e) => H(e.equal(e), e, F(0)).clamp(0, 1e7), $r = (e) => q(Qr(e.x), Qr(e.y), Qr(e.z)), ei = class extends E {
413
+ }, ri = (e) => V(e.equal(e), e, P(0)).clamp(0, 1e7), ii = (e) => q(ri(e.x), ri(e.y), ri(e.z)), ai = class extends O {
413
414
  constructor(e, t = {}) {
414
415
  super("ASVGF", {
415
416
  ...t,
416
417
  executionMode: ge.PER_CYCLE
417
- }), this.renderer = e, this.temporalAlpha = K(t.temporalAlpha ?? Hr.medium.temporalAlpha), this.gradientStrength = K(t.gradientStrength ?? Hr.medium.gradientStrength), this.gradientSigmaScale = K(t.gradientSigmaScale ?? Hr.medium.gradientSigmaScale), this.gradientNoiseFloor = K(t.gradientNoiseFloor ?? Hr.medium.gradientNoiseFloor), this.maxAccumFrames = K(t.maxAccumFrames ?? Hr.medium.maxAccumFrames), this.resW = K(t.width || 1), this.resH = K(t.height || 1), this.temporalEnabledU = K(1), this.forceResetU = K(0), this._colorTexNode = new N(), this._albedoTexNode = new N(), this._motionTexNode = new N(), this._normalDepthTexNode = new N(), this._prevNormalDepthTexNode = new N(), this._readTemporalTexNode = new N(), this._gradientReadTexNode = new N();
418
+ }), this.renderer = e, this.temporalAlpha = G(t.temporalAlpha ?? qr.medium.temporalAlpha), this.gradientStrength = G(t.gradientStrength ?? qr.medium.gradientStrength), this.gradientSigmaScale = G(t.gradientSigmaScale ?? qr.medium.gradientSigmaScale), this.gradientNoiseFloor = G(t.gradientNoiseFloor ?? qr.medium.gradientNoiseFloor), this.maxAccumFrames = G(t.maxAccumFrames ?? qr.medium.maxAccumFrames), this.resW = G(t.width || 1), this.resH = G(t.height || 1), this.temporalEnabledU = G(1), this.forceResetU = G(0), this._colorTexNode = new M(), this._albedoTexNode = new M(), this._motionTexNode = new M(), this._normalDepthTexNode = new M(), this._prevNormalDepthTexNode = new M(), this._readTemporalTexNode = new M(), this._gradientReadTexNode = new M();
418
419
  let n = t.width || 1, r = t.height || 1;
419
- this._temporalTexA = new M(k, k), this._temporalTexA.type = lr, this._temporalTexA.format = Q, this._temporalTexA.minFilter = X, this._temporalTexA.magFilter = X, this._temporalTexB = new M(k, k), this._temporalTexB.type = lr, this._temporalTexB.format = Q, this._temporalTexB.minFilter = X, this._temporalTexB.magFilter = X, this._outputModulatedTex = new M(k, k), this._outputModulatedTex.type = lr, this._outputModulatedTex.format = Q, this._outputModulatedTex.minFilter = X, this._outputModulatedTex.magFilter = X, this._gradientStorageTex = new M(k, k), this._gradientStorageTex.type = ur, this._gradientStorageTex.format = Q, this._gradientStorageTex.minFilter = X, this._gradientStorageTex.magFilter = X, this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0)), this._demodulatedRT = new Sn(n, r, {
420
- type: lr,
420
+ this._temporalTexA = new wn(A, A), this._temporalTexA.type = pr, this._temporalTexA.format = Q, this._temporalTexA.minFilter = X, this._temporalTexA.magFilter = X, this._temporalTexB = new wn(A, A), this._temporalTexB.type = pr, this._temporalTexB.format = Q, this._temporalTexB.minFilter = X, this._temporalTexB.magFilter = X, this._outputModulatedTex = new wn(A, A), this._outputModulatedTex.type = pr, this._outputModulatedTex.format = Q, this._outputModulatedTex.minFilter = X, this._outputModulatedTex.magFilter = X, this._gradientStorageTex = new wn(A, A), this._gradientStorageTex.type = mr, this._gradientStorageTex.format = Q, this._gradientStorageTex.minFilter = X, this._gradientStorageTex.magFilter = X, this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0)), this._demodulatedRT = new Cn(n, r, {
421
+ type: pr,
421
422
  format: Q,
422
423
  minFilter: X,
423
424
  magFilter: X,
424
425
  depthBuffer: !1,
425
426
  stencilBuffer: !1
426
- }), this._outputRT = new Sn(n, r, {
427
- type: lr,
427
+ }), this._outputRT = new Cn(n, r, {
428
+ type: pr,
428
429
  format: Q,
429
430
  minFilter: X,
430
431
  magFilter: X,
431
432
  depthBuffer: !1,
432
433
  stencilBuffer: !1
433
- }), this._gradientRT = new Sn(n, r, {
434
- type: ur,
434
+ }), this._gradientRT = new Cn(n, r, {
435
+ type: mr,
435
436
  format: Q,
436
437
  minFilter: X,
437
438
  magFilter: X,
438
439
  depthBuffer: !1,
439
440
  stencilBuffer: !1
440
- }), this.currentMoments = 0, this._compiled = !1, this._needsWarmReset = !1, this._dispatchX = Math.ceil(n / 8), this._dispatchY = Math.ceil(r / 8), this._buildGradientCompute(), this._buildTemporalCompute(), this.showHeatmap = !1, this.debugMode = K(0, "int"), this._heatmapStorageTex = new M(k, k), this._heatmapStorageTex.type = lr, this._heatmapStorageTex.format = Q, this._heatmapStorageTex.minFilter = Z, this._heatmapStorageTex.magFilter = Z, this.heatmapTarget = new Sn(n, r, {
441
- type: lr,
441
+ }), this.currentMoments = 0, this._compiled = !1, this._needsWarmReset = !1, this._dispatchX = Math.ceil(n / 8), this._dispatchY = Math.ceil(r / 8), this._buildGradientCompute(), this._buildTemporalCompute(), this.showHeatmap = !1, this.debugMode = G(0, "int"), this._heatmapStorageTex = new wn(A, A), this._heatmapStorageTex.type = pr, this._heatmapStorageTex.format = Q, this._heatmapStorageTex.minFilter = Z, this._heatmapStorageTex.magFilter = Z, this.heatmapTarget = new Cn(n, r, {
442
+ type: pr,
442
443
  format: Q,
443
444
  minFilter: Z,
444
445
  magFilter: Z,
445
446
  depthBuffer: !1,
446
447
  stencilBuffer: !1
447
- }), this._heatmapRawColorTexNode = new N(), this._heatmapColorTexNode = new N(), this._heatmapTemporalTexNode = new N(), this._heatmapNDTexNode = new N(), this._heatmapMotionTexNode = new N(), this._heatmapGradientTexNode = new N(), this._buildHeatmapCompute();
448
+ }), this._heatmapRawColorTexNode = new M(), this._heatmapColorTexNode = new M(), this._heatmapTemporalTexNode = new M(), this._heatmapNDTexNode = new M(), this._heatmapMotionTexNode = new M(), this._heatmapGradientTexNode = new M(), this._buildHeatmapCompute();
448
449
  }
449
450
  _buildGradientCompute() {
450
- let e = this._colorTexNode, t = this._albedoTexNode, n = this._motionTexNode, r = this._readTemporalTexNode, i = this.gradientNoiseFloor, a = this.gradientSigmaScale, s = this._gradientStorageTex, c = this.resW, l = this.resH, u = Yn("float", 144), d = Yn("float", 144);
451
- this._gradientNode = wn(() => {
452
- let f = R.x, p = R.y, m = p.mul(8).add(f), h = I(Y.x).mul(8).sub(2).toVar(), g = I(Y.y).mul(8).sub(2).toVar(), _ = (i) => {
453
- let a = i.mod(G(12)), s = i.div(G(12)), f = h.add(I(a)).clamp(I(0), I(c).sub(1)), p = g.add(I(s)).clamp(I(0), I(l).sub(1)), m = U(e, L(f, p)).xyz, _ = U(t, L(f, p)).xyz, v = o($r(m.div(z(_, q(Vr))))).toVar();
451
+ let e = this._colorTexNode, t = this._albedoTexNode, n = this._motionTexNode, r = this._readTemporalTexNode, i = this.gradientNoiseFloor, a = this.gradientSigmaScale, s = this._gradientStorageTex, c = this.resW, l = this.resH, u = $n("float", 144), d = $n("float", 144);
452
+ this._gradientNode = En(() => {
453
+ let f = L.x, p = L.y, m = p.mul(8).add(f), h = F(Y.x).mul(8).sub(2).toVar(), g = F(Y.y).mul(8).sub(2).toVar(), _ = (i) => {
454
+ let a = i.mod(W(12)), s = i.div(W(12)), f = h.add(F(a)).clamp(F(0), F(c).sub(1)), p = g.add(F(s)).clamp(F(0), F(l).sub(1)), m = H(e, I(f, p)).xyz, _ = H(t, I(f, p)).xyz, v = o(ii(m.div(R(_, q(Kr))))).toVar();
454
455
  u.element(i).assign(v);
455
- let y = U(n, L(f, p)), b = F(f).sub(y.x.mul(c)), x = F(p).sub(y.y.mul(l)), S = I(b.add(.5)).clamp(I(0), I(c).sub(1)), ee = I(x.add(.5)).clamp(I(0), I(l).sub(1)), C = y.w.greaterThan(.5), te = U(r, L(S, ee)).xyz, w = C.select(o(te), v);
456
- d.element(i).assign(w);
456
+ let y = H(n, I(f, p)), b = P(f).sub(y.x.mul(c)), x = P(p).sub(y.y.mul(l)), S = F(b.add(.5)).clamp(F(0), F(c).sub(1)), ee = F(x.add(.5)).clamp(F(0), F(l).sub(1)), C = y.w.greaterThan(.5), w = H(r, I(S, ee)).xyz, T = C.select(o(w), v);
457
+ d.element(i).assign(T);
457
458
  };
458
459
  _(m);
459
- let v = m.add(G(64));
460
- P(v.lessThan(G(144)), () => {
460
+ let v = m.add(W(64));
461
+ N(v.lessThan(W(144)), () => {
461
462
  _(v);
462
463
  });
463
- let y = m.add(G(128));
464
- P(y.lessThan(G(144)), () => {
464
+ let y = m.add(W(128));
465
+ N(y.lessThan(W(144)), () => {
465
466
  _(y);
466
- }), Xn();
467
- let b = I(Y.x).mul(8).add(I(f)), x = I(Y.y).mul(8).add(I(p));
468
- P(b.lessThan(I(c)).and(x.lessThan(I(l))), () => {
469
- let e = F(0).toVar(), t = F(0).toVar();
467
+ }), er();
468
+ let b = F(Y.x).mul(8).add(F(f)), x = F(Y.y).mul(8).add(F(p));
469
+ N(b.lessThan(F(c)).and(x.lessThan(F(l))), () => {
470
+ let e = P(0).toVar(), t = P(0).toVar();
470
471
  for (let n = -2; n <= 2; n++) for (let r = -2; r <= 2; r++) {
471
- let i = p.add(G(2 + n)).mul(G(12)).add(f.add(G(2 + r))), a = u.element(i);
472
+ let i = p.add(W(2 + n)).mul(W(12)).add(f.add(W(2 + r))), a = u.element(i);
472
473
  e.addAssign(a), t.addAssign(a.mul(a));
473
474
  }
474
- let o = e.div(25), m = Un(z(t.div(25).sub(o.mul(o)), F(0))).mul(a).toVar(), h = F(0).toVar();
475
+ let o = e.div(25), m = qn(R(t.div(25).sub(o.mul(o)), P(0))).mul(a).toVar(), h = P(0).toVar();
475
476
  for (let e = -2; e <= 2; e++) for (let t = -2; t <= 2; t++) {
476
- let n = p.add(G(2 + e)).mul(G(12)).add(f.add(G(2 + t))), r = u.element(n), a = d.element(n), o = z(z(Dn(r.sub(a)).sub(m), F(0)).div(z(z(r, a), F(.001))).sub(i), F(0)).div(z(F(1).sub(i), F(1e-4)));
477
+ let n = p.add(W(2 + e)).mul(W(12)).add(f.add(W(2 + t))), r = u.element(n), a = d.element(n), o = R(R(kn(r.sub(a)).sub(m), P(0)).div(R(R(r, a), P(.001))).sub(i), P(0)).div(R(P(1).sub(i), P(1e-4)));
477
478
  h.addAssign(o.mul(o));
478
479
  }
479
- let g = h.div(25).clamp(0, 1).toVar(), _ = U(n, L(b, x)), v = I(F(b).sub(_.x.mul(c)).add(.5)).clamp(I(0), I(c).sub(1)), y = I(F(x).sub(_.y.mul(l)).add(.5)).clamp(I(0), I(l).sub(1)), S = _.w.greaterThan(.5).select(U(r, L(v, y)).w, F(0)).div(4).clamp(0, 1), ee = g.mul(S);
480
- W(s, Gn(G(b), G(x)), J(ee, g, m, 1)).toWriteOnly();
480
+ let g = h.div(25).clamp(0, 1).toVar(), _ = H(n, I(b, x)), v = F(P(b).sub(_.x.mul(c)).add(.5)).clamp(F(0), F(c).sub(1)), y = F(P(x).sub(_.y.mul(l)).add(.5)).clamp(F(0), F(l).sub(1)), S = _.w.greaterThan(.5).select(H(r, I(v, y)).w, P(0)).div(4).clamp(0, 1), ee = g.mul(S);
481
+ U(s, Xn(W(b), W(x)), J(ee, g, m, 1)).toWriteOnly();
481
482
  });
482
483
  })().compute([
483
484
  this._dispatchX,
@@ -494,23 +495,23 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
494
495
  }
495
496
  _buildTemporalForDirection(e) {
496
497
  let t = this._colorTexNode, n = this._albedoTexNode, r = this._motionTexNode, i = this._normalDepthTexNode, a = this._prevNormalDepthTexNode, o = this._readTemporalTexNode, s = this._gradientReadTexNode, c = this._outputModulatedTex, l = this.maxAccumFrames, u = this.temporalAlpha, d = this.gradientStrength, f = this.temporalEnabledU, p = this.forceResetU, m = this.resW, h = this.resH;
497
- return wn(() => {
498
- let g = I(Y.x).mul(8).add(I(R.x)), _ = I(Y.y).mul(8).add(I(R.y));
499
- P(g.lessThan(I(m)).and(_.lessThan(I(h))), () => {
500
- let v = L(g, _), y = U(t, v), b = y.xyz, x = y.w, S = U(n, v).xyz, ee = z(S, q(Vr)), C = $r(b.div(ee)), te = J(C, 1).toVar(), w = J(b, x).toVar();
501
- P(f.greaterThan(.5).and(p.lessThan(.5)), () => {
502
- let e = U(r, v), t = e.w.greaterThan(.5), n = F(g).sub(e.x.mul(m)), c = F(_).sub(e.y.mul(h)), f = n.greaterThanEqual(0).and(n.lessThan(F(m))).and(c.greaterThanEqual(0)).and(c.lessThan(F(h)));
503
- P(t.and(f), () => {
504
- let e = U(i, v), t = e.xyz.mul(2).sub(1), r = e.w, f = I(n), p = I(c), g = f.add(I(1)), _ = p.add(I(1)), y = n.sub(F(f)), b = c.sub(F(p)), S = f.clamp(I(0), I(m).sub(1)), ne = g.clamp(I(0), I(m).sub(1)), re = p.clamp(I(0), I(h).sub(1)), T = _.clamp(I(0), I(h).sub(1)), ie = F(1).sub(y).mul(F(1).sub(b)), ae = y.mul(F(1).sub(b)), oe = F(1).sub(y).mul(b), se = y.mul(b), E = (e, n, i) => {
505
- let o = U(a, L(e, n)), s = o.xyz.mul(2).sub(1), c = o.w, l = Bn(Nn(t, s).clamp(0, 1), F(16)), u = Pn(Dn(r.sub(c)).div(z(r, F(.001))).div(F(.05)).negate());
498
+ return En(() => {
499
+ let g = F(Y.x).mul(8).add(F(L.x)), _ = F(Y.y).mul(8).add(F(L.y));
500
+ N(g.lessThan(F(m)).and(_.lessThan(F(h))), () => {
501
+ let v = I(g, _), y = H(t, v), b = y.xyz, x = y.w, S = H(n, v).xyz, ee = R(S, q(Kr)), C = ii(b.div(ee)), w = J(C, 1).toVar(), T = J(b, x).toVar();
502
+ N(f.greaterThan(.5).and(p.lessThan(.5)), () => {
503
+ let e = H(r, v), t = e.w.greaterThan(.5), n = P(g).sub(e.x.mul(m)), c = P(_).sub(e.y.mul(h)), f = n.greaterThanEqual(0).and(n.lessThan(P(m))).and(c.greaterThanEqual(0)).and(c.lessThan(P(h)));
504
+ N(t.and(f), () => {
505
+ let e = H(i, v), t = e.xyz.mul(2).sub(1), r = e.w, f = F(n), p = F(c), g = f.add(F(1)), _ = p.add(F(1)), y = n.sub(P(f)), b = c.sub(P(p)), S = f.clamp(F(0), F(m).sub(1)), E = g.clamp(F(0), F(m).sub(1)), te = p.clamp(F(0), F(h).sub(1)), D = _.clamp(F(0), F(h).sub(1)), ne = P(1).sub(y).mul(P(1).sub(b)), re = y.mul(P(1).sub(b)), ie = P(1).sub(y).mul(b), ae = y.mul(b), O = (e, n, i) => {
506
+ let o = H(a, I(e, n)), s = o.xyz.mul(2).sub(1), c = o.w, l = Wn(Fn(t, s).clamp(0, 1), P(16)), u = In(kn(r.sub(c)).div(R(r, P(.001))).div(P(.05)).negate());
506
507
  return i.mul(l).mul(u);
507
- }, D = E(S, re, ie), ce = E(ne, re, ae), O = E(S, T, oe), k = E(ne, T, se), le = D.add(ce).add(O).add(k);
508
- P(le.greaterThan(F(.01)), () => {
509
- let e = U(o, L(S, re)), t = U(o, L(ne, re)), n = U(o, L(S, T)), r = U(o, L(ne, T)), i = F(1).div(le), a = e.xyz.mul(D).add(t.xyz.mul(ce)).add(n.xyz.mul(O)).add(r.xyz.mul(k)).mul(i), c = e.w.mul(D).add(t.w.mul(ce)).add(n.w.mul(O)).add(r.w.mul(k)).mul(i), f = U(s, v).x.mul(d).clamp(0, 1), p = $r(B(a, C, B(z(F(1).div(c.add(1)), u), F(1), f))), m = Rn(c.add(1), l);
510
- te.assign(J(p, m)), w.assign(J(p.mul(ee), x));
508
+ }, k = O(S, te, ne), oe = O(E, te, re), se = O(S, D, ie), A = O(E, D, ae), ce = k.add(oe).add(se).add(A);
509
+ N(ce.greaterThan(P(.01)), () => {
510
+ let e = H(o, I(S, te)), t = H(o, I(E, te)), n = H(o, I(S, D)), r = H(o, I(E, D)), i = P(1).div(ce), a = e.xyz.mul(k).add(t.xyz.mul(oe)).add(n.xyz.mul(se)).add(r.xyz.mul(A)).mul(i), c = e.w.mul(k).add(t.w.mul(oe)).add(n.w.mul(se)).add(r.w.mul(A)).mul(i), f = H(s, v).x.mul(d).clamp(0, 1), p = ii(z(a, C, z(R(P(1).div(c.add(1)), u), P(1), f))), m = Hn(c.add(1), l);
511
+ w.assign(J(p, m)), T.assign(J(p.mul(ee), x));
511
512
  });
512
513
  });
513
- }), W(e, Gn(G(g), G(_)), te).toWriteOnly(), W(c, Gn(G(g), G(_)), w).toWriteOnly();
514
+ }), U(e, Xn(W(g), W(_)), w).toWriteOnly(), U(c, Xn(W(g), W(_)), T).toWriteOnly();
514
515
  });
515
516
  })().compute([
516
517
  this._dispatchX,
@@ -524,35 +525,35 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
524
525
  }
525
526
  _buildHeatmapCompute() {
526
527
  let e = this._heatmapRawColorTexNode, t = this._heatmapColorTexNode, n = this._heatmapTemporalTexNode, r = this._heatmapNDTexNode, i = this._heatmapMotionTexNode, a = this._heatmapGradientTexNode, s = this._heatmapStorageTex, c = this.debugMode, l = this.resW, u = this.resH;
527
- this._heatmapComputeNode = wn(() => {
528
- let d = I(Y.x).mul(8).add(I(R.x)), f = I(Y.y).mul(8).add(I(R.y));
529
- P(d.lessThan(I(l)).and(f.lessThan(I(u))), () => {
530
- let p = L(d, f), m = J(0, 0, 0, 1).toVar();
531
- P(c.equal(I(0)), () => {
532
- let e = U(t, p).xyz;
528
+ this._heatmapComputeNode = En(() => {
529
+ let d = F(Y.x).mul(8).add(F(L.x)), f = F(Y.y).mul(8).add(F(L.y));
530
+ N(d.lessThan(F(l)).and(f.lessThan(F(u))), () => {
531
+ let p = I(d, f), m = J(0, 0, 0, 1).toVar();
532
+ N(c.equal(F(0)), () => {
533
+ let e = H(t, p).xyz;
533
534
  m.assign(J(e, 1));
534
- }).ElseIf(c.equal(I(1)), () => {
535
- let t = F(0).toVar(), n = F(0).toVar();
535
+ }).ElseIf(c.equal(F(1)), () => {
536
+ let t = P(0).toVar(), n = P(0).toVar();
536
537
  for (let r = -1; r <= 1; r++) for (let i = -1; i <= 1; i++) {
537
- let a = U(e, L(d.add(i).clamp(I(0), I(l).sub(1)), f.add(r).clamp(I(0), I(u).sub(1)))).xyz, s = o(a);
538
+ let a = H(e, I(d.add(i).clamp(F(0), F(l).sub(1)), f.add(r).clamp(F(0), F(u).sub(1)))).xyz, s = o(a);
538
539
  t.addAssign(s), n.addAssign(s.mul(s));
539
540
  }
540
541
  t.divAssign(9), n.divAssign(9);
541
- let r = z(n.sub(t.mul(t)), F(0)).div(z(t.mul(t), F(1e-4))).mul(10).clamp(0, 1), i = r.sub(.5).mul(4).clamp(0, 1), a = r.mul(4).clamp(0, 1).sub(r.sub(.75).mul(4).clamp(0, 1)), s = F(1).sub(r.sub(.25).mul(4).clamp(0, 1));
542
+ let r = R(n.sub(t.mul(t)), P(0)).div(R(t.mul(t), P(1e-4))).mul(10).clamp(0, 1), i = r.sub(.5).mul(4).clamp(0, 1), a = r.mul(4).clamp(0, 1).sub(r.sub(.75).mul(4).clamp(0, 1)), s = P(1).sub(r.sub(.25).mul(4).clamp(0, 1));
542
543
  m.assign(J(i, a, s, 1));
543
- }).ElseIf(c.equal(I(2)), () => {
544
- let e = U(n, p).w.div(32).clamp(0, 1);
545
- m.assign(J(F(1).sub(e), e, F(.2), 1));
546
- }).ElseIf(c.equal(I(3)), () => {
547
- let e = U(i, p), t = Dn(e.x).mul(100).clamp(0, 1), n = Dn(e.y).mul(100).clamp(0, 1), r = t.add(n).clamp(0, 1);
544
+ }).ElseIf(c.equal(F(2)), () => {
545
+ let e = H(n, p).w.div(32).clamp(0, 1);
546
+ m.assign(J(P(1).sub(e), e, P(.2), 1));
547
+ }).ElseIf(c.equal(F(3)), () => {
548
+ let e = H(i, p), t = kn(e.x).mul(100).clamp(0, 1), n = kn(e.y).mul(100).clamp(0, 1), r = t.add(n).clamp(0, 1);
548
549
  m.assign(J(t, n, r.mul(.3), 1));
549
- }).ElseIf(c.equal(I(4)), () => {
550
- let e = U(r, p);
550
+ }).ElseIf(c.equal(F(4)), () => {
551
+ let e = H(r, p);
551
552
  m.assign(J(e.xyz, 1));
552
553
  }).Else(() => {
553
- let e = U(a, p).x.mul(5).clamp(0, 1);
554
- m.assign(J(e, e.mul(.5), F(1).sub(e), 1));
555
- }), W(s, Gn(G(d), G(f)), m).toWriteOnly();
554
+ let e = H(a, p).x.mul(5).clamp(0, 1);
555
+ m.assign(J(e, e.mul(.5), P(1).sub(e), 1));
556
+ }), U(s, Xn(W(d), W(f)), m).toWriteOnly();
556
557
  });
557
558
  })().compute([
558
559
  this._dispatchX,
@@ -593,10 +594,10 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
593
594
  reallocateReservedStorage() {
594
595
  this._gradientNode?.dispose(), this._temporalNodeA?.dispose(), this._temporalNodeB?.dispose(), this._heatmapComputeNode?.dispose(), this._temporalTexA?.dispose(), this._temporalTexB?.dispose(), this._outputModulatedTex?.dispose(), this._gradientStorageTex?.dispose(), this._heatmapStorageTex?.dispose();
595
596
  let e = (e, t) => {
596
- let n = new M(k, k);
597
+ let n = new wn(A, A);
597
598
  return n.type = e, n.format = Q, n.minFilter = t, n.magFilter = t, n;
598
599
  };
599
- this._temporalTexA = e(lr, X), this._temporalTexB = e(lr, X), this._outputModulatedTex = e(lr, X), this._gradientStorageTex = e(ur, X), this._heatmapStorageTex = e(lr, Z), this._buildGradientCompute(), this._buildTemporalCompute(), this._buildHeatmapCompute(), this._compiled = !1, this.currentMoments = 0, this._needsWarmReset = !0;
600
+ this._temporalTexA = e(pr, X), this._temporalTexB = e(pr, X), this._outputModulatedTex = e(pr, X), this._gradientStorageTex = e(mr, X), this._heatmapStorageTex = e(pr, Z), this._buildGradientCompute(), this._buildTemporalCompute(), this._buildHeatmapCompute(), this._compiled = !1, this.currentMoments = 0, this._needsWarmReset = !0;
600
601
  }
601
602
  setSize(e, t) {
602
603
  this._demodulatedRT.setSize(e, t), this._demodulatedRT.texture.needsUpdate = !0, this._outputRT.setSize(e, t), this._outputRT.texture.needsUpdate = !0, this._gradientRT.setSize(e, t), this._gradientRT.texture.needsUpdate = !0, this.heatmapTarget.setSize(e, t), this.heatmapTarget.texture.needsUpdate = !0, this.resW.value = e, this.resH.value = t, this._dispatchX = Math.ceil(e / 8), this._dispatchY = Math.ceil(t / 8), this._gradientNode.dispatchSize = [
@@ -624,7 +625,7 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
624
625
  dispose() {
625
626
  this._gradientNode?.dispose(), this._temporalNodeA?.dispose(), this._temporalNodeB?.dispose(), this._temporalTexA?.dispose(), this._temporalTexB?.dispose(), this._outputModulatedTex?.dispose(), this._gradientStorageTex?.dispose(), this._demodulatedRT?.dispose(), this._outputRT?.dispose(), this._gradientRT?.dispose(), this._heatmapComputeNode?.dispose(), this._heatmapStorageTex?.dispose(), this.heatmapTarget?.dispose(), this._colorTexNode?.dispose(), this._albedoTexNode?.dispose(), this._motionTexNode?.dispose(), this._normalDepthTexNode?.dispose(), this._prevNormalDepthTexNode?.dispose(), this._readTemporalTexNode?.dispose(), this._gradientReadTexNode?.dispose(), this._heatmapRawColorTexNode?.dispose(), this._heatmapColorTexNode?.dispose(), this._heatmapTemporalTexNode?.dispose(), this._heatmapNDTexNode?.dispose(), this._heatmapMotionTexNode?.dispose(), this._heatmapGradientTexNode?.dispose();
626
627
  }
627
- }, ti = 1e-6, ni = 1.5 / 255, ri = .01, ii = 3, ai = 2, oi = 2, si = 3, ci = 2, li = 38, ui = .1, di = 4, fi = Math.cos(89 * Math.PI / 180), pi = .5, mi = 16, hi = {
628
+ }, oi = 1e-6, si = 1.5 / 255, ci = .01, li = 3, ui = 2, di = 2, fi = 3, pi = 2, mi = 38, hi = .1, gi = 4, _i = Math.cos(89 * Math.PI / 180), vi = .5, yi = 16, bi = {
628
629
  pre: {
629
630
  radiusScale: 1,
630
631
  fractionScale: 2
@@ -637,7 +638,7 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
637
638
  radiusScale: 2,
638
639
  fractionScale: .5
639
640
  }
640
- }, gi = .25 * Math.SQRT2, _i = [
641
+ }, xi = .25 * Math.SQRT2, Si = [
641
642
  [
642
643
  -1,
643
644
  0,
@@ -659,62 +660,62 @@ var zr = 65504, Br = 6e4, Vr = .01, Hr = {
659
660
  1
660
661
  ],
661
662
  [
662
- -gi,
663
- gi,
663
+ -xi,
664
+ xi,
664
665
  .5
665
666
  ],
666
667
  [
667
- gi,
668
- gi,
668
+ xi,
669
+ xi,
669
670
  .5
670
671
  ],
671
672
  [
672
- gi,
673
- -gi,
673
+ xi,
674
+ -xi,
674
675
  .5
675
676
  ],
676
677
  [
677
- -gi,
678
- -gi,
678
+ -xi,
679
+ -xi,
679
680
  .5
680
681
  ]
681
- ], vi = (e, t, n) => Hn(0, 1, F(1).sub(e.mul(t).add(n).abs())), yi = (e, t, n) => {
682
- let r = e.mul(t).add(n).abs().mul(-ii);
683
- return F(1).div(r.mul(r).sub(r).add(1));
684
- }, bi = (e) => B(F(1.570796), F(1.395402), V(e)).mul(Un(V(F(1).sub(e)))), xi = (e, t) => F(1).sub(Fn(e.mul(e).mul(-200))).mul(Bn(V(e), t)), Si = (e, t) => V(e).mul(Un(t.div(F(1).sub(t).add(ti)))), Ci = (e, t, n, r) => {
685
- let i = z(On(Si(n, r.mul(B(V(t), F(1), e)))), F(ni));
686
- return F(1).div(i);
687
- }, wi = (e, t) => {
688
- let n = F(1).div(B(F(ri), F(1), V(e.mul(t))));
689
- return qn(n, e.mul(n).negate());
690
- }, Ti = (e, t, n) => {
691
- let r = F(1).div(B(F(n), F(1), B(e.mul(e), e, V(t))));
692
- return qn(r, e.mul(r).negate());
693
- }, Ei = (e, t) => {
694
- let n = F(1).div(t);
695
- return qn(n, e.mul(n).negate());
696
- }, Di = (e, t, n, r) => {
697
- let i = F(1).div(e.mul(t));
698
- return qn(i, Nn(r, n).mul(i).negate());
699
- }, Oi = (e) => qn(1).sub(qn(1).sub(Ln(e.mul(.5)).mul(2)).abs()).min(.99999), ki = (e) => q(Nn(e, q(.25, .5, .25)), Nn(e, q(.5, 0, -.5)), Nn(e, q(-.25, .5, -.25))), Ai = (e) => {
682
+ ], Ci = (e, t, n) => Kn(0, 1, P(1).sub(e.mul(t).add(n).abs())), wi = (e, t, n) => {
683
+ let r = e.mul(t).add(n).abs().mul(-li);
684
+ return P(1).div(r.mul(r).sub(r).add(1));
685
+ }, Ti = (e) => z(P(1.570796), P(1.395402), B(e)).mul(qn(B(P(1).sub(e)))), Ei = (e, t) => P(1).sub(Ln(e.mul(e).mul(-200))).mul(Wn(B(e), t)), Di = (e, t) => B(e).mul(qn(t.div(P(1).sub(t).add(oi)))), Oi = (e, t, n, r) => {
686
+ let i = R(An(Di(n, r.mul(z(B(t), P(1), e)))), P(si));
687
+ return P(1).div(i);
688
+ }, ki = (e, t) => {
689
+ let n = P(1).div(z(P(ci), P(1), B(e.mul(t))));
690
+ return K(n, e.mul(n).negate());
691
+ }, Ai = (e, t, n) => {
692
+ let r = P(1).div(z(P(n), P(1), z(e.mul(e), e, B(t))));
693
+ return K(r, e.mul(r).negate());
694
+ }, ji = (e, t) => {
695
+ let n = P(1).div(t);
696
+ return K(n, e.mul(n).negate());
697
+ }, Mi = (e, t, n, r) => {
698
+ let i = P(1).div(e.mul(t));
699
+ return K(i, Fn(r, n).mul(i).negate());
700
+ }, Ni = (e) => K(1).sub(K(1).sub(Bn(e.mul(.5)).mul(2)).abs()).min(.99999), Pi = (e) => q(Fn(e, q(.25, .5, .25)), Fn(e, q(.5, 0, -.5)), Fn(e, q(-.25, .5, -.25))), Fi = (e) => {
700
701
  let t = e.x.sub(e.z);
701
- return z(q(t.add(e.y), e.x.add(e.z), t.sub(e.y)), q(0));
702
- }, ji = (e, t) => t.add(ti).div(e.add(ti)), Mi = (e, t) => J(e.xyz.mul(ji(e.x, t)), e.w), Ni = (e) => J(ki(Ai(e.xyz)), V(e.w)), Pi = (e, t) => Un(t.sub(e.mul(e)).abs()), Fi = (e, t) => qn(e.x.mul(t.x).add(e.y.mul(t.y)), e.z.mul(t.x).add(e.w.mul(t.y))), Ii = (e, t) => H(e.equal(0), J(0), t);
703
- function Li(e) {
702
+ return R(q(t.add(e.y), e.x.add(e.z), t.sub(e.y)), q(0));
703
+ }, Ii = (e, t) => t.add(oi).div(e.add(oi)), Li = (e, t) => J(e.xyz.mul(Ii(e.x, t)), e.w), Ri = (e) => J(Pi(Fi(e.xyz)), B(e.w)), zi = (e, t) => qn(t.sub(e.mul(e)).abs()), Bi = (e, t) => K(e.x.mul(t.x).add(e.y.mul(t.y)), e.z.mul(t.x).add(e.w.mul(t.y))), Vi = (e, t) => V(e.equal(0), J(0), t);
704
+ function Hi(e) {
704
705
  let t = Math.imul(e | 0, 2654435761) >>> 0;
705
706
  return t ^= t >>> 15, t = Math.imul(t, 2246822507) >>> 0, t ^= t >>> 13, t = Math.imul(t, 3266489909) >>> 0, t ^= t >>> 16, t / 4294967296;
706
707
  }
707
- var Ri = class extends E {
708
+ var Ui = class extends O {
708
709
  constructor(e, t = {}) {
709
710
  super("NRD", {
710
711
  ...t,
711
712
  executionMode: ge.PER_CYCLE
712
713
  }), this.renderer = e, this.pathTracer = t.pathTracer || null, this.settings = {
713
- ...Gr,
714
+ ...Xr,
714
715
  ...t.settings || {}
715
- }, this._releaseHitDistance = this.pathTracer?.requestOutput?.("hitDistance", { encode: (e, t) => e.div(z(t.mul(.1).add(3), F(1e-4))).clamp(0, 1) }) ?? null;
716
+ }, this._releaseHitDistance = this.pathTracer?.requestOutput?.("hitDistance", { encode: (e, t) => e.div(R(t.mul(.1).add(3), P(1e-4))).clamp(0, 1) }) ?? null;
716
717
  let n = t.width || 1, r = t.height || 1;
717
- this.resW = K(n), this.resH = K(r), this.minRectDimMulUnproject = K(1), this.inputFrames = K(0), this.resetU = K(0), this.debugMode = K(0, "int"), this.rotPre = K(new Pr(1, 0, 0, 1), "vec4"), this.rotBlur = K(new Pr(1, 0, 0, 1), "vec4"), this.rotPost = K(new Pr(1, 0, 0, 1), "vec4"), this.camWorld = K(new hr(), "mat4"), this.camProjInv = K(new hr(), "mat4"), this.camView = K(new hr(), "mat4"), this.prevCamView = K(new hr(), "mat4"), this.camPos = K(new $(), "vec3"), this.prevCamPos = K(new $(), "vec3"), this.viewVector = K(new $(), "vec3"), this.prevViewVector = K(new $(), "vec3"), this.cameraRay = ce(), this.u = {};
718
+ this.resW = G(n), this.resH = G(r), this.minRectDimMulUnproject = G(1), this.inputFrames = G(0), this.resetU = G(0), this.debugMode = G(0, "int"), this.rotPre = G(new zr(1, 0, 0, 1), "vec4"), this.rotBlur = G(new zr(1, 0, 0, 1), "vec4"), this.rotPost = G(new zr(1, 0, 0, 1), "vec4"), this.camWorld = G(new br(), "mat4"), this.camProjInv = G(new br(), "mat4"), this.camView = G(new br(), "mat4"), this.prevCamView = G(new br(), "mat4"), this.camPos = G(new $(), "vec3"), this.prevCamPos = G(new $(), "vec3"), this.viewVector = G(new $(), "vec3"), this.prevViewVector = G(new $(), "vec3"), this.cameraRay = oe(), this.u = {};
718
719
  for (let e of [
719
720
  "maxAccum",
720
721
  "maxFast",
@@ -734,25 +735,25 @@ var Ri = class extends E {
734
735
  "disocclusionThreshold",
735
736
  "lobeVolumePercent",
736
737
  "handoverFrames"
737
- ]) this.u[e] = K(0);
738
- this.u.antilag = K(new Nr(), "vec2"), this.u.convergence = K(new $(), "vec3"), this._syncUniforms(), this._colorTexNode = new N(), this._albedoTexNode = new N(), this._ndTexNode = new N(), this._snTexNode = new N(), this._motionTexNode = new N(), this._placeholders = /* @__PURE__ */ new Map();
738
+ ]) this.u[e] = G(0);
739
+ this.u.antilag = G(new Rr(), "vec2"), this.u.convergence = G(new $(), "vec3"), this._syncUniforms(), this._colorTexNode = new M(), this._albedoTexNode = new M(), this._ndTexNode = new M(), this._snTexNode = new M(), this._motionTexNode = new M(), this._placeholders = /* @__PURE__ */ new Map();
739
740
  let i = () => {
740
- let e = new sr(new Float32Array(4), 1, 1, Q, lr);
741
+ let e = new dr(new Float32Array(4), 1, 1, Q, pr);
741
742
  e.needsUpdate = !0;
742
- let t = new N(e);
743
+ let t = new M(e);
743
744
  return this._placeholders.set(t, e), t;
744
745
  };
745
- this._nTmpA = i(), this._nTmpB = i(), this._nHist = i(), this._nFast = i(), this._nInternal = i(), this._nGeom = i(), this._nData = i(), this._nStabRead = i(), this._allocStorage(), this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0)), this.outputTarget = new Sn(n, r, {
746
- type: ur,
746
+ this._nTmpA = i(), this._nTmpB = i(), this._nHist = i(), this._nFast = i(), this._nInternal = i(), this._nGeom = i(), this._nData = i(), this._nStabRead = i(), this._allocStorage(), this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0)), this.outputTarget = new Cn(n, r, {
747
+ type: mr,
747
748
  format: Q,
748
749
  minFilter: X,
749
750
  magFilter: X,
750
751
  depthBuffer: !1,
751
752
  stencilBuffer: !1
752
- }), this._compiled = !1, this._needsReset = !0, this._stabPing = 0, this._camInitialized = !1, this._dispatchX = Math.ceil(n / mi), this._dispatchY = Math.ceil(r / mi), this._buildKernels();
753
+ }), this._compiled = !1, this._needsReset = !0, this._stabPing = 0, this._camInitialized = !1, this._dispatchX = Math.ceil(n / yi), this._dispatchY = Math.ceil(r / yi), this._buildKernels();
753
754
  }
754
755
  _allocStorage() {
755
- let e = () => T(ur);
756
+ let e = () => D(mr);
756
757
  this._tmpA = e(), this._tmpB = e(), this._hist = e(), this._fastHist = e(), this._internal = e(), this._geomPrev = e(), this._stabA = e(), this._stabB = e(), this._dataT = e();
757
758
  }
758
759
  _disposeStorage() {
@@ -773,7 +774,7 @@ var Ri = class extends E {
773
774
  }
774
775
  updateParameters(e) {
775
776
  if (e) {
776
- for (let t of Object.keys(e)) t === "debugMode" ? this.debugMode.value = e.debugMode | 0 : t in Gr && (this.settings[t] = e[t]);
777
+ for (let t of Object.keys(e)) t === "debugMode" ? this.debugMode.value = e.debugMode | 0 : t in Xr && (this.settings[t] = e[t]);
777
778
  this._syncUniforms();
778
779
  }
779
780
  }
@@ -784,32 +785,32 @@ var Ri = class extends E {
784
785
  t.fastClampSigmaScale.value = 3 + (e.fastHistoryClampingSigmaScale - 3) * a, t.fireflyMinRelativeScale.value = e.fireflySuppressorMinRelativeScale, t.antiFirefly.value = +!!e.enableAntiFirefly, t.antilag.value.set(e.antilagLuminanceSigmaScale, e.antilagLuminanceSensitivity), t.disocclusionThreshold.value = e.disocclusionThreshold, t.convergence.value.set(e.convergenceS, e.convergenceB, e.convergenceP), t.lobeVolumePercent.value = e.lobeVolumePercent, t.handoverFrames.value = e.handoverFrames > 0 ? e.handoverFrames : 2 * n;
785
786
  }
786
787
  _worldPosAt(e, t, n, r) {
787
- return ue(e, t, n, r, this.cameraRay);
788
+ return le(e, t, n, r, this.cameraRay);
788
789
  }
789
790
  _viewVector(e, t, n) {
790
- return H(ne(this.cameraRay.cameraProjection), n, zn(t.sub(e)));
791
+ return V(E(this.cameraRay.cameraProjection), n, Un(t.sub(e)));
791
792
  }
792
793
  _frustumSize(e) {
793
- return this.minRectDimMulUnproject.mul(H(ne(this.cameraRay.cameraProjection), F(1), e));
794
+ return this.minRectDimMulUnproject.mul(V(E(this.cameraRay.cameraProjection), P(1), e));
794
795
  }
795
796
  _pixelUv(e, t) {
796
- return qn(F(e).add(.5).div(this.resW), F(t).add(.5).div(this.resH));
797
+ return K(P(e).add(.5).div(this.resW), P(t).add(.5).div(this.resH));
797
798
  }
798
799
  _clampCoord(e, t) {
799
- return L(e.clamp(I(0), I(this.resW).sub(1)), t.clamp(I(0), I(this.resH).sub(1)));
800
+ return I(e.clamp(F(0), F(this.resW).sub(1)), t.clamp(F(0), F(this.resH).sub(1)));
800
801
  }
801
802
  _uvToCoord(e) {
802
- return this._clampCoord(I(e.x.mul(this.resW)), I(e.y.mul(this.resH)));
803
+ return this._clampCoord(F(e.x.mul(this.resW)), F(e.y.mul(this.resH)));
803
804
  }
804
805
  _advancedNonLinear(e) {
805
- let t = this.u.convergence, n = V(e.div(F(1).add(this.u.maxAccum.mul(t.z)))), r = t.x.mul(B(t.y, F(1), n));
806
- return F(1).div(F(1).add(r.mul(e)));
806
+ let t = this.u.convergence, n = B(e.div(P(1).add(this.u.maxAccum.mul(t.z)))), r = t.x.mul(z(t.y, P(1), n));
807
+ return P(1).div(P(1).add(r.mul(e)));
807
808
  }
808
809
  _handover(e) {
809
- return V(e.div(z(this.u.handoverFrames, 1)));
810
+ return B(e.div(R(this.u.handoverFrames, 1)));
810
811
  }
811
812
  _bilinear(e) {
812
- let t = e.mul(qn(this.resW, this.resH)).sub(.5), n = In(t), r = V(t.sub(n)), i = I(n.x), a = I(n.y), o = (e, t) => H(e.greaterThanEqual(I(0)).and(t.greaterThanEqual(I(0))).and(e.lessThan(I(this.resW))).and(t.lessThan(I(this.resH))), F(1), F(0));
813
+ let t = e.mul(K(this.resW, this.resH)).sub(.5), n = zn(t), r = B(t.sub(n)), i = F(n.x), a = F(n.y), o = (e, t) => V(e.greaterThanEqual(F(0)).and(t.greaterThanEqual(F(0))).and(e.lessThan(F(this.resW))).and(t.lessThan(F(this.resH))), P(1), P(0));
813
814
  return {
814
815
  f: r,
815
816
  taps: [
@@ -825,22 +826,22 @@ var Ri = class extends E {
825
826
  o(i.add(1), a.add(1))
826
827
  ],
827
828
  customWeights: (e) => [
828
- e[0].mul(F(1).sub(r.x)).mul(F(1).sub(r.y)),
829
- e[1].mul(r.x).mul(F(1).sub(r.y)),
830
- e[2].mul(F(1).sub(r.x)).mul(r.y),
829
+ e[0].mul(P(1).sub(r.x)).mul(P(1).sub(r.y)),
830
+ e[1].mul(r.x).mul(P(1).sub(r.y)),
831
+ e[2].mul(P(1).sub(r.x)).mul(r.y),
831
832
  e[3].mul(r.x).mul(r.y)
832
833
  ],
833
- filter: (e) => B(B(e[0], e[1], r.x), B(e[2], e[3], r.x), r.y)
834
+ filter: (e) => z(z(e[0], e[1], r.x), z(e[2], e[3], r.x), r.y)
834
835
  };
835
836
  }
836
837
  _applyCustomWeights(e, t, n) {
837
838
  let r = e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])), i = t[0].add(t[1]).add(t[2]).add(t[3]);
838
- return H(i.lessThan(1e-4), n, r.div(z(i, 1e-4)));
839
+ return V(i.lessThan(1e-4), n, r.div(R(i, 1e-4)));
839
840
  }
840
841
  _sampleHistory(e, t, n, r, i) {
841
842
  let a = J(0).toVar();
842
- return P(i, () => {
843
- let n = V(t).mul(qn(this.resW, this.resH)), r = In(n.sub(.5)).add(.5), i = V(n.sub(r)), o = pi, s = i.mul(i.mul(i.mul(-o).add(2 * o)).sub(o)), c = i.mul(i.mul(i.mul(2 - o).sub(3 - o))).add(1), l = i.mul(i.mul(i.mul(-(2 - o)).add(3 - 2 * o)).add(o)), u = i.mul(i.mul(i.mul(o).sub(o))), d = [
843
+ return N(i, () => {
844
+ let n = B(t).mul(K(this.resW, this.resH)), r = zn(n.sub(.5)).add(.5), i = B(n.sub(r)), o = vi, s = i.mul(i.mul(i.mul(-o).add(2 * o)).sub(o)), c = i.mul(i.mul(i.mul(2 - o).sub(3 - o))).add(1), l = i.mul(i.mul(i.mul(-(2 - o)).add(3 - 2 * o)).add(o)), u = i.mul(i.mul(i.mul(o).sub(o))), d = [
844
845
  s.x,
845
846
  c.x,
846
847
  l.x,
@@ -850,13 +851,13 @@ var Ri = class extends E {
850
851
  c.y,
851
852
  l.y,
852
853
  u.y
853
- ], p = I(r.x).sub(1), m = I(r.y).sub(1), h = J(0).toVar(), g = F(0).toVar();
854
+ ], p = F(r.x).sub(1), m = F(r.y).sub(1), h = J(0).toVar(), g = P(0).toVar();
854
855
  for (let t = 0; t < 4; t++) for (let n = 0; n < 4; n++) {
855
856
  if ((n === 0 || n === 3) && (t === 0 || t === 3)) continue;
856
857
  let r = d[n].mul(f[t]);
857
858
  h.addAssign(e(this._clampCoord(p.add(n), m.add(t))).mul(r)), g.addAssign(r);
858
859
  }
859
- a.assign(H(g.lessThan(1e-4), J(0), h.div(z(g, 1e-4))));
860
+ a.assign(V(g.lessThan(1e-4), J(0), h.div(R(g, 1e-4))));
860
861
  }).Else(() => {
861
862
  a.assign(this._applyCustomWeights(n.taps.map((t) => e(t)), r, J(0)));
862
863
  }), a;
@@ -878,176 +879,176 @@ var Ri = class extends E {
878
879
  this._dispatchY,
879
880
  1
880
881
  ], [
881
- mi,
882
- mi,
882
+ yi,
883
+ yi,
883
884
  1
884
885
  ]);
885
886
  }
886
887
  _buildSpatial(e) {
887
- let t = e === "pre", { radiusScale: i, fractionScale: a } = hi[e], o = this.u, s = this._colorTexNode, l = this._albedoTexNode, u = this._ndTexNode, d = this._snTexNode, f = this._nData, p = e === "blur" ? this._nTmpA : this._nTmpB, m = e === "blur" ? this._tmpB : t ? this._tmpA : this._hist, h = this._geomPrev, g = t ? this.rotPre : e === "blur" ? this.rotBlur : this.rotPost, _ = t ? o.prepassBlurRadius : o.maxBlurRadius, v = this.camView, y = this.camPos, b = this.resW, x = this.resH, S = this.inputFrames, ee = t ? (e) => {
888
- let t = U(s, e), i = U(l, e);
889
- return J(ki(n(t.xyz.div(z(i.xyz, q(Vr))))), r(i.w, c).min(1));
890
- } : (e) => U(p, e), C = wn(([n, r]) => {
891
- let s = I(Y.x).mul(mi).add(I(R.x)), c = I(Y.y).mul(mi).add(I(R.y));
892
- P(s.lessThan(I(b)).and(c.lessThan(I(x))), () => {
893
- let l = L(s, c), p = Gn(G(s), G(c)), C = U(u, l).w.toVar(), te = C.greaterThanEqual(Br), w = U(d, l).toVar(), ne = zn(w.xyz.mul(2).sub(1)).toVar(), re = w.w.clamp(.05, 1).toVar(), T = F(Br).toVar(), ie = ee(l).toVar();
894
- P(te.not(), () => {
888
+ let t = e === "pre", { radiusScale: i, fractionScale: a } = bi[e], o = this.u, s = this._colorTexNode, l = this._albedoTexNode, u = this._ndTexNode, d = this._snTexNode, f = this._nData, p = e === "blur" ? this._nTmpA : this._nTmpB, m = e === "blur" ? this._tmpB : t ? this._tmpA : this._hist, h = this._geomPrev, g = t ? this.rotPre : e === "blur" ? this.rotBlur : this.rotPost, _ = t ? o.prepassBlurRadius : o.maxBlurRadius, v = this.camView, y = this.camPos, b = this.resW, x = this.resH, S = this.inputFrames, ee = t ? (e) => {
889
+ let t = H(s, e), i = H(l, e);
890
+ return J(Pi(n(t.xyz.div(R(i.xyz, q(Kr))))), r(i.w, c).min(1));
891
+ } : (e) => H(p, e), C = En(([n, r]) => {
892
+ let s = F(Y.x).mul(yi).add(F(L.x)), c = F(Y.y).mul(yi).add(F(L.y));
893
+ N(s.lessThan(F(b)).and(c.lessThan(F(x))), () => {
894
+ let l = I(s, c), p = Xn(W(s), W(c)), C = H(u, l).w.toVar(), w = C.greaterThanEqual(Gr), T = H(d, l).toVar(), E = Un(T.xyz.mul(2).sub(1)).toVar(), te = T.w.clamp(.05, 1).toVar(), D = P(Gr).toVar(), ne = ee(l).toVar();
895
+ N(w.not(), () => {
895
896
  let e = this._pixelUv(s, c), p = this._worldPosAt(e, C, n, r).toVar();
896
- T.assign(v.mul(J(p, 1)).z.abs()), P(_.greaterThan(0), () => {
897
- let s = Nn(ne, this._viewVector(p, y, this.viewVector)).abs().toVar(), c = this._frustumSize(T).toVar(), m = S.add(1), h = t ? z(S, F(10)) : U(f, l).y.add(S), C = (t ? F(1).div(h.add(1)) : this._advancedNonLinear(h)).toVar(), te = xi(re, .5).toVar(), w = T.mul(Wr).add(3), ae = ie.w.toVar(), oe = V(ae.mul(w).div(c)), se = F(1).sub(this._handover(m)), E = (t ? oe.div(m) : oe.mul(C)).mul(se), D = o.minBlurRadius.mul(V(F(2).sub(h.div(z(o.maxAccum, 1))))), ce = z(V(Un(V(E)).mul(i)).mul(_).mul(te), D.mul(te)).toVar(), O = Di(o.planeDistSensitivity, c, p, ne).toVar(), k = Ci(C, o.lobeAngleFraction, re, o.lobeVolumePercent).div(a).toVar(), le = wi(re, o.roughnessFraction.mul(a)).toVar(), ue = Ei(ae, C).toVar(), de = o.minHitDistanceWeight.mul(a).mul(te);
898
- t || (de = de.mul(C)), de = de.toVar();
899
- let A = qn(1);
897
+ D.assign(v.mul(J(p, 1)).z.abs()), N(_.greaterThan(0), () => {
898
+ let s = Fn(E, this._viewVector(p, y, this.viewVector)).abs().toVar(), c = this._frustumSize(D).toVar(), m = S.add(1), h = t ? R(S, P(10)) : H(f, l).y.add(S), C = (t ? P(1).div(h.add(1)) : this._advancedNonLinear(h)).toVar(), w = Ei(te, .5).toVar(), T = D.mul(Yr).add(3), re = ne.w.toVar(), ie = B(re.mul(T).div(c)), ae = P(1).sub(this._handover(m)), O = (t ? ie.div(m) : ie.mul(C)).mul(ae), k = o.minBlurRadius.mul(B(P(2).sub(h.div(R(o.maxAccum, 1))))), oe = R(B(qn(B(O)).mul(i)).mul(_).mul(w), k.mul(w)).toVar(), se = Mi(o.planeDistSensitivity, c, p, E).toVar(), A = Oi(C, o.lobeAngleFraction, te, o.lobeVolumePercent).div(a).toVar(), ce = ki(te, o.roughnessFraction.mul(a)).toVar(), le = ji(re, C).toVar(), ue = o.minHitDistanceWeight.mul(a).mul(w);
899
+ t || (ue = ue.mul(C)), ue = ue.toVar();
900
+ let de = K(1);
900
901
  if (!t) {
901
- let e = v.mul(J(ne, 0)).xy;
902
- A = B(qn(1).sub(e.abs()), qn(1), s), A = A.div(z(A.x, A.y));
902
+ let e = v.mul(J(E, 0)).xy;
903
+ de = z(K(1).sub(e.abs()), K(1), s), de = de.div(R(de.x, de.y));
903
904
  }
904
- let fe = A.mul(qn(F(1).div(b), F(1).div(x))).mul(ce).toVar(), pe = F(1).toVar();
905
- for (let t = 0; t < _i.length; t++) {
906
- let i = _i[t], a = e.add(Fi(g, qn(i[0], i[1])).mul(fe)), o = Oi(a), s = H(o.x.notEqual(a.x).or(o.y.notEqual(a.y)), F(1), F(Math.exp(-.66 * i[2] * i[2]))).toVar(), c = this._uvToCoord(o), l = U(u, c).w, f = this._worldPosAt(o, l, n, r), p = U(d, c), m = bi(Nn(ne, zn(p.xyz.mul(2).sub(1))));
907
- s.mulAssign(vi(m, k, F(0))), s.mulAssign(vi(p.w, le.x, le.y)), s.mulAssign(vi(Nn(ne, f), O.x, O.y)), s.assign(H(l.greaterThanEqual(Br), F(0), s));
908
- let h = Ii(s, ee(c));
909
- s.mulAssign(de.add(yi(h.w, ue.x, ue.y))), pe.addAssign(s), ie.addAssign(h.mul(s));
905
+ let fe = de.mul(K(P(1).div(b), P(1).div(x))).mul(oe).toVar(), pe = P(1).toVar();
906
+ for (let t = 0; t < Si.length; t++) {
907
+ let i = Si[t], a = e.add(Bi(g, K(i[0], i[1])).mul(fe)), o = Ni(a), s = V(o.x.notEqual(a.x).or(o.y.notEqual(a.y)), P(1), P(Math.exp(-.66 * i[2] * i[2]))).toVar(), c = this._uvToCoord(o), l = H(u, c).w, f = this._worldPosAt(o, l, n, r), p = H(d, c), m = Ti(Fn(E, Un(p.xyz.mul(2).sub(1))));
908
+ s.mulAssign(Ci(m, A, P(0))), s.mulAssign(Ci(p.w, ce.x, ce.y)), s.mulAssign(Ci(Fn(E, f), se.x, se.y)), s.assign(V(l.greaterThanEqual(Gr), P(0), s));
909
+ let h = Vi(s, ee(c));
910
+ s.mulAssign(ue.add(wi(h.w, le.x, le.y))), pe.addAssign(s), ne.addAssign(h.mul(s));
910
911
  }
911
- ie.divAssign(z(pe, 1e-6)), t || ie.assign(J(ie.xyz, ae));
912
+ ne.divAssign(R(pe, 1e-6)), t || ne.assign(J(ne.xyz, re));
912
913
  });
913
- }), W(m, p, ie).toWriteOnly(), e === "post" && W(h, p, J(ne, T)).toWriteOnly();
914
+ }), U(m, p, ne).toWriteOnly(), e === "post" && U(h, p, J(E, D)).toWriteOnly();
914
915
  });
915
916
  });
916
917
  return this._dispatchOf(C);
917
918
  }
918
919
  _buildTemporalAccumulation() {
919
- let e = this.u, t = this._ndTexNode, n = this._snTexNode, r = this._motionTexNode, i = this._nTmpA, a = this._nHist, o = this._nFast, s = this._nInternal, c = this._nGeom, l = this._tmpB, u = this._dataT, d = this.camView, f = this.prevCamView, p = this.camPos, m = this.prevCamPos, h = this.resW, g = this.resH, _ = this.inputFrames, v = this.resetU, y = wn(([y, b]) => {
920
- let x = I(Y.x).mul(mi).add(I(R.x)), S = I(Y.y).mul(mi).add(I(R.y));
921
- P(x.lessThan(I(h)).and(S.lessThan(I(g))), () => {
922
- let h = L(x, S), g = Gn(G(x), G(S)), ee = U(t, h).w, C = U(i, h).toVar();
923
- P(ee.greaterThanEqual(Br), () => {
924
- W(l, g, C).toWriteOnly(), W(u, g, J(0)).toWriteOnly(), En();
920
+ let e = this.u, t = this._ndTexNode, n = this._snTexNode, r = this._motionTexNode, i = this._nTmpA, a = this._nHist, o = this._nFast, s = this._nInternal, c = this._nGeom, l = this._tmpB, u = this._dataT, d = this.camView, f = this.prevCamView, p = this.camPos, m = this.prevCamPos, h = this.resW, g = this.resH, _ = this.inputFrames, v = this.resetU, y = En(([y, b]) => {
921
+ let x = F(Y.x).mul(yi).add(F(L.x)), S = F(Y.y).mul(yi).add(F(L.y));
922
+ N(x.lessThan(F(h)).and(S.lessThan(F(g))), () => {
923
+ let h = I(x, S), g = Xn(W(x), W(S)), ee = H(t, h).w, C = H(i, h).toVar();
924
+ N(ee.greaterThanEqual(Gr), () => {
925
+ U(l, g, C).toWriteOnly(), U(u, g, J(0)).toWriteOnly(), On();
925
926
  });
926
- let te = e.maxAccum.mul(F(1).sub(v)).toVar(), w = e.maxFast.mul(F(1).sub(v)).toVar(), ne = U(n, h), re = zn(ne.xyz.mul(2).sub(1)).toVar(), T = ne.w.clamp(.05, 1).toVar(), ie = this._pixelUv(x, S), ae = this._worldPosAt(ie, ee, y, b).toVar(), oe = d.mul(J(ae, 1)).z.abs().toVar(), se = Nn(re, this._viewVector(ae, p, this.viewVector)).abs().toVar(), E = this._frustumSize(oe).toVar(), D = q(0).toVar();
927
- D.addAssign(re.mul(.25));
927
+ let w = e.maxAccum.mul(P(1).sub(v)).toVar(), T = e.maxFast.mul(P(1).sub(v)).toVar(), E = H(n, h), te = Un(E.xyz.mul(2).sub(1)).toVar(), D = E.w.clamp(.05, 1).toVar(), ne = this._pixelUv(x, S), re = this._worldPosAt(ne, ee, y, b).toVar(), ie = d.mul(J(re, 1)).z.abs().toVar(), ae = Fn(te, this._viewVector(re, p, this.viewVector)).abs().toVar(), O = this._frustumSize(ie).toVar(), k = q(0).toVar();
928
+ k.addAssign(te.mul(.25));
928
929
  for (let e = -1; e <= 0; e++) for (let r = -1; r <= 0; r++) {
929
930
  if (r === 0 && e === 0) continue;
930
- let i = this._clampCoord(x.add(r), S.add(e)), a = zn(U(n, i).xyz.mul(2).sub(1)), o = U(t, i).w.lessThan(Br);
931
- D.addAssign(H(o, a, re).mul(.25));
931
+ let i = this._clampCoord(x.add(r), S.add(e)), a = Un(H(n, i).xyz.mul(2).sub(1)), o = H(t, i).w.lessThan(Gr);
932
+ k.addAssign(V(o, a, te).mul(.25));
932
933
  }
933
- let ce = U(r, h), O = ie.sub(ce.xy).toVar(), k = f.mul(J(ae, 1)).z.abs().toVar(), le = this._bilinear(O), ue = E.mul(V(e.disocclusionThreshold.div(z(se, .05)))).sub(ti).toVar(), de = F(1).sub(v), A = [], fe = [];
934
+ let oe = H(r, h), se = ne.sub(oe.xy).toVar(), A = f.mul(J(re, 1)).z.abs().toVar(), ce = this._bilinear(se), le = O.mul(B(e.disocclusionThreshold.div(R(ae, .05)))).sub(oi).toVar(), ue = P(1).sub(v), de = [], fe = [];
934
935
  for (let e = 0; e < 4; e++) {
935
- let t = U(c, le.taps[e]), n = H(Nn(t.xyz, D).greaterThan(fi), F(1), F(0)), r = H(t.w.sub(k).abs().lessThanEqual(ue), F(1), F(0)), i = H(t.w.lessThan(Br), F(1), F(0));
936
- A.push(n.mul(r).mul(i).mul(le.inScreen[e]).mul(de).toVar()), fe.push(U(s, le.taps[e]).x);
936
+ let t = H(c, ce.taps[e]), n = V(Fn(t.xyz, k).greaterThan(_i), P(1), P(0)), r = V(t.w.sub(A).abs().lessThanEqual(le), P(1), P(0)), i = V(t.w.lessThan(Gr), P(1), P(0));
937
+ de.push(n.mul(r).mul(i).mul(ce.inScreen[e]).mul(ue).toVar()), fe.push(H(s, ce.taps[e]).x);
937
938
  }
938
- let pe = le.customWeights(A).map((e) => e.toVar()), me = A[0].add(A[1]).add(A[2]).add(A[3]).greaterThan(3.5).toVar(), he = A[0].add(A[1].mul(2)).add(A[2].mul(4)).add(A[3].mul(8)), ge = this._applyCustomWeights(fe, pe, F(0)).toVar(), _e = Nn(re, this._viewVector(ae, m, this.prevViewVector)).abs().add(.001).div(se.add(.001)).toVar();
939
- _e.assign(B(F(.1), F(1), V(_e.mul(_e))));
940
- let ve = Un(V(le.filter(A))).mul(_e).toVar();
941
- ge.assign(ge.mul(B(ve, F(1), F(1).div(ge.add(1))))), ge.assign(Rn(ge, te));
942
- let ye = Ni(this._sampleHistory((e) => U(a, e), O, le, pe, me)).toVar(), be = z(this._applyCustomWeights(le.taps.map((e) => U(o, e).x), pe, F(0)), 0).toVar(), xe = _.add(1), Se = this._handover(xe).toVar(), Ce = ge.mul(F(1).sub(Se)), we = xe.div(xe.add(Ce)).toVar(), j = F(1).div(F(1).add(xi(T, .25).mul(.5).mul(te))), Te = J(B(ye.xyz, C.xyz, we), B(ye.w, C.w, z(we, j))).toVar(), Ee = e.fireflyMinRelativeScale.add(F(li).div(ge.add(1))).toVar(), De = ge.mul(e.maxBlurRadius).mul(ui).toVar();
943
- De.assign(De.div(De.add(1)).mul(F(1).sub(Se)));
944
- let Oe = B(Te.x, Rn(Te.x, ye.x.mul(Ee)), De);
945
- Te.assign(Mi(Te, Oe));
946
- let ke = F(1.2).add(F(1).div(ge.add(1)));
947
- Te.assign(J(Te.xyz, B(Te.w, Rn(Te.w, ye.w.mul(ke)), De))), W(l, g, Te).toWriteOnly();
948
- let Ae = Rn(ge, w).mul(F(1).sub(Se)), je = xe.div(xe.add(Ae)), Me = B(be, C.x, je).toVar(), Ne = Rn(Me, ye.x.mul(Ee).mul(di));
949
- Me.assign(B(Me, Ne, De)), W(u, g, J(Me, ge, he, H(me, F(1), F(0)))).toWriteOnly();
939
+ let pe = ce.customWeights(de).map((e) => e.toVar()), me = de[0].add(de[1]).add(de[2]).add(de[3]).greaterThan(3.5).toVar(), he = de[0].add(de[1].mul(2)).add(de[2].mul(4)).add(de[3].mul(8)), ge = this._applyCustomWeights(fe, pe, P(0)).toVar(), _e = Fn(te, this._viewVector(re, m, this.prevViewVector)).abs().add(.001).div(ae.add(.001)).toVar();
940
+ _e.assign(z(P(.1), P(1), B(_e.mul(_e))));
941
+ let ve = qn(B(ce.filter(de))).mul(_e).toVar();
942
+ ge.assign(ge.mul(z(ve, P(1), P(1).div(ge.add(1))))), ge.assign(Hn(ge, w));
943
+ let ye = Ri(this._sampleHistory((e) => H(a, e), se, ce, pe, me)).toVar(), be = R(this._applyCustomWeights(ce.taps.map((e) => H(o, e).x), pe, P(0)), 0).toVar(), xe = _.add(1), Se = this._handover(xe).toVar(), Ce = ge.mul(P(1).sub(Se)), we = xe.div(xe.add(Ce)).toVar(), j = P(1).div(P(1).add(Ei(D, .25).mul(.5).mul(w))), Te = J(z(ye.xyz, C.xyz, we), z(ye.w, C.w, R(we, j))).toVar(), Ee = e.fireflyMinRelativeScale.add(P(mi).div(ge.add(1))).toVar(), De = ge.mul(e.maxBlurRadius).mul(hi).toVar();
944
+ De.assign(De.div(De.add(1)).mul(P(1).sub(Se)));
945
+ let Oe = z(Te.x, Hn(Te.x, ye.x.mul(Ee)), De);
946
+ Te.assign(Li(Te, Oe));
947
+ let ke = P(1.2).add(P(1).div(ge.add(1)));
948
+ Te.assign(J(Te.xyz, z(Te.w, Hn(Te.w, ye.w.mul(ke)), De))), U(l, g, Te).toWriteOnly();
949
+ let Ae = Hn(ge, T).mul(P(1).sub(Se)), je = xe.div(xe.add(Ae)), Me = z(be, C.x, je).toVar(), Ne = Hn(Me, ye.x.mul(Ee).mul(gi));
950
+ Me.assign(z(Me, Ne, De)), U(u, g, J(Me, ge, he, V(me, P(1), P(0)))).toWriteOnly();
950
951
  });
951
952
  });
952
953
  return this._dispatchOf(y);
953
954
  }
954
955
  _buildHistoryFix() {
955
- let e = this.u, t = this._ndTexNode, n = this._snTexNode, r = this._nTmpB, i = this._nData, a = this._tmpA, o = this._fastHist, s = this.camView, c = this.resW, l = this.resH, u = this.inputFrames, d = wn(([d, f]) => {
956
- let p = I(Y.x).mul(mi).add(I(R.x)), m = I(Y.y).mul(mi).add(I(R.y));
957
- P(p.lessThan(I(c)).and(m.lessThan(I(l))), () => {
958
- let h = L(p, m), g = Gn(G(p), G(m)), _ = U(t, h).w;
959
- P(_.greaterThanEqual(Br), () => {
960
- let e = U(r, h);
961
- W(a, g, e).toWriteOnly(), W(o, g, J(e.x, 0, 0, 0)).toWriteOnly(), En();
956
+ let e = this.u, t = this._ndTexNode, n = this._snTexNode, r = this._nTmpB, i = this._nData, a = this._tmpA, o = this._fastHist, s = this.camView, c = this.resW, l = this.resH, u = this.inputFrames, d = En(([d, f]) => {
957
+ let p = F(Y.x).mul(yi).add(F(L.x)), m = F(Y.y).mul(yi).add(F(L.y));
958
+ N(p.lessThan(F(c)).and(m.lessThan(F(l))), () => {
959
+ let h = I(p, m), g = Xn(W(p), W(m)), _ = H(t, h).w;
960
+ N(_.greaterThanEqual(Gr), () => {
961
+ let e = H(r, h);
962
+ U(a, g, e).toWriteOnly(), U(o, g, J(e.x, 0, 0, 0)).toWriteOnly(), On();
962
963
  });
963
- let v = U(i, h).toVar(), y = v.y.toVar(), b = y.add(u), x = this._handover(u.add(1)).toVar(), S = U(n, h), ee = zn(S.xyz.mul(2).sub(1)).toVar(), C = S.w.clamp(.05, 1).toVar(), te = this._pixelUv(p, m), w = this._worldPosAt(te, _, d, f).toVar(), ne = s.mul(J(w, 1)).z.abs(), re = this._frustumSize(ne).toVar(), T = U(r, h).toVar(), ie = F(1).div(b.add(1)).toVar(), ae = ne.mul(Wr).add(3), oe = V(T.w.mul(ae).div(re)), se = T.w.toVar(), E = Vn(H(b.lessThan(e.historyFixFrameNum), F(1), F(0)).mul(.5).mul(2 / ai).mul(e.historyFixStride).mul(B(F(.25).add(Un(oe).mul(.75)), F(1), ie))).toVar();
964
- P(E.notEqual(0), () => {
965
- let a = Ci(ie, e.lobeAngleFraction, C, e.lobeVolumePercent).toVar(), o = Di(e.planeDistSensitivity, re, w, ee).toVar(), s = Ei(se, ie).toVar(), u = Ti(C.mul(C), Un(e.roughnessFraction), ri).toVar(), p = F(1).add(y).toVar();
966
- T.mulAssign(p);
967
- for (let e = -ai; e <= ai; e++) for (let m = -ai; m <= ai; m++) {
968
- if (m === 0 && e === 0 || Math.abs(m) + Math.abs(e) === ai * 2) continue;
969
- let h = Oi(te.add(qn(m, e).mul(E).mul(qn(F(1).div(c), F(1).div(l))))), g = this._uvToCoord(h), _ = U(t, g).w, v = this._worldPosAt(h, _, d, f), y = U(n, g), b = yi(bi(Nn(zn(y.xyz.mul(2).sub(1)), ee)), a, F(0)).toVar();
970
- b.mulAssign(yi(y.w.mul(y.w), u.x, u.y)), b.mulAssign(F(1).add(U(i, g).y)), b.mulAssign(vi(Nn(ee, v), o.x, o.y)), b.assign(H(_.greaterThanEqual(Br), F(0), b));
971
- let x = Ii(b, U(r, g));
972
- b.mulAssign(yi(x.w, s.x, s.y)), p.addAssign(b), T.addAssign(x.mul(b));
964
+ let v = H(i, h).toVar(), y = v.y.toVar(), b = y.add(u), x = this._handover(u.add(1)).toVar(), S = H(n, h), ee = Un(S.xyz.mul(2).sub(1)).toVar(), C = S.w.clamp(.05, 1).toVar(), w = this._pixelUv(p, m), T = this._worldPosAt(w, _, d, f).toVar(), E = s.mul(J(T, 1)).z.abs(), te = this._frustumSize(E).toVar(), D = H(r, h).toVar(), ne = P(1).div(b.add(1)).toVar(), re = E.mul(Yr).add(3), ie = B(D.w.mul(re).div(te)), ae = D.w.toVar(), O = Gn(V(b.lessThan(e.historyFixFrameNum), P(1), P(0)).mul(.5).mul(2 / ui).mul(e.historyFixStride).mul(z(P(.25).add(qn(ie).mul(.75)), P(1), ne))).toVar();
965
+ N(O.notEqual(0), () => {
966
+ let a = Oi(ne, e.lobeAngleFraction, C, e.lobeVolumePercent).toVar(), o = Mi(e.planeDistSensitivity, te, T, ee).toVar(), s = ji(ae, ne).toVar(), u = Ai(C.mul(C), qn(e.roughnessFraction), ci).toVar(), p = P(1).add(y).toVar();
967
+ D.mulAssign(p);
968
+ for (let e = -ui; e <= ui; e++) for (let m = -ui; m <= ui; m++) {
969
+ if (m === 0 && e === 0 || Math.abs(m) + Math.abs(e) === ui * 2) continue;
970
+ let h = Ni(w.add(K(m, e).mul(O).mul(K(P(1).div(c), P(1).div(l))))), g = this._uvToCoord(h), _ = H(t, g).w, v = this._worldPosAt(h, _, d, f), y = H(n, g), b = wi(Ti(Fn(Un(y.xyz.mul(2).sub(1)), ee)), a, P(0)).toVar();
971
+ b.mulAssign(wi(y.w.mul(y.w), u.x, u.y)), b.mulAssign(P(1).add(H(i, g).y)), b.mulAssign(Ci(Fn(ee, v), o.x, o.y)), b.assign(V(_.greaterThanEqual(Gr), P(0), b));
972
+ let x = Vi(b, H(r, g));
973
+ b.mulAssign(wi(x.w, s.x, s.y)), p.addAssign(b), D.addAssign(x.mul(b));
973
974
  }
974
- T.divAssign(z(p, 1e-6));
975
+ D.divAssign(R(p, 1e-6));
975
976
  });
976
- let D = T.x.toVar(), ce = V(y.div(z(e.historyFixFrameNum, ti))), O = B(D, v.x, ce).toVar();
977
- W(o, g, J(O, 0, 0, 0)).toWriteOnly();
978
- let k = O.toVar(), le = O.mul(O).toVar(), ue = F(0).toVar(), de = F(0).toVar(), A = (e, n, r) => {
979
- let a = this._clampCoord(p.add(e), m.add(n)), o = U(t, a).w, s = H(o.greaterThanEqual(Br), O, U(i, a).x);
980
- Math.abs(e) <= oi && Math.abs(n) <= oi && (k.addAssign(s), le.addAssign(s.mul(s))), r && (ue.addAssign(s), de.addAssign(s.mul(s)));
977
+ let k = D.x.toVar(), oe = B(y.div(R(e.historyFixFrameNum, oi))), se = z(k, v.x, oe).toVar();
978
+ U(o, g, J(se, 0, 0, 0)).toWriteOnly();
979
+ let A = se.toVar(), ce = se.mul(se).toVar(), le = P(0).toVar(), ue = P(0).toVar(), de = (e, n, r) => {
980
+ let a = this._clampCoord(p.add(e), m.add(n)), o = H(t, a).w, s = V(o.greaterThanEqual(Gr), se, H(i, a).x);
981
+ Math.abs(e) <= di && Math.abs(n) <= di && (A.addAssign(s), ce.addAssign(s.mul(s))), r && (le.addAssign(s), ue.addAssign(s.mul(s)));
981
982
  }, fe = e.antiFirefly.greaterThan(.5);
982
- for (let e = -oi; e <= oi; e++) for (let t = -oi; t <= oi; t++) t === 0 && e === 0 || A(t, e, Math.abs(t) > 1 || Math.abs(e) > 1);
983
- P(fe, () => {
984
- for (let e = -si; e <= si; e++) for (let t = -si; t <= si; t++) Math.abs(t) <= oi && Math.abs(e) <= oi || A(t, e, !0);
985
- }), P(fe, () => {
986
- let e = 1 / ((si * 2 + 1) ** 2 - 9), t = ue.mul(e), n = Pi(t, de.mul(e)).mul(ci);
987
- D.assign(B(D.clamp(t.sub(n), t.add(n)), D, x));
983
+ for (let e = -di; e <= di; e++) for (let t = -di; t <= di; t++) t === 0 && e === 0 || de(t, e, Math.abs(t) > 1 || Math.abs(e) > 1);
984
+ N(fe, () => {
985
+ for (let e = -fi; e <= fi; e++) for (let t = -fi; t <= fi; t++) Math.abs(t) <= di && Math.abs(e) <= di || de(t, e, !0);
986
+ }), N(fe, () => {
987
+ let e = 1 / ((fi * 2 + 1) ** 2 - 9), t = le.mul(e), n = zi(t, ue.mul(e)).mul(pi);
988
+ k.assign(z(k.clamp(t.sub(n), t.add(n)), k, x));
988
989
  });
989
990
  {
990
- let t = 1 / (oi * 2 + 1) ** 2, n = k.mul(t), r = Pi(n, le.mul(t)).mul(e.fastClampSigmaScale), i = D.clamp(n.sub(r), n.add(r)), a = H(e.maxFast.lessThan(e.maxAccum), F(1), F(0)), o = B(F(1).div(F(1).add(a.mul(y).mul(2))), F(1), x);
991
- D.assign(B(i, D, o));
991
+ let t = 1 / (di * 2 + 1) ** 2, n = A.mul(t), r = zi(n, ce.mul(t)).mul(e.fastClampSigmaScale), i = k.clamp(n.sub(r), n.add(r)), a = V(e.maxFast.lessThan(e.maxAccum), P(1), P(0)), o = z(P(1).div(P(1).add(a.mul(y).mul(2))), P(1), x);
992
+ k.assign(z(i, k, o));
992
993
  }
993
- W(a, g, Mi(T, D)).toWriteOnly();
994
+ U(a, g, Li(D, k)).toWriteOnly();
994
995
  });
995
996
  });
996
997
  return this._dispatchOf(d);
997
998
  }
998
999
  _buildTemporalStabilization(e) {
999
1000
  let t = this.u, n = this._colorTexNode, r = this._albedoTexNode, i = this._ndTexNode, a = this._snTexNode, o = this._motionTexNode, s = this._nHist, c = this._nData, l = this._nStabRead, u = this._internal, d = this._tmpA, f = this.resW, p = this.resH, m = this.inputFrames, h = this.resetU, g = this.debugMode;
1000
- return wn(() => {
1001
- let _ = I(Y.x).mul(mi).add(I(R.x)), v = I(Y.y).mul(mi).add(I(R.y));
1002
- P(_.lessThan(I(f)).and(v.lessThan(I(p))), () => {
1003
- let f = L(_, v), p = Gn(G(_), G(v)), y = U(i, f).w, b = U(n, f).toVar();
1004
- P(y.greaterThanEqual(Br), () => {
1005
- W(d, p, b).toWriteOnly(), W(e, p, J(U(s, f).x, 0, 0, 0)).toWriteOnly(), W(u, p, J(0, 1, 0, 0)).toWriteOnly(), En();
1001
+ return En(() => {
1002
+ let _ = F(Y.x).mul(yi).add(F(L.x)), v = F(Y.y).mul(yi).add(F(L.y));
1003
+ N(_.lessThan(F(f)).and(v.lessThan(F(p))), () => {
1004
+ let f = I(_, v), p = Xn(W(_), W(v)), y = H(i, f).w, b = H(n, f).toVar();
1005
+ N(y.greaterThanEqual(Gr), () => {
1006
+ U(d, p, b).toWriteOnly(), U(e, p, J(H(s, f).x, 0, 0, 0)).toWriteOnly(), U(u, p, J(0, 1, 0, 0)).toWriteOnly(), On();
1006
1007
  });
1007
- let x = U(a, f).w.clamp(.05, 1), S = this._pixelUv(_, v), ee = U(o, f), C = S.sub(ee.xy).toVar(), te = U(c, f).toVar(), w = te.y.toVar(), ne = G(te.z.add(.5)).toVar(), re = te.w.greaterThan(.5), T = this._bilinear(C), ie = [
1008
+ let x = H(a, f).w.clamp(.05, 1), S = this._pixelUv(_, v), ee = H(o, f), C = S.sub(ee.xy).toVar(), w = H(c, f).toVar(), T = w.y.toVar(), E = W(w.z.add(.5)).toVar(), te = w.w.greaterThan(.5), D = this._bilinear(C), ne = [
1008
1009
  1,
1009
1010
  2,
1010
1011
  4,
1011
1012
  8
1012
- ].map((e) => H(ne.bitAnd(G(e)).notEqual(G(0)), F(1), F(0))), ae = T.customWeights(ie).map((e) => e.toVar()), oe = Un(V(T.filter(ie))).toVar(), se = U(s, f).toVar(), E = se.x.toVar(), D = E.toVar(), ce = E.mul(E).toVar();
1013
+ ].map((e) => V(E.bitAnd(W(e)).notEqual(W(0)), P(1), P(0))), re = D.customWeights(ne).map((e) => e.toVar()), ie = qn(B(D.filter(ne))).toVar(), ae = H(s, f).toVar(), O = ae.x.toVar(), k = O.toVar(), oe = O.mul(O).toVar();
1013
1014
  for (let e = -1; e <= 1; e++) for (let t = -1; t <= 1; t++) {
1014
1015
  if (t === 0 && e === 0) continue;
1015
- let n = this._clampCoord(_.add(t), v.add(e)), r = U(i, n).w, a = H(r.greaterThanEqual(Br), E, U(s, n).x);
1016
- D.addAssign(a), ce.addAssign(a.mul(a));
1016
+ let n = this._clampCoord(_.add(t), v.add(e)), r = H(i, n).w, a = V(r.greaterThanEqual(Gr), O, H(s, n).x);
1017
+ k.addAssign(a), oe.addAssign(a.mul(a));
1017
1018
  }
1018
- D.divAssign(9), ce.divAssign(9);
1019
- let O = Pi(D, ce).toVar();
1020
- P(w.lessThan(t.historyFixFrameNum), () => {
1021
- E.assign(Rn(E, D.mul(F(1.2).add(F(1).div(w.add(1))))));
1019
+ k.divAssign(9), oe.divAssign(9);
1020
+ let se = zi(k, oe).toVar();
1021
+ N(T.lessThan(t.historyFixFrameNum), () => {
1022
+ O.assign(Hn(O, k.mul(P(1.2).add(P(1).div(T.add(1))))));
1022
1023
  });
1023
- let k = z(this._sampleHistory((e) => U(l, e), C, T, ae, re).x, 0).toVar(), le = O.mul(t.antilag.x), ue = t.antilag.y.mul(4), de = k.clamp(D.sub(le), D.add(le)), A = k.sub(de).abs().div(z(k, de).add(ti)), fe = F(1).div(F(1).add(A.mul(w.mul(oe)).div(ue))).toVar(), pe = Rn(w, t.historyFixFrameNum);
1024
- w.assign(B(pe, w, fe));
1025
- let me = m.add(1), he = this._handover(me), ge = oe.mul(F(1).sub(this._advancedNonLinear(w.mul(F(1).sub(he)).div(me)))).mul(fe).toVar(), _e = F(1).add(ge.mul(6)), ve = t.stabilizationStrength.mul(F(1).sub(h)), ye = B(E, k.clamp(D.sub(O.mul(_e)), D.add(O.mul(_e))), Rn(ge, ve)).toVar();
1026
- se.assign(Mi(se, ye)), W(e, p, J(ye, 0, 0, 0)).toWriteOnly();
1027
- let be = t.maxAccum.mul(F(1).sub(h));
1028
- W(u, p, J(Rn(w.add(1), be), x, 0, 0)).toWriteOnly();
1029
- let xe = U(r, f), Se = J(Ai(se.xyz).mul(z(xe.xyz, q(Vr))), b.w).toVar();
1030
- P(g.equal(I(1)), () => {
1031
- let e = V(w.div(z(t.maxAccum, 1)));
1032
- Se.assign(J(F(1).sub(e), e, .2, 1));
1033
- }).ElseIf(g.equal(I(2)), () => {
1034
- Se.assign(J(q(se.w), 1));
1035
- }).ElseIf(g.equal(I(3)), () => {
1024
+ let A = R(this._sampleHistory((e) => H(l, e), C, D, re, te).x, 0).toVar(), ce = se.mul(t.antilag.x), le = t.antilag.y.mul(4), ue = A.clamp(k.sub(ce), k.add(ce)), de = A.sub(ue).abs().div(R(A, ue).add(oi)), fe = P(1).div(P(1).add(de.mul(T.mul(ie)).div(le))).toVar(), pe = Hn(T, t.historyFixFrameNum);
1025
+ T.assign(z(pe, T, fe));
1026
+ let me = m.add(1), he = this._handover(me), ge = ie.mul(P(1).sub(this._advancedNonLinear(T.mul(P(1).sub(he)).div(me)))).mul(fe).toVar(), _e = P(1).add(ge.mul(6)), ve = t.stabilizationStrength.mul(P(1).sub(h)), ye = z(O, A.clamp(k.sub(se.mul(_e)), k.add(se.mul(_e))), Hn(ge, ve)).toVar();
1027
+ ae.assign(Li(ae, ye)), U(e, p, J(ye, 0, 0, 0)).toWriteOnly();
1028
+ let be = t.maxAccum.mul(P(1).sub(h));
1029
+ U(u, p, J(Hn(T.add(1), be), x, 0, 0)).toWriteOnly();
1030
+ let xe = H(r, f), Se = J(Fi(ae.xyz).mul(R(xe.xyz, q(Kr))), b.w).toVar();
1031
+ N(g.equal(F(1)), () => {
1032
+ let e = B(T.div(R(t.maxAccum, 1)));
1033
+ Se.assign(J(P(1).sub(e), e, .2, 1));
1034
+ }).ElseIf(g.equal(F(2)), () => {
1035
+ Se.assign(J(q(ae.w), 1));
1036
+ }).ElseIf(g.equal(F(3)), () => {
1036
1037
  Se.assign(J(q(x), 1));
1037
- }).ElseIf(g.equal(I(4)), () => {
1038
- let e = te.x.div(te.x.add(1));
1038
+ }).ElseIf(g.equal(F(4)), () => {
1039
+ let e = w.x.div(w.x.add(1));
1039
1040
  Se.assign(J(q(e), 1));
1040
- }).ElseIf(g.equal(I(5)), () => {
1041
- Se.assign(J(q(te.z.div(15)), 1));
1042
- }), W(d, p, Se).toWriteOnly();
1041
+ }).ElseIf(g.equal(F(5)), () => {
1042
+ Se.assign(J(q(w.z.div(15)), 1));
1043
+ }), U(d, p, Se).toWriteOnly();
1043
1044
  });
1044
1045
  })().compute([
1045
1046
  this._dispatchX,
1046
1047
  this._dispatchY,
1047
1048
  1
1048
1049
  ], [
1049
- mi,
1050
- mi,
1050
+ yi,
1051
+ yi,
1051
1052
  1
1052
1053
  ]);
1053
1054
  }
@@ -1067,7 +1068,7 @@ var Ri = class extends E {
1067
1068
  }
1068
1069
  _updateRotators(e) {
1069
1070
  let t = (t, n) => {
1070
- let r = Li(e * 3 + n) * Math.PI * 2;
1071
+ let r = Hi(e * 3 + n) * Math.PI * 2;
1071
1072
  t.value.set(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r));
1072
1073
  };
1073
1074
  t(this.rotPre, 0), t(this.rotBlur, 1), t(this.rotPost, 2);
@@ -1094,7 +1095,7 @@ var Ri = class extends E {
1094
1095
  this._nTmpA.value = this._tmpA, this._nTmpB.value = this._tmpB, this._nHist.value = this._hist, this._nFast.value = this._fastHist, this._nInternal.value = this._internal, this._nGeom.value = this._geomPrev, this._nData.value = this._dataT, this._nStabRead.value = this._stabPing === 0 ? this._stabB : this._stabA, this.renderer.compute(this._kPre), this.renderer.compute(this._kTa), this.renderer.compute(this._kHf), this.renderer.compute(this._kBlur), this.renderer.compute(this._kPost), this.renderer.compute(this._stabPing === 0 ? this._kTsA : this._kTsB), this._srcRegion.max.set(this.outputTarget.width, this.outputTarget.height), this.renderer.copyTextureToTexture(this._tmpA, this.outputTarget.texture, this._srcRegion), e.setTexture("nrd:output", this.outputTarget.texture), this._stabPing = 1 - this._stabPing, this._needsReset = !1, this._needsReset = !1;
1095
1096
  }
1096
1097
  setSize(e, t) {
1097
- this.outputTarget.setSize(e, t), this.outputTarget.texture.needsUpdate = !0, this.resW.value = e, this.resH.value = t, this._dispatchX = Math.ceil(e / mi), this._dispatchY = Math.ceil(t / mi);
1098
+ this.outputTarget.setSize(e, t), this.outputTarget.texture.needsUpdate = !0, this.resW.value = e, this.resH.value = t, this._dispatchX = Math.ceil(e / yi), this._dispatchY = Math.ceil(t / yi);
1098
1099
  let n = [
1099
1100
  this._dispatchX,
1100
1101
  this._dispatchY,
@@ -1123,15 +1124,15 @@ var Ri = class extends E {
1123
1124
  for (let [e, t] of this._placeholders) e.dispose(), t.dispose();
1124
1125
  this._placeholders.clear();
1125
1126
  }
1126
- }, zi = (e) => H(e.equal(e), e, F(0)).clamp(0, 1e7), Bi = /* @__PURE__ */ Jn("\n fn temporalAccumulate(\n lum: f32,\n prevMean: f32,\n prevMeanSq: f32,\n alpha: f32,\n spatialVariance: f32,\n varianceBoost: f32\n ) -> vec4f {\n\n let newMean = prevMean + ( lum - prevMean ) * alpha;\n let newMeanSq = prevMeanSq + ( lum * lum - prevMeanSq ) * alpha;\n let temporalVariance = max( newMeanSq - newMean * newMean, 0.0 );\n\n return vec4f(\n newMean,\n newMeanSq,\n temporalVariance * varianceBoost,\n spatialVariance * varianceBoost\n );\n\n }\n"), Vi = class extends E {
1127
+ }, Wi = (e) => V(e.equal(e), e, P(0)).clamp(0, 1e7), Gi = /* @__PURE__ */ Qn("\n fn temporalAccumulate(\n lum: f32,\n prevMean: f32,\n prevMeanSq: f32,\n alpha: f32,\n spatialVariance: f32,\n varianceBoost: f32\n ) -> vec4f {\n\n let newMean = prevMean + ( lum - prevMean ) * alpha;\n let newMeanSq = prevMeanSq + ( lum * lum - prevMeanSq ) * alpha;\n let temporalVariance = max( newMeanSq - newMean * newMean, 0.0 );\n\n return vec4f(\n newMean,\n newMeanSq,\n temporalVariance * varianceBoost,\n spatialVariance * varianceBoost\n );\n\n }\n"), Ki = class extends O {
1127
1128
  constructor(e, t = {}) {
1128
1129
  super("VarianceEstimation", {
1129
1130
  ...t,
1130
1131
  executionMode: ge.ALWAYS
1131
- }), this.renderer = e, this.inputTextureName = t.inputTextureName || "pathtracer:color", this.varianceBoost = K(t.varianceBoost ?? 1), this.temporalAlpha = K(t.temporalAlpha ?? .1), this.resW = K(t.width || 1), this.resH = K(t.height || 1), this._colorTexNode = new N();
1132
+ }), this.renderer = e, this.inputTextureName = t.inputTextureName || "pathtracer:color", this.varianceBoost = G(t.varianceBoost ?? 1), this.temporalAlpha = G(t.temporalAlpha ?? .1), this.resW = G(t.width || 1), this.resH = G(t.height || 1), this._colorTexNode = new M();
1132
1133
  let n = t.width || 1, r = t.height || 1;
1133
- this._storageTexA = new M(k, k), this._storageTexA.type = lr, this._storageTexA.format = Q, this._storageTexA.minFilter = X, this._storageTexA.magFilter = X, this._storageTexB = new M(k, k), this._storageTexB.type = lr, this._storageTexB.format = Q, this._storageTexB.minFilter = X, this._storageTexB.magFilter = X, this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0)), this._outputTarget = new Sn(n, r, {
1134
- type: lr,
1134
+ this._storageTexA = new wn(A, A), this._storageTexA.type = pr, this._storageTexA.format = Q, this._storageTexA.minFilter = X, this._storageTexA.magFilter = X, this._storageTexB = new wn(A, A), this._storageTexB.type = pr, this._storageTexB.format = Q, this._storageTexB.minFilter = X, this._storageTexB.magFilter = X, this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0)), this._outputTarget = new Cn(n, r, {
1135
+ type: pr,
1135
1136
  format: Q,
1136
1137
  minFilter: X,
1137
1138
  magFilter: X,
@@ -1143,26 +1144,26 @@ var Ri = class extends E {
1143
1144
  this.on("pathtracer:viewpointChanged", () => this.reset());
1144
1145
  }
1145
1146
  _buildCompute() {
1146
- this._readTexNodeA = new N(), this._readTexNodeB = new N(), this._computeNodeA = this._buildComputeForDirection(this._storageTexA, this._readTexNodeB), this._computeNodeB = this._buildComputeForDirection(this._storageTexB, this._readTexNodeA);
1147
+ this._readTexNodeA = new M(), this._readTexNodeB = new M(), this._computeNodeA = this._buildComputeForDirection(this._storageTexA, this._readTexNodeB), this._computeNodeB = this._buildComputeForDirection(this._storageTexB, this._readTexNodeA);
1147
1148
  }
1148
1149
  _buildComputeForDirection(e, t) {
1149
- let n = this._colorTexNode, r = this.temporalAlpha, i = this.varianceBoost, a = this.resW, s = this.resH, c = Yn("float", 100);
1150
- return wn(() => {
1151
- let l = R.x, u = R.y, d = u.mul(8).add(l), f = I(Y.x).mul(8).sub(1), p = I(Y.y).mul(8).sub(1), m = d.mod(10), h = d.div(10), g = U(n, L(f.add(I(m)).clamp(I(0), I(a).sub(1)), p.add(I(h)).clamp(I(0), I(s).sub(1)))).xyz;
1152
- c.element(d).assign(zi(o(g))), P(d.lessThan(G(36)), () => {
1153
- let e = d.add(G(64)), t = e.mod(10), r = e.div(10), i = U(n, L(f.add(I(t)).clamp(I(0), I(a).sub(1)), p.add(I(r)).clamp(I(0), I(s).sub(1)))).xyz;
1154
- c.element(e).assign(zi(o(i)));
1155
- }), Xn();
1156
- let _ = I(Y.x).mul(8).add(I(l)), v = I(Y.y).mul(8).add(I(u));
1157
- P(_.lessThan(I(a)).and(v.lessThan(I(s))), () => {
1158
- let n = F(0).toVar(), a = F(0).toVar();
1150
+ let n = this._colorTexNode, r = this.temporalAlpha, i = this.varianceBoost, a = this.resW, s = this.resH, c = $n("float", 100);
1151
+ return En(() => {
1152
+ let l = L.x, u = L.y, d = u.mul(8).add(l), f = F(Y.x).mul(8).sub(1), p = F(Y.y).mul(8).sub(1), m = d.mod(10), h = d.div(10), g = H(n, I(f.add(F(m)).clamp(F(0), F(a).sub(1)), p.add(F(h)).clamp(F(0), F(s).sub(1)))).xyz;
1153
+ c.element(d).assign(Wi(o(g))), N(d.lessThan(W(36)), () => {
1154
+ let e = d.add(W(64)), t = e.mod(10), r = e.div(10), i = H(n, I(f.add(F(t)).clamp(F(0), F(a).sub(1)), p.add(F(r)).clamp(F(0), F(s).sub(1)))).xyz;
1155
+ c.element(e).assign(Wi(o(i)));
1156
+ }), er();
1157
+ let _ = F(Y.x).mul(8).add(F(l)), v = F(Y.y).mul(8).add(F(u));
1158
+ N(_.lessThan(F(a)).and(v.lessThan(F(s))), () => {
1159
+ let n = P(0).toVar(), a = P(0).toVar();
1159
1160
  for (let e = -1; e <= 1; e++) for (let t = -1; t <= 1; t++) {
1160
1161
  let r = c.element(u.add(1 + e).mul(10).add(l.add(1 + t)));
1161
1162
  n.addAssign(r), a.addAssign(r.mul(r));
1162
1163
  }
1163
1164
  n.divAssign(9), a.divAssign(9);
1164
- let o = z(a.sub(n.mul(n)), F(0)), s = c.element(u.add(1).mul(10).add(l.add(1))), d = U(t, L(_, v));
1165
- W(e, Gn(G(_), G(v)), Bi(s, d.x, d.y, r, o, i)).toWriteOnly();
1165
+ let o = R(a.sub(n.mul(n)), P(0)), s = c.element(u.add(1).mul(10).add(l.add(1))), d = H(t, I(_, v));
1166
+ U(e, Xn(W(_), W(v)), Gi(s, d.x, d.y, r, o, i)).toWriteOnly();
1166
1167
  });
1167
1168
  })().compute([
1168
1169
  this._dispatchX,
@@ -1208,23 +1209,23 @@ var Ri = class extends E {
1208
1209
  reallocateReservedStorage() {
1209
1210
  this._computeNodeA?.dispose(), this._computeNodeB?.dispose(), this._storageTexA?.dispose(), this._storageTexB?.dispose();
1210
1211
  let e = () => {
1211
- let e = new M(k, k);
1212
- return e.type = lr, e.format = Q, e.minFilter = X, e.magFilter = X, e;
1212
+ let e = new wn(A, A);
1213
+ return e.type = pr, e.format = Q, e.minFilter = X, e.magFilter = X, e;
1213
1214
  };
1214
1215
  this._storageTexA = e(), this._storageTexB = e(), this._buildCompute(), this._compiled = !1;
1215
1216
  }
1216
1217
  dispose() {
1217
1218
  this._computeNodeA?.dispose(), this._computeNodeB?.dispose(), this._storageTexA?.dispose(), this._storageTexB?.dispose(), this._outputTarget?.dispose(), this._colorTexNode?.dispose(), this._readTexNodeA?.dispose(), this._readTexNodeB?.dispose();
1218
1219
  }
1219
- }, Hi = /* @__PURE__ */ Jn("\n fn bilateralWeight(\n centerLum: f32, sLum: f32,\n centerNormal: vec3f, sNormal: vec3f,\n centerDepth: f32, sDepth: f32,\n centerColor: vec3f, sColor: vec3f,\n kernelW: f32,\n sigmaL: f32, phiNorm: f32, phiDep: f32, phiCol: f32\n ) -> f32 {\n\n let lumW = exp( -abs( centerLum - sLum ) / sigmaL );\n // clamp dot to [0,1]: miss-ray normals decode to (-1,-1,-1) with\n // dot=3 → pow saturates to +inf → inf*0 = NaN. See project_tsl_pitfalls.\n // max(phiNorm, 1e-6): pow(0.0, 0.0) is undefined in WGSL and returned NaN on ~12%\n // of pixels when phiNormal was set to 0.\n let normW = pow( clamp( dot( centerNormal, sNormal ), 0.0, 1.0 ), max( phiNorm, 1e-6 ) );\n let depW = exp( -abs( centerDepth - sDepth ) / max( centerDepth * phiDep, 0.001 ) );\n let maxDiff = max( max( abs( centerColor.x - sColor.x ),\n abs( centerColor.y - sColor.y ) ),\n abs( centerColor.z - sColor.z ) );\n let avgLum = max( ( centerLum + sLum ) * 0.5, 0.0001 );\n let colW = exp( -( maxDiff / avgLum ) / max( phiCol, 0.0001 ) );\n return kernelW * lumW * normW * depW * colW;\n\n }\n"), Ui = class extends E {
1220
+ }, qi = /* @__PURE__ */ Qn("\n fn bilateralWeight(\n centerLum: f32, sLum: f32,\n centerNormal: vec3f, sNormal: vec3f,\n centerDepth: f32, sDepth: f32,\n centerColor: vec3f, sColor: vec3f,\n kernelW: f32,\n sigmaL: f32, phiNorm: f32, phiDep: f32, phiCol: f32\n ) -> f32 {\n\n let lumW = exp( -abs( centerLum - sLum ) / sigmaL );\n // clamp dot to [0,1]: miss-ray normals decode to (-1,-1,-1) with\n // dot=3 → pow saturates to +inf → inf*0 = NaN. See project_tsl_pitfalls.\n // max(phiNorm, 1e-6): pow(0.0, 0.0) is undefined in WGSL and returned NaN on ~12%\n // of pixels when phiNormal was set to 0.\n let normW = pow( clamp( dot( centerNormal, sNormal ), 0.0, 1.0 ), max( phiNorm, 1e-6 ) );\n let depW = exp( -abs( centerDepth - sDepth ) / max( centerDepth * phiDep, 0.001 ) );\n let maxDiff = max( max( abs( centerColor.x - sColor.x ),\n abs( centerColor.y - sColor.y ) ),\n abs( centerColor.z - sColor.z ) );\n let avgLum = max( ( centerLum + sLum ) * 0.5, 0.0001 );\n let colW = exp( -( maxDiff / avgLum ) / max( phiCol, 0.0001 ) );\n return kernelW * lumW * normW * depW * colW;\n\n }\n"), Ji = class extends O {
1220
1221
  constructor(e, t = {}) {
1221
1222
  super("BilateralFiltering", {
1222
1223
  ...t,
1223
1224
  executionMode: ge.ALWAYS
1224
- }), this.renderer = e, this.inputTextureName = t.inputTextureName || "asvgf:demodulated", this.normalDepthTextureName = t.normalDepthTextureName || "pathtracer:normalDepth", this.shadingNormalTextureName = t.shadingNormalTextureName || "pathtracer:shadingNormal", this.albedoTextureName = t.albedoTextureName || "pathtracer:albedo", this.varianceTextureName = t.varianceTextureName || "variance:output", this.iterations = t.iterations ?? 4, this.phiColor = K(t.phiColor ?? .5), this.phiNormal = K(t.phiNormal ?? 128), this.phiDepth = K(t.phiDepth ?? .05), this.phiLuminance = K(t.phiLuminance ?? 4), this.spatialVarianceWeight = K(t.spatialVarianceWeight ?? 1), this.stepSizeU = K(1, "int"), this.isLastIterationU = K(0, "int"), this.isFirstIterationU = K(1, "int"), this.resW = K(t.width || 1), this.resH = K(t.height || 1), this._readTexNode = new N(), this._normalDepthTexNode = new N(), this._shadingNormalTexNode = new N(), this._albedoTexNode = new N(), this._varianceTexNode = new N(), this._srcAlphaTexNode = new N();
1225
+ }), this.renderer = e, this.inputTextureName = t.inputTextureName || "asvgf:demodulated", this.normalDepthTextureName = t.normalDepthTextureName || "pathtracer:normalDepth", this.shadingNormalTextureName = t.shadingNormalTextureName || "pathtracer:shadingNormal", this.albedoTextureName = t.albedoTextureName || "pathtracer:albedo", this.varianceTextureName = t.varianceTextureName || "variance:output", this.iterations = t.iterations ?? 4, this.phiColor = G(t.phiColor ?? .5), this.phiNormal = G(t.phiNormal ?? 128), this.phiDepth = G(t.phiDepth ?? .05), this.phiLuminance = G(t.phiLuminance ?? 4), this.spatialVarianceWeight = G(t.spatialVarianceWeight ?? 1), this.stepSizeU = G(1, "int"), this.isLastIterationU = G(0, "int"), this.isFirstIterationU = G(1, "int"), this.resW = G(t.width || 1), this.resH = G(t.height || 1), this._readTexNode = new M(), this._normalDepthTexNode = new M(), this._shadingNormalTexNode = new M(), this._albedoTexNode = new M(), this._varianceTexNode = new M(), this._srcAlphaTexNode = new M();
1225
1226
  let n = t.width || 1, r = t.height || 1;
1226
- this._storageTexA = new M(k, k), this._storageTexA.type = ur, this._storageTexA.format = Q, this._storageTexA.minFilter = X, this._storageTexA.magFilter = X, this._storageTexB = new M(k, k), this._storageTexB.type = ur, this._storageTexB.format = Q, this._storageTexB.minFilter = X, this._storageTexB.magFilter = X, this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0)), this._outputTarget = new Sn(n, r, {
1227
- type: ur,
1227
+ this._storageTexA = new wn(A, A), this._storageTexA.type = mr, this._storageTexA.format = Q, this._storageTexA.minFilter = X, this._storageTexA.magFilter = X, this._storageTexB = new wn(A, A), this._storageTexB.type = mr, this._storageTexB.format = Q, this._storageTexB.minFilter = X, this._storageTexB.magFilter = X, this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0)), this._outputTarget = new Cn(n, r, {
1228
+ type: mr,
1228
1229
  format: Q,
1229
1230
  minFilter: X,
1230
1231
  magFilter: X,
@@ -1263,19 +1264,19 @@ var Ri = class extends E {
1263
1264
  4 / 256,
1264
1265
  1 / 256
1265
1266
  ];
1266
- return wn(() => {
1267
- let y = I(Y.x).mul(8).add(I(R.x)), b = I(Y.y).mul(8).add(I(R.y));
1268
- P(y.lessThan(I(g)).and(b.lessThan(I(_))), () => {
1269
- let x = L(y, b), S = U(t, x), ee = S.xyz, C = U(n, x), te = U(r, x).xyz.mul(2).sub(1), w = C.w, ne = o(ee), re = z(U(i, x).xyz, q(Vr)), T = z(o(re), F(Vr)).toVar(), ie = h.equal(I(1)), ae = (e) => {
1270
- let t = U(a, e);
1271
- return B(t.z, z(t.z, t.w), f);
1272
- }, oe = ie.select(ae(x), S.w.mul(S.w)).toVar(), se = d.mul(Un(z(oe, F(0)))).div(T).add(F(1e-4)), E = q(0).toVar(), D = F(0).toVar(), ce = F(0).toVar();
1267
+ return En(() => {
1268
+ let y = F(Y.x).mul(8).add(F(L.x)), b = F(Y.y).mul(8).add(F(L.y));
1269
+ N(y.lessThan(F(g)).and(b.lessThan(F(_))), () => {
1270
+ let x = I(y, b), S = H(t, x), ee = S.xyz, C = H(n, x), w = H(r, x).xyz.mul(2).sub(1), T = C.w, E = o(ee), te = R(H(i, x).xyz, q(Kr)), D = R(o(te), P(Kr)).toVar(), ne = h.equal(F(1)), re = (e) => {
1271
+ let t = H(a, e);
1272
+ return z(t.z, R(t.z, t.w), f);
1273
+ }, ie = ne.select(re(x), S.w.mul(S.w)).toVar(), ae = d.mul(qn(R(ie, P(0)))).div(D).add(P(1e-4)), O = q(0).toVar(), k = P(0).toVar(), oe = P(0).toVar();
1273
1274
  for (let e = 0; e < 5; e++) for (let i = 0; i < 5; i++) {
1274
- let a = i - 2, s = e - 2, d = v[e * 5 + i], f = y.add(p.mul(a)).clamp(I(0), I(g).sub(1)), m = b.add(p.mul(s)).clamp(I(0), I(_).sub(1)), h = U(t, L(f, m)), x = h.xyz, S = U(n, L(f, m)), C = U(r, L(f, m)).xyz.mul(2).sub(1), re = S.w, T = Hi(ne, o(x), te, C, w, re, ee, x, F(d), se, l, u, c), oe = ie.select(ae(L(f, m)), h.w.mul(h.w));
1275
- E.addAssign(x.mul(T)), D.addAssign(T), ce.addAssign(T.mul(T).mul(z(oe, F(0))));
1275
+ let a = i - 2, s = e - 2, d = v[e * 5 + i], f = y.add(p.mul(a)).clamp(F(0), F(g).sub(1)), m = b.add(p.mul(s)).clamp(F(0), F(_).sub(1)), h = H(t, I(f, m)), x = h.xyz, S = H(n, I(f, m)), C = H(r, I(f, m)).xyz.mul(2).sub(1), te = S.w, D = qi(E, o(x), w, C, T, te, ee, x, P(d), ae, l, u, c), ie = ne.select(re(I(f, m)), h.w.mul(h.w));
1276
+ O.addAssign(x.mul(D)), k.addAssign(D), oe.addAssign(D.mul(D).mul(R(ie, P(0))));
1276
1277
  }
1277
- let O = E.div(z(D, F(1e-4))), k = ce.div(z(D.mul(D), F(1e-8))), le = m.equal(I(1)), ue = le.select(O.mul(re), O), de = le.select(U(s, x).w, Un(z(k, F(0))));
1278
- W(e, Gn(G(y), G(b)), J(ue, de)).toWriteOnly();
1278
+ let se = O.div(R(k, P(1e-4))), A = oe.div(R(k.mul(k), P(1e-8))), ce = m.equal(F(1)), le = ce.select(se.mul(te), se), ue = ce.select(H(s, x).w, qn(R(A, P(0))));
1279
+ U(e, Xn(W(y), W(b)), J(le, ue)).toWriteOnly();
1279
1280
  });
1280
1281
  })().compute([
1281
1282
  this._dispatchX,
@@ -1322,15 +1323,15 @@ var Ri = class extends E {
1322
1323
  reallocateReservedStorage() {
1323
1324
  this._computeNodeA?.dispose(), this._computeNodeB?.dispose(), this._storageTexA?.dispose(), this._storageTexB?.dispose();
1324
1325
  let e = () => {
1325
- let e = new M(k, k);
1326
- return e.type = ur, e.format = Q, e.minFilter = X, e.magFilter = X, e;
1326
+ let e = new wn(A, A);
1327
+ return e.type = mr, e.format = Q, e.minFilter = X, e.magFilter = X, e;
1327
1328
  };
1328
1329
  this._storageTexA = e(), this._storageTexB = e(), this._buildCompute(), this._compiled = !1;
1329
1330
  }
1330
1331
  dispose() {
1331
1332
  this._computeNodeA?.dispose(), this._computeNodeB?.dispose(), this._storageTexA?.dispose(), this._storageTexB?.dispose(), this._outputTarget?.dispose(), this._readTexNode?.dispose(), this._normalDepthTexNode?.dispose(), this._shadingNormalTexNode?.dispose(), this._albedoTexNode?.dispose(), this._varianceTexNode?.dispose(), this._srcAlphaTexNode?.dispose();
1332
1333
  }
1333
- }, Wi = 6e4, Gi = (e) => H(e.equal(e), e, F(0)).clamp(0, 1e7), Ki = (e) => q(Gi(e.x), Gi(e.y), Gi(e.z)), qi = 4, Ji = [
1334
+ }, Yi = 6e4, Xi = (e) => V(e.equal(e), e, P(0)).clamp(0, 1e7), Zi = (e) => q(Xi(e.x), Xi(e.y), Xi(e.z)), Qi = 4, $i = [
1334
1335
  1 / 256,
1335
1336
  4 / 256,
1336
1337
  6 / 256,
@@ -1356,15 +1357,15 @@ var Ri = class extends E {
1356
1357
  6 / 256,
1357
1358
  4 / 256,
1358
1359
  1 / 256
1359
- ], Yi = class extends E {
1360
+ ], ea = class extends O {
1360
1361
  constructor(e, t = {}) {
1361
1362
  super("EdgeAwareFiltering", {
1362
1363
  ...t,
1363
1364
  executionMode: ge.PER_CYCLE
1364
- }), this.renderer = e, this.filterStrength = K(t.filterStrength ?? 1), this.phiLuminance = K(t.phiLuminance ?? 1), this.phiNormal = K(t.phiNormal ?? 64), this.phiDepth = K(t.phiDepth ?? .1), this.iterations = t.atrousIterations ?? t.edgeAtrousIterations ?? 5, this.stepSizeU = K(1, "int"), this.isLastIterationU = K(0, "int"), this.isFirstIterationU = K(1, "int"), this.varianceHistoryU = K(0, "int"), this.resW = K(t.width || 1), this.resH = K(t.height || 1), this._colorTexNode = new N(), this._ndTexNode = new N(), this._snTexNode = new N(), this._albedoTexNode = new N(), this._varTexNode = new N(), this._readTexNode = new N();
1365
+ }), this.renderer = e, this.filterStrength = G(t.filterStrength ?? 1), this.phiLuminance = G(t.phiLuminance ?? 1), this.phiNormal = G(t.phiNormal ?? 64), this.phiDepth = G(t.phiDepth ?? .1), this.iterations = t.atrousIterations ?? t.edgeAtrousIterations ?? 5, this.stepSizeU = G(1, "int"), this.isLastIterationU = G(0, "int"), this.isFirstIterationU = G(1, "int"), this.varianceHistoryU = G(0, "int"), this.resW = G(t.width || 1), this.resH = G(t.height || 1), this._colorTexNode = new M(), this._ndTexNode = new M(), this._snTexNode = new M(), this._albedoTexNode = new M(), this._varTexNode = new M(), this._readTexNode = new M();
1365
1366
  let n = t.width || 1, r = t.height || 1;
1366
- this._demodTex = this._makeStorageTex(), this._storageTexA = this._makeStorageTex(), this._storageTexB = this._makeStorageTex(), this._srcRegion = new er(new Nr(0, 0), new Nr(0, 0)), this.outputTarget = new Sn(n, r, {
1367
- type: lr,
1367
+ this._demodTex = this._makeStorageTex(), this._storageTexA = this._makeStorageTex(), this._storageTexB = this._makeStorageTex(), this._srcRegion = new ir(new Rr(0, 0), new Rr(0, 0)), this.outputTarget = new Cn(n, r, {
1368
+ type: pr,
1368
1369
  format: Q,
1369
1370
  minFilter: X,
1370
1371
  magFilter: X,
@@ -1373,19 +1374,19 @@ var Ri = class extends E {
1373
1374
  }), this._compiled = !1, this._dispatchX = Math.ceil(n / 16), this._dispatchY = Math.ceil(r / 16), this._buildCompute();
1374
1375
  }
1375
1376
  _makeStorageTex() {
1376
- let e = new M(k, k);
1377
- return e.type = lr, e.format = Q, e.minFilter = X, e.magFilter = X, e;
1377
+ let e = new wn(A, A);
1378
+ return e.type = pr, e.format = Q, e.minFilter = X, e.magFilter = X, e;
1378
1379
  }
1379
1380
  _buildCompute() {
1380
1381
  this._computeDemod = this._buildDemod(), this._computeAtrousA = this._buildAtrous(this._storageTexA), this._computeAtrousB = this._buildAtrous(this._storageTexB);
1381
1382
  }
1382
1383
  _buildDemod() {
1383
1384
  let e = this._colorTexNode, t = this._ndTexNode, n = this._albedoTexNode, r = this._demodTex, i = this.resW, a = this.resH;
1384
- return wn(() => {
1385
- let o = I(Y.x).mul(16).add(I(R.x)), s = I(Y.y).mul(16).add(I(R.y));
1386
- P(o.lessThan(I(i)).and(s.lessThan(I(a))), () => {
1387
- let i = L(o, s), a = U(e, i).xyz, c = U(t, i).w.lessThan(F(Wi)), l = U(n, i).xyz, u = H(c, z(l, q(Vr)), q(1)), d = Ki(a.div(u));
1388
- W(r, Gn(G(o), G(s)), J(d, 1)).toWriteOnly();
1385
+ return En(() => {
1386
+ let o = F(Y.x).mul(16).add(F(L.x)), s = F(Y.y).mul(16).add(F(L.y));
1387
+ N(o.lessThan(F(i)).and(s.lessThan(F(a))), () => {
1388
+ let i = I(o, s), a = H(e, i).xyz, c = H(t, i).w.lessThan(P(Yi)), l = H(n, i).xyz, u = V(c, R(l, q(Kr)), q(1)), d = Zi(a.div(u));
1389
+ U(r, Xn(W(o), W(s)), J(d, 1)).toWriteOnly();
1389
1390
  });
1390
1391
  })().compute([
1391
1392
  this._dispatchX,
@@ -1399,19 +1400,19 @@ var Ri = class extends E {
1399
1400
  }
1400
1401
  _buildAtrous(e) {
1401
1402
  let t = this._readTexNode, n = this._colorTexNode, r = this._ndTexNode, i = this._snTexNode, a = this._albedoTexNode, s = this._varTexNode, c = this.filterStrength, l = this.phiLuminance, u = this.phiNormal, d = this.phiDepth, f = this.stepSizeU, p = this.isLastIterationU, m = this.isFirstIterationU, h = this.varianceHistoryU, g = this.resW, _ = this.resH;
1402
- return wn(() => {
1403
- let v = I(Y.x).mul(16).add(I(R.x)), y = I(Y.y).mul(16).add(I(R.y));
1404
- P(v.lessThan(I(g)).and(y.lessThan(I(_))), () => {
1405
- let b = L(v, y), x = U(t, b), S = x.xyz, ee = o(S), C = U(r, b).w, te = U(i, b).xyz.mul(2).sub(1), w = C.lessThan(F(Wi)), ne = H(w, F(1), F(0)), re = U(a, b).xyz, T = H(w, z(re, q(Vr)), q(1)), ie = z(o(T), F(Vr)), ae = m.equal(I(1)), oe = h.lessThan(I(qi)), se = (e) => {
1406
- let t = U(s, e);
1407
- return H(oe, z(t.z, t.w), t.z);
1408
- }, E = ae.select(se(b), x.w.mul(x.w)).toVar(), D = l.mul(Un(z(E, F(0)))).div(ie).add(F(1e-4)), ce = q(0).toVar(), O = F(0).toVar(), k = F(0).toVar();
1403
+ return En(() => {
1404
+ let v = F(Y.x).mul(16).add(F(L.x)), y = F(Y.y).mul(16).add(F(L.y));
1405
+ N(v.lessThan(F(g)).and(y.lessThan(F(_))), () => {
1406
+ let b = I(v, y), x = H(t, b), S = x.xyz, ee = o(S), C = H(r, b).w, w = H(i, b).xyz.mul(2).sub(1), T = C.lessThan(P(Yi)), E = V(T, P(1), P(0)), te = H(a, b).xyz, D = V(T, R(te, q(Kr)), q(1)), ne = R(o(D), P(Kr)), re = m.equal(F(1)), ie = h.lessThan(F(Qi)), ae = (e) => {
1407
+ let t = H(s, e);
1408
+ return V(ie, R(t.z, t.w), t.z);
1409
+ }, O = re.select(ae(b), x.w.mul(x.w)).toVar(), k = l.mul(qn(R(O, P(0)))).div(ne).add(P(1e-4)), oe = q(0).toVar(), se = P(0).toVar(), A = P(0).toVar();
1409
1410
  for (let e = 0; e < 5; e++) for (let n = 0; n < 5; n++) {
1410
- let a = n - 2, s = e - 2, c = Ji[e * 5 + n], l = L(v.add(f.mul(a)).clamp(I(0), I(g).sub(1)), y.add(f.mul(s)).clamp(I(0), I(_).sub(1))), p = U(t, l), m = p.xyz, h = o(m), b = U(r, l).w, x = U(i, l).xyz.mul(2).sub(1), S = H(b.lessThan(F(Wi)), F(1), F(0)), w = ee.sub(h).abs().div(D).negate().exp(), re = Bn(Nn(te, x).clamp(0, 1), u), T = C.sub(b).abs().div(z(C.mul(d), F(.001))).negate().exp(), ie = ne.mul(S), oe = ne.oneMinus().mul(S.oneMinus()), E = ie.add(oe), le = B(F(1), re.mul(T), ie), ue = F(c).mul(w).mul(le).mul(E), de = ae.select(se(l), p.w.mul(p.w));
1411
- ce.addAssign(m.mul(ue)), O.addAssign(ue), k.addAssign(ue.mul(ue).mul(z(de, F(0))));
1411
+ let a = n - 2, s = e - 2, c = $i[e * 5 + n], l = I(v.add(f.mul(a)).clamp(F(0), F(g).sub(1)), y.add(f.mul(s)).clamp(F(0), F(_).sub(1))), p = H(t, l), m = p.xyz, h = o(m), b = H(r, l).w, x = H(i, l).xyz.mul(2).sub(1), S = V(b.lessThan(P(Yi)), P(1), P(0)), T = ee.sub(h).abs().div(k).negate().exp(), te = Wn(Fn(w, x).clamp(0, 1), u), D = C.sub(b).abs().div(R(C.mul(d), P(.001))).negate().exp(), ne = E.mul(S), ie = E.oneMinus().mul(S.oneMinus()), O = ne.add(ie), ce = z(P(1), te.mul(D), ne), le = P(c).mul(T).mul(ce).mul(O), ue = re.select(ae(l), p.w.mul(p.w));
1412
+ oe.addAssign(m.mul(le)), se.addAssign(le), A.addAssign(le.mul(le).mul(R(ue, P(0))));
1412
1413
  }
1413
- let le = ce.div(z(O, F(1e-4))), ue = k.div(z(O.mul(O), F(1e-8))), de = p.equal(I(1)), A = U(n, b).xyz, fe = B(A, le.mul(T), c), pe = de.select(fe, le), me = de.select(U(n, b).w, Un(z(ue, F(0))));
1414
- W(e, Gn(G(v), G(y)), J(pe, me)).toWriteOnly();
1414
+ let ce = oe.div(R(se, P(1e-4))), le = A.div(R(se.mul(se), P(1e-8))), ue = p.equal(F(1)), de = H(n, b).xyz, fe = z(de, ce.mul(D), c), pe = ue.select(fe, ce), me = ue.select(H(n, b).w, qn(R(le, P(0))));
1415
+ U(e, Xn(W(v), W(y)), J(pe, me)).toWriteOnly();
1415
1416
  });
1416
1417
  })().compute([
1417
1418
  this._dispatchX,
@@ -1469,175 +1470,589 @@ var Ri = class extends E {
1469
1470
  dispose() {
1470
1471
  this._computeDemod?.dispose(), this._computeAtrousA?.dispose(), this._computeAtrousB?.dispose(), this._demodTex?.dispose(), this._storageTexA?.dispose(), this._storageTexB?.dispose(), this.outputTarget?.dispose(), this._colorTexNode?.dispose(), this._ndTexNode?.dispose(), this._snTexNode?.dispose(), this._albedoTexNode?.dispose(), this._varTexNode?.dispose(), this._readTexNode?.dispose();
1471
1472
  }
1472
- }, Xi = {
1473
+ }, ta = {
1473
1474
  autoExposure: !1,
1475
+ autoExposureMetering: "center",
1476
+ autoExposureStrength: .3,
1474
1477
  autoExposureKeyValue: .18,
1475
- autoExposureMinExposure: .1,
1476
- autoExposureMaxExposure: 20,
1478
+ autoExposureMinExposure: 2 ** -8,
1479
+ autoExposureMaxExposure: 2 ** 8,
1477
1480
  autoExposureAdaptSpeedBright: 3,
1478
- autoExposureAdaptSpeedDark: .5
1479
- }, Zi = 256, Qi = -8, $i = 6 - Qi, ea = $i / Zi, ta = 1e4, na = /* @__PURE__ */ Jn("\n fn adaptExposure(\n geoMean: f32,\n prevExposure: f32,\n keyValue: f32,\n minExp: f32,\n maxExp: f32,\n speedBright: f32,\n speedDark: f32,\n dt: f32,\n isFirstFrame: f32\n ) -> vec4f {\n\n let targetExp = clamp( keyValue / max( geoMean, 0.001 ), minExp, maxExp );\n var newExposure = targetExp;\n\n // Temporal smoothing (skip on first frame)\n if ( isFirstFrame < 0.5 ) {\n\n // Asymmetric speed: brighter scenes adapt faster\n let speed = select( speedDark, speedBright, targetExp < prevExposure );\n let alpha = 1.0 - exp( -dt * speed );\n newExposure = mix( prevExposure, targetExp, alpha );\n\n }\n\n return vec4f( newExposure, geoMean, targetExp, 1.0 );\n\n }\n"), ra = class extends E {
1481
+ autoExposureAdaptSpeedDark: 1
1482
+ }, na = [
1483
+ "average",
1484
+ "center",
1485
+ "spot"
1486
+ ], ra = 64, ia = 8, aa = 8, oa = 256, sa = -16, ca = (12 - sa) / oa, la = 2 ** -24, ua = 65536, da = 256, fa = 128, pa = 1.5, ma = .01, ha = .06, ga = .25, _a = 4, va = .3, ya = 1.5, ba = 3, xa = [
1487
+ .2126,
1488
+ .7152,
1489
+ .0722
1490
+ ];
1491
+ function Sa(e, t, n, r, i) {
1492
+ let a = t - e;
1493
+ if (a === 0 || !(n > 0)) return e;
1494
+ let o = Math.max(a < 0 ? r : i, .001);
1495
+ if (n === Infinity) return t;
1496
+ let s = Math.min(o * n, Math.abs(a) * (1 - Math.exp(-o * n / pa)));
1497
+ return e + Math.sign(a) * s;
1498
+ }
1499
+ function Ca(e, t, n) {
1500
+ let r = Math.abs(e);
1501
+ return e * (r <= ya ? n : r >= ba ? 1 : n + (1 - n) * (r - ya) / (ba - ya)) + n * (t - e);
1502
+ }
1503
+ function wa(e, t) {
1504
+ if (!e) return t.fromArray(xa);
1505
+ let n = new yr().set(...e).invert().elements;
1506
+ return t.set(xa[0] * n[0] + xa[1] * n[1] + xa[2] * n[2], xa[0] * n[3] + xa[1] * n[4] + xa[2] * n[5], xa[0] * n[6] + xa[1] * n[7] + xa[2] * n[8]);
1507
+ }
1508
+ var Ta = (e) => e < 16 ? 1 : e < 64 ? 4 : 16, Ea = class extends O {
1480
1509
  constructor(e, t = {}) {
1481
1510
  super("AutoExposure", {
1482
1511
  ...t,
1483
1512
  executionMode: ge.ALWAYS
1484
- }), this.renderer = e, this.REDUCTION_SIZE = 64, this.keyValueU = K(t.keyValue ?? Xi.autoExposureKeyValue), this.minExposureU = K(t.minExposure ?? Xi.autoExposureMinExposure), this.maxExposureU = K(t.maxExposure ?? Xi.autoExposureMaxExposure), this.adaptSpeedBrightU = K(t.adaptSpeedBright ?? Xi.autoExposureAdaptSpeedBright), this.adaptSpeedDarkU = K(t.adaptSpeedDark ?? Xi.autoExposureAdaptSpeedDark), this.epsilonU = K(t.epsilon ?? 1e-4), this.deltaTimeU = K(1 / 60), this.isFirstFrameU = K(1), this.previousExposureU = K(t.initialExposure ?? 1), this.lowPercentileU = K(t.lowPercentile ?? .1), this.highPercentileU = K(t.highPercentile ?? .9), this.centerWeightU = K(t.centerWeight ?? 8), this.inputResW = K(1), this.inputResH = K(1), this._inputTexNode = new N(), this._reductionReadTexNode = new N(), this.currentExposure = t.initialExposure ?? 1, this.currentLuminance = .18, this.targetExposure = 1, this.lastTime = performance.now(), this.isFirstFrame = !0, this._pendingReadback = !1, this._readbackGeneration = 0, this._initRenderTargets(), this._buildCompute();
1485
- }
1486
- _initRenderTargets() {
1487
- let e = {
1488
- type: lr,
1489
- format: Q,
1490
- minFilter: Z,
1491
- magFilter: Z,
1492
- depthBuffer: !1,
1493
- stencilBuffer: !1
1494
- };
1495
- this._downsampleTarget = new Sn(this.REDUCTION_SIZE, this.REDUCTION_SIZE, e), this._downsampleStorageTex = new M(this.REDUCTION_SIZE, this.REDUCTION_SIZE), this._downsampleStorageTex.type = lr, this._downsampleStorageTex.format = Q, this._downsampleStorageTex.minFilter = Z, this._downsampleStorageTex.magFilter = Z, this._reductionStorageTex = new M(1, 1), this._reductionStorageTex.type = lr, this._reductionStorageTex.format = Q, this._reductionStorageTex.minFilter = Z, this._reductionStorageTex.magFilter = Z, this._reductionReadTarget = new Sn(1, 1, e), this._adaptationResult = Mn(1, "vec4"), this._readbackBuffer = new xn(16), this._readbackBuffer.name = "AutoExposureAdaptation", this._histogramBuffer = Mn(Zi, "uint").toAtomic();
1496
- }
1497
- _buildCompute() {
1498
- this._buildDownsampleCompute(), this._buildHistogramCompute(), this._buildHistogramAnalyzeCompute(), this._buildAdaptationCompute();
1499
- }
1500
- _buildDownsampleCompute() {
1501
- let e = this._inputTexNode, t = this._downsampleStorageTex, n = this.epsilonU, r = this.inputResW, i = this.inputResH;
1502
- this._downsampleComputeNode = wn(() => {
1503
- let a = I(Y.x).mul(8).add(I(R.x)), s = I(Y.y).mul(8).add(I(R.y)), c = r.div(F(64)), l = i.div(F(64)), u = F(a).mul(c), d = F(s).mul(l), f = F(0).toVar(), p = F(0).toVar();
1504
- for (let t = 0; t < 4; t++) for (let r = 0; r < 4; r++) {
1505
- let i = o(U(e, L(I(u.add(F((r + .5) / 4).mul(c))), I(d.add(F((t + .5) / 4).mul(l))))).xyz);
1506
- P(i.greaterThan(n), () => {
1507
- f.addAssign(i.add(n).log()), p.addAssign(1);
1513
+ }), this.renderer = e, this.metering = t.metering ?? ta.autoExposureMetering, this.meteringPoint = new Rr(.5, .5), this.keyValue = t.keyValue ?? ta.autoExposureKeyValue, this.minExposure = t.minExposure ?? ta.autoExposureMinExposure, this.maxExposure = t.maxExposure ?? ta.autoExposureMaxExposure, this.adaptSpeedBright = t.adaptSpeedBright ?? ta.autoExposureAdaptSpeedBright, this.adaptSpeedDark = t.adaptSpeedDark ?? ta.autoExposureAdaptSpeedDark, this.centerWeight = t.centerWeight ?? 8, this.strength = t.strength ?? ta.autoExposureStrength, this.instant = !1, this.holdSamples = 0, this.onChange = null, this._lowU = G(t.lowPercentile ?? .1), this._highU = G(t.highPercentile ?? .9), this._falloffU = G(new Rr()), this._pointU = G(new Rr(.5, .5)), this._lumWeightsU = G(new $().fromArray(xa)), this._widthU = G(1, "int"), this._heightU = G(1, "int"), this._strideU = G(1, "int"), this._gridXU = G(ra, "int"), this._gridYU = G(ra, "int"), this._inputNode = new M(), this._workingMatrix = void 0, this._histogram = Pn(oa, "uint").toAtomic(), this._result = Pn(1, "vec4"), this._readback = new Sn(16), this._readback.name = "AutoExposure", this._kernels = [this._buildTileKernel(), this._buildResolveKernel()], this._compensation = 1, this._exposureEV = 0, this._targetEV = null, this._viewEV = null, this._roomEV = null, this._clock = 0, this._movingUntil = -1, this._viewMoves = 0, this._landed = null, this._meteredLog2 = null, this._snap = !0, this._lastUpdate = null, this._accumulating = !1, this._emittedEV = null, this._pending = null, this._generation = 0, this._restarts = 0, this._meteredAt = {
1514
+ restarts: -1,
1515
+ samples: -1
1516
+ }, this._stale = !1, this._disposed = !1;
1517
+ }
1518
+ _buildTileKernel() {
1519
+ let e = this._inputNode, t = this._histogram, n = this._widthU, r = this._heightU, i = this._strideU, a = this._gridXU, o = this._gridYU, s = this._lumWeightsU, c = this._falloffU, l = this._pointU;
1520
+ return En(() => {
1521
+ let u = L.y.mul(W(aa)).add(L.x), d = F(Y.x), f = F(Y.y), p = d.mul(n).div(a).toVar(), m = d.add(F(1)).mul(n).div(a).toVar(), h = f.mul(r).div(o).toVar(), g = f.add(F(1)).mul(r).div(o).toVar(), _ = i.mul(F(aa)), v = P(0).toVar(), y = P(0).toVar();
1522
+ Dn({
1523
+ start: h.add(F(L.y)),
1524
+ end: g,
1525
+ type: "int",
1526
+ condition: "<",
1527
+ update: _,
1528
+ name: "py"
1529
+ }, ({ py: t }) => {
1530
+ Dn({
1531
+ start: p.add(F(L.x)),
1532
+ end: m,
1533
+ type: "int",
1534
+ condition: "<",
1535
+ update: _,
1536
+ name: "px"
1537
+ }, ({ px: n }) => {
1538
+ let r = H(e, I(n, t)), i = Fn(r.xyz, s).toVar(), a = Rn(i).bitAnd(W(2139095040)).notEqual(W(2139095040)), o = r.w.clamp(0, 1);
1539
+ v.addAssign(V(a, i.clamp(0, 1e6), P(0)).mul(o)), y.addAssign(o);
1508
1540
  });
1509
- }
1510
- W(t, Gn(G(a), G(s)), J(f, p, 0, 1)).toWriteOnly();
1541
+ });
1542
+ let b = $n("float", aa * aa), x = $n("float", aa * aa);
1543
+ b.element(u).assign(v), x.element(u).assign(y), er();
1544
+ for (let e = aa * aa >> 1; e > 0; e >>= 1) N(u.lessThan(W(e)), () => {
1545
+ b.element(u).addAssign(b.element(u.add(W(e)))), x.element(u).addAssign(x.element(u.add(W(e))));
1546
+ }), er();
1547
+ N(u.equal(W(0)), () => {
1548
+ let e = b.element(W(0)).toVar(), i = x.element(W(0)).toVar(), a = (e) => e.div(_).mul(F(aa)).add(Hn(e.mod(_), F(aa))), o = P(a(m.sub(p)).mul(a(g.sub(h))));
1549
+ N(i.greaterThan(0).and(e.greaterThan(i.mul(la))), () => {
1550
+ let a = W(Vn(e.div(i)).sub(sa).div(ca).floor().clamp(0, oa - 1)), s = K(P(p.add(m)).div(P(n)), P(h.add(g)).div(P(r))).mul(.5).sub(l), u = W(In(Fn(s.mul(s), c).negate()).mul(i.div(R(o, 1))).mul(ua).add(.5));
1551
+ N(u.greaterThan(W(0)), () => {
1552
+ jn(t.element(a), u);
1553
+ });
1554
+ });
1555
+ });
1511
1556
  })().compute([
1512
- 64 / 8,
1513
- 64 / 8,
1557
+ ra,
1558
+ ra,
1514
1559
  1
1515
1560
  ], [
1516
- 8,
1517
- 8,
1561
+ aa,
1562
+ aa,
1518
1563
  1
1519
1564
  ]);
1520
1565
  }
1521
- _buildHistogramCompute() {
1522
- let e = this._downsampleTarget.texture, t = this._histogramBuffer, n = this.centerWeightU;
1523
- this._histogramComputeNode = wn(() => {
1524
- let r = R.x;
1525
- jn(t.element(r), G(0)), Xn();
1526
- for (let i = 0; i < 16; i++) {
1527
- let a = r.mul(16).add(i), o = a.mod(64), s = a.div(64), c = U(e, L(I(o), I(s))), l = c.x, u = c.y;
1528
- P(u.greaterThan(0), () => {
1529
- let e = G(l.div(u).sub(F(Qi)).div(F($i)).mul(F(Zi)).floor().clamp(0, F(Zi - 1))), r = F(o).add(.5).div(F(64)), i = F(s).add(.5).div(F(64)), a = r.sub(.5), c = i.sub(.5), d = G(a.mul(a).add(c.mul(c)).mul(n).negate().exp().mul(F(ta)));
1530
- kn(t.element(e), d);
1531
- });
1566
+ _buildResolveKernel() {
1567
+ let e = this._histogram, t = this._result, n = this._lowU, r = this._highU;
1568
+ return En(() => {
1569
+ let i = L.x, a = P(Mn(e.element(i))).toVar();
1570
+ Nn(e.element(i), W(0));
1571
+ let o = $n("float", oa), s = $n("float", oa);
1572
+ o.element(i).assign(a), er();
1573
+ for (let e = 1; e < oa; e <<= 1) {
1574
+ let t = o.element(i).toVar();
1575
+ N(i.greaterThanEqual(W(e)), () => {
1576
+ t.addAssign(o.element(i.sub(W(e))));
1577
+ }), er(), o.element(i).assign(t), er();
1532
1578
  }
1579
+ let c = o.element(W(oa - 1)).toVar(), l = o.element(i).toVar();
1580
+ er();
1581
+ let u = R(Hn(l, c.mul(r)).sub(R(l.sub(a), c.mul(n))), 0);
1582
+ o.element(i).assign(u), s.element(i).assign(u.mul(P(i).add(.5).mul(ca).add(sa))), er();
1583
+ for (let e = oa >> 1; e > 0; e >>= 1) N(i.lessThan(W(e)), () => {
1584
+ o.element(i).addAssign(o.element(i.add(W(e)))), s.element(i).addAssign(s.element(i.add(W(e))));
1585
+ }), er();
1586
+ N(i.equal(W(0)), () => {
1587
+ let e = o.element(W(0));
1588
+ t.element(W(0)).assign(J(s.element(W(0)).div(R(e, 1e-6)), c.div(ua), e.div(ua), 1));
1589
+ });
1533
1590
  })().compute([
1534
1591
  1,
1535
1592
  1,
1536
1593
  1
1537
1594
  ], [
1538
- 256,
1595
+ oa,
1539
1596
  1,
1540
1597
  1
1541
1598
  ]);
1542
1599
  }
1543
- _buildHistogramAnalyzeCompute() {
1544
- let e = this._histogramBuffer, t = this._reductionStorageTex, n = this.lowPercentileU, r = this.highPercentileU;
1545
- this._histogramAnalyzeNode = wn(() => {
1546
- let i = F(0).toVar();
1547
- Tn(Zi, ({ i: t }) => {
1548
- i.addAssign(F(An(e.element(t))));
1600
+ setupEventListeners() {
1601
+ this.on("pipeline:reset", () => this._restarts++), this.on("pipeline:lightingChanged", () => this.resetHistory());
1602
+ }
1603
+ render(e) {
1604
+ if (!this.enabled) return;
1605
+ let t = e.getState("pathtracer:samples") ?? 0;
1606
+ if (this._accumulating = t >= 2, !this._pending) {
1607
+ let n = this._meteredAt, r = this._stale || this._targetEV === null || n.restarts !== this._restarts || t - n.samples >= Ta(t), i = t < this.holdSamples && this._targetEV !== null && !this._stale;
1608
+ r && !i && this._meter(e, t);
1609
+ }
1610
+ e.setState("autoexposure:value", this.renderer.toneMappingExposure), e.setState("autoexposure:avgLuminance", this.luminance);
1611
+ }
1612
+ async meter(e = this.context) {
1613
+ for (; this._pending;) await this._pending;
1614
+ let t = this._meter(e, e?.getState("pathtracer:samples") ?? 0);
1615
+ return t ? await t : null;
1616
+ }
1617
+ _meter(e, t) {
1618
+ let n = e?.getTexture("pathtracer:color"), r = n?.image?.width | 0, i = n?.image?.height | 0;
1619
+ if (!n || r < 1 || i < 1 || this._disposed) return null;
1620
+ this._meteredAt.restarts = this._restarts, this._meteredAt.samples = t, this._stale = !1;
1621
+ let a = nt();
1622
+ a !== this._workingMatrix && (this._workingMatrix = a, wa(a, this._lumWeightsU.value));
1623
+ let o = Math.min(ra, Math.max(1, Math.floor(r / ia))), s = Math.min(ra, Math.max(1, Math.floor(i / ia))), c = r / o * (i / s);
1624
+ this._gridXU.value = o, this._gridYU.value = s, this._kernels[0].dispatchSize = [
1625
+ o,
1626
+ s,
1627
+ 1
1628
+ ], this._strideU.value = Math.max(1, Math.round(Math.sqrt(c / da))), this._widthU.value = r, this._heightU.value = i, this._updateMeteringPattern(r / i), this._inputNode.value = n, this.renderer.compute(this._kernels);
1629
+ let l = this._generation, u = {
1630
+ restarts: this._restarts,
1631
+ moves: this._viewMoves
1632
+ }, d = this.renderer.getArrayBufferAsync(this._result.value, this._readback).then((e) => {
1633
+ let t = e?.buffer ? new Float32Array(e.buffer.slice(0, 16)) : null;
1634
+ return this._readback.release(), t && l === this._generation && !this._disposed ? this._applyMetering(t, u) : null;
1635
+ }, () => (!this._disposed && this._readback._mapped && this._readback.release(), null)).finally(() => {
1636
+ this._pending === d && (this._pending = null);
1637
+ });
1638
+ return this._pending = d, d;
1639
+ }
1640
+ _updateMeteringPattern(e) {
1641
+ let t = this._falloffU.value, n = this._pointU.value;
1642
+ if (this.metering === "average") t.set(0, 0);
1643
+ else if (this.metering === "spot") {
1644
+ t.set(fa * e * e, fa), n.copy(this.meteringPoint);
1645
+ return;
1646
+ } else t.set(this.centerWeight, this.centerWeight);
1647
+ n.set(.5, .5);
1648
+ }
1649
+ _applyMetering(e, t = this._landed) {
1650
+ let [n, r, i] = e;
1651
+ if (!this.enabled || !(r > 0 && i > 0) || !Number.isFinite(n)) return null;
1652
+ let a = this._viewEV;
1653
+ this._meteredLog2 = n, this._viewEV = Math.log2(this.keyValue) - n, this._roomEV === null ? this._roomEV = this._viewEV : t?.moves === this._landed?.moves ? this._roomEV += this._viewEV - a : this._movingUntil = this._clock + va, this._landed = t;
1654
+ let o = this._aim(), s = this._targetEV === null || Math.abs(o - this._targetEV) > ma;
1655
+ return this._targetEV = o, (s || this.settling) && this.onChange?.(), n;
1656
+ }
1657
+ update(e = performance.now()) {
1658
+ let t = this._lastUpdate === null ? 0 : Math.min((e - this._lastUpdate) / 1e3, ga), n = this.advance(t, this._accumulating);
1659
+ return this._lastUpdate = this.settling || this._clock <= this._movingUntil ? e : null, n;
1660
+ }
1661
+ advance(e, t = !1) {
1662
+ if (!this.enabled || this._targetEV === null) return !1;
1663
+ e > 0 && e !== Infinity && (this._clock += e, this._clock <= this._movingUntil && (this._roomEV += (this._viewEV - this._roomEV) * (1 - Math.exp(-Math.min(e, ga) / _a)), this._targetEV = this._aim()));
1664
+ let n = this._exposureEV;
1665
+ return this._snap || this.instant ? (this._exposureEV = this._targetEV, this._snap = !1) : (this._exposureEV = t ? n + (this._targetEV - n) * (1 - Math.exp(-e / ha)) : Sa(n, this._targetEV, e, this.adaptSpeedBright, this.adaptSpeedDark), Math.abs(this._targetEV - this._exposureEV) <= ma && (this._exposureEV = this._targetEV)), this._exposureEV === n ? !1 : (this._apply(), !0);
1666
+ }
1667
+ _inRange(e) {
1668
+ return Math.min(Math.max(e, Math.log2(this.minExposure)), Math.log2(this.maxExposure));
1669
+ }
1670
+ _aim() {
1671
+ return this._inRange(Ca(this._roomEV, this._viewEV, this.strength));
1672
+ }
1673
+ noteViewChanged() {
1674
+ this._viewMoves++;
1675
+ }
1676
+ get settling() {
1677
+ return this.enabled && this._targetEV !== null && (this._snap || Math.abs(this._targetEV - this._exposureEV) > 0);
1678
+ }
1679
+ get wantsMetering() {
1680
+ return this.enabled && !this._pending && (this._stale || this._targetEV === null);
1681
+ }
1682
+ _apply() {
1683
+ this.renderer.toneMappingExposure = this.enabled ? 2 ** this._exposureEV * this._compensation : this._compensation, !(!this.enabled || this._emittedEV !== null && Math.abs(this._exposureEV - this._emittedEV) < .005) && (this._emittedEV = this._exposureEV, this.emit("autoexposure:updated", {
1684
+ exposure: this.renderer.toneMappingExposure,
1685
+ autoExposure: this.getExposure(),
1686
+ targetExposure: this._targetEV === null ? null : 2 ** this._targetEV,
1687
+ luminance: this.luminance
1688
+ }));
1689
+ }
1690
+ setEnabled(e, t = this._compensation) {
1691
+ if (this._compensation = t, e === this.enabled) {
1692
+ this._apply();
1693
+ return;
1694
+ }
1695
+ this.enabled = e, this._emittedEV = null, e && (this.resetHistory(), this._exposureEV = 0), this._apply(), this.onChange?.();
1696
+ }
1697
+ setCompensation(e) {
1698
+ this._compensation = e, this._apply();
1699
+ }
1700
+ resetHistory() {
1701
+ this._generation++, this._targetEV = null, this._viewEV = null, this._roomEV = null, this._landed = null, this._meteredLog2 = null, this._snap = !0;
1702
+ }
1703
+ getExposure() {
1704
+ return 2 ** this._exposureEV;
1705
+ }
1706
+ get luminance() {
1707
+ return this._meteredLog2 === null ? null : 2 ** this._meteredLog2;
1708
+ }
1709
+ getLuminance() {
1710
+ return this.luminance;
1711
+ }
1712
+ updateParameters(e) {
1713
+ let t = e.metering;
1714
+ t !== void 0 && na.includes(t) && (this.metering = t), e.meteringPoint && this.meteringPoint.set(e.meteringPoint.x, e.meteringPoint.y);
1715
+ for (let t of [
1716
+ "keyValue",
1717
+ "minExposure",
1718
+ "maxExposure",
1719
+ "adaptSpeedBright",
1720
+ "adaptSpeedDark",
1721
+ "centerWeight",
1722
+ "strength"
1723
+ ]) e[t] !== void 0 && (this[t] = e[t]);
1724
+ e.lowPercentile !== void 0 && (this._lowU.value = e.lowPercentile), e.highPercentile !== void 0 && (this._highU.value = e.highPercentile), this._stale = !0, this._meteredLog2 !== null && this._applyMetering([
1725
+ this._meteredLog2,
1726
+ 1,
1727
+ 1
1728
+ ]), this.onChange?.();
1729
+ }
1730
+ reset() {}
1731
+ setSize() {}
1732
+ dispose() {
1733
+ this._disposed = !0, this.onChange = null;
1734
+ for (let e of this._kernels) e.dispose();
1735
+ this._readback.dispose(), this._inputNode.dispose();
1736
+ }
1737
+ }, Da = {
1738
+ localExposure: !1,
1739
+ localExposureHighlightContrast: .6,
1740
+ localExposureShadowContrast: 1,
1741
+ localExposureDetailStrength: 1
1742
+ }, Oa = 128, ka = (Oa / 2) ** 2, Aa = 32, ja = -16, Ma = 16, Na = -40, Pa = 40, Fa = 256, Ia = 32, La = .6, Ra = 50, za = Math.log2(.18), Ba = 2 ** -24, Va = Math.ceil(Se / Oa), Ha = Math.ceil(Se / Ia), Ua = [
1743
+ .2126,
1744
+ .7152,
1745
+ .0722
1746
+ ], Wa = (e) => e < 16 ? 1 : e < 64 ? 4 : 16, Ga = (e, t, n) => Math.min(Math.max(e, t), n);
1747
+ function Ka(e, t, n, r, i, a, o) {
1748
+ let s = Math.min(Math.log2(Math.max(a, Ba)), Pa), c = e[6], l = e[7], u = Ga(r * e[2] - .5, 0, c - 1), d = Ga(i * e[3] - .5, 0, l - 1), f = Math.floor(u), p = Math.floor(d), m = Math.min(f + 1, c - 1), h = Math.min(p + 1, l - 1), g = u - f, _ = d - p, v = (e) => n[e * c + f] + (n[e * c + m] - n[e * c + f]) * g, y = v(p) + (v(h) - v(p)) * _, b = e[4], x = e[5], S = Ga(r * e[0] - .5, 0, b - 1), ee = Ga(i * e[1] - .5, 0, x - 1), C = Ga((s + e[8] - ja) / (Ma - ja), 0, 1) * (Aa - 1), w = Math.floor(S), T = Math.floor(ee), E = Math.floor(C), te = S - w, D = ee - T, ne = C - E, re = 0, ie = 0;
1749
+ for (let e = 0; e < 8; e++) {
1750
+ let n = e & 1, r = e >> 1 & 1, i = e >> 2, a = (n ? te : 1 - te) * (r ? D : 1 - D) * (i ? ne : 1 - ne), o = ((Math.min(T + r, x - 1) * b + Math.min(w + n, b - 1)) * Aa + Math.min(E + i, Aa - 1)) * 2;
1751
+ re += t[o] * a, ie += t[o + 1] * a;
1752
+ }
1753
+ let ae = ie * ka < .001 ? y : re / ie, O = ae + (y - ae) * e[12] + o, k = s + o, oe = O > e[13] ? e[9] : e[10];
1754
+ return 2 ** (e[13] + (O - e[13]) * oe + (k - O) * e[11] - k);
1755
+ }
1756
+ var qa = `
1757
+ @group(1) @binding(0) var<storage, read> leGrid: array<vec2<f32>>;
1758
+ @group(1) @binding(1) var<storage, read> leBlur: array<f32>;
1759
+ @group(1) @binding(2) var<uniform> le: array<vec4<f32>, 4>;
1760
+
1761
+ fn rayzee_gain( uv: vec2<f32>, linear: vec3<f32>, exposure: f32 ) -> f32 {
1762
+ let logL = min( log2( max( dot( linear, vec3<f32>( ${Ua.join(", ")} ) ), ${Ba} ) ), ${Pa}.0 );
1763
+ let logExposure = log2( exposure );
1764
+
1765
+ let bs = vec2<i32>( le[ 1 ].zw );
1766
+ let bp = clamp( uv * le[ 0 ].zw - 0.5, vec2<f32>( 0.0 ), vec2<f32>( bs - 1 ) );
1767
+ let b0 = vec2<i32>( floor( bp ) );
1768
+ let b1 = min( b0 + 1, bs - 1 );
1769
+ let bf = bp - floor( bp );
1770
+ let top = mix( leBlur[ b0.y * bs.x + b0.x ], leBlur[ b0.y * bs.x + b1.x ], bf.x );
1771
+ let bottom = mix( leBlur[ b1.y * bs.x + b0.x ], leBlur[ b1.y * bs.x + b1.x ], bf.x );
1772
+ let blurred = mix( top, bottom, bf.y );
1773
+
1774
+ let cs = vec2<i32>( le[ 1 ].xy );
1775
+ let gp = clamp( uv * le[ 0 ].xy - 0.5, vec2<f32>( 0.0 ), vec2<f32>( cs - 1 ) );
1776
+ let gz = clamp( ( logL + le[ 2 ].x - (${ja}.0) ) / ${Ma - ja}.0, 0.0, 1.0 ) * ${Aa - 1}.0;
1777
+ let g0 = vec3<i32>( vec2<i32>( floor( gp ) ), i32( floor( gz ) ) );
1778
+ let gf = vec3<f32>( gp - floor( gp ), gz - floor( gz ) );
1779
+ var acc = vec2<f32>( 0.0 );
1780
+ for ( var k = 0; k < 8; k++ ) {
1781
+ let d = vec3<i32>( k & 1, ( k >> 1u ) & 1, k >> 2u );
1782
+ let wv = select( 1.0 - gf, gf, d == vec3<i32>( 1 ) );
1783
+ let c = min( g0 + d, vec3<i32>( cs - 1, ${Aa - 1} ) );
1784
+ acc += leGrid[ ( c.y * cs.x + c.x ) * ${Aa} + c.z ] * ( wv.x * wv.y * wv.z );
1785
+ }
1786
+
1787
+ let bilateral = select( acc.x / acc.y, blurred, acc.y * ${ka}.0 < 1e-3 );
1788
+ let base = mix( bilateral, blurred, le[ 3 ].x ) + logExposure;
1789
+ let y = logL + logExposure;
1790
+ let contrast = select( le[ 2 ].z, le[ 2 ].y, base > le[ 3 ].y );
1791
+ return exp2( le[ 3 ].y + ( base - le[ 3 ].y ) * contrast + ( y - base ) * le[ 2 ].w - y );
1792
+ }
1793
+ `, Ja = class extends O {
1794
+ constructor(e, t = {}) {
1795
+ super("LocalExposure", {
1796
+ ...t,
1797
+ executionMode: ge.ALWAYS
1798
+ }), this.renderer = e, this.highlightContrast = t.highlightContrast ?? Da.localExposureHighlightContrast, this.shadowContrast = t.shadowContrast ?? Da.localExposureShadowContrast, this.detailStrength = t.detailStrength ?? Da.localExposureDetailStrength, this.onChange = null, this._grid = Pn(Va * Va * Aa, "vec2"), this._blur = Pn(Ha * Ha, "float"), this._blurTmp = Pn(Ha * Ha, "float"), this._inputNode = new M(), this._widthU = G(1, "int"), this._heightU = G(1, "int"), this._cellsXU = G(1, "int"), this._blurWU = G(1, "int"), this._blurHU = G(1, "int"), this._radiusU = G(1), this._logExposureU = G(0), this._p = [
1799
+ new zr(),
1800
+ new zr(),
1801
+ new zr(),
1802
+ new zr()
1803
+ ].map((e) => G(e)), this._params = new Float32Array(16), this._kernels = [
1804
+ this._buildGridKernel(),
1805
+ this._buildBlurSourceKernel(),
1806
+ this._buildBlurKernel(this._blur, this._blurTmp, !0),
1807
+ this._buildBlurKernel(this._blurTmp, this._blur, !1)
1808
+ ], this._built = !1, this._restarts = 0, this._builtAt = {
1809
+ restarts: -1,
1810
+ samples: -1
1811
+ }, this._stale = !1, this._paramsBuffer = null, this._disposed = !1;
1812
+ }
1813
+ _buildGridKernel() {
1814
+ let e = this._inputNode, t = this._grid, n = this._widthU, r = this._heightU, i = this._cellsXU, a = this._logExposureU, o = J(...Ua, 0).xyz;
1815
+ return En(() => {
1816
+ let s = L.y.mul(W(16)).add(L.x), c = $n("uint", Aa).toAtomic(), l = $n("uint", Aa).toAtomic();
1817
+ N(s.lessThan(W(Aa)), () => {
1818
+ Nn(c.element(s), W(0)), Nn(l.element(s), W(0));
1819
+ }), er();
1820
+ let u = F(Y.x).mul(F(Oa)).add(F(L.x).mul(F(8))), d = F(Y.y).mul(F(Oa)).add(F(L.y).mul(F(8)));
1821
+ Dn({
1822
+ start: F(0),
1823
+ end: F(8),
1824
+ type: "int",
1825
+ condition: "<",
1826
+ update: 2,
1827
+ name: "ty"
1828
+ }, ({ ty: t }) => {
1829
+ Dn({
1830
+ start: F(0),
1831
+ end: F(8),
1832
+ type: "int",
1833
+ condition: "<",
1834
+ update: 2,
1835
+ name: "tx"
1836
+ }, ({ tx: i }) => {
1837
+ let s = u.add(i), f = d.add(t);
1838
+ N(s.lessThan(n).and(f.lessThan(r)), () => {
1839
+ let t = Hn(s.add(F(1)), n.sub(F(1))), i = Hn(f.add(F(1)), r.sub(F(1))), u = Fn(H(e, I(s, f)).xyz, o).add(Fn(H(e, I(t, f)).xyz, o)).add(Fn(H(e, I(s, i)).xyz, o)).add(Fn(H(e, I(t, i)).xyz, o)).mul(.25).toVar();
1840
+ N(Rn(u).bitAnd(W(2139095040)).notEqual(W(2139095040)), () => {
1841
+ let e = Vn(R(u, Ba)).clamp(Na, Pa).toVar(), t = e.add(a).sub(ja).div(Ma - ja).clamp(0, 1).mul(Aa - 1).toVar(), n = W(zn(t)).min(W(Aa - 1)), r = n.add(W(1)).min(W(Aa - 1)), i = t.sub(zn(t)), o = P(1).sub(i), s = e.sub(Na).mul(Fa);
1842
+ jn(c.element(n), W(s.mul(o).add(.5))), jn(l.element(n), W(o.mul(Fa).add(.5))), jn(c.element(r), W(s.mul(i).add(.5))), jn(l.element(r), W(i.mul(Fa).add(.5)));
1843
+ });
1844
+ });
1845
+ });
1846
+ }), er(), N(s.lessThan(W(Aa)), () => {
1847
+ let e = P(Mn(l.element(s))).div(Fa), n = P(Mn(c.element(s))).div(Fa).add(e.mul(Na)), r = W(Y.y).mul(W(i)).add(W(Y.x));
1848
+ t.element(r.mul(W(Aa)).add(s)).assign(K(n, e).div(ka));
1549
1849
  });
1550
- let a = i.mul(n), o = i.mul(r), s = F(0).toVar(), c = F(0).toVar(), l = F(0).toVar(), u = F(0).toVar();
1551
- Tn(Zi, ({ i: t }) => {
1552
- let n = F(An(e.element(t)));
1553
- u.assign(s), s.addAssign(n), P(u.lessThan(o).and(s.greaterThan(a)), () => {
1554
- let e = F(Qi).add(F(t).add(.5).mul(F(ea)));
1555
- c.addAssign(e.mul(n)), l.addAssign(n);
1850
+ })().compute([
1851
+ 1,
1852
+ 1,
1853
+ 1
1854
+ ], [
1855
+ 16,
1856
+ 16,
1857
+ 1
1858
+ ]);
1859
+ }
1860
+ _buildBlurSourceKernel() {
1861
+ let e = this._inputNode, t = this._blur, n = this._widthU, r = this._heightU, i = this._blurWU, a = J(...Ua, 0).xyz;
1862
+ return En(() => {
1863
+ let o = L.y.mul(W(8)).add(L.x), s = F(Y.x).mul(F(Ia)), c = F(Y.y).mul(F(Ia)), l = P(0).toVar(), u = P(0).toVar();
1864
+ Dn({
1865
+ start: F(L.y),
1866
+ end: F(Ia),
1867
+ type: "int",
1868
+ condition: "<",
1869
+ update: 8,
1870
+ name: "by"
1871
+ }, ({ by: t }) => {
1872
+ Dn({
1873
+ start: F(L.x),
1874
+ end: F(Ia),
1875
+ type: "int",
1876
+ condition: "<",
1877
+ update: 8,
1878
+ name: "bx"
1879
+ }, ({ bx: i }) => {
1880
+ let o = s.add(i), d = c.add(t);
1881
+ N(o.lessThan(n).and(d.lessThan(r)), () => {
1882
+ let t = Fn(H(e, I(o, d)).xyz, a).toVar(), n = Rn(t).bitAnd(W(2139095040)).notEqual(W(2139095040));
1883
+ l.addAssign(V(n, t.max(0), P(0))), u.addAssign(V(n, P(1), P(0)));
1884
+ });
1556
1885
  });
1557
1886
  });
1558
- let d = z(l, F(1)), f = c.div(d), p = f.exp();
1559
- W(t, Gn(G(0), G(0)), J(p, i, f, 1)).toWriteOnly();
1560
- })().compute(1, [
1887
+ let d = $n("float", 64), f = $n("float", 64);
1888
+ d.element(o).assign(l), f.element(o).assign(u), er();
1889
+ for (let e = 32; e > 0; e >>= 1) N(o.lessThan(W(e)), () => {
1890
+ d.element(o).addAssign(d.element(o.add(W(e)))), f.element(o).addAssign(f.element(o.add(W(e))));
1891
+ }), er();
1892
+ N(o.equal(W(0)), () => {
1893
+ let e = d.element(W(0)).div(R(f.element(W(0)), 1));
1894
+ t.element(W(F(Y.y).mul(i).add(F(Y.x)))).assign(Vn(R(e, Ba)).clamp(Na, Pa));
1895
+ });
1896
+ })().compute([
1561
1897
  1,
1562
1898
  1,
1563
1899
  1
1900
+ ], [
1901
+ 8,
1902
+ 8,
1903
+ 1
1564
1904
  ]);
1565
1905
  }
1566
- _buildAdaptationCompute() {
1567
- let e = this._reductionReadTexNode, t = this._adaptationResult, n = this.keyValueU, r = this.minExposureU, i = this.maxExposureU, a = this.adaptSpeedBrightU, o = this.adaptSpeedDarkU, s = this.deltaTimeU, c = this.isFirstFrameU, l = this.previousExposureU;
1568
- this._adaptationComputeNode = wn(() => {
1569
- let u = U(e, L(I(0), I(0))).x, d = na(u, l, n, r, i, a, o, s, c);
1570
- t.element(G(0)).assign(d);
1571
- })().compute(1, [
1906
+ _buildBlurKernel(e, t, n) {
1907
+ let r = this._blurWU, i = this._blurHU, a = this._radiusU;
1908
+ return En(() => {
1909
+ let o = F(Y.x).mul(F(8)).add(F(L.x)), s = F(Y.y).mul(F(8)).add(F(L.y));
1910
+ N(o.lessThan(r).and(s.lessThan(i)), () => {
1911
+ let c = n ? r : i, l = n ? o : s, u = F(a.ceil()), d = P(0).toVar(), f = P(0).toVar();
1912
+ Dn({
1913
+ start: u.negate(),
1914
+ end: u.add(F(1)),
1915
+ type: "int",
1916
+ condition: "<",
1917
+ name: "o"
1918
+ }, ({ o: t }) => {
1919
+ let i = P(t).div(a), u = In(i.mul(i).mul(-16.7)), p = c.mul(F(2)), m = l.add(t).mod(p).add(p).mod(p).toVar();
1920
+ N(m.greaterThanEqual(c), () => {
1921
+ m.assign(p.sub(m).sub(F(1)));
1922
+ });
1923
+ let h = n ? s.mul(r).add(m) : m.mul(r).add(o);
1924
+ d.addAssign(e.element(W(h)).mul(u)), f.addAssign(u);
1925
+ }), t.element(W(s.mul(r).add(o))).assign(d.div(f));
1926
+ });
1927
+ })().compute([
1572
1928
  1,
1573
1929
  1,
1574
1930
  1
1931
+ ], [
1932
+ 8,
1933
+ 8,
1934
+ 1
1575
1935
  ]);
1576
1936
  }
1577
1937
  setupEventListeners() {
1578
- this.on("pipeline:reset", () => this.reset()), this.on("pipeline:lightingChanged", () => this.resetHistory());
1938
+ this.on("pipeline:reset", () => this._restarts++);
1579
1939
  }
1580
1940
  render(e) {
1581
1941
  if (!this.enabled) return;
1582
- let t = e.getTexture("edgeFiltering:output") || e.getTexture("asvgf:output") || e.getTexture("pathtracer:color");
1583
- if (!t) return;
1584
- let n = performance.now(), r = Math.min((n - this.lastTime) / 1e3, .1);
1585
- if (this.lastTime = n, this.deltaTimeU.value = this.isFirstFrame ? 1 : r, this.isFirstFrameU.value = +!!this.isFirstFrame, this.previousExposureU.value = this.currentExposure, this.inputResW.value = t.image?.width || 1, this.inputResH.value = t.image?.height || 1, this._inputTexNode.value = t, this.renderer.compute(this._downsampleComputeNode), this.renderer.copyTextureToTexture(this._downsampleStorageTex, this._downsampleTarget.texture), this.renderer.compute(this._histogramComputeNode), this.renderer.compute(this._histogramAnalyzeNode), this.renderer.copyTextureToTexture(this._reductionStorageTex, this._reductionReadTarget.texture), this._reductionReadTexNode.value = this._reductionReadTarget.texture, this.renderer.compute(this._adaptationComputeNode), !this._pendingReadback) {
1586
- this._pendingReadback = !0;
1587
- let e = this._readbackGeneration;
1588
- this.renderer.getArrayBufferAsync(this._adaptationResult.value, this._readbackBuffer).then((t) => {
1589
- let n = t && t.buffer ? new Float32Array(t.buffer.slice(0)) : null;
1590
- this._readbackBuffer.release(), this._pendingReadback = !1, n && e === this._readbackGeneration && this._applyReadback(n);
1591
- }).catch(() => {
1592
- try {
1593
- this._readbackBuffer.release();
1594
- } catch {}
1595
- this._pendingReadback = !1;
1596
- });
1597
- }
1598
- e.setState("autoexposure:value", this.currentExposure), e.setState("autoexposure:avgLuminance", this.currentLuminance), this.emit("autoexposure:updated", {
1599
- exposure: this.currentExposure,
1600
- luminance: this.currentLuminance,
1601
- targetExposure: this.targetExposure
1602
- }), this.isFirstFrame = !1;
1603
- }
1604
- _applyReadback(e) {
1605
- if (!this.enabled || !e || e.length < 3) return;
1606
- let t = e[0], n = e[1], r = e[2];
1607
- (!isFinite(t) || t <= 0) && (t = 1), (!isFinite(n) || n <= 0) && (n = .18), (!isFinite(r) || r <= 0) && (r = t), this.currentExposure = t, this.currentLuminance = n, this.targetExposure = r, this.renderer.toneMappingExposure = t;
1608
- }
1609
- reset() {
1610
- this.lastTime = performance.now(), this._readbackGeneration++, this._pendingReadback = !1;
1611
- }
1612
- resetHistory() {
1613
- this.isFirstFrame = !0, this.currentExposure = 1, this.currentLuminance = .18, this.targetExposure = 1, this.lastTime = performance.now(), this._readbackGeneration++, this._pendingReadback = !1;
1614
- }
1615
- setSize() {}
1616
- setExposure(e) {
1617
- this.currentExposure = e, this.previousExposureU.value = e, this.renderer.toneMappingExposure = e;
1618
- }
1619
- getExposure() {
1620
- return this.currentExposure;
1621
- }
1622
- getLuminance() {
1623
- return this.currentLuminance;
1942
+ let t = e.getState("pathtracer:samples") ?? 0, n = this._builtAt;
1943
+ (this._stale || !this._built || n.restarts !== this._restarts || t - n.samples >= Wa(t)) && this.build(e);
1944
+ }
1945
+ build(e = this.context) {
1946
+ let t = e?.getTexture("pathtracer:color"), n = t?.image?.width | 0, r = t?.image?.height | 0;
1947
+ if (!t || n < 1 || r < 1 || this._disposed) return !1;
1948
+ this._builtAt.restarts = this._restarts, this._builtAt.samples = e.getState("pathtracer:samples") ?? 0, this._stale = !1;
1949
+ let i = Math.min(Va, Math.ceil(n / Oa)), a = Math.min(Va, Math.ceil(r / Oa)), o = Math.min(Ha, Math.ceil(n / Ia)), s = Math.min(Ha, Math.ceil(r / Ia)), c = Math.log2(Math.max(this.renderer.toneMappingExposure, 1e-6));
1950
+ return this._inputNode.value = t, this._widthU.value = n, this._heightU.value = r, this._cellsXU.value = i, this._blurWU.value = o, this._blurHU.value = s, this._radiusU.value = Math.max(1, Ra / 100 * o), this._logExposureU.value = c, this._kernels[0].dispatchSize = [
1951
+ i,
1952
+ a,
1953
+ 1
1954
+ ], this._kernels[1].dispatchSize = [
1955
+ o,
1956
+ s,
1957
+ 1
1958
+ ], this._kernels[2].dispatchSize = this._kernels[3].dispatchSize = [
1959
+ Math.ceil(o / 8),
1960
+ Math.ceil(s / 8),
1961
+ 1
1962
+ ], this.renderer.compute(this._kernels), this._params.set([
1963
+ n / Oa,
1964
+ r / Oa,
1965
+ n / Ia,
1966
+ r / Ia,
1967
+ i,
1968
+ a,
1969
+ o,
1970
+ s,
1971
+ c
1972
+ ], 0), this._built = !0, this._writeParams(), !0;
1973
+ }
1974
+ _writeParams() {
1975
+ let e = this._params;
1976
+ e[9] = this.highlightContrast, e[10] = this.shadowContrast, e[11] = this.detailStrength, e[12] = La, e[13] = za;
1977
+ for (let t = 0; t < 4; t++) this._p[t].value.fromArray(e, t * 4);
1978
+ this.onChange?.();
1979
+ }
1980
+ get wantsBuild() {
1981
+ return this.enabled && (this._stale || !this._built);
1624
1982
  }
1625
1983
  updateParameters(e) {
1626
- e.keyValue !== void 0 && (this.keyValueU.value = e.keyValue), e.minExposure !== void 0 && (this.minExposureU.value = e.minExposure), e.maxExposure !== void 0 && (this.maxExposureU.value = e.maxExposure), e.adaptSpeedBright !== void 0 && (this.adaptSpeedBrightU.value = e.adaptSpeedBright), e.adaptSpeedDark !== void 0 && (this.adaptSpeedDarkU.value = e.adaptSpeedDark), e.lowPercentile !== void 0 && (this.lowPercentileU.value = e.lowPercentile), e.highPercentile !== void 0 && (this.highPercentileU.value = e.highPercentile), e.centerWeight !== void 0 && (this.centerWeightU.value = e.centerWeight);
1984
+ for (let t of [
1985
+ "highlightContrast",
1986
+ "shadowContrast",
1987
+ "detailStrength"
1988
+ ]) e[t] !== void 0 && (this[t] = e[t]);
1989
+ this._writeParams();
1990
+ }
1991
+ setEnabled(e) {
1992
+ this.enabled !== e && (this.enabled = e, this._stale = !0, this.onChange?.());
1993
+ }
1994
+ gainNode(e, t) {
1995
+ let n = Jn(this._grid.value, "vec2", Va * Va * Aa).toReadOnly(), r = Jn(this._blur.value, "float", Ha * Ha).toReadOnly(), [i, a, o, s] = this._p;
1996
+ return En(([e, t]) => {
1997
+ let c = Vn(R(Fn(e, J(...Ua, 0).xyz), Ba)).min(Pa).toVar(), l = Vn(Yn).toVar(), u = I(a.zw), d = t.mul(i.zw).sub(.5).clamp(K(0), K(u.sub(F(1)))).toVar(), f = I(zn(d)).toVar(), p = f.add(F(1)).min(u.sub(F(1))).toVar(), m = d.sub(zn(d)).toVar(), h = (e, t) => r.element(W(t.mul(u.x).add(e))), g = z(z(h(f.x, f.y), h(p.x, f.y), m.x), z(h(f.x, p.y), h(p.x, p.y), m.x), m.y).toVar(), _ = I(a.xy), v = t.mul(i.xy).sub(.5).clamp(K(0), K(_.sub(F(1)))).toVar(), y = c.add(o.x).sub(ja).div(Ma - ja).clamp(0, 1).mul(Aa - 1).toVar(), b = F(zn(v.x)), x = F(zn(v.y)), S = F(zn(y)), ee = v.x.sub(zn(v.x)), C = v.y.sub(zn(v.y)), w = y.sub(zn(y)), T = K(0).toVar();
1998
+ for (let e = 0; e < 8; e++) {
1999
+ let t = e & 1, r = e >> 1 & 1, i = e >> 2, a = (t ? ee : ee.oneMinus()).mul(r ? C : C.oneMinus()).mul(i ? w : w.oneMinus()), o = b.add(F(t)).min(_.x.sub(F(1))), s = x.add(F(r)).min(_.y.sub(F(1))), c = S.add(F(i)).min(F(Aa - 1));
2000
+ T.addAssign(n.element(W(s.mul(_.x).add(o).mul(F(Aa)).add(c))).mul(a));
2001
+ }
2002
+ let E = z(V(T.y.mul(ka).lessThan(.001), g, T.x.div(T.y)), g, s.x).add(l).toVar(), te = c.add(l), D = V(E.greaterThan(s.y), o.y, o.z);
2003
+ return Ln(s.y.add(E.sub(s.y).mul(D)).add(te.sub(E).mul(o.w)).sub(te));
2004
+ })(e, t);
2005
+ }
2006
+ toneGain() {
2007
+ if (!this.enabled || !this._built) return null;
2008
+ let e = this.renderer.backend, t = e.get(this._grid.value)?.buffer, n = e.get(this._blur.value)?.buffer;
2009
+ if (!t || !n) return null;
2010
+ this._paramsBuffer ??= e.device.createBuffer({
2011
+ label: "local-exposure-params",
2012
+ size: 64,
2013
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
2014
+ }), e.device.queue.writeBuffer(this._paramsBuffer, 0, this._params);
2015
+ let r = this._params.slice();
2016
+ return {
2017
+ key: "local-exposure",
2018
+ wgsl: qa,
2019
+ entries: [
2020
+ {
2021
+ binding: 0,
2022
+ resource: { buffer: t }
2023
+ },
2024
+ {
2025
+ binding: 1,
2026
+ resource: { buffer: n }
2027
+ },
2028
+ {
2029
+ binding: 2,
2030
+ resource: { buffer: this._paramsBuffer }
2031
+ }
2032
+ ],
2033
+ cpu: async () => {
2034
+ let [e, t] = await Promise.all([this.renderer.getArrayBufferAsync(this._grid.value), this.renderer.getArrayBufferAsync(this._blur.value)]), n = new Float32Array(e), i = new Float32Array(t);
2035
+ return (e, t, a, o) => Ka(r, n, i, e, t, a, o);
2036
+ }
2037
+ };
1627
2038
  }
2039
+ reset() {}
2040
+ setSize() {}
1628
2041
  dispose() {
1629
- this._downsampleComputeNode?.dispose(), this._histogramComputeNode?.dispose(), this._histogramAnalyzeNode?.dispose(), this._adaptationComputeNode?.dispose(), this._downsampleTarget?.dispose(), this._downsampleStorageTex?.dispose(), this._reductionStorageTex?.dispose(), this._reductionReadTarget?.dispose(), this._readbackBuffer?.dispose(), this._inputTexNode?.dispose(), this._reductionReadTexNode?.dispose();
2042
+ this._disposed = !0, this.onChange = null;
2043
+ for (let e of this._kernels) e.dispose();
2044
+ this._inputNode.dispose(), this._paramsBuffer?.destroy(), this._paramsBuffer = null;
1630
2045
  }
1631
- }, ia = new $(), aa = new $();
1632
- function oa(e, t) {
1633
- return aa.subVectors(e, t.position).dot(t.getWorldDirection(ia));
2046
+ }, Ya = new $(), Xa = new $();
2047
+ function Za(e, t) {
2048
+ return Xa.subVectors(e, t.position).dot(t.getWorldDirection(Ya));
1634
2049
  }
1635
- function sa(e, t, n = !1) {
1636
- return n ? e.distance : oa(e.point, t);
2050
+ function Qa(e, t, n = !1) {
2051
+ return n ? e.distance : Za(e.point, t);
1637
2052
  }
1638
- var ca = class extends cr {
2053
+ var $a = class extends fr {
1639
2054
  constructor({ scene: e, camera: t, canvas: n, assetLoader: r, pathTracer: i, floorPlane: a, isGeometryOnDisk: o = null }) {
1640
- super(), this.scene = e, this.isGeometryOnDisk = o, this.camera = t, this.canvas = n, this.assetLoader = r, this.pathTracer = i, this.floorPlane = a, this.raycaster = new Tr(), this.focusMode = !1, this.focusPointIndicator = null, this.afPointPlacementMode = !1, this.handleAFPointClick = this.handleAFPointClick.bind(this), this.selectedObject = null, this.selectMode = !1, this.clickTimeout = null, this.mouseDownPosition = null, this.dragThreshold = 5, this.handleFocusClick = this.handleFocusClick.bind(this), this.handleSelectClick = this.handleSelectClick.bind(this), this.handleSelectDoubleClick = this.handleSelectDoubleClick.bind(this), this.handleMouseDown = this.handleMouseDown.bind(this), this.handleMouseUp = this.handleMouseUp.bind(this), this.handleContextMenu = this.handleContextMenu.bind(this), this.handleContextPointerDown = this.handleContextPointerDown.bind(this), this.handleContextPointerUp = this.handleContextPointerUp.bind(this), this.contextPointerDownPosition = null, this.canvas.addEventListener("pointerdown", this.handleContextPointerDown), this.canvas.addEventListener("pointerup", this.handleContextPointerUp), this.canvas.addEventListener("contextmenu", this.handleContextMenu), this._overlayManager = null, this._transformManager = null, this._appDispatch = null, this._orbitControls = null, this._helperScene = null;
2055
+ super(), this.scene = e, this.isGeometryOnDisk = o, this.camera = t, this.canvas = n, this.assetLoader = r, this.pathTracer = i, this.floorPlane = a, this.raycaster = new Ar(), this.focusMode = !1, this.focusPointIndicator = null, this.afPointPlacementMode = !1, this.handleAFPointClick = this.handleAFPointClick.bind(this), this.selectedObject = null, this.selectMode = !1, this.clickTimeout = null, this.mouseDownPosition = null, this.dragThreshold = 5, this.handleFocusClick = this.handleFocusClick.bind(this), this.handleSelectClick = this.handleSelectClick.bind(this), this.handleSelectDoubleClick = this.handleSelectDoubleClick.bind(this), this.handleMouseDown = this.handleMouseDown.bind(this), this.handleMouseUp = this.handleMouseUp.bind(this), this.handleContextMenu = this.handleContextMenu.bind(this), this.handleContextPointerDown = this.handleContextPointerDown.bind(this), this.handleContextPointerUp = this.handleContextPointerUp.bind(this), this.contextPointerDownPosition = null, this.canvas.addEventListener("pointerdown", this.handleContextPointerDown), this.canvas.addEventListener("pointerup", this.handleContextPointerUp), this.canvas.addEventListener("contextmenu", this.handleContextMenu), this._overlayManager = null, this._transformManager = null, this._appDispatch = null, this._orbitControls = null, this._helperScene = null;
1641
2056
  }
1642
2057
  setDependencies({ overlayManager: e, transformManager: t, appDispatch: n, orbitControls: r, helperScene: i }) {
1643
2058
  this._overlayManager = e || null, this._transformManager = t || null, this._appDispatch = n || null, this._orbitControls = r || null, this._helperScene = i || null;
@@ -1669,7 +2084,7 @@ var ca = class extends cr {
1669
2084
  this.raycaster.setFromCamera(t, this.camera);
1670
2085
  let n = this._intersectScene();
1671
2086
  if (n.length > 0) {
1672
- let e = n[0], t = this.pathTracer?.cameraProjection?.value === Ae.equirectangular, r = sa(e, this.camera, t);
2087
+ let e = n[0], t = this.pathTracer?.cameraProjection?.value === Ae.equirectangular, r = Qa(e, this.camera, t);
1673
2088
  this.showFocusPoint(e.point), this.toggleFocusMode(), this.dispatchEvent({
1674
2089
  type: "focusChanged",
1675
2090
  distance: r / this.assetLoader.getSceneScale(),
@@ -1678,7 +2093,7 @@ var ca = class extends cr {
1678
2093
  }
1679
2094
  }
1680
2095
  showFocusPoint(e) {
1681
- this.focusPointIndicator && this.scene.remove(this.focusPointIndicator), this.focusPointIndicator = new gr(new kr(this.assetLoader.getSceneScale() * .02, 16, 16), new _r({
2096
+ this.focusPointIndicator && this.scene.remove(this.focusPointIndicator), this.focusPointIndicator = new xr(new Pr(this.assetLoader.getSceneScale() * .02, 16, 16), new Sr({
1682
2097
  color: 65280,
1683
2098
  transparent: !0,
1684
2099
  opacity: .8,
@@ -1880,7 +2295,7 @@ var ca = class extends cr {
1880
2295
  dispose() {
1881
2296
  this.canvas.removeEventListener("click", this.handleAFPointClick), this.canvas.removeEventListener("click", this.handleFocusClick), this.canvas.removeEventListener("mousedown", this.handleMouseDown), this.canvas.removeEventListener("mouseup", this.handleMouseUp), this.canvas.removeEventListener("click", this.handleSelectClick), this.canvas.removeEventListener("dblclick", this.handleSelectDoubleClick), this.canvas.removeEventListener("contextmenu", this.handleContextMenu), this.canvas.removeEventListener("pointerdown", this.handleContextPointerDown), this.canvas.removeEventListener("pointerup", this.handleContextPointerUp), this.clickTimeout &&= (clearTimeout(this.clickTimeout), null), this.mouseDownPosition = null, this.contextPointerDownPosition = null, this.focusPointIndicator &&= (this.scene.remove(this.focusPointIndicator), null), this.canvas.style.cursor = "auto", this.scene = null, this.camera = null, this.canvas = null, this.assetLoader = null, this.pathTracer = null, this.floorPlane = null, this.raycaster = null;
1882
2297
  }
1883
- }, la = 8, ua = 4, da = .25, fa = mr.degToRad(89), pa = .25, ma = {
2298
+ }, eo = 8, to = 4, no = .25, ro = vr.degToRad(89), io = .25, ao = {
1884
2299
  KeyD: [
1885
2300
  1,
1886
2301
  0,
@@ -1931,15 +2346,15 @@ var ca = class extends cr {
1931
2346
  0,
1932
2347
  -1
1933
2348
  ]
1934
- }, ha = "input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]", ga = (e) => e.shiftKey ? ua : e.altKey ? da : 1, _a = { type: "change" }, va = { type: "start" }, ya = new $(), ba = new $(), xa = new $(), Sa = new $(), Ca = new wr(), wa = class extends ir {
2349
+ }, oo = "input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), [role=textbox], [role=combobox], [role=listbox], [role=menu], [role=menuitem]", so = (e) => e.shiftKey ? to : e.altKey ? no : 1, co = { type: "change" }, lo = { type: "start" }, uo = new $(), fo = new $(), po = new $(), mo = new $(), ho = new kr(), go = class extends cr {
1935
2350
  constructor(e, t, n) {
1936
- super(e, t), this.orbit = n, this.enabled = !1, this.speed = 1 / la, this._held = /* @__PURE__ */ new Set(), this._factor = 1, this._lastTime = 0, this._drag = null, this._onKeyDown = this._onKeyDown.bind(this), this._onKeyUp = this._onKeyUp.bind(this), this.release = this.release.bind(this), this._onPointerDown = this._onPointerDown.bind(this), this._onPointerMove = this._onPointerMove.bind(this), this._onPointerUp = this._onPointerUp.bind(this), t && this.connect(t);
2351
+ super(e, t), this.orbit = n, this.enabled = !1, this.speed = 1 / eo, this._held = /* @__PURE__ */ new Set(), this._factor = 1, this._lastTime = 0, this._drag = null, this._onKeyDown = this._onKeyDown.bind(this), this._onKeyUp = this._onKeyUp.bind(this), this.release = this.release.bind(this), this._onPointerDown = this._onPointerDown.bind(this), this._onPointerMove = this._onPointerMove.bind(this), this._onPointerUp = this._onPointerUp.bind(this), t && this.connect(t);
1937
2352
  }
1938
2353
  get active() {
1939
2354
  return this.enabled && this.orbit.enabled;
1940
2355
  }
1941
2356
  fitSpeed(e) {
1942
- this.speed = (e > 0 ? e : 1) / la;
2357
+ this.speed = (e > 0 ? e : 1) / eo;
1943
2358
  }
1944
2359
  connect(e) {
1945
2360
  super.connect(e);
@@ -1959,34 +2374,34 @@ var ca = class extends cr {
1959
2374
  if (!this._held.size || !this.active) return !1;
1960
2375
  let t = 0, n = 0, r = 0;
1961
2376
  for (let e of this._held) {
1962
- let [i, a, o] = ma[e];
2377
+ let [i, a, o] = ao[e];
1963
2378
  t += i, n += a, r += o;
1964
2379
  }
1965
2380
  if (!t && !n && !r) return !1;
1966
2381
  let i = this.object;
1967
- return ba.set(1, 0, 0).applyQuaternion(i.quaternion), ya.crossVectors(i.up, ba).normalize(), ba.crossVectors(ya, i.up), xa.set(0, 0, 0).addScaledVector(ba, t).addScaledVector(ya, n).addScaledVector(i.up, r).normalize().multiplyScalar(this.speed * this._factor * e), i.position.add(xa), this.orbit.target.add(xa), i.updateMatrixWorld(), this.dispatchEvent(_a), !0;
2382
+ return fo.set(1, 0, 0).applyQuaternion(i.quaternion), uo.crossVectors(i.up, fo).normalize(), fo.crossVectors(uo, i.up), po.set(0, 0, 0).addScaledVector(fo, t).addScaledVector(uo, n).addScaledVector(i.up, r).normalize().multiplyScalar(this.speed * this._factor * e), i.position.add(po), this.orbit.target.add(po), i.updateMatrixWorld(), this.dispatchEvent(co), !0;
1968
2383
  }
1969
2384
  _elapsed() {
1970
- let e = performance.now(), t = Math.min((e - this._lastTime) / 1e3, pa);
2385
+ let e = performance.now(), t = Math.min((e - this._lastTime) / 1e3, io);
1971
2386
  return this._lastTime = e, t;
1972
2387
  }
1973
2388
  _look(e, t) {
1974
- let n = this.object, r = this.orbit.target, i = n.position.distanceTo(r) || 1, a = mr.degToRad(n.fov) / (this.domElement.clientHeight || 1);
1975
- n.quaternion.premultiply(Ca.setFromAxisAngle(n.up, e * a)), n.getWorldDirection(ya);
1976
- let o = Math.asin(mr.clamp(ya.dot(n.up), -1, 1)), s = mr.clamp(o + t * a, -fa, fa);
1977
- n.quaternion.multiply(Ca.setFromAxisAngle(Sa.set(1, 0, 0), s - o)), n.updateMatrixWorld(), r.copy(n.position).addScaledVector(n.getWorldDirection(ya), i), this.dispatchEvent(_a);
2389
+ let n = this.object, r = this.orbit.target, i = n.position.distanceTo(r) || 1, a = vr.degToRad(n.fov) / (this.domElement.clientHeight || 1);
2390
+ n.quaternion.premultiply(ho.setFromAxisAngle(n.up, e * a)), n.getWorldDirection(uo);
2391
+ let o = Math.asin(vr.clamp(uo.dot(n.up), -1, 1)), s = vr.clamp(o + t * a, -ro, ro);
2392
+ n.quaternion.multiply(ho.setFromAxisAngle(mo.set(1, 0, 0), s - o)), n.updateMatrixWorld(), r.copy(n.position).addScaledVector(n.getWorldDirection(uo), i), this.dispatchEvent(co);
1978
2393
  }
1979
2394
  _onKeyDown(e) {
1980
- if (!(!this.active || e.defaultPrevented || e.target?.closest?.(ha))) {
2395
+ if (!(!this.active || e.defaultPrevented || e.target?.closest?.(oo))) {
1981
2396
  if (e.metaKey || e.ctrlKey) {
1982
2397
  this.release();
1983
2398
  return;
1984
2399
  }
1985
- this._factor = ga(e), ma[e.code] && (e.preventDefault(), !this._held.has(e.code) && (this._held.add(e.code), this._held.size === 1 && (this._lastTime = performance.now(), this.dispatchEvent(va))));
2400
+ this._factor = so(e), ao[e.code] && (e.preventDefault(), !this._held.has(e.code) && (this._held.add(e.code), this._held.size === 1 && (this._lastTime = performance.now(), this.dispatchEvent(lo))));
1986
2401
  }
1987
2402
  }
1988
2403
  _onKeyUp(e) {
1989
- this._factor = ga(e), this._held.delete(e.code);
2404
+ this._factor = so(e), this._held.delete(e.code);
1990
2405
  }
1991
2406
  release() {
1992
2407
  this._held.clear(), this._factor = 1;
@@ -2007,24 +2422,24 @@ var ca = class extends cr {
2007
2422
  _onPointerUp(e) {
2008
2423
  this._drag?.id === e.pointerId && (this._drag = null, this.domElement.releasePointerCapture?.(e.pointerId));
2009
2424
  }
2010
- }, Ta = {
2425
+ }, _o = {
2011
2426
  autoFocusMode: "auto",
2012
2427
  afScreenPoint: {
2013
2428
  x: .5,
2014
2429
  y: .5
2015
2430
  },
2016
2431
  afSmoothingFactor: .15
2017
- }, Ea = .05, Da = 10, Oa = .5, ka = Object.freeze(new $(1, 1, 1)), Aa = (e) => e?.isOrthographicCamera ? (e.top - e.bottom) / e.zoom : null, ja = class extends cr {
2432
+ }, vo = .05, yo = 10, bo = .5, xo = Object.freeze(new $(1, 1, 1)), So = (e) => e?.isOrthographicCamera ? (e.top - e.bottom) / e.zoom : null, Co = class extends fr {
2018
2433
  constructor(e) {
2019
2434
  super();
2020
2435
  let t = e.clientWidth, n = e.clientHeight;
2021
- this.camera = new _(60, t / n || 1, .01, 1e3), this.camera.position.set(0, 0, 5), this.controls = new Ir(this.camera, e), this.controls.screenSpacePanning = !0, this.controls.zoomToCursor = !0, this.controls.saveState(), this._reportedOrthoHeight = null, this._reportOrthoHeight = this._reportOrthoHeight.bind(this), this.controls.addEventListener("change", this._reportOrthoHeight), this.walkControls = new wa(this.camera, e, this.controls), this.interactionManager = null, this.cameras = [this.camera], this.currentCameraIndex = 0, this._userCameraCounter = 0, this.autoFocusMode = Ta.autoFocusMode, this.afScreenPoint = { ...Ta.afScreenPoint }, this.afSmoothingFactor = Ta.afSmoothingFactor, this._lastValidFocusDistance = null, this._smoothedFocusDistance = null, this._afPointDirty = !1, this._afSuspended = !1, this._afPick = null, this._defaultCameraState = null, this._onResize = null, this._onReset = null, this._getSettings = null, this._applySettings = null;
2436
+ this.camera = new _(60, t / n || 1, .01, 1e3), this.camera.position.set(0, 0, 5), this.controls = new Vr(this.camera, e), this.controls.screenSpacePanning = !0, this.controls.zoomToCursor = !0, this.controls.saveState(), this._reportedOrthoHeight = null, this._reportOrthoHeight = this._reportOrthoHeight.bind(this), this.controls.addEventListener("change", this._reportOrthoHeight), this.walkControls = new go(this.camera, e, this.controls), this.interactionManager = null, this.cameras = [this.camera], this.currentCameraIndex = 0, this._userCameraCounter = 0, this.autoFocusMode = _o.autoFocusMode, this.afScreenPoint = { ..._o.afScreenPoint }, this.afSmoothingFactor = _o.afSmoothingFactor, this._lastValidFocusDistance = null, this._smoothedFocusDistance = null, this._afPointDirty = !1, this._afSuspended = !1, this._afPick = null, this._defaultCameraState = null, this._onResize = null, this._onReset = null, this._getSettings = null, this._applySettings = null;
2022
2437
  }
2023
2438
  setCameras(e) {
2024
2439
  this.cameras = e, this._userCameraCounter = 0, this.resetAutoFocus();
2025
2440
  }
2026
2441
  addCameraFromView(e) {
2027
- let t = this.camera, n = t.orthographic ? new xr(t.left, t.right, t.top, t.bottom, t.near, t.far) : new Sr(t.fov, t.aspect, t.near, t.far);
2442
+ let t = this.camera, n = t.orthographic ? new Er(t.left, t.right, t.top, t.bottom, t.near, t.far) : new Dr(t.fov, t.aspect, t.near, t.far);
2028
2443
  return n.zoom = t.zoom, n.position.copy(t.position), n.quaternion.copy(t.quaternion), n.scale.copy(t.scale), n.updateMatrixWorld(!0), n.userData.__rayzeeUserCamera = !0, n.userData.__rayzeeEffects = this._captureEffects(), this.controls && (n.userData.__rayzeeOrbitTarget = this.controls.target.clone()), this._userCameraCounter += 1, n.name = e || `View Camera ${this._userCameraCounter}`, this.cameras.push(n), this.cameras.length - 1;
2029
2444
  }
2030
2445
  removeCamera(e) {
@@ -2078,11 +2493,11 @@ var ca = class extends cr {
2078
2493
  target: this.controls ? this.controls.target.clone() : null
2079
2494
  }), this.currentCameraIndex = e, e === 0 && this._defaultCameraState) {
2080
2495
  let e = this._defaultCameraState;
2081
- this.camera.position.copy(e.position), this.camera.quaternion.copy(e.quaternion), this.camera.scale.copy(e.scale ?? ka), this.camera.fov = e.fov, this.camera.near = e.near, this.camera.far = e.far, this.camera.updateProjectionMatrix(), this.camera.updateMatrixWorld(!0), this.controls && e.target && (this.controls.target.copy(e.target), this.controls.update());
2496
+ this.camera.position.copy(e.position), this.camera.quaternion.copy(e.quaternion), this.camera.scale.copy(e.scale ?? xo), this.camera.fov = e.fov, this.camera.near = e.near, this.camera.far = e.far, this.camera.updateProjectionMatrix(), this.camera.updateMatrixWorld(!0), this.controls && e.target && (this.controls.target.copy(e.target), this.controls.update());
2082
2497
  } else this._placeAt(this.cameras[e], t);
2083
2498
  this.resetAutoFocus();
2084
2499
  let a = this.cameras[e], o = a?.userData?.__rayzeeEffects;
2085
- this._showOrthographic(o ? o.orthoHeight : Aa(a)), this._applyEffects(o), n?.(), r?.(), this.dispatchEvent({
2500
+ this._showOrthographic(o ? o.orthoHeight : So(a)), this._applyEffects(o), n?.(), r?.(), this.dispatchEvent({
2086
2501
  type: j.CAMERA_SWITCHED,
2087
2502
  cameraIndex: e,
2088
2503
  effects: this._captureEffects(),
@@ -2097,7 +2512,7 @@ var ca = class extends cr {
2097
2512
  return;
2098
2513
  }
2099
2514
  this._placeAt(e, this._getSettings?.("focusDistance"));
2100
- let t = Aa(e);
2515
+ let t = So(e);
2101
2516
  this.camera.orthographic && this._setView(!0, t ? t / 2 : this.camera.orthoHalfHeight), this._onReset?.();
2102
2517
  }
2103
2518
  _placeAt(e, t) {
@@ -2120,14 +2535,14 @@ var ca = class extends cr {
2120
2535
  if (t.orthographic !== n) {
2121
2536
  if (n) this._setView(!0, this._fittedHalfHeight());
2122
2537
  else {
2123
- let e = this.controls.target, n = this.orthoHeight / 2 / Math.tan(mr.degToRad(t.fov) / 2);
2538
+ let e = this.controls.target, n = this.orthoHeight / 2 / Math.tan(vr.degToRad(t.fov) / 2);
2124
2539
  t.position.sub(e).setLength(n).add(e), this._setView(!1);
2125
2540
  }
2126
2541
  this.controls.update();
2127
2542
  }
2128
2543
  }
2129
2544
  get orthoHeight() {
2130
- return Aa(this.camera);
2545
+ return So(this.camera);
2131
2546
  }
2132
2547
  setOrthoHeight(e) {
2133
2548
  e > 0 && (this._setView(this.camera.orthographic, e / 2), this._onReset?.());
@@ -2140,7 +2555,7 @@ var ca = class extends cr {
2140
2555
  n.orthographic = e, n.orthoHalfHeight = t, n.zoom = 1, n.updateProjectionMatrix(), this._reportOrthoHeight();
2141
2556
  }
2142
2557
  _fittedHalfHeight() {
2143
- return this.camera.position.distanceTo(this.controls.target) * Math.tan(mr.degToRad(this.camera.fov) / 2);
2558
+ return this.camera.position.distanceTo(this.controls.target) * Math.tan(vr.degToRad(this.camera.fov) / 2);
2144
2559
  }
2145
2560
  _reportOrthoHeight() {
2146
2561
  if (!this.camera.orthographic) return;
@@ -2161,7 +2576,7 @@ var ca = class extends cr {
2161
2576
  this.walkControls.release();
2162
2577
  let r = this.interactionManager?.pickSurface(0, 0);
2163
2578
  if (!r) return;
2164
- let i = mr.clamp(r.distance, n.minDistance, n.maxDistance);
2579
+ let i = vr.clamp(r.distance, n.minDistance, n.maxDistance);
2165
2580
  n.target.copy(this.camera.position).addScaledVector(this.camera.getWorldDirection(new $()), i), n.update();
2166
2581
  }
2167
2582
  get navigationMode() {
@@ -2217,7 +2632,7 @@ var ca = class extends cr {
2217
2632
  let n = {
2218
2633
  index: t,
2219
2634
  name: e.name ?? "",
2220
- effects: de(e.userData?.__rayzeeEffects) ?? null
2635
+ effects: ue(e.userData?.__rayzeeEffects) ?? null
2221
2636
  };
2222
2637
  return t === 0 || !e.userData?.__rayzeeUserCamera ? n : {
2223
2638
  ...n,
@@ -2249,7 +2664,7 @@ var ca = class extends cr {
2249
2664
  let n = /* @__PURE__ */ new Map();
2250
2665
  for (let r of e.cameras ?? []) {
2251
2666
  if (r.user) {
2252
- let e = r.orthographic ? new xr(...r.frustum, r.near, r.far) : new Sr(r.fov, r.aspect, r.near, r.far);
2667
+ let e = r.orthographic ? new Er(...r.frustum, r.near, r.far) : new Dr(r.fov, r.aspect, r.near, r.far);
2253
2668
  e.name = r.name, e.zoom = r.zoom ?? 1, e.position.fromArray(r.position), e.quaternion.fromArray(r.quaternion), e.scale.fromArray(r.scale), e.updateProjectionMatrix(), e.updateMatrixWorld(!0), e.userData.__rayzeeUserCamera = !0, e.userData.__rayzeeEffects = me(r.effects), r.orbitTarget && (e.userData.__rayzeeOrbitTarget = new $().fromArray(r.orbitTarget)), n.set(r.index, this.cameras.length), this.cameras.push(e);
2254
2669
  continue;
2255
2670
  }
@@ -2264,7 +2679,7 @@ var ca = class extends cr {
2264
2679
  let r = e.defaultView;
2265
2680
  this._defaultCameraState = r ? {
2266
2681
  position: new $().fromArray(r.position),
2267
- quaternion: new wr().fromArray(r.quaternion),
2682
+ quaternion: new kr().fromArray(r.quaternion),
2268
2683
  scale: new $().fromArray(r.scale),
2269
2684
  fov: r.fov,
2270
2685
  near: r.near,
@@ -2321,14 +2736,14 @@ var ca = class extends cr {
2321
2736
  let c = i;
2322
2737
  if (c?.isReady && c.renderMode?.value === 1 && c.frameCount > 0 && !c.isComplete) return;
2323
2738
  let l = this._pickFocusPoint(c.resetCount), u;
2324
- if (l) u = oa(l, this.camera), this._lastValidFocusDistance = u;
2739
+ if (l) u = Za(l, this.camera), this._lastValidFocusDistance = u;
2325
2740
  else if (this._lastValidFocusDistance !== null) u = this._lastValidFocusDistance;
2326
2741
  else {
2327
- let e = this.controls ? oa(this.controls.target, this.camera) : 0;
2328
- u = e > 0 ? e : Da * (n?.getSceneScale() || 1), this._lastValidFocusDistance = u;
2742
+ let e = this.controls ? Za(this.controls.target, this.camera) : 0;
2743
+ u = e > 0 ? e : yo * (n?.getSceneScale() || 1), this._lastValidFocusDistance = u;
2329
2744
  }
2330
2745
  let d = this._afPointDirty;
2331
- this._afPointDirty = !1, d || this._smoothedFocusDistance === null || this._smoothedFocusDistance === 0 || Math.abs(u - this._smoothedFocusDistance) / this._smoothedFocusDistance > Oa ? this._smoothedFocusDistance = u : this._smoothedFocusDistance += this.afSmoothingFactor * (u - this._smoothedFocusDistance);
2746
+ this._afPointDirty = !1, d || this._smoothedFocusDistance === null || this._smoothedFocusDistance === 0 || Math.abs(u - this._smoothedFocusDistance) / this._smoothedFocusDistance > bo ? this._smoothedFocusDistance = u : this._smoothedFocusDistance += this.afSmoothingFactor * (u - this._smoothedFocusDistance);
2332
2747
  let f = r, p = this._smoothedFocusDistance;
2333
2748
  if (d || f === 0 || Math.abs(p - f) / Math.max(f, .001) > .001) {
2334
2749
  a(p);
@@ -2339,7 +2754,7 @@ var ca = class extends cr {
2339
2754
  worldDistance: p
2340
2755
  });
2341
2756
  let t = Math.abs(p - f) / Math.max(f, .001);
2342
- d ? s?.() : t > Ea && o?.();
2757
+ d ? s?.() : t > vo && o?.();
2343
2758
  }
2344
2759
  }
2345
2760
  _pickFocusPoint(e) {
@@ -2349,8 +2764,8 @@ var ca = class extends cr {
2349
2764
  resetCount: NaN,
2350
2765
  x: NaN,
2351
2766
  y: NaN,
2352
- view: new hr(),
2353
- projection: new hr()
2767
+ view: new br(),
2768
+ projection: new br()
2354
2769
  };
2355
2770
  if (this._afPointDirty || e !== i.resetCount || n !== i.x || r !== i.y || !i.view.equals(t.matrixWorld) || !i.projection.equals(t.projectionMatrix)) {
2356
2771
  let a = this.interactionManager.pickSurface(n * 2 - 1, 1 - r * 2);
@@ -2373,7 +2788,7 @@ var ca = class extends cr {
2373
2788
  dispose() {
2374
2789
  this.walkControls?.dispose(), this.controls?.removeEventListener("change", this._reportOrthoHeight), this.controls?.dispose();
2375
2790
  }
2376
- }, Ma = .001, Na = 2, Pa = (e, t, n, r) => new e(t, n, r, dr).createInterpolant(), Fa = class {
2791
+ }, wo = .001, To = 2, Eo = (e, t, n, r) => new e(t, n, r, hr).createInterpolant(), Do = class {
2377
2792
  constructor(e, t) {
2378
2793
  this._cameraManager = e, this._onChange = t, this.keys = [], this._nextId = 1, this._interpolants = null;
2379
2794
  }
@@ -2383,7 +2798,7 @@ var ca = class extends cr {
2383
2798
  get duration() {
2384
2799
  return this.keys.length ? this.keys[this.keys.length - 1].time : 0;
2385
2800
  }
2386
- addKey(e = this.keys.length ? this.duration + Na : 0) {
2801
+ addKey(e = this.keys.length ? this.duration + To : 0) {
2387
2802
  return this.add(this._cameraManager.captureView(), e);
2388
2803
  }
2389
2804
  updateKey(e) {
@@ -2397,13 +2812,13 @@ var ca = class extends cr {
2397
2812
  let n = {
2398
2813
  id: this._nextId++,
2399
2814
  time: t,
2400
- ...Ia(e)
2815
+ ...Oo(e)
2401
2816
  };
2402
2817
  return this.keys.push(n), this._changed(), n;
2403
2818
  }
2404
2819
  update(e, t) {
2405
2820
  let n = this.get(e);
2406
- n && (Object.assign(n, Ia(t)), this._changed());
2821
+ n && (Object.assign(n, Oo(t)), this._changed());
2407
2822
  }
2408
2823
  setTime(e, t) {
2409
2824
  let n = this.get(e);
@@ -2448,12 +2863,12 @@ var ca = class extends cr {
2448
2863
  orthoHeight: 0
2449
2864
  }) {
2450
2865
  if (!this.keys.length) return null;
2451
- let { position: n, target: r, fov: i, logHeight: a, start: o, end: s } = this._interpolants ??= this._build(), c = mr.clamp(e, o, s);
2866
+ let { position: n, target: r, fov: i, logHeight: a, start: o, end: s } = this._interpolants ??= this._build(), c = vr.clamp(e, o, s);
2452
2867
  return t.position.fromArray(n.evaluate(c)), t.target.fromArray(r.evaluate(c)), t.fov = i.evaluate(c)[0], t.orthoHeight = Math.exp(a.evaluate(c)[0]), t;
2453
2868
  }
2454
2869
  _build() {
2455
2870
  let e = [];
2456
- for (let t of this.keys) e.push(e.length ? Math.max(t.time, e[e.length - 1] + Ma) : t.time);
2871
+ for (let t of this.keys) e.push(e.length ? Math.max(t.time, e[e.length - 1] + wo) : t.time);
2457
2872
  let t = e[0], n = e[e.length - 1], r = this.keys;
2458
2873
  if (r.length > 1) {
2459
2874
  let i = r.length;
@@ -2467,17 +2882,17 @@ var ca = class extends cr {
2467
2882
  return {
2468
2883
  start: t,
2469
2884
  end: n,
2470
- position: Pa(Fr, ".position", e, i((e) => e.position)),
2471
- target: Pa(Fr, ".target", e, i((e) => e.target)),
2472
- fov: Pa(yr, ".fov", e, r.map((e) => e.fov)),
2473
- logHeight: Pa(yr, ".orthoHeight", e, r.map((e) => Math.log(e.orthoHeight)))
2885
+ position: Eo(Br, ".position", e, i((e) => e.position)),
2886
+ target: Eo(Br, ".target", e, i((e) => e.target)),
2887
+ fov: Eo(wr, ".fov", e, r.map((e) => e.fov)),
2888
+ logHeight: Eo(wr, ".orthoHeight", e, r.map((e) => Math.log(e.orthoHeight)))
2474
2889
  };
2475
2890
  }
2476
2891
  _changed() {
2477
2892
  this.keys.sort((e, t) => e.time - t.time), this._interpolants = null, this._onChange?.();
2478
2893
  }
2479
2894
  };
2480
- function Ia({ position: e, target: t, fov: n, orthoHeight: r }) {
2895
+ function Oo({ position: e, target: t, fov: n, orthoHeight: r }) {
2481
2896
  return {
2482
2897
  position: e.clone(),
2483
2898
  target: t.clone(),
@@ -2487,9 +2902,9 @@ function Ia({ position: e, target: t, fov: n, orthoHeight: r }) {
2487
2902
  }
2488
2903
  //#endregion
2489
2904
  //#region src/managers/timeline/TimelineManager.js
2490
- var La = class extends cr {
2905
+ var ko = class extends fr {
2491
2906
  constructor({ cameraManager: e, onReset: t }) {
2492
- super(), this._cameraManager = e, this._onReset = t, this.camera = new Fa(e, () => this._changed("camera")), this._playback = null, this._timer = new Ar(), typeof document < "u" && this._timer.connect(document);
2907
+ super(), this._cameraManager = e, this._onReset = t, this.camera = new Do(e, () => this._changed("camera")), this._playback = null, this._timer = new Fr(), typeof document < "u" && this._timer.connect(document);
2493
2908
  }
2494
2909
  get duration() {
2495
2910
  return this.camera.duration;
@@ -2521,7 +2936,7 @@ var La = class extends cr {
2521
2936
  let e = this._playback;
2522
2937
  if (!e) return;
2523
2938
  this._timer.update(), e.elapsed += this._timer.getDelta();
2524
- let t = mr.clamp(e.elapsed, 0, this.duration);
2939
+ let t = vr.clamp(e.elapsed, 0, this.duration);
2525
2940
  this.seek(t), t >= this.duration && this.stop();
2526
2941
  }
2527
2942
  serialize() {
@@ -2542,14 +2957,14 @@ var La = class extends cr {
2542
2957
  track: e
2543
2958
  });
2544
2959
  }
2545
- }, Ra = class {
2960
+ }, Ao = class {
2546
2961
  constructor(e, t = {}) {
2547
2962
  this.pathTracer = e, this._onReset = t.onReset || null, this._issues = t.issues ?? null, this.texture = null, this.entries = [], this._size = 256;
2548
2963
  }
2549
2964
  async loadLibrary(e, { size: t = 256 } = {}) {
2550
2965
  if (!Array.isArray(e) || e.length === 0) return [];
2551
2966
  this._size = t;
2552
- let n = await Promise.all(e.map((e) => za(e.url))), r = t, i = t, a = n.length, o = new Uint8Array(r * i * a * 4), s = document.createElement("canvas");
2967
+ let n = await Promise.all(e.map((e) => jo(e.url))), r = t, i = t, a = n.length, o = new Uint8Array(r * i * a * 4), s = document.createElement("canvas");
2553
2968
  s.width = r, s.height = i;
2554
2969
  let c = s.getContext("2d", { willReadFrequently: !0 }), l = performance.now();
2555
2970
  for (let e = 0; e < a; e++) {
@@ -2557,8 +2972,8 @@ var La = class extends cr {
2557
2972
  let t = c.getImageData(0, 0, r, i);
2558
2973
  o.set(t.data, e * r * i * 4), performance.now() - l > 16 && (await new Promise((e) => setTimeout(e, 0)), l = performance.now());
2559
2974
  }
2560
- let u = new or(o, r, i, a);
2561
- u.minFilter = X, u.magFilter = X, u.format = Q, u.type = jr, u.generateMipmaps = !1, u.needsUpdate = !0;
2975
+ let u = new ur(o, r, i, a);
2976
+ u.minFilter = X, u.magFilter = X, u.format = Q, u.type = Ir, u.generateMipmaps = !1, u.needsUpdate = !0;
2562
2977
  let d = this.texture;
2563
2978
  return this.texture = u, this.entries = e.map((e, t) => ({
2564
2979
  name: e.name,
@@ -2581,7 +2996,7 @@ var La = class extends cr {
2581
2996
  o.userData.gobo = {
2582
2997
  name: e.name,
2583
2998
  index: e.index,
2584
- intensity: Ba(r),
2999
+ intensity: Mo(r),
2585
3000
  inverted: !!i,
2586
3001
  scale: Math.max(1e-4, a)
2587
3002
  };
@@ -2623,7 +3038,7 @@ var La = class extends cr {
2623
3038
  return t && t.isSpotLight ? t : null;
2624
3039
  }
2625
3040
  };
2626
- async function za(e) {
3041
+ async function jo(e) {
2627
3042
  let t = await v(e);
2628
3043
  try {
2629
3044
  return await new Promise((n, r) => {
@@ -2634,22 +3049,22 @@ async function za(e) {
2634
3049
  t.release();
2635
3050
  }
2636
3051
  }
2637
- function Ba(e) {
3052
+ function Mo(e) {
2638
3053
  return Math.max(0, Math.min(1, e));
2639
3054
  }
2640
3055
  //#endregion
2641
3056
  //#region src/Processor/IESParser.js
2642
- function Va(e, t = "ies") {
3057
+ function No(e, t = "ies") {
2643
3058
  let n = e.search(/TILT\s*=/i);
2644
3059
  if (n < 0) throw Error(`IES (${t}): missing TILT line`);
2645
3060
  let r = e.indexOf("\n", n);
2646
3061
  if (r < 0) throw Error(`IES (${t}): truncated TILT line`);
2647
3062
  let i = e.slice(n, r).match(/TILT\s*=\s*(\w+)/i), a = i ? i[1].toUpperCase() : "NONE", o = e.slice(r);
2648
3063
  if (a === "INCLUDE") {
2649
- let e = Ka(o), t = 2 + 2 * Number(e[1]);
2650
- o = qa(o, t);
3064
+ let e = Ro(o), t = 2 + 2 * Number(e[1]);
3065
+ o = zo(o, t);
2651
3066
  }
2652
- let s = Ka(o), c = 0, l = () => Number(s[c++]), u = l(), d = l(), f = l(), p = l(), m = l(), h = l();
3067
+ let s = Ro(o), c = 0, l = () => Number(s[c++]), u = l(), d = l(), f = l(), p = l(), m = l(), h = l();
2653
3068
  l(), l(), l(), l();
2654
3069
  let g = l();
2655
3070
  if (l(), l(), !Number.isFinite(p) || p <= 0) throw Error(`IES (${t}): invalid vertical angle count ${p}`);
@@ -2675,34 +3090,34 @@ function Va(e, t = "ies") {
2675
3090
  name: t
2676
3091
  };
2677
3092
  }
2678
- function Ha(e, t, n) {
3093
+ function Po(e, t, n) {
2679
3094
  if (t === 0 && n === 90) {
2680
3095
  let t = e % 180;
2681
3096
  return t > 90 ? 180 - t : t;
2682
3097
  }
2683
3098
  return t === 0 && n === 180 ? e > 180 ? 360 - e : e : t === 90 && n === 270 ? e >= 90 && e <= 270 ? e : (540 - e) % 360 : e;
2684
3099
  }
2685
- function Ua(e, t, n) {
3100
+ function Fo(e, t, n) {
2686
3101
  let r = new Uint8Array(t * n), { verticalAngles: i, horizontalAngles: a, candela: o, maxCandela: s, photometricType: c } = e;
2687
3102
  if (s <= 0) return r;
2688
3103
  let l = c === void 0 || c === 1, u = i[0], d = i[i.length - 1], f = a[0], p = a[a.length - 1], m = a.length === 1 || p === f, h = (e, t, n, r) => {
2689
- if (m) return Ya(o[e][0], o[t][0], n);
3104
+ if (m) return Vo(o[e][0], o[t][0], n);
2690
3105
  if (r < f || r > p) return 0;
2691
- let i = Ja(a, r), s = Math.min(i + 1, a.length - 1), c = a[s] - a[i], l = c > 0 ? (r - a[i]) / c : 0;
2692
- return Ya(Ya(o[e][i], o[e][s], l), Ya(o[t][i], o[t][s], l), n);
3106
+ let i = Bo(a, r), s = Math.min(i + 1, a.length - 1), c = a[s] - a[i], l = c > 0 ? (r - a[i]) / c : 0;
3107
+ return Vo(Vo(o[e][i], o[e][s], l), Vo(o[t][i], o[t][s], l), n);
2693
3108
  };
2694
3109
  for (let e = 0; e < n; e++) {
2695
3110
  let a = (e + .5) / n, o = l ? a * 180 : u + a * (d - u);
2696
3111
  if (o < u || o > d) continue;
2697
- let c = Ja(i, o), m = Math.min(c + 1, i.length - 1), g = i[m] - i[c], _ = g > 0 ? (o - i[c]) / g : 0;
3112
+ let c = Bo(i, o), m = Math.min(c + 1, i.length - 1), g = i[m] - i[c], _ = g > 0 ? (o - i[c]) / g : 0;
2698
3113
  for (let n = 0; n < t; n++) {
2699
- let i = (n + .5) / t, a = l ? Ha(i * 360, f, p) : f + i * (p - f), o = Math.min(1, Math.max(0, h(c, m, _, a) / s));
3114
+ let i = (n + .5) / t, a = l ? Po(i * 360, f, p) : f + i * (p - f), o = Math.min(1, Math.max(0, h(c, m, _, a) / s));
2700
3115
  r[e * t + n] = Math.round(o * 255);
2701
3116
  }
2702
3117
  }
2703
3118
  return r;
2704
3119
  }
2705
- function Wa(e, t = .1) {
3120
+ function Io(e, t = .1) {
2706
3121
  let { verticalAngles: n, horizontalAngles: r, candela: i, maxCandela: a } = e, o = Math.PI / 4;
2707
3122
  if (a <= 0 || !n?.length) return o;
2708
3123
  let s = a * t, c = r.length, l = n[n.length - 1], u = !1;
@@ -2717,7 +3132,7 @@ function Wa(e, t = .1) {
2717
3132
  let d = l * Math.PI / 180;
2718
3133
  return Math.min(Math.max(d, 5 * Math.PI / 180), 89 * Math.PI / 180);
2719
3134
  }
2720
- function Ga(e, t, n = .7) {
3135
+ function Lo(e, t, n = .7) {
2721
3136
  let { verticalAngles: r, horizontalAngles: i, candela: a, maxCandela: o } = e;
2722
3137
  if (o <= 0 || !r?.length || t <= 0) return 0;
2723
3138
  let s = o * n, c = i.length, l = 0;
@@ -2730,15 +3145,15 @@ function Ga(e, t, n = .7) {
2730
3145
  let u = t * 180 / Math.PI, d = u > 0 ? 1 - l / u : 0;
2731
3146
  return Math.min(Math.max(d, 0), 1);
2732
3147
  }
2733
- function Ka(e) {
3148
+ function Ro(e) {
2734
3149
  return e.split(/\s+/).filter((e) => e.length > 0);
2735
3150
  }
2736
- function qa(e, t) {
3151
+ function zo(e, t) {
2737
3152
  let n = /\S+/g, r = 0;
2738
3153
  for (; n.exec(e) !== null;) if (r++, r === t) return e.slice(n.lastIndex);
2739
3154
  return "";
2740
3155
  }
2741
- function Ja(e, t) {
3156
+ function Bo(e, t) {
2742
3157
  if (t <= e[0]) return 0;
2743
3158
  if (t >= e[e.length - 1]) return e.length - 1;
2744
3159
  let n = 0, r = e.length - 1;
@@ -2748,12 +3163,12 @@ function Ja(e, t) {
2748
3163
  }
2749
3164
  return n;
2750
3165
  }
2751
- function Ya(e, t, n) {
3166
+ function Vo(e, t, n) {
2752
3167
  return e + (t - e) * n;
2753
3168
  }
2754
3169
  //#endregion
2755
3170
  //#region src/managers/IESManager.js
2756
- var Xa = class {
3171
+ var Ho = class {
2757
3172
  constructor(e, t = {}) {
2758
3173
  this.pathTracer = e, this._onReset = t.onReset || null, this._issues = t.issues ?? null, this.texture = null, this.entries = [], this._gridWidth = 128, this._gridHeight = 128;
2759
3174
  }
@@ -2762,11 +3177,11 @@ var Xa = class {
2762
3177
  this._gridWidth = t, this._gridHeight = n;
2763
3178
  let r = (await Promise.all(e.map(async (e) => {
2764
3179
  try {
2765
- let { file: r, release: i } = await m().fetch(e.url), a = Va(await r.text().finally(i), e.name);
3180
+ let { file: r, release: i } = await m().fetch(e.url), a = No(await r.text().finally(i), e.name);
2766
3181
  return {
2767
3182
  it: e,
2768
3183
  profile: a,
2769
- grid: Ua(a, t, n)
3184
+ grid: Fo(a, t, n)
2770
3185
  };
2771
3186
  } catch (t) {
2772
3187
  return this._issues?.warn(Ze.ASSET_UNREACHABLE, `IES profile "${e.name}" could not be loaded: ${t.message}`, {
@@ -2784,19 +3199,19 @@ var Xa = class {
2784
3199
  let r = t[e];
2785
3200
  o[n + e * 4 + 0] = r, o[n + e * 4 + 1] = r, o[n + e * 4 + 2] = r, o[n + e * 4 + 3] = 255;
2786
3201
  }
2787
- let i = r[e].profile, c = Wa(i);
3202
+ let i = r[e].profile, c = Io(i);
2788
3203
  s.push({
2789
3204
  name: r[e].it.name,
2790
3205
  index: e,
2791
3206
  maxCandela: i.maxCandela,
2792
3207
  photometricType: i.photometricType,
2793
3208
  suggestedAngle: c,
2794
- suggestedPenumbra: Ga(i, c),
3209
+ suggestedPenumbra: Lo(i, c),
2795
3210
  lumens: i.lumens
2796
3211
  });
2797
3212
  }
2798
- let c = new or(o, t, n, i);
2799
- c.format = Q, c.type = jr, c.minFilter = X, c.magFilter = X, c.generateMipmaps = !1, c.needsUpdate = !0;
3213
+ let c = new ur(o, t, n, i);
3214
+ c.format = Q, c.type = Ir, c.minFilter = X, c.magFilter = X, c.generateMipmaps = !1, c.needsUpdate = !0;
2800
3215
  let l = this.texture;
2801
3216
  return this.texture = c, this.entries = s, this.pathTracer.iesProfiles = c, this.pathTracer.shaderBuilder?.updateIESProfiles?.(c), l?.dispose?.(), this.entries.map(({ name: e, index: t }) => ({
2802
3217
  name: e,
@@ -2827,7 +3242,7 @@ var Xa = class {
2827
3242
  l = Number.isFinite(e.lumens) ? e.lumens : null, i.userData.ies = {
2828
3243
  name: e.name,
2829
3244
  index: e.index,
2830
- intensity: Za(n),
3245
+ intensity: Uo(n),
2831
3246
  fixtureLumens: l
2832
3247
  }, r && (Number.isFinite(e.suggestedAngle) && (i.angle = e.suggestedAngle, o = e.suggestedAngle), Number.isFinite(e.suggestedPenumbra) && (i.penumbra = e.suggestedPenumbra, s = e.suggestedPenumbra), i.decay = 2, c = 2);
2833
3248
  }
@@ -2850,16 +3265,16 @@ var Xa = class {
2850
3265
  return t && t.isSpotLight ? t : null;
2851
3266
  }
2852
3267
  };
2853
- function Za(e) {
3268
+ function Uo(e) {
2854
3269
  return Math.max(0, Math.min(1, e));
2855
3270
  }
2856
3271
  //#endregion
2857
3272
  //#region src/Passes/OIDNDenoiser.js
2858
- var Qa = Ke("oidn"), $a = 16, eo = null;
2859
- async function to() {
2860
- return eo ||= (await import("oidn-web/dist/oidn.js")).initUNetFromBuffer, eo;
3273
+ var Wo = Ke("oidn"), Go = 16, Ko = null;
3274
+ async function qo() {
3275
+ return Ko ||= (await import("oidn-web/dist/oidn.js")).initUNetFromBuffer, Ko;
2861
3276
  }
2862
- var no = {
3277
+ var Jo = {
2863
3278
  QUALITY_MODELS: {
2864
3279
  fast: {
2865
3280
  model: "rt_hdr_alb_nrm_small",
@@ -2883,9 +3298,9 @@ var no = {
2883
3298
  oidnQuality: "fast",
2884
3299
  tileSize: 1024
2885
3300
  }
2886
- }, ro = .18, io = 256, ao = 256, oo = `
2887
- const WG: u32 = ${io}u;
2888
- const GROUPS: u32 = ${ao}u;
3301
+ }, Yo = .18, Xo = 256, Zo = 256, Qo = `
3302
+ const WG: u32 = ${Xo}u;
3303
+ const GROUPS: u32 = ${Zo}u;
2889
3304
 
2890
3305
  @group(0) @binding(0) var<storage, read> col: array<vec4<f32>>;
2891
3306
  @group(0) @binding(1) var<storage, read_write> partials: array<f32>;
@@ -2904,7 +3319,7 @@ fn treeSum( lid: u32 ) {
2904
3319
  }
2905
3320
  }
2906
3321
 
2907
- @compute @workgroup_size(${io})
3322
+ @compute @workgroup_size(${Xo})
2908
3323
  fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
2909
3324
  @builtin(local_invocation_id) lid: vec3<u32>,
2910
3325
  @builtin(workgroup_id) wid: vec3<u32> ) {
@@ -2927,7 +3342,7 @@ fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
2927
3342
  if ( lid.x == 0u ) { partials[ wid.x ] = sdata[ 0 ]; }
2928
3343
  }
2929
3344
 
2930
- @compute @workgroup_size(${io})
3345
+ @compute @workgroup_size(${Xo})
2931
3346
  fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
2932
3347
 
2933
3348
  var v = 0.0;
@@ -2937,12 +3352,12 @@ fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
2937
3352
  treeSum( lid.x );
2938
3353
 
2939
3354
  if ( lid.x == 0u ) {
2940
- let scale = ${ro} / exp2( sdata[ 0 ] / f32( params.x ) );
3355
+ let scale = ${Yo} / exp2( sdata[ 0 ] / f32( params.x ) );
2941
3356
  // Mirrors the CPU guard: a non-finite or non-positive scale means no scaling at all.
2942
3357
  scaleOut[ 0 ] = select( 1.0, scale, scale > 0.0 && scale < 3.4e38 );
2943
3358
  }
2944
3359
  }
2945
- `, so = "\n@group(0) @binding(0) var<storage, read_write> col: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> scaleBuf: array<f32>;\n\n@compute @workgroup_size(64)\nfn main( @builtin(global_invocation_id) gid: vec3<u32>,\n @builtin(num_workgroups) nwg: vec3<u32> ) {\n let i = gid.y * nwg.x * 64u + gid.x;\n if ( i >= arrayLength( &col ) ) { return; }\n let c = col[ i ];\n col[ i ] = vec4<f32>( c.xyz * scaleBuf[ 0 ], c.w );\n}\n", co = 64, lo = 32768, uo = 16, fo = 32, po = `
3360
+ `, $o = "\n@group(0) @binding(0) var<storage, read_write> col: array<vec4<f32>>;\n@group(0) @binding(1) var<storage, read> scaleBuf: array<f32>;\n\n@compute @workgroup_size(64)\nfn main( @builtin(global_invocation_id) gid: vec3<u32>,\n @builtin(num_workgroups) nwg: vec3<u32> ) {\n let i = gid.y * nwg.x * 64u + gid.x;\n if ( i >= arrayLength( &col ) ) { return; }\n let c = col[ i ];\n col[ i ] = vec4<f32>( c.xyz * scaleBuf[ 0 ], c.w );\n}\n", es = 64, ts = 32768, ns = 16, rs = 32, is = `
2946
3361
  struct UnpackParams {
2947
3362
  srcWidth: u32,
2948
3363
  tileX: u32,
@@ -2960,7 +3375,7 @@ struct UnpackParams {
2960
3375
  @group(0) @binding(3) var<storage, read> inColor: array<vec4<f32>>;
2961
3376
  @group(0) @binding(4) var dst: texture_storage_2d<rgba16float, write>;
2962
3377
 
2963
- @compute @workgroup_size(${uo}, ${uo})
3378
+ @compute @workgroup_size(${ns}, ${ns})
2964
3379
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
2965
3380
 
2966
3381
  if ( gid.x >= P.tileW || gid.y >= P.tileH ) { return; }
@@ -2974,18 +3389,18 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
2974
3389
  // survives the denoise.
2975
3390
  textureStore( dst, vec2<u32>( px, py ), vec4<f32>( src[ si ].xyz / scaleBuf[ 0 ], inColor[ si ].w ) );
2976
3391
  }
2977
- `, mo = 8, ho = `
3392
+ `, as = 8, os = `
2978
3393
  @group(0) @binding(0) var src: texture_2d<f32>;
2979
3394
  @group(0) @binding(1) var<storage, read_write> dst: array<vec4<f32>>;
2980
3395
  @group(0) @binding(2) var<uniform> size: vec2<u32>;
2981
3396
 
2982
- @compute @workgroup_size(${mo}, ${mo})
3397
+ @compute @workgroup_size(${as}, ${as})
2983
3398
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
2984
3399
 
2985
3400
  if ( gid.x >= size.x || gid.y >= size.y ) { return; }
2986
3401
  dst[ gid.y * size.x + gid.x ] = textureLoad( src, gid.xy, 0 );
2987
3402
  }
2988
- `, go = class extends cr {
3403
+ `, ss = class extends fr {
2989
3404
  constructor(e, t = {}) {
2990
3405
  if (super(), !e) throw Error("OIDNDenoiser requires a renderer");
2991
3406
  this.renderer = e, this._renderWidth = e.domElement.width, this._renderHeight = e.domElement.height, this.backendParamsGetter = t.backendParams || null, this.getGPUTextures = t.getGPUTextures || null, this.gpuDevice = null, this._gpuInputBuffers = {
@@ -2999,14 +3414,14 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
2999
3414
  width: 0,
3000
3415
  height: 0
3001
3416
  }, this.config = {
3002
- ...no.DEFAULT_OPTIONS,
3417
+ ...Jo.DEFAULT_OPTIONS,
3003
3418
  ...t
3004
3419
  }, this.enabled = this.config.enableOIDN, this.quality = this.config.oidnQuality, this.maxTileSize = this.config.tileSize, this._activeTileSize = 0, this.state = {
3005
3420
  isDenoising: !1,
3006
3421
  isLoading: !1,
3007
3422
  abortController: null
3008
3423
  }, this._tilesWritten = 0, this._runId = 0, this._hasOutput = !1, this.lastDenoiseMs = 0, this.currentTZAUrl = null, this.unet = null, this._weights = /* @__PURE__ */ new Map(), this._pendingStart = !1, this._pendingStartContinuous = !1, this._reloadPending = !1, this._initialize().catch((e) => {
3009
- Qa.error("init failed:", e), this.dispatchEvent({
3424
+ Wo.error("init failed:", e), this.dispatchEvent({
3010
3425
  type: "error",
3011
3426
  error: e
3012
3427
  });
@@ -3020,7 +3435,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3020
3435
  }
3021
3436
  }
3022
3437
  expectsCleanAux(e = this.quality) {
3023
- let { QUALITY_MODELS: t } = no;
3438
+ let { QUALITY_MODELS: t } = Jo;
3024
3439
  return (t[e] || t.balance).cleanAux;
3025
3440
  }
3026
3441
  getRuntimeInfo() {
@@ -3035,8 +3450,8 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3035
3450
  _resolveTileSize() {
3036
3451
  let e = Math.max(this._renderWidth, this._renderHeight);
3037
3452
  if (!e) return this.maxTileSize;
3038
- let t = Math.ceil(e / $a) * $a;
3039
- return t <= this.maxTileSize ? t : Math.max($a, Math.floor(this.maxTileSize / $a) * $a);
3453
+ let t = Math.ceil(e / Go) * Go;
3454
+ return t <= this.maxTileSize ? t : Math.max(Go, Math.floor(this.maxTileSize / Go) * Go);
3040
3455
  }
3041
3456
  _setupUNetDenoiser() {
3042
3457
  return this.state.isLoading ? (this._reloadPending = !0, Promise.resolve()) : (this._loading = this._loadUNet(), this._loading);
@@ -3050,7 +3465,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3050
3465
  try {
3051
3466
  await this._loadUNetWeights();
3052
3467
  } catch (e) {
3053
- Qa.error("UNet weights failed to load:", e), this.dispatchEvent({
3468
+ Wo.error("UNet weights failed to load:", e), this.dispatchEvent({
3054
3469
  type: "error",
3055
3470
  error: /* @__PURE__ */ Error(`Denoiser loading failed: ${e.message}`),
3056
3471
  url: this._generateTzaUrl()
@@ -3076,26 +3491,26 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3076
3491
  let e = this.backendParamsGetter();
3077
3492
  this.gpuDevice = e?.device ?? null, n = e?.device ? e : void 0;
3078
3493
  }
3079
- this.unet = await (await to())(await this._fetchWeights(e), n, {
3494
+ this.unet = await (await qo())(await this._fetchWeights(e), n, {
3080
3495
  aux: !0,
3081
3496
  hdr: !0,
3082
3497
  maxTileSize: t,
3083
3498
  dynamicTile: !1
3084
- }), this.currentTZAUrl = e, this._activeTileSize = t, this.dispatchEvent({ type: "loaded" }), Qa.debug("UNet weights loaded:", e);
3499
+ }), this.currentTZAUrl = e, this._activeTileSize = t, this.dispatchEvent({ type: "loaded" }), Wo.debug("UNet weights loaded:", e);
3085
3500
  }
3086
3501
  _fetchWeights(e) {
3087
3502
  let t = this._weights.get(e);
3088
3503
  return t || (t = m().fetch(e, { policy: C.IMMUTABLE }).then(({ file: e, release: t }) => e.arrayBuffer().finally(t)), t.catch(() => this._weights.delete(e)), this._weights.set(e, t)), t;
3089
3504
  }
3090
3505
  _generateTzaUrl() {
3091
- let { oidnWeightsBaseUrl: e } = at(), { QUALITY_MODELS: t } = no;
3506
+ let { oidnWeightsBaseUrl: e } = ot(), { QUALITY_MODELS: t } = Jo;
3092
3507
  return `${e}${(t[this.quality] || t.balance).model}.tza`;
3093
3508
  }
3094
3509
  async updateConfiguration(e) {
3095
3510
  Object.keys(e).some((t) => this.config[t] !== e[t]) && (Object.assign(this.config, e), this.quality = this.config.oidnQuality, this.maxTileSize = this.config.tileSize, await this._setupUNetDenoiser());
3096
3511
  }
3097
3512
  async updateQuality(e) {
3098
- if (!Object.prototype.hasOwnProperty.call(no.QUALITY_MODELS, e)) throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(no.QUALITY_MODELS).join(", ")}`);
3513
+ if (!Object.prototype.hasOwnProperty.call(Jo.QUALITY_MODELS, e)) throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(Jo.QUALITY_MODELS).join(", ")}`);
3099
3514
  await this.updateConfiguration({ oidnQuality: e });
3100
3515
  }
3101
3516
  async start({ continuous: e = !1 } = {}) {
@@ -3106,7 +3521,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3106
3521
  continuous: e
3107
3522
  });
3108
3523
  let t = performance.now(), n = await this.execute(e);
3109
- return n && (this.renderer?.resetState?.(), this.lastDenoiseMs = performance.now() - t, Qa.debug(`denoise complete in ${We.ms(this.lastDenoiseMs)} · quality ${this.quality}`)), n;
3524
+ return n && (this.renderer?.resetState?.(), this.lastDenoiseMs = performance.now() - t, Wo.debug(`denoise complete in ${We.ms(this.lastDenoiseMs)} · quality ${this.quality}`)), n;
3110
3525
  }
3111
3526
  async execute(e = !1) {
3112
3527
  if (!this.enabled || !this.unet) return !1;
@@ -3115,7 +3530,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3115
3530
  try {
3116
3531
  return await this._executeUNetGPU(e) !== !1;
3117
3532
  } catch (e) {
3118
- return e.name === "AbortError" ? Qa.debug("denoise aborted") : Qa.error("denoise error:", e), !1;
3533
+ return e.name === "AbortError" ? Wo.debug("denoise aborted") : Wo.error("denoise error:", e), !1;
3119
3534
  } finally {
3120
3535
  this._runId === t && (this.state.isDenoising = !1, this.state.abortController = null), this.dispatchEvent({
3121
3536
  type: "end",
@@ -3125,11 +3540,11 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3125
3540
  }
3126
3541
  async _executeUNetGPU(e = !1) {
3127
3542
  let t = this._renderWidth, n = this._renderHeight;
3128
- if (!this.getGPUTextures) return Qa.warn("GPU mode enabled but getGPUTextures not provided"), !1;
3543
+ if (!this.getGPUTextures) return Wo.warn("GPU mode enabled but getGPUTextures not provided"), !1;
3129
3544
  let r = this.getGPUTextures({ continuous: e });
3130
- if (!r?.color) return Qa.warn("GPU textures not ready yet"), !1;
3545
+ if (!r?.color) return Wo.warn("GPU textures not ready yet"), !1;
3131
3546
  let i = this.gpuDevice;
3132
- if (!i) return Qa.warn("gpuDevice not available"), !1;
3547
+ if (!i) return Wo.warn("gpuDevice not available"), !1;
3133
3548
  this._ensureGPUInputBuffers(t, n), this._copyInputs(i, r, t, n), this._computeInputScale(i, t * n), this._applyColorScale(i, t * n), !e && !this._hasOutput && this._unpackToTexture(this._gpuInputBuffers.color, t, {
3134
3549
  x: 0,
3135
3550
  y: 0,
@@ -3173,7 +3588,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3173
3588
  resource: { buffer: this._packParams }
3174
3589
  }
3175
3590
  ]
3176
- })), o.dispatchWorkgroups(Math.ceil(n / mo), Math.ceil(r / mo))) : i.copyTextureToBuffer({
3591
+ })), o.dispatchWorkgroups(Math.ceil(n / as), Math.ceil(r / as))) : i.copyTextureToBuffer({
3177
3592
  texture: t,
3178
3593
  mipLevel: 0
3179
3594
  }, {
@@ -3237,7 +3652,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3237
3652
  compute: {
3238
3653
  module: e.createShaderModule({
3239
3654
  label: "oidn-pack",
3240
- code: ho
3655
+ code: os
3241
3656
  }),
3242
3657
  entryPoint: "main"
3243
3658
  }
@@ -3290,7 +3705,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3290
3705
  });
3291
3706
  let t = e.createShaderModule({
3292
3707
  label: "oidn-autoexposure",
3293
- code: oo
3708
+ code: Qo
3294
3709
  }), n = e.createPipelineLayout({ bindGroupLayouts: [this._lumLayout] });
3295
3710
  this._lumReducePipeline = e.createComputePipeline({
3296
3711
  label: "oidn-autoexposure-reduce",
@@ -3314,7 +3729,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3314
3729
  compute: {
3315
3730
  module: e.createShaderModule({
3316
3731
  label: "oidn-color-scale",
3317
- code: so
3732
+ code: $o
3318
3733
  }),
3319
3734
  entryPoint: "main"
3320
3735
  }
@@ -3324,7 +3739,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3324
3739
  compute: {
3325
3740
  module: e.createShaderModule({
3326
3741
  label: "oidn-output-unpack",
3327
- code: po
3742
+ code: is
3328
3743
  }),
3329
3744
  entryPoint: "main"
3330
3745
  }
@@ -3334,7 +3749,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3334
3749
  size: 4
3335
3750
  }), this._lumPartials = e.createBuffer({
3336
3751
  label: "oidn-autoexposure-partials",
3337
- size: ao * 4,
3752
+ size: Zo * 4,
3338
3753
  usage: GPUBufferUsage.STORAGE
3339
3754
  }), this._lumParams = e.createBuffer({
3340
3755
  label: "oidn-autoexposure-params",
@@ -3386,13 +3801,13 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3386
3801
  0
3387
3802
  ]));
3388
3803
  let n = e.createCommandEncoder({ label: "oidn-autoexposure" }), r = n.beginComputePass({ label: "oidn-autoexposure-reduce" });
3389
- r.setPipeline(this._lumReducePipeline), r.setBindGroup(0, this._lumBindGroup), r.dispatchWorkgroups(ao, 1, 1), r.end();
3804
+ r.setPipeline(this._lumReducePipeline), r.setBindGroup(0, this._lumBindGroup), r.dispatchWorkgroups(Zo, 1, 1), r.end();
3390
3805
  let i = n.beginComputePass({ label: "oidn-autoexposure-finalize" });
3391
3806
  i.setPipeline(this._lumFinalizePipeline), i.setBindGroup(0, this._lumBindGroup), i.dispatchWorkgroups(1, 1, 1), i.end(), e.queue.submit([n.finish()]);
3392
3807
  }
3393
3808
  _applyColorScale(e, t) {
3394
3809
  if (!this._ensureScalePipelines(e)) return;
3395
- let n = Math.ceil(t / co), r = Math.min(n, lo), i = Math.ceil(n / r), a = e.createCommandEncoder({ label: "oidn-color-scale" }), o = a.beginComputePass({ label: "oidn-color-scale" });
3810
+ let n = Math.ceil(t / es), r = Math.min(n, ts), i = Math.ceil(n / r), a = e.createCommandEncoder({ label: "oidn-color-scale" }), o = a.beginComputePass({ label: "oidn-color-scale" });
3396
3811
  o.setPipeline(this._colorScalePipeline), o.setBindGroup(0, this._colorScaleBindGroup), o.dispatchWorkgroups(r, i, 1), o.end(), e.queue.submit([a.finish()]);
3397
3812
  }
3398
3813
  get outputTexture() {
@@ -3414,12 +3829,12 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3414
3829
  format: "rgba16float",
3415
3830
  usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC
3416
3831
  });
3417
- let r = new vn(this._outGPUTexture);
3832
+ let r = new yn(this._outGPUTexture);
3418
3833
  r.name = "oidn:output", r.image = {
3419
3834
  width: t,
3420
3835
  height: n,
3421
3836
  depth: 1
3422
- }, r.type = ur, r.format = Q, r.colorSpace = vr, r.minFilter = Z, r.magFilter = Z, r.wrapS = nr, r.wrapT = nr, r.generateMipmaps = !1, r.flipY = !1, this._outTexture = r, this._outTexSize = {
3837
+ }, r.type = mr, r.format = Q, r.colorSpace = Cr, r.minFilter = Z, r.magFilter = Z, r.wrapS = or, r.wrapT = or, r.generateMipmaps = !1, r.flipY = !1, this._outTexture = r, this._outTexSize = {
3423
3838
  width: t,
3424
3839
  height: n
3425
3840
  };
@@ -3437,7 +3852,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3437
3852
  if (this._ensureOutputTexture(i, this._renderWidth, this._renderHeight), !this._outGPUTexture) return;
3438
3853
  let l = i.createBuffer({
3439
3854
  label: "oidn-unpack-params",
3440
- size: fo,
3855
+ size: rs,
3441
3856
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
3442
3857
  });
3443
3858
  try {
@@ -3477,7 +3892,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3477
3892
  }
3478
3893
  ]
3479
3894
  }), u = i.createCommandEncoder({ label: "oidn-output-unpack" }), d = u.beginComputePass({ label: "oidn-output-unpack" });
3480
- d.setPipeline(this._unpackPipeline), d.setBindGroup(0, n), d.dispatchWorkgroups(Math.ceil(s / uo), Math.ceil(c / uo), 1), d.end(), i.queue.submit([u.finish()]), r && (this._hasOutput = !0);
3895
+ d.setPipeline(this._unpackPipeline), d.setBindGroup(0, n), d.dispatchWorkgroups(Math.ceil(s / ns), Math.ceil(c / ns), 1), d.end(), i.queue.submit([u.finish()]), r && (this._hasOutput = !0);
3481
3896
  } finally {
3482
3897
  l.destroy();
3483
3898
  }
@@ -3526,7 +3941,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3526
3941
  }
3527
3942
  _displayGPUOutput({ data: e, width: t, height: n }) {
3528
3943
  if (!this.gpuDevice) {
3529
- Qa.error("gpuDevice not available for the output picture");
3944
+ Wo.error("gpuDevice not available for the output picture");
3530
3945
  return;
3531
3946
  }
3532
3947
  this._unpackToTexture(e, t, {
@@ -3537,7 +3952,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3537
3952
  });
3538
3953
  }
3539
3954
  abort() {
3540
- this._pendingStart = !1, this._pendingStartContinuous = !1, !(!this.enabled || !this.state.isDenoising) && (this.state.abortController?.abort(), this.state.isDenoising = !1, Qa.debug("denoise aborted"));
3955
+ this._pendingStart = !1, this._pendingStartContinuous = !1, !(!this.enabled || !this.state.isDenoising) && (this.state.abortController?.abort(), this.state.isDenoising = !1, Wo.debug("denoise aborted"));
3541
3956
  }
3542
3957
  get hasOutput() {
3543
3958
  return this._hasOutput;
@@ -3548,13 +3963,13 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3548
3963
  setSize(e, t) {
3549
3964
  if (e <= 0 || t <= 0) throw Error(`Invalid dimensions: ${e}x${t}`);
3550
3965
  this._renderWidth = e, this._renderHeight = t, this._hasOutput = !1, this.lastDenoiseMs = 0, this._setupUNetDenoiser().catch((e) => {
3551
- Qa.error("reinitialize after size change failed:", e);
3966
+ Wo.error("reinitialize after size change failed:", e);
3552
3967
  });
3553
3968
  }
3554
3969
  dispose() {
3555
- this.abort(), this.unet?.dispose(), this._destroyGPUInputBuffers(), this._releaseOutputTexture(), this._colorScalePipeline = null, this._lumReducePipeline = null, this._lumFinalizePipeline = null, this._lumLayout = null, this._unpackPipeline = null, this.unet = null, this._weights.clear(), this.state.abortController = null, this.removeAllListeners?.(), Qa.debug("disposed");
3970
+ this.abort(), this.unet?.dispose(), this._destroyGPUInputBuffers(), this._releaseOutputTexture(), this._colorScalePipeline = null, this._lumReducePipeline = null, this._lumFinalizePipeline = null, this._lumLayout = null, this._unpackPipeline = null, this.unet = null, this._weights.clear(), this.state.abortController = null, this.removeAllListeners?.(), Wo.debug("disposed");
3556
3971
  }
3557
- }, _o = Object.freeze({
3972
+ }, cs = Object.freeze({
3558
3973
  maxLength: 8,
3559
3974
  smoothLength: 2,
3560
3975
  roughStart: .45,
@@ -3562,7 +3977,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3562
3977
  depthTolerance: .05,
3563
3978
  normalTolerance: .8,
3564
3979
  movedLength: 2
3565
- }), vo = 8, yo = 304, bo = 16, xo = 1, So = 2, Co = 4, wo = 1073741824, To = "\nstruct Params {\n size: vec2<u32>,\n reset: u32,\n flags: u32,\n maxLength: f32,\n smoothLength: f32,\n depthTolerance: f32,\n normalTolerance: f32,\n roughStart: f32,\n roughEnd: f32,\n samples: f32,\n historyScale: f32,\n camWorld: mat4x4<f32>,\n projInv: mat4x4<f32>,\n prevViewProj: mat4x4<f32>,\n prevCamPos: vec4<f32>,\n moved: vec4<u32>,\n movedLength: f32,\n prevCamDir: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> P: Params;\n\nfn finite3( v: vec3<f32> ) -> bool {\n let e = bitcast<vec3<u32>>( v ) & vec3<u32>( 0x7f800000u );\n return all( e != vec3<u32>( 0x7f800000u ) );\n}\n\n// [0,1]-encoded in and out, renormalised like FinalWrite's clean aux.\nfn mixNormal( h: vec3<f32>, c: vec3<f32>, t: f32 ) -> vec3<f32> {\n let m = mix( h * 2.0 - 1.0, c * 2.0 - 1.0, t );\n let l = length( m );\n return select( c, m / l * 0.5 + 0.5, l > 1e-4 );\n}\n", Eo = To + `
3980
+ }), ls = 8, us = 304, ds = 16, fs = 1, ps = 2, ms = 4, hs = 1073741824, gs = "\nstruct Params {\n size: vec2<u32>,\n reset: u32,\n flags: u32,\n maxLength: f32,\n smoothLength: f32,\n depthTolerance: f32,\n normalTolerance: f32,\n roughStart: f32,\n roughEnd: f32,\n samples: f32,\n historyScale: f32,\n camWorld: mat4x4<f32>,\n projInv: mat4x4<f32>,\n prevViewProj: mat4x4<f32>,\n prevCamPos: vec4<f32>,\n moved: vec4<u32>,\n movedLength: f32,\n prevCamDir: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> P: Params;\n\nfn finite3( v: vec3<f32> ) -> bool {\n let e = bitcast<vec3<u32>>( v ) & vec3<u32>( 0x7f800000u );\n return all( e != vec3<u32>( 0x7f800000u ) );\n}\n\n// [0,1]-encoded in and out, renormalised like FinalWrite's clean aux.\nfn mixNormal( h: vec3<f32>, c: vec3<f32>, t: f32 ) -> vec3<f32> {\n let m = mix( h * 2.0 - 1.0, c * 2.0 - 1.0, t );\n let l = length( m );\n return select( c, m / l * 0.5 + 0.5, l > 1e-4 );\n}\n", _s = gs + `
3566
3981
  @group(0) @binding(1) var geoCur: texture_2d<f32>;
3567
3982
  @group(0) @binding(2) var geoPrev: texture_2d<f32>;
3568
3983
  @group(0) @binding(3) var<storage, read_write> picked: array<i32>;
@@ -3588,7 +4003,7 @@ fn movedIndex( leaf: u32 ) -> i32 {
3588
4003
 
3589
4004
  }
3590
4005
 
3591
- @compute @workgroup_size(${vo}, ${vo})
4006
+ @compute @workgroup_size(${ls}, ${ls})
3592
4007
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3593
4008
 
3594
4009
  if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
@@ -3598,12 +4013,12 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3598
4013
  var pick = -1;
3599
4014
  var movedFlag = 0;
3600
4015
 
3601
- if ( P.reset == 0u && g.w < ${Br.toFixed(1)} ) {
4016
+ if ( P.reset == 0u && g.w < ${Gr.toFixed(1)} ) {
3602
4017
 
3603
4018
  let size = vec2<f32>( P.size );
3604
4019
  let uv = ( vec2<f32>( gid.xy ) + 0.5 ) / size;
3605
4020
  // Depth is along the ray: from the camera, or from its image plane when orthographic.
3606
- let ortho = ( P.flags & ${Co}u ) != 0u;
4021
+ let ortho = ( P.flags & ${ms}u ) != 0u;
3607
4022
  let ndc = vec2<f32>( uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0 );
3608
4023
  var origin = P.camWorld[ 3 ].xyz;
3609
4024
  var dir: vec3<f32>;
@@ -3627,7 +4042,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3627
4042
  let toPrev = movedToPrev[ u32( m ) ];
3628
4043
  wp = ( toPrev * vec4<f32>( wp, 1.0 ) ).xyz;
3629
4044
  n = normalize( ( toPrev * vec4<f32>( n, 0.0 ) ).xyz );
3630
- movedFlag = ${wo};
4045
+ movedFlag = ${hs};
3631
4046
 
3632
4047
  }
3633
4048
 
@@ -3664,7 +4079,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3664
4079
  if ( pick >= 0 ) { atomicAdd( &copies[ u32( pick ) ], 1u ); }
3665
4080
 
3666
4081
  }
3667
- `, Do = To + `
4082
+ `, vs = gs + `
3668
4083
  @group(0) @binding(1) var curColor: texture_2d<f32>;
3669
4084
  @group(0) @binding(2) var curAlbedo: texture_2d<f32>;
3670
4085
  @group(0) @binding(3) var curNormal: texture_2d<f32>;
@@ -3678,7 +4093,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3678
4093
  @group(0) @binding(11) var outAlbedo: texture_storage_2d<rgba32float, write>;
3679
4094
  @group(0) @binding(12) var outNormal: texture_storage_2d<rgba32float, write>;
3680
4095
 
3681
- @compute @workgroup_size(${vo}, ${vo})
4096
+ @compute @workgroup_size(${ls}, ${ls})
3682
4097
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3683
4098
 
3684
4099
  if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
@@ -3694,8 +4109,8 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3694
4109
  var ha = ca.xyz;
3695
4110
  var hn = cn.xyz;
3696
4111
  let raw = picked[ gid.y * P.size.x + gid.x ];
3697
- let movedPx = raw >= 0 && ( raw & ${wo} ) != 0;
3698
- let pick = select( raw, raw & ~${wo}, raw >= 0 );
4112
+ let movedPx = raw >= 0 && ( raw & ${hs} ) != 0;
4113
+ let pick = select( raw, raw & ~${hs}, raw >= 0 );
3699
4114
 
3700
4115
  if ( pick >= 0 ) {
3701
4116
 
@@ -3709,7 +4124,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3709
4124
  ha = a.xyz;
3710
4125
  hn = textureLoad( histNormal, q, 0 ).xyz;
3711
4126
  len = a.w;
3712
- if ( ( P.flags & ${So}u ) != 0u ) { len = len / f32( max( copies[ u32( pick ) ], 1u ) ); }
4127
+ if ( ( P.flags & ${ps}u ) != 0u ) { len = len / f32( max( copies[ u32( pick ) ], 1u ) ); }
3713
4128
 
3714
4129
  }
3715
4130
 
@@ -3723,11 +4138,11 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3723
4138
 
3724
4139
  textureStore( outColor, p, vec4<f32>( mix( hc, cur.xyz, t ), cur.w ) );
3725
4140
  textureStore( outAlbedo, p, vec4<f32>( mix( ha, ca.xyz, t ), newLen ) );
3726
- let n = select( cn.xyz, mixNormal( hn, cn.xyz, t ), ( P.flags & ${xo}u ) != 0u );
4141
+ let n = select( cn.xyz, mixNormal( hn, cn.xyz, t ), ( P.flags & ${fs}u ) != 0u );
3727
4142
  textureStore( outNormal, p, vec4<f32>( n, cn.w ) );
3728
4143
 
3729
4144
  }
3730
- `, Oo = To + `
4145
+ `, ys = gs + `
3731
4146
  @group(0) @binding(1) var accColor: texture_2d<f32>;
3732
4147
  @group(0) @binding(2) var accAlbedo: texture_2d<f32>;
3733
4148
  @group(0) @binding(3) var accNormal: texture_2d<f32>;
@@ -3738,7 +4153,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3738
4153
  @group(0) @binding(8) var outAlbedo: texture_storage_2d<rgba32float, write>;
3739
4154
  @group(0) @binding(9) var outNormal: texture_storage_2d<rgba32float, write>;
3740
4155
 
3741
- @compute @workgroup_size(${vo}, ${vo})
4156
+ @compute @workgroup_size(${ls}, ${ls})
3742
4157
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3743
4158
 
3744
4159
  if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
@@ -3772,32 +4187,32 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3772
4187
  let t = P.samples / max( k + P.samples, 1e-6 );
3773
4188
  textureStore( outColor, p, vec4<f32>( mix( hc, ac.xyz, t ), ac.w ) );
3774
4189
  textureStore( outAlbedo, p, vec4<f32>( mix( ha, aa.xyz, t ), min( k + P.samples, P.maxLength ) ) );
3775
- let n = select( an.xyz, mixNormal( hn, an.xyz, t ), ( P.flags & ${xo}u ) != 0u );
4190
+ let n = select( an.xyz, mixNormal( hn, an.xyz, t ), ( P.flags & ${fs}u ) != 0u );
3776
4191
  textureStore( outNormal, p, vec4<f32>( n, an.w ) );
3777
4192
 
3778
4193
  }
3779
- `, ko = (e) => ({
4194
+ `, bs = (e) => ({
3780
4195
  binding: e,
3781
4196
  visibility: GPUShaderStage.COMPUTE,
3782
4197
  texture: { sampleType: "unfilterable-float" }
3783
- }), Ao = (e) => ({
4198
+ }), xs = (e) => ({
3784
4199
  binding: e,
3785
4200
  visibility: GPUShaderStage.COMPUTE,
3786
4201
  storageTexture: {
3787
4202
  access: "write-only",
3788
4203
  format: "rgba32float"
3789
4204
  }
3790
- }), jo = (e, t) => ({
4205
+ }), Ss = (e, t) => ({
3791
4206
  binding: e,
3792
4207
  visibility: GPUShaderStage.COMPUTE,
3793
4208
  buffer: { type: t }
3794
- }), Mo = class {
4209
+ }), Cs = class {
3795
4210
  constructor(e) {
3796
4211
  this.device = e, this.settings = {
3797
- ..._o,
4212
+ ...cs,
3798
4213
  cleanAux: !1,
3799
4214
  splitCopies: !0
3800
- }, this.valid = !1, this.width = 0, this.height = 0, this._sets = null, this._current = 0, this._picked = null, this._copies = null, this._paramsBuffer = null, this._pipelines = null, this._movedLeaves = null, this._movedToPrev = null, this._movedCapacity = 0, this._movedCount = 0, this._paramData = new ArrayBuffer(yo), this._paramU32 = new Uint32Array(this._paramData), this._paramF32 = new Float32Array(this._paramData), this._prevViewProj = new Float32Array(16), this._prevCamPos = new Float32Array(4), this._prevCamDir = new Float32Array(4);
4215
+ }, this.valid = !1, this.width = 0, this.height = 0, this._sets = null, this._current = 0, this._picked = null, this._copies = null, this._paramsBuffer = null, this._pipelines = null, this._movedLeaves = null, this._movedToPrev = null, this._movedCapacity = 0, this._movedCount = 0, this._paramData = new ArrayBuffer(us), this._paramU32 = new Uint32Array(this._paramData), this._paramF32 = new Float32Array(this._paramData), this._prevViewProj = new Float32Array(16), this._prevCamPos = new Float32Array(4), this._prevCamDir = new Float32Array(4);
3801
4216
  }
3802
4217
  get textures() {
3803
4218
  return this.valid ? this._sets[this._current] : null;
@@ -3905,23 +4320,23 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3905
4320
  }),
3906
4321
  layout: i
3907
4322
  };
3908
- }, n = jo(0, "uniform");
4323
+ }, n = Ss(0, "uniform");
3909
4324
  this._pipelines = {
3910
- select: t("oidn-history-select", Eo, [
4325
+ select: t("oidn-history-select", _s, [
3911
4326
  n,
3912
- ko(1),
3913
- ko(2),
3914
- jo(3, "storage"),
3915
- jo(4, "storage"),
4327
+ bs(1),
4328
+ bs(2),
4329
+ Ss(3, "storage"),
4330
+ Ss(4, "storage"),
3916
4331
  {
3917
4332
  binding: 5,
3918
4333
  visibility: GPUShaderStage.COMPUTE,
3919
4334
  texture: { sampleType: "uint" }
3920
4335
  },
3921
- jo(6, "read-only-storage"),
3922
- jo(7, "read-only-storage")
4336
+ Ss(6, "read-only-storage"),
4337
+ Ss(7, "read-only-storage")
3923
4338
  ]),
3924
- blend: t("oidn-history-blend", Do, [
4339
+ blend: t("oidn-history-blend", vs, [
3925
4340
  n,
3926
4341
  ...[
3927
4342
  1,
@@ -3931,14 +4346,14 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3931
4346
  5,
3932
4347
  6,
3933
4348
  7
3934
- ].map(ko),
3935
- jo(8, "read-only-storage"),
3936
- jo(9, "read-only-storage"),
3937
- Ao(10),
3938
- Ao(11),
3939
- Ao(12)
4349
+ ].map(bs),
4350
+ Ss(8, "read-only-storage"),
4351
+ Ss(9, "read-only-storage"),
4352
+ xs(10),
4353
+ xs(11),
4354
+ xs(12)
3940
4355
  ]),
3941
- merge: t("oidn-history-merge", Oo, [
4356
+ merge: t("oidn-history-merge", ys, [
3942
4357
  n,
3943
4358
  ...[
3944
4359
  1,
@@ -3947,16 +4362,16 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3947
4362
  4,
3948
4363
  5,
3949
4364
  6
3950
- ].map(ko),
3951
- Ao(7),
3952
- Ao(8),
3953
- Ao(9)
4365
+ ].map(bs),
4366
+ xs(7),
4367
+ xs(8),
4368
+ xs(9)
3954
4369
  ])
3955
4370
  }, this._paramsBuffer = e.createBuffer({
3956
4371
  label: "oidn-history-params",
3957
- size: yo,
4372
+ size: us,
3958
4373
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
3959
- }), this._growMoved(bo);
4374
+ }), this._growMoved(ds);
3960
4375
  }
3961
4376
  _growMoved(e) {
3962
4377
  this._movedLeaves?.destroy(), this._movedToPrev?.destroy();
@@ -3982,11 +4397,11 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3982
4397
  a.setPipeline(t), a.setBindGroup(0, this.device.createBindGroup({
3983
4398
  layout: n,
3984
4399
  entries: i
3985
- })), a.dispatchWorkgroups(Math.ceil(this.width / vo), Math.ceil(this.height / vo)), a.end();
4400
+ })), a.dispatchWorkgroups(Math.ceil(this.width / ls), Math.ceil(this.height / ls)), a.end();
3986
4401
  }
3987
4402
  _writeParams(e, t, n, r) {
3988
4403
  let i = this.settings, a = this._paramU32, o = this._paramF32;
3989
- a[0] = this.width, a[1] = this.height, a[2] = +!!t, a[3] = (i.cleanAux ? xo : 0) | (i.splitCopies ? So : 0) | (e.orthographic ? Co : 0), o[4] = i.maxLength, o[5] = i.smoothLength, o[6] = i.depthTolerance, o[7] = i.normalTolerance, o[8] = i.roughStart, o[9] = i.roughEnd, o[10] = n, o[11] = r, o.set(e.world, 12), o.set(e.projInv, 28), o.set(this._prevViewProj, 44), o.set(this._prevCamPos, 60), a[64] = this._movedCount, o[68] = i.movedLength, o.set(this._prevCamDir, 72), this.device.queue.writeBuffer(this._paramsBuffer, 0, this._paramData);
4404
+ a[0] = this.width, a[1] = this.height, a[2] = +!!t, a[3] = (i.cleanAux ? fs : 0) | (i.splitCopies ? ps : 0) | (e.orthographic ? ms : 0), o[4] = i.maxLength, o[5] = i.smoothLength, o[6] = i.depthTolerance, o[7] = i.normalTolerance, o[8] = i.roughStart, o[9] = i.roughEnd, o[10] = n, o[11] = r, o.set(e.world, 12), o.set(e.projInv, 28), o.set(this._prevViewProj, 44), o.set(this._prevCamPos, 60), a[64] = this._movedCount, o[68] = i.movedLength, o.set(this._prevCamDir, 72), this.device.queue.writeBuffer(this._paramsBuffer, 0, this._paramData);
3990
4405
  }
3991
4406
  _rememberCamera(e) {
3992
4407
  this._prevViewProj.set(e.viewProj), this._prevCamPos[0] = e.world[12], this._prevCamPos[1] = e.world[13], this._prevCamPos[2] = e.world[14];
@@ -3996,11 +4411,11 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
3996
4411
  _releaseTextures() {
3997
4412
  this._sets?.forEach((e) => Object.values(e).forEach((e) => e.destroy())), this._picked?.destroy(), this._copies?.destroy(), this._sets = null, this._picked = null, this._copies = null, this.width = 0, this.height = 0, this.valid = !1;
3998
4413
  }
3999
- }, No = "const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,OUTPUT_TONEMAP_FALLBACK:`output.tonemap_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`,CAPABILITY_MISSING:`capability.missing`});Object.freeze({ERROR:`error`,WARNING:`warning`});const t=new Map;function n(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function r(e,r,a){let o=t.get(e);o||(o={shared:0,exclusive:!1,queue:[]},t.set(e,o));let s=i(()=>{for(r===`exclusive`?o.exclusive=!1:o.shared--;o.queue.length&&n(o,o.queue[0].mode);)o.queue.shift().grant();!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e)});return o.queue.length===0&&n(o,r)?Promise.resolve(s):a?(!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e),Promise.resolve(null)):new Promise(e=>o.queue.push({mode:r,grant:()=>e(s)}))}function i(e){let t=!1;return()=>{t||(t=!0,e())}}const a=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function o(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let o=a();return o?new Promise((r,a)=>{o.request(e,{mode:t,ifAvailable:n},e=>{if(!e){r(null);return}return new Promise(e=>r(i(e)))}).catch(a)}):r(e,t,n)}async function s(){let e=a();if(!e)return new Set(t.keys());let{held:n=[]}=await e.query();return new Set(n.map(e=>e.name))}const c=new TextEncoder;function l(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function u(e){let t=typeof e==`string`?c.encode(e):e;return l(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function d(e){return(await u(e)).slice(0,32)}var f=class{constructor(){this._handlers=new Map}addEventListener(e,t){this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t)}removeEventListener(e,t){this._handlers.get(e)?.delete(t)}dispatchEvent(e){for(let t of[...this._handlers.get(e.type)??[]])t.call(this,e)}},p=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}},m=class{constructor(e){this._ops=new p(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};const h=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),g=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`}),_=`meta.json`,v=100*1024**3,y=64*1024**2,b=8*1024**2,x=new TextEncoder;function S(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=x.encode(e)),e instanceof ArrayBuffer){if(!t||n)return{args:{buffer:e},list:[e]};let r=e.slice(0);return{args:{buffer:r},list:[r]}}if(!ArrayBuffer.isView(e))throw TypeError(`storage: write expects an ArrayBuffer, a typed array, a Blob or a string`);let{buffer:r,byteOffset:i,byteLength:a}=e,o=typeof SharedArrayBuffer<`u`&&r instanceof SharedArrayBuffer;if(!t)return{args:{buffer:r,byteOffset:i,byteLength:a},list:[]};if(o){let e=new Uint8Array(a);return e.set(new Uint8Array(r,i,a)),{args:{buffer:e.buffer},list:[e.buffer]}}if(n&&i===0&&a===r.byteLength)return{args:{buffer:r},list:[r]};let s=r.slice(i,i+a);return{args:{buffer:s},list:[s]}}async function C(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*w(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var T=class{constructor(e,t,n,r,i){this.area=e,this.id=t,this.key=n.key,this.meta=n,this._dir=r,this._release=i}get bytes(){return this.meta.bytes}get extra(){return this.meta.extra??{}}async file(t){try{return await(await this._dir.getFileHandle(t)).getFile()}catch(n){return this.area.manager._issue(e.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${t}`,{error:n.message}),null}}async json(e){let t=await this.file(e);return t?JSON.parse(await t.text()):null}release(){this._release?.(),this._release=null}},E=class{constructor(e,t,n,r,i,{sizes:a={},append:o=!1}={}){this.area=e,this.id=t,this.key=n,this._info=r,this._release=i,this._writers=new Map,this._sizes={...a},this._append=o,this._done=!1,this._committedBytes=o?Object.values(a).reduce((e,t)=>e+t,0):0}get _transport(){return this.area.manager._transport}get _path(){return[this.area.name,this.id]}async _writer(e){let t=this._writers.get(e);if(!t){let n=this._append&&e in this._sizes,r=n&&(this._info.growable??[]).includes(e)?this._sizes[e]:void 0;t=this._transport.call(`openWriter`,{path:this._path,name:e,truncate:!n,length:r}),this._writers.set(e,t)}return(await t).id}async write(e,t,{at:n,transfer:r=!1}={}){this._assertOpen();let{args:i,list:a}=(typeof Blob<`u`&&t instanceof Blob?null:S(t,{copy:!0,transfer:r}))??S(await t.arrayBuffer(),{copy:!0,transfer:!0}),o=await this._writer(e);return this._transport.call(`write`,{id:o,at:n,...i},a)}async writeFile(e,t){this._assertOpen(),typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer());let{args:n,list:r}=S(t,{copy:!0,transfer:!0}),{size:i}=await this._transport.call(`writeFile`,{path:this._path,name:e,...n},r);return this._sizes[e]=i,i}writeJSON(e,t){return this.writeFile(e,JSON.stringify(t))}async writeStream(e,t,{onProgress:n=null,signal:r=null,batchBytes:i=b}={}){let a=t.getReader(),o=[],s=new Uint8Array(i),c=0,l=0,u=async()=>{if(c===0)return;let t=c===i?s:s.slice(0,c);s=new Uint8Array(i),c=0,o.push(this.write(e,t,{transfer:!0})),o.length>=4&&await o.shift()};try{for(;;){if(r?.aborted)throw r.reason??new DOMException(`aborted`,`AbortError`);let{done:e,value:t}=await a.read();if(e)break;let o=0;for(;o<t.length;){let e=Math.min(t.length-o,i-c);s.set(t.subarray(o,o+e),c),c+=e,o+=e,l+=e,c===i&&await u()}n?.(l)}return await u(),await Promise.all(o),l}catch(e){throw a.cancel().catch(()=>{}),await Promise.allSettled(o),e}}async commit(e={}){this._assertOpen(),this._done=!0;try{for(let[e,t]of this._writers){let{size:n}=await this._transport.call(`closeWriter`,{id:(await t).id});this._sizes[e]=n}this._writers.clear();let t=Date.now(),n={v:1,key:this.key,label:this._info.label??``,kind:this.area.kind,files:{...this._sizes},bytes:Object.values(this._sizes).reduce((e,t)=>e+t,0),createdAt:this._info.createdAt??t,lastUsed:t,pinned:this._info.pinned===!0,extra:{...this._info.extra,...e}},r=this._info.growable??[];r.length&&(n.growable=r);let{args:i,list:a}=S(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:_,...i},a),this.area.kind===h.CACHE&&this.area.manager._countCacheBytes(n.bytes-this._committedBytes),this.area.manager._changed(this.area.name),n}catch(e){throw await this._discard(),this.area.manager._writeFailed(this.area.name,e),e}finally{this._release?.(),this._release=null}}async abort(){if(!this._done){this._done=!0;try{this._append?await this._closeAll(!0):await this._discard()}finally{this._release?.(),this._release=null}}}async _closeAll(e){for(let t of this._writers.values())try{await this._transport.call(`closeWriter`,{id:(await t).id,abort:e})}catch{}this._writers.clear()}async _discard(){await this._closeAll(!0),await this.area._removeDir(this.id)}_assertOpen(){if(this._done)throw Error(`storage: entry ${this.area.name}/${this.id} is already committed or aborted`)}},D=class{constructor(e,t,n){this.manager=e,this.name=t,this.kind=n}_lockName(e){return`${this.manager.namespace}:store:${this.name}:${e}`}async _dir(e=!1){try{return await this.manager._root.getDirectoryHandle(this.name,{create:e})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _entryDir(e,t=!1){let n=await this._dir(t);if(!n)return null;try{return await n.getDirectoryHandle(e,{create:t})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _removeDir(e){let t=await this._dir(!1);if(t)try{await t.removeEntry(e,{recursive:!0})}catch(e){if(e.name!==`NotFoundError`)throw e}}async _validMeta(e,t=null){let n=await C(e,_);if(!n||n.v!==1||typeof n.key!=`string`||t!==null&&n.key!==t)return null;let r=n.growable??[];for(let[t,i]of Object.entries(n.files??{}))try{let n=await(await e.getFileHandle(t)).getFile();if(n.size!==i&&!(r.includes(t)&&n.size>i))return null}catch{return null}return n}async open(t,{wait:n=!1}={}){let r=await d(t),i=await o(this._lockName(r),{mode:`shared`,ifAvailable:!n});if(!i)return null;try{let e=await this._entryDir(r),n=e?await this._validMeta(e,t):null;return n?(Date.now()-n.lastUsed>36e5&&this._touch(r,n),new T(this,r,n,e,i)):(i(),null)}catch(t){return i(),this.manager._issue(e.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:t.message}),null}}async has(e){let t=await this.open(e);return t?.release(),!!t}_touch(e,t){let n={...t,lastUsed:Date.now()},{args:r,list:i}=S(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:_,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(t,{label:n=``,pinned:r=!1,expectedBytes:i=0,extra:a={},growable:s=[]}={}){let c=await d(t),l=await o(this._lockName(c),{mode:`exclusive`});try{return i>0&&!await this.manager.ensureSpace(i,this.kind)?(l(),this.manager._issue(e.STORAGE_QUOTA_EXCEEDED,`no room for ${(i/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:i}),null):(await this._removeDir(c),await this._entryDir(c,!0),new E(this,c,t,{label:n,pinned:r,extra:a,growable:s},l))}catch(e){return l(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await d(e),r=await o(this._lockName(n),{mode:`shared`,ifAvailable:!0});if(!r)return!1;try{let r=await this._entryDir(n),i=r?await this._validMeta(r,e):null;if(!i)return!1;let{args:a,list:o}=S(JSON.stringify({...i,...t,v:1,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:_,...a},o),!0}finally{r()}}async edit(e){let t=await d(e),n=await o(this._lockName(t),{mode:`exclusive`});try{let r=await this._entryDir(t),i=r?await this._validMeta(r,e):null;if(!i)return n(),null;let a={label:i.label,pinned:i.pinned,extra:i.extra,createdAt:i.createdAt,growable:i.growable};return new E(this,t,e,a,n,{sizes:i.files,append:!0})}catch(e){return n(),this.manager._writeFailed(this.name,e),null}}async remove(e){return this.removeById(await d(e))}async removeById(e){let t=await o(this._lockName(e),{mode:`exclusive`,ifAvailable:!0});if(!t)return!1;try{return await this._removeDir(e),this.manager._changed(this.name),!0}finally{t()}}async list(){let e=await this._dir(!1);if(!e)return[];let t=[];for await(let[n,r]of w(e)){let e=await C(r,_);e?.v===1&&t.push({...e,id:n})}return t}async clear(){let e=0;for(let{id:t}of await this.list())await this.removeById(t)&&e++;return e}async sweep(){let e=await this._dir(!1);if(!e)return 0;let t=await s(),n=0;for await(let[r,i]of w(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},O=class extends f{constructor({root:e,transport:t,namespace:n}){super(),this.namespace=n,this._root=e,this._transport=t,this._areas=new Map,this._budget=null,this._cacheTotal=null;for(let e of Object.values(g))this.defineArea(e,{kind:e===g.SPILL?h.SCRATCH:h.CACHE})}defineArea(e,{kind:t=h.CACHE}={}){let n=this._areas.get(e);if(n){if(n.kind!==t)throw Error(`storage: area \"${e}\" is already defined as ${n.kind}`);return n}let r=new D(this,e,t);return this._areas.set(e,r),r}area(e){let t=this._areas.get(e);if(!t)throw Error(`storage: unknown area \"${e}\"`);return t}get areaNames(){return[...this._areas.keys()]}async estimate(){let e=typeof navigator<`u`?navigator.storage:null;if(!e?.estimate)return{quota:1/0,usage:0};let{quota:t=1/0,usage:n=0}=await e.estimate();return{quota:t,usage:n}}async persisted(){return await globalThis.navigator?.storage?.persisted?.()===!0}async persist(){let e=await globalThis.navigator?.storage?.persist?.()===!0;return this._changed(null),e}async budget(){if(this._budget!==null)return this._budget;let{quota:e}=await this.estimate();return Math.min(e*.3,v)}setBudget(e){this._budget=e===null?null:Math.max(0,e),this._changed(null)}async _cacheBytes(){let e=this._cacheTotal;return(!e||Date.now()-e.at>3e4)&&(e=this._cacheTotal={at:Date.now(),bytes:0,ready:null},e.ready=this._cacheEntries().then(t=>{e.bytes+=t.reduce((e,t)=>e+(t.meta.bytes??0),0)}),e.ready.catch(()=>{this._cacheTotal===e&&(this._cacheTotal=null)})),await e.ready,e.bytes}_countCacheBytes(e){this._cacheTotal&&(this._cacheTotal.bytes+=e)}async _cacheEntries(){let e=[];for(let t of this._areas.values())if(t.kind===h.CACHE)for(let n of await t.list())e.push({area:t,meta:n});return e}async usage(){let{quota:e,usage:t}=await this.estimate(),n={},r=0;for(let e of this._areas.values()){let t=await e.list(),i=t.reduce((e,t)=>e+(t.bytes??0),0);n[e.name]={kind:e.kind,bytes:i,entries:t.length},e.kind===h.CACHE&&(r+=i)}return{quota:e,usage:t,persisted:await this.persisted(),budget:await this.budget(),cacheBytes:r,areas:n}}async collect({freeBytes:e=null}={}){let t=await this._cacheEntries(),n=await this.budget(),r=this._cacheTotal={at:Date.now(),bytes:t.reduce((e,t)=>e+(t.meta.bytes??0),0),ready:null},i=e??Math.max(0,r.bytes-n);if(i<=0)return 0;let a=await s(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),c=0;for(let{area:e,meta:t}of o){if(c>=i)break;await e.removeById(t.id)&&(c+=t.bytes??0,r.bytes-=t.bytes??0)}return c}async ensureSpace(e,t=h.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+y-(n-r);return t===h.CACHE?{free:i,budget:await this._cacheBytes()+e-await this.budget()}:{free:i,budget:0}},r=await n();return r.free<=0&&r.budget<=0?!0:(await this.collect({freeBytes:Math.max(r.free,r.budget)}),(await n()).free<=0)}async sweep(){let e=0;for(let t of this._areas.values())e+=await t.sweep(),t.kind===h.SCRATCH&&(e+=await t.clear());return e}_changed(e){this.dispatchEvent({type:`change`,area:e})}_issue(e,t,n={}){this.dispatchEvent({type:`issue`,code:e,message:t,detail:n})}_writeFailed(t,n){let r=n?.name===`QuotaExceededError`;this._issue(r?e.STORAGE_QUOTA_EXCEEDED:e.STORAGE_WRITE_FAILED,`${t}: ${n?.message??n}`,{area:t,error:n?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function k({namespace:e,root:t}){let n=new m(t);n.inline=!0;let r=new O({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}const A=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),j=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),M=(e,t)=>e.headers?.get?.(t)??null,N=e=>e.reason??new DOMException(`aborted`,`AbortError`);function P(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function F(e,{onProgress:t,signal:n}){let r=Number(M(e,`content-length`))||0,i=M(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),N(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(j(s,r))}return new Blob(o,{type:i})}const I=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),L=()=>{};var R=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(g.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=P(e),policy:r=A.REVALIDATE,maxAgeMs:i=864e5,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==A.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===A.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(j(c.size,c.size)),{file:I(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw N(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(M(s,`content-length`))||0,l={url:e,contentType:M(s,`content-type`)??``,lastModified:M(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:I(await F(s,{onProgress:r,signal:i}),n,l.contentType),release:L,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(j(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:I(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=M(n,`last-modified`),t=n.status===206?Number(M(n,`content-range`)?.match(/\\/(\\d+)$/)?.[1])||null:Number(M(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};let z={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`,storage:`auto`},B=null;async function V(){return B||(B=await import(z.ortRuntimeUrl),B.env.wasm.wasmPaths=z.ortWasmPaths,B.env.logLevel=`error`,B)}let H=null,U=null,W=null;function G(){return W??=(async()=>{if(z.storage===!1||!navigator.storage?.getDirectory)return new R(null);try{let e=await(await navigator.storage.getDirectory()).getDirectoryHandle(z.cacheNamespace,{create:!0}),t=k({namespace:z.cacheNamespace,root:e});return await K(t).catch(()=>{}),new R(t)}catch{return new R(null)}})(),W}async function K(e){let t=`${z.cacheNamespace}:ai-upscaler-models`;if(typeof indexedDB>`u`||!indexedDB.databases||!(await indexedDB.databases()).some(e=>e.name===t))return;let n=await new Promise((e,n)=>{let r=indexedDB.open(t);r.onerror=()=>n(r.error),r.onsuccess=()=>{let t=r.result;if(!t.objectStoreNames.contains(`models`)){t.close(),e([]);return}let i=[],a=t.transaction(`models`,`readonly`).objectStore(`models`).openCursor();a.onerror=()=>n(a.error),a.onsuccess=()=>{let n=a.result;if(!n){t.close(),e(i);return}i.push([n.key,n.value]),n.continue()}}}),r=e.area(`downloads`);for(let[e,t]of n){if(typeof e!=`string`||!(t instanceof ArrayBuffer)||await r.has(e))continue;let n=await r.create(e,{label:e.split(`/`).pop(),expectedBytes:t.byteLength});n&&(await n.write(`data`,t,{transfer:!0}),await n.commit({url:e,contentType:`application/octet-stream`,checkedAt:Date.now()}))}await new Promise(e=>{let n=indexedDB.deleteDatabase(t);n.onsuccess=n.onerror=n.onblocked=()=>e()})}async function q(e){let{file:t,release:n,fromCache:r}=await(await G()).fetch(e);try{let e=await t.arrayBuffer();return r&&console.log(`AI Upscaler Worker: model loaded from cache (${(e.byteLength/1024/1024).toFixed(1)}MB)`),e}finally{n()}}async function J(e,t){if(H&&U===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}H&&=(await H.release(),null);let[n,r]=await Promise.all([q(e),V()]);H=await r.InferenceSession.create(n,t),U=e;let i=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);i=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU=\"${t?.description||t?.device||`unknown`}\", tileSize=${i}`)}catch{}let a=(n.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${a}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:i})}async function Y(e,t,n,r){let i=await V(),a=H.inputNames[0],o=H.outputNames[0],s=new i.Tensor(`float32`,e,[1,3,n,t]),c=(await H.run({[a]:s}))[o].data;self.postMessage({type:`inferred`,outputData:c,id:r},[c.buffer])}self.onmessage=async e=>{let{type:t}=e.data;try{t===`load`?(e.data.ortRuntimeUrl&&(z.ortRuntimeUrl=e.data.ortRuntimeUrl),e.data.ortWasmPaths&&(z.ortWasmPaths=e.data.ortWasmPaths),e.data.cacheNamespace&&(z.cacheNamespace=e.data.cacheNamespace),e.data.storage!==void 0&&(z.storage=e.data.storage),await J(e.data.url,e.data.sessionOptions)):t===`infer`?await Y(e.data.tileData,e.data.width,e.data.height,e.data.id):t===`dispose`&&H&&(await H.release(),H=null,U=null)}catch(t){self.postMessage({type:`error`,message:t.message,id:e.data?.id})}};", Po = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", No], { type: "text/javascript;charset=utf-8" });
4000
- function Fo(e) {
4414
+ }, ws = "const e=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`,STORAGE_UNAVAILABLE:`storage.unavailable`,STORAGE_QUOTA_EXCEEDED:`storage.quota_exceeded`,STORAGE_WRITE_FAILED:`storage.write_failed`,STORAGE_READ_FAILED:`storage.read_failed`,STORAGE_ENTRY_CORRUPT:`storage.entry_corrupt`,STORAGE_CACHE_MISMATCH:`storage.cache_mismatch`,DENOISER_UNAVAILABLE:`denoiser.unavailable`,OUTPUT_SOURCE_FALLBACK:`output.source_fallback`,OUTPUT_TONEMAP_FALLBACK:`output.tonemap_fallback`,LIGHT_PLACEHOLDER_SKIPPED:`light.placeholder_skipped`,CAPABILITY_MISSING:`capability.missing`});Object.freeze({ERROR:`error`,WARNING:`warning`});const t=new Map;function n(e,t){return e.exclusive||t===`exclusive`&&e.shared>0?!1:(t===`exclusive`?e.exclusive=!0:e.shared++,!0)}function r(e,r,a){let o=t.get(e);o||(o={shared:0,exclusive:!1,queue:[]},t.set(e,o));let s=i(()=>{for(r===`exclusive`?o.exclusive=!1:o.shared--;o.queue.length&&n(o,o.queue[0].mode);)o.queue.shift().grant();!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e)});return o.queue.length===0&&n(o,r)?Promise.resolve(s):a?(!o.exclusive&&o.shared===0&&o.queue.length===0&&t.delete(e),Promise.resolve(null)):new Promise(e=>o.queue.push({mode:r,grant:()=>e(s)}))}function i(e){let t=!1;return()=>{t||(t=!0,e())}}const a=()=>typeof navigator<`u`&&navigator.locks?.request?navigator.locks:null;function o(e,{mode:t=`exclusive`,ifAvailable:n=!1}={}){let o=a();return o?new Promise((r,a)=>{o.request(e,{mode:t,ifAvailable:n},e=>{if(!e){r(null);return}return new Promise(e=>r(i(e)))}).catch(a)}):r(e,t,n)}async function s(){let e=a();if(!e)return new Set(t.keys());let{held:n=[]}=await e.query();return new Set(n.map(e=>e.name))}const c=new TextEncoder;function l(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function u(e){let t=typeof e==`string`?c.encode(e):e;return l(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}async function d(e){return(await u(e)).slice(0,32)}var f=class{constructor(){this._handlers=new Map}addEventListener(e,t){this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t)}removeEventListener(e,t){this._handlers.get(e)?.delete(t)}dispatchEvent(e){for(let t of[...this._handlers.get(e.type)??[]])t.call(this,e)}},p=class{constructor(e){this._root=e,this._writers=new Map,this._nextId=1}async _dir(e,t){let n=await this._root;for(let r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async openWriter({path:e,name:t,truncate:n=!0,length:r}){let i=await(await(await this._dir(e,!0)).getFileHandle(t,{create:!0})).createSyncAccessHandle();n?i.truncate(0):r!==void 0&&i.getSize()>r&&i.truncate(r);let a=this._nextId++;return this._writers.set(a,{handle:i,end:i.getSize()}),{id:a}}write({id:e,buffer:t,byteOffset:n=0,byteLength:r,at:i}){let a=this._writers.get(e);if(!a)throw Error(`storage: writer ${e} is not open`);let o=new Uint8Array(t,n,r??t.byteLength-n),s=i??a.end,c=0;for(;c<o.length;){let e=a.handle.write(o.subarray(c),{at:s+c});if(e<=0)throw Error(`storage: write made no progress`);c+=e}return a.end=Math.max(a.end,s+o.length),{bytes:o.length}}closeWriter({id:e,abort:t=!1}){let n=this._writers.get(e);if(!n)return{size:0};this._writers.delete(e);try{return t||n.handle.flush(),{size:n.handle.getSize()}}finally{n.handle.close()}}async writeFile({path:e,name:t,buffer:n,byteOffset:r=0,byteLength:i}){let{id:a}=await this.openWriter({path:e,name:t});try{return this.write({id:a,buffer:n,byteOffset:r,byteLength:i}),this.closeWriter({id:a})}catch(e){throw this.closeWriter({id:a,abort:!0}),e}}async readRange({path:e,name:t,offset:n=0,length:r}){let i=await(await this._dir(e,!1)).getFileHandle(t),a=null;try{a=await i.createSyncAccessHandle()}catch(e){if(e.name!==`NoModificationAllowedError`)throw e}if(!a){let e=await i.getFile(),t=r===void 0?e.size:n+r;return{buffer:await e.slice(n,t).arrayBuffer()}}try{let e=a.getSize(),t=Math.max(0,Math.min(r??e-n,e-n)),i=new ArrayBuffer(t);return a.read(i,{at:n}),{buffer:i}}finally{a.close()}}dispose(){for(let e of[...this._writers.keys()])this.closeWriter({id:e,abort:!0})}},m=class{constructor(e){this._ops=new p(e)}async call(e,t){return this._ops[e](t)}dispose(){this._ops.dispose()}};const h=Object.freeze({CACHE:`cache`,USER:`user`,SCRATCH:`scratch`}),g=Object.freeze({DOWNLOADS:`downloads`,ARCHIVES:`archives`,SCENES:`scenes`,CDF:`cdf`,SPILL:`spill`}),_=`meta.json`,v=100*1024**3,y=64*1024**2,b=8*1024**2,x=new TextEncoder;function S(e,{copy:t,transfer:n}){if(typeof e==`string`&&(e=x.encode(e)),e instanceof ArrayBuffer){if(!t||n)return{args:{buffer:e},list:[e]};let r=e.slice(0);return{args:{buffer:r},list:[r]}}if(!ArrayBuffer.isView(e))throw TypeError(`storage: write expects an ArrayBuffer, a typed array, a Blob or a string`);let{buffer:r,byteOffset:i,byteLength:a}=e,o=typeof SharedArrayBuffer<`u`&&r instanceof SharedArrayBuffer;if(!t)return{args:{buffer:r,byteOffset:i,byteLength:a},list:[]};if(o){let e=new Uint8Array(a);return e.set(new Uint8Array(r,i,a)),{args:{buffer:e.buffer},list:[e.buffer]}}if(n&&i===0&&a===r.byteLength)return{args:{buffer:r},list:[r]};let s=r.slice(i,i+a);return{args:{buffer:s},list:[s]}}async function C(e,t){try{let n=await(await e.getFileHandle(t)).getFile();return JSON.parse(await n.text())}catch{return null}}async function*w(e){for await(let[t,n]of e.entries())n.kind===`directory`&&(yield[t,n])}var T=class{constructor(e,t,n,r,i){this.area=e,this.id=t,this.key=n.key,this.meta=n,this._dir=r,this._release=i}get bytes(){return this.meta.bytes}get extra(){return this.meta.extra??{}}async file(t){try{return await(await this._dir.getFileHandle(t)).getFile()}catch(n){return this.area.manager._issue(e.STORAGE_READ_FAILED,`could not read ${this.area.name}/${this.id}/${t}`,{error:n.message}),null}}async json(e){let t=await this.file(e);return t?JSON.parse(await t.text()):null}release(){this._release?.(),this._release=null}},E=class{constructor(e,t,n,r,i,{sizes:a={},append:o=!1}={}){this.area=e,this.id=t,this.key=n,this._info=r,this._release=i,this._writers=new Map,this._sizes={...a},this._append=o,this._done=!1,this._committedBytes=o?Object.values(a).reduce((e,t)=>e+t,0):0}get _transport(){return this.area.manager._transport}get _path(){return[this.area.name,this.id]}async _writer(e){let t=this._writers.get(e);if(!t){let n=this._append&&e in this._sizes,r=n&&(this._info.growable??[]).includes(e)?this._sizes[e]:void 0;t=this._transport.call(`openWriter`,{path:this._path,name:e,truncate:!n,length:r}),this._writers.set(e,t)}return(await t).id}async write(e,t,{at:n,transfer:r=!1}={}){this._assertOpen();let{args:i,list:a}=(typeof Blob<`u`&&t instanceof Blob?null:S(t,{copy:!0,transfer:r}))??S(await t.arrayBuffer(),{copy:!0,transfer:!0}),o=await this._writer(e);return this._transport.call(`write`,{id:o,at:n,...i},a)}async writeFile(e,t){this._assertOpen(),typeof Blob<`u`&&t instanceof Blob&&(t=await t.arrayBuffer());let{args:n,list:r}=S(t,{copy:!0,transfer:!0}),{size:i}=await this._transport.call(`writeFile`,{path:this._path,name:e,...n},r);return this._sizes[e]=i,i}writeJSON(e,t){return this.writeFile(e,JSON.stringify(t))}async writeStream(e,t,{onProgress:n=null,signal:r=null,batchBytes:i=b}={}){let a=t.getReader(),o=[],s=new Uint8Array(i),c=0,l=0,u=async()=>{if(c===0)return;let t=c===i?s:s.slice(0,c);s=new Uint8Array(i),c=0,o.push(this.write(e,t,{transfer:!0})),o.length>=4&&await o.shift()};try{for(;;){if(r?.aborted)throw r.reason??new DOMException(`aborted`,`AbortError`);let{done:e,value:t}=await a.read();if(e)break;let o=0;for(;o<t.length;){let e=Math.min(t.length-o,i-c);s.set(t.subarray(o,o+e),c),c+=e,o+=e,l+=e,c===i&&await u()}n?.(l)}return await u(),await Promise.all(o),l}catch(e){throw a.cancel().catch(()=>{}),await Promise.allSettled(o),e}}async commit(e={}){this._assertOpen(),this._done=!0;try{for(let[e,t]of this._writers){let{size:n}=await this._transport.call(`closeWriter`,{id:(await t).id});this._sizes[e]=n}this._writers.clear();let t=Date.now(),n={v:1,key:this.key,label:this._info.label??``,kind:this.area.kind,files:{...this._sizes},bytes:Object.values(this._sizes).reduce((e,t)=>e+t,0),createdAt:this._info.createdAt??t,lastUsed:t,pinned:this._info.pinned===!0,extra:{...this._info.extra,...e}},r=this._info.growable??[];r.length&&(n.growable=r);let{args:i,list:a}=S(JSON.stringify(n),{copy:!1});return await this._transport.call(`writeFile`,{path:this._path,name:_,...i},a),this.area.kind===h.CACHE&&this.area.manager._countCacheBytes(n.bytes-this._committedBytes),this.area.manager._changed(this.area.name),n}catch(e){throw await this._discard(),this.area.manager._writeFailed(this.area.name,e),e}finally{this._release?.(),this._release=null}}async abort(){if(!this._done){this._done=!0;try{this._append?await this._closeAll(!0):await this._discard()}finally{this._release?.(),this._release=null}}}async _closeAll(e){for(let t of this._writers.values())try{await this._transport.call(`closeWriter`,{id:(await t).id,abort:e})}catch{}this._writers.clear()}async _discard(){await this._closeAll(!0),await this.area._removeDir(this.id)}_assertOpen(){if(this._done)throw Error(`storage: entry ${this.area.name}/${this.id} is already committed or aborted`)}},D=class{constructor(e,t,n){this.manager=e,this.name=t,this.kind=n}_lockName(e){return`${this.manager.namespace}:store:${this.name}:${e}`}async _dir(e=!1){try{return await this.manager._root.getDirectoryHandle(this.name,{create:e})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _entryDir(e,t=!1){let n=await this._dir(t);if(!n)return null;try{return await n.getDirectoryHandle(e,{create:t})}catch(e){if(e.name===`NotFoundError`)return null;throw e}}async _removeDir(e){let t=await this._dir(!1);if(t)try{await t.removeEntry(e,{recursive:!0})}catch(e){if(e.name!==`NotFoundError`)throw e}}async _validMeta(e,t=null){let n=await C(e,_);if(!n||n.v!==1||typeof n.key!=`string`||t!==null&&n.key!==t)return null;let r=n.growable??[];for(let[t,i]of Object.entries(n.files??{}))try{let n=await(await e.getFileHandle(t)).getFile();if(n.size!==i&&!(r.includes(t)&&n.size>i))return null}catch{return null}return n}async open(t,{wait:n=!1}={}){let r=await d(t),i=await o(this._lockName(r),{mode:`shared`,ifAvailable:!n});if(!i)return null;try{let e=await this._entryDir(r),n=e?await this._validMeta(e,t):null;return n?(Date.now()-n.lastUsed>36e5&&this._touch(r,n),new T(this,r,n,e,i)):(i(),null)}catch(t){return i(),this.manager._issue(e.STORAGE_READ_FAILED,`could not open ${this.name} entry`,{error:t.message}),null}}async has(e){let t=await this.open(e);return t?.release(),!!t}_touch(e,t){let n={...t,lastUsed:Date.now()},{args:r,list:i}=S(JSON.stringify(n),{copy:!1});this.manager._transport.call(`writeFile`,{path:[this.name,e],name:_,...r},i).catch(()=>{}),t.lastUsed=n.lastUsed}async create(t,{label:n=``,pinned:r=!1,expectedBytes:i=0,extra:a={},growable:s=[]}={}){let c=await d(t),l=await o(this._lockName(c),{mode:`exclusive`});try{return i>0&&!await this.manager.ensureSpace(i,this.kind)?(l(),this.manager._issue(e.STORAGE_QUOTA_EXCEEDED,`no room for ${(i/1048576).toFixed(0)} MB in ${this.name}`,{area:this.name,expectedBytes:i}),null):(await this._removeDir(c),await this._entryDir(c,!0),new E(this,c,t,{label:n,pinned:r,extra:a,growable:s},l))}catch(e){return l(),this.manager._writeFailed(this.name,e),null}}async patchMeta(e,t){let n=await d(e),r=await o(this._lockName(n),{mode:`shared`,ifAvailable:!0});if(!r)return!1;try{let r=await this._entryDir(n),i=r?await this._validMeta(r,e):null;if(!i)return!1;let{args:a,list:o}=S(JSON.stringify({...i,...t,v:1,key:e}),{copy:!1});return await this.manager._transport.call(`writeFile`,{path:[this.name,n],name:_,...a},o),!0}finally{r()}}async edit(e){let t=await d(e),n=await o(this._lockName(t),{mode:`exclusive`});try{let r=await this._entryDir(t),i=r?await this._validMeta(r,e):null;if(!i)return n(),null;let a={label:i.label,pinned:i.pinned,extra:i.extra,createdAt:i.createdAt,growable:i.growable};return new E(this,t,e,a,n,{sizes:i.files,append:!0})}catch(e){return n(),this.manager._writeFailed(this.name,e),null}}async remove(e){return this.removeById(await d(e))}async removeById(e){let t=await o(this._lockName(e),{mode:`exclusive`,ifAvailable:!0});if(!t)return!1;try{return await this._removeDir(e),this.manager._changed(this.name),!0}finally{t()}}async list(){let e=await this._dir(!1);if(!e)return[];let t=[];for await(let[n,r]of w(e)){let e=await C(r,_);e?.v===1&&t.push({...e,id:n})}return t}async clear(){let e=0;for(let{id:t}of await this.list())await this.removeById(t)&&e++;return e}async sweep(){let e=await this._dir(!1);if(!e)return 0;let t=await s(),n=0;for await(let[r,i]of w(e))t.has(this._lockName(r))||await this._validMeta(i)||await this.removeById(r)&&n++;return n}},O=class extends f{constructor({root:e,transport:t,namespace:n}){super(),this.namespace=n,this._root=e,this._transport=t,this._areas=new Map,this._budget=null,this._cacheTotal=null;for(let e of Object.values(g))this.defineArea(e,{kind:e===g.SPILL?h.SCRATCH:h.CACHE})}defineArea(e,{kind:t=h.CACHE}={}){let n=this._areas.get(e);if(n){if(n.kind!==t)throw Error(`storage: area \"${e}\" is already defined as ${n.kind}`);return n}let r=new D(this,e,t);return this._areas.set(e,r),r}area(e){let t=this._areas.get(e);if(!t)throw Error(`storage: unknown area \"${e}\"`);return t}get areaNames(){return[...this._areas.keys()]}async estimate(){let e=typeof navigator<`u`?navigator.storage:null;if(!e?.estimate)return{quota:1/0,usage:0};let{quota:t=1/0,usage:n=0}=await e.estimate();return{quota:t,usage:n}}async persisted(){return await globalThis.navigator?.storage?.persisted?.()===!0}async persist(){let e=await globalThis.navigator?.storage?.persist?.()===!0;return this._changed(null),e}async budget(){if(this._budget!==null)return this._budget;let{quota:e}=await this.estimate();return Math.min(e*.3,v)}setBudget(e){this._budget=e===null?null:Math.max(0,e),this._changed(null)}async _cacheBytes(){let e=this._cacheTotal;return(!e||Date.now()-e.at>3e4)&&(e=this._cacheTotal={at:Date.now(),bytes:0,ready:null},e.ready=this._cacheEntries().then(t=>{e.bytes+=t.reduce((e,t)=>e+(t.meta.bytes??0),0)}),e.ready.catch(()=>{this._cacheTotal===e&&(this._cacheTotal=null)})),await e.ready,e.bytes}_countCacheBytes(e){this._cacheTotal&&(this._cacheTotal.bytes+=e)}async _cacheEntries(){let e=[];for(let t of this._areas.values())if(t.kind===h.CACHE)for(let n of await t.list())e.push({area:t,meta:n});return e}async usage(){let{quota:e,usage:t}=await this.estimate(),n={},r=0;for(let e of this._areas.values()){let t=await e.list(),i=t.reduce((e,t)=>e+(t.bytes??0),0);n[e.name]={kind:e.kind,bytes:i,entries:t.length},e.kind===h.CACHE&&(r+=i)}return{quota:e,usage:t,persisted:await this.persisted(),budget:await this.budget(),cacheBytes:r,areas:n}}async collect({freeBytes:e=null}={}){let t=await this._cacheEntries(),n=await this.budget(),r=this._cacheTotal={at:Date.now(),bytes:t.reduce((e,t)=>e+(t.meta.bytes??0),0),ready:null},i=e??Math.max(0,r.bytes-n);if(i<=0)return 0;let a=await s(),o=t.filter(({area:e,meta:t})=>!t.pinned&&!a.has(e._lockName(t.id))).sort((e,t)=>e.meta.lastUsed-t.meta.lastUsed),c=0;for(let{area:e,meta:t}of o){if(c>=i)break;await e.removeById(t.id)&&(c+=t.bytes??0,r.bytes-=t.bytes??0)}return c}async ensureSpace(e,t=h.CACHE){let n=async()=>{let{quota:n,usage:r}=await this.estimate(),i=e+y-(n-r);return t===h.CACHE?{free:i,budget:await this._cacheBytes()+e-await this.budget()}:{free:i,budget:0}},r=await n();return r.free<=0&&r.budget<=0?!0:(await this.collect({freeBytes:Math.max(r.free,r.budget)}),(await n()).free<=0)}async sweep(){let e=0;for(let t of this._areas.values())e+=await t.sweep(),t.kind===h.SCRATCH&&(e+=await t.clear());return e}_changed(e){this.dispatchEvent({type:`change`,area:e})}_issue(e,t,n={}){this.dispatchEvent({type:`issue`,code:e,message:t,detail:n})}_writeFailed(t,n){let r=n?.name===`QuotaExceededError`;this._issue(r?e.STORAGE_QUOTA_EXCEEDED:e.STORAGE_WRITE_FAILED,`${t}: ${n?.message??n}`,{area:t,error:n?.name})}dispose(){this._transport?.dispose(),this._transport=null,this._areas.clear()}};function k({namespace:e,root:t}){let n=new m(t);n.inline=!0;let r=new O({root:t,transport:n,namespace:e});return r.sweep().catch(()=>{}),r}const A=Object.freeze({IMMUTABLE:`immutable`,REVALIDATE:`revalidate`,NETWORK:`network`}),j=(e,t)=>({loaded:e,total:t,lengthComputable:t>0&&e<=t}),M=(e,t)=>e.headers?.get?.(t)??null,N=e=>e.reason??new DOMException(`aborted`,`AbortError`);function P(e){try{let t=new URL(e,globalThis.location?.href??`http://localhost/`).pathname;return decodeURIComponent(t.split(`/`).pop())||`download`}catch{return`download`}}async function F(e,{onProgress:t,signal:n}){let r=Number(M(e,`content-length`))||0,i=M(e,`content-type`)??``;if(!e.body)return new Blob([await e.arrayBuffer()],{type:i});let a=e.body.getReader(),o=[],s=0;for(;;){if(n?.aborted)throw a.cancel().catch(()=>{}),N(n);let{done:e,value:i}=await a.read();if(e)break;o.push(i),s+=i.length,t?.(j(s,r))}return new Blob(o,{type:i})}const I=(e,t,n)=>new File([e],t,{type:n||e.type,lastModified:e.lastModified??Date.now()}),L=()=>{};var R=class{constructor(e){this._storage=e,this._revalidating=new Set}get _area(){return this._storage?.area(g.DOWNLOADS)??null}async fetch(e,{key:t=e,name:n=P(e),policy:r=A.REVALIDATE,maxAgeMs:i=864e5,onProgress:a=null,signal:o=null,fetchOptions:s={}}={}){let c=this._area;if(c&&r!==A.NETWORK){let o=await c.open(t);if(o){let c=await o.file(`data`);if(c)return r===A.REVALIDATE&&Date.now()-(o.extra.checkedAt??0)>=i&&this._revalidate(e,t,n,o.extra,s),a?.(j(c.size,c.size)),{file:I(c,n,o.extra.contentType),release:()=>o.release(),fromCache:!0};o.release()}}return this._download(e,t,n,{onProgress:a,signal:o,fetchOptions:s,cache:!!c})}async has(e){return await this._area?.has(e)===!0}async _download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:o}){if(i?.aborted)throw N(i);let s=await fetch(e,{...a,signal:i});if(!s.ok)throw Error(`HTTP ${s.status} fetching ${e}`);let c=Number(M(s,`content-length`))||0,l={url:e,contentType:M(s,`content-type`)??``,lastModified:M(s,`last-modified`),contentLength:c||null,checkedAt:Date.now()},u=o&&s.body?await this._area.create(t,{label:n,expectedBytes:c}):null;if(!u)return{file:I(await F(s,{onProgress:r,signal:i}),n,l.contentType),release:L,fromCache:!1};try{await u.writeStream(`data`,s.body,{signal:i,onProgress:e=>r?.(j(e,c))}),await u.commit(l)}catch(o){if(await u.abort(),o?.name!==`QuotaExceededError`)throw o;return this._download(e,t,n,{onProgress:r,signal:i,fetchOptions:a,cache:!1})}let d=await this._area.open(t,{wait:!0}),f=d&&await d.file(`data`);if(!f)throw d?.release(),Error(`storage: ${n} vanished right after it was saved`);return{file:I(f,n,l.contentType),release:()=>d.release(),fromCache:!1}}async _revalidate(e,t,n,r,i){if(this._revalidating.has(t))return;this._revalidating.add(t);let a=!1;try{let t=new Headers(i?.headers);t.set(`Range`,`bytes=0-0`);let n=await fetch(e,{...i,headers:t});if(n.body?.cancel().catch(()=>{}),n.ok){let e=M(n,`last-modified`),t=n.status===206?Number(M(n,`content-range`)?.match(/\\/(\\d+)$/)?.[1])||null:Number(M(n,`content-length`))||null;a=!!(e&&r.lastModified&&e!==r.lastModified||t&&r.contentLength&&t!==r.contentLength)}}catch{}try{if(a){let{release:r}=await this._download(e,t,n,{fetchOptions:i,cache:!0});r()}else await this._area.patchMeta(t,{extra:{...r,checkedAt:Date.now()}})}catch{}finally{this._revalidating.delete(t)}}};let z={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`,storage:`auto`},B=null;async function V(){return B||(B=await import(z.ortRuntimeUrl),B.env.wasm.wasmPaths=z.ortWasmPaths,B.env.logLevel=`error`,B)}let H=null,U=null,W=null;function G(){return W??=(async()=>{if(z.storage===!1||!navigator.storage?.getDirectory)return new R(null);try{let e=await(await navigator.storage.getDirectory()).getDirectoryHandle(z.cacheNamespace,{create:!0}),t=k({namespace:z.cacheNamespace,root:e});return await K(t).catch(()=>{}),new R(t)}catch{return new R(null)}})(),W}async function K(e){let t=`${z.cacheNamespace}:ai-upscaler-models`;if(typeof indexedDB>`u`||!indexedDB.databases||!(await indexedDB.databases()).some(e=>e.name===t))return;let n=await new Promise((e,n)=>{let r=indexedDB.open(t);r.onerror=()=>n(r.error),r.onsuccess=()=>{let t=r.result;if(!t.objectStoreNames.contains(`models`)){t.close(),e([]);return}let i=[],a=t.transaction(`models`,`readonly`).objectStore(`models`).openCursor();a.onerror=()=>n(a.error),a.onsuccess=()=>{let n=a.result;if(!n){t.close(),e(i);return}i.push([n.key,n.value]),n.continue()}}}),r=e.area(`downloads`);for(let[e,t]of n){if(typeof e!=`string`||!(t instanceof ArrayBuffer)||await r.has(e))continue;let n=await r.create(e,{label:e.split(`/`).pop(),expectedBytes:t.byteLength});n&&(await n.write(`data`,t,{transfer:!0}),await n.commit({url:e,contentType:`application/octet-stream`,checkedAt:Date.now()}))}await new Promise(e=>{let n=indexedDB.deleteDatabase(t);n.onsuccess=n.onerror=n.onblocked=()=>e()})}async function q(e){let{file:t,release:n,fromCache:r}=await(await G()).fetch(e);try{let e=await t.arrayBuffer();return r&&console.log(`AI Upscaler Worker: model loaded from cache (${(e.byteLength/1024/1024).toFixed(1)}MB)`),e}finally{n()}}async function J(e,t){if(H&&U===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}H&&=(await H.release(),null);let[n,r]=await Promise.all([q(e),V()]);H=await r.InferenceSession.create(n,t),U=e;let i=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);i=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU=\"${t?.description||t?.device||`unknown`}\", tileSize=${i}`)}catch{}let a=(n.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${a}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:i})}async function Y(e,t,n,r){let i=await V(),a=H.inputNames[0],o=H.outputNames[0],s=new i.Tensor(`float32`,e,[1,3,n,t]),c=(await H.run({[a]:s}))[o].data;self.postMessage({type:`inferred`,outputData:c,id:r},[c.buffer])}self.onmessage=async e=>{let{type:t}=e.data;try{t===`load`?(e.data.ortRuntimeUrl&&(z.ortRuntimeUrl=e.data.ortRuntimeUrl),e.data.ortWasmPaths&&(z.ortWasmPaths=e.data.ortWasmPaths),e.data.cacheNamespace&&(z.cacheNamespace=e.data.cacheNamespace),e.data.storage!==void 0&&(z.storage=e.data.storage),await J(e.data.url,e.data.sessionOptions)):t===`infer`?await Y(e.data.tileData,e.data.width,e.data.height,e.data.id):t===`dispose`&&H&&(await H.release(),H=null,U=null)}catch(t){self.postMessage({type:`error`,message:t.message,id:e.data?.id})}};", Ts = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", ws], { type: "text/javascript;charset=utf-8" });
4415
+ function Es(e) {
4001
4416
  let t;
4002
4417
  try {
4003
- if (t = Po && (self.URL || self.webkitURL).createObjectURL(Po), !t) throw "";
4418
+ if (t = Ts && (self.URL || self.webkitURL).createObjectURL(Ts), !t) throw "";
4004
4419
  let n = new Worker(t, {
4005
4420
  type: "module",
4006
4421
  name: e?.name
@@ -4009,7 +4424,7 @@ function Fo(e) {
4009
4424
  (self.URL || self.webkitURL).revokeObjectURL(t);
4010
4425
  }), n;
4011
4426
  } catch {
4012
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(No), {
4427
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(ws), {
4013
4428
  type: "module",
4014
4429
  name: e?.name
4015
4430
  });
@@ -4017,7 +4432,7 @@ function Fo(e) {
4017
4432
  }
4018
4433
  //#endregion
4019
4434
  //#region src/Passes/AIUpscaler.js
4020
- var Io = {
4435
+ var Ds = {
4021
4436
  fast: {
4022
4437
  2: "2x-spanx2-ch48.onnx",
4023
4438
  4: "4xNomos8k_span_otf_strong_fp32_opset17.onnx"
@@ -4031,17 +4446,17 @@ var Io = {
4031
4446
  4: "4xNomos2_hq_mosr_fp32.onnx"
4032
4447
  }
4033
4448
  };
4034
- function Lo() {
4035
- let { upscalerModelBaseUrl: e } = at(), t = {};
4036
- for (let n in Io) {
4449
+ function Os() {
4450
+ let { upscalerModelBaseUrl: e } = ot(), t = {};
4451
+ for (let n in Ds) {
4037
4452
  t[n] = {};
4038
- for (let r in Io[n]) t[n][r] = e + Io[n][r];
4453
+ for (let r in Ds[n]) t[n][r] = e + Ds[n][r];
4039
4454
  }
4040
4455
  return t;
4041
4456
  }
4042
- var Ro = {
4457
+ var ks = {
4043
4458
  get QUALITY_PRESETS() {
4044
- return Lo();
4459
+ return Os();
4045
4460
  },
4046
4461
  TILE_SIZE: 512,
4047
4462
  TILE_OVERLAP: 16,
@@ -4052,17 +4467,17 @@ var Ro = {
4052
4467
  }],
4053
4468
  graphOptimizationLevel: "all"
4054
4469
  }
4055
- }, zo = class extends cr {
4470
+ }, As = class extends fr {
4056
4471
  constructor(e, t, n = {}) {
4057
4472
  if (super(), !e || !t) throw Error("AIUpscaler requires output canvas and renderer");
4058
- this.renderer = t, this.input = t.domElement, this.output = e, this.getSourceCanvas = n.getSourceCanvas || null, this.getGPUTextures = n.getGPUTextures || null, this.getExposure = n.getExposure || (() => 1), this.getToneMapping = n.getToneMapping || (() => Zn), this.getSaturation = n.getSaturation || (() => 1), this.enabled = !1, this.hdr = !1, this.scaleFactor = n.scaleFactor || 2, this.quality = n.quality || "fast", this.refreshInput = n.refreshInput || null, this.tileSize = n.tileSize || Ro.TILE_SIZE, this._tileSizeOverride = !!n.tileSize, this.state = {
4473
+ this.renderer = t, this.input = t.domElement, this.output = e, this.getSourceCanvas = n.getSourceCanvas || null, this.getGPUTextures = n.getGPUTextures || null, this.getExposure = n.getExposure || (() => 1), this.getToneMapping = n.getToneMapping || (() => tr), this.getSaturation = n.getSaturation || (() => 1), this.getDisplayGain = n.getDisplayGain || (() => null), this.enabled = !1, this.hdr = !1, this.scaleFactor = n.scaleFactor || 2, this.quality = n.quality || "fast", this.refreshInput = n.refreshInput || null, this.tileSize = n.tileSize || ks.TILE_SIZE, this._tileSizeOverride = !!n.tileSize, this.state = {
4059
4474
  isUpscaling: !1,
4060
4475
  isLoading: !1,
4061
4476
  abortController: null
4062
4477
  }, this._worker = null, this._currentModelUrl = null, this._tileId = 0, this._pendingWorkerHandlers = /* @__PURE__ */ new Set(), this._upscaledAlpha = null, this._upscaledAlphaWidth = 0, this._backupCanvas = null, this._baseWidth = e.width, this._baseHeight = e.height, this._toneMapper = null;
4063
4478
  }
4064
4479
  async _ensureSession() {
4065
- let e = Ro.QUALITY_PRESETS[this.quality];
4480
+ let e = ks.QUALITY_PRESETS[this.quality];
4066
4481
  if (!e) throw Error(`Unknown quality preset: ${this.quality}`);
4067
4482
  let t = e[this.scaleFactor];
4068
4483
  if (!t) throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);
@@ -4072,14 +4487,14 @@ var Ro = {
4072
4487
  message: `Loading ${this.scaleFactor}x upscale model...`
4073
4488
  });
4074
4489
  try {
4075
- this._worker ||= new Fo(), await new Promise((e, n) => {
4490
+ this._worker ||= new Es(), await new Promise((e, n) => {
4076
4491
  let r = (t) => {
4077
4492
  t.data.type === "loaded" ? (this._worker.removeEventListener("message", r), t.data.tileSize && !this._tileSizeOverride && (this.tileSize = t.data.tileSize), console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`), e()) : t.data.type === "error" && (this._worker.removeEventListener("message", r), n(Error(t.data.message)));
4078
- }, { ortRuntimeUrl: i, ortWasmPaths: a, cacheNamespace: o, storage: s } = at();
4493
+ }, { ortRuntimeUrl: i, ortWasmPaths: a, cacheNamespace: o, storage: s } = ot();
4079
4494
  this._worker.addEventListener("message", r), this._worker.postMessage({
4080
4495
  type: "load",
4081
4496
  url: t,
4082
- sessionOptions: Ro.SESSION_OPTIONS,
4497
+ sessionOptions: ks.SESSION_OPTIONS,
4083
4498
  ortRuntimeUrl: i,
4084
4499
  ortWasmPaths: a,
4085
4500
  cacheNamespace: o,
@@ -4154,7 +4569,7 @@ var Ro = {
4154
4569
  alpha: !0
4155
4570
  });
4156
4571
  this._cacheUpscaledAlpha(t, n * i, r * i);
4157
- let o = Ro.TILE_OVERLAP, s = this.tileSize, c = s - o * 2, l = Math.ceil(n / c), u = Math.ceil(r / c), d = l * u, f = 0;
4572
+ let o = ks.TILE_OVERLAP, s = this.tileSize, c = s - o * 2, l = Math.ceil(n / c), u = Math.ceil(r / c), d = l * u, f = 0;
4158
4573
  for (let o = 0; o < u; o++) for (let u = 0; u < l; u++) {
4159
4574
  if (e.aborted) throw new DOMException("Aborted", "AbortError");
4160
4575
  let l = Math.min(u * c, Math.max(0, n - s)), p = Math.min(o * c, Math.max(0, r - s)), m = Math.min(s, n - l), h = Math.min(s, r - p), g = this._extractTile(t, l, p, m, h), _ = await this._inferTile(g, m, h), v = l * i, y = p * i, b = m * i, x = h * i, S = this._tensorToImageData(_, b, x, v, y);
@@ -4195,14 +4610,15 @@ var Ro = {
4195
4610
  let e = this.getGPUTextures();
4196
4611
  if (!e?.color) throw Error("No GPU color texture available for HDR capture");
4197
4612
  let t = e.color, { width: n, height: r } = t;
4198
- this._toneMapper ??= new Et(this.renderer.backend.device, "aiupscaler-tonemap", {
4613
+ this._toneMapper ??= new Dt(this.renderer.backend.device, "aiupscaler-tonemap", {
4199
4614
  input: "texture",
4200
4615
  output: "planar"
4201
4616
  }), this._toneMapper.ensureSize(n, r);
4202
4617
  let i = await this._toneMapper.toPlanar(t, {
4203
4618
  exposure: this.getExposure(),
4204
- toneMapping: this.getToneMapping() ?? Zn,
4205
- saturation: this.getSaturation()
4619
+ toneMapping: this.getToneMapping() ?? tr,
4620
+ saturation: this.getSaturation(),
4621
+ gain: this.getDisplayGain()
4206
4622
  });
4207
4623
  return this._toneMapper.release(), {
4208
4624
  planes: i,
@@ -4296,7 +4712,7 @@ var Ro = {
4296
4712
  this.hdr = !!e;
4297
4713
  }
4298
4714
  setQuality(e) {
4299
- if (!Ro.QUALITY_PRESETS[e]) {
4715
+ if (!ks.QUALITY_PRESETS[e]) {
4300
4716
  console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);
4301
4717
  return;
4302
4718
  }
@@ -4319,9 +4735,9 @@ var Ro = {
4319
4735
  async dispose() {
4320
4736
  this.abort(), this._cleanupPendingWorkerHandlers(), this._worker &&= (this._worker.postMessage({ type: "dispose" }), this._worker.terminate(), null), this._currentModelUrl = null, this._backupCanvas = null, this._upscaledAlpha = null, this.state.abortController = null, this._toneMapper?.dispose(), this._toneMapper = null, console.log("AIUpscaler disposed");
4321
4737
  }
4322
- }, Bo = Ke("neural"), Vo = 120, Ho = 2, Uo = 1, Wo = 0, Go = 300, Ko = 5, qo = 3, Jo = 3, Yo = 16, Xo = (e) => Math.max(0, 1 - e / Yo), Zo = class extends cr {
4323
- constructor({ renderer: e, mainCanvas: t, stages: n, pipeline: r, getExposure: i, getSaturation: a, issues: o = null }) {
4324
- super(), this.renderer = e, this._issues = o, this.mainCanvas = t, this.upscalerCanvas = this._createUpscalerCanvas(t), this.pipeline = r, this._stages = n, this._getExposure = i, this._getSaturation = a, this.denoiser = null, this.upscaler = null, this.upscalerBackend = "esrgan", this._neuralUpscaler = null, this.neuralRendering = !1, this.neuralRenderingSettings = {}, this._retouch = null, this._superResModule = null, this._neuralPostBusy = !1, this._finalQuality = Yr.oidnQuality, this.finalDenoise = Yr.enableOIDN, this.continuousDenoise = Yr.continuousDenoise, this.continuousDenoiseInterval = Yr.continuousDenoiseInterval, this._lastCadenceAt = -Infinity, this._lastCadenceSamples = 0, this._failedRefreshes = 0, this._cadenceSuspended = !1, this._movingDenoiseMs = [], this._movingHopeless = !1, this._holdWhileMoving = null, this._onReset = null, this._onPostProcessRefresh = null, this._onDisplayRefresh = null, this.temporalHistory = Yr.oidnTemporalHistory, this._history = null, this._historyDirty = !0, this._knownResetCount = 0, this._seenTracedFrames = 0, this._viewProj = new hr(), this._historyCamera = {
4738
+ }, js = Ke("neural"), Ms = 120, Ns = 2, Ps = 1, Fs = 0, Is = 300, Ls = 5, Rs = 3, zs = 3, Bs = 16, Vs = (e) => Math.max(0, 1 - e / Bs), Hs = class extends fr {
4739
+ constructor({ renderer: e, mainCanvas: t, stages: n, pipeline: r, getExposure: i, getSaturation: a, getDisplayGain: o = null, issues: s = null }) {
4740
+ super(), this.renderer = e, this._issues = s, this.mainCanvas = t, this.upscalerCanvas = this._createUpscalerCanvas(t), this.pipeline = r, this._stages = n, this._getExposure = i, this._getSaturation = a, this._getDisplayGain = o, this.denoiser = null, this.upscaler = null, this.upscalerBackend = "esrgan", this._neuralUpscaler = null, this.neuralRendering = !1, this.neuralRenderingSettings = {}, this._retouch = null, this._superResModule = null, this._neuralPostBusy = !1, this._finalQuality = ei.oidnQuality, this.finalDenoise = ei.enableOIDN, this.continuousDenoise = ei.continuousDenoise, this.continuousDenoiseInterval = ei.continuousDenoiseInterval, this._lastCadenceAt = -Infinity, this._lastCadenceSamples = 0, this._failedRefreshes = 0, this._cadenceSuspended = !1, this._movingDenoiseMs = [], this._movingHopeless = !1, this._holdWhileMoving = null, this._onReset = null, this._onPostProcessRefresh = null, this._onDisplayRefresh = null, this.temporalHistory = ei.oidnTemporalHistory, this._history = null, this._historyDirty = !0, this._knownResetCount = 0, this._seenTracedFrames = 0, this._viewProj = new br(), this._historyCamera = {
4325
4741
  world: null,
4326
4742
  projInv: null,
4327
4743
  viewProj: null,
@@ -4330,7 +4746,7 @@ var Ro = {
4330
4746
  count: 0,
4331
4747
  leaves: new Uint32Array(),
4332
4748
  toPrev: new Float32Array()
4333
- }, this._matA = new hr(), this._matB = new hr(), this._lastRenderWidth = 0, this._lastRenderHeight = 0, this._pendingStartUpscaler = null, this._pendingCloseDenoise = null, this._denoiserStartHandler = null, this._denoiserEndHandler = null, this._denoiserTileHandler = null, this._denoiserErrorHandler = null, this._upscalerResChangedHandler = null, this._upscalerStartHandler = null, this._upscalerProgressHandler = null, this._upscalerEndHandler = null;
4749
+ }, this._matA = new br(), this._matB = new br(), this._lastRenderWidth = 0, this._lastRenderHeight = 0, this._pendingStartUpscaler = null, this._pendingCloseDenoise = null, this._denoiserStartHandler = null, this._denoiserEndHandler = null, this._denoiserTileHandler = null, this._denoiserErrorHandler = null, this._upscalerResChangedHandler = null, this._upscalerStartHandler = null, this._upscalerProgressHandler = null, this._upscalerEndHandler = null;
4334
4750
  }
4335
4751
  _createUpscalerCanvas(e) {
4336
4752
  let t = e.parentNode;
@@ -4352,9 +4768,9 @@ var Ro = {
4352
4768
  }
4353
4769
  setupDenoiser() {
4354
4770
  let e = this._stages.pathTracer;
4355
- this.denoiser = new go(this.renderer, {
4356
- enableOIDN: Yr.enableOIDN,
4357
- oidnQuality: Yr.oidnQuality,
4771
+ this.denoiser = new ss(this.renderer, {
4772
+ enableOIDN: ei.enableOIDN,
4773
+ oidnQuality: ei.oidnQuality,
4358
4774
  backendParams: () => ({
4359
4775
  device: this.renderer.backend.device,
4360
4776
  adapterInfo: null
@@ -4392,9 +4808,9 @@ var Ro = {
4392
4808
  setupUpscaler() {
4393
4809
  if (!this.upscalerCanvas) return;
4394
4810
  let e = this._stages.pathTracer;
4395
- this.upscaler = new zo(this.upscalerCanvas, this.renderer, {
4396
- scaleFactor: Yr.upscalerScale || 2,
4397
- quality: Yr.upscalerQuality || "fast",
4811
+ this.upscaler = new As(this.upscalerCanvas, this.renderer, {
4812
+ scaleFactor: ei.upscalerScale || 2,
4813
+ quality: ei.upscalerQuality || "fast",
4398
4814
  getSourceCanvas: () => this.renderer.domElement,
4399
4815
  refreshInput: () => {
4400
4816
  let e = this.pipeline?.context;
@@ -4407,8 +4823,9 @@ var Ro = {
4407
4823
  },
4408
4824
  getExposure: () => this._getEffectiveExposure(),
4409
4825
  getToneMapping: () => this._getToneMapping(),
4410
- getSaturation: () => this._getSaturation()
4411
- }), this.upscaler.enabled = Yr.enableUpscaler || !1, this._upscalerResChangedHandler = (e) => this.dispatchEvent({
4826
+ getSaturation: () => this._getSaturation(),
4827
+ getDisplayGain: () => this._getDisplayGain?.() ?? null
4828
+ }), this.upscaler.enabled = ei.enableUpscaler || !1, this._upscalerResChangedHandler = (e) => this.dispatchEvent({
4412
4829
  type: j.RESOLUTION_CHANGED,
4413
4830
  width: e.width,
4414
4831
  height: e.height
@@ -4443,8 +4860,7 @@ var Ro = {
4443
4860
  this._applyASVGFPreset(e);
4444
4861
  }
4445
4862
  setAutoExposureEnabled(e, t) {
4446
- let n = this._stages;
4447
- n.autoExposure && (n.autoExposure.enabled = e, !e && this.renderer && (this.renderer.toneMappingExposure = t));
4863
+ this._stages.autoExposure?.setEnabled(e, t);
4448
4864
  }
4449
4865
  get requiresMotionVectors() {
4450
4866
  return !!(this._stages.asvgf?.enabled || this._stages.nrd?.enabled);
@@ -4468,8 +4884,8 @@ var Ro = {
4468
4884
  get holdsWhileMoving() {
4469
4885
  if (!this._stages.pathTracer?.viewIsChanging || !this.continuousDenoise || this._cadenceSuspended || !this.denoiser?.enabled || this._movingHopeless) return !1;
4470
4886
  let e = this.movingCostMs, t = this._movingDenoiseMs.length;
4471
- e > Go * qo && (this._movingHopeless = !0, this._syncGBufferStages());
4472
- let n = !this._movingHopeless && (t < 2 || e <= Go);
4887
+ e > Is * Rs && (this._movingHopeless = !0, this._syncGBufferStages());
4888
+ let n = !this._movingHopeless && (t < 2 || e <= Is);
4473
4889
  return this._holdWhileMoving = (this._holdWhileMoving === null || this._holdWhileMoving) && n, this._holdWhileMoving;
4474
4890
  }
4475
4891
  skipsTrace() {
@@ -4486,7 +4902,7 @@ var Ro = {
4486
4902
  this.pipeline?.context?.removeTexture("oidn:output"), this.denoiser?.invalidateOutput();
4487
4903
  }
4488
4904
  _checkHeldFrameHealthy() {
4489
- !this.denoiser?.hasOutput || this._failedRefreshes < Jo || this._unpublishOutput();
4905
+ !this.denoiser?.hasOutput || this._failedRefreshes < zs || this._unpublishOutput();
4490
4906
  }
4491
4907
  tickContinuousDenoise(e) {
4492
4908
  let t = this.denoiser;
@@ -4496,12 +4912,12 @@ var Ro = {
4496
4912
  if (!n) this._holdWhileMoving = null, this._movingDenoiseMs.length = 0;
4497
4913
  else if (!this.holdsWhileMoving) return !1;
4498
4914
  if (t.state.isDenoising || t.state.isLoading || !n && e <= this._lastCadenceSamples) return !1;
4499
- let r = performance.now(), i = n ? Wo : this._lastCadenceSamples === 0 ? Uo : Ho, a = Math.max(this.continuousDenoiseInterval, t.lastDenoiseMs * i);
4915
+ let r = performance.now(), i = n ? Fs : this._lastCadenceSamples === 0 ? Ps : Ns, a = Math.max(this.continuousDenoiseInterval, t.lastDenoiseMs * i);
4500
4916
  if (r - this._lastCadenceAt < a) return !1;
4501
- this._lastCadenceAt = r, this._lastCadenceSamples = e, t.lastDenoiseMs > Vo && (this._cadenceDowngraded = !0);
4917
+ this._lastCadenceAt = r, this._lastCadenceSamples = e, t.lastDenoiseMs > Ms && (this._cadenceDowngraded = !0);
4502
4918
  let o = this._cadenceDowngraded ? this.previewQuality() : this._finalQuality;
4503
4919
  return t.quality !== o && t.updateQuality(o), t.start({ continuous: !0 }).then((e) => {
4504
- this._failedRefreshes = e ? 0 : this._failedRefreshes + 1, !(!e || !n) && (this._movingDenoiseMs.push(t.lastDenoiseMs), this._movingDenoiseMs.length > Ko && this._movingDenoiseMs.shift());
4920
+ this._failedRefreshes = e ? 0 : this._failedRefreshes + 1, !(!e || !n) && (this._movingDenoiseMs.push(t.lastDenoiseMs), this._movingDenoiseMs.length > Ls && this._movingDenoiseMs.shift());
4505
4921
  }), !0;
4506
4922
  }
4507
4923
  previewQuality() {
@@ -4543,7 +4959,7 @@ var Ro = {
4543
4959
  r && (this._ensureHistory().merge(r, t.frameCount, this._historyCameraNow(), {
4544
4960
  commit: !0,
4545
4961
  keepHistory: !this._historyDirty && !n,
4546
- historyScale: Xo(t.frameCount)
4962
+ historyScale: Vs(t.frameCount)
4547
4963
  }), this._historyDirty = !1);
4548
4964
  }
4549
4965
  afterReset() {
@@ -4585,9 +5001,9 @@ var Ro = {
4585
5001
  let e = this._stages.pathTracer, t = this._history;
4586
5002
  if (!t?.valid || this._historyDirty || !this.historyActive || e.isComplete || e.resetCount !== this._knownResetCount || t.width !== this._lastRenderWidth || t.height !== this._lastRenderHeight) return null;
4587
5003
  if (e.frameCount <= 1) return t.textures;
4588
- if (e.frameCount >= Yo) return null;
5004
+ if (e.frameCount >= Bs) return null;
4589
5005
  let n = this._historyInputs();
4590
- return n ? t.merge(n, e.frameCount, this._historyCameraNow(), { historyScale: Xo(e.frameCount) }) : null;
5006
+ return n ? t.merge(n, e.frameCount, this._historyCameraNow(), { historyScale: Vs(e.frameCount) }) : null;
4591
5007
  }
4592
5008
  _historyInputs() {
4593
5009
  let e = this._stages.pathTracer, t = this.pipeline?.context, n = this.renderer?.backend;
@@ -4612,7 +5028,7 @@ var Ro = {
4612
5028
  return t.world = e.cameraWorldMatrix.value.elements, t.projInv = e.cameraProjectionMatrixInverse.value.elements, t.viewProj = this._viewProj.elements, t.orthographic = e.uniforms?.get("cameraProjection")?.value === Ae.orthographic, t;
4613
5029
  }
4614
5030
  _ensureHistory() {
4615
- return this._history ??= new Mo(this.renderer.backend.device), this._history.settings.cleanAux = !!this.denoiser?.expectsCleanAux(this._finalQuality), this._history;
5031
+ return this._history ??= new Cs(this.renderer.backend.device), this._history.settings.cleanAux = !!this.denoiser?.expectsCleanAux(this._finalQuality), this._history;
4616
5032
  }
4617
5033
  _releaseHistory() {
4618
5034
  this._history?.dispose(), this._history = null, this._historyDirty = !0, this._movedPlacements.clear();
@@ -4649,19 +5065,20 @@ var Ro = {
4649
5065
  return;
4650
5066
  }
4651
5067
  if (!this.pipeline?.context?.getTexture("oidn:output")) {
4652
- Bo.warn("neural pass skipped: no denoised picture — it needs OIDN");
5068
+ js.warn("neural pass skipped: no denoised picture — it needs OIDN");
4653
5069
  return;
4654
5070
  }
4655
5071
  this._neuralPostBusy = !0, this.dispatchEvent({ type: j.UPSCALING_START });
4656
5072
  try {
4657
- let r = await import("./NeuralSuperRes-CZNQP13W.js").then((e) => e.t);
5073
+ let r = await import("./NeuralSuperRes-DV5TtURP.js").then((e) => e.t);
4658
5074
  this._superResModule = r;
4659
- let i = n ? await import("./NeuralRetouch-DiBH63kz.js").then((e) => e.t) : null, a = this.denoiser?._outTexSize, o = (a?.width ?? 0) * (a?.height ?? 0), s = n && o <= i.RETOUCH_MAX_PIXELS;
4660
- if (n && !s && (Bo.warn(`Neural rendering skipped: the render is ${(o / 1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS / 1e6).toFixed(1)} MP the pass survives.` + (t ? " The upscale still ran." : "")), this._releaseNeuralRetouch()), !t && !s) return;
5075
+ let i = n ? await import("./NeuralRetouch-C3Q2XqbF.js").then((e) => e.t) : null, a = this.denoiser?._outTexSize, o = (a?.width ?? 0) * (a?.height ?? 0), s = n && o <= i.RETOUCH_MAX_PIXELS;
5076
+ if (n && !s && (js.warn(`Neural rendering skipped: the render is ${(o / 1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS / 1e6).toFixed(1)} MP the pass survives.` + (t ? " The upscale still ran." : "")), this._releaseNeuralRetouch()), !t && !s) return;
4661
5077
  let c = {
4662
5078
  exposure: this._getEffectiveExposure(),
4663
5079
  toneMapping: this._getToneMapping(),
4664
- saturation: this._getSaturation?.() ?? 1
5080
+ saturation: this._getSaturation?.() ?? 1,
5081
+ gain: this._getDisplayGain?.() ?? null
4665
5082
  }, l = await r.readDenoisedHalf(this.denoiser);
4666
5083
  t && (this._neuralUpscaler && (this._neuralUpscaler.inputWidth !== l.width || this._neuralUpscaler.inputHeight !== l.height) && this._releaseNeuralUpscaler(), this._neuralUpscaler ||= await r.NeuralSuperRes.create({
4667
5084
  width: l.width,
@@ -4692,7 +5109,7 @@ var Ro = {
4692
5109
  height: u.height
4693
5110
  });
4694
5111
  } catch (e) {
4695
- Bo.warn("neural pass failed", e);
5112
+ js.warn("neural pass failed", e);
4696
5113
  } finally {
4697
5114
  this._neuralPostBusy = !1, this.dispatchEvent({ type: j.UPSCALING_END });
4698
5115
  }
@@ -4744,7 +5161,7 @@ var Ro = {
4744
5161
  this._unpublishOutput(), this._restoreRenderDisplay(), this._historyDirty = !0;
4745
5162
  }
4746
5163
  dispose() {
4747
- this._cleanupCompletionListener(), this._releaseNeuralUpscaler(), this._releaseNeuralRetouch(), this._unpublishOutput(), this._releaseHistory(), this.denoiser &&= (this._denoiserStartHandler && this.denoiser.removeEventListener("start", this._denoiserStartHandler), this._denoiserEndHandler && this.denoiser.removeEventListener("end", this._denoiserEndHandler), this._denoiserTileHandler && this.denoiser.removeEventListener("tileProgress", this._denoiserTileHandler), this._denoiserErrorHandler && this.denoiser.removeEventListener("error", this._denoiserErrorHandler), this.denoiser.dispose(), null), this.upscaler && (this._upscalerResChangedHandler && this.upscaler.removeEventListener("resolution_changed", this._upscalerResChangedHandler), this._upscalerStartHandler && this.upscaler.removeEventListener("start", this._upscalerStartHandler), this._upscalerProgressHandler && this.upscaler.removeEventListener("progress", this._upscalerProgressHandler), this._upscalerEndHandler && this.upscaler.removeEventListener("end", this._upscalerEndHandler), this.upscaler.dispose(), this.upscaler = null, this.upscalerBackend = "esrgan", this._neuralUpscaler = null), this._denoiserStartHandler = null, this._denoiserEndHandler = null, this._denoiserTileHandler = null, this._denoiserErrorHandler = null, this._upscalerResChangedHandler = null, this._upscalerStartHandler = null, this._upscalerProgressHandler = null, this._upscalerEndHandler = null, this._onReset = null, this._onPostProcessRefresh = null, this._onDisplayRefresh = null, this._issues = null, this.upscalerCanvas?.parentNode && (this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas), this.upscalerCanvas = null);
5164
+ this._cleanupCompletionListener(), this._releaseNeuralUpscaler(), this._releaseNeuralRetouch(), this._unpublishOutput(), this._releaseHistory(), this.denoiser &&= (this._denoiserStartHandler && this.denoiser.removeEventListener("start", this._denoiserStartHandler), this._denoiserEndHandler && this.denoiser.removeEventListener("end", this._denoiserEndHandler), this._denoiserTileHandler && this.denoiser.removeEventListener("tileProgress", this._denoiserTileHandler), this._denoiserErrorHandler && this.denoiser.removeEventListener("error", this._denoiserErrorHandler), this.denoiser.dispose(), null), this.upscaler && (this._upscalerResChangedHandler && this.upscaler.removeEventListener("resolution_changed", this._upscalerResChangedHandler), this._upscalerStartHandler && this.upscaler.removeEventListener("start", this._upscalerStartHandler), this._upscalerProgressHandler && this.upscaler.removeEventListener("progress", this._upscalerProgressHandler), this._upscalerEndHandler && this.upscaler.removeEventListener("end", this._upscalerEndHandler), this.upscaler.dispose(), this.upscaler = null, this.upscalerBackend = "esrgan", this._neuralUpscaler = null), this._denoiserStartHandler = null, this._denoiserEndHandler = null, this._denoiserTileHandler = null, this._denoiserErrorHandler = null, this._upscalerResChangedHandler = null, this._upscalerStartHandler = null, this._upscalerProgressHandler = null, this._upscalerEndHandler = null, this._onReset = null, this._onPostProcessRefresh = null, this._onDisplayRefresh = null, this._getExposure = null, this._getSaturation = null, this._getDisplayGain = null, this._issues = null, this.upscalerCanvas?.parentNode && (this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas), this.upscalerCanvas = null);
4748
5165
  }
4749
5166
  setOverlayManager(e) {
4750
5167
  this._overlayManager = e;
@@ -4807,7 +5224,7 @@ var Ro = {
4807
5224
  this.upscaler?.setQuality(e);
4808
5225
  }
4809
5226
  setAutoExposure(e) {
4810
- this.setAutoExposureEnabled(e, this._getExposure()), this._onReset?.();
5227
+ this.setAutoExposureEnabled(e, this._getExposure());
4811
5228
  }
4812
5229
  setStrategy(e, t) {
4813
5230
  this.setDenoiserStrategy(e, t), this._onReset?.();
@@ -4845,20 +5262,20 @@ var Ro = {
4845
5262
  ].forEach((t) => e.removeTexture(t));
4846
5263
  }
4847
5264
  _applyNRDPreset(e) {
4848
- let t = qr[e];
5265
+ let t = Qr[e];
4849
5266
  if (!t) return;
4850
5267
  let n = {};
4851
- for (let e of Kr) n[e] = Gr[e];
5268
+ for (let e of Zr) n[e] = Xr[e];
4852
5269
  this._stages.nrd?.updateParameters({
4853
5270
  ...n,
4854
5271
  ...t
4855
5272
  });
4856
5273
  }
4857
5274
  _applyASVGFPreset(e) {
4858
- let t = Hr[e];
5275
+ let t = qr[e];
4859
5276
  t && (this._stages.asvgf?.updateParameters(t), this._stages.bilateralFilter?.updateParameters(t), this._stages.variance && t.varianceBoost !== void 0 && (this._stages.variance.varianceBoost.value = t.varianceBoost));
4860
5277
  }
4861
- }, Qo = class {
5278
+ }, Us = class {
4862
5279
  constructor() {
4863
5280
  this.layer = "hud", this.visible = !1, this._tileBounds = null, this._imageWidth = 1, this._imageHeight = 1, this.enabled = !0, this._borderColor = "rgba(255, 0, 0, 0.6)", this._borderWidthRatio = 1 / 540, this._borderWidthMin = 1.5, this._borderWidthMax = 4;
4864
5281
  }
@@ -4882,18 +5299,18 @@ var Ro = {
4882
5299
  dispose() {
4883
5300
  this.visible = !1;
4884
5301
  }
4885
- }, $o = class {
5302
+ }, Ws = class {
4886
5303
  constructor(e, t) {
4887
5304
  this.layer = "scene", this._enabled = !0, this._scene = e, this._camera = t, this._build([]);
4888
5305
  }
4889
5306
  _build(e) {
4890
- this._orthographic = this._camera.isOrthographicCamera === !0, this._outlineNode = Lr(this._scene, this._camera, {
5307
+ this._orthographic = this._camera.isOrthographicCamera === !0, this._outlineNode = Hr(this._scene, this._camera, {
4891
5308
  selectedObjects: e,
4892
- edgeThickness: K(1),
4893
- edgeGlow: K(0)
5309
+ edgeThickness: G(1),
5310
+ edgeGlow: G(0)
4894
5311
  });
4895
- let t = K(3), n = K(new rr(16777215)), r = K(new rr(1640965)), { visibleEdge: i, hiddenEdge: a } = this._outlineNode, o = i.mul(n).add(a.mul(r)).mul(t), s = o.r.max(o.g).max(o.b).clamp(0, 1);
4896
- this._material = new yn(), this._material.colorNode = J(o, s), this._material.transparent = !0, this._material.blending = ar, this._material.blendEquation = Qn, this._material.blendSrc = br, this._material.blendDst = br, this._material.blendEquationAlpha = Qn, this._material.blendSrcAlpha = br, this._material.blendDstAlpha = br, this._material.toneMapped = !1, this._material.depthTest = !1, this._material.depthWrite = !1, this._quad = new bn(this._material);
5312
+ let t = G(3), n = G(new sr(16777215)), r = G(new sr(1640965)), { visibleEdge: i, hiddenEdge: a } = this._outlineNode, o = i.mul(n).add(a.mul(r)).mul(t), s = o.r.max(o.g).max(o.b).clamp(0, 1);
5313
+ this._material = new bn(), this._material.colorNode = J(o, s), this._material.transparent = !0, this._material.blending = lr, this._material.blendEquation = nr, this._material.blendSrc = Tr, this._material.blendDst = Tr, this._material.blendEquationAlpha = nr, this._material.blendSrcAlpha = Tr, this._material.blendDstAlpha = Tr, this._material.toneMapped = !1, this._material.depthTest = !1, this._material.depthWrite = !1, this._quad = new xn(this._material);
4897
5314
  }
4898
5315
  setSelectedObjects(e) {
4899
5316
  this._outlineNode.selectedObjects = e;
@@ -4920,11 +5337,11 @@ var Ro = {
4920
5337
  this._enabled = !1, this._outlineNode?.dispose(), this._material?.dispose(), this._quad = null;
4921
5338
  }
4922
5339
  };
4923
- function es(e = !1) {
5340
+ function Gs(e = !1) {
4924
5341
  let t = document.createElement("canvas");
4925
5342
  return t.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;" + (e ? "display:none;" : ""), t;
4926
5343
  }
4927
- function ts(e, t = Infinity) {
5344
+ function Ks(e, t = Infinity) {
4928
5345
  let n = e?.getBoundingClientRect();
4929
5346
  if (!n || n.width === 0 || n.height === 0) return null;
4930
5347
  let r = Math.min(window.devicePixelRatio || 1, 2), i = Math.round(n.width * r), a = Math.round(n.height * r), o = t / Math.max(i, a);
@@ -4935,26 +5352,26 @@ function ts(e, t = Infinity) {
4935
5352
  }
4936
5353
  //#endregion
4937
5354
  //#region src/managers/helpers/ViewOverlayRenderer.js
4938
- var ns = 4096, rs = class {
5355
+ var qs = 4096, Js = class {
4939
5356
  constructor() {
4940
- this.canvas = es(!0), this._visible = !1, this.renderer = null, this._sizeSource = null;
5357
+ this.canvas = Gs(!0), this._visible = !1, this.renderer = null, this._sizeSource = null;
4941
5358
  }
4942
5359
  async init({ device: e, sizeSource: t }) {
4943
5360
  this._sizeSource = t;
4944
- let n = e.onuncapturederror, r = new Cn({
5361
+ let n = e.onuncapturederror, r = new Tn({
4945
5362
  canvas: this.canvas,
4946
5363
  device: e,
4947
5364
  alpha: !0,
4948
5365
  antialias: (window.devicePixelRatio || 1) < 2
4949
5366
  });
4950
- return await r.init(), e.onuncapturederror = n, r.outputColorSpace = Dr, r.setPixelRatio(1), r.setClearColor(0, 0), r.autoClear = !1, this.renderer = r, this.syncSize(), this;
5367
+ return await r.init(), e.onuncapturederror = n, r.outputColorSpace = Mr, r.setPixelRatio(1), r.setClearColor(0, 0), r.autoClear = !1, this.renderer = r, this.syncSize(), this;
4951
5368
  }
4952
5369
  get isVisible() {
4953
5370
  return this._visible;
4954
5371
  }
4955
5372
  syncSize() {
4956
5373
  if (!this.renderer) return;
4957
- let e = ts(this._sizeSource, ns);
5374
+ let e = Ks(this._sizeSource, qs);
4958
5375
  !e || e.width === this.canvas.width && e.height === this.canvas.height || this.renderer.setSize(e.width, e.height, !1);
4959
5376
  }
4960
5377
  begin() {
@@ -4966,18 +5383,18 @@ var ns = 4096, rs = class {
4966
5383
  dispose() {
4967
5384
  Pe(this.renderer), this.renderer = null, this.canvas.parentElement?.removeChild(this.canvas);
4968
5385
  }
4969
- }, is = Ke("overlay"), as = (e, t) => e.visible && e.layer === t && e.render, os = class {
5386
+ }, Ys = Ke("overlay"), Xs = (e, t) => e.visible && e.layer === t && e.render, Zs = class {
4970
5387
  constructor(e) {
4971
- this.camera = e, this._helpers = /* @__PURE__ */ new Map(), this._hudCanvas = es(), this._hudCtx = this._hudCanvas.getContext("2d"), this._helperScene = null, this._viewOverlay = null;
5388
+ this.camera = e, this._helpers = /* @__PURE__ */ new Map(), this._hudCanvas = Gs(), this._hudCtx = this._hudCanvas.getContext("2d"), this._helperScene = null, this._viewOverlay = null;
4972
5389
  }
4973
5390
  async initViewRenderer({ device: e, sizeSource: t }) {
4974
5391
  if (!(!e || !t)) try {
4975
- this._viewOverlay = await new rs().init({
5392
+ this._viewOverlay = await new Js().init({
4976
5393
  device: e,
4977
5394
  sizeSource: t
4978
5395
  });
4979
5396
  } catch (e) {
4980
- is.error("overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled", e), this._viewOverlay = null;
5397
+ Ys.error("overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled", e), this._viewOverlay = null;
4981
5398
  }
4982
5399
  }
4983
5400
  gpuResources() {
@@ -4997,11 +5414,11 @@ var ns = 4096, rs = class {
4997
5414
  }
4998
5415
  setupDefaultHelpers({ helperScene: e, meshScene: t, pipeline: n, denoisingManager: r, app: i, renderWidth: a, renderHeight: o }) {
4999
5416
  this.setHelperScene(e);
5000
- let s = new Qo();
5417
+ let s = new Us();
5001
5418
  this.register("tiles", s), s.setRenderSize(a || 1, o || 1), i.addEventListener(j.RESOLUTION_CHANGED, (e) => {
5002
5419
  s.setRenderSize(e.width, e.height);
5003
5420
  }), n.eventBus.on("pipeline:reset", () => s.hide()), this._wireDenoiserTileEvents(s, r);
5004
- let c = new $o(t, this.camera);
5421
+ let c = new Ws(t, this.camera);
5005
5422
  this.register("outline", c);
5006
5423
  }
5007
5424
  _wireDenoiserTileEvents(e, t) {
@@ -5013,7 +5430,7 @@ var ns = 4096, rs = class {
5013
5430
  }));
5014
5431
  }
5015
5432
  register(e, t) {
5016
- this._helpers.has(e) && (is.warn(`helper "${e}" already registered — replacing.`), this._helpers.get(e).dispose?.()), this._helpers.set(e, t);
5433
+ this._helpers.has(e) && (Ys.warn(`helper "${e}" already registered — replacing.`), this._helpers.get(e).dispose?.()), this._helpers.set(e, t);
5017
5434
  }
5018
5435
  unregister(e) {
5019
5436
  let t = this._helpers.get(e);
@@ -5051,16 +5468,16 @@ var ns = 4096, rs = class {
5051
5468
  }
5052
5469
  _renderSceneLayer(e) {
5053
5470
  this._helperScene?.render(e, this.camera);
5054
- for (let t of this._helpers.values()) as(t, "scene") && t.render(e, this.camera);
5471
+ for (let t of this._helpers.values()) Xs(t, "scene") && t.render(e, this.camera);
5055
5472
  }
5056
5473
  _hasVisibleSceneOverlay() {
5057
5474
  if (this._helperScene?.isDrawing) return !0;
5058
- for (let e of this._helpers.values()) if (as(e, "scene")) return !0;
5475
+ for (let e of this._helpers.values()) if (Xs(e, "scene")) return !0;
5059
5476
  return !1;
5060
5477
  }
5061
5478
  refreshHUD() {
5062
5479
  let e = this._hudCanvas, t = this._hudCtx, n = !1;
5063
- for (let e of this._helpers.values()) if (as(e, "hud")) {
5480
+ for (let e of this._helpers.values()) if (Xs(e, "hud")) {
5064
5481
  n = !0;
5065
5482
  break;
5066
5483
  }
@@ -5069,10 +5486,10 @@ var ns = 4096, rs = class {
5069
5486
  return;
5070
5487
  }
5071
5488
  e.style.display !== "" && (e.style.display = "");
5072
- let r = e.clientWidth, i = e.clientHeight, a = r > 0 && i > 0 ? ts(e) : null;
5489
+ let r = e.clientWidth, i = e.clientHeight, a = r > 0 && i > 0 ? Ks(e) : null;
5073
5490
  if (a) {
5074
5491
  (e.width !== a.width || e.height !== a.height) && (e.width = a.width, e.height = a.height), t.clearRect(0, 0, a.width, a.height), t.save(), t.scale(a.width / r, a.height / i);
5075
- for (let e of this._helpers.values()) as(e, "hud") && e.render(t, r, i);
5492
+ for (let e of this._helpers.values()) Xs(e, "hud") && e.render(t, r, i);
5076
5493
  t.restore(), e.style.display !== "" && (e.style.display = "");
5077
5494
  }
5078
5495
  }
@@ -5083,7 +5500,7 @@ var ns = 4096, rs = class {
5083
5500
  };
5084
5501
  //#endregion
5085
5502
  //#region src/managers/AnimationManager.js
5086
- function ss(e, t) {
5503
+ function Qs(e, t) {
5087
5504
  let n = [...e].filter((t) => {
5088
5505
  for (let n = t.parent; n; n = n.parent) if (e.has(n)) return !1;
5089
5506
  return !0;
@@ -5092,18 +5509,18 @@ function ss(e, t) {
5092
5509
  for (let e of n) e.traverse?.(() => i++);
5093
5510
  return i + n.length / 2 < r ? n : null;
5094
5511
  }
5095
- var cs = class extends cr {
5512
+ var $s = class extends fr {
5096
5513
  constructor() {
5097
- super(), this.mixer = null, this.timer = new Ar(), this.actions = [], this.isPlaying = !1, this._scene = null, this._mixerRoot = null, this._meshes = null, this._meshTriRanges = null, this._meshPositions = null, this._tempVec = new $(), this._skinnedCache = null, this._clipsCache = null, this._savedTimeScale = 1, this.onFinished = null, this._rigid = !1, this._plans = null, this._allPlan = null, this._activeClip = 0, this._slotOf = null, this._lastWorld = null, this._lastVisible = null, this._lastMeshWorld = null, this._lastMorphWeights = null, this.wakeCallback = null, this.applyPoseCallback = null;
5514
+ super(), this.mixer = null, this.timer = new Fr(), this.actions = [], this.isPlaying = !1, this._scene = null, this._mixerRoot = null, this._meshes = null, this._meshTriRanges = null, this._meshPositions = null, this._tempVec = new $(), this._skinnedCache = null, this._clipsCache = null, this._savedTimeScale = 1, this.onFinished = null, this._rigid = !1, this._plans = null, this._allPlan = null, this._activeClip = 0, this._slotOf = null, this._lastWorld = null, this._lastVisible = null, this._lastMeshWorld = null, this._lastMorphWeights = null, this.wakeCallback = null, this.applyPoseCallback = null;
5098
5515
  }
5099
5516
  init(e, t, n, r) {
5100
5517
  if (this.dispose(), !r || r.length === 0) return;
5101
- this._scene = e, this._mixerRoot = t, this._meshes = n, this.mixer = new $n(t);
5518
+ this._scene = e, this._mixerRoot = t, this._meshes = n, this.mixer = new rr(t);
5102
5519
  let i = r.map((e) => this.mixer.clipAction(e)), a = (e, t) => e.name === t || e.getObjectByName(t) !== void 0;
5103
5520
  !i.some((e) => e.getClip().tracks.some((e) => {
5104
5521
  let n = e.name.split(".")[0];
5105
5522
  return a(t, n);
5106
- })) && t !== e && (console.log("[AnimationManager] Tracks did not resolve from model root, retrying with scene root"), this.mixer = new $n(e), this._mixerRoot = e, i = r.map((e) => this.mixer.clipAction(e))), this.actions = i, this._rigid = !n.some((e) => e?.isSkinnedMesh) && !r.some((e) => e.tracks.some((e) => e.name.includes("morphTargetInfluences"))), this._planClips(r), this.mixer.addEventListener("finished", () => {
5523
+ })) && t !== e && (console.log("[AnimationManager] Tracks did not resolve from model root, retrying with scene root"), this.mixer = new rr(e), this._mixerRoot = e, i = r.map((e) => this.mixer.clipAction(e))), this.actions = i, this._rigid = !n.some((e) => e?.isSkinnedMesh) && !r.some((e) => e.tracks.some((e) => e.name.includes("morphTargetInfluences"))), this._planClips(r), this.mixer.addEventListener("finished", () => {
5107
5524
  this.isPlaying = !1, this.timer.reset(), this.onFinished && this.onFinished();
5108
5525
  }), this._meshTriRanges = [], this._skinnedCache = [];
5109
5526
  let o = 0;
@@ -5127,7 +5544,7 @@ var cs = class extends cr {
5127
5544
  }), this._plans = e.map((e) => {
5128
5545
  let r = /* @__PURE__ */ new Set(), i = !1, a = !1;
5129
5546
  for (let o of e.tracks) {
5130
- let { nodeName: e, propertyName: s } = Cr.parseTrackName(o.name), c = e === "" || e === "." ? t : n.get(e);
5547
+ let { nodeName: e, propertyName: s } = Or.parseTrackName(o.name), c = e === "" || e === "." ? t : n.get(e);
5131
5548
  if (!c) {
5132
5549
  a = !0;
5133
5550
  continue;
@@ -5146,7 +5563,7 @@ var cs = class extends cr {
5146
5563
  visibility: i,
5147
5564
  cameras: [...s],
5148
5565
  nodes: a ? null : r,
5149
- roots: a ? null : ss(r, t)
5566
+ roots: a ? null : Qs(r, t)
5150
5567
  };
5151
5568
  }), this._allPlan = null, !this._rigid) return;
5152
5569
  this._slotOf = new Int32Array(this._meshes.length).fill(-1);
@@ -5165,7 +5582,7 @@ var cs = class extends cr {
5165
5582
  visibility: n,
5166
5583
  cameras: [...t],
5167
5584
  nodes: r,
5168
- roots: r ? ss(r, this._mixerRoot) : null
5585
+ roots: r ? Qs(r, this._mixerRoot) : null
5169
5586
  };
5170
5587
  }
5171
5588
  return this._allPlan;
@@ -5216,7 +5633,7 @@ var cs = class extends cr {
5216
5633
  this._savedTimeScale = e, this.mixer && this.isPlaying && (this.mixer.timeScale = e);
5217
5634
  }
5218
5635
  setLoop(e) {
5219
- let t = e ? pr : fr;
5636
+ let t = e ? _r : gr;
5220
5637
  for (let n of this.actions) n.setLoop(t), n.clampWhenFinished = !e;
5221
5638
  }
5222
5639
  seekTo(e, t = 0) {
@@ -5297,19 +5714,19 @@ var cs = class extends cr {
5297
5714
  dispose() {
5298
5715
  this.mixer &&= (this.mixer.stopAllAction(), this.mixer.uncacheRoot(this._mixerRoot), null), this.actions = [], this.isPlaying = !1, this.timer.reset(), this._scene = null, this._mixerRoot = null, this._meshes = null, this._meshTriRanges = null, this._meshPositions = null, this._skinnedCache = null, this._clipsCache = null, this._rigid = !1, this._plans = null, this._allPlan = null, this._activeClip = 0, this._slotOf = null, this._lastWorld = null, this._lastVisible = null, this._lastMeshWorld = null, this._lastMorphWeights = null;
5299
5716
  }
5300
- }, ls = new $(0, 0, -1), us = (e) => {
5717
+ }, ec = new $(0, 0, -1), tc = (e) => {
5301
5718
  for (; e.parent;) e = e.parent;
5302
5719
  return e.isScene ? e : null;
5303
- }, ds = class {
5720
+ }, nc = class {
5304
5721
  constructor({ camera: e, canvas: t, orbitControls: n, app: r }) {
5305
- this._app = r, this._orbitControls = n, this._camera = e, this._controls = new Rr(e, t), this._gizmoScene = new Or(), this._gizmoScene.add(this._controls.getHelper()), this._attached = null, this._isDragging = !1, this._meshes = null, this._refitInFlight = !1, this._baselineComputed = !1, this._moved = /* @__PURE__ */ new Set(), this._tempForward = new $(), this._lightTargetDistance = null, this._lastLightPosition = null, this._onDraggingChanged = this._onDraggingChanged.bind(this), this._onObjectChange = this._onObjectChange.bind(this), this._controls.addEventListener("dragging-changed", this._onDraggingChanged), this._controls.addEventListener("objectChange", this._onObjectChange);
5722
+ this._app = r, this._orbitControls = n, this._camera = e, this._controls = new Ur(e, t), this._gizmoScene = new Nr(), this._gizmoScene.add(this._controls.getHelper()), this._attached = null, this._isDragging = !1, this._meshes = null, this._refitInFlight = !1, this._baselineComputed = !1, this._moved = /* @__PURE__ */ new Set(), this._tempForward = new $(), this._lightTargetDistance = null, this._lastLightPosition = null, this._onDraggingChanged = this._onDraggingChanged.bind(this), this._onObjectChange = this._onObjectChange.bind(this), this._controls.addEventListener("dragging-changed", this._onDraggingChanged), this._controls.addEventListener("objectChange", this._onObjectChange);
5306
5723
  }
5307
5724
  setMeshData(e) {
5308
5725
  this._meshes = e;
5309
- for (let e of this._moved) us(e) || this._moved.delete(e);
5726
+ for (let e of this._moved) tc(e) || this._moved.delete(e);
5310
5727
  }
5311
5728
  get movedObjects() {
5312
- return [...this._moved].filter((e) => us(e));
5729
+ return [...this._moved].filter((e) => tc(e));
5313
5730
  }
5314
5731
  noteMoved(e) {
5315
5732
  e && !e.isLight && this._moved.add(e);
@@ -5370,7 +5787,7 @@ var cs = class extends cr {
5370
5787
  }
5371
5788
  _syncLightAim(e) {
5372
5789
  let t = this._tempForward.copy(e.target.position).sub(e.position), n = t.length();
5373
- n > 1e-4 ? (e.quaternion.setFromUnitVectors(ls, t.normalize()), this._lightTargetDistance = n) : this._lightTargetDistance = 1;
5790
+ n > 1e-4 ? (e.quaternion.setFromUnitVectors(ec, t.normalize()), this._lightTargetDistance = n) : this._lightTargetDistance = 1;
5374
5791
  }
5375
5792
  _recomputeAndRefit() {
5376
5793
  if (!this._meshes || this._refitInFlight || !this._attached) return;
@@ -5406,7 +5823,7 @@ var cs = class extends cr {
5406
5823
  dispose() {
5407
5824
  this._controls.removeEventListener("dragging-changed", this._onDraggingChanged), this._controls.removeEventListener("objectChange", this._onObjectChange), this.detach(), this._gizmoScene.remove(this._controls.getHelper()), this._controls.dispose(), this._meshes = null, this._moved.clear(), this._baselineComputed = !1, this._tempForward = null, this._lightTargetDistance = null, this._lastLightPosition = null, this._app = null, this._orbitControls = null, this._camera = null, this._controls = null, this._gizmoScene = null;
5408
5825
  }
5409
- }, fs = class {
5826
+ }, rc = class {
5410
5827
  constructor(e) {
5411
5828
  this.layer = "scene", this._transformManager = e, this._enabled = !0;
5412
5829
  }
@@ -5425,8 +5842,8 @@ var cs = class extends cr {
5425
5842
  dispose() {
5426
5843
  this._enabled = !1;
5427
5844
  }
5428
- }, ps = 1, ms = (e) => typeof e == "string" && /^https?:\/\//.test(e);
5429
- function hs(e, t) {
5845
+ }, ic = 1, ac = (e) => typeof e == "string" && /^https?:\/\//.test(e);
5846
+ function oc(e, t) {
5430
5847
  let n = [];
5431
5848
  for (; e && e !== t;) {
5432
5849
  let t = e.parent;
@@ -5435,12 +5852,12 @@ function hs(e, t) {
5435
5852
  }
5436
5853
  return e === t ? n : null;
5437
5854
  }
5438
- function gs(e, t) {
5855
+ function sc(e, t) {
5439
5856
  let n = e;
5440
5857
  for (let e of t) if (n = n?.children[e], !n) return null;
5441
5858
  return n;
5442
5859
  }
5443
- function _s(e) {
5860
+ function cc(e) {
5444
5861
  return {
5445
5862
  key: e.assetLoader?.sceneSourceKey ?? null,
5446
5863
  name: e.sceneModel?.name ?? null,
@@ -5448,7 +5865,7 @@ function _s(e) {
5448
5865
  materials: e.stages.pathTracer?.materialData.materialCount ?? 0
5449
5866
  };
5450
5867
  }
5451
- function vs(e) {
5868
+ function lc(e) {
5452
5869
  let t = /* @__PURE__ */ new Map();
5453
5870
  for (let n of e.sceneMeshes) {
5454
5871
  let e = n.userData?.materialIndex;
@@ -5456,7 +5873,7 @@ function vs(e) {
5456
5873
  }
5457
5874
  return t;
5458
5875
  }
5459
- function ys(e) {
5876
+ function uc(e) {
5460
5877
  if (!e) return null;
5461
5878
  let t = e.status(), n = t.activeView, r = t.config?.id ?? n?.configId ?? null;
5462
5879
  return {
@@ -5471,15 +5888,15 @@ function ys(e) {
5471
5888
  context: t.context ?? null
5472
5889
  };
5473
5890
  }
5474
- function bs(e) {
5475
- let t = e.meshScene, n = vs(e), r = [];
5891
+ function dc(e) {
5892
+ let t = e.meshScene, n = lc(e), r = [];
5476
5893
  return t.traverse((e) => {
5477
- e !== t && e.visible === !1 && r.push(hs(e, t));
5894
+ e !== t && e.visible === !1 && r.push(oc(e, t));
5478
5895
  }), {
5479
5896
  v: 1,
5480
5897
  engine: Be,
5481
5898
  savedAt: Date.now(),
5482
- scene: _s(e),
5899
+ scene: cc(e),
5483
5900
  appended: t.children.filter((t) => t !== e.sceneModel && t.userData?.__rayzeeSceneObject).map((e) => ({
5484
5901
  name: e.userData.__rayzeeName ?? e.name,
5485
5902
  url: e.userData.__rayzeeSourceUrl ?? null,
@@ -5487,7 +5904,7 @@ function bs(e) {
5487
5904
  })),
5488
5905
  settings: e.settings.serialize(),
5489
5906
  environment: e.environmentManager?.serialize() ?? null,
5490
- color: ys(e.color),
5907
+ color: uc(e.color),
5491
5908
  lights: e.lightManager.serialize(),
5492
5909
  cameras: e.cameraManager.serialize(),
5493
5910
  timeline: e.timeline?.serialize() ?? null,
@@ -5497,7 +5914,7 @@ function bs(e) {
5497
5914
  })),
5498
5915
  hidden: r,
5499
5916
  moved: (e.transformManager?.movedObjects ?? []).map((e) => ({
5500
- path: hs(e, t),
5917
+ path: oc(e, t),
5501
5918
  name: e.name,
5502
5919
  position: e.position.toArray(),
5503
5920
  quaternion: e.quaternion.toArray(),
@@ -5505,15 +5922,15 @@ function bs(e) {
5505
5922
  })).filter((e) => e.path)
5506
5923
  };
5507
5924
  }
5508
- function xs(e, t, n) {
5925
+ function fc(e, t, n) {
5509
5926
  let r = e[t];
5510
5927
  r?.copy && (n?.isColor || n?.isVector2 || n?.isVector3) ? r.copy(n) : e[t] = n, e.needsUpdate = !0;
5511
5928
  }
5512
- async function Ss(e, t, n, r) {
5929
+ async function pc(e, t, n, r) {
5513
5930
  if (!t) return;
5514
5931
  let i = e.environmentManager;
5515
5932
  if (t.hdri && t.hdri !== i.hdriSource) {
5516
- let i = ms(t.hdri) ? t.hdri : await n({
5933
+ let i = ac(t.hdri) ? t.hdri : await n({
5517
5934
  kind: "environment",
5518
5935
  source: t.hdri
5519
5936
  });
@@ -5525,7 +5942,7 @@ async function Ss(e, t, n, r) {
5525
5942
  }
5526
5943
  await i.restore(t);
5527
5944
  }
5528
- async function Cs(e, t, n, r) {
5945
+ async function mc(e, t, n, r) {
5529
5946
  let i = e.color;
5530
5947
  if (!t || !i) return;
5531
5948
  let a = i.status(), o = a.activeView, s = !!t.view && !!o && o.display === t.view.display && o.view === t.view.view && (o.look ?? null) === t.view.look, c = a.config?.id ?? null, l = c ?? o?.configId ?? null;
@@ -5550,7 +5967,7 @@ async function Cs(e, t, n, r) {
5550
5967
  r("color", e.message, { config: t.config?.id ?? null });
5551
5968
  }
5552
5969
  }
5553
- async function ws(e, t, { resolve: n = async () => null } = {}) {
5970
+ async function hc(e, t, { resolve: n = async () => null } = {}) {
5554
5971
  if (t?.v !== 1) throw Error(`scene state version ${t?.v} is not 1`);
5555
5972
  let r = [], i = (e, t, n = {}) => r.push({
5556
5973
  section: e,
@@ -5571,11 +5988,11 @@ async function ws(e, t, { resolve: n = async () => null } = {}) {
5571
5988
  i("appended", e.message, { name: n.name });
5572
5989
  }
5573
5990
  }
5574
- let a = _s(e), o = t.scene ?? {}, s = o.meshes === a.meshes && o.materials === a.materials;
5991
+ let a = cc(e), o = t.scene ?? {}, s = o.meshes === a.meshes && o.materials === a.materials;
5575
5992
  s || i("scene", "the loaded scene is not the one saved: objects and materials left as loaded", {
5576
5993
  saved: o,
5577
5994
  now: a
5578
- }), await Ss(e, t.environment, n, i), await Cs(e, t.color, n, i);
5995
+ }), await pc(e, t.environment, n, i), await mc(e, t.color, n, i);
5579
5996
  let c = e.settings.restore(t.settings);
5580
5997
  c.length && i("settings", "not settings in this engine", { keys: c });
5581
5998
  let l = e.lightManager.restore(t.lights);
@@ -5584,7 +6001,7 @@ async function ws(e, t, { resolve: n = async () => null } = {}) {
5584
6001
  n && e.goboManager?.entries?.length && e.goboManager.setLightGobo(t.uuid, n.name, n), r && e.iesManager?.entries?.length && e.iesManager.setSpotLightProfile(t.uuid, r.name, r.intensity, { applyAutoCone: !1 });
5585
6002
  }
5586
6003
  if (s) {
5587
- let n = vs(e);
6004
+ let n = lc(e);
5588
6005
  for (let r of t.materials ?? []) {
5589
6006
  let t = n.get(r.index);
5590
6007
  if (!t || (t.name ?? "") !== r.name) {
@@ -5596,16 +6013,16 @@ async function ws(e, t, { resolve: n = async () => null } = {}) {
5596
6013
  }
5597
6014
  for (let [n, i] of Object.entries(r.props)) {
5598
6015
  let a = me(i);
5599
- xs(t, n, a), e.setMaterialProperty(r.index, n, a);
6016
+ fc(t, n, a), e.setMaterialProperty(r.index, n, a);
5600
6017
  }
5601
6018
  }
5602
- let r = e.meshScene, a = new Set((t.hidden ?? []).map((e) => gs(r, e)).filter(Boolean));
6019
+ let r = e.meshScene, a = new Set((t.hidden ?? []).map((e) => sc(r, e)).filter(Boolean));
5603
6020
  r.traverse((e) => {
5604
6021
  e !== r && !e.isLight && (e.visible = !a.has(e));
5605
6022
  }), e.updateAllMeshVisibility();
5606
6023
  let o = [];
5607
6024
  for (let n of t.moved ?? []) {
5608
- let t = gs(r, n.path);
6025
+ let t = sc(r, n.path);
5609
6026
  if (!t || t.name !== n.name) {
5610
6027
  i("moved", "no such object", { name: n.name });
5611
6028
  continue;
@@ -5627,24 +6044,24 @@ async function ws(e, t, { resolve: n = async () => null } = {}) {
5627
6044
  }
5628
6045
  //#endregion
5629
6046
  //#region src/PathTracerApp.js
5630
- var Ts = Ke("engine"), Es = class extends te {
6047
+ var gc = Ke("engine"), _c = class extends w {
5631
6048
  constructor(e, t = {}) {
5632
- super(e, t), this.setColorManagement(Qt), this.setStorageOpener(ln), this.settings.define("interactionRenderScale", {
6049
+ super(e, t), this.setColorManagement($t), this.setStorageOpener(un), this.settings.define("interactionRenderScale", {
5633
6050
  default: .5,
5634
6051
  apply: () => {
5635
6052
  this.stages?.pathTracer?.interactionMode && this._requestRenderScale(this._interactionRenderScale());
5636
6053
  },
5637
6054
  reset: !1
5638
- }), this._container = t.container || null, this._animRefitInFlight = !1, this._emittersMoved = !1, this._pendingRenderScale = null, this.cameraManager = null, this.timeline = null, this.goboManager = null, this.iesManager = null, this.denoisingManager = null, this.overlayManager = null, this.interactionManager = null, this.transformManager = null, this.animationManager = new cs();
6055
+ }), this._container = t.container || null, this._animRefitInFlight = !1, this._emittersMoved = !1, this._pendingRenderScale = null, this.cameraManager = null, this.timeline = null, this.goboManager = null, this.iesManager = null, this.denoisingManager = null, this.overlayManager = null, this.interactionManager = null, this.transformManager = null, this.animationManager = new $s();
5639
6056
  }
5640
6057
  _createCamera() {
5641
- return this.cameraManager = new ja(this.canvas), this.timeline = new La({
6058
+ return this.cameraManager = new Co(this.canvas), this.timeline = new ko({
5642
6059
  cameraManager: this.cameraManager,
5643
6060
  onReset: () => this.reset()
5644
6061
  }), this.cameraManager.camera;
5645
6062
  }
5646
6063
  _initAssetPipeline() {
5647
- super._initAssetPipeline(), this.assetLoader.controls = this.cameraManager.controls, this.assetLoader.registerFormat(...Dt), this.assetLoader.setArchiveImporterLoader(() => import("./ArchiveImporter-D735xX-4.js").then((e) => e.r).then((e) => new e.ArchiveImporter(this.assetLoader)), wt);
6064
+ super._initAssetPipeline(), this.assetLoader.controls = this.cameraManager.controls, this.assetLoader.registerFormat(...Ot), this.assetLoader.setArchiveImporterLoader(() => import("./ArchiveImporter-Cgyx5AF7.js").then((e) => e.r).then((e) => new e.ArchiveImporter(this.assetLoader)), Tt);
5648
6065
  let e = () => {
5649
6066
  this.needsReset = !0, this.stages.pathTracer?.enterInteractionMode(), this.wake();
5650
6067
  };
@@ -5652,10 +6069,10 @@ var Ts = Ke("engine"), Es = class extends te {
5652
6069
  }
5653
6070
  _createExtraStages() {
5654
6071
  let { renderer: e, stages: t } = this;
5655
- return t.normalDepth = new Xr(e, { pathTracer: t.pathTracer }), t.motionVector = new Zr(e, this.camera, { pathTracer: t.pathTracer }), t.asvgf = new ei(e, { enabled: !1 }), t.nrd = new Ri(e, {
6072
+ return t.normalDepth = new ti(e, { pathTracer: t.pathTracer }), t.motionVector = new ni(e, this.camera, { pathTracer: t.pathTracer }), t.asvgf = new ai(e, { enabled: !1 }), t.nrd = new Ui(e, {
5656
6073
  enabled: !1,
5657
6074
  pathTracer: t.pathTracer
5658
- }), t.variance = new Vi(e, { enabled: !1 }), t.bilateralFilter = new Ui(e, { enabled: !1 }), t.edgeFilter = new Yi(e, { enabled: !1 }), t.autoExposure = new ra(e, { enabled: Xi.autoExposure }), [
6075
+ }), t.variance = new Ki(e, { enabled: !1 }), t.bilateralFilter = new Ji(e, { enabled: !1 }), t.edgeFilter = new ea(e, { enabled: !1 }), t.autoExposure = new Ea(e, { enabled: ta.autoExposure }), t.localExposure = new Ja(e, { enabled: Da.localExposure }), [
5659
6076
  t.normalDepth,
5660
6077
  t.motionVector,
5661
6078
  t.nrd,
@@ -5663,14 +6080,15 @@ var Ts = Ke("engine"), Es = class extends te {
5663
6080
  t.variance,
5664
6081
  t.bilateralFilter,
5665
6082
  t.edgeFilter,
5666
- t.autoExposure
6083
+ t.autoExposure,
6084
+ t.localExposure
5667
6085
  ];
5668
6086
  }
5669
6087
  _initPipeline() {
5670
6088
  super._initPipeline(), this.pipeline.eventBus.on("pathtracer:interactionStart", () => this._requestRenderScale(this._interactionRenderScale())), this.pipeline.eventBus.on("pathtracer:interactionEnd", () => this._applyRenderScale(1));
5671
6089
  }
5672
6090
  async _initManagers() {
5673
- await super._initManagers(), this.environmentManager.setProceduralSkyLoader(() => import("./PhysicalSky-DqmaS0lb.js").then((e) => e.n).then((e) => e.PhysicalSky)), this.stages.pathTracer.registerIntegrator(["bidirectional", "vcm"], (t) => new e(t)), this.stages.pathTracer.requestOutput("gBuffer"), this.interactionManager = new ca({
6091
+ await super._initManagers(), this.environmentManager.setProceduralSkyLoader(() => import("./PhysicalSky-CY4jiz6a.js").then((e) => e.n).then((e) => e.PhysicalSky)), this.stages.pathTracer.registerIntegrator(["bidirectional", "vcm"], (t) => new e(t)), this.stages.pathTracer.requestOutput("gBuffer"), this.interactionManager = new $a({
5674
6092
  scene: this.meshScene,
5675
6093
  camera: this.camera,
5676
6094
  canvas: this.canvas,
@@ -5678,18 +6096,18 @@ var Ts = Ke("engine"), Es = class extends te {
5678
6096
  pathTracer: null,
5679
6097
  floorPlane: this.assetLoader.floorPlane,
5680
6098
  isGeometryOnDisk: () => this.geometryOnDisk
5681
- }), this.interactionManager.wireAppEvents(this), this.cameraManager.setInteractionManager(this.interactionManager), this.goboManager = new Ra(this.stages.pathTracer, {
6099
+ }), this.interactionManager.wireAppEvents(this), this.cameraManager.setInteractionManager(this.interactionManager), this.goboManager = new Ao(this.stages.pathTracer, {
5682
6100
  onReset: () => this.reset(),
5683
6101
  issues: this._issues
5684
- }), this.iesManager = new Xa(this.stages.pathTracer, {
6102
+ }), this.iesManager = new Ho(this.stages.pathTracer, {
5685
6103
  onReset: () => this.reset(),
5686
6104
  issues: this._issues
5687
- }), this._setupDenoisingManager(), this._headless || (await this._setupOverlayManager(), this.transformManager = new ds({
6105
+ }), this._setupDenoisingManager(), this._headless || (await this._setupOverlayManager(), this.transformManager = new nc({
5688
6106
  camera: this.camera,
5689
6107
  canvas: this.canvas,
5690
6108
  orbitControls: this.cameraManager.controls,
5691
6109
  app: this
5692
- }), this.overlayManager.register("transform", new fs(this.transformManager))), this.interactionManager.setDependencies({
6110
+ }), this.overlayManager.register("transform", new rc(this.transformManager))), this.interactionManager.setDependencies({
5693
6111
  overlayManager: this.overlayManager,
5694
6112
  transformManager: this.transformManager,
5695
6113
  appDispatch: (e) => this.dispatchEvent(e),
@@ -5746,7 +6164,7 @@ var Ts = Ke("engine"), Es = class extends te {
5746
6164
  return {
5747
6165
  ...e,
5748
6166
  applyExposure: (t) => {
5749
- this.stages.autoExposure?.enabled || e.applyExposure(t);
6167
+ this.stages.autoExposure ? this.stages.autoExposure.setCompensation(t) : e.applyExposure(t);
5750
6168
  },
5751
6169
  onCameraProjection: (e) => {
5752
6170
  this.cameraManager.applyProjection(e), e === "equirectangular" && this.denoisingManager?.requiresMotionVectors && this.denoisingManager.setDenoiserStrategy("edgeaware");
@@ -5754,9 +6172,9 @@ var Ts = Ke("engine"), Es = class extends te {
5754
6172
  };
5755
6173
  }
5756
6174
  _beginFrame() {
5757
- if (this.timeline.update(), this.cameraManager.updateControls(), this._applyPendingRenderScale(), this.animationManager?.isPlaying && !this._animRefitInFlight) {
6175
+ if (this.timeline.update(), this.cameraManager.updateControls(), this._updateExposure(), this._applyPendingRenderScale(), this.animationManager?.isPlaying && !this._animRefitInFlight) {
5758
6176
  let e = this.animationManager.update();
5759
- e && (this._animRefitInFlight = !0, this.refitBVH(e).catch((e) => Ts.error("animation refit error:", e)).finally(() => {
6177
+ e && (this._animRefitInFlight = !0, this.refitBVH(e).catch((e) => gc.error("animation refit error:", e)).finally(() => {
5760
6178
  this._animRefitInFlight = !1;
5761
6179
  }));
5762
6180
  }
@@ -5771,11 +6189,45 @@ var Ts = Ke("engine"), Es = class extends te {
5771
6189
  this.denoisingManager?.afterTrace(), t && !e.isComplete && this.denoisingManager?.tickContinuousDenoise(e.frameCount);
5772
6190
  }
5773
6191
  _renderCompleted() {
5774
- this.denoisingManager.onRenderComplete({
6192
+ this.stages.autoExposure?.enabled && this._refreshFinished(), this.denoisingManager.onRenderComplete({
5775
6193
  isStillComplete: () => this.completion.renderCompleteDispatched,
5776
6194
  context: this.pipeline?.context
5777
6195
  });
5778
6196
  }
6197
+ _settling() {
6198
+ return !!this.stages.autoExposure?.settling;
6199
+ }
6200
+ _displayGain() {
6201
+ let e = this.stages.localExposure;
6202
+ return e?.wantsBuild && e.build(this.pipeline.context), e?.toneGain() ?? null;
6203
+ }
6204
+ setLocalExposure(e) {
6205
+ let t = this.stages.localExposure;
6206
+ t && (t.setEnabled(e), this.stages.compositor.setDisplayGain(e ? (e, n) => t.gainNode(e, n) : null), this.refreshFrame());
6207
+ }
6208
+ setLocalExposureParams(e) {
6209
+ this.stages.localExposure?.updateParameters(e);
6210
+ }
6211
+ _finishImage() {
6212
+ let e = this.stages.autoExposure;
6213
+ return e?.enabled ? e.meter(this.pipeline.context).then(() => e.advance(Infinity)) : null;
6214
+ }
6215
+ getProvenance() {
6216
+ let e = super.getProvenance(), t = this.stages.autoExposure, n = this.stages.localExposure;
6217
+ return e.exposure = {
6218
+ auto: t?.enabled ? {
6219
+ exposure: t.getExposure(),
6220
+ strength: t.strength,
6221
+ metering: t.metering,
6222
+ keyValue: t.keyValue
6223
+ } : null,
6224
+ local: n?.enabled ? {
6225
+ highlightContrast: n.highlightContrast,
6226
+ shadowContrast: n.shadowContrast,
6227
+ detailStrength: n.detailStrength
6228
+ } : null
6229
+ }, e;
6230
+ }
5779
6231
  _renderHelperOverlay() {
5780
6232
  super._renderHelperOverlay(), this.overlayManager?.render();
5781
6233
  }
@@ -5834,10 +6286,10 @@ var Ts = Ke("engine"), Es = class extends te {
5834
6286
  }
5835
6287
  _setDeterministicExtras(e, t) {
5836
6288
  if (e) {
5837
- this.cameraManager?.setAutoFocusMode("manual"), this.stages.autoExposure && (this.stages.autoExposure.enabled = !1), this.denoisingManager?.setContinuousDenoise(!1);
6289
+ this.cameraManager?.setAutoFocusMode("manual"), this.stages.autoExposure?.setEnabled(!1), this.denoisingManager?.setContinuousDenoise(!1);
5838
6290
  return;
5839
6291
  }
5840
- t.autoFocusMode !== void 0 && this.cameraManager?.setAutoFocusMode(t.autoFocusMode), this.stages.autoExposure && t.autoExposure !== void 0 && (this.stages.autoExposure.enabled = t.autoExposure), t.continuousDenoise !== void 0 && this.denoisingManager?.setContinuousDenoise(t.continuousDenoise);
6292
+ t.autoFocusMode !== void 0 && this.cameraManager?.setAutoFocusMode(t.autoFocusMode), t.autoExposure !== void 0 && this.stages.autoExposure?.setEnabled(t.autoExposure), t.continuousDenoise !== void 0 && this.denoisingManager?.setContinuousDenoise(t.continuousDenoise);
5841
6293
  }
5842
6294
  _disposeExtensions() {
5843
6295
  this.interactionManager?.deselect?.(), this.transformManager?.detach?.(), this.animationManager?.dispose(), this.transformManager?.dispose(), this.overlayManager?.dispose(), this.goboManager?.dispose(), this.iesManager?.dispose(), this.denoisingManager?.dispose(), this.interactionManager?.dispose(), this.timeline?.dispose(), this.cameraManager?.dispose();
@@ -5854,10 +6306,10 @@ var Ts = Ke("engine"), Es = class extends te {
5854
6306
  return t && this._dispatchCamerasUpdated(), t;
5855
6307
  }
5856
6308
  exportSceneState() {
5857
- return bs(this);
6309
+ return dc(this);
5858
6310
  }
5859
6311
  async importSceneState(e, t) {
5860
- return await ws(this, e, t);
6312
+ return await hc(this, e, t);
5861
6313
  }
5862
6314
  _dispatchCamerasUpdated() {
5863
6315
  this.dispatchEvent({
@@ -5916,7 +6368,7 @@ var Ts = Ke("engine"), Es = class extends te {
5916
6368
  }
5917
6369
  configureForMode(e, t = {}) {
5918
6370
  let n = e === "production", r = n ? De : Oe;
5919
- this.denoisingManager?.setCadenceSuspended(n), this.timeline.stop(), this.cameraManager.controls.enabled = !n, this.settings.setMany(je(r), {
6371
+ this.denoisingManager?.setCadenceSuspended(n), this.timeline.stop(), this.cameraManager.controls.enabled = !n, this.stages.autoExposure && (this.stages.autoExposure.holdSamples = n ? 8 : 0), this.settings.setMany(je(r), {
5920
6372
  silent: !0,
5921
6373
  source: x.MODE_PRESET
5922
6374
  }), this.stages.pathTracer?.setUniform("renderMode", parseInt(r.renderMode)), n && this._applyRenderScale(1), this.stages.pathTracer?.updateCompletionThreshold?.();
@@ -5979,7 +6431,7 @@ var Ts = Ke("engine"), Es = class extends te {
5979
6431
  this.transformManager?.setMeshData(this._sdf.meshes);
5980
6432
  }
5981
6433
  _setupDenoisingManager() {
5982
- this.denoisingManager = new Zo({
6434
+ this.denoisingManager = new Hs({
5983
6435
  renderer: this.renderer,
5984
6436
  mainCanvas: this.canvas,
5985
6437
  stages: {
@@ -5997,22 +6449,45 @@ var Ts = Ke("engine"), Es = class extends te {
5997
6449
  pipeline: this.pipeline,
5998
6450
  getExposure: () => this.settings.get("exposure") ?? 1,
5999
6451
  getSaturation: () => this.settings.get("saturation") ?? 1,
6452
+ getDisplayGain: () => this._displayGain(),
6000
6453
  issues: this._issues
6001
6454
  }), this.denoisingManager.setupDenoiser(), this.denoisingManager.setupUpscaler(), this.denoisingManager._syncGBufferStages();
6002
6455
  let e = this.canvas.clientWidth || 1, t = this.canvas.clientHeight || 1;
6003
6456
  this.denoisingManager.setRenderSize(e, t);
6004
6457
  }
6005
6458
  _setupAutoExposureListener() {
6006
- this.stages.autoExposure && this.stages.autoExposure.on("autoexposure:updated", (e) => {
6459
+ let e = this.stages.autoExposure;
6460
+ e && (e.setCompensation(this.settings.get("exposure") ?? 1), this.stages.localExposure && (this.stages.localExposure.onChange = () => this._refreshFinished()), e.onChange = () => this._refreshFinished(), this._addTrackedListener(this.cameraManager, j.CAMERA_SWITCHED, () => e.resetHistory()), e.on("autoexposure:updated", ({ exposure: e, autoExposure: t, targetExposure: n, luminance: r }) => {
6007
6461
  this.dispatchEvent({
6008
6462
  type: j.AUTO_EXPOSURE_UPDATED,
6009
- exposure: e.exposure,
6010
- luminance: e.luminance
6463
+ exposure: e,
6464
+ autoExposure: t,
6465
+ targetExposure: n,
6466
+ luminance: r
6011
6467
  });
6012
- });
6468
+ }));
6469
+ }
6470
+ _refreshFinished() {
6471
+ this.completion.renderCompleteDispatched && (this._needsDisplayRefresh = !0, this.wake());
6472
+ }
6473
+ _updateExposure() {
6474
+ let e = this.stages.localExposure;
6475
+ e?.wantsBuild && this.completion.renderCompleteDispatched && e.build(this.pipeline.context);
6476
+ let t = this.stages.autoExposure;
6477
+ if (!t?.enabled) return;
6478
+ this._noteExposureView();
6479
+ let n = this.cameraManager.afScreenPoint;
6480
+ t.metering === "spot" && (t.meteringPoint.x !== n.x || t.meteringPoint.y !== n.y) && t.updateParameters({ meteringPoint: n }), t.wantsMetering && this.completion.renderCompleteDispatched && t.meter(this.pipeline.context), t.update() && (this._needsDisplayRefresh = !0);
6481
+ }
6482
+ _noteExposureView() {
6483
+ let { matrixWorld: e, projectionMatrix: t } = this.camera, n = this._exposureView;
6484
+ n?.view.equals(e) && n.projection.equals(t) || (this._exposureView = {
6485
+ view: e.clone(),
6486
+ projection: t.clone()
6487
+ }, n && this.stages.autoExposure?.noteViewChanged());
6013
6488
  }
6014
6489
  async _setupOverlayManager() {
6015
- this.overlayManager = new os(this.cameraManager.camera), this.overlayManager.setupDefaultHelpers({
6490
+ this.overlayManager = new Zs(this.cameraManager.camera), this.overlayManager.setupDefaultHelpers({
6016
6491
  helperScene: this._sceneHelpers,
6017
6492
  meshScene: this.meshScene,
6018
6493
  pipeline: this.pipeline,
@@ -6030,7 +6505,7 @@ var Ts = Ke("engine"), Es = class extends te {
6030
6505
  }
6031
6506
  _recalibrateControlLimits() {
6032
6507
  if (!this.meshScene || !this.cameraManager) return;
6033
- let e = new tr(), t = new tr();
6508
+ let e = new ar(), t = new ar();
6034
6509
  for (let n of this.meshScene.children) n.userData?.__rayzeeSceneObject && (t.setFromObject(n), t.isEmpty() || e.union(t));
6035
6510
  if (e.isEmpty()) return;
6036
6511
  let n = Math.max(e.max.x - e.min.x, e.max.y - e.min.y, e.max.z - e.min.z);
@@ -6043,15 +6518,15 @@ var Ts = Ke("engine"), Es = class extends te {
6043
6518
  };
6044
6519
  //#endregion
6045
6520
  //#region src/Headless.js
6046
- async function Ds(e) {
6047
- let t = await ks(e);
6521
+ async function vc(e) {
6522
+ let t = await bc(e);
6048
6523
  try {
6049
- return await Os(t, e);
6524
+ return await yc(t, e);
6050
6525
  } finally {
6051
6526
  t.dispose();
6052
6527
  }
6053
6528
  }
6054
- async function Os(e, { samples: t = 64, colorSpace: n = "srgb", allowEarlyRetire: r = !1, denoise: i = !1, onProgress: a = void 0 } = {}) {
6529
+ async function yc(e, { samples: t = 64, colorSpace: n = "srgb", allowEarlyRetire: r = !1, denoise: i = !1, onProgress: a = void 0 } = {}) {
6055
6530
  let o = e.denoisingManager;
6056
6531
  i && o && !o.finalDenoise && (o.applyOIDNEnabled(!0), o._syncGBufferStages());
6057
6532
  let s = await e.renderFrames(t, {
@@ -6070,8 +6545,8 @@ async function Os(e, { samples: t = 64, colorSpace: n = "srgb", allowEarlyRetire
6070
6545
  provenance: e.getProvenance()
6071
6546
  };
6072
6547
  }
6073
- async function ks({ canvas: e, model: t = null, width: n = 1920, height: r = 1080, strict: i = !0, deterministic: a = !0, settings: o = null, storage: s = !1, hostMemoryGB: c = void 0 } = {}) {
6074
- let l = new Es(e ?? null, {
6548
+ async function bc({ canvas: e, model: t = null, width: n = 1920, height: r = 1080, strict: i = !0, deterministic: a = !0, settings: o = null, storage: s = !1, hostMemoryGB: c = void 0 } = {}) {
6549
+ let l = new _c(e ?? null, {
6075
6550
  autoResize: !1,
6076
6551
  strict: i,
6077
6552
  storage: s,
@@ -6085,7 +6560,7 @@ async function ks({ canvas: e, model: t = null, width: n = 1920, height: r = 108
6085
6560
  }
6086
6561
  //#endregion
6087
6562
  //#region src/managers/VideoRenderManager.js
6088
- var As = class {
6563
+ var xc = class {
6089
6564
  constructor(e) {
6090
6565
  this._app = e, this._cancelled = !1, this._rendering = !1;
6091
6566
  }
@@ -6102,24 +6577,32 @@ var As = class {
6102
6577
  }
6103
6578
  this._cancelled = !1, this._rendering = !0;
6104
6579
  let g = this._saveState({ view: !!o });
6105
- d.stopAnimation(), d.configureForMode("production"), d.settings.setMany({ maxSamples: i }, { silent: !0 }), d.stages.pathTracer?.updateCompletionThreshold?.(), d.cameraManager.controls && (d.cameraManager.controls.enabled = !1);
6580
+ d.stopAnimation(), d.configureForMode("production");
6581
+ let _ = d.stages.autoExposure?.enabled ? d.stages.autoExposure : null;
6582
+ _ && (_.instant = !1), d.settings.setMany({
6583
+ maxSamples: i,
6584
+ renderLimitMode: "frames"
6585
+ }, {
6586
+ silent: !0,
6587
+ reset: !1
6588
+ }), d.stages.pathTracer?.updateCompletionThreshold?.(), d.cameraManager.controls && (d.cameraManager.controls.enabled = !1);
6106
6589
  try {
6107
6590
  for (let e = Math.max(0, s); e < m && !this._cancelled; e++) {
6108
6591
  let n = e * h * r, i = f ? d.animationManager.seekTo(n, t) : null;
6109
- if (o?.seek(e * h) && (d.cameraManager.resetAutoFocus(), d.cameraManager.updateAutoFocus()), i ? await d.refitBVH(i) : d.reset(), d.stopAnimation(), await this._accumulateFrame(d), this._cancelled || (a && d.denoisingManager?.finalDenoise && await this._waitForDenoise(d), this._cancelled)) break;
6110
- let s = d.getCanvas();
6111
- if (s && c) {
6112
- let t = await createImageBitmap(s);
6592
+ if (o?.seek(e * h) && (d.cameraManager.resetAutoFocus(), d.cameraManager.updateAutoFocus()), i ? await d.refitBVH(i) : d.reset(), d.stopAnimation(), _ && d._noteExposureView(), await this._accumulateFrame(d), this._cancelled || (_ && (await _.meter(d.pipeline.context), _.advance(e === Math.max(0, s) ? Infinity : h), d._presentDisplay()), a && d.denoisingManager?.finalDenoise && await this._waitForDenoise(d), this._cancelled)) break;
6593
+ let u = d.getCanvas();
6594
+ if (u && c) {
6595
+ let t = await createImageBitmap(u);
6113
6596
  await c(t, e, m), t.close();
6114
6597
  }
6115
- let u = {
6598
+ let p = {
6116
6599
  frame: e + 1,
6117
6600
  totalFrames: m,
6118
6601
  percent: (e + 1) / m * 100
6119
6602
  };
6120
- l?.(u), d.dispatchEvent({
6603
+ l?.(p), d.dispatchEvent({
6121
6604
  type: j.VIDEO_RENDER_PROGRESS,
6122
- ...u
6605
+ ...p
6123
6606
  });
6124
6607
  }
6125
6608
  } catch (e) {
@@ -6166,7 +6649,7 @@ var As = class {
6166
6649
  });
6167
6650
  }
6168
6651
  _saveState({ view: e }) {
6169
- let t = this._app, n = t.settings.getEffective(), r = Object.keys(je(De));
6652
+ let t = this._app, n = t.settings.getEffective(), r = [...Object.keys(je(De)), "renderLimitMode"];
6170
6653
  return e && r.push("focusDistance"), {
6171
6654
  view: e ? t.cameraManager.captureView() : null,
6172
6655
  settings: r.map((e) => [e, n[e]]),
@@ -6174,6 +6657,8 @@ var As = class {
6174
6657
  controlsEnabled: t.cameraManager.controls?.enabled,
6175
6658
  oidnEnabled: t.denoisingManager?.finalDenoise,
6176
6659
  oidnQuality: t.denoisingManager?.oidnQuality,
6660
+ instantExposure: t.stages.autoExposure?.instant,
6661
+ holdExposureSamples: t.stages.autoExposure?.holdSamples,
6177
6662
  wasPlaying: t.animationManager?.isPlaying,
6178
6663
  pauseRendering: t.pauseRendering
6179
6664
  };
@@ -6185,8 +6670,8 @@ var As = class {
6185
6670
  reset: !1,
6186
6671
  source: r.source
6187
6672
  });
6188
- t.stages.pathTracer && e.renderMode !== void 0 && t.stages.pathTracer?.setUniform("renderMode", parseInt(e.renderMode)), t.stages.pathTracer?.updateCompletionThreshold?.(), t.cameraManager.controls && (t.cameraManager.controls.enabled = e.controlsEnabled ?? !0), t.denoisingManager?.denoiser && (t.denoisingManager.applyOIDNEnabled(e.oidnEnabled ?? !1), e.oidnQuality && t.denoisingManager.applyOIDNQuality(e.oidnQuality)), t.pauseRendering = e.pauseRendering ?? !1, e.view && t.cameraManager.applyPose(e.view), t.denoisingManager?.setCadenceSuspended(!1), t.animationManager?.stop(), t.reset(), t.wake();
6673
+ t.stages.pathTracer && e.renderMode !== void 0 && t.stages.pathTracer?.setUniform("renderMode", parseInt(e.renderMode)), t.stages.pathTracer?.updateCompletionThreshold?.(), t.cameraManager.controls && (t.cameraManager.controls.enabled = e.controlsEnabled ?? !0), t.denoisingManager?.denoiser && (t.denoisingManager.applyOIDNEnabled(e.oidnEnabled ?? !1), e.oidnQuality && t.denoisingManager.applyOIDNQuality(e.oidnQuality)), t.pauseRendering = e.pauseRendering ?? !1, t.stages.autoExposure && (t.stages.autoExposure.instant = e.instantExposure ?? !1, t.stages.autoExposure.holdSamples = e.holdExposureSamples ?? 0), e.view && t.cameraManager.applyPose(e.view), t.denoisingManager?.setCadenceSuspended(!1), t.animationManager?.stop(), t.reset(), t.wake();
6189
6674
  }
6190
6675
  };
6191
6676
  //#endregion
6192
- export { wt as ARCHIVE_FORMATS, Hr as ASVGF_QUALITY_PRESETS, Xi as AUTO_EXPOSURE_DEFAULTS, Ta as AUTO_FOCUS_DEFAULTS, cs as AnimationManager, Ye as BVH_LEAF_MARKERS, ja as CameraManager, Fa as CameraTrack, Qt as ColorManagement, Bt as DEFAULT_LUT_SIZE, Yt as DEFAULT_MAX_EV, Kt as DEFAULT_MIN_EV, _e as DEFAULT_SUN_PATH, gt as DEFAULT_VIEW, it as DEFAULT_WORKING_SPACE, Yr as DENOISER_DEFAULTS, C as DOWNLOAD_POLICY, Zo as DenoisingManager, f as DownloadCache, tt as ENGINE_AREAS, Ee as ENGINE_DEFAULTS, j as EngineEvents, $e as EngineIssueError, Ra as GoboManager, Xa as IESManager, Oe as INTERACTIVE_RENDER_CONFIG, Ze as ISSUE_CODES, Qe as ISSUE_SEVERITY, ca as InteractionManager, Xe as IssueLog, we as LEGACY_EVENT_NAMES, qe as LOG_LEVELS, ee as LightManager, Ge as Logger, ze as MATERIAL_DEFAULTS, Te as MATERIAL_VALUE_SOURCE, Se as MAX_RESERVABLE_RENDER_SIZE, Fe as MAX_SCENE_BYTES, mt as MAX_TABLE_TRANSFORMS, Me as MemoryLedger, Gr as NRD_DEFAULTS, Ur as NRD_HIT_DIST_A, Wr as NRD_HIT_DIST_B, Kr as NRD_PRESET_KEYS, qr as NRD_QUALITY_PRESETS, ut as OCIO_VIEW_BASE, os as OverlayManager, De as PRODUCTION_RENDER_CONFIG, Es as PathTracerApp, u as PipelineContext, gn as RETOUCH_DEFAULTS, _n as RETOUCH_MAX_PIXELS, hn as RETOUCH_RANGES, te as RayzeeRenderer, S as RenderPipeline, d as RenderSettings, E as RenderStage, Ne as SAFE_SCENE_BYTES, ps as SCENE_STATE_VERSION, x as SETTING_SOURCE, xe as SKY_DEFAULTS, pn as SR_MAX_INPUT, mn as SR_SCALE, et as STORAGE_KIND, ge as StageExecutionMode, cn as StorageManager, Je as TRIANGLE_DATA_LAYOUT, La as TimelineManager, ds as TransformManager, Be as VERSION, st as VIEW_TRANSFORMS, fe as VRAMTracker, As as VideoRenderManager, an as acquireLock, Ht as addAllOcioViews, Vt as addOcioView, ft as addViewTransform, nn as applyMatrixRGBA8, en as bakeLut, be as bufferBytes, Ft as buildOcioView, ht as buildToneMapWGSL, v as cachedObjectURL, qt as canvasColorSpaceFor, Os as captureHeadless, y as clearBindingAuditFindings, It as clearInputOverrides, ot as configureAssets, Ue as configurePlatform, Nt as convertColor, kt as convertEncodedRGBA8, tn as convertPixelsF32, Ke as createLogger, A as dayOfYearForMonth, ke as deriveAlphaMode, b as describeAdapter, Ot as displayCanvasFit, Re as estimateSceneBytes, Pt as extractMatrix, Tt as extractSceneMetadata, w as fetchFile, bt as fileIdentity, Xt as findNativeLinearSpace, We as fmt, xt as folderIdentity, me as fromPortable, rt as getActiveColorManagement, at as getAssetConfig, g as getBindingAuditFindings, He as getPlatform, dt as getRegistryVersion, _t as getViewTransform, jt as hasColorSpace, on as heldLockNames, yt as identityKey, Ut as isColorManaged, At as isDataSpace, Jt as isDataTexture, Mt as linearToSrgb, Zt as listFileRules, Rt as listInputOverrides, ct as listViewTransforms, St as localFolder, rn as makeCpuSampler, Lt as measureBakeError, p as nameFromUrl, pt as onRegistryChange, ks as openHeadless, sn as openStorage, dn as openZip, Ct as parseSceneMetadata, Ie as probeAddressSpace, un as readZipDirectory, lt as removeViewTransform, Ds as renderHeadless, fn as renderUpscaled, Gt as resolveInputSpace, vt as sameIdentity, nt as setActiveColorManagement, h as setBindingAudit, $t as setInputOverride, Wt as srgbToLinear, pe as sunPosition, ve as textureBytes, zt as textureInputSpace, ye as timeForSunElevation, de as toPortable };
6677
+ export { Tt as ARCHIVE_FORMATS, qr as ASVGF_QUALITY_PRESETS, ta as AUTO_EXPOSURE_DEFAULTS, _o as AUTO_FOCUS_DEFAULTS, $s as AnimationManager, Ye as BVH_LEAF_MARKERS, Co as CameraManager, Do as CameraTrack, $t as ColorManagement, Vt as DEFAULT_LUT_SIZE, Xt as DEFAULT_MAX_EV, qt as DEFAULT_MIN_EV, _e as DEFAULT_SUN_PATH, _t as DEFAULT_VIEW, at as DEFAULT_WORKING_SPACE, ei as DENOISER_DEFAULTS, C as DOWNLOAD_POLICY, Hs as DenoisingManager, f as DownloadCache, tt as ENGINE_AREAS, Ee as ENGINE_DEFAULTS, j as EngineEvents, $e as EngineIssueError, Ao as GoboManager, Ho as IESManager, Oe as INTERACTIVE_RENDER_CONFIG, Ze as ISSUE_CODES, Qe as ISSUE_SEVERITY, $a as InteractionManager, Xe as IssueLog, we as LEGACY_EVENT_NAMES, Da as LOCAL_EXPOSURE_DEFAULTS, qe as LOG_LEVELS, ee as LightManager, Ge as Logger, ze as MATERIAL_DEFAULTS, Te as MATERIAL_VALUE_SOURCE, Se as MAX_RESERVABLE_RENDER_SIZE, Fe as MAX_SCENE_BYTES, ht as MAX_TABLE_TRANSFORMS, Me as MemoryLedger, Xr as NRD_DEFAULTS, Jr as NRD_HIT_DIST_A, Yr as NRD_HIT_DIST_B, Zr as NRD_PRESET_KEYS, Qr as NRD_QUALITY_PRESETS, dt as OCIO_VIEW_BASE, Zs as OverlayManager, De as PRODUCTION_RENDER_CONFIG, _c as PathTracerApp, u as PipelineContext, _n as RETOUCH_DEFAULTS, vn as RETOUCH_MAX_PIXELS, gn as RETOUCH_RANGES, w as RayzeeRenderer, S as RenderPipeline, d as RenderSettings, O as RenderStage, Ne as SAFE_SCENE_BYTES, ic as SCENE_STATE_VERSION, x as SETTING_SOURCE, xe as SKY_DEFAULTS, mn as SR_MAX_INPUT, hn as SR_SCALE, et as STORAGE_KIND, ge as StageExecutionMode, ln as StorageManager, Je as TRIANGLE_DATA_LAYOUT, ko as TimelineManager, nc as TransformManager, Be as VERSION, ct as VIEW_TRANSFORMS, fe as VRAMTracker, xc as VideoRenderManager, on as acquireLock, Ut as addAllOcioViews, Ht as addOcioView, pt as addViewTransform, rn as applyMatrixRGBA8, tn as bakeLut, be as bufferBytes, It as buildOcioView, gt as buildToneMapWGSL, v as cachedObjectURL, Jt as canvasColorSpaceFor, yc as captureHeadless, y as clearBindingAuditFindings, Lt as clearInputOverrides, st as configureAssets, Ue as configurePlatform, Pt as convertColor, At as convertEncodedRGBA8, nn as convertPixelsF32, Ke as createLogger, de as dayOfYearForMonth, ke as deriveAlphaMode, b as describeAdapter, kt as displayCanvasFit, Re as estimateSceneBytes, Ft as extractMatrix, Et as extractSceneMetadata, T as fetchFile, xt as fileIdentity, Zt as findNativeLinearSpace, We as fmt, St as folderIdentity, me as fromPortable, it as getActiveColorManagement, ot as getAssetConfig, g as getBindingAuditFindings, He as getPlatform, ft as getRegistryVersion, vt as getViewTransform, Mt as hasColorSpace, sn as heldLockNames, bt as identityKey, Wt as isColorManaged, jt as isDataSpace, Yt as isDataTexture, Nt as linearToSrgb, Qt as listFileRules, zt as listInputOverrides, lt as listViewTransforms, Ct as localFolder, an as makeCpuSampler, Rt as measureBakeError, p as nameFromUrl, mt as onRegistryChange, bc as openHeadless, cn as openStorage, fn as openZip, wt as parseSceneMetadata, Ie as probeAddressSpace, dn as readZipDirectory, ut as removeViewTransform, vc as renderHeadless, pn as renderUpscaled, Kt as resolveInputSpace, yt as sameIdentity, rt as setActiveColorManagement, h as setBindingAudit, en as setInputOverride, Gt as srgbToLinear, pe as sunPosition, ve as textureBytes, Bt as textureInputSpace, ye as timeForSunElevation, ue as toPortable };