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
46 changes: 43 additions & 3 deletions Sources/UntoldEngine/Renderer/RenderPasses.swift
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,25 @@ public enum RenderPasses {
refuseTileLightStage(state, reason: "the stage's imageblock needs \(tileMemoryNeeded) bytes in a 16×16 tile, the GPU's tile memory holds \(renderInfo.device.maxThreadgroupMemoryLength)")
return nil
}
// Left at 0×0 (auto), Metal sometimes picks a tile whose thread count
// (dispatchThreadsPerTile covers it one thread per pixel) exceeds this very
// pipeline's own maxTotalThreadsPerThreadgroup -- seen under ARKit camera
// capture, where the GPU's tile budget is squeezed by the capture pipeline.
// Request the largest square tile that fits both the memory budget above and
// the pipeline's thread budget, so the dispatch below can never overrun it.
var tileSide = 16
while tileSide * 2 * (tileSide * 2) <= state.maxTotalThreadsPerThreadgroup,
bytesPerSample * max(1, renderInfo.opaqueSampleCount) * (tileSide * 2) * (tileSide * 2)
<= renderInfo.device.maxThreadgroupMemoryLength
{
tileSide *= 2
}
guard tileSide * tileSide <= state.maxTotalThreadsPerThreadgroup else {
refuseTileLightStage(state, reason: "the smallest 16×16 tile needs \(tileSide * tileSide) threads, the pipeline's budget is \(state.maxTotalThreadsPerThreadgroup)")
return nil
}
descriptor.tileWidth = tileSide
descriptor.tileHeight = tileSide
descriptor.imageblockSampleLength = state.imageblockSampleLength
return state
#endif
Expand Down Expand Up @@ -5276,8 +5295,29 @@ public enum RenderPasses {
renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreAction.store
renderPassDescriptor.depthAttachment.loadAction = MTLLoadAction.load
renderPassDescriptor.depthAttachment.storeAction = MTLStoreAction.store
renderPassDescriptor.tileWidth = 32
renderPassDescriptor.tileHeight = 32

// A fixed 32x32 tile dispatches 1024 threads (dispatchThreadsPerTile below covers
// the tile one thread per pixel); on a GPU whose tile budget for this pipeline is
// squeezed below that (seen under ARKit camera capture — see the identical fix for
// the light-tile stage above), that overruns initializePipelineState's own
// maxTotalThreadsPerThreadgroup, which hangs or kills the app with no Metal
// validation message to explain why. Pick the largest square tile, up to 32x32,
// that fits both this pipeline's thread budget and its imageblock's memory budget.
let gaussianBytesPerSample = (initializePipelineState.imageblockSampleLength + 15) / 16 * 16
var gaussianTileSide = 16
while gaussianTileSide < 32,
gaussianTileSide * 2 * (gaussianTileSide * 2) <= initializePipelineState.maxTotalThreadsPerThreadgroup,
gaussianBytesPerSample * (gaussianTileSide * 2) * (gaussianTileSide * 2)
<= renderInfo.device.maxThreadgroupMemoryLength
{
gaussianTileSide *= 2
}
guard gaussianTileSide * gaussianTileSide <= initializePipelineState.maxTotalThreadsPerThreadgroup else {
handleError(.pipelineStateNulled, "Gaussian TBDR initialize pipeline's thread budget (\(initializePipelineState.maxTotalThreadsPerThreadgroup)) is too small even for a 16x16 tile")
return
}
renderPassDescriptor.tileWidth = gaussianTileSide
renderPassDescriptor.tileHeight = gaussianTileSide
renderPassDescriptor.imageblockSampleLength = initializePipelineState.imageblockSampleLength

// Snapshot the opaque depth before the pass so splats can be occluded by it.
Expand Down Expand Up @@ -5319,7 +5359,7 @@ public enum RenderPasses {

renderEncoder.pushDebugGroup("Initialize")
renderEncoder.setRenderPipelineState(initializePipelineState)
renderEncoder.dispatchThreadsPerTile(MTLSize(width: 32, height: 32, depth: 1))
renderEncoder.dispatchThreadsPerTile(MTLSize(width: renderEncoder.tileWidth, height: renderEncoder.tileHeight, depth: 1))
profileTotals.dispatchCount += 1
renderEncoder.popDebugGroup()

Expand Down
5 changes: 4 additions & 1 deletion Sources/UntoldEngine/Renderer/UntoldEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,10 @@ public class UntoldRenderer: NSObject, MTKViewDelegate {
renderInfo.reverseZEnabled = true
renderInfo.colorPixelFormat = view.colorPixelFormat
renderInfo.depthPixelFormat = view.depthStencilPixelFormat
renderInfo.viewPort = simd_float2(Float(view.bounds.size.width), Float(view.bounds.size.height))
// Pixels, not points — matches the non-AR create(device:view:) above; drawRectResized
// corrects this on the first resize callback regardless, but starting from the same
// units as the working path avoids a transient wrong-aspect first frame.
renderInfo.viewPort = simd_float2(Float(view.drawableSize.width), Float(view.drawableSize.height))

renderInfo.fence = renderInfo.device.makeFence()
renderInfo.bufferAllocator = MTKMeshBufferAllocator(device: renderInfo.device)
Expand Down
15 changes: 12 additions & 3 deletions Sources/UntoldEngine/Shaders/ARShader.metal
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,18 @@ fragment float4 capturedImageFragmentShader(ImageColorInOut in [[stage_in]],
// Sample Y and CbCr textures to get the YCbCr color at the given texture coordinate
float4 ycbcr = float4(capturedImageTextureY.sample(colorSampler, in.texCoord).r,
capturedImageTextureCbCr.sample(colorSampler, in.texCoord).rg, 1.0);

// Return converted RGB color
return ycbcrToRGBTransform * ycbcr;

float4 rgb = ycbcrToRGBTransform * ycbcr;

// The camera feed is gamma (display-referred); this pass's target holds linear scene
// radiance (see fragmentEnvironmentShader, which writes HDR values straight through to
// the same attachment). Decode sRGB gamma to linear so the two sources agree, or the
// tonemap/exposure pipeline downstream reads the camera image as far brighter than it is.
float3 linearColor = select(rgb.rgb / 12.92f,
powr((rgb.rgb + 0.055f) / 1.055f, 2.4f),
rgb.rgb > 0.04045f);

return float4(linearColor, rgb.a);
}


Expand Down
21 changes: 21 additions & 0 deletions Sources/UntoldEngine/Systems/RenderingSystem.swift
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,27 @@ func UpdateXRRenderingSystem(commandBuffer: MTLCommandBuffer, passDescriptor: MT

commandBuffer.label = "XR Rendering Command Buffer"

// The AR path renders its single eye through this callback with no eye loop around it (see
// the HZB build below), so it never goes through executeXRSystemPass's once-before-the-eyes
// render prep — without this, visibleEntityIds is never snapshotted from this frame's cull
// (every mesh pass filters by it, so nothing draws, not just Gaussian splats), and frustum
// culling, the Gaussian cull/preprocess, and the radix sort that feeds
// GaussianSharedWorkingSet never run (gaussianExecution's first guard then silently skips
// the pass forever, with no error). Mirrors executeXRSystemPass's once-before-the-eyes
// block exactly; the stereo XR path already ran that once, so it must not run again here.
if renderInfo.immersionStyle == .ar {
renderInfo.currentInFlightFrameSlot = acquireUniformFrameSlot()
let loading = AssetLoadingGate.shared.isLoadingAny
if !loading {
visibleEntityIds = tripleVisibleEntities.snapshotForRead(frame: cullFrameIndex)
SceneRootTransform.shared.updateIfNeeded()
performFrustumCulling(commandBuffer: commandBuffer)
executeGaussianFrustumCulling(commandBuffer)
executeGaussianPreprocess(commandBuffer)
executeRadixSort(commandBuffer)
}
}

do {
// This eye's sub-pixel jitter (temporal anti-aliasing), before anything reads the projection.
TemporalAntiAliasing.shared.applyJitter()
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
18 changes: 18 additions & 0 deletions Sources/UntoldEngine/Utils/MathUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,24 @@ public func matrix_float4x4_from_double4x4(_ m: simd_double4x4) -> matrix_float4
)
}

/// Converts a standard (forward-Z, near→0 far→1) right-hand perspective matrix — e.g. one
/// ARKit hands back from `ARCamera.projectionMatrix(for:viewportSize:zNear:zFar:)` — into this
/// engine's reverse-Z convention (near→1 far→0), for use where `renderInfo.reverseZEnabled` is
/// true (every depth compare, HZB occlusion test, and shadow depth in the renderer assumes it).
/// Only the Z-mapping terms change (see `matrixPerspectiveRightHand` vs
/// `matrixPerspectiveRightHandReverseZ`, which differ solely in these two entries); the X/Y
/// terms — including any principal-point offset a real camera's matrix carries that an
/// idealized symmetric FOV does not — are passed through untouched.
public func matrixPerspectiveReverseZ(
fromForwardZ projection: matrix_float4x4, nearZ: Float, farZ: Float
) -> matrix_float4x4 {
var m = projection
let zs = nearZ / (farZ - nearZ)
m.columns.2.z = zs
m.columns.3.z = zs * farZ
return m
}

public func matrixPerspectiveRightHand(
fovyRadians fovy: Float, aspectRatio: Float, nearZ: Float, farZ: Float
) -> matrix_float4x4 {
Expand Down
15 changes: 13 additions & 2 deletions Sources/UntoldEngineAR/UntoldEngineAR.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,17 @@

currentARCamera = currentFrame.camera.viewMatrix(for: .landscapeRight)
let vpSize = CGSize(width: CGFloat(renderInfo.viewPort.x), height: CGFloat(renderInfo.viewPort.y))
currentARProjection = currentFrame.camera.projectionMatrix(for: .landscapeRight, viewportSize: vpSize, zNear: 0.001, zFar: 1000)
let arZNear: CGFloat = 0.001
let arZFar: CGFloat = 1000
let forwardZProjection = currentFrame.camera.projectionMatrix(for: .landscapeRight, viewportSize: vpSize, zNear: arZNear, zFar: arZFar)
// Every depth compare, HZB occlusion test, and shadow depth downstream assumes
// reverseZEnabled's near->1/far->0 mapping (see matrixPerspectiveRightHandReverseZ);
// ARKit's matrix is the standard near->0/far->1 one, so it must be converted here —
// there is no other camera path in the engine that hands reverseZEnabled a
// non-reversed projection.
currentARProjection = renderInfo.reverseZEnabled
? matrixPerspectiveReverseZ(fromForwardZ: forwardZProjection, nearZ: Float(arZNear), farZ: Float(arZFar))
: forwardZProjection

EngineProfiler.shared.beginScope(.renderPrep)
updateARStates(currentFrame: currentFrame)
Expand Down Expand Up @@ -220,7 +230,8 @@
capturedImagePipelineStateDescriptor.vertexFunction = capturedImageVertexFunction
capturedImagePipelineStateDescriptor.fragmentFunction = capturedImageFragmentFunction
capturedImagePipelineStateDescriptor.vertexDescriptor = imagePlaneVertexDescriptor
capturedImagePipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm_srgb
capturedImagePipelineStateDescriptor.colorAttachments[0].pixelFormat =
textureResources.environmentColorMap?.pixelFormat ?? .bgra8Unorm_srgb
capturedImagePipelineStateDescriptor.depthAttachmentPixelFormat = .depth32Float
// capturedImagePipelineStateDescriptor.stencilAttachmentPixelFormat = .depth32Float_stencil8

Expand Down
8 changes: 7 additions & 1 deletion Tests/UntoldEngineRenderTests/TileLightStageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,13 @@ final class TileLightStageTests: BaseRenderSetup {
setRendering(.tileLightStage(.enabled))
drawFrame()
XCTAssertTrue(renderInfo.tileLightStageUsed)
XCTAssertEqual(renderInfo.offscreenRenderPassDescriptor.tileWidth, 0, "the tile size is left to Metal")
// No longer left at 0 for Metal to auto-pick: Metal can choose a tile whose thread
// count overruns the pipeline's own maxTotalThreadsPerThreadgroup (seen on device
// under ARKit camera capture, where the GPU's tile budget is squeezed below what it
// picks by default) — tileLightStage now requests an explicit square tile sized to
// fit both the memory and thread budgets, at least the 16x16 floor.
XCTAssertEqual(renderInfo.offscreenRenderPassDescriptor.tileWidth, renderInfo.offscreenRenderPassDescriptor.tileHeight, "the stage requests a square tile")
XCTAssertGreaterThanOrEqual(renderInfo.offscreenRenderPassDescriptor.tileWidth, 16, "never below the smallest tile the memory check already assumed")
XCTAssertGreaterThan(renderInfo.offscreenRenderPassDescriptor.imageblockSampleLength, 0, "the stage tells the pass its imageblock")
}
}
Loading