@playcanvas/supersplat-viewer 1.35.2 → 1.36.1

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, PROJECTION_PERSPECTIVE, math, Script, Entity, Mat4, version as version$1, Quat, 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, 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.2";
2561
+ var version = "1.36.1";
2562
2562
 
2563
2563
  class Tooltip {
2564
2564
  register;
@@ -2723,6 +2723,58 @@ const initAnnotationControls = (viewer, root) => {
2723
2723
  };
2724
2724
  };
2725
2725
 
2726
+ /**
2727
+ * Displacement-based inputs (mouse, touch, wheel, pinch) return accumulated
2728
+ * pixel offsets that already scale with frame time. This factor converts
2729
+ * rate-based speed constants (tuned for degrees-per-second) to work with
2730
+ * per-frame displacements, making them frame-rate-independent.
2731
+ */
2732
+ const DISPLACEMENT_SCALE = 1 / 60;
2733
+ /** Maximum accumulated touch movement (px) to still count as a tap. */
2734
+ const TAP_EPSILON = 15;
2735
+ const tmpHalfSize = new Vec3();
2736
+ /**
2737
+ * Converts screen-space pixel deltas to a world-space pan vector at the
2738
+ * given depth.
2739
+ *
2740
+ * @param camera - The camera component.
2741
+ * @param dx - Horizontal pixel delta.
2742
+ * @param dy - Vertical pixel delta.
2743
+ * @param dz - Depth (world-space) at which to project the delta.
2744
+ * @param out - Optional output vector.
2745
+ * @returns The pan vector in world space.
2746
+ */
2747
+ const screenToWorld = (camera, dx, dy, dz, out = new Vec3()) => {
2748
+ const { system, fov, aspectRatio, horizontalFov, projection, orthoHeight } = camera;
2749
+ const { width, height } = system.app.graphicsDevice.clientRect;
2750
+ out.set(-(dx / width) * 2, (dy / height) * 2, 0);
2751
+ const halfSize = tmpHalfSize.set(0, 0, 0);
2752
+ if (projection === PROJECTION_PERSPECTIVE) {
2753
+ const halfSlice = dz * Math.tan(0.5 * fov * math.DEG_TO_RAD);
2754
+ if (horizontalFov) {
2755
+ halfSize.set(halfSlice, halfSlice / aspectRatio, 0);
2756
+ }
2757
+ else {
2758
+ halfSize.set(halfSlice * aspectRatio, halfSlice, 0);
2759
+ }
2760
+ }
2761
+ else {
2762
+ halfSize.set(orthoHeight * aspectRatio, orthoHeight, 0);
2763
+ }
2764
+ out.mul(halfSize);
2765
+ return out;
2766
+ };
2767
+ /**
2768
+ * The orbit camera and the fly camera disagree on the sign of the z-axis
2769
+ * for forward motion. Apply this when emitting a forward/back z-component
2770
+ * so the same wheel-style delta drives both cameras correctly.
2771
+ *
2772
+ * @param mode - The current camera mode.
2773
+ * @param z - The raw forward/back z-component.
2774
+ * @returns The z-component flipped for orbit mode, unchanged otherwise.
2775
+ */
2776
+ const flipZForOrbit = (mode, z) => (mode === 'orbit' ? -z : z);
2777
+
2726
2778
  const vec$1 = new Vec3();
2727
2779
  /**
2728
2780
  * A script for creating interactive 3D annotations in a scene. Each annotation consists of:
@@ -2798,8 +2850,9 @@ class Annotation extends Script {
2798
2850
  }
2799
2851
  /**
2800
2852
  * Update the screen-space elements for this annotation. Called each frame from the
2801
- * prerender callback, and also directly from showTooltip to ensure the tooltip is positioned
2802
- * correctly even when the camera hasn't moved (e.g. annotations sharing the same camera pose).
2853
+ * prerender callback, and also directly from revealTooltip to ensure the tooltip is
2854
+ * positioned correctly even when the camera hasn't moved (e.g. annotations sharing the same
2855
+ * camera pose).
2803
2856
  * @private
2804
2857
  */
2805
2858
  _update() {
@@ -2827,16 +2880,33 @@ class Annotation extends Script {
2827
2880
  this.hotspotDom.classList.toggle('sse-occluded', occluded);
2828
2881
  }
2829
2882
  /**
2883
+ * Make this the annotation whose tooltip shows. The tooltip itself waits for the camera to
2884
+ * near the end of its move here, when `Annotations` calls `revealTooltip`, rather than
2885
+ * chasing the hotspot across the screen during the flight.
2830
2886
  * @private
2831
2887
  */
2832
2888
  showTooltip() {
2833
2889
  const ctx = this.context;
2834
2890
  ctx.activeAnnotation = this;
2835
- ctx.titleDom.textContent = this.title;
2836
- ctx.textDom.textContent = this.text;
2837
- ctx.tooltipDom.classList.add('sse-visible');
2891
+ ctx.revealed = false;
2838
2892
  this.hotspotDom.classList.add('sse-active');
2839
- // Immediately update incase the camera doesn't move
2893
+ }
2894
+ /**
2895
+ * Show the tooltip beside this annotation, the camera being at or nearly at rest.
2896
+ * @private
2897
+ */
2898
+ revealTooltip() {
2899
+ const ctx = this.context;
2900
+ ctx.revealed = true;
2901
+ if (ctx.tooltipOwner !== this) {
2902
+ // taken over only now, so the tooltip fades out with the previous annotation's text,
2903
+ // beside its hotspot; and with no side yet, rather than the one it left it on
2904
+ ctx.tooltipOwner = this;
2905
+ ctx.titleDom.textContent = this.title;
2906
+ ctx.textDom.textContent = this.text;
2907
+ ctx.tooltipDom.classList.remove('sse-arrow-left', 'sse-arrow-right');
2908
+ }
2909
+ // the camera may be still, so no prerender may follow
2840
2910
  this._update();
2841
2911
  }
2842
2912
  /**
@@ -2854,7 +2924,7 @@ class Annotation extends Script {
2854
2924
  */
2855
2925
  _hideElements() {
2856
2926
  this.hotspotDom.style.display = 'none';
2857
- if (this.context.activeAnnotation === this) {
2927
+ if (this.context.tooltipOwner === this) {
2858
2928
  this.context.tooltipDom.classList.remove('sse-visible');
2859
2929
  }
2860
2930
  }
@@ -2873,28 +2943,43 @@ class Annotation extends Script {
2873
2943
  // nearer hotspots draw over farther ones
2874
2944
  hotspot.style.zIndex = String(Math.round(100000 / (1 + distance)));
2875
2945
  const ctx = this.context;
2876
- if (ctx.activeAnnotation !== this) {
2946
+ if (ctx.tooltipOwner !== this) {
2877
2947
  return;
2878
2948
  }
2879
- // Re-show tooltip if it was hidden while behind camera
2949
+ // Shown while this annotation is selected and revealed, clamped to the canvas when the
2950
+ // hotspot is beyond it, so moving the camera yourself does not lose it. Hidden, it fades
2951
+ // out, moving with the hotspot at the offset it last had rather than standing still while
2952
+ // the camera moves on
2880
2953
  const tooltip = ctx.tooltipDom;
2881
- tooltip.classList.add('sse-visible');
2882
- // Position tooltip, clamped to the canvas (screenPos is in canvas pixels)
2954
+ const vw = ctx.canvas.clientWidth;
2955
+ const vh = ctx.canvas.clientHeight;
2956
+ const onCanvas = screenPos.x >= 0 && screenPos.x <= vw && screenPos.y >= 0 && screenPos.y <= vh;
2957
+ if (ctx.activeAnnotation !== this || !ctx.revealed) {
2958
+ tooltip.classList.remove('sse-visible');
2959
+ const offset = ctx.tooltipOffset;
2960
+ if (offset) {
2961
+ tooltip.style.transform = `translate(${screenPos.x + offset.x}px, ${screenPos.y + offset.y}px)`;
2962
+ }
2963
+ return;
2964
+ }
2965
+ // Position tooltip, clamped to the canvas (screenPos is in canvas pixels). Measured
2966
+ // before it is shown, which also lets a tooltip that was empty, and so not displayed,
2967
+ // fade in rather than appear at once
2883
2968
  const margin = 8;
2884
2969
  const arrowOffset = 24;
2885
2970
  const tw = tooltip.offsetWidth;
2886
2971
  const th = tooltip.offsetHeight;
2887
- const vw = ctx.canvas.clientWidth;
2888
- const vh = ctx.canvas.clientHeight;
2889
- // Default position: to the right of hotspot, vertically centered
2890
- let left = screenPos.x + arrowOffset;
2972
+ // Beside the hotspot, vertically centered, on the side it is already on: changing sides
2973
+ // jumps it across the hotspot, so it does only when it no longer fits there and does on
2974
+ // the other side. With no side yet, the right unless that overflows
2975
+ const onRight = screenPos.x + arrowOffset;
2976
+ const onLeft = screenPos.x - arrowOffset - tw;
2977
+ let flipped = tooltip.classList.contains('sse-arrow-left');
2978
+ if (flipped ? onLeft < margin && onRight + tw <= vw - margin : onRight + tw > vw - margin) {
2979
+ flipped = !flipped;
2980
+ }
2981
+ let left = flipped ? onLeft : onRight;
2891
2982
  let top = screenPos.y - th / 2;
2892
- let flipped = false;
2893
- // If tooltip overflows right edge, flip to left side of hotspot
2894
- if (left + tw > vw - margin) {
2895
- left = screenPos.x - arrowOffset - tw;
2896
- flipped = true;
2897
- }
2898
2983
  // Clamp horizontal
2899
2984
  left = Math.max(margin, Math.min(left, vw - tw - margin));
2900
2985
  // Clamp vertical
@@ -2905,6 +2990,8 @@ class Annotation extends Script {
2905
2990
  tooltip.classList.toggle('sse-arrow-right', !flipped);
2906
2991
  tooltip.classList.toggle('sse-arrow-left', flipped);
2907
2992
  tooltip.style.transform = `translate(${left}px, ${top}px)`;
2993
+ tooltip.classList.add('sse-visible');
2994
+ ctx.tooltipOffset = onCanvas ? { x: left - screenPos.x, y: top - screenPos.y } : null;
2908
2995
  }
2909
2996
  }
2910
2997
  /**
@@ -2923,6 +3010,15 @@ class AnnotationContext {
2923
3010
  titleDom;
2924
3011
  textDom;
2925
3012
  activeAnnotation = null;
3013
+ // whether the active annotation's tooltip has been revealed: it hides for each camera
3014
+ // transition, the move to the annotation among them, until the transition nearly ends
3015
+ revealed = false;
3016
+ // the annotation the tooltip belongs to: the active one once revealed, until then the one
3017
+ // before it, beside whose hotspot it fades out. And its offset from that hotspot when it
3018
+ // last showed, which it keeps while fading; null when it last showed clamped to the canvas
3019
+ // with the hotspot beyond it, since it is not beside the hotspot, and then it fades in place
3020
+ tooltipOwner = null;
3021
+ tooltipOffset = null;
2926
3022
  constructor(canvas, camera, parentDom) {
2927
3023
  this.parentDom = parentDom;
2928
3024
  this.canvas = canvas;
@@ -2953,6 +3049,10 @@ const OCCLUDING_OPACITY = 0.5;
2953
3049
  const OCCLUSION_TOLERANCE = 0.1;
2954
3050
  // the hotspot's radius in css pixels: the opacity in front is averaged over its whole disc
2955
3051
  const HOTSPOT_RADIUS = 13;
3052
+ // the selected annotation's tooltip starts fading in once the camera has eased this far along
3053
+ // a transition, its move there among them: the move settles slowly, so waiting for it to stop
3054
+ // shows the tooltip well after the camera looks to have arrived
3055
+ const REVEAL_PROGRESS = 0.9;
2956
3056
  // Built-in hotspot and panel presentation. Selection and camera navigation belong to the viewer.
2957
3057
  class Annotations {
2958
3058
  parentDom;
@@ -2960,7 +3060,7 @@ class Annotations {
2960
3060
  subscriptions;
2961
3061
  removeClick;
2962
3062
  removeOcclusion;
2963
- constructor(viewer, root, camera, getPicker) {
3063
+ constructor(viewer, root, camera, getPicker, getCameraProgress) {
2964
3064
  const { app, state, events, annotations } = viewer;
2965
3065
  const parentDom = document.createElement('div');
2966
3066
  parentDom.className = 'sse-annotations';
@@ -2997,7 +3097,7 @@ class Annotations {
2997
3097
  // bumped on every camera move, so a test that resolves after the camera moved again is
2998
3098
  // discarded rather than applied to a pose it was not taken from
2999
3099
  let pose = 0;
3000
- const lastView = new Mat4();
3100
+ const lastWorld = new Mat4();
3001
3101
  const lastProjection = new Mat4();
3002
3102
  const testOcclusion = async () => {
3003
3103
  settleTimer = null;
@@ -3036,12 +3136,43 @@ class Annotations {
3036
3136
  clearTimeout(settleTimer);
3037
3137
  settleTimer = setTimeout(testOcclusion, SETTLE_MS);
3038
3138
  };
3039
- // after each frame, since the hotspots' screen positions are updated in prerender
3139
+ // A new camera transition (a reset, say): the tooltip hides until it nearly ends, as on
3140
+ // the move to an annotation. Checked after the camera update but before the frame
3141
+ // renders, so the tooltip is not laid out for the transition's first frame
3142
+ let lastProgress = 1;
3143
+ const onFrameRender = () => {
3144
+ const progress = getCameraProgress();
3145
+ if (progress < lastProgress)
3146
+ context.revealed = false;
3147
+ lastProgress = progress;
3148
+ };
3149
+ app.on('framerender', onFrameRender);
3150
+ // after each frame, since the hotspots' screen positions are updated in prerender. The
3151
+ // camera entity's transform rather than its view matrix, which the engine refreshes only
3152
+ // for frames that render: the viewer skips a frame whose camera moved too little to see,
3153
+ // and a stale view matrix would pass for a camera at rest
3040
3154
  const onFrameEnd = () => {
3041
- const { viewMatrix, projectionMatrix } = camera.camera;
3042
- if (lastView.equals(viewMatrix) && lastProjection.equals(projectionMatrix))
3155
+ const world = camera.getWorldTransform();
3156
+ const { projectionMatrix } = camera.camera;
3157
+ const still = lastWorld.equals(world) && lastProjection.equals(projectionMatrix);
3158
+ const progress = getCameraProgress();
3159
+ // Show the selected annotation's tooltip once the camera is nearly there with the
3160
+ // hotspot on the canvas, fading in as the camera lands, or once the camera is at rest.
3161
+ // A hotspot that ends beyond the canvas gets its tooltip at rest, clamped to the edge,
3162
+ // rather than one that shows and then hides again as the hotspot slides off
3163
+ const { activeAnnotation } = context;
3164
+ const screen = activeAnnotation?.screen;
3165
+ const onCanvas = screen &&
3166
+ screen.x >= 0 &&
3167
+ screen.x <= canvas.clientWidth &&
3168
+ screen.y >= 0 &&
3169
+ screen.y <= canvas.clientHeight;
3170
+ if (activeAnnotation && !context.revealed && (still || (progress >= REVEAL_PROGRESS && onCanvas))) {
3171
+ activeAnnotation.revealTooltip();
3172
+ }
3173
+ if (still)
3043
3174
  return;
3044
- lastView.copy(viewMatrix);
3175
+ lastWorld.copy(world);
3045
3176
  lastProjection.copy(projectionMatrix);
3046
3177
  pose++;
3047
3178
  scheduleOcclusion();
@@ -3067,6 +3198,7 @@ class Annotations {
3067
3198
  destroyed = true;
3068
3199
  if (settleTimer)
3069
3200
  clearTimeout(settleTimer);
3201
+ app.off('framerender', onFrameRender);
3070
3202
  app.off('frameend', onFrameEnd);
3071
3203
  gsplatSystem.off('frame:ready', onFrameReady);
3072
3204
  };
@@ -3094,12 +3226,32 @@ class Annotations {
3094
3226
  events.on('gamingControls:changed', update)
3095
3227
  ];
3096
3228
  update();
3229
+ // A click deselects, but a drag ends in a click too, so releasing an orbit would close
3230
+ // the tooltip. A press that moved farther than a tap may is a drag, as the navigation
3231
+ // clicks count it
3232
+ let pressMovement = 0;
3233
+ const onPointerDown = () => {
3234
+ pressMovement = 0;
3235
+ };
3236
+ const onPointerMove = (event) => {
3237
+ if (event.buttons)
3238
+ pressMovement += Math.abs(event.movementX) + Math.abs(event.movementY);
3239
+ };
3097
3240
  const onClick = () => {
3098
- if (state.loaded && state.selectedAnnotation !== null)
3241
+ // consumed, so a later click from the keyboard is not taken for the drag
3242
+ const dragged = pressMovement >= TAP_EPSILON;
3243
+ pressMovement = 0;
3244
+ if (!dragged && state.loaded && state.selectedAnnotation !== null)
3099
3245
  viewer.selectAnnotation(null);
3100
3246
  };
3247
+ root.addEventListener('pointerdown', onPointerDown);
3248
+ root.addEventListener('pointermove', onPointerMove);
3101
3249
  root.addEventListener('click', onClick);
3102
- this.removeClick = () => root.removeEventListener('click', onClick);
3250
+ this.removeClick = () => {
3251
+ root.removeEventListener('pointerdown', onPointerDown);
3252
+ root.removeEventListener('pointermove', onPointerMove);
3253
+ root.removeEventListener('click', onClick);
3254
+ };
3103
3255
  }
3104
3256
  destroy() {
3105
3257
  for (const subscription of this.subscriptions)
@@ -3784,8 +3936,9 @@ const getGpuName = (device) => {
3784
3936
  // document, screen) and cancels pending timers. Listeners on the subtree's own elements are
3785
3937
  // released with the elements.
3786
3938
  // `getPicker` returns the viewer's picker once the scene has loaded, for the annotation
3787
- // occlusion test
3788
- const initUI = (global, viewer, getPicker) => {
3939
+ // occlusion test; `getCameraProgress` how far the camera's current move has eased, 1 when there
3940
+ // is none, for the annotation tooltip's timing
3941
+ const initUI = (global, viewer, getPicker, getCameraProgress) => {
3789
3942
  const { root, localize } = global;
3790
3943
  const { events, state } = viewer;
3791
3944
  const disposers = [];
@@ -4149,7 +4302,7 @@ const initUI = (global, viewer, getPicker) => {
4149
4302
  disposers.push(initJoystick(viewer, root));
4150
4303
  disposers.push(initAnnotationControls(viewer, root));
4151
4304
  if (viewer.annotations.length > 0) {
4152
- const annotations = new Annotations(viewer, root, global.camera, getPicker);
4305
+ const annotations = new Annotations(viewer, root, global.camera, getPicker, getCameraProgress);
4153
4306
  disposers.push(() => annotations.destroy());
4154
4307
  }
4155
4308
  // tooltips
@@ -6149,6 +6302,9 @@ class CameraManager {
6149
6302
  // mutating `camera` and/or `state.cameraMode` to make the change
6150
6303
  // visible instantly.
6151
6304
  snap;
6305
+ // How far the current transition has eased toward its destination, from 0 to 1; 1 when
6306
+ // there is none. The annotations time their tooltip to the camera's arrival with it.
6307
+ transitionProgress;
6152
6308
  // Attach (or clear) collision after construction. The viewer reveals the scene without
6153
6309
  // waiting for collision data, which can be larger than the splats themselves, so this
6154
6310
  // arrives late. It re-tests whether walk mode is allowed, which gates the walk toggle
@@ -6242,6 +6398,7 @@ class CameraManager {
6242
6398
  transitionEase = ease;
6243
6399
  transitionTurnEase = turnEase;
6244
6400
  };
6401
+ this.transitionProgress = () => (transitionTimer < 1 ? transitionEase(transitionTimer) : 1);
6245
6402
  this.setCollision = (value) => {
6246
6403
  controllers.fly.collision = value;
6247
6404
  controllers.walk.collision = value;
@@ -7220,6 +7377,132 @@ const fitPlaneNormal = (points, toCamera, outNormal) => {
7220
7377
  outNormal.set(vx, vy, vz);
7221
7378
  return true;
7222
7379
  };
7380
+ // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a small
7381
+ // disc, which is the depth where the opacity in front reaches that. Null where it never does.
7382
+ const surfaceDepth = (depthAt, x, y) => {
7383
+ const samples = [];
7384
+ for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
7385
+ for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
7386
+ if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
7387
+ continue;
7388
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
7389
+ const depth = depthAt(x + dx, y + dy, trial);
7390
+ if (depth !== null)
7391
+ samples.push(depth);
7392
+ }
7393
+ }
7394
+ }
7395
+ if (samples.length === 0) {
7396
+ return null;
7397
+ }
7398
+ samples.sort((a, b) => a - b);
7399
+ const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
7400
+ return Number.isFinite(depth) && depth < 1 ? depth : null;
7401
+ };
7402
+ // The surface under a pixel and its normal, fitted through surface points on rings around it.
7403
+ // `depthAt` must cover NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX around the pixel.
7404
+ const estimateSurface = (depthAt, pickCamera, width, height, screenX, screenY) => {
7405
+ const surfacePoint = (px, py) => {
7406
+ const depth = surfaceDepth(depthAt, px, py);
7407
+ return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
7408
+ };
7409
+ const position = surfacePoint(screenX, screenY);
7410
+ if (!position) {
7411
+ return null;
7412
+ }
7413
+ const samplePixel = (px, py) => {
7414
+ if (px < 0 || px >= width || py < 0 || py >= height) {
7415
+ return null;
7416
+ }
7417
+ return surfacePoint(px, py);
7418
+ };
7419
+ // Pixel radius corresponding to a fixed world radius at the
7420
+ // picked-point's depth. Clamped so distant picks still sample
7421
+ // enough pixels and very-close picks stay inside the block read.
7422
+ const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
7423
+ const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
7424
+ const sampleRings = ringPixelRadii.map((radius) => {
7425
+ return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
7426
+ return samplePixel(screenX + dx * radius, screenY + dy * radius);
7427
+ });
7428
+ });
7429
+ const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
7430
+ // Collect every valid 3D sample: the picked position plus all ring
7431
+ // samples that didn't fall off-screen or find no surface.
7432
+ const fitPoints = [position];
7433
+ for (let i = 0; i < sampleRings.length; i++) {
7434
+ const ring = sampleRings[i];
7435
+ for (let j = 0; j < ring.length; j++) {
7436
+ const pt = ring[j];
7437
+ if (pt)
7438
+ fitPoints.push(pt);
7439
+ }
7440
+ }
7441
+ const normal = new Vec3();
7442
+ if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
7443
+ normal.copy(toCamera);
7444
+ }
7445
+ return {
7446
+ position,
7447
+ normal
7448
+ };
7449
+ };
7450
+ // The share of samples over a disc of `r` pixels whose nearest survivor is nearer than the view
7451
+ // depth `depth`; null where the disc has no samples. `depthAt` must cover the disc.
7452
+ const opacityInFront = (depthAt, pickCamera, screenX, screenY, r, depth) => {
7453
+ const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
7454
+ let total = 0;
7455
+ let inFront = 0;
7456
+ for (let dy = -r; dy <= r; dy++) {
7457
+ for (let dx = -r; dx <= r; dx++) {
7458
+ if (dx * dx + dy * dy > r * r)
7459
+ continue;
7460
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
7461
+ const nearest = depthAt(screenX + dx, screenY + dy, trial);
7462
+ if (nearest === null)
7463
+ continue;
7464
+ total++;
7465
+ if (nearest < threshold)
7466
+ inFront++;
7467
+ }
7468
+ }
7469
+ }
7470
+ return total > 0 ? inFront / total : null;
7471
+ };
7472
+ // One pick pixel per css pixel, never more than the backbuffer has: picking then behaves the
7473
+ // same in performance mode and at any device pixel ratio, since the pixel sizes above are css
7474
+ // pixels, and a high-density display does not multiply the pass's cost. Null before the device
7475
+ // or the canvas has been sized.
7476
+ const pickTargetSize = (graphicsDevice) => {
7477
+ const canvas = graphicsDevice.canvas;
7478
+ const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
7479
+ const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
7480
+ return width > 0 && height > 0 ? { width, height } : null;
7481
+ };
7482
+ const clampPixel = (v, size) => Math.min(size - 1, Math.max(0, Math.floor(v * size)));
7483
+ // Picks run one at a time, since they share one render. `fallback` is the result for a pick
7484
+ // that release overtakes: one queued behind another pick, or one whose read-back is cut short
7485
+ // as the device goes.
7486
+ class PickQueue {
7487
+ released = false;
7488
+ queue = Promise.resolve();
7489
+ run(operation, fallback) {
7490
+ const guarded = () => {
7491
+ if (this.released) {
7492
+ return Promise.resolve(fallback);
7493
+ }
7494
+ return operation().catch((error) => {
7495
+ if (this.released) {
7496
+ return fallback;
7497
+ }
7498
+ throw error;
7499
+ });
7500
+ };
7501
+ const result = this.queue.then(guarded, guarded);
7502
+ this.queue = result.then(() => undefined, () => undefined);
7503
+ return result;
7504
+ }
7505
+ }
7223
7506
  class Picker {
7224
7507
  pick;
7225
7508
  pickSurface;
@@ -7248,10 +7531,7 @@ class Picker {
7248
7531
  let pickTarget;
7249
7532
  let pickPass;
7250
7533
  let chunksPatched = false;
7251
- // set by release: queued and in-flight picks then resolve to nothing, rather than render
7252
- // with released resources or reach an app that is being destroyed
7253
- let released = false;
7254
- let pickQueue = Promise.resolve();
7534
+ const queue = new PickQueue();
7255
7535
  let cacheValid = false;
7256
7536
  let renders = 0;
7257
7537
  let cacheWidth = 0;
@@ -7304,8 +7584,6 @@ class Picker {
7304
7584
  return snapshot;
7305
7585
  };
7306
7586
  // Read the pick render around a pixel, `margin` pixels each way, clamped to the render.
7307
- // The accessor returns a pixel's nearest surviving normalised depth in one of its
7308
- // PICK_TRIALS trials, 1 where no fragment survived, or null outside the block.
7309
7587
  const readAround = async (screenX, screenY, margin, width, height) => {
7310
7588
  const blockX = Math.max(0, screenX - margin);
7311
7589
  const blockY = Math.max(0, screenY - margin);
@@ -7326,29 +7604,6 @@ class Picker {
7326
7604
  return half2Float(pixels[(row * blockWidth + localX) * 4 + trial]);
7327
7605
  };
7328
7606
  };
7329
- // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a
7330
- // small disc, which is the depth where the opacity in front reaches that. Null where it
7331
- // never does.
7332
- const surfaceDepth = (depthAt, x, y) => {
7333
- const samples = [];
7334
- for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
7335
- for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
7336
- if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
7337
- continue;
7338
- for (let trial = 0; trial < PICK_TRIALS; trial++) {
7339
- const depth = depthAt(x + dx, y + dy, trial);
7340
- if (depth !== null)
7341
- samples.push(depth);
7342
- }
7343
- }
7344
- }
7345
- if (samples.length === 0) {
7346
- return null;
7347
- }
7348
- samples.sort((a, b) => a - b);
7349
- const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
7350
- return Number.isFinite(depth) && depth < 1 ? depth : null;
7351
- };
7352
7607
  const ensureRendered = (width, height, worldLayer) => {
7353
7608
  if (cameraMatches(width, height)) {
7354
7609
  return;
@@ -7375,49 +7630,24 @@ class Picker {
7375
7630
  renders++;
7376
7631
  };
7377
7632
  const prepareSample = (x, y) => {
7378
- if (released) {
7633
+ if (queue.released) {
7379
7634
  return null;
7380
7635
  }
7381
- // One pick pixel per css pixel, never more than the backbuffer has: picking then
7382
- // behaves the same in performance mode and at any device pixel ratio, since the
7383
- // pixel sizes above are css pixels, and a high-density display does not multiply
7384
- // the pass's cost
7385
- const canvas = graphicsDevice.canvas;
7386
- const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
7387
- const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
7388
- // bail out if the device or the canvas hasn't been sized yet
7389
- if (width <= 0 || height <= 0) {
7636
+ const size = pickTargetSize(graphicsDevice);
7637
+ if (!size) {
7390
7638
  return null;
7391
7639
  }
7640
+ const { width, height } = size;
7392
7641
  const worldLayer = app.scene.layers.getLayerByName('World');
7393
7642
  if (!worldLayer) {
7394
7643
  return null;
7395
7644
  }
7396
- const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
7397
- const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
7645
+ const screenX = clampPixel(x, width);
7646
+ const screenY = clampPixel(y, height);
7398
7647
  ensureRendered(width, height, worldLayer);
7399
7648
  const pickCamera = getCacheCameraSnapshot();
7400
7649
  return { width, height, screenX, screenY, pickCamera };
7401
7650
  };
7402
- // `fallback` is the result for a pick that release overtakes: one queued behind another
7403
- // pick, or one whose read-back is cut short as the device goes
7404
- const serializePick = (operation, fallback) => {
7405
- const guarded = () => {
7406
- if (released) {
7407
- return Promise.resolve(fallback);
7408
- }
7409
- return operation().catch((error) => {
7410
- if (released) {
7411
- return fallback;
7412
- }
7413
- throw error;
7414
- });
7415
- };
7416
- // The render target is shared by all picks on this instance.
7417
- const result = pickQueue.then(guarded, guarded);
7418
- pickQueue = result.then(() => undefined, () => undefined);
7419
- return result;
7420
- };
7421
7651
  const pick = async (x, y) => {
7422
7652
  const sample = prepareSample(x, y);
7423
7653
  if (!sample) {
@@ -7438,50 +7668,7 @@ class Picker {
7438
7668
  // Sized to the maximum possible ring pixel-radius, plus the surface disc around each
7439
7669
  // sample, so the dynamic ring offsets always lie inside the buffer we read.
7440
7670
  const depthAt = await readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
7441
- const surfacePoint = (px, py) => {
7442
- const depth = surfaceDepth(depthAt, px, py);
7443
- return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
7444
- };
7445
- const position = surfacePoint(screenX, screenY);
7446
- if (!position) {
7447
- return null;
7448
- }
7449
- const samplePixel = (px, py) => {
7450
- if (px < 0 || px >= width || py < 0 || py >= height) {
7451
- return null;
7452
- }
7453
- return surfacePoint(px, py);
7454
- };
7455
- // Pixel radius corresponding to a fixed world radius at the
7456
- // picked-point's depth. Clamped so distant picks still sample
7457
- // enough pixels and very-close picks stay inside the block read.
7458
- const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
7459
- const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
7460
- const sampleRings = ringPixelRadii.map((radius) => {
7461
- return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
7462
- return samplePixel(screenX + dx * radius, screenY + dy * radius);
7463
- });
7464
- });
7465
- const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
7466
- // Collect every valid 3D sample: the picked position plus all ring
7467
- // samples that didn't fall off-screen or find no surface.
7468
- const fitPoints = [position];
7469
- for (let i = 0; i < sampleRings.length; i++) {
7470
- const ring = sampleRings[i];
7471
- for (let j = 0; j < ring.length; j++) {
7472
- const pt = ring[j];
7473
- if (pt)
7474
- fitPoints.push(pt);
7475
- }
7476
- }
7477
- const normal = new Vec3();
7478
- if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
7479
- normal.copy(toCamera);
7480
- }
7481
- return {
7482
- position,
7483
- normal
7484
- };
7671
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
7485
7672
  };
7486
7673
  const pickVisibility = async (points, radius) => {
7487
7674
  if (points.length === 0) {
@@ -7497,29 +7684,12 @@ class Picker {
7497
7684
  const { width, height, screenX, screenY, pickCamera } = sample;
7498
7685
  const r = Math.max(1, Math.round(radius * height));
7499
7686
  const depthAt = await readAround(screenX, screenY, r, width, height);
7500
- const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
7501
- let total = 0;
7502
- let inFront = 0;
7503
- for (let dy = -r; dy <= r; dy++) {
7504
- for (let dx = -r; dx <= r; dx++) {
7505
- if (dx * dx + dy * dy > r * r)
7506
- continue;
7507
- for (let trial = 0; trial < PICK_TRIALS; trial++) {
7508
- const nearest = depthAt(screenX + dx, screenY + dy, trial);
7509
- if (nearest === null)
7510
- continue;
7511
- total++;
7512
- if (nearest < threshold)
7513
- inFront++;
7514
- }
7515
- }
7516
- }
7517
- return total > 0 ? inFront / total : null;
7687
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
7518
7688
  }));
7519
7689
  };
7520
- this.pick = (x, y) => serializePick(() => pick(x, y), null);
7521
- this.pickSurface = (x, y) => serializePick(() => pickSurface(x, y), null);
7522
- this.pickVisibility = (points, radius) => serializePick(() => pickVisibility(points, radius), points.map(() => null));
7690
+ this.pick = (x, y) => queue.run(() => pick(x, y), null);
7691
+ this.pickSurface = (x, y) => queue.run(() => pickSurface(x, y), null);
7692
+ this.pickVisibility = (points, radius) => queue.run(() => pickVisibility(points, radius), points.map(() => null));
7523
7693
  this.renderView = () => (prepareSample(0, 0) ? { texture: pickBuffer, renders } : null);
7524
7694
  // The scene can change under a still camera, which the camera-based cache cannot see:
7525
7695
  // finer detail streams in after the reveal and after every move. The engine reports each
@@ -7538,7 +7708,7 @@ class Picker {
7538
7708
  };
7539
7709
  gsplatSystem.on('frame:ready', onFrameReady);
7540
7710
  this.release = () => {
7541
- released = true;
7711
+ queue.released = true;
7542
7712
  gsplatSystem.off('frame:ready', onFrameReady);
7543
7713
  if (chunksPatched) {
7544
7714
  unregisterPickerShaderPatches(app);
@@ -7909,6 +8079,20 @@ const STYLES = `
7909
8079
  .${PANEL_CLASS} button.sse-flash {
7910
8080
  background: rgba(120, 220, 140, 0.35);
7911
8081
  }
8082
+ .${PANEL_CLASS} button.sse-flash-bad {
8083
+ background: rgba(220, 100, 100, 0.45);
8084
+ }
8085
+ .${PANEL_CLASS} input.sse-debug-paste {
8086
+ width: 100%;
8087
+ box-sizing: border-box;
8088
+ margin-top: 6px;
8089
+ background: rgba(255, 255, 255, 0.08);
8090
+ color: #eee;
8091
+ border: 1px solid rgba(120, 180, 255, 0.6);
8092
+ border-radius: 3px;
8093
+ padding: 4px 8px;
8094
+ font: inherit;
8095
+ }
7912
8096
  .${PANEL_CLASS} button.sse-debug-on {
7913
8097
  background: rgba(120, 180, 255, 0.35);
7914
8098
  }
@@ -7931,6 +8115,14 @@ class DebugPanel {
7931
8115
  _global;
7932
8116
  _cameraManager;
7933
8117
  _picker;
8118
+ // the stochastic renderer when this viewer opted in, for its depth cull toggle and counts
8119
+ _splatRenderer;
8120
+ _cullButton = null;
8121
+ _taaButton = null;
8122
+ _poplessButton = null;
8123
+ _culledValue = null;
8124
+ _cullStatsFrames = 0;
8125
+ _cullStatsPending = false;
7934
8126
  _pickDepthOverlay = null;
7935
8127
  _focusTmp = new Vec3();
7936
8128
  _root = null;
@@ -7939,12 +8131,20 @@ class DebugPanel {
7939
8131
  _focusValue = null;
7940
8132
  _copyButton = null;
7941
8133
  _pasteButton = null;
8134
+ // shown when the clipboard cannot be read (a cross-origin iframe without clipboard-read):
8135
+ // the paste event of a focused field carries the text without that permission
8136
+ _pasteField = null;
8137
+ _miniStatsButton = null;
8138
+ // the viewer's MiniStats switch
8139
+ _miniStats;
7942
8140
  _screenshotButton = null;
7943
8141
  _pickDepthButton = null;
7944
8142
  _editing = null;
7945
8143
  _editCanceled = false;
7946
8144
  _visible = false;
7947
8145
  _onPrerender = () => this._render();
8146
+ // the cull state is decided inside the frame, so its row refreshes after it
8147
+ _onFrameEnd = () => this._renderCull();
7948
8148
  _onKeyDown = (event) => {
7949
8149
  // Ctrl+Shift+D — also accept Meta+Shift+D on macOS for parity
7950
8150
  if (!this._global.state.inputEnabled)
@@ -7954,10 +8154,12 @@ class DebugPanel {
7954
8154
  this.toggle();
7955
8155
  }
7956
8156
  };
7957
- constructor(global, cameraManager, picker) {
8157
+ constructor(global, cameraManager, picker, splatRenderer = null, miniStats = null) {
7958
8158
  this._global = global;
7959
8159
  this._cameraManager = cameraManager;
7960
8160
  this._picker = picker;
8161
+ this._splatRenderer = splatRenderer;
8162
+ this._miniStats = miniStats;
7961
8163
  window.addEventListener('keydown', this._onKeyDown);
7962
8164
  if (global.config.debug) {
7963
8165
  this.show();
@@ -7972,6 +8174,7 @@ class DebugPanel {
7972
8174
  }
7973
8175
  this._root.style.display = '';
7974
8176
  this._global.app.on('prerender', this._onPrerender);
8177
+ this._global.app.on('frameend', this._onFrameEnd);
7975
8178
  if (this._global.config.exposeGlobals) {
7976
8179
  window.getCameraState = () => captureCameraState(this._cameraManager, this._global.state);
7977
8180
  window.setCameraState = (snapshot) => restoreCameraState(this._cameraManager, this._global.state, snapshot);
@@ -7988,6 +8191,7 @@ class DebugPanel {
7988
8191
  // the view is only reachable from the panel, so it goes with it
7989
8192
  this._setPickDepth(false);
7990
8193
  this._global.app.off('prerender', this._onPrerender);
8194
+ this._global.app.off('frameend', this._onFrameEnd);
7991
8195
  if (this._global.config.exposeGlobals) {
7992
8196
  delete window.getCameraState;
7993
8197
  delete window.setCameraState;
@@ -8032,8 +8236,19 @@ class DebugPanel {
8032
8236
  </div>
8033
8237
  <div class="sse-debug-buttons">
8034
8238
  <button data-id="screenshot">Screenshot</button>
8035
- <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Pick depth</button>
8239
+ <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Show depth</button>
8240
+ <button data-id="ministats" title="Show the engine's MiniStats graphs (the viewer then renders every frame)">MiniStats</button>
8241
+ </div>
8242
+ <input class="sse-debug-paste" data-id="paste-field" placeholder="Clipboard blocked here: paste with Ctrl/Cmd+V" spellcheck="false" style="display: none">
8243
+ ${this._splatRenderer
8244
+ ? `
8245
+ <div class="sse-debug-buttons">
8246
+ <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>
8247
+ <button data-id="taa" title="Stochastic renderer: accumulate the samples over frames (reprojected while the camera moves)">TAA</button>
8248
+ <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>
8036
8249
  </div>
8250
+ <div class="sse-debug-row"><span class="sse-debug-label">culled</span><span class="sse-debug-value" data-id="culled">—</span></div>`
8251
+ : ''}
8037
8252
  `;
8038
8253
  host.appendChild(root);
8039
8254
  this._root = root;
@@ -8043,12 +8258,52 @@ class DebugPanel {
8043
8258
  this._pasteButton = root.querySelector('[data-id="paste"]');
8044
8259
  this._screenshotButton = root.querySelector('[data-id="screenshot"]');
8045
8260
  this._pickDepthButton = root.querySelector('[data-id="pick-depth"]');
8261
+ this._miniStatsButton = root.querySelector('[data-id="ministats"]');
8262
+ this._pasteField = root.querySelector('[data-id="paste-field"]');
8263
+ this._wirePasteField(this._pasteField);
8264
+ if (this._miniStats) {
8265
+ this._miniStatsButton.addEventListener('click', () => {
8266
+ this._miniStats.show(!this._miniStats.shown());
8267
+ this._renderMiniStats();
8268
+ });
8269
+ this._renderMiniStats();
8270
+ }
8271
+ else {
8272
+ this._miniStatsButton.remove();
8273
+ }
8046
8274
  this._copyButton.addEventListener('click', () => this._copy());
8047
8275
  this._pasteButton.addEventListener('click', () => this._paste());
8048
8276
  this._screenshotButton.addEventListener('click', () => this._screenshot());
8049
8277
  this._pickDepthButton.addEventListener('click', () => {
8050
8278
  this._setPickDepth(!this._pickDepthOverlay?.enabled);
8051
8279
  });
8280
+ if (this._splatRenderer) {
8281
+ this._cullButton = root.querySelector('[data-id="depth-cull"]');
8282
+ this._taaButton = root.querySelector('[data-id="taa"]');
8283
+ this._poplessButton = root.querySelector('[data-id="popless"]');
8284
+ this._poplessButton.addEventListener('click', () => {
8285
+ const renderer = this._splatRenderer;
8286
+ renderer.variant.popless = renderer.variant.popless === 'on' ? 'off' : 'on';
8287
+ renderer.applyVariant();
8288
+ this._renderCull();
8289
+ });
8290
+ this._culledValue = root.querySelector('[data-id="culled"]');
8291
+ this._taaButton.addEventListener('click', () => {
8292
+ const renderer = this._splatRenderer;
8293
+ renderer.variant.taa = renderer.variant.taa === 'on' ? 'off' : 'on';
8294
+ renderer.applyVariant();
8295
+ this._renderCull();
8296
+ });
8297
+ // cycles the cull mode: auto (the default) -> on (both grid levels) -> off
8298
+ this._cullButton.addEventListener('click', () => {
8299
+ const renderer = this._splatRenderer;
8300
+ const next = { auto: 'l2', l2: 'off', l1: 'off', off: 'auto' };
8301
+ renderer.variant.cull = next[renderer.variant.cull];
8302
+ renderer.applyVariant();
8303
+ this._renderCull();
8304
+ });
8305
+ this._renderCull();
8306
+ }
8052
8307
  this._wireEditable(this._positionValue, 'position');
8053
8308
  this._wireEditable(this._focusValue, 'focus');
8054
8309
  }
@@ -8144,27 +8399,153 @@ class DebugPanel {
8144
8399
  this._focusValue.textContent = fmt(this._focusTmp);
8145
8400
  }
8146
8401
  }
8402
+ // the cull button shows the mode; the counts come back from the gpu every few frames
8403
+ _renderCull() {
8404
+ const renderer = this._splatRenderer;
8405
+ if (!renderer || !this._cullButton || !this._culledValue)
8406
+ return;
8407
+ const mode = renderer.variant.cull;
8408
+ this._cullButton.textContent = `Depth cull: ${mode === 'off' ? 'off' : mode === 'auto' ? 'auto' : 'on'}`;
8409
+ this._cullButton.classList.toggle('sse-debug-on', mode !== 'off');
8410
+ if (this._taaButton) {
8411
+ this._taaButton.textContent = `TAA: ${renderer.variant.taa}`;
8412
+ this._taaButton.classList.toggle('sse-debug-on', renderer.variant.taa === 'on');
8413
+ }
8414
+ if (this._poplessButton) {
8415
+ this._poplessButton.textContent = `Popless: ${renderer.variant.popless}`;
8416
+ this._poplessButton.classList.toggle('sse-debug-on', renderer.variant.popless === 'on');
8417
+ }
8418
+ if (mode === 'off') {
8419
+ this._culledValue.textContent = 'off';
8420
+ return;
8421
+ }
8422
+ if (!renderer.culling) {
8423
+ this._culledValue.textContent = renderer.cullSuspended ? 'suspended' : 'no previous frame';
8424
+ return;
8425
+ }
8426
+ if (this._cullStatsPending || this._cullStatsFrames++ % 15 !== 0)
8427
+ return;
8428
+ this._cullStatsPending = true;
8429
+ renderer
8430
+ .readStats()
8431
+ .then(({ survivors, occluded }) => {
8432
+ const total = survivors + occluded;
8433
+ const pct = total > 0 ? ((100 * occluded) / total).toFixed(0) : '0';
8434
+ if (this._culledValue && renderer.culling) {
8435
+ this._culledValue.textContent = `${pct}% (${occluded.toLocaleString()} of ${total.toLocaleString()})`;
8436
+ }
8437
+ })
8438
+ .catch(() => {
8439
+ // a destroyed buffer or lost device; the next refresh tries again
8440
+ })
8441
+ .finally(() => {
8442
+ this._cullStatsPending = false;
8443
+ });
8444
+ }
8445
+ // The clipboard api, else a selection copied with execCommand: the api is refused in a
8446
+ // cross-origin iframe without clipboard-write (superspl.at's local-frontend frame), while
8447
+ // the command still works there inside the click
8147
8448
  async _copy() {
8148
- const snapshot = captureCameraState(this._cameraManager, this._global.state);
8449
+ const text = JSON.stringify(captureCameraState(this._cameraManager, this._global.state));
8450
+ let copied = false;
8149
8451
  try {
8150
- await navigator.clipboard.writeText(JSON.stringify(snapshot));
8452
+ await navigator.clipboard.writeText(text);
8453
+ copied = true;
8454
+ }
8455
+ catch {
8456
+ // destroyed while the clipboard was refusing
8457
+ if (!this._root)
8458
+ return;
8459
+ const area = document.createElement('textarea');
8460
+ area.value = text;
8461
+ area.style.cssText = 'position: fixed; opacity: 0; pointer-events: none';
8462
+ this._root.appendChild(area);
8463
+ area.select();
8464
+ try {
8465
+ copied = document.execCommand('copy');
8466
+ }
8467
+ catch {
8468
+ copied = false;
8469
+ }
8470
+ area.remove();
8471
+ }
8472
+ if (copied) {
8151
8473
  this._flash(this._copyButton);
8152
8474
  }
8153
- catch (err) {
8154
- console.warn('[debug-panel] copy failed', err);
8475
+ else {
8476
+ console.warn('[debug-panel] copy failed');
8477
+ this._flashBad(this._copyButton);
8155
8478
  }
8156
8479
  }
8480
+ // The clipboard api, else the paste field: reading needs clipboard-read, which a
8481
+ // cross-origin iframe only has when its embedder grants it
8157
8482
  async _paste() {
8483
+ let text;
8484
+ try {
8485
+ text = await navigator.clipboard.readText();
8486
+ }
8487
+ catch {
8488
+ this._showPasteField(true);
8489
+ return;
8490
+ }
8491
+ // destroyed while the clipboard was being read
8492
+ if (!this._root)
8493
+ return;
8494
+ this._applyPasted(text);
8495
+ }
8496
+ _applyPasted(text) {
8158
8497
  try {
8159
- const text = await navigator.clipboard.readText();
8160
8498
  const snapshot = JSON.parse(text);
8161
8499
  restoreCameraState(this._cameraManager, this._global.state, snapshot);
8162
8500
  this._flash(this._pasteButton);
8163
8501
  }
8164
8502
  catch (err) {
8165
8503
  console.warn('[debug-panel] paste failed', err);
8504
+ this._flashBad(this._pasteButton);
8166
8505
  }
8167
8506
  }
8507
+ _showPasteField(value) {
8508
+ const field = this._pasteField;
8509
+ if (!field)
8510
+ return;
8511
+ field.value = '';
8512
+ field.style.display = value ? '' : 'none';
8513
+ if (value)
8514
+ field.focus();
8515
+ }
8516
+ _wirePasteField(field) {
8517
+ // keys typed here are text, not camera controls (see _wireEditable)
8518
+ const stopKey = (e) => e.stopPropagation();
8519
+ field.addEventListener('keydown', (e) => {
8520
+ stopKey(e);
8521
+ if (e.key === 'Enter') {
8522
+ e.preventDefault();
8523
+ const text = field.value;
8524
+ this._showPasteField(false);
8525
+ this._applyPasted(text);
8526
+ }
8527
+ else if (e.key === 'Escape') {
8528
+ e.preventDefault();
8529
+ this._showPasteField(false);
8530
+ }
8531
+ });
8532
+ field.addEventListener('keyup', stopKey);
8533
+ field.addEventListener('keypress', stopKey);
8534
+ field.addEventListener('paste', (e) => {
8535
+ e.preventDefault();
8536
+ const text = e.clipboardData?.getData('text/plain') ?? '';
8537
+ this._showPasteField(false);
8538
+ this._applyPasted(text);
8539
+ });
8540
+ field.addEventListener('blur', () => this._showPasteField(false));
8541
+ }
8542
+ _renderMiniStats() {
8543
+ if (!this._miniStats || !this._miniStatsButton)
8544
+ return;
8545
+ const shown = this._miniStats.shown();
8546
+ this._miniStatsButton.textContent = `MiniStats: ${shown ? 'on' : 'off'}`;
8547
+ this._miniStatsButton.classList.toggle('sse-debug-on', shown);
8548
+ }
8168
8549
  _screenshot() {
8169
8550
  const app = this._global.app;
8170
8551
  const canvas = app.graphicsDevice.canvas;
@@ -8402,58 +8783,6 @@ class ModeShortcuts {
8402
8783
  }
8403
8784
  }
8404
8785
 
8405
- /**
8406
- * Displacement-based inputs (mouse, touch, wheel, pinch) return accumulated
8407
- * pixel offsets that already scale with frame time. This factor converts
8408
- * rate-based speed constants (tuned for degrees-per-second) to work with
8409
- * per-frame displacements, making them frame-rate-independent.
8410
- */
8411
- const DISPLACEMENT_SCALE = 1 / 60;
8412
- /** Maximum accumulated touch movement (px) to still count as a tap. */
8413
- const TAP_EPSILON = 15;
8414
- const tmpHalfSize = new Vec3();
8415
- /**
8416
- * Converts screen-space pixel deltas to a world-space pan vector at the
8417
- * given depth.
8418
- *
8419
- * @param camera - The camera component.
8420
- * @param dx - Horizontal pixel delta.
8421
- * @param dy - Vertical pixel delta.
8422
- * @param dz - Depth (world-space) at which to project the delta.
8423
- * @param out - Optional output vector.
8424
- * @returns The pan vector in world space.
8425
- */
8426
- const screenToWorld = (camera, dx, dy, dz, out = new Vec3()) => {
8427
- const { system, fov, aspectRatio, horizontalFov, projection, orthoHeight } = camera;
8428
- const { width, height } = system.app.graphicsDevice.clientRect;
8429
- out.set(-(dx / width) * 2, (dy / height) * 2, 0);
8430
- const halfSize = tmpHalfSize.set(0, 0, 0);
8431
- if (projection === PROJECTION_PERSPECTIVE) {
8432
- const halfSlice = dz * Math.tan(0.5 * fov * math.DEG_TO_RAD);
8433
- if (horizontalFov) {
8434
- halfSize.set(halfSlice, halfSlice / aspectRatio, 0);
8435
- }
8436
- else {
8437
- halfSize.set(halfSlice * aspectRatio, halfSlice, 0);
8438
- }
8439
- }
8440
- else {
8441
- halfSize.set(orthoHeight * aspectRatio, orthoHeight, 0);
8442
- }
8443
- out.mul(halfSize);
8444
- return out;
8445
- };
8446
- /**
8447
- * The orbit camera and the fly camera disagree on the sign of the z-axis
8448
- * for forward motion. Apply this when emitting a forward/back z-component
8449
- * so the same wheel-style delta drives both cameras correctly.
8450
- *
8451
- * @param mode - The current camera mode.
8452
- * @param z - The raw forward/back z-component.
8453
- * @returns The z-component flipped for orbit mode, unchanged otherwise.
8454
- */
8455
- const flipZForOrbit = (mode, z) => (mode === 'orbit' ? -z : z);
8456
-
8457
8786
  const tmpV$4 = new Vec3();
8458
8787
  const canTargetFly = (global) => global.state.cameraMode === 'fly' && !(global.state.inputMode === 'desktop' && global.state.gamingControls);
8459
8788
  // Mirror gaming-controls speed modifiers: shift = run/boost, ctrl = crawl/slow.
@@ -10139,13 +10468,3301 @@ class NavCursor {
10139
10468
  }
10140
10469
  }
10141
10470
 
10142
- // ---------------------------------------------------------------------------
10143
- // WGSL compute shader: ray-march through the sparse voxel octree per pixel
10144
- // ---------------------------------------------------------------------------
10145
- const voxelOverlayWGSL = /* wgsl */ `
10471
+ /**
10472
+ * World picking from the stochastic renderer's own frame.
10473
+ *
10474
+ * Every pixel of that renderer's depth texture holds the nearest surviving sample, which is
10475
+ * exactly what the pass picker in `picker.ts` renders on purpose: a stochastic depth whose
10476
+ * distribution over a disc is the scene's opacity along the ray. So no pick pass: the frame's
10477
+ * depth is snapshotted into the same encoding (normalised linear depth in four half-float
10478
+ * channels, 1 where nothing survived) at css resolution, and the shared estimators, the
10479
+ * annotation test and the debug overlay read it unchanged. A css pixel's four channels are four
10480
+ * of the device pixels it covers, so a high-density display supplies four trials as before.
10481
+ */
10482
+ // The frame's hardware depth as normalised linear view depth, in the pass picker's encoding.
10483
+ // Each snapshot pixel covers a block of device pixels; four of them, at the block's quarter
10484
+ // points, fill the four channels.
10485
+ const snapshotWgsl = /* wgsl */ `
10486
+ var splatDepth: texture_depth_2d;
10487
+ // clip z = a * viewDepth + b over w = viewDepth (x, y), near and far (z, w)
10488
+ uniform depthViewParams: vec4f;
10489
+ // device pixels per snapshot pixel (x, y), 1 for an orthographic camera (z)
10490
+ uniform snapshotParams: vec4f;
10146
10491
 
10147
- // Solid leaf sentinel: childMask=0xFF, baseOffset=0
10148
- const SOLID_LEAF_MARKER: u32 = 0xFF000000u;
10492
+ @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
10493
+ var output: FragmentOutput;
10494
+ let dims = vec2i(textureDimensions(splatDepth));
10495
+ let p = uniform.depthViewParams;
10496
+ let ortho = uniform.snapshotParams.z > 0.5;
10497
+ let origin = floor(pcPosition.xy);
10498
+ var trials = vec4f(1.0);
10499
+ for (var i = 0; i < 4; i++) {
10500
+ let corner = vec2f(0.25 + 0.5 * f32(i & 1), 0.25 + 0.5 * f32(i >> 1));
10501
+ let q = clamp(vec2i(floor((origin + corner) * uniform.snapshotParams.xy)), vec2i(0), dims - vec2i(1));
10502
+ let depth = textureLoad(splatDepth, q, 0);
10503
+ if (depth < 1.0) {
10504
+ let dz = depth - p.x;
10505
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
10506
+ let viewDepth = select(p.y / safeDz, (depth - p.y) / p.x, ortho);
10507
+ trials[i] = clamp((viewDepth - p.z) / (p.w - p.z), 0.0, 0.99951171875);
10508
+ }
10509
+ }
10510
+ output.color = trials;
10511
+ return output;
10512
+ }
10513
+ `;
10514
+ const cameraMatches = (frame, camera) => {
10515
+ const cam = camera.camera;
10516
+ return (frame.viewMatrix.equals(cam.viewMatrix) &&
10517
+ frame.projectionMatrix.equals(cam.projectionMatrix) &&
10518
+ frame.nearClip === cam.nearClip &&
10519
+ frame.farClip === cam.farClip &&
10520
+ frame.projection === cam.projection);
10521
+ };
10522
+ const sameCamera = (a, b) => a.viewMatrix.equals(b.viewMatrix) &&
10523
+ a.projectionMatrix.equals(b.projectionMatrix) &&
10524
+ a.nearClip === b.nearClip &&
10525
+ a.farClip === b.farClip &&
10526
+ a.projection === b.projection;
10527
+ const copyCameraSnapshot = (from, to) => {
10528
+ to.position.copy(from.position);
10529
+ to.viewMatrix.copy(from.viewMatrix);
10530
+ to.projectionMatrix.copy(from.projectionMatrix);
10531
+ to.nearClip = from.nearClip;
10532
+ to.farClip = from.farClip;
10533
+ to.projection = from.projection;
10534
+ };
10535
+ class FrameDepthPicker {
10536
+ app;
10537
+ camera;
10538
+ renderer;
10539
+ shader;
10540
+ texture = null;
10541
+ target = null;
10542
+ // the renderer frame the snapshot was taken from, and the camera it was drawn with
10543
+ snapshotFrame = -1;
10544
+ snapshotCamera = createPickCameraSnapshot();
10545
+ renders = 0;
10546
+ queue = new PickQueue();
10547
+ // picks waiting for a frame to render; settled by release as well
10548
+ waiters = new Set();
10549
+ constructor(app, camera, renderer) {
10550
+ this.app = app;
10551
+ this.camera = camera;
10552
+ this.renderer = renderer;
10553
+ this.shader = ShaderUtils.createShader(app.graphicsDevice, {
10554
+ uniqueName: 'sse-splat-depth-snapshot',
10555
+ attributes: { vertex_position: SEMANTIC_POSITION },
10556
+ vertexChunk: 'fullscreenQuadVS',
10557
+ fragmentWGSL: snapshotWgsl
10558
+ });
10559
+ }
10560
+ // Wait for the next frame to finish, or for release.
10561
+ nextFrame() {
10562
+ return new Promise((resolve) => {
10563
+ const done = () => {
10564
+ handle.off();
10565
+ this.waiters.delete(done);
10566
+ resolve();
10567
+ };
10568
+ const handle = this.app.once('frameend', done);
10569
+ this.waiters.add(done);
10570
+ });
10571
+ }
10572
+ // Snapshot the renderer's frame at css resolution, unless the snapshot already is of it. With
10573
+ // `latest` false a snapshot of an earlier frame from the same camera serves: every stochastic
10574
+ // frame is a new sample, so the debug overlay would otherwise ask for frames without end.
10575
+ snapshot(frame, latest) {
10576
+ const device = this.app.graphicsDevice;
10577
+ const size = pickTargetSize(device);
10578
+ if (!size)
10579
+ return null;
10580
+ const { width, height } = size;
10581
+ if (!this.texture) {
10582
+ this.texture = new Texture(device, {
10583
+ name: 'sse-splat-depth-snapshot',
10584
+ format: PIXELFORMAT_RGBA16F,
10585
+ width,
10586
+ height,
10587
+ mipmaps: false,
10588
+ minFilter: FILTER_NEAREST,
10589
+ magFilter: FILTER_NEAREST,
10590
+ addressU: ADDRESS_CLAMP_TO_EDGE,
10591
+ addressV: ADDRESS_CLAMP_TO_EDGE
10592
+ });
10593
+ this.target = new RenderTarget({
10594
+ name: 'sse-splat-depth-snapshot',
10595
+ colorBuffer: this.texture,
10596
+ depth: false
10597
+ });
10598
+ this.snapshotFrame = -1;
10599
+ }
10600
+ else if (this.texture.width !== width || this.texture.height !== height) {
10601
+ this.target.resize(width, height);
10602
+ this.snapshotFrame = -1;
10603
+ }
10604
+ const current = this.snapshotFrame === frame.id ||
10605
+ (!latest && this.snapshotFrame >= 0 && sameCamera(this.snapshotCamera, frame.camera));
10606
+ if (!current) {
10607
+ const { scope } = device;
10608
+ const { camera } = frame;
10609
+ scope.resolve('splatDepth').setValue(this.renderer.frameDepthTexture);
10610
+ scope
10611
+ .resolve('depthViewParams')
10612
+ .setValue([frame.clipZ[0], frame.clipZ[1], camera.nearClip, camera.farClip]);
10613
+ scope
10614
+ .resolve('snapshotParams')
10615
+ .setValue([
10616
+ frame.width / width,
10617
+ frame.height / height,
10618
+ camera.projection === PROJECTION_ORTHOGRAPHIC ? 1 : 0,
10619
+ 0
10620
+ ]);
10621
+ device.setBlendState(BlendState.NOBLEND);
10622
+ drawQuadWithShader(device, this.target, this.shader);
10623
+ this.snapshotFrame = frame.id;
10624
+ copyCameraSnapshot(frame.camera, this.snapshotCamera);
10625
+ this.renders++;
10626
+ }
10627
+ // the renderer rewrites its snapshot every frame, and frames render while a pick awaits
10628
+ // its readback: the pick unprojects with a copy of the camera its depth was drawn with
10629
+ const pickCamera = createPickCameraSnapshot();
10630
+ copyCameraSnapshot(frame.camera, pickCamera);
10631
+ return { width, height, pickCamera };
10632
+ }
10633
+ // The frame to pick from: the last one rendered if the camera has not moved since, else
10634
+ // one requested now. Its own camera unprojects it, whatever the live camera does meanwhile.
10635
+ async prepare() {
10636
+ if (this.queue.released)
10637
+ return null;
10638
+ let frame = this.renderer.depthFrame;
10639
+ if (!frame || !cameraMatches(frame.camera, this.camera)) {
10640
+ this.app.renderNextFrame = true;
10641
+ await this.nextFrame();
10642
+ frame = this.renderer.depthFrame;
10643
+ if (!frame || this.queue.released)
10644
+ return null;
10645
+ }
10646
+ return this.snapshot(frame, true);
10647
+ }
10648
+ // Read the snapshot around a pixel, `margin` pixels each way, clamped to it.
10649
+ async readAround(screenX, screenY, margin, width, height) {
10650
+ const blockX = Math.max(0, screenX - margin);
10651
+ const blockY = Math.max(0, screenY - margin);
10652
+ const blockWidth = Math.min(width - 1, screenX + margin) - blockX + 1;
10653
+ const blockHeight = Math.min(height - 1, screenY + margin) - blockY + 1;
10654
+ const pixels = (await this.texture.read(blockX, blockY, blockWidth, blockHeight, {
10655
+ renderTarget: this.target,
10656
+ immediate: true
10657
+ }));
10658
+ return (x, y, trial) => {
10659
+ const localX = x - blockX;
10660
+ const localY = y - blockY;
10661
+ if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
10662
+ return null;
10663
+ }
10664
+ return half2Float(pixels[(localY * blockWidth + localX) * 4 + trial]);
10665
+ };
10666
+ }
10667
+ pick(x, y) {
10668
+ return this.queue.run(async () => {
10669
+ const sample = await this.prepare();
10670
+ if (!sample)
10671
+ return null;
10672
+ const { width, height, pickCamera } = sample;
10673
+ const screenX = clampPixel(x, width);
10674
+ const screenY = clampPixel(y, height);
10675
+ const depthAt = await this.readAround(screenX, screenY, SURFACE_RADIUS_PX, width, height);
10676
+ const depth = surfaceDepth(depthAt, screenX, screenY);
10677
+ return depth === null ? null : getWorldPoint(pickCamera, screenX, screenY, width, height, depth);
10678
+ }, null);
10679
+ }
10680
+ pickSurface(x, y) {
10681
+ return this.queue.run(async () => {
10682
+ const sample = await this.prepare();
10683
+ if (!sample)
10684
+ return null;
10685
+ const { width, height, pickCamera } = sample;
10686
+ const screenX = clampPixel(x, width);
10687
+ const screenY = clampPixel(y, height);
10688
+ const depthAt = await this.readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
10689
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
10690
+ }, null);
10691
+ }
10692
+ pickVisibility(points, radius) {
10693
+ if (points.length === 0) {
10694
+ return Promise.resolve([]);
10695
+ }
10696
+ return this.queue.run(async () => {
10697
+ const sample = await this.prepare();
10698
+ if (!sample)
10699
+ return points.map(() => null);
10700
+ const { width, height, pickCamera } = sample;
10701
+ const r = Math.max(1, Math.round(radius * height));
10702
+ return Promise.all(points.map(async ({ x, y, depth }) => {
10703
+ const screenX = clampPixel(x, width);
10704
+ const screenY = clampPixel(y, height);
10705
+ const depthAt = await this.readAround(screenX, screenY, r, width, height);
10706
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
10707
+ }));
10708
+ }, points.map(() => null));
10709
+ }
10710
+ // The last frame's snapshot, for the debug overlay; it asks after each frame, so the frame
10711
+ // is the current camera's.
10712
+ renderView() {
10713
+ if (this.queue.released)
10714
+ return null;
10715
+ const frame = this.renderer.depthFrame;
10716
+ if (!frame || !this.snapshot(frame, false))
10717
+ return null;
10718
+ return { texture: this.texture, renders: this.renders };
10719
+ }
10720
+ release() {
10721
+ this.queue.released = true;
10722
+ for (const done of [...this.waiters])
10723
+ done();
10724
+ this.target?.destroy();
10725
+ this.texture?.destroy();
10726
+ this.target = null;
10727
+ this.texture = null;
10728
+ this.shader.destroy();
10729
+ }
10730
+ }
10731
+
10732
+ // The resident set: which splats the engine's LOD and streaming have made resident this
10733
+ // frame, and where each node's data sits. The engine keeps octree LOD, the budget, file
10734
+ // streaming and the block allocator (one slot range per node); the stochastic renderer
10735
+ // consumes its decisions and owns everything after them.
10736
+ //
10737
+ // Read through the engine's internal (@ignore) gsplat-unified classes until the public
10738
+ // `world:update` api lands (engine change E3 in the plan). Every internal shape used is
10739
+ // narrowed here to the members this file reads, so a change in the engine fails in one place.
10740
+ const tmpVec = new Vec3();
10741
+ const tmpVec2$1 = new Vec3();
10742
+ /**
10743
+ * Hooks the engine's per-frame gsplat update for one camera and layer and exposes the resident
10744
+ * set. `frame:ready` fires inside `GSplatManager.update()` after `world.bake()` and after the
10745
+ * engine's own render prep (both in 2.22.4 and on main), so a listener sees the baked state of
10746
+ * the current frame and can replace that prep.
10747
+ */
10748
+ class EngineResidentSetProvider {
10749
+ app;
10750
+ camera;
10751
+ layer;
10752
+ handles = [];
10753
+ callbacks = new Set();
10754
+ set = null;
10755
+ // the engine renderers this provider has switched off, with their original prep function
10756
+ takenOver = new Map();
10757
+ // while false the engine keeps rendering the splats itself (XR), and the hook stays quiet
10758
+ active = true;
10759
+ constructor(app, camera, layer) {
10760
+ this.app = app;
10761
+ this.camera = camera;
10762
+ this.layer = layer;
10763
+ const system = app.systems.gsplat;
10764
+ // fires when a manager is created for a camera and layer, before its first update:
10765
+ // the earliest point to switch the engine's own renderer off, so it never allocates
10766
+ // its projector, sort and draw resources
10767
+ this.handles.push(system.on('material:created', (material, cam, lyr) => {
10768
+ if (cam === this.camera && lyr === this.layer && this.active) {
10769
+ const manager = this.manager();
10770
+ if (manager)
10771
+ this.takeOver(manager);
10772
+ }
10773
+ }));
10774
+ this.handles.push(system.on('frame:ready', (cam, lyr) => {
10775
+ if (cam !== this.camera || lyr !== this.layer || !this.active)
10776
+ return;
10777
+ const manager = this.manager();
10778
+ if (!manager)
10779
+ return;
10780
+ this.takeOver(manager);
10781
+ const state = manager.world.currentState;
10782
+ if (!state)
10783
+ return;
10784
+ const changed = !this.set || this.set.version !== state.version;
10785
+ if (changed) {
10786
+ this.set = buildResidentSet(state);
10787
+ }
10788
+ for (const cb of this.callbacks) {
10789
+ cb(this.set, changed, manager);
10790
+ }
10791
+ }));
10792
+ }
10793
+ /** The engine manager for this camera and layer, once the engine has created it. */
10794
+ manager() {
10795
+ const director = this.app.renderer.gsplatDirector;
10796
+ // the director keys its cameras by the scene camera, not the component
10797
+ const cameraData = director?.camerasMap.get(this.camera.camera);
10798
+ return cameraData?.layersMap.get(this.layer)?.gsplatManager ?? null;
10799
+ }
10800
+ /** Hand the splats back to the engine's renderer (false), or take them over again (true). */
10801
+ setActive(value) {
10802
+ if (this.active === value)
10803
+ return;
10804
+ this.active = value;
10805
+ if (value) {
10806
+ const manager = this.manager();
10807
+ if (manager)
10808
+ this.takeOver(manager);
10809
+ }
10810
+ else {
10811
+ this.restore();
10812
+ }
10813
+ }
10814
+ onFrame(cb) {
10815
+ this.callbacks.add(cb);
10816
+ return () => this.callbacks.delete(cb);
10817
+ }
10818
+ /**
10819
+ * Switch the engine's own splat rendering off for this manager: its render prep returns
10820
+ * false (so the hybrid renderer never builds its projector, sorter or cache) and its mesh
10821
+ * instance is hidden. The world (LOD, streaming, allocation, the work-buffer copy) keeps
10822
+ * running. Reversed by {@link restore}.
10823
+ */
10824
+ takeOver(manager) {
10825
+ const renderer = manager.renderer;
10826
+ if (!this.takenOver.has(renderer)) {
10827
+ this.takenOver.set(renderer, renderer.prepareRenderView);
10828
+ renderer.prepareRenderView = () => false;
10829
+ }
10830
+ if (renderer.meshInstance)
10831
+ renderer.meshInstance.visible = false;
10832
+ // The manager's first update runs its render prep before frame:ready fires, and
10833
+ // material:created fires before the layer data holds the manager, so the engine's
10834
+ // projector, sorter and compaction get allocated once (32 bytes a splat and more).
10835
+ // Release them; the engine recreates them lazily if it renders again (XR, restore)
10836
+ // or picks through its sorted path.
10837
+ for (const key of ['gpuSorter', 'projector', 'intervalCompaction']) {
10838
+ const resource = renderer[key];
10839
+ if (resource) {
10840
+ resource.destroy();
10841
+ renderer[key] = null;
10842
+ }
10843
+ }
10844
+ }
10845
+ restore() {
10846
+ for (const [renderer, original] of this.takenOver) {
10847
+ renderer.prepareRenderView = original;
10848
+ if (renderer.meshInstance)
10849
+ renderer.meshInstance.visible = true;
10850
+ }
10851
+ this.takenOver.clear();
10852
+ }
10853
+ destroy() {
10854
+ this.restore();
10855
+ for (const handle of this.handles)
10856
+ handle.off();
10857
+ this.handles.length = 0;
10858
+ this.callbacks.clear();
10859
+ this.set = null;
10860
+ }
10861
+ }
10862
+ // Flatten the engine world state into files and nodes with world-space bounds.
10863
+ const buildResidentSet = (state) => {
10864
+ const files = [];
10865
+ const nodes = [];
10866
+ const spheres = [];
10867
+ const pushNode = (node, cx, cy, cz, radius) => {
10868
+ nodes.push(node);
10869
+ spheres.push(cx, cy, cz, radius);
10870
+ };
10871
+ state.splats.forEach((info, fileIndex) => {
10872
+ const modelMatrix = info.node.getWorldTransform().clone();
10873
+ const scale = modelMatrix.getScale(tmpVec2$1);
10874
+ const maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
10875
+ const file = {
10876
+ fileIndex,
10877
+ lodIndex: info.lodIndex,
10878
+ nodes: [],
10879
+ modelMatrix,
10880
+ resource: info.resource
10881
+ };
10882
+ const numIntervals = info.intervals.length / 2;
10883
+ if (numIntervals === 0) {
10884
+ // a single-file resource: one range covering it whole, bounded by its aabb
10885
+ const node = {
10886
+ fileIndex,
10887
+ nodeIndex: nodes.length,
10888
+ lodIndex: info.lodIndex,
10889
+ sourceBase: 0,
10890
+ count: info.activeSplats,
10891
+ slotBase: info.intervalOffsets[0] ?? 0,
10892
+ allocId: info.allocId
10893
+ };
10894
+ modelMatrix.transformPoint(info.aabb.center, tmpVec);
10895
+ const he = info.aabb.halfExtents;
10896
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, he.length() * maxScale);
10897
+ file.nodes.push(node);
10898
+ }
10899
+ else {
10900
+ for (let j = 0; j < numIntervals; j++) {
10901
+ const start = info.intervals[j * 2];
10902
+ const end = info.intervals[j * 2 + 1];
10903
+ const nodeIndex = info.intervalNodeIndices[j];
10904
+ const node = {
10905
+ fileIndex,
10906
+ nodeIndex: nodes.length,
10907
+ lodIndex: info.lodIndex,
10908
+ sourceBase: start,
10909
+ count: end - start,
10910
+ slotBase: info.intervalOffsets[j] ?? 0,
10911
+ allocId: info.intervalAllocIds[j]
10912
+ };
10913
+ const sphere = info.octreeNodes?.[nodeIndex]?.boundingSphere;
10914
+ if (sphere) {
10915
+ tmpVec.set(sphere.x, sphere.y, sphere.z);
10916
+ modelMatrix.transformPoint(tmpVec, tmpVec);
10917
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, sphere.w * maxScale);
10918
+ }
10919
+ else {
10920
+ // no bounds: never culled
10921
+ pushNode(node, 0, 0, 0, Infinity);
10922
+ }
10923
+ file.nodes.push(node);
10924
+ }
10925
+ }
10926
+ files.push(file);
10927
+ });
10928
+ return {
10929
+ version: state.version,
10930
+ activeSplats: state.totalActiveSplats,
10931
+ slotCapacity: state.textureSize * state.textureSize,
10932
+ fullRebuild: state.fullRebuild,
10933
+ changedAllocIds: state.needsUploadIds,
10934
+ files,
10935
+ nodes,
10936
+ nodeSpheres: new Float32Array(spheres)
10937
+ };
10938
+ };
10939
+
10940
+ // Single-thread pass turning the projector's survivor count into the indexed indirect draw
10941
+ // arguments for the raster pass and the indirect dispatch size of the order scatter. Nothing
10942
+ // comes back to the cpu, so a frame never stalls on the count. Entry layouts match the engine's
10943
+ // indirect draw buffer (5 u32 per slot) and indirect dispatch buffer (3 u32 per slot).
10944
+ const argsWGSL = /* wgsl */ `
10945
+ struct DrawIndexedIndirectArgs {
10946
+ indexCount: u32,
10947
+ instanceCount: u32,
10948
+ firstIndex: u32,
10949
+ baseVertex: i32,
10950
+ firstInstance: u32
10951
+ }
10952
+
10953
+ struct ArgsUniforms {
10954
+ drawSlot: u32,
10955
+ indexCount: u32,
10956
+ quadsPerInstance: u32,
10957
+ dispatchSlot: u32,
10958
+ scatterWorkgroupSize: u32
10959
+ }
10960
+
10961
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
10962
+ @group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>;
10963
+ @group(0) @binding(2) var<storage, read_write> indirectDispatchArgs: array<u32>;
10964
+ @group(0) @binding(3) var<uniform> uniforms: ArgsUniforms;
10965
+
10966
+ @compute @workgroup_size(1)
10967
+ fn main() {
10968
+ let count = counter[0];
10969
+ indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs(
10970
+ uniforms.indexCount,
10971
+ (count + uniforms.quadsPerInstance - 1u) / uniforms.quadsPerInstance,
10972
+ 0u,
10973
+ 0,
10974
+ 0u
10975
+ );
10976
+ // the scatter: one workgroup per scatterWorkgroupSize survivors, 2D past the 65535 limit
10977
+ let groups = (count + uniforms.scatterWorkgroupSize - 1u) / uniforms.scatterWorkgroupSize;
10978
+ let x = max(min(groups, 65535u), 1u);
10979
+ let base = uniforms.dispatchSlot * 3u;
10980
+ indirectDispatchArgs[base] = x;
10981
+ indirectDispatchArgs[base + 1u] = (groups + x - 1u) / x;
10982
+ indirectDispatchArgs[base + 2u] = 1u;
10983
+ }
10984
+ `;
10985
+
10986
+ // Temporal accumulation for the stochastic frame. Each frame the raster leaves one sample per
10987
+ // pixel (a colour where a splat's fragment survived its coverage test, nothing otherwise) and
10988
+ // the nearest surviving depth; this pass folds it into a per-pixel history of premultiplied
10989
+ // colour and coverage, so a still camera converges to the expected image over a few hundred
10990
+ // frames and a moving one keeps most of that history by reprojecting it.
10991
+ //
10992
+ // Reprojection uses the sample's own depth: the pixel's world point is carried into the
10993
+ // previous view and the history is fetched there, clamped to the colours this frame's
10994
+ // neighbourhood holds so a stale colour cannot survive a disocclusion. A pixel with no sample
10995
+ // this frame reprojects through the mean depth its own history remembers, so coverage fades out
10996
+ // where a surface has moved away rather than smearing into the background.
10997
+ //
10998
+ // The history is 12 bytes a pixel (24 with the ping-pong). The colour is the running mean as
10999
+ // 16-bit fixed point: a half float cannot hold it, since its steps in [0.5, 1) are 1 / 2048 and
11000
+ // the 1 / N step of a 256-sample mean rounds away once a sample lies within 1 / 16 of the mean
11001
+ // (an error floor of about 5 rms in 8-bit units), while fixed point steps by 1 / 65535
11002
+ // everywhere, so the same step only rounds away within half an 8-bit level of the mean. The
11003
+ // depth record is the mean view depth of the pixel's samples and their count in one 32-bit word.
11004
+ // the most samples the history's count field holds
11005
+ const TAA_MAX_COUNT = 511;
11006
+ const taaVertexWGSL = /* wgsl */ `
11007
+ attribute vertex_position: vec2f;
11008
+
11009
+ @vertex
11010
+ fn vertexMain(input: VertexInput) -> VertexOutput {
11011
+ var output: VertexOutput;
11012
+ output.position = vec4f(vertex_position, 0.0, 1.0);
11013
+ return output;
11014
+ }
11015
+ `;
11016
+ // The history's encoding, shared with the compose that reads it
11017
+ const taaHistoryWGSL = /* wgsl */ `
11018
+ const TAA_COLOR_SCALE = 65535.0;
11019
+
11020
+ fn decodeColor(v: vec4u) -> vec4f {
11021
+ return vec4f(v) / TAA_COLOR_SCALE;
11022
+ }
11023
+
11024
+ // premultiplied colour and coverage: coverage in [0, 1] and colour within it (the Catmull-Rom
11025
+ // fetch over- and undershoots both), rounded to the nearest step
11026
+ fn encodeColor(c: vec4f) -> vec4u {
11027
+ let a = clamp(c.a, 0.0, 1.0);
11028
+ return vec4u(round(vec4f(clamp(c.rgb, vec3f(0.0), vec3f(a)), a) * TAA_COLOR_SCALE));
11029
+ }
11030
+
11031
+ struct HistoryInfo {
11032
+ depth: f32,
11033
+ count: f32
11034
+ }
11035
+
11036
+ // The mean view depth keeps the float's exponent and top 15 mantissa bits, rounded: a relative
11037
+ // step of 2^-15, which stalls a 256-sample mean only within 0.4 % of the depth (the depth steers
11038
+ // the reprojection, where that is far below a pixel). The count takes the low 9 bits
11039
+ fn decodeInfo(v: u32) -> HistoryInfo {
11040
+ var info: HistoryInfo;
11041
+ info.depth = bitcast<f32>((v >> 9u) << 8u);
11042
+ info.count = f32(v & ${TAA_MAX_COUNT}u);
11043
+ return info;
11044
+ }
11045
+
11046
+ fn encodeInfo(depth: f32, count: f32) -> u32 {
11047
+ let bits = bitcast<u32>(max(depth, 0.0));
11048
+ return (((bits + 0x80u) >> 8u) << 9u) | min(u32(count), ${TAA_MAX_COUNT}u);
11049
+ }
11050
+ `;
11051
+ const taaFragmentWGSL = /* wgsl */ `
11052
+ var curColor: texture_2d<f32>;
11053
+ var curColorSampler: sampler;
11054
+ var curDepth: texture_depth_2d;
11055
+ // premultiplied colour and coverage, unorm16 (decodeColor)
11056
+ var histColor: texture_2d<u32>;
11057
+ // the mean view depth of the pixel's samples and their count, in the previous frame's view
11058
+ // depths (decodeInfo)
11059
+ var histInfo: texture_2d<u32>;
11060
+
11061
+ // the camera's world transform (the inverse view), and its projection's x and y terms: x, y the
11062
+ // scales, z, w the offsets (the column that multiplies view z for a perspective camera, the
11063
+ // translation for an orthographic one)
11064
+ uniform cameraWorld: mat4x4f;
11065
+ uniform unproject: vec4f;
11066
+ uniform prevViewProj: mat4x4f;
11067
+ uniform prevView: mat4x4f;
11068
+ // clip z = a * viewDepth + b over w = viewDepth (x, y); z: 1 for an orthographic camera
11069
+ uniform clipZParams: vec4f;
11070
+ // x: sample cap, y: 1 when the history holds the previous frame, z: 1 when the camera moved
11071
+ // since that frame, w: the frames the camera has rested, this one included (0 on a frame whose
11072
+ // resident set changed)
11073
+ uniform taaParams: vec4f;
11074
+ // width, height, 1 / width, 1 / height
11075
+ uniform taaViewport: vec4f;
11076
+ // x: -1 when the target's rows run bottom-up (an offscreen target), else 1; y: the colour
11077
+ // clamp width in neighbourhood standard deviations (0: no clamp); z: 1 when the raster's
11078
+ // thresholds are quad-stratified
11079
+ uniform taaControl: vec4f;
11080
+ // x: 1 for a Catmull-Rom history fetch while moving (0: bilinear); y: 1 to reproject through
11081
+ // the pixel's accumulated mean depth rather than this frame's sample depth; z: image motion in
11082
+ // pixels a frame that halves the moving sample cap (0: fixed cap)
11083
+ uniform taaFilter: vec4f;
11084
+ // 1: write the accumulation state instead of colour (r: count / cap, g: history accepted,
11085
+ // b: the camera moved since the previous frame)
11086
+ uniform taaDebug: f32;
11087
+
11088
+ ${taaHistoryWGSL}
11089
+
11090
+ fn viewDepthOf(z: f32) -> f32 {
11091
+ let p = uniform.clipZParams;
11092
+ let dz = z - p.x;
11093
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
11094
+ return select(p.y / safeDz, (z - p.y) / p.x, p.z != 0.0);
11095
+ }
11096
+
11097
+ struct Reprojected {
11098
+ valid: bool,
11099
+ uv: vec2f,
11100
+ prevDepth: f32
11101
+ }
11102
+
11103
+ // The previous frame's view depth and texture coordinate of this pixel's point at a view
11104
+ // depth. The point is built in view space from the depth and the projection's x and y terms,
11105
+ // then moved by the camera's rigid transform: through the inverse view-projection instead, a
11106
+ // near plane at 1e-4 of the depth (the viewer's floor once the camera is inside the scene
11107
+ // bound) leaves a 32-bit float about three digits of the point, a pixel of error that changes
11108
+ // with every frame's sample depths and shakes the history.
11109
+ fn reproject(pix: vec2i, viewDepth: f32) -> Reprojected {
11110
+ var r: Reprojected;
11111
+ let flip = uniform.taaControl.x;
11112
+ let uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
11113
+ let ndc = vec2f(uv.x * 2.0 - 1.0, flip * (1.0 - 2.0 * uv.y));
11114
+ let u = uniform.unproject;
11115
+ let viewXY = select((ndc + u.zw) * viewDepth, ndc - u.zw, uniform.clipZParams.z != 0.0) / u.xy;
11116
+ let world = (uniform.cameraWorld * vec4f(viewXY, -viewDepth, 1.0)).xyz;
11117
+ let prevClip = uniform.prevViewProj * vec4f(world, 1.0);
11118
+ r.prevDepth = -(uniform.prevView * vec4f(world, 1.0)).z;
11119
+ r.valid = prevClip.w > 0.0;
11120
+ let prevNdc = prevClip.xy / max(prevClip.w, 1e-9);
11121
+ r.uv = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * flip * 0.5);
11122
+ r.valid = r.valid && all(r.uv >= vec2f(0.0)) && all(r.uv <= vec2f(1.0));
11123
+ return r;
11124
+ }
11125
+
11126
+ // the premultiplied sample at a texel: its colour where a fragment landed, nothing otherwise
11127
+ fn sampleAt(pix: vec2i, dims: vec2i) -> vec4f {
11128
+ let p = clamp(pix, vec2i(0), dims - vec2i(1));
11129
+ let c = textureLoad(curColor, p, 0);
11130
+ let z = textureLoad(curDepth, p, 0);
11131
+ return select(vec4f(0.0), vec4f(c.rgb, 1.0), c.a > 0.0 && z < 1.0);
11132
+ }
11133
+
11134
+ // The mean of the 2x2 quad's samples, bilinear between quad centres (the compose's resolve of
11135
+ // the raster's quad-stratified thresholds): four samples a pixel, at a little sharpness, for
11136
+ // the frames where the history is too short to carry the noise on its own
11137
+ fn quadSample(pix: vec2i, dims: vec2i) -> vec4f {
11138
+ let size = vec2f(dims);
11139
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
11140
+ let q0 = floor(u);
11141
+ let f = u - q0;
11142
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
11143
+ let step = vec2f(2.0) / size;
11144
+ let a = textureSampleLevel(curColor, curColorSampler, uv, 0.0);
11145
+ let b = textureSampleLevel(curColor, curColorSampler, uv + vec2f(step.x, 0.0), 0.0);
11146
+ let c = textureSampleLevel(curColor, curColorSampler, uv + vec2f(0.0, step.y), 0.0);
11147
+ let d = textureSampleLevel(curColor, curColorSampler, uv + step, 0.0);
11148
+ let m = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
11149
+ // the raster leaves empty texels transparent black, so the mean is premultiplied coverage
11150
+ return vec4f(m.rgb, m.a);
11151
+ }
11152
+
11153
+ fn historyTexel(p: vec2i, dims: vec2i) -> vec4f {
11154
+ return decodeColor(textureLoad(histColor, clamp(p, vec2i(0), dims - vec2i(1)), 0));
11155
+ }
11156
+
11157
+ // Catmull-Rom fetch of the history: sharper than bilinear, whose blur compounds over the
11158
+ // frames a moving history lives. Its lobes over- and undershoot; the encoding clamps both
11159
+ fn historyCubicAt(uv: vec2f, dims: vec2i) -> vec4f {
11160
+ let p = uv * vec2f(dims) - vec2f(0.5);
11161
+ let i0 = vec2i(floor(p));
11162
+ let f = p - floor(p);
11163
+ let f2 = f * f;
11164
+ let f3 = f2 * f;
11165
+ // Catmull-Rom weights for taps at -1, 0, 1, 2
11166
+ let w0 = -0.5 * f3 + f2 - 0.5 * f;
11167
+ let w1 = 1.5 * f3 - 2.5 * f2 + vec2f(1.0);
11168
+ let w2 = -1.5 * f3 + 2.0 * f2 + 0.5 * f;
11169
+ let w3 = 0.5 * f3 - 0.5 * f2;
11170
+ let wx = array<f32, 4>(w0.x, w1.x, w2.x, w3.x);
11171
+ let wy = array<f32, 4>(w0.y, w1.y, w2.y, w3.y);
11172
+ var sum = vec4f(0.0);
11173
+ for (var y = 0; y < 4; y++) {
11174
+ for (var x = 0; x < 4; x++) {
11175
+ sum += historyTexel(i0 + vec2i(x - 1, y - 1), dims) * (wx[x] * wy[y]);
11176
+ }
11177
+ }
11178
+ return sum;
11179
+ }
11180
+
11181
+ // bilinear fetch of the history
11182
+ fn historyAt(uv: vec2f, dims: vec2i) -> vec4f {
11183
+ let p = uv * vec2f(dims) - vec2f(0.5);
11184
+ let i0 = vec2i(floor(p));
11185
+ let f = p - floor(p);
11186
+ let a = historyTexel(i0, dims);
11187
+ let b = historyTexel(i0 + vec2i(1, 0), dims);
11188
+ let c = historyTexel(i0 + vec2i(0, 1), dims);
11189
+ let d = historyTexel(i0 + vec2i(1, 1), dims);
11190
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
11191
+ }
11192
+
11193
+ @fragment
11194
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
11195
+ var output: FragmentOutput;
11196
+ let pix = vec2i(pcPosition.xy);
11197
+ let dims = vec2i(textureDimensions(curColor));
11198
+ let cur = textureLoad(curColor, pix, 0);
11199
+ let z = textureLoad(curDepth, pix, 0);
11200
+ let hit = cur.a > 0.0 && z < 1.0;
11201
+ let d = viewDepthOf(z);
11202
+
11203
+ let own = decodeInfo(textureLoad(histInfo, pix, 0).x);
11204
+ let maxCount = uniform.taaParams.x;
11205
+ let historyValid = uniform.taaParams.y > 0.5;
11206
+ let moving = uniform.taaParams.z > 0.5;
11207
+ // still: this pixel's own sample, so the history converges to full resolution; moving:
11208
+ // the quad's four
11209
+ var sample = select(vec4f(0.0), vec4f(cur.rgb, 1.0), hit);
11210
+ if (moving && uniform.taaControl.z > 0.5) {
11211
+ sample = quadSample(pix, dims);
11212
+ }
11213
+
11214
+ // Where to look in the history: through this frame's sample, or, with no sample, through
11215
+ // the depth this pixel's own history remembers, so an emptied pixel fades rather than
11216
+ // holding a stale colour
11217
+ var r: Reprojected;
11218
+ r.valid = false;
11219
+ var carryDepth = 0.0;
11220
+ if (!moving) {
11221
+ // a resting camera maps every pixel onto itself: the exact texel, not the round trip
11222
+ // through the matrices, whose rounding would blur the history a little every frame
11223
+ r.valid = true;
11224
+ r.uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
11225
+ r.prevDepth = select(own.depth, d, hit);
11226
+ carryDepth = r.prevDepth;
11227
+ } else if (uniform.taaFilter.y > 0.5 && own.count > 0.5) {
11228
+ // through the depth the pixel's history has settled on: one stochastic sample's depth
11229
+ // is one layer of the mixture the history holds, and reprojecting the mixture through
11230
+ // a different layer every frame smears it by their parallax
11231
+ r = reproject(pix, own.depth);
11232
+ carryDepth = own.depth;
11233
+ } else if (hit) {
11234
+ r = reproject(pix, d);
11235
+ carryDepth = d;
11236
+ } else if (own.count > 0.5) {
11237
+ r = reproject(pix, own.depth);
11238
+ carryDepth = own.depth;
11239
+ }
11240
+ r.valid = r.valid && historyValid;
11241
+
11242
+ var hist = vec4f(0.0);
11243
+ var info: HistoryInfo;
11244
+ var accepted = false;
11245
+ if (r.valid) {
11246
+ // at rest the exact texel; moving, a filtered fetch of the reprojected position
11247
+ if (!moving) {
11248
+ hist = decodeColor(textureLoad(histColor, pix, 0));
11249
+ info = own;
11250
+ } else {
11251
+ if (uniform.taaFilter.x > 0.5) {
11252
+ hist = historyCubicAt(r.uv, dims);
11253
+ } else {
11254
+ hist = historyAt(r.uv, dims);
11255
+ }
11256
+ info = decodeInfo(textureLoad(histInfo, clamp(vec2i(r.uv * vec2f(dims)), vec2i(0), dims - vec2i(1)), 0).x);
11257
+ }
11258
+ // a resting camera cannot disocclude anything, so every sample is accepted and the
11259
+ // pixel converges; moving, the colour clamp below keeps a disoccluded history out
11260
+ accepted = info.count > 0.5;
11261
+ }
11262
+
11263
+ var color: vec4f;
11264
+ var mean: f32;
11265
+ var count: f32;
11266
+ if (!accepted) {
11267
+ color = sample;
11268
+ mean = d;
11269
+ count = select(0.0, 1.0, hit);
11270
+ // at rest a pixel with no hit yet has still been sampled on every rest frame, so its
11271
+ // first hit is one of that many samples: at full weight a rare hit would flash to full
11272
+ // coverage, and freeze there once the viewer stops rendering. Its depth is the hit's
11273
+ if (hit && !moving && historyValid) {
11274
+ count = clamp(uniform.taaParams.w, 1.0, maxCount);
11275
+ color = sample / count;
11276
+ }
11277
+ } else {
11278
+ // moving, the history is clamped to the colours this frame's neighbourhood holds, so a
11279
+ // stale colour cannot survive where nothing like it is drawn any more
11280
+ if (moving && uniform.taaControl.y > 0.0) {
11281
+ var m1 = vec4f(0.0);
11282
+ var m2 = vec4f(0.0);
11283
+ for (var dy = -1; dy <= 1; dy++) {
11284
+ for (var dx = -1; dx <= 1; dx++) {
11285
+ let n = sampleAt(pix + vec2i(dx, dy), dims);
11286
+ m1 += n;
11287
+ m2 += n * n;
11288
+ }
11289
+ }
11290
+ let mu = m1 / 9.0;
11291
+ let sd = sqrt(max(m2 / 9.0 - mu * mu, vec4f(0.0)));
11292
+ let halfWidth = sd * uniform.taaControl.y;
11293
+ hist = clamp(hist, mu - halfWidth, mu + halfWidth);
11294
+ }
11295
+ // the faster the image moves, the shorter the history: a stochastic pixel's layers
11296
+ // reproject through one layer's depth, so their parallax smears the history by an
11297
+ // amount that grows with the motion, and a raw frame is the better estimate past it
11298
+ var cap = maxCount;
11299
+ if (moving && uniform.taaFilter.z > 0.0) {
11300
+ let speed = length(r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5));
11301
+ cap = max(2.0, maxCount / (1.0 + speed / uniform.taaFilter.z));
11302
+ }
11303
+ count = min(info.count + 1.0, cap);
11304
+ let w = 1.0 / count;
11305
+ color = mix(hist, sample, w);
11306
+ // an empty sample takes at least a step off the coverage: rounded to the nearest, a
11307
+ // decay of less than half a step holds (below cap / 2 steps, about 0.002 at the default
11308
+ // cap), so a faint pixel would keep its coverage, and the depth the compose writes for
11309
+ // it, forever. The colour follows, since the encoding keeps it within the coverage
11310
+ if (sample.a == 0.0) {
11311
+ color.a = min(color.a, max(hist.a - 1.0 / TAA_COLOR_SCALE, 0.0));
11312
+ }
11313
+ // carry the mean depth into this view: the point moved along the ray by the change in
11314
+ // its depth, then the sample joins it
11315
+ let shifted = info.depth + (carryDepth - r.prevDepth);
11316
+ mean = select(shifted, shifted + w * (d - shifted), hit);
11317
+ }
11318
+
11319
+ if (uniform.taaDebug > 1.5) {
11320
+ // the reprojection offset in pixels, 8 px full scale, centred on 0.5
11321
+ let mv = select(vec2f(0.0), r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5), r.valid);
11322
+ color = vec4f(mv / 16.0 + vec2f(0.5), select(0.0, 1.0, r.valid), 1.0);
11323
+ } else if (uniform.taaDebug > 0.5) {
11324
+ color = vec4f(count / maxCount, select(0.0, 1.0, accepted), select(0.0, 1.0, moving), 1.0);
11325
+ }
11326
+ output.color = encodeColor(color);
11327
+ output.color1 = encodeInfo(mean, count);
11328
+ return output;
11329
+ }
11330
+ `;
11331
+
11332
+ // The compose: a fullscreen quad in the World layer's transparent sublayer that blends the
11333
+ // stochastic target over the camera's target (after the skybox and opaque meshes) and writes
11334
+ // its depth, so everything drawn later depth-tests against the splats. The colour transform
11335
+ // the engine's own splat shader applies (gsplatOutputVS: tonemap and gamma, or the viewer's
11336
+ // pass-through patch under CameraFrame) runs here, once per pixel instead of once per splat.
11337
+ const composeVertexWGSL = /* wgsl */ `
11338
+ attribute vertex_position: vec2f;
11339
+
11340
+ @vertex
11341
+ fn vertexMain(input: VertexInput) -> VertexOutput {
11342
+ var output: VertexOutput;
11343
+ output.position = vec4f(vertex_position, 0.0, 1.0);
11344
+ return output;
11345
+ }
11346
+ `;
11347
+ const composeFragmentWGSL = /* wgsl */ `
11348
+ #include "gsplatOutputVS"
11349
+
11350
+ var splatColor: texture_2d<f32>;
11351
+ var splatColorSampler: sampler;
11352
+ var splatDepth: texture_depth_2d;
11353
+ // the temporally accumulated frame (premultiplied colour, coverage), when taa ran this frame
11354
+ var taaColor: texture_2d<u32>;
11355
+ // its depth record: the mean view depth of the pixel's samples and their count
11356
+ var taaInfo: texture_2d<u32>;
11357
+ // x: 1 when the splat target's rows run the other way to the camera target's; y: 1 for an
11358
+ // orthographic camera; z: 1 to read the taa history instead of the raw frame
11359
+ uniform composeParams: vec4f;
11360
+ // the splat target's depth: clip z = a * viewDepth + b over w = viewDepth (x, y), and the
11361
+ // camera's near and far (z, w) for the depth view
11362
+ uniform depthViewParams: vec4f;
11363
+ // the camera's own depth, the one written for the rest of the scene: clip z = a * viewDepth + b
11364
+ // (x, y). The splat target's far plane is at infinity where the camera's is fitted to the scene
11365
+ uniform cameraClipZ: vec4f;
11366
+
11367
+ ${taaHistoryWGSL}
11368
+
11369
+ const FAR_DEPTH = 0.999999;
11370
+
11371
+ // the splat target's depth texel of a view depth, just inside its far plane at most: the
11372
+ // raster clamps there too, since a depth of 1 reads as no sample
11373
+ fn clipZOf(viewDepth: f32) -> f32 {
11374
+ let p = uniform.depthViewParams;
11375
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
11376
+ return min(clamp(p.x * viewDepth + p.y, 0.0, w) / w, FAR_DEPTH);
11377
+ }
11378
+
11379
+ // the view depth of a splat target depth texel
11380
+ fn viewDepthOf(z: f32) -> f32 {
11381
+ let p = uniform.depthViewParams;
11382
+ let dz = z - p.x;
11383
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
11384
+ return select(p.y / safeDz, (z - p.y) / p.x, uniform.composeParams.y > 0.5);
11385
+ }
11386
+
11387
+ // A splat target depth in the camera's depth, clamped just inside the camera's far plane as the
11388
+ // engine clamps its splats: splats beyond it stay behind everything the scene draws
11389
+ fn cameraDepthOf(z: f32) -> f32 {
11390
+ let viewDepth = viewDepthOf(z);
11391
+ let c = uniform.cameraClipZ;
11392
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
11393
+ return min(clamp(c.x * viewDepth + c.y, 0.0, w) / w, FAR_DEPTH);
11394
+ }
11395
+
11396
+ @fragment
11397
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
11398
+ var output: FragmentOutput;
11399
+ let dims = vec2i(textureDimensions(splatColor));
11400
+ var pix = vec2i(pcPosition.xy);
11401
+ if (uniform.composeParams.x > 0.5) {
11402
+ pix.y = dims.y - 1 - pix.y;
11403
+ }
11404
+ pix = clamp(pix, vec2i(0), dims - vec2i(1));
11405
+
11406
+ var depth = textureLoad(splatDepth, pix, 0);
11407
+ var color: vec4f;
11408
+ if (uniform.composeParams.z > 0.5) {
11409
+ // the accumulated history: coverage in alpha, colour premultiplied by it
11410
+ color = decodeColor(textureLoad(taaColor, pix, 0));
11411
+ if (depth >= 1.0 && color.a > 0.001) {
11412
+ // covered by the history but no sample this frame, which a faint pixel sees on
11413
+ // most frames: the mean depth of the pixel's own samples, or, for a history this
11414
+ // frame started (moving, from the quad's samples), the nearest sampled neighbour's,
11415
+ // so the pixel still occludes what is behind the splats
11416
+ let info = decodeInfo(textureLoad(taaInfo, pix, 0).x);
11417
+ if (info.count > 0.5) {
11418
+ depth = clipZOf(info.depth);
11419
+ } else {
11420
+ for (var dy = -1; dy <= 1; dy++) {
11421
+ for (var dx = -1; dx <= 1; dx++) {
11422
+ depth = min(depth, textureLoad(splatDepth, clamp(pix + vec2i(dx, dy), vec2i(0), dims - vec2i(1)), 0));
11423
+ }
11424
+ }
11425
+ }
11426
+ }
11427
+ } else {
11428
+ #ifdef SSE_SPP_QUAD
11429
+ // the mean of each 2x2 quad, bilinearly interpolated between quad centres: the four
11430
+ // strata of the raster's thresholds average out to the splat's coverage. Empty texels
11431
+ // are transparent black, so the result is premultiplied coverage
11432
+ let size = vec2f(dims);
11433
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
11434
+ let q0 = floor(u);
11435
+ let f = u - q0;
11436
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
11437
+ let step = vec2f(2.0) / size;
11438
+ let a = textureSampleLevel(splatColor, splatColorSampler, uv, 0.0);
11439
+ let b = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(step.x, 0.0), 0.0);
11440
+ let c = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(0.0, step.y), 0.0);
11441
+ let d = textureSampleLevel(splatColor, splatColorSampler, uv + step, 0.0);
11442
+ color = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
11443
+ if (depth >= 1.0) {
11444
+ // no sample at this pixel but coverage from its quad: the quad's nearest depth
11445
+ let quad = (pix >> vec2u(1u)) << vec2u(1u);
11446
+ depth = min(
11447
+ min(textureLoad(splatDepth, quad, 0), textureLoad(splatDepth, min(quad + vec2i(1, 0), dims - 1), 0)),
11448
+ min(textureLoad(splatDepth, min(quad + vec2i(0, 1), dims - 1), 0), textureLoad(splatDepth, min(quad + vec2i(1, 1), dims - 1), 0))
11449
+ );
11450
+ }
11451
+ #else
11452
+ color = textureLoad(splatColor, pix, 0);
11453
+ #endif
11454
+ }
11455
+ if (color.a <= 0.001) {
11456
+ discard;
11457
+ }
11458
+ // coverage with no depth anywhere near: shown, behind everything the scene drew
11459
+ depth = min(depth, FAR_DEPTH);
11460
+
11461
+ #ifdef SSE_SHOW_DEPTH
11462
+ // the nearest sample's view depth, log-spaced between near and far, as grey
11463
+ let p = uniform.depthViewParams;
11464
+ let viewDepth = viewDepthOf(depth);
11465
+ let t = clamp(log(max(viewDepth, p.z) / p.z) / log(p.w / p.z), 0.0, 1.0);
11466
+ // 24-bit fixed point across rgb (high byte in red), so a capture can read it precisely
11467
+ let fixed = floor(t * 16777215.0);
11468
+ let hi = floor(fixed / 65536.0);
11469
+ let mid = floor((fixed - hi * 65536.0) / 256.0);
11470
+ let lo = fixed - hi * 65536.0 - mid * 256.0;
11471
+ output.color = vec4f(vec3f(hi, mid, lo) / 255.0, 1.0);
11472
+ output.fragDepth = cameraDepthOf(depth);
11473
+ return output;
11474
+ #endif
11475
+
11476
+ // un-premultiply for the output transform, then premultiply for the blend
11477
+ let gamma = color.rgb / color.a;
11478
+ let rgb = prepareOutputFromGamma(gamma, 0.0);
11479
+ output.color = vec4f(rgb * color.a, color.a);
11480
+ output.fragDepth = cameraDepthOf(depth);
11481
+ return output;
11482
+ }
11483
+ `;
11484
+
11485
+ // The projector: one 256-thread workgroup per chunk of the resident set. Each thread reads one
11486
+ // splat through the source's read code, projects it, applies the culls, and survivors append
11487
+ // themselves to a dense cache with one global atomic per workgroup. The chunk table and node
11488
+ // visibility come from the cpu (resident-set rebuild on version change, frustum cull per frame).
11489
+ /** Words per cache entry. See the layout in the plan: ndc, depth, axis1, len2|alpha|flags, rgb, popless, id. */
11490
+ const CACHE_WORDS = 7;
11491
+ const PROJECTOR_WORKGROUP_SIZE = 256;
11492
+ /** Buckets of the counting order (order:bucket); the workgroup size, so each thread owns one. */
11493
+ const ORDER_BUCKETS = PROJECTOR_WORKGROUP_SIZE;
11494
+ /** Splats per chunk-table entry; a chunk is one workgroup. */
11495
+ const CHUNK_SIZE = PROJECTOR_WORKGROUP_SIZE;
11496
+ const projectorWGSL = (readChunk, occlusion, order) => /* wgsl */ `
11497
+ struct ProjectorUniforms {
11498
+ view: mat4x4f,
11499
+ viewProj: mat4x4f,
11500
+ // the previous frame, for the occlusion cull: its view and view-projection, its clip-z
11501
+ // mapping (a, b, isOrtho, 0), viewport and focal length
11502
+ prevViewProj: mat4x4f,
11503
+ prevView: mat4x4f,
11504
+ prevClipZ: vec4f,
11505
+ viewport: vec2f,
11506
+ focal: vec2f,
11507
+ prevViewport: vec2f,
11508
+ prevFocal: vec2f,
11509
+ numChunks: u32,
11510
+ splatTextureSize: u32,
11511
+ isOrtho: u32,
11512
+ minPixelSize: f32,
11513
+ alphaClip: f32,
11514
+ minContribution: f32,
11515
+ // the occlusion grid: level 1 (8 px) and level 2 (32 px) block counts
11516
+ occBlocksX1: u32,
11517
+ occBlocksY1: u32,
11518
+ occBlocksX2: u32,
11519
+ occBlocksY2: u32,
11520
+ // 0 off, 1 level 1 only, 2 both levels
11521
+ occlusionMode: u32,
11522
+ // -1 when the previous depth texture's rows run bottom-up (an offscreen target), else 1
11523
+ prevFlip: f32,
11524
+ // the order key: bucket = (log(depth) - keyLogNear) * keyInvLogRange, over [0, 1)
11525
+ keyLogNear: f32,
11526
+ keyInvLogRange: f32,
11527
+ // first chunk-table entry of this dispatch (per-file sources dispatch one run each)
11528
+ chunkBase: u32,
11529
+ // the file's model transform, for sources that read splats in the file's own space
11530
+ model: mat4x4f,
11531
+ modelRotation: vec4f,
11532
+ modelScale: vec4f,
11533
+ cameraPosition: vec4f,
11534
+ // colour ceiling per channel: 8 keeps the cache's range, 1 clamps like the engine's 8-bit cache
11535
+ colorMax: f32,
11536
+ // 1: covariance in true pixels. 2: the engine's convention (its focal is viewport * proj[0][0],
11537
+ // twice the pixel focal), which makes its 0.3 dilation 0.075 px^2 and scales its culls
11538
+ unitScale: f32,
11539
+ // the view depths of the near plane and of the raster's far clamp
11540
+ depthNear: f32,
11541
+ depthFar: f32
11542
+ }
11543
+
11544
+ // chunk table entry: slotBase, count, node, lod | file << 16
11545
+ @group(0) @binding(0) var<storage, read> chunks: array<vec4u>;
11546
+ // one bit per node: 1 = inside the frustum this frame
11547
+ @group(0) @binding(1) var<storage, read> nodeVisible: array<u32>;
11548
+ @group(0) @binding(2) var<storage, read_write> cache: array<u32>;
11549
+ // [0] survivors this frame, [1] splats the occlusion cull removed
11550
+ @group(0) @binding(3) var<storage, read_write> counter: array<atomic<u32>>;
11551
+ @group(0) @binding(4) var<uniform> uniforms: ProjectorUniforms;
11552
+ // the previous frame's farthest depth per block, as f32 bits (see shaders/reduce.ts)
11553
+ @group(0) @binding(5) var<storage, read> occL1: array<u32>;
11554
+ @group(0) @binding(6) var<storage, read> occL2: array<u32>;
11555
+ // order:bucket: survivors per depth bucket (see shaders/order.ts)
11556
+ @group(0) @binding(7) var<storage, read_write> buckets: array<atomic<u32>>;
11557
+
11558
+ struct Splat {
11559
+ index: u32,
11560
+ uv: vec2i
11561
+ }
11562
+ var<private> splat: Splat;
11563
+ fn setSplat(idx: u32) {
11564
+ splat.index = idx;
11565
+ splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize));
11566
+ }
11567
+
11568
+ ${readChunk}
11569
+
11570
+ // quaternion (x, y, z, w) to a rotation matrix (columns)
11571
+ fn rotationMatrix(qIn: vec4f) -> mat3x3f {
11572
+ let q = normalize(qIn);
11573
+ let x = q.x;
11574
+ let y = q.y;
11575
+ let z = q.z;
11576
+ let w = q.w;
11577
+ return mat3x3f(
11578
+ vec3f(1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + w * z), 2.0 * (x * z - w * y)),
11579
+ vec3f(2.0 * (x * y - w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z + w * x)),
11580
+ vec3f(2.0 * (x * z + w * y), 2.0 * (y * z - w * x), 1.0 - 2.0 * (x * x + y * y))
11581
+ );
11582
+ }
11583
+
11584
+ struct Projected {
11585
+ valid: bool,
11586
+ occluded: bool,
11587
+ words: array<u32, ${CACHE_WORDS}>
11588
+ }
11589
+
11590
+ // The farthest depth over the (2g+1)^2 blocks around a block, on one grid level.
11591
+ fn farthestL1(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
11592
+ var farthest = 0u;
11593
+ for (var dy = -gather; dy <= gather; dy++) {
11594
+ for (var dx = -gather; dx <= gather; dx++) {
11595
+ farthest = max(farthest, occL1[u32((block.y + dy) * blocks.x + block.x + dx)]);
11596
+ }
11597
+ }
11598
+ return farthest;
11599
+ }
11600
+
11601
+ fn farthestL2(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
11602
+ var farthest = 0u;
11603
+ for (var dy = -gather; dy <= gather; dy++) {
11604
+ for (var dx = -gather; dx <= gather; dx++) {
11605
+ farthest = max(farthest, occL2[u32((block.y + dy) * blocks.x + block.x + dx)]);
11606
+ }
11607
+ }
11608
+ return farthest;
11609
+ }
11610
+
11611
+ fn project(slot: u32, file: u32) -> Projected {
11612
+ var result: Projected;
11613
+ result.valid = false;
11614
+ result.occluded = false;
11615
+
11616
+ setSplat(slot);
11617
+ let center = srcCenter();
11618
+ let opacity = srcOpacity();
11619
+ if (opacity < uniforms.alphaClip) {
11620
+ return result;
11621
+ }
11622
+
11623
+ let viewCenter = uniforms.view * vec4f(center, 1.0);
11624
+ let depth = -viewCenter.z;
11625
+ if (uniforms.isOrtho == 0u && depth <= 0.0) {
11626
+ return result;
11627
+ }
11628
+ let clip = uniforms.viewProj * vec4f(center, 1.0);
11629
+ if (clip.w == 0.0) {
11630
+ return result;
11631
+ }
11632
+
11633
+ let viewport = uniforms.viewport;
11634
+ let focal = uniforms.focal;
11635
+
11636
+ // the work buffer holds world-space splats, so the view matrix is the model-view
11637
+ let rot = srcRotation();
11638
+ let scale = srcScale();
11639
+ let linear = mat3x3f(uniforms.view[0].xyz, uniforms.view[1].xyz, uniforms.view[2].xyz);
11640
+ let gaussian = linear * rotationMatrix(vec4f(rot.yzw, rot.x)) * mat3x3f(
11641
+ vec3f(scale.x, 0.0, 0.0),
11642
+ vec3f(0.0, scale.y, 0.0),
11643
+ vec3f(0.0, 0.0, scale.z)
11644
+ );
11645
+ let row0 = vec3f(gaussian[0].x, gaussian[1].x, gaussian[2].x);
11646
+ let row1 = vec3f(gaussian[0].y, gaussian[1].y, gaussian[2].y);
11647
+ let row2 = vec3f(gaussian[0].z, gaussian[1].z, gaussian[2].z);
11648
+ let c00 = dot(row0, row0);
11649
+ let c01 = dot(row0, row1);
11650
+ let c02 = dot(row0, row2);
11651
+ let c11 = dot(row1, row1);
11652
+ let c12 = dot(row1, row2);
11653
+ let c22 = dot(row2, row2);
11654
+
11655
+ var cov00: f32;
11656
+ var cov01: f32;
11657
+ var cov11: f32;
11658
+ if (uniforms.isOrtho != 0u) {
11659
+ cov00 = focal.x * focal.x * c00;
11660
+ cov01 = focal.x * focal.y * c01;
11661
+ cov11 = focal.y * focal.y * c11;
11662
+ } else {
11663
+ let safeDepth = max(depth, 0.001);
11664
+ let invDepth = 1.0 / safeDepth;
11665
+ let jx0 = focal.x * invDepth;
11666
+ let jx2 = focal.x * viewCenter.x * invDepth * invDepth;
11667
+ let jy1 = focal.y * invDepth;
11668
+ let jy2 = focal.y * viewCenter.y * invDepth * invDepth;
11669
+ let u00 = jx0 * c00 + jx2 * c02;
11670
+ let u01 = jx0 * c01 + jx2 * c12;
11671
+ let u02 = jx0 * c02 + jx2 * c22;
11672
+ let u11 = jy1 * c11 + jy2 * c12;
11673
+ let u12 = jy1 * c12 + jy2 * c22;
11674
+ cov00 = u00 * jx0 + u02 * jx2;
11675
+ cov01 = u01 * jy1 + u02 * jy2;
11676
+ cov11 = u11 * jy1 + u12 * jy2;
11677
+ }
11678
+
11679
+ // the low-pass dilation every splat renderer applies, 0.3 in the chosen units
11680
+ let us2 = uniforms.unitScale * uniforms.unitScale;
11681
+ cov00 += 0.3 / us2;
11682
+ cov11 += 0.3 / us2;
11683
+ let determinant = cov00 * cov11 - cov01 * cov01;
11684
+ if (determinant <= 0.0) {
11685
+ return result;
11686
+ }
11687
+
11688
+ let mid = 0.5 * (cov00 + cov11);
11689
+ let radius = length(vec2f(0.5 * (cov00 - cov11), cov01));
11690
+ let lambda1 = mid + radius;
11691
+ let lambda2 = max(mid - radius, 0.1 / us2);
11692
+
11693
+ // size cull on the footprint's radius in pixels. minPixelSize is a diameter: the engine's
11694
+ // projector is dispatched with half of it, and its quad path tests the full extent
11695
+ // (2 sqrt(2 lambda)) against the whole value, so both cut at the same place
11696
+ if (uniforms.unitScale * sqrt(2.0 * lambda1) < 0.5 * uniforms.minPixelSize) {
11697
+ return result;
11698
+ }
11699
+
11700
+ // contribution cull: the splat's alpha mass in pixels (the engine's minContribution rule)
11701
+ if (opacity * 6.283185 * sqrt(determinant) * us2 < uniforms.minContribution) {
11702
+ return result;
11703
+ }
11704
+
11705
+ // principal axis; a circular footprint has no defined eigenvector, any axis is right
11706
+ let eigenVec = vec2f(cov01, lambda1 - cov00);
11707
+ let eigenLen = length(eigenVec);
11708
+ let direction = select(vec2f(1.0, 0.0), eigenVec / eigenLen, eigenLen > 1e-9);
11709
+ let maxRadius = min(1024.0, min(viewport.x, viewport.y));
11710
+ let len1 = 2.0 * sqrt(2.0 * lambda1);
11711
+ let radiusScale = min(1.0, maxRadius / len1);
11712
+ let axis1 = len1 * radiusScale * direction;
11713
+ let len2 = 2.0 * sqrt(2.0 * lambda2) * radiusScale;
11714
+ let axis2 = len2 * vec2f(direction.y, -direction.x);
11715
+
11716
+ let ndc = clip.xy / clip.w;
11717
+ let extent = abs(axis1) + abs(axis2);
11718
+ let centerPixels = (ndc * 0.5 + 0.5) * viewport;
11719
+ if (centerPixels.x + extent.x < 0.0 || centerPixels.x - extent.x > viewport.x
11720
+ || centerPixels.y + extent.y < 0.0 || centerPixels.y - extent.y > viewport.y) {
11721
+ return result;
11722
+ }
11723
+
11724
+ ${occlusion
11725
+ ? `
11726
+ // Occlusion cull against the previous frame. Each stored depth is the nearest sample that
11727
+ // survived there, so the farthest depth over the blocks a splat covered bounds what could
11728
+ // still have shown behind it; a splat whose front (its centre less 2 sqrt(2) sigma along the
11729
+ // view, the same cut-off as the quad's edge) lies beyond that bound was invisible last
11730
+ // frame, up to sampling. Static splats reproject exactly through the previous view, so only
11731
+ // true disocclusions arrive a frame late. The footprint the splat had last frame bounds the
11732
+ // gather; footprints up to 16 px use the 8 px grid, up to 64 px the 32 px grid, larger ones
11733
+ // skip the test.
11734
+ if (uniforms.occlusionMode != 0u) {
11735
+ let prevClip = uniforms.prevViewProj * vec4f(center, 1.0);
11736
+ let prevDepth = -(uniforms.prevView * vec4f(center, 1.0)).z;
11737
+ let prevOrtho = uniforms.prevClipZ.z != 0.0;
11738
+ if (prevClip.w > 0.0 && (prevOrtho || prevDepth > 0.0)) {
11739
+ let prevNdc = prevClip.xy / prevClip.w;
11740
+ let halfExtent = len1 * radiusScale;
11741
+ let prevHalfExtent = halfExtent * (uniforms.prevFocal.x / focal.x)
11742
+ * select(depth / max(prevDepth, 0.001), 1.0, prevOrtho);
11743
+ let footprint = max(halfExtent, prevHalfExtent);
11744
+ var level = 1u;
11745
+ var blockSize = 8.0;
11746
+ var blocks = vec2i(i32(uniforms.occBlocksX1), i32(uniforms.occBlocksY1));
11747
+ if (footprint > 16.0) {
11748
+ level = 2u;
11749
+ blockSize = 32.0;
11750
+ blocks = vec2i(i32(uniforms.occBlocksX2), i32(uniforms.occBlocksY2));
11751
+ }
11752
+ if (footprint <= 64.0 && level <= uniforms.occlusionMode) {
11753
+ let gather = max(i32(ceil(footprint / blockSize)), 1);
11754
+ let prevPixel = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * uniforms.prevFlip * 0.5) * uniforms.prevViewport;
11755
+ let block = vec2i(floor(prevPixel / blockSize));
11756
+ if (block.x >= gather && block.y >= gather && block.x < blocks.x - gather && block.y < blocks.y - gather) {
11757
+ let front = prevDepth - 2.8284 * sqrt(c22);
11758
+ let w = select(front, 1.0, prevOrtho);
11759
+ if (w > 0.0) {
11760
+ let frontZ = clamp(uniforms.prevClipZ.x * front + uniforms.prevClipZ.y, 0.0, w) / w;
11761
+ // the block under the centre first: the neighbourhood's maximum is at
11762
+ // least its maximum, so a splat that block alone cannot cull is visible,
11763
+ // and most splats leave here after one load
11764
+ let centreIndex = u32(block.y * blocks.x + block.x);
11765
+ var farthest = select(occL1[centreIndex], occL2[centreIndex], level == 2u);
11766
+ if (frontZ > bitcast<f32>(farthest)) {
11767
+ if (level == 1u) {
11768
+ farthest = farthestL1(block, gather, blocks);
11769
+ } else {
11770
+ farthest = farthestL2(block, gather, blocks);
11771
+ }
11772
+ if (frontZ > bitcast<f32>(farthest)) {
11773
+ result.occluded = true;
11774
+ return result;
11775
+ }
11776
+ }
11777
+ }
11778
+ }
11779
+ }
11780
+ }
11781
+ }
11782
+
11783
+ `
11784
+ : ''}
11785
+ let color = clamp(srcColor(), vec3f(0.0), vec3f(uniforms.colorMax));
11786
+
11787
+ // rgb: 10/10/10 unorm with a 2-bit shared exponent (scale 1/2/4/8, range [0, 8])
11788
+ let maxChannel = max(color.r, max(color.g, color.b));
11789
+ var exponent = 0u;
11790
+ if (maxChannel > 4.0) {
11791
+ exponent = 3u;
11792
+ } else if (maxChannel > 2.0) {
11793
+ exponent = 2u;
11794
+ } else if (maxChannel > 1.0) {
11795
+ exponent = 1u;
11796
+ }
11797
+ let rgb = vec3u(clamp(color / f32(1u << exponent), vec3f(0.0), vec3f(1.0)) * 1023.0 + 0.5);
11798
+
11799
+ // centre as snorm16 over the range the offscreen cull bounds visible centres to; the
11800
+ // raster shader derives the same range from its viewport
11801
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / viewport;
11802
+
11803
+ result.valid = true;
11804
+ result.words[0] = pack2x16snorm(ndc / ndcRange);
11805
+ result.words[1] = bitcast<u32>(depth);
11806
+ result.words[2] = pack2x16float(axis1);
11807
+ result.words[3] = pack2x16float(vec2f(len2, 0.0)) | (u32(clamp(opacity, 0.0, 1.0) * 255.0 + 0.5) << 16u);
11808
+ ${order
11809
+ ? `
11810
+ // the depth bucket, log-spaced from the near plane, in the flags byte
11811
+ let key = clamp((log(max(depth, 1e-6)) - uniforms.keyLogNear) * uniforms.keyInvLogRange, 0.0, 0.999) * ${ORDER_BUCKETS}.0;
11812
+ result.words[3] |= u32(key) << 24u;
11813
+ `
11814
+ : ''}
11815
+ result.words[4] = rgb.r | (rgb.g << 10u) | (rgb.b << 20u) | (exponent << 30u);
11816
+ // Popless depth (StochasticSplats 3.4): the quad is tilted onto the plane through the
11817
+ // centre with normal adj(Sigma) mu (view space; adj rather than the inverse, so a flat
11818
+ // splat needs no division by its tiny determinant), and the raster gives each corner the
11819
+ // depth where its own view ray meets that plane, so hardware interpolation hands every
11820
+ // fragment the depth of the Gaussian's peak along its ray instead of the centre's. Stored
11821
+ // as g = n.xy / (n . mu): a corner at view offset d (in the plane z = -depth) lands at
11822
+ // depth / (1 + g . d). Orthographic rays are parallel, so there n = adj(Sigma) e_z and
11823
+ // the corner depth is depth + g . d with g = n.xy / n.z. Bounded so every corner stays
11824
+ // within 2 sqrt(2) sigma_z of the centre (the occlusion cull's front margin) and the
11825
+ // perspective scale stays positive, and so no corner crosses the near plane or the
11826
+ // raster's far clamp: a corner clamped there while the others are not bends the quad, whose
11827
+ // two triangles then take different depths and show as polygons (large far splats, the
11828
+ // sky, sit right at a far plane fitted to the scene). A centre beyond the clamp stays flat.
11829
+ let ortho = uniforms.isOrtho != 0u;
11830
+ let a00 = c11 * c22 - c12 * c12;
11831
+ let a01 = c02 * c12 - c01 * c22;
11832
+ let a02 = c01 * c12 - c02 * c11;
11833
+ let a11 = c00 * c22 - c02 * c02;
11834
+ let a12 = c01 * c02 - c00 * c12;
11835
+ let a22 = c00 * c11 - c01 * c01;
11836
+ let toward = select(viewCenter.xyz, vec3f(0.0, 0.0, -1.0), ortho);
11837
+ let n = vec3f(
11838
+ a00 * toward.x + a01 * toward.y + a02 * toward.z,
11839
+ a01 * toward.x + a11 * toward.y + a12 * toward.z,
11840
+ a02 * toward.x + a12 * toward.y + a22 * toward.z
11841
+ );
11842
+ let denom = select(dot(n, viewCenter.xyz), n.z, ortho);
11843
+ var g = vec2f(0.0);
11844
+ if (abs(denom) > 1e-20) {
11845
+ g = n.xy / denom;
11846
+ // view units per pixel at the centre's depth, and the quad's half extents in them
11847
+ let viewScale = select(depth, 1.0, ortho) / focal;
11848
+ let ext = (abs(axis1) + abs(axis2)) * viewScale;
11849
+ let bound = abs(g.x) * ext.x + abs(g.y) * ext.y;
11850
+ let margin = 2.8284 * sqrt(max(c22, 0.0));
11851
+ let inRange = select(
11852
+ min(1.0 - depth / uniforms.depthFar, depth / max(uniforms.depthNear, 1e-6) - 1.0),
11853
+ min(uniforms.depthFar - depth, depth - uniforms.depthNear),
11854
+ ortho
11855
+ );
11856
+ let limit = max(0.0, min(select(min(0.25, margin / max(depth, 1e-6)), margin, ortho), 0.999 * inRange));
11857
+ if (bound > limit) {
11858
+ g *= limit / max(bound, 1e-20);
11859
+ }
11860
+ }
11861
+ result.words[5] = pack2x16float(g);
11862
+ // the stable id the coverage hash seeds from: the slot, salted by the file for sources
11863
+ // whose indices restart per file
11864
+ result.words[6] = slot ^ (file * 2654435761u);
11865
+ return result;
11866
+ }
11867
+
11868
+ var<workgroup> wgCount: atomic<u32>;
11869
+ var<workgroup> wgOccluded: atomic<u32>;
11870
+ var<workgroup> wgBase: u32;
11871
+ ${order ? `var<workgroup> wgBuckets: array<atomic<u32>, ${ORDER_BUCKETS}>;` : ''}
11872
+
11873
+ @compute @workgroup_size(${PROJECTOR_WORKGROUP_SIZE})
11874
+ fn main(
11875
+ @builtin(workgroup_id) wg: vec3u,
11876
+ @builtin(num_workgroups) numWorkgroups: vec3u,
11877
+ @builtin(local_invocation_index) local: u32
11878
+ ) {
11879
+ // no early returns: the barriers below need every thread of the workgroup
11880
+ let chunkIndex = wg.x + wg.y * numWorkgroups.x;
11881
+ ${order ? ` atomicStore(&wgBuckets[local], 0u);` : ''}
11882
+ var projected: Projected;
11883
+ projected.valid = false;
11884
+ projected.occluded = false;
11885
+ if (chunkIndex < uniforms.numChunks) {
11886
+ let chunk = chunks[uniforms.chunkBase + chunkIndex];
11887
+ let visible = (nodeVisible[chunk.z >> 5u] >> (chunk.z & 31u)) & 1u;
11888
+ if (visible != 0u && local < chunk.y) {
11889
+ projected = project(chunk.x + local, chunk.w >> 16u);
11890
+ }
11891
+ }
11892
+
11893
+ // survivors claim consecutive slots: one workgroup-local count, one global atomic
11894
+ var localSlot = 0u;
11895
+ if (projected.valid) {
11896
+ localSlot = atomicAdd(&wgCount, 1u);
11897
+ }
11898
+ if (projected.occluded) {
11899
+ atomicAdd(&wgOccluded, 1u);
11900
+ }
11901
+ workgroupBarrier();
11902
+ if (local == 0u) {
11903
+ let n = atomicLoad(&wgCount);
11904
+ wgBase = select(0u, atomicAdd(&counter[0], n), n > 0u);
11905
+ let o = atomicLoad(&wgOccluded);
11906
+ if (o > 0u) {
11907
+ atomicAdd(&counter[1], o);
11908
+ }
11909
+ }
11910
+ workgroupBarrier();
11911
+ if (projected.valid) {
11912
+ let base = (wgBase + localSlot) * ${CACHE_WORDS}u;
11913
+ for (var i = 0u; i < ${CACHE_WORDS}u; i++) {
11914
+ cache[base + i] = projected.words[i];
11915
+ }
11916
+ ${order ? ` atomicAdd(&wgBuckets[projected.words[3] >> 24u], 1u);` : ''}
11917
+ }
11918
+ ${order
11919
+ ? `
11920
+ // a chunk's splats are spatially coherent, so few of its buckets are non-empty: one
11921
+ // workgroup count each, then one global atomic per non-empty bucket
11922
+ workgroupBarrier();
11923
+ let bucketCount = atomicLoad(&wgBuckets[local]);
11924
+ if (bucketCount > 0u) {
11925
+ atomicAdd(&buckets[local], bucketCount);
11926
+ }
11927
+ `
11928
+ : ''}
11929
+ }
11930
+ `;
11931
+
11932
+ // The ordering passes (variant order:bucket): the projector counts its survivors into 256
11933
+ // depth buckets, front to back; a one-workgroup scan turns the counts into bucket offsets, and
11934
+ // the scatter writes each survivor's cache slot into the ordered list the raster then follows.
11935
+ // Splats inside a bucket land in append order, so a bucket keeps its chunks' locality.
11936
+ // exclusive prefix sum of the bucket counts into the bucket offsets, in one workgroup
11937
+ const orderScanWGSL = /* wgsl */ `
11938
+ // [0, ${ORDER_BUCKETS}) counts, [${ORDER_BUCKETS}, ${2 * ORDER_BUCKETS}) offsets
11939
+ @group(0) @binding(0) var<storage, read_write> buckets: array<u32>;
11940
+
11941
+ var<workgroup> partial: array<u32, ${ORDER_BUCKETS}>;
11942
+
11943
+ @compute @workgroup_size(${ORDER_BUCKETS})
11944
+ fn main(@builtin(local_invocation_index) local: u32) {
11945
+ partial[local] = buckets[local];
11946
+ for (var stride = 1u; stride < ${ORDER_BUCKETS}u; stride <<= 1u) {
11947
+ workgroupBarrier();
11948
+ let value = select(0u, partial[local - stride], local >= stride);
11949
+ workgroupBarrier();
11950
+ partial[local] += value;
11951
+ }
11952
+ // inclusive to exclusive
11953
+ buckets[${ORDER_BUCKETS}u + local] = partial[local] - buckets[local];
11954
+ }
11955
+ `;
11956
+ // One thread per cache slot, one workgroup per 256 consecutive slots. Consecutive slots come
11957
+ // from one chunk, so a workgroup touches few buckets: it counts them locally, claims each
11958
+ // bucket's range with one global atomic, and places its splats in append order inside it.
11959
+ const orderScatterWGSL = /* wgsl */ `
11960
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
11961
+ @group(0) @binding(1) var<storage, read> cache: array<u32>;
11962
+ @group(0) @binding(2) var<storage, read_write> buckets: array<atomic<u32>>;
11963
+ @group(0) @binding(3) var<storage, read_write> ordered: array<u32>;
11964
+
11965
+ var<workgroup> wgCounts: array<atomic<u32>, ${ORDER_BUCKETS}>;
11966
+ var<workgroup> wgBase: array<u32, ${ORDER_BUCKETS}>;
11967
+
11968
+ @compute @workgroup_size(${ORDER_BUCKETS})
11969
+ fn main(
11970
+ @builtin(workgroup_id) wg: vec3u,
11971
+ @builtin(num_workgroups) numWorkgroups: vec3u,
11972
+ @builtin(local_invocation_index) local: u32
11973
+ ) {
11974
+ // no early returns: the barriers need every thread
11975
+ atomicStore(&wgCounts[local], 0u);
11976
+ let slot = (wg.x + wg.y * numWorkgroups.x) * ${ORDER_BUCKETS}u + local;
11977
+ let live = slot < counter[0];
11978
+ var key = 0u;
11979
+ var rank = 0u;
11980
+ workgroupBarrier();
11981
+ if (live) {
11982
+ key = cache[slot * ${CACHE_WORDS}u + 3u] >> 24u;
11983
+ rank = atomicAdd(&wgCounts[key], 1u);
11984
+ }
11985
+ workgroupBarrier();
11986
+ let count = atomicLoad(&wgCounts[local]);
11987
+ if (count > 0u) {
11988
+ wgBase[local] = atomicAdd(&buckets[${ORDER_BUCKETS}u + local], count);
11989
+ }
11990
+ workgroupBarrier();
11991
+ if (live) {
11992
+ ordered[wgBase[key] + rank] = slot;
11993
+ }
11994
+ }
11995
+ `;
11996
+
11997
+ // The raster pass: an indirect instanced draw of 128-quad meshes over the projector's
11998
+ // survivors, into the renderer's own colour + depth target. Fragments keep themselves with
11999
+ // probability alpha (StochasticSplats, Listing 1) and write opaque colour with hardware depth,
12000
+ // so no sort is needed and the depth buffer holds the nearest surviving sample per pixel.
12001
+ /** Quads per draw instance; the mesh holds this many quads. */
12002
+ const QUADS_PER_INSTANCE = 128;
12003
+ /** The raster's far clamp in normalised depth: just inside 1, which the compose reads as empty. */
12004
+ const FAR_CLIP_Z = 0.999999;
12005
+ const rasterVertexWGSL = /* wgsl */ `
12006
+ attribute vertex_position: vec3f;
12007
+
12008
+ // width, height, 2 / width, 2 / height
12009
+ uniform viewportSize: vec4f;
12010
+ // clip z = a * viewDepth + b (x, y); z = 1 for an orthographic camera
12011
+ uniform clipZParams: vec4f;
12012
+ // set by the engine's forward renderer for the target being rendered
12013
+ uniform projectionFlipY: f32;
12014
+ // focal length in pixels (x, y), for the popless corner depths
12015
+ uniform focalParams: vec4f;
12016
+
12017
+ var<storage, read> splatCache: array<u32>;
12018
+ var<storage, read> splatCount: array<u32>;
12019
+ #ifdef SSE_ORDERED
12020
+ // cache slots in draw order (variant order:bucket)
12021
+ var<storage, read> orderedSlots: array<u32>;
12022
+ #endif
12023
+
12024
+ // screen-linear: the corners share one screen footprint whatever depth they carry
12025
+ varying @interpolate(linear) gaussianUV: vec2f;
12026
+ varying @interpolate(flat, either) packedColor: u32;
12027
+ varying @interpolate(flat, either) packedAlpha: u32;
12028
+ varying @interpolate(flat, either) splatId: u32;
12029
+
12030
+ const discardPosition = vec4f(0.0, 0.0, 2.0, 1.0);
12031
+
12032
+ @vertex
12033
+ fn vertexMain(input: VertexInput) -> VertexOutput {
12034
+ var output: VertexOutput;
12035
+ let order = pcInstanceIndex * ${QUADS_PER_INSTANCE}u + u32(vertex_position.z);
12036
+ // the indirect instance count rounds up to whole instances; the tail is discarded here
12037
+ if (order >= splatCount[0]) {
12038
+ output.position = discardPosition;
12039
+ return output;
12040
+ }
12041
+
12042
+ #ifdef SSE_ORDERED
12043
+ let base = orderedSlots[order] * ${CACHE_WORDS}u;
12044
+ #else
12045
+ let base = order * ${CACHE_WORDS}u;
12046
+ #endif
12047
+ let maxRadius = min(1024.0, min(uniform.viewportSize.x, uniform.viewportSize.y));
12048
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / uniform.viewportSize.xy;
12049
+ let ndc = unpack2x16snorm(splatCache[base]) * ndcRange;
12050
+ let depth = bitcast<f32>(splatCache[base + 1u]);
12051
+ let ortho = uniform.clipZParams.z != 0.0;
12052
+
12053
+ let axis1 = unpack2x16float(splatCache[base + 2u]);
12054
+ let word3 = splatCache[base + 3u];
12055
+ let len2 = unpack2x16float(word3).x;
12056
+ let axis2 = len2 * normalize(vec2f(axis1.y, -axis1.x));
12057
+
12058
+ let corner = vertex_position.xy;
12059
+ let pixelOffset = corner.x * axis1 + corner.y * axis2;
12060
+ #ifdef SSE_POPLESS
12061
+ // the corner's depth on the splat's plane (see the projector): its view-space offset
12062
+ // at the centre's depth, times the stored gradient
12063
+ let g = unpack2x16float(splatCache[base + 5u]);
12064
+ let shift = dot(g, pixelOffset * select(depth, 1.0, ortho) / uniform.focalParams.xy);
12065
+ let cornerDepth = select(depth / (1.0 + shift), depth + shift, ortho);
12066
+ #else
12067
+ let cornerDepth = depth;
12068
+ #endif
12069
+ let w = select(cornerDepth, 1.0, ortho);
12070
+ let ndcCorner = ndc + pixelOffset * uniform.viewportSize.zw;
12071
+ // clip z clamped into range like the engine's splat shader, so splats beyond the far plane
12072
+ // still draw; just inside it, since the compose and the accumulation read depth 1 as empty
12073
+ let pos = vec4f(ndcCorner * w, clamp(uniform.clipZParams.x * cornerDepth + uniform.clipZParams.y, 0.0, w * ${FAR_CLIP_Z}), w);
12074
+ output.position = vec4f(pos.x, pos.y * uniform.projectionFlipY, pos.z, pos.w);
12075
+ output.gaussianUV = corner;
12076
+ output.packedColor = splatCache[base + 4u];
12077
+ output.packedAlpha = word3 >> 16u;
12078
+ output.splatId = splatCache[base + 6u];
12079
+ return output;
12080
+ }
12081
+ `;
12082
+ const rasterFragmentWGSL = /* wgsl */ `
12083
+ varying @interpolate(linear) gaussianUV: vec2f;
12084
+ varying @interpolate(flat, either) packedColor: u32;
12085
+ varying @interpolate(flat, either) packedAlpha: u32;
12086
+ varying @interpolate(flat, either) splatId: u32;
12087
+
12088
+ uniform sseAlphaClip: f32;
12089
+ // 0 while the camera rests, so a still frame reproduces itself; the frame index once TAA
12090
+ // accumulates
12091
+ uniform frameSeed: u32;
12092
+
12093
+ const EXP4 = exp(-4.0);
12094
+ const INV_EXP4 = 1.0 / (1.0 - EXP4);
12095
+
12096
+ // the engine's falloff: zero at the quad edge, which sits at 2 sqrt(2) sigma
12097
+ fn normExp(x: f32) -> f32 {
12098
+ return (exp(x * -4.0) - EXP4) * INV_EXP4;
12099
+ }
12100
+
12101
+ // integer hash (Wellons' prospector mix)
12102
+ fn hashU32(x: u32) -> u32 {
12103
+ var v = x;
12104
+ v ^= v >> 16u;
12105
+ v *= 0x7feb352du;
12106
+ v ^= v >> 15u;
12107
+ v *= 0x846ca68bu;
12108
+ v ^= v >> 16u;
12109
+ return v;
12110
+ }
12111
+
12112
+ @fragment
12113
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
12114
+ var output: FragmentOutput;
12115
+ let radius = dot(gaussianUV, gaussianUV);
12116
+ if (radius > 1.0) {
12117
+ discard;
12118
+ }
12119
+ let opacity = f32(packedAlpha & 0xffu) / 255.0;
12120
+ let alpha = normExp(radius) * opacity;
12121
+ if (alpha < uniform.sseAlphaClip) {
12122
+ discard;
12123
+ }
12124
+
12125
+ let pix = vec2u(pcPosition.xy);
12126
+ #ifdef SSE_SPP_QUAD
12127
+ // one sample per pixel, thresholds stratified over each 2x2 pixel quad: the quad's four
12128
+ // pixels take the four strata of [0, 1) in a per-(quad, splat) scrambled order, so a
12129
+ // splat with alpha a covers 4a +- 1 of its quad and the compose's quad mean is nearly
12130
+ // exact. Hashing quad and splat keeps overlapping splats decorrelated
12131
+ let quad = pix >> vec2u(1u);
12132
+ let h = hashU32((quad.x * 1973u) ^ (quad.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
12133
+ let stratum = ((pix.y & 1u) * 2u + (pix.x & 1u)) ^ (h & 3u);
12134
+ let rnd = (f32(stratum) + f32(h >> 8u) * (1.0 / 16777216.0)) * 0.25;
12135
+ #else
12136
+ let h = hashU32((pix.x * 1973u) ^ (pix.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
12137
+ let rnd = f32(h >> 8u) * (1.0 / 16777216.0);
12138
+ #endif
12139
+ if (rnd >= alpha) {
12140
+ discard;
12141
+ }
12142
+
12143
+ let bits = packedColor;
12144
+ let color = vec3f(vec3u(bits, bits >> 10u, bits >> 20u) & vec3u(1023u)) * (f32(1u << (bits >> 30u)) / 1023.0);
12145
+ // opaque coverage: the compose reads alpha 1 as "a sample landed here"
12146
+ output.color = vec4f(color, 1.0);
12147
+ return output;
12148
+ }
12149
+ `;
12150
+
12151
+ // The occlusion grid: the previous frame's depth texture reduced to the farthest depth per 8x8
12152
+ // pixel block (level 1), and the farthest of each 4x4 group of those (level 2, 32 px). Each
12153
+ // pixel's depth is the nearest surviving sample there, so a block's maximum bounds what could
12154
+ // still have shown behind it; a splat whose front lies beyond that bound over every block it
12155
+ // covers was invisible last frame. Depths are hardware z in [0, 1], stored as their f32 bits
12156
+ // (non-negative floats order the same as their bits, so atomicMax works on them).
12157
+ const reduceL1WGSL = /* wgsl */ `
12158
+ struct ReduceUniforms {
12159
+ width: u32,
12160
+ height: u32,
12161
+ blocksX: u32,
12162
+ blocksY: u32
12163
+ }
12164
+
12165
+ @group(0) @binding(0) var prevDepth: texture_depth_2d;
12166
+ @group(0) @binding(1) var<storage, read_write> blockMax: array<u32>;
12167
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
12168
+
12169
+ var<workgroup> wgMax: atomic<u32>;
12170
+
12171
+ @compute @workgroup_size(8, 8)
12172
+ fn main(
12173
+ @builtin(workgroup_id) wg: vec3u,
12174
+ @builtin(local_invocation_id) lid: vec3u,
12175
+ @builtin(local_invocation_index) li: u32
12176
+ ) {
12177
+ let pixel = wg.xy * 8u + lid.xy;
12178
+ // pixels off the texture count as far, so an edge block never culls
12179
+ var depth = 1.0;
12180
+ if (pixel.x < uniforms.width && pixel.y < uniforms.height) {
12181
+ depth = textureLoad(prevDepth, vec2i(pixel), 0);
12182
+ }
12183
+ atomicMax(&wgMax, bitcast<u32>(depth));
12184
+ workgroupBarrier();
12185
+ if (li == 0u) {
12186
+ blockMax[wg.y * uniforms.blocksX + wg.x] = atomicLoad(&wgMax);
12187
+ }
12188
+ }
12189
+ `;
12190
+ const reduceL2WGSL = /* wgsl */ `
12191
+ struct ReduceUniforms {
12192
+ blocksX1: u32,
12193
+ blocksY1: u32,
12194
+ blocksX2: u32,
12195
+ blocksY2: u32
12196
+ }
12197
+
12198
+ @group(0) @binding(0) var<storage, read> level1: array<u32>;
12199
+ @group(0) @binding(1) var<storage, read_write> level2: array<u32>;
12200
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
12201
+
12202
+ @compute @workgroup_size(64)
12203
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
12204
+ let index = gid.x;
12205
+ if (index >= uniforms.blocksX2 * uniforms.blocksY2) {
12206
+ return;
12207
+ }
12208
+ let bx = index % uniforms.blocksX2;
12209
+ let by = index / uniforms.blocksX2;
12210
+ var farthest = 0u;
12211
+ for (var dy = 0u; dy < 4u; dy++) {
12212
+ for (var dx = 0u; dx < 4u; dx++) {
12213
+ let x = bx * 4u + dx;
12214
+ let y = by * 4u + dy;
12215
+ if (x < uniforms.blocksX1 && y < uniforms.blocksY1) {
12216
+ farthest = max(farthest, level1[y * uniforms.blocksX1 + x]);
12217
+ } else {
12218
+ farthest = max(farthest, bitcast<u32>(1.0));
12219
+ }
12220
+ }
12221
+ }
12222
+ level2[index] = farthest;
12223
+ }
12224
+ `;
12225
+
12226
+ // Data path (ii): the projector reads each resident file's own textures (sog, ply or
12227
+ // compressed ply) through the engine's format read chunks, so nothing is copied into a work
12228
+ // buffer: no decoded 24-byte copy per splat, no re-copy when a node's lod changes, no
12229
+ // colour refresh when the camera turns. The price is one dispatch per resident file, the
12230
+ // model transform and the sh evaluation per splat per frame.
12231
+ //
12232
+ // Interim: the engine still allocates its work buffer and would keep copying into it, so the
12233
+ // copy passes are switched off on the work buffer this source sees; the textures themselves
12234
+ // stay until engine change E2 (no work buffer in external mode) lands.
12235
+ const tmpScale = new Vec3();
12236
+ const tmpRotation = new Quat();
12237
+ class DirectSplatSource {
12238
+ kind = 'direct';
12239
+ device;
12240
+ resource = null;
12241
+ set = null;
12242
+ constants = new Map();
12243
+ patched = null;
12244
+ constructor(device) {
12245
+ this.device = device;
12246
+ }
12247
+ update(set, manager) {
12248
+ // one format per scene: a sog lod set shares its format across files. The first file's
12249
+ // format compiles the projector; a file of another format is skipped by dispatchPlan
12250
+ this.resource = set.files[0]?.resource ?? this.resource;
12251
+ this.set = set;
12252
+ this.constants.clear();
12253
+ for (const file of set.files) {
12254
+ const m = file.modelMatrix;
12255
+ m.getScale(tmpScale);
12256
+ tmpRotation.setFromMat4(m);
12257
+ if (tmpRotation.w < 0)
12258
+ tmpRotation.mulScalar(-1);
12259
+ this.constants.set(file.fileIndex, {
12260
+ rotation: [tmpRotation.x, tmpRotation.y, tmpRotation.z, tmpRotation.w],
12261
+ scale: [tmpScale.x, tmpScale.y, tmpScale.z, 0]
12262
+ });
12263
+ }
12264
+ this.patchWorkBuffer(manager.world.workBuffer);
12265
+ }
12266
+ // the engine's copy into the work buffer is wasted work for this path
12267
+ patchWorkBuffer(workBuffer) {
12268
+ if (this.patched?.workBuffer === workBuffer)
12269
+ return;
12270
+ this.restoreWorkBuffer();
12271
+ this.patched = { workBuffer, render: workBuffer.render, renderColor: workBuffer.renderColor };
12272
+ const skip = () => undefined;
12273
+ workBuffer.render = skip;
12274
+ workBuffer.renderColor = skip;
12275
+ }
12276
+ restoreWorkBuffer() {
12277
+ if (!this.patched)
12278
+ return;
12279
+ const { workBuffer, render, renderColor } = this.patched;
12280
+ workBuffer.render = render;
12281
+ workBuffer.renderColor = renderColor;
12282
+ this.patched = null;
12283
+ }
12284
+ readChunk(bindingBase) {
12285
+ const format = this.require().format;
12286
+ // The format's read chunk reads the file's own space and returns sh0 colour + alpha;
12287
+ // the adapter below applies the file's model transform and evaluates its sh for this
12288
+ // camera. Its loose `uniform` and texture declarations (dequantisation constants, the
12289
+ // compressed format's chunk texture) are reflected by the engine into a second bind
12290
+ // group and set by name like any other parameter.
12291
+ // The engine writes its 32-bit float streams (the sog v2 codebook) as `texture_2d<uff>`,
12292
+ // an alias only its reflection of loose declarations resolves; explicit bindings need
12293
+ // the wgsl type, and the matching unfilterable sample type in bindFormats()
12294
+ const declarations = format
12295
+ .getComputeInputDeclarations(bindingBase)
12296
+ .replace(/texture_2d<uff>/g, 'texture_2d<f32>');
12297
+ return /* wgsl */ `
12298
+ #include "halfTypesCS"
12299
+ #include "gsplatEvalSHVS"
12300
+ ${declarations}
12301
+ ${format.getReadCode()}
12302
+
12303
+ var<private> srcWorldCenter: vec3f;
12304
+ var<private> srcColorCache: vec4f;
12305
+
12306
+ fn quatMulF(a: vec4f, b: vec4f) -> vec4f {
12307
+ return vec4f(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
12308
+ }
12309
+
12310
+ // v rotated by the inverse of q (x, y, z, w)
12311
+ fn quatRotateInvF(q: vec4f, v: vec3f) -> vec3f {
12312
+ let u = -q.xyz;
12313
+ return v + 2.0 * cross(u, cross(u, v) + q.w * v);
12314
+ }
12315
+
12316
+ fn srcCenter() -> vec3f {
12317
+ srcWorldCenter = (uniforms.model * vec4f(getCenter(), 1.0)).xyz;
12318
+ return srcWorldCenter;
12319
+ }
12320
+
12321
+ fn srcOpacity() -> f32 {
12322
+ srcColorCache = getColor();
12323
+ return srcColorCache.a;
12324
+ }
12325
+
12326
+ // the format returns (w, x, y, z); world = model * source
12327
+ fn srcRotation() -> vec4f {
12328
+ let q = quatMulF(uniforms.modelRotation, getRotation().yzwx);
12329
+ return q.wxyz;
12330
+ }
12331
+
12332
+ fn srcScale() -> vec3f {
12333
+ return uniforms.modelScale.xyz * getScale();
12334
+ }
12335
+
12336
+ fn srcColor() -> vec3f {
12337
+ var color = srcColorCache.rgb;
12338
+ #if SH_BANDS > 0
12339
+ // the view direction in the file's space; orthographic rays all run along the camera forward
12340
+ let view = uniforms.view;
12341
+ let orthoDir = vec3f(0.0, 0.0, -1.0) * mat3x3f(view[0].xyz, view[1].xyz, view[2].xyz);
12342
+ let viewDir = select(srcWorldCenter - uniforms.cameraPosition.xyz, orthoDir, uniforms.isOrtho != 0u);
12343
+ let dir = normalize(quatRotateInvF(uniforms.modelRotation, viewDir));
12344
+ var sh: array<half3, SH_COEFFS>;
12345
+ var shScale: f32;
12346
+ readSHData(&sh, &shScale);
12347
+ color += vec3f(evalSH(&sh, dir) * half(shScale));
12348
+ #endif
12349
+ return color;
12350
+ }
12351
+ `;
12352
+ }
12353
+ bindFormats() {
12354
+ const format = this.require().format;
12355
+ const entries = format.getComputeBindFormats();
12356
+ for (const entry of entries) {
12357
+ const stream = format.streams.find((s) => s.name === entry.name);
12358
+ if (stream?.format === PIXELFORMAT_RGBA32F)
12359
+ entry.sampleType = SAMPLETYPE_UNFILTERABLE_FLOAT;
12360
+ }
12361
+ return entries;
12362
+ }
12363
+ shaderIncludes() {
12364
+ // the read chunks include the engine's own gsplat chunks by name
12365
+ return new Map(ShaderChunks.get(this.device, SHADERLANGUAGE_WGSL));
12366
+ }
12367
+ shaderDefines() {
12368
+ const defines = new Map();
12369
+ this.require().configureMaterialDefines(defines);
12370
+ return defines;
12371
+ }
12372
+ chunkBase(node) {
12373
+ return node.sourceBase;
12374
+ }
12375
+ dispatchPlan(set) {
12376
+ // one run of the chunk table per file (the table is built file by file)
12377
+ const groups = [];
12378
+ let chunkBase = 0;
12379
+ const hash = this.resource?.format.hash;
12380
+ for (const file of set.files) {
12381
+ let chunkCount = 0;
12382
+ for (const node of file.nodes)
12383
+ chunkCount += Math.ceil(node.count / 256);
12384
+ if (chunkCount > 0 && file.resource.format.hash === hash) {
12385
+ groups.push({ fileIndex: file.fileIndex, chunkBase, chunkCount });
12386
+ }
12387
+ chunkBase += chunkCount;
12388
+ }
12389
+ return groups;
12390
+ }
12391
+ bind(compute, group, set) {
12392
+ const file = set.files[group.fileIndex];
12393
+ const { resource } = file;
12394
+ for (const [name, texture] of resource.streams.textures) {
12395
+ compute.setParameter(name, texture);
12396
+ }
12397
+ for (const [name, value] of resource.parameters) {
12398
+ compute.setParameter(name, value);
12399
+ }
12400
+ const constants = this.constants.get(file.fileIndex);
12401
+ compute.setParameter('model', file.modelMatrix.data);
12402
+ compute.setParameter('modelRotation', constants.rotation);
12403
+ compute.setParameter('modelScale', constants.scale);
12404
+ }
12405
+ textureSize(group) {
12406
+ return this.set?.files[group.fileIndex].resource.textureDimensions.x ?? 0;
12407
+ }
12408
+ gpuBytes() {
12409
+ // the file textures belong to the engine and are counted by app.stats.vram
12410
+ return 0;
12411
+ }
12412
+ shaderKey() {
12413
+ const resource = this.resource;
12414
+ if (!resource)
12415
+ return 'direct:';
12416
+ const defines = this.shaderDefines();
12417
+ return `direct:${resource.format.hash}:${[...defines].map(([k, v]) => `${k}=${v}`).join(',')}`;
12418
+ }
12419
+ destroy() {
12420
+ this.restoreWorkBuffer();
12421
+ this.resource = null;
12422
+ this.set = null;
12423
+ this.constants.clear();
12424
+ }
12425
+ require() {
12426
+ if (!this.resource)
12427
+ throw new Error('DirectSplatSource: update() has not run');
12428
+ return this.resource;
12429
+ }
12430
+ }
12431
+
12432
+ class WorkBufferSplatSource {
12433
+ kind = 'workbuffer';
12434
+ workBuffer = null;
12435
+ update(set, manager) {
12436
+ this.workBuffer = manager.world.workBuffer;
12437
+ }
12438
+ readChunk(bindingBase) {
12439
+ const format = this.require().format;
12440
+ // the engine's declarations bind one texture per stream from bindingBase and define
12441
+ // loadDataX(); its read code decodes them into getCenter() and friends, already in
12442
+ // world space with the sh colour baked for this camera
12443
+ return /* wgsl */ `
12444
+ ${format.getComputeInputDeclarations(bindingBase)}
12445
+ ${format.getReadCode()}
12446
+ fn srcCenter() -> vec3f { return getCenter(); }
12447
+ fn srcOpacity() -> f32 { return getOpacity(); }
12448
+ fn srcRotation() -> vec4f { return getRotation(); }
12449
+ fn srcScale() -> vec3f { return getScale(); }
12450
+ fn srcColor() -> vec3f { return getColor(); }
12451
+ `;
12452
+ }
12453
+ bindFormats() {
12454
+ return this.require().format.getComputeBindFormats();
12455
+ }
12456
+ shaderIncludes() {
12457
+ return undefined;
12458
+ }
12459
+ shaderDefines() {
12460
+ return undefined;
12461
+ }
12462
+ chunkBase(node) {
12463
+ return node.slotBase;
12464
+ }
12465
+ dispatchPlan(set, numChunks) {
12466
+ return [{ fileIndex: -1, chunkBase: 0, chunkCount: numChunks }];
12467
+ }
12468
+ bind(compute) {
12469
+ const workBuffer = this.require();
12470
+ for (const stream of workBuffer.format.streams) {
12471
+ compute.setParameter(stream.name, workBuffer.getTexture(stream.name));
12472
+ }
12473
+ }
12474
+ textureSize() {
12475
+ return this.require().textureSize;
12476
+ }
12477
+ gpuBytes() {
12478
+ // the work buffer belongs to the engine and is counted by app.stats.vram
12479
+ return 0;
12480
+ }
12481
+ shaderKey() {
12482
+ const workBuffer = this.workBuffer;
12483
+ return workBuffer ? `wb:${workBuffer.format.streams.map((s) => s.name).join(',')}` : 'wb:';
12484
+ }
12485
+ destroy() {
12486
+ this.workBuffer = null;
12487
+ }
12488
+ require() {
12489
+ if (!this.workBuffer)
12490
+ throw new Error('WorkBufferSplatSource: update() has not run');
12491
+ return this.workBuffer;
12492
+ }
12493
+ }
12494
+
12495
+ // The stochastic splat renderer (WebGPU, opt-in). The engine keeps LOD, streaming and the
12496
+ // work-buffer copy; this owns everything after: per frame it culls nodes on the cpu, projects
12497
+ // the resident splats in a compute pass into a dense cache, writes the indirect draw arguments,
12498
+ // rasterises the survivors as opaque depth-tested quads into its own colour + depth target
12499
+ // (StochasticSplats: keep a fragment with probability alpha, no sort), and composes that target
12500
+ // over the camera's target from a fullscreen quad in the World layer that also writes depth.
12501
+ //
12502
+ // Frame flow: the compute runs inside the engine's gsplat update (the `frame:ready` hook, before
12503
+ // the frame graph), the raster pass runs from `camera.beforePasses`, and the compose is an
12504
+ // ordinary mesh instance in the camera's forward pass. See docs/stochastic-renderer.md.
12505
+ const defaultVariant = () => ({
12506
+ spp: 'quad',
12507
+ compose: 'blend',
12508
+ cull: 'auto',
12509
+ order: 'bucket',
12510
+ contribution: 0,
12511
+ popless: 'on',
12512
+ taa: 'on',
12513
+ taaMax: 256,
12514
+ taaMoveMax: 16,
12515
+ taaClip: 1.25,
12516
+ taaFilter: 'cubic',
12517
+ taaReproj: 'sample',
12518
+ taaMotion: 4,
12519
+ taaDebug: 0,
12520
+ taaFlip: 0,
12521
+ colorMax: 8,
12522
+ units: 'engine'
12523
+ });
12524
+ const taaCount = (value) => Math.min(TAA_MAX_COUNT, Math.max(1, Math.round(value)));
12525
+ const parseVariant = (text) => {
12526
+ const variant = defaultVariant();
12527
+ for (const part of (text ?? '').split(',')) {
12528
+ const [key, value] = part.split(':').map((s) => s.trim());
12529
+ if (!key || value === undefined)
12530
+ continue;
12531
+ if (key === 'spp' && (value === '1' || value === 'quad'))
12532
+ variant.spp = value;
12533
+ if (key === 'compose' && (value === 'blend' || value === 'none' || value === 'depth'))
12534
+ variant.compose = value;
12535
+ if (key === 'popless' && (value === 'on' || value === 'off'))
12536
+ variant.popless = value;
12537
+ if (key === 'taa' && (value === 'on' || value === 'off'))
12538
+ variant.taa = value;
12539
+ if (key === 'taaMax' && Number.isFinite(Number(value)))
12540
+ variant.taaMax = taaCount(Number(value));
12541
+ if (key === 'taaMoveMax' && Number.isFinite(Number(value)))
12542
+ variant.taaMoveMax = taaCount(Number(value));
12543
+ if (key === 'taaDebug' && Number.isFinite(Number(value)))
12544
+ variant.taaDebug = Number(value);
12545
+ if (key === 'taaClip' && Number.isFinite(Number(value)))
12546
+ variant.taaClip = Math.max(0, Number(value));
12547
+ if (key === 'taaFilter' && (value === 'linear' || value === 'cubic'))
12548
+ variant.taaFilter = value;
12549
+ if (key === 'taaReproj' && (value === 'sample' || value === 'history'))
12550
+ variant.taaReproj = value;
12551
+ if (key === 'taaMotion' && Number.isFinite(Number(value)))
12552
+ variant.taaMotion = Math.max(0, Number(value));
12553
+ if (key === 'taaFlip' && Number.isFinite(Number(value)))
12554
+ variant.taaFlip = Number(value);
12555
+ if (key === 'colorMax' && Number.isFinite(Number(value)))
12556
+ variant.colorMax = Math.max(0, Number(value));
12557
+ if (key === 'units' && (value === 'px' || value === 'engine'))
12558
+ variant.units = value;
12559
+ if (key === 'cull' && (value === 'off' || value === 'l1' || value === 'l2' || value === 'auto')) {
12560
+ variant.cull = value;
12561
+ }
12562
+ if (key === 'order' && (value === 'append' || value === 'bucket'))
12563
+ variant.order = value;
12564
+ if (key === 'contribution' && Number.isFinite(Number(value)))
12565
+ variant.contribution = Math.max(0, Number(value));
12566
+ }
12567
+ return variant;
12568
+ };
12569
+ // Renders an explicit mesh-instance list into the renderer's own target (the raster and the
12570
+ // taa resolve). Not a layer: a layer in camera.layers is culled once and drawn by every pass
12571
+ // for the camera, so the scene pass would draw the splats into the camera target as well.
12572
+ class SplatRasterPass extends RenderPass {
12573
+ forward;
12574
+ camera;
12575
+ instances;
12576
+ constructor(device, forward, camera, instances, name = 'sse-splat-raster') {
12577
+ super(device);
12578
+ this.forward = forward;
12579
+ this.camera = camera;
12580
+ this.instances = instances;
12581
+ this.name = name;
12582
+ }
12583
+ execute() {
12584
+ this.forward.renderForwardLayer(this.camera.camera, this.renderTarget, null, undefined, SHADER_FORWARD, {
12585
+ meshInstances: this.instances
12586
+ });
12587
+ }
12588
+ }
12589
+ const createQuadMesh = (device, quads) => {
12590
+ const positions = new Float32Array(quads * 4 * 3);
12591
+ const indices = new Uint32Array(quads * 6);
12592
+ for (let i = 0; i < quads; ++i) {
12593
+ // z carries the quad's index within the instance
12594
+ positions.set([-1, -1, i, 1, -1, i, 1, 1, i, -1, 1, i], i * 12);
12595
+ const v = i * 4;
12596
+ indices.set([v, v + 1, v + 2, v, v + 2, v + 3], i * 6);
12597
+ }
12598
+ const mesh = new Mesh(device);
12599
+ mesh.setPositions(positions, 3);
12600
+ mesh.setIndices(indices);
12601
+ mesh.update(PRIMITIVE_TRIANGLES);
12602
+ return mesh;
12603
+ };
12604
+ const createFullscreenMesh = (device) => {
12605
+ const mesh = new Mesh(device);
12606
+ mesh.setPositions(new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), 2);
12607
+ mesh.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3]));
12608
+ mesh.update(PRIMITIVE_TRIANGLES);
12609
+ return mesh;
12610
+ };
12611
+ const tmpVec2 = new Vec2();
12612
+ class StochasticSplatRenderer {
12613
+ variant;
12614
+ source;
12615
+ app;
12616
+ device;
12617
+ camera;
12618
+ worldLayer;
12619
+ provider;
12620
+ unsubscribe;
12621
+ enabled = true;
12622
+ // the resident set and its chunk table
12623
+ set = null;
12624
+ numChunks = 0;
12625
+ chunkData = new Uint32Array(0);
12626
+ chunkBuffer = null;
12627
+ nodeVisibleData = new Uint32Array(0);
12628
+ nodeVisibleBuffer = null;
12629
+ cacheBuffer = null;
12630
+ cacheSlots = 0;
12631
+ counter;
12632
+ // compute
12633
+ // one projector shader per source and occlusion / order specialisation: the test's code
12634
+ // costs a little even when a uniform disables it, so a disabled or suspended cull runs
12635
+ // without it. One compute per shader and dispatch group, since a compute owns the uniform
12636
+ // buffer its dispatch reads and per-file sources dispatch once per file
12637
+ projectorShaders = new Map();
12638
+ projectorComputes = new Map();
12639
+ projectorBindGroupFormat = null;
12640
+ projectorSourceKey = '';
12641
+ args;
12642
+ argsBindGroupFormat;
12643
+ // order:bucket: bucket counts then offsets, the ordered slot list, and its two passes
12644
+ orderBuckets;
12645
+ orderedBuffer = null;
12646
+ orderScan;
12647
+ orderScatter;
12648
+ orderFormats = [];
12649
+ // the occlusion grid: farthest depth per 8 px block (level 1) and per 32 px block (level 2)
12650
+ occL1;
12651
+ occL2;
12652
+ occBlocks = { x1: 0, y1: 0, x2: 0, y2: 0 };
12653
+ reduceL1;
12654
+ reduceL2;
12655
+ reduceFormats = [];
12656
+ // the previous frame the grid and the reprojection describe; valid only when that frame
12657
+ // rendered to the same target at the same size from the same world state
12658
+ prevValid = false;
12659
+ prevViewProjection = new Mat4();
12660
+ prevView = new Mat4();
12661
+ prevProjection = new Mat4();
12662
+ prevClipZ = [0, 0, 0, 0];
12663
+ prevViewport = [0, 0];
12664
+ prevFocal = [0, 0];
12665
+ prevFlip = 1;
12666
+ prevWidth = 0;
12667
+ prevHeight = 0;
12668
+ prevVersion = -1;
12669
+ // the allocations resident when the previous frame drew, and whether any of them has gone
12670
+ // since: only a removed splat can make the previous depth wrong (it may have hidden what is
12671
+ // now behind it), so arrivals leave the cull on while a scene streams in
12672
+ residentAllocIds = new Set();
12673
+ nodesRemoved = false;
12674
+ prevOrtho = false;
12675
+ /** Whether the last frame ran the occlusion cull, for the debug panel and the harness. */
12676
+ culling = false;
12677
+ /** Whether cull:auto currently has the test switched off for culling too little. */
12678
+ get cullSuspended() {
12679
+ return this.variant.cull === 'auto' && (!this.cullActive || this.cullSuspendedFrames > 0);
12680
+ }
12681
+ // cull:auto bookkeeping. The last decision holds while a readback is in flight: while the
12682
+ // test is active every culled frame's counts are read back and a poor one suspends it;
12683
+ // while suspended the frames count down, then one probe frame runs the test and the rest
12684
+ // wait for its counts
12685
+ cullActive = true;
12686
+ cullSuspendedFrames = 0;
12687
+ cullStatsPending = false;
12688
+ /** Frames the test stays off after culling too little (cull:auto). */
12689
+ /**
12690
+ * Whether the projected cache for `splats` resident splats fits one storage binding on this
12691
+ * device. The cache reserves 25% over the resident count; adapters differ in the limit
12692
+ * (128 MiB is the WebGPU default), so a viewer checks before opting in.
12693
+ */
12694
+ static cacheFits(device, splats) {
12695
+ const limit = device.wgpu?.limits
12696
+ ?.maxStorageBufferBindingSize;
12697
+ return !limit || Math.ceil(splats * 1.25) * CACHE_WORDS * 4 <= limit;
12698
+ }
12699
+ static CULL_SUSPEND_FRAMES = 60;
12700
+ /** The culled fraction below which cull:auto suspends the test. */
12701
+ static CULL_MIN_FRACTION = 0.08;
12702
+ /**
12703
+ * Let a capture (query) frame cull against the previous on-screen frame when it renders at
12704
+ * the same size. Off by default: a query frame is not culled, since its cull thins what a
12705
+ * pick or a thumbnail should see. The harness turns it on to photograph culled frames.
12706
+ */
12707
+ allowQueryCull = false;
12708
+ // raster
12709
+ colorTexture;
12710
+ depthTexture;
12711
+ target;
12712
+ rasterMesh;
12713
+ rasterMaterial;
12714
+ rasterInstance;
12715
+ rasterPass;
12716
+ // taa: ping-pong history (premultiplied colour + coverage as unorm16, and the depth mean and
12717
+ // sample count packed in 32 bits; shaders/taa.ts), resolved by a fullscreen pass after the
12718
+ // raster. Sized with the target on the first accumulating frame, and shrunk back while taa is off
12719
+ taaColor = [];
12720
+ taaInfo = [];
12721
+ taaTargets = [];
12722
+ taaWrite = 0;
12723
+ taaMesh;
12724
+ taaMaterial;
12725
+ taaInstance;
12726
+ taaPass;
12727
+ // whether the history holds the previous on-screen frame at the current size
12728
+ taaHistoryValid = false;
12729
+ // the previous taa frame's matrices as the pass reads them, and this frame's, copied over
12730
+ // at the start of the next frame: the material holds the data arrays by reference and
12731
+ // uploads them when it draws, after this hook has run
12732
+ taaPrevViewProjection = new Mat4();
12733
+ taaPrevView = new Mat4();
12734
+ taaLastViewProjection = new Mat4();
12735
+ taaLastView = new Mat4();
12736
+ taaWidth = 0;
12737
+ taaHeight = 0;
12738
+ // the camera's world transform, for the accumulation's reprojection
12739
+ cameraWorld = new Mat4();
12740
+ // frames since the camera or the scene last changed, for converging at rest
12741
+ restFrames = 0;
12742
+ /** The frame the depth texture holds, null while it holds a capture's or nothing. */
12743
+ depthFrame = null;
12744
+ depthFrameCount = 0;
12745
+ depthFrameCamera = createPickCameraSnapshot();
12746
+ // a frame requested from inside the render: the engine clears app.renderNextFrame right
12747
+ // after render(), so the request is applied on frameend instead
12748
+ frameWanted = false;
12749
+ onFrameEnd = () => {
12750
+ if (this.frameWanted) {
12751
+ this.frameWanted = false;
12752
+ this.app.renderNextFrame = true;
12753
+ }
12754
+ };
12755
+ frameIndex = 0;
12756
+ // the seed the harness sets; the frame index replaces it while taa accumulates
12757
+ userSeed = 0;
12758
+ /** Whether the last frame ran the temporal accumulation, for the debug panel. */
12759
+ taaActive = false;
12760
+ /**
12761
+ * Let a capture (query) frame at the on-screen size run the accumulation over the on-screen
12762
+ * history, so the harness can photograph converged and moving frames. Off by default.
12763
+ */
12764
+ allowQueryTaa = false;
12765
+ // compose
12766
+ composeMesh;
12767
+ composeMaterial;
12768
+ composeInstance;
12769
+ frustum = new Frustum();
12770
+ sphere = new BoundingSphere();
12771
+ shaderProjection = new Mat4();
12772
+ viewProjection = new Mat4();
12773
+ frameSeed = 0;
12774
+ ready = false;
12775
+ /** Byte sizes of the buffers this renderer owns, for the bench harness and the debug panel. */
12776
+ /** The renderer's depth texture: the nearest surviving sample per pixel of `depthFrame`. */
12777
+ get frameDepthTexture() {
12778
+ return this.depthTexture;
12779
+ }
12780
+ get gpuBytes() {
12781
+ const buffers = [
12782
+ this.chunkBuffer,
12783
+ this.nodeVisibleBuffer,
12784
+ this.cacheBuffer,
12785
+ this.orderedBuffer,
12786
+ this.counter,
12787
+ this.orderBuckets,
12788
+ this.occL1,
12789
+ this.occL2
12790
+ ];
12791
+ let bytes = 0;
12792
+ for (const buffer of buffers)
12793
+ bytes += buffer?.byteSize ?? 0;
12794
+ bytes += this.colorTexture.gpuSize + this.depthTexture.gpuSize;
12795
+ for (const texture of [...this.taaColor, ...this.taaInfo])
12796
+ bytes += texture.gpuSize;
12797
+ return bytes + this.source.gpuBytes();
12798
+ }
12799
+ /**
12800
+ * The seed mixed into every coverage hash. 0 makes a still camera reproduce its frame;
12801
+ * the harness varies it to measure the sampling noise floor, and TAA will animate it.
12802
+ */
12803
+ get seed() {
12804
+ return this.frameSeed;
12805
+ }
12806
+ set seed(value) {
12807
+ this.userSeed = value >>> 0;
12808
+ this.frameSeed = this.userSeed;
12809
+ this.app.renderNextFrame = true;
12810
+ }
12811
+ /** The last projected frame's survivor count and occlusion-culled count, read back from the gpu. */
12812
+ async readStats() {
12813
+ // without a typed array the engine hands back bytes
12814
+ const data = new Uint32Array(2);
12815
+ await this.counter.read(0, 8, data, true);
12816
+ return { survivors: data[0], occluded: data[1] };
12817
+ }
12818
+ // reduce the previous frame's depth into the two grid levels
12819
+ reduceDepth(width, height) {
12820
+ const { device } = this;
12821
+ const x1 = Math.ceil(width / 8);
12822
+ const y1 = Math.ceil(height / 8);
12823
+ const x2 = Math.ceil(x1 / 4);
12824
+ const y2 = Math.ceil(y1 / 4);
12825
+ if (this.occBlocks.x1 !== x1 || this.occBlocks.y1 !== y1) {
12826
+ this.occL1.destroy();
12827
+ this.occL2.destroy();
12828
+ this.occL1 = new StorageBuffer(device, x1 * y1 * 4, BUFFERUSAGE_COPY_DST);
12829
+ this.occL2 = new StorageBuffer(device, x2 * y2 * 4, BUFFERUSAGE_COPY_DST);
12830
+ this.occBlocks = { x1, y1, x2, y2 };
12831
+ }
12832
+ const l1 = this.reduceL1;
12833
+ l1.setParameter('prevDepth', this.depthTexture);
12834
+ l1.setParameter('blockMax', this.occL1);
12835
+ l1.setParameter('width', width);
12836
+ l1.setParameter('height', height);
12837
+ l1.setParameter('blocksX', x1);
12838
+ l1.setParameter('blocksY', y1);
12839
+ l1.setupDispatch(x1, y1, 1);
12840
+ const l2 = this.reduceL2;
12841
+ l2.setParameter('level1', this.occL1);
12842
+ l2.setParameter('level2', this.occL2);
12843
+ l2.setParameter('blocksX1', x1);
12844
+ l2.setParameter('blocksY1', y1);
12845
+ l2.setParameter('blocksX2', x2);
12846
+ l2.setParameter('blocksY2', y2);
12847
+ Compute.calcDispatchSize(Math.ceil((x2 * y2) / 64), tmpVec2);
12848
+ l2.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
12849
+ device.computeDispatch([l1], 'sse-splat-reduce1');
12850
+ device.computeDispatch([l2], 'sse-splat-reduce2');
12851
+ }
12852
+ /** Survivors of the last frame's projection are only known to the gpu; this is the resident count. */
12853
+ activeSplats = 0;
12854
+ constructor(app, camera, worldLayer, options = {}) {
12855
+ this.app = app;
12856
+ this.device = app.graphicsDevice;
12857
+ this.camera = camera;
12858
+ this.worldLayer = worldLayer;
12859
+ this.variant = parseVariant(options.variant);
12860
+ const { device } = this;
12861
+ if (options.source === 'direct') {
12862
+ this.source = new DirectSplatSource(device);
12863
+ }
12864
+ else {
12865
+ if (options.source && options.source !== 'workbuffer') {
12866
+ console.warn(`StochasticSplatRenderer: splat source '${options.source}' is not implemented yet, using the work buffer`);
12867
+ }
12868
+ this.source = new WorkBufferSplatSource();
12869
+ }
12870
+ this.counter = new StorageBuffer(device, 16, BUFFERUSAGE_COPY_DST | BUFFERUSAGE_COPY_SRC);
12871
+ // indirect draw arguments
12872
+ this.argsBindGroupFormat = new BindGroupFormat(device, [
12873
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
12874
+ new BindStorageBufferFormat('indirectDrawArgs', SHADERSTAGE_COMPUTE),
12875
+ new BindStorageBufferFormat('indirectDispatchArgs', SHADERSTAGE_COMPUTE),
12876
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
12877
+ ]);
12878
+ this.args = new Compute(device, new Shader(device, {
12879
+ name: 'sse-splat-args',
12880
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12881
+ cshader: argsWGSL,
12882
+ computeUniformBufferFormats: {
12883
+ uniforms: new UniformBufferFormat(device, [
12884
+ new UniformFormat('drawSlot', UNIFORMTYPE_UINT),
12885
+ new UniformFormat('indexCount', UNIFORMTYPE_UINT),
12886
+ new UniformFormat('quadsPerInstance', UNIFORMTYPE_UINT),
12887
+ new UniformFormat('dispatchSlot', UNIFORMTYPE_UINT),
12888
+ new UniformFormat('scatterWorkgroupSize', UNIFORMTYPE_UINT)
12889
+ ])
12890
+ },
12891
+ computeBindGroupFormat: this.argsBindGroupFormat
12892
+ }), 'sse-splat-args');
12893
+ // the ordering passes
12894
+ this.orderBuckets = new StorageBuffer(device, 2 * ORDER_BUCKETS * 4, BUFFERUSAGE_COPY_DST);
12895
+ const scanFormat = new BindGroupFormat(device, [new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)]);
12896
+ const scatterFormat = new BindGroupFormat(device, [
12897
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
12898
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE, true),
12899
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE),
12900
+ new BindStorageBufferFormat('ordered', SHADERSTAGE_COMPUTE)
12901
+ ]);
12902
+ this.orderFormats = [scanFormat, scatterFormat];
12903
+ this.orderScan = new Compute(device, new Shader(device, {
12904
+ name: 'sse-splat-order-scan',
12905
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12906
+ cshader: orderScanWGSL,
12907
+ computeBindGroupFormat: scanFormat
12908
+ }), 'sse-splat-order-scan');
12909
+ this.orderScatter = new Compute(device, new Shader(device, {
12910
+ name: 'sse-splat-order-scatter',
12911
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12912
+ cshader: orderScatterWGSL,
12913
+ computeBindGroupFormat: scatterFormat
12914
+ }), 'sse-splat-order-scatter');
12915
+ // the occlusion grid and its two reduce passes
12916
+ this.occL1 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
12917
+ this.occL2 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
12918
+ const reduceL1Format = new BindGroupFormat(device, [
12919
+ new BindTextureFormat('prevDepth', SHADERSTAGE_COMPUTE, TEXTUREDIMENSION_2D, SAMPLETYPE_DEPTH, false),
12920
+ new BindStorageBufferFormat('blockMax', SHADERSTAGE_COMPUTE),
12921
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
12922
+ ]);
12923
+ const reduceL2Format = new BindGroupFormat(device, [
12924
+ new BindStorageBufferFormat('level1', SHADERSTAGE_COMPUTE, true),
12925
+ new BindStorageBufferFormat('level2', SHADERSTAGE_COMPUTE),
12926
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
12927
+ ]);
12928
+ this.reduceFormats = [reduceL1Format, reduceL2Format];
12929
+ this.reduceL1 = new Compute(device, new Shader(device, {
12930
+ name: 'sse-splat-reduce1',
12931
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12932
+ cshader: reduceL1WGSL,
12933
+ computeUniformBufferFormats: {
12934
+ uniforms: new UniformBufferFormat(device, [
12935
+ new UniformFormat('width', UNIFORMTYPE_UINT),
12936
+ new UniformFormat('height', UNIFORMTYPE_UINT),
12937
+ new UniformFormat('blocksX', UNIFORMTYPE_UINT),
12938
+ new UniformFormat('blocksY', UNIFORMTYPE_UINT)
12939
+ ])
12940
+ },
12941
+ computeBindGroupFormat: reduceL1Format
12942
+ }), 'sse-splat-reduce1');
12943
+ this.reduceL2 = new Compute(device, new Shader(device, {
12944
+ name: 'sse-splat-reduce2',
12945
+ shaderLanguage: SHADERLANGUAGE_WGSL,
12946
+ cshader: reduceL2WGSL,
12947
+ computeUniformBufferFormats: {
12948
+ uniforms: new UniformBufferFormat(device, [
12949
+ new UniformFormat('blocksX1', UNIFORMTYPE_UINT),
12950
+ new UniformFormat('blocksY1', UNIFORMTYPE_UINT),
12951
+ new UniformFormat('blocksX2', UNIFORMTYPE_UINT),
12952
+ new UniformFormat('blocksY2', UNIFORMTYPE_UINT)
12953
+ ])
12954
+ },
12955
+ computeBindGroupFormat: reduceL2Format
12956
+ }), 'sse-splat-reduce2');
12957
+ // the raster target: colour, and a depth texture the compose, the occlusion cull and
12958
+ // (later) the picker read
12959
+ this.colorTexture = new Texture(device, {
12960
+ name: 'sse-splat-color',
12961
+ width: 4,
12962
+ height: 4,
12963
+ format: PIXELFORMAT_RGBA8,
12964
+ mipmaps: false,
12965
+ minFilter: FILTER_LINEAR,
12966
+ magFilter: FILTER_LINEAR,
12967
+ addressU: ADDRESS_CLAMP_TO_EDGE,
12968
+ addressV: ADDRESS_CLAMP_TO_EDGE
12969
+ });
12970
+ this.depthTexture = new Texture(device, {
12971
+ name: 'sse-splat-depth',
12972
+ width: 4,
12973
+ height: 4,
12974
+ format: PIXELFORMAT_DEPTH,
12975
+ mipmaps: false,
12976
+ addressU: ADDRESS_CLAMP_TO_EDGE,
12977
+ addressV: ADDRESS_CLAMP_TO_EDGE
12978
+ });
12979
+ this.target = new RenderTarget({
12980
+ name: 'sse-splat-target',
12981
+ colorBuffer: this.colorTexture,
12982
+ depthBuffer: this.depthTexture,
12983
+ samples: 1
12984
+ });
12985
+ this.rasterMesh = createQuadMesh(device, QUADS_PER_INSTANCE);
12986
+ this.rasterMaterial = new ShaderMaterial({
12987
+ uniqueName: 'sse-splat-raster',
12988
+ vertexWGSL: rasterVertexWGSL,
12989
+ fragmentWGSL: rasterFragmentWGSL,
12990
+ attributes: { vertex_position: SEMANTIC_POSITION }
12991
+ });
12992
+ this.rasterMaterial.blendType = BLEND_NONE;
12993
+ this.rasterMaterial.depthWrite = true;
12994
+ this.rasterMaterial.depthTest = true;
12995
+ this.rasterMaterial.cull = CULLFACE_NONE;
12996
+ // the forward renderer reads the instance's node for its cull setup and world transform
12997
+ this.rasterInstance = new MeshInstance(this.rasterMesh, this.rasterMaterial, new GraphNode('sse-splat-raster'));
12998
+ this.rasterInstance.cull = false;
12999
+ this.rasterInstance.castShadow = false;
13000
+ this.rasterInstance.receiveShadow = false;
13001
+ this.rasterPass = new SplatRasterPass(device, app.renderer, camera, [
13002
+ this.rasterInstance
13003
+ ]);
13004
+ this.rasterPass.init(this.target);
13005
+ this.rasterPass.setClearColor(new Color(0, 0, 0, 0));
13006
+ this.rasterPass.setClearDepth(1);
13007
+ // nothing to draw, and no buffers bound, until the first populated frame
13008
+ this.rasterPass.enabled = false;
13009
+ // the taa resolve: a fullscreen pass from the raster target and the previous history
13010
+ // into the other history, sized with the target on its first frame
13011
+ for (let i = 0; i < 2; i++) {
13012
+ this.taaColor.push(new Texture(device, {
13013
+ name: `sse-splat-taa-color-${i}`,
13014
+ width: 4,
13015
+ height: 4,
13016
+ format: PIXELFORMAT_RGBA16U,
13017
+ mipmaps: false,
13018
+ minFilter: FILTER_NEAREST,
13019
+ magFilter: FILTER_NEAREST,
13020
+ addressU: ADDRESS_CLAMP_TO_EDGE,
13021
+ addressV: ADDRESS_CLAMP_TO_EDGE
13022
+ }));
13023
+ this.taaInfo.push(new Texture(device, {
13024
+ name: `sse-splat-taa-info-${i}`,
13025
+ width: 4,
13026
+ height: 4,
13027
+ format: PIXELFORMAT_R32U,
13028
+ mipmaps: false,
13029
+ minFilter: FILTER_NEAREST,
13030
+ magFilter: FILTER_NEAREST,
13031
+ addressU: ADDRESS_CLAMP_TO_EDGE,
13032
+ addressV: ADDRESS_CLAMP_TO_EDGE
13033
+ }));
13034
+ this.taaTargets.push(new RenderTarget({
13035
+ name: `sse-splat-taa-${i}`,
13036
+ colorBuffers: [this.taaColor[i], this.taaInfo[i]],
13037
+ depth: false,
13038
+ samples: 1
13039
+ }));
13040
+ }
13041
+ this.taaMesh = createFullscreenMesh(device);
13042
+ this.taaMaterial = new ShaderMaterial({
13043
+ uniqueName: 'sse-splat-taa',
13044
+ vertexWGSL: taaVertexWGSL,
13045
+ fragmentWGSL: taaFragmentWGSL,
13046
+ attributes: { vertex_position: SEMANTIC_POSITION },
13047
+ fragmentOutputTypes: ['uvec4', 'uint']
13048
+ });
13049
+ this.taaMaterial.blendType = BLEND_NONE;
13050
+ this.taaMaterial.depthWrite = false;
13051
+ this.taaMaterial.depthTest = false;
13052
+ this.taaMaterial.cull = CULLFACE_NONE;
13053
+ this.taaInstance = new MeshInstance(this.taaMesh, this.taaMaterial, new GraphNode('sse-splat-taa'));
13054
+ this.taaInstance.cull = false;
13055
+ this.taaInstance.castShadow = false;
13056
+ this.taaInstance.receiveShadow = false;
13057
+ this.taaPass = new SplatRasterPass(device, app.renderer, camera, [this.taaInstance], 'sse-splat-taa');
13058
+ this.taaPass.init(this.taaTargets[0]);
13059
+ this.taaPass.enabled = false;
13060
+ // the compose quad, blended over the skybox and opaque meshes with the splat depth
13061
+ this.composeMesh = createFullscreenMesh(device);
13062
+ this.composeMaterial = new ShaderMaterial({
13063
+ uniqueName: 'sse-splat-compose',
13064
+ vertexWGSL: composeVertexWGSL,
13065
+ fragmentWGSL: composeFragmentWGSL,
13066
+ attributes: { vertex_position: SEMANTIC_POSITION }
13067
+ });
13068
+ this.composeMaterial.blendType = BLEND_PREMULTIPLIED;
13069
+ this.composeMaterial.depthWrite = true;
13070
+ this.composeMaterial.depthTest = true;
13071
+ this.composeMaterial.cull = CULLFACE_NONE;
13072
+ this.composeMaterial.setParameter('splatColor', this.colorTexture);
13073
+ this.composeMaterial.setParameter('splatDepth', this.depthTexture);
13074
+ // always bound, even while taa is off: a declared texture without a value makes the
13075
+ // engine create and upload a placeholder inside the forward pass, which submits the
13076
+ // command buffer mid-pass on WebGPU
13077
+ this.composeMaterial.setParameter('taaColor', this.taaColor[0]);
13078
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[0]);
13079
+ this.composeInstance = new MeshInstance(this.composeMesh, this.composeMaterial, new GraphNode('sse-splat-compose'));
13080
+ this.composeInstance.cull = false;
13081
+ this.composeInstance.castShadow = false;
13082
+ this.composeInstance.receiveShadow = false;
13083
+ // the picker pass draws every pickable instance of the layer into a target without a
13084
+ // depth attachment; this shader writes frag_depth, which makes that pipeline invalid
13085
+ // and drops the whole submit, the frame's command buffer included
13086
+ this.composeInstance.pick = false;
13087
+ // first among the transparents, whichever way the layer sorts them
13088
+ this.composeInstance.drawOrder = -1e3;
13089
+ this.composeInstance.calculateSortDistance = () => Number.MAX_VALUE;
13090
+ this.applyVariant();
13091
+ this.provider = new EngineResidentSetProvider(app, camera, worldLayer);
13092
+ this.unsubscribe = this.provider.onFrame((set, changed, manager) => this.frame(set, changed, manager));
13093
+ app.on('frameend', this.onFrameEnd);
13094
+ this.attach();
13095
+ }
13096
+ /** Switch the renderer off and hand the splats back to the engine's renderer (XR), or on again. */
13097
+ setEnabled(value) {
13098
+ if (this.enabled === value)
13099
+ return;
13100
+ this.enabled = value;
13101
+ if (value) {
13102
+ this.attach();
13103
+ }
13104
+ else {
13105
+ this.detach();
13106
+ }
13107
+ this.app.renderNextFrame = true;
13108
+ }
13109
+ /** Replace the experiment switches from a `key:value,key:value` string (unset keys reset). */
13110
+ setVariant(text) {
13111
+ Object.assign(this.variant, parseVariant(text));
13112
+ // the cull decides afresh under new switches
13113
+ this.cullActive = true;
13114
+ this.cullSuspendedFrames = 0;
13115
+ this.applyVariant();
13116
+ }
13117
+ /**
13118
+ * Drop the temporal history; the next frame starts accumulating from its own sample. The
13119
+ * coverage seeds restart too, so a variant accumulates the same samples every time (the
13120
+ * harness compares builds image for image).
13121
+ */
13122
+ resetHistory() {
13123
+ this.taaHistoryValid = false;
13124
+ this.restFrames = 0;
13125
+ this.frameIndex = 0;
13126
+ }
13127
+ /** Re-read {@link variant} after a field changed. */
13128
+ applyVariant() {
13129
+ // a switch changes what the frames hold; an old history would leak into the new ones
13130
+ this.resetHistory();
13131
+ const quad = this.variant.spp === 'quad';
13132
+ this.rasterMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
13133
+ this.rasterMaterial.setDefine('SSE_ORDERED', this.variant.order === 'bucket' ? '' : undefined);
13134
+ this.rasterMaterial.setDefine('SSE_POPLESS', this.variant.popless === 'on' ? '' : undefined);
13135
+ this.composeMaterial.setDefine('SSE_SHOW_DEPTH', this.variant.compose === 'depth' ? '' : undefined);
13136
+ this.composeMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
13137
+ this.rasterMaterial.update();
13138
+ this.composeMaterial.update();
13139
+ this.setReady(this.ready);
13140
+ this.app.renderNextFrame = true;
13141
+ }
13142
+ // the raster pass and the compose only run once a frame has bound the buffers they read
13143
+ setReady(value) {
13144
+ this.ready = value;
13145
+ this.rasterPass.enabled = value;
13146
+ this.composeInstance.visible = value && this.variant.compose !== 'none';
13147
+ }
13148
+ attach() {
13149
+ const passes = this.camera.camera.beforePasses;
13150
+ if (!passes.includes(this.rasterPass))
13151
+ passes.push(this.rasterPass);
13152
+ if (!passes.includes(this.taaPass))
13153
+ passes.push(this.taaPass);
13154
+ this.worldLayer.addMeshInstances([this.composeInstance]);
13155
+ this.provider.setActive(true);
13156
+ }
13157
+ detach() {
13158
+ const passes = this.camera.camera.beforePasses;
13159
+ for (const pass of [this.rasterPass, this.taaPass]) {
13160
+ const index = passes.indexOf(pass);
13161
+ if (index >= 0)
13162
+ passes.splice(index, 1);
13163
+ }
13164
+ this.resetHistory();
13165
+ this.depthFrame = null;
13166
+ this.worldLayer.removeMeshInstances([this.composeInstance]);
13167
+ this.provider.setActive(false);
13168
+ }
13169
+ frame(set, changed, manager) {
13170
+ if (!this.enabled)
13171
+ return;
13172
+ const { device, camera } = this;
13173
+ const cam = camera.camera;
13174
+ this.nodesRemoved = false;
13175
+ if (changed || this.set !== set) {
13176
+ const ids = new Set(set.nodes.map((node) => node.allocId));
13177
+ for (const id of this.residentAllocIds) {
13178
+ if (!ids.has(id)) {
13179
+ this.nodesRemoved = true;
13180
+ break;
13181
+ }
13182
+ }
13183
+ this.residentAllocIds = ids;
13184
+ this.source.update(set, manager);
13185
+ this.rebuildChunkTable(set);
13186
+ this.ensureCache(set.activeSplats);
13187
+ this.activeSplats = set.activeSplats;
13188
+ this.pruneProjectorComputes(set);
13189
+ // recorded last, so a rebuild that throws is retried next frame
13190
+ this.set = set;
13191
+ }
13192
+ if (this.numChunks === 0) {
13193
+ // nothing resident: draw nothing
13194
+ this.setReady(false);
13195
+ return;
13196
+ }
13197
+ // the target follows whatever the camera renders into this frame: the backbuffer, or a
13198
+ // capture's render target at another size
13199
+ const rt = camera.renderTarget;
13200
+ const width = rt ? rt.width : device.width;
13201
+ const height = rt ? rt.height : device.height;
13202
+ if (this.target.width !== width || this.target.height !== height) {
13203
+ this.target.resize(width, height);
13204
+ }
13205
+ const view = cam.viewMatrix;
13206
+ const projection = cam.projectionMatrix;
13207
+ const isOrtho = cam.projection === PROJECTION_ORTHOGRAPHIC;
13208
+ // the clip z the raster shader reconstructs must match the engine's WebGPU depth range
13209
+ const shaderProjection = Camera$1.applyShaderProjectionTransform(projection, this.shaderProjection, false, true);
13210
+ this.viewProjection.mul2(shaderProjection, view);
13211
+ // The splats' own depth: clip z = a * depth + b (over w = depth for a perspective
13212
+ // camera). The camera's far plane is fitted to the scene bound, which can leave a sky
13213
+ // outside it, and splats clamped there share one depth and lose their order; so a
13214
+ // perspective raster puts its far plane at infinity (z = 1 - near / depth), with the same
13215
+ // near plane and, near where precision matters, the same resolution. The compose converts
13216
+ // back to the camera's depth where the splats meet the rest of the scene. An orthographic
13217
+ // camera keeps its own mapping: a linear depth has no far plane at infinity.
13218
+ const cameraClipZ = [-shaderProjection.data[10], shaderProjection.data[14]];
13219
+ const clipZ = isOrtho ? cameraClipZ : [1, cameraClipZ[1] / cameraClipZ[0]];
13220
+ const clipZParams = [clipZ[0], clipZ[1], isOrtho ? 1 : 0, 0];
13221
+ this.cullNodes(set, this.viewProjection);
13222
+ const focal = [Math.abs(projection.data[0]) * width * 0.5, Math.abs(projection.data[5]) * height * 0.5];
13223
+ const gsplat = this.app.scene.gsplat;
13224
+ // the moving-camera contribution cull: a raised threshold while the view changes, then
13225
+ // one more frame at the scene's threshold once it has stopped
13226
+ const moved = this.viewMoved(view, projection);
13227
+ const raised = moved && this.variant.contribution > 0;
13228
+ const minContribution = raised
13229
+ ? Math.max(gsplat.minContribution, this.variant.contribution)
13230
+ : gsplat.minContribution;
13231
+ if (raised)
13232
+ this.frameWanted = true;
13233
+ // Temporal accumulation runs on on-screen frames (and, for the harness, on a capture at
13234
+ // the same size); the history is only trusted when it holds the previous such frame at
13235
+ // this size. While it runs the coverage seed changes every frame, and a resting camera
13236
+ // keeps requesting frames until the history has filled its cap
13237
+ const isQuery = !!rt;
13238
+ const taaOn = this.variant.taa === 'on' &&
13239
+ (!isQuery || (this.allowQueryTaa && width === this.taaWidth && height === this.taaHeight));
13240
+ if (taaOn) {
13241
+ if (this.taaWidth !== width || this.taaHeight !== height) {
13242
+ this.resizeHistory(width, height);
13243
+ this.taaWidth = width;
13244
+ this.taaHeight = height;
13245
+ this.taaHistoryValid = false;
13246
+ this.restFrames = 0;
13247
+ }
13248
+ this.frameSeed = this.frameIndex++ >>> 0;
13249
+ if (moved || changed)
13250
+ this.restFrames = 0;
13251
+ else
13252
+ this.restFrames++;
13253
+ if (this.restFrames < this.variant.taaMax + 2)
13254
+ this.frameWanted = true;
13255
+ }
13256
+ else {
13257
+ this.frameSeed = this.userSeed;
13258
+ // a capture at another size does not accumulate; the next on-screen frame starts over
13259
+ this.taaHistoryValid = false;
13260
+ this.restFrames = 0;
13261
+ // switched off: the history goes back to its placeholder size until it is wanted
13262
+ if (this.variant.taa === 'off' && this.taaWidth !== 0) {
13263
+ this.resizeHistory(4, 4);
13264
+ this.taaWidth = 0;
13265
+ this.taaHeight = 0;
13266
+ }
13267
+ }
13268
+ this.taaActive = taaOn;
13269
+ // The occlusion cull reads the depth texture as the previous frame left it, so it needs
13270
+ // that frame to have drawn to this target at this size (a resize loses the texture, a
13271
+ // capture draws elsewhere), with no splat removed since (its depth would hide what is
13272
+ // now behind it; arrivals are safe) and the same projection type. A capture frame is
13273
+ // never culled and never becomes the previous frame.
13274
+ // a new world state can change what is occluded: try the test again
13275
+ if (this.prevVersion !== set.version) {
13276
+ this.cullSuspendedFrames = 0;
13277
+ this.cullActive = true;
13278
+ }
13279
+ const cullMode = this.variant.cull;
13280
+ let wanted = cullMode !== 'off';
13281
+ let probe = false;
13282
+ if (cullMode === 'auto' && !isQuery) {
13283
+ if (this.cullSuspendedFrames > 0) {
13284
+ // a moving camera changes what is occluded, so the probe comes sooner
13285
+ const moved = this.viewMoved(view, projection);
13286
+ this.cullSuspendedFrames = Math.max(0, this.cullSuspendedFrames - (moved ? 4 : 1));
13287
+ wanted = false;
13288
+ }
13289
+ else if (!this.cullActive) {
13290
+ // suspended and due: one probe frame, then wait for its counts
13291
+ probe = !this.cullStatsPending;
13292
+ wanted = probe;
13293
+ }
13294
+ }
13295
+ const culling = wanted &&
13296
+ (!isQuery || this.allowQueryCull) &&
13297
+ this.prevValid &&
13298
+ this.prevWidth === width &&
13299
+ this.prevHeight === height &&
13300
+ !this.nodesRemoved &&
13301
+ this.prevOrtho === isOrtho;
13302
+ this.culling = culling;
13303
+ if (culling) {
13304
+ this.reduceDepth(width, height);
13305
+ }
13306
+ this.counter.clear();
13307
+ const ordered = this.variant.order === 'bucket';
13308
+ if (ordered)
13309
+ this.orderBuckets.clear();
13310
+ // the order key spans the fitted clip range, log-spaced
13311
+ const logNear = Math.log(Math.max(cam.nearClip, 1e-6));
13312
+ const invLogRange = 1 / Math.max(Math.log(Math.max(cam.farClip, 1e-6)) - logNear, 1e-6);
13313
+ // the view depths where the raster's clip z reaches 0 and its far clamp (FAR_CLIP_Z), from
13314
+ // clip z = a * depth + b (over w = depth for a perspective camera)
13315
+ const [clipA, clipB] = clipZ;
13316
+ const depthNear = -clipB / clipA;
13317
+ const depthFar = isOrtho ? (FAR_CLIP_Z - clipB) / clipA : clipB / (FAR_CLIP_Z - clipA);
13318
+ const cameraPosition = camera.entity.getPosition();
13319
+ const groups = this.source.dispatchPlan(set, this.numChunks);
13320
+ for (const group of groups) {
13321
+ // a file with no node in the frustum has nothing to dispatch
13322
+ if (group.fileIndex >= 0 && !this.anyNodeVisible(set.files[group.fileIndex].nodes))
13323
+ continue;
13324
+ const projector = this.ensureProjector(culling, ordered, group);
13325
+ this.source.bind(projector, group, set);
13326
+ projector.setParameter('chunks', this.chunkBuffer);
13327
+ projector.setParameter('nodeVisible', this.nodeVisibleBuffer);
13328
+ projector.setParameter('cache', this.cacheBuffer);
13329
+ projector.setParameter('counter', this.counter);
13330
+ projector.setParameter('occL1', this.occL1);
13331
+ projector.setParameter('occL2', this.occL2);
13332
+ projector.setParameter('buckets', this.orderBuckets);
13333
+ projector.setParameter('view', view.data);
13334
+ projector.setParameter('viewProj', this.viewProjection.data);
13335
+ projector.setParameter('prevViewProj', this.prevViewProjection.data);
13336
+ projector.setParameter('prevView', this.prevView.data);
13337
+ projector.setParameter('prevClipZ', this.prevClipZ);
13338
+ projector.setParameter('viewport', [width, height]);
13339
+ projector.setParameter('focal', focal);
13340
+ projector.setParameter('prevViewport', this.prevViewport);
13341
+ projector.setParameter('prevFocal', this.prevFocal);
13342
+ projector.setParameter('numChunks', group.chunkCount);
13343
+ projector.setParameter('chunkBase', group.chunkBase);
13344
+ projector.setParameter('cameraPosition', [cameraPosition.x, cameraPosition.y, cameraPosition.z, 0]);
13345
+ projector.setParameter('splatTextureSize', this.source.textureSize(group));
13346
+ projector.setParameter('isOrtho', isOrtho ? 1 : 0);
13347
+ projector.setParameter('minPixelSize', gsplat.minPixelSize);
13348
+ projector.setParameter('alphaClip', gsplat.alphaClipForward);
13349
+ projector.setParameter('minContribution', minContribution);
13350
+ projector.setParameter('colorMax', this.variant.colorMax);
13351
+ projector.setParameter('unitScale', this.variant.units === 'engine' ? 2 : 1);
13352
+ projector.setParameter('occBlocksX1', this.occBlocks.x1);
13353
+ projector.setParameter('occBlocksY1', this.occBlocks.y1);
13354
+ projector.setParameter('occBlocksX2', this.occBlocks.x2);
13355
+ projector.setParameter('occBlocksY2', this.occBlocks.y2);
13356
+ projector.setParameter('occlusionMode', culling ? (cullMode === 'l1' ? 1 : 2) : 0);
13357
+ projector.setParameter('prevFlip', this.prevFlip);
13358
+ projector.setParameter('keyLogNear', logNear);
13359
+ projector.setParameter('keyInvLogRange', invLogRange);
13360
+ projector.setParameter('depthNear', depthNear);
13361
+ projector.setParameter('depthFar', depthFar);
13362
+ Compute.calcDispatchSize(group.chunkCount, tmpVec2);
13363
+ projector.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
13364
+ device.computeDispatch([projector], 'sse-splat-project');
13365
+ }
13366
+ // indirect draw arguments for the raster and dispatch size for the scatter; slots are
13367
+ // per frame
13368
+ const drawSlot = device.getIndirectDrawSlot(1);
13369
+ const dispatchSlot = device.getIndirectDispatchSlot(1);
13370
+ this.args.setParameter('counter', this.counter);
13371
+ this.args.setParameter('indirectDrawArgs', device.indirectDrawBuffer);
13372
+ this.args.setParameter('indirectDispatchArgs', device.indirectDispatchBuffer);
13373
+ this.args.setParameter('drawSlot', drawSlot);
13374
+ this.args.setParameter('indexCount', QUADS_PER_INSTANCE * 6);
13375
+ this.args.setParameter('quadsPerInstance', QUADS_PER_INSTANCE);
13376
+ this.args.setParameter('dispatchSlot', dispatchSlot);
13377
+ this.args.setParameter('scatterWorkgroupSize', ORDER_BUCKETS);
13378
+ this.args.setupDispatch(1, 1, 1);
13379
+ device.computeDispatch([this.args], 'sse-splat-args');
13380
+ this.rasterInstance.setIndirect(null, drawSlot, 1);
13381
+ if (ordered) {
13382
+ // bucket offsets, then every survivor claims its place in its bucket
13383
+ this.orderScan.setParameter('buckets', this.orderBuckets);
13384
+ this.orderScan.setupDispatch(1, 1, 1);
13385
+ device.computeDispatch([this.orderScan], 'sse-splat-order-scan');
13386
+ const scatter = this.orderScatter;
13387
+ scatter.setParameter('counter', this.counter);
13388
+ scatter.setParameter('cache', this.cacheBuffer);
13389
+ scatter.setParameter('buckets', this.orderBuckets);
13390
+ scatter.setParameter('ordered', this.orderedBuffer);
13391
+ scatter.setupIndirectDispatch(dispatchSlot);
13392
+ device.computeDispatch([scatter], 'sse-splat-order-scatter');
13393
+ }
13394
+ const material = this.rasterMaterial;
13395
+ material.setParameter('splatCache', this.cacheBuffer);
13396
+ material.setParameter('splatCount', this.counter);
13397
+ if (ordered)
13398
+ material.setParameter('orderedSlots', this.orderedBuffer);
13399
+ material.setParameter('viewportSize', [width, height, 2 / width, 2 / height]);
13400
+ material.setParameter('clipZParams', clipZParams);
13401
+ material.setParameter('focalParams', [focal[0], focal[1], 0, 0]);
13402
+ material.setParameter('sseAlphaClip', gsplat.alphaClipForward);
13403
+ material.setParameter('frameSeed', this.frameSeed);
13404
+ this.taaPass.enabled = taaOn;
13405
+ if (taaOn) {
13406
+ const read = this.taaWrite ^ 1;
13407
+ const taa = this.taaMaterial;
13408
+ this.taaPrevViewProjection.copy(this.taaLastViewProjection);
13409
+ this.taaPrevView.copy(this.taaLastView);
13410
+ this.cameraWorld.copy(view).invert();
13411
+ taa.setParameter('curColor', this.colorTexture);
13412
+ taa.setParameter('curDepth', this.depthTexture);
13413
+ taa.setParameter('histColor', this.taaColor[read]);
13414
+ taa.setParameter('histInfo', this.taaInfo[read]);
13415
+ taa.setParameter('cameraWorld', this.cameraWorld.data);
13416
+ // x_ndc = (m00 x + m02 z) / -z for a perspective camera, m00 x + m03 for an orthographic one
13417
+ const sp = shaderProjection.data;
13418
+ taa.setParameter('unproject', isOrtho ? [sp[0], sp[5], sp[12], sp[13]] : [sp[0], sp[5], sp[8], sp[9]]);
13419
+ taa.setParameter('prevViewProj', this.taaPrevViewProjection.data);
13420
+ taa.setParameter('prevView', this.taaPrevView.data);
13421
+ taa.setParameter('clipZParams', clipZParams);
13422
+ // a changed resident set (detail streamed in) keeps the history but caps its weight,
13423
+ // so the new content shows within taaMoveMax frames rather than 1 / taaMax a frame
13424
+ taa.setParameter('taaParams', [
13425
+ moved || changed ? this.variant.taaMoveMax : this.variant.taaMax,
13426
+ this.taaHistoryValid ? 1 : 0,
13427
+ moved ? 1 : 0,
13428
+ this.restFrames
13429
+ ]);
13430
+ taa.setParameter('taaViewport', [width, height, 1 / width, 1 / height]);
13431
+ taa.setParameter('taaControl', [
13432
+ this.variant.taaFlip || (this.target.flipY ? -1 : 1),
13433
+ this.variant.taaClip,
13434
+ this.variant.spp === 'quad' ? 1 : 0,
13435
+ 0
13436
+ ]);
13437
+ taa.setParameter('taaDebug', this.variant.taaDebug);
13438
+ taa.setParameter('taaFilter', [
13439
+ this.variant.taaFilter === 'cubic' ? 1 : 0,
13440
+ this.variant.taaReproj === 'history' ? 1 : 0,
13441
+ this.variant.taaMotion,
13442
+ 0
13443
+ ]);
13444
+ this.taaPass.renderTarget = this.taaTargets[this.taaWrite];
13445
+ this.composeMaterial.setParameter('taaColor', this.taaColor[this.taaWrite]);
13446
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[this.taaWrite]);
13447
+ this.taaLastViewProjection.copy(this.viewProjection);
13448
+ this.taaLastView.copy(view);
13449
+ this.taaHistoryValid = true;
13450
+ this.taaWrite ^= 1;
13451
+ }
13452
+ // an offscreen target's rows run the other way to the backbuffer's on WebGPU
13453
+ const targetFlipY = rt ? rt.flipY : device.backBuffer.flipY;
13454
+ this.composeMaterial.setParameter('composeParams', [
13455
+ this.target.flipY !== targetFlipY ? 1 : 0,
13456
+ isOrtho ? 1 : 0,
13457
+ taaOn ? 1 : 0,
13458
+ 0
13459
+ ]);
13460
+ this.composeMaterial.setParameter('depthViewParams', [
13461
+ clipZ[0],
13462
+ clipZ[1],
13463
+ Math.max(cam.nearClip, 1e-4),
13464
+ Math.max(cam.farClip, cam.nearClip * 2)
13465
+ ]);
13466
+ this.composeMaterial.setParameter('cameraClipZ', [cameraClipZ[0], cameraClipZ[1], isOrtho ? 1 : 0, 0]);
13467
+ // cull:auto: read this culled frame's counts back (asynchronously, off the frame) and
13468
+ // keep the test only while it removes enough to pay for itself
13469
+ if (culling && cullMode === 'auto' && !isQuery && !this.cullStatsPending) {
13470
+ this.cullStatsPending = true;
13471
+ const data = new Uint32Array(2);
13472
+ this.counter
13473
+ .read(0, 8, data, false)
13474
+ .then(() => {
13475
+ const total = data[0] + data[1];
13476
+ const worthwhile = total > 0 && data[1] / total >= StochasticSplatRenderer.CULL_MIN_FRACTION;
13477
+ this.cullActive = worthwhile;
13478
+ if (!worthwhile)
13479
+ this.cullSuspendedFrames = StochasticSplatRenderer.CULL_SUSPEND_FRAMES;
13480
+ })
13481
+ .catch(() => {
13482
+ // a lost device or a destroyed buffer; the next frame tries again
13483
+ })
13484
+ .finally(() => {
13485
+ this.cullStatsPending = false;
13486
+ });
13487
+ }
13488
+ // this frame becomes the previous one, unless it is a capture
13489
+ if (isQuery) {
13490
+ // the capture drew elsewhere; the on-screen depth texture is no longer this frame's
13491
+ this.prevValid = false;
13492
+ this.depthFrame = null;
13493
+ this.setReady(true);
13494
+ return;
13495
+ }
13496
+ captureCameraSnapshot(camera.entity, this.depthFrameCamera);
13497
+ this.depthFrame = {
13498
+ id: ++this.depthFrameCount,
13499
+ camera: this.depthFrameCamera,
13500
+ width,
13501
+ height,
13502
+ clipZ: [clipZ[0], clipZ[1]]
13503
+ };
13504
+ this.prevViewProjection.copy(this.viewProjection);
13505
+ this.prevView.copy(view);
13506
+ this.prevProjection.copy(projection);
13507
+ this.prevClipZ = clipZParams;
13508
+ this.prevViewport = [width, height];
13509
+ this.prevFocal = focal;
13510
+ this.prevFlip = this.target.flipY ? -1 : 1;
13511
+ this.prevWidth = width;
13512
+ this.prevHeight = height;
13513
+ this.prevVersion = set.version;
13514
+ this.prevOrtho = isOrtho;
13515
+ this.prevValid = !isQuery;
13516
+ this.setReady(true);
13517
+ }
13518
+ resizeHistory(width, height) {
13519
+ for (const texture of [...this.taaColor, ...this.taaInfo])
13520
+ texture.resize(width, height);
13521
+ for (const target of this.taaTargets)
13522
+ target.resize(width, height);
13523
+ }
13524
+ // whether the view or the projection differs from the previous on-screen frame's beyond
13525
+ // float noise (the camera controllers settle over many frames; a fov animation moves the
13526
+ // image without moving the camera)
13527
+ viewMoved(view, projection) {
13528
+ for (let i = 0; i < 16; i++) {
13529
+ if (Math.abs(view.data[i] - this.prevView.data[i]) > 1e-6)
13530
+ return true;
13531
+ if (Math.abs(projection.data[i] - this.prevProjection.data[i]) > 1e-6)
13532
+ return true;
13533
+ }
13534
+ return false;
13535
+ }
13536
+ // one chunk-table entry per CHUNK_SIZE splats of every resident node
13537
+ rebuildChunkTable(set) {
13538
+ let count = 0;
13539
+ for (const node of set.nodes)
13540
+ count += Math.ceil(node.count / CHUNK_SIZE);
13541
+ if (this.chunkData.length < count * 4) {
13542
+ this.chunkData = new Uint32Array(Math.ceil(count * 1.25) * 4);
13543
+ this.chunkBuffer?.destroy();
13544
+ this.chunkBuffer = new StorageBuffer(this.device, this.chunkData.byteLength, BUFFERUSAGE_COPY_DST);
13545
+ }
13546
+ const data = this.chunkData;
13547
+ let k = 0;
13548
+ set.nodes.forEach((node, nodeIndex) => {
13549
+ const base = this.source.chunkBase(node);
13550
+ for (let offset = 0; offset < node.count; offset += CHUNK_SIZE) {
13551
+ data[k++] = base + offset;
13552
+ data[k++] = Math.min(CHUNK_SIZE, node.count - offset);
13553
+ data[k++] = nodeIndex;
13554
+ data[k++] = (node.lodIndex & 0xffff) | (node.fileIndex << 16);
13555
+ }
13556
+ });
13557
+ this.numChunks = count;
13558
+ // writeBuffer counts typed-array elements, not bytes
13559
+ if (count > 0)
13560
+ this.chunkBuffer.write(0, data, 0, count * 4);
13561
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
13562
+ if (this.nodeVisibleData.length < words) {
13563
+ this.nodeVisibleData = new Uint32Array(words);
13564
+ this.nodeVisibleBuffer?.destroy();
13565
+ this.nodeVisibleBuffer = new StorageBuffer(this.device, words * 4, BUFFERUSAGE_COPY_DST);
13566
+ }
13567
+ }
13568
+ // the cache is dense (indexed by compact slot), so it only needs room for the resident
13569
+ // splats, not the allocator's address space; grown geometrically, never shrunk
13570
+ ensureCache(splats) {
13571
+ if (splats <= this.cacheSlots)
13572
+ return;
13573
+ this.cacheBuffer?.destroy();
13574
+ this.orderedBuffer?.destroy();
13575
+ this.cacheSlots = Math.max(1, Math.ceil(splats * 1.25));
13576
+ this.cacheBuffer = new StorageBuffer(this.device, this.cacheSlots * CACHE_WORDS * 4, BUFFERUSAGE_COPY_SRC);
13577
+ this.orderedBuffer = new StorageBuffer(this.device, this.cacheSlots * 4);
13578
+ }
13579
+ // sphere-frustum test per node on the cpu: thousands of nodes, one bit each
13580
+ cullNodes(set, viewProjection) {
13581
+ const bits = this.nodeVisibleData;
13582
+ bits.fill(0);
13583
+ this.frustum.setFromMat4(viewProjection);
13584
+ const spheres = set.nodeSpheres;
13585
+ const { sphere } = this;
13586
+ for (let i = 0; i < set.nodes.length; i++) {
13587
+ sphere.center.set(spheres[i * 4], spheres[i * 4 + 1], spheres[i * 4 + 2]);
13588
+ sphere.radius = spheres[i * 4 + 3];
13589
+ if (this.frustum.containsSphere(sphere) !== 0) {
13590
+ bits[i >> 5] |= 1 << (i & 31);
13591
+ }
13592
+ }
13593
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
13594
+ this.nodeVisibleBuffer.write(0, bits, 0, words);
13595
+ }
13596
+ anyNodeVisible(nodes) {
13597
+ const bits = this.nodeVisibleData;
13598
+ return nodes.some((node) => (bits[node.nodeIndex >> 5] >>> (node.nodeIndex & 31)) & 1);
13599
+ }
13600
+ ensureProjector(occlusion, ordered, group) {
13601
+ const sourceKey = this.source.shaderKey();
13602
+ if (this.projectorSourceKey !== sourceKey) {
13603
+ // a different source: every specialisation and the bind group format go
13604
+ this.destroyProjector();
13605
+ this.projectorSourceKey = sourceKey;
13606
+ }
13607
+ const key = `${occlusion ? 'occlusion' : 'plain'}-${ordered ? 'bucket' : 'append'}`;
13608
+ const computeKey = `${key}:${group.fileIndex}`;
13609
+ const existing = this.projectorComputes.get(computeKey);
13610
+ if (existing)
13611
+ return existing;
13612
+ const shader = this.ensureProjectorShader(key, occlusion, ordered);
13613
+ const compute = new Compute(this.device, shader, 'sse-splat-project');
13614
+ this.projectorComputes.set(computeKey, compute);
13615
+ return compute;
13616
+ }
13617
+ // drop the computes of files that left the resident set
13618
+ pruneProjectorComputes(set) {
13619
+ for (const [key, compute] of this.projectorComputes) {
13620
+ const fileIndex = Number(key.slice(key.lastIndexOf(':') + 1));
13621
+ if (fileIndex >= 0 && !set.files[fileIndex]) {
13622
+ compute.destroy();
13623
+ this.projectorComputes.delete(key);
13624
+ }
13625
+ }
13626
+ }
13627
+ ensureProjectorShader(key, occlusion, ordered) {
13628
+ const existing = this.projectorShaders.get(key);
13629
+ if (existing)
13630
+ return existing;
13631
+ const { device } = this;
13632
+ const fixed = [
13633
+ new BindStorageBufferFormat('chunks', SHADERSTAGE_COMPUTE, true),
13634
+ new BindStorageBufferFormat('nodeVisible', SHADERSTAGE_COMPUTE, true),
13635
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE),
13636
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE),
13637
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE),
13638
+ new BindStorageBufferFormat('occL1', SHADERSTAGE_COMPUTE, true),
13639
+ new BindStorageBufferFormat('occL2', SHADERSTAGE_COMPUTE, true),
13640
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)
13641
+ ];
13642
+ const formats = [...fixed, ...this.source.bindFormats()];
13643
+ this.projectorBindGroupFormat ??= new BindGroupFormat(device, formats);
13644
+ const shader = new Shader(device, {
13645
+ name: `sse-splat-project-${key}`,
13646
+ shaderLanguage: SHADERLANGUAGE_WGSL,
13647
+ cshader: projectorWGSL(this.source.readChunk(fixed.length), occlusion, ordered),
13648
+ cincludes: this.source.shaderIncludes(),
13649
+ cdefines: this.source.shaderDefines(),
13650
+ computeUniformBufferFormats: {
13651
+ // the same order as the wgsl struct; both follow the same alignment rules
13652
+ uniforms: new UniformBufferFormat(device, [
13653
+ new UniformFormat('view', UNIFORMTYPE_MAT4),
13654
+ new UniformFormat('viewProj', UNIFORMTYPE_MAT4),
13655
+ new UniformFormat('prevViewProj', UNIFORMTYPE_MAT4),
13656
+ new UniformFormat('prevView', UNIFORMTYPE_MAT4),
13657
+ new UniformFormat('prevClipZ', UNIFORMTYPE_VEC4),
13658
+ new UniformFormat('viewport', UNIFORMTYPE_VEC2),
13659
+ new UniformFormat('focal', UNIFORMTYPE_VEC2),
13660
+ new UniformFormat('prevViewport', UNIFORMTYPE_VEC2),
13661
+ new UniformFormat('prevFocal', UNIFORMTYPE_VEC2),
13662
+ new UniformFormat('numChunks', UNIFORMTYPE_UINT),
13663
+ new UniformFormat('splatTextureSize', UNIFORMTYPE_UINT),
13664
+ new UniformFormat('isOrtho', UNIFORMTYPE_UINT),
13665
+ new UniformFormat('minPixelSize', UNIFORMTYPE_FLOAT),
13666
+ new UniformFormat('alphaClip', UNIFORMTYPE_FLOAT),
13667
+ new UniformFormat('minContribution', UNIFORMTYPE_FLOAT),
13668
+ new UniformFormat('occBlocksX1', UNIFORMTYPE_UINT),
13669
+ new UniformFormat('occBlocksY1', UNIFORMTYPE_UINT),
13670
+ new UniformFormat('occBlocksX2', UNIFORMTYPE_UINT),
13671
+ new UniformFormat('occBlocksY2', UNIFORMTYPE_UINT),
13672
+ new UniformFormat('occlusionMode', UNIFORMTYPE_UINT),
13673
+ new UniformFormat('prevFlip', UNIFORMTYPE_FLOAT),
13674
+ new UniformFormat('keyLogNear', UNIFORMTYPE_FLOAT),
13675
+ new UniformFormat('keyInvLogRange', UNIFORMTYPE_FLOAT),
13676
+ new UniformFormat('chunkBase', UNIFORMTYPE_UINT),
13677
+ new UniformFormat('model', UNIFORMTYPE_MAT4),
13678
+ new UniformFormat('modelRotation', UNIFORMTYPE_VEC4),
13679
+ new UniformFormat('modelScale', UNIFORMTYPE_VEC4),
13680
+ new UniformFormat('cameraPosition', UNIFORMTYPE_VEC4),
13681
+ new UniformFormat('colorMax', UNIFORMTYPE_FLOAT),
13682
+ new UniformFormat('unitScale', UNIFORMTYPE_FLOAT),
13683
+ new UniformFormat('depthNear', UNIFORMTYPE_FLOAT),
13684
+ new UniformFormat('depthFar', UNIFORMTYPE_FLOAT)
13685
+ ])
13686
+ },
13687
+ computeBindGroupFormat: this.projectorBindGroupFormat
13688
+ });
13689
+ this.projectorShaders.set(key, shader);
13690
+ return shader;
13691
+ }
13692
+ destroyProjector() {
13693
+ for (const compute of this.projectorComputes.values())
13694
+ compute.destroy();
13695
+ this.projectorComputes.clear();
13696
+ for (const shader of this.projectorShaders.values())
13697
+ shader.destroy();
13698
+ this.projectorShaders.clear();
13699
+ this.projectorBindGroupFormat?.destroy();
13700
+ this.projectorBindGroupFormat = null;
13701
+ this.projectorSourceKey = '';
13702
+ }
13703
+ destroy() {
13704
+ this.unsubscribe();
13705
+ this.app.off('frameend', this.onFrameEnd);
13706
+ this.detach();
13707
+ this.provider.destroy();
13708
+ this.source.destroy();
13709
+ this.destroyProjector();
13710
+ this.args.shader.destroy();
13711
+ this.args.destroy();
13712
+ this.argsBindGroupFormat.destroy();
13713
+ for (const compute of [this.reduceL1, this.reduceL2]) {
13714
+ compute.shader.destroy();
13715
+ compute.destroy();
13716
+ }
13717
+ for (const format of this.reduceFormats)
13718
+ format.destroy();
13719
+ this.occL1.destroy();
13720
+ this.occL2.destroy();
13721
+ for (const compute of [this.orderScan, this.orderScatter]) {
13722
+ compute.shader.destroy();
13723
+ compute.destroy();
13724
+ }
13725
+ for (const format of this.orderFormats)
13726
+ format.destroy();
13727
+ this.orderBuckets.destroy();
13728
+ this.orderedBuffer?.destroy();
13729
+ this.orderedBuffer = null;
13730
+ this.chunkBuffer?.destroy();
13731
+ this.nodeVisibleBuffer?.destroy();
13732
+ this.cacheBuffer?.destroy();
13733
+ this.counter.destroy();
13734
+ this.chunkBuffer = this.nodeVisibleBuffer = this.cacheBuffer = null;
13735
+ this.rasterPass.destroy();
13736
+ this.rasterInstance.destroy();
13737
+ this.rasterMaterial.destroy();
13738
+ this.rasterMesh.destroy();
13739
+ this.taaPass.destroy();
13740
+ this.taaInstance.destroy();
13741
+ this.taaMaterial.destroy();
13742
+ this.taaMesh.destroy();
13743
+ for (const target of this.taaTargets)
13744
+ target.destroy();
13745
+ for (const texture of [...this.taaColor, ...this.taaInfo])
13746
+ texture.destroy();
13747
+ this.taaTargets.length = 0;
13748
+ this.taaColor.length = 0;
13749
+ this.taaInfo.length = 0;
13750
+ this.target.destroy();
13751
+ this.colorTexture.destroy();
13752
+ this.depthTexture.destroy();
13753
+ this.composeInstance.destroy();
13754
+ this.composeMaterial.destroy();
13755
+ this.composeMesh.destroy();
13756
+ }
13757
+ }
13758
+
13759
+ // ---------------------------------------------------------------------------
13760
+ // WGSL compute shader: ray-march through the sparse voxel octree per pixel
13761
+ // ---------------------------------------------------------------------------
13762
+ const voxelOverlayWGSL = /* wgsl */ `
13763
+
13764
+ // Solid leaf sentinel: childMask=0xFF, baseOffset=0
13765
+ const SOLID_LEAF_MARKER: u32 = 0xFF000000u;
10149
13766
 
10150
13767
  // Maximum DDA steps to prevent infinite loops
10151
13768
  const MAX_STEPS: u32 = 512u;
@@ -10985,6 +14602,17 @@ const rendererTable = {
10985
14602
  webgl: GSPLAT_RENDERER_RASTER_CPU_SORT,
10986
14603
  webgpu: GSPLAT_RENDERER_RASTER_GPU_SORT
10987
14604
  };
14605
+ // quality budget, millions of splats
14606
+ const budgets = {
14607
+ mobile: {
14608
+ low: 1,
14609
+ high: 2
14610
+ },
14611
+ desktop: {
14612
+ low: 2,
14613
+ high: 4
14614
+ }
14615
+ };
10988
14616
  const tonemapTable = {
10989
14617
  none: TONEMAP_NONE,
10990
14618
  linear: TONEMAP_LINEAR,
@@ -11079,6 +14707,13 @@ class Viewer {
11079
14707
  meshOverlay = null;
11080
14708
  navCursor = null;
11081
14709
  debugPanel = null;
14710
+ /** The opt-in stochastic renderer (WebGPU only); null when the engine's sorted renderer draws. */
14711
+ splatRenderer = null;
14712
+ /**
14713
+ * The engine's MiniStats panel once first shown (`?ministats` or the debug panel), else null.
14714
+ * Hiding disables it rather than destroying it.
14715
+ */
14716
+ miniStats = null;
11082
14717
  /** Set once {@link destroy} has run. Load continuations check it and bail. */
11083
14718
  destroyed = false;
11084
14719
  disposers = [];
@@ -11138,10 +14773,35 @@ class Viewer {
11138
14773
  app.autoRender = true;
11139
14774
  // configure the camera
11140
14775
  this.configureCamera(settings);
11141
- // reconfigure camera when entering/exiting XR
14776
+ // The stochastic renderer, when opted in. Created before the first frame so it can
14777
+ // switch the engine's own splat renderer off as soon as the engine creates it. An
14778
+ // instance without the flag never constructs it, and the sorted path is untouched.
14779
+ if (config.stochastic && renderer === 'webgpu') {
14780
+ const worldLayer = app.scene.layers.getLayerByName('World');
14781
+ // the largest budget this instance can ask for must fit the device's storage binding
14782
+ const budget = (config.budget && config.budget > 0
14783
+ ? config.budget
14784
+ : (platform.mobile ? budgets.mobile : budgets.desktop).high) * 1000000;
14785
+ if (!StochasticSplatRenderer.cacheFits(app.graphicsDevice, budget)) {
14786
+ console.warn(`stochastic renderer: a ${budget / 1000000}M splat budget exceeds this device's storage binding limit; the sorted renderer draws`);
14787
+ }
14788
+ else if (worldLayer) {
14789
+ this.splatRenderer = new StochasticSplatRenderer(app, camera.camera, worldLayer, {
14790
+ source: config.splatSource,
14791
+ variant: config.variant
14792
+ });
14793
+ // announced on the first frame rather than here: createViewer resolves after this
14794
+ // constructor, so a page can only subscribe once loading is under way
14795
+ events.once('firstFrame', () => events.fire('splatRenderer:ready', this.splatRenderer));
14796
+ }
14797
+ }
14798
+ // reconfigure camera when entering/exiting XR. The stochastic renderer has no stereo
14799
+ // path yet, so the engine's renderer draws the splats for the session
11142
14800
  const configureXrCamera = () => {
11143
- if (!this.destroyed)
11144
- this.configureCamera(settings);
14801
+ if (this.destroyed)
14802
+ return;
14803
+ this.configureCamera(settings);
14804
+ this.splatRenderer?.setEnabled(!app.xr.active);
11145
14805
  };
11146
14806
  const xrStart = app.xr.on('start', configureXrCamera);
11147
14807
  const xrEnd = app.xr.on('end', configureXrCamera);
@@ -11149,28 +14809,12 @@ class Viewer {
11149
14809
  xrStart.off();
11150
14810
  xrEnd.off();
11151
14811
  });
11152
- // construct debug ministats
11153
- if (config.ministats) {
11154
- const options = MiniStats.getDefaultOptions();
11155
- options.cpu.enabled = false;
11156
- options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
11157
- options.stats.push({
11158
- name: 'VRAM',
11159
- stats: ['vram.tex'],
11160
- decimalPlaces: 1,
11161
- multiplier: 1 / (1024 * 1024),
11162
- unitsName: 'MB',
11163
- watermark: 1024
11164
- }, {
11165
- name: 'Splats',
11166
- stats: ['frame.gsplats'],
11167
- decimalPlaces: 3,
11168
- multiplier: 1 / 1000000,
11169
- unitsName: 'M',
11170
- watermark: 5
11171
- });
11172
- new MiniStats(app, options);
11173
- }
14812
+ // debug ministats, from the flag at start and the debug panel's toggle after
14813
+ this.setMiniStats(config.ministats);
14814
+ this.onDestroy(() => {
14815
+ this.miniStats?.destroy();
14816
+ this.miniStats = null;
14817
+ });
11174
14818
  const prevProj = new Mat4();
11175
14819
  const prevWorld = new Mat4();
11176
14820
  const sceneBound = new BoundingBox();
@@ -11179,7 +14823,7 @@ class Viewer {
11179
14823
  const world = camera.getWorldTransform();
11180
14824
  const proj = camera.camera.projectionMatrix;
11181
14825
  if (!app.renderNextFrame) {
11182
- if (config.ministats ||
14826
+ if (this.miniStats?.enabled ||
11183
14827
  !nearlyEquals(world.data, prevWorld.data) ||
11184
14828
  !nearlyEquals(proj.data, prevProj.data)) {
11185
14829
  app.renderNextFrame = true;
@@ -11360,7 +15004,12 @@ class Viewer {
11360
15004
  if (gsplatBbox) {
11361
15005
  sceneBound.setFromTransformedAabb(gsplatBbox, results[0].getWorldTransform());
11362
15006
  }
11363
- this.picker = new Picker(app, camera);
15007
+ // the stochastic renderer leaves its frame's depth behind, so no pick pass is needed
15008
+ this.picker = this.splatRenderer
15009
+ ? new FrameDepthPicker(app, camera, this.splatRenderer)
15010
+ : new Picker(app, camera);
15011
+ // for development pages (the bench measures pick noise), as splatRenderer:ready
15012
+ events.fire('picker:ready', this.picker);
11364
15013
  this.inputController = new InputController(global, this.picker);
11365
15014
  this.cameraManager = new CameraManager(global, sceneBound);
11366
15015
  applyCamera(this.cameraManager.camera);
@@ -11410,18 +15059,10 @@ class Viewer {
11410
15059
  // collision may already have landed while the splats were still streaming
11411
15060
  if (collisionReady)
11412
15061
  attachCollision(collisionReady);
11413
- this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker);
11414
- // quality budget
11415
- const budgets = {
11416
- mobile: {
11417
- low: 1,
11418
- high: 2
11419
- },
11420
- desktop: {
11421
- low: 2,
11422
- high: 4
11423
- }
11424
- };
15062
+ this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker, this.splatRenderer, {
15063
+ shown: () => !!this.miniStats?.enabled,
15064
+ show: (value) => this.setMiniStats(value)
15065
+ });
11425
15066
  const applyPerfSettings = () => {
11426
15067
  const budget = () => {
11427
15068
  if (config.budget !== undefined && Number.isFinite(config.budget) && config.budget > 0) {
@@ -11476,7 +15117,12 @@ class Viewer {
11476
15117
  // handle quality mode changes
11477
15118
  events.on('performanceMode:changed', applyPerfSettings);
11478
15119
  applyPerfSettings();
11479
- gsplat.renderer = rendererTable[renderer];
15120
+ // the stochastic renderer consumes the engine's world under whatever
15121
+ // renderer mode the engine resolved; switching modes here would rebuild
15122
+ // the work buffer for nothing
15123
+ if (!this.splatRenderer) {
15124
+ gsplat.renderer = rendererTable[renderer];
15125
+ }
11480
15126
  // wait for the first valid frame to complete rendering
11481
15127
  app.once('frameend', () => {
11482
15128
  events.fire('firstFrame');
@@ -11626,6 +15272,49 @@ class Viewer {
11626
15272
  }
11627
15273
  this.disposers.push(fn);
11628
15274
  }
15275
+ /**
15276
+ * Show or hide the engine's MiniStats panel. While shown the viewer renders every frame, so
15277
+ * the graphs keep moving.
15278
+ */
15279
+ setMiniStats(value) {
15280
+ if (value === !!this.miniStats?.enabled)
15281
+ return;
15282
+ // hidden by disabling rather than destroying: the engine's destroy() leaves its stats
15283
+ // timers reading every frame and its buffers allocated, so a panel per toggle would pile
15284
+ // them up until teardown
15285
+ if (this.miniStats) {
15286
+ this.miniStats.enabled = value;
15287
+ // the panel's transparent div would keep catching clicks over the canvas
15288
+ this.miniStats.div.style.display = value ? '' : 'none';
15289
+ if (value) {
15290
+ // enabling turns every graph on, the text-only size's too: its size puts them back
15291
+ const size = this.miniStats.activeSizeIndex;
15292
+ this.miniStats.activeSizeIndex = size;
15293
+ this.global.app.renderNextFrame = true;
15294
+ }
15295
+ return;
15296
+ }
15297
+ const options = MiniStats.getDefaultOptions();
15298
+ options.cpu.enabled = false;
15299
+ options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
15300
+ options.stats.push({
15301
+ name: 'VRAM',
15302
+ stats: ['vram.tex'],
15303
+ decimalPlaces: 1,
15304
+ multiplier: 1 / (1024 * 1024),
15305
+ unitsName: 'MB',
15306
+ watermark: 1024
15307
+ }, {
15308
+ name: 'Splats',
15309
+ stats: ['frame.gsplats'],
15310
+ decimalPlaces: 3,
15311
+ multiplier: 1 / 1000000,
15312
+ unitsName: 'M',
15313
+ watermark: 5
15314
+ });
15315
+ this.miniStats = new MiniStats(this.global.app, options);
15316
+ this.global.app.renderNextFrame = true;
15317
+ }
11629
15318
  /**
11630
15319
  * Tear the viewer down: stop rendering, remove every listener it added to the window,
11631
15320
  * document and canvas, restore the globals it patched, and release the graphics device.
@@ -11656,6 +15345,8 @@ class Viewer {
11656
15345
  this.voxelOverlay?.destroy();
11657
15346
  this.meshOverlay?.destroy();
11658
15347
  this.picker?.release();
15348
+ this.splatRenderer?.destroy();
15349
+ this.splatRenderer = null;
11659
15350
  this.capture?.destroy();
11660
15351
  this.capture = null;
11661
15352
  if (this.cameraFrame) {
@@ -11851,6 +15542,12 @@ const createApp = async (canvas, config) => {
11851
15542
  touch: new TouchDevice$1(canvas),
11852
15543
  keyboard: new Keyboard(window)
11853
15544
  });
15545
+ // The stochastic renderer never sorts on the cpu, so the per-splat centres the engine
15546
+ // reads back for its cpu sort (12 bytes each, plus a gpu readback per file) are dead
15547
+ // weight. Read once per file at load, so it has to be set before any asset loads.
15548
+ if (config.stochastic && renderer === 'webgpu') {
15549
+ app.scene.gsplatCentersEnabled = false;
15550
+ }
11854
15551
  // enable anonymous CORS for image loading in safari (must be set before any
11855
15552
  // texture asset starts loading, otherwise the <img> is fetched without the
11856
15553
  // crossorigin attribute and WebGL rejects it with SecurityError)
@@ -11954,6 +15651,9 @@ const resolveConfig = (options) => ({
11954
15651
  colorize: options.colorize ?? false,
11955
15652
  fullload: options.fullload ?? false,
11956
15653
  aa: options.aa ?? false,
15654
+ stochastic: options.stochastic ?? false,
15655
+ splatSource: options.splatSource ?? 'workbuffer',
15656
+ variant: options.variant ?? '',
11957
15657
  budget: options.budget,
11958
15658
  heatmap: options.heatmap ?? false,
11959
15659
  debug: options.debug ?? false,
@@ -12108,7 +15808,9 @@ const createViewer = async (options) => {
12108
15808
  destroy: () => viewer.destroy()
12109
15809
  };
12110
15810
  // The built-in controls use the same handle returned to an embedding host.
12111
- const disposeUI = config.ui ? initUI(global, handle, () => viewer.picker) : null;
15811
+ const disposeUI = config.ui
15812
+ ? initUI(global, handle, () => viewer.picker, () => viewer.cameraManager?.transitionProgress() ?? 1)
15813
+ : null;
12112
15814
  viewer.onDestroy(() => {
12113
15815
  destroyed = true;
12114
15816
  });