Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions Sources/CShaderTypes/ShaderTypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
133 changes: 133 additions & 0 deletions Sources/UntoldEngine/RuntimeAssets/GaussianPagingPolicy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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 }
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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() }
Expand Down
Loading
Loading