Commit 33b63482b3

33b63482b32872ca98ffcad0ac66ce10b2ae4f1e

parent: d1caa68b31

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-20 04:36 UTC

Metal paper renderer with hybrid depth and cluster ordering

Ref #5

Layout: unified · split

Packages/FoldKit/Package.swift +3
@@ -10,6 +10,7 @@ let package = Package(
10 .library(name: "FoldCompiler", targets: ["FoldCompiler"]), 10 .library(name: "FoldCompiler", targets: ["FoldCompiler"]),
11 .library(name: "Models", targets: ["Models"]), 11 .library(name: "Models", targets: ["Models"]),
12 .library(name: "Notation", targets: ["Notation"]), 12 .library(name: "Notation", targets: ["Notation"]),
13 .library(name: "Renderer", targets: ["Renderer"]),
13 .executable(name: "foldc", targets: ["foldc"]), 14 .executable(name: "foldc", targets: ["foldc"]),
14 .executable(name: "foldlint", targets: ["foldlint"]), 15 .executable(name: "foldlint", targets: ["foldlint"]),
15 ], 16 ],
@@ -19,6 +20,7 @@ let package = Package(
19 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), 20 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]),
20 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]), 21 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]),
21 .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]), 22 .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]),
23 .target(name: "Renderer", dependencies: ["Folding"], resources: [.copy("Shaders.metal")]),
22 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), 24 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]),
23 .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]), 25 .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]),
24 .target( 26 .target(
@@ -35,6 +37,7 @@ let package = Package(
35 .testTarget(name: "NotationTests", 37 .testTarget(name: "NotationTests",
36 dependencies: ["Notation", "Models", "Folding", "FoldFormat", "FoldKitTestSupport"], 38 dependencies: ["Notation", "Models", "Folding", "FoldFormat", "FoldKitTestSupport"],
37 resources: [.copy("Snapshots")]), 39 resources: [.copy("Snapshots")]),
40 .testTarget(name: "RendererTests", dependencies: ["Renderer", "Folding", "FoldFormat"]),
38 ], 41 ],
39 swiftLanguageModes: [.v6] 42 swiftLanguageModes: [.v6]
40) 43)
Packages/FoldKit/Sources/Folding/Camera.swift added +46
@@ -0,0 +1,46 @@
1import simd
2
3/// A perspective camera at `eye` looking at `target`. `fieldOfView` is vertical, in radians.
4public struct Camera: Sendable {
5 public var eye: SIMD3<Double>
6 public var target: SIMD3<Double>
7 public var up: SIMD3<Double>
8 public var fieldOfView: Double
9
10 public init(eye: SIMD3<Double>, target: SIMD3<Double>, up: SIMD3<Double>, fieldOfView: Double) {
11 self.eye = eye
12 self.target = target
13 self.up = up
14 self.fieldOfView = fieldOfView
15 }
16
17 /// The unit vector from `eye` toward `target`.
18 public var viewDirection: SIMD3<Double> {
19 let d = target - eye
20 return d / length(d)
21 }
22
23 /// World to clip space, Metal's: depth 0 at the near plane and 1 at the far plane, which are
24 /// 1/100 and 100 times the distance from `eye` to `target`.
25 public func viewProjection(aspect: Double) -> simd_double4x4 {
26 let f = viewDirection
27 let s = normalize(cross(f, up))
28 let u = cross(s, f)
29 let view = simd_double4x4(rows: [
30 SIMD4(s.x, s.y, s.z, -dot(s, eye)),
31 SIMD4(u.x, u.y, u.z, -dot(u, eye)),
32 SIMD4(-f.x, -f.y, -f.z, dot(f, eye)),
33 SIMD4(0, 0, 0, 1),
34 ])
35 let distance = length(target - eye)
36 let near = distance / 100, far = distance * 100
37 let y = 1 / tan(fieldOfView / 2), z = far / (near - far)
38 let projection = simd_double4x4(columns: (
39 SIMD4(y / aspect, 0, 0, 0),
40 SIMD4(0, y, 0, 0),
41 SIMD4(0, 0, z, -1),
42 SIMD4(0, 0, z * near, 0)
43 ))
44 return projection * view
45 }
46}
Packages/FoldKit/Sources/Renderer/PaperRenderer.swift added +186
@@ -0,0 +1,186 @@
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
41 private struct PaperVertex {
42 var position: SIMD3<Float>
43 var normal: SIMD3<Float>
44 }
45
46 private struct Shading {
47 var front: SIMD4<Float>
48 var back: SIMD4<Float>
49 var light: SIMD4<Float>
50 }
51
52 public init(device: MTLDevice) throws {
53 guard let url = Bundle.module.url(forResource: "Shaders", withExtension: "metal") else {
54 throw RendererError.shadersMissing
55 }
56 let library = try device.makeLibrary(source: String(contentsOf: url, encoding: .utf8), options: nil)
57 guard let vertexFunction = library.makeFunction(name: "paperVertex"),
58 let fragmentFunction = library.makeFunction(name: "paperFragment") else {
59 throw RendererError.shadersMissing
60 }
61 let depth = MTLDepthStencilDescriptor()
62 depth.depthCompareFunction = .lessEqual
63 depth.isDepthWriteEnabled = false
64 let colourPass = device.makeDepthStencilState(descriptor: depth)
65 depth.isDepthWriteEnabled = true
66 guard let queue = device.makeCommandQueue(), let colourPass,
67 let depthPass = device.makeDepthStencilState(descriptor: depth) else {
68 throw RendererError.allocationFailed
69 }
70 self.device = device
71 commandQueue = queue
72 self.vertexFunction = vertexFunction
73 self.fragmentFunction = fragmentFunction
74 self.colourPass = colourPass
75 self.depthPass = depthPass
76 }
77
78 /// Draws `mesh` with its vertices at `positions` into `target`, cleared to `background`.
79 /// Faces in no cluster are not drawn. `faceColours`, when given, draws FOLD face i in
80 /// `faceColours[i]`, unlit, on both sides. Commits to `commandQueue` without waiting.
81 public func render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera,
82 faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws {
83 let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh)
84 let pipeline = try pipelines(for: target.pixelFormat)
85 guard let buffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<PaperVertex>.stride),
86 let depth = depthTexture(width: target.width, height: target.height),
87 let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed }
88
89 let pass = MTLRenderPassDescriptor()
90 let b = Self.background
91 pass.colorAttachments[0].texture = target
92 pass.colorAttachments[0].loadAction = .clear
93 pass.colorAttachments[0].clearColor = MTLClearColor(red: Double(b.x), green: Double(b.y),
94 blue: Double(b.z), alpha: Double(b.w))
95 pass.colorAttachments[0].storeAction = .store
96 pass.depthAttachment.texture = depth
97 pass.depthAttachment.loadAction = .clear
98 pass.depthAttachment.clearDepth = 1
99 pass.depthAttachment.storeAction = .dontCare
100 guard let encoder = commands.makeRenderCommandEncoder(descriptor: pass) else {
101 throw RendererError.allocationFailed
102 }
103
104 let d = SIMD3<Float>(camera.viewDirection)
105 let lit = Shading(front: Self.frontColour, back: Self.backColour, light: SIMD4(d, Self.edgeOnShade))
106 let vp = camera.viewProjection(aspect: Double(target.width) / Double(target.height))
107 var viewProjection = simd_float4x4(columns: (SIMD4<Float>(vp.columns.0), SIMD4<Float>(vp.columns.1),
108 SIMD4<Float>(vp.columns.2), SIMD4<Float>(vp.columns.3)))
109 encoder.setFrontFacing(.counterClockwise)
110 encoder.setCullMode(.none)
111 encoder.setVertexBuffer(buffer, offset: 0, index: 0)
112 encoder.setVertexBytes(&viewProjection, length: MemoryLayout<simd_float4x4>.stride, index: 1)
113 func draw(_ face: Int) {
114 guard ranges.indices.contains(face), !ranges[face].isEmpty else { return }
115 encoder.drawPrimitives(type: .triangle, vertexStart: ranges[face].lowerBound,
116 vertexCount: ranges[face].count)
117 }
118 func setShading(_ shading: Shading) {
119 var shading = shading
120 encoder.setFragmentBytes(&shading, length: MemoryLayout<Shading>.stride, index: 0)
121 }
122 if faceColours == nil { setShading(lit) }
123
124 for cluster in clusters {
125 encoder.setRenderPipelineState(pipeline.colour)
126 encoder.setDepthStencilState(colourPass)
127 for face in cluster.faces {
128 if let colour = faceColours?[face] {
129 setShading(Shading(front: colour, back: colour, light: SIMD4(d, 1)))
130 }
131 draw(face)
132 }
133 encoder.setRenderPipelineState(pipeline.depth)
134 encoder.setDepthStencilState(depthPass)
135 for face in cluster.faces { draw(face) }
136 }
137 encoder.endEncoding()
138 commands.commit()
139 }
140
141 /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and
142 /// each FOLD face's range in them.
143 private func groupedVertices(positions: [SIMD3<Double>], mesh: RenderMesh) -> ([PaperVertex], [Range<Int>]) {
144 let faceCount = (mesh.faceOf.max() ?? -1) + 1
145 var start = Array(repeating: 0, count: faceCount + 1)
146 for f in mesh.faceOf { start[f + 1] += 3 }
147 for f in 0..<faceCount { start[f + 1] += start[f] }
148 var next = start
149 var vertices = Array(repeating: PaperVertex(position: .zero, normal: .zero), count: 3 * mesh.triangles.count)
150 for (t, (a, b, c)) in mesh.triangles.enumerated() {
151 let n = cross(positions[b] - positions[a], positions[c] - positions[a])
152 let normal = SIMD3<Float>(length(n) > 0 ? normalize(n) : .zero)
153 let f = mesh.faceOf[t]
154 for v in [a, b, c] {
155 vertices[next[f]] = PaperVertex(position: SIMD3<Float>(positions[v]), normal: normal)
156 next[f] += 1
157 }
158 }
159 return (vertices, (0..<faceCount).map { start[$0]..<start[$0 + 1] })
160 }
161
162 private func pipelines(for format: MTLPixelFormat) throws -> (colour: MTLRenderPipelineState,
163 depth: MTLRenderPipelineState) {
164 if let cached = pipelines[format] { return cached }
165 let descriptor = MTLRenderPipelineDescriptor()
166 descriptor.vertexFunction = vertexFunction
167 descriptor.fragmentFunction = fragmentFunction
168 descriptor.colorAttachments[0].pixelFormat = format
169 descriptor.depthAttachmentPixelFormat = .depth32Float
170 let colour = try device.makeRenderPipelineState(descriptor: descriptor)
171 descriptor.colorAttachments[0].writeMask = []
172 let depth = try device.makeRenderPipelineState(descriptor: descriptor)
173 pipelines[format] = (colour, depth)
174 return (colour, depth)
175 }
176
177 private func depthTexture(width: Int, height: Int) -> MTLTexture? {
178 if let depthTexture, depthTexture.width == width, depthTexture.height == height { return depthTexture }
179 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width,
180 height: height, mipmapped: false)
181 descriptor.usage = .renderTarget
182 descriptor.storageMode = .private
183 depthTexture = device.makeTexture(descriptor: descriptor)
184 return depthTexture
185 }
186}
Packages/FoldKit/Sources/Renderer/Shaders.metal added +37
@@ -0,0 +1,37 @@
1#include <metal_stdlib>
2using namespace metal;
3
4struct PaperVertex {
5 float3 position;
6 float3 normal;
7};
8
9/// `light.xyz` is the view direction, `light.w` the shade of a face seen edge-on.
10struct Shading {
11 float4 front;
12 float4 back;
13 float4 light;
14};
15
16struct Fragment {
17 float4 position [[position]];
18 float3 normal [[flat]];
19};
20
21vertex Fragment paperVertex(uint id [[vertex_id]],
22 const device PaperVertex *vertices [[buffer(0)]],
23 constant float4x4 &viewProjection [[buffer(1)]]) {
24 Fragment out;
25 out.position = viewProjection * float4(vertices[id].position, 1);
26 out.normal = vertices[id].normal;
27 return out;
28}
29
30fragment float4 paperFragment(Fragment in [[stage_in]],
31 bool front [[front_facing]],
32 constant Shading &shading [[buffer(0)]]) {
33 float facing = abs(dot(in.normal, shading.light.xyz));
34 float shade = 1 - (1 - shading.light.w) * (1 - facing);
35 float4 colour = front ? shading.front : shading.back;
36 return float4(colour.rgb * shade, colour.a);
37}
Packages/FoldKit/Tests/FoldingTests/CameraTests.swift added +10
@@ -0,0 +1,10 @@
1import Testing
2import simd
3import Folding
4
5@Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() {
6 let c = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
7 let p = c.viewProjection(aspect: 1.5) * SIMD4(0, 0, 0, 1)
8 #expect(abs(p.x / p.w) < 1e-12 && abs(p.y / p.w) < 1e-12)
9 #expect(c.viewDirection == SIMD3(0, 0, -1))
10}
Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift added +69
@@ -0,0 +1,69 @@
1import Metal
2import Testing
3import Folding
4import Renderer
5
6@Suite(.enabled(if: MTLCreateSystemDefaultDevice() != nil, "needs a Metal device"))
7struct PaperRendererTests {
8 @Test func coplanarStackedFacesDoNotZFight() throws {
9 let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [1, 0])],
10 camera: cameraAbove(), faceColours: [red, green])
11 #expect(uniqueColours(pixels) == [red])
12 }
13
14 @Test func clusterOrderDeterminesWhichCoplanarFaceIsVisible() throws {
15 let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [0, 1])],
16 camera: cameraAbove(), faceColours: [red, green])
17 #expect(uniqueColours(pixels) == [green])
18 }
19
20 @Test func nearlyCoplanarFacesDoNotZFight() throws {
21 // face 0 tilted 1° about its left edge, resting on face 1, in one cluster
22 let pixels = try renderToPixels(squareOverATiltedSquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])],
23 camera: cameraAbove(), faceColours: [red, green])
24 #expect(uniqueColours(pixels) == [red])
25 }
26
27 @Test func withinAClusterOrderWinsOverDepth() throws {
28 // face 0 crosses face 1 at 1°, half of it behind; ordered above it
29 let pixels = try renderToPixels(squareCrossingASquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])],
30 camera: cameraAbove(), faceColours: [red, green])
31 #expect(uniqueColours(pixels) == [red])
32 }
33
34 @Test func facesSeparatedInSpaceAreResolvedByDepthNotByOrder() throws {
35 // face 0 is nearer the camera but drawn first
36 let pixels = try renderToPixels(separatedSquares(),
37 clusters: [CoplanarCluster(faces: [0]), CoplanarCluster(faces: [1])],
38 camera: cameraAbove(), faceColours: [red, green])
39 #expect(dominantColour(pixels) == red)
40 }
41
42 @Test func aStackDrawnFirstStillHidesAFaceBehindItDrawnLater() throws {
43 // faces 0 and 1 stacked near the camera, face 2 farther away and drawn last
44 let pixels = try renderToPixels(nearStackAndFarSquare(),
45 clusters: [CoplanarCluster(faces: [1, 0]), CoplanarCluster(faces: [2])],
46 camera: cameraAbove(), faceColours: [red, green, blue])
47 #expect(dominantColour(pixels) == red)
48 }
49
50 @Test func orbitingUnderneathShowsTheBottomOfTheStack() throws {
51 // clusters computed by Task 5 for each camera, as the app does
52 let above = try renderStackWithComputedClusters(camera: cameraAbove(), faceColours: [red, green])
53 let below = try renderStackWithComputedClusters(camera: cameraBelow(), faceColours: [red, green])
54 #expect(uniqueColours(above) == [red])
55 #expect(uniqueColours(below) == [green])
56 }
57
58 @Test func backOfPaperRendersInTheBackColour() throws {
59 let pixels = try renderToPixels(singleSquareFacingAway(), clusters: [CoplanarCluster(faces: [0])],
60 camera: cameraAbove())
61 #expect(uniqueColours(pixels) == [backColour])
62 }
63
64 @Test func frontOfPaperRendersInTheFrontColour() throws {
65 let pixels = try renderToPixels(singleSquareFacingTheCamera(), clusters: [CoplanarCluster(faces: [0])],
66 camera: cameraAbove())
67 #expect(uniqueColours(pixels) == [frontColour])
68 }
69}
Packages/FoldKit/Tests/RendererTests/Scenes.swift added +144
@@ -0,0 +1,144 @@
1import Metal
2import Testing
3import simd
4import FoldFormat
5import Folding
6import Renderer
7
8let red = SIMD4<Float>(1, 0, 0, 1)
9let green = SIMD4<Float>(0, 1, 0, 1)
10let blue = SIMD4<Float>(0, 0, 1, 1)
11let frontColour = PaperRenderer.frontColour
12let backColour = PaperRenderer.backColour
13
14/// Faces placed in space, with the render mesh of a frame 0 that lays the same faces apart in its
15/// plane, so that no mesh vertex is shared between faces.
16struct Scene {
17 let positions: [SIMD3<Double>]
18 let faces: [[Int]]
19 let normals: [SIMD3<Double>]
20 let mesh: RenderMesh
21
22 /// Unit squares, each given by where its corners (0, 0), (1, 0), (1, 1) and (0, 1) are.
23 init(squares: [[SIMD3<Double>]]) {
24 positions = squares.flatMap { $0 }
25 faces = squares.indices.map { i in (0..<4).map { 4 * i + $0 } }
26 normals = faceNormals(positions: positions, faces: faces)
27 // square i at x = 2i in frame 0; a spacing wider than the sheet leaves each square two triangles
28 let flat = squares.indices.flatMap { i -> [SIMD3<Double>] in
29 let x = 2 * Double(i)
30 return [SIMD3(x, 0, 0), SIMD3(x + 1, 0, 0), SIMD3(x + 1, 1, 0), SIMD3(x, 1, 0)]
31 }
32 let file = FoldFile(fileSpec: 1.2, fileAuthor: "Traditional", edgesVertices: [], facesVertices: faces,
33 edgesFirstCreasedAtStep: [],
34 frames: [FoldFrame(verticesCoords: flat, edgesAssignment: [], edgesFoldAngle: [],
35 faceOrders: [])])
36 mesh = RenderMesh(file: file, spacing: 2 * Double(squares.count))
37 precondition(mesh.vertices.count == positions.count)
38 }
39
40 var meshPositions: [SIMD3<Double>] {
41 var result = positions
42 for (v, m) in mesh.meshVertexOf.enumerated() { result[m] = positions[v] }
43 return result
44 }
45}
46
47private func unitSquare(z: Double) -> [SIMD3<Double>] {
48 [SIMD3(0, 0, z), SIMD3(1, 0, z), SIMD3(1, 1, z), SIMD3(0, 1, z)]
49}
50
51/// Two coincident unit squares facing +z; with `[[0, 1, 1]]` face 0 is above face 1.
52func stackedCoplanarSquares() -> Scene { Scene(squares: [unitSquare(z: 0), unitSquare(z: 0)]) }
53
54/// Face 0 turned `degrees` up about its left edge, x = 0, off face 1 at z = 0.
55func squareOverATiltedSquare(degrees: Double) -> Scene {
56 let c = cos(degrees * .pi / 180), s = sin(degrees * .pi / 180)
57 return Scene(squares: [[SIMD3(0, 0, 0), SIMD3(c, 0, s), SIMD3(c, 1, s), SIMD3(0, 1, 0)], unitSquare(z: 0)])
58}
59
60/// Face 0 at z = 1, face 1 at z = 0.
61func separatedSquares() -> Scene { Scene(squares: [unitSquare(z: 1), unitSquare(z: 0)]) }
62
63/// Faces 0 and 1 at z = 1, face 2 at z = 0.
64func nearStackAndFarSquare() -> Scene {
65 Scene(squares: [unitSquare(z: 1), unitSquare(z: 1), unitSquare(z: 0)])
66}
67
68/// A unit square at z = 0 facing +z.
69func singleSquareFacingTheCamera() -> Scene { Scene(squares: [unitSquare(z: 0)]) }
70
71/// A unit square at z = 0 turned over about x = 0.5, so it faces −z.
72func singleSquareFacingAway() -> Scene {
73 Scene(squares: [[SIMD3(1, 0, 0), SIMD3(0, 0, 0), SIMD3(0, 1, 0), SIMD3(1, 1, 0)]])
74}
75
76func cameraAbove() -> Camera {
77 Camera(eye: SIMD3(0.5, 0.5, 4), target: SIMD3(0.5, 0.5, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
78}
79
80func cameraBelow() -> Camera {
81 Camera(eye: SIMD3(0.5, 0.5, -4), target: SIMD3(0.5, 0.5, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4)
82}
83
84/// Width and height of the offscreen target, in pixels.
85private let size = 64
86
87/// `scene` rendered into a `size` × `size` `rgba32Float` texture, row by row from the top. Without
88/// `clusters`, they are computed with no layer order.
89func renderToPixels(_ scene: Scene, clusters: [CoplanarCluster]? = nil, camera: Camera,
90 faceColours: [SIMD4<Float>]? = nil) throws -> [SIMD4<Float>] {
91 let device = try #require(MTLCreateSystemDefaultDevice())
92 let renderer = try PaperRenderer(device: device)
93 let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba32Float, width: size, height: size,
94 mipmapped: false)
95 descriptor.usage = .renderTarget
96 descriptor.storageMode = .private
97 let texture = try #require(device.makeTexture(descriptor: descriptor))
98 let clusters = try clusters ?? LayerOrder(faceOrders: [], normals: scene.normals)
99 .clusters(positions: scene.positions, faces: scene.faces, viewDirection: camera.viewDirection)
100 try renderer.render(positions: scene.meshPositions, mesh: scene.mesh, clusters: clusters, camera: camera,
101 faceColours: faceColours, into: texture)
102
103 let rowBytes = size * MemoryLayout<SIMD4<Float>>.stride
104 let buffer = try #require(device.makeBuffer(length: rowBytes * size, options: .storageModeShared))
105 let commands = try #require(renderer.commandQueue.makeCommandBuffer())
106 let blit = try #require(commands.makeBlitCommandEncoder())
107 blit.copy(from: texture, sourceSlice: 0, sourceLevel: 0, sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
108 sourceSize: MTLSize(width: size, height: size, depth: 1), to: buffer, destinationOffset: 0,
109 destinationBytesPerRow: rowBytes, destinationBytesPerImage: rowBytes * size)
110 blit.endEncoding()
111 commands.commit()
112 commands.waitUntilCompleted()
113 return Array(UnsafeBufferPointer(start: buffer.contents().assumingMemoryBound(to: SIMD4<Float>.self),
114 count: size * size))
115}
116
117/// `stackedCoplanarSquares()` with face 0 above face 1, clustered by `LayerOrder` for `camera`.
118func renderStackWithComputedClusters(camera: Camera, faceColours: [SIMD4<Float>]) throws -> [SIMD4<Float>] {
119 let scene = stackedCoplanarSquares()
120 let clusters = try LayerOrder(faceOrders: [[0, 1, 1]], normals: scene.normals)
121 .clusters(positions: scene.positions, faces: scene.faces, viewDirection: camera.viewDirection)
122 return try renderToPixels(scene, clusters: clusters, camera: camera, faceColours: faceColours)
123}
124
125/// The colours other than the background, in the order they first appear.
126func uniqueColours(_ pixels: [SIMD4<Float>]) -> [SIMD4<Float>] {
127 var seen = Set<SIMD4<Float>>()
128 return pixels.filter { $0 != PaperRenderer.background && seen.insert($0).inserted }
129}
130
131/// The most frequent colour other than the background.
132func dominantColour(_ pixels: [SIMD4<Float>]) -> SIMD4<Float>? {
133 var counts: [SIMD4<Float>: Int] = [:]
134 for p in pixels where p != PaperRenderer.background { counts[p, default: 0] += 1 }
135 return counts.max { $0.value < $1.value }?.key
136}
137
138/// Face 0 turned `degrees` about the line x = 0.5 through face 1 at z = 0, its right half above
139/// face 1 and its left half below.
140func squareCrossingASquare(degrees: Double) -> Scene {
141 let c = 0.5 * cos(degrees * .pi / 180), s = 0.5 * sin(degrees * .pi / 180)
142 return Scene(squares: [[SIMD3(0.5 - c, 0, -s), SIMD3(0.5 + c, 0, s), SIMD3(0.5 + c, 1, s), SIMD3(0.5 - c, 1, -s)],
143 unitSquare(z: 0)])
144}