Rigid interpolation, layer order and interpenetration (Tasks 4–6) !4

merged merged by cmc on 2026-10-20 01:54 UTC · krz/fold:folding-engine into main

10 files changed, +1169 −37

Layout: unified · split

Packages/FoldKit/Package.swift +1 −1
@@ -13,7 +13,7 @@ let package = Package(
1313 .target(name: "Folding", dependencies: ["FoldFormat"]),
1414 .target(
1515 name: "FoldKitTestSupport",
16 dependencies: ["FoldFormat"],
16 dependencies: ["FoldFormat", "Folding"],
1717 resources: [.copy("Fixtures")]
1818 ),
1919 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]),
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +54 −33
@@ -164,6 +164,44 @@ public func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) ->
164164 }
165165}
166166
167/// Each triple `[f, g, s]` with `s ≠ 0` in a form that a rigid motion of both faces together leaves
168/// unchanged: rewritten with the lower face first, `s` negated when swapping two faces whose
169/// normals agree (the spec's rule for a reverse triple). Triples with `s = 0`, a repeated face or
170/// a face outside `normals` are skipped.
171public func rigidInvariantFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(pair: SIMD2<Int>, s: Int)] {
172 validTriples(orders, faceCount: normals.count).map { f, g, s in
173 if f < g { return (SIMD2(f, g), s) }
174 return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s)
175 }
176}
177
178/// A cycle in the stacking relation `pairs` over faces `0..<faceCount`, as the faces along it,
179/// each above the next, starting at the cycle's smallest face index; nil when there is none.
180/// Pairs naming a face outside `0..<faceCount` are skipped.
181public func faceOrderCycle(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [Int]? {
182 guard let cycle = firstCycle(stackingGraph(pairs, faceCount: faceCount)),
183 let start = cycle.indices.min(by: { cycle[$0] < cycle[$1] }) else { return nil }
184 return Array(cycle[start...] + cycle[..<start])
185}
186
187/// Whether two convex polygons share interior area wider than `tolerance`, by separating axes.
188/// Polygons that only touch do not.
189public func convexPolygonsOverlap(_ p: [SIMD2<Double>], _ q: [SIMD2<Double>], tolerance: Double) -> Bool {
190 var tested = false
191 for polygon in [p, q] {
192 for i in polygon.indices {
193 let edge = polygon[(i + 1) % polygon.count] - polygon[i]
194 guard length(edge) > tolerance else { continue }
195 let axis = normalize(SIMD2(-edge.y, edge.x))
196 let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) }
197 guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false }
198 if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false }
199 tested = true
200 }
201 }
202 return tested
203}
204
167205// MARK: - File-level rules
168206
169207private func sheetSize(_ file: FoldFile) -> Double {
@@ -301,14 +339,11 @@ private func layerOrderDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, e
301339 signs[SIMD2(f, g)] = s
302340 }
303341
304 var aboveOf = Array(repeating: Set<Int>(), count: faceCount)
305 for pair in normalisedFaceOrders(frame.faceOrders, normals: normals) {
306 aboveOf[pair.below].insert(pair.above)
307 }
308 let graph = aboveOf.map { $0.sorted() }
309 if let cycle = firstCycle(graph) {
342 let pairs = normalisedFaceOrders(frame.faceOrders, normals: normals)
343 if let cycle = faceOrderCycle(pairs, faceCount: faceCount) {
310344 defects.append(.cyclicFaceOrder(frame: n, cycle: cycle))
311345 }
346 let graph = stackingGraph(pairs, faceCount: faceCount)
312347
313348 // isAbove[x][y]: y lies above x in the stack, directly or through other faces
314349 let isAbove = reachability(graph)
@@ -377,18 +412,12 @@ private func isometryDefects(_ file: FoldFile, step n: Int, tolerance: Double) -
377412 }
378413}
379414
380/// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way.
381/// Each triple is compared in a form a rigid motion leaves unchanged: rewritten with the lower
382/// face first, `s` negated when swapping two faces whose normals agree.
415/// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way,
416/// compared with `rigidInvariantFaceOrders`.
383417private func stillFaceDefects(_ file: FoldFile, step n: Int, moving: Set<Int>) -> [FoldDefect] {
384418 func relations(_ frame: FoldFrame) -> [(pair: SIMD2<Int>, s: Int)] {
385 let normals = faceNormals(frame, file)
386 return validTriples(frame.faceOrders, faceCount: file.facesVertices.count)
387 .filter { f, g, _ in !moving.contains(f) && !moving.contains(g) }
388 .map { f, g, s in
389 if f < g { return (SIMD2(f, g), s) }
390 return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s)
391 }
419 rigidInvariantFaceOrders(frame.faceOrders, normals: faceNormals(frame, file))
420 .filter { !moving.contains($0.pair[0]) && !moving.contains($0.pair[1]) }
392421 }
393422 var after: [SIMD2<Int>: Int] = [:]
394423 for (pair, s) in relations(file.frames[n]) where after[pair] == nil {
@@ -456,6 +485,15 @@ private func firstCycle(_ graph: [[Int]]) -> [Int]? {
456485 return nil
457486}
458487
488/// For each face, the faces directly above it, in index order.
489private func stackingGraph(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [[Int]] {
490 var aboveOf = Array(repeating: Set<Int>(), count: faceCount)
491 for pair in pairs where (0..<faceCount).contains(pair.below) && (0..<faceCount).contains(pair.above) {
492 aboveOf[pair.below].insert(pair.above)
493 }
494 return aboveOf.map { $0.sorted() }
495}
496
459497private func reachability(_ graph: [[Int]]) -> [[Bool]] {
460498 graph.indices.map { start in
461499 var seen = Array(repeating: false, count: graph.count)
@@ -469,23 +507,6 @@ private func reachability(_ graph: [[Int]]) -> [[Bool]] {
469507 }
470508}
471509
472/// Whether two convex polygons share interior area wider than `tolerance`, by separating axes.
473private func convexPolygonsOverlap(_ p: [SIMD2<Double>], _ q: [SIMD2<Double>], tolerance: Double) -> Bool {
474 var tested = false
475 for polygon in [p, q] {
476 for i in polygon.indices {
477 let edge = polygon[(i + 1) % polygon.count] - polygon[i]
478 guard length(edge) > tolerance else { continue }
479 let axis = normalize(SIMD2(-edge.y, edge.x))
480 let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) }
481 guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false }
482 if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false }
483 tested = true
484 }
485 }
486 return tested
487}
488
489510private struct FrameGeometry {
490511 let points: [SIMD3<Double>]
491512 let faces: [[Int]]
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +188
@@ -1,5 +1,7 @@
11import Foundation
22import FoldFormat
3import Folding
4import simd
35
46/// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases
57/// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step.
@@ -99,3 +101,189 @@ public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double {
99101}
100102
101103private func radians(_ degrees: Double) -> Double { degrees * .pi / 180 }
104
105/// A fixture file, and the interpolator for its step `step` (counted from 1).
106public func interpolator(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldInterpolator) {
107 let file = try FoldFile(contentsOf: fixture(fixtureName))
108 return (file, FoldInterpolator(file: file, step: try readSteps(file)[step - 1]))
109}
110
111/// The largest change, against frame 0, in the length of any FOLD edge.
112public func maxEdgeLengthDrift(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Double {
113 let flat = file.frames[0].verticesCoords
114 return file.edgesVertices.map { e in
115 abs(simd_distance(positions[e[0]], positions[e[1]]) - simd_distance(flat[e[0]], flat[e[1]]))
116 }.max() ?? 0
117}
118
119/// Whether every pairwise distance between the points agrees, within 1e-9, across both arrays.
120public func pairwiseDistancesAgree(_ a: [SIMD3<Double>], _ b: [SIMD3<Double>]) -> Bool {
121 guard a.count == b.count else { return false }
122 for i in a.indices {
123 for j in a.indices where j > i {
124 if abs(simd_distance(a[i], a[j]) - simd_distance(b[i], b[j])) > 1e-9 { return false }
125 }
126 }
127 return true
128}
129
130/// The longer side of frame 0's bounding box.
131public func sheetSize(_ file: FoldFile) -> Double {
132 let points = file.frames[0].verticesCoords
133 let lower = points.dropFirst().reduce(points[0], simd_min)
134 let upper = points.dropFirst().reduce(points[0], simd_max)
135 let extent = upper - lower
136 return max(extent.x, extent.y, extent.z)
137}
138
139/// A `cells` × `cells` grid of unit cells, with one step folding the right half over the left
140/// about the vertical line through the middle. Cells are faces, numbered row by row from the
141/// bottom left; `cells` must be even.
142public func gridSheet(cells: Int) -> FoldFile {
143 precondition(cells >= 2 && cells.isMultiple(of: 2), "gridSheet needs an even number of cells")
144 let n = cells, half = n / 2
145 func vertex(_ i: Int, _ j: Int) -> Int { j * (n + 1) + i }
146
147 var flat: [SIMD3<Double>] = []
148 for j in 0...n { for i in 0...n { flat.append(SIMD3(Double(i), Double(j), 0)) } }
149 let folded = flat.map { p in SIMD3(p.x > Double(half) ? Double(n) - p.x : p.x, p.y, 0) }
150
151 var edges: [[Int]] = [], assignment: [EdgeAssignment] = [], angle: [Double] = []
152 var created: [Int?] = []
153 func addEdge(_ a: Int, _ b: Int, boundary: Bool, crease: Bool) {
154 edges.append([a, b])
155 assignment.append(boundary ? .boundary : crease ? .valley : .flat)
156 angle.append(crease ? 180 : 0)
157 created.append(crease ? 1 : nil)
158 }
159 var axisEdge = 0
160 for j in 0...n {
161 for i in 0..<n {
162 addEdge(vertex(i, j), vertex(i + 1, j), boundary: j == 0 || j == n, crease: false)
163 }
164 }
165 for j in 0..<n {
166 for i in 0...n {
167 let crease = i == half
168 if crease && j == 0 { axisEdge = edges.count }
169 addEdge(vertex(i, j), vertex(i, j + 1), boundary: i == 0 || i == n, crease: crease)
170 }
171 }
172
173 var faces: [[Int]] = []
174 for j in 0..<n {
175 for i in 0..<n {
176 faces.append([vertex(i, j), vertex(i + 1, j), vertex(i + 1, j + 1), vertex(i, j + 1)])
177 }
178 }
179 let right = faces.indices.filter { $0 % n >= half }
180 // each right cell lies flipped on top of its mirror image in the left half
181 let orders = right.map { f in [f, f - 2 * (f % n - half) - 1, 1] }
182
183 let step = StepRecord(
184 kind: .fold,
185 technique: .plain,
186 instruction: "Valley fold the right half over to the left.",
187 axes: [AxisRecord(edge: axisEdge, movingFaces: right, startAngle: 0, endAngle: 180)],
188 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
189 )
190 return FoldFile(
191 fileSpec: 1.2,
192 fileTitle: "Grid",
193 fileAuthor: "Traditional",
194 fileClasses: ["diagrams"],
195 edgesVertices: edges,
196 facesVertices: faces,
197 edgesFirstCreasedAtStep: created,
198 frames: [
199 FoldFrame(verticesCoords: flat,
200 edgesAssignment: assignment.map { $0 == .valley ? .flat : $0 },
201 edgesFoldAngle: Array(repeating: 0, count: edges.count),
202 faceOrders: []),
203 FoldFrame(verticesCoords: folded, edgesAssignment: assignment, edgesFoldAngle: angle,
204 faceOrders: orders, step: step),
205 ]
206 )
207}
208
209/// A fixture file, its step `step` (counted from 1), and the interpolator for that step.
210public func interpolatorWithStep(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator) {
211 let file = try FoldFile(contentsOf: fixture(fixtureName))
212 let s = try readSteps(file)[step - 1]
213 return (file, s, FoldInterpolator(file: file, step: s))
214}
215
216/// The corners of a unit square in the plane z = `z`, counterclockwise seen from +z.
217private func unitSquare(z: Double) -> [SIMD3<Double>] {
218 [SIMD3(0, 0, z), SIMD3(1, 0, z), SIMD3(1, 1, z), SIMD3(0, 1, z)]
219}
220
221/// Two unit squares, both at z = 0.
222public func stackedSquarePositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 0) }
223
224/// Two unit squares, at z = 0 and z = 1.
225public func separatedSquarePositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 1) }
226
227/// Three unit squares, all at z = 0.
228public func threeStackedPositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 0) + unitSquare(z: 0) }
229
230/// The faces of two squares of four vertices each, facing +z.
231public func twoSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7]] }
232
233/// The faces of three squares of four vertices each, facing +z.
234public func threeSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] }
235
236/// `letter.fold`'s sheet with both outer thirds valley-folded in front of the middle one on one
237/// window of t, linear 0 → 180°. The flaps meet at 120°, t = 2/3, and pass through each other
238/// after.
239public func interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator) {
240 let file = try FoldFile(contentsOf: fixture("letter.fold"))
241 let step = FoldStep(
242 index: 1,
243 kind: .fold,
244 instruction: "Valley fold both thirds in front.",
245 axes: [
246 // f0 traverses e8 from v1 up the sheet, f2 traverses e9 from v5 down it
247 FoldAxis(edge: 8, origin: SIMD3(1, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [0],
248 startAngle: 0, endAngle: 180),
249 FoldAxis(edge: 9, origin: SIMD3(2, 3, 0), direction: SIMD3(0, -1, 0), movingFaces: [2],
250 startAngle: 0, endAngle: 180),
251 ],
252 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
253 )
254 return (file, FoldInterpolator(file: file, step: step))
255}
256
257/// A fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4) and a moving triangle (0,0,0), (0,2,0),
258/// (-1,1,0) hinged on its edge along the y-axis, folding toward +z from 0 to 180°. They share
259/// vertex 0 only. The fixed triangle is tilted, so this is not a flat frame 0 and the file is
260/// built directly.
261public func interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator) {
262 let start: [SIMD3<Double>] = [
263 SIMD3(0, 0, 0), SIMD3(1, 1.2, 0.4), SIMD3(-1, 1.2, 0.4), SIMD3(0, 2, 0), SIMD3(-1, 1, 0),
264 ]
265 var end = start
266 end[4] = SIMD3(1, 1, 0)
267 let assignment: [EdgeAssignment] = [.boundary, .boundary, .boundary, .valley, .boundary, .boundary]
268 func frame(_ points: [SIMD3<Double>], angle: Double) -> FoldFrame {
269 FoldFrame(verticesCoords: points, edgesAssignment: assignment,
270 edgesFoldAngle: [0, 0, 0, angle, 0, 0], faceOrders: [])
271 }
272 let file = FoldFile(
273 fileSpec: 1.2,
274 fileAuthor: "Traditional",
275 edgesVertices: [[0, 1], [1, 2], [2, 0], [0, 3], [3, 4], [4, 0]],
276 facesVertices: [[0, 1, 2], [0, 3, 4]],
277 edgesFirstCreasedAtStep: [nil, nil, nil, 1, nil, nil],
278 frames: [frame(start, angle: 0), frame(end, angle: 180)]
279 )
280 let step = FoldStep(
281 index: 1,
282 kind: .fold,
283 instruction: "Fold the flap up.",
284 axes: [FoldAxis(edge: 3, origin: SIMD3(0, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [1],
285 startAngle: 0, endAngle: 180)],
286 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
287 )
288 return (file, FoldInterpolator(file: file, step: step))
289}
Packages/FoldKit/Sources/Folding/FoldInterpolator.swift added +127
@@ -0,0 +1,127 @@
1import FoldFormat
2import simd
3
4/// Interpolates a rigid step from frame `step.index − 1` to frame `step.index`.
5///
6/// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an
7/// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates
8/// the whole of the start frame about its bounding-box centre. Steps flagged `nonRigid` are not
9/// handled here.
10public struct FoldInterpolator: Sendable {
11 private struct Motion: Sendable {
12 let step: FoldStep
13 /// Per axis, the vertices that take their position from that axis's face group.
14 let vertices: [[Int]]
15 }
16
17 private struct Reorientation: Sendable {
18 let centre: SIMD3<Double>
19 let axis: SIMD3<Double>
20 /// Radians at t = 1.
21 let angle: Double
22 }
23
24 private enum Mode: Sendable {
25 case folds(Motion)
26 case reorient(Reorientation)
27 }
28
29 private let start: [SIMD3<Double>]
30 private let kind: StepKind
31 private let mode: Mode
32
33 public init(file: FoldFile, step: FoldStep) {
34 precondition(!step.nonRigid, "FoldInterpolator handles rigid steps only; the non-rigid path is added by Task 7b")
35 start = file.frames[step.index - 1].verticesCoords
36 kind = step.kind
37
38 switch step.kind {
39 case .fold, .foldAndUnfold:
40 var axisOfFace: [Int: Int] = [:]
41 for (a, axis) in step.axes.enumerated() {
42 for f in axis.movingFaces { axisOfFace[f] = a }
43 }
44 // a vertex takes its position from the first face containing it
45 var owner = Array<Int?>(repeating: nil, count: start.count)
46 var seen = Array(repeating: false, count: start.count)
47 for (f, face) in file.facesVertices.enumerated() {
48 for v in face where !seen[v] {
49 seen[v] = true
50 owner[v] = axisOfFace[f]
51 }
52 }
53 var groups = Array(repeating: [Int](), count: step.axes.count)
54 for (v, a) in owner.enumerated() {
55 if let a { groups[a].append(v) }
56 }
57 mode = .folds(Motion(step: step, vertices: groups))
58
59 case .turnOver, .rotate:
60 var lower = start[0], upper = start[0]
61 for p in start {
62 lower = simd_min(lower, p)
63 upper = simd_max(upper, p)
64 }
65 let eye = normalize(step.viewpoint.eye), up = normalize(step.viewpoint.up)
66 let axis: SIMD3<Double>, degrees: Double
67 if step.kind == .rotate {
68 axis = eye
69 degrees = step.rotateDegrees ?? 0
70 } else {
71 axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up
72 degrees = 180
73 }
74 mode = .reorient(Reorientation(centre: (lower + upper) / 2, axis: axis,
75 angle: degrees * .pi / 180))
76 }
77 }
78
79 /// The vertex positions at `t` of the step, `t` in 0...1.
80 public func positions(at t: Double) -> [SIMD3<Double>] {
81 switch mode {
82 case .reorient(let r):
83 let q = simd_quatd(angle: r.angle * t, axis: r.axis)
84 return start.map { r.centre + q.act($0 - r.centre) }
85
86 case .folds(let motion):
87 // each axis's full transform: its own rotation, then its parent's
88 var full: [Transform] = []
89 full.reserveCapacity(motion.step.axes.count)
90 for axis in motion.step.axes {
91 let degrees = axis.angle(at: t, kind: kind) - axis.startAngle
92 let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction)
93 let own = Transform(rotation: simd_double3x3(q), about: axis.origin)
94 full.append(axis.parent.map { full[$0].after(own) } ?? own)
95 }
96 var result = start
97 for (a, group) in motion.vertices.enumerated() {
98 for v in group { result[v] = full[a].apply(start[v]) }
99 }
100 return result
101 }
102 }
103}
104
105/// p ↦ linear · p + offset
106private struct Transform {
107 var linear: simd_double3x3
108 var offset: SIMD3<Double>
109
110 /// The rotation `linear` about the point `centre`.
111 init(rotation linear: simd_double3x3, about centre: SIMD3<Double>) {
112 self.linear = linear
113 offset = centre - linear * centre
114 }
115
116 private init(linear: simd_double3x3, offset: SIMD3<Double>) {
117 self.linear = linear
118 self.offset = offset
119 }
120
121 func apply(_ p: SIMD3<Double>) -> SIMD3<Double> { linear * p + offset }
122
123 /// This transform applied after `inner`.
124 func after(_ inner: Transform) -> Transform {
125 Transform(linear: linear * inner.linear, offset: linear * inner.offset + offset)
126 }
127}
Packages/FoldKit/Sources/Folding/Interpenetration.swift added +132
@@ -0,0 +1,132 @@
1import FoldFormat
2import simd
3
4/// Two faces that pass through each other. `t` is the first sample, `k / samples`, at which they
5/// do; `faceA < faceB`.
6public struct Intersection: Equatable, Sendable {
7 public let faceA: Int
8 public let faceB: Int
9 public let t: Double
10
11 public init(faceA: Int, faceB: Int, t: Double) {
12 self.faceA = faceA
13 self.faceB = faceB
14 self.t = t
15 }
16}
17
18/// Contact this close to a face's boundary does not count.
19private let contactTolerance = 1e-9
20/// Coplanar faces: normals within this many radians (as lines), planes within this fraction of
21/// the sheet's size.
22private let coplanarAngle = 1e-6
23private let coplanarOffset = 1e-6
24
25/// The pairs of faces that interpenetrate at some sample `t = k / samples`, `k` in 0...samples,
26/// each reported once at the first such sample.
27///
28/// Faces are convex. A pair interpenetrates when the line where their planes meet cuts both and
29/// the stretch common to both has its midpoint more than 1e-9 inside every edge of each. Contact
30/// along an edge or at a vertex, shared or coincident, does not count, but pairs that share a
31/// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's.
32/// The sheet's size is the longest side of the bounding box of the positions at `t = 0`.
33public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] {
34 precondition(samples > 0, "interpenetrations needs at least one sample")
35 let size = boundingExtent(interpolator.positions(at: 0)).max()
36 let usable = faces.indices.filter { faces[$0].count >= 3 }
37
38 var found: [Intersection] = []
39 var reported = Set<SIMD2<Int>>()
40 for k in 0...samples {
41 let t = Double(k) / Double(samples)
42 let positions = interpolator.positions(at: t)
43 let normals = faceNormals(positions: positions, faces: faces)
44 let polygons = faces.map { $0.map { positions[$0] } }
45 let boxes = polygons.map(bounds)
46
47 for (n, a) in usable.enumerated() where normals[a] != .zero {
48 for b in usable[(n + 1)...] where normals[b] != .zero {
49 let pair = SIMD2(a, b)
50 guard !reported.contains(pair), boxesMeet(boxes[a], boxes[b]),
51 !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size),
52 passThrough(polygons[a], normals[a], polygons[b], normals[b])
53 else { continue }
54 reported.insert(pair)
55 found.append(Intersection(faceA: a, faceB: b, t: t))
56 }
57 }
58 }
59 return found
60}
61
62private typealias Box = (lower: SIMD3<Double>, upper: SIMD3<Double>)
63
64private func bounds(_ points: [SIMD3<Double>]) -> Box {
65 guard let first = points.first else { return (.zero, .zero) }
66 return points.dropFirst().reduce((first, first)) { (simd_min($0.0, $1), simd_max($0.1, $1)) }
67}
68
69private func boundingExtent(_ points: [SIMD3<Double>]) -> SIMD3<Double> {
70 let box = bounds(points)
71 return box.upper - box.lower
72}
73
74/// Whether the boxes, grown by the contact tolerance, meet. Faces whose boxes do not meet cannot
75/// pass through each other.
76private func boxesMeet(_ a: Box, _ b: Box) -> Bool {
77 all(a.lower - contactTolerance .<= b.upper) && all(b.lower - contactTolerance .<= a.upper)
78}
79
80private func coplanar(_ a: [SIMD3<Double>], _ na: SIMD3<Double>, _ b: [SIMD3<Double>], _ nb: SIMD3<Double>,
81 size: Double) -> Bool {
82 guard length(cross(na, nb)) <= coplanarAngle else { return false }
83 let centre = b.reduce(.zero, +) / Double(b.count)
84 return abs(dot(na, centre - a[0])) <= coplanarOffset * size
85}
86
87/// The inward unit normal of each edge of a counterclockwise polygon, in its plane, with a corner
88/// on that edge.
89private func edgeInwardNormals(_ polygon: [SIMD3<Double>], _ normal: SIMD3<Double>)
90 -> [(corner: SIMD3<Double>, inward: SIMD3<Double>)] {
91 polygon.indices.compactMap { i in
92 let corner = polygon[i], edge = polygon[(i + 1) % polygon.count] - corner
93 let size = length(edge)
94 return size > 0 ? (corner, cross(normal, edge) / size) : nil
95 }
96}
97
98/// The interval of `s` for which `p + s·d` lies in the polygon, `p` and `d` being in its plane.
99private func clip(_ edges: [(corner: SIMD3<Double>, inward: SIMD3<Double>)], _ p: SIMD3<Double>,
100 _ d: SIMD3<Double>) -> ClosedRange<Double>? {
101 var low = -Double.infinity, high = Double.infinity
102 for (corner, inward) in edges {
103 let distance = dot(inward, p - corner), rate = dot(inward, d)
104 if abs(rate) < 1e-15 {
105 if distance < 0 { return nil }
106 continue
107 }
108 let s = -distance / rate
109 if rate > 0 { low = max(low, s) } else { high = min(high, s) }
110 }
111 return low <= high ? low...high : nil
112}
113
114private func passThrough(_ a: [SIMD3<Double>], _ na: SIMD3<Double>, _ b: [SIMD3<Double>], _ nb: SIMD3<Double>) -> Bool {
115 let along = cross(na, nb)
116 let squared = dot(along, along)
117 guard squared > 0 else { return false }
118 let d = along / sqrt(squared)
119 // a point on both planes
120 let p = (dot(na, a[0]) * cross(nb, along) + dot(nb, b[0]) * cross(along, na)) / squared
121
122 let edgesA = edgeInwardNormals(a, na), edgesB = edgeInwardNormals(b, nb)
123 guard let inA = clip(edgesA, p, d), let inB = clip(edgesB, p, d) else { return false }
124 let low = max(inA.lowerBound, inB.lowerBound), high = min(inA.upperBound, inB.upperBound)
125 guard low < high else { return false }
126
127 // A convex chord whose midpoint is on a face's boundary lies on it, so the midpoint decides.
128 let middle = p + d * ((low + high) / 2)
129 return [edgesA, edgesB].allSatisfy { edges in
130 edges.allSatisfy { dot($0.inward, middle - $0.corner) > contactTolerance }
131 }
132}
Packages/FoldKit/Sources/Folding/LayerOrder.swift added +304
@@ -0,0 +1,304 @@
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 private struct Triple: Sendable {
32 let f: Int, g: Int, s: Int
33 }
34
35 private 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.
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.movingFaceUnion
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 let diagonal = boundingBoxDiagonal(positions)
115 let tolerance = diagonal * relativeTolerance
116 let offPlane = diagonal * sin(clusterAngle * .pi / 180)
117 let cosine = cos(clusterAngle * .pi / 180)
118
119 func withinPlane(_ face: Int, of other: Int) -> Bool {
120 let corner = positions[faces[other][0]]
121 return faces[face].allSatisfy { abs(dot(positions[$0] - corner, normals[other])) <= offPlane }
122 }
123 func linked(_ a: Int, _ b: Int) -> Bool {
124 guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= cosine,
125 withinPlane(a, of: b), withinPlane(b, of: a) else { return false }
126 let (u, v) = planeBasis(normals[a])
127 let project = { (face: Int) in faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
128 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
129 }
130
131 return components(faces.count, linked: linked).map { members in
132 CoplanarCluster(faces: backToFront(members, normals: normals, viewDirection: viewDirection))
133 }
134 }
135
136 /// Whether the two orders relate every pair they share the same way, in the form a rigid
137 /// motion leaves unchanged, ignoring pairs with a face in `movingFaces`.
138 public func agreesWith(_ other: LayerOrder, ignoring movingFaces: Set<Int>) -> Bool {
139 invariant.allSatisfy { pair, s in
140 movingFaces.contains(pair[0]) || movingFaces.contains(pair[1]) || (other.invariant[pair] ?? s) == s
141 }
142 }
143
144 /// `members`, in index order, topologically sorted so that every face comes after the faces
145 /// behind it, taking the smallest ready face first. The triples are read against one normal for
146 /// the whole cluster, its smallest face's, so that faces a little off parallel cannot disagree
147 /// about which side the camera is on.
148 private func backToFront(_ members: [Int], normals: [SIMD3<Double>], viewDirection: SIMD3<Double>) -> [Int] {
149 guard members.count > 1 else { return members }
150 let reference = normals[members[0]]
151 let cameraOnReferenceSide = dot(reference, viewDirection) < 0
152 let inCluster = Set(members)
153
154 var inFront: [Int: Set<Int>] = [:]
155 for t in triples where inCluster.contains(t.f) && inCluster.contains(t.g) {
156 let gAlongReference = dot(normals[t.g], reference) > 0
157 let fOnReferenceSide = (t.s > 0) == gAlongReference
158 let (back, front) = fOnReferenceSide == cameraOnReferenceSide ? (t.g, t.f) : (t.f, t.g)
159 inFront[back, default: []].insert(front)
160 }
161 var behind = Dictionary(uniqueKeysWithValues: members.map { ($0, 0) })
162 for fronts in inFront.values {
163 for f in fronts { behind[f]! += 1 }
164 }
165
166 var remaining = members
167 var sorted: [Int] = []
168 while !remaining.isEmpty {
169 // two sources can together order a cluster in a cycle; the smallest remaining face breaks it
170 let i = remaining.firstIndex { behind[$0] == 0 } ?? 0
171 let face = remaining.remove(at: i)
172 sorted.append(face)
173 for f in inFront[face] ?? [] { behind[f]! -= 1 }
174 }
175 return sorted
176 }
177}
178
179/// The most faces whose open interiors cover one point, over each group of coincident faces. A
180/// flat sheet is 1.
181///
182/// Each group's outlines are projected onto its plane and every outline is cut by the edge lines
183/// of the others, so each piece lies wholly inside or outside every face; the count is taken at
184/// each piece's centroid.
185public func stackDepth(positions: [SIMD3<Double>], faces: [[Int]]) -> Int {
186 let normals = faceNormals(positions: positions, faces: faces)
187 let tolerance = boundingBoxDiagonal(positions) * relativeTolerance
188
189 func coincident(_ a: Int, _ b: Int) -> Bool {
190 guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= parallelCosine else {
191 return false
192 }
193 let corner = positions[faces[a][0]]
194 return faces[b].allSatisfy { abs(dot(positions[$0] - corner, normals[a])) <= tolerance }
195 }
196
197 var deepest = 0
198 for group in components(faces.count, linked: coincident) where normals[group[0]] != .zero {
199 let (u, v) = planeBasis(normals[group[0]])
200 let outlines = group.map { face in
201 counterclockwise(faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) })
202 }
203 let lines = outlines.flatMap { outline in
204 outline.indices.map { (outline[$0], outline[($0 + 1) % outline.count]) }
205 }
206 for outline in outlines {
207 var pieces = [outline]
208 for (a, b) in lines where length(b - a) > tolerance {
209 pieces = pieces.flatMap { split($0, along: a, b, tolerance: tolerance) }
210 }
211 for piece in pieces where area(piece) > tolerance * tolerance {
212 let c = centroid(piece)
213 deepest = max(deepest, outlines.filter { contains($0, c) }.count)
214 }
215 }
216 }
217 return deepest
218}
219
220// MARK: - Helpers
221
222/// The connected components of `linked` over `0..<count`, each in index order, ordered by their
223/// smallest member.
224private func components(_ count: Int, linked: (Int, Int) -> Bool) -> [[Int]] {
225 var component = Array<Int?>(repeating: nil, count: count)
226 var result: [[Int]] = []
227 for start in 0..<count where component[start] == nil {
228 component[start] = result.count
229 var members = [start], stack = [start]
230 while let a = stack.popLast() {
231 for b in 0..<count where component[b] == nil && linked(min(a, b), max(a, b)) {
232 component[b] = result.count
233 members.append(b)
234 stack.append(b)
235 }
236 }
237 result.append(members.sorted())
238 }
239 return result
240}
241
242private func boundingBoxDiagonal(_ points: [SIMD3<Double>]) -> Double {
243 guard let first = points.first else { return 0 }
244 return length(points.reduce(first, simd_max) - points.reduce(first, simd_min))
245}
246
247/// Two unit vectors spanning the plane with unit normal `n`.
248private func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) {
249 let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0)
250 let u = normalize(cross(n, helper))
251 return (u, cross(n, u))
252}
253
254private func signedArea(_ p: [SIMD2<Double>]) -> Double {
255 p.indices.reduce(0) { sum, i in
256 let a = p[i], b = p[(i + 1) % p.count]
257 return sum + (a.x * b.y - b.x * a.y) / 2
258 }
259}
260
261private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) }
262
263private func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
264 signedArea(p) < 0 ? p.reversed() : p
265}
266
267private func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> {
268 var sum = SIMD2<Double>.zero
269 for i in p.indices {
270 let a = p[i], b = p[(i + 1) % p.count]
271 sum += (a + b) * (a.x * b.y - b.x * a.y)
272 }
273 return sum / (6 * signedArea(p))
274}
275
276/// Whether `point` is in the open interior of the counterclockwise convex polygon `p`.
277private func contains(_ p: [SIMD2<Double>], _ point: SIMD2<Double>) -> Bool {
278 p.indices.allSatisfy { i in
279 let a = p[i], b = p[(i + 1) % p.count]
280 let side = b - a, offset = point - a
281 return side.x * offset.y - side.y * offset.x > 0
282 }
283}
284
285/// The convex polygon `p` cut in two by the line through `a` and `b`, or `p` alone when no
286/// corner lies more than `tolerance` to each side.
287private func split(_ p: [SIMD2<Double>], along a: SIMD2<Double>, _ b: SIMD2<Double>,
288 tolerance: Double) -> [[SIMD2<Double>]] {
289 let d = normalize(b - a)
290 let side = p.map { q in d.x * (q.y - a.y) - d.y * (q.x - a.x) }
291 guard let low = side.min(), let high = side.max(), low < -tolerance, high > tolerance else { return [p] }
292 var left: [SIMD2<Double>] = [], right: [SIMD2<Double>] = []
293 for i in p.indices {
294 let j = (i + 1) % p.count
295 if side[i] >= 0 { left.append(p[i]) }
296 if side[i] <= 0 { right.append(p[i]) }
297 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
298 let crossing = p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j]))
299 left.append(crossing)
300 right.append(crossing)
301 }
302 }
303 return [left, right]
304}
Packages/FoldKit/Tests/FoldingTests/InterpenetrationTests.swift added +48
@@ -0,0 +1,48 @@
1import Foundation
2import Testing
3import simd
4import FoldFormat
5import Folding
6import FoldKitTestSupport
7
8@Test func aCleanFoldHasNoIntersections() throws {
9 let (file, i) = try interpolator("half.fold", step: 1)
10 #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
11}
12
13@Test func twoFlapsFoldingIntoEachOtherAreDetected() throws {
14 // both thirds of the letter sheet valley-folded at once: they meet at the midline from ~120°
15 let (file, i) = try interpolatorForBothThirdsInFront()
16 #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
17}
18
19@Test func staggeredFlapsDoNotCollide() throws {
20 // the same two flaps on separate windows of t
21 let (file, i) = try interpolator("letter-staggered.fold", step: 1)
22 #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
23}
24
25@Test func aFaceSwingingThroughAFaceItSharesAVertexWithIsDetected() throws {
26 // built in code: fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4); moving triangle
27 // (0,0,0), (0,2,0), (-1,1,0) hinged on its edge along the y-axis, folding toward +z
28 let (file, i) = try interpolatorForSharedVertexSweep()
29 #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
30}
31
32@Test func coplanarFacesAreNotReportedAsIntersecting() throws {
33 let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
34 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
35 #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty)
36}
37
38@Test func edgeAdjacentFacesAreNotReportedAsIntersecting() throws {
39 let (file, i) = try interpolator("quarters.fold", step: 3)
40 #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty)
41}
42
43@Test func theReportedParameterIsWhereTheIntersectionBegins() throws {
44 let (file, i) = try interpolatorForBothThirdsInFront()
45 let found = interpenetrations(i, faces: file.facesVertices, samples: 64)
46 #expect(!found.isEmpty)
47 #expect(found.allSatisfy { abs($0.t - 2.0 / 3) <= 1.0 / 64 }) // the flaps meet at 120°
48}
Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift added +109
@@ -0,0 +1,109 @@
1import Foundation
2import Testing
3import simd
4import FoldFormat
5import Folding
6import FoldKitTestSupport
7
8let modelFixtures = ["half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold",
9 "letter-staggered.fold", "quarters.fold", "occlusion.fold"]
10
11@Test func tZeroReproducesTheStartFrame() throws {
12 let (file, i) = try interpolator("half.fold", step: 1)
13 #expect(zip(i.positions(at: 0), file.frames[0].verticesCoords)
14 .allSatisfy { simd_distance($0, $1) < 1e-12 })
15}
16
17@Test(arguments: modelFixtures)
18func tOneReproducesTheEndFrameForEveryStep(_ name: String) throws {
19 let file = try FoldFile(contentsOf: fixture(name))
20 for step in try readSteps(file) {
21 let i = FoldInterpolator(file: file, step: step)
22 #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords)
23 .allSatisfy { simd_distance($0, $1) < 1e-9 }, "\(name) step \(step.index)")
24 }
25}
26
27@Test(arguments: modelFixtures)
28func everyEdgeLengthIsPreservedThroughoutEveryStep(_ name: String) throws {
29 let file = try FoldFile(contentsOf: fixture(name))
30 for step in try readSteps(file) {
31 let i = FoldInterpolator(file: file, step: step)
32 for t in stride(from: 0.0, through: 1.0, by: 0.05) {
33 #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-9,
34 "\(name) step \(step.index) t \(t)")
35 }
36 }
37}
38
39@Test func verticesOnTheAxisDoNotMove() throws {
40 let (file, i) = try interpolator("half.fold", step: 1)
41 for v in [1, 4] {
42 #expect(simd_distance(i.positions(at: 0.37)[v], file.frames[0].verticesCoords[v]) < 1e-12)
43 }
44}
45
46@Test func aValleyFoldRisesTowardTheViewerAndAMountainFoldFallsAway() throws {
47 let (_, valley) = try interpolator("half.fold", step: 1)
48 let (_, mountain) = try interpolator("mountain.fold", step: 1)
49 #expect(valley.positions(at: 0.5)[2].z > 0)
50 #expect(mountain.positions(at: 0.5)[2].z < 0)
51}
52
53@Test func multiAxisStepMovesEverySetOnTheSharedParameter() throws {
54 let (file, i) = try interpolator("letter.fold", step: 1)
55 let start = file.frames[0].verticesCoords, mid = i.positions(at: 0.5)
56 #expect(simd_distance(mid[0], start[0]) > 0.1) // left flap
57 #expect(simd_distance(mid[3], start[3]) > 0.1) // right flap
58}
59
60@Test func foldAndUnfoldPassesThroughThePeakAndReturns() throws {
61 let (file, i) = try interpolator("quarters.fold", step: 1)
62 #expect(simd_distance(i.positions(at: 0.5)[2], SIMD3(0, 0, 0)) < 1e-9)
63 #expect(zip(i.positions(at: 1), file.frames[0].verticesCoords)
64 .allSatisfy { simd_distance($0, $1) < 1e-9 })
65}
66
67@Test func aCoupledVertexStaysWholeThroughout() throws {
68 // decision 0001, case 3: curves from the closed form, sampled at 257 points
69 let file = degreeFourVertex()
70 let i = FoldInterpolator(file: file, step: try readSteps(file)[0])
71 for n in 0...1024 {
72 #expect(maxEdgeLengthDrift(i.positions(at: Double(n) / 1024), file) < 1e-6)
73 }
74 #expect(zip(i.positions(at: 1), file.frames[1].verticesCoords)
75 .allSatisfy { simd_distance($0, $1) < 1e-9 })
76}
77
78@Test func theSameVertexWithLinearAnglesTears() throws {
79 // the control: drop the curve and the paper does not hold together
80 let file = degreeFourVertex(linear: true)
81 let i = FoldInterpolator(file: file, step: try readSteps(file)[0])
82 #expect(maxEdgeLengthDrift(i.positions(at: 0.5), file) > 0.1)
83}
84
85@Test func aStaggeredAxisMovesOnlyInItsWindow() throws {
86 let (file, i) = try interpolator("letter-staggered.fold", step: 1)
87 let start = file.frames[0].verticesCoords
88 #expect(simd_distance(i.positions(at: 0.25)[3], start[3]) < 1e-12) // right flap waits
89 #expect(simd_distance(i.positions(at: 0.5)[0], SIMD3(2, 0, 0)) < 1e-9) // left flap down
90}
91
92@Test func turnOverRotatesTheModelRigidly() throws {
93 let (_, i) = try interpolator("half.fold", step: 2)
94 #expect(pairwiseDistancesAgree(i.positions(at: 0.5), i.positions(at: 0)))
95 #expect(i.positions(at: 0.5).contains { $0.z != 0 })
96}
97
98@Test func interpolationFitsInAFrameBudget() throws {
99 let file = gridSheet(cells: 12) // built in code: a 12×12 grid, one fold down the middle
100 let i = FoldInterpolator(file: file, step: try readSteps(file)[0])
101 let elapsed = ContinuousClock().measure {
102 for n in 0..<1000 { _ = i.positions(at: Double(n) / 1000) }
103 }
104 #expect(elapsed / 1000 < .milliseconds(1))
105}
106
107@Test func theGridSheetIsAValidFile() {
108 #expect(validate(gridSheet(cells: 12)).isEmpty)
109}
Packages/FoldKit/Tests/FoldingTests/LayerOrderTests.swift added +203
@@ -0,0 +1,203 @@
1import Testing
2import simd
3import FoldFormat
4import Folding
5import FoldKitTestSupport
6
7let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)]
8let up3 = up2 + [SIMD3(0, 0, 1)]
9
10@Test func twoStackedCoplanarFacesFormOneClusterOrderedFarthestFirst() throws {
11 let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) // 0 above 1
12 let c = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(),
13 viewDirection: SIMD3(0, 0, -1))
14 #expect(c.count == 1)
15 #expect(c[0].faces == [1, 0])
16}
17
18@Test func orbitingUnderneathReversesTheClusterOrder() throws {
19 let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2)
20 let above = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(),
21 viewDirection: SIMD3(0, 0, -1))
22 let below = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(),
23 viewDirection: SIMD3(0, 0, 1))
24 #expect(above[0].faces == below[0].faces.reversed())
25}
26
27@Test func facesSeparatedInSpaceFormSeparateClusters() throws {
28 let order = try LayerOrder(faceOrders: [], normals: up2)
29 #expect(order.clusters(positions: separatedSquarePositions(), faces: twoSquares(),
30 viewDirection: SIMD3(0, 0, -1)).count == 2)
31}
32
33@Test func unorderedCoplanarFacesKeepIndexOrder() throws {
34 let order = try LayerOrder(faceOrders: [], normals: up3)
35 #expect(order.clusters(positions: threeStackedPositions(), faces: threeSquares(),
36 viewDirection: SIMD3(0, 0, -1))[0].faces == [0, 1, 2])
37}
38
39@Test func anArrivingFlapJoinsTheStackItLandsOn() throws {
40 // letter-sequential step 2 at 179.5°: f2 is half a degree above f0 and f1
41 let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2)
42 let c = try LayerOrder.active(for: step, in: file)
43 .clusters(positions: i.positions(at: 179.5 / 180), faces: file.facesVertices,
44 viewDirection: SIMD3(0, 0, -1))
45 #expect(c.contains { Set($0.faces) == [0, 1, 2] && $0.faces.last == 2 })
46}
47
48@Test func aFlapAtThirtyDegreesIsItsOwnCluster() throws {
49 let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2)
50 let c = try LayerOrder.active(for: step, in: file)
51 .clusters(positions: i.positions(at: 150.0 / 180), faces: file.facesVertices,
52 viewDirection: SIMD3(0, 0, -1))
53 #expect(c.contains { $0.faces == [2] })
54}
55
56@Test func aFoldAndUnfoldPeakIsOrderedByItsMidFoldOrder() throws {
57 // quarters step 1 at the peak: f2 lies on f3 and f1 on f0, the moving faces on top
58 let (file, step, i) = try interpolatorWithStep("quarters.fold", step: 1)
59 let c = try LayerOrder.active(for: step, in: file)
60 .clusters(positions: i.positions(at: 0.5), faces: file.facesVertices,
61 viewDirection: SIMD3(0, 0, -1))
62 let left = try #require(c.first { $0.faces.contains(3) })
63 #expect(left.faces.firstIndex(of: 2)! > left.faces.firstIndex(of: 3)!)
64}
65
66@Test func aPageTurningOverAStillLayerStaysInFrontOfItThroughoutTheFold() throws {
67 // S under the hinge, M turning over onto N; the end frame's [0, 2, 1] is written against M's
68 // normal at the end, opposite to its normal at the start
69 let (file, step) = pageTurnOverStillLayer()
70 let order = try LayerOrder.active(for: step, in: file)
71 let interpolator = FoldInterpolator(file: file, step: step)
72 for degrees in [0.5, 179.5] {
73 let c = order.clusters(positions: interpolator.positions(at: degrees / 180), faces: file.facesVertices,
74 viewDirection: SIMD3(0, 0, -1))
75 let stack = try #require(c.first { $0.faces.contains(0) })
76 #expect(stack.faces.contains(2) && stack.faces.firstIndex(of: 2)! > stack.faces.firstIndex(of: 0)!,
77 "\(degrees)°: \(c.map(\.faces))")
78 }
79}
80
81@Test func aFlapLeavingAStackIsOrderedByTheStartFrame() throws {
82 // frame 2 is flat and orders nothing, so frame 1's order must apply as f0 lifts off f1
83 let (file, step) = halfUnfolded()
84 let c = try LayerOrder.active(for: step, in: file)
85 .clusters(positions: FoldInterpolator(file: file, step: step).positions(at: 0.01),
86 faces: file.facesVertices, viewDirection: SIMD3(0, 0, -1))
87 #expect(c.map(\.faces) == [[1, 0]])
88}
89
90@Test func cyclicOrderThrows() {
91 #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) {
92 try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3)
93 }
94}
95
96@Test func aRawCycleThatNormalisesAwayIsAccepted() {
97 // f0 and f2 face down: these triples say f1 < f0, f1 < f2, f2 < f0
98 #expect(throws: Never.self) {
99 try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]],
100 normals: [SIMD3(0, 0, -1), SIMD3(0, 0, 1), SIMD3(0, 0, -1)])
101 }
102}
103
104@Test func consecutiveOrderingsAgreeAwayFromTheMovingFaces() throws {
105 let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
106 for step in try readSteps(file) {
107 let start = try LayerOrder(faceOrders: file.frames[step.index - 1].faceOrders,
108 normals: faceNormals(file.frames[step.index - 1], file))
109 let end = try LayerOrder(faceOrders: file.frames[step.index].faceOrders,
110 normals: faceNormals(file.frames[step.index], file))
111 #expect(start.agreesWith(end, ignoring: step.movingFaceUnion), "step \(step.index)")
112 }
113}
114
115@Test func stackDepthCountsTheLayersOverOnePoint() throws {
116 let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
117 #expect(stackDepth(positions: file.frames[2].verticesCoords, faces: file.facesVertices) == 3)
118}
119
120@Test func stackDepthOfAFlatSheetIsOne() throws {
121 // four faces meet at the centre vertex
122 let file = try FoldFile(contentsOf: fixture("quarters.fold"))
123 #expect(stackDepth(positions: file.frames[0].verticesCoords, faces: file.facesVertices) == 1)
124}
125
126/// S, f0, a 2 × 1 face at z = 0, under a 2 × 1 top layer of N, f1, on x ∈ [0, 1] and M, f2, on
127/// x ∈ [1, 2], hinged at x = 1. Step 1 valley folds M over onto N.
128private func pageTurnOverStillLayer() -> (FoldFile, FoldStep) {
129 let start: [SIMD3<Double>] = [
130 SIMD3(0, 0, 0), SIMD3(2, 0, 0), SIMD3(2, 1, 0), SIMD3(0, 1, 0),
131 SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(2, 1, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0),
132 ]
133 var end = start
134 end[6] = SIMD3(0, 0, 0)
135 end[7] = SIMD3(0, 1, 0)
136 let boundary = Array(repeating: EdgeAssignment.boundary, count: 10)
137 let file = FoldFile(
138 fileSpec: 1.2,
139 fileAuthor: "Traditional",
140 edgesVertices: [[0, 1], [1, 2], [2, 3], [3, 0],
141 [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 4], [5, 8]],
142 facesVertices: [[0, 1, 2, 3], [4, 5, 8, 9], [5, 6, 7, 8]],
143 edgesFirstCreasedAtStep: Array(repeating: nil, count: 10) + [1],
144 frames: [
145 FoldFrame(verticesCoords: start, edgesAssignment: boundary + [.flat],
146 edgesFoldAngle: Array(repeating: 0, count: 11),
147 faceOrders: [[0, 1, -1], [0, 2, -1]]),
148 // normals +z, +z, −z: S below N, S below M, N below M
149 FoldFrame(verticesCoords: end, edgesAssignment: boundary + [.valley],
150 edgesFoldAngle: Array(repeating: 0, count: 10) + [180],
151 faceOrders: [[0, 1, -1], [0, 2, 1], [1, 2, 1]]),
152 ]
153 )
154 let step = FoldStep(
155 index: 1,
156 kind: .fold,
157 instruction: "Turn the page over.",
158 // M traverses the hinge from v8 down to v5
159 axes: [FoldAxis(edge: 10, origin: SIMD3(1, 0, 0), direction: SIMD3(0, -1, 0), movingFaces: [2],
160 startAngle: 0, endAngle: 180)],
161 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
162 )
163 return (file, step)
164}
165
166/// `half.fold`'s sheet with its faces listed right half first, so the flap is f0. Step 1 valley
167/// folds f0 over f1; step 2 unfolds it flat again.
168private func halfUnfolded() -> (FoldFile, FoldStep) {
169 let flat: [SIMD3<Double>] = [
170 SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(2, 2, 0), SIMD3(1, 2, 0), SIMD3(0, 2, 0),
171 ]
172 var folded = flat
173 folded[2] = SIMD3(0, 0, 0)
174 folded[3] = SIMD3(0, 2, 0)
175 let boundary = Array(repeating: EdgeAssignment.boundary, count: 6)
176 func frame(_ points: [SIMD3<Double>], angle: Double, faceOrders: [[Int]]) -> FoldFrame {
177 FoldFrame(verticesCoords: points, edgesAssignment: boundary + [angle == 0 ? .flat : .valley],
178 edgesFoldAngle: Array(repeating: 0, count: 6) + [angle], faceOrders: faceOrders)
179 }
180 let file = FoldFile(
181 fileSpec: 1.2,
182 fileAuthor: "Traditional",
183 edgesVertices: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [1, 4]],
184 facesVertices: [[1, 2, 3, 4], [0, 1, 4, 5]],
185 edgesFirstCreasedAtStep: Array(repeating: nil, count: 6) + [1],
186 frames: [
187 frame(flat, angle: 0, faceOrders: []),
188 // f0 faces −z, f1 faces +z: f0 on top
189 frame(folded, angle: 180, faceOrders: [[0, 1, 1]]),
190 frame(flat, angle: 0, faceOrders: []),
191 ]
192 )
193 let step = FoldStep(
194 index: 2,
195 kind: .fold,
196 instruction: "Unfold.",
197 // f0 traverses the crease from v4 down to v1
198 axes: [FoldAxis(edge: 6, origin: SIMD3(1, 0, 0), direction: SIMD3(0, -1, 0), movingFaces: [0],
199 startAngle: 180, endAngle: 0)],
200 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
201 )
202 return (file, step)
203}
docs/superpowers/plans/2026-10-19-fold.md +3 −3
@@ -843,7 +843,7 @@ git commit -m "Rigid interpolation on an axis tree with windows and solved curve
843843
844844The output is **clusters**, not one global draw order, because the renderer is hybrid: the depth buffer separates clusters and the active ordering orders within them. Two faces are linked when they overlap in projection, their normals are within 2° of each other's line, and each one's vertices lie within sin 2° × the model's bounding-box diagonal of the other's plane — the distance tolerance follows the angular one, since a flap hinged at the edge of a stack and 2° off it rises that far. A cluster is a connected group of linked faces. The tolerance is wide on purpose: a facet just leaving or just arriving on a stack is nearly coplanar with it, and the depth buffer alone would z-fight there.
845845
846Each triple's `s` is resolved against `viewDirection` using `g`'s normal **at the given positions**, since "above" in FOLD means "on the side `g`'s normal points toward", that reverses when the view crosses `g`'s plane, and a moving stack's normals turn with it. The fallback to frame n − 1 covers a flap leaving a stack, whose pairs exist only in the start frame; `foldAndUnfold` carries its peak order in `krz:faceOrders_midFold` (Task 2 requires it).
846Each triple's `s` is resolved against `viewDirection` using `g`'s normal **at the given positions**, since "above" in FOLD means "on the side `g`'s normal points toward", that reverses when the view crosses `g`'s plane, and a moving stack's normals turn with it. In `active`, a triple whose `g` moves in the step and whose `f` does not is rewritten into its reverse with that source's normals, so a moving/still pair is always read against the still face, whose normal does not turn. The fallback to frame n − 1 covers a flap leaving a stack, whose pairs exist only in the start frame; `foldAndUnfold` carries its peak order in `krz:faceOrders_midFold` (Task 2 requires it).
847847
848848- [ ] **Step 1: Write the failing tests**
849849
@@ -1164,7 +1164,7 @@ Expected: FAIL.
11641164
11651165- [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point**
11661166
1167Every face of the crease pattern must be counterclockwise with the sheet's top side up; rewind clockwise faces, or reject a pattern exported y-down, so that valley and mountain keep their meaning. Every solved curve has exactly 257 samples. Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Apply each step's rotations in order to produce the next frame. Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly.
1167Every face of the crease pattern must be counterclockwise with the sheet's top side up; rewind clockwise faces, or reject a pattern exported y-down, so that valley and mountain keep their meaning. Every solved curve has exactly 257 samples. Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Produce each step's end frame by building the step and calling `FoldInterpolator.positions(at: 1)` on it, so vertex ownership, carried axes and reorientation have one implementation; this needs a per-step axis reader that does not require a fully validated file. Add a validator rule: a moving face may not have an overlapping still face on the side it departs toward in frame n − 1, or on the side it arrives from in frame n (a flap leaving from under a layer that covers its hinge, which the interpenetration checker cannot see). Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly.
11681168
11691169- [ ] **Step 4: Run tests to verify they pass**
11701170
@@ -1615,7 +1615,7 @@ git commit -m "Diagram generation with layer-aware edge occlusion"
16151615
16161616Depth handling is **hybrid**. `faceOrders` is defined only for faces that overlap geometrically, so it says nothing about the facets separated in space that make up most of a folded model, and depth testing off everywhere would be wrong for them:
16171617
1618- clusters come from Task 5, already resolved against `camera.viewDirection`;
1618- clusters come from Task 5, already resolved against `camera.viewDirection`, over FOLD faces, never render-mesh triangles; compute membership once per *t* and re-sort only when the camera moves;
16191619- each cluster is drawn back-to-front in its order with depth test on (less-or-equal) and depth **writes off**, so stacked faces resolve by order rather than by z;
16201620- then the same cluster is drawn again **depth-only** (colour writes off), so that clusters drawn after it are hidden behind it. Without this pass a cluster writes no depth and anything drawn later draws over it.
16211621