/** * Device profiling and the default active-splat budget. * * Streaming is splat-count budgeted rather than byte budgeted: every cost in * the renderer (pool textures, sort buffers) scales with the number of * resident splats - roughly 64 bytes of GPU memory per splat (three RGBA32F * data textures + one RGBA8, plus the sort index/order/bucket buffers), or * about 48 bytes when `poolFloatTextures: 'float16'` halves centers and * covarianceA; plus about 52 more bytes of CPU-side backing per splat of * pool capacity. Capping the active splat count therefore caps memory * directly, which is what matters on mobile GPUs. */ import type { StreamedSplatFormat } from '../loaders/loading'; import type { SplatSortStrategy } from './splat-mesh-types'; /** * Desktop GPU capability class for budget / quality defaults. * * Mobile still keys off {@link SplatDeviceProfile.isMobile}; this splits * non-mobile machines that would otherwise share the ~8M workstation path. * Unset means "unknown" - keep the pre-existing desktop defaults (fail open). */ export type SplatGpuClass = 'discrete' | 'integrated' | 'fallback'; /** Browser/device signals used for deterministic budget selection. */ export interface SplatDeviceProfile { /** Coarse memory estimate in GiB, when exposed by the browser. */ deviceMemoryGb?: number; /** Whether the runtime is an iOS/iPadOS-class device. */ isIOS?: boolean; /** Whether the runtime is a phone/tablet-class device (includes iOS). */ isMobile?: boolean; /** * Whether the runtime is a standalone XR headset browser (Quest, Pico, …). * Headsets are mobile-class GPUs asked to fill a stereo framebuffer larger * than a 4K desktop, so they get their own, tighter defaults. */ isHeadset?: boolean; /** * Whether this is a *budget* phone rather than a flagship one. * * `isMobile` cannot tell a Galaxy A51 from an iPhone 15 Pro, and the memory * signal cannot either - Chrome privacy-caps `deviceMemory` at 8 GiB, so the * flagship and the mid-ranger both land on the same ceiling despite an order * of magnitude between their GPUs. A coarse signal, and a *downward* one: a * reading of ≤4 is trustworthy because the cap only ever lowers it, while a * reading of 8 says nothing. {@link hasWebGpu} is the sharper signal where it * applies, since it names a difference in how the sort runs rather than * guessing capability from RAM. */ isLowPower?: boolean; /** * Whether the runtime exposes WebGPU at all. * * `false` means the renderer will take the WebGL2 fallback, where the depth * sort runs on the CPU rather than as a GPU compute pass - a different cost * curve, not just a slower one. See {@link resolveSplatBudget}. * * Detected from the presence of `navigator.gpu`, which is a *browser support* * signal rather than an adapter one: a runtime that exposes the API but whose * `requestAdapter` fails (driver blocklist) still reports `true` here and will * fall back to WebGL2 anyway. A host that knows its renderer's real backend * can correct this by passing its own profile. */ hasWebGpu?: boolean; /** * Desktop GPU class from {@link probeSplatGpuClass} / {@link classifySplatGpuClass}. * Omit when unknown so workstations without adapter info keep the 8M path. */ gpuClass?: SplatGpuClass; } /** Adapter identifying fields used by {@link classifySplatGpuClass}. */ export interface SplatGpuAdapterInfo { vendor?: string; architecture?: string; device?: string; description?: string; isFallbackAdapter?: boolean; } /** * How expensive a format's splats are *per splat*, which is not the same across * formats and is the reason one mobile budget cannot serve them all. * * - `'sampled'` - coarser LOD levels are subsamples of the same surface, so a * splat costs about the same however deep the cut is. Streamed SOG. * - `'lcc'` - XGRIDS' levels are decimated *alternatives* whose splats merge * into wide flat discs (see {@link liftBudgetToFinestLevel}). Cost per splat * therefore *rises* as the budget falls, because a tighter budget serves * coarser levels and each of their splats covers more pixels. `.rad`, `.lcc`, * `.lcc2`. * * Measured on one iPhone 15 Pro, which is what the numbers below are worth: * `oldtimers-route` (`.rad`) ran 31-39 fps at 750k and 45-50 at 600k, while * `sandwijck` (streamed SOG) held 52-57 fps at 675k resident. Two streamed * scenes, near-identical splat counts, ~20 fps apart - splat count is a poor * proxy for cost, and the format is the only better signal available for free * before a single byte is fetched. */ export type SplatCostClass = 'lcc' | 'sampled'; /** * Classifies a WebGPU adapter from its identifying strings. * * Heuristics only - browsers may blank fields for privacy. Prefer * {@link probeSplatGpuClass} when both power-preference adapters are available. */ export declare function classifySplatGpuClass(info: SplatGpuAdapterInfo | undefined): SplatGpuClass; /** Minimal `navigator.gpu` surface for {@link probeSplatGpuClass}. */ export interface SplatGpuProbeEntry { requestAdapter(options?: { powerPreference?: 'low-power' | 'high-performance'; }): Promise; } /** Adapter handle with optional `.info` (WebGPU GPUAdapterInfo). */ export interface SplatGpuProbeAdapter { readonly info?: SplatGpuAdapterInfo; } /** * Probes WebGPU adapters to choose a {@link SplatGpuClass}. * * Requests both `low-power` and `high-performance` adapters when possible. A * hybrid laptop that exposes two different devices is `discrete`; a single * shared / unified GPU (Apple Silicon, many iGPU-only machines) is classified * from {@link classifySplatGpuClass}. Returns `undefined` when WebGPU is absent * or the probe fails, so budget resolution keeps the legacy desktop path. */ export declare function probeSplatGpuClass(gpu?: SplatGpuProbeEntry | null | undefined): Promise; /** * Whether fill-rate / laptop-class defaults apply (mobile, or desktop * integrated / software fallback). Exported so hosts and the demo share one * predicate for performance-mode defaults and adaptive DPR. */ export declare function isFillConstrainedSplatDevice(profile?: SplatDeviceProfile | undefined): boolean; /** * Pool capacity as a multiple of the resident ceiling for a streamed mesh. * * Indexed page-table needs two complete selections in reserved storage (2×). * Staged swaps keep the outgoing LOD set resident until the incoming one is * staged, so a large view change peaks near 1.5× the budget. On a discrete * desktop GPU 1.75× leaves room for that overlap plus row fragmentation; at * 1.5× the pool fills and every such swap compacts it. Every other device * (phones, headsets, integrated GPUs sharing system memory, and a GPU whose * class was never probed) keeps 1.5×; pass a `deviceProfile` with * `gpuClass: 'discrete'` to opt in. Without staged swaps the slack only * absorbs row-alignment waste (1.4×). */ export declare function streamedPoolCapacityFactor(options: { pageTable: boolean; stagedSwaps: boolean; profile?: SplatDeviceProfile | undefined; }): number; /** Reads the available browser device signals without requiring a DOM runtime. */ export declare function detectSplatDeviceProfile(): SplatDeviceProfile | undefined; /** Scene-side signals for {@link resolveSplatBudget}. */ export interface SplatBudgetOptions { /** * The format about to be loaded, which selects the {@link SplatCostClass} * whose mobile tier applies. Omit when it is not yet known - the `'sampled'` * numbers are what every caller resolved before cost classes existed. */ format?: StreamedSplatFormat; /** * A ceiling on the resolved default, for callers that want to tighten without * overriding what this function knows. * * `override` is absolute: it wins over the device tier, the cost class and * everything else, because a caller who names a number has said they know * better. That is the right contract and the wrong tool for "the same as * usual, but no more than N" - which is what a performance toggle or a host * default actually means. Pinning a number there has twice shipped as a bug: * a demo performance mode that *raised* the load on the weakest device tested, * and a host default that bypassed every device tier. * * Applied only when `override` is omitted, and only downward. */ cap?: number; } /** * Chooses a default active-splat budget for the current device. * * The default is derived from the coarsest device-memory signal the platform * exposes; callers who know better (or want a hard cap for a mobile test on * desktop) should pass an explicit override. * * @param override - Explicit budget in splats; wins over device detection when * positive. Throws `RangeError` if it is not a positive finite number. * @param profile - Device signals to decide from; defaults to detecting them. * @param options - Scene signals. `format` selects the {@link SplatCostClass} * whose mobile tier applies; omitting it keeps the `'sampled'` numbers, which * are what every caller resolved before cost classes existed. `cap` is a * ceiling on the *resolved default*, for callers who want to tighten without * overriding - see {@link SplatBudgetOptions.cap}. * @returns A splat-count budget, clamped to a sensible range. */ export declare function resolveSplatBudget(override?: number, profile?: SplatDeviceProfile | undefined, options?: SplatBudgetOptions): number; /** * The budget to run at **while an immersive session presents**, given whatever * budget the page is using outside one. * * Stereo is the cost, and stereo is a property of the *session*, not of the * device: every splat is drawn twice, into two eye viewports that together * exceed a 4K desktop, on a GPU that must hold 72–90 Hz or the compositor * reprojects. That is true of a standalone headset and equally true of a * desktop machine driving a tethered one - which is exactly the case device * sniffing cannot see, since such a machine is a desktop right up until the * moment it is not. * * Keying off presentation instead of identity is also the only approach that * survives new hardware. `detectSplatDeviceProfile`'s `isHeadset` is a * user-agent guess: it misses Apple Vision Pro outright (visionOS Safari * presents as desktop Safari, so a headset would otherwise take the multi- * million desktop budget) and misses every headset released after it is * written. This function needs to know none of that. * * Apply it on `sessionstart` and restore the original on `sessionend` - via * `BudgetGovernor.setBudget` when several meshes share a pool, or a streamed * mesh's own budget setter otherwise. * * @param pageBudget - The budget in use outside the session, typically from * {@link resolveSplatBudget}. Throws `RangeError` if not a positive finite * number. * @returns `pageBudget` lowered to the stereo ceiling; never raised - a device * already rendering below the ceiling stays where it is. */ export declare function resolveXrSplatBudget(pageBudget: number): number; /** * Raises `budget` far enough to hold a scene's finest level in full, when * that level is small enough to be worth taking whole. * * The LOD budget assumes coarser levels are cheap *approximations* of the * same surface, so trading detail for memory is nearly free. XGRIDS' LCC * LCC breaks that assumption: its five levels are decimated alternatives * whose splats merge into wide flat discs (correct at distance, streaked up * close), so any budget shortfall costs visible quality - sub-chunking gives * the scheduler ~128k-splat granularity to thin cells with, but a thinned * fine level is still sparser than the capture intends. A capture whose * finest level fits under the desktop ceiling is better shown whole: Casino's * level 0 is 4.74M splats and sits under the 8M default. * * Mobile and fill-constrained desktops (integrated / fallback GPU class) are * exempt: their cap is a fill-rate limit, not a sizing accident. * * @param budget - The resolved device budget. * @param finestLevelSplats - Splats in the scene's finest level. * @returns `budget`, or the finest level's size when that is the better fit. */ export declare function liftBudgetToFinestLevel(budget: number, finestLevelSplats: number, profile?: SplatDeviceProfile | undefined): number; /** Options for {@link estimateSplatPoolBytes}. */ export interface SplatPoolBytesOptions { /** * Pool texture precision, matching `SplatMeshOptions.poolFloatTextures`. * `'float16'` halves centers and covarianceA. Default `'float32'`. */ floatTextures?: 'float32' | 'float16'; /** Per-splat SH bands the pool allocates for. Default `0`. */ shBands?: 0 | 1 | 2 | 3; /** * Sorter allocation to include. Defaults to the production `'counting'` * path; `'worker'` includes the worker's retained mirrors and scratch. */ sortStrategy?: SplatSortStrategy; /** * Pool capacity as a multiple of `splats`. `StreamedSplatMesh` allocates * 1.5× (the default here) so per-run row alignment and the * append-before-remove window during LOD swaps have somewhere to go; pass * `1.4` to model `experimentalStagedSwaps: false`, or `1` for a static mesh. */ capacityFactor?: number; /** * Whether to include the CPU-side backing arrays. Default `true` - they are * real host memory a device has to find, so the honest answer to "can I * afford this ceiling" includes them. */ includeCpuBacking?: boolean; } /** * Estimates the memory a splat pool of `splats` costs. * * This exists to make a streamed mesh's `maxBudget` a computation rather than a * guess. A pool is allocated **once, from the ceiling** and never * grows, so several governed meshes cost the sum of their ceilings whatever the * shared budget is set to - a `BudgetGovernor` redistributes *sharpness* within * that envelope, it does not shrink it. Price the ceilings before choosing them: * * ```js * // 1 main + 4 additional meshes, each able to reach 1.5M splats * const bytes = estimateSplatPoolBytes(4_000_000) + 4 * estimateSplatPoolBytes(1_500_000); * ``` * * Per splat of *capacity* (`splats × capacityFactor`), counted from what the * constructor actually allocates: * * - **Pool textures** 52 B - centers RGBA32F 16, colors RGBA8 4, * covarianceA RGBA32F 16, covarianceB RGBA32F 16. `'float16'` drops centers * and covarianceA to 8 each (36 B); covarianceB stays float32 because it * packs integer IDs. * - **Packed SH** 16 B per `RGBA32UI` texture, `ceil(coefficients / 4)` of them * - so 16 / 32 / 64 B at 1 / 2 / 3 bands. * - **Sort storage** follows `sortStrategy`: counting allocates a source and * draw index plus a capacity-sized bucket buffer, while radix adds its * key/value ping-pong, histogram and masks. The CPU worker includes its * independent center mirror and retained radix scratch. * - **CPU backing** 68 B - the float32/uint8 arrays kept for partial uploads * (always full precision, even under `'float16'`): centers 16, colors 4, * covarianceA 16, covarianceB 16, plus four u32-per-splat arrays - draw-order * indices, the active-list source index, the pool-slot map, and the picker's * pool-index template (allocated lazily, counted because a picked scene pays * it). Under `'float16'` add a further 16 B: the half-encoded texture images * are held alongside the float32 backing, not instead of it, so that * precision saves GPU bytes only. Included unless `includeCpuBacking` is * `false`. * * The module header's "roughly 64 bytes per splat" rounds the GPU side of this. * * @param splats - The ceiling in splats (e.g. a mesh's `maxBudget`). * @returns Estimated bytes. Indicative, not a device-memory guarantee: driver * texture/driver overhead, transient decoded caches and unified work buffers * sit outside it. CPU values include conservative initialization mirrors. * @throws {RangeError} if `splats` is not a positive finite number, or * `capacityFactor` is not a finite number `>= 1`. */ export declare function estimateSplatPoolBytes(splats: number, options?: SplatPoolBytesOptions): number; /** * Suggested ceiling for the renderer's pixel ratio on this device. * * Splat rendering is fragment-bound, so render resolution is one of the * largest costs on a high-DPI phone: a 2.6x display renders ~7x the pixels of * a 1x one, and every one of them blends the full depth-sorted splat stack. * The library cannot apply this itself (it draws into a renderer the app * owns), so it exports the policy - pass it to `renderer.setPixelRatio`: * * ```js * renderer.setPixelRatio(Math.min(window.devicePixelRatio, recommendedMaxPixelRatio())); * ``` * * This is the *quality* ceiling. Viewers that offer a performance mode * (SuperSplat halves mobile resolution in its own) should go lower still when * it is on. */ export declare function recommendedMaxPixelRatio(profile?: SplatDeviceProfile | undefined): number; /** * The Gaussian cutoff a `.rad` renders at, in standard deviations, or * `undefined` to accept the device-wide default. * * Spark hard-codes `sqrt(8)` (≈2.83σ) for every device, and matching it is what * makes a `.rad` look like Spark's render on a desktop. On a phone it is the * wrong trade: rendering is fill-bound on mobile, so a format override bypasses * the device policy that every other format accepts. * * Returning `undefined` on mobile lets `SplatMesh` apply its own 3σ cutoff and * undersized-splat floor; `.rad` must not escape that mobile policy. * * @returns √8 on discrete desktop; `undefined` on fill-constrained devices, * meaning "no format override". */ export declare function recommendedRadMaxStdDev(profile?: SplatDeviceProfile | undefined): number | undefined; /** * Suggested WebXR framebuffer scale for this device. On three 0.185.x this is * a **WebGL XR** policy: apply it once before the session starts with * `renderer.xr.setFramebufferScaleFactor`. three's WebGPU XR path creates its * `XRGPUBinding` projection layer at native scale and does not consume that * setting, so WebGPU hosts should leave the native scale and use the presenting * splat budget plus fixed foveation for runtime headroom instead. * * Splat rendering is fill-bound, and a headset's default framebuffer is * already supersampled past its panels (~1680×1760 per eye on Quest 3): * 0.8 cuts fragment work ~36% for a barely visible softening. Non-headset * XR (desktop-tethered) keeps the native 1.0. */ export declare function recommendedXrFramebufferScale(profile?: SplatDeviceProfile | undefined): number; /** * Host-threaded samples to ignore before the EMA starts. * * First `renderer.compute` and first `copyTextureToTexture` each compile a * WebGPU pipeline (~200 ms). Seeding the EMA from those drops the ratio to * the floor, and a 60 Hz display's 16.7–16.8 ms cadence now clears the raise * bar (`targetFrameMs * 0.95` ≈ 17.1 ms). Pass the * returned {@link AdaptivePixelRatioResult.warmupRemaining} back each frame. */ export declare const ADAPTIVE_PIXEL_RATIO_WARMUP_FRAMES = 5; /** Inputs for {@link suggestAdaptivePixelRatio}. */ export interface AdaptivePixelRatioInput { /** Latest wall-frame time in milliseconds. */ frameMs: number; /** Currently applied pixel ratio. */ current: number; /** Quality ceiling (typically {@link recommendedMaxPixelRatio}). */ max: number; /** Floor; defaults to `1`. */ min?: number; /** EMA of frame time from the previous call; omit before the first sample. */ emaMs?: number; /** * Samples still ignored before the EMA starts. Omit or `0` to start * immediately. Thread the result's `warmupRemaining` when using * {@link ADAPTIVE_PIXEL_RATIO_WARMUP_FRAMES}. */ warmupRemaining?: number; /** * Comfortable frame time (ms). Below this (with headroom) the helper may * step the ratio up. Default `18` (~55 fps). */ targetFrameMs?: number; /** * Sustained frame time (ms) that triggers a step down. Default `22` * (~45 fps) so brief spikes do not thrash the canvas size. */ pressureFrameMs?: number; } /** Result of {@link suggestAdaptivePixelRatio}. */ export interface AdaptivePixelRatioResult { /** Suggested pixel ratio after hysteresis (quarter steps). */ pixelRatio: number; /** Updated EMA to pass back on the next call. Unset while warming up. */ emaMs: number | undefined; /** Remaining warmup samples; pass back as `warmupRemaining`. */ warmupRemaining: number; } /** * Suggests a pixel ratio under frame-time pressure. * * The library cannot call `renderer.setPixelRatio` (the host owns the * renderer); this is a pure policy helper. Pass the previous result's * `emaMs` and `warmupRemaining` each frame, and only re-size the canvas when * `pixelRatio` changes. * * Steps are quarter-units with asymmetric thresholds (pressure to lower, * comfortable headroom to raise) so the ratio does not oscillate. The host * should gate lower suggestions behind a short continuous-pressure dwell and * must not apply every upward suggestion. Gate a higher ratio behind two * seconds of healthy active time, a five-second probation, and failed-probe * backoff; this helper only returns the raw per-frame suggestion. * After warm-up, an undefined EMA is seeded from `targetFrameMs` before the * first sample is incorporated. This limits the influence of a startup hitch * while retaining the normal 0.15 response to real sustained load. One-off * hitches (pipeline compiles, tab resume) that are * several times the EMA do not count as pressure. * * Timers for pressure, recovery, probation, and retry backoff must advance only * while rendering is visible and active. Neutral jitter should decay recovery * time instead of clearing it. See the `fast-on-phones` example for the complete * host controller. */ export declare function suggestAdaptivePixelRatio(input: AdaptivePixelRatioInput): AdaptivePixelRatioResult; /** * Chooses a decoded-chunk CPU cache cap from the same safe device profile. * * **The unknown-memory fallback must not read as "tiny".** iOS Safari does not * implement `navigator.deviceMemory` at all, so every iPhone lands on this * branch - and an earlier version resolved it to 1 GiB, i.e. the 32 MiB floor, * on hardware with 8 GiB. That is not a conservative guess, it is a wrong one, * and it is invisible on `.rad`, whose page-table cache has its own floor. * * On streamed SOG there is no such floor and the cost is immediate: measured on * an iPhone 15 Pro against `sandwijck`, the scheduler asked for 539,734 splats * and the mesh could only hold 466,499 of them across 3 chunk files (desktop: * 5), evicting continuously. The finest level is wanted *nearest the camera* and * lives in the largest files, so those are what fail to stay resident - the * middle of the view drops out and the scene renders as a donut. * * A device that declines to report its memory is far likelier to be a modern * phone withholding a fingerprinting signal than an actual 1 GiB device, so the * fallback assumes 4 GiB (128 MiB of cache). The floor stays for the genuinely * profile-less case - SSR and Node tooling, which never stream a scene anyway. */ export declare function resolveCpuCacheBytes(profile?: SplatDeviceProfile | undefined): number;