Packages/FoldKit/Sources/Folding/RenderMesh.swift
281 lines · 13583 bytes
17 symbols in this file
1import FoldFormat
2import simd
3
4/// The triangles the renderer draws, finer than the FOLD faces (decision 0003). Each side of each
5/// frame 0 face is divided into round(length / `spacing`) equal parts; inside each face, points of
6/// a triangular lattice `spacing` apart are kept at least 0.6 `spacing` from its sides; each face
7/// is triangulated on those points by ear clipping, point insertion and Lawson flips, so it is
8/// Delaunay within the face. Faces sharing a side share its points, so the mesh is one connected
9/// sheet. The FOLD topology is unchanged; a non-rigid step bends this mesh, not the FOLD faces.
10/// The construction assumes convex faces, which the validator enforces.
11public struct RenderMesh: Sendable {
12 /// Frame 0 positions in its plane.
13 public let vertices: [SIMD2<Double>]
14 public let triangles: [(Int, Int, Int)]
15 /// The FOLD face each triangle lies in.
16 public let faceOf: [Int]
17 /// The mesh vertex at each FOLD vertex.
18 public let meshVertexOf: [Int]
19 /// Each mesh vertex as a point of one FOLD face, for placing it in a rigid pose.
20 private let anchors: [Anchor]
21
22 /// A point of a face: `corners[0] + a·(corners[1] − corners[0]) + b·(corners[2] − corners[0])`.
23 private struct Anchor: Sendable {
24 let corners: SIMD3<Int>
25 let a: Double
26 let b: Double
27 }
28
29 public init(file: FoldFile, spacing: Double) {
30 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
31 let lower = flat.dropFirst().reduce(flat[0], simd_min)
32 let upper = flat.dropFirst().reduce(flat[0], simd_max)
33 let tolerance = (upper - lower).max() * 1e-9
34 let rowSpacing = spacing * 3.0.squareRoot() / 2
35
36 var points = PointSet(tolerance: tolerance)
37 let meshVertexOf = flat.map { points.index(of: $0) }
38 // each side's points from its lower-numbered end, so both faces compute the same ones
39 var sides: [SIMD2<Int>: [Int]] = [:]
40 func side(_ a: Int, _ b: Int) -> [Int] {
41 let key = SIMD2(min(a, b), max(a, b))
42 if sides[key] == nil {
43 let p = flat[key.x], q = flat[key.y]
44 let parts = max(1, Int((simd_distance(p, q) / spacing).rounded()))
45 sides[key] = [meshVertexOf[key.x]]
46 + (1..<parts).map { points.index(of: p + Double($0) / Double(parts) * (q - p)) }
47 + [meshVertexOf[key.y]]
48 }
49 return a == key.x ? sides[key]! : sides[key]!.reversed()
50 }
51
52 var triangles: [(Int, Int, Int)] = []
53 var faceOf: [Int] = []
54 var anchors: [Int: Anchor] = [:]
55 for (f, face) in file.facesVertices.enumerated() {
56 let outline = face.map { flat[$0] }
57 let corners = signedArea(outline) < 0 ? face.reversed() : face
58 let polygon = corners.map { flat[$0] }
59 var boundary: [Int] = []
60 for k in corners.indices { boundary += side(corners[k], corners[(k + 1) % corners.count]).dropLast() }
61
62 var inside: [Int] = []
63 let low = polygon.dropFirst().reduce(polygon[0], simd_min)
64 let high = polygon.dropFirst().reduce(polygon[0], simd_max)
65 var row = Int(((low.y - lower.y) / rowSpacing).rounded(.down))
66 while lower.y + Double(row) * rowSpacing <= high.y {
67 let y = lower.y + Double(row) * rowSpacing
68 let shift = row.isMultiple(of: 2) ? 0 : 0.5
69 var column = Int(((low.x - lower.x) / spacing - shift).rounded(.down))
70 while lower.x + (Double(column) + shift) * spacing <= high.x {
71 let p = SIMD2(lower.x + (Double(column) + shift) * spacing, y)
72 if distanceInside(polygon, p) >= 0.6 * spacing { inside.append(points.index(of: p)) }
73 column += 1
74 }
75 row += 1
76 }
77
78 for triangle in triangulate(boundary: boundary, inside: inside, points.points) {
79 triangles.append(triangle)
80 faceOf.append(f)
81 }
82 let widest = widestCorners(outline)
83 let origin = outline[widest[0]]
84 let u = outline[widest[1]] - origin, v = outline[widest[2]] - origin
85 let det = u.x * v.y - u.y * v.x
86 for id in boundary + inside where anchors[id] == nil {
87 let w = points.points[id] - origin
88 anchors[id] = Anchor(corners: SIMD3(face[widest[0]], face[widest[1]], face[widest[2]]),
89 a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det)
90 }
91 }
92 self.meshVertexOf = meshVertexOf
93 vertices = points.points
94 self.triangles = triangles
95 self.faceOf = faceOf
96 self.anchors = vertices.indices.map { anchors[$0]! }
97 }
98
99 /// Frame 0's bounding box's longer side / 32.
100 public static func spacing(for file: FoldFile) -> Double {
101 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
102 let lower = flat.dropFirst().reduce(flat[0], simd_min)
103 let upper = flat.dropFirst().reduce(flat[0], simd_max)
104 return (upper - lower).max() / 32
105 }
106
107 /// The mesh vertices when the FOLD vertices are at `positions`, each face placed rigidly.
108 func pose(_ positions: [SIMD3<Double>]) -> [SIMD3<Double>] {
109 anchors.map { anchor in
110 let o = positions[anchor.corners.x]
111 return o + anchor.a * (positions[anchor.corners.y] - o) + anchor.b * (positions[anchor.corners.z] - o)
112 }
113 }
114}
115
116/// The largest relative change in a mesh edge's length against frame 0.
117public func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double {
118 var worst = 0.0
119 for (a, b, c) in mesh.triangles {
120 for (i, j) in [(a, b), (b, c), (c, a)] {
121 let rest = simd_distance(mesh.vertices[i], mesh.vertices[j])
122 worst = max(worst, abs(simd_distance(positions[i], positions[j]) - rest) / rest)
123 }
124 }
125 return worst
126}
127
128/// Twice the signed area of a polygon, positive when its corners run counterclockwise.
129private func signedArea(_ polygon: [SIMD2<Double>]) -> Double {
130 polygon.indices.reduce(0) { sum, k in
131 let p = polygon[k], q = polygon[(k + 1) % polygon.count]
132 return sum + p.x * q.y - p.y * q.x
133 }
134}
135
136private func cross(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x }
137
138/// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside.
139private func distanceInside(_ polygon: [SIMD2<Double>], _ p: SIMD2<Double>) -> Double {
140 polygon.indices.map { k in
141 let a = polygon[k], b = polygon[(k + 1) % polygon.count]
142 return cross(b - a, p - a) / simd_distance(a, b)
143 }.min() ?? 0
144}
145
146/// A Delaunay triangulation of a convex polygon whose `boundary` points run counterclockwise
147/// (straight runs allowed), with `inside` points strictly inside, keeping the boundary's edges.
148/// Ear clipping on the boundary, each time the largest ear with no other boundary point on or in
149/// it; then each inside point inserted into the triangle holding it, splitting an edge it lies
150/// on; then Lawson flips of every edge off the boundary until each is locally Delaunay.
151/// Triangles are counterclockwise.
152private func triangulate(boundary: [Int], inside: [Int], _ p: [SIMD2<Double>]) -> [(Int, Int, Int)] {
153 func area(_ a: Int, _ b: Int, _ c: Int) -> Double { cross(p[b] - p[a], p[c] - p[a]) / 2 }
154 let scale = boundary.map { simd_length_squared(p[$0] - p[boundary[0]]) }.max() ?? 1
155 var triangles: [SIMD3<Int>] = []
156
157 var ring = boundary
158 while ring.count > 3 {
159 var best = -1, bestArea = 0.0
160 for k in ring.indices {
161 let i = ring[(k + ring.count - 1) % ring.count], j = ring[k], l = ring[(k + 1) % ring.count]
162 let a = area(i, j, l)
163 guard a > bestArea else { continue }
164 let blocked = ring.contains { m in
165 m != i && m != j && m != l && area(i, j, m) >= -1e-12 * scale && area(j, l, m) >= -1e-12 * scale
166 && area(l, i, m) >= -1e-12 * scale
167 }
168 if !blocked { (best, bestArea) = (k, a) }
169 }
170 if best < 0 || bestArea < 1e-14 * scale { break }
171 triangles.append(SIMD3(ring[(best + ring.count - 1) % ring.count], ring[best], ring[(best + 1) % ring.count]))
172 ring.remove(at: best)
173 }
174 if ring.count == 3, area(ring[0], ring[1], ring[2]) > 0 { triangles.append(SIMD3(ring[0], ring[1], ring[2])) }
175
176 for v in inside {
177 // the newest triangles first: consecutive points of a lattice row lie close together
178 for k in triangles.indices.reversed() {
179 let t = triangles[k]
180 let total = area(t.x, t.y, t.z)
181 let w = [area(v, t.y, t.z), area(t.x, v, t.z), area(t.x, t.y, v)]
182 guard w.allSatisfy({ $0 >= -1e-12 * total }) else { continue }
183 if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) {
184 // on the edge opposite corner `zero`: split both triangles beside it
185 let c = [t.x, t.y, t.z]
186 let a = c[(zero + 1) % 3], b = c[(zero + 2) % 3]
187 triangles[k] = SIMD3(c[zero], a, v)
188 triangles.append(SIMD3(c[zero], v, b))
189 if let n = triangles.indices.first(where: { n in
190 let u = triangles[n]
191 return n != k && [u.x, u.y, u.z].contains(a) && [u.x, u.y, u.z].contains(b)
192 }) {
193 let u = triangles[n]
194 let other = [u.x, u.y, u.z].first { $0 != a && $0 != b }!
195 triangles[n] = SIMD3(other, b, v)
196 triangles.append(SIMD3(other, v, a))
197 }
198 } else {
199 triangles[k] = SIMD3(t.x, t.y, v)
200 triangles.append(SIMD3(t.y, t.z, v))
201 triangles.append(SIMD3(t.z, t.x, v))
202 }
203 break
204 }
205 }
206
207 let kept = Set(boundary.indices.map { k in
208 SIMD2(min(boundary[k], boundary[(k + 1) % boundary.count]), max(boundary[k], boundary[(k + 1) % boundary.count]))
209 })
210 // whether d lies strictly inside the circle through the counterclockwise a, b, c
211 func inCircle(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool {
212 let pa = p[a] - p[d], pb = p[b] - p[d], pc = p[c] - p[d]
213 let det = simd_length_squared(pa) * cross(pb, pc) - simd_length_squared(pb) * cross(pa, pc)
214 + simd_length_squared(pc) * cross(pa, pb)
215 return det > 1e-15 * scale * scale
216 }
217 func key(_ a: Int, _ b: Int) -> SIMD2<Int> { SIMD2(min(a, b), max(a, b)) }
218 func corners(_ k: Int) -> [Int] { [triangles[k].x, triangles[k].y, triangles[k].z] }
219 var sides: [SIMD2<Int>: [Int]] = [:]
220 for k in triangles.indices {
221 let c = corners(k)
222 for i in 0..<3 { sides[key(c[i], c[(i + 1) % 3]), default: []].append(k) }
223 }
224 var pending = sides.keys.filter { !kept.contains($0) }.sorted { ($0.x, $0.y) > ($1.x, $1.y) }
225 while let edge = pending.popLast() {
226 guard let pair = sides[edge], pair.count == 2 else { continue }
227 let (k1, k2) = (pair[0], pair[1])
228 let first = corners(k1)
229 let i = first.firstIndex { $0 != edge.x && $0 != edge.y }!
230 let (c1, a, b) = (first[i], first[(i + 1) % 3], first[(i + 2) % 3])
231 let c2 = corners(k2).first { $0 != edge.x && $0 != edge.y }!
232 guard inCircle(c1, a, b, c2), area(c1, a, c2) > 0, area(c2, b, c1) > 0 else { continue }
233 triangles[k1] = SIMD3(c1, a, c2)
234 triangles[k2] = SIMD3(c2, b, c1)
235 sides[edge] = nil
236 sides[key(c1, c2)] = [k1, k2]
237 sides[key(a, c2)] = sides[key(a, c2)]!.map { $0 == k2 ? k1 : $0 }
238 sides[key(b, c1)] = sides[key(b, c1)]!.map { $0 == k1 ? k2 : $0 }
239 pending += [key(c1, a), key(a, c2), key(c2, b), key(b, c1)].filter { !kept.contains($0) }
240 }
241 return triangles.map { ($0.x, $0.y, $0.z) }
242}
243
244/// The indices of the three corners spanning the largest triangle, the first such in index order.
245func widestCorners(_ corners: [SIMD2<Double>]) -> [Int] {
246 var best = [0, 1, 2], largest = -1.0
247 for i in corners.indices {
248 for j in corners.indices where j > i {
249 for k in corners.indices where k > j {
250 let u = corners[j] - corners[i], v = corners[k] - corners[i]
251 let area = abs(u.x * v.y - u.y * v.x)
252 if area > largest { (best, largest) = ([i, j, k], area) }
253 }
254 }
255 }
256 return best
257}
258
259/// Points merged within a tolerance, found through a grid of buckets one tolerance wide.
260private struct PointSet {
261 let tolerance: Double
262 private(set) var points: [SIMD2<Double>] = []
263 private var buckets: [SIMD2<Int64>: [Int]] = [:]
264
265 init(tolerance: Double) { self.tolerance = tolerance }
266
267 /// The index of the point within the tolerance of `p`, added when there is none.
268 mutating func index(of p: SIMD2<Double>) -> Int {
269 let key = SIMD2(Int64((p.x / tolerance).rounded(.down)), Int64((p.y / tolerance).rounded(.down)))
270 for dx in -1...1 {
271 for dy in -1...1 {
272 for i in buckets[key &+ SIMD2(Int64(dx), Int64(dy))] ?? [] where simd_distance(points[i], p) <= tolerance {
273 return i
274 }
275 }
276 }
277 points.append(p)
278 buckets[key, default: []].append(points.count - 1)
279 return points.count - 1
280 }
281}