Commit 366cfa80c6

366cfa80c66b3807947864bf05ded9a0cca2202a

parent: 70453b66a3

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-20 03:18 UTC

Folding: flag faces that leave or arrive through a still face

Ref #4

Layout: unified · split

Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +6 −1
@@ -51,7 +51,8 @@ private let interpenetrationSamples = 64
51/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the 51/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the
52/// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed 52/// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed
53/// and overridden, and the file so far validated and checked for interpenetration. A step that 53/// and overridden, and the file so far validated and checked for interpenetration. A step that
54/// names a `spine` is a reverse fold or sink and moves by `compilePop`'s open, pop and close. 54/// names a `spine` is a reverse fold or sink and moves by `compilePop`'s open, pop and close. The
55/// whole file is then checked with `layerMotionDefects`; a defect fails the step it names.
55public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile { 56public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile {
56 let flat = pattern.frames[0] 57 let flat = pattern.frames[0]
57 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 { 58 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 {
@@ -73,6 +74,10 @@ public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile
73 viewpoint = step.viewpoint ?? viewpoint 74 viewpoint = step.viewpoint ?? viewpoint
74 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment) 75 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment)
75 } 76 }
77 let motion = layerMotionDefects(file)
78 if case .movesThroughStillFace(let n, _, _)? = motion.first {
79 throw CompileError.stepFailed(step: n, defects: motion)
80 }
76 81
77 let last = file.frames[file.frames.count - 1] 82 let last = file.frames[file.frames.count - 1]
78 for e in file.edgesVertices.indices 83 for e in file.edgesVertices.indices
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +3
@@ -24,6 +24,9 @@ public enum FoldDefect: Equatable, Sendable {
24 /// A non-rigid step without a pop, or a pop whose `popped` lacks a position per vertex or 24 /// A non-rigid step without a pop, or a pop whose `popped` lacks a position per vertex or
25 /// whose phases are not 0 < p0 < p1 < 1. 25 /// whose phases are not 0 < p0 < p1 < 1.
26 case popMalformed(step: Int) 26 case popMalformed(step: Int)
27 /// In step `step`, the face `moving` departs toward the still face `still` it overlaps in
28 /// frame n − 1, or arrives from the side of it opposite the one frame n's order gives.
29 case movesThroughStillFace(step: Int, moving: Int, still: Int)
27} 30}
28 31
29/// Lengths are compared to within this fraction of the sheet's longer side. 32/// Lengths are compared to within this fraction of the sheet's longer side.
Packages/FoldKit/Sources/Folding/LayerMotion.swift added +173
@@ -0,0 +1,173 @@
1import FoldFormat
2import simd
3
4/// How long after a face starts moving, and before it stops, its side of a still face is read, as
5/// a fraction of the window of the axis that starts or stops it. The compiler's layer-order guess
6/// reads arrivals at the same moment.
7private let lead = 1e-3
8/// Two unit normals whose dot product's magnitude reaches this lie on one line.
9private let parallelCosine = 1 - 1e-9
10/// Lengths are compared to within this fraction of the sheet's longer side.
11private let relativeTolerance = 1e-6
12/// A face closer than this fraction of the sheet's size to a still face's plane is on neither side.
13private let separationTolerance = 1e-9
14
15/// Faces that pass through a still face as they start or finish moving: the coplanar contact that
16/// the validator, which reads one frame at a time, and the interpenetration checker, which skips
17/// coplanar faces, cannot see.
18///
19/// In step n, a moving face that overlaps a still face in frame n − 1 may not leave toward the
20/// side of it opposite the one frame n − 1's `faceOrders` give, read just after the face starts
21/// moving; a moving face that overlaps a still face in frame n may not arrive from the side
22/// opposite the one frame n's `faceOrders` give, read just before it stops. Pairs the orders do
23/// not relate are not checked. A face is still when none of the step's axes moves it, counting a
24/// non-rigid step's open and close axes, so the faces that open on the spine are moving.
25/// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the
26/// pop between is not. Turn-over and rotate steps move every face together and have no still face.
27///
28/// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped.
29public func layerMotionDefects(_ file: FoldFile) -> [FoldDefect] {
30 let size = sheetExtent(file)
31 var defects: [FoldDefect] = []
32 for n in file.frames.indices.dropFirst() {
33 guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else {
34 continue
35 }
36 let pop = step.nonRigid ? step.pop : nil
37 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes
38 let moving = (step.axes + departing + arriving).reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
39 let interpolator = FoldInterpolator(file: file, step: step)
40 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in
41 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) },
42 interpolator: interpolator, file: file, size: size)
43 }
44 var reported = Set<SIMD2<Int>>()
45 for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false)
46 where reported.insert(SIMD2(m, s)).inserted {
47 defects.append(.movesThroughStillFace(step: n, moving: m, still: s))
48 }
49 }
50 return defects
51}
52
53/// The pairs `(moving, still)` in which a face `axes` move is, just after it starts moving
54/// (`departure`) or just before it stops, on the side of a still face it overlaps in `frame`
55/// opposite the one `frame`'s orders give.
56private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, still: (Int) -> Bool,
57 interpolator: FoldInterpolator, file: FoldFile, size: Double) -> [(Int, Int)] {
58 let tolerance = size * relativeTolerance
59 let faces = file.facesVertices
60 let points = frame.verticesCoords
61 let normals = faceNormals(positions: points, faces: faces)
62 var axisOfFace: [Int: Int] = [:]
63 for (a, axis) in axes.enumerated() {
64 for f in axis.movingFaces { axisOfFace[f] = a }
65 }
66
67 var sampled: [Double: [SIMD3<Double>]] = [:]
68 var result: [(Int, Int)] = []
69 for m in axisOfFace.keys.sorted() where normals[m] != .zero {
70 var carriers: [Int] = [], a = axisOfFace[m]
71 while let axis = a, !carriers.contains(axis) {
72 carriers.append(axis)
73 a = axes[axis].parent
74 }
75 let windows = carriers.map { axes[$0].window }
76 let t: Double
77 if departure {
78 let w = windows.min { $0.lowerBound < $1.lowerBound }!
79 t = w.lowerBound + lead * (w.upperBound - w.lowerBound)
80 } else {
81 let w = windows.max { $0.upperBound < $1.upperBound }!
82 t = w.upperBound - lead * (w.upperBound - w.lowerBound)
83 }
84 let near = sampled[t] ?? interpolator.positions(at: t)
85 sampled[t] = near
86
87 for s in faces.indices where s != m && still(s) && normals[s] != .zero
88 && overlap(m, s, points, faces, normals, tolerance: tolerance) {
89 guard let side = side(of: m, from: s, frame.faceOrders, normals) else { continue }
90 let centre = overlapCentre(m, s, points, faces, normals)
91 let offset = dot(carry(centre, on: faces[m], from: points, to: near) - centre, normals[s])
92 if abs(offset) > size * separationTolerance && (offset > 0) != (side > 0) {
93 result.append((m, s))
94 }
95 }
96 }
97 return result
98}
99
100/// The side of face `s` along its normal on which `orders` put face `m`: +1 the side the normal
101/// points toward, −1 the other, nil when no triple relates them.
102private func side(of m: Int, from s: Int, _ orders: [[Int]], _ normals: [SIMD3<Double>]) -> Int? {
103 for t in orders where t.count == 3 && (t[2] == 1 || t[2] == -1) {
104 if t[0] == m && t[1] == s { return t[2] }
105 if t[0] == s && t[1] == m { return dot(normals[m], normals[s]) > 0 ? -t[2] : t[2] }
106 }
107 return nil
108}
109
110/// Whether faces `a` and `b` lie in one plane and their interiors overlap.
111private func overlap(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>],
112 tolerance: Double) -> Bool {
113 guard abs(dot(normals[a], normals[b])) >= parallelCosine else { return false }
114 let corner = points[faces[b][0]]
115 guard faces[a].allSatisfy({ abs(dot(points[$0] - corner, normals[b])) <= tolerance }) else { return false }
116 let (u, v) = planeBasis(normals[b])
117 let project = { (f: Int) in faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) } }
118 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
119}
120
121/// The centroid of the overlap of two coplanar faces, in the plane of `b`.
122private func overlapCentre(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]],
123 _ normals: [SIMD3<Double>]) -> SIMD3<Double> {
124 let n = normals[b]
125 let (u, v) = planeBasis(n)
126 let project = { (f: Int) in counterclockwise(faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) }) }
127 var common = project(a)
128 let clip = project(b)
129 for i in clip.indices where !common.isEmpty {
130 common = keepLeft(of: clip[i], clip[(i + 1) % clip.count], common)
131 }
132 let c = centroid(common)
133 return c.x * u + c.y * v + dot(points[faces[b][0]], n) * n
134}
135
136/// `point`, a point of the face with corners `corners` at `from`, where the same point of paper
137/// is at `to`. Both states place the face rigidly.
138private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>],
139 to: [SIMD3<Double>]) -> SIMD3<Double> {
140 let first = corners[0]
141 let far = corners.max { distance(from[$0], from[first]) < distance(from[$1], from[first]) }!
142 func frame(_ p: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>) {
143 let u = normalize(p[far] - p[first])
144 let n = faceNormals(positions: p, faces: [corners])[0]
145 return (u, cross(n, u), n)
146 }
147 let (u, v, n) = frame(from), (u2, v2, n2) = frame(to)
148 let d = point - from[first]
149 return to[first] + dot(d, u) * u2 + dot(d, v) * v2 + dot(d, n) * n2
150}
151
152/// The part of convex polygon `p` to the left of the directed line from `a` to `b`.
153private func keepLeft(of a: SIMD2<Double>, _ b: SIMD2<Double>, _ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
154 let d = b - a
155 let side = p.map { d.x * ($0.y - a.y) - d.y * ($0.x - a.x) }
156 var result: [SIMD2<Double>] = []
157 for i in p.indices {
158 let j = (i + 1) % p.count
159 if side[i] >= 0 { result.append(p[i]) }
160 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
161 result.append(p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])))
162 }
163 }
164 return result
165}
166
167/// The longer side of frame 0's bounding box.
168private func sheetExtent(_ file: FoldFile) -> Double {
169 let points = file.frames[0].verticesCoords
170 let lower = points.dropFirst().reduce(points[0], simd_min)
171 let upper = points.dropFirst().reduce(points[0], simd_max)
172 return (upper - lower).max()
173}
Packages/FoldKit/Sources/Folding/LayerOrder.swift +3 −3
@@ -245,7 +245,7 @@ private func boundingBoxDiagonal(_ points: [SIMD3<Double>]) -> Double {
245} 245}
246 246
247/// Two unit vectors spanning the plane with unit normal `n`. 247/// Two unit vectors spanning the plane with unit normal `n`.
248private func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) { 248func 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) 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)) 250 let u = normalize(cross(n, helper))
251 return (u, cross(n, u)) 251 return (u, cross(n, u))
@@ -260,11 +260,11 @@ private func signedArea(_ p: [SIMD2<Double>]) -> Double {
260 260
261private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) } 261private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) }
262 262
263private func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] { 263func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
264 signedArea(p) < 0 ? p.reversed() : p 264 signedArea(p) < 0 ? p.reversed() : p
265} 265}
266 266
267private func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> { 267func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> {
268 var sum = SIMD2<Double>.zero 268 var sum = SIMD2<Double>.zero
269 for i in p.indices { 269 for i in p.indices {
270 let a = p[i], b = p[(i + 1) % p.count] 270 let a = p[i], b = p[(i + 1) % p.count]
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +15
@@ -210,3 +210,18 @@ private func splitLetterPattern() -> FoldFile {
210 try compile(script, pattern: degreeFourPattern()) 210 try compile(script, pattern: degreeFourPattern())
211 } 211 }
212} 212}
213
214@Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws {
215 // step 2's flap folds over the top, so it cannot end under f0
216 var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
217 let step = script.steps[1]
218 script = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [
219 script.steps[0],
220 ScriptStep(kind: step.kind, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
221 repeatOf: step.repeatOf,
222 faceOrders: [OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))]),
223 ])
224 #expect(throws: CompileError.stepFailed(step: 2, defects: [.movesThroughStillFace(step: 2, moving: 2, still: 0)])) {
225 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
226 }
227}
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +5
@@ -92,3 +92,8 @@ import FoldKitTestSupport
92 mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y) 92 mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y)
93 }) 93 })
94} 94}
95
96@Test func theReverseFoldMovesThroughNoStillFace() throws {
97 // the open phase departs from frame 1 and the close phase arrives at frame 2
98 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)
99}
Packages/FoldKit/Tests/FoldingTests/LayerMotionTests.swift added +38
@@ -0,0 +1,38 @@
1import Testing
2import FoldFormat
3import Folding
4import FoldKitTestSupport
5
6@Test func aFlapArrivingFromTheSideOppositeItsOrderIsFlagged() throws {
7 // frame 2 puts f2 between f0 and f1; f2 folds over the top, so it arrives from above f0
8 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
9 file.frames[2].faceOrders = [[0, 1, 1], [0, 2, -1], [1, 2, 1]]
10 // x = 1 is f2's edge, not its interior, so the taco rules do not catch it
11 #expect(validate(file).isEmpty)
12 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)])
13}
14
15@Test func aFlapDepartingTowardALayerAboveItIsFlagged() throws {
16 // step 3 unfolds f0 from under f2, which covers f0's hinge at x = 1
17 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
18 var points = file.frames[2].verticesCoords
19 points[0] = SIMD3(0, 0, 0)
20 points[7] = SIMD3(0, 3, 0)
21 var assignment = file.frames[2].edgesAssignment
22 assignment[8] = .flat
23 var angles = file.frames[2].edgesFoldAngle
24 angles[8] = 0
25 let step = StepRecord(kind: .fold, instruction: "Unfold the left third.",
26 axes: [AxisRecord(edge: 8, movingFaces: [0], startAngle: 180, endAngle: 0)],
27 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)))
28 file.frames.append(FoldFrame(verticesCoords: points, edgesAssignment: assignment, edgesFoldAngle: angles,
29 faceOrders: [[1, 2, 1]], step: step))
30 #expect(validate(file).isEmpty)
31 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 3, moving: 0, still: 2)])
32}
33
34@Test(arguments: ["square", "half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters",
35 "occlusion"])
36func noSyntheticModelMovesThroughAStillFace(_ name: String) throws {
37 #expect(layerMotionDefects(try FoldFile(contentsOf: fixture("\(name).fold"))).isEmpty)
38}