rayzee 7.15.0 → 7.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,19 +1,53 @@
1
1
  # Rayzee Engine
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/rayzee?label=npm)](https://www.npmjs.com/package/rayzee)
4
- [![minzipped size](https://img.shields.io/badge/minzipped-169.6%20KB-blue)](https://www.npmjs.com/package/rayzee)
4
+ [![minzipped size](https://img.shields.io/badge/minzipped-170.1%20KB-blue)](https://www.npmjs.com/package/rayzee)
5
5
  [![downloads](https://img.shields.io/npm/dw/rayzee?label=downloads)](https://www.npmjs.com/package/rayzee)
6
6
  [![jsDelivr](https://img.shields.io/jsdelivr/npm/hm/rayzee?label=jsDelivr)](https://www.jsdelivr.com/package/npm/rayzee)
7
7
 
8
8
  A real-time WebGPU path tracing engine built on Three.js. Framework-agnostic — use it with React, Vue, vanilla JS, or any other setup.
9
9
 
10
+ 🌐 **[Live Demo](https://atul-mourya.github.io/RayTracing/)** — the same demo app linked from the root monorepo README, built on this engine.
11
+
12
+ ## Table of Contents
13
+
14
+ - [Installation](#installation)
15
+ - [Getting Started](#getting-started)
16
+ - [Vanilla JS with Vite](#vanilla-js-with-vite)
17
+ - [Vanilla JS (no bundler)](#vanilla-js-no-bundler)
18
+ - [React](#react)
19
+ - [Integrating Alongside an Existing Three.js App](#integrating-alongside-an-existing-threejs-app)
20
+ - [Vite tip](#vite-tip)
21
+ - [API Reference](#api-reference)
22
+ - [Configuring Assets (CDN URLs & cache namespace)](#configuring-assets-cdn-urls--cache-namespace)
23
+ - [PathTracerApp](#pathtracerapp)
24
+ - [engine.cameraManager](#enginecameramanager)
25
+ - [engine.lightManager](#enginelightmanager)
26
+ - [engine.animationManager](#engineanimationmanager)
27
+ - [Materials](#materials)
28
+ - [engine.environmentManager](#engineenvironmentmanager)
29
+ - [engine.denoisingManager](#enginedenoisingmanager)
30
+ - [engine.interactionManager](#engineinteractionmanager)
31
+ - [engine.transformManager](#enginetransformmanager)
32
+ - [Output Methods](#output-methods)
33
+ - [Memory Monitoring](#memory-monitoring)
34
+ - [Events](#events)
35
+ - [Advanced: Custom Pipeline Stages](#advanced-custom-pipeline-stages)
36
+ - [All Exports](#all-exports)
37
+ - [Browser Requirements](#browser-requirements)
38
+ - [Optional Dependencies](#optional-dependencies)
39
+ - [Enabling OIDN (Intel Open Image Denoise)](#enabling-oidn-intel-open-image-denoise)
40
+ - [Enabling the AI Upscaler](#enabling-the-ai-upscaler)
41
+ - [Troubleshooting](#troubleshooting)
42
+ - [License](#license)
43
+
10
44
  ## Installation
11
45
 
12
46
  ```bash
13
47
  npm install rayzee three
14
48
  ```
15
49
 
16
- `three` (>=0.183.0) is a required peer dependency.
50
+ `three` (>=0.185.0) is a required peer dependency.
17
51
 
18
52
  ## Getting Started
19
53
 
@@ -65,7 +99,7 @@ npm install rayzee three
65
99
  });
66
100
 
67
101
  // Tweak settings
68
- engine.settings.set('bounces', 8);
102
+ engine.settings.set('maxBounces', 8);
69
103
  engine.settings.set('exposure', 1.2);
70
104
 
71
105
  // Use namespaced APIs and direct methods
@@ -95,10 +129,10 @@ A single HTML file — no Node.js, no build step. Uses [ES module import maps](h
95
129
  <script type="importmap">
96
130
  {
97
131
  "imports": {
98
- "three": "https://cdn.jsdelivr.net/npm/three@0.183.0/build/three.webgpu.js",
99
- "three/tsl": "https://cdn.jsdelivr.net/npm/three@0.183.0/build/three.tsl.js",
100
- "three/webgpu": "https://cdn.jsdelivr.net/npm/three@0.183.0/build/three.webgpu.js",
101
- "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.183.0/examples/jsm/",
132
+ "three": "https://cdn.jsdelivr.net/npm/three@0.185.0/build/three.webgpu.js",
133
+ "three/tsl": "https://cdn.jsdelivr.net/npm/three@0.185.0/build/three.tsl.js",
134
+ "three/webgpu": "https://cdn.jsdelivr.net/npm/three@0.185.0/build/three.webgpu.js",
135
+ "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.185.0/examples/jsm/",
102
136
  "oidn-web": "https://cdn.jsdelivr.net/npm/oidn-web@0.3.5/dist/oidn.js",
103
137
  "rayzee": "https://cdn.jsdelivr.net/npm/rayzee/dist/rayzee.es.js"
104
138
  }
@@ -291,21 +325,33 @@ Constructing a new `PathTracerApp` on a canvas that already has an active instan
291
325
  #### Loading Assets
292
326
 
293
327
  ```js
294
- await engine.loadModel(url) // Load GLB/GLTF/FBX/OBJ/STL/PLY/DAE/3MF/USDZ/ZIP
295
- await engine.loadObject3D(object3d) // Load a Three.js Object3D directly
296
- await engine.loadEnvironment(url) // Load HDR/EXR environment map
328
+ await engine.loadModel(url) // Load GLB/GLTF/FBX/OBJ/STL/PLY/DAE/3MF/USDZ/ZIP
329
+ await engine.loadObject3D(object3d, name?) // Load a Three.js Object3D directly (name is optional, defaults to 'object3d')
330
+ await engine.loadEnvironment(url) // Load HDR/EXR environment map
331
+ engine.cancelLoad() // Abort an in-flight download (network phase only; no-op once processing starts)
332
+ ```
333
+
334
+ `loadModel` / `loadObject3D` **replace** the current scene. To add or remove objects from a live scene without a full reload (and without reframing the camera):
335
+
336
+ ```js
337
+ const id = await engine.addModel(url, { name }) // Append a model, rebuild in place
338
+ const id = await engine.addModelFromObject3D(object3d, { name }) // Append a caller-owned Object3D (caller retains ownership)
339
+ await engine.removeSceneObject(id) // Remove by id — returns false if not found
340
+ engine.setSceneObjectVisibility(id, visible) // Toggle visibility with an O(1) BVH-leaf patch, no rebuild
297
341
  ```
298
342
 
343
+ `id` is the appended root's `Object3D.uuid`, returned by `addModel`/`addModelFromObject3D`. The built-in ground plane is permanent and can't be removed.
344
+
299
345
  #### Settings
300
346
 
301
347
  ```js
302
- engine.settings.set('bounces', 8) // Set a single parameter
348
+ engine.settings.set('maxBounces', 8) // Set a single parameter
303
349
  engine.settings.setMany({ // Set multiple parameters at once
304
- bounces: 8,
350
+ maxBounces: 8,
305
351
  maxSamples: 60,
306
352
  exposure: 1.0
307
353
  })
308
- engine.settings.get('bounces') // Read a parameter
354
+ engine.settings.get('maxBounces') // Read a parameter
309
355
  engine.settings.getAll() // Get all current settings
310
356
  ```
311
357
 
@@ -313,30 +359,43 @@ Key settings:
313
359
 
314
360
  | Setting | Type | Default | Description |
315
361
  |---|---|---|---|
316
- | `bounces` | `number` | 3 | Max ray bounce depth |
362
+ | `maxBounces` | `number` | 3 | Max ray bounce depth |
317
363
  | `maxSamples` | `number` | 60 | Max accumulated samples before stopping |
318
364
  | `exposure` | `number` | 1.0 | Exposure value |
319
365
  | `saturation` | `number` | 1.2 | Color saturation |
320
366
  | `enableEnvironment` | `boolean` | true | Use environment lighting |
321
367
  | `environmentIntensity` | `number` | 1.0 | Environment light strength |
322
368
  | `environmentRotation` | `number` | 270 | Environment Y-rotation (degrees) |
369
+ | `showBackground` | `boolean` | true | Show the environment as a visible backdrop for camera-miss rays (vs. a solid/transparent background) |
370
+ | `samplingTechnique` | `number` | 3 | Light-sampling / MIS technique selector |
323
371
  | `fireflyThreshold` | `number` | 3.0 | Firefly clamping threshold |
324
372
  | `transmissiveBounces` | `number` | 5 | Max bounces for transmissive materials |
373
+ | `maxSubsurfaceSteps` | `number` | 8 | Max random-walk steps for subsurface scattering (raised to 64 by `configureForMode('production')`) |
374
+ | `enableAlphaShadows` | `boolean` | false | Alpha-tested shadow rays (enabled by `configureForMode('production')`) |
325
375
  | `enableDOF` | `boolean` | false | Enable depth of field |
326
376
  | `focusDistance` | `number` | 0.8 | DOF focus distance |
327
377
  | `aperture` | `number` | 5.6 | DOF aperture (f-stop) |
328
378
  | `focalLength` | `number` | 50 | DOF focal length (mm) |
329
379
  | `transparentBackground` | `boolean` | false | Transparent canvas background |
330
380
  | `interactionModeEnabled` | `boolean` | true | Lower quality during camera movement for smoother navigation |
331
- | `debugMode` | `number` | 0 | Debug visualization mode (0 = off) |
332
- | `environmentMode` | `string` | 'hdri' | Sky mode: `'hdri'` \| `'procedural'` \| `'gradient'` \| `'color'` |
381
+ | `renderMode` | `number` | 0 | Internal preview(0)/production(1) flag driving accumulation & ASVGF behavior — normally set via `configureForMode()`, not written directly |
382
+ | `visMode` | `number` | 0 | Debug visualization mode (0 = off) |
383
+ | `environmentMode` | `string` | 'hdri' | Sky mode: `'hdri'` \| `'procedural'` \| `'gradient'` \| `'color'` — not routed through `engine.settings`; use `engine.environmentManager.setMode()` instead |
384
+ | `useAdaptiveSampling` | `boolean` | true | Whole-frame early-stop once convergence reaches `adaptiveStopFraction` |
385
+ | `noiseThreshold` | `number` | 0.02 | Relative-error threshold below which a pixel is considered converged |
386
+ | `darkNoiseFloor` | `number` | 0.003 | Absolute-error floor so dim pixels don't stall convergence |
387
+ | `adaptiveMinSamples` | `number` | 8 | Minimum samples before adaptive sampling can trigger |
388
+ | `adaptiveStopFraction` | `number` | 0.95 | Fraction of pixels that must converge before the frame retires |
389
+ | `usePixelFreeze` | `boolean` | false | Per-pixel freeze (Tier-2): skip individually-converged pixels via active-list compaction |
390
+ | `pixelFreezeThreshold` | `number` | 0.02 | Relative-error threshold for a pixel to become a freeze candidate |
391
+ | `pixelFreezeStability` | `number` | 8 | Consecutive candidate frames required before a pixel freezes |
333
392
 
334
393
  See `ENGINE_DEFAULTS` for the full list with default values.
335
394
 
336
395
  #### Rendering Modes
337
396
 
338
397
  ```js
339
- engine.configureForMode('production') // High quality (tiled, 20 bounces, OIDN, controls disabled)
398
+ engine.configureForMode('production') // High quality (full-frame, 20 bounces, OIDN, controls disabled)
340
399
  engine.configureForMode('interactive') // Real-time navigation (3 bounces, controls enabled)
341
400
  ```
342
401
 
@@ -396,6 +455,11 @@ engine.reset() // Re-upload all material data to GPU
396
455
  engine.stages.pathTracer.materialData.updateMaterial(index, mat) // Replace a material
397
456
  await engine.rebuildMaterials(scene) // Full rebuild (after texture changes)
398
457
 
458
+ // Cap the longest edge of processed material textures (clamped to the hardware max).
459
+ // Larger = sharper textures, ~quadratic VRAM. Reprocesses the current scene by default.
460
+ await engine.setMaxTextureSize(2048)
461
+ await engine.setMaxTextureSize(4096, { reprocess: false })
462
+
399
463
  // Per-mesh visibility — recommended UUID-based API (handles lookup + sync internally)
400
464
  engine.setMeshVisibilityByUuid(uuid, true) // explicit set
401
465
  engine.setMeshVisibilityByUuid(uuid, prev => !prev) // toggle via updater fn
@@ -550,6 +614,7 @@ engine.addEventListener(EngineEvents.RENDER_COMPLETE, (e) => {
550
614
  | `AF_POINT_PLACED` | Focus point placed on screen |
551
615
  | `ANIMATION_STARTED` / `ANIMATION_PAUSED` / `ANIMATION_STOPPED` / `ANIMATION_FINISHED` | Animation lifecycle |
552
616
  | `VIDEO_RENDER_PROGRESS` / `VIDEO_RENDER_COMPLETE` | Video export progress |
617
+ | `DEVICE_LOST` | The GPU device was lost (driver crash/reset) — rendering halts instead of throwing into a dead device |
553
618
  | `DISPOSE` | Engine is being disposed (fires before teardown begins, so listeners can release their own references) |
554
619
 
555
620
  ### Advanced: Custom Pipeline Stages
@@ -604,6 +669,8 @@ import {
604
669
  RenderSettings,
605
670
  CameraManager,
606
671
  LightManager,
672
+ GoboManager,
673
+ IESManager,
607
674
  DenoisingManager,
608
675
  OverlayManager,
609
676
  AnimationManager,
@@ -632,6 +699,8 @@ import { VRAMTracker, bufferBytes, textureBytes } from 'rayzee';
632
699
  | `oidn-web` | Intel Open Image Denoise for high-quality final renders | Yes — `npm install oidn-web` |
633
700
  | `onnxruntime-web` | AI-powered upscaling | No — loaded from CDN at runtime |
634
701
 
702
+ > **Note:** `onnxruntime-web` is also listed in `package.json` under `optionalDependencies` for bundler compatibility, but the engine's own runtime path always fetches it from a CDN (see `ortRuntimeUrl` / `ortWasmPaths` in [Configuring Assets](#configuring-assets-cdn-urls--cache-namespace)) rather than importing the installed package — installing it locally has no effect unless you also override those URLs to point at your own copy.
703
+
635
704
  ### Enabling OIDN (Intel Open Image Denoise)
636
705
 
637
706
  OIDN provides high-quality AI denoising for final renders. It runs automatically after the render converges (reaches `maxSamples`).
package/dist/rayzee.es.js CHANGED
@@ -6026,48 +6026,49 @@ function qs(e, t) {
6026
6026
  //#region src/Processor/EmissiveTriangleBuilder.js
6027
6027
  var Js = class {
6028
6028
  constructor() {
6029
- this.emissiveTriangles = [], this.emissiveCount = 0, this.totalEmissivePower = 0, this.emissiveIndicesArray = null, this.emissivePowerArray = null, this.cdfArray = null, this.lightBVHNodeData = null, this.lightBVHNodeCount = 0, this.emissiveBitTrailMap = null, this._totalTriangleCount = 0;
6029
+ this.emissiveTriangles = [], this.emissiveCount = 0, this.totalEmissivePower = 0, this.emissiveIndicesArray = null, this.emissivePowerArray = null, this.cdfArray = null, this.lightBVHNodeData = null, this.lightBVHNodeCount = 0, this.emissiveBitTrailMap = null, this._totalTriangleCount = 0, this._hiddenMeshes = /* @__PURE__ */ new Set();
6030
6030
  }
6031
6031
  extractEmissiveTriangles(e, t, n) {
6032
6032
  console.log("[EmissiveTriangleBuilder] Extracting emissive triangles..."), this.emissiveTriangles = [], this.totalEmissivePower = 0, this._totalTriangleCount = n;
6033
- let r = Z.FLOATS_PER_TRIANGLE, i = Z.UV_C_MAT_OFFSET + 2;
6034
- for (let a = 0; a < n; a++) {
6035
- let n = a * r, o = Math.floor(e[n + i]), s = t[o];
6036
- if (!s) continue;
6037
- let c = s.emissive || {
6033
+ let r = Z.FLOATS_PER_TRIANGLE, i = Z.UV_C_MAT_OFFSET + 2, a = Z.UV_C_MAT_OFFSET + 3;
6034
+ for (let o = 0; o < n; o++) {
6035
+ let n = o * r, s = Math.floor(e[n + i]), c = Math.floor(e[n + a]), l = t[s];
6036
+ if (!l) continue;
6037
+ let u = l.emissive || {
6038
6038
  r: 0,
6039
6039
  g: 0,
6040
6040
  b: 0
6041
- }, l = s.emissiveIntensity || 0;
6042
- if (l > 0 && (c.r > 0 || c.g > 0 || c.b > 0)) {
6043
- let t = e[n + 0], r = e[n + 1], i = e[n + 2], u = e[n + 4], d = e[n + 5], f = e[n + 6], p = e[n + 8], m = e[n + 9], h = e[n + 10], g = this._calculateTriangleArea(t, r, i, u, d, f, p, m, h), _ = (.2126 * c.r + .7152 * c.g + .0722 * c.b) * l * g, v = (d - r) * (h - i) - (f - i) * (m - r), y = (f - i) * (p - t) - (u - t) * (h - i), b = (u - t) * (m - r) - (d - r) * (p - t), x = Math.sqrt(v * v + y * y + b * b) || 1, S = s.side === 1 ? -1 : 1;
6044
- v = v / x * S, y = y / x * S, b = b / x * S;
6045
- let C = s.side === 2, w = (t + u + p) / 3, T = (r + d + m) / 3, E = (i + f + h) / 3, D = Math.min(t, u, p), O = Math.min(r, d, m), k = Math.min(i, f, h), A = Math.max(t, u, p), j = Math.max(r, d, m), M = Math.max(i, f, h);
6041
+ }, d = l.emissiveIntensity || 0;
6042
+ if (d > 0 && (u.r > 0 || u.g > 0 || u.b > 0)) {
6043
+ let t = e[n + 0], r = e[n + 1], i = e[n + 2], a = e[n + 4], f = e[n + 5], p = e[n + 6], m = e[n + 8], h = e[n + 9], g = e[n + 10], _ = this._calculateTriangleArea(t, r, i, a, f, p, m, h, g), v = (.2126 * u.r + .7152 * u.g + .0722 * u.b) * d * _, y = (f - r) * (g - i) - (p - i) * (h - r), b = (p - i) * (m - t) - (a - t) * (g - i), x = (a - t) * (h - r) - (f - r) * (m - t), S = Math.sqrt(y * y + b * b + x * x) || 1, C = l.side === 1 ? -1 : 1;
6044
+ y = y / S * C, b = b / S * C, x = x / S * C;
6045
+ let w = l.side === 2, T = (t + a + m) / 3, E = (r + f + h) / 3, D = (i + p + g) / 3, O = Math.min(t, a, m), k = Math.min(r, f, h), A = Math.min(i, p, g), j = Math.max(t, a, m), M = Math.max(r, f, h), ee = Math.max(i, p, g);
6046
6046
  this.emissiveTriangles.push({
6047
- triangleIndex: a,
6048
- materialIndex: o,
6049
- power: _,
6050
- area: g,
6047
+ triangleIndex: o,
6048
+ materialIndex: s,
6049
+ meshIndex: c,
6050
+ power: v,
6051
+ area: _,
6051
6052
  emissive: {
6052
- r: c.r,
6053
- g: c.g,
6054
- b: c.b
6053
+ r: u.r,
6054
+ g: u.g,
6055
+ b: u.b
6055
6056
  },
6056
- emissiveIntensity: l,
6057
- cx: w,
6058
- cy: T,
6059
- cz: E,
6060
- bMinX: D,
6061
- bMinY: O,
6062
- bMinZ: k,
6063
- bMaxX: A,
6064
- bMaxY: j,
6065
- bMaxZ: M,
6066
- nx: v,
6067
- ny: y,
6068
- nz: b,
6069
- twoSided: C
6070
- }), this.totalEmissivePower += _;
6057
+ emissiveIntensity: d,
6058
+ cx: T,
6059
+ cy: E,
6060
+ cz: D,
6061
+ bMinX: O,
6062
+ bMinY: k,
6063
+ bMinZ: A,
6064
+ bMaxX: j,
6065
+ bMaxY: M,
6066
+ bMaxZ: ee,
6067
+ nx: y,
6068
+ ny: b,
6069
+ nz: x,
6070
+ twoSided: w
6071
+ }), this.totalEmissivePower += v;
6071
6072
  }
6072
6073
  }
6073
6074
  return this.emissiveCount = this.emissiveTriangles.length, console.log(`[EmissiveTriangleBuilder] Found ${this.emissiveCount} emissive triangles (${(this.emissiveCount / n * 100).toFixed(2)}%)`), console.log(`[EmissiveTriangleBuilder] Total emissive power: ${this.totalEmissivePower.toFixed(2)}`), this._buildDataArrays(), this.emissiveCount;
@@ -6161,44 +6162,57 @@ var Js = class {
6161
6162
  if (s !== this.emissiveTriangles.some((t) => t.materialIndex === e)) return this.extractEmissiveTriangles(n, r, i), !0;
6162
6163
  if (!s) return !1;
6163
6164
  let c = .2126 * a.r + .7152 * a.g + .0722 * a.b;
6164
- this.totalEmissivePower = 0;
6165
- for (let t = 0; t < this.emissiveCount; t++) {
6166
- let n = this.emissiveTriangles[t];
6167
- n.materialIndex === e && (n.power = c * o * n.area, n.emissive = {
6168
- r: a.r,
6169
- g: a.g,
6170
- b: a.b
6171
- }, n.emissiveIntensity = o, this.emissivePowerArray[t] = n.power), this.totalEmissivePower += this.emissiveTriangles[t].power;
6165
+ for (let t of this.emissiveTriangles) t.materialIndex === e && (t.power = c * o * t.area, t.emissive = {
6166
+ r: a.r,
6167
+ g: a.g,
6168
+ b: a.b
6169
+ }, t.emissiveIntensity = o);
6170
+ return !0;
6171
+ }
6172
+ setHiddenMeshes(e) {
6173
+ let t = /* @__PURE__ */ new Set();
6174
+ for (let e of this.emissiveTriangles) t.add(e.meshIndex);
6175
+ let n = /* @__PURE__ */ new Set();
6176
+ for (let r of e) t.has(r) && n.add(r);
6177
+ let r = this._hiddenMeshes, i = n.size !== r.size;
6178
+ if (!i) {
6179
+ for (let e of n) if (!r.has(e)) {
6180
+ i = !0;
6181
+ break;
6182
+ }
6172
6183
  }
6173
- return this._buildCDF(), !0;
6184
+ return this._hiddenMeshes = n, i;
6174
6185
  }
6175
6186
  buildLightBVH() {
6176
- if (this.emissiveCount === 0) return this.lightBVHNodeData = new Float32Array(16), this.lightBVHNodeData[7] = 1, this.lightBVHNodeData[14] = 1, this.lightBVHNodeData[15] = -1, this.lightBVHNodeCount = 1, this.emissiveBitTrailMap = new Float32Array(Math.max(this._totalTriangleCount, 1)).fill(-1), 1;
6177
- let { nodeData: e, nodeCount: t, sortedPerm: n, bitTrails: r } = new Gs().build(this.emissiveTriangles);
6178
- this.lightBVHNodeData = e, this.lightBVHNodeCount = t, this._rebuildSortedEmissiveData(n), this.emissiveBitTrailMap = new Float32Array(Math.max(this._totalTriangleCount, 1)).fill(-1);
6179
- for (let e = 0; e < n.length; e++) {
6180
- let t = this.emissiveTriangles[n[e]].triangleIndex;
6181
- this.emissiveBitTrailMap[t] = r[e];
6187
+ let e = this._hiddenMeshes.size === 0 ? this.emissiveTriangles : this.emissiveTriangles.filter((e) => !this._hiddenMeshes.has(e.meshIndex));
6188
+ this.emissiveCount = e.length, this.totalEmissivePower = 0;
6189
+ for (let t of e) this.totalEmissivePower += t.power;
6190
+ if (e.length === 0) return this.lightBVHNodeData = new Float32Array(16), this.lightBVHNodeData[7] = 1, this.lightBVHNodeData[14] = 1, this.lightBVHNodeData[15] = -1, this.lightBVHNodeCount = 1, this.emissiveBitTrailMap = new Float32Array(Math.max(this._totalTriangleCount, 1)).fill(-1), this.emissiveIndicesArray = new Int32Array(), this.emissivePowerArray = new Float32Array(), this._buildCDF(), this.emissiveTriangleData = new Float32Array(8), 1;
6191
+ let { nodeData: t, nodeCount: n, sortedPerm: r, bitTrails: i } = new Gs().build(e);
6192
+ this.lightBVHNodeData = t, this.lightBVHNodeCount = n, this._rebuildSortedEmissiveData(r, e), this.emissiveBitTrailMap = new Float32Array(Math.max(this._totalTriangleCount, 1)).fill(-1);
6193
+ for (let t = 0; t < r.length; t++) {
6194
+ let n = e[r[t]].triangleIndex;
6195
+ this.emissiveBitTrailMap[n] = i[t];
6182
6196
  }
6183
- return t;
6197
+ return n;
6184
6198
  }
6185
- _rebuildSortedEmissiveData(e) {
6186
- let t = e.length;
6187
- this.emissiveIndicesArray = new Int32Array(t), this.emissivePowerArray = new Float32Array(t);
6188
- for (let n = 0; n < t; n++) {
6189
- let t = e[n];
6190
- this.emissiveIndicesArray[n] = this.emissiveTriangles[t].triangleIndex, this.emissivePowerArray[n] = this.emissiveTriangles[t].power;
6199
+ _rebuildSortedEmissiveData(e, t) {
6200
+ let n = e.length;
6201
+ this.emissiveIndicesArray = new Int32Array(n), this.emissivePowerArray = new Float32Array(n);
6202
+ for (let r = 0; r < n; r++) {
6203
+ let n = e[r];
6204
+ this.emissiveIndicesArray[r] = t[n].triangleIndex, this.emissivePowerArray[r] = t[n].power;
6191
6205
  }
6192
6206
  this._buildCDF();
6193
- let n = new Float32Array(t * 8);
6194
- for (let r = 0; r < t; r++) {
6195
- let t = e[r], i = this.emissiveTriangles[t], a = r * 8;
6196
- n[a + 0] = i.triangleIndex, n[a + 1] = i.power, n[a + 2] = this.cdfArray[r], n[a + 3] = this.totalEmissivePower > 0 ? i.power / this.totalEmissivePower : 0, n[a + 4] = i.emissive.r * i.emissiveIntensity, n[a + 5] = i.emissive.g * i.emissiveIntensity, n[a + 6] = i.emissive.b * i.emissiveIntensity, n[a + 7] = i.area;
6207
+ let r = new Float32Array(n * 8);
6208
+ for (let i = 0; i < n; i++) {
6209
+ let n = t[e[i]], a = i * 8;
6210
+ r[a + 0] = n.triangleIndex, r[a + 1] = n.power, r[a + 2] = this.cdfArray[i], r[a + 3] = this.totalEmissivePower > 0 ? n.power / this.totalEmissivePower : 0, r[a + 4] = n.emissive.r * n.emissiveIntensity, r[a + 5] = n.emissive.g * n.emissiveIntensity, r[a + 6] = n.emissive.b * n.emissiveIntensity, r[a + 7] = n.area;
6197
6211
  }
6198
- this.emissiveTriangleData = n, console.log(`[EmissiveTriangleBuilder] Rebuilt sorted emissive data: ${t} entries`);
6212
+ this.emissiveTriangleData = r, console.log(`[EmissiveTriangleBuilder] Rebuilt sorted emissive data: ${n} entries`);
6199
6213
  }
6200
6214
  clear() {
6201
- this.emissiveTriangles = [], this.emissiveCount = 0, this.totalEmissivePower = 0, this.emissiveIndicesArray = null, this.emissivePowerArray = null, this.cdfArray = null, this.lightBVHNodeData = null, this.lightBVHNodeCount = 0, this.emissiveBitTrailMap = null, this._totalTriangleCount = 0;
6215
+ this.emissiveTriangles = [], this.emissiveCount = 0, this.totalEmissivePower = 0, this.emissiveIndicesArray = null, this.emissivePowerArray = null, this.cdfArray = null, this.lightBVHNodeData = null, this.lightBVHNodeCount = 0, this.emissiveBitTrailMap = null, this._totalTriangleCount = 0, this._hiddenMeshes = /* @__PURE__ */ new Set();
6202
6216
  }
6203
6217
  }, Ys = class {
6204
6218
  constructor(e = "Build") {
@@ -6558,7 +6572,7 @@ var Js = class {
6558
6572
  for (let n of this.materials) n.map = t(n.map, e.albedo), n.emissiveMap = t(n.emissiveMap, e.emissive), n.normalMap = t(n.normalMap, e.normal), n.bumpMap = t(n.bumpMap, e.bump), n.roughnessMap = t(n.roughnessMap, e.roughness), n.metalnessMap = t(n.metalnessMap, e.metalness), n.displacementMap = t(n.displacementMap, e.displacement), n.anisotropyMap = t(n.anisotropyMap, e.anisotropy), n.transmissionMap = t(n.transmissionMap, e.transmission), n.clearcoatMap = t(n.clearcoatMap, e.clearcoat), n.clearcoatRoughnessMap = t(n.clearcoatRoughnessMap, e.clearcoatRoughness), n.sheenColorMap = t(n.sheenColorMap, e.sheenColor), n.sheenRoughnessMap = t(n.sheenRoughnessMap, e.sheenRoughness), n.iridescenceMap = t(n.iridescenceMap, e.iridescence), n.iridescenceThicknessMap = t(n.iridescenceThicknessMap, e.iridescenceThickness), n.specularIntensityMap = t(n.specularIntensityMap, e.specularIntensity), n.specularColorMap = t(n.specularColorMap, e.specularColor);
6559
6573
  }
6560
6574
  _buildEmissiveData() {
6561
- this.emissiveTriangleCount = this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangleData, this.materials, this.triangleCount), this.emissiveTriangleData = this.emissiveTriangleBuilder.createEmissiveRawData(), this.emissiveTotalPower = this.emissiveTriangleBuilder.totalEmissivePower, this._log("Emissive triangle extraction complete", this.emissiveTriangleBuilder.getStats()), this.emissiveTriangleBuilder.buildLightBVH(), this.lightBVHNodeData = this.emissiveTriangleBuilder.lightBVHNodeData, this.lightBVHNodeCount = this.emissiveTriangleBuilder.lightBVHNodeCount, this.emissiveTriangleData = this.emissiveTriangleBuilder.emissiveTriangleData || this.emissiveTriangleData, this.emissiveBitTrailMap = this.emissiveTriangleBuilder.emissiveBitTrailMap;
6575
+ this.emissiveTriangleCount = this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangleData, this.materials, this.triangleCount), this.emissiveTriangleData = this.emissiveTriangleBuilder.createEmissiveRawData(), this.emissiveTotalPower = this.emissiveTriangleBuilder.totalEmissivePower, this._log("Emissive triangle extraction complete", this.emissiveTriangleBuilder.getStats()), this.emissiveTriangleBuilder.buildLightBVH(), this.lightBVHNodeData = this.emissiveTriangleBuilder.lightBVHNodeData, this.lightBVHNodeCount = this.emissiveTriangleBuilder.lightBVHNodeCount, this.emissiveTriangleData = this.emissiveTriangleBuilder.emissiveTriangleData || this.emissiveTriangleData, this.emissiveBitTrailMap = this.emissiveTriangleBuilder.emissiveBitTrailMap, this.emissiveTriangleCount = this.emissiveTriangleBuilder.emissiveCount, this.emissiveTotalPower = this.emissiveTriangleBuilder.totalEmissivePower;
6562
6576
  }
6563
6577
  _createSpheres() {
6564
6578
  return [];
@@ -6713,14 +6727,20 @@ var Js = class {
6713
6727
  updateMaterialEmissive(e, t, n) {
6714
6728
  if (!this.emissiveTriangleBuilder) return null;
6715
6729
  let r = this.materials[e];
6716
- return !r || (t === "emissive" ? r.emissive = n : t === "emissiveIntensity" && (r.emissiveIntensity = n), !this.emissiveTriangleBuilder.updateMaterialEmissive(e, r, this.triangleData, this.materials, this.triangleCount)) ? null : (this.emissiveTriangleBuilder.buildLightBVH(), this.lightBVHNodeData = this.emissiveTriangleBuilder.lightBVHNodeData, this.lightBVHNodeCount = this.emissiveTriangleBuilder.lightBVHNodeCount, this.emissiveTriangleData = this.emissiveTriangleBuilder.emissiveTriangleData, this.emissiveBitTrailMap = this.emissiveTriangleBuilder.emissiveBitTrailMap, this.emissiveTriangleCount = this.emissiveTriangleBuilder.emissiveCount, this.emissiveTotalPower = this.emissiveTriangleBuilder.totalEmissivePower, {
6717
- rawData: this.emissiveTriangleBuilder.emissiveTriangleData,
6718
- emissiveCount: this.emissiveTriangleBuilder.emissiveCount,
6719
- totalPower: this.emissiveTriangleBuilder.totalEmissivePower,
6730
+ return !r || (t === "emissive" ? r.emissive = n : t === "emissiveIntensity" && (r.emissiveIntensity = n), !this.emissiveTriangleBuilder.updateMaterialEmissive(e, r, this.triangleData, this.materials, this.triangleCount)) ? null : this._collectEmissivePayload();
6731
+ }
6732
+ rebuildEmissiveForVisibility(e, t = !1) {
6733
+ return !this.emissiveTriangleBuilder || !this.emissiveTriangleBuilder.setHiddenMeshes(e) && !t ? null : this._collectEmissivePayload();
6734
+ }
6735
+ _collectEmissivePayload() {
6736
+ return this.emissiveTriangleBuilder.buildLightBVH(), this.lightBVHNodeData = this.emissiveTriangleBuilder.lightBVHNodeData, this.lightBVHNodeCount = this.emissiveTriangleBuilder.lightBVHNodeCount, this.emissiveTriangleData = this.emissiveTriangleBuilder.emissiveTriangleData, this.emissiveBitTrailMap = this.emissiveTriangleBuilder.emissiveBitTrailMap, this.emissiveTriangleCount = this.emissiveTriangleBuilder.emissiveCount, this.emissiveTotalPower = this.emissiveTriangleBuilder.totalEmissivePower, {
6737
+ rawData: this.emissiveTriangleData,
6738
+ emissiveCount: this.emissiveTriangleCount,
6739
+ totalPower: this.emissiveTotalPower,
6720
6740
  bitTrailMap: this.emissiveBitTrailMap,
6721
6741
  lightBVHNodeData: this.lightBVHNodeData,
6722
6742
  lightBVHNodeCount: this.lightBVHNodeCount
6723
- });
6743
+ };
6724
6744
  }
6725
6745
  _updateMeshTrianglePositions(e, t) {
6726
6746
  let n = Z.FLOATS_PER_TRIANGLE, r = Z.POSITION_A_OFFSET, i = Z.POSITION_B_OFFSET, a = Z.POSITION_C_OFFSET, o = Z.NORMAL_A_OFFSET, s = Z.NORMAL_B_OFFSET, c = Z.NORMAL_C_OFFSET, l = e.bvhToOriginal;
@@ -7188,7 +7208,7 @@ var cc = 4, lc = class extends $n {
7188
7208
  }, this.environment = new _i(this.scene, this.uniforms), this.environment.callbacks.onReset = () => this.reset(), this.environment.callbacks.getSceneTextureNodes = () => this.shaderBuilder.getSceneTextureNodes(), this.shaderBuilder = new us(), this._initRenderingState(), this.setupBlueNoise(), this.tempVector2 = new nn(), this.lastCameraMatrix = new bt(), this.lastProjectionMatrix = new bt(), this.lastRenderMode = -1, this.renderModeChangeTimeout = null, this.renderModeChangeDelay = 50, this.pendingRenderMode = null, this.lastInteractionModeState = !1, this.cameraChanged = !1, this.updateCompletionThreshold();
7189
7209
  }
7190
7210
  _initDataTextures() {
7191
- this.triangleStorageAttr = null, this.triangleStorageNode = null, this.triangleCount = 0, this.bvhStorageAttr = null, this.bvhStorageNode = null, this.bvhNodeCount = 0, this.directionalLightsData = null, this.pointLightsData = null, this.spotLightsData = null, this.areaLightsData = null, this.goboMaps = null, this.iesProfiles = null, this.stbnScalarTexture = null, this.stbnVec2Texture = null, this.lightStorageAttr = new o(new Float32Array(16), 4), this.lightStorageNode = Se(this.lightStorageAttr, "vec4", 1).toReadOnly(), this._lbvhDataCache = null, this._emissiveDataCache = null, this._bitTrailMapCache = null, this._instanceTable = null, this.spheres = [];
7211
+ this.triangleStorageAttr = null, this.triangleStorageNode = null, this.triangleCount = 0, this.bvhStorageAttr = null, this.bvhStorageNode = null, this.bvhNodeCount = 0, this.directionalLightsData = null, this.pointLightsData = null, this.spotLightsData = null, this.areaLightsData = null, this.goboMaps = null, this.iesProfiles = null, this.stbnScalarTexture = null, this.stbnVec2Texture = null, this.lightStorageAttr = new o(new Float32Array(16), 4), this.lightStorageNode = Se(this.lightStorageAttr, "vec4", 1).toReadOnly(), this._lightBufferRealloc = !1, this._lbvhDataCache = null, this._emissiveDataCache = null, this._bitTrailMapCache = null, this._instanceTable = null, this.spheres = [];
7192
7212
  }
7193
7213
  _defineUniformGetters() {
7194
7214
  let e = this.uniforms;
@@ -7478,8 +7498,15 @@ var cc = 4, lc = class extends $n {
7478
7498
  this.stbnScalarTexture = e, e && (Fn.value = e);
7479
7499
  }
7480
7500
  _rebuildLightBuffer() {
7481
- let e = this._lbvhDataCache, t = this._emissiveDataCache, n = this._bitTrailMapCache, r = e ? e.length : 0, i = t ? t.length : 0, a = n ? Math.ceil(n.length / 4) * 4 : 0, s = Math.max(r + i + a, 4), c = new Float32Array(s);
7482
- e && c.set(e, 0), t && c.set(t, r), n && c.set(n, r + i), this.lightStorageAttr = new o(c, 4), this.lightStorageNode.value = this.lightStorageAttr, this.lightStorageNode.bufferCount = c.length / 4, this.emissiveVec4Offset.value = (this.lightBVHNodeCount.value || 0) * 4, this.reverseMapVec4Offset.value = (r + i) / 4;
7501
+ let e = this._lbvhDataCache, t = this._emissiveDataCache, n = this._bitTrailMapCache, r = e ? e.length : 0, i = t ? t.length : 0, a = n ? Math.ceil(n.length / 4) * 4 : 0, s = Math.max(r + i + a, 4);
7502
+ if (this.lightStorageAttr && s <= this.lightStorageAttr.array.length) {
7503
+ let a = this.lightStorageAttr.array;
7504
+ e && a.set(e, 0), t && a.set(t, r), n && a.set(n, r + i), this.lightStorageAttr.needsUpdate = !0;
7505
+ } else {
7506
+ let a = new Float32Array(s);
7507
+ e && a.set(e, 0), t && a.set(t, r), n && a.set(n, r + i), this.lightStorageAttr = new o(a, 4), this.lightStorageNode.value = this.lightStorageAttr, this.lightStorageNode.bufferCount = a.length / 4, this._lightBufferRealloc = !0;
7508
+ }
7509
+ this.emissiveVec4Offset.value = (this.lightBVHNodeCount.value || 0) * 4, this.reverseMapVec4Offset.value = (r + i) / 4;
7483
7510
  }
7484
7511
  setEmissiveTriangleData(e, t, n = 0, r = null) {
7485
7512
  e && (this._emissiveDataCache = e, r && (this._bitTrailMapCache = r), this.emissiveTriangleCount.value = t, this.emissiveTotalPower.value = n, this._rebuildLightBuffer(), console.log(`PathTracer: ${t} emissive triangles, totalPower=${n.toFixed(4)} (storage buffer)`));
@@ -8896,8 +8923,8 @@ var vl = /* @__PURE__ */ G("\n fn equirectDirectionToUv( direction: vec3f, envir
8896
8923
  }), cu = f(([e, t, n, r]) => {
8897
8924
  let i = t.sub(e), a = n.sub(e), o = n.sub(t), s = F(A(i, i), F(A(a, a), A(o, o))), c = O(i, a), l = A(c, c), u = T(!1).toVar();
8898
8925
  return p(l.greaterThan(1e-20), () => {
8899
- let t = A(c, r.sub(e)), n = t.mul(t).div(l);
8900
- u.assign(s.greaterThan(n));
8926
+ let t = A(c, r.sub(e)), n = t.mul(t).div(l), i = s.mul(s).lessThan(l.mul(64));
8927
+ u.assign(s.greaterThan(n).and(i));
8901
8928
  }), u;
8902
8929
  }), lu = wn({
8903
8930
  direction: "vec3",
@@ -9818,7 +9845,7 @@ var Yu = class extends lc {
9818
9845
  super.setupMaterial(), this.materialData?.materialCount > 0 && (this._kernelManager && this._kernelManager.dispose(), this._wavefrontReady = !1, this._buildWavefrontKernels());
9819
9846
  }
9820
9847
  render(e) {
9821
- if (!this.isReady || !this._wavefrontReady) return;
9848
+ if (!this.isReady || !this._wavefrontReady || this._lightBufferRealloc && (this._kernelManager && this._kernelManager.dispose(), this._wavefrontReady = !1, this._buildWavefrontKernels(), !this._wavefrontReady)) return;
9822
9849
  if (this.isComplete || this.frameCount >= this.completionThreshold || this._isConvergedComplete()) {
9823
9850
  this.isComplete ||= !0;
9824
9851
  return;
@@ -9957,6 +9984,7 @@ var Yu = class extends lc {
9957
9984
  _buildWavefrontKernels() {
9958
9985
  let e = this.shaderBuilder.getSceneTextureNodes();
9959
9986
  if (!e) return;
9987
+ this._lightBufferRealloc = !1;
9960
9988
  let t = this.storageTextures.renderWidth, n = this.storageTextures.renderHeight, r = t * n;
9961
9989
  this._bounceEarlyExitThreshold !== -1 && (this._bounceEarlyExitThreshold = Math.max(100, Math.floor(r / 1e3))), this._packedBuffers ? this._packedBuffers.resize(r) : this._packedBuffers = new hc(r, this.renderer);
9962
9990
  let i = hc.requiredCapacity(r) * 1;
@@ -16360,7 +16388,7 @@ var Yf = {
16360
16388
  status: "Transferring data to GPU...",
16361
16389
  progress: 86
16362
16390
  }), await new Promise((e) => setTimeout(e, 0)), e.start("GPU data transfer"), !this._sdf.uploadToPathTracer(this.stages.pathTracer, this.lightManager, this.meshScene, t)) return !1;
16363
- this.stages.pathTracer._meshRefs = this.stages.pathTracer._collectMeshRefs(this.meshScene), this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs), e.end("GPU data transfer"), ir({
16391
+ this.stages.pathTracer._meshRefs = this.stages.pathTracer._collectMeshRefs(this.meshScene), this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs), this._refreshEmissiveForVisibility(), e.end("GPU data transfer"), ir({
16364
16392
  status: "Compiling shaders...",
16365
16393
  progress: 90
16366
16394
  }), await new Promise((e) => setTimeout(e, 0)), e.start("Material setup (TSL compile)"), this.stages.pathTracer.setupMaterial(), e.end("Material setup (TSL compile)"), e.start("Pipeline precompile");
@@ -16375,7 +16403,7 @@ var Yf = {
16375
16403
  }), await n, this.stages.pathTracer.environment.applyCDFResults());
16376
16404
  let r = this.getSceneMinY();
16377
16405
  if (this.settings.set("groundProjectionLevel", r, { reset: !1 }), this.settings.set("groundCatcherHeight", r, { reset: !1 }), !this._emissiveSamplingUserSet) {
16378
- let e = (this._sdf?.emissiveTriangleCount ?? 0) > 0;
16406
+ let e = (this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length ?? this._sdf?.emissiveTriangleCount ?? 0) > 0;
16379
16407
  this.settings.set("enableEmissiveTriangleSampling", e, { reset: !1 });
16380
16408
  }
16381
16409
  return e.start("Apply settings"), this.settings.applyAll(), this.stages.compositor.setTransparentBackground(this.settings.get("transparentBackground")), e.end("Apply settings"), e.print(), rr(), this._initAnimationAndTransforms(), this.dispatchEvent({ type: "SceneRebuild" }), !0;
@@ -16553,23 +16581,29 @@ var Yf = {
16553
16581
  return Number.isFinite(e.min.y) ? e.min.y : 0;
16554
16582
  }
16555
16583
  setMaterialProperty(e, t, n) {
16556
- if (this.stages.pathTracer?.materialData.updateMaterialProperty(e, t, n), ["emissive", "emissiveIntensity"].includes(t) && this.stages.pathTracer?.enableEmissiveTriangleSampling?.value) {
16557
- let r = this._sdf.updateMaterialEmissive(e, t, n);
16558
- r && (this.stages.pathTracer.setEmissiveTriangleData(r.rawData, r.emissiveCount, r.totalPower, r.bitTrailMap), r.lightBVHNodeData && this.stages.pathTracer.setLightBVHData(r.lightBVHNodeData, r.lightBVHNodeCount));
16559
- }
16560
- this.reset();
16584
+ this.stages.pathTracer?.materialData.updateMaterialProperty(e, t, n), ["emissive", "emissiveIntensity"].includes(t) && this._sdf && this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e, t, n)), this.reset();
16585
+ }
16586
+ _uploadEmissivePayload(e) {
16587
+ !e || !this.stages.pathTracer || (this.stages.pathTracer.setEmissiveTriangleData(e.rawData, e.emissiveCount, e.totalPower, e.bitTrailMap), e.lightBVHNodeData && this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData, e.lightBVHNodeCount));
16588
+ }
16589
+ _refreshEmissiveForVisibility() {
16590
+ let e = this._sdf?.instanceTable?.entries;
16591
+ if (!e) return;
16592
+ let t = /* @__PURE__ */ new Set();
16593
+ for (let n of e) n && n.visible === !1 && t.add(n.meshIndex);
16594
+ this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t));
16561
16595
  }
16562
16596
  setEmissiveTriangleSampling(e) {
16563
16597
  this._emissiveSamplingUserSet = !0, this.settings.set("enableEmissiveTriangleSampling", e);
16564
16598
  }
16565
16599
  hasEmissiveGeometry() {
16566
- return (this._sdf?.emissiveTriangleCount ?? 0) > 0;
16600
+ return (this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length ?? this._sdf?.emissiveTriangleCount ?? 0) > 0;
16567
16601
  }
16568
16602
  setMeshVisibility(e, t) {
16569
- this.stages.pathTracer?.updateMeshVisibility(e, t), this.reset();
16603
+ this.stages.pathTracer?.updateMeshVisibility(e, t), this._refreshEmissiveForVisibility(), this.reset();
16570
16604
  }
16571
16605
  updateAllMeshVisibility() {
16572
- this.stages.pathTracer?.updateAllMeshVisibility(), this.reset();
16606
+ this.stages.pathTracer?.updateAllMeshVisibility(), this._refreshEmissiveForVisibility(), this.reset();
16573
16607
  }
16574
16608
  getScene() {
16575
16609
  return this.meshScene || this.scene;