Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift

326 lines · 16936 bytes

35 symbols in this file
  1import Foundation
  2import simd
  3import Testing
  4import FoldCompiler
  5import FoldFormat
  6import Folding
  7import FoldKitTestSupport
  8
  9@Test(arguments: ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"])
 10func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws {
 11    let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
 12                          pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
 13    #expect(structurallyEqual(out, try FoldFile(contentsOf: fixture("\(name).fold")), tolerance: 1e-12))
 14    #expect(validate(out).isEmpty)
 15}
 16
 17@Test func aCreaseThroughTwoLayersChangesBothEdges() throws {
 18    let out = try compiled("quarters")
 19    #expect(out.frames[3].edgesFoldAngle[8] == 180)
 20    #expect(out.frames[3].edgesFoldAngle[9] == -180)
 21    #expect(out.frames[3].edgesAssignment[9] == .mountain)
 22}
 23
 24@Test func firstCreasedAtStepIsTheFirstStepThatMakesTheCrease() throws {
 25    // x = 1 is made by the fold-and-unfold in step 1 and refolded in step 3
 26    #expect(try compiled("quarters").edgesFirstCreasedAtStep
 27        == [nil, nil, nil, nil, nil, nil, nil, nil, 1, 1, 2, 2])
 28}
 29
 30@Test func movingSideIsResolvedFromAContainedPoint() throws {
 31    #expect(try compiled("half").frames[1].step?.axes[0].movingFaces == [1])
 32}
 33
 34@Test func creaseGivenByEndpointsResolvesToAnEdgeIndex() throws {
 35    #expect(try compiled("half").frames[1].step?.axes[0].edge == 6)
 36}
 37
 38@Test func anOverrideReplacesTheGuessForThatPair() throws {
 39    let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
 40    let frame = file.frames[2]
 41    // the guess puts f2 (folded last) above f0; the override puts f0 above f2
 42    let swapped = try applyOrderOverrides([OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))],
 43                                          to: frame.faceOrders, frame: frame,
 44                                          viewpoint: frame.step!.viewpoint, file: file)
 45    #expect(swapped != frame.faceOrders)
 46    #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) }
 47}
 48
 49@Test func aCoupledStepIsSolvedIntoCurves() throws {
 50    // decision 0001's case 3 as a script: the 140° crease drives, the 260° crease
 51    // gets a curve, the 0° crease rides on it, the 60° crease closes the loop
 52    let out = try compile(degreeFourScript(), pattern: degreeFourPattern())
 53    let axes = try #require(out.frames[1].step?.axes)
 54    #expect(axes.contains { $0.angles != nil })
 55    #expect(axes.contains { $0.parent != nil })
 56    for axis in axes where axis.angles != nil {
 57        #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6)
 58    }
 59}
 60
 61@Test func aDegreeSixVertexCollapsesToAPreliminaryBase() throws {
 62    // four midlines and two diagonal halves: two degrees of freedom beyond the driver, held near
 63    // their linear angles; the three moving corners land on the still one, flat
 64    let out = try compiled("preliminary")
 65    let last = out.frames[1].verticesCoords
 66    for v in [2, 4, 6] { #expect(simd_distance(last[v], last[0]) < 1e-9, "corner \(v)") }
 67    #expect(last.allSatisfy { abs($0.z) < 1e-9 })
 68}
 69
 70@Test func anUnresolvedCreaseNamesItsStepAndReference() {
 71    #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
 72        try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
 73                    pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
 74    }
 75}
 76
 77@Test func aStepThatFailsValidationNamesItsStep() {
 78    #expect {
 79        try compile(FoldScript(contentsOf: fixture("angle-out-of-range.foldscript")),
 80                    pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
 81    } throws: { if case CompileError.stepFailed(step: 2, _) = $0 { true } else { false } }
 82}
 83
 84@Test func guessedFaceOrdersAreAcyclic() throws {
 85    let out = try compiled("occlusion")
 86    for frame in out.frames { #expect(throws: Never.self) {
 87        try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, out)) } }
 88}
 89
 90@Test func aClockwiseFaceIsRejected() throws {
 91    var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
 92    pattern.facesVertices[1].reverse()
 93    #expect(throws: CompileError.clockwiseFace(face: 1)) {
 94        try compile(FoldScript(contentsOf: fixture("half.foldscript")), pattern: pattern)
 95    }
 96}
 97
 98@Test func aCoupledStepReproducesTheClosedForm() throws {
 99    #expect(structurallyEqual(try compile(degreeFourScript(), pattern: degreeFourPattern()), degreeFourVertex(),
100                              tolerance: 1e-9))
101}
102
103private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind: StepKind = .fold,
104                      movingSide: SIMD2<Double> = SIMD2(1.5, 1), faceOrders: [OrderOverride]? = nil,
105                      spine: CreaseRef? = nil, openOn: CreaseRef? = nil) -> FoldScript {
106    FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
107        ScriptStep(kind: kind, instruction: "Fold the right half.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 2))],
108                   movingSide: [movingSide], angles: angles, peakAngles: peakAngles, faceOrders: faceOrders,
109                   spine: spine, openOn: openOn),
110    ])
111}
112
113@Test func aCreaseFoldedAgainstThePatternIsRejected() throws {
114    #expect(throws: CompileError.assignmentDisagreesWithPattern(edge: 6)) {
115        try compile(halfFold(angles: [-180]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
116    }
117}
118
119@Test func aMovingSideOffTheSheetIsRejected() throws {
120    #expect(throws: CompileError.unresolvedMovingSide(step: 1)) {
121        try compile(halfFold(movingSide: SIMD2(5, 5)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
122    }
123}
124
125@Test func anOverrideOffTheSheetNamesItsStep() throws {
126    let override = OrderOverride(above: SIMD2(0.5, 1), below: SIMD2(5, 5))
127    #expect(throws: CompileError.unresolvedFace(step: 1, point: SIMD2(5, 5))) {
128        try compile(halfFold(faceOrders: [override]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
129    }
130}
131
132@Test func anUnassignedCreaseNeedsAnAngle() throws {
133    var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
134    pattern.frames[0].edgesAssignment[6] = .flat
135    #expect(throws: CompileError.missingAngle(step: 1, crease: .betweenVertices(SIMD2(1, 0), SIMD2(1, 2)))) {
136        try compile(halfFold(kind: .foldAndUnfold), pattern: pattern)
137    }
138}
139
140@Test func anglesPairWithCreases() throws {
141    #expect(throws: CompileError.creaseListMismatch(step: 1)) {
142        try compile(halfFold(angles: [180, 180]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
143    }
144}
145
146@Test func aSpineThatIsNotFoldedIsRejected() throws {
147    // a flap opens on a spine folded flat in the frame the step starts from
148    #expect(throws: CompileError.invalidSpine(step: 1)) {
149        try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
150    }
151}
152
153@Test func anOpeningCreaseWithoutASpineIsRejected() throws {
154    #expect(throws: CompileError.missingSpine(step: 1)) {
155        try compile(halfFold(openOn: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
156    }
157}
158
159@Test func aLoopCreaseScriptedAtTheWrongAngleHasNoRigidMotion() throws {
160    let step = degreeFourScript().steps[0]
161    let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
162        ScriptStep(kind: .fold, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
163                   angles: [180, 180, 180, 180]),
164    ])
165    #expect(throws: CompileError.noRigidMotion(step: 1)) { try compile(script, pattern: degreeFourPattern()) }
166}
167
168@Test func twoFlapsFoldedIntoEachOtherAreRejected() throws {
169    let script = FoldScript(creasePattern: "letter-sequential-cp.fold", title: "Letter", steps: [
170        ScriptStep(kind: .fold, instruction: "Valley fold both thirds over at once.",
171                   creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 3)), .betweenVertices(SIMD2(2, 0), SIMD2(2, 3))],
172                   movingSide: [SIMD2(0.5, 1.5), SIMD2(2.5, 1.5)]),
173    ])
174    #expect {
175        try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
176    } throws: { if case CompileError.interpenetration(step: 1, _) = $0 { true } else { false } }
177}
178
179@Test func aCreaseNamedTwiceIsUnresolved() throws {
180    let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
181        ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)],
182                   movingSide: [SIMD2(1.5, 1)]),
183    ])
184    #expect(throws: CompileError.unresolvedCrease(step: 1, crease: .edgeIndex(6))) {
185        try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
186    }
187}
188
189@Test func aSpineOnAStepThatIsNotAFoldIsRejected() throws {
190    #expect(throws: CompileError.invalidSpine(step: 1)) {
191        try compile(halfFold(kind: .foldAndUnfold, spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
192    }
193}
194
195@Test func aDriverThatIsNotAStepCreaseIsUnresolved() throws {
196    let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
197        ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6)],
198                   movingSide: [SIMD2(1.5, 1)], driver: .edgeIndex(0)),
199    ])
200    #expect(throws: CompileError.unresolvedCrease(step: 1, crease: .edgeIndex(0))) {
201        try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
202    }
203}
204
205@Test func aFoldWithNoCreaseIsRejected() throws {
206    let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
207        ScriptStep(kind: .fold, instruction: "Fold the right half.", movingSide: [SIMD2(1.5, 1)]),
208    ])
209    #expect(throws: CompileError.noCreases(step: 1)) {
210        try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
211    }
212}
213
214/// `letter-sequential-cp.fold`'s sheet with the x = 1 crease split at (1, 1.5) into e8 (lower)
215/// and e10 (upper), so folding along it closes a loop of two coincident edges.
216private func splitLetterPattern() -> FoldFile {
217    let points: [SIMD3<Double>] = [
218        SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(3, 0, 0),
219        SIMD3(3, 3, 0), SIMD3(2, 3, 0), SIMD3(1, 3, 0), SIMD3(0, 3, 0), SIMD3(1, 1.5, 0),
220    ]
221    let assignment = Array(repeating: EdgeAssignment.boundary, count: 8) + [.valley, .valley, .valley]
222    return FoldFile(fileSpec: 1.2, fileTitle: "Split letter", fileAuthor: "Traditional",
223                    fileClasses: ["creasePattern"],
224                    edgesVertices: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0],
225                                    [1, 8], [2, 5], [8, 6]],
226                    facesVertices: [[0, 1, 8, 6, 7], [1, 2, 5, 6, 8], [2, 3, 4, 5]],
227                    edgesFirstCreasedAtStep: Array(repeating: nil, count: 11),
228                    frames: [FoldFrame(verticesCoords: points, edgesAssignment: assignment,
229                                       edgesFoldAngle: Array(repeating: 0, count: 11), faceOrders: [])])
230}
231
232@Test func anAxisOffEveryLoopKeepsItsWindowAndStaysLinear() throws {
233    let script = FoldScript(creasePattern: "", title: "Split letter", steps: [
234        ScriptStep(kind: .fold, instruction: "Valley fold the left third over, then the right third over the top.",
235                   creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1.5)), .betweenVertices(SIMD2(2, 0), SIMD2(2, 3))],
236                   movingSide: [SIMD2(0.5, 1.5), SIMD2(2.5, 1.5)], windows: [[0, 0.5], [0.5, 1]]),
237    ])
238    let axes = try #require(try compile(script, pattern: splitLetterPattern()).frames[1].step?.axes)
239    let flap = try #require(axes.first { $0.edge == 9 })
240    #expect(flap.window == [0.5, 1])
241    #expect(flap.angles == nil)
242}
243
244@Test func aSolvedAxisScriptedOnAnotherWindowIsRejected() throws {
245    let step = degreeFourScript().steps[0]
246    let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
247        ScriptStep(kind: .fold, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
248                   windows: [[0, 1], [0, 0.5], [0, 1], [0, 1]]),
249    ])
250    #expect(throws: CompileError.solvedAxisWindowConflict(step: 1, edge: 11)) {
251        try compile(script, pattern: degreeFourPattern())
252    }
253}
254
255/// A 4 × 1 strip with valley creases at x = 1 (e10) and x = 2 (e11) and a mountain at x = 3 (e12).
256/// Folded in half at x = 2, e12 lies on e10's line in a separate layer.
257private func stripPattern() -> FoldFile {
258    let points: [SIMD3<Double>] = [
259        SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(3, 0, 0), SIMD3(4, 0, 0),
260        SIMD3(4, 1, 0), SIMD3(3, 1, 0), SIMD3(2, 1, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0),
261    ]
262    let assignment = Array(repeating: EdgeAssignment.boundary, count: 10) + [.valley, .valley, .mountain]
263    return FoldFile(fileSpec: 1.2, fileTitle: "Strip", fileAuthor: "Traditional", fileClasses: ["creasePattern"],
264                    edgesVertices: (0..<10).map { [$0, ($0 + 1) % 10] } + [[1, 8], [2, 7], [3, 6]],
265                    facesVertices: [[0, 1, 8, 9], [1, 2, 7, 8], [2, 3, 6, 7], [3, 4, 5, 6]],
266                    edgesFirstCreasedAtStep: Array(repeating: nil, count: 13),
267                    frames: [FoldFrame(verticesCoords: points, edgesAssignment: assignment,
268                                       edgesFoldAngle: Array(repeating: 0, count: 13), faceOrders: [])])
269}
270
271@Test func aCoincidentAxisUnderAScriptedAngleIsRejected() throws {
272    // step 2's crease at x = 1 cuts both layers; the upper layer's edge, e12, is an axis of its own
273    let script = FoldScript(creasePattern: "", title: "Strip", steps: [
274        ScriptStep(kind: .fold, instruction: "Valley fold in half.", creases: [.betweenVertices(SIMD2(2, 0), SIMD2(2, 1))],
275                   movingSide: [SIMD2(3, 0.5)]),
276        ScriptStep(kind: .fold, instruction: "Fold the end up to stand.",
277                   creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1))],
278                   movingSide: [SIMD2(0.5, 0.5), SIMD2(3.5, 0.5)], angles: [90]),
279    ])
280    #expect(throws: CompileError.coincidentAxisAngle(step: 2, edge: 12)) {
281        try compile(script, pattern: stripPattern())
282    }
283}
284
285@Test func aCoincidentAxisFoldedFlatCompiles() throws {
286    let script = FoldScript(creasePattern: "", title: "Strip", steps: [
287        ScriptStep(kind: .fold, instruction: "Valley fold in half.", creases: [.betweenVertices(SIMD2(2, 0), SIMD2(2, 1))],
288                   movingSide: [SIMD2(3, 0.5)]),
289        ScriptStep(kind: .fold, instruction: "Fold the end over.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1))],
290                   movingSide: [SIMD2(0.5, 0.5), SIMD2(3.5, 0.5)], angles: [180]),
291    ])
292    let out = try compile(script, pattern: stripPattern())
293    #expect(out.frames[2].edgesFoldAngle[10] == 180)
294    #expect(out.frames[2].edgesFoldAngle[12] == -180)
295}
296
297@Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws {
298    // step 2's flap folds over the top, so it cannot end under f0
299    var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
300    let step = script.steps[1]
301    script = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [
302        script.steps[0],
303        ScriptStep(kind: step.kind, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
304                   repeatOf: step.repeatOf,
305                   faceOrders: [OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))]),
306    ])
307    #expect(throws: CompileError.stepFailed(step: 2, defects: [.movesThroughStillFace(step: 2, moving: 2, still: 0)])) {
308        try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
309    }
310}
311
312@Test func aFlapThroughAStillFaceFailsItsStepBeforeLaterSteps() throws {
313    // step 2 moves through a still face; step 3 has no moving side on the sheet
314    let script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
315    let (first, second) = (script.steps[0], script.steps[1])
316    let failing = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [
317        first,
318        ScriptStep(kind: second.kind, instruction: second.instruction, creases: second.creases,
319                   movingSide: second.movingSide, repeatOf: second.repeatOf,
320                   faceOrders: [OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))]),
321        ScriptStep(kind: .fold, instruction: "Fold off the sheet.", creases: first.creases, movingSide: [SIMD2(5, 5)]),
322    ])
323    #expect(throws: CompileError.stepFailed(step: 2, defects: [.movesThroughStillFace(step: 2, moving: 2, still: 0)])) {
324        try compile(failing, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
325    }
326}