Sample CodeiOS, iPadOS, Mac Catalyst, visionOSReviewed 2026-07-21View on Apple Developer

Creating a Spaceship game

At a glance

Item Summary
Purpose Build an immersive game using RealityKit audio, simulation, and rendering features.
App architecture A C/Objective-C header, Objective-C++, Swift sample with the source-visible chain SpaceshipAppMenuViewHangarViewModelClosureSystemRealityKit APIs.
Main patterns Model-View-ViewModel
Project style 57 scanned source file(s) across C/Objective-C header, Objective-C++, Swift, organized around ranked entry, type, and file boundaries.
Execution model Source-visible boundaries: async declaration or closure, @MainActor, Task closure isolated to MainActor, Task; none alone proves a background thread.
State/event model Source-visible mechanisms: @Observable, SwiftUI state property wrapper.
Key frameworks/packages RealityKit, SwiftUI, QuartzCore, CoreAudio, Foundation; these are source dependencies, not architecture labels.

Project structure

Source bundle/
└── Spaceship/
    ├── SpaceshipApp.swift
    ├── ECS/
    │   ├── SpaceshipControl/
    │   │   └── HandsShipControlProvider.swift
    │   └── SpaceshipBehavior/
    │       └── ShipFlight.swift
    ├── ViewModels/
    │   ├── HangarViewModel.swift
    │   └── ImmersiveViewModel.swift
    ├── Views/
    │   ├── HangarView.swift
    │   ├── ShipControlView.swift
    │   ├── FlightSchoolView.swift
    │   ├── MenuView.swift
    │   ├── AudioMixerView.swift
    │   └── ImmersiveView.swift
    └── AppModel.swift

Structure observations

  • Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
  • Primary languages: C/Objective-C header, Objective-C++, Swift.
  • The verified tree contains 4 project/configuration file(s) and 72 source declaration(s).

Overall architecture

Reference code

Spaceship/SpaceshipApp.swift:11 — architecture anchor

@main
struct SpaceshipApp: App {
    // ...
    @State var appModel = AppModel()
    // ...
}

Interpretation

The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into RealityKit.

Ownership and state

Ownership evidence

Spaceship/SpaceshipApp.swift:14 — stored dependency or nearest verified ownership anchor

@main
struct SpaceshipApp: App {
    // ...
    @State var appModel = AppModel()
    // ...
}
Owner Object or state Relationship Mutation authority
SpaceshipApp AppModel (appModel) owns wrapper-managed state App/module collaborators
SpaceshipApp Bool (isMenuExpanded) owns wrapper-managed state App/module collaborators
HandTrackingComponent Location (location) stores or receives Initialized by the owner; the binding is immutable
HandsShipControlProviderSystem Array (dependencies) owns value state App/module collaborators

Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.

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
Suspension boundary async declaration or closure The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. Spaceship/ECS/Entity+Planet.swift:63
Main isolation @MainActor The cited annotation marks its attached declaration or closure as main-actor isolated. Spaceship/ECS/SpaceshipControl/HandsShipControlProvider.swift:57
Main isolation Task closure isolated to MainActor The cited operation explicitly enters a main-actor-isolated region. Spaceship/ECS/SpaceshipControl/HandsShipControlProvider.swift:57
Task creation Task The source creates an unstructured task; surrounding context determines inherited actor isolation. Spaceship/ECS/SpaceshipControl/HandsShipControlProvider.swift:57

@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.

Reference code

Spaceship/ECS/Entity+Planet.swift:63 — representative execution boundary

    static func makePlanet(radius: Float = 0.25) async throws -> Entity {
        // ...
        let planet = try await Entity(named: PlanetNames.resource, in: realityKitContentBundle)
        // ...
    }

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 @Observable Observation macro publishes source-visible changes. Spaceship/AppModel.swift:11
State propagation SwiftUI state property wrapper A SwiftUI property wrapper supplies or observes UI state. Spaceship/SpaceshipApp.swift:14
Source import RealityKit The cited file imports this module; runtime use and architectural role are not inferred. Spaceship/AppModel.swift:9
Source import SwiftUI The cited file imports this module; runtime use and architectural role are not inferred. Spaceship/AppModel.swift:8
Source import QuartzCore The cited file imports this module; runtime use and architectural role are not inferred. Spaceship/ECS/Entity+Planet.swift:9
Source import CoreAudio The cited file imports this module; runtime use and architectural role are not inferred. Spaceship/ECS/SpaceshipBehavior/ShipAudio.swift:8
Source import Foundation The cited file imports this module; runtime use and architectural role are not inferred. Packages/RealityKitContent/Sources/RealityKitContent/RealityKitContent.swift:8
Source import RealityKitContent The cited file imports this module; runtime use and architectural role are not inferred. Spaceship/ECS/Entity+Planet.swift:11

receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.

Class and protocol design

Spaceship/SpaceshipApp.swift:12 — representative type boundary

@main
struct SpaceshipApp: App {
    // ...
    @State var appModel = AppModel()
    // ...
}
Type Responsibility Depends on or conforms to
SpaceshipApp Application entry and top-level composition App
HandTrackingComponent Stores entity-component data or behavior Component
ThrottleLabelPlacementComponent Stores entity-component data or behavior Component
PitchRollLabelPlacementComponent Stores entity-component data or behavior Component
HandsShipControlProviderSystem Runs entity-component-system update logic System
HangarViewModel UI-facing state and feature coordination Concrete collaborators/imported frameworks
ImmersiveViewModel UI-facing state and feature coordination Concrete collaborators/imported frameworks
HangarView User-interface presentation and input forwarding View
SpaceshipView User-interface presentation and input forwarding View, Animatable
ThrottleControlView User-interface presentation and input forwarding View

No local protocol conformance is claimed as protocol-oriented design; external framework conformances are listed only as dependencies.

Access control

Symbol Access Verified effect Likely rationale
realityKitContentBundle (Packages/RealityKitContent/Sources/RealityKitContent/RealityKitContent.swift:11) public The symbol is visible to importing modules. Inference: make the declaration available across a module or target boundary.
studioBundle (Packages/Studio/Sources/Studio/Studio.swift:11) public The symbol is visible to importing modules. Inference: make the declaration available across a module or target boundary.
throttle (Spaceship/AudioUnitTurbine/AudioUnitTurbine.h:26) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.
carrierFrequencyMin (Spaceship/AudioUnitTurbine/AudioUnitTurbine.h:27) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.

Reference code

Packages/RealityKitContent/Sources/RealityKitContent/RealityKitContent.swift:11 — representative boundary

public let realityKitContentBundle = Bundle.module

Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.

Logic ownership and placement

Logic Owning type or file Placement rationale
Application entry and top-level composition SpaceshipApp The source’s App suffix makes this role explicit.
Stores entity-component data or behavior AsteroidComponent, AudioMaterialComponent, AudioMaterialLookupComponent, CargoComponent The source’s Component suffix makes this role explicit.
Feature data or observable state AppModel The source’s Model suffix makes this role explicit.
Runs entity-component-system update logic ClosureSystem, EnvironmentLightingFadeSystem, HandsShipControlProviderSystem, PlanetVisualsSystem The source’s System suffix makes this role explicit.
User-interface presentation and input forwarding AudioMixerView, FlightSchoolView, HangarView, ImmersiveView The source’s View suffix makes this role explicit.
UI-facing state and feature coordination HangarViewModel, ImmersiveViewModel The source’s ViewModel suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
Model-View-ViewModel Spaceship/ViewModels/HangarViewModel.swift:14 Role-named view models keep UI-facing state or coordination outside view declarations.

Main application flow

Reference code

Spaceship/ViewModels/ImmersiveViewModel+Surroundings.swift:37transitionSurroundings()

    func transitionSurroundings(from previous: Surroundings, to current: Surroundings) async throws {
        #if os(visionOS)
        if current == .passthrough {
            try await sceneReconstruction.start()
            rootEntity.addChild(sceneReconstruction.entity)
        } else {
            sceneReconstruction.entity.removeFromParent()
            sceneReconstruction.stop()
        }
        #endif

        switch (previous, current) {
            case (.passthrough, .passthrough):
                break
            case (.passthrough, .studio), (.studio, .studio), (.deepSpace, .studio):
                try await immersiveEnvironment.enterStudio()
            case (.passthrough, .outerSpace), (.outerSpace, .outerSpace), (.deepSpace, .outerSpace):
                try await immersiveEnvironment.enterOuterSpace()
            case (.passthrough, .deepSpace):
                break
            case (.studio, .passthrough), (.studio, .deepSpace):
                try await immersiveEnvironment.exitStudio()
            case (.studio, .outerSpace):
                try await immersiveEnvironment.enterOuterSpace()
                try await immersiveEnvironment.exitStudio()
            case (.outerSpace, .passthrough), (.outerSpace, .deepSpace):
                try await immersiveEnvironment.exitOuterSpace()
            case (.outerSpace, .studio):
                try await immersiveEnvironment.enterStudio()
                try await immersiveEnvironment.exitOuterSpace()
            case (.deepSpace, .deepSpace), (.deepSpace, .passthrough):
                break
        }
    }

Naming conventions

  • Types: App: SpaceshipApp; Component: AsteroidComponent, AudioMaterialComponent, AudioMaterialLookupComponent, CargoComponent, ClosureComponent; Model: AppModel; System: ClosureSystem, EnvironmentLightingFadeSystem, HandsShipControlProviderSystem, PlanetVisualsSystem, ShipAudioSystem; View: AudioMixerView, FlightSchoolView, HangarView, ImmersiveView, MenuView; ViewModel: HangarViewModel, ImmersiveViewModel.
  • Protocols: no local protocol declaration in the scanned source.
  • Methods: computeTransformWith, update, updateShipControlParameters, interpolateThrottle, computeTargetThrottle, computePitchAndRoll, interpolate, makeHandTrackingEntities.
  • Files: Spaceship/SpaceshipApp.swift, Spaceship/ViewModels/HangarViewModel.swift, Spaceship/ViewModels/ImmersiveViewModel.swift, Spaceship/Views/HangarView.swift, Spaceship/Views/ShipControlView.swift, Spaceship/AppModel.swift.

Architecture takeaways

  • SpaceshipApp is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches RealityKit, SwiftUI, QuartzCore, CoreAudio through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
  • Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
  • Access-control conclusions separate verified language visibility from the likely design rationale.
  • The source does not justify labeling the design protocol-oriented.

Source map

Source file Relevant symbols
Spaceship/SpaceshipApp.swift Cited implementation, SpaceshipApp, SwiftUI state property wrapper
Packages/RealityKitContent/Sources/RealityKitContent/RealityKitContent.swift Cited implementation, Foundation, Feature implementation
Packages/Studio/Sources/Studio/Studio.swift Cited implementation, Feature implementation
Spaceship/AudioUnitTurbine/AudioUnitTurbine.h throttle, carrierFrequencyMin, AudioUnitTurbine
Spaceship/ViewModels/HangarViewModel.swift HangarViewModel
Spaceship/ECS/Entity+Planet.swift async declaration or closure, QuartzCore, RealityKitContent, PlanetNames, PlanetVisualsComponent, PlanetVisualsSystem
Spaceship/ECS/SpaceshipControl/HandsShipControlProvider.swift @MainActor, Task closure isolated to MainActor, Task, HandTrackingComponent, Location, ThrottleLabelPlacementComponent, PitchRollLabelPlacementComponent, HandsShipControlProviderSystem
Spaceship/AppModel.swift @Observable, RealityKit, SwiftUI, AppModel, GamePhase
Spaceship/ECS/SpaceshipBehavior/ShipAudio.swift CoreAudio, ShipAudioSystem, TurbineAudioComponent, ShipAudioComponent
Spaceship/ViewModels/ImmersiveViewModel.swift ImmersiveViewModel
Spaceship/Views/HangarView.swift HangarView, SpaceshipView, DragRotationModifier
Spaceship/Views/ShipControlView.swift ThrottleControlView, PitchRollControlView, ShipControlView
Spaceship/Views/FlightSchoolView.swift FlightSchoolView, FlightSchoolLabelModifier
Spaceship/Views/MenuView.swift MenuView, FlyReturnToggleStyle
Spaceship/ECS/SpaceshipBehavior/ShipFlight.swift ShipFlightComponent, ShipFlightSystem, ShipFlightStateComponent, PrimaryThrustComponent
Spaceship/Views/AudioMixerView.swift AudioMixerView
Spaceship/ViewModels/ImmersiveViewModel+Surroundings.swift transitionSurroundings