PulseCanvas / app / visionOS / VisionImmersiveView.swift
| 1 | import SwiftUI |
| 2 | import RealityKit |
| 3 | import Metal |
| 4 | |
| 5 | @MainActor private final class VisionImmersiveSurface { |
| 6 | let texture: TextureResource |
| 7 | private let lowLevel: LowLevelTexture |
| 8 | private let renderer: VisualizerRenderer |
| 9 | private let queue: MTLCommandQueue |
| 10 | private let source: MTLTexture |
| 11 | private let smoothing: MTLComputePipelineState |
| 12 | private var task: Task<Void, Never>? |
| 13 | private var pending = 0 |
| 14 | |
| 15 | init(studio: VisionStudio, session: VisionSession) async throws { |
| 16 | renderer = VisualizerRenderer(state: studio.render) |
| 17 | // Initialize pipelines without keeping an unused full-size export texture alive. |
| 18 | try renderer.prepareOffscreen(width: 1, height: 1) |
| 19 | guard let device = renderer.offscreenDevice, let queue = device.makeCommandQueue() else { throw CocoaError(.coderInvalidValue) } |
| 20 | self.queue = queue |
| 21 | let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, |
| 22 | width: VisionPresentation.width, height: VisionPresentation.height, mipmapped: false) |
| 23 | descriptor.usage = [.renderTarget, .shaderRead]; descriptor.storageMode = .private |
| 24 | guard let source = device.makeTexture(descriptor: descriptor), |
| 25 | let function = try await device.makeLibrary(source: VisionPresentation.smoothingShader, options: nil) |
| 26 | .makeFunction(name: "smoothPresentation") else { throw CocoaError(.coderInvalidValue) } |
| 27 | self.source = source |
| 28 | smoothing = try await device.makeComputePipelineState(function: function) |
| 29 | lowLevel = try LowLevelTexture(descriptor: .init(pixelFormat: .bgra8Unorm, |
| 30 | width: VisionPresentation.width, height: VisionPresentation.height, |
| 31 | textureUsage: [.shaderWrite, .shaderRead])) |
| 32 | texture = try await TextureResource(from: lowLevel) |
| 33 | task = Task { [weak self, weak studio, weak session] in |
| 34 | let clock = ContinuousClock() |
| 35 | var deadline = clock.now |
| 36 | while !Task.isCancelled { |
| 37 | guard let self, let studio, let session else { return } |
| 38 | // Never queue stale frames behind a slow shader, or block the main actor waiting for the GPU. |
| 39 | if self.pending == 0, let command = self.queue.makeCommandBuffer() { |
| 40 | do { |
| 41 | let target = self.lowLevel.replace(using: command) |
| 42 | try self.renderer.encodeImmersive(into: self.source, command: command, |
| 43 | time: studio.render.playbackTime ?? 0) |
| 44 | guard let encoder = command.makeComputeCommandEncoder() else { throw CocoaError(.coderInvalidValue) } |
| 45 | encoder.setComputePipelineState(self.smoothing) |
| 46 | encoder.setTexture(self.source, index: 0); encoder.setTexture(target, index: 1) |
| 47 | var enabled: UInt32 = session.edgeSmoothing ? 1 : 0 |
| 48 | encoder.setBytes(&enabled, length: MemoryLayout<UInt32>.size, index: 0) |
| 49 | let width = self.smoothing.threadExecutionWidth |
| 50 | encoder.dispatchThreads(MTLSize(width: target.width, height: target.height, depth: 1), |
| 51 | threadsPerThreadgroup: MTLSize(width: width, height: min(8, self.smoothing.maxTotalThreadsPerThreadgroup / width), depth: 1)) |
| 52 | encoder.endEncoding() |
| 53 | self.pending += 1 |
| 54 | command.addCompletedHandler { [weak self, weak studio] command in |
| 55 | let error = command.error?.localizedDescription |
| 56 | Task { @MainActor in |
| 57 | self?.pending -= 1 |
| 58 | if let error { studio?.message = String(localized: "Immersive rendering failed: \(error)") } |
| 59 | } |
| 60 | } |
| 61 | command.commit() |
| 62 | } catch { studio.message = error.localizedDescription; return } |
| 63 | } |
| 64 | // Encoding time counts toward the frame interval, rather than being added to it. |
| 65 | deadline = max(deadline + .milliseconds(17), clock.now) |
| 66 | do { try await clock.sleep(until: deadline) } catch { return } |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | func stop() { task?.cancel(); task = nil } |
| 71 | deinit { task?.cancel() } |
| 72 | } |
| 73 | |
| 74 | struct VisionImmersiveView: View { |
| 75 | @ObservedObject var studio: VisionStudio |
| 76 | @ObservedObject var session: VisionSession |
| 77 | @State private var surface: VisionImmersiveSurface? |
| 78 | @State private var controls = true |
| 79 | @State private var controlsEpoch = UUID() |
| 80 | @Environment(\.openWindow) private var openWindow |
| 81 | @Environment(\.dismissImmersiveSpace) private var dismissSpace |
| 82 | |
| 83 | var body: some View { |
| 84 | RealityView { content, attachments in |
| 85 | if let panel = attachments.entity(for: "controls") { |
| 86 | panel.position = [0, 1.05, -1.5]; content.add(panel) |
| 87 | } |
| 88 | do { |
| 89 | let surface = try await VisionImmersiveSurface(studio: studio, session: session) |
| 90 | self.surface = surface |
| 91 | var material = UnlitMaterial() |
| 92 | material.color = .init(texture: .init(surface.texture)) |
| 93 | material.faceCulling = .none |
| 94 | let screen = ModelEntity(mesh: try mesh(distance: 1, full: session.fullImmersion), materials: [material]) |
| 95 | screen.name = "PulseCanvas immersive screen" |
| 96 | screen.position.y = studio.screenHeight |
| 97 | screen.scale = SIMD3(repeating: studio.screenDistance) |
| 98 | screen.components.set(InputTargetComponent()) |
| 99 | screen.components.set(CollisionComponent(shapes: [.generateBox(size: [20, 14, 0.1]) |
| 100 | .offsetBy(translation: [0, 0, -1])])) |
| 101 | content.add(screen) |
| 102 | } catch { studio.message = error.localizedDescription } |
| 103 | } update: { content, _ in |
| 104 | if let screen = content.entities.first(where: { $0.name == "PulseCanvas immersive screen" }) as? ModelEntity { |
| 105 | screen.position.y = studio.screenHeight |
| 106 | screen.scale = SIMD3(repeating: studio.screenDistance) |
| 107 | } |
| 108 | } attachments: { |
| 109 | Attachment(id: "controls") { |
| 110 | if controls { VisionImmersiveControls(studio: studio, session: session, hide: { controls = false }, returnToStudio: { |
| 111 | openWindow(id: "studio"); session.studioWindowHidden = false |
| 112 | Task { await dismissSpace() } |
| 113 | }).padding(20).glassBackgroundEffect() |
| 114 | .simultaneousGesture(TapGesture().onEnded { controlsEpoch = UUID() }) } |
| 115 | } |
| 116 | } |
| 117 | .gesture(SpatialTapGesture().targetedToAnyEntity().onEnded { value in |
| 118 | guard value.entity.name == "PulseCanvas immersive screen" else { return } |
| 119 | controls.toggle(); controlsEpoch = UUID() |
| 120 | }) |
| 121 | .task(id: controlsEpoch) { |
| 122 | do { try await Task.sleep(for: .seconds(5)) } catch { return } |
| 123 | if studio.transport.playing && studio.message == nil { controls = false } |
| 124 | } |
| 125 | .onChange(of: studio.screenDistance) { _, _ in controlsEpoch = UUID() } |
| 126 | .onAppear { studio.immersiveActive = true; session.immersiveActive = true } |
| 127 | .onDisappear { |
| 128 | surface?.stop(); surface = nil; studio.immersiveActive = false; session.immersiveActive = false |
| 129 | if session.studioWindowHidden { openWindow(id: "studio"); session.studioWindowHidden = false } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | private func mesh(distance: Float, full: Bool) throws -> MeshResource { |
| 134 | var positions = [SIMD3<Float>](), uv = [SIMD2<Float>](), indices = [UInt32]() |
| 135 | let columns = 48, rows = 12 |
| 136 | let arc: Float = full ? 2.8 : 1.65 |
| 137 | let height = full ? distance * 1.9 : distance * arc * 9 / 16 |
| 138 | for row in 0...rows { |
| 139 | for column in 0...columns { |
| 140 | let u = Float(column) / Float(columns), v = Float(row) / Float(rows) |
| 141 | let angle = (u - 0.5) * arc |
| 142 | positions.append(SIMD3(sin(angle) * distance, (0.5 - v) * height, -cos(angle) * distance)) |
| 143 | uv.append(SIMD2(u, v)) |
| 144 | if row < rows && column < columns { |
| 145 | let a = UInt32(row * (columns + 1) + column), next = UInt32(columns + 1) |
| 146 | indices += [a, a + next, a + 1, a + 1, a + next, a + next + 1] |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | var descriptor = MeshDescriptor(name: "Curved viewing canvas") |
| 151 | descriptor.positions = .init(positions); descriptor.textureCoordinates = .init(uv) |
| 152 | descriptor.primitives = .triangles(indices) |
| 153 | return try MeshResource.generate(from: [descriptor]) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | private struct VisionImmersiveControls: View { |
| 158 | @ObservedObject var studio: VisionStudio |
| 159 | @ObservedObject var session: VisionSession |
| 160 | @ObservedObject private var library = ProjectMPresets.shared |
| 161 | let hide: () -> Void |
| 162 | let returnToStudio: () -> Void |
| 163 | var body: some View { |
| 164 | VStack(spacing: 10) { |
| 165 | if let message = studio.message { Text(message).font(.callout).foregroundStyle(.orange) } |
| 166 | HStack(alignment: .center, spacing: 12) { |
| 167 | VisionImmersivePlayback(studio: studio, transport: studio.transport, session: session) |
| 168 | if session.radioMode { |
| 169 | Button("Next song", systemImage: "forward.end.fill") { session.radio.nextSong() } |
| 170 | .labelStyle(.iconOnly).disabled(session.radio.loading) |
| 171 | .frame(minWidth: 44, minHeight: 44) |
| 172 | separator |
| 173 | VisionImmersiveSongControls(radio: session.radio) |
| 174 | } else { |
| 175 | Label(studio.project.audioTitle, systemImage: "music.note") |
| 176 | .font(.callout).lineLimit(1).frame(maxWidth: 190, alignment: .leading) |
| 177 | } |
| 178 | separator |
| 179 | Button { |
| 180 | library.toggleFavorite(studio.selectedScene, appearance: studio.look.preset) |
| 181 | } label: { |
| 182 | Label(library.isFavorite(studio.selectedScene) ? "Visualizer saved" : "Save visualizer", |
| 183 | systemImage: library.isFavorite(studio.selectedScene) ? "heart.fill" : "heart") |
| 184 | .labelStyle(.iconOnly).frame(width: 44, height: 32) |
| 185 | }.accessibilityLabel(library.isFavorite(studio.selectedScene) ? "Unfavorite visualizer" : "Favorite visualizer") |
| 186 | .accessibilityIdentifier("favoriteImmersiveVisualizerButton") |
| 187 | Label(NativeEffects.names[studio.selectedScene], systemImage: "sparkles") |
| 188 | .font(.callout).lineLimit(1).frame(maxWidth: 210, alignment: .leading) |
| 189 | .accessibilityIdentifier("immersiveVisualizerName") |
| 190 | |
| 191 | Button("Random visualizer", systemImage: "shuffle") { studio.randomizeVisualizer() } |
| 192 | .labelStyle(.iconOnly).disabled(library.eligibleScenes.isEmpty) |
| 193 | .frame(minWidth: 44, minHeight: 44) |
| 194 | separator |
| 195 | Menu { |
| 196 | Toggle("Edge smoothing", isOn: $session.edgeSmoothing) |
| 197 | } label: { Image(systemName: "slider.horizontal.3").frame(width: 32, height: 32) } |
| 198 | .accessibilityLabel("Viewing settings") |
| 199 | Button("Hide controls", systemImage: "eye.slash", action: hide) |
| 200 | .labelStyle(.iconOnly).frame(minWidth: 44, minHeight: 44) |
| 201 | Button("Studio", systemImage: "rectangle.on.rectangle", action: returnToStudio) |
| 202 | .frame(minHeight: 32) |
| 203 | .accessibilityLabel("Back to Studio") |
| 204 | .accessibilityIdentifier("backToStudioButton") |
| 205 | }.font(.callout).lineLimit(1).fixedSize(horizontal: false, vertical: true) |
| 206 | }.frame(width: session.radioMode ? 1280 : 1080) |
| 207 | } |
| 208 | |
| 209 | private var separator: some View { |
| 210 | Divider().frame(height: 32).padding(.horizontal, 2) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | private struct VisionImmersiveSongControls: View { |
| 215 | @ObservedObject var radio: VisionRadio |
| 216 | var body: some View { |
| 217 | HStack(alignment: .center, spacing: 12) { |
| 218 | if let track = radio.playingTrack, !radio.isPersonalMusic { |
| 219 | Button { radio.toggleFavoriteSong(track) } label: { |
| 220 | Label(radio.isFavoriteSong(track) ? "Song saved" : "Save song", |
| 221 | systemImage: radio.isFavoriteSong(track) ? "heart.fill" : "heart") |
| 222 | .labelStyle(.iconOnly).frame(width: 44, height: 32) |
| 223 | }.disabled(radio.loading) |
| 224 | .accessibilityLabel(radio.isFavoriteSong(track) ? "Unfavorite song" : "Favorite song") |
| 225 | .accessibilityIdentifier("favoriteImmersiveSongButton") |
| 226 | } |
| 227 | Label(radio.playingTrack?.title ?? "Radio", systemImage: "music.note") |
| 228 | .font(.callout).lineLimit(1).frame(maxWidth: 190, alignment: .leading) |
| 229 | .accessibilityIdentifier("immersiveSongName") |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | private struct VisionImmersivePlayback: View { |
| 235 | @ObservedObject var studio: VisionStudio |
| 236 | @ObservedObject var transport: VisionTransport |
| 237 | @ObservedObject var session: VisionSession |
| 238 | var body: some View { |
| 239 | if session.radioMode { |
| 240 | VisionRadioPlaybackButton(radio: session.radio, transport: transport) |
| 241 | .accessibilityIdentifier("immersivePlayPauseButton") |
| 242 | } else { |
| 243 | Button { studio.togglePlayback() } label: { |
| 244 | Image(systemName: transport.playing ? "pause.fill" : "play.fill").frame(width: 44, height: 32) |
| 245 | }.disabled(studio.loading) |
| 246 | .accessibilityIdentifier("immersivePlayPauseButton") |
| 247 | } |
| 248 | } |
| 249 | } |