Packages/FoldKit/Sources/Renderer/PaperRenderer.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/Packages/FoldKit/Sources/Renderer/PaperRenderer.swift history · blame · raw

209 lines · 10459 bytes

11 symbols in this file
  1import Folding
  2import Foundation
  3import Metal
  4import simd
  5
  6public enum RendererError: Error, Equatable, Sendable {
  7    case shadersMissing
  8    case allocationFailed
  9}
 10
 11/// Draws a render mesh with Metal.
 12///
 13/// Each coplanar cluster is drawn back to front in its order with the depth test on and depth
 14/// writes off, so that its stacked faces resolve by layer order, then drawn again depth-only, so
 15/// that clusters drawn after it are hidden behind it. Faces in different clusters resolve by depth.
 16///
 17/// Facets are two-sided. Unless `faceColours` is given, the side a FOLD face's normal points toward
 18/// is drawn in `frontColour` and the other in `backColour`, shaded by a light along the view
 19/// direction.
 20public final class PaperRenderer {
 21    public static let frontColour = SIMD4<Float>(0.80, 0.22, 0.18, 1)
 22    public static let backColour = SIMD4<Float>(0.96, 0.94, 0.89, 1)
 23    /// The clear colour.
 24    public static let background = SIMD4<Float>(0, 0, 0, 0)
 25    /// The shade of a face seen edge-on; a face square to the view direction has its full colour.
 26    private static let edgeOnShade: Float = 0.35
 27
 28    public let device: MTLDevice
 29    /// The queue `render` commits to. Work committed to it afterwards runs after the frame.
 30    public let commandQueue: MTLCommandQueue
 31    private let vertexFunction: MTLFunction
 32    private let fragmentFunction: MTLFunction
 33    /// Depth test on, writes off: a cluster's colour pass.
 34    private let colourPass: MTLDepthStencilState
 35    /// Depth test and writes on: a cluster's depth pass.
 36    private let depthPass: MTLDepthStencilState
 37    /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only.
 38    private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:]
 39    private var depthTexture: MTLTexture?
 40    /// The vertex buffer, reused while it is large enough.
 41    private var vertexBuffer: MTLBuffer?
 42    /// The last frame's commands, which read `vertexBuffer`.
 43    private var lastFrame: MTLCommandBuffer?
 44
 45    private struct PaperVertex {
 46        var position: SIMD3<Float>
 47        var normal: SIMD3<Float>
 48    }
 49
 50    private struct Shading {
 51        var front: SIMD4<Float>
 52        var back: SIMD4<Float>
 53        var light: SIMD4<Float>
 54    }
 55
 56    public init(device: MTLDevice) throws {
 57        guard let url = Bundle.module.url(forResource: "Shaders", withExtension: "metal") else {
 58            throw RendererError.shadersMissing
 59        }
 60        let library = try device.makeLibrary(source: String(contentsOf: url, encoding: .utf8), options: nil)
 61        guard let vertexFunction = library.makeFunction(name: "paperVertex"),
 62              let fragmentFunction = library.makeFunction(name: "paperFragment") else {
 63            throw RendererError.shadersMissing
 64        }
 65        let depth = MTLDepthStencilDescriptor()
 66        depth.depthCompareFunction = .lessEqual
 67        depth.isDepthWriteEnabled = false
 68        let colourPass = device.makeDepthStencilState(descriptor: depth)
 69        depth.isDepthWriteEnabled = true
 70        guard let queue = device.makeCommandQueue(), let colourPass,
 71              let depthPass = device.makeDepthStencilState(descriptor: depth) else {
 72            throw RendererError.allocationFailed
 73        }
 74        self.device = device
 75        commandQueue = queue
 76        self.vertexFunction = vertexFunction
 77        self.fragmentFunction = fragmentFunction
 78        self.colourPass = colourPass
 79        self.depthPass = depthPass
 80    }
 81
 82    /// Draws `mesh` with its vertices at `positions` into `target`, cleared to `background`.
 83    /// Faces in no cluster are not drawn. `faceColours`, when given, draws FOLD face i in
 84    /// `faceColours[i]`, unlit, on both sides. Waits for the previous frame to finish, since it
 85    /// reuses that frame's vertex buffer, then commits to `commandQueue` without waiting for this one.
 86    public func render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera,
 87                       faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws {
 88        let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh)
 89        let pipeline = try pipelines(for: target.pixelFormat)
 90        guard let buffer = vertexBuffer(holding: vertices),
 91              let depth = depthTexture(width: target.width, height: target.height),
 92              let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed }
 93
 94        let pass = MTLRenderPassDescriptor()
 95        let b = Self.background
 96        pass.colorAttachments[0].texture = target
 97        pass.colorAttachments[0].loadAction = .clear
 98        pass.colorAttachments[0].clearColor = MTLClearColor(red: Double(b.x), green: Double(b.y),
 99                                                            blue: Double(b.z), alpha: Double(b.w))
100        pass.colorAttachments[0].storeAction = .store
101        pass.depthAttachment.texture = depth
102        pass.depthAttachment.loadAction = .clear
103        pass.depthAttachment.clearDepth = 1
104        pass.depthAttachment.storeAction = .dontCare
105        guard let encoder = commands.makeRenderCommandEncoder(descriptor: pass) else {
106            throw RendererError.allocationFailed
107        }
108
109        let d = SIMD3<Float>(camera.viewDirection)
110        let lit = Shading(front: Self.frontColour, back: Self.backColour, light: SIMD4(d, Self.edgeOnShade))
111        let vp = camera.viewProjection(aspect: Double(target.width) / Double(target.height))
112        var viewProjection = simd_float4x4(columns: (SIMD4<Float>(vp.columns.0), SIMD4<Float>(vp.columns.1),
113                                                     SIMD4<Float>(vp.columns.2), SIMD4<Float>(vp.columns.3)))
114        encoder.setFrontFacing(.counterClockwise)
115        encoder.setCullMode(.none)
116        encoder.setVertexBuffer(buffer, offset: 0, index: 0)
117        encoder.setVertexBytes(&viewProjection, length: MemoryLayout<simd_float4x4>.stride, index: 1)
118        func draw(_ face: Int) {
119            guard ranges.indices.contains(face), !ranges[face].isEmpty else { return }
120            encoder.drawPrimitives(type: .triangle, vertexStart: ranges[face].lowerBound,
121                                   vertexCount: ranges[face].count)
122        }
123        func setShading(_ shading: Shading) {
124            var shading = shading
125            encoder.setFragmentBytes(&shading, length: MemoryLayout<Shading>.stride, index: 0)
126        }
127        if faceColours == nil { setShading(lit) }
128
129        for cluster in clusters {
130            encoder.setRenderPipelineState(pipeline.colour)
131            encoder.setDepthStencilState(colourPass)
132            for face in cluster.faces {
133                if let colour = faceColours?[face] {
134                    setShading(Shading(front: colour, back: colour, light: SIMD4(d, 1)))
135                }
136                draw(face)
137            }
138            encoder.setRenderPipelineState(pipeline.depth)
139            encoder.setDepthStencilState(depthPass)
140            for face in cluster.faces { draw(face) }
141        }
142        encoder.endEncoding()
143        commands.commit()
144        lastFrame = commands
145    }
146
147    /// `vertexBuffer` filled with `vertices`, after the last frame has finished reading it; a new
148    /// one when it is too small.
149    private func vertexBuffer(holding vertices: [PaperVertex]) -> MTLBuffer? {
150        let length = vertices.count * MemoryLayout<PaperVertex>.stride
151        lastFrame?.waitUntilCompleted()
152        if (vertexBuffer?.length ?? 0) < length {
153            vertexBuffer = device.makeBuffer(length: length, options: .storageModeShared)
154        }
155        guard let vertexBuffer else { return nil }
156        memcpy(vertexBuffer.contents(), vertices, length)
157        return vertexBuffer
158    }
159
160    /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and
161    /// each FOLD face's range in them.
162    private func groupedVertices(positions: [SIMD3<Double>], mesh: RenderMesh) -> ([PaperVertex], [Range<Int>]) {
163        let faceCount = (mesh.faceOf.max() ?? -1) + 1
164        var start = Array(repeating: 0, count: faceCount + 1)
165        for f in mesh.faceOf { start[f + 1] += 3 }
166        for f in 0..<faceCount { start[f + 1] += start[f] }
167        var next = start
168        var vertices = Array(repeating: PaperVertex(position: .zero, normal: .zero), count: 3 * mesh.triangles.count)
169        for (t, (a, b, c)) in mesh.triangles.enumerated() {
170            let n = cross(positions[b] - positions[a], positions[c] - positions[a])
171            let normal = SIMD3<Float>(length(n) > 0 ? normalize(n) : .zero)
172            let f = mesh.faceOf[t]
173            for v in [a, b, c] {
174                vertices[next[f]] = PaperVertex(position: SIMD3<Float>(positions[v]), normal: normal)
175                next[f] += 1
176            }
177        }
178        return (vertices, (0..<faceCount).map { start[$0]..<start[$0 + 1] })
179    }
180
181    private func pipelines(for format: MTLPixelFormat) throws -> (colour: MTLRenderPipelineState,
182                                                                  depth: MTLRenderPipelineState) {
183        if let cached = pipelines[format] { return cached }
184        let descriptor = MTLRenderPipelineDescriptor()
185        descriptor.vertexFunction = vertexFunction
186        descriptor.fragmentFunction = fragmentFunction
187        descriptor.colorAttachments[0].pixelFormat = format
188        descriptor.depthAttachmentPixelFormat = .depth32Float
189        let colour = try device.makeRenderPipelineState(descriptor: descriptor)
190        descriptor.colorAttachments[0].writeMask = []
191        let depth = try device.makeRenderPipelineState(descriptor: descriptor)
192        pipelines[format] = (colour, depth)
193        return (colour, depth)
194    }
195
196    private func depthTexture(width: Int, height: Int) -> MTLTexture? {
197        if let depthTexture, depthTexture.width == width, depthTexture.height == height { return depthTexture }
198        let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width,
199                                                                  height: height, mipmapped: false)
200        descriptor.usage = .renderTarget
201        #if os(iOS)
202        descriptor.storageMode = .memoryless
203        #else
204        descriptor.storageMode = .private
205        #endif
206        depthTexture = device.makeTexture(descriptor: descriptor)
207        return depthTexture
208    }
209}