Commit f8a2b36461

f8a2b364618c15b534df7c2a71901d1c628406e3

parent: 13a69d14b0

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 21:06 UTC

Nested openings: openOn turns an earlier fold's opening again

Ref #7

Layout: unified · split

Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift +7 −3
@@ -28,8 +28,9 @@ public struct FoldScript: Codable, Sendable {
2828/// - `viewpoint`: defaults to the previous step's, or eye `[0, 0, 1]`, up `[0, 1, 0]` for step 1.
2929/// - `driver`: the crease held linear when the step's creases close a loop; defaults to the first.
3030/// - `faceOrders`, `faceOrdersMidFold`: corrections to the guessed layer order.
31/// - `spine`, `openAngle`: a reverse fold or sink, compiled by the non-rigid path. `openAngle`
32/// defaults to 20.
31/// - `spine`, `openAngle`, `openOn`: a reverse fold or sink, compiled by the non-rigid path.
32/// `openAngle` defaults to 20. `openOn` names the crease whose opening opens the flap when that
33/// is not the spine: the spine of the earlier reverse fold whose flap this step's flap is in.
3334public struct ScriptStep: Codable, Sendable {
3435 public let kind: StepKind
3536 public let technique: StepTechnique?
@@ -48,13 +49,14 @@ public struct ScriptStep: Codable, Sendable {
4849 public let windows: [[Double]]?
4950 public let spine: CreaseRef?
5051 public let openAngle: Double?
52 public let openOn: CreaseRef?
5153
5254 public init(kind: StepKind, technique: StepTechnique? = nil, instruction: String, creases: [CreaseRef] = [],
5355 movingSide: [SIMD2<Double>] = [], angles: [Double]? = nil, peakAngles: [Double]? = nil,
5456 rotateDegrees: Double? = nil, turnOverAxis: TurnOverAxis? = nil, repeatOf: Int? = nil,
5557 viewpoint: Viewpoint? = nil, faceOrders: [OrderOverride]? = nil,
5658 faceOrdersMidFold: [OrderOverride]? = nil, driver: CreaseRef? = nil, windows: [[Double]]? = nil,
57 spine: CreaseRef? = nil, openAngle: Double? = nil) {
59 spine: CreaseRef? = nil, openAngle: Double? = nil, openOn: CreaseRef? = nil) {
5860 self.kind = kind
5961 self.technique = technique
6062 self.instruction = instruction
@@ -72,6 +74,7 @@ public struct ScriptStep: Codable, Sendable {
7274 self.windows = windows
7375 self.spine = spine
7476 self.openAngle = openAngle
77 self.openOn = openOn
7578 }
7679
7780 public init(from decoder: any Decoder) throws {
@@ -93,6 +96,7 @@ public struct ScriptStep: Codable, Sendable {
9396 windows = try c.decodeIfPresent([[Double]].self, forKey: .windows)
9497 spine = try c.decodeIfPresent(CreaseRef.self, forKey: .spine)
9598 openAngle = try c.decodeIfPresent(Double.self, forKey: .openAngle)
99 openOn = try c.decodeIfPresent(CreaseRef.self, forKey: .openOn)
96100 }
97101}
98102
Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +2 −2
@@ -33,7 +33,7 @@ public enum CompileError: Error, Equatable, Sendable {
3333 case solvedAxisWindowConflict(step: Int, edge: Int)
3434 /// The pop's largest relative change in a render-mesh edge's length exceeds 10%.
3535 case popTooStrained(step: Int, strain: Double)
36 /// A reverse fold or sink names no `spine` to open on.
36 /// A reverse fold or sink, or a step naming `openOn`, names no `spine`.
3737 case missingSpine(step: Int)
3838 /// A `spine` is given on a step that is not a fold, or is not folded flat in frame n − 1.
3939 case invalidSpine(step: Int)
@@ -99,7 +99,7 @@ public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile
9999private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile,
100100 finalAssignment: [EdgeAssignment]) throws {
101101 let technique = script.technique ?? .plain
102 if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) {
102 if script.spine == nil && ([.insideReverse, .outsideReverse, .sink].contains(technique) || script.openOn != nil) {
103103 throw CompileError.missingSpine(step: n)
104104 }
105105 if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) }
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift +116 −46
@@ -18,28 +18,34 @@ private let angleSamples = 256
1818/// on, with decision 0003's opening. `before` is frame n − 1; `after` is frame n as the step's axes
1919/// place it, carrying the step's record; `file` holds frames 0…n − 1.
2020///
21/// The named crease is folded flat. The paper is cut along every edge on its line in `before`;
22/// the spine is the edges of that line whose faces then fall on different sides, each folded flat
23/// or flat. A flat one is a bend line: it bends while the flap is open and is never creased. The
24/// side nearer the viewpoint opens: the open axis turns it about the line, from ±180 to
25/// ±`openAngle`. The pop and close move on a tree cut along the spine and the step's creases,
26/// grown from the faces neither the opening nor the step moves, spine first. In `popped` the spine
27/// is held as the open phase leaves it, reversed where both its faces move in the step, and the
28/// other tree axes are solved to keep the paper whole, starting from `openAngle / 180` of their
29/// way. The close axes drive the named spine edge back to ±180 and solve the rest, as for a rigid
30/// step, and must arrive at `after`'s coordinates.
21/// The flap opens on the opening crease: `openOn`, or the named spine crease. Both are folded
22/// flat. The paper is cut along every edge on either crease's line in `before`, and, with
23/// `openOn`, along the creases of the earlier reverse fold that opened on `openOn` and whose flap
24/// holds this step's. Of each line, the edges whose faces then fall on different sides are kept,
25/// each folded flat or flat; a flat one is a bend line, which bends while the flap is open and is
26/// never creased. The side of the opening crease nearer the viewpoint opens, with the earlier
27/// fold's flap: the open axes are a tree grown from the other faces across the kept edges, the
28/// opening crease first and driven from ±180 to ±`openAngle`, the earlier fold's creases and the
29/// spine solved to keep the paper whole. The pop and close move on a tree cut along those edges and
30/// the step's creases, grown from the faces neither the opening nor the step moves, the opening
31/// crease first. In `popped` the opening crease and the spine's edges in the flap are held as the
32/// open phase leaves them, the latter reversed, and the other tree axes are solved, starting where
33/// the open phase leaves them or `openAngle / 180` of their way. The close axes drive the opening
34/// crease back to ±180 and solve the rest, as for a rigid step, and must arrive at `after`'s
35/// coordinates.
3136///
3237/// The starting guess can lead the solver to another branch of the vertex's motion. Closing the
3338/// loops does not catch that: every branch is closed. A branch is caught when the close does not
3439/// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the
35/// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixture's
36/// test that the tip lands between the flap's layers covers that fixture. `layerMotionDefects`
37/// does not add a check here: frame n's orders for the faces the step's axes move are guessed
38/// from the same close, read near the same moment.
40/// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixtures'
41/// tests that the tip lands between the flap's layers cover them. `layerMotionDefects` does not
42/// add a check here: frame n's orders for the faces the step's axes move are guessed from the same
43/// close, read near the same moment.
3944///
40/// - Throws: `unresolvedCrease` when the spine names no edge, `invalidSpine` when it is not
41/// folded flat, `noRigidMotion` when the flap cannot open on its spine, `popped` does not close
42/// or the close does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%.
45/// - Throws: `unresolvedCrease` when the spine or `openOn` names no edge, `invalidSpine` when one
46/// of them is not folded flat or a kept edge is neither folded flat nor flat, `noRigidMotion`
47/// when the flap cannot open, `popped` does not close or the close does not reach `after`, and
48/// `popTooStrained` when the pop's strain exceeds 10%.
4349public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame,
4450 file: FoldFile) throws -> PopRecord {
4551 guard let reference = script.spine, let record = after.step else {
@@ -50,12 +56,13 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after
5056 let tolerance = sheetExtent(file) * relativeTolerance
5157 let openAngle = script.openAngle ?? defaultOpenAngle
5258 func foldedFlat(_ e: Int) -> Bool { abs(abs(before.edgesFoldAngle[e]) - 180) <= angleSnapTolerance }
53
54 guard let named = resolve(reference, file, edgeFaces) else {
55 throw CompileError.unresolvedCrease(step: n, crease: reference)
59 func edge(_ ref: CreaseRef) throws -> Int {
60 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) }
61 guard foldedFlat(e) else { throw CompileError.invalidSpine(step: n) }
62 return e
5663 }
57 guard foldedFlat(named) else { throw CompileError.invalidSpine(step: n) }
58 let line = onLine(named, before, file, edgeFaces, tolerance)
64 let named = try edge(reference)
65 let opener = try script.openOn.map(edge) ?? named
5966
6067 var group = Array(repeating: -1, count: faceCount)
6168 for (a, axis) in record.axes.enumerated() {
@@ -64,47 +71,63 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after
6471 let moving = group.map { $0 >= 0 }
6572 let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] }
6673
67 // edges on the line whose faces stay connected without it lie within one side
68 let sides = regions(cut: Set(line), file, edgeFaces)
69 let spine = line.filter { sides[edgeFaces[$0][0]] != sides[edgeFaces[$0][1]] }
70 guard spine.allSatisfy({ foldedFlat($0) || abs(before.edgesFoldAngle[$0]) <= angleSnapTolerance }) else {
74 // the earlier reverse fold this step's flap is in, which opened on the opening crease
75 let tip = Set((0..<faceCount).filter { moving[$0] })
76 let earlier = script.openOn == nil ? nil : (1..<n).reversed().lazy.compactMap { file.frames[$0].step }.first { s in
77 s.nonRigid && s.pop?.spine.contains(opener) == true && tip.isSubset(of: s.axes.flatMap(\.movingFaces))
78 }
79 let earlierFlap = Set(earlier?.axes.flatMap(\.movingFaces) ?? [])
80 let earlierCreases = edgeFaces.indices.filter { e in
81 edgeFaces[e].count == 2 && earlierFlap.contains(edgeFaces[e][0]) != earlierFlap.contains(edgeFaces[e][1])
82 }
83
84 // edges on a line whose faces stay connected without it lie within one side
85 let openerLine = onLine(opener, before, file, edgeFaces, tolerance)
86 let spineLine = onLine(named, before, file, edgeFaces, tolerance)
87 let sides = regions(cut: Set(openerLine + earlierCreases + spineLine), file, edgeFaces)
88 func across(_ e: Int) -> Bool { sides[edgeFaces[e][0]] != sides[edgeFaces[e][1]] }
89 let openLine = openerLine.filter(across)
90 let spine = spineLine.filter(across)
91 guard (openLine + spine).allSatisfy({ foldedFlat($0) || abs(before.edgesFoldAngle[$0]) <= angleSnapTolerance }) else {
7192 throw CompileError.invalidSpine(step: n)
7293 }
73 let tipSpine = Set(spine.filter { edgeFaces[$0].allSatisfy { moving[$0] } })
94 let tipSpine = Set(spine.filter { edgeFaces[$0].allSatisfy(tip.contains) })
7495
75 // the layer nearer the viewer opens: of the named edge's faces, the one a valley puts on the
76 // first face's normal side, or a mountain on the other
77 let (f, g) = (edgeFaces[named][0], edgeFaces[named][1])
96 // the layer nearer the viewer opens: of the opening crease's faces, the one a valley puts on
97 // the first face's normal side, or a mountain on the other
98 let (f, g) = (edgeFaces[opener][0], edgeFaces[opener][1])
7899 let normals = faceNormals(before, file)
79 let gNearer = (before.edgesFoldAngle[named] > 0) == (dot(normals[f], record.viewpoint.eye) > 0)
100 let gNearer = (before.edgesFoldAngle[opener] > 0) == (dot(normals[f], record.viewpoint.eye) > 0)
80101 let (near, far) = gNearer ? (g, f) : (f, g)
81 guard sides[far] != sides[near] else { throw CompileError.noRigidMotion(step: n) }
82 let opening = (0..<faceCount).filter { sides[$0] == sides[near] }
83 let openSign = before.edgesFoldAngle[named] > 0 ? 1.0 : -1.0
84 let openAxes = [AxisRecord(edge: named, movingFaces: opening, startAngle: before.edgesFoldAngle[named],
85 endAngle: openSign * openAngle, window: [0, phases[0]])]
86 let opened = try openEndAngles(n, openAxes, edges: spine, before: before, record, file)
102 guard sides[far] != sides[near], !earlierFlap.contains(far) else { throw CompileError.noRigidMotion(step: n) }
103 let opening = Set((0..<faceCount).filter { sides[$0] == sides[near] || earlierFlap.contains($0) })
104 let openEdges = unique(openLine + earlierCreases + spine)
105 let openTree = growTree(order: openEdges, fixed: Set((0..<faceCount).filter { !opening.contains($0) }),
106 file, edgeFaces)
107 guard openTree.axes.first?.edge == opener else { throw CompileError.noRigidMotion(step: n) }
108 let openSign = before.edgesFoldAngle[opener] > 0 ? 1.0 : -1.0
109 let openAxes = try openingAxes(n, openTree, end: openSign * openAngle, before: before, record, file)
110 let opened = try openEndAngles(n, openAxes, edges: openEdges, before: before, record, file)
87111
88112 // the tree the pop and the close move on
89113 let fixed = Set((0..<faceCount).filter { !moving[$0] && !opening.contains($0) })
90114 guard !fixed.isEmpty else { throw CompileError.noRigidMotion(step: n) }
91 let order = spine + record.axes.map(\.edge).filter { !spine.contains($0) }
92 + creased.filter { e in !spine.contains(e) && !record.axes.contains { $0.edge == e } }
115 let order = unique(openEdges + record.axes.map(\.edge) + creased)
93116 let tree = growTree(order: order, fixed: fixed, file, edgeFaces)
94117
95 // popped: the spine held as the opening leaves it, reversed beyond the step's creases; the
96 // rest solved. The close returns the spine to where it was, reversed beyond the step's creases.
97 func held(_ e: Int) -> Double { tipSpine.contains(e) ? -opened[e]! : opened[e]! }
118 // popped: the open edges as the opening leaves them, the spine reversed in the flap; the rest
119 // solved. The close returns the open edges to where they were, the spine reversed in the flap.
98120 func closed(_ e: Int) -> Double {
99 spine.contains(e) ? (tipSpine.contains(e) ? -1 : 1) * before.edgesFoldAngle[e] : after.edgesFoldAngle[e]
121 opened[e] == nil ? after.edgesFoldAngle[e] : (tipSpine.contains(e) ? -1 : 1) * before.edgesFoldAngle[e]
100122 }
101123 var guess: [Int: Double] = [:]
102124 for axis in tree.axes {
103125 let start = before.edgesFoldAngle[axis.edge]
104 guess[axis.edge] = spine.contains(axis.edge) ? held(axis.edge)
105 : start + (closed(axis.edge) - start) * openAngle / 180
126 guess[axis.edge] = opened[axis.edge].map { tipSpine.contains(axis.edge) ? -$0 : $0 }
127 ?? start + (closed(axis.edge) - start) * openAngle / 180
106128 }
107 let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(spine), record, file)
129 let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(openLine).union(tipSpine),
130 record, file)
108131 var poppedFrame = before
109132 poppedFrame.verticesCoords = popped.positions
110133
@@ -126,6 +149,53 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after
126149 return pop
127150}
128151
152/// `edges` without repeats, in order.
153private func unique(_ edges: [Int]) -> [Int] {
154 var seen = Set<Int>()
155 return edges.filter { seen.insert($0).inserted }
156}
157
158/// The open axes on `[0, phases[0]]`: the tree's first axis, the opening crease, linear from its
159/// angle in `before` to `end`; the axes on a loop's cycle solved so the loops close, continued
160/// from `before` along the window to find where they end and then solved as for a rigid step; the
161/// rest held.
162private func openingAxes(_ n: Int, _ tree: RegionTree, end: Double, before: FoldFrame, _ record: StepRecord,
163 _ file: FoldFile) throws -> [AxisRecord] {
164 let opener = tree.axes[0].edge
165 func draft(_ ends: [Int: Double]) -> (StepRecord, FoldFile) {
166 let axes = records(tree, start: { before.edgesFoldAngle[$0] }, end: { ends[$0] ?? before.edgesFoldAngle[$0] },
167 window: [0, phases[0]])
168 let open = withAxes(record, axes)
169 var draft = file
170 draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment,
171 edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], step: open))
172 return (open, draft)
173 }
174 let (held, heldFile) = draft([opener: end])
175 guard !tree.loops.isEmpty else { return held.axes }
176 let step = try readStep(n, in: heldFile)
177 let driver = step.axes.firstIndex { $0.edge == opener }!
178 let free = axesOnCycles(step, loops: tree.loops, heldFile).subtracting([driver]).sorted()
179 guard !free.isEmpty else { return held.axes }
180
181 let kinematics = LoopKinematics(step: step, file: heldFile)
182 let tolerance = sheetExtent(file) * relativeTolerance
183 var previous = step.axes.map(\.startAngle), angles = previous
184 for k in 1...angleSamples {
185 var guess = zip(angles, previous).map { 2 * $0 - $1 }
186 guess[driver] = step.axes[driver].startAngle + Double(k) / Double(angleSamples) * (end - step.axes[driver].startAngle)
187 guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) }
188 (previous, angles) = (angles, guess)
189 }
190 let (open, openFile) = draft(Dictionary(uniqueKeysWithValues: zip(step.axes.map(\.edge), angles)))
191 let solved = try solveLoops(n, open, try readStep(n, in: openFile), loops: tree.loops, openFile)
192 var solvedFile = openFile
193 solvedFile.frames[n].step = solved
194 try checkClosure(n, try readStep(n, in: solvedFile), driver: opener, solvedFile,
195 solved: solved.axes.contains { $0.angles != nil })
196 return solved.axes
197}
198
129199/// `named` and every other interior edge on its line in `frame`.
130200private func onLine(_ named: Int, _ frame: FoldFrame, _ file: FoldFile, _ edgeFaces: [[Int]],
131201 _ tolerance: Double) -> [Int] {
Packages/FoldKit/Sources/FoldFormat/StepRecord.swift +4 −3
@@ -48,9 +48,10 @@ public struct Viewpoint: Codable, Equatable, Sendable {
4848 }
4949}
5050
51/// The open, pop and close of a non-rigid step: `openAxes` open the flap about its `spine` to
52/// `openAngle` on `[0, phases[0]]`, every vertex reaches `popped` by `phases[1]`, and
53/// `closeAxes`, relative to `popped`, close the flap on `[phases[1], 1]`.
51/// The open, pop and close of a non-rigid step: `openAxes` open the flap on `[0, phases[0]]`, the
52/// first turning the opening crease to `openAngle` (the `spine`, or for a nested opening an
53/// earlier fold's spine), every vertex reaches `popped` by `phases[1]`, and `closeAxes`, relative
54/// to `popped`, close the flap on `[phases[1], 1]`.
5455public struct PopRecord: Codable, Equatable, Sendable {
5556 public let spine: [Int]
5657 public let openAngle: Double
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-nested-cp.fold added +13
@@ -0,0 +1,13 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Nested reverse folds",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [3, 0], [4, 0], [4, 1], [4, 2], [3, 2], [0, 2], [0, 1], [2, 1],
7 [3.5, 1], [4, 0.5], [4, 1.5]],
8 "edges_vertices": [[0, 1], [1, 2], [2, 10], [10, 3], [3, 11], [11, 4], [4, 5], [5, 6], [6, 7], [7, 0],
9 [7, 8], [8, 9], [9, 3], [8, 1], [8, 5], [9, 10], [9, 11]],
10 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
11 "V", "M", "V", "V", "V", "M", "M"],
12 "faces_vertices": [[0, 1, 8, 7], [1, 2, 10, 9, 8], [10, 3, 9], [9, 3, 11], [8, 9, 11, 4, 5], [7, 8, 5, 6]]
13}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-nested.foldscript added +31
@@ -0,0 +1,31 @@
1{
2 "creasePattern": "reverse-nested-cp.fold",
3 "title": "Nested reverse folds",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the top half down onto the bottom half.",
8 "creases": [[[0, 1], [2, 1]]],
9 "movingSide": [[1, 1.5]]
10 },
11 {
12 "kind": "fold",
13 "technique": "insideReverse",
14 "instruction": "Inside reverse fold the right end down between the layers.",
15 "creases": [[[2, 1], [3, 0]], [[2, 1], [3, 2]]],
16 "movingSide": [[3.2, 0.5]],
17 "spine": [[0, 1], [2, 1]],
18 "faceOrders": [{"above": [3.2, 1.5], "below": [3.2, 0.5]}, {"above": [3.9, 1.1], "below": [3.9, 0.9]}]
19 },
20 {
21 "kind": "fold",
22 "technique": "insideReverse",
23 "instruction": "Inside reverse fold the end of the flap up between its layers.",
24 "creases": [[[3.5, 1], [4, 0.5]], [[3.5, 1], [4, 1.5]]],
25 "movingSide": [[3.9, 0.9]],
26 "spine": [[3.5, 1], [4, 1]],
27 "openOn": [[0, 1], [2, 1]],
28 "faceOrders": [{"above": [3.9, 1.1], "below": [3.9, 0.9]}]
29 }
30 ]
31}
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +13 −7
@@ -407,10 +407,16 @@ private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double
407407}
408408
409409/// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point
410/// (2.75, 0.75) lies strictly between the body's two layers: the planes of the faces containing
411/// sheet points (0.5, 0.5) and (0.5, 1.5), at the tip point's x and y. False when the tip point is
412/// not over both layers.
410/// (2.75, 0.75) lies strictly between the body's two layers: the faces containing sheet points
411/// (0.5, 0.5) and (0.5, 1.5).
413412public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool {
413 pointIsBetweenLayers(positions, file, point: SIMD2(2.75, 0.75), lower: SIMD2(0.5, 0.5), upper: SIMD2(0.5, 1.5))
414}
415
416/// Whether, at `positions`, sheet point `point` lies strictly between the planes of the faces
417/// containing sheet points `lower` and `upper`, at its x and y. False when it is not over both.
418public func pointIsBetweenLayers(_ positions: [SIMD3<Double>], _ file: FoldFile, point: SIMD2<Double>,
419 lower lowerPoint: SIMD2<Double>, upper upperPoint: SIMD2<Double>) -> Bool {
414420 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
415421 func face(containing p: SIMD2<Double>) -> Int? {
416422 file.facesVertices.indices.first { f in
@@ -444,9 +450,9 @@ public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFil
444450 guard inside else { return nil }
445451 return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z
446452 }
447 guard let tip = face(containing: SIMD2(2.75, 0.75)), let lower = face(containing: SIMD2(0.5, 0.5)),
448 let upper = face(containing: SIMD2(0.5, 1.5)) else { return false }
449 let probe = place(SIMD2(2.75, 0.75), on: tip)
453 guard let tip = face(containing: point), let lower = face(containing: lowerPoint),
454 let upper = face(containing: upperPoint) else { return false }
455 let probe = place(point, on: tip)
450456 let q = SIMD2(probe.x, probe.y)
451457 guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false }
452458 return probe.z > min(a, b) && probe.z < max(a, b)
@@ -475,7 +481,7 @@ private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -
475481 movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees,
476482 turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders,
477483 faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine,
478 openAngle: openAngle)
484 openAngle: openAngle, openOn: s.openOn)
479485}
480486
481487/// The repository's `Models/` directory: this file's path with its last five components, up to
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +8 −2
@@ -102,11 +102,11 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th
102102
103103private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind: StepKind = .fold,
104104 movingSide: SIMD2<Double> = SIMD2(1.5, 1), faceOrders: [OrderOverride]? = nil,
105 spine: CreaseRef? = nil) -> FoldScript {
105 spine: CreaseRef? = nil, openOn: CreaseRef? = nil) -> FoldScript {
106106 FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
107107 ScriptStep(kind: kind, instruction: "Fold the right half.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 2))],
108108 movingSide: [movingSide], angles: angles, peakAngles: peakAngles, faceOrders: faceOrders,
109 spine: spine),
109 spine: spine, openOn: openOn),
110110 ])
111111}
112112
@@ -150,6 +150,12 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
150150 }
151151}
152152
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
153159@Test func aLoopCreaseScriptedAtTheWrongAngleHasNoRigidMotion() throws {
154160 let step = degreeFourScript().steps[0]
155161 let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +24
@@ -119,6 +119,30 @@ import FoldKitTestSupport
119119 #expect(meshInterpenetrations(i, samples: 64).isEmpty)
120120}
121121
122@Test func aNestedReverseFoldOpensOnTheOuterSpine() throws {
123 // decision 0003: the head reopens the neck by turning the body's near side again, the neck's
124 // creases solved on their reversed branch, then pops and closes between the neck's layers
125 let file = try compiled("reverse-nested")
126 let step = try readSteps(file)[2]
127 let pop = try #require(step.pop)
128 #expect(pop.openAxes.first?.edge == 10)
129 #expect(Set(pop.openAxes.map(\.edge)).isSuperset(of: [13, 14]))
130 #expect(pop.openAxes.contains { $0.curve != nil })
131 let i = FoldInterpolator(file: file, step: step)
132 let (lo, hi) = (pop.phases.lowerBound, pop.phases.upperBound)
133 for n in 0...256 {
134 let t = Double(n) / 256
135 guard t <= lo || t >= hi else { continue }
136 #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)")
137 }
138 let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
139 #expect(worst <= 0.10)
140 #expect(meshInterpenetrations(i, samples: 64).isEmpty)
141 #expect(pointIsBetweenLayers(i.positions(at: hi + 0.97 * (1 - hi)), file, point: SIMD2(3.9, 0.9),
142 lower: SIMD2(3.2, 0.5), upper: SIMD2(3.2, 1.5)))
143 #expect(layerMotionDefects(file).isEmpty)
144}
145
122146@Test func theReverseFoldMovesThroughNoStillFace() throws {
123147 // the open phase departs from frame 1 and the close phase arrives at frame 2
124148 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)