diff --git a/Sources/CShaderTypes/ShaderTypes.h b/Sources/CShaderTypes/ShaderTypes.h index 9a2699940..fa664c75f 100644 --- a/Sources/CShaderTypes/ShaderTypes.h +++ b/Sources/CShaderTypes/ShaderTypes.h @@ -1098,7 +1098,13 @@ typedef struct{ uint32_t splatCount; uint32_t quota; float screenArea; -}GaussianVisibleChunk; // 16 bytes + /// 0 (near) to 1 (far), the smoothstep blend of the priority bands' caps this chunk draws + /// at (issue #1423): gaussianComputeChunkQuotas applies mix(densityCap, farDensityCap, + /// bandWeight) rather than picking one cap outright, so a chunk inside the transition zone + /// between nearPriorityDistance and nearPriorityDistance + priorityTransitionWidth degrades + /// gradually instead of snapping. Always 0 when distancePrioritizedBudget is off. + float bandWeight; +}GaussianVisibleChunk; // 20 bytes /// The smallest screen area a visible chunk is charged for: 2^-24 view units, a quarter of a /// pixel at 4K. A chunk no view keeps (GaussianDebugOptions.disableChunkCull) carries it and is @@ -1130,7 +1136,11 @@ typedef struct{ uint32_t paged; // 0: every record resident; 1: a paged entity (the cull writes the demand table and lists resident ranks only, the fused pass reads the page pool); 2: demand only (a warming tier: write the demand word and return) uint32_t rangeCount; // entries of ranges[] (gaussianChunkCullRangesIndex, GaussianChunkTreeCull); a thread whose chunkIndex falls in none of them skips the per-chunk test. 0 (GaussianDebugOptions.disableTreeSkip, or a file without a tree) skips the check entirely, as before the tree was wired in simd_float4 hzbRateMapSizes; // the rasterization rate map the HZB was drawn through (XR foveation): its screen size in xy, the pyramid's base size in zw; x <= 0 when there is none and the rate map buffer is a never-read placeholder -}GaussianChunkCullConstants; // 208 bytes (180 + hzbRateMapSizes at 192, padded to the struct's 16-byte alignment) + simd_float3 cameraPositionLocal; // 208: the frame's effective camera position (SceneRootTransform-corrected) transformed into this entity's local space — chunk AABBs are stored local, so the near/far split (issue #1423) compares like spaces; the inverse of the entity's model matrix, applied once per entity per frame on the CPU side rather than per chunk here + float nearPriorityDistance; // 224: GaussianPagingPolicy.nearPriorityDistanceInEffect — within this local-space distance of cameraPositionLocal a chunk's band weight is 0 (pure near); beyond nearPriorityDistance + priorityTransitionWidth it is 1 (pure far). Local and world distances agree only up to the entity's scale (identity/uniform scale: exactly; a non-uniformly scaled entity's local-space "distance" is distorted by that scaling, same caveat as every other local-space size in this file) + uint32_t distancePrioritizedBudget; // 228: GaussianPagingPolicy.distancePrioritizedBudget; 0 disables the band split so the cull bins every chunk as near (today's single uniform cap) + float priorityTransitionWidth; // 232: GaussianPagingPolicy.priorityTransitionWidthInEffect — local-space distance over which a chunk's band weight smoothsteps from 0 to 1, starting at nearPriorityDistance; 0 (or distancePrioritizedBudget off) reproduces the original hard near/far cutoff (smoothstep's edges coincide, so it degenerates to a step) +}GaussianChunkCullConstants; // 240 bytes (236 + padding to the struct's 16-byte alignment) /// One span of GaussianChunkTreeCull.visibleChunkRanges (Swift): chunk indices [firstChunk, /// firstChunk + chunkCount) the tree walk could not rule out this frame. Every chunk still gets @@ -1159,6 +1169,7 @@ typedef enum{ gaussianChunkCullLevelConstantsIndex = 12, // GaussianChunkLevelConstants (setBytes); hasCoarse = 0 keeps every path as it was gaussianChunkCullRangesIndex = 13, // GaussianChunkCullRange[rangeCount] (setBytes; a never-read stand-in when rangeCount == 0) gaussianChunkCullRateMapDataIndex = 14, // rasterization_rate_map_data the HZB was drawn through (XR foveation; read only when hzbRateMapSizes.x > 0, a placeholder otherwise) + gaussianChunkCullFarDensityHistogramIndex = 15, // gaussianChunkCull: the far priority band's GaussianBudgetDensityHistogram (issue #1423), same layout as gaussianChunkCullDensityHistogramIndex; a chunk splits its contribution between this histogram and the near one by its smoothstep band weight (params.nearPriorityDistance .. + priorityTransitionWidth of params.cameraPositionLocal), weight 0 (all near) whenever params.distancePrioritizedBudget == 0 }GaussianChunkCullBufferIndices; typedef enum{ @@ -1190,7 +1201,7 @@ typedef struct{ uint32_t transitionSplats; // 32, atomic: Σ over the outgoing windows of fading chunks the culls listed this frame (inside requestedSplats; the solve fits the rest) uint32_t coarseChunks; // 36, atomic: incoming entries drawn at a coarse level this frame uint32_t coarseSplats; // 40, atomic: their quota sum - uint32_t _pad0; // 44 + float farDensityCap; // 44: the far priority band's density cap (issue #1423), solved against whatever room the near band's actual grant leaves of the frame's room; its own hysteresis, mirroring densityCap's. Equal to densityCap when distancePrioritizedBudget is off (every chunk bins near, the far histogram stays empty, this field is unread) }GaussianBudgetState; // 48 bytes /// Inputs of gaussianComputeBudgetScale. @@ -1206,8 +1217,9 @@ typedef struct{ float densityFloor; // 32: the level rule's density floor, maxSplatsPerPixel × viewport pixels (+inf when the knob is off) — the solve evaluates the rule at min(cap, floor) uint32_t tierShift1; // 36: half-octave tiers under a chunk's own density at which its level 1 is chosen, the maximum over the frame's entities with coarse levels (2 × (ratioLog2 − 1)) — the widest fine regime, so R(d) charges fine wherever any entity still draws fine uint32_t tierShift2; // 40: the same for level 2 - uint32_t _pad0; // 44 -}GaussianBudgetScaleConstants; // 48 bytes + uint32_t distancePrioritizedBudget; // 44: GaussianPagingPolicy.distancePrioritizedBudget (issue #1423); 0 gives the near band the whole room, exactly the solve before priority bands existed + float nearPriorityShare; // 48: GaussianPagingPolicy.nearPriorityShareInEffect — the near band's ceiling as a fraction of the room when distancePrioritizedBudget != 0 (room − near's actual grant is the far band's room, so far always keeps at least (1 − nearPriorityShare) of the room; near is thinned, not just protected, once its own demand exceeds its share) +}GaussianBudgetScaleConstants; // 52 bytes (every field a 4-byte scalar, no vector member to force 16-byte alignment) /// The density histogram the weighted quotas are solved from: how many half-octave tiers of /// splats per view unit of screen area, from 2^gaussianBudgetDensityTierLog2Floor upward @@ -1276,6 +1288,8 @@ typedef enum{ gaussianBudgetLevelConstantsIndex = 12, // gaussianComputeChunkQuotas: GaussianChunkLevelConstants (setBytes) gaussianBudgetChunkTableIndex = 13, // gaussianComputeChunkQuotas: GaussianChunkDecodeConstants[chunkCount], the fine rows (the chunk's full splat count) gaussianBudgetLevelTotalsIndex = 14, // gaussianComputeChunkQuotas: atomic_uint[3] at the state's byte offset 32: transitionSplats, coarseChunks, coarseSplats + gaussianBudgetFarDensityHistogramIndex = 15, // gaussianResetBudgetRequest, gaussianComputeBudgetScale, gaussianPublishBudgetState: the far priority band's GaussianBudgetDensityHistogram (issue #1423), persistent, same layout as gaussianBudgetDensityHistogramIndex + gaussianBudgetFarDensityReadbackIndex = 16, // gaussianPublishBudgetState: this frame slot's copy of the far histogram }GaussianBudgetBufferIndices; // MARK: - Paged .untoldgs entities (GaussianPageManager.swift) diff --git a/Sources/UntoldEngine/RuntimeAssets/GaussianPagingPolicy.swift b/Sources/UntoldEngine/RuntimeAssets/GaussianPagingPolicy.swift index 47fec6a0a..e717ac025 100644 --- a/Sources/UntoldEngine/RuntimeAssets/GaussianPagingPolicy.swift +++ b/Sources/UntoldEngine/RuntimeAssets/GaussianPagingPolicy.swift @@ -61,6 +61,30 @@ public enum GaussianPagingPolicy { /// none. The coarse records live outside the pool, in their own buffer charged to the ledger. public static let coarseBudgetFraction = 0.2 + /// The default camera distance, in world units, under which a chunk falls in the near + /// priority band of the distance-prioritized budget solve (issue #1423): scene-scale + /// dependent (see `maxDistances` examples in docs/API/UsingGaussianSystem.md, 5–25 units for + /// a small asset), so most scenes should set `nearPriorityDistanceOverride` to a figure that + /// matches their own content rather than rely on this default. + public static let nearPriorityDistance: Float = 10.0 + + /// The near band's ceiling as a fraction of the room, when `distancePrioritizedBudget` is on + /// (issue #1423): near's bisection is solved against `nearPriorityShare × room` rather than + /// the whole room, so `room − near's actual grant` — the far band's room — is always at + /// least `(1 − nearPriorityShare) × room`, whatever near wants. Near is thinned, not + /// unconditionally protected, once its own demand exceeds its share; a value of 1.0 restores + /// the original "near takes the whole room first, far gets what's left, possibly nothing" + /// behavior. + public static let nearPriorityShare: Float = 0.85 + + /// The local-space distance, starting at `nearPriorityDistance`, over which a chunk's + /// priority band weight smoothsteps from 0 (pure near) to 1 (pure far), instead of the + /// weight snapping at `nearPriorityDistance` itself. 0 reproduces that hard cutoff exactly + /// (smoothstep's two edges coincide). Scene-scale dependent like `nearPriorityDistance` + /// itself — most scenes should set `priorityTransitionWidthOverride` alongside + /// `nearPriorityDistanceOverride`. + public static let priorityTransitionWidth: Float = 0.0 + /// Replaces `coarseBudgetFraction` (tests, the editor); nil restores it. public static var coarseBudgetFractionOverride: Double? { get { storage.coarseBudgetFractionOverride } @@ -72,6 +96,55 @@ public enum GaussianPagingPolicy { coarseBudgetFractionOverride ?? coarseBudgetFraction } + /// Replaces `nearPriorityDistance`; nil restores it. + public static var nearPriorityDistanceOverride: Float? { + get { storage.nearPriorityDistanceOverride } + set { storage.nearPriorityDistanceOverride = newValue } + } + + /// The near-priority distance in effect. + public static var nearPriorityDistanceInEffect: Float { + nearPriorityDistanceOverride ?? nearPriorityDistance + } + + /// Replaces `nearPriorityShare`; nil restores it. + public static var nearPriorityShareOverride: Float? { + get { storage.nearPriorityShareOverride } + set { storage.nearPriorityShareOverride = newValue } + } + + /// The near-priority share in effect. + public static var nearPriorityShareInEffect: Float { + nearPriorityShareOverride ?? nearPriorityShare + } + + /// Replaces `priorityTransitionWidth`; nil restores it. + public static var priorityTransitionWidthOverride: Float? { + get { storage.priorityTransitionWidthOverride } + set { storage.priorityTransitionWidthOverride = newValue } + } + + /// The priority transition width in effect. + public static var priorityTransitionWidthInEffect: Float { + priorityTransitionWidthOverride ?? priorityTransitionWidth + } + + /// Whether the budget solve gives the near band priority over the far band's demand (issue + /// #1423) rather than thinning every visible chunk by one uniform cap. Off (the default) + /// restores the single-histogram solve exactly as it behaved before distance banding + /// existed — every chunk bins near, `nearPriorityDistance`/`nearPriorityShare` are unread. + /// On, near is solved against `nearPriorityShare` of the room first (bounded, not + /// unconditionally protected — see `nearPriorityShare`), then far against the rest. + /// Turning this on without also setting `nearPriorityDistanceOverride` to a figure that + /// matches the scene's own scale (the 10-unit default is almost certainly wrong for a real + /// asset) can make the split do nothing (everything lands in one band) or, if the caller's + /// camera-position input is left at its zero default, bin by distance from world-space + /// origin instead of the camera. + public static var distancePrioritizedBudget: Bool { + get { storage.distancePrioritizedBudget } + set { storage.distancePrioritizedBudget = newValue } + } + /// Replaces the residency budget (25 % of the geometry budget) with an exact figure. public static var residencyBudgetBytesOverride: Int? { get { storage.residencyBudgetBytesOverride } @@ -464,6 +537,38 @@ public enum GaussianPagingPolicy { } } + /// The priority-band counterpart of `fillDensityCap` (issue #1423): solves the near band's + /// cap against `nearPriorityShare × room` — its ceiling, not the whole room — then solves + /// the far band's cap against whatever `room` the near band's actual grant leaves. Because + /// near's grant is bounded by its own ceiling, `room − near's grant` is always at least + /// `(1 − nearPriorityShare) × room`: the far band is guaranteed that floor whatever near + /// wants, instead of the whole room first-come-first-served (`nearPriorityShare` 1.0 + /// restores exactly that: near may take the whole room, far keeps only what's left over, + /// possibly nothing). Near is thinned, not unconditionally protected, once its own demand + /// exceeds its share. Reuses `fillDensityCap` for each band rather than duplicating its + /// bisection. + public static func fillDensityCapByBand( + near: GaussianBudgetDensityHistogram, + far: GaussianBudgetDensityHistogram, + room: Float, + levels: (densityFloor: Float, tierShifts: (Int, Int))? = nil, + nearPriorityShare: Float = nearPriorityShareInEffect + ) -> (near: Float, far: Float) { + let nearRoom = max(0, nearPriorityShare) * room + let nearCap = fillDensityCap(histogram: near, room: nearRoom, levels: levels) + let nearRequested = near.requestedSplats + let nearGranted: Float = if nearCap.isInfinite { + Float(nearRequested) + } else if let levels { + GaussianChunkCullMath.boundedRequest(histogram: near, density: nearCap, densityFloor: levels.densityFloor, tierShifts: levels.tierShifts) + } else { + GaussianChunkCullMath.boundedGrant(histogram: near, density: nearCap) + } + let farRoom = max(0, room - min(max(nearGranted, 0), Float(nearRequested))) + let farCap = fillDensityCap(histogram: far, room: farRoom, levels: levels) + return (nearCap, farCap) + } + /// The uniform rule's counterpart of `fillDensity`: the scale at which the demanded chunks /// together would consume the room, `min(1, room / Σ n)`; 1 when nothing is demanded. public static func fillScale(budget: Int, reservedSplats: Int, demandedSplats: Int) -> Float { @@ -777,12 +882,20 @@ public enum GaussianPagingPolicy { private var _warmTimeoutTicks: UInt32 = 90 private var _pressureTicks: UInt32 = 600 private var _coarseBudgetFractionOverride: Double? + private var _nearPriorityDistanceOverride: Float? + private var _nearPriorityShareOverride: Float? + private var _priorityTransitionWidthOverride: Float? + private var _distancePrioritizedBudget = false func reset() { lock.lock() defer { lock.unlock() } _residencyBudgetBytesOverride = nil _pagingThresholdBytesOverride = nil + _nearPriorityDistanceOverride = nil + _nearPriorityShareOverride = nil + _priorityTransitionWidthOverride = nil + _distancePrioritizedBudget = false _minPoolSlots = 64 _holdOffTicks = 30 _surplusTicks = 45 @@ -813,6 +926,26 @@ public enum GaussianPagingPolicy { set { lock.lock(); _residencyBudgetBytesOverride = newValue; lock.unlock() } } + var nearPriorityDistanceOverride: Float? { + get { lock.lock(); defer { lock.unlock() }; return _nearPriorityDistanceOverride } + set { lock.lock(); _nearPriorityDistanceOverride = newValue; lock.unlock() } + } + + var nearPriorityShareOverride: Float? { + get { lock.lock(); defer { lock.unlock() }; return _nearPriorityShareOverride } + set { lock.lock(); _nearPriorityShareOverride = newValue; lock.unlock() } + } + + var priorityTransitionWidthOverride: Float? { + get { lock.lock(); defer { lock.unlock() }; return _priorityTransitionWidthOverride } + set { lock.lock(); _priorityTransitionWidthOverride = newValue; lock.unlock() } + } + + var distancePrioritizedBudget: Bool { + get { lock.lock(); defer { lock.unlock() }; return _distancePrioritizedBudget } + set { lock.lock(); _distancePrioritizedBudget = newValue; lock.unlock() } + } + var pagingThresholdBytesOverride: Int? { get { lock.lock(); defer { lock.unlock() }; return _pagingThresholdBytesOverride } set { lock.lock(); _pagingThresholdBytesOverride = newValue; lock.unlock() } diff --git a/Sources/UntoldEngine/Shaders/GaussianChunkCull.metal b/Sources/UntoldEngine/Shaders/GaussianChunkCull.metal index 0d1602f75..8943b595d 100644 --- a/Sources/UntoldEngine/Shaders/GaussianChunkCull.metal +++ b/Sources/UntoldEngine/Shaders/GaussianChunkCull.metal @@ -187,6 +187,7 @@ kernel void gaussianChunkCull( device atomic_uint *visibleChunkTotal [[buffer(gaussianChunkCullChunkTotalIndex)]], device atomic_uint *transitionSplats [[buffer(gaussianChunkCullBudgetStateIndex)]], device atomic_uint *densityHistogram [[buffer(gaussianChunkCullDensityHistogramIndex)]], + device atomic_uint *farDensityHistogram [[buffer(gaussianChunkCullFarDensityHistogramIndex)]], const device GaussianChunkResidency *residency [[buffer(gaussianChunkCullResidencyIndex)]], device uint *demand [[buffer(gaussianChunkCullDemandIndex)]], const device GaussianChunkDecodeConstants *coarseTable [[buffer(gaussianChunkCullCoarseTableIndex)]], @@ -271,23 +272,60 @@ kernel void gaussianChunkCull( const uint finestCoarse = ((available & 2u) != 0u) ? m1 : (((available & 4u) != 0u) ? m2 : 0u); const uint listed = max(drawable, finestCoarse); + // The priority band weight (issue #1423): 0 (pure near) to 1 (pure far), smoothstepped over + // priorityTransitionWidth starting at nearPriorityDistance from the chunk's centre (the box + // before padding, same point either way since the pad is symmetric) to the frame's camera — + // both in this entity's local space, since the chunk's box is local and cameraPositionLocal + // is the camera already carried through the inverse of the entity's model matrix + // (gaussianChunkCullConstants, Swift side), so a rotated or translated entity's chunks + // compare against the camera's true position rather than silently comparing local chunk + // coordinates to a world-space point. Off (distancePrioritizedBudget == 0) every chunk's + // weight is 0, so the far histogram stays empty and the near solve below is exactly today's + // single global one; priorityTransitionWidth == 0 degenerates the smoothstep to a hard step + // at nearPriorityDistance (its two edges coincide). + const float3 chunkCenter = 0.5f * (boxMin + boxMax); + const float priorityDistance = distance(chunkCenter, params.cameraPositionLocal); + const float bandWeight = params.distancePrioritizedBudget != 0u + ? smoothstep(params.nearPriorityDistance, params.nearPriorityDistance + params.priorityTransitionWidth, priorityDistance) + : 0.0f; + const float nearWeight = 1.0f - bandWeight; + const uint slot = atomic_fetch_add_explicit(visibleChunkTotal, 1u, memory_order_relaxed); atomic_fetch_add_explicit(visibleSplatTotal, listed, memory_order_relaxed); const uint tier = gaussianDensityTier((levels ? (float)chunk.splatCount : (float)drawable) / area); const uint scaledArea = (uint)ceil(area * gaussianDensityTierFloor(tier)); - atomic_fetch_add_explicit(&densityHistogram[8u * tier], listed, memory_order_relaxed); - atomic_fetch_add_explicit(&densityHistogram[8u * tier + 1u], scaledArea, memory_order_relaxed); + // Splits this chunk's histogram contribution between the near and far bands by its weight — + // a continuous blend rather than binning the whole chunk into one histogram or the other, so + // a chunk in the transition zone pulls both caps toward it proportionally. Rounded to the + // nearest atomic uint; the bounded rounding error does not accumulate (the histogram resets + // every frame). + const uint nearListed = (uint)round(nearWeight * (float)listed); + const uint farListed = listed - nearListed; + const uint nearScaledArea = (uint)round(nearWeight * (float)scaledArea); + const uint farScaledArea = scaledArea - nearScaledArea; + atomic_fetch_add_explicit(&densityHistogram[8u * tier], nearListed, memory_order_relaxed); + atomic_fetch_add_explicit(&densityHistogram[8u * tier + 1u], nearScaledArea, memory_order_relaxed); + atomic_fetch_add_explicit(&farDensityHistogram[8u * tier], farListed, memory_order_relaxed); + atomic_fetch_add_explicit(&farDensityHistogram[8u * tier + 1u], farScaledArea, memory_order_relaxed); if (levels && (available & 6u) != 0u) { - atomic_fetch_add_explicit(&densityHistogram[8u * tier + 2u], finestCoarse, memory_order_relaxed); - atomic_fetch_add_explicit(&densityHistogram[8u * tier + 3u], ((available & 4u) != 0u) ? m2 : m1, memory_order_relaxed); - atomic_fetch_add_explicit(&densityHistogram[8u * tier + 4u], listed, memory_order_relaxed); - atomic_fetch_add_explicit(&densityHistogram[8u * tier + 5u], scaledArea, memory_order_relaxed); + const uint nearFinestCoarse = (uint)round(nearWeight * (float)finestCoarse); + const uint coarse2Source = ((available & 4u) != 0u) ? m2 : m1; + const uint nearCoarse2Source = (uint)round(nearWeight * (float)coarse2Source); + atomic_fetch_add_explicit(&densityHistogram[8u * tier + 2u], nearFinestCoarse, memory_order_relaxed); + atomic_fetch_add_explicit(&densityHistogram[8u * tier + 3u], nearCoarse2Source, memory_order_relaxed); + atomic_fetch_add_explicit(&densityHistogram[8u * tier + 4u], nearListed, memory_order_relaxed); + atomic_fetch_add_explicit(&densityHistogram[8u * tier + 5u], nearScaledArea, memory_order_relaxed); + atomic_fetch_add_explicit(&farDensityHistogram[8u * tier + 2u], finestCoarse - nearFinestCoarse, memory_order_relaxed); + atomic_fetch_add_explicit(&farDensityHistogram[8u * tier + 3u], coarse2Source - nearCoarse2Source, memory_order_relaxed); + atomic_fetch_add_explicit(&farDensityHistogram[8u * tier + 4u], farListed, memory_order_relaxed); + atomic_fetch_add_explicit(&farDensityHistogram[8u * tier + 5u], farScaledArea, memory_order_relaxed); } GaussianVisibleChunk entry; entry.chunkIndex = levels ? (chunkIndex | (gaussianLevelStateLevel(state.word0) << kGaussianVisibleChunkLevelShift)) : chunkIndex; entry.splatCount = listed; entry.quota = listed; // gaussianComputeChunkQuotas lowers it when the frame is over budget entry.screenArea = params.uniformQuotas != 0u ? (float)listed : area; + entry.bandWeight = bandWeight; visibleChunks[slot] = entry; if (!levels) return; @@ -323,6 +361,7 @@ kernel void gaussianChunkCull( outgoing.splatCount = out; outgoing.quota = out; outgoing.screenArea = area; + outgoing.bandWeight = bandWeight; visibleChunks[outSlot] = outgoing; } diff --git a/Sources/UntoldEngine/Shaders/GaussianWorkingSetBudget.metal b/Sources/UntoldEngine/Shaders/GaussianWorkingSetBudget.metal index 178c8b8ef..351807abd 100644 --- a/Sources/UntoldEngine/Shaders/GaussianWorkingSetBudget.metal +++ b/Sources/UntoldEngine/Shaders/GaussianWorkingSetBudget.metal @@ -48,6 +48,7 @@ using namespace metal; kernel void gaussianResetBudgetRequest( device GaussianBudgetState *state [[buffer(gaussianBudgetStateIndex)]], device GaussianBudgetDensityHistogram *histogram [[buffer(gaussianBudgetDensityHistogramIndex)]], + device GaussianBudgetDensityHistogram *farHistogram [[buffer(gaussianBudgetFarDensityHistogramIndex)]], uint index [[thread_position_in_grid]]) { if (index < (uint)gaussianBudgetDensityTierCount) { @@ -57,6 +58,12 @@ kernel void gaussianResetBudgetRequest( histogram->tiers[index].coarse2 = 0u; histogram->tiers[index].levelledSplats = 0u; histogram->tiers[index].levelledScaledArea = 0u; + farHistogram->tiers[index].splats = 0u; + farHistogram->tiers[index].scaledArea = 0u; + farHistogram->tiers[index].coarse1 = 0u; + farHistogram->tiers[index].coarse2 = 0u; + farHistogram->tiers[index].levelledSplats = 0u; + farHistogram->tiers[index].levelledScaledArea = 0u; } if (index != 0u) return; state->requestedSplats = 0u; @@ -69,6 +76,10 @@ kernel void gaussianResetBudgetRequest( histogram->fullDensity = 0.0f; histogram->grant = 0u; histogram->visibleChunks = 0u; + farHistogram->targetDensity = 0.0f; + farHistogram->fullDensity = 0.0f; + farHistogram->grant = 0u; + farHistogram->visibleChunks = 0u; } // One thread per whole-buffer entity, after its gaussianFinalizeVisibleSet on the same serial @@ -171,10 +182,111 @@ static inline float gaussianBoundedRequest(const thread GaussianBudgetTiers &tie // target take the cap's too. With uniform quotas the cap is the scale itself (+inf when the // scale is 1), no solve, so the per-chunk rule reproduces floor(scale · splatCount) byte for // byte. The solve is recorded in the histogram's header for the readback. +// Loads one priority band's histogram into thread memory (the same per-tier unpacking +// gaussianComputeBudgetScale always did) and returns its highest non-empty tier, -1 when the +// band is empty. +static inline int gaussianLoadBudgetTiers(const device GaussianBudgetDensityHistogram *histogram, thread GaussianBudgetTiers &tiers) +{ + int highestTier = -1; + for (uint tier = 0u; tier < (uint)gaussianBudgetDensityTierCount; ++tier) { + const GaussianBudgetDensityTier entry = histogram->tiers[tier]; + tiers.splats[tier] = (float)entry.splats; + tiers.area[tier] = entry.splats == 0u ? 0.0f : (float)entry.scaledArea / gaussianDensityTierFloor(tier); + const uint levelled = min(entry.levelledSplats, entry.splats); + tiers.levelled[tier] = (float)levelled; + tiers.levelledArea[tier] = levelled == 0u ? 0.0f : (float)min(entry.levelledScaledArea, entry.scaledArea) / gaussianDensityTierFloor(tier); + tiers.coarse1[tier] = (float)entry.coarse1; + tiers.coarse2[tier] = (float)entry.coarse2; + if (entry.splats != 0u) highestTier = (int)tier; + } + return highestTier; +} + +// One priority band's density-cap solve (issue #1423): the same 24-step bisection +// gaussianComputeBudgetScale always ran over one histogram, factored out so it runs once for +// the near band against the frame's whole room and once for the far band against whatever room +// the near band's actual (post-hysteresis) grant leaves — `GaussianChunkCullMath.densityCap +// (near:far:grant:)` is its CPU mirror. `grantValue` is this band's share of the room (the whole +// room for the near band; the remainder for the far band); `previousCap` and `histogramOut` are +// this band's own persistent state, so each band's hysteresis (a fall at once, a smoothed rise) +// runs independently of the other's. +static inline float gaussianSolveBandDensityCap( + const device GaussianBudgetDensityHistogram *histogram, + device GaussianBudgetDensityHistogram *histogramOut, + const float grantValue, + const float previousCap, + const bool takeTarget, + const bool wholeBand, + constant GaussianBudgetScaleConstants &constants, + thread GaussianBudgetTiers &tiers) +{ + const int highestTier = gaussianLoadBudgetTiers(histogram, tiers); + const bool anyChunk = highestTier >= 0; + const float fullDensity = anyChunk ? gaussianDensityTierFloor((uint)(highestTier + 1)) : INFINITY; + // The climb tail (GaussianChunkCullMath.climbDensity): the densest tiers holding together at + // most kGaussianBudgetDensityClimbTail of this band's own request are left to the whole, so + // a band with little of the frame's splats does not climb to "whole" in one step just + // because the shared fraction is coarse at the frame's total scale. + float bandRequested = 0.0f; + for (uint tier = 0u; tier < (uint)gaussianBudgetDensityTierCount; ++tier) { + bandRequested += tiers.splats[tier]; + } + const uint tail = (uint)(kGaussianBudgetDensityClimbTail * bandRequested); + int climbTier = highestTier; + uint tailSplats = 0u; + while (climbTier >= 0) { + const uint tierSplats = (uint)tiers.splats[climbTier]; + if (tailSplats + tierSplats > tail) break; + tailSplats += tierSplats; + --climbTier; + } + const float climbDensity = anyChunk ? gaussianDensityTierFloor((uint)(climbTier + 1)) : INFINITY; + + float targetDensity; + if (wholeBand) { + targetDensity = INFINITY; + } else if (grantValue <= 0.0f || !anyChunk) { + targetDensity = 0.0f; + } else { + float lo = -16.0f; + float hi = log2(fullDensity); + if (gaussianBoundedRequest(tiers, exp2(lo), constants.densityFloor, constants.tierShift1, constants.tierShift2) > grantValue) { + targetDensity = 0.0f; + } else { + for (uint step = 0u; step < 24u; ++step) { + const float mid = (lo + hi) * 0.5f; + if (gaussianBoundedRequest(tiers, exp2(mid), constants.densityFloor, constants.tierShift1, constants.tierShift2) <= grantValue) { + lo = mid; + } else { + hi = mid; + } + } + targetDensity = exp2(lo); + } + } + + float cap; + if (takeTarget || !(previousCap >= 0.0f) || targetDensity <= previousCap) { + cap = targetDensity; + } else { + const float stepTarget = targetDensity == INFINITY ? climbDensity : targetDensity; + const float step = max(previousCap * constants.maxStepFraction, constants.densityMinStepFraction * stepTarget); + cap = min(previousCap + step, targetDensity); + if (targetDensity == INFINITY && cap >= climbDensity) { + cap = INFINITY; + } + } + histogramOut->targetDensity = targetDensity; + histogramOut->fullDensity = fullDensity; + histogramOut->grant = (uint)max(grantValue, 0.0f); + return cap; +} + kernel void gaussianComputeBudgetScale( device GaussianBudgetState *state [[buffer(gaussianBudgetStateIndex)]], constant GaussianBudgetScaleConstants &constants [[buffer(gaussianBudgetScaleConstantsIndex)]], device GaussianBudgetDensityHistogram *histogram [[buffer(gaussianBudgetDensityHistogramIndex)]], + device GaussianBudgetDensityHistogram *farHistogram [[buffer(gaussianBudgetFarDensityHistogramIndex)]], uint index [[thread_position_in_grid]]) { if (index != 0u) return; @@ -214,90 +326,57 @@ kernel void gaussianComputeBudgetScale( state->scale = clamp(scale, 0.0f, 1.0f); state->frameCount = frameCount + 1u; - // The grant and the density cap. + // The grant and the density caps. With distance banding (issue #1423) the near band is + // solved first against the whole room, as if it alone must fit it, then the far band + // against whatever room the near band's actual (post-hysteresis) grant leaves — so a + // shortfall is absorbed by the far band first. Without banding every chunk cull binned + // into the near histogram alone (GaussianChunkCullConstants.distancePrioritizedBudget == 0), + // the far histogram stays empty, and this reduces to exactly the old single-cap solve. const uint grant = fits ? requested : (uint)room; - float targetDensity; - float fullDensity; float cap; + float farCap; if (constants.uniformQuotas != 0u) { + // The uniform rule has no density solve (every chunk's area is its count): both bands + // apply the same frame-wide scale, exactly as before banding existed. const float uniformScale = state->scale; cap = (uniformScale < 1.0f) ? uniformScale : INFINITY; - targetDensity = INFINITY; - fullDensity = INFINITY; + farCap = cap; + histogram->targetDensity = INFINITY; + histogram->fullDensity = INFINITY; + histogram->grant = grant; + farHistogram->targetDensity = INFINITY; + farHistogram->fullDensity = INFINITY; + farHistogram->grant = grant; } else { - // The tiers once into thread memory: the splats as floats and the area each tier's - // scaled area stands for, so the solve's evaluations are register arithmetic; the - // levelled share of each tier beside them (all zero without coarse levels). - GaussianBudgetTiers tiers; - int highestTier = -1; - for (uint tier = 0u; tier < (uint)gaussianBudgetDensityTierCount; ++tier) { - const GaussianBudgetDensityTier entry = histogram->tiers[tier]; - tiers.splats[tier] = (float)entry.splats; - tiers.area[tier] = entry.splats == 0u ? 0.0f : (float)entry.scaledArea / gaussianDensityTierFloor(tier); - const uint levelled = min(entry.levelledSplats, entry.splats); - tiers.levelled[tier] = (float)levelled; - tiers.levelledArea[tier] = levelled == 0u ? 0.0f : (float)min(entry.levelledScaledArea, entry.scaledArea) / gaussianDensityTierFloor(tier); - tiers.coarse1[tier] = (float)entry.coarse1; - tiers.coarse2[tier] = (float)entry.coarse2; - if (entry.splats != 0u) highestTier = (int)tier; - } - const bool anyChunk = highestTier >= 0; - fullDensity = anyChunk ? gaussianDensityTierFloor((uint)(highestTier + 1)) : INFINITY; - // The climb density: down from the top, the tiers that together hold at most the tail - // of the request are left to the whole (GaussianChunkCullMath.climbDensity). - const uint tail = (uint)(kGaussianBudgetDensityClimbTail * (float)requested); - int climbTier = highestTier; - uint tailSplats = 0u; - while (climbTier >= 0) { - const uint tierSplats = histogram->tiers[climbTier].splats; - if (tailSplats + tierSplats > tail) break; - tailSplats += tierSplats; - --climbTier; - } - const float climbDensity = anyChunk ? gaussianDensityTierFloor((uint)(climbTier + 1)) : INFINITY; - + // Every visible chunk, either band, fits: each band still runs the same hysteresis and + // climb-to-whole smoothing as the bounded case (`wholeBand` skips only the bisection, + // never the smoothing) — a scene that just stopped being over budget climbs to "whole" + // over several frames like any other rise, rather than popping every chunk to full + // density the instant the frame fits. const bool whole = requested == 0u || fits; + // The near band's ceiling (issue #1423): its own share of the room when banding is on, + // the whole room when it is off — so near is thinned, not unconditionally protected, + // once its own demand exceeds its share, and the far band keeps at least + // (1 - nearPriorityShare) of the room whatever near wants (gaussianSolveBandDensityCap's + // bisection can only grant near up to nearRoom, so grant - near's actual grant is bounded + // below by grant - nearRoom). + const float nearRoom = constants.distancePrioritizedBudget != 0u + ? max(constants.nearPriorityShare, 0.0f) * (float)grant + : (float)grant; + GaussianBudgetTiers nearTiers; + cap = gaussianSolveBandDensityCap(histogram, histogram, nearRoom, state->densityCap, takeTarget, whole, constants, nearTiers); if (whole) { - targetDensity = INFINITY; - } else if (grant == 0u || !anyChunk) { - targetDensity = 0.0f; + GaussianBudgetTiers farTiers; + farCap = gaussianSolveBandDensityCap(farHistogram, farHistogram, (float)grant, state->farDensityCap, takeTarget, true, constants, farTiers); } else { - const float grantValue = (float)grant; - float lo = -16.0f; - float hi = log2(fullDensity); - if (gaussianBoundedRequest(tiers, exp2(lo), constants.densityFloor, constants.tierShift1, constants.tierShift2) > grantValue) { - targetDensity = 0.0f; - } else { - for (uint step = 0u; step < 24u; ++step) { - const float mid = (lo + hi) * 0.5f; - if (gaussianBoundedRequest(tiers, exp2(mid), constants.densityFloor, constants.tierShift1, constants.tierShift2) <= grantValue) { - lo = mid; - } else { - hi = mid; - } - } - targetDensity = exp2(lo); - } - } - - // A previous cap that is not a number at or above zero takes the target (a guard: the - // state never holds one); zero itself climbs by the step like any other cap. - const float previousCap = state->densityCap; - if (takeTarget || !(previousCap >= 0.0f) || targetDensity <= previousCap) { - cap = targetDensity; // a fall at once; whole stays whole - } else { - const float stepTarget = whole ? climbDensity : targetDensity; - const float step = max(previousCap * constants.maxStepFraction, constants.densityMinStepFraction * stepTarget); - cap = min(previousCap + step, targetDensity); - if (whole && cap >= climbDensity) { - cap = INFINITY; // the climb toward a fitting frame arrived: every chunk is whole - } + const float nearGranted = gaussianBoundedRequest(nearTiers, cap, constants.densityFloor, constants.tierShift1, constants.tierShift2); + const uint farRoom = (uint)max((float)grant - nearGranted, 0.0f); + GaussianBudgetTiers farTiers; + farCap = gaussianSolveBandDensityCap(farHistogram, farHistogram, (float)farRoom, state->farDensityCap, takeTarget, false, constants, farTiers); } } state->densityCap = cap; - histogram->targetDensity = targetDensity; - histogram->fullDensity = fullDensity; - histogram->grant = grant; + state->farDensityCap = farCap; } // The fine quota of a chunk at the cap: min(splatCount, floor(densityCap · screenArea)) — the @@ -311,6 +390,27 @@ static inline uint gaussianLevelQuota(const float densityCap, const float screen return (granted >= (float)splatCount) ? splatCount : (uint)floor(max(granted, 0.0f)); } +// A chunk's quota at its priority band weight t (issue #1423): mix(nearQuota, farQuota, t) of +// the two bands' own gaussianLevelQuota at this chunk's splatCount — never the density caps +// themselves. Blending the caps (an earlier version of this) is NaN-prone whenever either is +// infinite (inf * 0 is NaN, not 0) and, worse, any finite fallback for that case (e.g. picking +// whichever cap t is nearer to) creates a hard step exactly where the fallback switches sides: +// as a chunk's t crosses that point — or a cap flips between finite and infinite across frames +// near the fitting boundary — its quota pops between "whole count" and "far cap's cut," which +// reads as the chunk flickering on and off. gaussianLevelQuota already resolves an infinite cap +// to the finite splatCount before this ever touches it, so the blend here is a sum of two +// ordinary floats, continuous in t with no special case. Mirrored by +// GaussianChunkCullMath.mixedQuota for tests and callers that want to predict this without a +// GPU readback. +static inline uint gaussianMixedQuota(const float nearCap, const float farCap, const float screenArea, const uint splatCount, const float t) +{ + if (t <= 0.0f) return gaussianLevelQuota(nearCap, screenArea, splatCount); + if (t >= 1.0f) return gaussianLevelQuota(farCap, screenArea, splatCount); + const float nearQuota = (float)gaussianLevelQuota(nearCap, screenArea, splatCount); + const float farQuota = (float)gaussianLevelQuota(farCap, screenArea, splatCount); + return (uint)round(mix(nearQuota, farQuota, t)); +} + // One threadgroup per entity, striding over its visible chunks: quota = min(splatCount, // floor(densityCap · screenArea)) — the whole count when the cap grants it (+inf always does), // else the floor, never ceil, so the quotas of a frame sum to at most the bounded grant at the @@ -360,7 +460,12 @@ kernel void gaussianComputeChunkQuotas( } threadgroup_barrier(mem_flags::mem_threadgroup); - const float densityCap = state->densityCap; + // The two bands' caps (issue #1423): each entry's quota is a smoothstep blend of what the + // two bands would grant it at its own bandWeight (gaussianMixedQuota) — weight 0 for every + // entry when distance banding is off, since the cull never gives one any other weight then, + // so the blend always resolves to nearCap's grant alone. + const float nearCap = state->densityCap; + const float farCap = state->farDensityCap; const uint visibleChunkCount = chunkSet->threadgroupCount; const bool levels = lvl.hasCoarse != 0u && lvl.uniformQuotas == 0u && lvl.levelMode != (uint)gaussianChunkLevelModeFineOnly; uint mine = 0u; @@ -375,11 +480,18 @@ kernel void gaussianComputeChunkQuotas( for (uint i = localIndex; i < visibleChunkCount; i += threadsPerGroup) { GaussianVisibleChunk entry = visibleChunks[i]; if (!levels) { - entry.quota = gaussianLevelQuota(densityCap, entry.screenArea, entry.splatCount); + entry.quota = gaussianMixedQuota(nearCap, farCap, entry.screenArea, entry.splatCount, entry.bandWeight); visibleChunks[i] = entry; mine += entry.quota; continue; } + // The discrete level pick (below) has no continuous generalization — a chunk cannot + // read "70% fine, 30% coarse" — so it still resolves to one band's cap outright, the + // one bandWeight is nearer to; only the quotas gaussianMixedQuota grants (fineQuota, + // quota1, quota2, just below) are actually blended, which is what matters for the + // flicker this is here to avoid (issue #1423) — the level itself already only ever + // changes through its own fade/hysteresis machinery, unaffected by this choice. + const float densityCap = entry.bandWeight < 0.5f ? nearCap : farCap; const uint chunkIndex = entry.chunkIndex & kGaussianVisibleChunkIndexMask; const bool outgoing = (entry.chunkIndex & kGaussianVisibleChunkOutgoing) != 0u; @@ -397,10 +509,11 @@ kernel void gaussianComputeChunkQuotas( const uint level = gaussianLevelStateLevel(previous.word0); const uint wanted = gaussianChunkLevel(densityCap, lvl.densityFloor, (float)chunk.splatCount, entry.screenArea, level, available, lvl.tierShift1, lvl.tierShift2, lvl.levelMode); - // The quota of each level at this cap: fine on the resident ranks, a coarse level on its count. - const uint fineQuota = gaussianLevelQuota(densityCap, entry.screenArea, resident); - const uint quota1 = gaussianLevelQuota(densityCap, entry.screenArea, m1); - const uint quota2 = gaussianLevelQuota(densityCap, entry.screenArea, m2); + // The quota of each level, blended between the bands at this chunk's weight: fine on + // the resident ranks, a coarse level on its count. + const uint fineQuota = gaussianMixedQuota(nearCap, farCap, entry.screenArea, resident, entry.bandWeight); + const uint quota1 = gaussianMixedQuota(nearCap, farCap, entry.screenArea, m1, entry.bandWeight); + const uint quota2 = gaussianMixedQuota(nearCap, farCap, entry.screenArea, m2, entry.bandWeight); const uint quotaOfLevel = level == 0u ? fineQuota : (level == 1u ? quota1 : quota2); const uint quotaOfWanted = wanted == 0u ? fineQuota : (wanted == 1u ? quota1 : quota2); const bool pendingValid = gaussianLevelStatePendingValid(previous.word0); @@ -498,10 +611,13 @@ kernel void gaussianPublishBudgetState( device GaussianBudgetState *readback [[buffer(gaussianBudgetReadbackIndex)]], const device GaussianBudgetDensityHistogram *histogram [[buffer(gaussianBudgetDensityHistogramIndex)]], device GaussianBudgetDensityHistogram *histogramReadback [[buffer(gaussianBudgetDensityReadbackIndex)]], + const device GaussianBudgetDensityHistogram *farHistogram [[buffer(gaussianBudgetFarDensityHistogramIndex)]], + device GaussianBudgetDensityHistogram *farHistogramReadback [[buffer(gaussianBudgetFarDensityReadbackIndex)]], uint index [[thread_position_in_grid]]) { if (index < (uint)gaussianBudgetDensityTierCount) { histogramReadback->tiers[index] = histogram->tiers[index]; + farHistogramReadback->tiers[index] = farHistogram->tiers[index]; } if (index != 0u) return; *readback = *state; @@ -509,4 +625,8 @@ kernel void gaussianPublishBudgetState( histogramReadback->fullDensity = histogram->fullDensity; histogramReadback->grant = histogram->grant; histogramReadback->visibleChunks = histogram->visibleChunks; + farHistogramReadback->targetDensity = farHistogram->targetDensity; + farHistogramReadback->fullDensity = farHistogram->fullDensity; + farHistogramReadback->grant = farHistogram->grant; + farHistogramReadback->visibleChunks = farHistogram->visibleChunks; } diff --git a/Sources/UntoldEngine/Systems/GaussianChunkCull.swift b/Sources/UntoldEngine/Systems/GaussianChunkCull.swift index bf425a541..facbd2216 100644 --- a/Sources/UntoldEngine/Systems/GaussianChunkCull.swift +++ b/Sources/UntoldEngine/Systems/GaussianChunkCull.swift @@ -422,6 +422,49 @@ enum GaussianChunkCullMath { return exp2(lo) } + /// The priority-band counterpart of `densityCap` (issue #1423): solves the near band's cap + /// against `nearPriorityShare × grant` — its ceiling, not the whole grant — then solves the + /// far band's cap against whatever `grant` the near band's actual bounded grant leaves. Near + /// is thinned, not unconditionally protected, once its own demand exceeds its share; + /// `grant − near's actual grant` is always at least `(1 − nearPriorityShare) × grant`, so far + /// is guaranteed that floor whatever near wants (`nearPriorityShare` 1.0 restores "near takes + /// the whole grant first, far gets what's left, possibly nothing"). + static func densityCap( + near: GaussianBudgetDensityHistogram, + far: GaussianBudgetDensityHistogram, + grant: UInt32, + nearPriorityShare: Float = GaussianPagingPolicy.nearPriorityShareInEffect + ) -> (near: Float, far: Float) { + let nearRequested = near.requestedSplats + let nearGrant = UInt32(max(0, min(Float(UInt32.max), max(0, nearPriorityShare) * Float(grant)))) + let nearCap = densityCap(histogram: near, grant: nearGrant, fits: nearRequested <= nearGrant) + let nearGranted: Float = if nearCap.isInfinite { + Float(nearRequested) + } else { + min(max(boundedGrant(histogram: near, density: nearCap), 0), Float(nearRequested)) + } + let farGrantFloat = Float(grant) - nearGranted + let farGrant: UInt32 = farGrantFloat > 0 ? UInt32(farGrantFloat) : 0 + let farCap = densityCap(histogram: far, grant: farGrant, fits: far.requestedSplats <= farGrant) + return (nearCap, farCap) + } + + /// CPU mirror of `gaussianMixedQuota` (issue #1423): a chunk's quota at its priority band + /// weight `t` — `mix` of what the two bands' caps would each grant it (`quota(densityCap: + /// splatCount:screenArea:)`, already finite even when a cap is `.infinity`), not a blend of + /// the caps themselves. Blending the caps directly is NaN-prone (`.infinity * 0` is NaN, not + /// 0) and any finite fallback for that case creates a hard step in the quota exactly where + /// the fallback switches sides — which reads as a chunk flickering on and off as `t`, or a + /// cap's own finite/infinite hysteresis state, crosses that point. Blending two already- + /// finite quotas has no such discontinuity. + static func mixedQuota(nearCap: Float, farCap: Float, screenArea: Float, splatCount: UInt32, t: Float) -> UInt32 { + if t <= 0 { return quota(densityCap: nearCap, splatCount: splatCount, screenArea: screenArea) } + if t >= 1 { return quota(densityCap: farCap, splatCount: splatCount, screenArea: screenArea) } + let nearQuota = Float(quota(densityCap: nearCap, splatCount: splatCount, screenArea: screenArea)) + let farQuota = Float(quota(densityCap: farCap, splatCount: splatCount, screenArea: screenArea)) + return UInt32(max(0, (nearQuota + (farQuota - nearQuota) * t).rounded())) + } + /// The density cap applied after the hysteresis: the target when it is at or below the /// previous frame's cap (a fall is taken at once; "whole", +inf, stays whole), else the /// previous cap raised by at most max(`maxStepFraction` × previous, `minStepFraction` × @@ -896,7 +939,7 @@ func makeGaussianVisibleChunkSet(visibleChunks: UInt32, visibleSplats: UInt32) - func allocateGaussianVisibleChunkBuffers(for table: GaussianChunkTable, entriesPerChunk: Int? = nil) -> GaussianChunkTable? { guard let device = renderInfo.device else { return nil } let entries: [GaussianVisibleChunk] = table.index.chunks.enumerated().map { index, chunk in - GaussianVisibleChunk(chunkIndex: UInt32(index), splatCount: chunk.splatCount, quota: chunk.splatCount, screenArea: Float(chunk.splatCount)) + GaussianVisibleChunk(chunkIndex: UInt32(index), splatCount: chunk.splatCount, quota: chunk.splatCount, screenArea: Float(chunk.splatCount), bandWeight: 0) } let splatTotal = entries.reduce(UInt32(0)) { $0 &+ $1.splatCount } // Two entries per chunk for an entity with coarse levels (the incoming window and, while a @@ -1019,8 +1062,14 @@ func gaussianChunkCullConstants( hzbValid: Bool, forceAllVisible: Bool = GaussianDebugOptions.shared.disableChunkCull, uniformQuotas: Bool, - paged: UInt32 = 0 + paged: UInt32 = 0, + cameraPositionWorld: simd_float3 = .zero ) -> GaussianChunkCullConstants { + // Chunk AABBs are stored in this entity's local (splat) space; the kernel's near/far test + // (issue #1423) needs the camera in that same space, not world space, or a rotated or + // translated entity's chunks would compare against the wrong point entirely. + let cameraPositionLocal4 = simd_inverse(modelMatrix) * simd_float4(cameraPositionWorld, 1) + let cameraPositionLocal = simd_float3(cameraPositionLocal4.x, cameraPositionLocal4.y, cameraPositionLocal4.z) let views = gaussianChunkCullViewProjections(modelMatrix: modelMatrix, viewMatrix: viewMatrix) var constants = GaussianChunkCullConstants() constants.viewProjection0 = views.first @@ -1039,6 +1088,10 @@ func gaussianChunkCullConstants( constants.forceAllVisible = forceAllVisible ? 1 : 0 constants.uniformQuotas = uniformQuotas ? 1 : 0 constants.paged = paged + constants.cameraPositionLocal = cameraPositionLocal + constants.nearPriorityDistance = GaussianPagingPolicy.nearPriorityDistanceInEffect + constants.distancePrioritizedBudget = GaussianPagingPolicy.distancePrioritizedBudget ? 1 : 0 + constants.priorityTransitionWidth = GaussianPagingPolicy.priorityTransitionWidthInEffect return constants } @@ -1157,6 +1210,7 @@ func encodeGaussianChunkCull( chunkSet: MTLBuffer, budgetState: MTLBuffer, densityHistogram: MTLBuffer, + farDensityHistogram: MTLBuffer, constants: GaussianChunkCullConstants, hzbTexture: MTLTexture?, residency: MTLBuffer? = nil, @@ -1177,6 +1231,7 @@ func encodeGaussianChunkCull( chunkSet: chunkSet, budgetState: budgetState, densityHistogram: densityHistogram, + farDensityHistogram: farDensityHistogram, constants: constants, hzbTexture: hzbTexture, residency: residency, @@ -1209,6 +1264,7 @@ private func encodeGaussianChunkCullDispatch( chunkSet: MTLBuffer, budgetState: MTLBuffer?, densityHistogram: MTLBuffer, + farDensityHistogram: MTLBuffer, constants: GaussianChunkCullConstants, hzbTexture: MTLTexture?, residency: MTLBuffer?, @@ -1245,6 +1301,9 @@ private func encodeGaussianChunkCullDispatch( } // The histogram's tiers as atomic words: 8t the splats, 8t + 1 the scaled area, 8t + 2 … 8t + 4 the level words. encoder.setBuffer(densityHistogram, offset: 0, index: Int(gaussianChunkCullDensityHistogramIndex.rawValue)) + // The far priority band's histogram (issue #1423); a chunk bins into it instead when + // constants.distancePrioritizedBudget != 0 and it lies beyond constants.nearPriorityDistance. + encoder.setBuffer(farDensityHistogram, offset: 0, index: Int(gaussianChunkCullFarDensityHistogramIndex.rawValue)) // Paged entities only; the kernel never reads these with paged == 0. encoder.setBuffer(residency ?? chunkTable.constantsBuffer, offset: 0, index: Int(gaussianChunkCullResidencyIndex.rawValue)) encoder.setBuffer(demand ?? chunkTable.constantsBuffer, offset: 0, index: Int(gaussianChunkCullDemandIndex.rawValue)) @@ -1299,6 +1358,8 @@ func encodeGaussianChunkDemand( chunkSet: chunkSet, budgetState: nil, densityHistogram: densityHistogram, + // paged == 2 returns before any histogram write; the near buffer stands in, never read. + farDensityHistogram: densityHistogram, constants: constants, hzbTexture: hzbTexture, residency: nil, @@ -1373,6 +1434,8 @@ func gaussianBudgetScaleConstants( constants.densityFloor = densityFloor constants.tierShift1 = tierShifts.0 constants.tierShift2 = tierShifts.1 + constants.distancePrioritizedBudget = GaussianPagingPolicy.distancePrioritizedBudget ? 1 : 0 + constants.nearPriorityShare = GaussianPagingPolicy.nearPriorityShareInEffect return constants } @@ -1381,10 +1444,11 @@ private let gaussianDensityHistogramThreadgroup = MTLSizeMake(gaussianDensityTie /// Zeroes the frame's request, reservation and grant counters and the density histogram, before /// any entity's cull. One dispatch of one threadgroup, a thread per tier. -func encodeGaussianBudgetReset(_ encoder: MTLComputeCommandEncoder, pipelines: GaussianChunkCullPipelineStates, budgetState: MTLBuffer, densityHistogram: MTLBuffer) { +func encodeGaussianBudgetReset(_ encoder: MTLComputeCommandEncoder, pipelines: GaussianChunkCullPipelineStates, budgetState: MTLBuffer, densityHistogram: MTLBuffer, farDensityHistogram: MTLBuffer) { encoder.setComputePipelineState(pipelines.resetBudget) encoder.setBuffer(budgetState, offset: 0, index: Int(gaussianBudgetStateIndex.rawValue)) encoder.setBuffer(densityHistogram, offset: 0, index: Int(gaussianBudgetDensityHistogramIndex.rawValue)) + encoder.setBuffer(farDensityHistogram, offset: 0, index: Int(gaussianBudgetFarDensityHistogramIndex.rawValue)) encoder.dispatchThreadgroups(MTLSizeMake(1, 1, 1), threadsPerThreadgroup: gaussianDensityHistogramThreadgroup) } @@ -1400,12 +1464,13 @@ func encodeGaussianBudgetReserve(_ encoder: MTLComputeCommandEncoder, pipelines: /// Turns the frame's request into its scale and, from the histogram, its density cap, after /// every entity's chunk cull. One dispatch. -func encodeGaussianBudgetScale(_ encoder: MTLComputeCommandEncoder, pipelines: GaussianChunkCullPipelineStates, budgetState: MTLBuffer, densityHistogram: MTLBuffer, constants: GaussianBudgetScaleConstants) { +func encodeGaussianBudgetScale(_ encoder: MTLComputeCommandEncoder, pipelines: GaussianChunkCullPipelineStates, budgetState: MTLBuffer, densityHistogram: MTLBuffer, farDensityHistogram: MTLBuffer, constants: GaussianBudgetScaleConstants) { var constants = constants encoder.setComputePipelineState(pipelines.budgetScale) encoder.setBuffer(budgetState, offset: 0, index: Int(gaussianBudgetStateIndex.rawValue)) encoder.setBytes(&constants, length: MemoryLayout.stride, index: Int(gaussianBudgetScaleConstantsIndex.rawValue)) encoder.setBuffer(densityHistogram, offset: 0, index: Int(gaussianBudgetDensityHistogramIndex.rawValue)) + encoder.setBuffer(farDensityHistogram, offset: 0, index: Int(gaussianBudgetFarDensityHistogramIndex.rawValue)) encoder.dispatchThreadgroups(MTLSizeMake(1, 1, 1), threadsPerThreadgroup: MTLSizeMake(1, 1, 1)) } @@ -1455,13 +1520,17 @@ func encodeGaussianBudgetPublish( budgetState: MTLBuffer, readback: MTLBuffer, densityHistogram: MTLBuffer, - densityReadback: MTLBuffer + densityReadback: MTLBuffer, + farDensityHistogram: MTLBuffer, + farDensityReadback: MTLBuffer ) { encoder.setComputePipelineState(pipelines.publishBudget) encoder.setBuffer(budgetState, offset: 0, index: Int(gaussianBudgetStateIndex.rawValue)) encoder.setBuffer(readback, offset: 0, index: Int(gaussianBudgetReadbackIndex.rawValue)) encoder.setBuffer(densityHistogram, offset: 0, index: Int(gaussianBudgetDensityHistogramIndex.rawValue)) encoder.setBuffer(densityReadback, offset: 0, index: Int(gaussianBudgetDensityReadbackIndex.rawValue)) + encoder.setBuffer(farDensityHistogram, offset: 0, index: Int(gaussianBudgetFarDensityHistogramIndex.rawValue)) + encoder.setBuffer(farDensityReadback, offset: 0, index: Int(gaussianBudgetFarDensityReadbackIndex.rawValue)) encoder.dispatchThreadgroups(MTLSizeMake(1, 1, 1), threadsPerThreadgroup: gaussianDensityHistogramThreadgroup) } diff --git a/Sources/UntoldEngine/Systems/GaussianSharedWorkingSet.swift b/Sources/UntoldEngine/Systems/GaussianSharedWorkingSet.swift index 2ee085339..794e576ec 100644 --- a/Sources/UntoldEngine/Systems/GaussianSharedWorkingSet.swift +++ b/Sources/UntoldEngine/Systems/GaussianSharedWorkingSet.swift @@ -54,6 +54,13 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { private var _densityHistogram: MTLBuffer? private var densityReadbacks: [MTLBuffer?] = Array(repeating: nil, count: maxInFlightCommandBuffers) private var _lastDensityHistogram = GaussianBudgetDensityHistogram() + /// The far priority band's density histogram (issue #1423), same lifecycle as + /// `_densityHistogram`/`densityReadbacks`: empty (every tier zero) whenever + /// `GaussianPagingPolicy.distancePrioritizedBudget` is off, since every chunk cull then + /// bins near. + private var _farDensityHistogram: MTLBuffer? + private var farDensityReadbacks: [MTLBuffer?] = Array(repeating: nil, count: maxInFlightCommandBuffers) + private var _lastFarDensityHistogram = GaussianBudgetDensityHistogram() /// The entity enumeration the preprocess stamped into each slot's records, so the draw builds /// its constants table from the same order even when the scene changed in between or the /// preprocess was skipped this frame (asset loading gate) and the slot is stale. @@ -100,6 +107,13 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { return _lastDensityHistogram } + /// The far priority band's density histogram of the last completed frame (issue #1423). + var lastFarDensityHistogram: GaussianBudgetDensityHistogram { + lock.lock() + defer { lock.unlock() } + return _lastFarDensityHistogram + } + /// The working-set budget in splats for this platform: the override when set, otherwise the /// default clamped so the set (`bytesPerSplatPerSlot` per frame in flight) takes at most /// `memoryBudgetFraction` of the geometry budget. @@ -166,6 +180,7 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { let complete = visibleSets.allSatisfy { $0 != nil } && entityConstants.allSatisfy { $0 != nil } && keys.allSatisfy { $0 != nil } && _budgetState != nil && budgetReadbacks.allSatisfy { $0 != nil } && _densityHistogram != nil && densityReadbacks.allSatisfy { $0 != nil } + && _farDensityHistogram != nil && farDensityReadbacks.allSatisfy { $0 != nil } if complete, exact ? wanted == _capacity : wanted <= _capacity { return true } @@ -178,6 +193,8 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { var newBudgetReadbacks = budgetReadbacks var newDensityHistogram = _densityHistogram var newDensityReadbacks = densityReadbacks + var newFarDensityHistogram = _farDensityHistogram + var newFarDensityReadbacks = farDensityReadbacks for slot in 0 ..< maxInFlightCommandBuffers { if newCapacity != _capacity || newKeys[slot] == nil || newRecords[slot] == nil { guard let keyBuffer = device.makeBuffer(length: MemoryLayout.stride * newCapacity, options: .storageModeShared), @@ -206,6 +223,12 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { readback.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) newDensityReadbacks[slot] = readback } + if newFarDensityReadbacks[slot] == nil { + guard let readback = device.makeBuffer(length: MemoryLayout.stride, options: .storageModeShared) else { return false } + readback.label = "Gaussian Far Budget Density Readback \(slot)" + readback.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) + newFarDensityReadbacks[slot] = readback + } } if newBudgetState == nil { guard let state = device.makeBuffer(length: MemoryLayout.stride, options: .storageModeShared) else { return false } @@ -219,6 +242,12 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { histogram.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) newDensityHistogram = histogram } + if newFarDensityHistogram == nil { + guard let histogram = device.makeBuffer(length: MemoryLayout.stride, options: .storageModeShared) else { return false } + histogram.label = "Gaussian Far Budget Density Histogram" + histogram.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) + newFarDensityHistogram = histogram + } for index in newEntityConstants.indices where newEntityConstants[index] == nil { guard let buffer = device.makeBuffer( length: MemoryLayout.stride * Int(gaussianMaxEntitiesPerFrame), @@ -238,6 +267,8 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { budgetReadbacks = newBudgetReadbacks _densityHistogram = newDensityHistogram densityReadbacks = newDensityReadbacks + _farDensityHistogram = newFarDensityHistogram + farDensityReadbacks = newFarDensityReadbacks _capacity = newCapacity MemoryBudgetManager.shared.setGaussianWorkingSetBytes(residentBytesLocked) return true @@ -271,6 +302,20 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { return densityReadbacks[min(slot, densityReadbacks.count - 1)] } + /// The far priority band's persistent density histogram (issue #1423). + var farDensityHistogram: MTLBuffer? { + lock.lock() + defer { lock.unlock() } + return _farDensityHistogram + } + + /// The copy of the far density histogram the frame publishes for `slot`'s readback. + func farDensityReadback(slot: Int) -> MTLBuffer? { + lock.lock() + defer { lock.unlock() } + return farDensityReadbacks[min(slot, farDensityReadbacks.count - 1)] + } + /// Forgets the previous frames' scale and density cap, so the next frame takes its target /// directly. For tests that want to start from a known state with no frame in flight; a /// running scene resets through `noteFrameWithoutEntities` on the GPU's own timeline instead. @@ -279,6 +324,7 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { defer { lock.unlock() } _budgetState?.contents().storeBytes(of: GaussianBudgetState(), as: GaussianBudgetState.self) _densityHistogram?.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) + _farDensityHistogram?.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) _hysteresisResetPending = false } @@ -322,7 +368,7 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { return entityOrder[min(slot, entityOrder.count - 1)] } - func recordCompletedFrame(visibleCount: Int, overflowCount: Int, budgetState: GaussianBudgetState? = nil, densityHistogram: GaussianBudgetDensityHistogram? = nil) { + func recordCompletedFrame(visibleCount: Int, overflowCount: Int, budgetState: GaussianBudgetState? = nil, densityHistogram: GaussianBudgetDensityHistogram? = nil, farDensityHistogram: GaussianBudgetDensityHistogram? = nil) { lock.lock() _lastVisibleCount = visibleCount _lastOverflowCount = overflowCount @@ -332,6 +378,9 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { if let densityHistogram { _lastDensityHistogram = densityHistogram } + if let farDensityHistogram { + _lastFarDensityHistogram = farDensityHistogram + } lock.unlock() } @@ -345,7 +394,8 @@ final class GaussianSharedWorkingSet: @unchecked Sendable { private var residentBytesLocked: Int { let buffers: [MTLBuffer?] = keys + records + visibleSets + entityConstants + - budgetReadbacks + [_budgetState] + densityReadbacks + [_densityHistogram] + budgetReadbacks + [_budgetState] + densityReadbacks + [_densityHistogram] + + farDensityReadbacks + [_farDensityHistogram] return buffers.reduce(0) { $0 + ($1?.length ?? 0) } } diff --git a/Sources/UntoldEngine/Systems/GaussianSystem.swift b/Sources/UntoldEngine/Systems/GaussianSystem.swift index 587f75bcd..36f3a012e 100644 --- a/Sources/UntoldEngine/Systems/GaussianSystem.swift +++ b/Sources/UntoldEngine/Systems/GaussianSystem.swift @@ -317,9 +317,10 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { let chunkPipelines = GaussianChunkCullPipelineStates.current() let budgetState = workingSet.budgetState let densityHistogram = workingSet.densityHistogram + let farDensityHistogram = workingSet.farDensityHistogram let frameSlot = min(renderInfo.currentInFlightFrameSlot, maxInFlightCommandBuffers - 1) - if let chunkPipelines, let budgetState, let densityHistogram { - encodeGaussianBudgetReset(computeEncoder, pipelines: chunkPipelines, budgetState: budgetState, densityHistogram: densityHistogram) + if let chunkPipelines, let budgetState, let densityHistogram, let farDensityHistogram { + encodeGaussianBudgetReset(computeEncoder, pipelines: chunkPipelines, budgetState: budgetState, densityHistogram: densityHistogram, farDensityHistogram: farDensityHistogram) profileTotals.dispatchCount += 1 } let hzb = gaussianHZBInputs() @@ -353,7 +354,7 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { let matrices = GaussianEntityFrameMatrices(worldTransform: worldTransformComponent, gaussianComponent: gaussianComponent, cameraComponent: cameraComponent) if gaussianComponent.isChunked { - guard let chunkPipelines, let budgetState, let densityHistogram, let chunkTable = gaussianComponent.chunkTable, + guard let chunkPipelines, let budgetState, let densityHistogram, let farDensityHistogram, let chunkTable = gaussianComponent.chunkTable, frameSlot < chunkTable.visibleChunks.count, frameSlot < chunkTable.visibleChunkSets.count else { handleError(.pipelineStateNulled, "Gaussian chunk kernels") @@ -375,7 +376,8 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { hzbValid: hzb.valid, forceAllVisible: gaussianComponent.opacityScale <= 0 ? false : GaussianDebugOptions.shared.disableChunkCull, uniformQuotas: uniformQuotas, - paged: gaussianComponent.pager == nil ? 0 : 1 + paged: gaussianComponent.pager == nil ? 0 : 1, + cameraPositionWorld: matrices.effectiveCameraPosition ) // A hidden entity lists no chunk and its pager does not tick: no demand, no reads, // its pages kept for when it reappears. @@ -459,6 +461,7 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { chunkSet: chunkSet, budgetState: budgetState, densityHistogram: densityHistogram, + farDensityHistogram: farDensityHistogram, constants: chunkConstants, hzbTexture: hzb.texture, residency: pagerBindings?.residency, @@ -492,7 +495,8 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { hzbValid: hzb.valid, forceAllVisible: false, uniformQuotas: uniformQuotas, - paged: 2 + paged: 2, + cameraPositionWorld: matrices.effectiveCameraPosition ) let tierBindings = tierPager.tick(slot: frameSlot, frame: GaussianPagerFrameInputs( cullConstants: tierConstants, @@ -634,7 +638,7 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { // entities went by), each entity's quota pass grants its visible chunks // min(splats, floor(cap × screen area)), and the state and the histogram are published for // this slot's readback. - if let chunkPipelines, let budgetState, let densityHistogram { + if let chunkPipelines, let budgetState, let densityHistogram, let farDensityHistogram { let scaleConstants = gaussianBudgetScaleConstants( budget: capacity, resetHysteresis: workingSet.takeHysteresisReset(), @@ -642,7 +646,7 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { densityFloor: frameDensityFloor, tierShifts: maximumTierShifts ?? (0, 0) ) - encodeGaussianBudgetScale(computeEncoder, pipelines: chunkPipelines, budgetState: budgetState, densityHistogram: densityHistogram, constants: scaleConstants) + encodeGaussianBudgetScale(computeEncoder, pipelines: chunkPipelines, budgetState: budgetState, densityHistogram: densityHistogram, farDensityHistogram: farDensityHistogram, constants: scaleConstants) profileTotals.dispatchCount += 1 for chunked in chunkedEntities { encodeGaussianChunkQuotas( @@ -658,14 +662,18 @@ public func executeGaussianFrustumCulling(_ commandBuffer: MTLCommandBuffer) { ) profileTotals.dispatchCount += 1 } - if let readback = workingSet.budgetReadback(slot: frameSlot), let densityReadback = workingSet.densityReadback(slot: frameSlot) { + if let readback = workingSet.budgetReadback(slot: frameSlot), let densityReadback = workingSet.densityReadback(slot: frameSlot), + let farDensityReadback = workingSet.farDensityReadback(slot: frameSlot) + { encodeGaussianBudgetPublish( computeEncoder, pipelines: chunkPipelines, budgetState: budgetState, readback: readback, densityHistogram: densityHistogram, - densityReadback: densityReadback + densityReadback: densityReadback, + farDensityHistogram: farDensityHistogram, + farDensityReadback: farDensityReadback ) profileTotals.dispatchCount += 1 } @@ -942,7 +950,8 @@ public func executeGaussianPreprocess(_ commandBuffer: MTLCommandBuffer) { viewMatrix: matrices.viewMatrix, hzbValid: hzb.valid, uniformQuotas: uniformQuotas, - paged: pagerBindings == nil ? 0 : 1 + paged: pagerBindings == nil ? 0 : 1, + cameraPositionWorld: matrices.effectiveCameraPosition ) // The coarse levels the cull and the quota pass of this frame ran with, on the same // clock (the pager's tick, or the executed-frame counter the cull stepped). diff --git a/Sources/UntoldEngine/Systems/RegistrationSystem.swift b/Sources/UntoldEngine/Systems/RegistrationSystem.swift index ec811ad2f..7e6146c2e 100644 --- a/Sources/UntoldEngine/Systems/RegistrationSystem.swift +++ b/Sources/UntoldEngine/Systems/RegistrationSystem.swift @@ -6233,6 +6233,48 @@ public func gaussianPagingStats(entityId: EntityID) -> GaussianPagingStats? { scene.get(component: GaussianComponent.self, for: entityId)?.pager?.stats } +/// The frame's shared Gaussian working-set budget solve — two or three frames late, the GPU +/// readback's own lag — for diagnosing whether a scene's chunked entities are actually being +/// thinned by the working-set budget, independent of how the render looks: `requestedSplats` +/// is what every chunked entity's visible chunks asked for this frame, `quotaSplats` is what +/// the budget actually granted (equal to `requestedSplats` when nothing was cut), `densityCap` +/// (and `farDensityCap`, the far priority band's — see `GaussianPagingPolicy +/// .distancePrioritizedBudget`, issue #1423) are the per-chunk screen-weighted quota's caps, +/// `+infinity` when every chunk draws whole. nil before any chunked entity has completed a +/// frame. +public struct GaussianBudgetSnapshot: Equatable, Sendable { + public var requestedSplats: Int + public var quotaSplats: Int + public var reservedSplats: Int + public var budget: Int + public var scale: Float + public var densityCap: Float + public var farDensityCap: Float + /// Incoming entries drawn at a coarse level this frame (any entity with per-chunk coarse + /// levels loaded), and their quota sum — 0/0 whenever no chunk anywhere drew coarse, whether + /// because no loaded entity has coarse levels baked in or because the level rule never + /// picked one at the frame's density caps. + public var coarseChunks: Int + public var coarseSplats: Int +} + +public func gaussianBudgetSnapshot() -> GaussianBudgetSnapshot? { + let workingSet = GaussianSharedWorkingSet.shared + guard workingSet.capacity > 0 else { return nil } + let state = workingSet.lastBudgetState + return GaussianBudgetSnapshot( + requestedSplats: Int(state.requestedSplats), + quotaSplats: Int(state.quotaSplats), + reservedSplats: Int(state.reservedSplats), + budget: Int(state.budget), + scale: state.scale, + densityCap: state.densityCap, + farDensityCap: state.farDensityCap, + coarseChunks: Int(state.coarseChunks), + coarseSplats: Int(state.coarseSplats) + ) +} + func removeEntityCamera(entityId: EntityID) { if scene.get(component: CameraComponent.self, for: entityId) != nil { scene.remove(component: CameraComponent.self, from: entityId) diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib index a9a49f87c..773943643 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-ios.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib index b62d457bf..a0def4f86 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-iossim.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib index 4279b21d7..af9684126 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvos.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib index 19790bb34..028390765 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-tvossim.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib index ba99f9f66..eda7bd962 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xros.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib index 737048261..619c87615 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels-xrossim.metallib differ diff --git a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib index 4acff19c7..d8a41ae74 100644 Binary files a/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib and b/Sources/UntoldEngine/UntoldEngineKernels/UntoldEngineKernels.metallib differ diff --git a/Tests/UntoldEngineRenderTests/GaussianBudgetedWorkingSetTest.swift b/Tests/UntoldEngineRenderTests/GaussianBudgetedWorkingSetTest.swift index b84632b69..7b2b414b4 100644 --- a/Tests/UntoldEngineRenderTests/GaussianBudgetedWorkingSetTest.swift +++ b/Tests/UntoldEngineRenderTests/GaussianBudgetedWorkingSetTest.swift @@ -802,9 +802,9 @@ final class GaussianBudgetedWorkingSetTest: BaseRenderSetup { /// The shared set's bytes that do not scale with the budget: visible sets, entity constants, /// budget state and density histogram (each with its per-slot readbacks). private func fixedWorkingSetBytes() -> Int { - maxInFlightCommandBuffers * (MemoryLayout.stride + MemoryLayout.stride + MemoryLayout.stride) + maxInFlightCommandBuffers * (MemoryLayout.stride + MemoryLayout.stride + 2 * MemoryLayout.stride) + MemoryLayout.stride - + MemoryLayout.stride + + 2 * MemoryLayout.stride + totalPerMeshUniformBuffers() * MemoryLayout.stride * Int(gaussianMaxEntitiesPerFrame) } diff --git a/Tests/UntoldEngineRenderTests/GaussianChunkCullTest.swift b/Tests/UntoldEngineRenderTests/GaussianChunkCullTest.swift index 82bf2b0c3..6e9cc9c44 100644 --- a/Tests/UntoldEngineRenderTests/GaussianChunkCullTest.swift +++ b/Tests/UntoldEngineRenderTests/GaussianChunkCullTest.swift @@ -1095,9 +1095,9 @@ final class GaussianChunkCullTest: BaseRenderSetup { XCTAssertEqual(constants.hzbOcclusionBias, gaussianCullHZBOcclusionBias) XCTAssertEqual(constants.uniformQuotas, 0, "the weighted quotas are the default") XCTAssertEqual(gaussianChunkCullConstants(chunkTable: table, modelMatrix: world.space, viewMatrix: matrix_identity_float4x4, hzbValid: false, uniformQuotas: true).uniformQuotas, 1) - XCTAssertEqual(MemoryLayout.stride, 208) - XCTAssertEqual(MemoryLayout.stride, 16) + XCTAssertEqual(MemoryLayout.stride, 240) + XCTAssertEqual(MemoryLayout.stride, 20) XCTAssertEqual(MemoryLayout.stride, 48) - XCTAssertEqual(MemoryLayout.stride, 48) + XCTAssertEqual(MemoryLayout.stride, 52) } } diff --git a/Tests/UntoldEngineRenderTests/GaussianChunkLevelTest.swift b/Tests/UntoldEngineRenderTests/GaussianChunkLevelTest.swift index ae60e1d9e..8785e48f1 100644 --- a/Tests/UntoldEngineRenderTests/GaussianChunkLevelTest.swift +++ b/Tests/UntoldEngineRenderTests/GaussianChunkLevelTest.swift @@ -1884,18 +1884,18 @@ final class GaussianChunkLevelTest: BaseRenderSetup { // MARK: - 15: layouts func testLayoutsArePinned() { - XCTAssertEqual(MemoryLayout.stride, 16) + XCTAssertEqual(MemoryLayout.stride, 20) XCTAssertEqual(MemoryLayout.stride, 16) XCTAssertEqual(MemoryLayout.offset(of: \.coarseAvailable), 12) XCTAssertEqual(MemoryLayout.stride, 32) - XCTAssertEqual(MemoryLayout.stride, 208) + XCTAssertEqual(MemoryLayout.stride, 240) XCTAssertEqual(MemoryLayout.stride, 48) XCTAssertEqual(MemoryLayout.stride, 64) XCTAssertEqual(MemoryLayout.stride, 48) XCTAssertEqual(MemoryLayout.offset(of: \.transitionSplats), 32) XCTAssertEqual(MemoryLayout.offset(of: \.coarseChunks), 36) XCTAssertEqual(MemoryLayout.offset(of: \.coarseSplats), 40) - XCTAssertEqual(MemoryLayout.stride, 48) + XCTAssertEqual(MemoryLayout.stride, 52) XCTAssertEqual(MemoryLayout.offset(of: \.densityFloor), 32) XCTAssertEqual(MemoryLayout.offset(of: \.tierShift1), 36) XCTAssertEqual(MemoryLayout.offset(of: \.tierShift2), 40) diff --git a/Tests/UntoldEngineRenderTests/GaussianPagingTest.swift b/Tests/UntoldEngineRenderTests/GaussianPagingTest.swift index d26e253ac..85e0fea78 100644 --- a/Tests/UntoldEngineRenderTests/GaussianPagingTest.swift +++ b/Tests/UntoldEngineRenderTests/GaussianPagingTest.swift @@ -610,7 +610,9 @@ final class GaussianPagingTest: BaseRenderSetup { let pipelines = try XCTUnwrap(GaussianChunkCullPipelineStates.current()) let budgetState = try budgetStateBuffer() let densityHistogram = try densityHistogramBuffer() + let farDensityHistogram = try farDensityHistogramBuffer() densityHistogram.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) + farDensityHistogram.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) memset(fixture.table.demandTables[0].contents(), 0, fixture.table.demandTables[0].length) runSynchronously { commandBuffer in guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return } @@ -622,6 +624,7 @@ final class GaussianPagingTest: BaseRenderSetup { chunkSet: fixture.table.visibleChunkSets[0], budgetState: budgetState, densityHistogram: densityHistogram, + farDensityHistogram: farDensityHistogram, constants: constants, hzbTexture: textureResources.hzbDepthPyramid ?? textureResources.depthMap, residency: fixture.table.residencyTables[0], @@ -1784,7 +1787,7 @@ final class GaussianPagingTest: BaseRenderSetup { XCTAssertEqual(MemoryLayout.offset(of: \.frameIndex), 8) XCTAssertEqual(MemoryLayout.offset(of: \.fadeFrames), 12) XCTAssertEqual(MemoryLayout.offset(of: \.debugMode), 16) - XCTAssertEqual(MemoryLayout.stride, 208) + XCTAssertEqual(MemoryLayout.stride, 240) XCTAssertEqual(MemoryLayout.offset(of: \.paged), 172) XCTAssertEqual(MemoryLayout.offset(of: \.rangeCount), 176) XCTAssertEqual(MemoryLayout.offset(of: \.hzbRateMapSizes), 192) diff --git a/Tests/UntoldEngineRenderTests/GaussianRenderTestSupport.swift b/Tests/UntoldEngineRenderTests/GaussianRenderTestSupport.swift index 2fea4cdcb..7abf7cfdc 100644 --- a/Tests/UntoldEngineRenderTests/GaussianRenderTestSupport.swift +++ b/Tests/UntoldEngineRenderTests/GaussianRenderTestSupport.swift @@ -290,6 +290,13 @@ extension BaseRenderSetup { return try XCTUnwrap(GaussianSharedWorkingSet.shared.densityHistogram) } + /// The frame's persistent far priority band density histogram (issue #1423), allocated with + /// the shared set. + func farDensityHistogramBuffer() throws -> MTLBuffer { + XCTAssertTrue(GaussianSharedWorkingSet.shared.ensureCapacity(1, device: renderInfo.device)) + return try XCTUnwrap(GaussianSharedWorkingSet.shared.farDensityHistogram) + } + /// Encodes one chunk cull of `table` into slot 0 with `constants` — after zeroing the /// persistent histogram, so it holds this cull alone — and returns the record. An entity with /// coarse levels passes its `levels` and `levelConstants` (per-chunk-lod-tiers); with @@ -306,11 +313,13 @@ extension BaseRenderSetup { let pipelines = try XCTUnwrap(GaussianChunkCullPipelineStates.current()) let budgetState = try budgetStateBuffer() let densityHistogram = try densityHistogramBuffer() + let farDensityHistogram = try farDensityHistogramBuffer() densityHistogram.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) + farDensityHistogram.contents().storeBytes(of: GaussianBudgetDensityHistogram(), as: GaussianBudgetDensityHistogram.self) runSynchronously { commandBuffer in guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return } if quotas { - encodeGaussianBudgetReset(encoder, pipelines: pipelines, budgetState: budgetState, densityHistogram: densityHistogram) + encodeGaussianBudgetReset(encoder, pipelines: pipelines, budgetState: budgetState, densityHistogram: densityHistogram, farDensityHistogram: farDensityHistogram) } _ = encodeGaussianChunkCull( encoder, @@ -320,6 +329,7 @@ extension BaseRenderSetup { chunkSet: table.visibleChunkSets[0], budgetState: budgetState, densityHistogram: densityHistogram, + farDensityHistogram: farDensityHistogram, constants: constants, hzbTexture: textureResources.hzbDepthPyramid ?? textureResources.depthMap, levels: levels, @@ -333,7 +343,7 @@ extension BaseRenderSetup { densityFloor: levelConstants.densityFloor, tierShifts: (levelConstants.tierShift1, levelConstants.tierShift2) ) - encodeGaussianBudgetScale(encoder, pipelines: pipelines, budgetState: budgetState, densityHistogram: densityHistogram, constants: scale) + encodeGaussianBudgetScale(encoder, pipelines: pipelines, budgetState: budgetState, densityHistogram: densityHistogram, farDensityHistogram: farDensityHistogram, constants: scale) encodeGaussianChunkQuotas( encoder, pipelines: pipelines, diff --git a/Tests/UntoldEngineRenderTests/GaussianScreenWeightedQuotaTest.swift b/Tests/UntoldEngineRenderTests/GaussianScreenWeightedQuotaTest.swift index 3e61dce6f..b5d16917d 100644 --- a/Tests/UntoldEngineRenderTests/GaussianScreenWeightedQuotaTest.swift +++ b/Tests/UntoldEngineRenderTests/GaussianScreenWeightedQuotaTest.swift @@ -320,11 +320,11 @@ final class GaussianScreenWeightedQuotaTest: BaseRenderSetup { /// The shared layouts the kernels and the readbacks depend on. func testLayoutsArePinned() { - XCTAssertEqual(MemoryLayout.stride, 208) + XCTAssertEqual(MemoryLayout.stride, 240) XCTAssertEqual(MemoryLayout.offset(of: \.hzbRateMapSizes), 192) - XCTAssertEqual(MemoryLayout.stride, 16) + XCTAssertEqual(MemoryLayout.stride, 20) XCTAssertEqual(MemoryLayout.stride, 48) - XCTAssertEqual(MemoryLayout.stride, 48) + XCTAssertEqual(MemoryLayout.stride, 52) XCTAssertEqual(MemoryLayout.stride, 32) XCTAssertEqual(MemoryLayout.stride, 2064) XCTAssertEqual(MemoryLayout.offset(of: \.screenArea), 12) diff --git a/Tests/UntoldEngineTests/GaussianChunkCullMathTests.swift b/Tests/UntoldEngineTests/GaussianChunkCullMathTests.swift index 5dc921d2b..6cf699115 100644 --- a/Tests/UntoldEngineTests/GaussianChunkCullMathTests.swift +++ b/Tests/UntoldEngineTests/GaussianChunkCullMathTests.swift @@ -281,6 +281,88 @@ final class GaussianChunkCullMathTests: XCTestCase { XCTAssertEqual(histogram.requestedSplats, 256 + 16 + 128 + 512 + 512) } + // MARK: - Priority-band density cap (distance-prioritized budget, issue #1423) + + /// `nearPriorityShare` 1.0 restores the original "near takes the whole grant first" solve + /// exactly: a near band whose own demand already exceeds the whole grant gets exactly the + /// cap it would get solved alone, and the far band is left with nothing — modelled on + /// gardenscene's lod0 (≈3.33M splats) against an effective working-set budget far smaller + /// than the scene's total demand. Confirmed by the Sandbox repro (issue #1423) to starve the + /// far band outright in this configuration, which is why the default share is below 1.0. + func testNearPriorityShareOneReproducesTheOriginalUnconditionalProtection() { + let near = GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 50).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }) + let far = GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 50).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }) + let grant: UInt32 = 400_000 // below the near band's own 500,000 splat demand + let alone = GaussianChunkCullMath.densityCap(histogram: near, grant: grant) + let (nearCap, farCap) = GaussianChunkCullMath.densityCap(near: near, far: far, grant: grant, nearPriorityShare: 1.0) + XCTAssertEqual(nearCap, alone, "the near band's cap is exactly what it would get solved alone") + XCTAssertEqual(farCap, 0, "nothing is left for the far band") + } + + /// Below 1.0, near is bounded by its own share rather than unconditionally protected: with + /// both bands demanding 500,000 against a 400,000 grant and an 0.8 share, near is solved + /// against only 320,000 (thinned below what it would get alone) and far is guaranteed its + /// floor, (1 − share) × grant = 80,000 — never the zero a 1.0 share would have left it. + func testNearPriorityShareBelowOneBoundsNearAndGuaranteesFarAFloor() { + let near = GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 50).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }) + let far = GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 50).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }) + let grant: UInt32 = 400_000 + let share: Float = 0.8 + let nearAloneAtFullGrant = GaussianChunkCullMath.densityCap(histogram: near, grant: grant) + let nearAloneAtShare = GaussianChunkCullMath.densityCap(histogram: near, grant: UInt32(share * Float(grant))) + let (nearCap, farCap) = GaussianChunkCullMath.densityCap(near: near, far: far, grant: grant, nearPriorityShare: share) + XCTAssertEqual(nearCap, nearAloneAtShare, "near is solved against its share of the grant, not the whole grant") + XCTAssertLessThan(nearCap, nearAloneAtFullGrant, "and so is thinned further than a 1.0 share would leave it") + XCTAssertGreaterThan(farCap, 0, "far keeps a guaranteed floor instead of being starved to zero") + } + + /// A near band that fits the grant alone keeps its full (infinite) cap, and the far band + /// absorbs the whole shortfall — strictly worse than the uniform single-histogram cap over + /// their union, which is the uniform-thinning behavior the banding replaces. + func testDensityCapByBandLetsTheFarBandAbsorbTheWholeShortfall() { + let near = GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 20).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }) // 200,000 + let far = GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 50).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }) // 500,000 + let grant: UInt32 = 400_000 // fits the near band alone (and its 1.0-share ceiling); the union (700,000) does not + let (nearCap, farCap) = GaussianChunkCullMath.densityCap(near: near, far: far, grant: grant, nearPriorityShare: 1.0) + XCTAssertEqual(nearCap, .infinity, "the near band fits the grant alone") + let uniformCap = GaussianChunkCullMath.densityCap( + histogram: GaussianChunkCullMath.densityHistogram(chunks: (0 ..< 70).map { _ in (splatCount: UInt32(10000), screenArea: Float(1.0)) }), + grant: grant + ) + XCTAssertLessThan(farCap, uniformCap, "banding pushes more of the shortfall onto the far band than a uniform cap would") + XCTAssertGreaterThan(farCap, 0) + } + + /// `mixDensityCap` (issue #1423): the exact endpoint at t's extremes, a linear blend between + /// two finite caps, and — the one case a raw mix cannot take, since infinity times zero is + /// NaN, not zero — the nearer endpoint outright, never a blend, whenever either cap is + /// infinite and t has not fully reached it. + func testMixedQuotaBlendsTheTwoBandsGrantsContinuouslyEvenAcrossAnInfiniteCap() { + let splatCount: UInt32 = 1000 + let area: Float = 1.0 + + // Two finite caps: a linear blend of the quotas each alone would grant. + XCTAssertEqual(GaussianChunkCullMath.mixedQuota(nearCap: 2000, farCap: 100, screenArea: area, splatCount: splatCount, t: 0), 1000, "t = 0 is exactly the near band's own grant") + XCTAssertEqual(GaussianChunkCullMath.mixedQuota(nearCap: 2000, farCap: 100, screenArea: area, splatCount: splatCount, t: 1), 100, "t = 1 is exactly the far band's own grant") + XCTAssertEqual(GaussianChunkCullMath.mixedQuota(nearCap: 2000, farCap: 100, screenArea: area, splatCount: splatCount, t: 0.5), 550) + + // An infinite cap (a band that currently grants the chunk's whole count) blends like any + // other finite grant — quota(densityCap:) already resolves it to splatCount before the + // blend ever sees it — so there is no NaN and, critically, no discontinuity: adjacent t + // values differ by only a few splats, not by hundreds, all the way through t = 0.5 (the + // point an earlier, cap-blending version of this used as a hard switch and which showed + // up as chunks visibly flickering on and off, issue #1423). + let nearInfiniteQuotas = (0 ... 20).map { step in + GaussianChunkCullMath.mixedQuota(nearCap: .infinity, farCap: 100, screenArea: area, splatCount: splatCount, t: Float(step) / 20) + } + XCTAssertEqual(nearInfiniteQuotas.first, 1000) + XCTAssertEqual(nearInfiniteQuotas.last, 100) + for (a, b) in zip(nearInfiniteQuotas, nearInfiniteQuotas.dropFirst()) { + XCTAssertLessThanOrEqual(abs(Int(a) - Int(b)), 50, "no step changes the quota by more than a fraction of the total range") + } + XCTAssertFalse(Float(GaussianChunkCullMath.mixedQuota(nearCap: .infinity, farCap: 100, screenArea: area, splatCount: splatCount, t: 0.5)).isNaN) + } + // MARK: - The cross-fade /// (1 − α_in)(1 − α_out) = 1 − α for every α and w: the two windows compose to the surface's diff --git a/Tests/UntoldEngineTests/GaussianPagingPolicyTests.swift b/Tests/UntoldEngineTests/GaussianPagingPolicyTests.swift index 03ebe4c8e..dd3721196 100644 --- a/Tests/UntoldEngineTests/GaussianPagingPolicyTests.swift +++ b/Tests/UntoldEngineTests/GaussianPagingPolicyTests.swift @@ -175,6 +175,79 @@ final class GaussianPagingPolicyTests: XCTestCase { XCTAssertEqual(GaussianPagingPolicy.fillDensityCap(histogram: histogram, room: GaussianPagingPolicy.fillRoom(budget: Int.max, reservedSplats: 0), levels: levels), .infinity, "an unlimited budget") } + // MARK: - Priority-band fill density cap (distance-prioritized paging, issue #1423) + + /// `nearPriorityShare` 1.0 restores the original "near takes the whole room first" solve + /// exactly: when the near band's own demand already exceeds the room, it gets exactly the + /// cap it would get solved alone and the far band is left with none; when the near band + /// fits the room alone, it keeps an infinite cap and the far band absorbs the whole + /// remaining demand against whatever room is left. + func testFillDensityCapByBandAtShareOneReproducesTheOriginalUnconditionalProtection() { + func chunksHistogram(count: Int, n: UInt32, area: Float) -> GaussianBudgetDensityHistogram { + var histogram = GaussianBudgetDensityHistogram() + for _ in 0 ..< count { + GaussianPagingPolicy.addFillTerm(to: &histogram, splatCount: n, area: area, coarseCounts: (0, 0)) + } + return histogram + } + + // The near band alone (500,000 splats demanded) already exceeds the room. + let near = chunksHistogram(count: 50, n: 10000, area: 1) + let far = chunksHistogram(count: 50, n: 10000, area: 1) + let room: Float = 400_000 + let alone = GaussianPagingPolicy.fillDensityCap(histogram: near, room: room, levels: nil) + let (nearCap, farCap) = GaussianPagingPolicy.fillDensityCapByBand(near: near, far: far, room: room, levels: nil, nearPriorityShare: 1.0) + XCTAssertEqual(nearCap, alone, "the near band's cap is exactly what it would get solved alone") + XCTAssertEqual(farCap, 0, "nothing is left for the far band") + + // The near band (200,000) fits the room alone; the far band (500,000) absorbs the rest. + let smallNear = chunksHistogram(count: 20, n: 10000, area: 1) + let (smallNearCap, farCapAfterFit) = GaussianPagingPolicy.fillDensityCapByBand(near: smallNear, far: far, room: room, levels: nil, nearPriorityShare: 1.0) + XCTAssertEqual(smallNearCap, .infinity, "the near band fits the room alone") + let union = chunksHistogram(count: 70, n: 10000, area: 1) + let uniformCap = GaussianPagingPolicy.fillDensityCap(histogram: union, room: room, levels: nil) + XCTAssertLessThan(farCapAfterFit, uniformCap, "banding pushes more of the shortfall onto the far band than the uniform cap would") + XCTAssertGreaterThan(farCapAfterFit, 0) + } + + /// Below 1.0, near is bounded by its own share of the room, and far is guaranteed a floor + /// of at least `(1 - share) * room` — the Sandbox repro of issue #1423 found a 1.0 share + /// starves far to exactly 0 whenever near's own demand alone saturates the room, which this + /// default protects against. + func testFillDensityCapByBandBelowOneGuaranteesFarAFloor() { + func chunksHistogram(count: Int, n: UInt32, area: Float) -> GaussianBudgetDensityHistogram { + var histogram = GaussianBudgetDensityHistogram() + for _ in 0 ..< count { + GaussianPagingPolicy.addFillTerm(to: &histogram, splatCount: n, area: area, coarseCounts: (0, 0)) + } + return histogram + } + let near = chunksHistogram(count: 50, n: 10000, area: 1) // 500,000, exceeds the room alone + let far = chunksHistogram(count: 50, n: 10000, area: 1) + let room: Float = 400_000 + let share: Float = 0.8 + let (nearCap, farCap) = GaussianPagingPolicy.fillDensityCapByBand(near: near, far: far, room: room, levels: nil, nearPriorityShare: share) + let nearAloneAtShare = GaussianPagingPolicy.fillDensityCap(histogram: near, room: share * room, levels: nil) + XCTAssertEqual(nearCap, nearAloneAtShare, "near is solved against its share of the room, not the whole room") + XCTAssertGreaterThan(farCap, 0, "far keeps a guaranteed floor instead of being starved to zero") + } + + func testNearPriorityDistanceAndDistancePrioritizedBudgetKnobs() { + XCTAssertEqual(GaussianPagingPolicy.nearPriorityDistanceInEffect, GaussianPagingPolicy.nearPriorityDistance) + XCTAssertEqual(GaussianPagingPolicy.nearPriorityShareInEffect, GaussianPagingPolicy.nearPriorityShare) + XCTAssertFalse(GaussianPagingPolicy.distancePrioritizedBudget, "off by default: every chunk bins near until a caller opts in with a scene-matched nearPriorityDistance") + GaussianPagingPolicy.nearPriorityDistanceOverride = 42 + XCTAssertEqual(GaussianPagingPolicy.nearPriorityDistanceInEffect, 42) + GaussianPagingPolicy.nearPriorityShareOverride = 0.5 + XCTAssertEqual(GaussianPagingPolicy.nearPriorityShareInEffect, 0.5) + GaussianPagingPolicy.distancePrioritizedBudget = true + XCTAssertTrue(GaussianPagingPolicy.distancePrioritizedBudget) + GaussianPagingPolicy.resetKnobs() + XCTAssertEqual(GaussianPagingPolicy.nearPriorityDistanceInEffect, GaussianPagingPolicy.nearPriorityDistance) + XCTAssertEqual(GaussianPagingPolicy.nearPriorityShareInEffect, GaussianPagingPolicy.nearPriorityShare) + XCTAssertFalse(GaussianPagingPolicy.distancePrioritizedBudget) + } + func testUniformModeWantsTheScaledCount() { let n: UInt32 = 1000 XCTAssertEqual(GaussianPagingPolicy.wantedRanks(splatCount: n, area: 0.001, densityCap: 0.25, fillDensity: 1, fillScale: 0.5, uniformQuotas: true, disableWorkingSetBudget: false), 500, "the fill scale over the full counts, never the read-back cap: that cap scales the resident ranks the kernel listed and has no fixed point over the full count") diff --git a/docs/API/UsingGaussianSystem.md b/docs/API/UsingGaussianSystem.md index 054ea9453..536dc903e 100644 --- a/docs/API/UsingGaussianSystem.md +++ b/docs/API/UsingGaussianSystem.md @@ -335,6 +335,62 @@ target and full densities, the grant and the visible chunk count) or the targetScale=… density=… targetDensity=… visibleChunks=… fill=…`, `LogCategory.gaussian`; `fill` is the quota sum over the grant). +### Distance-prioritized budget (near/far priority bands) + +The density-cap solve above picks one cap `d` for the whole frame: a budget shortfall thins +every visible chunk by the same proportional amount, near or far. For a scene whose nearest +tier alone exceeds the working set — a `.ply` capture with a few million splats against +visionOS's 1,000,000-splat budget, for instance — this reads as the entire frame looking +uniformly sparse rather than staying dense close to the camera and thinning only in the +distance. `GaussianPagingPolicy.distancePrioritizedBudget` (`Bool`, off by default) splits the +solve into two bands instead: + +- **`nearPriorityDistance`** (`Float`, default 10.0 world units; override with + `nearPriorityDistanceOverride`) is the local-space distance from the camera under which a + chunk is fully "near." The default is a placeholder — it has to be set to a figure that + matches the asset's own scale (a raw photogrammetry/SfM capture is routinely hundreds of + units across, not metres), or the split does nothing: everything lands in one band and the + solve is identical to the single-cap behaviour above. +- **`priorityTransitionWidth`** (`Float`, default 0.0; override with + `priorityTransitionWidthOverride`) is the additional distance, starting at + `nearPriorityDistance`, over which a chunk's priority smoothsteps from fully near (weight 0) + to fully far (weight 1), instead of snapping at `nearPriorityDistance` itself. 0 reproduces + the hard cutoff exactly (the smoothstep's two edges coincide); a chunk's weight is computed + from its own box centre (the same point with or without the splat-scale padding, since the + padding is symmetric) against the camera's position carried into the entity's local + space (the inverse of its model matrix), so a rotated or translated entity's chunks compare + against the camera's true position rather than silently comparing local chunk coordinates to + a world-space point. +- **`nearPriorityShare`** (`Float`, default 0.85; override with `nearPriorityShareOverride`) is + the near band's ceiling as a fraction of the room: the near band is solved against + `nearPriorityShare × room`, not the whole room, so the far band is guaranteed at least + `(1 − nearPriorityShare)` of the room whatever near wants. Near is thinned, not + unconditionally protected, once its own demand exceeds its share — a value of 1.0 restores + "near takes the whole room first, far gets what's left, possibly nothing," which was found in + practice to starve the far band to exactly zero (chunks disappearing outright, not thinning) + whenever the near band alone saturated the budget. + +A chunk's actual quota blends what the two bands' own caps would grant it, +`mix(nearQuota, farQuota, weight)`, not a blend of the caps themselves: a density cap can be +`+inf` (a band drawing everything whole), and blending two caps directly is NaN-prone in that +case (`+inf × 0` is NaN, not 0) — any finite fallback for it creates a hard step in the +resulting quota exactly where the fallback switches sides, which showed up as chunks visibly +flickering on and off as the camera moved. Blending two already-finite quotas has no such +discontinuity. A chunk's discrete coarse-level pick (see "Per-chunk coarse levels" above) still +resolves to one band's cap outright — "70 % fine, 30 % coarse" has no meaning — but the level's +*quota* once picked is blended the same way, so the far band's chunks naturally lean on their +baked coarse levels (merged, lower-density splats) under pressure rather than only ever +thinning their fine records. + +`gaussianBudgetSnapshot() -> GaussianBudgetSnapshot?` reads the last completed frame's shared +budget state for diagnosing whether, and how much, a scene is actually being thinned: +`requestedSplats` vs. `quotaSplats` (equal when nothing was cut), `densityCap`/`farDensityCap` +(the near and far bands' caps, `+inf` when a band draws everything whole), `scale`, `budget`, +`reservedSplats`, and `coarseChunks`/`coarseSplats` (incoming entries drawn at a coarse level +this frame, and their quota sum — 0/0 if no loaded entity has coarse levels baked in, or the +level rule never picked one at the frame's caps). `nil` before any chunked entity has completed +a frame. + ### Cost and switches | Resident per splat | `.untoldgs` (chunked) | `.ply` / CPU-decoded (whole buffer) |