import * as THREE from 'three/webgpu'; import type { WebGLRenderer } from 'three'; import { type DepthOfFieldSettings } from '../core/depth-of-field'; import { SplatMesh } from '../core/splat-mesh'; import type { SplatPickOptions, SplatPickResult } from '../core/splat-mesh'; import type { DisplayColorModifier } from '../core/splat-mesh-material'; import { type SplatPerformanceProfile, type SplatProjectionStrategy, type SplatSortMetric, type SplatSortStrategyFactory } from '../core/splat-mesh-types'; export interface UnifiedDrawPublicationSnapshot { /** * The draw has an order to show: a publication with sources and active * splats. Unlike {@link ready} it does not wait for a rendered frame, so a * host replacing a unified mesh can switch to the new one as soon as this is * true instead of showing a blank frame. */ readonly drawable: boolean; readonly ready: boolean; readonly publicationRevision: number; readonly renderedPublicationRevision: number; readonly contentRevision: number; readonly orderRevision: number; readonly sourceCount: number; readonly activeCount: number; readonly instanceCount: number; readonly computeProjection: boolean; } /** Registration settings for one source in a {@link UnifiedSplatMesh}. */ export interface UnifiedSplatSourceOptions { /** Whole-source display opacity applied after gather falloff. Defaults to `1`. * Does not change RAD LOD classification or splat shape. */ opacity?: number; /** Whether this source contributes to the unified draw. Defaults to `true`. */ visible?: boolean; /** Higher values survive a fixed work-buffer overflow first. Defaults to `0`. */ priority?: number; /** * Cache a modifier-bearing source until {@link UnifiedSplatMesh.invalidateSource} * is called. Defaults to `false`, which safely re-gathers live modifier * uniforms every frame. * * Use this for static modifiers, or when the host has a natural dirty signal * for every uniform/channel mutation. Forgetting to invalidate leaves the * unified work-buffer output stale. */ cacheModifiers?: boolean; /** * When {@link cacheModifiers} is set, refresh only SH color if the camera * moves. Reuses cached SDF visibility, covariance, and world centers. * Defaults to `false` so cached color-writing modifiers keep a full gather. * Hosts should enable this only for visibility-only stacks such as hard clip. */ shColorRefresh?: boolean; } /** * Result of a successful {@link UnifiedSplatMesh.pick}: the frontmost hit * across every visible registered source, tagged with the source it landed on. */ export interface UnifiedSplatPickResult extends SplatPickResult { /** The registered source mesh whose splat produced the winning hit. */ readonly source: SplatMesh; } /** * Construction settings shared by every source in a unified renderer. * */ export type UnifiedSplatPrepareStage = 'setup' | 'sourceUpdate' | 'sourceView' | 'sourceComparison' | 'admission' | 'gather' | 'layout' | 'sortSubmit' | 'publication'; export interface UnifiedSplatMeshOptions { /** Optional synchronous timing sink; omitted in normal rendering. */ onPrepareStage?: (stage: UnifiedSplatPrepareStage, durationMs: number) => void; /** Vertex projection by default, or an injected experimental projector. */ projectionStrategy?: SplatProjectionStrategy; /** * Contribution-culling profile used by the shared unified draw. Defaults to * the same device-aware profile as {@link SplatMesh}; every source must * resolve to the same contribution thresholds. */ performanceProfile?: SplatPerformanceProfile; /** Override the shared SuperSplat-style on-screen diameter cull in px. */ minPixelSize?: number; /** Override the shared opacity × major × minor cull. */ minContribution?: number; /** Composite source colors in display (sRGB) space. Defaults to `false`. */ srgbOutput?: boolean; /** * Global depth-sort strategy. Defaults to the lower-cost counting sorter. * `'worker'` is unsupported: unified rendering is WebGPU-only. The strings * `'radix'` and `'exact'` are not accepted; pass `radixSort()` / `exactSort()`. */ sortStrategy?: 'counting' | SplatSortStrategyFactory; /** * Camera-space key used for global ordering. Defaults to `'depth'` for * compatibility; `'radial'` matches Spark's rotation-invariant ordering. */ sortMetric?: SplatSortMetric; } /** CPU submission timings for the last unified gather/sort preparation. */ export interface UnifiedSplatPerformanceTimings { totalMs: number; gatherMs: number; sortSubmitMs: number; sourceCount: number; activeCount: number; sortSubmitted: boolean; gatherDispatches: number; fullGatherDispatches: number; colorGatherDispatches: number; cacheHits: number; gatherSlots: number; projectionSubmissions: number; projectionPasses: number; sortSubmissions: number; sortPasses: number; activeListBytes: number; activeListRanges: number; sortSerial: number; sortSubmissionFrame: number; sortAction: 'none' | 'submitted' | 'coalesced' | 'suppressed'; sortTracking: 'pending' | 'gpu-completion' | 'render-ack-fallback' | null; sortAcknowledgementMs: number | null; sortInputCount: number; } /** * Returns true when `renderer` can drive {@link UnifiedSplatMesh}. * Heterogeneous gather/sort/draw is WebGPU-only; WebGL2 hosts keep standalone * `SplatMesh` draws or static {@link MergedSplatMesh}. */ export declare function supportsUnifiedSplatMesh(renderer: object): boolean; /** * One gather → global-sort → draw path for static and streamed splat sources. * Sources retain their own residency and update lifecycle; this mesh gathers * their current active pool ranges into one shared work buffer per frame. * * The unified mesh stays at identity (`matrixAutoUpdate` is off). Pose each * registered source mesh instead - sorter bounds and the draw material both * consume world-space centers written by gather. * * WebGPU only. Prefer {@link supportsUnifiedSplatMesh} before construction. * * `capacity` (the work-buffer slots, shared by every source's active splats) * may not exceed 2²⁴: the draw indexes the work buffer through a float32 * `splatIndex`, so the constructor throws a `RangeError` above it rather than * drawing a corrupt permutation. Load whole-file sources under one * `SplatSceneBudget` (`@voluma/vlam/loaders`) to keep their sum below it. */ export declare class UnifiedSplatMesh extends THREE.Mesh { /** * Brand shared by every VLAM splat draw (`SplatMesh` and its subclasses, and * both unified meshes), for code that must find them in a scene without * importing each class. */ readonly isSplatDraw: true; private readonly workBuffer; private readonly workSourceIndex; /** The sorted draw-order buffer; lives outside the geometry, freed on dispose. */ private readonly orderAttribute; /** * Frees the JS mirrors three keeps behind `workSourceIndex` and `order`. * * `workSourceIndex` is an identity ramp written once at construction; `order` * is written only by the sorter, on the GPU. Neither is ever read back, so * both mirrors are 4 B/slot of dead JS heap once uploaded. */ private readonly mirrors; private readonly sorter; private readonly projectedSorter; private readonly projectedPipeline; private readonly onPrepareStage; private readonly performanceTimingsValue; private computeProjectionActive; private readonly renderer; private readonly sources; private previousLayout; /** Previous layout keyed by source; kept in step with {@link previousLayout}. */ private readonly previousLayoutBySource; /** Per-prepare scratch lists, reused so a steady frame allocates nothing. */ private readonly candidateScratch; private readonly admittedScratch; private readonly drawingBufferSize; /** Reused target dimensions for secondary views; avoids per-view garbage. */ private readonly secondaryViewSize; /** * `renderView` sorted the shared order buffer for another camera. Until a * primary preparation sorts again, a held gate must not keep that order: the * primary draw would show the scene in the secondary view's order (a mirror * camera's order shows the far side of an object through its near side). */ private foreignOrder; /** * Camera gating for the global sorter, mirroring the standalone * `SplatMesh.requestSortIfNeeded` path: an unchanged work buffer under a * stationary camera skips the whole-buffer re-sort. Content changes * (regather, layout change) force the next sort through the scheduler. */ private readonly sortScheduler; /** Primary refinement frame number used by the non-blocking sort gate. */ private refinementFrameNumber; /** Pose signature of the last accepted sort; starts unmatchable (zero scale). */ private readonly lastSortedState; private readonly currentSortState; /** * Sum of the admitted sources' `invalidateSortDisplacement` revisions the * current order was built from. Revisions only grow, so a differing sum * means some source's displaced centers moved since the last sort. */ private sortedDisplacementKey; /** Reused per held prepare: moved sources and their views, interleaved. */ private readonly heldMoveScratch; /** * Total admitted splats in the last prepared frame. `removeSource` filters * {@link previousLayout} directly, so a tail source's removal can leave the * remaining entries identical - only this total betrays the shrink, and a * shrunk draw range must re-sort (the old permutation indexes past it). */ private previousAdmittedTotal; /** * Inputs of the last compute-projection dispatch, mirroring the standalone * `SplatMesh.needsProjectedSort` signature. The projector both culls and * writes per-splat clip-space data, so unlike {@link lastSortedState} this * deliberately covers the projection, raster viewport, admitted count and * the live DoF uniforms the projector reads - a stationary depth key alone * is not enough to reuse its output. Starts unmatchable (zero scale) so the * first prepared frame always dispatches. A held sort gate re-projects only * once this signature changes, see {@link reprojectWhileHeld}. */ private readonly lastProjectedView; private readonly lastProjectedProjection; private readonly lastProjectedViewport; private lastProjectedActiveCount; private lastProjectedDofFocusDistance; private lastProjectedDofAperture; /** * Last work-buffer count whose GPU order has been allowed to draw. Stays 0 * until the first `onSubmittedWorkDone` so the identity fill of `order` * never reaches the canvas. */ private orderedDrawCount; /** Count waiting on the in-flight GPU sort, or null. */ private pendingOrderedDrawCount; private readonly bounds; private readonly focal; private readonly viewport; private readonly maxStdDev; private readonly minSplatSizePx; /** Shared construction-time contribution thresholds, baked into both paths. */ private readonly minPixelSize; private readonly minContribution; private readonly antialias; private readonly projectedLowPassVariance; private readonly compensateProjectedLowPass; private readonly dofFocusDistance; private readonly dofAperture; private readonly liveOpacityRangeValues; private readonly liveOpacityRanges; private readonly liveOpacityCount; private readonly liveOpacitySlices; private displayColorModifierValue; private readonly srgbOutput; private readonly sortMetric; private readonly projectionStrategyValue; private readonly projectionStrategyState; private sourceMaxStdDev; private sourceAntialias; private sourceProjectedFilterProfile; private overflowedSourceCount; private overflowedSplatCount; private unifiedPublicationVersion; private readyPublicationVersion; private readyPublication; private queuedPublicationVersion; private renderedPublicationVersion; private unifiedContentRevision; private unifiedOrderRevision; private readyPublicationContentRevision; private readyPublicationOrderRevision; private primaryPublicationCamera; private disposed; constructor(renderer: THREE.WebGPURenderer, capacity: number, options?: UnifiedSplatMeshOptions); /** Fixed work-buffer splat capacity chosen at construction. */ get capacity(): number; /** Requested projection strategy. */ get projectionStrategy(): SplatProjectionStrategy; /** Resolved unified projection path and its deliberate auto fallback reason. */ get projectionStrategyStatus(): Readonly<{ effective: 'vertex' | 'compute'; reason: string; }>; /** Strategy currently used by the draw (XR temporarily resolves to vertex). */ get effectiveProjectionStrategy(): 'vertex' | 'compute'; readGpuVisibleSplatCount(): Promise; /** Registers a source. The caller keeps ownership and may still query it. */ addSource(source: SplatMesh, options?: UnifiedSplatSourceOptions): void; /** * Invalidates one registered source's cached gather output. * * Required after changing modifier uniforms or channels when that source was * registered with `cacheModifiers: true`. The following {@link update} * re-gathers the source and re-sorts because modifiers may move splats. * Returns `false` when the source is not registered. */ invalidateSource(source: SplatMesh): boolean; /** * Opts a registered source into or out of {@link UnifiedSplatSourceOptions.cacheModifiers}. * * Enabling keeps the current gather until the next invalidation. Disabling * clears it so live uniforms (lights, fog, camera-dependent edits) re-gather * on the following {@link update}. Returns `false` when the source is not * registered. */ setSourceCacheModifiers(source: SplatMesh, cacheModifiers: boolean): boolean; /** * Atomically updates the supported cache behavior for an existing source. * * Hosts use this instead of removing and re-adding a source, which would * change its stable sort order, visibility, and pick ownership. */ setSourceCachePolicy(source: SplatMesh, policy: Pick): boolean; /** Number of whole sources omitted in the most recent update due to capacity. */ get droppedSourceCount(): number; /** Number of active splats omitted in the most recent update due to capacity. */ get droppedSplatCount(): number; /** * Sets whole-source display opacity without rebuilding the gather pipeline. * * This scales the completed fragment after RAD merged-vs-leaf classification * and falloff. It must never alter LOD selection or splat shape; hosts such as * marker crossfades rely on that. Values `<= 0` skip drawing the source. */ setSourceOpacity(source: SplatMesh, opacity: number): void; /** Shows or hides a source without changing its residency. */ setSourceVisible(source: SplatMesh, visible: boolean): void; /** * Core projected-2D depth of field on the unified draw pass (not gather). * Live uniforms - no gather-cache invalidation. Pass `aperture: 0` to disable. */ setDepthOfField(settings: Partial): void; /** Current core DoF uniforms (`aperture === 0` means off). */ getDepthOfField(): DepthOfFieldSettings; /** * Optional RGB transform in the unified display draw. Replacing the callback * rebuilds the draw material only; gathered source data stays valid. */ get displayColorModifier(): DisplayColorModifier | null; set displayColorModifier(modifier: DisplayColorModifier | null); /** * Asynchronously picks the frontmost visible splat under an NDC coordinate * across every registered source. * * Semantics: each source that is * currently visible in this unified renderer runs its own depth-tested GPU * pick pass; the hit nearest the camera wins and the result names its source * mesh. Hidden sources (`setSourceVisible(source, false)`) never hit. A hit * whose source was removed, hidden, or disposed while its readback was in * flight is dropped rather than misattributed. Resolves `null` for misses, * an empty source list, and picks pending across {@link dispose}. * * Uses the construction renderer. Concurrent calls are safe: each source * serializes its own picks and shared renderer state is restored * synchronously before any await. */ pick(ndc: THREE.Vector2, camera: THREE.Camera, options?: SplatPickOptions): Promise; private pickAdmission; /** * Unregisters a source. Its standalone draw comes back once no other * unified mesh draws it. */ removeSource(source: SplatMesh): boolean; /** Updates source LODs, gathers their active splats, then globally sorts them. */ update(camera: THREE.PerspectiveCamera): void; /** Returns the last unified gather/sort CPU submission timings. */ get performanceTimings(): Readonly; /** * Reports whether a primary draw rendered the current gathered content with * its matching sort publication. Positive instanceCount alone is not enough: * compute projection intentionally exposes work-buffer capacity there. */ getDrawPublicationSnapshot(): UnifiedDrawPublicationSnapshot; /** * Re-sorts and draws this unified source list for a secondary camera. * Mirrors and portals use this instead of rendering the hidden source meshes * individually, so their reflection keeps one global transparent order. * * @param _options - Accepted for signature parity with * `SplatMesh.renderView`. `reuseShColor` has no effect here: source SH * caches are not used on the unified path. */ renderView(camera: THREE.PerspectiveCamera, renderer: THREE.WebGPURenderer, target?: THREE.RenderTarget | null, _options?: { reuseShColor?: boolean; }): void; private prepare; private publicationCanDraw; onAfterRender(_renderer: WebGLRenderer, _scene: THREE.Scene, _camera: THREE.Camera): void; dispose(): void; private hasGpuCompletionQueue; /** Starts the GPU-completion watch for a sort that has already been submitted. */ private acknowledgeSortSubmission; /** * Whether a held frame may re-gather this source in place: it moved (world * matrix or sort displacement, such as a skin pose) since its last gather, * and nothing about its slots changed, so the queued order still indexes * the same splats. A new cut, content, graph, slot or size keeps holding as * before: drawing it through the old permutation is the stale-scatter * flash the gate exists to prevent. Compute projection draws from projected * centers, which a gather does not refresh, so it keeps holding too. Static * sources (a scan main) never move, so the hold keeps saving their gathers. */ private canRegatherHeldInPlace; private recordGatheredPose; /** * Compute projection draws from cached clip-space centers and axes (the * shared material returns them whenever `projected` buffers are bound), so * a camera move cannot wait out a held gate the way a vertex-path sort can, * where only the blend order lags a frame. Dropping it draws the previous * pose under the new camera until the gate releases, and on a real adapter * the acknowledged `onSubmittedWorkDone` often lands after the next frame's * update, so every such frame rendered one pose behind. The caller keeps * coalescing content changes (new, changed or re-gathered sources), so the * replacement projection and sort read the same work buffer as the queued * pass and simply supersede it; the gate is re-marked so it follows the * newer dispatch. A stationary camera dispatches nothing. * * Like the standalone path, the re-projection follows the adaptive sort * cadence rather than every held frame: a free frame always re-projects a * moved camera, so once the fence outlasts a frame this path sets the * dispatch rate, and at large admitted totals a per-frame replacement * projection plus counting sort misses vsync. A skipped held frame draws * one pose behind until the gate releases or the cadence is due. */ private reprojectWhileHeld; /** * Draw through a GPU-sorted order, not the identity fill of `order`. * Hosts without `onSubmittedWorkDone` (unit mocks) still publish `offset` * on the submitting frame so tests that run a single `update()` stay valid. */ private publishOrderedInstanceCount; /** * Whether any input consumed by the compute projector or its sort differs * from the last dispatch. `view` is the sort camera's inverse world matrix * (the unified work buffer already holds world-space centers). */ private projectedPoseChanged; /** Captures every input consumed by the compute projector just dispatched. */ private recordProjectedPose; /** Makes the next compute-projection preparation dispatch unconditionally. */ private invalidateProjectedPose; private setComputeProjectionActive; /** Opacity the gather bakes into `centers.w` for this source (see `live-opacity.ts`). */ private gatherOpacityOf; /** * Refreshes the draw's live-opacity ranges from the *drawn* layout and each * slice's gathered opacity. Runs every prepare, held or not, so fades advance * every frame instead of only when a gather lands. */ private updateLiveOpacity; private assertNotDisposed; /** Rebuilds the EWA draw material after a display-graph structural change. */ private rebuildDrawMaterial; private createGather; private buildGather; }