import * as THREE from 'three/webgpu'; import type { LodManifest } from './lod-manifest'; import type { LodSource } from './lod-source'; /** * A contiguous splat range within one chunk file, at one LOD level - the * unit the pool activates. Adjacent manifest leaves that resolve to the same * `(file, level)` and whose ranges abut are coalesced into one run, so the * pool sees a handful of large ranges instead of thousands of tiny leaves. */ export interface LodRun { readonly file: number; readonly level: number; readonly offset: number; readonly count: number; /** First manifest-leaf index this run covers. */ readonly leafStart: number; /** One past the last covered leaf index. */ readonly leafEnd: number; /** * Physical-coverage identity when several manifest leaves form one region. * A classic LCC cell may be split into fetch-sized leaves, but its slices * must still swap as one visible unit. Undefined retains interval-based * grouping for hierarchical sources. */ readonly coverageGroup?: number; /** * Camera distance (mesh-local) of the nearest leaf in this run, from the * last {@link LodScheduler.computeDesiredRuns} pass. Streamed meshes use it * to fetch near detail before far coarse coverage. Absent on sources that * do not track per-leaf distance. */ readonly distance?: number; /** * True when any leaf in this run intersects the view frustum (with the * scheduler's edge margin). Used to rank classic-path fetches so in-view * detail beats behind-camera work; absent when the source does not track it. */ readonly inView?: boolean; /** * Fetch-only angular distance from the camera's forward axis. Smaller values * are nearer the screen centre. It never affects LOD selection or budget. */ readonly screenImportance?: number; /** * True when this run only exists to keep a not-yet-decoded chunk in the * fetch pipe. Prefix-reader `.rad` appends these ahead of the resident * frontier; they are not part of the drawable cut and never block publishing * that cut when their speculative fetch does not land. */ readonly fetchIntent?: boolean; } /** Stable identity of a run, for diffing desired vs. resident sets. */ export declare function runKey(run: LodRun): string; /** * Chooses a level of detail per spatial leaf from the camera, keeps the * total within a splat budget, and coalesces the result into runs. * * The scheduler is pure with respect to rendering: it takes a camera * position and frustum (both in the mesh's local space) and returns the set * of runs that should be resident. It owns only the small amount of state * needed for temporal stability (each leaf's current level and when it last * changed), so it is straightforward to drive from a test harness. * * LOD distance model (PlayCanvas-compatible): level 0 is used within * `lodBaseDistance`; each successive level covers a band `lodMultiplier`× * farther out. By default out-of-frustum leaves act {@link FRUSTUM_PENALTY}× * farther away. Formats with broad spatial cells can disable that bias so an * orbit does not churn already-refined cells at the frustum edges. * * The distance model only sets the *floor* and the *priority*: when the * distance-chosen set leaves budget unused, {@link fillBudget} promotes * in-frustum leaves nearest-first until its configured headroom target is * spent (90% by default). Formats can cap that optional refinement and avoid * a full-finest cut even when an explicitly large budget could hold it. The * budget * therefore decides how far refinement reaches - a desktop budget yields * full detail even with the whole scene in view, a mobile budget refines * only near the camera. */ export declare class LodScheduler implements LodSource { /** World-unit distance inside which the finest level (0) is used. */ lodBaseDistance: number; /** Distance ratio between successive LOD levels. */ lodMultiplier: number; /** Maximum active splats; the desired set is demoted to fit. */ budget: number; private readonly leaves; private readonly coarsest; /** Per leaf: lowest/highest LOD level that has data. */ private readonly minLevel; private readonly maxLevel; /** * Per leaf: the distance *ambition* - the finest level the camera distance * asks for, with hysteresis/dwell applied. This is the hysteresis *state*: * only {@link selectLevels} writes it, so budget demotion can never feed * back into the dead-band/dwell logic and oscillate. With `fillPastDistance` * false, {@link fillBudget} restores {@link resolved} only up to here. */ private readonly level; /** * Per leaf: the resolved target - the ambition capped to fit the budget by * {@link enforceBudget}, then refilled from leftover headroom by * {@link fillBudget} (or DROPPED). This is what {@link coalesceRuns} emits. */ private readonly resolved; /** Per leaf: timestamp of the last distance-level change, for dwell. */ private readonly changedAt; private readonly distance; private readonly inFrustum; /** Leaves that must move through the budget cut together. */ private readonly budgetGroups; /** Per-leaf physical coverage group, when the manifest defines one. */ private readonly coverageGroups; /** Whether view-frustum membership affects distance and fill priority. */ private readonly frustumAware; /** Fraction of the usable budget that optional refinement may consume. */ private readonly budgetFillFraction; /** Absolute cap on optional refinement; distance-selected detail may exceed it. */ private readonly budgetFillCap; /** Whether a budget that holds every finest leaf forces a full-finest cut. */ private readonly forceFinestWhenFits; /** * Leaves at or inside this camera distance always resolve to their finest * available level (no hysteresis climb). Classic LCC uses a multi-band * radius so adjacent broad cells do not paint coarse discs at startup. */ private readonly forceFinestWithin; /** * When false, {@link fillBudget} only restores toward each leaf's * distance-selected {@link level} - never finer. Classic LCC sets this so * a mid-range cell does not fetch L0 only to demote to L1 once the cut * settles. */ private readonly fillPastDistance; /** * What the last cut actually decided, for the HUD. * * The resident splat count alone cannot distinguish "the scheduler asked for * this" from "the scheduler asked for more and the mesh could not apply it", * and those have opposite fixes. Measured rather than inferred after a * zoomed-out `sandwijck` sat at exactly its coarsest total (190,730) with a * 600k budget - 68% of the budget unspent, with no way to see which stage * declined to spend it. */ readonly stats: { /** Leaves the frustum test accepted - `fillBudget`'s candidate set. */ inFrustum: number; /** Total leaves in the tree. */ leaves: number; /** Splats implied by the resolved cut, before the mesh applies anything. */ desired: number; /** Splats `fillBudget` added on top of the distance-chosen levels. */ filled: number; }; private readonly scratchBox; private readonly scratchSize; private readonly scratchCenter; private readonly screenImportance; /** Whether the last selection pass received a camera-forward vector. */ private hasScreenImportance; /** * Persistent leaf-index ordering scratch for {@link enforceBudget} and * {@link fillBudget}, sorted in place per call instead of allocating a * fresh `[...keys]` array. Comparators break ties on the index itself so * the order is identical to the stable `Array#sort` this replaces * (`TypedArray#sort` stability is not guaranteed). */ private readonly orderScratch; constructor(manifest: LodManifest, options: { budget: number; lodBaseDistance: number; lodMultiplier: number; frustumAware?: boolean; budgetFillFraction?: number; budgetFillCap?: number; forceFinestWhenFits?: boolean; forceFinestWithin?: number; /** * When false, leftover-budget fill never refines past the distance- * selected level (see {@link fillPastDistance}). Default true. */ fillPastDistance?: boolean; }); /** * Recomputes the desired resident run set for the current camera. * * @param cameraLocal - Camera position in the mesh's local space. * @param frustum - View frustum in the mesh's local space. * @param now - Monotonic timestamp (ms) for dwell hysteresis. */ computeDesiredRuns(cameraLocal: THREE.Vector3, frustum: THREE.Frustum, now: number, cameraForward?: THREE.Vector3): LodRun[]; /** Total active splats implied by the current resolved levels. */ private activeTotal; /** Splats if every leaf sat at its finest available level (none dropped). */ private finestTotal; private selectLevels; /** * Pure distance→level band (independent of the leaf's current level), so a * classic LCC cut never has to dwell through intermediate rungs. */ private distanceBandLevel; /** * Stable level from distance: coarsen only past `threshold·(1 + margin)`, * refine only within `threshold·(1 − margin)`. The available-level clamp * keeps leaves that lack a level on their nearest coarser one. */ private hysteresisLevel; private resolveAvailable; /** Demotes/drops lowest-priority leaves until the total fits the budget. */ private enforceBudget; /** * Uses leftover budget to restore detail after {@link enforceBudget} * demoted leaves, nearest first, while the total stays under the fill * target. By default this may also refine *past* the distance-chosen level * when headroom remains (octree / page-table streams). With * {@link fillPastDistance} false (classic LCC), fill never goes finer than * each leaf's distance-selected level - so a cell at the L1 band does not * fetch L0 only to demote moments later with the camera still. */ private fillBudget; private coalesceRuns; /** * Runs covering [from, to) at each leaf's coarsest available level - used * to substitute always-cached coverage while a finer level is fetching. */ coarsestRunsFor(from: number, to: number): LodRun[]; /** * Covering runs for physical coverage groups currently in the camera frustum * (or containing the camera). Classic LCC cells that split into sub-leaves * share a group, so one in-view slice holds the whole cell. Leaves without a * coverage group (Streamed SOG, the environment tile) are ignored. An empty * frustum falls back to the nearest group so a skyward start still paints * something. * * Classic cells tile X/Y and span the full scene Z. An AABB frustum test * (especially with {@link FRUSTUM_MARGIN} on that diagonal) then hits the * whole grid from any indoor pose. Unpadded intersection plus an AABB vs * forward half-space test (support vertex along `cameraForward`) keeps the * hold to cells that poke in front of the camera, including a neighbour * whose centre sits behind the look. Cells within `lodBaseDistance` that * poke forward are held even when the unpadded frustum misses — a 30 m * PentHouse column 5 m away can fill the frame while the look is 60° off * its face. * * Nearby groups (`distance ≤ lodBaseDistance · lodMultiplier`) freeze at * finest+1 (L1 when L0 exists). Farther in-view groups freeze at coarsest. * A view that includes multiple physical cells also holds every other cell * at coarsest when that floor is comfortably within budget. Otherwise the * first frame can claim complete coverage while large parts of a broad * scene are still absent. Single-cell views keep the camera-directed hold. * Startup never waits for L0. */ coverageRunsFor(cameraLocal: THREE.Vector3, frustum: THREE.Frustum, cameraForward?: THREE.Vector3): LodRun[]; /** * True when any point of `box` sits strictly in front of the camera plane * (`origin` + `forward`). Uses the AABB support vertex along `forward`, so a * cell that straddles the camera still counts if it pokes into the view. */ private boxPokesForward; /** Leaf AABB expanded by {@link FRUSTUM_MARGIN}, written into scratch. */ private expandLeafBox; private leafIntersectsFrustum; /** * Runs covering [from, to) at `level`, clamped per leaf to an available rung * (prefer the requested level, else the next coarser, else the next finer). */ runsAtLevelFor(from: number, to: number, level: number): LodRun[]; /** Prefer `wanted`, else next coarser, else next finer; {@link DROPPED} if none. */ private clampLeafLevel; /** Coalesces leaves [from, to) at `levelOf(leaf)` into contiguous runs. */ private buildRuns; }