PulseCanvas / app / Sources / PulseCanvas / VisualizerRenderer.swift
| 1 | #if canImport(UIKit) |
| 2 | import UIKit |
| 3 | #else |
| 4 | import AppKit |
| 5 | #endif |
| 6 | import Combine |
| 7 | import Foundation |
| 8 | @preconcurrency import Metal |
| 9 | import MetalKit |
| 10 | import simd |
| 11 | import SwiftUI |
| 12 | |
| 13 | @MainActor |
| 14 | final class RenderState: ObservableObject { |
| 15 | // PulseCanvas display names; numeric scene IDs keep saved projects compatible. |
| 16 | // Native designs are fragment shaders (NativeEffects), spatial raymarches |
| 17 | // (SpatialVisuals.metal) or OriginalGeometry meshes and bead sprites (Canvas.metal). |
| 18 | static let nativeSceneNames = NativeEffects.names |
| 19 | static var sceneNames: [String] { ProjectMPresets.shared.sceneNames } |
| 20 | // The draw loop reads telemetry directly; publishing it would invalidate the editor every frame. |
| 21 | var audioPCM: [Float] = [] |
| 22 | var projectMFramesPerSecond = 60 |
| 23 | /// Retired native IDs always resolve to their replacement design. |
| 24 | @Published var scene: Int = NativeEffects.defaultScene { |
| 25 | didSet { if NativeEffects.isRetired(scene) { scene = NativeEffects.resolved(scene) } } |
| 26 | } |
| 27 | @Published var speed: Float = 1 |
| 28 | @Published var chaos: Float = 0.5 |
| 29 | var audioBeatMotionTime: Double = 0 |
| 30 | @Published var brightness: Float = 1 |
| 31 | @Published var particleSize: Float = 1 |
| 32 | @Published var liquidDetail: Float = 0.6 |
| 33 | @Published var zoomSpeed: Float = 1.5 |
| 34 | @Published var haloCount: Int = 6 |
| 35 | var audioTrebleAttackTime: Double? = nil |
| 36 | var audioTreblePulse: Float? = nil |
| 37 | var audioMomentum: Float = 0 |
| 38 | var audioPulse: Float = 0 |
| 39 | var audioBands: [Float] = Array(repeating: 0, count: 32) |
| 40 | /// Per-song smoothed band levels and attack swell from SoundtrackAnalyzer. |
| 41 | var audioEnvelopes = SIMD4<Float>(repeating: 0) |
| 42 | var audioSwell: Float = 0 |
| 43 | @Published var palette: Int = 0 |
| 44 | @Published var fog: Float = 0.5 |
| 45 | @Published var rotation: Float = 0 |
| 46 | @Published var zoom: Float = 1 |
| 47 | @Published var motionBlur: Float = 0 |
| 48 | @Published var strobeEnabled = false |
| 49 | @Published var strobeSensitivity: Float = 1 |
| 50 | @Published var strobeStrength: Float = 1 |
| 51 | var playbackTime: Double? = nil |
| 52 | @Published var paused = false |
| 53 | @Published var errorMessage: String? |
| 54 | } |
| 55 | |
| 56 | #if canImport(UIKit) |
| 57 | @MainActor |
| 58 | struct VisualizerView: UIViewRepresentable { |
| 59 | @ObservedObject var state: RenderState |
| 60 | #if os(iOS) |
| 61 | @Environment(\.scenePhase) private var phase |
| 62 | #endif |
| 63 | func makeCoordinator() -> VisualizerRenderer { VisualizerRenderer(state: state) } |
| 64 | func makeUIView(context: Context) -> MTKView { |
| 65 | let view = MTKView(frame: .zero, device: MTLCreateSystemDefaultDevice()) |
| 66 | view.colorPixelFormat = .bgra8Unorm |
| 67 | view.framebufferOnly = false |
| 68 | view.preferredFramesPerSecond = 30 |
| 69 | view.delegate = context.coordinator |
| 70 | view.isPaused = true |
| 71 | context.coordinator.attachLive(view) |
| 72 | return view |
| 73 | } |
| 74 | func updateUIView(_ view: MTKView, context: Context) { |
| 75 | context.coordinator.state = state |
| 76 | #if os(iOS) |
| 77 | view.isPaused = !context.coordinator.isReady || phase != .active |
| 78 | #endif |
| 79 | } |
| 80 | static func dismantleUIView(_ view: MTKView, coordinator: VisualizerRenderer) { |
| 81 | coordinator.cancelLiveAttachment() |
| 82 | view.isPaused = true; view.delegate = nil |
| 83 | } |
| 84 | } |
| 85 | #else |
| 86 | @MainActor |
| 87 | struct VisualizerView: NSViewRepresentable { |
| 88 | @ObservedObject var state: RenderState |
| 89 | func makeCoordinator() -> VisualizerRenderer { VisualizerRenderer(state: state) } |
| 90 | func makeNSView(context: Context) -> MTKView { |
| 91 | let view = MTKView(frame: .zero, device: MTLCreateSystemDefaultDevice()) |
| 92 | view.colorPixelFormat = .bgra8Unorm |
| 93 | view.clearColor = MTLClearColor(red: 0.003, green: 0.003, blue: 0.012, alpha: 1) |
| 94 | view.framebufferOnly = false |
| 95 | view.preferredFramesPerSecond = 60 |
| 96 | view.delegate = context.coordinator |
| 97 | context.coordinator.attach(view) |
| 98 | context.coordinator.prewarmNativeEffects() |
| 99 | return view |
| 100 | } |
| 101 | static func dismantleNSView(_ view: MTKView, coordinator: VisualizerRenderer) { |
| 102 | view.isPaused = true |
| 103 | view.delegate = nil |
| 104 | } |
| 105 | func updateNSView(_ view: MTKView, context: Context) { |
| 106 | context.coordinator.state = state |
| 107 | } |
| 108 | } |
| 109 | #endif |
| 110 | |
| 111 | private struct VisualVertex { |
| 112 | var position: SIMD3<Float> |
| 113 | var color: SIMD4<Float> |
| 114 | var uv: SIMD2<Float> |
| 115 | /// Zero selects deterministic per-triangle lighting in Canvas.metal. |
| 116 | var normal = SIMD3<Float>(repeating: 0) |
| 117 | } |
| 118 | private struct CanvasPointUniforms { |
| 119 | var mvp: simd_float4x4 |
| 120 | var pointSize: Float |
| 121 | var viewportScale: Float |
| 122 | var padding = SIMD2<Float>(repeating: 0) |
| 123 | } |
| 124 | private struct SpatialUniforms { |
| 125 | var resolution: SIMD2<Float> |
| 126 | var time: Float |
| 127 | var scene: Int32 |
| 128 | var rhythm: SIMD4<Float> |
| 129 | var style: SIMD4<Float> |
| 130 | var camera: SIMD4<Float> |
| 131 | var color0: SIMD4<Float> |
| 132 | var color1: SIMD4<Float> |
| 133 | var color2: SIMD4<Float> |
| 134 | var color3: SIMD4<Float> |
| 135 | var color4: SIMD4<Float> |
| 136 | // Native designs only; the spatial shader reads the prefix above. |
| 137 | var bands = SIMD4<Float>(repeating: 0) |
| 138 | var motion = SIMD4<Float>(repeating: 0) |
| 139 | } |
| 140 | /// Time inputs for native designs. Audio levels arrive already smoothed per song from |
| 141 | /// SoundtrackAnalyzer, so every frame is a pure function of soundtrack time. Live slider |
| 142 | /// changes are absorbed into offsets so procedural time, zoom travel and the music clock |
| 143 | /// stay continuous while dragging; offline frames and seeks use none. |
| 144 | private struct NativeMotion { |
| 145 | var scene = -1 |
| 146 | var lastSource: Double? |
| 147 | var speed: Float = 1, zoomSpeed: Float = 0, clockScale: Float = 0 |
| 148 | var timeOffset: Double = 0, travelOffset: Double = 0, clockOffset: Double = 0 |
| 149 | var musicTravelOffset: Double = 0 |
| 150 | |
| 151 | /// Returns (procedural time, zoom travel, music clock). |
| 152 | mutating func advance(scene: Int, source: Double, live: Bool, speed: Float, zoomSpeed: Float, chaos: Float, beatMotion: Double, musicZoom: Bool) -> (Double, Double, Double) { |
| 153 | let elapsed = lastSource.map { source - $0 } ?? -1 |
| 154 | let continuous = live && scene == self.scene && elapsed >= 0 && elapsed < 0.5 |
| 155 | let scale = chaos * speed |
| 156 | if continuous { |
| 157 | timeOffset += source * Double(self.speed - speed) |
| 158 | let base = source * Double(speed) + timeOffset |
| 159 | travelOffset += base * Double(self.zoomSpeed - zoomSpeed) |
| 160 | clockOffset += beatMotion * Double(clockScale - scale) |
| 161 | if musicZoom { musicTravelOffset += beatMotion * 1.6 * Double(clockScale * self.zoomSpeed - scale * zoomSpeed) } |
| 162 | } else { |
| 163 | timeOffset = 0; travelOffset = 0; clockOffset = 0; musicTravelOffset = 0 |
| 164 | } |
| 165 | // Zero Chaos must not retain a phase derived from earlier music. |
| 166 | if chaos == 0 { clockOffset = 0; musicTravelOffset = 0 } |
| 167 | if zoomSpeed == 0 { musicTravelOffset = 0 } |
| 168 | self.scene = scene; lastSource = source |
| 169 | self.speed = speed; self.zoomSpeed = zoomSpeed; clockScale = scale |
| 170 | let base = source * Double(speed) + timeOffset |
| 171 | let musicTravel = musicZoom ? beatMotion * Double(scale * zoomSpeed) * 1.6 + musicTravelOffset : 0 |
| 172 | return (base, base * Double(zoomSpeed) + travelOffset + musicTravel, beatMotion * Double(scale) + clockOffset) |
| 173 | } |
| 174 | } |
| 175 | @MainActor |
| 176 | final class VisualizerRenderer: NSObject, MTKViewDelegate { |
| 177 | var state: RenderState |
| 178 | #if !STORE_BUILD |
| 179 | private var projectMEngine: ProjectMEngine? |
| 180 | private var projectMPipeline: MTLRenderPipelineState? |
| 181 | private var projectMCommand: MTLCommandBuffer? |
| 182 | #endif |
| 183 | private var device: MTLDevice? |
| 184 | private var queue: MTLCommandQueue? |
| 185 | private var zoomTexture: MTLTexture? |
| 186 | private var zoomPipeline: MTLRenderPipelineState? |
| 187 | private var vertexBuffer: MTLBuffer? |
| 188 | private var indexBuffer: MTLBuffer? |
| 189 | private var time: Float = 0 |
| 190 | private var lastTime: CFTimeInterval = 0 |
| 191 | private var sourceClock: Double = 0 |
| 192 | private var lastError: String? |
| 193 | private var timelineTime: Double? |
| 194 | private var offscreenTarget: MTLTexture? |
| 195 | private var strobeDetector = StrobeDetector() |
| 196 | private var depthTexture: MTLTexture? |
| 197 | private var depthState: MTLDepthStencilState? |
| 198 | private var spatialPipeline: MTLRenderPipelineState? |
| 199 | private var nativeLibraries: [String: MTLLibrary] = [:] |
| 200 | private var nativeCompileErrors: [String: String] = [:] |
| 201 | private var nativePipelines: [String: MTLRenderPipelineState] = [:] |
| 202 | private var nativeMotion = NativeMotion() |
| 203 | private var offscreenFrame = false |
| 204 | private var canvasPipeline: MTLRenderPipelineState? |
| 205 | private var pointPipeline: MTLRenderPipelineState? |
| 206 | private var canvasHeight: Float = 24 |
| 207 | private var contentBlurPipeline: MTLRenderPipelineState? |
| 208 | private var blurTexture: MTLTexture? |
| 209 | private var strobePipeline: MTLRenderPipelineState? |
| 210 | private let flightSlots = DispatchSemaphore(value: 3) |
| 211 | |
| 212 | // Share immutable compiled GPU programs across previews and exports. Textures, |
| 213 | // frame clocks, command queues and audio state remain owned by each renderer. |
| 214 | // Metal programs are immutable after creation. The worker relinquishes this |
| 215 | // value before the main actor installs it and updates the pipeline dictionary. |
| 216 | private struct CompiledAssets: @unchecked Sendable { |
| 217 | let strobe, zoom, blur, canvas, point, spatial: MTLRenderPipelineState? |
| 218 | #if !STORE_BUILD |
| 219 | let projectM: MTLRenderPipelineState? |
| 220 | #endif |
| 221 | let depth: MTLDepthStencilState? |
| 222 | let libraries: [String: MTLLibrary] |
| 223 | let errors: [String: String] |
| 224 | var nativePipelines: [String: MTLRenderPipelineState] |
| 225 | } |
| 226 | private static var sharedAssets: [UInt64: CompiledAssets] = [:] |
| 227 | private static var preparingAssets: [UInt64: Task<CompiledAssets, Error>] = [:] |
| 228 | private var liveAttachment: Task<Void, Never>? |
| 229 | private(set) var isReady = false |
| 230 | private(set) static var shaderResourceBuilds = 0 |
| 231 | |
| 232 | init(state: RenderState) { self.state = state; super.init() } |
| 233 | |
| 234 | /// Synchronous attachment remains available to offline exports. Live UIKit |
| 235 | /// previews prepare the same immutable programs on a worker instead. |
| 236 | func attach(_ view: MTKView) { |
| 237 | do { |
| 238 | guard let device = view.device, let queue = device.makeCommandQueue() else { |
| 239 | throw RenderError(String(localized: "Metal is unavailable")) |
| 240 | } |
| 241 | let assets: CompiledAssets |
| 242 | if let cached = Self.sharedAssets[device.registryID] { assets = cached } |
| 243 | else { |
| 244 | assets = try Self.compileAssets(device: device) |
| 245 | Self.sharedAssets[device.registryID] = assets |
| 246 | Self.shaderResourceBuilds += 1 |
| 247 | } |
| 248 | install(assets, device: device, queue: queue) |
| 249 | } catch { report(error.localizedDescription) } |
| 250 | } |
| 251 | |
| 252 | private func install(_ assets: CompiledAssets, device: MTLDevice, queue: MTLCommandQueue) { |
| 253 | self.device = device; self.queue = queue |
| 254 | strobePipeline = assets.strobe; zoomPipeline = assets.zoom |
| 255 | contentBlurPipeline = assets.blur; canvasPipeline = assets.canvas |
| 256 | pointPipeline = assets.point; spatialPipeline = assets.spatial |
| 257 | #if !STORE_BUILD |
| 258 | projectMPipeline = assets.projectM |
| 259 | #endif |
| 260 | depthState = assets.depth; nativeLibraries = assets.libraries |
| 261 | nativeCompileErrors = assets.errors; nativePipelines = assets.nativePipelines |
| 262 | lastError = nil; isReady = true |
| 263 | if state.errorMessage != nil { state.errorMessage = nil } |
| 264 | } |
| 265 | |
| 266 | /// One shared compilation job, even when onboarding, a preview and another |
| 267 | /// window request preparation together. Cancellation of a view never cancels |
| 268 | /// the shared work needed by other views. |
| 269 | static func prepareLiveAssets() async throws { |
| 270 | guard let device = MTLCreateSystemDefaultDevice() else { throw RenderError(String(localized: "Metal is unavailable")) } |
| 271 | try await prepareLiveAssets(device: device) |
| 272 | } |
| 273 | |
| 274 | private static func prepareLiveAssets(device: MTLDevice) async throws { |
| 275 | if sharedAssets[device.registryID] != nil { return } |
| 276 | let task: Task<CompiledAssets, Error> |
| 277 | if let pending = preparingAssets[device.registryID] { task = pending } |
| 278 | else { |
| 279 | task = Task.detached(priority: .userInitiated) { try compileAssets(device: device) } |
| 280 | preparingAssets[device.registryID] = task |
| 281 | } |
| 282 | do { |
| 283 | let compiled = try await task.value |
| 284 | if sharedAssets[device.registryID] == nil { |
| 285 | sharedAssets[device.registryID] = compiled |
| 286 | shaderResourceBuilds += 1 |
| 287 | } |
| 288 | preparingAssets[device.registryID] = nil |
| 289 | } catch { |
| 290 | preparingAssets[device.registryID] = nil |
| 291 | throw error |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | #if canImport(UIKit) |
| 296 | func attachLive(_ view: MTKView) { |
| 297 | let spinner = UIActivityIndicatorView(style: .large) |
| 298 | spinner.startAnimating() |
| 299 | let label = UILabel() |
| 300 | label.text = "Preparing your canvas…"; label.textColor = .white |
| 301 | label.font = .preferredFont(forTextStyle: .callout) |
| 302 | let loading = UIStackView(arrangedSubviews: [spinner, label]) |
| 303 | loading.axis = .vertical; loading.spacing = 12; loading.alignment = .center |
| 304 | loading.isAccessibilityElement = true; loading.accessibilityLabel = label.text |
| 305 | loading.accessibilityIdentifier = "visualizerPreparing" |
| 306 | loading.translatesAutoresizingMaskIntoConstraints = false |
| 307 | view.addSubview(loading) |
| 308 | NSLayoutConstraint.activate([loading.centerXAnchor.constraint(equalTo: view.centerXAnchor), |
| 309 | loading.centerYAnchor.constraint(equalTo: view.centerYAnchor)]) |
| 310 | liveAttachment = Task { @MainActor [weak self, weak view] in |
| 311 | guard let device = view?.device else { return } |
| 312 | do { |
| 313 | try await Self.prepareLiveAssets(device: device) |
| 314 | // Compile the first selected effect before starting the draw loop. |
| 315 | // Other scene changes retain the existing per-effect cache. |
| 316 | if let scene = self?.state.scene, NativeEffects.all.indices.contains(scene) { |
| 317 | let effect = NativeEffects.all[scene] |
| 318 | if let shader = effect.shader, let assets = Self.sharedAssets[device.registryID], |
| 319 | assets.nativePipelines[shader] == nil, |
| 320 | let descriptor = Self.nativeDescriptor(for: effect, libraries: assets.libraries) { |
| 321 | let pipeline = try await Task.detached(priority: .userInitiated) { |
| 322 | try device.makeRenderPipelineState(descriptor: descriptor) |
| 323 | }.value |
| 324 | Self.sharedAssets[device.registryID]?.nativePipelines[shader] = pipeline |
| 325 | } |
| 326 | } |
| 327 | guard !Task.isCancelled, let self, let view, |
| 328 | let assets = Self.sharedAssets[device.registryID] else { return } |
| 329 | guard let queue = device.makeCommandQueue() else { throw RenderError(String(localized: "Could not create the Metal command queue")) } |
| 330 | self.install(assets, device: device, queue: queue) |
| 331 | loading.removeFromSuperview() |
| 332 | #if os(iOS) |
| 333 | view.isPaused = UIApplication.shared.applicationState != .active |
| 334 | #else |
| 335 | view.isPaused = false |
| 336 | #endif |
| 337 | } catch { |
| 338 | guard !Task.isCancelled else { return } |
| 339 | loading.removeFromSuperview() |
| 340 | self?.report(error.localizedDescription) |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | func cancelLiveAttachment() { liveAttachment?.cancel(); liveAttachment = nil } |
| 345 | #endif |
| 346 | |
| 347 | /// This function only builds immutable GPU objects, with no renderer or UI state. |
| 348 | nonisolated private static func compileAssets(device: MTLDevice) throws -> CompiledAssets { |
| 349 | let effectCandidates = [Bundle.module.url(forResource: "Strobe", withExtension: "metal", subdirectory: "NativeAssets"), Bundle.module.url(forResource: "Strobe", withExtension: "metal", subdirectory: "Resources"), Bundle.module.url(forResource: "Strobe", withExtension: "metal"), URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("Sources/PulseCanvas/Resources/Strobe.metal")] |
| 350 | guard let effectURL = effectCandidates.compactMap({ $0 }).first(where: { FileManager.default.fileExists(atPath: $0.path) }) else { throw RenderError(String(localized: "White flash shader is missing")) } |
| 351 | let effects = try device.makeLibrary(source: String(contentsOf: effectURL, encoding: .utf8), options: nil) |
| 352 | let effect = MTLRenderPipelineDescriptor() |
| 353 | effect.vertexFunction = effects.makeFunction(name: "whiteFlashVertex") |
| 354 | effect.fragmentFunction = effects.makeFunction(name: "whiteFlashFragment") |
| 355 | effect.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 356 | effect.colorAttachments[0].isBlendingEnabled = true |
| 357 | effect.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha |
| 358 | effect.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha |
| 359 | effect.colorAttachments[0].sourceAlphaBlendFactor = .one |
| 360 | effect.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha |
| 361 | let strobePipeline = try device.makeRenderPipelineState(descriptor: effect) |
| 362 | #if !STORE_BUILD |
| 363 | let projectMEffect = MTLRenderPipelineDescriptor() |
| 364 | projectMEffect.vertexFunction = effects.makeFunction(name: "whiteFlashVertex") |
| 365 | projectMEffect.fragmentFunction = effects.makeFunction(name: "projectMFragment") |
| 366 | projectMEffect.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 367 | let projectMPipeline = try device.makeRenderPipelineState(descriptor: projectMEffect) |
| 368 | #endif |
| 369 | let zoomEffect = MTLRenderPipelineDescriptor() |
| 370 | zoomEffect.vertexFunction = effects.makeFunction(name: "whiteFlashVertex") |
| 371 | zoomEffect.fragmentFunction = effects.makeFunction(name: "forwardZoomFragment") |
| 372 | zoomEffect.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 373 | let zoomPipeline = try device.makeRenderPipelineState(descriptor: zoomEffect) |
| 374 | let blurEffect = MTLRenderPipelineDescriptor() |
| 375 | blurEffect.vertexFunction = effects.makeFunction(name: "whiteFlashVertex") |
| 376 | blurEffect.fragmentFunction = effects.makeFunction(name: "contentBlurFragment") |
| 377 | blurEffect.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 378 | let contentBlurPipeline = try device.makeRenderPipelineState(descriptor: blurEffect) |
| 379 | let canvasSource = effectURL.deletingLastPathComponent().appendingPathComponent("Canvas.metal") |
| 380 | let canvasLibrary = try device.makeLibrary(source: String(contentsOf: canvasSource, encoding: .utf8), options: nil) |
| 381 | let canvas = MTLRenderPipelineDescriptor() |
| 382 | canvas.vertexFunction = canvasLibrary.makeFunction(name: "canvasVertex") |
| 383 | canvas.fragmentFunction = canvasLibrary.makeFunction(name: "canvasFragment") |
| 384 | let descriptor = MTLVertexDescriptor() |
| 385 | descriptor.attributes[0].format = .float3; descriptor.attributes[0].offset = 0; descriptor.attributes[0].bufferIndex = 0 |
| 386 | descriptor.attributes[1].format = .float4; descriptor.attributes[1].offset = 16; descriptor.attributes[1].bufferIndex = 0 |
| 387 | descriptor.attributes[2].format = .float2; descriptor.attributes[2].offset = 32; descriptor.attributes[2].bufferIndex = 0 |
| 388 | descriptor.attributes[3].format = .float3; descriptor.attributes[3].offset = MemoryLayout<VisualVertex>.offset(of: \.normal)!; descriptor.attributes[3].bufferIndex = 0 |
| 389 | descriptor.layouts[0].stride = MemoryLayout<VisualVertex>.stride |
| 390 | canvas.depthAttachmentPixelFormat = .depth32Float |
| 391 | canvas.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 392 | let canvasPipeline = try device.makeRenderPipelineState(descriptor: canvas) |
| 393 | let point = MTLRenderPipelineDescriptor() |
| 394 | point.vertexFunction = canvasLibrary.makeFunction(name: "canvasPointVertex") |
| 395 | point.fragmentFunction = canvasLibrary.makeFunction(name: "canvasPointFragment") |
| 396 | point.vertexDescriptor = descriptor |
| 397 | point.inputPrimitiveTopology = .point |
| 398 | point.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 399 | let blend = point.colorAttachments[0]! |
| 400 | blend.isBlendingEnabled = true |
| 401 | blend.sourceRGBBlendFactor = .sourceAlpha; blend.destinationRGBBlendFactor = .oneMinusSourceAlpha |
| 402 | blend.sourceAlphaBlendFactor = .one; blend.destinationAlphaBlendFactor = .oneMinusSourceAlpha |
| 403 | let pointPipeline = try device.makeRenderPipelineState(descriptor: point) |
| 404 | let spatialSource = effectURL.deletingLastPathComponent().appendingPathComponent("SpatialVisuals.metal") |
| 405 | let spatialLibrary = try device.makeLibrary(source: String(contentsOf: spatialSource, encoding: .utf8), options: nil) |
| 406 | let spatial = MTLRenderPipelineDescriptor() |
| 407 | spatial.vertexFunction = spatialLibrary.makeFunction(name: "spatialVertex") |
| 408 | spatial.fragmentFunction = spatialLibrary.makeFunction(name: "spatialFragment") |
| 409 | spatial.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 410 | let spatialPipeline = try device.makeRenderPipelineState(descriptor: spatial) |
| 411 | let (nativeLibraries, nativeCompileErrors) = try compileNativeLibraries(device: device, folder: effectURL.deletingLastPathComponent()) |
| 412 | let nativePipelines: [String: MTLRenderPipelineState] = [:] |
| 413 | let depth = MTLDepthStencilDescriptor(); depth.depthCompareFunction = .lessEqual; depth.isDepthWriteEnabled = true |
| 414 | let depthState = device.makeDepthStencilState(descriptor: depth) |
| 415 | #if !STORE_BUILD |
| 416 | let compiled = CompiledAssets(strobe: strobePipeline, zoom: zoomPipeline, blur: contentBlurPipeline, |
| 417 | canvas: canvasPipeline, point: pointPipeline, spatial: spatialPipeline, projectM: projectMPipeline, |
| 418 | depth: depthState, libraries: nativeLibraries, errors: nativeCompileErrors, nativePipelines: nativePipelines) |
| 419 | #else |
| 420 | let compiled = CompiledAssets(strobe: strobePipeline, zoom: zoomPipeline, blur: contentBlurPipeline, |
| 421 | canvas: canvasPipeline, point: pointPipeline, spatial: spatialPipeline, |
| 422 | depth: depthState, libraries: nativeLibraries, errors: nativeCompileErrors, nativePipelines: nativePipelines) |
| 423 | #endif |
| 424 | return compiled |
| 425 | } |
| 426 | |
| 427 | private func report(_ text: String) { |
| 428 | if text != lastError { lastError = text; state.errorMessage = text } |
| 429 | } |
| 430 | |
| 431 | /// Each native file is compiled after the shared prelude, so effects can be added |
| 432 | /// by writing one function and registering it in NativeEffects. A file that fails |
| 433 | /// to compile disables only its own designs, which report the compiler message. |
| 434 | nonisolated private static func compileNativeLibraries(device: MTLDevice, folder: URL) throws -> ([String: MTLLibrary], [String: String]) { |
| 435 | let prelude = try String(contentsOf: folder.appendingPathComponent("NativeCommon.metal"), encoding: .utf8) |
| 436 | let options = MTLCompileOptions() |
| 437 | var nativeLibraries: [String: MTLLibrary] = [:] |
| 438 | var nativeCompileErrors: [String: String] = [:] |
| 439 | for file in NativeEffects.shaderFiles { |
| 440 | do { |
| 441 | let source = try String(contentsOf: folder.appendingPathComponent(file), encoding: .utf8) |
| 442 | let activePrelude = file.hasPrefix("NativeExpansion") ? try String(contentsOf: folder.appendingPathComponent("NativeExpansionCommon.metal"), encoding: .utf8) : prelude |
| 443 | nativeLibraries[file] = try device.makeLibrary(source: activePrelude + "\n#line 1 \"\(file)\"\n" + source, options: options) |
| 444 | } catch { nativeCompileErrors[file] = "Native shader \(file) failed to compile: \(error.localizedDescription)" } |
| 445 | } |
| 446 | return (nativeLibraries, nativeCompileErrors) |
| 447 | } |
| 448 | |
| 449 | private func nativeDescriptor(for effect: NativeEffect) -> MTLRenderPipelineDescriptor? { |
| 450 | Self.nativeDescriptor(for: effect, libraries: nativeLibraries) |
| 451 | } |
| 452 | nonisolated private static func nativeDescriptor(for effect: NativeEffect, libraries: [String: MTLLibrary]) -> MTLRenderPipelineDescriptor? { |
| 453 | guard let shader = effect.shader, let file = effect.file, let library = libraries[file], |
| 454 | let vertex = library.makeFunction(name: "nativeVertex"), |
| 455 | let fragment = library.makeFunction(name: shader + "Fragment") else { return nil } |
| 456 | let descriptor = MTLRenderPipelineDescriptor() |
| 457 | descriptor.label = effect.name |
| 458 | descriptor.vertexFunction = vertex; descriptor.fragmentFunction = fragment |
| 459 | descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm |
| 460 | return descriptor |
| 461 | } |
| 462 | |
| 463 | private func nativePipeline(for effect: NativeEffect) throws -> MTLRenderPipelineState { |
| 464 | guard let shader = effect.shader else { throw RenderError(String(localized: "\(effect.name) is not a native Metal design")) } |
| 465 | if let cached = nativePipelines[shader] ?? device.flatMap({ Self.sharedAssets[$0.registryID]?.nativePipelines[shader] }) { |
| 466 | nativePipelines[shader] = cached |
| 467 | return cached |
| 468 | } |
| 469 | if let file = effect.file, let error = nativeCompileErrors[file] { throw RenderError(error) } |
| 470 | guard let device, let descriptor = nativeDescriptor(for: effect) else { throw RenderError(String(localized: "Native shader \(shader) is missing")) } |
| 471 | let pipeline = try device.makeRenderPipelineState(descriptor: descriptor) |
| 472 | nativePipelines[shader] = pipeline |
| 473 | Self.sharedAssets[device.registryID]?.nativePipelines[shader] = pipeline |
| 474 | return pipeline |
| 475 | } |
| 476 | |
| 477 | /// Builds every native pipeline in the background so the first switch to a design |
| 478 | /// never stalls the live view. Offline renderers build on demand instead. |
| 479 | func prewarmNativeEffects() { |
| 480 | guard let device else { return } |
| 481 | for effect in NativeEffects.all { |
| 482 | guard let shader = effect.shader, nativePipelines[shader] == nil, let descriptor = nativeDescriptor(for: effect) else { continue } |
| 483 | device.makeRenderPipelineState(descriptor: descriptor) { [weak self] pipeline, _ in |
| 484 | guard let pipeline else { return } |
| 485 | Task { @MainActor in |
| 486 | guard let self, self.nativePipelines[shader] == nil else { return } |
| 487 | self.nativePipelines[shader] = pipeline |
| 488 | Self.sharedAssets[device.registryID]?.nativePipelines[shader] = pipeline |
| 489 | } |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { blurTexture = nil } |
| 495 | |
| 496 | func draw(in view: MTKView) { |
| 497 | #if os(iOS) |
| 498 | guard UIApplication.shared.applicationState != .background else { return } |
| 499 | #endif |
| 500 | guard device != nil, let queue, canvasPipeline != nil, let drawable = view.currentDrawable else { return } |
| 501 | guard flightSlots.wait(timeout: .now()) == .success else { return } |
| 502 | guard let command = queue.makeCommandBuffer() else { flightSlots.signal(); return } |
| 503 | command.label = "Visual shader frame" |
| 504 | let now = CACurrentMediaTime() |
| 505 | let dt = lastTime == 0 ? Float(1.0 / 60.0) : Float(min(now - lastTime, 0.05)) |
| 506 | lastTime = now |
| 507 | if !state.paused { sourceClock += Double(dt) } |
| 508 | timelineTime = state.playbackTime |
| 509 | offscreenFrame = false |
| 510 | if let absoluteTime = timelineTime { |
| 511 | time = animationTime(at: absoluteTime) |
| 512 | } else if !state.paused { time += dt * max(0, state.speed) } |
| 513 | do { try encodeFrame(command: command, target: drawable.texture, preview: true); if lastError != nil {lastError = nil; state.errorMessage = nil} } |
| 514 | catch { report(error.localizedDescription); flightSlots.signal(); return } |
| 515 | command.present(drawable) |
| 516 | let semaphore = flightSlots |
| 517 | command.addCompletedHandler { [weak self] buffer in |
| 518 | semaphore.signal() |
| 519 | let error = buffer.error?.localizedDescription |
| 520 | Task { @MainActor [weak self] in |
| 521 | guard let self else { return } |
| 522 | if let error { self.report("GPU render failed: \(error)") } |
| 523 | } |
| 524 | } |
| 525 | command.commit() |
| 526 | } |
| 527 | |
| 528 | /// Prepare an independent renderer for exact-size offline output. No window or drawable is required. |
| 529 | func prepareOffscreen(width: Int, height: Int) throws { |
| 530 | guard (1...8192).contains(width), (1...8192).contains(height) else { |
| 531 | throw RenderError(String(localized: "Export dimensions must be between 1 and 8192 pixels")) |
| 532 | } |
| 533 | if device == nil { |
| 534 | let view = MTKView(frame: CGRect(x: 0, y: 0, width: width, height: height), device: MTLCreateSystemDefaultDevice()) |
| 535 | attach(view) |
| 536 | } |
| 537 | if let error = state.errorMessage { throw RenderError(error) } |
| 538 | guard let device, let target = makeTarget(device, width, height, shared: true) else { |
| 539 | throw RenderError(String(localized: "Could not allocate offline render target")) |
| 540 | } |
| 541 | offscreenTarget = target |
| 542 | } |
| 543 | |
| 544 | /// Returns GPU-complete, shared BGRA8 pixels at absolute soundtrack time. |
| 545 | /// The target is reused; consumers must read it before requesting the next frame. |
| 546 | func renderOffscreen(time absoluteTime: Double, audioBands: [Float], audioPulse: Float = 0, audioMomentum: Float = 0, audioBeatMotionTime: Double = 0, audioTreblePulse: Float? = nil, audioTrebleAttackTime: Double? = nil, audioEnvelopes: SIMD4<Float> = .zero, audioSwell: Float = 0) throws -> MTLTexture { |
| 547 | guard let target = offscreenTarget else { throw RenderError(String(localized: "Call prepareOffscreen(width:height:) before rendering")) } |
| 548 | let command = try offscreenCommand(target: target, time: absoluteTime, audioBands: audioBands, audioPulse: audioPulse, audioMomentum: audioMomentum, audioBeatMotionTime: audioBeatMotionTime, audioTreblePulse: audioTreblePulse, audioTrebleAttackTime: audioTrebleAttackTime, audioEnvelopes: audioEnvelopes, audioSwell: audioSwell) |
| 549 | command.commit(); command.waitUntilCompleted() |
| 550 | if let error = command.error { throw RenderError(String(localized: "Offline GPU render failed: \(error.localizedDescription)")) } |
| 551 | return target |
| 552 | } |
| 553 | |
| 554 | var offscreenDevice: MTLDevice? { device } |
| 555 | |
| 556 | #if os(visionOS) |
| 557 | /// RealityKit owns presentation; it supplies a LowLevelTexture and tracks this command buffer. |
| 558 | func encodeImmersive(into target: MTLTexture, command: MTLCommandBuffer, time: Double) throws { |
| 559 | guard time.isFinite, time >= 0 else { throw RenderError(String(localized: "Invalid immersive timestamp")) } |
| 560 | timelineTime = time; offscreenFrame = false |
| 561 | self.time = animationTime(at: time) |
| 562 | try encodeFrame(command: command, target: target) |
| 563 | } |
| 564 | #endif |
| 565 | |
| 566 | /// Render directly into the encoder's IOSurface, yielding the UI while the GPU works. |
| 567 | func renderOffscreen(into target: MTLTexture, time absoluteTime: Double, audioBands: [Float], audioPulse: Float = 0, audioMomentum: Float = 0, audioBeatMotionTime: Double = 0, audioTreblePulse: Float? = nil, audioTrebleAttackTime: Double? = nil, audioEnvelopes: SIMD4<Float> = .zero, audioSwell: Float = 0) async throws { |
| 568 | let command = try offscreenCommand(target: target, time: absoluteTime, audioBands: audioBands, audioPulse: audioPulse, audioMomentum: audioMomentum, audioBeatMotionTime: audioBeatMotionTime, audioTreblePulse: audioTreblePulse, audioTrebleAttackTime: audioTrebleAttackTime, audioEnvelopes: audioEnvelopes, audioSwell: audioSwell) |
| 569 | await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in |
| 570 | command.addCompletedHandler { _ in continuation.resume() } |
| 571 | command.commit() |
| 572 | } |
| 573 | if let error = command.error { throw RenderError(String(localized: "Offline GPU render failed: \(error.localizedDescription)")) } |
| 574 | } |
| 575 | |
| 576 | private func offscreenCommand(target: MTLTexture, time absoluteTime: Double, audioBands: [Float], audioPulse: Float, audioMomentum: Float, audioBeatMotionTime: Double, audioTreblePulse: Float?, audioTrebleAttackTime: Double?, audioEnvelopes: SIMD4<Float>, audioSwell: Float) throws -> MTLCommandBuffer { |
| 577 | guard absoluteTime.isFinite, absoluteTime >= 0 else { throw RenderError(String(localized: "Invalid export timestamp")) } |
| 578 | guard let queue, let command = queue.makeCommandBuffer(), target.pixelFormat == .bgra8Unorm else { |
| 579 | throw RenderError(String(localized: "Offline renderer is unavailable or the frame format is invalid")) |
| 580 | } |
| 581 | timelineTime = absoluteTime |
| 582 | offscreenFrame = true |
| 583 | state.audioBeatMotionTime = audioBeatMotionTime.isFinite ? max(0, audioBeatMotionTime) : 0 |
| 584 | time = animationTime(at: absoluteTime) |
| 585 | state.audioTrebleAttackTime = audioTrebleAttackTime |
| 586 | state.audioTreblePulse = audioTreblePulse |
| 587 | state.audioMomentum = audioMomentum.isFinite ? min(1, max(0, audioMomentum)) : 0 |
| 588 | state.audioPulse = audioPulse.isFinite ? min(1, max(0, audioPulse)) : 0 |
| 589 | state.audioBands = audioBands.map { $0.isFinite ? max(0, min(1, $0)) : 0 } |
| 590 | state.audioEnvelopes = simd_clamp(audioEnvelopes, .zero, SIMD4(repeating: 1)) |
| 591 | state.audioSwell = audioSwell.isFinite ? min(1, max(0, audioSwell)) : 0 |
| 592 | try encodeFrame(command: command, target: target) |
| 593 | if lastError != nil {lastError = nil; state.errorMessage = nil} |
| 594 | return command |
| 595 | } |
| 596 | |
| 597 | private var chaosAmount: Float { state.chaos.isFinite ? min(1, max(0, state.chaos)) : 0.5 } |
| 598 | private var visualPulse: Float { |
| 599 | (state.audioPulse.isFinite ? min(1, max(0, state.audioPulse)) : 0) * chaosAmount |
| 600 | } |
| 601 | private var chaosDrive: Float { min(1, max(0, state.audioMomentum)) * chaosAmount * 2 } |
| 602 | // Keep source analysis intact for playback/export. Scale every visual |
| 603 | // consumer here so zero Chaos is pure procedural motion in every family. |
| 604 | // Geometry that moves with the music reads the per-song smoothed levels and |
| 605 | // attack swell, so motion swells instead of jumping frame to frame. |
| 606 | private var visualLevels: SIMD4<Float> { |
| 607 | simd_clamp(state.audioEnvelopes, .zero, SIMD4(repeating: 1)) * chaosAmount |
| 608 | } |
| 609 | private var visualSwell: Float { |
| 610 | (state.audioSwell.isFinite ? min(1, max(0, state.audioSwell)) : 0) * chaosAmount |
| 611 | } |
| 612 | private var visualBands: [Float] { |
| 613 | state.audioBands.map { ($0.isFinite ? min(1, max(0, $0)) : 0) * chaosAmount } |
| 614 | } |
| 615 | |
| 616 | private func animationTime(at sourceTime: Double) -> Float { |
| 617 | // Integrating the source beat envelope accelerates smoothly without a |
| 618 | // changing time multiplier that would rewind or jump on every attack. |
| 619 | let motion = state.audioBeatMotionTime.isFinite ? max(0, state.audioBeatMotionTime) : 0 |
| 620 | return Float(sourceTime + motion * Double(chaosAmount) * 3) * max(0, state.speed) |
| 621 | } |
| 622 | |
| 623 | private func encodeFrame(command: MTLCommandBuffer, target: MTLTexture, preview: Bool = false) throws { |
| 624 | guard let d = device else { throw RenderError(String(localized: "Metal device is unavailable")) } |
| 625 | #if !STORE_BUILD |
| 626 | if let preset = ProjectMPresets.shared.preset(for: state.scene) { |
| 627 | // The external engine writes a shared surface. Finish its previous |
| 628 | // Metal consumer before reusing that surface on the OpenGL queue. |
| 629 | projectMCommand?.waitUntilCompleted() |
| 630 | if projectMEngine == nil { projectMEngine = try ProjectMEngine() } |
| 631 | let size = preview ? ProjectMPreviewSize.dimensions(width: target.width, height: target.height) : (width: target.width, height: target.height) |
| 632 | let source = try projectMEngine!.frame(preset: ProjectMPresets.shared.url(for: preset), |
| 633 | texturePaths: ProjectMPresets.shared.texturePaths(for: preset), device: d, |
| 634 | width: size.width, height: size.height, time: Double(time), |
| 635 | sourceTime: timelineTime ?? sourceClock, pcm: state.audioPCM, chaos: chaosAmount, fps: state.projectMFramesPerSecond) |
| 636 | let pass = MTLRenderPassDescriptor(); pass.colorAttachments[0].texture = target |
| 637 | pass.colorAttachments[0].loadAction = .dontCare; pass.colorAttachments[0].storeAction = .store |
| 638 | guard let encoder = command.makeRenderCommandEncoder(descriptor: pass), let projectMPipeline else { throw RenderError(String(localized: "ProjectM compositor is unavailable")) } |
| 639 | encoder.setRenderPipelineState(projectMPipeline); encoder.setFragmentTexture(source, index: 0) |
| 640 | var style = SIMD4<Float>(state.brightness, state.zoom, state.rotation, 0) |
| 641 | encoder.setFragmentBytes(&style, length: MemoryLayout<SIMD4<Float>>.stride, index: 0) |
| 642 | var outputSize = SIMD2<Float>(Float(target.width), Float(target.height)) |
| 643 | encoder.setFragmentBytes(&outputSize, length: MemoryLayout<SIMD2<Float>>.stride, index: 1) |
| 644 | encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3); encoder.endEncoding() |
| 645 | try encodeEffects(command: command, target: target) |
| 646 | projectMCommand = command |
| 647 | return |
| 648 | } |
| 649 | projectMEngine = nil; projectMCommand = nil |
| 650 | #endif |
| 651 | if let effect = NativeEffects.effect(state.scene), effect.shader != nil { |
| 652 | try encodeNative(effect, command: command, target: target) |
| 653 | return |
| 654 | } |
| 655 | if Self.spatialScenes.contains(state.scene) { |
| 656 | try encodeSpatial(command: command, target: target) |
| 657 | return |
| 658 | } |
| 659 | try encodeCanvas(d, command: command, target: target) |
| 660 | } |
| 661 | |
| 662 | /// Released designs drawn by SpatialVisuals.metal. |
| 663 | private static let spatialScenes: Set<Int> = [4, 10, 12, 22, 23, 24, 25, 26, 27, 28, 29] |
| 664 | |
| 665 | /// Released designs 15–21: OriginalGeometry surfaces and bead sprites on a drifting canvas. |
| 666 | private func encodeCanvas(_ d: MTLDevice, command: MTLCommandBuffer, target: MTLTexture) throws { |
| 667 | guard let canvasPipeline, let pointPipeline else { throw RenderError(String(localized: "Canvas shaders are unavailable")) } |
| 668 | let width = target.width, height = target.height |
| 669 | let aspect = Float(width) / Float(max(height, 1)) |
| 670 | canvasHeight = (state.scene == 18 ? 20 : 24) / max(0.65, state.zoom) |
| 671 | let distance: Float = 44 |
| 672 | let projection = perspective(fov: 2 * atan(canvasHeight / (2 * distance)), aspect: aspect, near: 0.1, far: 180) |
| 673 | var camera = matrix_identity_float4x4 |
| 674 | camera.columns.3 = SIMD4(sin(time * 0.33) * 0.7, cos(time * 0.27) * 0.5, -distance, 1) |
| 675 | let pitch = sin(time * 0.28) * 0.22 |
| 676 | let yaw = sin(time * 0.21) * 0.35 |
| 677 | var mvp = projection * camera * rotateX(pitch) * rotateY(yaw) * rotateZ(state.rotation) |
| 678 | let mesh = OriginalGeometry.make(scene: state.scene, time: time, spectrum: visualBands, intensity: 1 + chaosDrive * 0.9, palette: state.palette) |
| 679 | let (rawVertices, indices) = immersive(mesh: mesh, aspect: aspect) |
| 680 | let strength = visualSwell * (0.2 + chaosAmount * 0.55) + chaosDrive * 0.08 + visualLevels.x * 0.12 |
| 681 | let vertices = strength > 0 ? rawVertices.map { vertex -> VisualVertex in |
| 682 | var result = vertex |
| 683 | let p = vertex.position |
| 684 | let ripple = SIMD3<Float>(sin(p.y * 0.53 + p.z * 0.31 - time * 1.3), |
| 685 | sin(p.x * 0.47 - p.z * 0.39 + time * 1.1), |
| 686 | sin(p.x * 0.41 + p.y * 0.37 - time * 0.9)) |
| 687 | // Waves bend individual points and surface patches, leaving the |
| 688 | // camera framing steady instead of scaling the whole screen. |
| 689 | result.position += ripple * (strength * 0.85) |
| 690 | return result |
| 691 | } : rawVertices |
| 692 | guard !vertices.isEmpty else { throw RenderError(String(localized: "Scene geometry is empty")) } |
| 693 | vertexBuffer = vertices.withUnsafeBytes { d.makeBuffer(bytes: $0.baseAddress!, length: $0.count, options: .storageModeShared) } |
| 694 | if !indices.isEmpty { indexBuffer = indices.withUnsafeBytes { d.makeBuffer(bytes: $0.baseAddress!, length: $0.count, options: .storageModeShared) } } |
| 695 | let pass = MTLRenderPassDescriptor() |
| 696 | pass.colorAttachments[0].texture = target |
| 697 | pass.colorAttachments[0].loadAction = .clear; pass.colorAttachments[0].storeAction = .store |
| 698 | pass.colorAttachments[0].clearColor = MTLClearColor(red: 0.002, green: 0.002, blue: 0.007, alpha: 1) |
| 699 | // Bead sprites arrive sorted far to near and blend without a depth buffer. |
| 700 | let beads = indices.isEmpty |
| 701 | if !beads { |
| 702 | if depthTexture?.width != width || depthTexture?.height != height { |
| 703 | let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width, height: height, mipmapped: false) |
| 704 | descriptor.storageMode = .private; descriptor.usage = .renderTarget |
| 705 | depthTexture = d.makeTexture(descriptor: descriptor) |
| 706 | } |
| 707 | guard let depthTexture else { throw RenderError(String(localized: "Cannot allocate surface depth buffer")) } |
| 708 | pass.depthAttachment.texture = depthTexture; pass.depthAttachment.clearDepth = 1 |
| 709 | pass.depthAttachment.loadAction = .clear; pass.depthAttachment.storeAction = .dontCare |
| 710 | } |
| 711 | guard let encoder = command.makeRenderCommandEncoder(descriptor: pass), let vertexBuffer else { throw RenderError(String(localized: "Could not create Metal render encoder")) } |
| 712 | encoder.label = "Canvas frame" |
| 713 | encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0) |
| 714 | encoder.setCullMode(.none) |
| 715 | if beads { |
| 716 | var uniforms = CanvasPointUniforms(mvp: mvp, pointSize: (state.scene == 18 ? 0.36 : 0.30) * max(0.1, state.particleSize), |
| 717 | viewportScale: Float(height) * distance / canvasHeight) |
| 718 | encoder.setRenderPipelineState(pointPipeline) |
| 719 | encoder.setVertexBytes(&uniforms, length: MemoryLayout<CanvasPointUniforms>.stride, index: 1) |
| 720 | encoder.drawPrimitives(type: .point, vertexStart: 0, vertexCount: vertices.count) |
| 721 | } else { |
| 722 | encoder.setRenderPipelineState(canvasPipeline) |
| 723 | encoder.setDepthStencilState(depthState) |
| 724 | encoder.setVertexBytes(&mvp, length: 64, index: 1) |
| 725 | encoder.setVertexBuffer(indexBuffer, offset: 0, index: 3) |
| 726 | encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: indices.count) |
| 727 | } |
| 728 | encoder.endEncoding() |
| 729 | try encodeEffects(command: command, target: target) |
| 730 | } |
| 731 | |
| 732 | private func encodeSpatial(command: MTLCommandBuffer, target: MTLTexture) throws { |
| 733 | guard let pipeline = spatialPipeline else { throw RenderError(String(localized: "Spatial visual shader is unavailable")) } |
| 734 | let pass = MTLRenderPassDescriptor() |
| 735 | pass.colorAttachments[0].texture = target |
| 736 | pass.colorAttachments[0].loadAction = .dontCare; pass.colorAttachments[0].storeAction = .store |
| 737 | guard let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { throw RenderError(String(localized: "Could not encode spatial visual")) } |
| 738 | let palette = VisualPalette(rawValue: state.palette) ?? .ultraviolet |
| 739 | let colors = palette.stops.map { SIMD4<Float>($0, 1) } |
| 740 | var frame = SpatialUniforms(resolution: SIMD2(Float(target.width), Float(target.height)), time: time, scene: Int32(state.scene), |
| 741 | rhythm: SIMD4(visualSwell, chaosDrive, visualLevels.x, visualLevels.w), |
| 742 | style: SIMD4(state.brightness, state.particleSize, state.fog, state.zoom), |
| 743 | camera: SIMD4(state.rotation, chaosAmount, state.scene == 28 ? Float(state.haloCount) : state.liquidDetail, state.zoomSpeed), |
| 744 | color0: colors[0], color1: colors[1], color2: colors[2], color3: colors[3], color4: colors[4]) |
| 745 | encoder.setRenderPipelineState(pipeline) |
| 746 | encoder.setFragmentBytes(&frame, length: MemoryLayout<SpatialUniforms>.stride, index: 0) |
| 747 | encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) |
| 748 | encoder.endEncoding() |
| 749 | try encodeEffects(command: command, target: target) |
| 750 | } |
| 751 | |
| 752 | private func encodeNative(_ effect: NativeEffect, command: MTLCommandBuffer, target: MTLTexture) throws { |
| 753 | let pipeline = try nativePipeline(for: effect) |
| 754 | let speed = state.speed.isFinite ? max(0, state.speed) : 1 |
| 755 | let zoomSpeed = state.zoomSpeed.isFinite ? min(3, max(0, state.zoomSpeed)) : 0 |
| 756 | let beatMotion = state.audioBeatMotionTime.isFinite ? max(0, state.audioBeatMotionTime) : 0 |
| 757 | let momentum = state.audioMomentum.isFinite ? min(1, max(0, state.audioMomentum)) : 0 |
| 758 | let expansion = effect.file?.hasPrefix("NativeExpansion") == true |
| 759 | let atmospheric = effect.file == NativeEffects.atmospheric |
| 760 | let (base, travel, clock) = nativeMotion.advance(scene: state.scene, source: timelineTime ?? sourceClock, live: !offscreenFrame, |
| 761 | speed: speed, zoomSpeed: zoomSpeed, chaos: chaosAmount, beatMotion: beatMotion, musicZoom: expansion && !atmospheric) |
| 762 | let swell = state.audioSwell.isFinite ? min(1, max(0, state.audioSwell)) : 0 |
| 763 | let pass = MTLRenderPassDescriptor() |
| 764 | pass.colorAttachments[0].texture = target |
| 765 | pass.colorAttachments[0].loadAction = .dontCare; pass.colorAttachments[0].storeAction = .store |
| 766 | guard let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { throw RenderError(String(localized: "Could not encode \(effect.name)")) } |
| 767 | let palette = VisualPalette(rawValue: state.palette) ?? .ultraviolet |
| 768 | var colors = palette.stops.map { SIMD4<Float>($0, 1) } |
| 769 | // Atmospheric shaders use their authored color grade at the default palette. |
| 770 | if atmospheric && palette.rawValue == effect.look.palette { colors[0].w = 0 } |
| 771 | // Expansion designs read the sharp attack in x and the quarter-second attack swell in z, |
| 772 | // which their shared beat motion uses so beats read as movement rather than a flick. |
| 773 | var frame = SpatialUniforms(resolution: SIMD2(Float(target.width), Float(target.height)), time: Float(base), scene: Int32(state.scene), |
| 774 | rhythm: SIMD4(expansion ? visualPulse : swell * chaosAmount, chaosDrive, expansion ? swell * chaosAmount : visualLevels.x, visualLevels.w), |
| 775 | style: SIMD4(state.brightness, state.particleSize, state.fog, state.zoom), |
| 776 | camera: SIMD4(state.rotation, chaosAmount, state.liquidDetail, zoomSpeed), |
| 777 | color0: colors[0], color1: colors[1], color2: colors[2], color3: colors[3], color4: colors[4], |
| 778 | bands: simd_clamp(state.audioEnvelopes, .zero, SIMD4(repeating: 1)) * chaosAmount, |
| 779 | motion: SIMD4(Float(travel), Float(clock), Float(base), momentum * chaosAmount)) |
| 780 | encoder.setRenderPipelineState(pipeline) |
| 781 | encoder.setFragmentBytes(&frame, length: MemoryLayout<SpatialUniforms>.stride, index: 0) |
| 782 | encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) |
| 783 | encoder.endEncoding() |
| 784 | try encodeEffects(command: command, target: target) |
| 785 | } |
| 786 | |
| 787 | private func encodeEffects(command: MTLCommandBuffer, target: MTLTexture) throws { |
| 788 | // Spatial corridors move their camera through the actual scene. Other |
| 789 | // designs use seamless expanding layers, with no zoom pass at zero. |
| 790 | let hasSpatialTravel = NativeEffects.effect(state.scene)?.travels ?? false |
| 791 | let zoomSpeed = state.zoomSpeed.isFinite ? min(3, max(0, state.zoomSpeed)) : 0 |
| 792 | if !hasSpatialTravel && zoomSpeed > 0, let device, let zoomPipeline { |
| 793 | if zoomTexture?.width != target.width || zoomTexture?.height != target.height { |
| 794 | zoomTexture = makeTarget(device, target.width, target.height, shared: false) |
| 795 | } |
| 796 | guard let source = zoomTexture, let blit = command.makeBlitCommandEncoder() else { throw RenderError(String(localized: "Could not prepare forward zoom")) } |
| 797 | blit.copy(from: target, sourceSlice: 0, sourceLevel: 0, sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0), sourceSize: MTLSize(width: target.width, height: target.height, depth: 1), to: source, destinationSlice: 0, destinationLevel: 0, destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0)) |
| 798 | blit.endEncoding() |
| 799 | let pass = MTLRenderPassDescriptor(); pass.colorAttachments[0].texture = target |
| 800 | pass.colorAttachments[0].loadAction = .dontCare; pass.colorAttachments[0].storeAction = .store |
| 801 | guard let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { throw RenderError(String(localized: "Could not encode forward zoom")) } |
| 802 | encoder.setRenderPipelineState(zoomPipeline) |
| 803 | encoder.setFragmentTexture(source, index: 0) |
| 804 | var travel = time * zoomSpeed * 0.16 |
| 805 | encoder.setFragmentBytes(&travel, length: 4, index: 0) |
| 806 | encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) |
| 807 | encoder.endEncoding() |
| 808 | } |
| 809 | if state.motionBlur > 0.001 { |
| 810 | guard let device, let contentBlurPipeline else { throw RenderError(String(localized: "Content blur is unavailable")) } |
| 811 | if blurTexture?.width != target.width || blurTexture?.height != target.height { |
| 812 | blurTexture = makeTarget(device, target.width, target.height, shared: false) |
| 813 | } |
| 814 | guard let horizontal = blurTexture else { throw RenderError(String(localized: "Cannot allocate blur texture")) } |
| 815 | // Radius scales with output size, keeping preview and 4K exports consistent. |
| 816 | let step = min(1, max(0, state.motionBlur)) * Float(min(target.width, target.height)) * 0.003 |
| 817 | for (input, output, direction) in [(target, horizontal, SIMD2<Float>(step / Float(target.width), 0)), |
| 818 | (horizontal, target, SIMD2<Float>(0, step / Float(target.height)))] { |
| 819 | let pass = MTLRenderPassDescriptor(); pass.colorAttachments[0].texture = output |
| 820 | pass.colorAttachments[0].loadAction = .dontCare; pass.colorAttachments[0].storeAction = .store |
| 821 | guard let encoder = command.makeRenderCommandEncoder(descriptor: pass) else { throw RenderError(String(localized: "Could not encode content blur")) } |
| 822 | encoder.setRenderPipelineState(contentBlurPipeline) |
| 823 | encoder.setFragmentTexture(input, index: 0) |
| 824 | var direction = direction |
| 825 | encoder.setFragmentBytes(&direction, length: MemoryLayout<SIMD2<Float>>.stride, index: 0) |
| 826 | encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) |
| 827 | encoder.endEncoding() |
| 828 | } |
| 829 | } |
| 830 | let flash: Float |
| 831 | if state.strobeEnabled && chaosAmount > 0 { |
| 832 | let sourceTime = timelineTime ?? sourceClock |
| 833 | let onset: Float |
| 834 | if let strength = state.audioTreblePulse { |
| 835 | onset = strobeDetector.nextSourceFrame(time: sourceTime, attackTime: state.audioTrebleAttackTime, |
| 836 | strength: strength, sensitivity: state.strobeSensitivity) |
| 837 | } else { onset = strobeDetector.nextFrame(time: sourceTime, bands: state.audioBands, sensitivity: state.strobeSensitivity) } |
| 838 | flash = onset * min(1, max(0, state.strobeStrength)) |
| 839 | } else { strobeDetector.reset(); flash = 0 } |
| 840 | if flash > 0, let strobePipeline { |
| 841 | let overlay = MTLRenderPassDescriptor() |
| 842 | overlay.colorAttachments[0].texture = target |
| 843 | overlay.colorAttachments[0].loadAction = .load |
| 844 | overlay.colorAttachments[0].storeAction = .store |
| 845 | guard let e = command.makeRenderCommandEncoder(descriptor: overlay) else { throw RenderError(String(localized: "Could not encode white flash")) } |
| 846 | e.setRenderPipelineState(strobePipeline) |
| 847 | var strength = flash |
| 848 | e.setFragmentBytes(&strength, length: 4, index: 0) |
| 849 | e.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3) |
| 850 | e.endEncoding() |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | private func drawMesh(_ encoder: MTLRenderCommandEncoder, count: Int) { |
| 855 | guard let indexBuffer else { return } |
| 856 | encoder.drawIndexedPrimitives(type: .triangle, indexCount: count, indexType: .uint32, indexBuffer: indexBuffer, indexBufferOffset: 0) |
| 857 | } |
| 858 | |
| 859 | private func makeTarget(_ device: MTLDevice, _ width: Int, _ height: Int, shared: Bool) -> MTLTexture? { |
| 860 | let t = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false) |
| 861 | t.storageMode = shared ? .shared : .private; t.usage = [.renderTarget, .shaderRead] |
| 862 | return device.makeTexture(descriptor: t) |
| 863 | } |
| 864 | |
| 865 | /// Thin-strip mesh designs shade with averaged mesh normals: screen-derivative normals |
| 866 | /// occasionally shaded their strips differently between identical frames on the GPU. |
| 867 | /// Resonant Shell keeps its deterministic faceted lighting, which smooth normals would change. |
| 868 | private static let smoothShadedScenes: Set<Int> = [15, 16, 17, 20] |
| 869 | |
| 870 | private func meshNormals(_ mesh: OriginalGeometry.Mesh) -> [SIMD3<Float>] { |
| 871 | var normals = [SIMD3<Float>](repeating: .zero, count: mesh.vertices.count) |
| 872 | var index = 0 |
| 873 | while index + 2 < mesh.indices.count { |
| 874 | let a = Int(mesh.indices[index]), b = Int(mesh.indices[index + 1]), c = Int(mesh.indices[index + 2]) |
| 875 | let face = simd_cross(mesh.vertices[b].position - mesh.vertices[a].position, mesh.vertices[c].position - mesh.vertices[a].position) |
| 876 | normals[a] += face; normals[b] += face; normals[c] += face |
| 877 | index += 3 |
| 878 | } |
| 879 | return normals.map { simd_length($0) > 1e-12 ? simd_normalize($0) : SIMD3<Float>(0, 0, 1) } |
| 880 | } |
| 881 | |
| 882 | private func immersive(mesh: OriginalGeometry.Mesh, aspect: Float) -> ([VisualVertex], [UInt32]) { |
| 883 | let normals = Self.smoothShadedScenes.contains(state.scene) ? meshNormals(mesh) : nil |
| 884 | let scale: Float |
| 885 | let step: SIMD2<Float> |
| 886 | switch state.scene { |
| 887 | case 15: scale = 1.4; step = SIMD2(23, 23) |
| 888 | case 16: scale = 1.4; step = SIMD2(22, 22) |
| 889 | case 17: scale = 1.3; step = SIMD2(21, 24) |
| 890 | case 18: scale = 1.5; step = SIMD2(11, 30) |
| 891 | case 19: scale = 1.25; step = SIMD2(14, 24) |
| 892 | case 20: scale = 1.2; step = SIMD2(25.92, 25.92) |
| 893 | default: scale = 1.6; step = SIMD2(19, 23) |
| 894 | } |
| 895 | let c = abs(cos(state.rotation)), s = abs(sin(state.rotation)) |
| 896 | let halfX = canvasHeight * (aspect * c + s) * 0.80 |
| 897 | let halfY = canvasHeight * (aspect * s + c) * 0.80 |
| 898 | let columns = Int(ceil(halfX / step.x)) + 1 |
| 899 | let rows = Int(ceil(halfY / step.y)) + 1 |
| 900 | let drift = SIMD2<Float>(sin(time * 0.22) * step.x * 0.14, cos(time * 0.17) * step.y * 0.12) |
| 901 | var vertices: [VisualVertex] = [], indices: [UInt32] = [] |
| 902 | let capacity = (rows * 2 + 1) * (columns * 2 + 1) |
| 903 | let twist = state.scene == 18 |
| 904 | let brightness = max(0, state.brightness) |
| 905 | vertices.reserveCapacity(mesh.vertices.count * capacity) |
| 906 | indices.reserveCapacity(mesh.indices.count * capacity) |
| 907 | for row in -rows...rows { |
| 908 | for column in -columns...columns { |
| 909 | let center = SIMD2(Float(column) * step.x, Float(row) * step.y) + drift |
| 910 | // Skip instances completely outside the rotated viewport, while |
| 911 | // retaining a full surrounding tile for camera motion and beats. |
| 912 | if abs(center.x) > halfX + step.x * 0.7 || abs(center.y) > halfY + step.y * 0.7 { continue } |
| 913 | let offset = UInt32(vertices.count) |
| 914 | var vertexIndex = 0 |
| 915 | let depthOffset = sin(time * 0.45 + Float(column) * 1.7 + Float(row) * 2.1) * (twist ? 6 : 3) |
| 916 | for v in mesh.vertices { |
| 917 | var position = v.position * scale |
| 918 | position.x += center.x; position.y += center.y |
| 919 | if twist { position.z *= 2.5 } |
| 920 | position.z += depthOffset |
| 921 | var color = v.color * SIMD4<Float>(repeating: brightness) |
| 922 | color.w = 1 |
| 923 | vertices.append(VisualVertex(position: position, color: color, uv: v.uv, normal: normals?[vertexIndex] ?? .zero)) |
| 924 | vertexIndex += 1 |
| 925 | } |
| 926 | indices.append(contentsOf: mesh.indices.map { $0 + offset }) |
| 927 | } |
| 928 | } |
| 929 | if mesh.indices.isEmpty { vertices.sort { $0.position.z < $1.position.z } } |
| 930 | |
| 931 | return (vertices, indices) |
| 932 | } |
| 933 | |
| 934 | private func perspective(fov: Float, aspect: Float, near: Float, far: Float) -> simd_float4x4 { |
| 935 | let y = 1 / tan(fov * 0.5), x = y / max(aspect, 0.01), z = far / (near - far) |
| 936 | return simd_float4x4(columns: (SIMD4<Float>(x, 0, 0, 0), SIMD4<Float>(0, y, 0, 0), SIMD4<Float>(0, 0, z, -1), SIMD4<Float>(0, 0, z * near, 0))) |
| 937 | } |
| 938 | private func rotateX(_ angle: Float) -> simd_float4x4 { |
| 939 | let c = cos(angle), s = sin(angle) |
| 940 | return simd_float4x4(columns: (SIMD4(1,0,0,0), SIMD4(0,c,s,0), SIMD4(0,-s,c,0), SIMD4(0,0,0,1))) |
| 941 | } |
| 942 | private func rotateY(_ angle: Float) -> simd_float4x4 { |
| 943 | let c = cos(angle), s = sin(angle) |
| 944 | return simd_float4x4(columns: (SIMD4(c,0,-s,0), SIMD4(0,1,0,0), SIMD4(s,0,c,0), SIMD4(0,0,0,1))) |
| 945 | } |
| 946 | private func rotateZ(_ angle: Float) -> simd_float4x4 { |
| 947 | let c = cos(angle), s = sin(angle) |
| 948 | return simd_float4x4(columns: (SIMD4<Float>(c, s, 0, 0), SIMD4<Float>(-s, c, 0, 0), SIMD4<Float>(0, 0, 1, 0), SIMD4<Float>(0, 0, 0, 1))) |
| 949 | } |
| 950 | } |
| 951 | |
| 952 | private struct RenderError: LocalizedError { |
| 953 | let text: String |
| 954 | init(_ text: String) { self.text = text } |
| 955 | var errorDescription: String? { text } |
| 956 | } |