0.2.0-dev Download ZIP
324 lines ·11.9 KB Raw
| 1 | /**************************************************************************/ |
| 2 | /* app_visionos.swift */ |
| 3 | /**************************************************************************/ |
| 4 | /* This file is part of: */ |
| 5 | /* GODOT ENGINE */ |
| 6 | /* https://godotengine.org */ |
| 7 | /**************************************************************************/ |
| 8 | /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ |
| 9 | /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ |
| 10 | /* */ |
| 11 | /* Permission is hereby granted, free of charge, to any person obtaining */ |
| 12 | /* a copy of this software and associated documentation files (the */ |
| 13 | /* "Software"), to deal in the Software without restriction, including */ |
| 14 | /* without limitation the rights to use, copy, modify, merge, publish, */ |
| 15 | /* distribute, sublicense, and/or sell copies of the Software, and to */ |
| 16 | /* permit persons to whom the Software is furnished to do so, subject to */ |
| 17 | /* the following conditions: */ |
| 18 | /* */ |
| 19 | /* The above copyright notice and this permission notice shall be */ |
| 20 | /* included in all copies or substantial portions of the Software. */ |
| 21 | /* */ |
| 22 | /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ |
| 23 | /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ |
| 24 | /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ |
| 25 | /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ |
| 26 | /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ |
| 27 | /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ |
| 28 | /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ |
| 29 | /**************************************************************************/ |
| 30 | |
| 31 | import SwiftUI |
| 32 | @preconcurrency import CompositorServices |
| 33 | import OSLog |
| 34 | |
| 35 | // MARK: Helpers |
| 36 | |
| 37 | extension os.Logger { |
| 38 | static let godot = Logger(subsystem: "com.GodotFoundation.Godot", category: "SwiftUI") |
| 39 | } |
| 40 | |
| 41 | // MARK: Renderer |
| 42 | |
| 43 | final class RendererTaskExecutor: TaskExecutor { |
| 44 | private let queue = DispatchQueue(label: "RenderThreadQueue", qos: .userInteractive) |
| 45 | func enqueue(_ job: UnownedJob) { |
| 46 | queue.async { |
| 47 | job.runSynchronously(on: self.asUnownedSerialExecutor()) |
| 48 | } |
| 49 | } |
| 50 | nonisolated func asUnownedSerialExecutor() -> UnownedTaskExecutor { |
| 51 | return UnownedTaskExecutor(ordinary: self) |
| 52 | } |
| 53 | static let shared: RendererTaskExecutor = RendererTaskExecutor() |
| 54 | } |
| 55 | |
| 56 | // MARK: Swift Bridge |
| 57 | |
| 58 | /// Source of truth for SwiftUI scene state. ObjC/C++ mutates it through |
| 59 | /// `GDTSwiftBridge`; the scene reads its properties directly (Observation tracking). |
| 60 | @MainActor |
| 61 | @Observable |
| 62 | final class Model { |
| 63 | static let shared = Model() |
| 64 | |
| 65 | var immersionStyle: any ImmersionStyle |
| 66 | var upperLimbVisibility: Visibility = .automatic |
| 67 | var persistentSystemOverlays: Visibility = .automatic |
| 68 | |
| 69 | private init() { |
| 70 | immersionStyle = Self.readInitialImmersionStyleFromInfoPlist() |
| 71 | } |
| 72 | |
| 73 | /// Seeds the project-setting-backed properties. Called at layer creation rather than |
| 74 | /// from `init()`, because `ProjectSettings` is not loaded yet when the scene is declared. |
| 75 | func seedFromProjectSettings() { |
| 76 | upperLimbVisibility = GDTAppDelegateServiceVisionOS.initialUpperLimbVisibility.swiftUI |
| 77 | persistentSystemOverlays = GDTAppDelegateServiceVisionOS.initialPersistentSystemOverlays.swiftUI |
| 78 | } |
| 79 | |
| 80 | private static func readInitialImmersionStyleFromInfoPlist() -> any ImmersionStyle { |
| 81 | guard let sceneManifest = Bundle.main.infoDictionary?["UIApplicationSceneManifest"] as? [String: Any], |
| 82 | let sceneConfigurations = sceneManifest["UISceneConfigurations"] as? [String: Any], |
| 83 | let cpSceneConfiguration = sceneConfigurations["UISceneSessionRoleImmersiveSpaceApplication"] as? [[String: Any]], |
| 84 | let immersionStyleString = cpSceneConfiguration.first?["UISceneInitialImmersionStyle"] as? String else { |
| 85 | return .full |
| 86 | } |
| 87 | switch immersionStyleString { |
| 88 | case "UIImmersionStyleFull": return .full |
| 89 | case "UIImmersionStyleMixed": return .mixed |
| 90 | case "UIImmersionStyleProgressive": return .progressive |
| 91 | default: return .full |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | /// ObjC-accessible interface for `Model`. |
| 97 | @MainActor |
| 98 | @objc |
| 99 | public final class GDTSwiftBridge: NSObject { |
| 100 | @objc public class var immersionStyle: GDTImmersionStyle { |
| 101 | get { GDTImmersionStyle(fromSwiftUIType: Model.shared.immersionStyle) } |
| 102 | set { |
| 103 | guard let swiftUIStyle = newValue.swiftUI else { return } |
| 104 | Model.shared.immersionStyle = swiftUIStyle |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | @objc public class var upperLimbVisibility: GDTVisibility { |
| 109 | get { GDTVisibility(fromSwiftUIType: Model.shared.upperLimbVisibility) } |
| 110 | set { Model.shared.upperLimbVisibility = newValue.swiftUI } |
| 111 | } |
| 112 | |
| 113 | @objc public class var persistentSystemOverlays: GDTVisibility { |
| 114 | get { GDTVisibility(fromSwiftUIType: Model.shared.persistentSystemOverlays) } |
| 115 | set { Model.shared.persistentSystemOverlays = newValue.swiftUI } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// ObjC-accessible version of SwiftUI's "SpatialEventCollection.Event". |
| 120 | /// https://developer.apple.com/documentation/swiftui/spatialeventcollection/event |
| 121 | @MainActor |
| 122 | @objc |
| 123 | public final class SpatialEventObjC: NSObject { |
| 124 | |
| 125 | // Ray |
| 126 | @objc var hasRay: Bool = false |
| 127 | @objc var rayOrigin: simd_double3 = .init() |
| 128 | @objc var rayDirection: simd_double3 = .init() |
| 129 | |
| 130 | // Hand |
| 131 | @objc enum Chirality: Int { |
| 132 | case none, left, right |
| 133 | } |
| 134 | @objc var chirality: Chirality |
| 135 | @objc var handPose: simd_double4x4 |
| 136 | |
| 137 | // Phase |
| 138 | @objc enum Phase: Int { |
| 139 | case unknown, active, cancelled, ended |
| 140 | } |
| 141 | @objc var phase: Phase |
| 142 | |
| 143 | init(_ event: SpatialEventCollection.Event) { |
| 144 | if let ray = event.selectionRay { |
| 145 | hasRay = true |
| 146 | rayOrigin = ray.origin.vector |
| 147 | rayDirection = ray.direction.vector |
| 148 | } |
| 149 | |
| 150 | chirality = event.chirality.map { |
| 151 | switch $0 { |
| 152 | case .left: return .left |
| 153 | case .right: return .right |
| 154 | } |
| 155 | } ?? .none |
| 156 | |
| 157 | handPose = event.inputDevicePose.map { |
| 158 | return $0.pose3D.matrix |
| 159 | } ?? .init(diagonal: SIMD4<Double>(repeating: 1.0)) |
| 160 | |
| 161 | phase = { |
| 162 | switch event.phase { |
| 163 | case .active: return .active |
| 164 | case .cancelled: return .cancelled |
| 165 | case .ended: return .ended |
| 166 | default: return .unknown |
| 167 | } |
| 168 | }() |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // MARK: Compositor Services Scene |
| 173 | |
| 174 | struct ContentStageConfiguration: CompositorLayerConfiguration { |
| 175 | func makeConfiguration(capabilities: LayerRenderer.Capabilities, configuration: inout LayerRenderer.Configuration) { |
| 176 | |
| 177 | GDTAppDelegateServiceVisionOS.layerRendererCapabilities = capabilities as __CP_OBJECT_cp_layer_renderer_capabilities |
| 178 | |
| 179 | configuration.depthFormat = .depth32Float_stencil8 |
| 180 | configuration.colorFormat = .rgba16Float |
| 181 | |
| 182 | let foveationEnabled = capabilities.supportsFoveation |
| 183 | configuration.isFoveationEnabled = foveationEnabled |
| 184 | |
| 185 | let options: LayerRenderer.Capabilities.SupportedLayoutsOptions = foveationEnabled ? [.foveationEnabled] : [] |
| 186 | let supportedLayouts = capabilities.supportedLayouts(options: options) |
| 187 | if (!supportedLayouts.contains(.layered)) { |
| 188 | fatalError("Only the .layered layout is supported by Godot's visionOS XR module.") |
| 189 | } |
| 190 | configuration.layout = .layered |
| 191 | |
| 192 | if GDTAppDelegateServiceVisionOS.isDynamicRenderQualityEnabled { |
| 193 | let maxRenderQuality = GDTAppDelegateServiceVisionOS.maxRenderQuality |
| 194 | Logger.godot.log("Enabled dynamic render quality (maxRenderQuality: \(maxRenderQuality))") |
| 195 | configuration.maxRenderQuality = .init(maxRenderQuality) |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | extension GDTCompositorServicesRenderer: @unchecked Sendable {} |
| 201 | |
| 202 | extension GDTImmersionStyle { |
| 203 | |
| 204 | var swiftUI: ImmersionStyle? { |
| 205 | switch self { |
| 206 | case .full: return .full |
| 207 | case .mixed: return .mixed |
| 208 | case .progressive: return .progressive |
| 209 | @unknown default: return nil |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | init(fromSwiftUIType swiftUIType: ImmersionStyle) { |
| 214 | switch swiftUIType.self { |
| 215 | case is FullImmersionStyle: self = .full |
| 216 | case is MixedImmersionStyle: self = .mixed |
| 217 | case is ProgressiveImmersionStyle: self = .progressive |
| 218 | default: fatalError("Unsupported style") |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | } |
| 223 | |
| 224 | extension GDTVisibility { |
| 225 | var swiftUI: Visibility { |
| 226 | switch self { |
| 227 | case .automatic: return .automatic |
| 228 | case .visible: return .visible |
| 229 | case .hidden: return .hidden |
| 230 | @unknown default: return .automatic |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | init(fromSwiftUIType visibility: Visibility) { |
| 235 | switch visibility { |
| 236 | case .automatic: self = .automatic |
| 237 | case .visible: self = .visible |
| 238 | case .hidden: self = .hidden |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | struct CompositorServicesImmersiveSpace: Scene { |
| 244 | |
| 245 | let model: Model = .shared |
| 246 | |
| 247 | @State var renderer: GDTCompositorServicesRenderer! |
| 248 | @State var didSetUpRenderer: Bool = false |
| 249 | |
| 250 | var body: some Scene { |
| 251 | ImmersiveSpace(id: "ImmersiveSpace") { |
| 252 | CompositorLayer(configuration: ContentStageConfiguration()) { @MainActor layerRenderer in |
| 253 | |
| 254 | Logger.godot.log("CompositorLayer init (initialImmersionStyle: \(String(describing: model.immersionStyle)))") |
| 255 | |
| 256 | model.seedFromProjectSettings() |
| 257 | |
| 258 | GDTAppDelegateServiceVisionOS.layerRenderer = layerRenderer |
| 259 | renderer = GDTCompositorServicesRenderer(layerRenderer: layerRenderer, |
| 260 | capabilities: GDTAppDelegateServiceVisionOS.layerRendererCapabilities) |
| 261 | |
| 262 | layerRenderer.onSpatialEvent = { events in |
| 263 | for event in events { |
| 264 | renderer.onSpatialEvent(.init(event)) |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | let signposter = OSSignposter(subsystem: "org.godotengine.godot.compositorservices", category: "loading") |
| 269 | let signpostID = signposter.makeSignpostID() |
| 270 | |
| 271 | if !didSetUpRenderer { |
| 272 | let signpost = signposter.beginInterval("setup", id: signpostID) |
| 273 | renderer.setUp() |
| 274 | didSetUpRenderer = true |
| 275 | signposter.endInterval("setup", signpost) |
| 276 | } else { |
| 277 | let signpost = signposter.beginInterval("updateXRInterface", id: signpostID) |
| 278 | renderer.updateXRInterface() |
| 279 | signposter.endInterval("updateXRInterface", signpost) |
| 280 | } |
| 281 | Task(executorPreference: RendererTaskExecutor.shared) { |
| 282 | let signpost = signposter.beginInterval("startRenderLoop", id: signpostID) |
| 283 | await renderer.startRenderLoop() |
| 284 | signposter.endInterval("startRenderLoop", signpost) |
| 285 | } |
| 286 | } |
| 287 | .onWorldRecenter { |
| 288 | renderer.worldRecentered() |
| 289 | } |
| 290 | } |
| 291 | .immersionStyle( |
| 292 | selection: Binding(get: { model.immersionStyle }, set: { model.immersionStyle = $0 }), |
| 293 | in: .mixed, .full, .progressive |
| 294 | ) |
| 295 | .upperLimbVisibility(model.upperLimbVisibility) |
| 296 | .persistentSystemOverlays(model.persistentSystemOverlays) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | // MARK: App |
| 301 | |
| 302 | @main |
| 303 | struct SwiftUIApp: App { |
| 304 | @UIApplicationDelegateAdaptor(GDTAppDelegateVisionOS.self) var appDelegate |
| 305 | |
| 306 | private var useCompositorServices: Bool = { |
| 307 | guard let sceneManifest = Bundle.main.infoDictionary?["UIApplicationSceneManifest"] as? [String: Any], |
| 308 | let defaultSessionRole = sceneManifest["UIApplicationPreferredDefaultSceneSessionRole"] as? String else { |
| 309 | return false |
| 310 | } |
| 311 | return defaultSessionRole == "CPSceneSessionRoleImmersiveSpaceApplication" |
| 312 | }() |
| 313 | |
| 314 | init() { |
| 315 | let useCompositorServices = self.useCompositorServices |
| 316 | Logger.godot.log("visionOS app init (useCompositorServices: \(useCompositorServices))") |
| 317 | GDTAppDelegateServiceVisionOS.renderMode = useCompositorServices ? .compositorServices : .windowed |
| 318 | } |
| 319 | |
| 320 | var body: some Scene { |
| 321 | GodotWindowScene() |
| 322 | CompositorServicesImmersiveSpace() |
| 323 | } |
| 324 | } |