Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / BlurSmoke.swift

Raw 5.3 KB on 0e4fe45e403a1b6b5a57aa68addd681995d37722
1import AppKit
2import MetalKit
3import Foundation
4
5@main struct BlurSmoke {
6 @MainActor static func main() throws {
7 _ = NSApplication.shared
8 let device = MTLCreateSystemDefaultDevice()!, queue = device.makeCommandQueue()!
9 let source = try String(contentsOfFile: "Sources/PulseCanvas/Resources/Strobe.metal", encoding: .utf8)
10 let library = try device.makeLibrary(source: source, options: nil)
11 let descriptor = MTLRenderPipelineDescriptor()
12 descriptor.vertexFunction = library.makeFunction(name: "whiteFlashVertex")
13 descriptor.fragmentFunction = library.makeFunction(name: "contentBlurFragment")
14 descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
15 let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
16 let width = 512, height = 256
17 func texture() -> MTLTexture {
18 let d = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false)
19 d.storageMode = .shared; d.usage = [.shaderRead, .renderTarget]
20 return device.makeTexture(descriptor: d)!
21 }
22 func soften(_ bytes: [UInt8]) -> [UInt8] {
23 let input = texture(), horizontal = texture(), output = texture()
24 bytes.withUnsafeBytes { input.replace(region: MTLRegionMake2D(0,0,width,height), mipmapLevel: 0, withBytes: $0.baseAddress!, bytesPerRow: width * 4) }
25 let command = queue.makeCommandBuffer()!
26 for (src, dst, offset) in [(input, horizontal, SIMD2<Float>(1 / Float(width), 0)), (horizontal, output, SIMD2<Float>(0, 1 / Float(height)))] {
27 let pass = MTLRenderPassDescriptor(); pass.colorAttachments[0].texture = dst
28 pass.colorAttachments[0].loadAction = .dontCare; pass.colorAttachments[0].storeAction = .store
29 let encoder = command.makeRenderCommandEncoder(descriptor: pass)!
30 encoder.setRenderPipelineState(pipeline); encoder.setFragmentTexture(src, index: 0)
31 var offset = offset
32 encoder.setFragmentBytes(&offset, length: MemoryLayout<SIMD2<Float>>.stride, index: 0)
33 encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3); encoder.endEncoding()
34 }
35 command.commit(); command.waitUntilCompleted(); precondition(command.status == .completed)
36 var result = [UInt8](repeating: 0, count: bytes.count)
37 result.withUnsafeMutableBytes { output.getBytes($0.baseAddress!, bytesPerRow: width * 4, from: MTLRegionMake2D(0,0,width,height), mipmapLevel: 0) }
38 return result
39 }
40 var impulses = [UInt8](repeating: 0, count: width * height * 4)
41 let points = [(256,128), (20,20), (491,235)]
42 for (x,y) in points { for c in 0..<3 { impulses[(y * width + x) * 4 + c] = 255 } }
43 let blurred = soften(impulses)
44 for (x,y) in points.dropFirst() {
45 for dy in -6...6 { for dx in -6...6 {
46 precondition(blurred[((y+dy)*width+x+dx)*4] == blurred[((128+dy)*width+256+dx)*4], "Blur cannot grow or smear toward canvas edges")
47 } }
48 }
49 precondition(blurred[(128*width+256)*4] < 255 && blurred[(128*width+257)*4] > 0)
50 var solid = [UInt8](repeating: 0, count: impulses.count)
51 for i in stride(from: 0, to: solid.count, by: 4) { solid[i] = 40; solid[i+1] = 100; solid[i+2] = 180; solid[i+3] = 255 }
52 precondition(soften(solid) == solid, "Solid color must stay unchanged at all borders")
53 // A bright left edge must never wrap onto the dark right edge.
54 var border = [UInt8](repeating: 0, count: impulses.count)
55 for y in 0..<height { for c in 0..<3 { border[y*width*4+c] = 255 } }
56 let edge = soften(border)
57 for y in 0..<height { precondition(edge[(y*width+width-1)*4] == 0) }
58 print("PASS: Gaussian kernel identical at centre and near all borders, solid colors preserved, no opposite-edge wrapping")
59
60 let state = RenderState(), renderer = VisualizerRenderer(state: state)
61 let w = 640, h = 360
62 try renderer.prepareOffscreen(width: w, height: h)
63 state.zoomSpeed = 0
64 func frame() throws -> [UInt8] {
65 let t = try renderer.renderOffscreen(time: 2.3, audioBands: Array(repeating: 0, count: 32))
66 var b = [UInt8](repeating: 0, count: w*h*4)
67 b.withUnsafeMutableBytes { t.getBytes($0.baseAddress!, bytesPerRow: w*4, from: MTLRegionMake2D(0,0,w,h), mipmapLevel: 0) }
68 return b
69 }
70 for scene in NativeEffects.activeIDs {
71 state.scene = scene; state.motionBlur = 0
72 let sharp = try frame()
73 state.motionBlur = 0.9
74 let soft = try frame(), repeatSoft = try frame()
75 let difference = zip(sharp,soft).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(sharp.count)
76 precondition(difference > 0.05 && soft == repeatSoft, "Softness must visibly and deterministically affect every visualizer")
77 state.motionBlur = 0
78 let restored = try frame()
79 precondition(sharp == restored, "Zero blur must restore exact sharp frame")
80 print("PASS: \(RenderState.sceneNames[scene]) whole-image blur changes GPU pixels, deterministic, zero restores exact frame")
81 }
82 }
83}