Adding realistic reflections to an AR experience
At a glance
| Item | Summary |
|---|---|
| Purpose | Use ARKit environment texturing to light a reflective sphere, either with automatically placed probes or with probe anchors the app places and refreshes around the object. |
| App architecture | A UIKit storyboard app. AppDelegate checks ARKit support and supplies a scene configuration; an empty SceneDelegate lets the scene manifest load Main.storyboard. One ViewController owns the ARSCNView, runs and pauses the session, receives SceneKit and ARKit delegate callbacks, handles gestures, and manages a nested ManualProbe value. |
| Main patterns | View-controller organization (one controller is the whole feature) and delegate callbacks from ARSCNView and ARSession. |
| Project style | Four Swift files: app delegate, scene delegate, view controller, and Utilities.swift extensions on ARSCNView, SCNNode, CGPoint, and float4x4. |
| Execution model | No Swift concurrency. UI updates are submitted with DispatchQueue.main.async; first-object placement is submitted to DispatchQueue.global(). The controller has no lock. |
| State/event model | Direct mutation of controller properties from gesture actions and delegate callbacks; a didSet on environmentTexturingMode creates or clears the ManualProbe. |
| Key frameworks/packages | ARKit, SceneKit, UIKit. The project declares no Swift package. |
Project structure
EnvironmentTexturing.xcodeproj/ one app target, Swift 5, iOS 15.0 deployment target
EnvironmentTexturing/
├── AppDelegate.swift @UIApplicationMain; ARKit support check; scene configuration
├── SceneDelegate.swift UIWindowSceneDelegate with empty lifecycle methods
├── ViewController.swift ViewController + nested ManualProbe struct
├── Utilities.swift smartHitTest, extents, float4x4(translation:)
├── Base.lproj/Main.storyboard scene storyboard (ViewController, segmented control, gestures)
└── Resources/Info.plist UIApplicationSceneManifest, arkit device capability
Documentation/ README images
Structure observations
- The scene manifest names
$(PRODUCT_MODULE_NAME).SceneDelegateand theMainstoryboard, with multiple scenes disabled (EnvironmentTexturing/Resources/Info.plist:31,EnvironmentTexturing/Resources/Info.plist:43).SceneDelegateonly checks that the scene is aUIWindowScene(EnvironmentTexturing/SceneDelegate.swift:15); the storyboard createsViewController. Info.plistrequires thearkitdevice capability (EnvironmentTexturing/Resources/Info.plist:53), andAppDelegatestill guardsARWorldTrackingConfiguration.isSupportedwithfatalError(EnvironmentTexturing/AppDelegate.swift:17).- All feature logic is in
ViewController.swift, organized with// MARK:sections for outlets, configuration, life cycle, session management, environment texturing, delegates, and gestures.
Overall architecture
flowchart LR
App["AppDelegate"] -->|"UISceneConfiguration"| Scene["SceneDelegate + Main.storyboard"]
Scene --> VC["ViewController"]
VC -->|"IBOutlet"| View["ARSCNView"]
View --> Session["ARSession (world tracking + environment texturing)"]
View -. "ARSCNViewDelegate" .-> VC
Session -. "ARSessionDelegate" .-> VC
VC --> Probe["ManualProbe (value)"]
VC -->|"add / remove AREnvironmentProbeAnchor"| Session
Reference code
EnvironmentTexturing/ViewController.swift:72 — delegate wiring and session run
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
// ...
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.session.delegate = self
// ...
}
/// - Tag: RunARSession
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Prevent the screen from dimming to avoid interrupting the AR experience.
UIApplication.shared.isIdleTimerDisabled = true
// Start the AR session with automatic environment texturing.
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
configuration.environmentTexturing = .automatic
sceneView.session.run(configuration)
}
// ...
}Interpretation
Observed: ViewController is the only type with behavior. It assigns itself as both the view delegate and the session delegate, runs the session in viewDidAppear, and pauses it in viewWillDisappear (EnvironmentTexturing/ViewController.swift:105). Mode changes and resets go through one method, resetTracking(changeMode:), which removes only probe anchors when switching modes and resets tracking otherwise (EnvironmentTexturing/ViewController.swift:128).
Inference: the app and scene delegates carry no feature state, so the scene-based lifecycle is a launch-time change only; the AR feature does not depend on which lifecycle object created the window.
Ownership and state
classDiagram
ViewController o-- ARSCNView : @IBOutlet sceneView
ARSCNView *-- ARSession : session
ViewController *-- SCNNode : virtualObjectModel
ViewController o-- SCNNode : virtualObject (placed node)
ViewController *-- ManualProbe : manualProbe (optional value)
ManualProbe o-- AREnvironmentProbeAnchor : objectProbeAnchor
ManualProbe o-- AREnvironmentProbeAnchor : sceneProbeAnchor
AppDelegate o-- UIWindow : window
SceneDelegate o-- UIWindow : window
Ownership evidence
EnvironmentTexturing/ViewController.swift:53 — mode state creates and clears the manual probe
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
struct ManualProbe {
// An environment probe for shading the virtual object.
var objectProbeAnchor: AREnvironmentProbeAnchor?
// A fallback environment probe encompassing the whole scene.
var sceneProbeAnchor: AREnvironmentProbeAnchor?
// Indicates whether manually placed probes need updating.
var requiresRefresh: Bool = true
// Tracks timing of manual probe updates to prevent updating too frequently.
var lastUpdateTime: TimeInterval = 0
}
// ...
var manualProbe: ManualProbe?
/// Place environment probes manually or allow ARKit to place them automatically.
var environmentTexturingMode: ARWorldTrackingConfiguration.EnvironmentTexturing = .automatic {
didSet {
switch environmentTexturingMode {
case .manual:
manualProbe = ManualProbe()
default:
manualProbe = nil
}
}
}
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
Storyboard / ViewController |
ARSCNView |
Strong @IBOutlet var sceneView (EnvironmentTexturing/ViewController.swift:27); label, effect view, and segmented control are weak outlets |
Storyboard creates it |
ViewController |
virtualObjectModel |
Stored property initialized by a closure that loads sphere.scn as an SCNReferenceNode (EnvironmentTexturing/ViewController.swift:35) |
Never reassigned |
ViewController |
virtualObject |
Set in place(_:basedOn:) and cleared in restartExperience() (EnvironmentTexturing/ViewController.swift:361, EnvironmentTexturing/ViewController.swift:122) |
ViewController |
ViewController |
manualProbe |
Optional value type; copied, mutated, and written back in updateEnvironmentProbe(atTime:) (EnvironmentTexturing/ViewController.swift:195, EnvironmentTexturing/ViewController.swift:226) |
ViewController; gestures set requiresRefresh |
ViewController |
isEnvironmentTextureAvailable |
Set from probe-anchor updates and reset by resetTracking (EnvironmentTexturing/ViewController.swift:254, EnvironmentTexturing/ViewController.swift:146) |
ViewController |
ARSession |
AREnvironmentProbeAnchor objects |
The controller adds and removes them; the session holds them as anchors | ViewController via session.add / session.remove |
Observed: ManualProbe is a struct, so updates are copy-modify-write. updateEnvironmentProbe binds a local var manualProbe, changes it, and assigns it back to self.manualProbe at the end; other sites mutate through optional chaining (manualProbe?.requiresRefresh = true).
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 |
|---|---|---|---|
| Main-queue UI updates | DispatchQueue.main.async { UIView.animate ... } |
The session label and its effect-view alpha are changed in a work item on the main queue, whichever callback computed the message | EnvironmentTexturing/ViewController.swift:175 |
| Main-queue alert | DispatchQueue.main.async { ... present(alertController ...) } |
Session-failure alert and its restart action are presented from the main queue | EnvironmentTexturing/ViewController.swift:277 |
| Global-queue placement | DispatchQueue.global().async { self.place(...) } |
First-object placement, which adds the node to the scene graph, assigns virtualObject, and sets requiresRefresh, is submitted to a global concurrent queue |
EnvironmentTexturing/ViewController.swift:337, EnvironmentTexturing/ViewController.swift:341 |
| Render-loop callback | renderer(_:updateAtTime:) calls updateEnvironmentProbe(atTime:) |
Manual probe refresh is driven by SceneKit’s per-frame callback and throttled to once per second while requiresRefresh is set |
EnvironmentTexturing/ViewController.swift:245, EnvironmentTexturing/ViewController.swift:196 |
| Frame callback | session(_:didUpdate:) |
Creates the room-sized fallback probe once and refreshes the status label | EnvironmentTexturing/ViewController.swift:291 |
| Shared-state safety | None | virtualObject, manualProbe, and isEnvironmentTextureAvailable are read and written from gesture actions, delegate callbacks, and the global-queue work item with no lock, serial queue, or actor |
EnvironmentTexturing/ViewController.swift:48, EnvironmentTexturing/ViewController.swift:50 |
| Compiler mode | SWIFT_VERSION = 5.0 |
No Swift 6 data-race checking applies to these crossings | EnvironmentTexturing.xcodeproj/project.pbxproj:349 |
Reference code
EnvironmentTexturing/ViewController.swift:337 — placement submitted to a global queue
@IBAction func didTap(_ gesture: UITapGestureRecognizer) {
// ...
if let object = virtualObject {
// ...
} else {
// Add the object to the scene at the tap location.
DispatchQueue.global().async {
self.place(self.virtualObjectModel, basedOn: touchLocation)
// Newly added object requires an environment probe anchor.
self.manualProbe?.requiresRefresh = true
}
}
}Not established by source: which thread SceneKit uses for renderer(_:updateAtTime:) or which queue ARKit uses for session callbacks (the code never sets delegateQueue). Interpretation: the controller’s state is shared between those callbacks and the global-queue work item without synchronization, so this sample should not be read as a thread-safety model.
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 |
|---|---|---|---|
| Mode change | @IBAction changeMode(_:) sets environmentTexturingMode, whose didSet creates or clears ManualProbe, then calls resetTracking(changeMode: true) |
The segmented control is the only mode input | EnvironmentTexturing/ViewController.swift:110 |
| Texture readiness | renderer(_:didUpdate:for:) checks AREnvironmentProbeAnchor.environmentTexture |
Gates object placement in didTap until a texture exists |
EnvironmentTexturing/ViewController.swift:249, EnvironmentTexturing/ViewController.swift:325 |
| Refresh signal | manualProbe?.requiresRefresh = true from pan, tap, pinch, and placement |
Marks the object probe stale; the render callback rebuilds it | EnvironmentTexturing/ViewController.swift:311, EnvironmentTexturing/ViewController.swift:354 |
| Framework import | ARKit, SceneKit, UIKit |
View-controller compilation dependencies | EnvironmentTexturing/ViewController.swift:8, EnvironmentTexturing/ViewController.swift:9, EnvironmentTexturing/ViewController.swift:10 |
| Framework import | UIKit, ARKit |
App delegate: launch and support check | EnvironmentTexturing/AppDelegate.swift:8, EnvironmentTexturing/AppDelegate.swift:9 |
| Package declaration | None | The project file declares no Swift package | EnvironmentTexturing.xcodeproj/project.pbxproj:258 |
The source uses no Combine, notifications, or observation framework.
Class and protocol design
classDiagram
class ARSCNViewDelegate {
<<protocol>>
}
class ARSessionDelegate {
<<protocol>>
}
class UIWindowSceneDelegate {
<<protocol>>
}
ViewController ..|> ARSCNViewDelegate
ViewController ..|> ARSessionDelegate
SceneDelegate ..|> UIWindowSceneDelegate
ViewController *-- ManualProbe : nested struct
ViewController --> ARSCNView : smartHitTest (extension)
Reference code
EnvironmentTexturing/Utilities.swift:24 — hit-test fallback chain shared by tap, pan, and placement
extension ARSCNView {
func smartHitTest(_ point: CGPoint) -> ARHitTestResult? {
// Perform the hit test.
let results = hitTest(point, types: [.existingPlaneUsingGeometry])
// 1. Check for a result on an existing plane using geometry.
if let existingPlaneUsingGeometryResult = results.first(where: { $0.type == .existingPlaneUsingGeometry }) {
return existingPlaneUsingGeometryResult
}
// 2. Check for a result on an existing plane, assuming its dimensions are infinite.
let infinitePlaneResults = hitTest(point, types: .existingPlane)
if let infinitePlaneResult = infinitePlaneResults.first {
return infinitePlaneResult
}
// 3. As a final fallback, check for a result on estimated planes.
return results.first(where: { $0.type == .estimatedHorizontalPlane })
}
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
AppDelegate |
ARKit support check; returns the Default Configuration scene configuration |
UIApplicationDelegate |
SceneDelegate |
Empty scene lifecycle; storyboard loading comes from the manifest | UIWindowSceneDelegate |
ViewController |
Session lifecycle, probe management, gestures, status UI | UIViewController, ARSCNViewDelegate, ARSessionDelegate |
ManualProbe |
Value holding the object probe, fallback probe, refresh flag, and last update time | AREnvironmentProbeAnchor |
Utilities.swift extensions |
Hit testing, node extents, translation matrices | ARSCNView, SCNNode, float4x4 |
Observed: the sample declares no local protocol. Reuse is through extensions on framework types.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
ViewController and all its members (EnvironmentTexturing/ViewController.swift:12) |
implicit internal |
Every property, including virtualObject and manualProbe, is writable from anywhere in the module |
Inference: a single-controller sample with no other module clients. |
ManualProbe (EnvironmentTexturing/ViewController.swift:14) |
implicit internal, nested |
Usable module-wide as ViewController.ManualProbe |
Nesting scopes the name to its owner without restricting access. |
sessionInfoLabel, sessionInfoView, textureModeSelectionControl (EnvironmentTexturing/ViewController.swift:28) |
implicit internal, weak @IBOutlet |
The view hierarchy retains them | Standard storyboard ownership. |
smartHitTest(_:), extents, translation (EnvironmentTexturing/Utilities.swift:24) |
implicit internal extensions |
Available to all module code | Shared helpers. |
Reference code
EnvironmentTexturing/ViewController.swift:27 — outlets
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
// ...
@IBOutlet var sceneView: ARSCNView!
@IBOutlet weak var sessionInfoLabel: UILabel!
@IBOutlet weak var sessionInfoView: UIVisualEffectView!
@IBOutlet weak var textureModeSelectionControl: UISegmentedControl!
// ...
}The source uses no explicit private, fileprivate, public, or open modifier; every declaration is Swift’s default internal.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Manual probe sizing | ViewController.updateEnvironmentProbe(atTime:) |
Extent is the object’s scaled bounds, tripled in x and z and doubled in y, with the probe raised so its bottom stays at the object’s base (EnvironmentTexturing/ViewController.swift:207, EnvironmentTexturing/ViewController.swift:213). |
| Fallback probe | ViewController.updateSceneEnvironmentProbe(for:) |
A 5 m identity-transform probe named sceneProbe, created once in manual mode (EnvironmentTexturing/ViewController.swift:238). |
| Probe throttling | updateEnvironmentProbe(atTime:) guard |
At most once per second, and only when requiresRefresh is set (EnvironmentTexturing/ViewController.swift:193). |
| Mode switch without losing tracking | resetTracking(changeMode:) |
Removes only AREnvironmentProbeAnchor anchors and reruns without .resetTracking (EnvironmentTexturing/ViewController.swift:136). |
| Status messaging | updateSessionInfoLabel(for:trackingState:) |
Maps tracking state and texture readiness to a message (EnvironmentTexturing/ViewController.swift:150). |
| Hit testing | ARSCNView.smartHitTest(_:) |
Shared fallback chain in Utilities.swift. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | ViewController runs the session in viewDidAppear, pauses it in viewWillDisappear, and owns all gestures and probe state (EnvironmentTexturing/ViewController.swift:88, EnvironmentTexturing/ViewController.swift:102) |
Keeps a small sample readable in one file; there is no separate model or service layer. |
| Delegate or data-source callbacks | sceneView.delegate = self and sceneView.session.delegate = self (EnvironmentTexturing/ViewController.swift:74, EnvironmentTexturing/ViewController.swift:75) |
Render-loop and frame callbacks drive probe updates and status UI. |
Naming conventions
- Types: framework-role names (
AppDelegate,SceneDelegate,ViewController) plus one domain value,ManualProbe. - Methods:
update…for per-frame work (updateEnvironmentProbe(atTime:),updateSceneEnvironmentProbe(for:),updateSessionInfoLabel(for:trackingState:)); gesture actions usedid…(didTap,didPan,didScale);resetTracking(changeMode:)andrestartExperience()for session control. - Properties: Booleans read as states (
isEnvironmentTextureAvailable,requiresRefresh);virtualObjectModelis the template node andvirtualObjectthe placed instance. - Files: one primary type per file;
Utilities.swiftcollects extensions.
Architecture takeaways
- Environment probes are ordinary anchors: the controller adds, removes, and resizes them with the session, and keeps their bookkeeping in a small value type.
- A cheap dirty flag (
requiresRefresh) plus a one-second throttle in the render callback limits probe churn while the object moves. - A large fallback probe prevents reflections from going blank while the object’s own probe is being replaced.
- The scene-based lifecycle is added with an empty
SceneDelegateand a manifest entry; feature code is unchanged by it. - Controller state is touched from several callback contexts and one global-queue work item without synchronization; treat that as a sample shortcut.
Source map
| Source file | Relevant symbols |
|---|---|
EnvironmentTexturing/AppDelegate.swift |
AppDelegate, application(_:didFinishLaunchingWithOptions:), application(_:configurationForConnecting:options:) |
EnvironmentTexturing/SceneDelegate.swift |
SceneDelegate |
EnvironmentTexturing/ViewController.swift |
ViewController, ManualProbe, environmentTexturingMode, resetTracking(changeMode:), updateEnvironmentProbe(atTime:), updateSceneEnvironmentProbe(for:), updateSessionInfoLabel(for:trackingState:), didTap(_:), place(_:basedOn:) |
EnvironmentTexturing/Utilities.swift |
smartHitTest(_:), extents, float4x4(translation:), translation |
EnvironmentTexturing/Resources/Info.plist |
UIApplicationSceneManifest, UIRequiredDeviceCapabilities |
EnvironmentTexturing.xcodeproj/project.pbxproj |
SWIFT_VERSION, IPHONEOS_DEPLOYMENT_TARGET |