@playcanvas/supersplat-viewer 1.35.1 → 1.36.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.
package/dist/viewer.js CHANGED
@@ -1,4 +1,4 @@
1
- import { AppBase, AppOptions, CameraComponentSystem, LightComponentSystem, RenderComponentSystem, GSplatComponentSystem, ScriptComponentSystem, ContainerHandler, TextureHandler, GSplatHandler, BinaryHandler, XrManager, Asset, SEMANTIC_POSITION, INDEXFORMAT_UINT32, Vec3, Script, Entity, Mat4, version as version$1, Quat, math, Pose, OrbitController as OrbitController$1, Vec2, ShaderUtils, Texture, ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, PIXELFORMAT_RGBA8, RenderTarget, ASPECT_AUTO, BlendState, drawQuadWithShader, Vec4, Color, ShaderChunks, FILTER_NEAREST, PIXELFORMAT_RGBA16F, RenderPassPicker, BLENDEQUATION_MIN, BLENDMODE_ONE, PROJECTION_ORTHOGRAPHIC, ShaderMaterial, CULLFACE_NONE, BLEND_NONE, PIXELFORMAT_R32F, PIXELFORMAT_R16F, PROJECTION_PERSPECTIVE, GamepadSource, KeyboardMouseSource, MultiTouchSource, InputFrame, Mesh, PRIMITIVE_TRIANGLES, Layer, SORTMODE_MANUAL, CULLFACE_BACK, BLEND_NORMAL, MeshInstance, FUNC_EQUAL, StandardMaterial, FUNC_LESSEQUAL, RENDERSTYLE_WIREFRAME, StorageBuffer, BUFFERUSAGE_COPY_DST, BindGroupFormat, BindUniformBufferFormat, BindStorageBufferFormat, BindStorageTextureFormat, SHADERSTAGE_COMPUTE, TEXTUREDIMENSION_2D, UniformBufferFormat, UniformFormat, UNIFORMTYPE_MAT4, UNIFORMTYPE_UINT, UNIFORMTYPE_FLOAT, Shader, SHADERLANGUAGE_WGSL, Compute, BLEND_PREMULTIPLIED, DEVICETYPE_WEBGL2, MiniStats, BoundingBox, GSPLAT_LODMODE_DISTANCE, GSPLAT_DEBUG_LOD, GSPLAT_DEBUG_NONE, CameraFrame, TONEMAP_NEUTRAL, TONEMAP_ACES2, TONEMAP_ACES, TONEMAP_HEJL, TONEMAP_FILMIC, TONEMAP_LINEAR, TONEMAP_NONE, PIXELFORMAT_RGBA32F, GSPLAT_RENDERER_RASTER_GPU_SORT, GSPLAT_RENDERER_RASTER_CPU_SORT, platform, revision, EventHandler, createGraphicsDevice, Keyboard, TouchDevice as TouchDevice$1, Mouse } from 'playcanvas';
1
+ import { AppBase, AppOptions, CameraComponentSystem, LightComponentSystem, RenderComponentSystem, GSplatComponentSystem, ScriptComponentSystem, ContainerHandler, TextureHandler, GSplatHandler, BinaryHandler, XrManager, Asset, SEMANTIC_POSITION, INDEXFORMAT_UINT32, Vec3, Script, Entity, Mat4, version as version$1, Quat, math, Pose, OrbitController as OrbitController$1, Vec2, ShaderUtils, Texture, ADDRESS_CLAMP_TO_EDGE, FILTER_LINEAR, PIXELFORMAT_RGBA8, RenderTarget, ASPECT_AUTO, BlendState, drawQuadWithShader, Vec4, Color, PROJECTION_ORTHOGRAPHIC, ShaderChunks, FILTER_NEAREST, PIXELFORMAT_RGBA16F, RenderPassPicker, BLENDEQUATION_MIN, BLENDMODE_ONE, ShaderMaterial, CULLFACE_NONE, BLEND_NONE, PIXELFORMAT_R32F, PIXELFORMAT_R16F, PROJECTION_PERSPECTIVE, GamepadSource, KeyboardMouseSource, MultiTouchSource, InputFrame, Mesh, PRIMITIVE_TRIANGLES, Layer, SORTMODE_MANUAL, CULLFACE_BACK, BLEND_NORMAL, MeshInstance, FUNC_EQUAL, StandardMaterial, FUNC_LESSEQUAL, RENDERSTYLE_WIREFRAME, PIXELFORMAT_RGBA32F, SAMPLETYPE_UNFILTERABLE_FLOAT, SHADERLANGUAGE_WGSL, Frustum, BoundingSphere, StorageBuffer, BUFFERUSAGE_COPY_DST, Compute, BUFFERUSAGE_COPY_SRC, BindGroupFormat, BindStorageBufferFormat, BindUniformBufferFormat, SHADERSTAGE_COMPUTE, Shader, UniformBufferFormat, UniformFormat, UNIFORMTYPE_UINT, BindTextureFormat, TEXTUREDIMENSION_2D, SAMPLETYPE_DEPTH, PIXELFORMAT_DEPTH, GraphNode, PIXELFORMAT_RGBA16U, PIXELFORMAT_R32U, BLEND_PREMULTIPLIED, Camera as Camera$1, UNIFORMTYPE_MAT4, UNIFORMTYPE_VEC4, UNIFORMTYPE_VEC2, UNIFORMTYPE_FLOAT, RenderPass, SHADER_FORWARD, BindStorageTextureFormat, DEVICETYPE_WEBGL2, platform, BoundingBox, GSPLAT_LODMODE_DISTANCE, GSPLAT_DEBUG_LOD, GSPLAT_DEBUG_NONE, MiniStats, CameraFrame, TONEMAP_NEUTRAL, TONEMAP_ACES2, TONEMAP_ACES, TONEMAP_HEJL, TONEMAP_FILMIC, TONEMAP_LINEAR, TONEMAP_NONE, GSPLAT_RENDERER_RASTER_GPU_SORT, GSPLAT_RENDERER_RASTER_CPU_SORT, revision, EventHandler, createGraphicsDevice, Keyboard, TouchDevice as TouchDevice$1, Mouse } from 'playcanvas';
2
2
  import { XrControllers } from 'playcanvas/scripts/esm/xr/xr-controllers.mjs';
3
3
  import { XrNavigation } from 'playcanvas/scripts/esm/xr/xr-navigation.mjs';
4
4
 
@@ -2558,7 +2558,7 @@ const importSettings = (settings) => {
2558
2558
  return result;
2559
2559
  };
2560
2560
 
2561
- var version = "1.35.1";
2561
+ var version = "1.36.0";
2562
2562
 
2563
2563
  class Tooltip {
2564
2564
  register;
@@ -2773,7 +2773,9 @@ class Annotation extends Script {
2773
2773
  initialize() {
2774
2774
  const ctx = this.context;
2775
2775
  this.hotspotDom = document.createElement('div');
2776
- this.hotspotDom.className = 'sse-annotation-hotspot';
2776
+ // dimmed until the occlusion test first shows it in view, rather than every hotspot
2777
+ // showing at full strength on the reveal and the hidden ones fading afterwards
2778
+ this.hotspotDom.className = 'sse-annotation-hotspot sse-occluded';
2777
2779
  this.hotspotDom.textContent = this.label;
2778
2780
  const onClick = (e) => {
2779
2781
  e.stopPropagation();
@@ -2902,8 +2904,7 @@ class Annotation extends Script {
2902
2904
  tooltip.style.setProperty('--arrow-top', `${arrowY}px`);
2903
2905
  tooltip.classList.toggle('sse-arrow-right', !flipped);
2904
2906
  tooltip.classList.toggle('sse-arrow-left', flipped);
2905
- tooltip.style.left = `${left}px`;
2906
- tooltip.style.top = `${top}px`;
2907
+ tooltip.style.transform = `translate(${left}px, ${top}px)`;
2907
2908
  }
2908
2909
  }
2909
2910
  /**
@@ -7219,6 +7220,132 @@ const fitPlaneNormal = (points, toCamera, outNormal) => {
7219
7220
  outNormal.set(vx, vy, vz);
7220
7221
  return true;
7221
7222
  };
7223
+ // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a small
7224
+ // disc, which is the depth where the opacity in front reaches that. Null where it never does.
7225
+ const surfaceDepth = (depthAt, x, y) => {
7226
+ const samples = [];
7227
+ for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
7228
+ for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
7229
+ if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
7230
+ continue;
7231
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
7232
+ const depth = depthAt(x + dx, y + dy, trial);
7233
+ if (depth !== null)
7234
+ samples.push(depth);
7235
+ }
7236
+ }
7237
+ }
7238
+ if (samples.length === 0) {
7239
+ return null;
7240
+ }
7241
+ samples.sort((a, b) => a - b);
7242
+ const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
7243
+ return Number.isFinite(depth) && depth < 1 ? depth : null;
7244
+ };
7245
+ // The surface under a pixel and its normal, fitted through surface points on rings around it.
7246
+ // `depthAt` must cover NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX around the pixel.
7247
+ const estimateSurface = (depthAt, pickCamera, width, height, screenX, screenY) => {
7248
+ const surfacePoint = (px, py) => {
7249
+ const depth = surfaceDepth(depthAt, px, py);
7250
+ return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
7251
+ };
7252
+ const position = surfacePoint(screenX, screenY);
7253
+ if (!position) {
7254
+ return null;
7255
+ }
7256
+ const samplePixel = (px, py) => {
7257
+ if (px < 0 || px >= width || py < 0 || py >= height) {
7258
+ return null;
7259
+ }
7260
+ return surfacePoint(px, py);
7261
+ };
7262
+ // Pixel radius corresponding to a fixed world radius at the
7263
+ // picked-point's depth. Clamped so distant picks still sample
7264
+ // enough pixels and very-close picks stay inside the block read.
7265
+ const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
7266
+ const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
7267
+ const sampleRings = ringPixelRadii.map((radius) => {
7268
+ return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
7269
+ return samplePixel(screenX + dx * radius, screenY + dy * radius);
7270
+ });
7271
+ });
7272
+ const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
7273
+ // Collect every valid 3D sample: the picked position plus all ring
7274
+ // samples that didn't fall off-screen or find no surface.
7275
+ const fitPoints = [position];
7276
+ for (let i = 0; i < sampleRings.length; i++) {
7277
+ const ring = sampleRings[i];
7278
+ for (let j = 0; j < ring.length; j++) {
7279
+ const pt = ring[j];
7280
+ if (pt)
7281
+ fitPoints.push(pt);
7282
+ }
7283
+ }
7284
+ const normal = new Vec3();
7285
+ if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
7286
+ normal.copy(toCamera);
7287
+ }
7288
+ return {
7289
+ position,
7290
+ normal
7291
+ };
7292
+ };
7293
+ // The share of samples over a disc of `r` pixels whose nearest survivor is nearer than the view
7294
+ // depth `depth`; null where the disc has no samples. `depthAt` must cover the disc.
7295
+ const opacityInFront = (depthAt, pickCamera, screenX, screenY, r, depth) => {
7296
+ const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
7297
+ let total = 0;
7298
+ let inFront = 0;
7299
+ for (let dy = -r; dy <= r; dy++) {
7300
+ for (let dx = -r; dx <= r; dx++) {
7301
+ if (dx * dx + dy * dy > r * r)
7302
+ continue;
7303
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
7304
+ const nearest = depthAt(screenX + dx, screenY + dy, trial);
7305
+ if (nearest === null)
7306
+ continue;
7307
+ total++;
7308
+ if (nearest < threshold)
7309
+ inFront++;
7310
+ }
7311
+ }
7312
+ }
7313
+ return total > 0 ? inFront / total : null;
7314
+ };
7315
+ // One pick pixel per css pixel, never more than the backbuffer has: picking then behaves the
7316
+ // same in performance mode and at any device pixel ratio, since the pixel sizes above are css
7317
+ // pixels, and a high-density display does not multiply the pass's cost. Null before the device
7318
+ // or the canvas has been sized.
7319
+ const pickTargetSize = (graphicsDevice) => {
7320
+ const canvas = graphicsDevice.canvas;
7321
+ const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
7322
+ const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
7323
+ return width > 0 && height > 0 ? { width, height } : null;
7324
+ };
7325
+ const clampPixel = (v, size) => Math.min(size - 1, Math.max(0, Math.floor(v * size)));
7326
+ // Picks run one at a time, since they share one render. `fallback` is the result for a pick
7327
+ // that release overtakes: one queued behind another pick, or one whose read-back is cut short
7328
+ // as the device goes.
7329
+ class PickQueue {
7330
+ released = false;
7331
+ queue = Promise.resolve();
7332
+ run(operation, fallback) {
7333
+ const guarded = () => {
7334
+ if (this.released) {
7335
+ return Promise.resolve(fallback);
7336
+ }
7337
+ return operation().catch((error) => {
7338
+ if (this.released) {
7339
+ return fallback;
7340
+ }
7341
+ throw error;
7342
+ });
7343
+ };
7344
+ const result = this.queue.then(guarded, guarded);
7345
+ this.queue = result.then(() => undefined, () => undefined);
7346
+ return result;
7347
+ }
7348
+ }
7222
7349
  class Picker {
7223
7350
  pick;
7224
7351
  pickSurface;
@@ -7247,10 +7374,7 @@ class Picker {
7247
7374
  let pickTarget;
7248
7375
  let pickPass;
7249
7376
  let chunksPatched = false;
7250
- // set by release: queued and in-flight picks then resolve to nothing, rather than render
7251
- // with released resources or reach an app that is being destroyed
7252
- let released = false;
7253
- let pickQueue = Promise.resolve();
7377
+ const queue = new PickQueue();
7254
7378
  let cacheValid = false;
7255
7379
  let renders = 0;
7256
7380
  let cacheWidth = 0;
@@ -7303,8 +7427,6 @@ class Picker {
7303
7427
  return snapshot;
7304
7428
  };
7305
7429
  // Read the pick render around a pixel, `margin` pixels each way, clamped to the render.
7306
- // The accessor returns a pixel's nearest surviving normalised depth in one of its
7307
- // PICK_TRIALS trials, 1 where no fragment survived, or null outside the block.
7308
7430
  const readAround = async (screenX, screenY, margin, width, height) => {
7309
7431
  const blockX = Math.max(0, screenX - margin);
7310
7432
  const blockY = Math.max(0, screenY - margin);
@@ -7325,29 +7447,6 @@ class Picker {
7325
7447
  return half2Float(pixels[(row * blockWidth + localX) * 4 + trial]);
7326
7448
  };
7327
7449
  };
7328
- // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a
7329
- // small disc, which is the depth where the opacity in front reaches that. Null where it
7330
- // never does.
7331
- const surfaceDepth = (depthAt, x, y) => {
7332
- const samples = [];
7333
- for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
7334
- for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
7335
- if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
7336
- continue;
7337
- for (let trial = 0; trial < PICK_TRIALS; trial++) {
7338
- const depth = depthAt(x + dx, y + dy, trial);
7339
- if (depth !== null)
7340
- samples.push(depth);
7341
- }
7342
- }
7343
- }
7344
- if (samples.length === 0) {
7345
- return null;
7346
- }
7347
- samples.sort((a, b) => a - b);
7348
- const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
7349
- return Number.isFinite(depth) && depth < 1 ? depth : null;
7350
- };
7351
7450
  const ensureRendered = (width, height, worldLayer) => {
7352
7451
  if (cameraMatches(width, height)) {
7353
7452
  return;
@@ -7374,49 +7473,24 @@ class Picker {
7374
7473
  renders++;
7375
7474
  };
7376
7475
  const prepareSample = (x, y) => {
7377
- if (released) {
7476
+ if (queue.released) {
7378
7477
  return null;
7379
7478
  }
7380
- // One pick pixel per css pixel, never more than the backbuffer has: picking then
7381
- // behaves the same in performance mode and at any device pixel ratio, since the
7382
- // pixel sizes above are css pixels, and a high-density display does not multiply
7383
- // the pass's cost
7384
- const canvas = graphicsDevice.canvas;
7385
- const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
7386
- const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
7387
- // bail out if the device or the canvas hasn't been sized yet
7388
- if (width <= 0 || height <= 0) {
7479
+ const size = pickTargetSize(graphicsDevice);
7480
+ if (!size) {
7389
7481
  return null;
7390
7482
  }
7483
+ const { width, height } = size;
7391
7484
  const worldLayer = app.scene.layers.getLayerByName('World');
7392
7485
  if (!worldLayer) {
7393
7486
  return null;
7394
7487
  }
7395
- const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
7396
- const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
7488
+ const screenX = clampPixel(x, width);
7489
+ const screenY = clampPixel(y, height);
7397
7490
  ensureRendered(width, height, worldLayer);
7398
7491
  const pickCamera = getCacheCameraSnapshot();
7399
7492
  return { width, height, screenX, screenY, pickCamera };
7400
7493
  };
7401
- // `fallback` is the result for a pick that release overtakes: one queued behind another
7402
- // pick, or one whose read-back is cut short as the device goes
7403
- const serializePick = (operation, fallback) => {
7404
- const guarded = () => {
7405
- if (released) {
7406
- return Promise.resolve(fallback);
7407
- }
7408
- return operation().catch((error) => {
7409
- if (released) {
7410
- return fallback;
7411
- }
7412
- throw error;
7413
- });
7414
- };
7415
- // The render target is shared by all picks on this instance.
7416
- const result = pickQueue.then(guarded, guarded);
7417
- pickQueue = result.then(() => undefined, () => undefined);
7418
- return result;
7419
- };
7420
7494
  const pick = async (x, y) => {
7421
7495
  const sample = prepareSample(x, y);
7422
7496
  if (!sample) {
@@ -7437,50 +7511,7 @@ class Picker {
7437
7511
  // Sized to the maximum possible ring pixel-radius, plus the surface disc around each
7438
7512
  // sample, so the dynamic ring offsets always lie inside the buffer we read.
7439
7513
  const depthAt = await readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
7440
- const surfacePoint = (px, py) => {
7441
- const depth = surfaceDepth(depthAt, px, py);
7442
- return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
7443
- };
7444
- const position = surfacePoint(screenX, screenY);
7445
- if (!position) {
7446
- return null;
7447
- }
7448
- const samplePixel = (px, py) => {
7449
- if (px < 0 || px >= width || py < 0 || py >= height) {
7450
- return null;
7451
- }
7452
- return surfacePoint(px, py);
7453
- };
7454
- // Pixel radius corresponding to a fixed world radius at the
7455
- // picked-point's depth. Clamped so distant picks still sample
7456
- // enough pixels and very-close picks stay inside the block read.
7457
- const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
7458
- const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
7459
- const sampleRings = ringPixelRadii.map((radius) => {
7460
- return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
7461
- return samplePixel(screenX + dx * radius, screenY + dy * radius);
7462
- });
7463
- });
7464
- const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
7465
- // Collect every valid 3D sample: the picked position plus all ring
7466
- // samples that didn't fall off-screen or find no surface.
7467
- const fitPoints = [position];
7468
- for (let i = 0; i < sampleRings.length; i++) {
7469
- const ring = sampleRings[i];
7470
- for (let j = 0; j < ring.length; j++) {
7471
- const pt = ring[j];
7472
- if (pt)
7473
- fitPoints.push(pt);
7474
- }
7475
- }
7476
- const normal = new Vec3();
7477
- if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
7478
- normal.copy(toCamera);
7479
- }
7480
- return {
7481
- position,
7482
- normal
7483
- };
7514
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
7484
7515
  };
7485
7516
  const pickVisibility = async (points, radius) => {
7486
7517
  if (points.length === 0) {
@@ -7496,29 +7527,12 @@ class Picker {
7496
7527
  const { width, height, screenX, screenY, pickCamera } = sample;
7497
7528
  const r = Math.max(1, Math.round(radius * height));
7498
7529
  const depthAt = await readAround(screenX, screenY, r, width, height);
7499
- const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
7500
- let total = 0;
7501
- let inFront = 0;
7502
- for (let dy = -r; dy <= r; dy++) {
7503
- for (let dx = -r; dx <= r; dx++) {
7504
- if (dx * dx + dy * dy > r * r)
7505
- continue;
7506
- for (let trial = 0; trial < PICK_TRIALS; trial++) {
7507
- const nearest = depthAt(screenX + dx, screenY + dy, trial);
7508
- if (nearest === null)
7509
- continue;
7510
- total++;
7511
- if (nearest < threshold)
7512
- inFront++;
7513
- }
7514
- }
7515
- }
7516
- return total > 0 ? inFront / total : null;
7530
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
7517
7531
  }));
7518
7532
  };
7519
- this.pick = (x, y) => serializePick(() => pick(x, y), null);
7520
- this.pickSurface = (x, y) => serializePick(() => pickSurface(x, y), null);
7521
- this.pickVisibility = (points, radius) => serializePick(() => pickVisibility(points, radius), points.map(() => null));
7533
+ this.pick = (x, y) => queue.run(() => pick(x, y), null);
7534
+ this.pickSurface = (x, y) => queue.run(() => pickSurface(x, y), null);
7535
+ this.pickVisibility = (points, radius) => queue.run(() => pickVisibility(points, radius), points.map(() => null));
7522
7536
  this.renderView = () => (prepareSample(0, 0) ? { texture: pickBuffer, renders } : null);
7523
7537
  // The scene can change under a still camera, which the camera-based cache cannot see:
7524
7538
  // finer detail streams in after the reveal and after every move. The engine reports each
@@ -7537,7 +7551,7 @@ class Picker {
7537
7551
  };
7538
7552
  gsplatSystem.on('frame:ready', onFrameReady);
7539
7553
  this.release = () => {
7540
- released = true;
7554
+ queue.released = true;
7541
7555
  gsplatSystem.off('frame:ready', onFrameReady);
7542
7556
  if (chunksPatched) {
7543
7557
  unregisterPickerShaderPatches(app);
@@ -7908,6 +7922,20 @@ const STYLES = `
7908
7922
  .${PANEL_CLASS} button.sse-flash {
7909
7923
  background: rgba(120, 220, 140, 0.35);
7910
7924
  }
7925
+ .${PANEL_CLASS} button.sse-flash-bad {
7926
+ background: rgba(220, 100, 100, 0.45);
7927
+ }
7928
+ .${PANEL_CLASS} input.sse-debug-paste {
7929
+ width: 100%;
7930
+ box-sizing: border-box;
7931
+ margin-top: 6px;
7932
+ background: rgba(255, 255, 255, 0.08);
7933
+ color: #eee;
7934
+ border: 1px solid rgba(120, 180, 255, 0.6);
7935
+ border-radius: 3px;
7936
+ padding: 4px 8px;
7937
+ font: inherit;
7938
+ }
7911
7939
  .${PANEL_CLASS} button.sse-debug-on {
7912
7940
  background: rgba(120, 180, 255, 0.35);
7913
7941
  }
@@ -7930,6 +7958,14 @@ class DebugPanel {
7930
7958
  _global;
7931
7959
  _cameraManager;
7932
7960
  _picker;
7961
+ // the stochastic renderer when this viewer opted in, for its depth cull toggle and counts
7962
+ _splatRenderer;
7963
+ _cullButton = null;
7964
+ _taaButton = null;
7965
+ _poplessButton = null;
7966
+ _culledValue = null;
7967
+ _cullStatsFrames = 0;
7968
+ _cullStatsPending = false;
7933
7969
  _pickDepthOverlay = null;
7934
7970
  _focusTmp = new Vec3();
7935
7971
  _root = null;
@@ -7938,12 +7974,20 @@ class DebugPanel {
7938
7974
  _focusValue = null;
7939
7975
  _copyButton = null;
7940
7976
  _pasteButton = null;
7977
+ // shown when the clipboard cannot be read (a cross-origin iframe without clipboard-read):
7978
+ // the paste event of a focused field carries the text without that permission
7979
+ _pasteField = null;
7980
+ _miniStatsButton = null;
7981
+ // the viewer's MiniStats switch
7982
+ _miniStats;
7941
7983
  _screenshotButton = null;
7942
7984
  _pickDepthButton = null;
7943
7985
  _editing = null;
7944
7986
  _editCanceled = false;
7945
7987
  _visible = false;
7946
7988
  _onPrerender = () => this._render();
7989
+ // the cull state is decided inside the frame, so its row refreshes after it
7990
+ _onFrameEnd = () => this._renderCull();
7947
7991
  _onKeyDown = (event) => {
7948
7992
  // Ctrl+Shift+D — also accept Meta+Shift+D on macOS for parity
7949
7993
  if (!this._global.state.inputEnabled)
@@ -7953,10 +7997,12 @@ class DebugPanel {
7953
7997
  this.toggle();
7954
7998
  }
7955
7999
  };
7956
- constructor(global, cameraManager, picker) {
8000
+ constructor(global, cameraManager, picker, splatRenderer = null, miniStats = null) {
7957
8001
  this._global = global;
7958
8002
  this._cameraManager = cameraManager;
7959
8003
  this._picker = picker;
8004
+ this._splatRenderer = splatRenderer;
8005
+ this._miniStats = miniStats;
7960
8006
  window.addEventListener('keydown', this._onKeyDown);
7961
8007
  if (global.config.debug) {
7962
8008
  this.show();
@@ -7971,6 +8017,7 @@ class DebugPanel {
7971
8017
  }
7972
8018
  this._root.style.display = '';
7973
8019
  this._global.app.on('prerender', this._onPrerender);
8020
+ this._global.app.on('frameend', this._onFrameEnd);
7974
8021
  if (this._global.config.exposeGlobals) {
7975
8022
  window.getCameraState = () => captureCameraState(this._cameraManager, this._global.state);
7976
8023
  window.setCameraState = (snapshot) => restoreCameraState(this._cameraManager, this._global.state, snapshot);
@@ -7987,6 +8034,7 @@ class DebugPanel {
7987
8034
  // the view is only reachable from the panel, so it goes with it
7988
8035
  this._setPickDepth(false);
7989
8036
  this._global.app.off('prerender', this._onPrerender);
8037
+ this._global.app.off('frameend', this._onFrameEnd);
7990
8038
  if (this._global.config.exposeGlobals) {
7991
8039
  delete window.getCameraState;
7992
8040
  delete window.setCameraState;
@@ -8031,8 +8079,19 @@ class DebugPanel {
8031
8079
  </div>
8032
8080
  <div class="sse-debug-buttons">
8033
8081
  <button data-id="screenshot">Screenshot</button>
8034
- <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Pick depth</button>
8082
+ <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Show depth</button>
8083
+ <button data-id="ministats" title="Show the engine's MiniStats graphs (the viewer then renders every frame)">MiniStats</button>
8084
+ </div>
8085
+ <input class="sse-debug-paste" data-id="paste-field" placeholder="Clipboard blocked here: paste with Ctrl/Cmd+V" spellcheck="false" style="display: none">
8086
+ ${this._splatRenderer
8087
+ ? `
8088
+ <div class="sse-debug-buttons">
8089
+ <button data-id="depth-cull" title="Stochastic renderer: cull splats hidden in the previous frame's depth (auto suspends the test when it removes too little)">Depth cull</button>
8090
+ <button data-id="taa" title="Stochastic renderer: accumulate the samples over frames (reprojected while the camera moves)">TAA</button>
8091
+ <button data-id="popless" title="Stochastic renderer: give each fragment the depth of the Gaussian's peak along its ray, rather than the splat centre's">Popless</button>
8035
8092
  </div>
8093
+ <div class="sse-debug-row"><span class="sse-debug-label">culled</span><span class="sse-debug-value" data-id="culled">—</span></div>`
8094
+ : ''}
8036
8095
  `;
8037
8096
  host.appendChild(root);
8038
8097
  this._root = root;
@@ -8042,12 +8101,52 @@ class DebugPanel {
8042
8101
  this._pasteButton = root.querySelector('[data-id="paste"]');
8043
8102
  this._screenshotButton = root.querySelector('[data-id="screenshot"]');
8044
8103
  this._pickDepthButton = root.querySelector('[data-id="pick-depth"]');
8104
+ this._miniStatsButton = root.querySelector('[data-id="ministats"]');
8105
+ this._pasteField = root.querySelector('[data-id="paste-field"]');
8106
+ this._wirePasteField(this._pasteField);
8107
+ if (this._miniStats) {
8108
+ this._miniStatsButton.addEventListener('click', () => {
8109
+ this._miniStats.show(!this._miniStats.shown());
8110
+ this._renderMiniStats();
8111
+ });
8112
+ this._renderMiniStats();
8113
+ }
8114
+ else {
8115
+ this._miniStatsButton.remove();
8116
+ }
8045
8117
  this._copyButton.addEventListener('click', () => this._copy());
8046
8118
  this._pasteButton.addEventListener('click', () => this._paste());
8047
8119
  this._screenshotButton.addEventListener('click', () => this._screenshot());
8048
8120
  this._pickDepthButton.addEventListener('click', () => {
8049
8121
  this._setPickDepth(!this._pickDepthOverlay?.enabled);
8050
8122
  });
8123
+ if (this._splatRenderer) {
8124
+ this._cullButton = root.querySelector('[data-id="depth-cull"]');
8125
+ this._taaButton = root.querySelector('[data-id="taa"]');
8126
+ this._poplessButton = root.querySelector('[data-id="popless"]');
8127
+ this._poplessButton.addEventListener('click', () => {
8128
+ const renderer = this._splatRenderer;
8129
+ renderer.variant.popless = renderer.variant.popless === 'on' ? 'off' : 'on';
8130
+ renderer.applyVariant();
8131
+ this._renderCull();
8132
+ });
8133
+ this._culledValue = root.querySelector('[data-id="culled"]');
8134
+ this._taaButton.addEventListener('click', () => {
8135
+ const renderer = this._splatRenderer;
8136
+ renderer.variant.taa = renderer.variant.taa === 'on' ? 'off' : 'on';
8137
+ renderer.applyVariant();
8138
+ this._renderCull();
8139
+ });
8140
+ // cycles the cull mode: auto (the default) -> on (both grid levels) -> off
8141
+ this._cullButton.addEventListener('click', () => {
8142
+ const renderer = this._splatRenderer;
8143
+ const next = { auto: 'l2', l2: 'off', l1: 'off', off: 'auto' };
8144
+ renderer.variant.cull = next[renderer.variant.cull];
8145
+ renderer.applyVariant();
8146
+ this._renderCull();
8147
+ });
8148
+ this._renderCull();
8149
+ }
8051
8150
  this._wireEditable(this._positionValue, 'position');
8052
8151
  this._wireEditable(this._focusValue, 'focus');
8053
8152
  }
@@ -8143,27 +8242,153 @@ class DebugPanel {
8143
8242
  this._focusValue.textContent = fmt(this._focusTmp);
8144
8243
  }
8145
8244
  }
8245
+ // the cull button shows the mode; the counts come back from the gpu every few frames
8246
+ _renderCull() {
8247
+ const renderer = this._splatRenderer;
8248
+ if (!renderer || !this._cullButton || !this._culledValue)
8249
+ return;
8250
+ const mode = renderer.variant.cull;
8251
+ this._cullButton.textContent = `Depth cull: ${mode === 'off' ? 'off' : mode === 'auto' ? 'auto' : 'on'}`;
8252
+ this._cullButton.classList.toggle('sse-debug-on', mode !== 'off');
8253
+ if (this._taaButton) {
8254
+ this._taaButton.textContent = `TAA: ${renderer.variant.taa}`;
8255
+ this._taaButton.classList.toggle('sse-debug-on', renderer.variant.taa === 'on');
8256
+ }
8257
+ if (this._poplessButton) {
8258
+ this._poplessButton.textContent = `Popless: ${renderer.variant.popless}`;
8259
+ this._poplessButton.classList.toggle('sse-debug-on', renderer.variant.popless === 'on');
8260
+ }
8261
+ if (mode === 'off') {
8262
+ this._culledValue.textContent = 'off';
8263
+ return;
8264
+ }
8265
+ if (!renderer.culling) {
8266
+ this._culledValue.textContent = renderer.cullSuspended ? 'suspended' : 'no previous frame';
8267
+ return;
8268
+ }
8269
+ if (this._cullStatsPending || this._cullStatsFrames++ % 15 !== 0)
8270
+ return;
8271
+ this._cullStatsPending = true;
8272
+ renderer
8273
+ .readStats()
8274
+ .then(({ survivors, occluded }) => {
8275
+ const total = survivors + occluded;
8276
+ const pct = total > 0 ? ((100 * occluded) / total).toFixed(0) : '0';
8277
+ if (this._culledValue && renderer.culling) {
8278
+ this._culledValue.textContent = `${pct}% (${occluded.toLocaleString()} of ${total.toLocaleString()})`;
8279
+ }
8280
+ })
8281
+ .catch(() => {
8282
+ // a destroyed buffer or lost device; the next refresh tries again
8283
+ })
8284
+ .finally(() => {
8285
+ this._cullStatsPending = false;
8286
+ });
8287
+ }
8288
+ // The clipboard api, else a selection copied with execCommand: the api is refused in a
8289
+ // cross-origin iframe without clipboard-write (superspl.at's local-frontend frame), while
8290
+ // the command still works there inside the click
8146
8291
  async _copy() {
8147
- const snapshot = captureCameraState(this._cameraManager, this._global.state);
8292
+ const text = JSON.stringify(captureCameraState(this._cameraManager, this._global.state));
8293
+ let copied = false;
8148
8294
  try {
8149
- await navigator.clipboard.writeText(JSON.stringify(snapshot));
8295
+ await navigator.clipboard.writeText(text);
8296
+ copied = true;
8297
+ }
8298
+ catch {
8299
+ // destroyed while the clipboard was refusing
8300
+ if (!this._root)
8301
+ return;
8302
+ const area = document.createElement('textarea');
8303
+ area.value = text;
8304
+ area.style.cssText = 'position: fixed; opacity: 0; pointer-events: none';
8305
+ this._root.appendChild(area);
8306
+ area.select();
8307
+ try {
8308
+ copied = document.execCommand('copy');
8309
+ }
8310
+ catch {
8311
+ copied = false;
8312
+ }
8313
+ area.remove();
8314
+ }
8315
+ if (copied) {
8150
8316
  this._flash(this._copyButton);
8151
8317
  }
8152
- catch (err) {
8153
- console.warn('[debug-panel] copy failed', err);
8318
+ else {
8319
+ console.warn('[debug-panel] copy failed');
8320
+ this._flashBad(this._copyButton);
8154
8321
  }
8155
8322
  }
8323
+ // The clipboard api, else the paste field: reading needs clipboard-read, which a
8324
+ // cross-origin iframe only has when its embedder grants it
8156
8325
  async _paste() {
8326
+ let text;
8327
+ try {
8328
+ text = await navigator.clipboard.readText();
8329
+ }
8330
+ catch {
8331
+ this._showPasteField(true);
8332
+ return;
8333
+ }
8334
+ // destroyed while the clipboard was being read
8335
+ if (!this._root)
8336
+ return;
8337
+ this._applyPasted(text);
8338
+ }
8339
+ _applyPasted(text) {
8157
8340
  try {
8158
- const text = await navigator.clipboard.readText();
8159
8341
  const snapshot = JSON.parse(text);
8160
8342
  restoreCameraState(this._cameraManager, this._global.state, snapshot);
8161
8343
  this._flash(this._pasteButton);
8162
8344
  }
8163
8345
  catch (err) {
8164
8346
  console.warn('[debug-panel] paste failed', err);
8347
+ this._flashBad(this._pasteButton);
8165
8348
  }
8166
8349
  }
8350
+ _showPasteField(value) {
8351
+ const field = this._pasteField;
8352
+ if (!field)
8353
+ return;
8354
+ field.value = '';
8355
+ field.style.display = value ? '' : 'none';
8356
+ if (value)
8357
+ field.focus();
8358
+ }
8359
+ _wirePasteField(field) {
8360
+ // keys typed here are text, not camera controls (see _wireEditable)
8361
+ const stopKey = (e) => e.stopPropagation();
8362
+ field.addEventListener('keydown', (e) => {
8363
+ stopKey(e);
8364
+ if (e.key === 'Enter') {
8365
+ e.preventDefault();
8366
+ const text = field.value;
8367
+ this._showPasteField(false);
8368
+ this._applyPasted(text);
8369
+ }
8370
+ else if (e.key === 'Escape') {
8371
+ e.preventDefault();
8372
+ this._showPasteField(false);
8373
+ }
8374
+ });
8375
+ field.addEventListener('keyup', stopKey);
8376
+ field.addEventListener('keypress', stopKey);
8377
+ field.addEventListener('paste', (e) => {
8378
+ e.preventDefault();
8379
+ const text = e.clipboardData?.getData('text/plain') ?? '';
8380
+ this._showPasteField(false);
8381
+ this._applyPasted(text);
8382
+ });
8383
+ field.addEventListener('blur', () => this._showPasteField(false));
8384
+ }
8385
+ _renderMiniStats() {
8386
+ if (!this._miniStats || !this._miniStatsButton)
8387
+ return;
8388
+ const shown = this._miniStats.shown();
8389
+ this._miniStatsButton.textContent = `MiniStats: ${shown ? 'on' : 'off'}`;
8390
+ this._miniStatsButton.classList.toggle('sse-debug-on', shown);
8391
+ }
8167
8392
  _screenshot() {
8168
8393
  const app = this._global.app;
8169
8394
  const canvas = app.graphicsDevice.canvas;
@@ -10138,101 +10363,3389 @@ class NavCursor {
10138
10363
  }
10139
10364
  }
10140
10365
 
10141
- // ---------------------------------------------------------------------------
10142
- // WGSL compute shader: ray-march through the sparse voxel octree per pixel
10143
- // ---------------------------------------------------------------------------
10144
- const voxelOverlayWGSL = /* wgsl */ `
10145
-
10146
- // Solid leaf sentinel: childMask=0xFF, baseOffset=0
10147
- const SOLID_LEAF_MARKER: u32 = 0xFF000000u;
10148
-
10149
- // Maximum DDA steps to prevent infinite loops
10150
- const MAX_STEPS: u32 = 512u;
10151
-
10152
- // Target wireframe edge width in pixels
10153
- const EDGE_PIXELS: f32 = 1.5;
10154
-
10155
- // Keep edges tinted so dense grids retain the solid/free-space distinction.
10156
- const EDGE_ALPHA: f32 = 0.8;
10157
-
10158
- const FILL_ALPHA: f32 = 0.4;
10366
+ /**
10367
+ * World picking from the stochastic renderer's own frame.
10368
+ *
10369
+ * Every pixel of that renderer's depth texture holds the nearest surviving sample, which is
10370
+ * exactly what the pass picker in `picker.ts` renders on purpose: a stochastic depth whose
10371
+ * distribution over a disc is the scene's opacity along the ray. So no pick pass: the frame's
10372
+ * depth is snapshotted into the same encoding (normalised linear depth in four half-float
10373
+ * channels, 1 where nothing survived) at css resolution, and the shared estimators, the
10374
+ * annotation test and the debug overlay read it unchanged. A css pixel's four channels are four
10375
+ * of the device pixels it covers, so a high-density display supplies four trials as before.
10376
+ */
10377
+ // The frame's hardware depth as normalised linear view depth, in the pass picker's encoding.
10378
+ // Each snapshot pixel covers a block of device pixels; four of them, at the block's quarter
10379
+ // points, fill the four channels.
10380
+ const snapshotWgsl = /* wgsl */ `
10381
+ var splatDepth: texture_depth_2d;
10382
+ // clip z = a * viewDepth + b over w = viewDepth (x, y), near and far (z, w)
10383
+ uniform depthViewParams: vec4f;
10384
+ // device pixels per snapshot pixel (x, y), 1 for an orthographic camera (z)
10385
+ uniform snapshotParams: vec4f;
10159
10386
 
10160
- struct Uniforms {
10161
- invVP: mat4x4<f32>,
10162
- screenWidth: u32,
10163
- screenHeight: u32,
10164
- gridMinX: f32,
10165
- gridMinY: f32,
10166
- gridMinZ: f32,
10167
- voxelRes: f32,
10168
- numVoxelsX: u32,
10169
- numVoxelsY: u32,
10170
- numVoxelsZ: u32,
10171
- leafSize: u32,
10172
- treeDepth: u32,
10173
- projScaleY: f32,
10174
- displayMode: u32,
10175
- inverted: u32
10387
+ @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
10388
+ var output: FragmentOutput;
10389
+ let dims = vec2i(textureDimensions(splatDepth));
10390
+ let p = uniform.depthViewParams;
10391
+ let ortho = uniform.snapshotParams.z > 0.5;
10392
+ let origin = floor(pcPosition.xy);
10393
+ var trials = vec4f(1.0);
10394
+ for (var i = 0; i < 4; i++) {
10395
+ let corner = vec2f(0.25 + 0.5 * f32(i & 1), 0.25 + 0.5 * f32(i >> 1));
10396
+ let q = clamp(vec2i(floor((origin + corner) * uniform.snapshotParams.xy)), vec2i(0), dims - vec2i(1));
10397
+ let depth = textureLoad(splatDepth, q, 0);
10398
+ if (depth < 1.0) {
10399
+ let dz = depth - p.x;
10400
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
10401
+ let viewDepth = select(p.y / safeDz, (depth - p.y) / p.x, ortho);
10402
+ trials[i] = clamp((viewDepth - p.z) / (p.w - p.z), 0.0, 0.99951171875);
10403
+ }
10404
+ }
10405
+ output.color = trials;
10406
+ return output;
10407
+ }
10408
+ `;
10409
+ const cameraMatches = (frame, camera) => {
10410
+ const cam = camera.camera;
10411
+ return (frame.viewMatrix.equals(cam.viewMatrix) &&
10412
+ frame.projectionMatrix.equals(cam.projectionMatrix) &&
10413
+ frame.nearClip === cam.nearClip &&
10414
+ frame.farClip === cam.farClip &&
10415
+ frame.projection === cam.projection);
10176
10416
  };
10177
-
10178
- @group(0) @binding(0) var<uniform> uniforms: Uniforms;
10179
- @group(0) @binding(1) var<storage, read> nodes: array<u32>;
10180
- @group(0) @binding(2) var<storage, read> leafData: array<u32>;
10181
- @group(0) @binding(3) var outputTexture: texture_storage_2d<rgba8unorm, write>;
10182
-
10183
- // ---- helpers ----
10184
-
10185
- // Traverse the octree for block (bx, by, bz). Returns vec2u(result, skipLevel):
10186
- // result: 0 = empty, 1 = solid, 2+ = mixed leaf (2 + leafDataIndex)
10187
- // skipLevel: octree level for multi-block skipping (meaningful when result == 0 or 1)
10188
- fn queryBlock(bx: i32, by: i32, bz: i32) -> vec2u {
10189
- let depth = uniforms.treeDepth;
10190
- var nodeIndex: u32 = 0u;
10191
-
10192
- for (var level: u32 = depth - 1u; ; ) {
10193
- let node = nodes[nodeIndex];
10194
-
10195
- // Solid leaf sentinel -- return level + 1 so the caller can skip 2^(level+1) blocks
10196
- if (node == SOLID_LEAF_MARKER) {
10197
- return vec2u(1u, level + 1u);
10417
+ const sameCamera = (a, b) => a.viewMatrix.equals(b.viewMatrix) &&
10418
+ a.projectionMatrix.equals(b.projectionMatrix) &&
10419
+ a.nearClip === b.nearClip &&
10420
+ a.farClip === b.farClip &&
10421
+ a.projection === b.projection;
10422
+ const copyCameraSnapshot = (from, to) => {
10423
+ to.position.copy(from.position);
10424
+ to.viewMatrix.copy(from.viewMatrix);
10425
+ to.projectionMatrix.copy(from.projectionMatrix);
10426
+ to.nearClip = from.nearClip;
10427
+ to.farClip = from.farClip;
10428
+ to.projection = from.projection;
10429
+ };
10430
+ class FrameDepthPicker {
10431
+ app;
10432
+ camera;
10433
+ renderer;
10434
+ shader;
10435
+ texture = null;
10436
+ target = null;
10437
+ // the renderer frame the snapshot was taken from, and the camera it was drawn with
10438
+ snapshotFrame = -1;
10439
+ snapshotCamera = createPickCameraSnapshot();
10440
+ renders = 0;
10441
+ queue = new PickQueue();
10442
+ // picks waiting for a frame to render; settled by release as well
10443
+ waiters = new Set();
10444
+ constructor(app, camera, renderer) {
10445
+ this.app = app;
10446
+ this.camera = camera;
10447
+ this.renderer = renderer;
10448
+ this.shader = ShaderUtils.createShader(app.graphicsDevice, {
10449
+ uniqueName: 'sse-splat-depth-snapshot',
10450
+ attributes: { vertex_position: SEMANTIC_POSITION },
10451
+ vertexChunk: 'fullscreenQuadVS',
10452
+ fragmentWGSL: snapshotWgsl
10453
+ });
10454
+ }
10455
+ // Wait for the next frame to finish, or for release.
10456
+ nextFrame() {
10457
+ return new Promise((resolve) => {
10458
+ const done = () => {
10459
+ handle.off();
10460
+ this.waiters.delete(done);
10461
+ resolve();
10462
+ };
10463
+ const handle = this.app.once('frameend', done);
10464
+ this.waiters.add(done);
10465
+ });
10466
+ }
10467
+ // Snapshot the renderer's frame at css resolution, unless the snapshot already is of it. With
10468
+ // `latest` false a snapshot of an earlier frame from the same camera serves: every stochastic
10469
+ // frame is a new sample, so the debug overlay would otherwise ask for frames without end.
10470
+ snapshot(frame, latest) {
10471
+ const device = this.app.graphicsDevice;
10472
+ const size = pickTargetSize(device);
10473
+ if (!size)
10474
+ return null;
10475
+ const { width, height } = size;
10476
+ if (!this.texture) {
10477
+ this.texture = new Texture(device, {
10478
+ name: 'sse-splat-depth-snapshot',
10479
+ format: PIXELFORMAT_RGBA16F,
10480
+ width,
10481
+ height,
10482
+ mipmaps: false,
10483
+ minFilter: FILTER_NEAREST,
10484
+ magFilter: FILTER_NEAREST,
10485
+ addressU: ADDRESS_CLAMP_TO_EDGE,
10486
+ addressV: ADDRESS_CLAMP_TO_EDGE
10487
+ });
10488
+ this.target = new RenderTarget({
10489
+ name: 'sse-splat-depth-snapshot',
10490
+ colorBuffer: this.texture,
10491
+ depth: false
10492
+ });
10493
+ this.snapshotFrame = -1;
10198
10494
  }
10199
-
10200
- let childMask = (node >> 24u) & 0xFFu;
10201
-
10202
- // childMask == 0 means this is a mixed leaf node
10203
- if (childMask == 0u) {
10204
- let leafIdx = node & 0x00FFFFFFu;
10205
- return vec2u(2u + leafIdx, 0u);
10495
+ else if (this.texture.width !== width || this.texture.height !== height) {
10496
+ this.target.resize(width, height);
10497
+ this.snapshotFrame = -1;
10206
10498
  }
10207
-
10208
- // Determine octant at this level
10209
- let bitX = (u32(bx) >> level) & 1u;
10210
- let bitY = (u32(by) >> level) & 1u;
10211
- let bitZ = (u32(bz) >> level) & 1u;
10212
- let octant = (bitZ << 2u) | (bitY << 1u) | bitX;
10213
-
10214
- // Check if child exists
10215
- if ((childMask & (1u << octant)) == 0u) {
10216
- return vec2u(0u, level);
10499
+ const current = this.snapshotFrame === frame.id ||
10500
+ (!latest && this.snapshotFrame >= 0 && sameCamera(this.snapshotCamera, frame.camera));
10501
+ if (!current) {
10502
+ const { scope } = device;
10503
+ const { camera } = frame;
10504
+ scope.resolve('splatDepth').setValue(this.renderer.frameDepthTexture);
10505
+ scope
10506
+ .resolve('depthViewParams')
10507
+ .setValue([frame.clipZ[0], frame.clipZ[1], camera.nearClip, camera.farClip]);
10508
+ scope
10509
+ .resolve('snapshotParams')
10510
+ .setValue([
10511
+ frame.width / width,
10512
+ frame.height / height,
10513
+ camera.projection === PROJECTION_ORTHOGRAPHIC ? 1 : 0,
10514
+ 0
10515
+ ]);
10516
+ device.setBlendState(BlendState.NOBLEND);
10517
+ drawQuadWithShader(device, this.target, this.shader);
10518
+ this.snapshotFrame = frame.id;
10519
+ copyCameraSnapshot(frame.camera, this.snapshotCamera);
10520
+ this.renders++;
10521
+ }
10522
+ // the renderer rewrites its snapshot every frame, and frames render while a pick awaits
10523
+ // its readback: the pick unprojects with a copy of the camera its depth was drawn with
10524
+ const pickCamera = createPickCameraSnapshot();
10525
+ copyCameraSnapshot(frame.camera, pickCamera);
10526
+ return { width, height, pickCamera };
10527
+ }
10528
+ // The frame to pick from: the last one rendered if the camera has not moved since, else
10529
+ // one requested now. Its own camera unprojects it, whatever the live camera does meanwhile.
10530
+ async prepare() {
10531
+ if (this.queue.released)
10532
+ return null;
10533
+ let frame = this.renderer.depthFrame;
10534
+ if (!frame || !cameraMatches(frame.camera, this.camera)) {
10535
+ this.app.renderNextFrame = true;
10536
+ await this.nextFrame();
10537
+ frame = this.renderer.depthFrame;
10538
+ if (!frame || this.queue.released)
10539
+ return null;
10217
10540
  }
10218
-
10219
- // Compute child index
10220
- let baseOffset = node & 0x00FFFFFFu;
10221
- let prefix = (1u << octant) - 1u;
10222
- let childOffset = countOneBits(childMask & prefix);
10223
- nodeIndex = baseOffset + childOffset;
10224
-
10225
- if (level == 0u) { break; }
10226
- level -= 1u;
10541
+ return this.snapshot(frame, true);
10542
+ }
10543
+ // Read the snapshot around a pixel, `margin` pixels each way, clamped to it.
10544
+ async readAround(screenX, screenY, margin, width, height) {
10545
+ const blockX = Math.max(0, screenX - margin);
10546
+ const blockY = Math.max(0, screenY - margin);
10547
+ const blockWidth = Math.min(width - 1, screenX + margin) - blockX + 1;
10548
+ const blockHeight = Math.min(height - 1, screenY + margin) - blockY + 1;
10549
+ const pixels = (await this.texture.read(blockX, blockY, blockWidth, blockHeight, {
10550
+ renderTarget: this.target,
10551
+ immediate: true
10552
+ }));
10553
+ return (x, y, trial) => {
10554
+ const localX = x - blockX;
10555
+ const localY = y - blockY;
10556
+ if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
10557
+ return null;
10558
+ }
10559
+ return half2Float(pixels[(localY * blockWidth + localX) * 4 + trial]);
10560
+ };
10227
10561
  }
10228
-
10229
- // Reached leaf level
10230
- let node = nodes[nodeIndex];
10231
- if (node == SOLID_LEAF_MARKER) {
10232
- return vec2u(1u, 0u);
10562
+ pick(x, y) {
10563
+ return this.queue.run(async () => {
10564
+ const sample = await this.prepare();
10565
+ if (!sample)
10566
+ return null;
10567
+ const { width, height, pickCamera } = sample;
10568
+ const screenX = clampPixel(x, width);
10569
+ const screenY = clampPixel(y, height);
10570
+ const depthAt = await this.readAround(screenX, screenY, SURFACE_RADIUS_PX, width, height);
10571
+ const depth = surfaceDepth(depthAt, screenX, screenY);
10572
+ return depth === null ? null : getWorldPoint(pickCamera, screenX, screenY, width, height, depth);
10573
+ }, null);
10233
10574
  }
10234
- let leafIdx = node & 0x00FFFFFFu;
10235
- return vec2u(2u + leafIdx, 0u);
10575
+ pickSurface(x, y) {
10576
+ return this.queue.run(async () => {
10577
+ const sample = await this.prepare();
10578
+ if (!sample)
10579
+ return null;
10580
+ const { width, height, pickCamera } = sample;
10581
+ const screenX = clampPixel(x, width);
10582
+ const screenY = clampPixel(y, height);
10583
+ const depthAt = await this.readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
10584
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
10585
+ }, null);
10586
+ }
10587
+ pickVisibility(points, radius) {
10588
+ if (points.length === 0) {
10589
+ return Promise.resolve([]);
10590
+ }
10591
+ return this.queue.run(async () => {
10592
+ const sample = await this.prepare();
10593
+ if (!sample)
10594
+ return points.map(() => null);
10595
+ const { width, height, pickCamera } = sample;
10596
+ const r = Math.max(1, Math.round(radius * height));
10597
+ return Promise.all(points.map(async ({ x, y, depth }) => {
10598
+ const screenX = clampPixel(x, width);
10599
+ const screenY = clampPixel(y, height);
10600
+ const depthAt = await this.readAround(screenX, screenY, r, width, height);
10601
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
10602
+ }));
10603
+ }, points.map(() => null));
10604
+ }
10605
+ // The last frame's snapshot, for the debug overlay; it asks after each frame, so the frame
10606
+ // is the current camera's.
10607
+ renderView() {
10608
+ if (this.queue.released)
10609
+ return null;
10610
+ const frame = this.renderer.depthFrame;
10611
+ if (!frame || !this.snapshot(frame, false))
10612
+ return null;
10613
+ return { texture: this.texture, renders: this.renders };
10614
+ }
10615
+ release() {
10616
+ this.queue.released = true;
10617
+ for (const done of [...this.waiters])
10618
+ done();
10619
+ this.target?.destroy();
10620
+ this.texture?.destroy();
10621
+ this.target = null;
10622
+ this.texture = null;
10623
+ this.shader.destroy();
10624
+ }
10625
+ }
10626
+
10627
+ // The resident set: which splats the engine's LOD and streaming have made resident this
10628
+ // frame, and where each node's data sits. The engine keeps octree LOD, the budget, file
10629
+ // streaming and the block allocator (one slot range per node); the stochastic renderer
10630
+ // consumes its decisions and owns everything after them.
10631
+ //
10632
+ // Read through the engine's internal (@ignore) gsplat-unified classes until the public
10633
+ // `world:update` api lands (engine change E3 in the plan). Every internal shape used is
10634
+ // narrowed here to the members this file reads, so a change in the engine fails in one place.
10635
+ const tmpVec = new Vec3();
10636
+ const tmpVec2$1 = new Vec3();
10637
+ /**
10638
+ * Hooks the engine's per-frame gsplat update for one camera and layer and exposes the resident
10639
+ * set. `frame:ready` fires inside `GSplatManager.update()` after `world.bake()` and after the
10640
+ * engine's own render prep (both in 2.22.4 and on main), so a listener sees the baked state of
10641
+ * the current frame and can replace that prep.
10642
+ */
10643
+ class EngineResidentSetProvider {
10644
+ app;
10645
+ camera;
10646
+ layer;
10647
+ handles = [];
10648
+ callbacks = new Set();
10649
+ set = null;
10650
+ // the engine renderers this provider has switched off, with their original prep function
10651
+ takenOver = new Map();
10652
+ // while false the engine keeps rendering the splats itself (XR), and the hook stays quiet
10653
+ active = true;
10654
+ constructor(app, camera, layer) {
10655
+ this.app = app;
10656
+ this.camera = camera;
10657
+ this.layer = layer;
10658
+ const system = app.systems.gsplat;
10659
+ // fires when a manager is created for a camera and layer, before its first update:
10660
+ // the earliest point to switch the engine's own renderer off, so it never allocates
10661
+ // its projector, sort and draw resources
10662
+ this.handles.push(system.on('material:created', (material, cam, lyr) => {
10663
+ if (cam === this.camera && lyr === this.layer && this.active) {
10664
+ const manager = this.manager();
10665
+ if (manager)
10666
+ this.takeOver(manager);
10667
+ }
10668
+ }));
10669
+ this.handles.push(system.on('frame:ready', (cam, lyr) => {
10670
+ if (cam !== this.camera || lyr !== this.layer || !this.active)
10671
+ return;
10672
+ const manager = this.manager();
10673
+ if (!manager)
10674
+ return;
10675
+ this.takeOver(manager);
10676
+ const state = manager.world.currentState;
10677
+ if (!state)
10678
+ return;
10679
+ const changed = !this.set || this.set.version !== state.version;
10680
+ if (changed) {
10681
+ this.set = buildResidentSet(state);
10682
+ }
10683
+ for (const cb of this.callbacks) {
10684
+ cb(this.set, changed, manager);
10685
+ }
10686
+ }));
10687
+ }
10688
+ /** The engine manager for this camera and layer, once the engine has created it. */
10689
+ manager() {
10690
+ const director = this.app.renderer.gsplatDirector;
10691
+ // the director keys its cameras by the scene camera, not the component
10692
+ const cameraData = director?.camerasMap.get(this.camera.camera);
10693
+ return cameraData?.layersMap.get(this.layer)?.gsplatManager ?? null;
10694
+ }
10695
+ /** Hand the splats back to the engine's renderer (false), or take them over again (true). */
10696
+ setActive(value) {
10697
+ if (this.active === value)
10698
+ return;
10699
+ this.active = value;
10700
+ if (value) {
10701
+ const manager = this.manager();
10702
+ if (manager)
10703
+ this.takeOver(manager);
10704
+ }
10705
+ else {
10706
+ this.restore();
10707
+ }
10708
+ }
10709
+ onFrame(cb) {
10710
+ this.callbacks.add(cb);
10711
+ return () => this.callbacks.delete(cb);
10712
+ }
10713
+ /**
10714
+ * Switch the engine's own splat rendering off for this manager: its render prep returns
10715
+ * false (so the hybrid renderer never builds its projector, sorter or cache) and its mesh
10716
+ * instance is hidden. The world (LOD, streaming, allocation, the work-buffer copy) keeps
10717
+ * running. Reversed by {@link restore}.
10718
+ */
10719
+ takeOver(manager) {
10720
+ const renderer = manager.renderer;
10721
+ if (!this.takenOver.has(renderer)) {
10722
+ this.takenOver.set(renderer, renderer.prepareRenderView);
10723
+ renderer.prepareRenderView = () => false;
10724
+ }
10725
+ if (renderer.meshInstance)
10726
+ renderer.meshInstance.visible = false;
10727
+ // The manager's first update runs its render prep before frame:ready fires, and
10728
+ // material:created fires before the layer data holds the manager, so the engine's
10729
+ // projector, sorter and compaction get allocated once (32 bytes a splat and more).
10730
+ // Release them; the engine recreates them lazily if it renders again (XR, restore)
10731
+ // or picks through its sorted path.
10732
+ for (const key of ['gpuSorter', 'projector', 'intervalCompaction']) {
10733
+ const resource = renderer[key];
10734
+ if (resource) {
10735
+ resource.destroy();
10736
+ renderer[key] = null;
10737
+ }
10738
+ }
10739
+ }
10740
+ restore() {
10741
+ for (const [renderer, original] of this.takenOver) {
10742
+ renderer.prepareRenderView = original;
10743
+ if (renderer.meshInstance)
10744
+ renderer.meshInstance.visible = true;
10745
+ }
10746
+ this.takenOver.clear();
10747
+ }
10748
+ destroy() {
10749
+ this.restore();
10750
+ for (const handle of this.handles)
10751
+ handle.off();
10752
+ this.handles.length = 0;
10753
+ this.callbacks.clear();
10754
+ this.set = null;
10755
+ }
10756
+ }
10757
+ // Flatten the engine world state into files and nodes with world-space bounds.
10758
+ const buildResidentSet = (state) => {
10759
+ const files = [];
10760
+ const nodes = [];
10761
+ const spheres = [];
10762
+ const pushNode = (node, cx, cy, cz, radius) => {
10763
+ nodes.push(node);
10764
+ spheres.push(cx, cy, cz, radius);
10765
+ };
10766
+ state.splats.forEach((info, fileIndex) => {
10767
+ const modelMatrix = info.node.getWorldTransform().clone();
10768
+ const scale = modelMatrix.getScale(tmpVec2$1);
10769
+ const maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
10770
+ const file = {
10771
+ fileIndex,
10772
+ lodIndex: info.lodIndex,
10773
+ nodes: [],
10774
+ modelMatrix,
10775
+ resource: info.resource
10776
+ };
10777
+ const numIntervals = info.intervals.length / 2;
10778
+ if (numIntervals === 0) {
10779
+ // a single-file resource: one range covering it whole, bounded by its aabb
10780
+ const node = {
10781
+ fileIndex,
10782
+ nodeIndex: nodes.length,
10783
+ lodIndex: info.lodIndex,
10784
+ sourceBase: 0,
10785
+ count: info.activeSplats,
10786
+ slotBase: info.intervalOffsets[0] ?? 0,
10787
+ allocId: info.allocId
10788
+ };
10789
+ modelMatrix.transformPoint(info.aabb.center, tmpVec);
10790
+ const he = info.aabb.halfExtents;
10791
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, he.length() * maxScale);
10792
+ file.nodes.push(node);
10793
+ }
10794
+ else {
10795
+ for (let j = 0; j < numIntervals; j++) {
10796
+ const start = info.intervals[j * 2];
10797
+ const end = info.intervals[j * 2 + 1];
10798
+ const nodeIndex = info.intervalNodeIndices[j];
10799
+ const node = {
10800
+ fileIndex,
10801
+ nodeIndex: nodes.length,
10802
+ lodIndex: info.lodIndex,
10803
+ sourceBase: start,
10804
+ count: end - start,
10805
+ slotBase: info.intervalOffsets[j] ?? 0,
10806
+ allocId: info.intervalAllocIds[j]
10807
+ };
10808
+ const sphere = info.octreeNodes?.[nodeIndex]?.boundingSphere;
10809
+ if (sphere) {
10810
+ tmpVec.set(sphere.x, sphere.y, sphere.z);
10811
+ modelMatrix.transformPoint(tmpVec, tmpVec);
10812
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, sphere.w * maxScale);
10813
+ }
10814
+ else {
10815
+ // no bounds: never culled
10816
+ pushNode(node, 0, 0, 0, Infinity);
10817
+ }
10818
+ file.nodes.push(node);
10819
+ }
10820
+ }
10821
+ files.push(file);
10822
+ });
10823
+ return {
10824
+ version: state.version,
10825
+ activeSplats: state.totalActiveSplats,
10826
+ slotCapacity: state.textureSize * state.textureSize,
10827
+ fullRebuild: state.fullRebuild,
10828
+ changedAllocIds: state.needsUploadIds,
10829
+ files,
10830
+ nodes,
10831
+ nodeSpheres: new Float32Array(spheres)
10832
+ };
10833
+ };
10834
+
10835
+ // Single-thread pass turning the projector's survivor count into the indexed indirect draw
10836
+ // arguments for the raster pass and the indirect dispatch size of the order scatter. Nothing
10837
+ // comes back to the cpu, so a frame never stalls on the count. Entry layouts match the engine's
10838
+ // indirect draw buffer (5 u32 per slot) and indirect dispatch buffer (3 u32 per slot).
10839
+ const argsWGSL = /* wgsl */ `
10840
+ struct DrawIndexedIndirectArgs {
10841
+ indexCount: u32,
10842
+ instanceCount: u32,
10843
+ firstIndex: u32,
10844
+ baseVertex: i32,
10845
+ firstInstance: u32
10846
+ }
10847
+
10848
+ struct ArgsUniforms {
10849
+ drawSlot: u32,
10850
+ indexCount: u32,
10851
+ quadsPerInstance: u32,
10852
+ dispatchSlot: u32,
10853
+ scatterWorkgroupSize: u32
10854
+ }
10855
+
10856
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
10857
+ @group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>;
10858
+ @group(0) @binding(2) var<storage, read_write> indirectDispatchArgs: array<u32>;
10859
+ @group(0) @binding(3) var<uniform> uniforms: ArgsUniforms;
10860
+
10861
+ @compute @workgroup_size(1)
10862
+ fn main() {
10863
+ let count = counter[0];
10864
+ indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs(
10865
+ uniforms.indexCount,
10866
+ (count + uniforms.quadsPerInstance - 1u) / uniforms.quadsPerInstance,
10867
+ 0u,
10868
+ 0,
10869
+ 0u
10870
+ );
10871
+ // the scatter: one workgroup per scatterWorkgroupSize survivors, 2D past the 65535 limit
10872
+ let groups = (count + uniforms.scatterWorkgroupSize - 1u) / uniforms.scatterWorkgroupSize;
10873
+ let x = max(min(groups, 65535u), 1u);
10874
+ let base = uniforms.dispatchSlot * 3u;
10875
+ indirectDispatchArgs[base] = x;
10876
+ indirectDispatchArgs[base + 1u] = (groups + x - 1u) / x;
10877
+ indirectDispatchArgs[base + 2u] = 1u;
10878
+ }
10879
+ `;
10880
+
10881
+ // Temporal accumulation for the stochastic frame. Each frame the raster leaves one sample per
10882
+ // pixel (a colour where a splat's fragment survived its coverage test, nothing otherwise) and
10883
+ // the nearest surviving depth; this pass folds it into a per-pixel history of premultiplied
10884
+ // colour and coverage, so a still camera converges to the expected image over a few hundred
10885
+ // frames and a moving one keeps most of that history by reprojecting it.
10886
+ //
10887
+ // Reprojection uses the sample's own depth: the pixel's world point is carried into the
10888
+ // previous view and the history is fetched there, clamped to the colours this frame's
10889
+ // neighbourhood holds so a stale colour cannot survive a disocclusion. A pixel with no sample
10890
+ // this frame reprojects through the mean depth its own history remembers, so coverage fades out
10891
+ // where a surface has moved away rather than smearing into the background.
10892
+ //
10893
+ // The history is 12 bytes a pixel (24 with the ping-pong). The colour is the running mean as
10894
+ // 16-bit fixed point: a half float cannot hold it, since its steps in [0.5, 1) are 1 / 2048 and
10895
+ // the 1 / N step of a 256-sample mean rounds away once a sample lies within 1 / 16 of the mean
10896
+ // (an error floor of about 5 rms in 8-bit units), while fixed point steps by 1 / 65535
10897
+ // everywhere, so the same step only rounds away within half an 8-bit level of the mean. The
10898
+ // depth record is the mean view depth of the pixel's samples and their count in one 32-bit word.
10899
+ // the most samples the history's count field holds
10900
+ const TAA_MAX_COUNT = 511;
10901
+ const taaVertexWGSL = /* wgsl */ `
10902
+ attribute vertex_position: vec2f;
10903
+
10904
+ @vertex
10905
+ fn vertexMain(input: VertexInput) -> VertexOutput {
10906
+ var output: VertexOutput;
10907
+ output.position = vec4f(vertex_position, 0.0, 1.0);
10908
+ return output;
10909
+ }
10910
+ `;
10911
+ // The history's encoding, shared with the compose that reads it
10912
+ const taaHistoryWGSL = /* wgsl */ `
10913
+ const TAA_COLOR_SCALE = 65535.0;
10914
+
10915
+ fn decodeColor(v: vec4u) -> vec4f {
10916
+ return vec4f(v) / TAA_COLOR_SCALE;
10917
+ }
10918
+
10919
+ // premultiplied colour and coverage: coverage in [0, 1] and colour within it (the Catmull-Rom
10920
+ // fetch over- and undershoots both), rounded to the nearest step
10921
+ fn encodeColor(c: vec4f) -> vec4u {
10922
+ let a = clamp(c.a, 0.0, 1.0);
10923
+ return vec4u(round(vec4f(clamp(c.rgb, vec3f(0.0), vec3f(a)), a) * TAA_COLOR_SCALE));
10924
+ }
10925
+
10926
+ struct HistoryInfo {
10927
+ depth: f32,
10928
+ count: f32
10929
+ }
10930
+
10931
+ // The mean view depth keeps the float's exponent and top 15 mantissa bits, rounded: a relative
10932
+ // step of 2^-15, which stalls a 256-sample mean only within 0.4 % of the depth (the depth steers
10933
+ // the reprojection, where that is far below a pixel). The count takes the low 9 bits
10934
+ fn decodeInfo(v: u32) -> HistoryInfo {
10935
+ var info: HistoryInfo;
10936
+ info.depth = bitcast<f32>((v >> 9u) << 8u);
10937
+ info.count = f32(v & ${TAA_MAX_COUNT}u);
10938
+ return info;
10939
+ }
10940
+
10941
+ fn encodeInfo(depth: f32, count: f32) -> u32 {
10942
+ let bits = bitcast<u32>(max(depth, 0.0));
10943
+ return (((bits + 0x80u) >> 8u) << 9u) | min(u32(count), ${TAA_MAX_COUNT}u);
10944
+ }
10945
+ `;
10946
+ const taaFragmentWGSL = /* wgsl */ `
10947
+ var curColor: texture_2d<f32>;
10948
+ var curColorSampler: sampler;
10949
+ var curDepth: texture_depth_2d;
10950
+ // premultiplied colour and coverage, unorm16 (decodeColor)
10951
+ var histColor: texture_2d<u32>;
10952
+ // the mean view depth of the pixel's samples and their count, in the previous frame's view
10953
+ // depths (decodeInfo)
10954
+ var histInfo: texture_2d<u32>;
10955
+
10956
+ // the camera's world transform (the inverse view), and its projection's x and y terms: x, y the
10957
+ // scales, z, w the offsets (the column that multiplies view z for a perspective camera, the
10958
+ // translation for an orthographic one)
10959
+ uniform cameraWorld: mat4x4f;
10960
+ uniform unproject: vec4f;
10961
+ uniform prevViewProj: mat4x4f;
10962
+ uniform prevView: mat4x4f;
10963
+ // clip z = a * viewDepth + b over w = viewDepth (x, y); z: 1 for an orthographic camera
10964
+ uniform clipZParams: vec4f;
10965
+ // x: sample cap, y: 1 when the history holds the previous frame, z: 1 when the camera moved
10966
+ // since that frame, w: the frames the camera has rested, this one included (0 on a frame whose
10967
+ // resident set changed)
10968
+ uniform taaParams: vec4f;
10969
+ // width, height, 1 / width, 1 / height
10970
+ uniform taaViewport: vec4f;
10971
+ // x: -1 when the target's rows run bottom-up (an offscreen target), else 1; y: the colour
10972
+ // clamp width in neighbourhood standard deviations (0: no clamp); z: 1 when the raster's
10973
+ // thresholds are quad-stratified
10974
+ uniform taaControl: vec4f;
10975
+ // x: 1 for a Catmull-Rom history fetch while moving (0: bilinear); y: 1 to reproject through
10976
+ // the pixel's accumulated mean depth rather than this frame's sample depth; z: image motion in
10977
+ // pixels a frame that halves the moving sample cap (0: fixed cap)
10978
+ uniform taaFilter: vec4f;
10979
+ // 1: write the accumulation state instead of colour (r: count / cap, g: history accepted,
10980
+ // b: the camera moved since the previous frame)
10981
+ uniform taaDebug: f32;
10982
+
10983
+ ${taaHistoryWGSL}
10984
+
10985
+ fn viewDepthOf(z: f32) -> f32 {
10986
+ let p = uniform.clipZParams;
10987
+ let dz = z - p.x;
10988
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
10989
+ return select(p.y / safeDz, (z - p.y) / p.x, p.z != 0.0);
10990
+ }
10991
+
10992
+ struct Reprojected {
10993
+ valid: bool,
10994
+ uv: vec2f,
10995
+ prevDepth: f32
10996
+ }
10997
+
10998
+ // The previous frame's view depth and texture coordinate of this pixel's point at a view
10999
+ // depth. The point is built in view space from the depth and the projection's x and y terms,
11000
+ // then moved by the camera's rigid transform: through the inverse view-projection instead, a
11001
+ // near plane at 1e-4 of the depth (the viewer's floor once the camera is inside the scene
11002
+ // bound) leaves a 32-bit float about three digits of the point, a pixel of error that changes
11003
+ // with every frame's sample depths and shakes the history.
11004
+ fn reproject(pix: vec2i, viewDepth: f32) -> Reprojected {
11005
+ var r: Reprojected;
11006
+ let flip = uniform.taaControl.x;
11007
+ let uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
11008
+ let ndc = vec2f(uv.x * 2.0 - 1.0, flip * (1.0 - 2.0 * uv.y));
11009
+ let u = uniform.unproject;
11010
+ let viewXY = select((ndc + u.zw) * viewDepth, ndc - u.zw, uniform.clipZParams.z != 0.0) / u.xy;
11011
+ let world = (uniform.cameraWorld * vec4f(viewXY, -viewDepth, 1.0)).xyz;
11012
+ let prevClip = uniform.prevViewProj * vec4f(world, 1.0);
11013
+ r.prevDepth = -(uniform.prevView * vec4f(world, 1.0)).z;
11014
+ r.valid = prevClip.w > 0.0;
11015
+ let prevNdc = prevClip.xy / max(prevClip.w, 1e-9);
11016
+ r.uv = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * flip * 0.5);
11017
+ r.valid = r.valid && all(r.uv >= vec2f(0.0)) && all(r.uv <= vec2f(1.0));
11018
+ return r;
11019
+ }
11020
+
11021
+ // the premultiplied sample at a texel: its colour where a fragment landed, nothing otherwise
11022
+ fn sampleAt(pix: vec2i, dims: vec2i) -> vec4f {
11023
+ let p = clamp(pix, vec2i(0), dims - vec2i(1));
11024
+ let c = textureLoad(curColor, p, 0);
11025
+ let z = textureLoad(curDepth, p, 0);
11026
+ return select(vec4f(0.0), vec4f(c.rgb, 1.0), c.a > 0.0 && z < 1.0);
11027
+ }
11028
+
11029
+ // The mean of the 2x2 quad's samples, bilinear between quad centres (the compose's resolve of
11030
+ // the raster's quad-stratified thresholds): four samples a pixel, at a little sharpness, for
11031
+ // the frames where the history is too short to carry the noise on its own
11032
+ fn quadSample(pix: vec2i, dims: vec2i) -> vec4f {
11033
+ let size = vec2f(dims);
11034
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
11035
+ let q0 = floor(u);
11036
+ let f = u - q0;
11037
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
11038
+ let step = vec2f(2.0) / size;
11039
+ let a = textureSampleLevel(curColor, curColorSampler, uv, 0.0);
11040
+ let b = textureSampleLevel(curColor, curColorSampler, uv + vec2f(step.x, 0.0), 0.0);
11041
+ let c = textureSampleLevel(curColor, curColorSampler, uv + vec2f(0.0, step.y), 0.0);
11042
+ let d = textureSampleLevel(curColor, curColorSampler, uv + step, 0.0);
11043
+ let m = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
11044
+ // the raster leaves empty texels transparent black, so the mean is premultiplied coverage
11045
+ return vec4f(m.rgb, m.a);
11046
+ }
11047
+
11048
+ fn historyTexel(p: vec2i, dims: vec2i) -> vec4f {
11049
+ return decodeColor(textureLoad(histColor, clamp(p, vec2i(0), dims - vec2i(1)), 0));
11050
+ }
11051
+
11052
+ // Catmull-Rom fetch of the history: sharper than bilinear, whose blur compounds over the
11053
+ // frames a moving history lives. Its lobes over- and undershoot; the encoding clamps both
11054
+ fn historyCubicAt(uv: vec2f, dims: vec2i) -> vec4f {
11055
+ let p = uv * vec2f(dims) - vec2f(0.5);
11056
+ let i0 = vec2i(floor(p));
11057
+ let f = p - floor(p);
11058
+ let f2 = f * f;
11059
+ let f3 = f2 * f;
11060
+ // Catmull-Rom weights for taps at -1, 0, 1, 2
11061
+ let w0 = -0.5 * f3 + f2 - 0.5 * f;
11062
+ let w1 = 1.5 * f3 - 2.5 * f2 + vec2f(1.0);
11063
+ let w2 = -1.5 * f3 + 2.0 * f2 + 0.5 * f;
11064
+ let w3 = 0.5 * f3 - 0.5 * f2;
11065
+ let wx = array<f32, 4>(w0.x, w1.x, w2.x, w3.x);
11066
+ let wy = array<f32, 4>(w0.y, w1.y, w2.y, w3.y);
11067
+ var sum = vec4f(0.0);
11068
+ for (var y = 0; y < 4; y++) {
11069
+ for (var x = 0; x < 4; x++) {
11070
+ sum += historyTexel(i0 + vec2i(x - 1, y - 1), dims) * (wx[x] * wy[y]);
11071
+ }
11072
+ }
11073
+ return sum;
11074
+ }
11075
+
11076
+ // bilinear fetch of the history
11077
+ fn historyAt(uv: vec2f, dims: vec2i) -> vec4f {
11078
+ let p = uv * vec2f(dims) - vec2f(0.5);
11079
+ let i0 = vec2i(floor(p));
11080
+ let f = p - floor(p);
11081
+ let a = historyTexel(i0, dims);
11082
+ let b = historyTexel(i0 + vec2i(1, 0), dims);
11083
+ let c = historyTexel(i0 + vec2i(0, 1), dims);
11084
+ let d = historyTexel(i0 + vec2i(1, 1), dims);
11085
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
11086
+ }
11087
+
11088
+ @fragment
11089
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
11090
+ var output: FragmentOutput;
11091
+ let pix = vec2i(pcPosition.xy);
11092
+ let dims = vec2i(textureDimensions(curColor));
11093
+ let cur = textureLoad(curColor, pix, 0);
11094
+ let z = textureLoad(curDepth, pix, 0);
11095
+ let hit = cur.a > 0.0 && z < 1.0;
11096
+ let d = viewDepthOf(z);
11097
+
11098
+ let own = decodeInfo(textureLoad(histInfo, pix, 0).x);
11099
+ let maxCount = uniform.taaParams.x;
11100
+ let historyValid = uniform.taaParams.y > 0.5;
11101
+ let moving = uniform.taaParams.z > 0.5;
11102
+ // still: this pixel's own sample, so the history converges to full resolution; moving:
11103
+ // the quad's four
11104
+ var sample = select(vec4f(0.0), vec4f(cur.rgb, 1.0), hit);
11105
+ if (moving && uniform.taaControl.z > 0.5) {
11106
+ sample = quadSample(pix, dims);
11107
+ }
11108
+
11109
+ // Where to look in the history: through this frame's sample, or, with no sample, through
11110
+ // the depth this pixel's own history remembers, so an emptied pixel fades rather than
11111
+ // holding a stale colour
11112
+ var r: Reprojected;
11113
+ r.valid = false;
11114
+ var carryDepth = 0.0;
11115
+ if (!moving) {
11116
+ // a resting camera maps every pixel onto itself: the exact texel, not the round trip
11117
+ // through the matrices, whose rounding would blur the history a little every frame
11118
+ r.valid = true;
11119
+ r.uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
11120
+ r.prevDepth = select(own.depth, d, hit);
11121
+ carryDepth = r.prevDepth;
11122
+ } else if (uniform.taaFilter.y > 0.5 && own.count > 0.5) {
11123
+ // through the depth the pixel's history has settled on: one stochastic sample's depth
11124
+ // is one layer of the mixture the history holds, and reprojecting the mixture through
11125
+ // a different layer every frame smears it by their parallax
11126
+ r = reproject(pix, own.depth);
11127
+ carryDepth = own.depth;
11128
+ } else if (hit) {
11129
+ r = reproject(pix, d);
11130
+ carryDepth = d;
11131
+ } else if (own.count > 0.5) {
11132
+ r = reproject(pix, own.depth);
11133
+ carryDepth = own.depth;
11134
+ }
11135
+ r.valid = r.valid && historyValid;
11136
+
11137
+ var hist = vec4f(0.0);
11138
+ var info: HistoryInfo;
11139
+ var accepted = false;
11140
+ if (r.valid) {
11141
+ // at rest the exact texel; moving, a filtered fetch of the reprojected position
11142
+ if (!moving) {
11143
+ hist = decodeColor(textureLoad(histColor, pix, 0));
11144
+ info = own;
11145
+ } else {
11146
+ if (uniform.taaFilter.x > 0.5) {
11147
+ hist = historyCubicAt(r.uv, dims);
11148
+ } else {
11149
+ hist = historyAt(r.uv, dims);
11150
+ }
11151
+ info = decodeInfo(textureLoad(histInfo, clamp(vec2i(r.uv * vec2f(dims)), vec2i(0), dims - vec2i(1)), 0).x);
11152
+ }
11153
+ // a resting camera cannot disocclude anything, so every sample is accepted and the
11154
+ // pixel converges; moving, the colour clamp below keeps a disoccluded history out
11155
+ accepted = info.count > 0.5;
11156
+ }
11157
+
11158
+ var color: vec4f;
11159
+ var mean: f32;
11160
+ var count: f32;
11161
+ if (!accepted) {
11162
+ color = sample;
11163
+ mean = d;
11164
+ count = select(0.0, 1.0, hit);
11165
+ // at rest a pixel with no hit yet has still been sampled on every rest frame, so its
11166
+ // first hit is one of that many samples: at full weight a rare hit would flash to full
11167
+ // coverage, and freeze there once the viewer stops rendering. Its depth is the hit's
11168
+ if (hit && !moving && historyValid) {
11169
+ count = clamp(uniform.taaParams.w, 1.0, maxCount);
11170
+ color = sample / count;
11171
+ }
11172
+ } else {
11173
+ // moving, the history is clamped to the colours this frame's neighbourhood holds, so a
11174
+ // stale colour cannot survive where nothing like it is drawn any more
11175
+ if (moving && uniform.taaControl.y > 0.0) {
11176
+ var m1 = vec4f(0.0);
11177
+ var m2 = vec4f(0.0);
11178
+ for (var dy = -1; dy <= 1; dy++) {
11179
+ for (var dx = -1; dx <= 1; dx++) {
11180
+ let n = sampleAt(pix + vec2i(dx, dy), dims);
11181
+ m1 += n;
11182
+ m2 += n * n;
11183
+ }
11184
+ }
11185
+ let mu = m1 / 9.0;
11186
+ let sd = sqrt(max(m2 / 9.0 - mu * mu, vec4f(0.0)));
11187
+ let halfWidth = sd * uniform.taaControl.y;
11188
+ hist = clamp(hist, mu - halfWidth, mu + halfWidth);
11189
+ }
11190
+ // the faster the image moves, the shorter the history: a stochastic pixel's layers
11191
+ // reproject through one layer's depth, so their parallax smears the history by an
11192
+ // amount that grows with the motion, and a raw frame is the better estimate past it
11193
+ var cap = maxCount;
11194
+ if (moving && uniform.taaFilter.z > 0.0) {
11195
+ let speed = length(r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5));
11196
+ cap = max(2.0, maxCount / (1.0 + speed / uniform.taaFilter.z));
11197
+ }
11198
+ count = min(info.count + 1.0, cap);
11199
+ let w = 1.0 / count;
11200
+ color = mix(hist, sample, w);
11201
+ // an empty sample takes at least a step off the coverage: rounded to the nearest, a
11202
+ // decay of less than half a step holds (below cap / 2 steps, about 0.002 at the default
11203
+ // cap), so a faint pixel would keep its coverage, and the depth the compose writes for
11204
+ // it, forever. The colour follows, since the encoding keeps it within the coverage
11205
+ if (sample.a == 0.0) {
11206
+ color.a = min(color.a, max(hist.a - 1.0 / TAA_COLOR_SCALE, 0.0));
11207
+ }
11208
+ // carry the mean depth into this view: the point moved along the ray by the change in
11209
+ // its depth, then the sample joins it
11210
+ let shifted = info.depth + (carryDepth - r.prevDepth);
11211
+ mean = select(shifted, shifted + w * (d - shifted), hit);
11212
+ }
11213
+
11214
+ if (uniform.taaDebug > 1.5) {
11215
+ // the reprojection offset in pixels, 8 px full scale, centred on 0.5
11216
+ let mv = select(vec2f(0.0), r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5), r.valid);
11217
+ color = vec4f(mv / 16.0 + vec2f(0.5), select(0.0, 1.0, r.valid), 1.0);
11218
+ } else if (uniform.taaDebug > 0.5) {
11219
+ color = vec4f(count / maxCount, select(0.0, 1.0, accepted), select(0.0, 1.0, moving), 1.0);
11220
+ }
11221
+ output.color = encodeColor(color);
11222
+ output.color1 = encodeInfo(mean, count);
11223
+ return output;
11224
+ }
11225
+ `;
11226
+
11227
+ // The compose: a fullscreen quad in the World layer's transparent sublayer that blends the
11228
+ // stochastic target over the camera's target (after the skybox and opaque meshes) and writes
11229
+ // its depth, so everything drawn later depth-tests against the splats. The colour transform
11230
+ // the engine's own splat shader applies (gsplatOutputVS: tonemap and gamma, or the viewer's
11231
+ // pass-through patch under CameraFrame) runs here, once per pixel instead of once per splat.
11232
+ const composeVertexWGSL = /* wgsl */ `
11233
+ attribute vertex_position: vec2f;
11234
+
11235
+ @vertex
11236
+ fn vertexMain(input: VertexInput) -> VertexOutput {
11237
+ var output: VertexOutput;
11238
+ output.position = vec4f(vertex_position, 0.0, 1.0);
11239
+ return output;
11240
+ }
11241
+ `;
11242
+ const composeFragmentWGSL = /* wgsl */ `
11243
+ #include "gsplatOutputVS"
11244
+
11245
+ var splatColor: texture_2d<f32>;
11246
+ var splatColorSampler: sampler;
11247
+ var splatDepth: texture_depth_2d;
11248
+ // the temporally accumulated frame (premultiplied colour, coverage), when taa ran this frame
11249
+ var taaColor: texture_2d<u32>;
11250
+ // its depth record: the mean view depth of the pixel's samples and their count
11251
+ var taaInfo: texture_2d<u32>;
11252
+ // x: 1 when the splat target's rows run the other way to the camera target's; y: 1 for an
11253
+ // orthographic camera; z: 1 to read the taa history instead of the raw frame
11254
+ uniform composeParams: vec4f;
11255
+ // the splat target's depth: clip z = a * viewDepth + b over w = viewDepth (x, y), and the
11256
+ // camera's near and far (z, w) for the depth view
11257
+ uniform depthViewParams: vec4f;
11258
+ // the camera's own depth, the one written for the rest of the scene: clip z = a * viewDepth + b
11259
+ // (x, y). The splat target's far plane is at infinity where the camera's is fitted to the scene
11260
+ uniform cameraClipZ: vec4f;
11261
+
11262
+ ${taaHistoryWGSL}
11263
+
11264
+ const FAR_DEPTH = 0.999999;
11265
+
11266
+ // the splat target's depth texel of a view depth, just inside its far plane at most: the
11267
+ // raster clamps there too, since a depth of 1 reads as no sample
11268
+ fn clipZOf(viewDepth: f32) -> f32 {
11269
+ let p = uniform.depthViewParams;
11270
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
11271
+ return min(clamp(p.x * viewDepth + p.y, 0.0, w) / w, FAR_DEPTH);
11272
+ }
11273
+
11274
+ // the view depth of a splat target depth texel
11275
+ fn viewDepthOf(z: f32) -> f32 {
11276
+ let p = uniform.depthViewParams;
11277
+ let dz = z - p.x;
11278
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
11279
+ return select(p.y / safeDz, (z - p.y) / p.x, uniform.composeParams.y > 0.5);
11280
+ }
11281
+
11282
+ // A splat target depth in the camera's depth, clamped just inside the camera's far plane as the
11283
+ // engine clamps its splats: splats beyond it stay behind everything the scene draws
11284
+ fn cameraDepthOf(z: f32) -> f32 {
11285
+ let viewDepth = viewDepthOf(z);
11286
+ let c = uniform.cameraClipZ;
11287
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
11288
+ return min(clamp(c.x * viewDepth + c.y, 0.0, w) / w, FAR_DEPTH);
11289
+ }
11290
+
11291
+ @fragment
11292
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
11293
+ var output: FragmentOutput;
11294
+ let dims = vec2i(textureDimensions(splatColor));
11295
+ var pix = vec2i(pcPosition.xy);
11296
+ if (uniform.composeParams.x > 0.5) {
11297
+ pix.y = dims.y - 1 - pix.y;
11298
+ }
11299
+ pix = clamp(pix, vec2i(0), dims - vec2i(1));
11300
+
11301
+ var depth = textureLoad(splatDepth, pix, 0);
11302
+ var color: vec4f;
11303
+ if (uniform.composeParams.z > 0.5) {
11304
+ // the accumulated history: coverage in alpha, colour premultiplied by it
11305
+ color = decodeColor(textureLoad(taaColor, pix, 0));
11306
+ if (depth >= 1.0 && color.a > 0.001) {
11307
+ // covered by the history but no sample this frame, which a faint pixel sees on
11308
+ // most frames: the mean depth of the pixel's own samples, or, for a history this
11309
+ // frame started (moving, from the quad's samples), the nearest sampled neighbour's,
11310
+ // so the pixel still occludes what is behind the splats
11311
+ let info = decodeInfo(textureLoad(taaInfo, pix, 0).x);
11312
+ if (info.count > 0.5) {
11313
+ depth = clipZOf(info.depth);
11314
+ } else {
11315
+ for (var dy = -1; dy <= 1; dy++) {
11316
+ for (var dx = -1; dx <= 1; dx++) {
11317
+ depth = min(depth, textureLoad(splatDepth, clamp(pix + vec2i(dx, dy), vec2i(0), dims - vec2i(1)), 0));
11318
+ }
11319
+ }
11320
+ }
11321
+ }
11322
+ } else {
11323
+ #ifdef SSE_SPP_QUAD
11324
+ // the mean of each 2x2 quad, bilinearly interpolated between quad centres: the four
11325
+ // strata of the raster's thresholds average out to the splat's coverage. Empty texels
11326
+ // are transparent black, so the result is premultiplied coverage
11327
+ let size = vec2f(dims);
11328
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
11329
+ let q0 = floor(u);
11330
+ let f = u - q0;
11331
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
11332
+ let step = vec2f(2.0) / size;
11333
+ let a = textureSampleLevel(splatColor, splatColorSampler, uv, 0.0);
11334
+ let b = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(step.x, 0.0), 0.0);
11335
+ let c = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(0.0, step.y), 0.0);
11336
+ let d = textureSampleLevel(splatColor, splatColorSampler, uv + step, 0.0);
11337
+ color = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
11338
+ if (depth >= 1.0) {
11339
+ // no sample at this pixel but coverage from its quad: the quad's nearest depth
11340
+ let quad = (pix >> vec2u(1u)) << vec2u(1u);
11341
+ depth = min(
11342
+ min(textureLoad(splatDepth, quad, 0), textureLoad(splatDepth, min(quad + vec2i(1, 0), dims - 1), 0)),
11343
+ min(textureLoad(splatDepth, min(quad + vec2i(0, 1), dims - 1), 0), textureLoad(splatDepth, min(quad + vec2i(1, 1), dims - 1), 0))
11344
+ );
11345
+ }
11346
+ #else
11347
+ color = textureLoad(splatColor, pix, 0);
11348
+ #endif
11349
+ }
11350
+ if (color.a <= 0.001) {
11351
+ discard;
11352
+ }
11353
+ // coverage with no depth anywhere near: shown, behind everything the scene drew
11354
+ depth = min(depth, FAR_DEPTH);
11355
+
11356
+ #ifdef SSE_SHOW_DEPTH
11357
+ // the nearest sample's view depth, log-spaced between near and far, as grey
11358
+ let p = uniform.depthViewParams;
11359
+ let viewDepth = viewDepthOf(depth);
11360
+ let t = clamp(log(max(viewDepth, p.z) / p.z) / log(p.w / p.z), 0.0, 1.0);
11361
+ // 24-bit fixed point across rgb (high byte in red), so a capture can read it precisely
11362
+ let fixed = floor(t * 16777215.0);
11363
+ let hi = floor(fixed / 65536.0);
11364
+ let mid = floor((fixed - hi * 65536.0) / 256.0);
11365
+ let lo = fixed - hi * 65536.0 - mid * 256.0;
11366
+ output.color = vec4f(vec3f(hi, mid, lo) / 255.0, 1.0);
11367
+ output.fragDepth = cameraDepthOf(depth);
11368
+ return output;
11369
+ #endif
11370
+
11371
+ // un-premultiply for the output transform, then premultiply for the blend
11372
+ let gamma = color.rgb / color.a;
11373
+ let rgb = prepareOutputFromGamma(gamma, 0.0);
11374
+ output.color = vec4f(rgb * color.a, color.a);
11375
+ output.fragDepth = cameraDepthOf(depth);
11376
+ return output;
11377
+ }
11378
+ `;
11379
+
11380
+ // The projector: one 256-thread workgroup per chunk of the resident set. Each thread reads one
11381
+ // splat through the source's read code, projects it, applies the culls, and survivors append
11382
+ // themselves to a dense cache with one global atomic per workgroup. The chunk table and node
11383
+ // visibility come from the cpu (resident-set rebuild on version change, frustum cull per frame).
11384
+ /** Words per cache entry. See the layout in the plan: ndc, depth, axis1, len2|alpha|flags, rgb, popless, id. */
11385
+ const CACHE_WORDS = 7;
11386
+ const PROJECTOR_WORKGROUP_SIZE = 256;
11387
+ /** Buckets of the counting order (order:bucket); the workgroup size, so each thread owns one. */
11388
+ const ORDER_BUCKETS = PROJECTOR_WORKGROUP_SIZE;
11389
+ /** Splats per chunk-table entry; a chunk is one workgroup. */
11390
+ const CHUNK_SIZE = PROJECTOR_WORKGROUP_SIZE;
11391
+ const projectorWGSL = (readChunk, occlusion, order) => /* wgsl */ `
11392
+ struct ProjectorUniforms {
11393
+ view: mat4x4f,
11394
+ viewProj: mat4x4f,
11395
+ // the previous frame, for the occlusion cull: its view and view-projection, its clip-z
11396
+ // mapping (a, b, isOrtho, 0), viewport and focal length
11397
+ prevViewProj: mat4x4f,
11398
+ prevView: mat4x4f,
11399
+ prevClipZ: vec4f,
11400
+ viewport: vec2f,
11401
+ focal: vec2f,
11402
+ prevViewport: vec2f,
11403
+ prevFocal: vec2f,
11404
+ numChunks: u32,
11405
+ splatTextureSize: u32,
11406
+ isOrtho: u32,
11407
+ minPixelSize: f32,
11408
+ alphaClip: f32,
11409
+ minContribution: f32,
11410
+ // the occlusion grid: level 1 (8 px) and level 2 (32 px) block counts
11411
+ occBlocksX1: u32,
11412
+ occBlocksY1: u32,
11413
+ occBlocksX2: u32,
11414
+ occBlocksY2: u32,
11415
+ // 0 off, 1 level 1 only, 2 both levels
11416
+ occlusionMode: u32,
11417
+ // -1 when the previous depth texture's rows run bottom-up (an offscreen target), else 1
11418
+ prevFlip: f32,
11419
+ // the order key: bucket = (log(depth) - keyLogNear) * keyInvLogRange, over [0, 1)
11420
+ keyLogNear: f32,
11421
+ keyInvLogRange: f32,
11422
+ // first chunk-table entry of this dispatch (per-file sources dispatch one run each)
11423
+ chunkBase: u32,
11424
+ // the file's model transform, for sources that read splats in the file's own space
11425
+ model: mat4x4f,
11426
+ modelRotation: vec4f,
11427
+ modelScale: vec4f,
11428
+ cameraPosition: vec4f,
11429
+ // colour ceiling per channel: 8 keeps the cache's range, 1 clamps like the engine's 8-bit cache
11430
+ colorMax: f32,
11431
+ // 1: covariance in true pixels. 2: the engine's convention (its focal is viewport * proj[0][0],
11432
+ // twice the pixel focal), which makes its 0.3 dilation 0.075 px^2 and scales its culls
11433
+ unitScale: f32,
11434
+ // the view depths of the near plane and of the raster's far clamp
11435
+ depthNear: f32,
11436
+ depthFar: f32
11437
+ }
11438
+
11439
+ // chunk table entry: slotBase, count, node, lod | file << 16
11440
+ @group(0) @binding(0) var<storage, read> chunks: array<vec4u>;
11441
+ // one bit per node: 1 = inside the frustum this frame
11442
+ @group(0) @binding(1) var<storage, read> nodeVisible: array<u32>;
11443
+ @group(0) @binding(2) var<storage, read_write> cache: array<u32>;
11444
+ // [0] survivors this frame, [1] splats the occlusion cull removed
11445
+ @group(0) @binding(3) var<storage, read_write> counter: array<atomic<u32>>;
11446
+ @group(0) @binding(4) var<uniform> uniforms: ProjectorUniforms;
11447
+ // the previous frame's farthest depth per block, as f32 bits (see shaders/reduce.ts)
11448
+ @group(0) @binding(5) var<storage, read> occL1: array<u32>;
11449
+ @group(0) @binding(6) var<storage, read> occL2: array<u32>;
11450
+ // order:bucket: survivors per depth bucket (see shaders/order.ts)
11451
+ @group(0) @binding(7) var<storage, read_write> buckets: array<atomic<u32>>;
11452
+
11453
+ struct Splat {
11454
+ index: u32,
11455
+ uv: vec2i
11456
+ }
11457
+ var<private> splat: Splat;
11458
+ fn setSplat(idx: u32) {
11459
+ splat.index = idx;
11460
+ splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize));
11461
+ }
11462
+
11463
+ ${readChunk}
11464
+
11465
+ // quaternion (x, y, z, w) to a rotation matrix (columns)
11466
+ fn rotationMatrix(qIn: vec4f) -> mat3x3f {
11467
+ let q = normalize(qIn);
11468
+ let x = q.x;
11469
+ let y = q.y;
11470
+ let z = q.z;
11471
+ let w = q.w;
11472
+ return mat3x3f(
11473
+ vec3f(1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + w * z), 2.0 * (x * z - w * y)),
11474
+ vec3f(2.0 * (x * y - w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z + w * x)),
11475
+ vec3f(2.0 * (x * z + w * y), 2.0 * (y * z - w * x), 1.0 - 2.0 * (x * x + y * y))
11476
+ );
11477
+ }
11478
+
11479
+ struct Projected {
11480
+ valid: bool,
11481
+ occluded: bool,
11482
+ words: array<u32, ${CACHE_WORDS}>
11483
+ }
11484
+
11485
+ // The farthest depth over the (2g+1)^2 blocks around a block, on one grid level.
11486
+ fn farthestL1(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
11487
+ var farthest = 0u;
11488
+ for (var dy = -gather; dy <= gather; dy++) {
11489
+ for (var dx = -gather; dx <= gather; dx++) {
11490
+ farthest = max(farthest, occL1[u32((block.y + dy) * blocks.x + block.x + dx)]);
11491
+ }
11492
+ }
11493
+ return farthest;
11494
+ }
11495
+
11496
+ fn farthestL2(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
11497
+ var farthest = 0u;
11498
+ for (var dy = -gather; dy <= gather; dy++) {
11499
+ for (var dx = -gather; dx <= gather; dx++) {
11500
+ farthest = max(farthest, occL2[u32((block.y + dy) * blocks.x + block.x + dx)]);
11501
+ }
11502
+ }
11503
+ return farthest;
11504
+ }
11505
+
11506
+ fn project(slot: u32, file: u32) -> Projected {
11507
+ var result: Projected;
11508
+ result.valid = false;
11509
+ result.occluded = false;
11510
+
11511
+ setSplat(slot);
11512
+ let center = srcCenter();
11513
+ let opacity = srcOpacity();
11514
+ if (opacity < uniforms.alphaClip) {
11515
+ return result;
11516
+ }
11517
+
11518
+ let viewCenter = uniforms.view * vec4f(center, 1.0);
11519
+ let depth = -viewCenter.z;
11520
+ if (uniforms.isOrtho == 0u && depth <= 0.0) {
11521
+ return result;
11522
+ }
11523
+ let clip = uniforms.viewProj * vec4f(center, 1.0);
11524
+ if (clip.w == 0.0) {
11525
+ return result;
11526
+ }
11527
+
11528
+ let viewport = uniforms.viewport;
11529
+ let focal = uniforms.focal;
11530
+
11531
+ // the work buffer holds world-space splats, so the view matrix is the model-view
11532
+ let rot = srcRotation();
11533
+ let scale = srcScale();
11534
+ let linear = mat3x3f(uniforms.view[0].xyz, uniforms.view[1].xyz, uniforms.view[2].xyz);
11535
+ let gaussian = linear * rotationMatrix(vec4f(rot.yzw, rot.x)) * mat3x3f(
11536
+ vec3f(scale.x, 0.0, 0.0),
11537
+ vec3f(0.0, scale.y, 0.0),
11538
+ vec3f(0.0, 0.0, scale.z)
11539
+ );
11540
+ let row0 = vec3f(gaussian[0].x, gaussian[1].x, gaussian[2].x);
11541
+ let row1 = vec3f(gaussian[0].y, gaussian[1].y, gaussian[2].y);
11542
+ let row2 = vec3f(gaussian[0].z, gaussian[1].z, gaussian[2].z);
11543
+ let c00 = dot(row0, row0);
11544
+ let c01 = dot(row0, row1);
11545
+ let c02 = dot(row0, row2);
11546
+ let c11 = dot(row1, row1);
11547
+ let c12 = dot(row1, row2);
11548
+ let c22 = dot(row2, row2);
11549
+
11550
+ var cov00: f32;
11551
+ var cov01: f32;
11552
+ var cov11: f32;
11553
+ if (uniforms.isOrtho != 0u) {
11554
+ cov00 = focal.x * focal.x * c00;
11555
+ cov01 = focal.x * focal.y * c01;
11556
+ cov11 = focal.y * focal.y * c11;
11557
+ } else {
11558
+ let safeDepth = max(depth, 0.001);
11559
+ let invDepth = 1.0 / safeDepth;
11560
+ let jx0 = focal.x * invDepth;
11561
+ let jx2 = focal.x * viewCenter.x * invDepth * invDepth;
11562
+ let jy1 = focal.y * invDepth;
11563
+ let jy2 = focal.y * viewCenter.y * invDepth * invDepth;
11564
+ let u00 = jx0 * c00 + jx2 * c02;
11565
+ let u01 = jx0 * c01 + jx2 * c12;
11566
+ let u02 = jx0 * c02 + jx2 * c22;
11567
+ let u11 = jy1 * c11 + jy2 * c12;
11568
+ let u12 = jy1 * c12 + jy2 * c22;
11569
+ cov00 = u00 * jx0 + u02 * jx2;
11570
+ cov01 = u01 * jy1 + u02 * jy2;
11571
+ cov11 = u11 * jy1 + u12 * jy2;
11572
+ }
11573
+
11574
+ // the low-pass dilation every splat renderer applies, 0.3 in the chosen units
11575
+ let us2 = uniforms.unitScale * uniforms.unitScale;
11576
+ cov00 += 0.3 / us2;
11577
+ cov11 += 0.3 / us2;
11578
+ let determinant = cov00 * cov11 - cov01 * cov01;
11579
+ if (determinant <= 0.0) {
11580
+ return result;
11581
+ }
11582
+
11583
+ let mid = 0.5 * (cov00 + cov11);
11584
+ let radius = length(vec2f(0.5 * (cov00 - cov11), cov01));
11585
+ let lambda1 = mid + radius;
11586
+ let lambda2 = max(mid - radius, 0.1 / us2);
11587
+
11588
+ // size cull on the footprint's radius in pixels. minPixelSize is a diameter: the engine's
11589
+ // projector is dispatched with half of it, and its quad path tests the full extent
11590
+ // (2 sqrt(2 lambda)) against the whole value, so both cut at the same place
11591
+ if (uniforms.unitScale * sqrt(2.0 * lambda1) < 0.5 * uniforms.minPixelSize) {
11592
+ return result;
11593
+ }
11594
+
11595
+ // contribution cull: the splat's alpha mass in pixels (the engine's minContribution rule)
11596
+ if (opacity * 6.283185 * sqrt(determinant) * us2 < uniforms.minContribution) {
11597
+ return result;
11598
+ }
11599
+
11600
+ // principal axis; a circular footprint has no defined eigenvector, any axis is right
11601
+ let eigenVec = vec2f(cov01, lambda1 - cov00);
11602
+ let eigenLen = length(eigenVec);
11603
+ let direction = select(vec2f(1.0, 0.0), eigenVec / eigenLen, eigenLen > 1e-9);
11604
+ let maxRadius = min(1024.0, min(viewport.x, viewport.y));
11605
+ let len1 = 2.0 * sqrt(2.0 * lambda1);
11606
+ let radiusScale = min(1.0, maxRadius / len1);
11607
+ let axis1 = len1 * radiusScale * direction;
11608
+ let len2 = 2.0 * sqrt(2.0 * lambda2) * radiusScale;
11609
+ let axis2 = len2 * vec2f(direction.y, -direction.x);
11610
+
11611
+ let ndc = clip.xy / clip.w;
11612
+ let extent = abs(axis1) + abs(axis2);
11613
+ let centerPixels = (ndc * 0.5 + 0.5) * viewport;
11614
+ if (centerPixels.x + extent.x < 0.0 || centerPixels.x - extent.x > viewport.x
11615
+ || centerPixels.y + extent.y < 0.0 || centerPixels.y - extent.y > viewport.y) {
11616
+ return result;
11617
+ }
11618
+
11619
+ ${occlusion
11620
+ ? `
11621
+ // Occlusion cull against the previous frame. Each stored depth is the nearest sample that
11622
+ // survived there, so the farthest depth over the blocks a splat covered bounds what could
11623
+ // still have shown behind it; a splat whose front (its centre less 2 sqrt(2) sigma along the
11624
+ // view, the same cut-off as the quad's edge) lies beyond that bound was invisible last
11625
+ // frame, up to sampling. Static splats reproject exactly through the previous view, so only
11626
+ // true disocclusions arrive a frame late. The footprint the splat had last frame bounds the
11627
+ // gather; footprints up to 16 px use the 8 px grid, up to 64 px the 32 px grid, larger ones
11628
+ // skip the test.
11629
+ if (uniforms.occlusionMode != 0u) {
11630
+ let prevClip = uniforms.prevViewProj * vec4f(center, 1.0);
11631
+ let prevDepth = -(uniforms.prevView * vec4f(center, 1.0)).z;
11632
+ let prevOrtho = uniforms.prevClipZ.z != 0.0;
11633
+ if (prevClip.w > 0.0 && (prevOrtho || prevDepth > 0.0)) {
11634
+ let prevNdc = prevClip.xy / prevClip.w;
11635
+ let halfExtent = len1 * radiusScale;
11636
+ let prevHalfExtent = halfExtent * (uniforms.prevFocal.x / focal.x)
11637
+ * select(depth / max(prevDepth, 0.001), 1.0, prevOrtho);
11638
+ let footprint = max(halfExtent, prevHalfExtent);
11639
+ var level = 1u;
11640
+ var blockSize = 8.0;
11641
+ var blocks = vec2i(i32(uniforms.occBlocksX1), i32(uniforms.occBlocksY1));
11642
+ if (footprint > 16.0) {
11643
+ level = 2u;
11644
+ blockSize = 32.0;
11645
+ blocks = vec2i(i32(uniforms.occBlocksX2), i32(uniforms.occBlocksY2));
11646
+ }
11647
+ if (footprint <= 64.0 && level <= uniforms.occlusionMode) {
11648
+ let gather = max(i32(ceil(footprint / blockSize)), 1);
11649
+ let prevPixel = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * uniforms.prevFlip * 0.5) * uniforms.prevViewport;
11650
+ let block = vec2i(floor(prevPixel / blockSize));
11651
+ if (block.x >= gather && block.y >= gather && block.x < blocks.x - gather && block.y < blocks.y - gather) {
11652
+ let front = prevDepth - 2.8284 * sqrt(c22);
11653
+ let w = select(front, 1.0, prevOrtho);
11654
+ if (w > 0.0) {
11655
+ let frontZ = clamp(uniforms.prevClipZ.x * front + uniforms.prevClipZ.y, 0.0, w) / w;
11656
+ // the block under the centre first: the neighbourhood's maximum is at
11657
+ // least its maximum, so a splat that block alone cannot cull is visible,
11658
+ // and most splats leave here after one load
11659
+ let centreIndex = u32(block.y * blocks.x + block.x);
11660
+ var farthest = select(occL1[centreIndex], occL2[centreIndex], level == 2u);
11661
+ if (frontZ > bitcast<f32>(farthest)) {
11662
+ if (level == 1u) {
11663
+ farthest = farthestL1(block, gather, blocks);
11664
+ } else {
11665
+ farthest = farthestL2(block, gather, blocks);
11666
+ }
11667
+ if (frontZ > bitcast<f32>(farthest)) {
11668
+ result.occluded = true;
11669
+ return result;
11670
+ }
11671
+ }
11672
+ }
11673
+ }
11674
+ }
11675
+ }
11676
+ }
11677
+
11678
+ `
11679
+ : ''}
11680
+ let color = clamp(srcColor(), vec3f(0.0), vec3f(uniforms.colorMax));
11681
+
11682
+ // rgb: 10/10/10 unorm with a 2-bit shared exponent (scale 1/2/4/8, range [0, 8])
11683
+ let maxChannel = max(color.r, max(color.g, color.b));
11684
+ var exponent = 0u;
11685
+ if (maxChannel > 4.0) {
11686
+ exponent = 3u;
11687
+ } else if (maxChannel > 2.0) {
11688
+ exponent = 2u;
11689
+ } else if (maxChannel > 1.0) {
11690
+ exponent = 1u;
11691
+ }
11692
+ let rgb = vec3u(clamp(color / f32(1u << exponent), vec3f(0.0), vec3f(1.0)) * 1023.0 + 0.5);
11693
+
11694
+ // centre as snorm16 over the range the offscreen cull bounds visible centres to; the
11695
+ // raster shader derives the same range from its viewport
11696
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / viewport;
11697
+
11698
+ result.valid = true;
11699
+ result.words[0] = pack2x16snorm(ndc / ndcRange);
11700
+ result.words[1] = bitcast<u32>(depth);
11701
+ result.words[2] = pack2x16float(axis1);
11702
+ result.words[3] = pack2x16float(vec2f(len2, 0.0)) | (u32(clamp(opacity, 0.0, 1.0) * 255.0 + 0.5) << 16u);
11703
+ ${order
11704
+ ? `
11705
+ // the depth bucket, log-spaced from the near plane, in the flags byte
11706
+ let key = clamp((log(max(depth, 1e-6)) - uniforms.keyLogNear) * uniforms.keyInvLogRange, 0.0, 0.999) * ${ORDER_BUCKETS}.0;
11707
+ result.words[3] |= u32(key) << 24u;
11708
+ `
11709
+ : ''}
11710
+ result.words[4] = rgb.r | (rgb.g << 10u) | (rgb.b << 20u) | (exponent << 30u);
11711
+ // Popless depth (StochasticSplats 3.4): the quad is tilted onto the plane through the
11712
+ // centre with normal adj(Sigma) mu (view space; adj rather than the inverse, so a flat
11713
+ // splat needs no division by its tiny determinant), and the raster gives each corner the
11714
+ // depth where its own view ray meets that plane, so hardware interpolation hands every
11715
+ // fragment the depth of the Gaussian's peak along its ray instead of the centre's. Stored
11716
+ // as g = n.xy / (n . mu): a corner at view offset d (in the plane z = -depth) lands at
11717
+ // depth / (1 + g . d). Orthographic rays are parallel, so there n = adj(Sigma) e_z and
11718
+ // the corner depth is depth + g . d with g = n.xy / n.z. Bounded so every corner stays
11719
+ // within 2 sqrt(2) sigma_z of the centre (the occlusion cull's front margin) and the
11720
+ // perspective scale stays positive, and so no corner crosses the near plane or the
11721
+ // raster's far clamp: a corner clamped there while the others are not bends the quad, whose
11722
+ // two triangles then take different depths and show as polygons (large far splats, the
11723
+ // sky, sit right at a far plane fitted to the scene). A centre beyond the clamp stays flat.
11724
+ let ortho = uniforms.isOrtho != 0u;
11725
+ let a00 = c11 * c22 - c12 * c12;
11726
+ let a01 = c02 * c12 - c01 * c22;
11727
+ let a02 = c01 * c12 - c02 * c11;
11728
+ let a11 = c00 * c22 - c02 * c02;
11729
+ let a12 = c01 * c02 - c00 * c12;
11730
+ let a22 = c00 * c11 - c01 * c01;
11731
+ let toward = select(viewCenter.xyz, vec3f(0.0, 0.0, -1.0), ortho);
11732
+ let n = vec3f(
11733
+ a00 * toward.x + a01 * toward.y + a02 * toward.z,
11734
+ a01 * toward.x + a11 * toward.y + a12 * toward.z,
11735
+ a02 * toward.x + a12 * toward.y + a22 * toward.z
11736
+ );
11737
+ let denom = select(dot(n, viewCenter.xyz), n.z, ortho);
11738
+ var g = vec2f(0.0);
11739
+ if (abs(denom) > 1e-20) {
11740
+ g = n.xy / denom;
11741
+ // view units per pixel at the centre's depth, and the quad's half extents in them
11742
+ let viewScale = select(depth, 1.0, ortho) / focal;
11743
+ let ext = (abs(axis1) + abs(axis2)) * viewScale;
11744
+ let bound = abs(g.x) * ext.x + abs(g.y) * ext.y;
11745
+ let margin = 2.8284 * sqrt(max(c22, 0.0));
11746
+ let inRange = select(
11747
+ min(1.0 - depth / uniforms.depthFar, depth / max(uniforms.depthNear, 1e-6) - 1.0),
11748
+ min(uniforms.depthFar - depth, depth - uniforms.depthNear),
11749
+ ortho
11750
+ );
11751
+ let limit = max(0.0, min(select(min(0.25, margin / max(depth, 1e-6)), margin, ortho), 0.999 * inRange));
11752
+ if (bound > limit) {
11753
+ g *= limit / max(bound, 1e-20);
11754
+ }
11755
+ }
11756
+ result.words[5] = pack2x16float(g);
11757
+ // the stable id the coverage hash seeds from: the slot, salted by the file for sources
11758
+ // whose indices restart per file
11759
+ result.words[6] = slot ^ (file * 2654435761u);
11760
+ return result;
11761
+ }
11762
+
11763
+ var<workgroup> wgCount: atomic<u32>;
11764
+ var<workgroup> wgOccluded: atomic<u32>;
11765
+ var<workgroup> wgBase: u32;
11766
+ ${order ? `var<workgroup> wgBuckets: array<atomic<u32>, ${ORDER_BUCKETS}>;` : ''}
11767
+
11768
+ @compute @workgroup_size(${PROJECTOR_WORKGROUP_SIZE})
11769
+ fn main(
11770
+ @builtin(workgroup_id) wg: vec3u,
11771
+ @builtin(num_workgroups) numWorkgroups: vec3u,
11772
+ @builtin(local_invocation_index) local: u32
11773
+ ) {
11774
+ // no early returns: the barriers below need every thread of the workgroup
11775
+ let chunkIndex = wg.x + wg.y * numWorkgroups.x;
11776
+ ${order ? ` atomicStore(&wgBuckets[local], 0u);` : ''}
11777
+ var projected: Projected;
11778
+ projected.valid = false;
11779
+ projected.occluded = false;
11780
+ if (chunkIndex < uniforms.numChunks) {
11781
+ let chunk = chunks[uniforms.chunkBase + chunkIndex];
11782
+ let visible = (nodeVisible[chunk.z >> 5u] >> (chunk.z & 31u)) & 1u;
11783
+ if (visible != 0u && local < chunk.y) {
11784
+ projected = project(chunk.x + local, chunk.w >> 16u);
11785
+ }
11786
+ }
11787
+
11788
+ // survivors claim consecutive slots: one workgroup-local count, one global atomic
11789
+ var localSlot = 0u;
11790
+ if (projected.valid) {
11791
+ localSlot = atomicAdd(&wgCount, 1u);
11792
+ }
11793
+ if (projected.occluded) {
11794
+ atomicAdd(&wgOccluded, 1u);
11795
+ }
11796
+ workgroupBarrier();
11797
+ if (local == 0u) {
11798
+ let n = atomicLoad(&wgCount);
11799
+ wgBase = select(0u, atomicAdd(&counter[0], n), n > 0u);
11800
+ let o = atomicLoad(&wgOccluded);
11801
+ if (o > 0u) {
11802
+ atomicAdd(&counter[1], o);
11803
+ }
11804
+ }
11805
+ workgroupBarrier();
11806
+ if (projected.valid) {
11807
+ let base = (wgBase + localSlot) * ${CACHE_WORDS}u;
11808
+ for (var i = 0u; i < ${CACHE_WORDS}u; i++) {
11809
+ cache[base + i] = projected.words[i];
11810
+ }
11811
+ ${order ? ` atomicAdd(&wgBuckets[projected.words[3] >> 24u], 1u);` : ''}
11812
+ }
11813
+ ${order
11814
+ ? `
11815
+ // a chunk's splats are spatially coherent, so few of its buckets are non-empty: one
11816
+ // workgroup count each, then one global atomic per non-empty bucket
11817
+ workgroupBarrier();
11818
+ let bucketCount = atomicLoad(&wgBuckets[local]);
11819
+ if (bucketCount > 0u) {
11820
+ atomicAdd(&buckets[local], bucketCount);
11821
+ }
11822
+ `
11823
+ : ''}
11824
+ }
11825
+ `;
11826
+
11827
+ // The ordering passes (variant order:bucket): the projector counts its survivors into 256
11828
+ // depth buckets, front to back; a one-workgroup scan turns the counts into bucket offsets, and
11829
+ // the scatter writes each survivor's cache slot into the ordered list the raster then follows.
11830
+ // Splats inside a bucket land in append order, so a bucket keeps its chunks' locality.
11831
+ // exclusive prefix sum of the bucket counts into the bucket offsets, in one workgroup
11832
+ const orderScanWGSL = /* wgsl */ `
11833
+ // [0, ${ORDER_BUCKETS}) counts, [${ORDER_BUCKETS}, ${2 * ORDER_BUCKETS}) offsets
11834
+ @group(0) @binding(0) var<storage, read_write> buckets: array<u32>;
11835
+
11836
+ var<workgroup> partial: array<u32, ${ORDER_BUCKETS}>;
11837
+
11838
+ @compute @workgroup_size(${ORDER_BUCKETS})
11839
+ fn main(@builtin(local_invocation_index) local: u32) {
11840
+ partial[local] = buckets[local];
11841
+ for (var stride = 1u; stride < ${ORDER_BUCKETS}u; stride <<= 1u) {
11842
+ workgroupBarrier();
11843
+ let value = select(0u, partial[local - stride], local >= stride);
11844
+ workgroupBarrier();
11845
+ partial[local] += value;
11846
+ }
11847
+ // inclusive to exclusive
11848
+ buckets[${ORDER_BUCKETS}u + local] = partial[local] - buckets[local];
11849
+ }
11850
+ `;
11851
+ // One thread per cache slot, one workgroup per 256 consecutive slots. Consecutive slots come
11852
+ // from one chunk, so a workgroup touches few buckets: it counts them locally, claims each
11853
+ // bucket's range with one global atomic, and places its splats in append order inside it.
11854
+ const orderScatterWGSL = /* wgsl */ `
11855
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
11856
+ @group(0) @binding(1) var<storage, read> cache: array<u32>;
11857
+ @group(0) @binding(2) var<storage, read_write> buckets: array<atomic<u32>>;
11858
+ @group(0) @binding(3) var<storage, read_write> ordered: array<u32>;
11859
+
11860
+ var<workgroup> wgCounts: array<atomic<u32>, ${ORDER_BUCKETS}>;
11861
+ var<workgroup> wgBase: array<u32, ${ORDER_BUCKETS}>;
11862
+
11863
+ @compute @workgroup_size(${ORDER_BUCKETS})
11864
+ fn main(
11865
+ @builtin(workgroup_id) wg: vec3u,
11866
+ @builtin(num_workgroups) numWorkgroups: vec3u,
11867
+ @builtin(local_invocation_index) local: u32
11868
+ ) {
11869
+ // no early returns: the barriers need every thread
11870
+ atomicStore(&wgCounts[local], 0u);
11871
+ let slot = (wg.x + wg.y * numWorkgroups.x) * ${ORDER_BUCKETS}u + local;
11872
+ let live = slot < counter[0];
11873
+ var key = 0u;
11874
+ var rank = 0u;
11875
+ workgroupBarrier();
11876
+ if (live) {
11877
+ key = cache[slot * ${CACHE_WORDS}u + 3u] >> 24u;
11878
+ rank = atomicAdd(&wgCounts[key], 1u);
11879
+ }
11880
+ workgroupBarrier();
11881
+ let count = atomicLoad(&wgCounts[local]);
11882
+ if (count > 0u) {
11883
+ wgBase[local] = atomicAdd(&buckets[${ORDER_BUCKETS}u + local], count);
11884
+ }
11885
+ workgroupBarrier();
11886
+ if (live) {
11887
+ ordered[wgBase[key] + rank] = slot;
11888
+ }
11889
+ }
11890
+ `;
11891
+
11892
+ // The raster pass: an indirect instanced draw of 128-quad meshes over the projector's
11893
+ // survivors, into the renderer's own colour + depth target. Fragments keep themselves with
11894
+ // probability alpha (StochasticSplats, Listing 1) and write opaque colour with hardware depth,
11895
+ // so no sort is needed and the depth buffer holds the nearest surviving sample per pixel.
11896
+ /** Quads per draw instance; the mesh holds this many quads. */
11897
+ const QUADS_PER_INSTANCE = 128;
11898
+ /** The raster's far clamp in normalised depth: just inside 1, which the compose reads as empty. */
11899
+ const FAR_CLIP_Z = 0.999999;
11900
+ const rasterVertexWGSL = /* wgsl */ `
11901
+ attribute vertex_position: vec3f;
11902
+
11903
+ // width, height, 2 / width, 2 / height
11904
+ uniform viewportSize: vec4f;
11905
+ // clip z = a * viewDepth + b (x, y); z = 1 for an orthographic camera
11906
+ uniform clipZParams: vec4f;
11907
+ // set by the engine's forward renderer for the target being rendered
11908
+ uniform projectionFlipY: f32;
11909
+ // focal length in pixels (x, y), for the popless corner depths
11910
+ uniform focalParams: vec4f;
11911
+
11912
+ var<storage, read> splatCache: array<u32>;
11913
+ var<storage, read> splatCount: array<u32>;
11914
+ #ifdef SSE_ORDERED
11915
+ // cache slots in draw order (variant order:bucket)
11916
+ var<storage, read> orderedSlots: array<u32>;
11917
+ #endif
11918
+
11919
+ // screen-linear: the corners share one screen footprint whatever depth they carry
11920
+ varying @interpolate(linear) gaussianUV: vec2f;
11921
+ varying @interpolate(flat, either) packedColor: u32;
11922
+ varying @interpolate(flat, either) packedAlpha: u32;
11923
+ varying @interpolate(flat, either) splatId: u32;
11924
+
11925
+ const discardPosition = vec4f(0.0, 0.0, 2.0, 1.0);
11926
+
11927
+ @vertex
11928
+ fn vertexMain(input: VertexInput) -> VertexOutput {
11929
+ var output: VertexOutput;
11930
+ let order = pcInstanceIndex * ${QUADS_PER_INSTANCE}u + u32(vertex_position.z);
11931
+ // the indirect instance count rounds up to whole instances; the tail is discarded here
11932
+ if (order >= splatCount[0]) {
11933
+ output.position = discardPosition;
11934
+ return output;
11935
+ }
11936
+
11937
+ #ifdef SSE_ORDERED
11938
+ let base = orderedSlots[order] * ${CACHE_WORDS}u;
11939
+ #else
11940
+ let base = order * ${CACHE_WORDS}u;
11941
+ #endif
11942
+ let maxRadius = min(1024.0, min(uniform.viewportSize.x, uniform.viewportSize.y));
11943
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / uniform.viewportSize.xy;
11944
+ let ndc = unpack2x16snorm(splatCache[base]) * ndcRange;
11945
+ let depth = bitcast<f32>(splatCache[base + 1u]);
11946
+ let ortho = uniform.clipZParams.z != 0.0;
11947
+
11948
+ let axis1 = unpack2x16float(splatCache[base + 2u]);
11949
+ let word3 = splatCache[base + 3u];
11950
+ let len2 = unpack2x16float(word3).x;
11951
+ let axis2 = len2 * normalize(vec2f(axis1.y, -axis1.x));
11952
+
11953
+ let corner = vertex_position.xy;
11954
+ let pixelOffset = corner.x * axis1 + corner.y * axis2;
11955
+ #ifdef SSE_POPLESS
11956
+ // the corner's depth on the splat's plane (see the projector): its view-space offset
11957
+ // at the centre's depth, times the stored gradient
11958
+ let g = unpack2x16float(splatCache[base + 5u]);
11959
+ let shift = dot(g, pixelOffset * select(depth, 1.0, ortho) / uniform.focalParams.xy);
11960
+ let cornerDepth = select(depth / (1.0 + shift), depth + shift, ortho);
11961
+ #else
11962
+ let cornerDepth = depth;
11963
+ #endif
11964
+ let w = select(cornerDepth, 1.0, ortho);
11965
+ let ndcCorner = ndc + pixelOffset * uniform.viewportSize.zw;
11966
+ // clip z clamped into range like the engine's splat shader, so splats beyond the far plane
11967
+ // still draw; just inside it, since the compose and the accumulation read depth 1 as empty
11968
+ let pos = vec4f(ndcCorner * w, clamp(uniform.clipZParams.x * cornerDepth + uniform.clipZParams.y, 0.0, w * ${FAR_CLIP_Z}), w);
11969
+ output.position = vec4f(pos.x, pos.y * uniform.projectionFlipY, pos.z, pos.w);
11970
+ output.gaussianUV = corner;
11971
+ output.packedColor = splatCache[base + 4u];
11972
+ output.packedAlpha = word3 >> 16u;
11973
+ output.splatId = splatCache[base + 6u];
11974
+ return output;
11975
+ }
11976
+ `;
11977
+ const rasterFragmentWGSL = /* wgsl */ `
11978
+ varying @interpolate(linear) gaussianUV: vec2f;
11979
+ varying @interpolate(flat, either) packedColor: u32;
11980
+ varying @interpolate(flat, either) packedAlpha: u32;
11981
+ varying @interpolate(flat, either) splatId: u32;
11982
+
11983
+ uniform sseAlphaClip: f32;
11984
+ // 0 while the camera rests, so a still frame reproduces itself; the frame index once TAA
11985
+ // accumulates
11986
+ uniform frameSeed: u32;
11987
+
11988
+ const EXP4 = exp(-4.0);
11989
+ const INV_EXP4 = 1.0 / (1.0 - EXP4);
11990
+
11991
+ // the engine's falloff: zero at the quad edge, which sits at 2 sqrt(2) sigma
11992
+ fn normExp(x: f32) -> f32 {
11993
+ return (exp(x * -4.0) - EXP4) * INV_EXP4;
11994
+ }
11995
+
11996
+ // integer hash (Wellons' prospector mix)
11997
+ fn hashU32(x: u32) -> u32 {
11998
+ var v = x;
11999
+ v ^= v >> 16u;
12000
+ v *= 0x7feb352du;
12001
+ v ^= v >> 15u;
12002
+ v *= 0x846ca68bu;
12003
+ v ^= v >> 16u;
12004
+ return v;
12005
+ }
12006
+
12007
+ @fragment
12008
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
12009
+ var output: FragmentOutput;
12010
+ let radius = dot(gaussianUV, gaussianUV);
12011
+ if (radius > 1.0) {
12012
+ discard;
12013
+ }
12014
+ let opacity = f32(packedAlpha & 0xffu) / 255.0;
12015
+ let alpha = normExp(radius) * opacity;
12016
+ if (alpha < uniform.sseAlphaClip) {
12017
+ discard;
12018
+ }
12019
+
12020
+ let pix = vec2u(pcPosition.xy);
12021
+ #ifdef SSE_SPP_QUAD
12022
+ // one sample per pixel, thresholds stratified over each 2x2 pixel quad: the quad's four
12023
+ // pixels take the four strata of [0, 1) in a per-(quad, splat) scrambled order, so a
12024
+ // splat with alpha a covers 4a +- 1 of its quad and the compose's quad mean is nearly
12025
+ // exact. Hashing quad and splat keeps overlapping splats decorrelated
12026
+ let quad = pix >> vec2u(1u);
12027
+ let h = hashU32((quad.x * 1973u) ^ (quad.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
12028
+ let stratum = ((pix.y & 1u) * 2u + (pix.x & 1u)) ^ (h & 3u);
12029
+ let rnd = (f32(stratum) + f32(h >> 8u) * (1.0 / 16777216.0)) * 0.25;
12030
+ #else
12031
+ let h = hashU32((pix.x * 1973u) ^ (pix.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
12032
+ let rnd = f32(h >> 8u) * (1.0 / 16777216.0);
12033
+ #endif
12034
+ if (rnd >= alpha) {
12035
+ discard;
12036
+ }
12037
+
12038
+ let bits = packedColor;
12039
+ let color = vec3f(vec3u(bits, bits >> 10u, bits >> 20u) & vec3u(1023u)) * (f32(1u << (bits >> 30u)) / 1023.0);
12040
+ // opaque coverage: the compose reads alpha 1 as "a sample landed here"
12041
+ output.color = vec4f(color, 1.0);
12042
+ return output;
12043
+ }
12044
+ `;
12045
+
12046
+ // The occlusion grid: the previous frame's depth texture reduced to the farthest depth per 8x8
12047
+ // pixel block (level 1), and the farthest of each 4x4 group of those (level 2, 32 px). Each
12048
+ // pixel's depth is the nearest surviving sample there, so a block's maximum bounds what could
12049
+ // still have shown behind it; a splat whose front lies beyond that bound over every block it
12050
+ // covers was invisible last frame. Depths are hardware z in [0, 1], stored as their f32 bits
12051
+ // (non-negative floats order the same as their bits, so atomicMax works on them).
12052
+ const reduceL1WGSL = /* wgsl */ `
12053
+ struct ReduceUniforms {
12054
+ width: u32,
12055
+ height: u32,
12056
+ blocksX: u32,
12057
+ blocksY: u32
12058
+ }
12059
+
12060
+ @group(0) @binding(0) var prevDepth: texture_depth_2d;
12061
+ @group(0) @binding(1) var<storage, read_write> blockMax: array<u32>;
12062
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
12063
+
12064
+ var<workgroup> wgMax: atomic<u32>;
12065
+
12066
+ @compute @workgroup_size(8, 8)
12067
+ fn main(
12068
+ @builtin(workgroup_id) wg: vec3u,
12069
+ @builtin(local_invocation_id) lid: vec3u,
12070
+ @builtin(local_invocation_index) li: u32
12071
+ ) {
12072
+ let pixel = wg.xy * 8u + lid.xy;
12073
+ // pixels off the texture count as far, so an edge block never culls
12074
+ var depth = 1.0;
12075
+ if (pixel.x < uniforms.width && pixel.y < uniforms.height) {
12076
+ depth = textureLoad(prevDepth, vec2i(pixel), 0);
12077
+ }
12078
+ atomicMax(&wgMax, bitcast<u32>(depth));
12079
+ workgroupBarrier();
12080
+ if (li == 0u) {
12081
+ blockMax[wg.y * uniforms.blocksX + wg.x] = atomicLoad(&wgMax);
12082
+ }
12083
+ }
12084
+ `;
12085
+ const reduceL2WGSL = /* wgsl */ `
12086
+ struct ReduceUniforms {
12087
+ blocksX1: u32,
12088
+ blocksY1: u32,
12089
+ blocksX2: u32,
12090
+ blocksY2: u32
12091
+ }
12092
+
12093
+ @group(0) @binding(0) var<storage, read> level1: array<u32>;
12094
+ @group(0) @binding(1) var<storage, read_write> level2: array<u32>;
12095
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
12096
+
12097
+ @compute @workgroup_size(64)
12098
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
12099
+ let index = gid.x;
12100
+ if (index >= uniforms.blocksX2 * uniforms.blocksY2) {
12101
+ return;
12102
+ }
12103
+ let bx = index % uniforms.blocksX2;
12104
+ let by = index / uniforms.blocksX2;
12105
+ var farthest = 0u;
12106
+ for (var dy = 0u; dy < 4u; dy++) {
12107
+ for (var dx = 0u; dx < 4u; dx++) {
12108
+ let x = bx * 4u + dx;
12109
+ let y = by * 4u + dy;
12110
+ if (x < uniforms.blocksX1 && y < uniforms.blocksY1) {
12111
+ farthest = max(farthest, level1[y * uniforms.blocksX1 + x]);
12112
+ } else {
12113
+ farthest = max(farthest, bitcast<u32>(1.0));
12114
+ }
12115
+ }
12116
+ }
12117
+ level2[index] = farthest;
12118
+ }
12119
+ `;
12120
+
12121
+ // Data path (ii): the projector reads each resident file's own textures (sog, ply or
12122
+ // compressed ply) through the engine's format read chunks, so nothing is copied into a work
12123
+ // buffer: no decoded 24-byte copy per splat, no re-copy when a node's lod changes, no
12124
+ // colour refresh when the camera turns. The price is one dispatch per resident file, the
12125
+ // model transform and the sh evaluation per splat per frame.
12126
+ //
12127
+ // Interim: the engine still allocates its work buffer and would keep copying into it, so the
12128
+ // copy passes are switched off on the work buffer this source sees; the textures themselves
12129
+ // stay until engine change E2 (no work buffer in external mode) lands.
12130
+ const tmpScale = new Vec3();
12131
+ const tmpRotation = new Quat();
12132
+ class DirectSplatSource {
12133
+ kind = 'direct';
12134
+ device;
12135
+ resource = null;
12136
+ set = null;
12137
+ constants = new Map();
12138
+ patched = null;
12139
+ constructor(device) {
12140
+ this.device = device;
12141
+ }
12142
+ update(set, manager) {
12143
+ // one format per scene: a sog lod set shares its format across files. The first file's
12144
+ // format compiles the projector; a file of another format is skipped by dispatchPlan
12145
+ this.resource = set.files[0]?.resource ?? this.resource;
12146
+ this.set = set;
12147
+ this.constants.clear();
12148
+ for (const file of set.files) {
12149
+ const m = file.modelMatrix;
12150
+ m.getScale(tmpScale);
12151
+ tmpRotation.setFromMat4(m);
12152
+ if (tmpRotation.w < 0)
12153
+ tmpRotation.mulScalar(-1);
12154
+ this.constants.set(file.fileIndex, {
12155
+ rotation: [tmpRotation.x, tmpRotation.y, tmpRotation.z, tmpRotation.w],
12156
+ scale: [tmpScale.x, tmpScale.y, tmpScale.z, 0]
12157
+ });
12158
+ }
12159
+ this.patchWorkBuffer(manager.world.workBuffer);
12160
+ }
12161
+ // the engine's copy into the work buffer is wasted work for this path
12162
+ patchWorkBuffer(workBuffer) {
12163
+ if (this.patched?.workBuffer === workBuffer)
12164
+ return;
12165
+ this.restoreWorkBuffer();
12166
+ this.patched = { workBuffer, render: workBuffer.render, renderColor: workBuffer.renderColor };
12167
+ const skip = () => undefined;
12168
+ workBuffer.render = skip;
12169
+ workBuffer.renderColor = skip;
12170
+ }
12171
+ restoreWorkBuffer() {
12172
+ if (!this.patched)
12173
+ return;
12174
+ const { workBuffer, render, renderColor } = this.patched;
12175
+ workBuffer.render = render;
12176
+ workBuffer.renderColor = renderColor;
12177
+ this.patched = null;
12178
+ }
12179
+ readChunk(bindingBase) {
12180
+ const format = this.require().format;
12181
+ // The format's read chunk reads the file's own space and returns sh0 colour + alpha;
12182
+ // the adapter below applies the file's model transform and evaluates its sh for this
12183
+ // camera. Its loose `uniform` and texture declarations (dequantisation constants, the
12184
+ // compressed format's chunk texture) are reflected by the engine into a second bind
12185
+ // group and set by name like any other parameter.
12186
+ // The engine writes its 32-bit float streams (the sog v2 codebook) as `texture_2d<uff>`,
12187
+ // an alias only its reflection of loose declarations resolves; explicit bindings need
12188
+ // the wgsl type, and the matching unfilterable sample type in bindFormats()
12189
+ const declarations = format
12190
+ .getComputeInputDeclarations(bindingBase)
12191
+ .replace(/texture_2d<uff>/g, 'texture_2d<f32>');
12192
+ return /* wgsl */ `
12193
+ #include "halfTypesCS"
12194
+ #include "gsplatEvalSHVS"
12195
+ ${declarations}
12196
+ ${format.getReadCode()}
12197
+
12198
+ var<private> srcWorldCenter: vec3f;
12199
+ var<private> srcColorCache: vec4f;
12200
+
12201
+ fn quatMulF(a: vec4f, b: vec4f) -> vec4f {
12202
+ return vec4f(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
12203
+ }
12204
+
12205
+ // v rotated by the inverse of q (x, y, z, w)
12206
+ fn quatRotateInvF(q: vec4f, v: vec3f) -> vec3f {
12207
+ let u = -q.xyz;
12208
+ return v + 2.0 * cross(u, cross(u, v) + q.w * v);
12209
+ }
12210
+
12211
+ fn srcCenter() -> vec3f {
12212
+ srcWorldCenter = (uniforms.model * vec4f(getCenter(), 1.0)).xyz;
12213
+ return srcWorldCenter;
12214
+ }
12215
+
12216
+ fn srcOpacity() -> f32 {
12217
+ srcColorCache = getColor();
12218
+ return srcColorCache.a;
12219
+ }
12220
+
12221
+ // the format returns (w, x, y, z); world = model * source
12222
+ fn srcRotation() -> vec4f {
12223
+ let q = quatMulF(uniforms.modelRotation, getRotation().yzwx);
12224
+ return q.wxyz;
12225
+ }
12226
+
12227
+ fn srcScale() -> vec3f {
12228
+ return uniforms.modelScale.xyz * getScale();
12229
+ }
12230
+
12231
+ fn srcColor() -> vec3f {
12232
+ var color = srcColorCache.rgb;
12233
+ #if SH_BANDS > 0
12234
+ // the view direction in the file's space; orthographic rays all run along the camera forward
12235
+ let view = uniforms.view;
12236
+ let orthoDir = vec3f(0.0, 0.0, -1.0) * mat3x3f(view[0].xyz, view[1].xyz, view[2].xyz);
12237
+ let viewDir = select(srcWorldCenter - uniforms.cameraPosition.xyz, orthoDir, uniforms.isOrtho != 0u);
12238
+ let dir = normalize(quatRotateInvF(uniforms.modelRotation, viewDir));
12239
+ var sh: array<half3, SH_COEFFS>;
12240
+ var shScale: f32;
12241
+ readSHData(&sh, &shScale);
12242
+ color += vec3f(evalSH(&sh, dir) * half(shScale));
12243
+ #endif
12244
+ return color;
12245
+ }
12246
+ `;
12247
+ }
12248
+ bindFormats() {
12249
+ const format = this.require().format;
12250
+ const entries = format.getComputeBindFormats();
12251
+ for (const entry of entries) {
12252
+ const stream = format.streams.find((s) => s.name === entry.name);
12253
+ if (stream?.format === PIXELFORMAT_RGBA32F)
12254
+ entry.sampleType = SAMPLETYPE_UNFILTERABLE_FLOAT;
12255
+ }
12256
+ return entries;
12257
+ }
12258
+ shaderIncludes() {
12259
+ // the read chunks include the engine's own gsplat chunks by name
12260
+ return new Map(ShaderChunks.get(this.device, SHADERLANGUAGE_WGSL));
12261
+ }
12262
+ shaderDefines() {
12263
+ const defines = new Map();
12264
+ this.require().configureMaterialDefines(defines);
12265
+ return defines;
12266
+ }
12267
+ chunkBase(node) {
12268
+ return node.sourceBase;
12269
+ }
12270
+ dispatchPlan(set) {
12271
+ // one run of the chunk table per file (the table is built file by file)
12272
+ const groups = [];
12273
+ let chunkBase = 0;
12274
+ const hash = this.resource?.format.hash;
12275
+ for (const file of set.files) {
12276
+ let chunkCount = 0;
12277
+ for (const node of file.nodes)
12278
+ chunkCount += Math.ceil(node.count / 256);
12279
+ if (chunkCount > 0 && file.resource.format.hash === hash) {
12280
+ groups.push({ fileIndex: file.fileIndex, chunkBase, chunkCount });
12281
+ }
12282
+ chunkBase += chunkCount;
12283
+ }
12284
+ return groups;
12285
+ }
12286
+ bind(compute, group, set) {
12287
+ const file = set.files[group.fileIndex];
12288
+ const { resource } = file;
12289
+ for (const [name, texture] of resource.streams.textures) {
12290
+ compute.setParameter(name, texture);
12291
+ }
12292
+ for (const [name, value] of resource.parameters) {
12293
+ compute.setParameter(name, value);
12294
+ }
12295
+ const constants = this.constants.get(file.fileIndex);
12296
+ compute.setParameter('model', file.modelMatrix.data);
12297
+ compute.setParameter('modelRotation', constants.rotation);
12298
+ compute.setParameter('modelScale', constants.scale);
12299
+ }
12300
+ textureSize(group) {
12301
+ return this.set?.files[group.fileIndex].resource.textureDimensions.x ?? 0;
12302
+ }
12303
+ gpuBytes() {
12304
+ // the file textures belong to the engine and are counted by app.stats.vram
12305
+ return 0;
12306
+ }
12307
+ shaderKey() {
12308
+ const resource = this.resource;
12309
+ if (!resource)
12310
+ return 'direct:';
12311
+ const defines = this.shaderDefines();
12312
+ return `direct:${resource.format.hash}:${[...defines].map(([k, v]) => `${k}=${v}`).join(',')}`;
12313
+ }
12314
+ destroy() {
12315
+ this.restoreWorkBuffer();
12316
+ this.resource = null;
12317
+ this.set = null;
12318
+ this.constants.clear();
12319
+ }
12320
+ require() {
12321
+ if (!this.resource)
12322
+ throw new Error('DirectSplatSource: update() has not run');
12323
+ return this.resource;
12324
+ }
12325
+ }
12326
+
12327
+ class WorkBufferSplatSource {
12328
+ kind = 'workbuffer';
12329
+ workBuffer = null;
12330
+ update(set, manager) {
12331
+ this.workBuffer = manager.world.workBuffer;
12332
+ }
12333
+ readChunk(bindingBase) {
12334
+ const format = this.require().format;
12335
+ // the engine's declarations bind one texture per stream from bindingBase and define
12336
+ // loadDataX(); its read code decodes them into getCenter() and friends, already in
12337
+ // world space with the sh colour baked for this camera
12338
+ return /* wgsl */ `
12339
+ ${format.getComputeInputDeclarations(bindingBase)}
12340
+ ${format.getReadCode()}
12341
+ fn srcCenter() -> vec3f { return getCenter(); }
12342
+ fn srcOpacity() -> f32 { return getOpacity(); }
12343
+ fn srcRotation() -> vec4f { return getRotation(); }
12344
+ fn srcScale() -> vec3f { return getScale(); }
12345
+ fn srcColor() -> vec3f { return getColor(); }
12346
+ `;
12347
+ }
12348
+ bindFormats() {
12349
+ return this.require().format.getComputeBindFormats();
12350
+ }
12351
+ shaderIncludes() {
12352
+ return undefined;
12353
+ }
12354
+ shaderDefines() {
12355
+ return undefined;
12356
+ }
12357
+ chunkBase(node) {
12358
+ return node.slotBase;
12359
+ }
12360
+ dispatchPlan(set, numChunks) {
12361
+ return [{ fileIndex: -1, chunkBase: 0, chunkCount: numChunks }];
12362
+ }
12363
+ bind(compute) {
12364
+ const workBuffer = this.require();
12365
+ for (const stream of workBuffer.format.streams) {
12366
+ compute.setParameter(stream.name, workBuffer.getTexture(stream.name));
12367
+ }
12368
+ }
12369
+ textureSize() {
12370
+ return this.require().textureSize;
12371
+ }
12372
+ gpuBytes() {
12373
+ // the work buffer belongs to the engine and is counted by app.stats.vram
12374
+ return 0;
12375
+ }
12376
+ shaderKey() {
12377
+ const workBuffer = this.workBuffer;
12378
+ return workBuffer ? `wb:${workBuffer.format.streams.map((s) => s.name).join(',')}` : 'wb:';
12379
+ }
12380
+ destroy() {
12381
+ this.workBuffer = null;
12382
+ }
12383
+ require() {
12384
+ if (!this.workBuffer)
12385
+ throw new Error('WorkBufferSplatSource: update() has not run');
12386
+ return this.workBuffer;
12387
+ }
12388
+ }
12389
+
12390
+ // The stochastic splat renderer (WebGPU, opt-in). The engine keeps LOD, streaming and the
12391
+ // work-buffer copy; this owns everything after: per frame it culls nodes on the cpu, projects
12392
+ // the resident splats in a compute pass into a dense cache, writes the indirect draw arguments,
12393
+ // rasterises the survivors as opaque depth-tested quads into its own colour + depth target
12394
+ // (StochasticSplats: keep a fragment with probability alpha, no sort), and composes that target
12395
+ // over the camera's target from a fullscreen quad in the World layer that also writes depth.
12396
+ //
12397
+ // Frame flow: the compute runs inside the engine's gsplat update (the `frame:ready` hook, before
12398
+ // the frame graph), the raster pass runs from `camera.beforePasses`, and the compose is an
12399
+ // ordinary mesh instance in the camera's forward pass. See docs/stochastic-renderer.md.
12400
+ const defaultVariant = () => ({
12401
+ spp: 'quad',
12402
+ compose: 'blend',
12403
+ cull: 'auto',
12404
+ order: 'bucket',
12405
+ contribution: 0,
12406
+ popless: 'on',
12407
+ taa: 'on',
12408
+ taaMax: 256,
12409
+ taaMoveMax: 16,
12410
+ taaClip: 1.25,
12411
+ taaFilter: 'cubic',
12412
+ taaReproj: 'sample',
12413
+ taaMotion: 4,
12414
+ taaDebug: 0,
12415
+ taaFlip: 0,
12416
+ colorMax: 8,
12417
+ units: 'engine'
12418
+ });
12419
+ const taaCount = (value) => Math.min(TAA_MAX_COUNT, Math.max(1, Math.round(value)));
12420
+ const parseVariant = (text) => {
12421
+ const variant = defaultVariant();
12422
+ for (const part of (text ?? '').split(',')) {
12423
+ const [key, value] = part.split(':').map((s) => s.trim());
12424
+ if (!key || value === undefined)
12425
+ continue;
12426
+ if (key === 'spp' && (value === '1' || value === 'quad'))
12427
+ variant.spp = value;
12428
+ if (key === 'compose' && (value === 'blend' || value === 'none' || value === 'depth'))
12429
+ variant.compose = value;
12430
+ if (key === 'popless' && (value === 'on' || value === 'off'))
12431
+ variant.popless = value;
12432
+ if (key === 'taa' && (value === 'on' || value === 'off'))
12433
+ variant.taa = value;
12434
+ if (key === 'taaMax' && Number.isFinite(Number(value)))
12435
+ variant.taaMax = taaCount(Number(value));
12436
+ if (key === 'taaMoveMax' && Number.isFinite(Number(value)))
12437
+ variant.taaMoveMax = taaCount(Number(value));
12438
+ if (key === 'taaDebug' && Number.isFinite(Number(value)))
12439
+ variant.taaDebug = Number(value);
12440
+ if (key === 'taaClip' && Number.isFinite(Number(value)))
12441
+ variant.taaClip = Math.max(0, Number(value));
12442
+ if (key === 'taaFilter' && (value === 'linear' || value === 'cubic'))
12443
+ variant.taaFilter = value;
12444
+ if (key === 'taaReproj' && (value === 'sample' || value === 'history'))
12445
+ variant.taaReproj = value;
12446
+ if (key === 'taaMotion' && Number.isFinite(Number(value)))
12447
+ variant.taaMotion = Math.max(0, Number(value));
12448
+ if (key === 'taaFlip' && Number.isFinite(Number(value)))
12449
+ variant.taaFlip = Number(value);
12450
+ if (key === 'colorMax' && Number.isFinite(Number(value)))
12451
+ variant.colorMax = Math.max(0, Number(value));
12452
+ if (key === 'units' && (value === 'px' || value === 'engine'))
12453
+ variant.units = value;
12454
+ if (key === 'cull' && (value === 'off' || value === 'l1' || value === 'l2' || value === 'auto')) {
12455
+ variant.cull = value;
12456
+ }
12457
+ if (key === 'order' && (value === 'append' || value === 'bucket'))
12458
+ variant.order = value;
12459
+ if (key === 'contribution' && Number.isFinite(Number(value)))
12460
+ variant.contribution = Math.max(0, Number(value));
12461
+ }
12462
+ return variant;
12463
+ };
12464
+ // Renders an explicit mesh-instance list into the renderer's own target (the raster and the
12465
+ // taa resolve). Not a layer: a layer in camera.layers is culled once and drawn by every pass
12466
+ // for the camera, so the scene pass would draw the splats into the camera target as well.
12467
+ class SplatRasterPass extends RenderPass {
12468
+ forward;
12469
+ camera;
12470
+ instances;
12471
+ constructor(device, forward, camera, instances, name = 'sse-splat-raster') {
12472
+ super(device);
12473
+ this.forward = forward;
12474
+ this.camera = camera;
12475
+ this.instances = instances;
12476
+ this.name = name;
12477
+ }
12478
+ execute() {
12479
+ this.forward.renderForwardLayer(this.camera.camera, this.renderTarget, null, undefined, SHADER_FORWARD, {
12480
+ meshInstances: this.instances
12481
+ });
12482
+ }
12483
+ }
12484
+ const createQuadMesh = (device, quads) => {
12485
+ const positions = new Float32Array(quads * 4 * 3);
12486
+ const indices = new Uint32Array(quads * 6);
12487
+ for (let i = 0; i < quads; ++i) {
12488
+ // z carries the quad's index within the instance
12489
+ positions.set([-1, -1, i, 1, -1, i, 1, 1, i, -1, 1, i], i * 12);
12490
+ const v = i * 4;
12491
+ indices.set([v, v + 1, v + 2, v, v + 2, v + 3], i * 6);
12492
+ }
12493
+ const mesh = new Mesh(device);
12494
+ mesh.setPositions(positions, 3);
12495
+ mesh.setIndices(indices);
12496
+ mesh.update(PRIMITIVE_TRIANGLES);
12497
+ return mesh;
12498
+ };
12499
+ const createFullscreenMesh = (device) => {
12500
+ const mesh = new Mesh(device);
12501
+ mesh.setPositions(new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), 2);
12502
+ mesh.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3]));
12503
+ mesh.update(PRIMITIVE_TRIANGLES);
12504
+ return mesh;
12505
+ };
12506
+ const tmpVec2 = new Vec2();
12507
+ class StochasticSplatRenderer {
12508
+ variant;
12509
+ source;
12510
+ app;
12511
+ device;
12512
+ camera;
12513
+ worldLayer;
12514
+ provider;
12515
+ unsubscribe;
12516
+ enabled = true;
12517
+ // the resident set and its chunk table
12518
+ set = null;
12519
+ numChunks = 0;
12520
+ chunkData = new Uint32Array(0);
12521
+ chunkBuffer = null;
12522
+ nodeVisibleData = new Uint32Array(0);
12523
+ nodeVisibleBuffer = null;
12524
+ cacheBuffer = null;
12525
+ cacheSlots = 0;
12526
+ counter;
12527
+ // compute
12528
+ // one projector shader per source and occlusion / order specialisation: the test's code
12529
+ // costs a little even when a uniform disables it, so a disabled or suspended cull runs
12530
+ // without it. One compute per shader and dispatch group, since a compute owns the uniform
12531
+ // buffer its dispatch reads and per-file sources dispatch once per file
12532
+ projectorShaders = new Map();
12533
+ projectorComputes = new Map();
12534
+ projectorBindGroupFormat = null;
12535
+ projectorSourceKey = '';
12536
+ args;
12537
+ argsBindGroupFormat;
12538
+ // order:bucket: bucket counts then offsets, the ordered slot list, and its two passes
12539
+ orderBuckets;
12540
+ orderedBuffer = null;
12541
+ orderScan;
12542
+ orderScatter;
12543
+ orderFormats = [];
12544
+ // the occlusion grid: farthest depth per 8 px block (level 1) and per 32 px block (level 2)
12545
+ occL1;
12546
+ occL2;
12547
+ occBlocks = { x1: 0, y1: 0, x2: 0, y2: 0 };
12548
+ reduceL1;
12549
+ reduceL2;
12550
+ reduceFormats = [];
12551
+ // the previous frame the grid and the reprojection describe; valid only when that frame
12552
+ // rendered to the same target at the same size from the same world state
12553
+ prevValid = false;
12554
+ prevViewProjection = new Mat4();
12555
+ prevView = new Mat4();
12556
+ prevProjection = new Mat4();
12557
+ prevClipZ = [0, 0, 0, 0];
12558
+ prevViewport = [0, 0];
12559
+ prevFocal = [0, 0];
12560
+ prevFlip = 1;
12561
+ prevWidth = 0;
12562
+ prevHeight = 0;
12563
+ prevVersion = -1;
12564
+ // the allocations resident when the previous frame drew, and whether any of them has gone
12565
+ // since: only a removed splat can make the previous depth wrong (it may have hidden what is
12566
+ // now behind it), so arrivals leave the cull on while a scene streams in
12567
+ residentAllocIds = new Set();
12568
+ nodesRemoved = false;
12569
+ prevOrtho = false;
12570
+ /** Whether the last frame ran the occlusion cull, for the debug panel and the harness. */
12571
+ culling = false;
12572
+ /** Whether cull:auto currently has the test switched off for culling too little. */
12573
+ get cullSuspended() {
12574
+ return this.variant.cull === 'auto' && (!this.cullActive || this.cullSuspendedFrames > 0);
12575
+ }
12576
+ // cull:auto bookkeeping. The last decision holds while a readback is in flight: while the
12577
+ // test is active every culled frame's counts are read back and a poor one suspends it;
12578
+ // while suspended the frames count down, then one probe frame runs the test and the rest
12579
+ // wait for its counts
12580
+ cullActive = true;
12581
+ cullSuspendedFrames = 0;
12582
+ cullStatsPending = false;
12583
+ /** Frames the test stays off after culling too little (cull:auto). */
12584
+ /**
12585
+ * Whether the projected cache for `splats` resident splats fits one storage binding on this
12586
+ * device. The cache reserves 25% over the resident count; adapters differ in the limit
12587
+ * (128 MiB is the WebGPU default), so a viewer checks before opting in.
12588
+ */
12589
+ static cacheFits(device, splats) {
12590
+ const limit = device.wgpu?.limits
12591
+ ?.maxStorageBufferBindingSize;
12592
+ return !limit || Math.ceil(splats * 1.25) * CACHE_WORDS * 4 <= limit;
12593
+ }
12594
+ static CULL_SUSPEND_FRAMES = 60;
12595
+ /** The culled fraction below which cull:auto suspends the test. */
12596
+ static CULL_MIN_FRACTION = 0.08;
12597
+ /**
12598
+ * Let a capture (query) frame cull against the previous on-screen frame when it renders at
12599
+ * the same size. Off by default: a query frame is not culled, since its cull thins what a
12600
+ * pick or a thumbnail should see. The harness turns it on to photograph culled frames.
12601
+ */
12602
+ allowQueryCull = false;
12603
+ // raster
12604
+ colorTexture;
12605
+ depthTexture;
12606
+ target;
12607
+ rasterMesh;
12608
+ rasterMaterial;
12609
+ rasterInstance;
12610
+ rasterPass;
12611
+ // taa: ping-pong history (premultiplied colour + coverage as unorm16, and the depth mean and
12612
+ // sample count packed in 32 bits; shaders/taa.ts), resolved by a fullscreen pass after the
12613
+ // raster. Sized with the target on the first accumulating frame, and shrunk back while taa is off
12614
+ taaColor = [];
12615
+ taaInfo = [];
12616
+ taaTargets = [];
12617
+ taaWrite = 0;
12618
+ taaMesh;
12619
+ taaMaterial;
12620
+ taaInstance;
12621
+ taaPass;
12622
+ // whether the history holds the previous on-screen frame at the current size
12623
+ taaHistoryValid = false;
12624
+ // the previous taa frame's matrices as the pass reads them, and this frame's, copied over
12625
+ // at the start of the next frame: the material holds the data arrays by reference and
12626
+ // uploads them when it draws, after this hook has run
12627
+ taaPrevViewProjection = new Mat4();
12628
+ taaPrevView = new Mat4();
12629
+ taaLastViewProjection = new Mat4();
12630
+ taaLastView = new Mat4();
12631
+ taaWidth = 0;
12632
+ taaHeight = 0;
12633
+ // the camera's world transform, for the accumulation's reprojection
12634
+ cameraWorld = new Mat4();
12635
+ // frames since the camera or the scene last changed, for converging at rest
12636
+ restFrames = 0;
12637
+ /** The frame the depth texture holds, null while it holds a capture's or nothing. */
12638
+ depthFrame = null;
12639
+ depthFrameCount = 0;
12640
+ depthFrameCamera = createPickCameraSnapshot();
12641
+ // a frame requested from inside the render: the engine clears app.renderNextFrame right
12642
+ // after render(), so the request is applied on frameend instead
12643
+ frameWanted = false;
12644
+ onFrameEnd = () => {
12645
+ if (this.frameWanted) {
12646
+ this.frameWanted = false;
12647
+ this.app.renderNextFrame = true;
12648
+ }
12649
+ };
12650
+ frameIndex = 0;
12651
+ // the seed the harness sets; the frame index replaces it while taa accumulates
12652
+ userSeed = 0;
12653
+ /** Whether the last frame ran the temporal accumulation, for the debug panel. */
12654
+ taaActive = false;
12655
+ /**
12656
+ * Let a capture (query) frame at the on-screen size run the accumulation over the on-screen
12657
+ * history, so the harness can photograph converged and moving frames. Off by default.
12658
+ */
12659
+ allowQueryTaa = false;
12660
+ // compose
12661
+ composeMesh;
12662
+ composeMaterial;
12663
+ composeInstance;
12664
+ frustum = new Frustum();
12665
+ sphere = new BoundingSphere();
12666
+ shaderProjection = new Mat4();
12667
+ viewProjection = new Mat4();
12668
+ frameSeed = 0;
12669
+ ready = false;
12670
+ /** Byte sizes of the buffers this renderer owns, for the bench harness and the debug panel. */
12671
+ /** The renderer's depth texture: the nearest surviving sample per pixel of `depthFrame`. */
12672
+ get frameDepthTexture() {
12673
+ return this.depthTexture;
12674
+ }
12675
+ get gpuBytes() {
12676
+ const buffers = [
12677
+ this.chunkBuffer,
12678
+ this.nodeVisibleBuffer,
12679
+ this.cacheBuffer,
12680
+ this.orderedBuffer,
12681
+ this.counter,
12682
+ this.orderBuckets,
12683
+ this.occL1,
12684
+ this.occL2
12685
+ ];
12686
+ let bytes = 0;
12687
+ for (const buffer of buffers)
12688
+ bytes += buffer?.byteSize ?? 0;
12689
+ bytes += this.colorTexture.gpuSize + this.depthTexture.gpuSize;
12690
+ for (const texture of [...this.taaColor, ...this.taaInfo])
12691
+ bytes += texture.gpuSize;
12692
+ return bytes + this.source.gpuBytes();
12693
+ }
12694
+ /**
12695
+ * The seed mixed into every coverage hash. 0 makes a still camera reproduce its frame;
12696
+ * the harness varies it to measure the sampling noise floor, and TAA will animate it.
12697
+ */
12698
+ get seed() {
12699
+ return this.frameSeed;
12700
+ }
12701
+ set seed(value) {
12702
+ this.userSeed = value >>> 0;
12703
+ this.frameSeed = this.userSeed;
12704
+ this.app.renderNextFrame = true;
12705
+ }
12706
+ /** The last projected frame's survivor count and occlusion-culled count, read back from the gpu. */
12707
+ async readStats() {
12708
+ // without a typed array the engine hands back bytes
12709
+ const data = new Uint32Array(2);
12710
+ await this.counter.read(0, 8, data, true);
12711
+ return { survivors: data[0], occluded: data[1] };
12712
+ }
12713
+ // reduce the previous frame's depth into the two grid levels
12714
+ reduceDepth(width, height) {
12715
+ const { device } = this;
12716
+ const x1 = Math.ceil(width / 8);
12717
+ const y1 = Math.ceil(height / 8);
12718
+ const x2 = Math.ceil(x1 / 4);
12719
+ const y2 = Math.ceil(y1 / 4);
12720
+ if (this.occBlocks.x1 !== x1 || this.occBlocks.y1 !== y1) {
12721
+ this.occL1.destroy();
12722
+ this.occL2.destroy();
12723
+ this.occL1 = new StorageBuffer(device, x1 * y1 * 4, BUFFERUSAGE_COPY_DST);
12724
+ this.occL2 = new StorageBuffer(device, x2 * y2 * 4, BUFFERUSAGE_COPY_DST);
12725
+ this.occBlocks = { x1, y1, x2, y2 };
12726
+ }
12727
+ const l1 = this.reduceL1;
12728
+ l1.setParameter('prevDepth', this.depthTexture);
12729
+ l1.setParameter('blockMax', this.occL1);
12730
+ l1.setParameter('width', width);
12731
+ l1.setParameter('height', height);
12732
+ l1.setParameter('blocksX', x1);
12733
+ l1.setParameter('blocksY', y1);
12734
+ l1.setupDispatch(x1, y1, 1);
12735
+ const l2 = this.reduceL2;
12736
+ l2.setParameter('level1', this.occL1);
12737
+ l2.setParameter('level2', this.occL2);
12738
+ l2.setParameter('blocksX1', x1);
12739
+ l2.setParameter('blocksY1', y1);
12740
+ l2.setParameter('blocksX2', x2);
12741
+ l2.setParameter('blocksY2', y2);
12742
+ Compute.calcDispatchSize(Math.ceil((x2 * y2) / 64), tmpVec2);
12743
+ l2.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
12744
+ device.computeDispatch([l1], 'sse-splat-reduce1');
12745
+ device.computeDispatch([l2], 'sse-splat-reduce2');
12746
+ }
12747
+ /** Survivors of the last frame's projection are only known to the gpu; this is the resident count. */
12748
+ activeSplats = 0;
12749
+ constructor(app, camera, worldLayer, options = {}) {
12750
+ this.app = app;
12751
+ this.device = app.graphicsDevice;
12752
+ this.camera = camera;
12753
+ this.worldLayer = worldLayer;
12754
+ this.variant = parseVariant(options.variant);
12755
+ const { device } = this;
12756
+ if (options.source === 'direct') {
12757
+ this.source = new DirectSplatSource(device);
12758
+ }
12759
+ else {
12760
+ if (options.source && options.source !== 'workbuffer') {
12761
+ console.warn(`StochasticSplatRenderer: splat source '${options.source}' is not implemented yet, using the work buffer`);
12762
+ }
12763
+ this.source = new WorkBufferSplatSource();
12764
+ }
12765
+ this.counter = new StorageBuffer(device, 16, BUFFERUSAGE_COPY_DST | BUFFERUSAGE_COPY_SRC);
12766
+ // indirect draw arguments
12767
+ this.argsBindGroupFormat = new BindGroupFormat(device, [
12768
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
12769
+ new BindStorageBufferFormat('indirectDrawArgs', SHADERSTAGE_COMPUTE),
12770
+ new BindStorageBufferFormat('indirectDispatchArgs', SHADERSTAGE_COMPUTE),
12771
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
12772
+ ]);
12773
+ this.args = new Compute(device, new Shader(device, {
12774
+ name: 'sse-splat-args',
12775
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12776
+ cshader: argsWGSL,
12777
+ computeUniformBufferFormats: {
12778
+ uniforms: new UniformBufferFormat(device, [
12779
+ new UniformFormat('drawSlot', UNIFORMTYPE_UINT),
12780
+ new UniformFormat('indexCount', UNIFORMTYPE_UINT),
12781
+ new UniformFormat('quadsPerInstance', UNIFORMTYPE_UINT),
12782
+ new UniformFormat('dispatchSlot', UNIFORMTYPE_UINT),
12783
+ new UniformFormat('scatterWorkgroupSize', UNIFORMTYPE_UINT)
12784
+ ])
12785
+ },
12786
+ computeBindGroupFormat: this.argsBindGroupFormat
12787
+ }), 'sse-splat-args');
12788
+ // the ordering passes
12789
+ this.orderBuckets = new StorageBuffer(device, 2 * ORDER_BUCKETS * 4, BUFFERUSAGE_COPY_DST);
12790
+ const scanFormat = new BindGroupFormat(device, [new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)]);
12791
+ const scatterFormat = new BindGroupFormat(device, [
12792
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
12793
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE, true),
12794
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE),
12795
+ new BindStorageBufferFormat('ordered', SHADERSTAGE_COMPUTE)
12796
+ ]);
12797
+ this.orderFormats = [scanFormat, scatterFormat];
12798
+ this.orderScan = new Compute(device, new Shader(device, {
12799
+ name: 'sse-splat-order-scan',
12800
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12801
+ cshader: orderScanWGSL,
12802
+ computeBindGroupFormat: scanFormat
12803
+ }), 'sse-splat-order-scan');
12804
+ this.orderScatter = new Compute(device, new Shader(device, {
12805
+ name: 'sse-splat-order-scatter',
12806
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12807
+ cshader: orderScatterWGSL,
12808
+ computeBindGroupFormat: scatterFormat
12809
+ }), 'sse-splat-order-scatter');
12810
+ // the occlusion grid and its two reduce passes
12811
+ this.occL1 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
12812
+ this.occL2 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
12813
+ const reduceL1Format = new BindGroupFormat(device, [
12814
+ new BindTextureFormat('prevDepth', SHADERSTAGE_COMPUTE, TEXTUREDIMENSION_2D, SAMPLETYPE_DEPTH, false),
12815
+ new BindStorageBufferFormat('blockMax', SHADERSTAGE_COMPUTE),
12816
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
12817
+ ]);
12818
+ const reduceL2Format = new BindGroupFormat(device, [
12819
+ new BindStorageBufferFormat('level1', SHADERSTAGE_COMPUTE, true),
12820
+ new BindStorageBufferFormat('level2', SHADERSTAGE_COMPUTE),
12821
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
12822
+ ]);
12823
+ this.reduceFormats = [reduceL1Format, reduceL2Format];
12824
+ this.reduceL1 = new Compute(device, new Shader(device, {
12825
+ name: 'sse-splat-reduce1',
12826
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12827
+ cshader: reduceL1WGSL,
12828
+ computeUniformBufferFormats: {
12829
+ uniforms: new UniformBufferFormat(device, [
12830
+ new UniformFormat('width', UNIFORMTYPE_UINT),
12831
+ new UniformFormat('height', UNIFORMTYPE_UINT),
12832
+ new UniformFormat('blocksX', UNIFORMTYPE_UINT),
12833
+ new UniformFormat('blocksY', UNIFORMTYPE_UINT)
12834
+ ])
12835
+ },
12836
+ computeBindGroupFormat: reduceL1Format
12837
+ }), 'sse-splat-reduce1');
12838
+ this.reduceL2 = new Compute(device, new Shader(device, {
12839
+ name: 'sse-splat-reduce2',
12840
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12841
+ cshader: reduceL2WGSL,
12842
+ computeUniformBufferFormats: {
12843
+ uniforms: new UniformBufferFormat(device, [
12844
+ new UniformFormat('blocksX1', UNIFORMTYPE_UINT),
12845
+ new UniformFormat('blocksY1', UNIFORMTYPE_UINT),
12846
+ new UniformFormat('blocksX2', UNIFORMTYPE_UINT),
12847
+ new UniformFormat('blocksY2', UNIFORMTYPE_UINT)
12848
+ ])
12849
+ },
12850
+ computeBindGroupFormat: reduceL2Format
12851
+ }), 'sse-splat-reduce2');
12852
+ // the raster target: colour, and a depth texture the compose, the occlusion cull and
12853
+ // (later) the picker read
12854
+ this.colorTexture = new Texture(device, {
12855
+ name: 'sse-splat-color',
12856
+ width: 4,
12857
+ height: 4,
12858
+ format: PIXELFORMAT_RGBA8,
12859
+ mipmaps: false,
12860
+ minFilter: FILTER_LINEAR,
12861
+ magFilter: FILTER_LINEAR,
12862
+ addressU: ADDRESS_CLAMP_TO_EDGE,
12863
+ addressV: ADDRESS_CLAMP_TO_EDGE
12864
+ });
12865
+ this.depthTexture = new Texture(device, {
12866
+ name: 'sse-splat-depth',
12867
+ width: 4,
12868
+ height: 4,
12869
+ format: PIXELFORMAT_DEPTH,
12870
+ mipmaps: false,
12871
+ addressU: ADDRESS_CLAMP_TO_EDGE,
12872
+ addressV: ADDRESS_CLAMP_TO_EDGE
12873
+ });
12874
+ this.target = new RenderTarget({
12875
+ name: 'sse-splat-target',
12876
+ colorBuffer: this.colorTexture,
12877
+ depthBuffer: this.depthTexture,
12878
+ samples: 1
12879
+ });
12880
+ this.rasterMesh = createQuadMesh(device, QUADS_PER_INSTANCE);
12881
+ this.rasterMaterial = new ShaderMaterial({
12882
+ uniqueName: 'sse-splat-raster',
12883
+ vertexWGSL: rasterVertexWGSL,
12884
+ fragmentWGSL: rasterFragmentWGSL,
12885
+ attributes: { vertex_position: SEMANTIC_POSITION }
12886
+ });
12887
+ this.rasterMaterial.blendType = BLEND_NONE;
12888
+ this.rasterMaterial.depthWrite = true;
12889
+ this.rasterMaterial.depthTest = true;
12890
+ this.rasterMaterial.cull = CULLFACE_NONE;
12891
+ // the forward renderer reads the instance's node for its cull setup and world transform
12892
+ this.rasterInstance = new MeshInstance(this.rasterMesh, this.rasterMaterial, new GraphNode('sse-splat-raster'));
12893
+ this.rasterInstance.cull = false;
12894
+ this.rasterInstance.castShadow = false;
12895
+ this.rasterInstance.receiveShadow = false;
12896
+ this.rasterPass = new SplatRasterPass(device, app.renderer, camera, [
12897
+ this.rasterInstance
12898
+ ]);
12899
+ this.rasterPass.init(this.target);
12900
+ this.rasterPass.setClearColor(new Color(0, 0, 0, 0));
12901
+ this.rasterPass.setClearDepth(1);
12902
+ // nothing to draw, and no buffers bound, until the first populated frame
12903
+ this.rasterPass.enabled = false;
12904
+ // the taa resolve: a fullscreen pass from the raster target and the previous history
12905
+ // into the other history, sized with the target on its first frame
12906
+ for (let i = 0; i < 2; i++) {
12907
+ this.taaColor.push(new Texture(device, {
12908
+ name: `sse-splat-taa-color-${i}`,
12909
+ width: 4,
12910
+ height: 4,
12911
+ format: PIXELFORMAT_RGBA16U,
12912
+ mipmaps: false,
12913
+ minFilter: FILTER_NEAREST,
12914
+ magFilter: FILTER_NEAREST,
12915
+ addressU: ADDRESS_CLAMP_TO_EDGE,
12916
+ addressV: ADDRESS_CLAMP_TO_EDGE
12917
+ }));
12918
+ this.taaInfo.push(new Texture(device, {
12919
+ name: `sse-splat-taa-info-${i}`,
12920
+ width: 4,
12921
+ height: 4,
12922
+ format: PIXELFORMAT_R32U,
12923
+ mipmaps: false,
12924
+ minFilter: FILTER_NEAREST,
12925
+ magFilter: FILTER_NEAREST,
12926
+ addressU: ADDRESS_CLAMP_TO_EDGE,
12927
+ addressV: ADDRESS_CLAMP_TO_EDGE
12928
+ }));
12929
+ this.taaTargets.push(new RenderTarget({
12930
+ name: `sse-splat-taa-${i}`,
12931
+ colorBuffers: [this.taaColor[i], this.taaInfo[i]],
12932
+ depth: false,
12933
+ samples: 1
12934
+ }));
12935
+ }
12936
+ this.taaMesh = createFullscreenMesh(device);
12937
+ this.taaMaterial = new ShaderMaterial({
12938
+ uniqueName: 'sse-splat-taa',
12939
+ vertexWGSL: taaVertexWGSL,
12940
+ fragmentWGSL: taaFragmentWGSL,
12941
+ attributes: { vertex_position: SEMANTIC_POSITION },
12942
+ fragmentOutputTypes: ['uvec4', 'uint']
12943
+ });
12944
+ this.taaMaterial.blendType = BLEND_NONE;
12945
+ this.taaMaterial.depthWrite = false;
12946
+ this.taaMaterial.depthTest = false;
12947
+ this.taaMaterial.cull = CULLFACE_NONE;
12948
+ this.taaInstance = new MeshInstance(this.taaMesh, this.taaMaterial, new GraphNode('sse-splat-taa'));
12949
+ this.taaInstance.cull = false;
12950
+ this.taaInstance.castShadow = false;
12951
+ this.taaInstance.receiveShadow = false;
12952
+ this.taaPass = new SplatRasterPass(device, app.renderer, camera, [this.taaInstance], 'sse-splat-taa');
12953
+ this.taaPass.init(this.taaTargets[0]);
12954
+ this.taaPass.enabled = false;
12955
+ // the compose quad, blended over the skybox and opaque meshes with the splat depth
12956
+ this.composeMesh = createFullscreenMesh(device);
12957
+ this.composeMaterial = new ShaderMaterial({
12958
+ uniqueName: 'sse-splat-compose',
12959
+ vertexWGSL: composeVertexWGSL,
12960
+ fragmentWGSL: composeFragmentWGSL,
12961
+ attributes: { vertex_position: SEMANTIC_POSITION }
12962
+ });
12963
+ this.composeMaterial.blendType = BLEND_PREMULTIPLIED;
12964
+ this.composeMaterial.depthWrite = true;
12965
+ this.composeMaterial.depthTest = true;
12966
+ this.composeMaterial.cull = CULLFACE_NONE;
12967
+ this.composeMaterial.setParameter('splatColor', this.colorTexture);
12968
+ this.composeMaterial.setParameter('splatDepth', this.depthTexture);
12969
+ // always bound, even while taa is off: a declared texture without a value makes the
12970
+ // engine create and upload a placeholder inside the forward pass, which submits the
12971
+ // command buffer mid-pass on WebGPU
12972
+ this.composeMaterial.setParameter('taaColor', this.taaColor[0]);
12973
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[0]);
12974
+ this.composeInstance = new MeshInstance(this.composeMesh, this.composeMaterial, new GraphNode('sse-splat-compose'));
12975
+ this.composeInstance.cull = false;
12976
+ this.composeInstance.castShadow = false;
12977
+ this.composeInstance.receiveShadow = false;
12978
+ // the picker pass draws every pickable instance of the layer into a target without a
12979
+ // depth attachment; this shader writes frag_depth, which makes that pipeline invalid
12980
+ // and drops the whole submit, the frame's command buffer included
12981
+ this.composeInstance.pick = false;
12982
+ // first among the transparents, whichever way the layer sorts them
12983
+ this.composeInstance.drawOrder = -1e3;
12984
+ this.composeInstance.calculateSortDistance = () => Number.MAX_VALUE;
12985
+ this.applyVariant();
12986
+ this.provider = new EngineResidentSetProvider(app, camera, worldLayer);
12987
+ this.unsubscribe = this.provider.onFrame((set, changed, manager) => this.frame(set, changed, manager));
12988
+ app.on('frameend', this.onFrameEnd);
12989
+ this.attach();
12990
+ }
12991
+ /** Switch the renderer off and hand the splats back to the engine's renderer (XR), or on again. */
12992
+ setEnabled(value) {
12993
+ if (this.enabled === value)
12994
+ return;
12995
+ this.enabled = value;
12996
+ if (value) {
12997
+ this.attach();
12998
+ }
12999
+ else {
13000
+ this.detach();
13001
+ }
13002
+ this.app.renderNextFrame = true;
13003
+ }
13004
+ /** Replace the experiment switches from a `key:value,key:value` string (unset keys reset). */
13005
+ setVariant(text) {
13006
+ Object.assign(this.variant, parseVariant(text));
13007
+ // the cull decides afresh under new switches
13008
+ this.cullActive = true;
13009
+ this.cullSuspendedFrames = 0;
13010
+ this.applyVariant();
13011
+ }
13012
+ /**
13013
+ * Drop the temporal history; the next frame starts accumulating from its own sample. The
13014
+ * coverage seeds restart too, so a variant accumulates the same samples every time (the
13015
+ * harness compares builds image for image).
13016
+ */
13017
+ resetHistory() {
13018
+ this.taaHistoryValid = false;
13019
+ this.restFrames = 0;
13020
+ this.frameIndex = 0;
13021
+ }
13022
+ /** Re-read {@link variant} after a field changed. */
13023
+ applyVariant() {
13024
+ // a switch changes what the frames hold; an old history would leak into the new ones
13025
+ this.resetHistory();
13026
+ const quad = this.variant.spp === 'quad';
13027
+ this.rasterMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
13028
+ this.rasterMaterial.setDefine('SSE_ORDERED', this.variant.order === 'bucket' ? '' : undefined);
13029
+ this.rasterMaterial.setDefine('SSE_POPLESS', this.variant.popless === 'on' ? '' : undefined);
13030
+ this.composeMaterial.setDefine('SSE_SHOW_DEPTH', this.variant.compose === 'depth' ? '' : undefined);
13031
+ this.composeMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
13032
+ this.rasterMaterial.update();
13033
+ this.composeMaterial.update();
13034
+ this.setReady(this.ready);
13035
+ this.app.renderNextFrame = true;
13036
+ }
13037
+ // the raster pass and the compose only run once a frame has bound the buffers they read
13038
+ setReady(value) {
13039
+ this.ready = value;
13040
+ this.rasterPass.enabled = value;
13041
+ this.composeInstance.visible = value && this.variant.compose !== 'none';
13042
+ }
13043
+ attach() {
13044
+ const passes = this.camera.camera.beforePasses;
13045
+ if (!passes.includes(this.rasterPass))
13046
+ passes.push(this.rasterPass);
13047
+ if (!passes.includes(this.taaPass))
13048
+ passes.push(this.taaPass);
13049
+ this.worldLayer.addMeshInstances([this.composeInstance]);
13050
+ this.provider.setActive(true);
13051
+ }
13052
+ detach() {
13053
+ const passes = this.camera.camera.beforePasses;
13054
+ for (const pass of [this.rasterPass, this.taaPass]) {
13055
+ const index = passes.indexOf(pass);
13056
+ if (index >= 0)
13057
+ passes.splice(index, 1);
13058
+ }
13059
+ this.resetHistory();
13060
+ this.depthFrame = null;
13061
+ this.worldLayer.removeMeshInstances([this.composeInstance]);
13062
+ this.provider.setActive(false);
13063
+ }
13064
+ frame(set, changed, manager) {
13065
+ if (!this.enabled)
13066
+ return;
13067
+ const { device, camera } = this;
13068
+ const cam = camera.camera;
13069
+ this.nodesRemoved = false;
13070
+ if (changed || this.set !== set) {
13071
+ const ids = new Set(set.nodes.map((node) => node.allocId));
13072
+ for (const id of this.residentAllocIds) {
13073
+ if (!ids.has(id)) {
13074
+ this.nodesRemoved = true;
13075
+ break;
13076
+ }
13077
+ }
13078
+ this.residentAllocIds = ids;
13079
+ this.source.update(set, manager);
13080
+ this.rebuildChunkTable(set);
13081
+ this.ensureCache(set.activeSplats);
13082
+ this.activeSplats = set.activeSplats;
13083
+ this.pruneProjectorComputes(set);
13084
+ // recorded last, so a rebuild that throws is retried next frame
13085
+ this.set = set;
13086
+ }
13087
+ if (this.numChunks === 0) {
13088
+ // nothing resident: draw nothing
13089
+ this.setReady(false);
13090
+ return;
13091
+ }
13092
+ // the target follows whatever the camera renders into this frame: the backbuffer, or a
13093
+ // capture's render target at another size
13094
+ const rt = camera.renderTarget;
13095
+ const width = rt ? rt.width : device.width;
13096
+ const height = rt ? rt.height : device.height;
13097
+ if (this.target.width !== width || this.target.height !== height) {
13098
+ this.target.resize(width, height);
13099
+ }
13100
+ const view = cam.viewMatrix;
13101
+ const projection = cam.projectionMatrix;
13102
+ const isOrtho = cam.projection === PROJECTION_ORTHOGRAPHIC;
13103
+ // the clip z the raster shader reconstructs must match the engine's WebGPU depth range
13104
+ const shaderProjection = Camera$1.applyShaderProjectionTransform(projection, this.shaderProjection, false, true);
13105
+ this.viewProjection.mul2(shaderProjection, view);
13106
+ // The splats' own depth: clip z = a * depth + b (over w = depth for a perspective
13107
+ // camera). The camera's far plane is fitted to the scene bound, which can leave a sky
13108
+ // outside it, and splats clamped there share one depth and lose their order; so a
13109
+ // perspective raster puts its far plane at infinity (z = 1 - near / depth), with the same
13110
+ // near plane and, near where precision matters, the same resolution. The compose converts
13111
+ // back to the camera's depth where the splats meet the rest of the scene. An orthographic
13112
+ // camera keeps its own mapping: a linear depth has no far plane at infinity.
13113
+ const cameraClipZ = [-shaderProjection.data[10], shaderProjection.data[14]];
13114
+ const clipZ = isOrtho ? cameraClipZ : [1, cameraClipZ[1] / cameraClipZ[0]];
13115
+ const clipZParams = [clipZ[0], clipZ[1], isOrtho ? 1 : 0, 0];
13116
+ this.cullNodes(set, this.viewProjection);
13117
+ const focal = [Math.abs(projection.data[0]) * width * 0.5, Math.abs(projection.data[5]) * height * 0.5];
13118
+ const gsplat = this.app.scene.gsplat;
13119
+ // the moving-camera contribution cull: a raised threshold while the view changes, then
13120
+ // one more frame at the scene's threshold once it has stopped
13121
+ const moved = this.viewMoved(view, projection);
13122
+ const raised = moved && this.variant.contribution > 0;
13123
+ const minContribution = raised
13124
+ ? Math.max(gsplat.minContribution, this.variant.contribution)
13125
+ : gsplat.minContribution;
13126
+ if (raised)
13127
+ this.frameWanted = true;
13128
+ // Temporal accumulation runs on on-screen frames (and, for the harness, on a capture at
13129
+ // the same size); the history is only trusted when it holds the previous such frame at
13130
+ // this size. While it runs the coverage seed changes every frame, and a resting camera
13131
+ // keeps requesting frames until the history has filled its cap
13132
+ const isQuery = !!rt;
13133
+ const taaOn = this.variant.taa === 'on' &&
13134
+ (!isQuery || (this.allowQueryTaa && width === this.taaWidth && height === this.taaHeight));
13135
+ if (taaOn) {
13136
+ if (this.taaWidth !== width || this.taaHeight !== height) {
13137
+ this.resizeHistory(width, height);
13138
+ this.taaWidth = width;
13139
+ this.taaHeight = height;
13140
+ this.taaHistoryValid = false;
13141
+ this.restFrames = 0;
13142
+ }
13143
+ this.frameSeed = this.frameIndex++ >>> 0;
13144
+ if (moved || changed)
13145
+ this.restFrames = 0;
13146
+ else
13147
+ this.restFrames++;
13148
+ if (this.restFrames < this.variant.taaMax + 2)
13149
+ this.frameWanted = true;
13150
+ }
13151
+ else {
13152
+ this.frameSeed = this.userSeed;
13153
+ // a capture at another size does not accumulate; the next on-screen frame starts over
13154
+ this.taaHistoryValid = false;
13155
+ this.restFrames = 0;
13156
+ // switched off: the history goes back to its placeholder size until it is wanted
13157
+ if (this.variant.taa === 'off' && this.taaWidth !== 0) {
13158
+ this.resizeHistory(4, 4);
13159
+ this.taaWidth = 0;
13160
+ this.taaHeight = 0;
13161
+ }
13162
+ }
13163
+ this.taaActive = taaOn;
13164
+ // The occlusion cull reads the depth texture as the previous frame left it, so it needs
13165
+ // that frame to have drawn to this target at this size (a resize loses the texture, a
13166
+ // capture draws elsewhere), with no splat removed since (its depth would hide what is
13167
+ // now behind it; arrivals are safe) and the same projection type. A capture frame is
13168
+ // never culled and never becomes the previous frame.
13169
+ // a new world state can change what is occluded: try the test again
13170
+ if (this.prevVersion !== set.version) {
13171
+ this.cullSuspendedFrames = 0;
13172
+ this.cullActive = true;
13173
+ }
13174
+ const cullMode = this.variant.cull;
13175
+ let wanted = cullMode !== 'off';
13176
+ let probe = false;
13177
+ if (cullMode === 'auto' && !isQuery) {
13178
+ if (this.cullSuspendedFrames > 0) {
13179
+ // a moving camera changes what is occluded, so the probe comes sooner
13180
+ const moved = this.viewMoved(view, projection);
13181
+ this.cullSuspendedFrames = Math.max(0, this.cullSuspendedFrames - (moved ? 4 : 1));
13182
+ wanted = false;
13183
+ }
13184
+ else if (!this.cullActive) {
13185
+ // suspended and due: one probe frame, then wait for its counts
13186
+ probe = !this.cullStatsPending;
13187
+ wanted = probe;
13188
+ }
13189
+ }
13190
+ const culling = wanted &&
13191
+ (!isQuery || this.allowQueryCull) &&
13192
+ this.prevValid &&
13193
+ this.prevWidth === width &&
13194
+ this.prevHeight === height &&
13195
+ !this.nodesRemoved &&
13196
+ this.prevOrtho === isOrtho;
13197
+ this.culling = culling;
13198
+ if (culling) {
13199
+ this.reduceDepth(width, height);
13200
+ }
13201
+ this.counter.clear();
13202
+ const ordered = this.variant.order === 'bucket';
13203
+ if (ordered)
13204
+ this.orderBuckets.clear();
13205
+ // the order key spans the fitted clip range, log-spaced
13206
+ const logNear = Math.log(Math.max(cam.nearClip, 1e-6));
13207
+ const invLogRange = 1 / Math.max(Math.log(Math.max(cam.farClip, 1e-6)) - logNear, 1e-6);
13208
+ // the view depths where the raster's clip z reaches 0 and its far clamp (FAR_CLIP_Z), from
13209
+ // clip z = a * depth + b (over w = depth for a perspective camera)
13210
+ const [clipA, clipB] = clipZ;
13211
+ const depthNear = -clipB / clipA;
13212
+ const depthFar = isOrtho ? (FAR_CLIP_Z - clipB) / clipA : clipB / (FAR_CLIP_Z - clipA);
13213
+ const cameraPosition = camera.entity.getPosition();
13214
+ const groups = this.source.dispatchPlan(set, this.numChunks);
13215
+ for (const group of groups) {
13216
+ // a file with no node in the frustum has nothing to dispatch
13217
+ if (group.fileIndex >= 0 && !this.anyNodeVisible(set.files[group.fileIndex].nodes))
13218
+ continue;
13219
+ const projector = this.ensureProjector(culling, ordered, group);
13220
+ this.source.bind(projector, group, set);
13221
+ projector.setParameter('chunks', this.chunkBuffer);
13222
+ projector.setParameter('nodeVisible', this.nodeVisibleBuffer);
13223
+ projector.setParameter('cache', this.cacheBuffer);
13224
+ projector.setParameter('counter', this.counter);
13225
+ projector.setParameter('occL1', this.occL1);
13226
+ projector.setParameter('occL2', this.occL2);
13227
+ projector.setParameter('buckets', this.orderBuckets);
13228
+ projector.setParameter('view', view.data);
13229
+ projector.setParameter('viewProj', this.viewProjection.data);
13230
+ projector.setParameter('prevViewProj', this.prevViewProjection.data);
13231
+ projector.setParameter('prevView', this.prevView.data);
13232
+ projector.setParameter('prevClipZ', this.prevClipZ);
13233
+ projector.setParameter('viewport', [width, height]);
13234
+ projector.setParameter('focal', focal);
13235
+ projector.setParameter('prevViewport', this.prevViewport);
13236
+ projector.setParameter('prevFocal', this.prevFocal);
13237
+ projector.setParameter('numChunks', group.chunkCount);
13238
+ projector.setParameter('chunkBase', group.chunkBase);
13239
+ projector.setParameter('cameraPosition', [cameraPosition.x, cameraPosition.y, cameraPosition.z, 0]);
13240
+ projector.setParameter('splatTextureSize', this.source.textureSize(group));
13241
+ projector.setParameter('isOrtho', isOrtho ? 1 : 0);
13242
+ projector.setParameter('minPixelSize', gsplat.minPixelSize);
13243
+ projector.setParameter('alphaClip', gsplat.alphaClipForward);
13244
+ projector.setParameter('minContribution', minContribution);
13245
+ projector.setParameter('colorMax', this.variant.colorMax);
13246
+ projector.setParameter('unitScale', this.variant.units === 'engine' ? 2 : 1);
13247
+ projector.setParameter('occBlocksX1', this.occBlocks.x1);
13248
+ projector.setParameter('occBlocksY1', this.occBlocks.y1);
13249
+ projector.setParameter('occBlocksX2', this.occBlocks.x2);
13250
+ projector.setParameter('occBlocksY2', this.occBlocks.y2);
13251
+ projector.setParameter('occlusionMode', culling ? (cullMode === 'l1' ? 1 : 2) : 0);
13252
+ projector.setParameter('prevFlip', this.prevFlip);
13253
+ projector.setParameter('keyLogNear', logNear);
13254
+ projector.setParameter('keyInvLogRange', invLogRange);
13255
+ projector.setParameter('depthNear', depthNear);
13256
+ projector.setParameter('depthFar', depthFar);
13257
+ Compute.calcDispatchSize(group.chunkCount, tmpVec2);
13258
+ projector.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
13259
+ device.computeDispatch([projector], 'sse-splat-project');
13260
+ }
13261
+ // indirect draw arguments for the raster and dispatch size for the scatter; slots are
13262
+ // per frame
13263
+ const drawSlot = device.getIndirectDrawSlot(1);
13264
+ const dispatchSlot = device.getIndirectDispatchSlot(1);
13265
+ this.args.setParameter('counter', this.counter);
13266
+ this.args.setParameter('indirectDrawArgs', device.indirectDrawBuffer);
13267
+ this.args.setParameter('indirectDispatchArgs', device.indirectDispatchBuffer);
13268
+ this.args.setParameter('drawSlot', drawSlot);
13269
+ this.args.setParameter('indexCount', QUADS_PER_INSTANCE * 6);
13270
+ this.args.setParameter('quadsPerInstance', QUADS_PER_INSTANCE);
13271
+ this.args.setParameter('dispatchSlot', dispatchSlot);
13272
+ this.args.setParameter('scatterWorkgroupSize', ORDER_BUCKETS);
13273
+ this.args.setupDispatch(1, 1, 1);
13274
+ device.computeDispatch([this.args], 'sse-splat-args');
13275
+ this.rasterInstance.setIndirect(null, drawSlot, 1);
13276
+ if (ordered) {
13277
+ // bucket offsets, then every survivor claims its place in its bucket
13278
+ this.orderScan.setParameter('buckets', this.orderBuckets);
13279
+ this.orderScan.setupDispatch(1, 1, 1);
13280
+ device.computeDispatch([this.orderScan], 'sse-splat-order-scan');
13281
+ const scatter = this.orderScatter;
13282
+ scatter.setParameter('counter', this.counter);
13283
+ scatter.setParameter('cache', this.cacheBuffer);
13284
+ scatter.setParameter('buckets', this.orderBuckets);
13285
+ scatter.setParameter('ordered', this.orderedBuffer);
13286
+ scatter.setupIndirectDispatch(dispatchSlot);
13287
+ device.computeDispatch([scatter], 'sse-splat-order-scatter');
13288
+ }
13289
+ const material = this.rasterMaterial;
13290
+ material.setParameter('splatCache', this.cacheBuffer);
13291
+ material.setParameter('splatCount', this.counter);
13292
+ if (ordered)
13293
+ material.setParameter('orderedSlots', this.orderedBuffer);
13294
+ material.setParameter('viewportSize', [width, height, 2 / width, 2 / height]);
13295
+ material.setParameter('clipZParams', clipZParams);
13296
+ material.setParameter('focalParams', [focal[0], focal[1], 0, 0]);
13297
+ material.setParameter('sseAlphaClip', gsplat.alphaClipForward);
13298
+ material.setParameter('frameSeed', this.frameSeed);
13299
+ this.taaPass.enabled = taaOn;
13300
+ if (taaOn) {
13301
+ const read = this.taaWrite ^ 1;
13302
+ const taa = this.taaMaterial;
13303
+ this.taaPrevViewProjection.copy(this.taaLastViewProjection);
13304
+ this.taaPrevView.copy(this.taaLastView);
13305
+ this.cameraWorld.copy(view).invert();
13306
+ taa.setParameter('curColor', this.colorTexture);
13307
+ taa.setParameter('curDepth', this.depthTexture);
13308
+ taa.setParameter('histColor', this.taaColor[read]);
13309
+ taa.setParameter('histInfo', this.taaInfo[read]);
13310
+ taa.setParameter('cameraWorld', this.cameraWorld.data);
13311
+ // x_ndc = (m00 x + m02 z) / -z for a perspective camera, m00 x + m03 for an orthographic one
13312
+ const sp = shaderProjection.data;
13313
+ taa.setParameter('unproject', isOrtho ? [sp[0], sp[5], sp[12], sp[13]] : [sp[0], sp[5], sp[8], sp[9]]);
13314
+ taa.setParameter('prevViewProj', this.taaPrevViewProjection.data);
13315
+ taa.setParameter('prevView', this.taaPrevView.data);
13316
+ taa.setParameter('clipZParams', clipZParams);
13317
+ // a changed resident set (detail streamed in) keeps the history but caps its weight,
13318
+ // so the new content shows within taaMoveMax frames rather than 1 / taaMax a frame
13319
+ taa.setParameter('taaParams', [
13320
+ moved || changed ? this.variant.taaMoveMax : this.variant.taaMax,
13321
+ this.taaHistoryValid ? 1 : 0,
13322
+ moved ? 1 : 0,
13323
+ this.restFrames
13324
+ ]);
13325
+ taa.setParameter('taaViewport', [width, height, 1 / width, 1 / height]);
13326
+ taa.setParameter('taaControl', [
13327
+ this.variant.taaFlip || (this.target.flipY ? -1 : 1),
13328
+ this.variant.taaClip,
13329
+ this.variant.spp === 'quad' ? 1 : 0,
13330
+ 0
13331
+ ]);
13332
+ taa.setParameter('taaDebug', this.variant.taaDebug);
13333
+ taa.setParameter('taaFilter', [
13334
+ this.variant.taaFilter === 'cubic' ? 1 : 0,
13335
+ this.variant.taaReproj === 'history' ? 1 : 0,
13336
+ this.variant.taaMotion,
13337
+ 0
13338
+ ]);
13339
+ this.taaPass.renderTarget = this.taaTargets[this.taaWrite];
13340
+ this.composeMaterial.setParameter('taaColor', this.taaColor[this.taaWrite]);
13341
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[this.taaWrite]);
13342
+ this.taaLastViewProjection.copy(this.viewProjection);
13343
+ this.taaLastView.copy(view);
13344
+ this.taaHistoryValid = true;
13345
+ this.taaWrite ^= 1;
13346
+ }
13347
+ // an offscreen target's rows run the other way to the backbuffer's on WebGPU
13348
+ const targetFlipY = rt ? rt.flipY : device.backBuffer.flipY;
13349
+ this.composeMaterial.setParameter('composeParams', [
13350
+ this.target.flipY !== targetFlipY ? 1 : 0,
13351
+ isOrtho ? 1 : 0,
13352
+ taaOn ? 1 : 0,
13353
+ 0
13354
+ ]);
13355
+ this.composeMaterial.setParameter('depthViewParams', [
13356
+ clipZ[0],
13357
+ clipZ[1],
13358
+ Math.max(cam.nearClip, 1e-4),
13359
+ Math.max(cam.farClip, cam.nearClip * 2)
13360
+ ]);
13361
+ this.composeMaterial.setParameter('cameraClipZ', [cameraClipZ[0], cameraClipZ[1], isOrtho ? 1 : 0, 0]);
13362
+ // cull:auto: read this culled frame's counts back (asynchronously, off the frame) and
13363
+ // keep the test only while it removes enough to pay for itself
13364
+ if (culling && cullMode === 'auto' && !isQuery && !this.cullStatsPending) {
13365
+ this.cullStatsPending = true;
13366
+ const data = new Uint32Array(2);
13367
+ this.counter
13368
+ .read(0, 8, data, false)
13369
+ .then(() => {
13370
+ const total = data[0] + data[1];
13371
+ const worthwhile = total > 0 && data[1] / total >= StochasticSplatRenderer.CULL_MIN_FRACTION;
13372
+ this.cullActive = worthwhile;
13373
+ if (!worthwhile)
13374
+ this.cullSuspendedFrames = StochasticSplatRenderer.CULL_SUSPEND_FRAMES;
13375
+ })
13376
+ .catch(() => {
13377
+ // a lost device or a destroyed buffer; the next frame tries again
13378
+ })
13379
+ .finally(() => {
13380
+ this.cullStatsPending = false;
13381
+ });
13382
+ }
13383
+ // this frame becomes the previous one, unless it is a capture
13384
+ if (isQuery) {
13385
+ // the capture drew elsewhere; the on-screen depth texture is no longer this frame's
13386
+ this.prevValid = false;
13387
+ this.depthFrame = null;
13388
+ this.setReady(true);
13389
+ return;
13390
+ }
13391
+ captureCameraSnapshot(camera.entity, this.depthFrameCamera);
13392
+ this.depthFrame = {
13393
+ id: ++this.depthFrameCount,
13394
+ camera: this.depthFrameCamera,
13395
+ width,
13396
+ height,
13397
+ clipZ: [clipZ[0], clipZ[1]]
13398
+ };
13399
+ this.prevViewProjection.copy(this.viewProjection);
13400
+ this.prevView.copy(view);
13401
+ this.prevProjection.copy(projection);
13402
+ this.prevClipZ = clipZParams;
13403
+ this.prevViewport = [width, height];
13404
+ this.prevFocal = focal;
13405
+ this.prevFlip = this.target.flipY ? -1 : 1;
13406
+ this.prevWidth = width;
13407
+ this.prevHeight = height;
13408
+ this.prevVersion = set.version;
13409
+ this.prevOrtho = isOrtho;
13410
+ this.prevValid = !isQuery;
13411
+ this.setReady(true);
13412
+ }
13413
+ resizeHistory(width, height) {
13414
+ for (const texture of [...this.taaColor, ...this.taaInfo])
13415
+ texture.resize(width, height);
13416
+ for (const target of this.taaTargets)
13417
+ target.resize(width, height);
13418
+ }
13419
+ // whether the view or the projection differs from the previous on-screen frame's beyond
13420
+ // float noise (the camera controllers settle over many frames; a fov animation moves the
13421
+ // image without moving the camera)
13422
+ viewMoved(view, projection) {
13423
+ for (let i = 0; i < 16; i++) {
13424
+ if (Math.abs(view.data[i] - this.prevView.data[i]) > 1e-6)
13425
+ return true;
13426
+ if (Math.abs(projection.data[i] - this.prevProjection.data[i]) > 1e-6)
13427
+ return true;
13428
+ }
13429
+ return false;
13430
+ }
13431
+ // one chunk-table entry per CHUNK_SIZE splats of every resident node
13432
+ rebuildChunkTable(set) {
13433
+ let count = 0;
13434
+ for (const node of set.nodes)
13435
+ count += Math.ceil(node.count / CHUNK_SIZE);
13436
+ if (this.chunkData.length < count * 4) {
13437
+ this.chunkData = new Uint32Array(Math.ceil(count * 1.25) * 4);
13438
+ this.chunkBuffer?.destroy();
13439
+ this.chunkBuffer = new StorageBuffer(this.device, this.chunkData.byteLength, BUFFERUSAGE_COPY_DST);
13440
+ }
13441
+ const data = this.chunkData;
13442
+ let k = 0;
13443
+ set.nodes.forEach((node, nodeIndex) => {
13444
+ const base = this.source.chunkBase(node);
13445
+ for (let offset = 0; offset < node.count; offset += CHUNK_SIZE) {
13446
+ data[k++] = base + offset;
13447
+ data[k++] = Math.min(CHUNK_SIZE, node.count - offset);
13448
+ data[k++] = nodeIndex;
13449
+ data[k++] = (node.lodIndex & 0xffff) | (node.fileIndex << 16);
13450
+ }
13451
+ });
13452
+ this.numChunks = count;
13453
+ // writeBuffer counts typed-array elements, not bytes
13454
+ if (count > 0)
13455
+ this.chunkBuffer.write(0, data, 0, count * 4);
13456
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
13457
+ if (this.nodeVisibleData.length < words) {
13458
+ this.nodeVisibleData = new Uint32Array(words);
13459
+ this.nodeVisibleBuffer?.destroy();
13460
+ this.nodeVisibleBuffer = new StorageBuffer(this.device, words * 4, BUFFERUSAGE_COPY_DST);
13461
+ }
13462
+ }
13463
+ // the cache is dense (indexed by compact slot), so it only needs room for the resident
13464
+ // splats, not the allocator's address space; grown geometrically, never shrunk
13465
+ ensureCache(splats) {
13466
+ if (splats <= this.cacheSlots)
13467
+ return;
13468
+ this.cacheBuffer?.destroy();
13469
+ this.orderedBuffer?.destroy();
13470
+ this.cacheSlots = Math.max(1, Math.ceil(splats * 1.25));
13471
+ this.cacheBuffer = new StorageBuffer(this.device, this.cacheSlots * CACHE_WORDS * 4, BUFFERUSAGE_COPY_SRC);
13472
+ this.orderedBuffer = new StorageBuffer(this.device, this.cacheSlots * 4);
13473
+ }
13474
+ // sphere-frustum test per node on the cpu: thousands of nodes, one bit each
13475
+ cullNodes(set, viewProjection) {
13476
+ const bits = this.nodeVisibleData;
13477
+ bits.fill(0);
13478
+ this.frustum.setFromMat4(viewProjection);
13479
+ const spheres = set.nodeSpheres;
13480
+ const { sphere } = this;
13481
+ for (let i = 0; i < set.nodes.length; i++) {
13482
+ sphere.center.set(spheres[i * 4], spheres[i * 4 + 1], spheres[i * 4 + 2]);
13483
+ sphere.radius = spheres[i * 4 + 3];
13484
+ if (this.frustum.containsSphere(sphere) !== 0) {
13485
+ bits[i >> 5] |= 1 << (i & 31);
13486
+ }
13487
+ }
13488
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
13489
+ this.nodeVisibleBuffer.write(0, bits, 0, words);
13490
+ }
13491
+ anyNodeVisible(nodes) {
13492
+ const bits = this.nodeVisibleData;
13493
+ return nodes.some((node) => (bits[node.nodeIndex >> 5] >>> (node.nodeIndex & 31)) & 1);
13494
+ }
13495
+ ensureProjector(occlusion, ordered, group) {
13496
+ const sourceKey = this.source.shaderKey();
13497
+ if (this.projectorSourceKey !== sourceKey) {
13498
+ // a different source: every specialisation and the bind group format go
13499
+ this.destroyProjector();
13500
+ this.projectorSourceKey = sourceKey;
13501
+ }
13502
+ const key = `${occlusion ? 'occlusion' : 'plain'}-${ordered ? 'bucket' : 'append'}`;
13503
+ const computeKey = `${key}:${group.fileIndex}`;
13504
+ const existing = this.projectorComputes.get(computeKey);
13505
+ if (existing)
13506
+ return existing;
13507
+ const shader = this.ensureProjectorShader(key, occlusion, ordered);
13508
+ const compute = new Compute(this.device, shader, 'sse-splat-project');
13509
+ this.projectorComputes.set(computeKey, compute);
13510
+ return compute;
13511
+ }
13512
+ // drop the computes of files that left the resident set
13513
+ pruneProjectorComputes(set) {
13514
+ for (const [key, compute] of this.projectorComputes) {
13515
+ const fileIndex = Number(key.slice(key.lastIndexOf(':') + 1));
13516
+ if (fileIndex >= 0 && !set.files[fileIndex]) {
13517
+ compute.destroy();
13518
+ this.projectorComputes.delete(key);
13519
+ }
13520
+ }
13521
+ }
13522
+ ensureProjectorShader(key, occlusion, ordered) {
13523
+ const existing = this.projectorShaders.get(key);
13524
+ if (existing)
13525
+ return existing;
13526
+ const { device } = this;
13527
+ const fixed = [
13528
+ new BindStorageBufferFormat('chunks', SHADERSTAGE_COMPUTE, true),
13529
+ new BindStorageBufferFormat('nodeVisible', SHADERSTAGE_COMPUTE, true),
13530
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE),
13531
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE),
13532
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE),
13533
+ new BindStorageBufferFormat('occL1', SHADERSTAGE_COMPUTE, true),
13534
+ new BindStorageBufferFormat('occL2', SHADERSTAGE_COMPUTE, true),
13535
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)
13536
+ ];
13537
+ const formats = [...fixed, ...this.source.bindFormats()];
13538
+ this.projectorBindGroupFormat ??= new BindGroupFormat(device, formats);
13539
+ const shader = new Shader(device, {
13540
+ name: `sse-splat-project-${key}`,
13541
+ shaderLanguage: SHADERLANGUAGE_WGSL,
13542
+ cshader: projectorWGSL(this.source.readChunk(fixed.length), occlusion, ordered),
13543
+ cincludes: this.source.shaderIncludes(),
13544
+ cdefines: this.source.shaderDefines(),
13545
+ computeUniformBufferFormats: {
13546
+ // the same order as the wgsl struct; both follow the same alignment rules
13547
+ uniforms: new UniformBufferFormat(device, [
13548
+ new UniformFormat('view', UNIFORMTYPE_MAT4),
13549
+ new UniformFormat('viewProj', UNIFORMTYPE_MAT4),
13550
+ new UniformFormat('prevViewProj', UNIFORMTYPE_MAT4),
13551
+ new UniformFormat('prevView', UNIFORMTYPE_MAT4),
13552
+ new UniformFormat('prevClipZ', UNIFORMTYPE_VEC4),
13553
+ new UniformFormat('viewport', UNIFORMTYPE_VEC2),
13554
+ new UniformFormat('focal', UNIFORMTYPE_VEC2),
13555
+ new UniformFormat('prevViewport', UNIFORMTYPE_VEC2),
13556
+ new UniformFormat('prevFocal', UNIFORMTYPE_VEC2),
13557
+ new UniformFormat('numChunks', UNIFORMTYPE_UINT),
13558
+ new UniformFormat('splatTextureSize', UNIFORMTYPE_UINT),
13559
+ new UniformFormat('isOrtho', UNIFORMTYPE_UINT),
13560
+ new UniformFormat('minPixelSize', UNIFORMTYPE_FLOAT),
13561
+ new UniformFormat('alphaClip', UNIFORMTYPE_FLOAT),
13562
+ new UniformFormat('minContribution', UNIFORMTYPE_FLOAT),
13563
+ new UniformFormat('occBlocksX1', UNIFORMTYPE_UINT),
13564
+ new UniformFormat('occBlocksY1', UNIFORMTYPE_UINT),
13565
+ new UniformFormat('occBlocksX2', UNIFORMTYPE_UINT),
13566
+ new UniformFormat('occBlocksY2', UNIFORMTYPE_UINT),
13567
+ new UniformFormat('occlusionMode', UNIFORMTYPE_UINT),
13568
+ new UniformFormat('prevFlip', UNIFORMTYPE_FLOAT),
13569
+ new UniformFormat('keyLogNear', UNIFORMTYPE_FLOAT),
13570
+ new UniformFormat('keyInvLogRange', UNIFORMTYPE_FLOAT),
13571
+ new UniformFormat('chunkBase', UNIFORMTYPE_UINT),
13572
+ new UniformFormat('model', UNIFORMTYPE_MAT4),
13573
+ new UniformFormat('modelRotation', UNIFORMTYPE_VEC4),
13574
+ new UniformFormat('modelScale', UNIFORMTYPE_VEC4),
13575
+ new UniformFormat('cameraPosition', UNIFORMTYPE_VEC4),
13576
+ new UniformFormat('colorMax', UNIFORMTYPE_FLOAT),
13577
+ new UniformFormat('unitScale', UNIFORMTYPE_FLOAT),
13578
+ new UniformFormat('depthNear', UNIFORMTYPE_FLOAT),
13579
+ new UniformFormat('depthFar', UNIFORMTYPE_FLOAT)
13580
+ ])
13581
+ },
13582
+ computeBindGroupFormat: this.projectorBindGroupFormat
13583
+ });
13584
+ this.projectorShaders.set(key, shader);
13585
+ return shader;
13586
+ }
13587
+ destroyProjector() {
13588
+ for (const compute of this.projectorComputes.values())
13589
+ compute.destroy();
13590
+ this.projectorComputes.clear();
13591
+ for (const shader of this.projectorShaders.values())
13592
+ shader.destroy();
13593
+ this.projectorShaders.clear();
13594
+ this.projectorBindGroupFormat?.destroy();
13595
+ this.projectorBindGroupFormat = null;
13596
+ this.projectorSourceKey = '';
13597
+ }
13598
+ destroy() {
13599
+ this.unsubscribe();
13600
+ this.app.off('frameend', this.onFrameEnd);
13601
+ this.detach();
13602
+ this.provider.destroy();
13603
+ this.source.destroy();
13604
+ this.destroyProjector();
13605
+ this.args.shader.destroy();
13606
+ this.args.destroy();
13607
+ this.argsBindGroupFormat.destroy();
13608
+ for (const compute of [this.reduceL1, this.reduceL2]) {
13609
+ compute.shader.destroy();
13610
+ compute.destroy();
13611
+ }
13612
+ for (const format of this.reduceFormats)
13613
+ format.destroy();
13614
+ this.occL1.destroy();
13615
+ this.occL2.destroy();
13616
+ for (const compute of [this.orderScan, this.orderScatter]) {
13617
+ compute.shader.destroy();
13618
+ compute.destroy();
13619
+ }
13620
+ for (const format of this.orderFormats)
13621
+ format.destroy();
13622
+ this.orderBuckets.destroy();
13623
+ this.orderedBuffer?.destroy();
13624
+ this.orderedBuffer = null;
13625
+ this.chunkBuffer?.destroy();
13626
+ this.nodeVisibleBuffer?.destroy();
13627
+ this.cacheBuffer?.destroy();
13628
+ this.counter.destroy();
13629
+ this.chunkBuffer = this.nodeVisibleBuffer = this.cacheBuffer = null;
13630
+ this.rasterPass.destroy();
13631
+ this.rasterInstance.destroy();
13632
+ this.rasterMaterial.destroy();
13633
+ this.rasterMesh.destroy();
13634
+ this.taaPass.destroy();
13635
+ this.taaInstance.destroy();
13636
+ this.taaMaterial.destroy();
13637
+ this.taaMesh.destroy();
13638
+ for (const target of this.taaTargets)
13639
+ target.destroy();
13640
+ for (const texture of [...this.taaColor, ...this.taaInfo])
13641
+ texture.destroy();
13642
+ this.taaTargets.length = 0;
13643
+ this.taaColor.length = 0;
13644
+ this.taaInfo.length = 0;
13645
+ this.target.destroy();
13646
+ this.colorTexture.destroy();
13647
+ this.depthTexture.destroy();
13648
+ this.composeInstance.destroy();
13649
+ this.composeMaterial.destroy();
13650
+ this.composeMesh.destroy();
13651
+ }
13652
+ }
13653
+
13654
+ // ---------------------------------------------------------------------------
13655
+ // WGSL compute shader: ray-march through the sparse voxel octree per pixel
13656
+ // ---------------------------------------------------------------------------
13657
+ const voxelOverlayWGSL = /* wgsl */ `
13658
+
13659
+ // Solid leaf sentinel: childMask=0xFF, baseOffset=0
13660
+ const SOLID_LEAF_MARKER: u32 = 0xFF000000u;
13661
+
13662
+ // Maximum DDA steps to prevent infinite loops
13663
+ const MAX_STEPS: u32 = 512u;
13664
+
13665
+ // Target wireframe edge width in pixels
13666
+ const EDGE_PIXELS: f32 = 1.5;
13667
+
13668
+ // Keep edges tinted so dense grids retain the solid/free-space distinction.
13669
+ const EDGE_ALPHA: f32 = 0.8;
13670
+
13671
+ const FILL_ALPHA: f32 = 0.4;
13672
+
13673
+ struct Uniforms {
13674
+ invVP: mat4x4<f32>,
13675
+ screenWidth: u32,
13676
+ screenHeight: u32,
13677
+ gridMinX: f32,
13678
+ gridMinY: f32,
13679
+ gridMinZ: f32,
13680
+ voxelRes: f32,
13681
+ numVoxelsX: u32,
13682
+ numVoxelsY: u32,
13683
+ numVoxelsZ: u32,
13684
+ leafSize: u32,
13685
+ treeDepth: u32,
13686
+ projScaleY: f32,
13687
+ displayMode: u32,
13688
+ inverted: u32
13689
+ };
13690
+
13691
+ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
13692
+ @group(0) @binding(1) var<storage, read> nodes: array<u32>;
13693
+ @group(0) @binding(2) var<storage, read> leafData: array<u32>;
13694
+ @group(0) @binding(3) var outputTexture: texture_storage_2d<rgba8unorm, write>;
13695
+
13696
+ // ---- helpers ----
13697
+
13698
+ // Traverse the octree for block (bx, by, bz). Returns vec2u(result, skipLevel):
13699
+ // result: 0 = empty, 1 = solid, 2+ = mixed leaf (2 + leafDataIndex)
13700
+ // skipLevel: octree level for multi-block skipping (meaningful when result == 0 or 1)
13701
+ fn queryBlock(bx: i32, by: i32, bz: i32) -> vec2u {
13702
+ let depth = uniforms.treeDepth;
13703
+ var nodeIndex: u32 = 0u;
13704
+
13705
+ for (var level: u32 = depth - 1u; ; ) {
13706
+ let node = nodes[nodeIndex];
13707
+
13708
+ // Solid leaf sentinel -- return level + 1 so the caller can skip 2^(level+1) blocks
13709
+ if (node == SOLID_LEAF_MARKER) {
13710
+ return vec2u(1u, level + 1u);
13711
+ }
13712
+
13713
+ let childMask = (node >> 24u) & 0xFFu;
13714
+
13715
+ // childMask == 0 means this is a mixed leaf node
13716
+ if (childMask == 0u) {
13717
+ let leafIdx = node & 0x00FFFFFFu;
13718
+ return vec2u(2u + leafIdx, 0u);
13719
+ }
13720
+
13721
+ // Determine octant at this level
13722
+ let bitX = (u32(bx) >> level) & 1u;
13723
+ let bitY = (u32(by) >> level) & 1u;
13724
+ let bitZ = (u32(bz) >> level) & 1u;
13725
+ let octant = (bitZ << 2u) | (bitY << 1u) | bitX;
13726
+
13727
+ // Check if child exists
13728
+ if ((childMask & (1u << octant)) == 0u) {
13729
+ return vec2u(0u, level);
13730
+ }
13731
+
13732
+ // Compute child index
13733
+ let baseOffset = node & 0x00FFFFFFu;
13734
+ let prefix = (1u << octant) - 1u;
13735
+ let childOffset = countOneBits(childMask & prefix);
13736
+ nodeIndex = baseOffset + childOffset;
13737
+
13738
+ if (level == 0u) { break; }
13739
+ level -= 1u;
13740
+ }
13741
+
13742
+ // Reached leaf level
13743
+ let node = nodes[nodeIndex];
13744
+ if (node == SOLID_LEAF_MARKER) {
13745
+ return vec2u(1u, 0u);
13746
+ }
13747
+ let leafIdx = node & 0x00FFFFFFu;
13748
+ return vec2u(2u + leafIdx, 0u);
10236
13749
  }
10237
13750
 
10238
13751
  // Ray-AABB intersection returning (tNear, tFar). If tNear > tFar → miss.
@@ -10984,6 +14497,17 @@ const rendererTable = {
10984
14497
  webgl: GSPLAT_RENDERER_RASTER_CPU_SORT,
10985
14498
  webgpu: GSPLAT_RENDERER_RASTER_GPU_SORT
10986
14499
  };
14500
+ // quality budget, millions of splats
14501
+ const budgets = {
14502
+ mobile: {
14503
+ low: 1,
14504
+ high: 2
14505
+ },
14506
+ desktop: {
14507
+ low: 2,
14508
+ high: 4
14509
+ }
14510
+ };
10987
14511
  const tonemapTable = {
10988
14512
  none: TONEMAP_NONE,
10989
14513
  linear: TONEMAP_LINEAR,
@@ -11078,6 +14602,13 @@ class Viewer {
11078
14602
  meshOverlay = null;
11079
14603
  navCursor = null;
11080
14604
  debugPanel = null;
14605
+ /** The opt-in stochastic renderer (WebGPU only); null when the engine's sorted renderer draws. */
14606
+ splatRenderer = null;
14607
+ /**
14608
+ * The engine's MiniStats panel once first shown (`?ministats` or the debug panel), else null.
14609
+ * Hiding disables it rather than destroying it.
14610
+ */
14611
+ miniStats = null;
11081
14612
  /** Set once {@link destroy} has run. Load continuations check it and bail. */
11082
14613
  destroyed = false;
11083
14614
  disposers = [];
@@ -11137,10 +14668,35 @@ class Viewer {
11137
14668
  app.autoRender = true;
11138
14669
  // configure the camera
11139
14670
  this.configureCamera(settings);
11140
- // reconfigure camera when entering/exiting XR
14671
+ // The stochastic renderer, when opted in. Created before the first frame so it can
14672
+ // switch the engine's own splat renderer off as soon as the engine creates it. An
14673
+ // instance without the flag never constructs it, and the sorted path is untouched.
14674
+ if (config.stochastic && renderer === 'webgpu') {
14675
+ const worldLayer = app.scene.layers.getLayerByName('World');
14676
+ // the largest budget this instance can ask for must fit the device's storage binding
14677
+ const budget = (config.budget && config.budget > 0
14678
+ ? config.budget
14679
+ : (platform.mobile ? budgets.mobile : budgets.desktop).high) * 1000000;
14680
+ if (!StochasticSplatRenderer.cacheFits(app.graphicsDevice, budget)) {
14681
+ console.warn(`stochastic renderer: a ${budget / 1000000}M splat budget exceeds this device's storage binding limit; the sorted renderer draws`);
14682
+ }
14683
+ else if (worldLayer) {
14684
+ this.splatRenderer = new StochasticSplatRenderer(app, camera.camera, worldLayer, {
14685
+ source: config.splatSource,
14686
+ variant: config.variant
14687
+ });
14688
+ // announced on the first frame rather than here: createViewer resolves after this
14689
+ // constructor, so a page can only subscribe once loading is under way
14690
+ events.once('firstFrame', () => events.fire('splatRenderer:ready', this.splatRenderer));
14691
+ }
14692
+ }
14693
+ // reconfigure camera when entering/exiting XR. The stochastic renderer has no stereo
14694
+ // path yet, so the engine's renderer draws the splats for the session
11141
14695
  const configureXrCamera = () => {
11142
- if (!this.destroyed)
11143
- this.configureCamera(settings);
14696
+ if (this.destroyed)
14697
+ return;
14698
+ this.configureCamera(settings);
14699
+ this.splatRenderer?.setEnabled(!app.xr.active);
11144
14700
  };
11145
14701
  const xrStart = app.xr.on('start', configureXrCamera);
11146
14702
  const xrEnd = app.xr.on('end', configureXrCamera);
@@ -11148,28 +14704,12 @@ class Viewer {
11148
14704
  xrStart.off();
11149
14705
  xrEnd.off();
11150
14706
  });
11151
- // construct debug ministats
11152
- if (config.ministats) {
11153
- const options = MiniStats.getDefaultOptions();
11154
- options.cpu.enabled = false;
11155
- options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
11156
- options.stats.push({
11157
- name: 'VRAM',
11158
- stats: ['vram.tex'],
11159
- decimalPlaces: 1,
11160
- multiplier: 1 / (1024 * 1024),
11161
- unitsName: 'MB',
11162
- watermark: 1024
11163
- }, {
11164
- name: 'Splats',
11165
- stats: ['frame.gsplats'],
11166
- decimalPlaces: 3,
11167
- multiplier: 1 / 1000000,
11168
- unitsName: 'M',
11169
- watermark: 5
11170
- });
11171
- new MiniStats(app, options);
11172
- }
14707
+ // debug ministats, from the flag at start and the debug panel's toggle after
14708
+ this.setMiniStats(config.ministats);
14709
+ this.onDestroy(() => {
14710
+ this.miniStats?.destroy();
14711
+ this.miniStats = null;
14712
+ });
11173
14713
  const prevProj = new Mat4();
11174
14714
  const prevWorld = new Mat4();
11175
14715
  const sceneBound = new BoundingBox();
@@ -11178,7 +14718,7 @@ class Viewer {
11178
14718
  const world = camera.getWorldTransform();
11179
14719
  const proj = camera.camera.projectionMatrix;
11180
14720
  if (!app.renderNextFrame) {
11181
- if (config.ministats ||
14721
+ if (this.miniStats?.enabled ||
11182
14722
  !nearlyEquals(world.data, prevWorld.data) ||
11183
14723
  !nearlyEquals(proj.data, prevProj.data)) {
11184
14724
  app.renderNextFrame = true;
@@ -11359,7 +14899,12 @@ class Viewer {
11359
14899
  if (gsplatBbox) {
11360
14900
  sceneBound.setFromTransformedAabb(gsplatBbox, results[0].getWorldTransform());
11361
14901
  }
11362
- this.picker = new Picker(app, camera);
14902
+ // the stochastic renderer leaves its frame's depth behind, so no pick pass is needed
14903
+ this.picker = this.splatRenderer
14904
+ ? new FrameDepthPicker(app, camera, this.splatRenderer)
14905
+ : new Picker(app, camera);
14906
+ // for development pages (the bench measures pick noise), as splatRenderer:ready
14907
+ events.fire('picker:ready', this.picker);
11363
14908
  this.inputController = new InputController(global, this.picker);
11364
14909
  this.cameraManager = new CameraManager(global, sceneBound);
11365
14910
  applyCamera(this.cameraManager.camera);
@@ -11409,18 +14954,10 @@ class Viewer {
11409
14954
  // collision may already have landed while the splats were still streaming
11410
14955
  if (collisionReady)
11411
14956
  attachCollision(collisionReady);
11412
- this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker);
11413
- // quality budget
11414
- const budgets = {
11415
- mobile: {
11416
- low: 1,
11417
- high: 2
11418
- },
11419
- desktop: {
11420
- low: 2,
11421
- high: 4
11422
- }
11423
- };
14957
+ this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker, this.splatRenderer, {
14958
+ shown: () => !!this.miniStats?.enabled,
14959
+ show: (value) => this.setMiniStats(value)
14960
+ });
11424
14961
  const applyPerfSettings = () => {
11425
14962
  const budget = () => {
11426
14963
  if (config.budget !== undefined && Number.isFinite(config.budget) && config.budget > 0) {
@@ -11475,7 +15012,12 @@ class Viewer {
11475
15012
  // handle quality mode changes
11476
15013
  events.on('performanceMode:changed', applyPerfSettings);
11477
15014
  applyPerfSettings();
11478
- gsplat.renderer = rendererTable[renderer];
15015
+ // the stochastic renderer consumes the engine's world under whatever
15016
+ // renderer mode the engine resolved; switching modes here would rebuild
15017
+ // the work buffer for nothing
15018
+ if (!this.splatRenderer) {
15019
+ gsplat.renderer = rendererTable[renderer];
15020
+ }
11479
15021
  // wait for the first valid frame to complete rendering
11480
15022
  app.once('frameend', () => {
11481
15023
  events.fire('firstFrame');
@@ -11625,6 +15167,49 @@ class Viewer {
11625
15167
  }
11626
15168
  this.disposers.push(fn);
11627
15169
  }
15170
+ /**
15171
+ * Show or hide the engine's MiniStats panel. While shown the viewer renders every frame, so
15172
+ * the graphs keep moving.
15173
+ */
15174
+ setMiniStats(value) {
15175
+ if (value === !!this.miniStats?.enabled)
15176
+ return;
15177
+ // hidden by disabling rather than destroying: the engine's destroy() leaves its stats
15178
+ // timers reading every frame and its buffers allocated, so a panel per toggle would pile
15179
+ // them up until teardown
15180
+ if (this.miniStats) {
15181
+ this.miniStats.enabled = value;
15182
+ // the panel's transparent div would keep catching clicks over the canvas
15183
+ this.miniStats.div.style.display = value ? '' : 'none';
15184
+ if (value) {
15185
+ // enabling turns every graph on, the text-only size's too: its size puts them back
15186
+ const size = this.miniStats.activeSizeIndex;
15187
+ this.miniStats.activeSizeIndex = size;
15188
+ this.global.app.renderNextFrame = true;
15189
+ }
15190
+ return;
15191
+ }
15192
+ const options = MiniStats.getDefaultOptions();
15193
+ options.cpu.enabled = false;
15194
+ options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
15195
+ options.stats.push({
15196
+ name: 'VRAM',
15197
+ stats: ['vram.tex'],
15198
+ decimalPlaces: 1,
15199
+ multiplier: 1 / (1024 * 1024),
15200
+ unitsName: 'MB',
15201
+ watermark: 1024
15202
+ }, {
15203
+ name: 'Splats',
15204
+ stats: ['frame.gsplats'],
15205
+ decimalPlaces: 3,
15206
+ multiplier: 1 / 1000000,
15207
+ unitsName: 'M',
15208
+ watermark: 5
15209
+ });
15210
+ this.miniStats = new MiniStats(this.global.app, options);
15211
+ this.global.app.renderNextFrame = true;
15212
+ }
11628
15213
  /**
11629
15214
  * Tear the viewer down: stop rendering, remove every listener it added to the window,
11630
15215
  * document and canvas, restore the globals it patched, and release the graphics device.
@@ -11655,6 +15240,8 @@ class Viewer {
11655
15240
  this.voxelOverlay?.destroy();
11656
15241
  this.meshOverlay?.destroy();
11657
15242
  this.picker?.release();
15243
+ this.splatRenderer?.destroy();
15244
+ this.splatRenderer = null;
11658
15245
  this.capture?.destroy();
11659
15246
  this.capture = null;
11660
15247
  if (this.cameraFrame) {
@@ -11850,6 +15437,12 @@ const createApp = async (canvas, config) => {
11850
15437
  touch: new TouchDevice$1(canvas),
11851
15438
  keyboard: new Keyboard(window)
11852
15439
  });
15440
+ // The stochastic renderer never sorts on the cpu, so the per-splat centres the engine
15441
+ // reads back for its cpu sort (12 bytes each, plus a gpu readback per file) are dead
15442
+ // weight. Read once per file at load, so it has to be set before any asset loads.
15443
+ if (config.stochastic && renderer === 'webgpu') {
15444
+ app.scene.gsplatCentersEnabled = false;
15445
+ }
11853
15446
  // enable anonymous CORS for image loading in safari (must be set before any
11854
15447
  // texture asset starts loading, otherwise the <img> is fetched without the
11855
15448
  // crossorigin attribute and WebGL rejects it with SecurityError)
@@ -11953,6 +15546,9 @@ const resolveConfig = (options) => ({
11953
15546
  colorize: options.colorize ?? false,
11954
15547
  fullload: options.fullload ?? false,
11955
15548
  aa: options.aa ?? false,
15549
+ stochastic: options.stochastic ?? false,
15550
+ splatSource: options.splatSource ?? 'workbuffer',
15551
+ variant: options.variant ?? '',
11956
15552
  budget: options.budget,
11957
15553
  heatmap: options.heatmap ?? false,
11958
15554
  debug: options.debug ?? false,