Commit 5e0fe5ad34

5e0fe5ad34be52c2a98fc423377f7e7a5ed75922

parent: 0ce8c8b65a

Verified · cmc

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

foldc: coincident-axis guard, per-step layer motion, crease errors

Reject an edge on a named crease's line that becomes its own axis under a
scripted angle other than ±180. Run layerMotionDefects per step and throw
on any defect. unresolvedCrease and missingAngle carry the crease
reference; noCreases and invalidSpine are their own cases. Break arrival
ties by axis index in the guess and the arrival check. structurallyEqual
compares pops within the tolerance. Correct the PopCompiler, LayerMotion
and Helpers comments.

Ref #4

Layout: unified · split

Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +33 −19
@@ -3,9 +3,12 @@ import Folding
3import simd 3import simd
4 4
5public enum CompileError: Error, Equatable, Sendable { 5public enum CompileError: Error, Equatable, Sendable {
6 /// A crease names no edge, a boundary edge or an edge already named in the step, or the driver 6 /// A crease, driver or spine names no edge or a boundary edge, a crease names an edge already
7 /// is not one of the step's creases. 7 /// named in the step, or the driver is not one of the step's creases. `crease` is the
8 case unresolvedCrease(step: Int) 8 /// reference as the script gives it.
9 case unresolvedCrease(step: Int, crease: CreaseRef)
10 /// A fold or fold-and-unfold step names no crease.
11 case noCreases(step: Int)
9 /// A `movingSide` point lies on no face, every region has one, or a crease does not separate 12 /// A `movingSide` point lies on no face, every region has one, or a crease does not separate
10 /// a moving region from the rest. 13 /// a moving region from the rest.
11 case unresolvedMovingSide(step: Int) 14 case unresolvedMovingSide(step: Int)
@@ -21,8 +24,9 @@ public enum CompileError: Error, Equatable, Sendable {
21 case curveTooCoarse(step: Int) 24 case curveTooCoarse(step: Int)
22 /// A face of the crease pattern is clockwise seen from +z. 25 /// A face of the crease pattern is clockwise seen from +z.
23 case clockwiseFace(face: Int) 26 case clockwiseFace(face: Int)
24 /// A crease has no angle in the script and is neither `V` nor `M` in the crease pattern. 27 /// `crease`, or an edge on its line, has no angle in the script and is neither `V` nor `M` in
25 case missingAngle(step: Int) 28 /// the crease pattern.
29 case missingAngle(step: Int, crease: CreaseRef)
26 /// `angles`, `peakAngles` or `windows` does not have one entry per crease. 30 /// `angles`, `peakAngles` or `windows` does not have one entry per crease.
27 case creaseListMismatch(step: Int) 31 case creaseListMismatch(step: Int)
28 /// An axis the step solves to close a loop has a scripted window other than the driver's. 32 /// An axis the step solves to close a loop has a scripted window other than the driver's.
@@ -31,6 +35,11 @@ public enum CompileError: Error, Equatable, Sendable {
31 case popTooStrained(step: Int, strain: Double) 35 case popTooStrained(step: Int, strain: Double)
32 /// A reverse fold or sink names no `spine` to open on. 36 /// A reverse fold or sink names no `spine` to open on.
33 case missingSpine(step: Int) 37 case missingSpine(step: Int)
38 /// A `spine` is given on a step that is not a fold, or is not folded flat in frame n − 1.
39 case invalidSpine(step: Int)
40 /// An edge on a named crease's line, in another layer, becomes an axis of its own while the
41 /// named crease's scripted angle is not ±180; its angle is not derived.
42 case coincidentAxisAngle(step: Int, edge: Int)
34} 43}
35 44
36/// Samples in a solved curve, evenly spaced over its window. 45/// Samples in a solved curve, evenly spaced over its window.
@@ -50,9 +59,9 @@ private let interpenetrationSamples = 64
50/// 59///
51/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the 60/// 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 61/// 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 62/// and overridden, and the file so far validated and checked with `layerMotionDefects` and for
54/// names a `spine` is a reverse fold or sink and moves by `compilePop`'s open, pop and close. The 63/// interpenetration. A step that names a `spine` is a reverse fold or sink and moves by
55/// whole file is then checked with `layerMotionDefects`; a defect fails the step it names. 64/// `compilePop`'s open, pop and close.
56public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile { 65public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile {
57 let flat = pattern.frames[0] 66 let flat = pattern.frames[0]
58 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 { 67 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 {
@@ -74,10 +83,6 @@ public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile
74 viewpoint = step.viewpoint ?? viewpoint 83 viewpoint = step.viewpoint ?? viewpoint
75 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment) 84 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment)
76 } 85 }
77 let motion = layerMotionDefects(file)
78 if case .movesThroughStillFace(let n, _, _)? = motion.first {
79 throw CompileError.stepFailed(step: n, defects: motion)
80 }
81 86
82 let last = file.frames[file.frames.count - 1] 87 let last = file.frames[file.frames.count - 1]
83 for e in file.edgesVertices.indices 88 for e in file.edgesVertices.indices
@@ -94,7 +99,7 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to
94 if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) { 99 if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) {
95 throw CompileError.missingSpine(step: n) 100 throw CompileError.missingSpine(step: n)
96 } 101 }
97 if script.spine != nil && script.kind != .fold { throw CompileError.unresolvedCrease(step: n) } 102 if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) }
98 let previous = file.frames[n - 1] 103 let previous = file.frames[n - 1]
99 104
100 var plan: FoldPlan? 105 var plan: FoldPlan?
@@ -176,6 +181,8 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to
176 181
177 let defects = validate(file) 182 let defects = validate(file)
178 guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) } 183 guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) }
184 let motion = layerMotionDefects(step: n, in: file)
185 guard motion.isEmpty else { throw CompileError.stepFailed(step: n, defects: motion) }
179 let collisions = step.nonRigid 186 let collisions = step.nonRigid
180 ? meshInterpenetrations(interpolator, samples: interpenetrationSamples) 187 ? meshInterpenetrations(interpolator, samples: interpenetrationSamples)
181 : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples) 188 : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples)
@@ -211,7 +218,8 @@ private struct FoldPlan {
211/// 218///
212/// Every edge that lies on a named crease's line in the start frame is cut too, so a crease 219/// Every edge that lies on a named crease's line in the start frame is cut too, so a crease
213/// through several layers folds each of them; one whose faces end up in the same region is not 220/// through several layers folds each of them; one whose faces end up in the same region is not
214/// creased. 221/// creased. One that becomes an axis of its own takes ±180 by the pattern's assignment, so its
222/// named crease must be scripted at ±180 or not at all.
215private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile, 223private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
216 _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan { 224 _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan {
217 let start = file.frames[n - 1] 225 let start = file.frames[n - 1]
@@ -221,15 +229,18 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
221 throw CompileError.creaseListMismatch(step: n) 229 throw CompileError.creaseListMismatch(step: n)
222 } 230 }
223 231
232 guard count > 0 else { throw CompileError.noCreases(step: n) }
224 let named = try script.creases.map { ref in 233 let named = try script.creases.map { ref in
225 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n) } 234 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) }
226 return e 235 return e
227 } 236 }
228 guard !named.isEmpty, Set(named).count == named.count else { throw CompileError.unresolvedCrease(step: n) } 237 if let repeated = named.indices.first(where: { named[..<$0].contains(named[$0]) }) {
238 throw CompileError.unresolvedCrease(step: n, crease: script.creases[repeated])
239 }
229 var driver = 0 240 var driver = 0
230 if let ref = script.driver { 241 if let ref = script.driver {
231 guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else { 242 guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else {
232 throw CompileError.unresolvedCrease(step: n) 243 throw CompileError.unresolvedCrease(step: n, crease: ref)
233 } 244 }
234 driver = i 245 driver = i
235 } 246 }
@@ -328,11 +339,14 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
328 let window = script.windows?[t.source] 339 let window = script.windows?[t.source]
329 let written = window == [0, 1] ? nil : window 340 let written = window == [0, 1] ? nil : window
330 func endAngle(_ list: [Double]?) throws -> Double { 341 func endAngle(_ list: [Double]?) throws -> Double {
331 if isNamed, let list { return list[t.source] } 342 if let list {
343 if isNamed { return list[t.source] }
344 if abs(list[t.source]) != 180 { throw CompileError.coincidentAxisAngle(step: n, edge: t.edge) }
345 }
332 switch finalAssignment[t.edge] { 346 switch finalAssignment[t.edge] {
333 case .valley: return 180 347 case .valley: return 180
334 case .mountain: return -180 348 case .mountain: return -180
335 default: throw CompileError.missingAngle(step: n) 349 default: throw CompileError.missingAngle(step: n, crease: script.creases[t.source])
336 } 350 }
337 } 351 }
338 if script.kind == .foldAndUnfold { 352 if script.kind == .foldAndUnfold {
Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift +6 −5
@@ -13,10 +13,10 @@ private let separationTolerance = 1e-9
13/// 13///
14/// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face 14/// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face
15/// that arrives last is placed on the side it arrives from: the pair is compared just before the 15/// that arrives last is placed on the side it arrives from: the pair is compared just before the
16/// last axis that moves them differently finishes, at the paper points that meet in the middle 16/// last axis that moves them differently finishes, the higher-indexed of axes that finish
17/// of their overlap. A moving set that has turned over arrives with its layers reversed. This is 17/// together, at the paper points that meet in the middle of their overlap. A moving set that has
18/// right for plain valley and mountain folds and wrong for a flap tucked between layers, which the 18/// turned over arrives with its layers reversed. This is right for plain valley and mountain
19/// script corrects with overrides. 19/// folds and wrong for a flap tucked between layers, which the script corrects with overrides.
20/// 20///
21/// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame. 21/// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame.
22public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] { 22public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] {
@@ -60,7 +60,8 @@ func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpol
60 var orders: [[Int]] = [] 60 var orders: [[Int]] = []
61 for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) { 61 for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) {
62 let differing = carriers(a).symmetricDifference(carriers(b)) 62 let differing = carriers(a).symmetricDifference(carriers(b))
63 guard let last = differing.max(by: { arrival(step.axes[$0].window) < arrival(step.axes[$1].window) }) else { 63 let last = differing.max { (arrival(step.axes[$0].window), $0) < (arrival(step.axes[$1].window), $1) }
64 guard let last else {
64 if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) } 65 if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) }
65 continue 66 continue
66 } 67 }
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift +13 −9
@@ -27,14 +27,16 @@ private let angleSamples = 256
27/// rigid step, and must arrive at `after`'s coordinates. 27/// rigid step, and must arrive at `after`'s coordinates.
28/// 28///
29/// The starting guess can lead the solver to another branch of the vertex's motion. Closing the 29/// The starting guess can lead the solver to another branch of the vertex's motion. Closing the
30/// loops does not catch that: every branch is closed. The check that the close reaches `after` 30/// loops does not catch that: every branch is closed. A branch is caught when the close does not
31/// catches a branch that ends elsewhere; one that ends on the same coordinates with the tip 31/// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the
32/// outside is caught by the validator's layer-order rules on frame n, and in general by the rule 32/// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixture's
33/// on the side a moving face departs toward and arrives from. 33/// test that the tip lands between the flap's layers covers that fixture. `layerMotionDefects`
34/// does not add a check here: frame n's orders for the faces the step's axes move are guessed
35/// from the same close, read near the same moment.
34/// 36///
35/// - Throws: `unresolvedCrease` when the spine names no edge or is not folded flat, 37/// - Throws: `unresolvedCrease` when the spine names no edge, `invalidSpine` when it is not
36/// `noRigidMotion` when the flap cannot open on its spine, `popped` does not close or the close 38/// folded flat, `noRigidMotion` when the flap cannot open on its spine, `popped` does not close
37/// does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%. 39/// or the close does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%.
38public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, 40public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame,
39 file: FoldFile) throws -> PopRecord { 41 file: FoldFile) throws -> PopRecord {
40 guard let reference = script.spine, let record = after.step else { 42 guard let reference = script.spine, let record = after.step else {
@@ -45,14 +47,16 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after
45 let tolerance = sheetExtent(file) * relativeTolerance 47 let tolerance = sheetExtent(file) * relativeTolerance
46 let openAngle = script.openAngle ?? defaultOpenAngle 48 let openAngle = script.openAngle ?? defaultOpenAngle
47 49
48 guard let named = resolve(reference, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n) } 50 guard let named = resolve(reference, file, edgeFaces) else {
51 throw CompileError.unresolvedCrease(step: n, crease: reference)
52 }
49 let ends = file.edgesVertices[named].map { before.verticesCoords[$0] } 53 let ends = file.edgesVertices[named].map { before.verticesCoords[$0] }
50 let spine = [named] + edgeFaces.indices.filter { e in 54 let spine = [named] + edgeFaces.indices.filter { e in
51 e != named && edgeFaces[e].count == 2 55 e != named && edgeFaces[e].count == 2
52 && file.edgesVertices[e].allSatisfy { onLine(before.verticesCoords[$0], ends[0], ends[1], tolerance) } 56 && file.edgesVertices[e].allSatisfy { onLine(before.verticesCoords[$0], ends[0], ends[1], tolerance) }
53 } 57 }
54 guard spine.allSatisfy({ abs(abs(before.edgesFoldAngle[$0]) - 180) <= angleSnapTolerance }) else { 58 guard spine.allSatisfy({ abs(abs(before.edgesFoldAngle[$0]) - 180) <= angleSnapTolerance }) else {
55 throw CompileError.unresolvedCrease(step: n) 59 throw CompileError.invalidSpine(step: n)
56 } 60 }
57 61
58 var group = Array(repeating: -1, count: faceCount) 62 var group = Array(repeating: -1, count: faceCount)
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +23 −7
@@ -328,8 +328,8 @@ public func compiled(_ name: String) throws -> FoldFile {
328} 328}
329 329
330/// Whether two files have the same metadata, topology, assignments, layer orders and steps, with 330/// Whether two files have the same metadata, topology, assignments, layer orders and steps, with
331/// coordinates and angles within `tolerance`. Face orders compare as sets; `file_creator` is 331/// coordinates, angles and pop phases within `tolerance`. Face orders compare as sets;
332/// ignored. 332/// `file_creator` is ignored.
333public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool { 333public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool {
334 guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor, 334 guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor,
335 a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices, 335 a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices,
@@ -369,10 +369,25 @@ private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) -
369 let view = { (v: Viewpoint) in [v.eye.x, v.eye.y, v.eye.z, v.up.x, v.up.y, v.up.z] } 369 let view = { (v: Viewpoint) in [v.eye.x, v.eye.y, v.eye.z, v.up.x, v.up.y, v.up.z] }
370 guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction, 370 guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction,
371 close(a.rotateDegrees, b.rotateDegrees, tolerance), a.turnOverAxis == b.turnOverAxis, 371 close(a.rotateDegrees, b.rotateDegrees, tolerance), a.turnOverAxis == b.turnOverAxis,
372 a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid, a.pop == b.pop, 372 a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid,
373 close(view(a.viewpoint), view(b.viewpoint), tolerance), 373 close(view(a.viewpoint), view(b.viewpoint), tolerance) else { return false }
374 a.axes.count == b.axes.count else { return false } 374 switch (a.pop, b.pop) {
375 return zip(a.axes, b.axes).allSatisfy { x, y in 375 case (nil, nil): break
376 case let (x?, y?): guard popsAgree(x, y, tolerance) else { return false }
377 default: return false
378 }
379 return axesAgree(a.axes, b.axes, tolerance)
380}
381
382private func popsAgree(_ a: PopRecord, _ b: PopRecord, _ tolerance: Double) -> Bool {
383 let flatten = { (points: [SIMD3<Double>]) in points.flatMap { [$0.x, $0.y, $0.z] } }
384 return a.spine == b.spine && close(a.openAngle, b.openAngle, tolerance) && close(a.phases, b.phases, tolerance)
385 && close(flatten(a.popped), flatten(b.popped), tolerance)
386 && axesAgree(a.openAxes, b.openAxes, tolerance) && axesAgree(a.closeAxes, b.closeAxes, tolerance)
387}
388
389private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double) -> Bool {
390 a.count == b.count && zip(a, b).allSatisfy { x, y in
376 x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent 391 x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent
377 && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance) 392 && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance)
378 && close(x.peakAngle, y.peakAngle, tolerance) 393 && close(x.peakAngle, y.peakAngle, tolerance)
@@ -453,7 +468,8 @@ private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -
453 openAngle: openAngle) 468 openAngle: openAngle)
454} 469}
455 470
456/// The repository's `Models/` directory, four levels above this package's `Sources/`. 471/// The repository's `Models/` directory: this file's path with its last five components, up to
472/// and including `Packages`, replaced by `Models`.
457private let modelsDirectory = URL(fileURLWithPath: #filePath) 473private let modelsDirectory = URL(fileURLWithPath: #filePath)
458 .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() 474 .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
459 .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models") 475 .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models")
Packages/FoldKit/Sources/Folding/LayerMotion.swift +27 −20
@@ -25,27 +25,35 @@ private let separationTolerance = 1e-9
25/// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the 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. 26/// pop between is not. Turn-over and rotate steps move every face together and have no still face.
27/// 27///
28/// Arrivals are read on the last axis to finish, the higher-indexed of axes that finish together,
29/// at the moment the compiler's layer-order guess reads them. In a rigid step the guess places
30/// the arriving face on the side it arrives from, so in a compiled file an arrival disagrees with
31/// frame n's orders only where the script overrides them.
32///
28/// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped. 33/// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped.
29public func layerMotionDefects(_ file: FoldFile) -> [FoldDefect] { 34public func layerMotionDefects(_ file: FoldFile) -> [FoldDefect] {
35 file.frames.indices.dropFirst().flatMap { layerMotionDefects(step: $0, in: file) }
36}
37
38/// `layerMotionDefects(_:)` for step `n` alone. `file` needs frames 0…n.
39public func layerMotionDefects(step n: Int, in file: FoldFile) -> [FoldDefect] {
40 guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else {
41 return []
42 }
30 let size = sheetExtent(file) 43 let size = sheetExtent(file)
44 let pop = step.nonRigid ? step.pop : nil
45 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes
46 let moving = (step.axes + departing + arriving).reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
47 let interpolator = FoldInterpolator(file: file, step: step)
48 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in
49 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) },
50 interpolator: interpolator, file: file, size: size)
51 }
31 var defects: [FoldDefect] = [] 52 var defects: [FoldDefect] = []
32 for n in file.frames.indices.dropFirst() { 53 var reported = Set<SIMD2<Int>>()
33 guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else { 54 for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false)
34 continue 55 where reported.insert(SIMD2(m, s)).inserted {
35 } 56 defects.append(.movesThroughStillFace(step: n, moving: m, still: s))
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 } 57 }
50 return defects 58 return defects
51} 59}
@@ -72,13 +80,12 @@ private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, st
72 carriers.append(axis) 80 carriers.append(axis)
73 a = axes[axis].parent 81 a = axes[axis].parent
74 } 82 }
75 let windows = carriers.map { axes[$0].window }
76 let t: Double 83 let t: Double
77 if departure { 84 if departure {
78 let w = windows.min { $0.lowerBound < $1.lowerBound }! 85 let w = carriers.map { axes[$0].window }.min { $0.lowerBound < $1.lowerBound }!
79 t = w.lowerBound + lead * (w.upperBound - w.lowerBound) 86 t = w.lowerBound + lead * (w.upperBound - w.lowerBound)
80 } else { 87 } else {
81 let w = windows.max { $0.upperBound < $1.upperBound }! 88 let w = axes[carriers.max { (axes[$0].window.upperBound, $0) < (axes[$1].window.upperBound, $1) }!].window
82 t = w.upperBound - lead * (w.upperBound - w.lowerBound) 89 t = w.upperBound - lead * (w.upperBound - w.lowerBound)
83 } 90 }
84 let near = sampled[t] ?? interpolator.positions(at: t) 91 let near = sampled[t] ?? interpolator.positions(at: t)
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +88 −5
@@ -57,8 +57,8 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th
57 } 57 }
58} 58}
59 59
60@Test func anUnresolvedCreaseNamesItsStep() { 60@Test func anUnresolvedCreaseNamesItsStepAndReference() {
61 #expect(throws: CompileError.unresolvedCrease(step: 2)) { 61 #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
62 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), 62 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
63 pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) 63 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
64 } 64 }
@@ -122,7 +122,7 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
122@Test func anUnassignedCreaseNeedsAnAngle() throws { 122@Test func anUnassignedCreaseNeedsAnAngle() throws {
123 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold")) 123 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
124 pattern.frames[0].edgesAssignment[6] = .flat 124 pattern.frames[0].edgesAssignment[6] = .flat
125 #expect(throws: CompileError.missingAngle(step: 1)) { 125 #expect(throws: CompileError.missingAngle(step: 1, crease: .betweenVertices(SIMD2(1, 0), SIMD2(1, 2)))) {
126 try compile(halfFold(kind: .foldAndUnfold), pattern: pattern) 126 try compile(halfFold(kind: .foldAndUnfold), pattern: pattern)
127 } 127 }
128} 128}
@@ -135,7 +135,7 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
135 135
136@Test func aSpineThatIsNotFoldedIsRejected() throws { 136@Test func aSpineThatIsNotFoldedIsRejected() throws {
137 // a flap opens on a spine folded flat in the frame the step starts from 137 // a flap opens on a spine folded flat in the frame the step starts from
138 #expect(throws: CompileError.unresolvedCrease(step: 1)) { 138 #expect(throws: CompileError.invalidSpine(step: 1)) {
139 try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) 139 try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
140 } 140 }
141} 141}
@@ -165,7 +165,32 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
165 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)], 165 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)],
166 movingSide: [SIMD2(1.5, 1)]), 166 movingSide: [SIMD2(1.5, 1)]),
167 ]) 167 ])
168 #expect(throws: CompileError.unresolvedCrease(step: 1)) { 168 #expect(throws: CompileError.unresolvedCrease(step: 1, crease: .edgeIndex(6))) {
169 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
170 }
171}
172
173@Test func aSpineOnAStepThatIsNotAFoldIsRejected() throws {
174 #expect(throws: CompileError.invalidSpine(step: 1)) {
175 try compile(halfFold(kind: .foldAndUnfold, spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
176 }
177}
178
179@Test func aDriverThatIsNotAStepCreaseIsUnresolved() throws {
180 let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
181 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6)],
182 movingSide: [SIMD2(1.5, 1)], driver: .edgeIndex(0)),
183 ])
184 #expect(throws: CompileError.unresolvedCrease(step: 1, crease: .edgeIndex(0))) {
185 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
186 }
187}
188
189@Test func aFoldWithNoCreaseIsRejected() throws {
190 let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
191 ScriptStep(kind: .fold, instruction: "Fold the right half.", movingSide: [SIMD2(1.5, 1)]),
192 ])
193 #expect(throws: CompileError.noCreases(step: 1)) {
169 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) 194 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
170 } 195 }
171} 196}
@@ -211,6 +236,48 @@ private func splitLetterPattern() -> FoldFile {
211 } 236 }
212} 237}
213 238
239/// A 4 × 1 strip with valley creases at x = 1 (e10) and x = 2 (e11) and a mountain at x = 3 (e12).
240/// Folded in half at x = 2, e12 lies on e10's line in a separate layer.
241private func stripPattern() -> FoldFile {
242 let points: [SIMD3<Double>] = [
243 SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(3, 0, 0), SIMD3(4, 0, 0),
244 SIMD3(4, 1, 0), SIMD3(3, 1, 0), SIMD3(2, 1, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0),
245 ]
246 let assignment = Array(repeating: EdgeAssignment.boundary, count: 10) + [.valley, .valley, .mountain]
247 return FoldFile(fileSpec: 1.2, fileTitle: "Strip", fileAuthor: "Traditional", fileClasses: ["creasePattern"],
248 edgesVertices: (0..<10).map { [$0, ($0 + 1) % 10] } + [[1, 8], [2, 7], [3, 6]],
249 facesVertices: [[0, 1, 8, 9], [1, 2, 7, 8], [2, 3, 6, 7], [3, 4, 5, 6]],
250 edgesFirstCreasedAtStep: Array(repeating: nil, count: 13),
251 frames: [FoldFrame(verticesCoords: points, edgesAssignment: assignment,
252 edgesFoldAngle: Array(repeating: 0, count: 13), faceOrders: [])])
253}
254
255@Test func aCoincidentAxisUnderAScriptedAngleIsRejected() throws {
256 // step 2's crease at x = 1 cuts both layers; the upper layer's edge, e12, is an axis of its own
257 let script = FoldScript(creasePattern: "", title: "Strip", steps: [
258 ScriptStep(kind: .fold, instruction: "Valley fold in half.", creases: [.betweenVertices(SIMD2(2, 0), SIMD2(2, 1))],
259 movingSide: [SIMD2(3, 0.5)]),
260 ScriptStep(kind: .fold, instruction: "Fold the end up to stand.",
261 creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1))],
262 movingSide: [SIMD2(0.5, 0.5), SIMD2(3.5, 0.5)], angles: [90]),
263 ])
264 #expect(throws: CompileError.coincidentAxisAngle(step: 2, edge: 12)) {
265 try compile(script, pattern: stripPattern())
266 }
267}
268
269@Test func aCoincidentAxisFoldedFlatCompiles() throws {
270 let script = FoldScript(creasePattern: "", title: "Strip", steps: [
271 ScriptStep(kind: .fold, instruction: "Valley fold in half.", creases: [.betweenVertices(SIMD2(2, 0), SIMD2(2, 1))],
272 movingSide: [SIMD2(3, 0.5)]),
273 ScriptStep(kind: .fold, instruction: "Fold the end over.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1))],
274 movingSide: [SIMD2(0.5, 0.5), SIMD2(3.5, 0.5)], angles: [180]),
275 ])
276 let out = try compile(script, pattern: stripPattern())
277 #expect(out.frames[2].edgesFoldAngle[10] == 180)
278 #expect(out.frames[2].edgesFoldAngle[12] == -180)
279}
280
214@Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws { 281@Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws {
215 // step 2's flap folds over the top, so it cannot end under f0 282 // step 2's flap folds over the top, so it cannot end under f0
216 var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript")) 283 var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
@@ -225,3 +292,19 @@ private func splitLetterPattern() -> FoldFile {
225 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold"))) 292 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
226 } 293 }
227} 294}
295
296@Test func aFlapThroughAStillFaceFailsItsStepBeforeLaterSteps() throws {
297 // step 2 moves through a still face; step 3 has no moving side on the sheet
298 let script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
299 let (first, second) = (script.steps[0], script.steps[1])
300 let failing = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [
301 first,
302 ScriptStep(kind: second.kind, instruction: second.instruction, creases: second.creases,
303 movingSide: second.movingSide, repeatOf: second.repeatOf,
304 faceOrders: [OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))]),
305 ScriptStep(kind: .fold, instruction: "Fold off the sheet.", creases: first.creases, movingSide: [SIMD2(5, 5)]),
306 ])
307 #expect(throws: CompileError.stepFailed(step: 2, defects: [.movesThroughStillFace(step: 2, moving: 2, still: 0)])) {
308 try compile(failing, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
309 }
310}
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +20
@@ -97,3 +97,23 @@ import FoldKitTestSupport
97 // the open phase departs from frame 1 and the close phase arrives at frame 2 97 // the open phase departs from frame 1 and the close phase arrives at frame 2
98 #expect(layerMotionDefects(try compiled("reverse")).isEmpty) 98 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)
99} 99}
100
101@Test func popsCompareWithinTheTolerance() throws {
102 let file = try compiled("reverse")
103 func nudged(by d: Double) -> FoldFile {
104 let record = file.frames[2].step!, p = record.pop!
105 let close = p.closeAxes.map {
106 AxisRecord(edge: $0.edge, movingFaces: $0.movingFaces, startAngle: $0.startAngle + d, endAngle: $0.endAngle,
107 peakAngle: $0.peakAngle, parent: $0.parent, window: $0.window, angles: $0.angles?.map { $0 + d })
108 }
109 let pop = PopRecord(spine: p.spine, openAngle: p.openAngle + d, phases: p.phases.map { $0 + d },
110 openAxes: p.openAxes, popped: p.popped.map { $0 + d }, closeAxes: close)
111 var copy = file
112 copy.frames[2].step = StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
113 axes: record.axes, nonRigid: record.nonRigid, pop: pop,
114 viewpoint: record.viewpoint)
115 return copy
116 }
117 #expect(structurallyEqual(nudged(by: 1e-13), file, tolerance: 1e-12))
118 #expect(!structurallyEqual(nudged(by: 1e-9), file, tolerance: 1e-12))
119}
Packages/FoldKit/Tests/FoldingTests/LayerMotionTests.swift +9
@@ -12,6 +12,15 @@ import FoldKitTestSupport
12 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)]) 12 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)])
13} 13}
14 14
15@Test func oneStepIsCheckedOnTheFramesUpToIt() throws {
16 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
17 file.frames[2].faceOrders = [[0, 1, 1], [0, 2, -1], [1, 2, 1]]
18 var head = file
19 head.frames.removeLast()
20 #expect(layerMotionDefects(step: 1, in: head).isEmpty)
21 #expect(layerMotionDefects(step: 2, in: file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)])
22}
23
15@Test func aFlapDepartingTowardALayerAboveItIsFlagged() throws { 24@Test func aFlapDepartingTowardALayerAboveItIsFlagged() throws {
16 // step 3 unfolds f0 from under f2, which covers f0's hinge at x = 1 25 // 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")) 26 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))