Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift
214 lines · 10155 bytes
19 symbols in this file
aReverseFoldCompilesToANonRigidStepaReverseFoldWithoutASpineIsRejectedtheOpenAndCloseLegsAreRigidthePopStaysWithinTheBoundtheBandedPopStrainsTheFixtureLessThanPerFaceTurnsthePopStartsAndEndsOnTheRigidPosestheStepEndsOnItsEndFramenothingPassesThroughAnythingtheTipLandsBetweenTheFlapsLayersaFlapOpenedOnlyTo60DegreesIsRejectedthePopFitsInAFrameBudgetaBendLineOnTheSpineFoldsWhileTheFlapIsOpenAndFlattensAgainaNestedReverseFoldOpensOnTheOuterSpineaNestedOpeningLeavesABendLineOnItsOpeningCreaseUncreasedanOpeningCreaseNoEarlierFoldOpenedIsRejectedtheReverseFoldMovesThroughNoStillFacepopsCompareWithinTheTolerancenudgedconcurrentPopSolvesAgreeWithSerialOnes
1import Foundation
2import Testing
3import simd
4import FoldCompiler
5import FoldFormat
6import Folding
7import FoldKitTestSupport
8
9@Test func aReverseFoldCompilesToANonRigidStep() throws {
10 let out = try compiled("reverse")
11 let step = try #require(out.frames[2].step)
12 #expect(step.nonRigid)
13 #expect(step.pop?.openAngle == 20)
14 #expect(step.technique == .insideReverse)
15}
16
17@Test func aReverseFoldWithoutASpineIsRejected() {
18 #expect(throws: CompileError.missingSpine(step: 2)) {
19 try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withoutSpine(step: 2),
20 pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
21 }
22}
23
24@Test func theOpenAndCloseLegsAreRigid() throws {
25 // checked on the FOLD edges, as rigid steps are; mesh slivers at creases make relative mesh strain noisy
26 let file = try compiled("reverse")
27 let step = try readSteps(file)[1]
28 let i = FoldInterpolator(file: file, step: step)
29 for n in 0...256 {
30 let t = Double(n) / 256
31 guard t <= step.pop!.phases.lowerBound || t >= step.pop!.phases.upperBound else { continue }
32 #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)")
33 }
34}
35
36@Test func thePopStaysWithinTheBound() throws {
37 let file = try compiled("reverse")
38 let step = try readSteps(file)[1]
39 let i = FoldInterpolator(file: file, step: step)
40 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
41 let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
42 #expect(worst <= 0.10)
43}
44
45@Test func theBandedPopStrainsTheFixtureLessThanPerFaceTurns() throws {
46 // decision 0003 at 20° from flat: 3.08% banded, 4.36% with each face turned on its own
47 let file = try compiled("reverse")
48 let step = try readSteps(file)[1]
49 let i = FoldInterpolator(file: file, step: step)
50 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
51 let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
52 #expect(worst < 0.035)
53}
54
55@Test func thePopStartsAndEndsOnTheRigidPoses() throws {
56 let file = try compiled("reverse")
57 let step = try readSteps(file)[1]
58 let i = FoldInterpolator(file: file, step: step)
59 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
60 // at the phases' ends the mesh is placed rigidly; just inside them it is bent
61 for (bent, rigid) in [(lo + 1e-12, lo), (hi - 1e-12, hi)] {
62 #expect(zip(i.meshPositions(at: bent), i.meshPositions(at: rigid)).allSatisfy { simd_distance($0, $1) < 1e-9 },
63 "t \(rigid)")
64 }
65}
66
67@Test func theStepEndsOnItsEndFrame() throws {
68 let file = try compiled("reverse")
69 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
70 #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 })
71}
72
73@Test func nothingPassesThroughAnything() throws {
74 // in all three phases, on the render mesh
75 let file = try compiled("reverse")
76 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
77 #expect(meshInterpenetrations(i, samples: 64).isEmpty)
78}
79
80@Test func theTipLandsBetweenTheFlapsLayers() throws {
81 // 97% of the way through the closing phase, a point of the tip lies between the body's two layers
82 let file = try compiled("reverse")
83 let step = try readSteps(file)[1]
84 let i = FoldInterpolator(file: file, step: step)
85 let upper = step.pop!.phases.upperBound
86 #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file))
87}
88
89@Test func aFlapOpenedOnlyTo60DegreesIsRejected() {
90 #expect {
91 try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2),
92 pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
93 } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } }
94}
95
96@Test func thePopFitsInAFrameBudget() throws {
97 let file = try compiled("reverse")
98 let step = try readSteps(file)[1]
99 let i = FoldInterpolator(file: file, step: step)
100 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
101 let elapsed = ContinuousClock().measure {
102 for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) }
103 }
104 #expect(elapsed / 100 < .milliseconds(4))
105}
106
107@Test func aBendLineOnTheSpineFoldsWhileTheFlapIsOpenAndFlattensAgain() throws {
108 // decision 0003: the tab's bend line (1 of its 2 faces beyond the spine's line) is cut with the
109 // spine, so the tab's near half opens with the flap; the line is never creased
110 let file = try compiled("reverse-bend")
111 let bend = 18
112 #expect(file.edgesFirstCreasedAtStep[bend] == nil)
113 #expect(file.frames.allSatisfy { $0.edgesFoldAngle[bend] == 0 && $0.edgesAssignment[bend] == .flat })
114 let step = try readSteps(file)[2]
115 let i = FoldInterpolator(file: file, step: step)
116 let open = i.positions(at: step.pop!.phases.lowerBound)
117 let normals = faceNormals(positions: open, faces: file.facesVertices)
118 let between = acos(simd_dot(normals[4], normals[5])) * 180 / .pi
119 #expect(abs(between - 160) < 1e-6)
120 #expect(meshInterpenetrations(i, samples: 64).isEmpty)
121}
122
123@Test func aNestedReverseFoldOpensOnTheOuterSpine() throws {
124 // decision 0003: the head reopens the neck by turning the body's near side again, the neck's
125 // creases solved on their reversed branch, then pops and closes between the neck's layers
126 let file = try compiled("reverse-nested")
127 let step = try readSteps(file)[2]
128 let pop = try #require(step.pop)
129 #expect(pop.openAxes.first?.edge == 10)
130 #expect(Set(pop.openAxes.map(\.edge)).isSuperset(of: [13, 14]))
131 #expect(pop.openAxes.contains { $0.curve != nil })
132 let i = FoldInterpolator(file: file, step: step)
133 let (lo, hi) = (pop.phases.lowerBound, pop.phases.upperBound)
134 for n in 0...256 {
135 let t = Double(n) / 256
136 guard t <= lo || t >= hi else { continue }
137 #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)")
138 }
139 let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
140 #expect(worst <= 0.10)
141 #expect(meshInterpenetrations(i, samples: 64).isEmpty)
142 #expect(pointIsBetweenLayers(i.positions(at: hi + 0.97 * (1 - hi)), file, point: SIMD2(3.9, 0.9),
143 lower: SIMD2(3.2, 0.5), upper: SIMD2(3.2, 1.5)))
144 #expect(layerMotionDefects(file).isEmpty)
145}
146
147@Test func aNestedOpeningLeavesABendLineOnItsOpeningCreaseUncreased() throws {
148 // the head reopens on the body's spine, whose line holds the tab's bend line (edge 23)
149 let file = try compiled("reverse-nested-bend")
150 let bend = 23
151 #expect(file.edgesFirstCreasedAtStep[bend] == nil)
152 #expect(file.frames.allSatisfy { $0.edgesFoldAngle[bend] == 0 && $0.edgesAssignment[bend] == .flat })
153 #expect(try readSteps(file)[3].pop?.spine.contains(bend) == true)
154 #expect(validate(file).isEmpty)
155}
156
157@Test func anOpeningCreaseNoEarlierFoldOpenedIsRejected() throws {
158 let script = try FoldScript(contentsOf: fixture("reverse.foldscript"))
159 let s = script.steps[1]
160 let reopened = ScriptStep(kind: s.kind, technique: s.technique, instruction: s.instruction, creases: s.creases,
161 movingSide: s.movingSide, faceOrders: s.faceOrders, spine: s.spine, openOn: s.spine)
162 #expect(throws: CompileError.noEarlierOpening(step: 2)) {
163 try compile(FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [script.steps[0], reopened]),
164 pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
165 }
166}
167
168@Test func theReverseFoldMovesThroughNoStillFace() throws {
169 // the open phase departs from frame 1 and the close phase arrives at frame 2
170 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)
171}
172
173@Test func popsCompareWithinTheTolerance() throws {
174 let file = try compiled("reverse")
175 func nudged(by d: Double) -> FoldFile {
176 let record = file.frames[2].step!, p = record.pop!
177 let close = p.closeAxes.map {
178 AxisRecord(edge: $0.edge, movingFaces: $0.movingFaces, startAngle: $0.startAngle + d, endAngle: $0.endAngle,
179 peakAngle: $0.peakAngle, parent: $0.parent, window: $0.window, angles: $0.angles?.map { $0 + d })
180 }
181 let pop = PopRecord(spine: p.spine, openAngle: p.openAngle + d, phases: p.phases.map { $0 + d },
182 openAxes: p.openAxes, popped: p.popped.map { $0 + d }, closeAxes: close)
183 var copy = file
184 copy.frames[2].step = StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
185 axes: record.axes, nonRigid: record.nonRigid, pop: pop,
186 viewpoint: record.viewpoint)
187 return copy
188 }
189 #expect(structurallyEqual(nudged(by: 1e-13), file, tolerance: 1e-12))
190 #expect(!structurallyEqual(nudged(by: 1e-9), file, tolerance: 1e-12))
191}
192
193@Test func concurrentPopSolvesAgreeWithSerialOnes() async throws {
194 // one interpolator, so one factor, solved from eight tasks at once
195 let file = try compiled("reverse")
196 let step = try readSteps(file)[1]
197 let i = FoldInterpolator(file: file, step: step)
198 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
199 let times = (1..<64).map { lo + Double($0) / 64 * (hi - lo) }
200 let serial = times.map { i.meshPositions(at: $0) }
201 let mismatches = await withTaskGroup(of: Int.self) { group in
202 for _ in 0..<8 {
203 group.addTask {
204 var count = 0
205 for _ in 0..<20 {
206 for (t, expected) in zip(times, serial) where i.meshPositions(at: t) != expected { count += 1 }
207 }
208 return count
209 }
210 }
211 return await group.reduce(0, +)
212 }
213 #expect(mismatches == 0)
214}