Packages/FoldKit/Sources/Folding/LayerOrder.swift
314 lines · 14713 bytes
21 symbols in this file
1import FoldFormat
2import Foundation
3import simd
4
5public enum LayerError: Error, Equatable, Sendable {
6 /// One source's order has a cycle: the faces along it, each above the next, starting at the
7 /// smallest face index.
8 case cyclic(cycle: [Int])
9}
10
11/// A connected group of nearly coplanar faces whose interiors overlap, sorted back to front for
12/// the view it was computed for.
13public struct CoplanarCluster: Equatable, Sendable {
14 public let faces: [Int]
15
16 public init(faces: [Int]) {
17 self.faces = faces
18 }
19}
20
21/// Faces closer than this to one line, in degrees, can be linked into a cluster.
22private let clusterAngle = 2.0
23/// Lengths are compared to within this fraction of the bounding-box diagonal.
24private let relativeTolerance = 1e-6
25/// Two unit normals whose dot product's magnitude reaches this lie on one line.
26private let parallelCosine = 1 - 1e-9
27
28/// The stacking order of faces in one state of a step, kept as raw `faceOrders` triples so that
29/// each is read against its `g`'s normal wherever the faces are.
30public struct LayerOrder: Sendable {
31 struct Triple: Sendable {
32 let f: Int, g: Int, s: Int
33 }
34
35 let triples: [Triple]
36 /// Each pair's relation in the form `rigidInvariantFaceOrders` gives, from the source that
37 /// supplied the pair.
38 private let invariant: [SIMD2<Int>: Int]
39
40 /// Each source is a set of triples with the face normals of the state it describes. Earlier
41 /// sources win for a pair present in several.
42 ///
43 /// - Throws: `LayerError.cyclic` when one source's triples, normalised with its normals,
44 /// form a cycle.
45 public init(sources: [(faceOrders: [[Int]], normals: [SIMD3<Double>])]) throws {
46 var triples: [Triple] = []
47 var invariant: [SIMD2<Int>: Int] = [:]
48 for source in sources {
49 let pairs = normalisedFaceOrders(source.faceOrders, normals: source.normals)
50 if let cycle = faceOrderCycle(pairs, faceCount: source.normals.count) {
51 throw LayerError.cyclic(cycle: cycle)
52 }
53 let claimed = Set(invariant.keys)
54 for (pair, s) in rigidInvariantFaceOrders(source.faceOrders, normals: source.normals)
55 where !claimed.contains(pair) && invariant[pair] == nil {
56 invariant[pair] = s
57 }
58 let faces = source.normals.indices
59 for t in source.faceOrders where t.count == 3 && faces.contains(t[0]) && faces.contains(t[1])
60 && t[0] != t[1] && (t[2] == 1 || t[2] == -1)
61 && !claimed.contains(SIMD2(min(t[0], t[1]), max(t[0], t[1]))) {
62 triples.append(Triple(f: t[0], g: t[1], s: t[2]))
63 }
64 }
65 self.triples = triples
66 self.invariant = invariant
67 }
68
69 public init(faceOrders: [[Int]], normals: [SIMD3<Double>]) throws {
70 try self.init(sources: [(faceOrders: faceOrders, normals: normals)])
71 }
72
73 /// The order that applies throughout step n: frame n's `krz:faceOrders_midFold` (with the
74 /// normals at the peak for a `foldAndUnfold`, else frame n's), or without one frame n's
75 /// `faceOrders`; then frame n − 1's `faceOrders` for the pairs the first lacks, such as a flap
76 /// leaving a stack.
77 ///
78 /// A triple whose `g` moves in the step and whose `f` does not is replaced, with its source's
79 /// normals, by its reverse, so that the pair is read against the still face's normal, which
80 /// does not turn during the step. A face moves when it is in `step.allMovingFaces`.
81 public static func active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder {
82 let start = file.frames[step.index - 1], end = file.frames[step.index]
83 let first: (faceOrders: [[Int]], normals: [SIMD3<Double>])
84 if let midFold = end.faceOrdersMidFold {
85 let normals = step.kind == .foldAndUnfold
86 ? faceNormals(positions: FoldInterpolator(file: file, step: step).positions(at: 0.5),
87 faces: file.facesVertices)
88 : faceNormals(end, file)
89 first = (midFold, normals)
90 } else {
91 first = (end.faceOrders, faceNormals(end, file))
92 }
93 let moving = step.allMovingFaces
94 let sources = [first, (start.faceOrders, faceNormals(start, file))].map { source in
95 (faceOrders: source.faceOrders.map { t -> [Int] in
96 guard t.count == 3, source.normals.indices.contains(t[0]), source.normals.indices.contains(t[1]),
97 moving.contains(t[1]), !moving.contains(t[0]) else { return t }
98 return [t[1], t[0], dot(source.normals[t[0]], source.normals[t[1]]) > 0 ? -t[2] : t[2]]
99 }, normals: source.normals)
100 }
101 return try LayerOrder(sources: sources)
102 }
103
104 /// The faces grouped into clusters, each sorted back to front as seen looking along
105 /// `viewDirection`, ordered by their smallest face index. Every face is in exactly one.
106 ///
107 /// Two faces are linked when, projected onto the first's plane, their interiors overlap, their
108 /// normals are within 2° of one line, and each one's vertices lie within sin 2° × the
109 /// bounding-box diagonal of `positions` from the other's plane. A cluster is a connected group
110 /// of linked faces. Within a cluster each triple is read against its `g`'s normal at
111 /// `positions`; faces the order leaves unrelated keep index order.
112 public func clusters(positions: [SIMD3<Double>], faces: [[Int]], viewDirection: SIMD3<Double>) -> [CoplanarCluster] {
113 let normals = faceNormals(positions: positions, faces: faces)
114 return clusterMembers(positions: positions, faces: faces).map { members in
115 CoplanarCluster(faces: backToFront(members, normals: normals, viewDirection: viewDirection))
116 }
117 }
118
119 /// Whether the two orders relate every pair they share the same way, in the form a rigid
120 /// motion leaves unchanged, ignoring pairs with a face in `movingFaces`.
121 public func agreesWith(_ other: LayerOrder, ignoring movingFaces: Set<Int>) -> Bool {
122 invariant.allSatisfy { pair, s in
123 movingFaces.contains(pair[0]) || movingFaces.contains(pair[1]) || (other.invariant[pair] ?? s) == s
124 }
125 }
126
127 /// `members`, in index order, topologically sorted so that every face comes after the faces
128 /// behind it, taking the smallest ready face first. The triples are read against one normal for
129 /// the whole cluster, its smallest face's, so that faces a little off parallel cannot disagree
130 /// about which side the camera is on.
131 private func backToFront(_ members: [Int], normals: [SIMD3<Double>], viewDirection: SIMD3<Double>) -> [Int] {
132 guard members.count > 1 else { return members }
133 let reference = normals[members[0]]
134 let cameraOnReferenceSide = dot(reference, viewDirection) < 0
135 let inCluster = Set(members)
136
137 var inFront: [Int: Set<Int>] = [:]
138 for t in triples where inCluster.contains(t.f) && inCluster.contains(t.g) {
139 let gAlongReference = dot(normals[t.g], reference) > 0
140 let fOnReferenceSide = (t.s > 0) == gAlongReference
141 let (back, front) = fOnReferenceSide == cameraOnReferenceSide ? (t.g, t.f) : (t.f, t.g)
142 inFront[back, default: []].insert(front)
143 }
144 var behind = Dictionary(uniqueKeysWithValues: members.map { ($0, 0) })
145 for fronts in inFront.values {
146 for f in fronts { behind[f]! += 1 }
147 }
148
149 var remaining = members
150 var sorted: [Int] = []
151 while !remaining.isEmpty {
152 // two sources can together order a cluster in a cycle; the smallest remaining face breaks it
153 let i = remaining.firstIndex { behind[$0] == 0 } ?? 0
154 let face = remaining.remove(at: i)
155 sorted.append(face)
156 for f in inFront[face] ?? [] { behind[f]! -= 1 }
157 }
158 return sorted
159 }
160}
161
162/// The most faces whose open interiors cover one point, over each group of coincident faces. A
163/// flat sheet is 1.
164///
165/// Each group's outlines are projected onto its plane and every outline is cut by the edge lines
166/// of the others, so each piece lies wholly inside or outside every face; the count is taken at
167/// each piece's centroid.
168public func stackDepth(positions: [SIMD3<Double>], faces: [[Int]]) -> Int {
169 let normals = faceNormals(positions: positions, faces: faces)
170 let tolerance = boundingBoxDiagonal(positions) * relativeTolerance
171
172 func coincident(_ a: Int, _ b: Int) -> Bool {
173 guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= parallelCosine else {
174 return false
175 }
176 let corner = positions[faces[a][0]]
177 return faces[b].allSatisfy { abs(dot(positions[$0] - corner, normals[a])) <= tolerance }
178 }
179
180 var deepest = 0
181 for group in components(faces.count, linked: coincident) where normals[group[0]] != .zero {
182 let (u, v) = planeBasis(normals[group[0]])
183 let outlines = group.map { face in
184 counterclockwise(faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) })
185 }
186 let lines = outlines.flatMap { outline in
187 outline.indices.map { (outline[$0], outline[($0 + 1) % outline.count]) }
188 }
189 for outline in outlines {
190 var pieces = [outline]
191 for (a, b) in lines where length(b - a) > tolerance {
192 pieces = pieces.flatMap { split($0, along: a, b, tolerance: tolerance) }
193 }
194 for piece in pieces where area(piece) > tolerance * tolerance {
195 let c = centroid(piece)
196 deepest = max(deepest, outlines.filter { contains($0, c) }.count)
197 }
198 }
199 }
200 return deepest
201}
202
203// MARK: - Helpers
204
205/// The faces of each near-coplanar cluster, in index order, ordered by their smallest face, as
206/// `LayerOrder.clusters` links them: normals within 2° of one line, each face's vertices within
207/// sin 2° × the positions' bounding-box diagonal of the other's plane, and interiors overlapping.
208func clusterMembers(positions: [SIMD3<Double>], faces: [[Int]]) -> [[Int]] {
209 let normals = faceNormals(positions: positions, faces: faces)
210 let diagonal = boundingBoxDiagonal(positions)
211 let tolerance = diagonal * relativeTolerance
212 let offPlane = diagonal * sin(clusterAngle * .pi / 180)
213 let cosine = cos(clusterAngle * .pi / 180)
214
215 func withinPlane(_ face: Int, of other: Int) -> Bool {
216 let corner = positions[faces[other][0]]
217 return faces[face].allSatisfy { abs(dot(positions[$0] - corner, normals[other])) <= offPlane }
218 }
219 func linked(_ a: Int, _ b: Int) -> Bool {
220 guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= cosine,
221 withinPlane(a, of: b), withinPlane(b, of: a) else { return false }
222 let (u, v) = planeBasis(normals[a])
223 let project = { (face: Int) in faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
224 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
225 }
226 return components(faces.count, linked: linked)
227}
228
229/// The connected components of `linked` over `0..<count`, each in index order, ordered by their
230/// smallest member.
231private func components(_ count: Int, linked: (Int, Int) -> Bool) -> [[Int]] {
232 var component = Array<Int?>(repeating: nil, count: count)
233 var result: [[Int]] = []
234 for start in 0..<count where component[start] == nil {
235 component[start] = result.count
236 var members = [start], stack = [start]
237 while let a = stack.popLast() {
238 for b in 0..<count where component[b] == nil && linked(min(a, b), max(a, b)) {
239 component[b] = result.count
240 members.append(b)
241 stack.append(b)
242 }
243 }
244 result.append(members.sorted())
245 }
246 return result
247}
248
249private func boundingBoxDiagonal(_ points: [SIMD3<Double>]) -> Double {
250 guard let first = points.first else { return 0 }
251 return length(points.reduce(first, simd_max) - points.reduce(first, simd_min))
252}
253
254/// Two unit vectors spanning the plane with unit normal `n`.
255package func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) {
256 let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0)
257 let u = normalize(cross(n, helper))
258 return (u, cross(n, u))
259}
260
261private func signedArea(_ p: [SIMD2<Double>]) -> Double {
262 p.indices.reduce(0) { sum, i in
263 let a = p[i], b = p[(i + 1) % p.count]
264 return sum + (a.x * b.y - b.x * a.y) / 2
265 }
266}
267
268private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) }
269
270func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
271 signedArea(p) < 0 ? p.reversed() : p
272}
273
274/// The area centroid of a polygon, or its corners' mean when it has no area.
275func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> {
276 let area = signedArea(p)
277 guard abs(area) > 0 else { return p.reduce(.zero, +) / Double(max(p.count, 1)) }
278 var sum = SIMD2<Double>.zero
279 for i in p.indices {
280 let a = p[i], b = p[(i + 1) % p.count]
281 sum += (a + b) * (a.x * b.y - b.x * a.y)
282 }
283 return sum / (6 * area)
284}
285
286/// Whether `point` is in the open interior of the counterclockwise convex polygon `p`.
287private func contains(_ p: [SIMD2<Double>], _ point: SIMD2<Double>) -> Bool {
288 p.indices.allSatisfy { i in
289 let a = p[i], b = p[(i + 1) % p.count]
290 let side = b - a, offset = point - a
291 return side.x * offset.y - side.y * offset.x > 0
292 }
293}
294
295/// The convex polygon `p` cut in two by the line through `a` and `b`, or `p` alone when no
296/// corner lies more than `tolerance` to each side.
297private func split(_ p: [SIMD2<Double>], along a: SIMD2<Double>, _ b: SIMD2<Double>,
298 tolerance: Double) -> [[SIMD2<Double>]] {
299 let d = normalize(b - a)
300 let side = p.map { q in d.x * (q.y - a.y) - d.y * (q.x - a.x) }
301 guard let low = side.min(), let high = side.max(), low < -tolerance, high > tolerance else { return [p] }
302 var left: [SIMD2<Double>] = [], right: [SIMD2<Double>] = []
303 for i in p.indices {
304 let j = (i + 1) % p.count
305 if side[i] >= 0 { left.append(p[i]) }
306 if side[i] <= 0 { right.append(p[i]) }
307 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
308 let crossing = p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j]))
309 left.append(crossing)
310 right.append(crossing)
311 }
312 }
313 return [left, right]
314}