Sample CodeiOS, iPadOSReviewed 2026-11-01View on Apple Developer

Creating a fog effect using scene depth

At a glance

Item Summary
Purpose Render the camera feed with depth-based fog, using ARKit sceneDepth or smoothedSceneDepth, a Metal Performance Shaders blur, and a Metal fragment shader.
App architecture Storyboard UIKit app. ViewController creates the ARSession and a Renderer, and forwards MTKViewDelegate callbacks to it. Renderer reads session.currentFrame on every draw and encodes a blur pass and a fog pass.
Main patterns View-controller organization, a RenderDestinationProvider protocol that MTKView conforms to, and MetalKit and ARKit delegate callbacks
Project style Flat ARDepthDataExample/ folder: app and scene delegates, controller, renderer, and the Metal shader with its bridged ShaderTypes.h
Execution model MTKView draw callbacks drive a pull-based render loop. A DispatchSemaphore limits command buffers in flight to three. The error alert is sent to DispatchQueue.main.
State/event model The renderer pulls the latest frame from ARSession.currentFrame instead of receiving frame callbacks. A UI switch changes the frame semantics and reruns the session.
Key frameworks/packages ARKit, Metal, MetalKit, MetalPerformanceShaders, UIKit

Project structure

ARDepthDataExample/
├── AppDelegate.swift                 // @UIApplicationMain, scene configuration
├── SceneDelegate.swift               // device-capability gate → unsupported-device screen
├── ViewController.swift              // ARSession, MTKView delegate, smoothing switch
├── Renderer.swift                    // RenderDestinationProvider, per-frame texture upload, blur + fog passes
├── Shaders.metal                     // fogVertexTransform, fogFragmentShader
├── ShaderTypes.h                     // shared C types (bridged)
├── ARDepthDataExampleSwift-Bridging-Header.h
└── Info.plist                        // UIApplicationSceneManifest, arkit/metal capabilities

Structure observations

  • The scene delegate checks device support before showing the AR screen. If scene depth isn’t supported, it replaces the root controller with an “unsupportedDeviceMessage” scene from the storyboard (ARDepthDataExample/SceneDelegate.swift:17).
  • Renderer.swift defines the RenderDestinationProvider protocol. ViewController.swift adds the MTKView conformance (ARDepthDataExample/ViewController.swift:13).

Overall architecture

Reference code

ARDepthDataExample/ViewController.swift:43 — ViewController.viewDidLoad

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Set this view controller as the session's delegate.
        session = ARSession()
        session.delegate = self
        
        // Set the view to use the default device.
        if let view = self.view as? MTKView {
            view.device = MTLCreateSystemDefaultDevice()
            view.backgroundColor = UIColor.clear
            view.delegate = self
            
            guard view.device != nil else {
                print("Metal is not supported on this device")
                return
            }
            
            // Configure the renderer to draw to the view.
            renderer = Renderer(session: session, metalDevice: view.device!, renderDestination: view)
            // ...
        }
        
    }

Interpretation

ViewController is the composition point. It creates the session, makes itself the MTKView delegate, and passes the session and view to Renderer. The renderer depends on the view only through RenderDestinationProvider.

Ownership and state

Ownership evidence

ARDepthDataExample/Renderer.swift:35 — Renderer stored state

class Renderer {
    let session: ARSession
    let device: MTLDevice
    let inFlightSemaphore = DispatchSemaphore(value: kMaxBuffersInFlight)
    var renderDestination: RenderDestinationProvider
    // ...
}
Owner Object or state Relationship Mutation authority
ViewController session, configuration, renderer Creates and stores (ARDepthDataExample/ViewController.swift:28, ARDepthDataExample/ViewController.swift:43) ViewController reruns the session when the smoothing switch changes
Renderer session, device, renderDestination Received in init (ARDepthDataExample/Renderer.swift:69) Set once
Renderer commandQueue, imagePlaneVertexBuffer, fogPipelineState, texture cache Created in loadMetal() Renderer
Renderer cameraImageTextureY/CbCr, depthTexture, confidenceTexture Replaced each frame in updateAppState() (ARDepthDataExample/Renderer.swift:200) Renderer
Renderer blurFilter, filteredDepthTexture Created lazily the first time a depth texture is available (ARDepthDataExample/Renderer.swift:342) Renderer
Renderer viewportSize Set through drawRectResized(size:) from the controller ViewController → Renderer

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Backpressure DispatchSemaphore(value: kMaxBuffersInFlight) update() waits before encoding. The command-buffer completion handler signals. This limits GPU work in flight to three frames. It doesn’t protect shared state. ARDepthDataExample/Renderer.swift:35, ARDepthDataExample/Renderer.swift:86, ARDepthDataExample/Renderer.swift:98
Render loop MTKViewDelegate.draw(in:) Each view draw calls renderer.update() ARDepthDataExample/ViewController.swift:86
Frame acquisition session.currentFrame polling The renderer pulls the latest frame at draw time. It does not receive session(_:didUpdate:). ARDepthDataExample/Renderer.swift:195
Main-queue scheduling DispatchQueue.main.async Presents the AR-session failure alert. Its restart action reruns the session with .resetSceneReconstruction. ARDepthDataExample/ViewController.swift:101
Callback capture [weak self] in addCompletedHandler The completion handler doesn’t keep the renderer alive ARDepthDataExample/Renderer.swift:96

Reference code

ARDepthDataExample/Renderer.swift:86 — frames in flight are limited

    func update() {
        // Wait to ensure only kMaxBuffersInFlight are getting proccessed by any stage in the Metal
        // pipeline (App, Metal, Drivers, GPU, etc).
        _ = inFlightSemaphore.wait(timeout: DispatchTime.distantFuture)
        
        // Create a new command buffer for each renderpass to the current drawable.
        if let commandBuffer = commandQueue.makeCommandBuffer() {
            commandBuffer.label = "MyCommand"
            // ...
            commandBuffer.addCompletedHandler { [weak self] commandBuffer in
                if let strongSelf = self {
                    strongSelf.inFlightSemaphore.signal()
                }
            }
            // ...
        }
    }

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
State propagation Frame-semantics switch The @IBAction changes between .smoothedSceneDepth and .sceneDepth, then reruns the session ARDepthDataExample/ViewController.swift:126
State propagation Fallback depth source The renderer uses smoothedSceneDepth if present, otherwise sceneDepth ARDepthDataExample/Renderer.swift:232
GPU data flow Fragment textures 0–3 Camera Y and CbCr, blurred depth, and confidence are bound to the indices the shader declares ARDepthDataExample/Renderer.swift:312, ARDepthDataExample/Shaders.metal:67
Framework import ARKit, Metal, MetalKit, MetalPerformanceShaders Imported by the renderer ARDepthDataExample/Renderer.swift:12
Framework import ARKit Imported by the scene delegate for the capability check ARDepthDataExample/SceneDelegate.swift:9
Local header ShaderTypes.h Bridged to Swift ARDepthDataExample/ARDepthDataExampleSwift-Bridging-Header.h:8

Platform boundary

The project targets iPhone and iPad (TARGETED_DEVICE_FAMILY = "1,2", ARDepthDataExample.xcodeproj/project.pbxproj:354). On iOS 27, the controller passes the view’s layer to the session and supports all orientations. The renderer then uses session.viewRotationAngle for the display transform. Earlier versions are fixed to .landscapeRight (ARDepthDataExample/ViewController.swift:47, ARDepthDataExample/Renderer.swift:275).

Class and protocol design

Reference code

ARDepthDataExample/Renderer.swift:14 — RenderDestinationProvider

protocol RenderDestinationProvider {
    var currentRenderPassDescriptor: MTLRenderPassDescriptor? { get }
    var currentDrawable: CAMetalDrawable? { get }
    var colorPixelFormat: MTLPixelFormat { get set }
    var sampleCount: Int { get set }
}
Type Responsibility Depends on
SceneDelegate Device-capability gate ARWorldTrackingConfiguration.supportsFrameSemantics
ViewController Session lifecycle, view delegate forwarding, smoothing toggle, error alert ARSession, Renderer
Renderer Per-frame texture upload, image-plane transform, blur pass, fog pass ARSession, RenderDestinationProvider, MPS
fogFragmentShader Mixes camera color toward grey by clamped depth / 4 m, with an optional confidence overlay Bound textures

Access control

Symbol Access Verified effect Likely rationale
Renderer.setMTLPixelFormat(_:basedOn:) fileprivate Visible only inside Renderer.swift Inference: a pixel-format helper used only by depth-texture setup
Renderer properties (textures, viewportSize, pipeline state) implicit internal Visible to the whole module. No private modifier hides renderer state. Inference: a sample with a single module and a single owner
ViewController.session, renderer, configuration implicit internal Visible to the whole module Inference: no wider boundary was needed
kMaxBuffersInFlight, kImagePlaneVertexData implicit internal global let Constants shared by the whole module Inference: shared render configuration

Reference code

ARDepthDataExample/Renderer.swift:219 — fileprivate helper

    fileprivate func setMTLPixelFormat(_ texturePixelFormat: inout MTLPixelFormat?, basedOn pixelBuffer: CVPixelBuffer!) {
        if CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_DepthFloat32 {
            texturePixelFormat = .r32Float
        } else if CVPixelBufferGetPixelFormatType(pixelBuffer) == kCVPixelFormatType_OneComponent8 {
            texturePixelFormat = .r8Uint
        } else {
            fatalError("Unsupported ARDepthData pixel-buffer format.")
        }
    }

Logic ownership and placement

Logic Owning type or file Placement rationale
Device capability check SceneDelegate Runs before the AR screen is used (ARDepthDataExample/SceneDelegate.swift:17)
Choosing depth semantics ViewController Session configuration belongs with the session owner (ARDepthDataExample/ViewController.swift:67)
Image-plane transform Renderer.updateImagePlane Recomputed every frame from the viewport size and, on iOS 27, rotation (ARDepthDataExample/Renderer.swift:206)
Depth smoothing for display Renderer.applyGaussianBlur Spatial MPS blur (sigma 5) on the GPU before the fog pass (ARDepthDataExample/Renderer.swift:348)
Fog math fogFragmentShader Per-pixel work stays on the GPU (ARDepthDataExample/Shaders.metal:106)

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization ARDepthDataExample/ViewController.swift:16, ARDepthDataExample/ViewController.swift:43 The controller owns the session and renderer and forwards view callbacks
Protocol-oriented abstraction ARDepthDataExample/Renderer.swift:14, ARDepthDataExample/ViewController.swift:13 Renderer depends on drawable and pixel-format capabilities, not on MTKView
Delegate or data-source callbacks ARDepthDataExample/ViewController.swift:79, ARDepthDataExample/ViewController.swift:91 MTKViewDelegate drives the render loop and resizes. ARSessionDelegate reports failures.

Main application flow

Reference code

ARDepthDataExample/ViewController.swift:86 — view callback drives the renderer

    func draw(in view: MTKView) {
        renderer.update()
    }

ARDepthDataExample/Renderer.swift:195 — renderer pulls the current frame

    func updateAppState() {

        // Get the AR session's current frame.
        guard let currentFrame = session.currentFrame else {
            return
        }
        
        // Prepare the current frame's camera image for transfer to the GPU.
        updateCameraImageTextures(frame: currentFrame)
        // ...
    }

ARDepthDataExample/Renderer.swift:126 — passes are encoded and committed

    func update() {
        // ...
        if let commandBuffer = commandQueue.makeCommandBuffer() {
            // ...
            updateAppState()
            
            applyGaussianBlur(commandBuffer: commandBuffer)
            // ...
            // Finalize rendering here & push the command buffer to the GPU.
            commandBuffer.commit()
        }
    }

Naming conventions

  • Types: Renderer draws. RenderDestinationProvider names the thing that supplies a render target.
  • Protocols: the …Provider suffix describes a supplier capability.
  • Methods: update… for per-frame refresh (updateAppState, updateCameraImageTextures, updateImagePlane), do…RenderPass for encoding, setup… and load… for one-time setup.
  • Files and extensions: one primary type per Swift file. Constants shared with shaders are in ShaderTypes.h.

Architecture takeaways

  • Pulling session.currentFrame inside the view’s draw callback ties AR sampling to the display’s refresh rate and removes the need for a frame-callback queue.
  • A semaphore plus a command-buffer completion handler is a simple, explicit way to limit how far the CPU can run ahead of the GPU. It is backpressure, not a lock.
  • Putting the device-capability gate at scene connection keeps unsupported devices away from the AR controller.
  • Requiring only RenderDestinationProvider lets Renderer render to any drawable source that has the properties it needs.

Source map

Source file Relevant symbols
ARDepthDataExample/AppDelegate.swift AppDelegate, application(_:configurationForConnecting:options:)
ARDepthDataExample/SceneDelegate.swift SceneDelegate, capability gate
ARDepthDataExample/ViewController.swift ViewController, viewDidLoad, draw(in:), smoothingSwitchToggled, MTKView: RenderDestinationProvider
ARDepthDataExample/Renderer.swift RenderDestinationProvider, Renderer, update, updateAppState, updateImagePlane, applyGaussianBlur, doFogRenderPass
ARDepthDataExample/Shaders.metal fogVertexTransform, fogFragmentShader
ARDepthDataExample/ARDepthDataExampleSwift-Bridging-Header.h ShaderTypes.h import
ARDepthDataExample.xcodeproj/project.pbxproj TARGETED_DEVICE_FAMILY