Creating a spatial drawing app with RealityKit
At a glance
| Item | Summary |
|---|---|
| Purpose | Draw solid and particle (“sparkle”) brush strokes with hand tracking, updating LowLevelMesh geometry every frame, and export the drawing as a .reality file. |
| App architecture | A SwiftUI App owns a Mode (splash, choose work volume, drawing), the canvas and brush state, and an asynchronously created DrawingDocument; RealityKit systems pull hand input into the document and push generated meshes into entities. |
| Main patterns | RealityKit entity-component-system for input and mesh updates; custom EnvironmentKey injection of the document and a setMode closure; a local HermiteInterpolant protocol for generic curve math. |
| Project style | Folders by concern: Document/ (state and input), Brushes/Solid and Brushes/Sparkle (generators, components, shaders), Canvas/, UI/, Splash Screen/, Utilities/, plus the local RealityKitContent package. |
| Execution model | DrawingDocument and AnchorEntityInputProvider are @MainActor classes; DrawingSource and generator members that touch RealityKit or Metal state are individually @MainActor; a Metal command buffer’s completion handler hops back with Task(priority: .high) { @MainActor in … }. |
| State/event model | @Observable BrushState and DrawingCanvasSettings; per-frame RealityKit System.update calls; direct method calls from the input system into the document. |
| Key frameworks/packages | SwiftUI, RealityKit, Metal; remote packages swift-algorithms and swift-collections and the local RealityKitContent package. |
Project structure
RealityKitDrawingApp/
├── RealityKitDrawingApp.swift App, Mode, SetModeKey, DocumentKey
├── Document/
│ ├── DrawingDocument.swift root entity, left/right sources, displayMode
│ ├── DrawingDocument+Transferable.swift .reality export
│ ├── DrawingSource.swift per-hand stroke state and styling
│ └── AnchorEntityInputProvider.swift HandComponent, DrawingSystem
├── Brushes/
│ ├── Solid/ SmoothCurveSampler, CurveExtruder, SolidBrushSystem
│ └── Sparkle/ GPU particle generator, SparkleBrushSystem, .metal
├── Canvas/ canvas settings, placement and visualization ECS
├── UI/ DrawingMeshView, DrawingPreviewView, Palette/
├── Splash Screen/ splash views and shader-backed background
├── Utilities/ CurveProcessing (HermiteInterpolant), Metal helpers
└── Packages/RealityKitContent/ Reality Composer Pro materials
Structure observations
- Each brush folder pairs a mesh generator with a
TransientComponentand aSystemthat installs the generated mesh (RealityKitDrawingApp/Brushes/Solid/SolidBrushComponent.swift:15). - Sharing lives in a dedicated extension file that adds
Transferableto the document (RealityKitDrawingApp/Document/DrawingDocument+Transferable.swift:11). - The app target links
AlgorithmsandCollectionsproducts from remote packages (RealityKitDrawingApp.xcodeproj/project.pbxproj:690).
Overall architecture
flowchart LR
App["RealityKitDrawingApp (Mode, @State)"] -->|environment| Windows["Splash / Configure / Palette / Preview"]
App --> Space["ImmersiveSpace"]
Space --> MeshView["DrawingMeshView"]
MeshView --> Input["AnchorEntityInputProvider"]
Input --> DrawSys["DrawingSystem"]
DrawSys --> Doc["DrawingDocument"]
Doc --> Source["DrawingSource x2"]
Source --> Gen["Solid / Sparkle generators"]
Gen --> BrushSys["SolidBrushSystem / SparkleBrushSystem"]
BrushSys --> Entity["ModelComponent on entities"]
Reference code
RealityKitDrawingApp/RealityKitDrawingApp.swift:70 — setMode(_:)
@MainActor private func setMode(_ newMode: Mode) async {
if !immersiveSpacePresented && newMode.needsImmersiveSpace {
let result = await openImmersiveSpace(id: Self.immersiveSpaceWindowId)
if result != .opened {
return
}
} else if immersiveSpacePresented && !newMode.needsImmersiveSpace {
await dismissImmersiveSpace()
}
let oldMode = mode
if newMode == oldMode { return }
mode = newMode
openWindow(id: newMode.windowId)
dismissWindow(id: oldMode.windowId)
}Interpretation
The app struct is the only place that opens and dismisses windows and the immersive space: each Mode maps to one window ID and a needsImmersiveSpace flag, and child views receive setMode as an environment closure rather than the environment actions themselves. The palette window shows PaletteView while the immersive space is presented and DrawingPreviewView otherwise (RealityKitDrawingApp/RealityKitDrawingApp.swift:115). Inference: centralizing the transitions keeps window/space consistency rules in one function.
Ownership and state
classDiagram
RealityKitDrawingApp *-- DrawingCanvasSettings : @State
RealityKitDrawingApp *-- BrushState : @State
RealityKitDrawingApp *-- DrawingDocument : @State optional
DrawingDocument *-- DrawingSource : left, right
DrawingSource *-- SolidDrawingMeshGenerator
DrawingSource *-- SparkleDrawingMeshGenerator
DrawingMeshView *-- AnchorEntityInputProvider : @State
AnchorEntityInputProvider o-- DrawingDocument
HandComponent o-- AnchorEntityInputProvider
Ownership evidence
RealityKitDrawingApp/RealityKitDrawingApp.swift:83 — app state and document creation
struct RealityKitDrawingApp: App {
// ...
@State private var mode: Mode = .splashScreen
@State private var canvas = DrawingCanvasSettings()
@State private var brushState = BrushState()
@State private var document: DrawingDocument?
// ...
var body: some Scene {
Group {
WindowGroup(id: Self.splashScreenWindowId) {
SplashScreenView()
.environment(\.setMode, setMode)
.frame(width: 1000, height: 700)
.fixedSize()
.task {
// Initialize the document in the background, while the splash screen loads.
self.document = await DrawingDocument(brushState: brushState, canvas: canvas)
}
}
// ...
}
}
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
RealityKitDrawingApp |
mode, canvas, brushState, document |
Creates in @State; the document is assigned when its async initializer finishes |
setMode; the splash .task |
DrawingDocument |
rootEntity, leftSource, rightSource, startDate |
Creates in init; sources are private var |
receive(input:chirality:), displayMode |
DrawingSource |
generators, SmoothCurveSampler, style providers, inputsOverTime |
Value type owning its generators and sampling state | receive(input:time:state:) |
DrawingMeshView |
AnchorEntityInputProvider |
Created inside RealityView’s make closure and kept in @State (RealityKitDrawingApp/UI/DrawingMeshView.swift:42) |
— |
AnchorEntityInputProvider |
SpatialTrackingSession, left/right hand entities |
Creates and retains (private let) |
— |
HandComponent |
provider reference, thumb and index AnchorEntity |
Stored on the hand entity | Read each frame by DrawingSystem |
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-actor isolation | @MainActor class |
DrawingDocument and AnchorEntityInputProvider state and methods |
RealityKitDrawingApp/Document/DrawingDocument.swift:56 |
| Async construction | async initializers |
Document loads two ShaderGraphMaterials and builds two sources; started by a SwiftUI .task on the splash window, which SwiftUI cancels if the view disappears |
RealityKitDrawingApp/Document/DrawingDocument.swift:115 |
| Per-frame updates | System.update(context:) with .rendering |
Input polling and mesh installation run as RealityKit systems | RealityKitDrawingApp/Document/AnchorEntityInputProvider.swift:85 |
| GPU completion handoff | addCompletedHandler → Task(priority: .high) { @MainActor in … } |
Clears activeCommandBuffer and delivers a reallocated mesh on the main actor |
RealityKitDrawingApp/Brushes/Sparkle/SparkleDrawingMeshGenerator.swift:243 |
| Shared-state safety | @MainActor activeCommandBuffer guard |
update returns early while a buffer is in flight, so lowLevelMesh and simulationBuffer are not encoded concurrently |
RealityKitDrawingApp/Brushes/Sparkle/SparkleDrawingMeshGenerator.swift:222 |
| Blocking wait | waitUntilCompleted() |
Switching to .previewing blocks until in-flight GPU work finishes before reading particle bounds |
RealityKitDrawingApp/Brushes/Sparkle/SparkleDrawingMeshGenerator.swift:92 |
Reference code
RealityKitDrawingApp/Brushes/Sparkle/SparkleDrawingMeshGenerator.swift:243 — update(deltaTime:_:)
@MainActor
func update(deltaTime: Float, _ onCreatedNewMesh: @escaping @MainActor (LowLevelMesh) async -> Void) throws {
guard displayMode == .editing else { return }
let oldBuffer = simulationBuffer
// Halt if a mesh update is already in flight. Need to wait for a command buffer from a previous frame.
if activeCommandBuffer != nil { return }
// ...
commandBuffer.addCompletedHandler { [self] commandBuffer in
Task(priority: .high) { @MainActor in
if didReallocate {
await onCreatedNewMesh(lowLevelMesh!)
}
precondition(activeCommandBuffer === commandBuffer)
activeCommandBuffer = nil
}
}
activeCommandBuffer = commandBuffer
commandBuffer.enqueue()
// ...
}The completion task is not stored or cancelled; activeCommandBuffer is the only in-flight marker.
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 | Custom EnvironmentKey |
setMode closure and optional DrawingDocument reach windows and views |
RealityKitDrawingApp/RealityKitDrawingApp.swift:158 |
| State propagation | @Observable |
BrushState (brush type and style settings) and DrawingCanvasSettings (radius, placement) |
RealityKitDrawingApp/UI/BrushState.swift:32 |
| State propagation | @Binding |
PaletteView and DrawingMeshView receive brushState from the app |
RealityKitDrawingApp/UI/DrawingMeshView.swift:16 |
| Sharing | ShareLink + Transferable |
Palette exports the document as .realityFile data |
RealityKitDrawingApp/Document/DrawingDocument+Transferable.swift:14 |
| Package declaration | XCRemoteSwiftPackageReference |
swift-algorithms, swift-collections |
RealityKitDrawingApp.xcodeproj/project.pbxproj:698 |
| Package declaration | Local package manifest | RealityKitContent library with no dependencies |
RealityKitDrawingApp/Packages/RealityKitContent/Package.swift:13 |
| Framework import | Algorithms, Collections |
adjacentPairs() and Deque in stroke speed smoothing |
RealityKitDrawingApp/Document/DrawingSource.swift:8 |
No Combine usage appears in the source.
Class and protocol design
classDiagram
class HermiteInterpolant {
<<protocol>>
}
Float ..|> HermiteInterpolant
SIMD3 ..|> HermiteInterpolant
HermiteControlPoint --> HermiteInterpolant : T
SmoothCurveSampler --> SolidDrawingMeshGenerator : curve
SolidDrawingMeshGenerator *-- CurveExtruderWithEndcaps
SolidBrushComponent --> SolidDrawingMeshGenerator
SparkleBrushComponent --> SparkleDrawingMeshGenerator
Reference code
RealityKitDrawingApp/Utilities/CurveProcessing.swift:12 — HermiteInterpolant
protocol HermiteInterpolant {
static func distance(_: Self, _: Self) -> Float
static func length(_: Self) -> Float
static func dot(_: Self, _: Self) -> Float
static func + (left: Self, right: Self) -> Self
static func - (left: Self, right: Self) -> Self
static func * (left: Float, right: Self) -> Self
static func * (left: Self, right: Float) -> Self
static func / (left: Self, right: Float) -> Self
}Float and SIMD2/3/4<Float> conform, and the Hermite and Catmull-Rom evaluators are generic over it (RealityKitDrawingApp/Utilities/CurveProcessing.swift:97).
| Type | Responsibility | Depends on |
|---|---|---|
DrawingDocument |
Routes input to the per-hand source; toggles editing/previewing configuration | DrawingSource, DrawingCanvasSettings, BrushState |
DrawingSource |
Smooths speed, applies style, feeds the active generator | Style providers, SmoothCurveSampler, generators |
SolidDrawingMeshGenerator / CurveExtruder |
Extrude a profile along sampled curves into a LowLevelMesh |
RealityKit LowLevelMesh |
SparkleDrawingMeshGenerator |
GPU particle simulation writing into a LowLevelMesh |
Metal command queue and compute kernels |
AnchorEntityInputProvider, HandComponent, DrawingSystem |
Hand-anchor tracking and per-frame input delivery | SpatialTrackingSession, AnchorEntity |
SolidBrushSystem, SparkleBrushSystem |
Install new meshes into ModelComponent |
Brush components |
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
DrawingDocument.leftSource, rightSource, brushState, startDate |
private |
Only the document routes input and reads timing | Inference: callers interact through receive and displayMode |
DrawingSystem |
private class |
System type is file-private to AnchorEntityInputProvider.swift |
Inference: only the provider registers it |
DrawingCanvasPlacementSystem |
private struct |
Placement system is file-private | Inference: same encapsulation of a view-specific system |
CurveExtruder.lowLevelMesh, cachedSampleCount |
private; samples is private(set) |
Mesh buffers and cache counters change only inside the extruder | Inference: protect incremental-meshing invariants |
Mode.windowId |
fileprivate |
Window IDs are resolved only in the app file | Inference: keep window identity out of child views |
HandComponent, DrawingSource, Chirality |
public |
Visible outside the module, though the sample is a single app target | — |
Reference code
RealityKitDrawingApp/Document/AnchorEntityInputProvider.swift:88 — DrawingSystem
@MainActor
private class DrawingSystem: System {
private static let handQuery = EntityQuery(where: .has(HandComponent.self))
required init(scene: RealityKit.Scene) { }
func update(context: SceneUpdateContext) {
for entity in context.entities(matching: Self.handQuery, updatingSystemWhen: .rendering) {
let handComponent = entity.components[HandComponent.self]!
let provider = handComponent.provider
provider.document.receive(input: handComponent.currentData, chirality: handComponent.chirality)
}
}
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Window and immersive-space transitions | RealityKitDrawingApp.setMode |
One function owns presentation state |
| Canvas bounds check | DrawingDocument.receive → DrawingCanvasSettings.isInsideCanvas |
Input outside the canvas is dropped before reaching a source (RealityKitDrawingApp/Document/DrawingDocument.swift:156) |
| Pinch detection and brush tip | InputData |
Thumb/index distance under 0.015 m means drawing (RealityKitDrawingApp/Document/DrawingDocument.swift:33) |
| Speed smoothing and brush selection | DrawingSource |
Truncated mean over a 0.1 s window; switch on brushType |
| Editing vs. preview configuration | DrawingDocument.displayMode |
Sets tight bounds and a CollisionComponent for preview/export, removes them for editing (RealityKitDrawingApp/Document/DrawingDocument.swift:80) |
.reality export |
DrawingDocument+Transferable |
Temporarily switches to .previewing, writes the root entity, restores the mode |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Entity-component-system composition | HandComponent + DrawingSystem (RealityKitDrawingApp/Document/AnchorEntityInputProvider.swift:11); SolidBrushComponent + SolidBrushSystem (RealityKitDrawingApp/Brushes/Solid/SolidBrushComponent.swift:10) |
Input polling and mesh installation run in RealityKit’s frame loop instead of view code |
| SwiftUI environment injection | SetModeKey, DocumentKey (RealityKitDrawingApp/RealityKitDrawingApp.swift:148) |
Windows receive the document and a transition closure without referencing the App |
| Protocol-oriented abstraction | HermiteInterpolant and generic evaluators (RealityKitDrawingApp/Utilities/CurveProcessing.swift:12) |
One curve implementation serves scalars and SIMD vectors |
Main application flow
Scope: one render-loop update while a person pinches to draw with the uniform brush.
sequenceDiagram
participant System as DrawingSystem
participant Hand as HandComponent
participant Doc as DrawingDocument
participant Source as DrawingSource
participant Sampler as SmoothCurveSampler
System->>Hand: currentData (thumb and index positions)
System->>Doc: receive(input, chirality)
Doc->>Doc: drop input outside canvas
Doc->>Source: receive(input, time, brushState)
Source->>Source: smooth speed over recent inputs
Source->>Sampler: trace styled point
Reference code
RealityKitDrawingApp/Document/DrawingDocument.swift:162 — receive(input:chirality:)
func receive(input: InputData?, chirality: Chirality) {
var input = input
if let brushTip = input?.brushTip, !canvas.isInsideCanvas(rootEntity.convert(position: brushTip, to: nil)) {
input = .none
}
switch chirality {
case .left:
leftSource.receive(input: input, time: startDate.distance(to: .now), state: brushState)
case .right:
rightSource.receive(input: input, time: startDate.distance(to: .now), state: brushState)
}
}RealityKitDrawingApp/Document/DrawingSource.swift:142 — receive(input:time:state:)
@MainActor
mutating func receive(input: InputData?, time: TimeInterval, state: BrushState) {
// ...
let smoothSpeed = speedsOverTime.truncatedMean(truncation: 2)
if let input, input.isDrawing {
trace(position: input.brushTip, speed: smoothSpeed, state: state)
} else {
// ...
}
}RealityKitDrawingApp/Document/DrawingSource.swift:79 — trace(position:speed:state:)
@MainActor
private mutating func trace(position: SIMD3<Float>, speed: Float, state: BrushState) {
guard displayMode == .editing else { return }
switch state.brushType {
case .uniform:
let styled = solidProvider.styleInput(position: position, speed: speed,
settings: state.uniformStyleSettings)
smoothCurveSampler.trace(point: styled)
// ...
}
}RealityKitDrawingApp/Document/AnchorEntityInputProvider.swift:85 — DrawingSystem.update(context:)
func update(context: SceneUpdateContext) {
for entity in context.entities(matching: Self.handQuery, updatingSystemWhen: .rendering) {
let handComponent = entity.components[HandComponent.self]!
let provider = handComponent.provider
provider.document.receive(input: handComponent.currentData, chirality: handComponent.chirality)
}
}Naming conventions
- Types:
<Brush>DrawingMeshGenerator,<Brush>BrushComponent/<Brush>BrushSystem,<Brush>BrushStyleProvider;Drawing…prefix for document-level types;…Settingsfor observable configuration. - Protocols:
HermiteInterpolantnames the capability the curve math needs. - Methods:
receive(input:…)for input delivery,trace(point:)/beginNewStroke()/endStroke()for stroke building,configureFor…in views,updatein systems and generators. - Files and extensions:
DrawingDocument+Transferable.swiftandSparkleDrawingMeshGenerator+Simulation.swiftsplit one type by capability.
Architecture takeaways
- Put frame-rate work in RealityKit systems that query components; let the component hold a reference to the owning object so the system can call back into app state.
- Model edit vs. export as an explicit display mode that reconfigures bounds, collision, and mesh updates, and switch it temporarily during
Transferableexport. - Build the expensive document asynchronously while a splash window is visible and inject it through an optional environment value.
- Guard GPU-backed mesh updates with a single in-flight command buffer and hop back to the main actor in the completion handler.
- Keep window/space transitions in one
asyncfunction exposed to children as an environment closure.
Source map
| Source file | Relevant symbols |
|---|---|
RealityKitDrawingApp/RealityKitDrawingApp.swift |
RealityKitDrawingApp, Mode, setMode, SetModeKey, DocumentKey |
RealityKitDrawingApp/Document/DrawingDocument.swift |
DrawingDocument, InputData, DocumentDisplayMode, receive |
RealityKitDrawingApp/Document/DrawingDocument+Transferable.swift |
transferRepresentation |
RealityKitDrawingApp/Document/DrawingSource.swift |
DrawingSource, receive, trace |
RealityKitDrawingApp/Document/AnchorEntityInputProvider.swift |
HandComponent, AnchorEntityInputProvider, DrawingSystem |
RealityKitDrawingApp/Brushes/Solid/SolidBrushComponent.swift |
SolidBrushComponent, SolidBrushSystem |
RealityKitDrawingApp/Brushes/Sparkle/SparkleDrawingMeshGenerator.swift |
SparkleDrawingMeshGenerator, update(deltaTime:_:) |
RealityKitDrawingApp/Utilities/CurveProcessing.swift |
HermiteInterpolant, evaluateHermiteCurve |
RealityKitDrawingApp/UI/DrawingMeshView.swift |
DrawingMeshView |
RealityKitDrawingApp/UI/BrushState.swift |
BrushState |
RealityKitDrawingApp/Packages/RealityKitContent/Package.swift |
RealityKitContent |
RealityKitDrawingApp.xcodeproj/project.pbxproj |
remote package references |