PulseCanvas / app · pulsecanvas.ai / scripts / RendererReuseSmoke.swift
| 1 | import AppKit |
| 2 | import MetalKit |
| 3 | import Foundation |
| 4 | |
| 5 | @main struct RendererReuseSmoke { |
| 6 | @MainActor static func main() throws { |
| 7 | _ = NSApplication.shared |
| 8 | func pixels(_ texture: MTLTexture) -> [UInt8] { |
| 9 | var result = [UInt8](repeating: 0, count: texture.width * texture.height * 4) |
| 10 | result.withUnsafeMutableBytes { |
| 11 | texture.getBytes($0.baseAddress!, bytesPerRow: texture.width * 4, |
| 12 | from: MTLRegionMake2D(0, 0, texture.width, texture.height), mipmapLevel: 0) |
| 13 | } |
| 14 | return result |
| 15 | } |
| 16 | let state = RenderState(), first = VisualizerRenderer(state: RenderState()) |
| 17 | first.state = state |
| 18 | let cold = Date() |
| 19 | try first.prepareOffscreen(width: 160, height: 100) |
| 20 | let coldTime = Date().timeIntervalSince(cold) |
| 21 | let builds = VisualizerRenderer.shaderResourceBuilds |
| 22 | precondition(builds == 1) |
| 23 | let ids = NativeEffects.activeIDs |
| 24 | let scenes = Array(ids.prefix(3)) + [ids[ids.count / 2]] + Array(ids.suffix(3)) |
| 25 | let bands = (0..<32).map { Float($0 % 8) / 10 } |
| 26 | var reference: [[UInt8]] = [] |
| 27 | for scene in scenes { |
| 28 | state.scene = scene; state.motionBlur = 0.4 |
| 29 | reference.append(pixels(try first.renderOffscreen(time: 4.2, audioBands: bands))) |
| 30 | } |
| 31 | var warmTimes: [Double] = [] |
| 32 | for _ in 0..<4 { |
| 33 | let nextState = RenderState(), next = VisualizerRenderer(state: nextState) |
| 34 | let warm = Date() |
| 35 | try next.prepareOffscreen(width: 160, height: 100) |
| 36 | warmTimes.append(Date().timeIntervalSince(warm)) |
| 37 | precondition(VisualizerRenderer.shaderResourceBuilds == builds, "Preview recreation recompiled shader resources") |
| 38 | for (index, scene) in scenes.enumerated() { |
| 39 | nextState.scene = scene; nextState.motionBlur = 0.4 |
| 40 | let result = pixels(try next.renderOffscreen(time: 4.2, audioBands: bands)) |
| 41 | precondition(result == reference[index], "Shared programs changed frame contents for scene \(scene)") |
| 42 | precondition(nextState.errorMessage == nil) |
| 43 | } |
| 44 | } |
| 45 | print("PASS: four preview recreations reuse compiled programs; 28 GPU frames match exactly with isolated render targets") |
| 46 | print("Cold attach: \(coldTime) s; warm attach: \(warmTimes) s") |
| 47 | } |
| 48 | } |