Commit 13265c0964

13265c096423405354ad3b3cc7e7ecc059d47996

parent: ae2d67750c

Unsigned

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

foldc, non-rigid steps, foldlint and the cup (Tasks 7, 7b, 8) (!5)

- `foldc` compiles a crease pattern and a fold script into a FOLD sequence. Each end frame comes from `FoldInterpolator` through `readStep`. Only the axes on a loop's cycle are solved. Layer order is guessed by arrival side, with overrides from the script. Every step is validated, checked for interpenetration and checked for layer motion.
- Non-rigid steps move by open, pop, close (decision 0002). `RenderMesh`, an ARAP pop with a sparse Cholesky factor, and `PopCompiler` hold the pop to 10% strain.
- `layerMotionDefects` adds the departure/arrival rule, run by `foldc`, `foldlint` and the catalogue tests.
- `foldlint`, `ModelLibrary` and the catalogue gate.
- The cup: crease pattern, script, generated `cup.fold` and `docs/authoring/cup.md`. It regenerates byte-identical and needs no layer-order overrides.
- The plan and spec are amended for rulings R22–R34 and the cup's eight-layer centre.

`swift test --package-path Packages/FoldKit`: 151 tests pass.

Closes #4

Layout: unified · split

Models/cup-cp.fold added +33
@@ -0,0 +1,33 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Cup",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [
7 [1, 0],
8 [1.4142135623730951, 0.41421356237309515],
9 [2, 1],
10 [1.4142135623730951, 1.5857864376269049],
11 [1, 2],
12 [0.5857864376269049, 1.5857864376269049],
13 [0, 1],
14 [0.5857864376269049, 0.41421356237309515],
15 [0.8284271247461903, 1],
16 [1.1715728752538097, 1]
17 ],
18 "edges_vertices": [
19 [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0],
20 [6, 8], [8, 9], [9, 2],
21 [9, 3], [9, 1],
22 [8, 5], [8, 7],
23 [7, 1], [5, 3]
24 ],
25 "edges_assignment": [
26 "B", "B", "B", "B", "B", "B", "B", "B",
27 "V", "V", "V",
28 "V", "M",
29 "V", "M",
30 "M", "M"
31 ],
32 "faces_vertices": [[7, 0, 1], [7, 1, 9, 8], [1, 2, 9], [6, 7, 8], [6, 8, 5], [8, 9, 3, 5], [9, 2, 3], [5, 3, 4]]
33}
Models/cup.foldscript added +41
@@ -0,0 +1,41 @@
1{
2 "creasePattern": "cup-cp.fold",
3 "title": "Cup",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold in half along the diagonal, bottom corner up to the top corner.",
8 "creases": [[[0.8284271247461903, 1], [1.1715728752538097, 1]]],
9 "movingSide": [[1, 0.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Valley fold the right corner across to touch the left edge, so that the top edge of the flap is level.",
14 "creases": [[[1.1715728752538097, 1], [1.4142135623730951, 1.5857864376269049]]],
15 "movingSide": [[1.6, 1.2]]
16 },
17 {
18 "kind": "fold",
19 "instruction": "Valley fold the left corner across to touch the right edge, over the first flap.",
20 "creases": [[[0.8284271247461903, 1], [0.5857864376269049, 1.5857864376269049]]],
21 "movingSide": [[0.4, 1.2]]
22 },
23 {
24 "kind": "fold",
25 "instruction": "Valley fold the front top flap down over the front.",
26 "creases": [[[0.5857864376269049, 0.41421356237309515], [1.4142135623730951, 0.41421356237309515]]],
27 "movingSide": [[1, 0.2]]
28 },
29 {
30 "kind": "turnOver",
31 "instruction": "Turn over.",
32 "turnOverAxis": "vertical"
33 },
34 {
35 "kind": "fold",
36 "instruction": "Valley fold the remaining top flap down.",
37 "creases": [[[0.5857864376269049, 1.5857864376269049], [1.4142135623730951, 1.5857864376269049]]],
38 "movingSide": [[1, 1.8]]
39 }
40 ]
41}
Packages/FoldKit/Package.swift +13 −1
@@ -7,17 +7,29 @@ let package = Package(
7 products: [ 7 products: [
8 .library(name: "FoldFormat", targets: ["FoldFormat"]), 8 .library(name: "FoldFormat", targets: ["FoldFormat"]),
9 .library(name: "Folding", targets: ["Folding"]), 9 .library(name: "Folding", targets: ["Folding"]),
10 .library(name: "FoldCompiler", targets: ["FoldCompiler"]),
11 .library(name: "Models", targets: ["Models"]),
12 .executable(name: "foldc", targets: ["foldc"]),
13 .executable(name: "foldlint", targets: ["foldlint"]),
10 ], 14 ],
11 targets: [ 15 targets: [
12 .target(name: "FoldFormat"), 16 .target(name: "FoldFormat"),
13 .target(name: "Folding", dependencies: ["FoldFormat"]), 17 .target(name: "Folding", dependencies: ["FoldFormat"]),
18 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]),
19 .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]),
20 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]),
21 .executableTarget(name: "foldlint", dependencies: ["FoldFormat", "Folding"]),
14 .target( 22 .target(
15 name: "FoldKitTestSupport", 23 name: "FoldKitTestSupport",
16 dependencies: ["FoldFormat", "Folding"], 24 dependencies: ["FoldFormat", "Folding", "FoldCompiler"],
17 resources: [.copy("Fixtures")] 25 resources: [.copy("Fixtures")]
18 ), 26 ),
19 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), 27 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]),
20 .testTarget(name: "FoldingTests", dependencies: ["Folding", "FoldFormat", "FoldKitTestSupport"]), 28 .testTarget(name: "FoldingTests", dependencies: ["Folding", "FoldFormat", "FoldKitTestSupport"]),
29 .testTarget(name: "FoldCompilerTests",
30 dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]),
31 .testTarget(name: "ModelsTests",
32 dependencies: ["Models", "FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport", "foldlint"]),
21 ], 33 ],
22 swiftLanguageModes: [.v6] 34 swiftLanguageModes: [.v6]
23) 35)
Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift added +136
@@ -0,0 +1,136 @@
1import FoldFormat
2import Foundation
3
4/// A fold script: a crease pattern and the steps that fold it. `creasePattern` is a path
5/// relative to the script.
6public struct FoldScript: Codable, Sendable {
7 public let creasePattern: String
8 public let title: String
9 public let steps: [ScriptStep]
10
11 public init(creasePattern: String, title: String, steps: [ScriptStep]) {
12 self.creasePattern = creasePattern
13 self.title = title
14 self.steps = steps
15 }
16
17 public init(contentsOf url: URL) throws {
18 self = try JSONDecoder().decode(FoldScript.self, from: Data(contentsOf: url))
19 }
20}
21
22/// One authored step. Points are in crease-pattern coordinates.
23///
24/// - `creases`: the creases the step folds; each must separate a moving region from the rest.
25/// - `movingSide`: a point inside each region that moves; the region no point lies in is fixed.
26/// - `angles`, `peakAngles`, `windows`: one per crease. An angle defaults to ±180 by the crease
27/// pattern's assignment, a window to `[0, 1]`.
28/// - `viewpoint`: defaults to the previous step's, or eye `[0, 0, 1]`, up `[0, 1, 0]` for step 1.
29/// - `driver`: the crease held linear when the step's creases close a loop; defaults to the first.
30/// - `faceOrders`, `faceOrdersMidFold`: corrections to the guessed layer order.
31/// - `spine`, `openAngle`: a reverse fold or sink, compiled by the non-rigid path.
32public struct ScriptStep: Codable, Sendable {
33 public let kind: StepKind
34 public let technique: StepTechnique?
35 public let instruction: String
36 public let creases: [CreaseRef]
37 public let movingSide: [SIMD2<Double>]
38 public let angles: [Double]?
39 public let peakAngles: [Double]?
40 public let rotateDegrees: Double?
41 public let turnOverAxis: TurnOverAxis?
42 public let repeatOf: Int?
43 public let viewpoint: Viewpoint?
44 public let faceOrders: [OrderOverride]?
45 public let faceOrdersMidFold: [OrderOverride]?
46 public let driver: CreaseRef?
47 public let windows: [[Double]]?
48 public let spine: CreaseRef?
49 public let openAngle: Double?
50
51 public init(kind: StepKind, technique: StepTechnique? = nil, instruction: String, creases: [CreaseRef] = [],
52 movingSide: [SIMD2<Double>] = [], angles: [Double]? = nil, peakAngles: [Double]? = nil,
53 rotateDegrees: Double? = nil, turnOverAxis: TurnOverAxis? = nil, repeatOf: Int? = nil,
54 viewpoint: Viewpoint? = nil, faceOrders: [OrderOverride]? = nil,
55 faceOrdersMidFold: [OrderOverride]? = nil, driver: CreaseRef? = nil, windows: [[Double]]? = nil,
56 spine: CreaseRef? = nil, openAngle: Double? = nil) {
57 self.kind = kind
58 self.technique = technique
59 self.instruction = instruction
60 self.creases = creases
61 self.movingSide = movingSide
62 self.angles = angles
63 self.peakAngles = peakAngles
64 self.rotateDegrees = rotateDegrees
65 self.turnOverAxis = turnOverAxis
66 self.repeatOf = repeatOf
67 self.viewpoint = viewpoint
68 self.faceOrders = faceOrders
69 self.faceOrdersMidFold = faceOrdersMidFold
70 self.driver = driver
71 self.windows = windows
72 self.spine = spine
73 self.openAngle = openAngle
74 }
75
76 public init(from decoder: any Decoder) throws {
77 let c = try decoder.container(keyedBy: CodingKeys.self)
78 kind = try c.decode(StepKind.self, forKey: .kind)
79 technique = try c.decodeIfPresent(StepTechnique.self, forKey: .technique)
80 instruction = try c.decode(String.self, forKey: .instruction)
81 creases = try c.decodeIfPresent([CreaseRef].self, forKey: .creases) ?? []
82 movingSide = try c.decodeIfPresent([SIMD2<Double>].self, forKey: .movingSide) ?? []
83 angles = try c.decodeIfPresent([Double].self, forKey: .angles)
84 peakAngles = try c.decodeIfPresent([Double].self, forKey: .peakAngles)
85 rotateDegrees = try c.decodeIfPresent(Double.self, forKey: .rotateDegrees)
86 turnOverAxis = try c.decodeIfPresent(TurnOverAxis.self, forKey: .turnOverAxis)
87 repeatOf = try c.decodeIfPresent(Int.self, forKey: .repeatOf)
88 viewpoint = try c.decodeIfPresent(Viewpoint.self, forKey: .viewpoint)
89 faceOrders = try c.decodeIfPresent([OrderOverride].self, forKey: .faceOrders)
90 faceOrdersMidFold = try c.decodeIfPresent([OrderOverride].self, forKey: .faceOrdersMidFold)
91 driver = try c.decodeIfPresent(CreaseRef.self, forKey: .driver)
92 windows = try c.decodeIfPresent([[Double]].self, forKey: .windows)
93 spine = try c.decodeIfPresent(CreaseRef.self, forKey: .spine)
94 openAngle = try c.decodeIfPresent(Double.self, forKey: .openAngle)
95 }
96}
97
98/// A crease, as the two points it runs between or as an edge index. In a script, `[[x0, y0],
99/// [x1, y1]]` or an integer.
100public enum CreaseRef: Codable, Sendable, Equatable {
101 case betweenVertices(SIMD2<Double>, SIMD2<Double>)
102 case edgeIndex(Int)
103
104 public init(from decoder: any Decoder) throws {
105 let c = try decoder.singleValueContainer()
106 if let edge = try? c.decode(Int.self) {
107 self = .edgeIndex(edge)
108 return
109 }
110 let ends = try c.decode([SIMD2<Double>].self)
111 guard ends.count == 2 else {
112 throw DecodingError.dataCorruptedError(in: c, debugDescription: "a crease runs between two points")
113 }
114 self = .betweenVertices(ends[0], ends[1])
115 }
116
117 public func encode(to encoder: any Encoder) throws {
118 var c = encoder.singleValueContainer()
119 switch self {
120 case .betweenVertices(let a, let b): try c.encode([a, b])
121 case .edgeIndex(let edge): try c.encode(edge)
122 }
123 }
124}
125
126/// Puts the face containing `above` over the face containing `below`, as seen from the step's
127/// viewpoint. Points are in crease-pattern coordinates.
128public struct OrderOverride: Codable, Sendable, Equatable {
129 public let above: SIMD2<Double>
130 public let below: SIMD2<Double>
131
132 public init(above: SIMD2<Double>, below: SIMD2<Double>) {
133 self.above = above
134 self.below = below
135 }
136}
Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift added +682
@@ -0,0 +1,682 @@
1import FoldFormat
2import Folding
3import simd
4
5public enum CompileError: Error, Equatable, Sendable {
6 /// A crease, driver or spine names no edge or a boundary edge, a crease names an edge already
7 /// named in the step, or the driver is not one of the step's creases. `crease` is the
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)
12 /// A `movingSide` point lies on no face, every region has one, or a crease does not separate
13 /// a moving region from the rest.
14 case unresolvedMovingSide(step: Int)
15 /// An order override's point lies on no face.
16 case unresolvedFace(step: Int, point: SIMD2<Double>)
17 case stepFailed(step: Int, defects: [FoldDefect])
18 case interpenetration(step: Int, [Intersection])
19 /// A crease folded in the last frame has a different assignment in the crease pattern.
20 case assignmentDisagreesWithPattern(edge: Int)
21 /// The step's creases close a loop that does not stay closed.
22 case noRigidMotion(step: Int)
23 /// A solved curve, rebuilt from its samples, opens a gap between them.
24 case curveTooCoarse(step: Int)
25 /// A face of the crease pattern is clockwise seen from +z.
26 case clockwiseFace(face: Int)
27 /// `crease`, or an edge on its line, has no angle in the script and is neither `V` nor `M` in
28 /// the crease pattern.
29 case missingAngle(step: Int, crease: CreaseRef)
30 /// `angles`, `peakAngles` or `windows` does not have one entry per crease.
31 case creaseListMismatch(step: Int)
32 /// An axis the step solves to close a loop has a scripted window other than the driver's.
33 case solvedAxisWindowConflict(step: Int, edge: Int)
34 /// The pop's largest relative change in a render-mesh edge's length exceeds 10%.
35 case popTooStrained(step: Int, strain: Double)
36 /// A reverse fold or sink names no `spine` to open on.
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)
43}
44
45/// Samples in a solved curve, evenly spaced over its window.
46private let curveSamples = 257
47/// Lengths are compared to within this fraction of the sheet's longer side.
48let relativeTolerance = 1e-6
49/// A crease's named endpoints match an edge's within this distance in crease-pattern units.
50private let creaseMatchTolerance = 1e-6
51/// A solved angle within this many degrees of linear at every sample is written without a curve.
52private let linearTolerance = 1e-9
53/// A measured end angle within this many degrees of an expected one is taken to be it.
54let angleSnapTolerance = 1e-6
55/// Samples of a step checked for interpenetration.
56private let interpenetrationSamples = 64
57
58/// Compiles a fold script against its crease pattern into a FOLD sequence.
59///
60/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the
61/// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed
62/// and overridden, and the file so far validated and checked with `layerMotionDefects` and for
63/// interpenetration. A step that names a `spine` is a reverse fold or sink and moves by
64/// `compilePop`'s open, pop and close.
65public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile {
66 let flat = pattern.frames[0]
67 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 {
68 throw CompileError.clockwiseFace(face: f)
69 }
70 let finalAssignment = flat.edgesAssignment
71 let keyFrame = FoldFrame(verticesCoords: flat.verticesCoords,
72 edgesAssignment: finalAssignment.map { $0 == .boundary ? .boundary : .flat },
73 edgesFoldAngle: finalAssignment.map { _ in 0 },
74 faceOrders: [])
75 var file = FoldFile(fileSpec: 1.2, fileTitle: script.title, fileAuthor: pattern.fileAuthor,
76 fileClasses: ["diagrams"], edgesVertices: pattern.edgesVertices,
77 facesVertices: pattern.facesVertices,
78 edgesFirstCreasedAtStep: pattern.edgesVertices.map { _ in nil },
79 frames: [keyFrame])
80
81 var viewpoint = Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
82 for (i, step) in script.steps.enumerated() {
83 viewpoint = step.viewpoint ?? viewpoint
84 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment)
85 }
86
87 let last = file.frames[file.frames.count - 1]
88 for e in file.edgesVertices.indices
89 where last.edgesFoldAngle[e] != 0 && last.edgesAssignment[e] != finalAssignment[e] {
90 throw CompileError.assignmentDisagreesWithPattern(edge: e)
91 }
92 return file
93}
94
95/// Compiles step `n` and appends frame n to `file`.
96private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile,
97 finalAssignment: [EdgeAssignment]) throws {
98 let technique = script.technique ?? .plain
99 if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) {
100 throw CompileError.missingSpine(step: n)
101 }
102 if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) }
103 let previous = file.frames[n - 1]
104
105 var plan: FoldPlan?
106 if script.kind == .fold || script.kind == .foldAndUnfold {
107 plan = try planFolds(n, script, file, finalAssignment)
108 }
109 var record = StepRecord(kind: script.kind, technique: technique,
110 instruction: script.instruction, axes: plan?.axes ?? [],
111 rotateDegrees: script.rotateDegrees, turnOverAxis: script.turnOverAxis,
112 repeatOf: script.repeatOf, viewpoint: viewpoint)
113
114 // frame n with the start's coordinates, enough for readStep
115 var draft = file
116 draft.frames.append(FoldFrame(verticesCoords: previous.verticesCoords,
117 edgesAssignment: previous.edgesAssignment,
118 edgesFoldAngle: previous.edgesFoldAngle, faceOrders: [], step: record))
119 var step = try readStep(n, in: draft)
120 if let plan, !plan.loops.isEmpty {
121 record = try solveLoops(n, record, step, loops: plan.loops, draft)
122 draft.frames[n].step = record
123 step = try readStep(n, in: draft)
124 try checkClosure(n, step, driver: record.axes[0].edge, draft, solved: record.axes.contains { $0.angles != nil })
125 }
126 var interpolator = FoldInterpolator(file: draft, step: step)
127
128 var angles = previous.edgesFoldAngle
129 var assignment = previous.edgesAssignment
130 if let plan {
131 for axis in record.axes { angles[axis.edge] = axis.endAngle }
132 if script.kind == .fold {
133 for (e, angle) in try loopEndAngles(n, plan, previous, interpolator, file) { angles[e] = angle }
134 }
135 for e in plan.creased {
136 assignment[e] = angles[e] > 0 ? .valley : angles[e] < 0 ? .mountain : .flat
137 if file.edgesFirstCreasedAtStep[e] == nil { file.edgesFirstCreasedAtStep[e] = n }
138 }
139 }
140
141 var frame = FoldFrame(verticesCoords: interpolator.positions(at: 1), edgesAssignment: assignment,
142 edgesFoldAngle: angles, faceOrders: [], step: record)
143 if script.spine != nil {
144 // the step's axes give frame n's coordinates; the pop is how the paper gets there
145 let pop = try compilePop(step: n, script: script, before: previous, after: frame, file: file)
146 record = withPop(record, pop)
147 draft.frames[n].step = record
148 step = try readStep(n, in: draft)
149 interpolator = FoldInterpolator(file: draft, step: step)
150 frame.verticesCoords = interpolator.positions(at: 1)
151 frame.step = record
152 for (e, angle) in popEndAngles(step, interpolator, previous: previous, file: file) {
153 frame.edgesFoldAngle[e] = angle
154 frame.edgesAssignment[e] = angle > 0 ? .valley : angle < 0 ? .mountain : .flat
155 if file.edgesFirstCreasedAtStep[e] == nil { file.edgesFirstCreasedAtStep[e] = n }
156 }
157 }
158 let guess = guessFaceOrders(previous: previous, next: frame, step: record, file: file)
159 frame.faceOrders = try naming(n) {
160 try applyOrderOverrides(script.faceOrders ?? [], to: guess, frame: frame, viewpoint: viewpoint, file: file)
161 }
162 file.frames.append(frame)
163
164 if script.kind == .foldAndUnfold {
165 var peak = frame
166 peak.verticesCoords = interpolator.positions(at: 0.5)
167 let peakGuess = guessOrders(previous: previous, step: step, interpolator: interpolator,
168 positions: peak.verticesCoords, file: file,
169 arrival: { ($0.lowerBound + $0.upperBound) / 2 })
170 file.frames[n].faceOrdersMidFold = try naming(n) {
171 try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: peakGuess, frame: peak,
172 viewpoint: viewpoint, file: file)
173 }
174 } else if script.kind == .fold
175 && (script.faceOrdersMidFold != nil || movingSetsOverlapInProjection(step: n, file)) {
176 file.frames[n].faceOrdersMidFold = try naming(n) {
177 try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: frame.faceOrders, frame: frame,
178 viewpoint: viewpoint, file: file)
179 }
180 }
181
182 let defects = validate(file)
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) }
186 let collisions = step.nonRigid
187 ? meshInterpenetrations(interpolator, samples: interpenetrationSamples)
188 : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples)
189 guard collisions.isEmpty else { throw CompileError.interpenetration(step: n, collisions) }
190}
191
192/// Runs `body`, giving an `unresolvedFace` error the step number `n`.
193private func naming<T>(_ n: Int, _ body: () throws -> T) throws -> T {
194 do {
195 return try body()
196 } catch CompileError.unresolvedFace(_, let point) {
197 throw CompileError.unresolvedFace(step: n, point: point)
198 }
199}
200
201// MARK: - Planning a fold
202
203/// A fold or fold-and-unfold step's axes and the edges it creases.
204private struct FoldPlan {
205 /// One per edge of the region tree, driver first, without curves.
206 var axes: [AxisRecord]
207 /// Every edge whose two faces the step moves differently.
208 var creased: [Int]
209 /// Creased edges off the region tree, each closing a loop.
210 var loops: [Int]
211 /// The scripted end angle of each crease in `loops` that the script names with an angle.
212 var expected: [Int: Double]
213}
214
215/// Resolves the step's creases and moving side, cuts the sheet into regions along the creases
216/// and grows a tree of regions from the fixed one, across the creases in script order, driver
217/// first. Each tree edge is an axis; each other crease between different regions closes a loop.
218///
219/// Every edge that lies on a named crease's line in the start frame is cut too, so a crease
220/// through several layers folds each of them; one whose faces end up in the same region is not
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.
223private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
224 _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan {
225 let start = file.frames[n - 1]
226 let edgeFaces = edgesFaces(file)
227 let count = script.creases.count
228 for list in [script.angles?.count, script.peakAngles?.count, script.windows?.count] where list != nil && list != count {
229 throw CompileError.creaseListMismatch(step: n)
230 }
231
232 guard count > 0 else { throw CompileError.noCreases(step: n) }
233 let named = try script.creases.map { ref in
234 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) }
235 return e
236 }
237 if let repeated = named.indices.first(where: { named[..<$0].contains(named[$0]) }) {
238 throw CompileError.unresolvedCrease(step: n, crease: script.creases[repeated])
239 }
240 var driver = 0
241 if let ref = script.driver {
242 guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else {
243 throw CompileError.unresolvedCrease(step: n, crease: ref)
244 }
245 driver = i
246 }
247 let order = [driver] + named.indices.filter { $0 != driver }
248
249 // each crease with the index of the script crease it belongs to
250 var creases = order.map { (edge: named[$0], source: $0) }
251 let tolerance = sheetExtent(file) * relativeTolerance
252 for i in order {
253 let ends = file.edgesVertices[named[i]].map { start.verticesCoords[$0] }
254 for e in edgeFaces.indices where edgeFaces[e].count == 2 && !creases.contains(where: { $0.edge == e })
255 && file.edgesVertices[e].allSatisfy({ onLine(start.verticesCoords[$0], ends[0], ends[1], tolerance) }) {
256 creases.append((e, i))
257 }
258 }
259
260 // regions: faces connected across edges the step does not cut
261 let cut = Set(creases.map(\.edge))
262 var region = Array(repeating: -1, count: file.facesVertices.count)
263 var regionCount = 0
264 for seed in region.indices where region[seed] < 0 {
265 region[seed] = regionCount
266 var stack = [seed]
267 while let f = stack.popLast() {
268 for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) {
269 let g = faces[0] == f ? faces[1] : faces[0]
270 if region[g] < 0 {
271 region[g] = regionCount
272 stack.append(g)
273 }
274 }
275 }
276 regionCount += 1
277 }
278
279 // nodes: 0 for the fixed regions, then each moving region in the order its point appears
280 guard !script.movingSide.isEmpty else { throw CompileError.unresolvedMovingSide(step: n) }
281 var nodeOfRegion = Array(repeating: 0, count: regionCount)
282 var nodeCount = 1
283 for point in script.movingSide {
284 guard let f = face(containing: point, file) else { throw CompileError.unresolvedMovingSide(step: n) }
285 if nodeOfRegion[region[f]] == 0 {
286 nodeOfRegion[region[f]] = nodeCount
287 nodeCount += 1
288 }
289 }
290 guard nodeOfRegion.contains(0) else { throw CompileError.unresolvedMovingSide(step: n) }
291 let node = region.map { nodeOfRegion[$0] }
292
293 // the tree, by union-find over the creases in order
294 var component = Array(0..<nodeCount)
295 func find(_ x: Int) -> Int {
296 var x = x
297 while component[x] != x { x = component[x] }
298 return x
299 }
300 var tree: [(edge: Int, source: Int, ends: (Int, Int))] = []
301 var creased: [Int] = [], loops: [Int] = []
302 for (e, source) in creases {
303 let a = node[edgeFaces[e][0]], b = node[edgeFaces[e][1]]
304 if a == b {
305 if e == named[source] { throw CompileError.unresolvedMovingSide(step: n) }
306 continue
307 }
308 creased.append(e)
309 if find(a) != find(b) {
310 component[find(a)] = find(b)
311 tree.append((e, source, (a, b)))
312 } else {
313 loops.append(e)
314 }
315 }
316
317 // orient the tree from the fixed node
318 var parentNode = Array<Int?>(repeating: nil, count: nodeCount)
319 var axisOfNode = Array<Int?>(repeating: nil, count: nodeCount)
320 var reached: Set<Int> = [0]
321 var queue = [0]
322 while !queue.isEmpty {
323 let a = queue.removeFirst()
324 for (k, t) in tree.enumerated() where t.ends.0 == a || t.ends.1 == a {
325 let b = t.ends.0 == a ? t.ends.1 : t.ends.0
326 guard reached.insert(b).inserted else { continue }
327 parentNode[b] = a
328 axisOfNode[b] = k
329 queue.append(b)
330 }
331 }
332
333 let axes = try tree.enumerated().map { k, t -> AxisRecord in
334 let child = axisOfNode[t.ends.0] == k ? t.ends.0 : t.ends.1
335 let parent = parentNode[child].flatMap { axisOfNode[$0] }
336 let isNamed = t.edge == named[t.source]
337 let movingFaces = node.indices.filter { node[$0] == child }
338 let startAngle = start.edgesFoldAngle[t.edge]
339 let window = script.windows?[t.source]
340 let written = window == [0, 1] ? nil : window
341 func endAngle(_ list: [Double]?) throws -> Double {
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 }
346 switch finalAssignment[t.edge] {
347 case .valley: return 180
348 case .mountain: return -180
349 default: throw CompileError.missingAngle(step: n, crease: script.creases[t.source])
350 }
351 }
352 if script.kind == .foldAndUnfold {
353 return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle, endAngle: startAngle,
354 peakAngle: try endAngle(script.peakAngles), parent: parent, window: written)
355 }
356 return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle,
357 endAngle: try endAngle(script.angles), parent: parent, window: written)
358 }
359
360 var expected: [Int: Double] = [:]
361 if let angles = script.angles {
362 for (e, source) in creases where loops.contains(e) && e == named[source] {
363 expected[e] = angles[source]
364 }
365 }
366 return FoldPlan(axes: axes, creased: creased, loops: loops, expected: expected)
367}
368
369/// The edge a crease reference names: by index, or the edge whose endpoints in the crease
370/// pattern are nearest the named points, within 1e-6. Boundary edges are not creases.
371func resolve(_ ref: CreaseRef, _ file: FoldFile, _ edgeFaces: [[Int]]) -> Int? {
372 switch ref {
373 case .edgeIndex(let e):
374 return edgeFaces.indices.contains(e) && edgeFaces[e].count == 2 ? e : nil
375 case .betweenVertices(let p, let q):
376 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
377 let nearest = file.edgesVertices.indices.map { e -> (edge: Int, distance: Double) in
378 let u = flat[file.edgesVertices[e][0]], v = flat[file.edgesVertices[e][1]]
379 return (e, min(max(distance(u, p), distance(v, q)), max(distance(u, q), distance(v, p))))
380 }.min { $0.distance < $1.distance }
381 guard let nearest, nearest.distance <= creaseMatchTolerance, edgeFaces[nearest.edge].count == 2 else {
382 return nil
383 }
384 return nearest.edge
385 }
386}
387
388/// The first face of the crease pattern whose closed outline contains `point`.
389func face(containing point: SIMD2<Double>, _ file: FoldFile) -> Int? {
390 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
391 return file.facesVertices.indices.first { f in
392 let corners = file.facesVertices[f].map { flat[$0] }
393 return corners.indices.allSatisfy { i in
394 let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = point - a
395 return side.x * offset.y - side.y * offset.x >= 0
396 }
397 }
398}
399
400func onLine(_ p: SIMD3<Double>, _ a: SIMD3<Double>, _ b: SIMD3<Double>, _ tolerance: Double) -> Bool {
401 length(cross(p - a, normalize(b - a))) <= tolerance
402}
403
404/// The longer side of frame 0's bounding box.
405func sheetExtent(_ file: FoldFile) -> Double {
406 let points = file.frames[0].verticesCoords
407 let lower = points.dropFirst().reduce(points[0], simd_min)
408 let upper = points.dropFirst().reduce(points[0], simd_max)
409 return (upper - lower).max()
410}
411
412// MARK: - Loops
413
414/// Holds the driver (the first axis in `record`) linear on its window and solves the other axes
415/// on a loop's cycle, the tree path between the two sides of a loop crease, so the loops stay
416/// closed: damped Gauss–Newton on the gap between vertex copies, continued along the window from
417/// the previous samples. Each solved axis takes the driver's window and a curve of 257 samples, or
418/// none when it is linear to within 1e-9°; the last sample is the end angle exactly. Axes on no
419/// cycle stay linear on their own windows.
420///
421/// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window.
422func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int],
423 _ file: FoldFile) throws -> StepRecord {
424 guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record }
425 let free = axesOnCycles(step, loops: loops, file).subtracting([driver]).sorted()
426 guard !free.isEmpty else { return record }
427 for a in free where step.axes[a].window != step.axes[driver].window {
428 throw CompileError.solvedAxisWindowConflict(step: n, edge: step.axes[a].edge)
429 }
430
431 let kinematics = LoopKinematics(step: step, file: file)
432 let tolerance = sheetExtent(file) * relativeTolerance
433 let fraction = { (k: Int) in Double(k) / Double(curveSamples - 1) }
434 func linear(_ axis: FoldAxis, _ u: Double) -> Double {
435 step.kind == .foldAndUnfold
436 ? axis.startAngle + ((axis.peakAngle ?? axis.endAngle) - axis.startAngle) * (1 - abs(2 * u - 1))
437 : axis.startAngle + u * (axis.endAngle - axis.startAngle)
438 }
439
440 var samples: [[Double]] = []
441 for k in 0..<curveSamples {
442 let u = fraction(k)
443 var guess = switch k {
444 case 0: step.axes.map(\.startAngle)
445 case 1: step.axes.map { linear($0, u) }
446 default: zip(samples[k - 1], samples[k - 2]).map { 2 * $0 - $1 }
447 }
448 guess[driver] = linear(step.axes[driver], u)
449 guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) }
450 samples.append(guess)
451 }
452
453 var axes = record.axes
454 for a in free {
455 let axis = step.axes[a]
456 var curve = samples.map { $0[a] }
457 curve[curveSamples - 1] = axis.endAngle
458 let isLinear = curve.indices.allSatisfy { abs(curve[$0] - linear(axis, fraction($0))) <= linearTolerance }
459 guard let i = axes.firstIndex(where: { $0.edge == axis.edge }) else { continue }
460 let r = axes[i]
461 axes[i] = AxisRecord(edge: r.edge, movingFaces: r.movingFaces, startAngle: r.startAngle,
462 endAngle: r.endAngle, peakAngle: r.peakAngle, parent: r.parent,
463 window: r.window,
464 angles: isLinear ? nil : curve)
465 }
466 return StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
467 axes: axes, rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis,
468 repeatOf: record.repeatOf, nonRigid: record.nonRigid, pop: record.pop,
469 viewpoint: record.viewpoint)
470}
471
472/// The indices in `step.axes` of the axes on some loop's cycle: the tree path between the two
473/// faces of a loop crease.
474func axesOnCycles(_ step: FoldStep, loops: [Int], _ file: FoldFile) -> Set<Int> {
475 var axisOfFace: [Int: Int] = [:]
476 for (a, axis) in step.axes.enumerated() {
477 for f in axis.movingFaces { axisOfFace[f] = a }
478 }
479 func carriers(_ f: Int) -> Set<Int> {
480 var result = Set<Int>(), a = axisOfFace[f]
481 while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent }
482 return result
483 }
484 let edgeFaces = edgesFaces(file)
485 return loops.reduce(into: Set<Int>()) { cycle, e in
486 cycle.formUnion(carriers(edgeFaces[e][0]).symmetricDifference(carriers(edgeFaces[e][1])))
487 }
488}
489
490/// Checks the step's loops stay closed as its axes move, at four times the curve sample density
491/// over the window of the axis on `driver` and over the whole step.
492func checkClosure(_ n: Int, _ step: FoldStep, driver: Int, _ file: FoldFile, solved: Bool) throws {
493 let kinematics = LoopKinematics(step: step, file: file)
494 let tolerance = sheetExtent(file) * relativeTolerance
495 let intervals = 4 * (curveSamples - 1)
496 let window = step.axes.first { $0.edge == driver }?.window ?? 0...1
497 let times = (0...intervals).flatMap { k -> [Double] in
498 let u = Double(k) / Double(intervals)
499 return [u, window.lowerBound + u * (window.upperBound - window.lowerBound)]
500 }
501 for t in times where kinematics.gap(step.axes.map { $0.angle(at: t, kind: step.kind) }) > tolerance {
502 throw solved ? CompileError.curveTooCoarse(step: n) : CompileError.noRigidMotion(step: n)
503 }
504}
505
506/// The end angle of each loop crease, measured from the faces' normals along the step and
507/// unwrapped from its start angle, then taken to be its scripted angle, ±180 or 0 when within
508/// 1e-6° of one.
509private func loopEndAngles(_ n: Int, _ plan: FoldPlan, _ previous: FoldFrame, _ interpolator: FoldInterpolator,
510 _ file: FoldFile) throws -> [Int: Double] {
511 let edgeFaces = edgesFaces(file)
512 var current = Dictionary(uniqueKeysWithValues: plan.loops.map { ($0, previous.edgesFoldAngle[$0]) })
513 let intervals = curveSamples - 1
514 for k in 1...intervals {
515 let positions = interpolator.positions(at: Double(k) / Double(intervals))
516 let normals = faceNormals(positions: positions, faces: file.facesVertices)
517 for e in plan.loops {
518 let measured = dihedral(e, edgeFaces[e], positions, normals, file)
519 current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded()
520 }
521 }
522 var result: [Int: Double] = [:]
523 for (e, angle) in current {
524 let candidates = (plan.expected[e].map { [$0] } ?? []) + [180, -180, 0]
525 let snapped = candidates.first { abs(angle - $0) <= angleSnapTolerance } ?? angle
526 if let expected = plan.expected[e], snapped != expected { throw CompileError.noRigidMotion(step: n) }
527 result[e] = snapped
528 }
529 return result
530}
531
532/// The fold angle in degrees of an interior edge between faces `faces`, positive for a valley:
533/// the turn from the first face's normal to the second's about the edge, directed as the second
534/// face traverses it.
535func dihedral(_ e: Int, _ faces: [Int], _ positions: [SIMD3<Double>], _ normals: [SIMD3<Double>],
536 _ file: FoldFile) -> Double {
537 let corners = file.facesVertices[faces[1]], ends = Set(file.edgesVertices[e])
538 let i = corners.indices.first { ends == Set([corners[$0], corners[($0 + 1) % corners.count]]) }!
539 let d = normalize(positions[corners[(i + 1) % corners.count]] - positions[corners[i]])
540 let a = normals[faces[0]], b = normals[faces[1]]
541 return atan2(dot(cross(a, b), d), dot(a, b)) * 180 / .pi
542}
543
544/// p ↦ q·p + t
545private struct Rigid {
546 var q = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
547 var t = SIMD3<Double>.zero
548
549 func apply(_ p: SIMD3<Double>) -> SIMD3<Double> { q.act(p) + t }
550
551 /// This transform applied after `inner`.
552 func after(_ inner: Rigid) -> Rigid { Rigid(q: q * inner.q, t: q.act(inner.t) + t) }
553
554 static func rotation(about origin: SIMD3<Double>, direction: SIMD3<Double>, degrees: Double) -> Rigid {
555 let q = simd_quatd(angle: degrees * .pi / 180, axis: direction)
556 return Rigid(q: q, t: origin - q.act(origin))
557 }
558}
559
560/// A step's axes as functions of their angles, and the gap between the copies of each vertex
561/// that faces moving with different axes carry.
562struct LoopKinematics {
563 let axes: [FoldAxis]
564 let start: [SIMD3<Double>]
565 /// Each vertex shared by faces that move differently, with the axes that move them, −1 for
566 /// a still face.
567 let copies: [(vertex: Int, axes: [Int])]
568
569 init(step: FoldStep, file: FoldFile) {
570 axes = step.axes
571 start = file.frames[step.index - 1].verticesCoords
572 var axisOfFace = Array(repeating: -1, count: file.facesVertices.count)
573 for (a, axis) in step.axes.enumerated() {
574 for f in axis.movingFaces { axisOfFace[f] = a }
575 }
576 var movers = Array(repeating: [Int](), count: start.count)
577 for (f, corners) in file.facesVertices.enumerated() {
578 for v in corners where !movers[v].contains(axisOfFace[f]) { movers[v].append(axisOfFace[f]) }
579 }
580 copies = movers.indices.filter { movers[$0].count > 1 }.map { ($0, movers[$0]) }
581 }
582
583 func residual(_ angles: [Double]) -> [Double] {
584 var full: [Rigid] = []
585 for (a, axis) in axes.enumerated() {
586 let own = Rigid.rotation(about: axis.origin, direction: axis.direction,
587 degrees: angles[a] - axis.startAngle)
588 full.append(axis.parent.map { full[$0].after(own) } ?? own)
589 }
590 func place(_ a: Int, _ p: SIMD3<Double>) -> SIMD3<Double> { a < 0 ? p : full[a].apply(p) }
591 var r: [Double] = []
592 for (v, movers) in copies {
593 let base = place(movers[0], start[v])
594 for a in movers.dropFirst() {
595 let d = place(a, start[v]) - base
596 r += [d.x, d.y, d.z]
597 }
598 }
599 return r
600 }
601
602 /// The largest distance between two copies of one vertex.
603 func gap(_ angles: [Double]) -> Double {
604 let r = residual(angles)
605 return stride(from: 0, to: r.count, by: 3).map { length(SIMD3(r[$0], r[$0 + 1], r[$0 + 2])) }.max() ?? 0
606 }
607
608 /// Damped Gauss–Newton on the angles of the axes in `free`, holding the rest. Returns the gap
609 /// it reaches.
610 func solve(_ angles: inout [Double], free: [Int], iterations: Int = 60) -> Double {
611 var lambda = 1e-6
612 var r = residual(angles)
613 var cost = r.reduce(0) { $0 + $1 * $1 }
614 for _ in 0..<iterations {
615 if cost < 1e-26 { break }
616 let h = 1e-6
617 var jacobian = Array(repeating: [Double](repeating: 0, count: free.count), count: r.count)
618 for (k, a) in free.enumerated() {
619 var probe = angles
620 probe[a] += h
621 let plus = residual(probe)
622 probe[a] -= 2 * h
623 let minus = residual(probe)
624 for i in r.indices { jacobian[i][k] = (plus[i] - minus[i]) / (2 * h) }
625 }
626 var improved = false
627 for _ in 0..<20 {
628 var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count)
629 var gradient = [Double](repeating: 0, count: free.count)
630 for i in r.indices {
631 for a in free.indices {
632 gradient[a] -= jacobian[i][a] * r[i]
633 for b in free.indices { normal[a][b] += jacobian[i][a] * jacobian[i][b] }
634 }
635 }
636 for a in free.indices { normal[a][a] += lambda * (1 + normal[a][a]) }
637 guard let delta = solveLinear(normal, gradient) else {
638 lambda *= 10
639 continue
640 }
641 var trial = angles
642 for (k, a) in free.enumerated() { trial[a] += delta[k] }
643 let rt = residual(trial)
644 let ct = rt.reduce(0) { $0 + $1 * $1 }
645 if ct < cost {
646 angles = trial
647 r = rt
648 cost = ct
649 lambda = max(lambda / 10, 1e-12)
650 improved = true
651 break
652 }
653 lambda *= 10
654 }
655 if !improved { break }
656 }
657 return gap(angles)
658 }
659}
660
661/// Gaussian elimination with partial pivoting; nil when `a` is singular.
662private func solveLinear(_ a: [[Double]], _ b: [Double]) -> [Double]? {
663 var m = a, x = b
664 let n = b.count
665 for c in 0..<n {
666 guard let p = (c..<n).max(by: { abs(m[$0][c]) < abs(m[$1][c]) }), abs(m[p][c]) > 1e-300 else { return nil }
667 m.swapAt(c, p)
668 x.swapAt(c, p)
669 for r in (c + 1)..<n {
670 let f = m[r][c] / m[c][c]
671 if f == 0 { continue }
672 for k in c..<n { m[r][k] -= f * m[c][k] }
673 x[r] -= f * x[c]
674 }
675 }
676 for c in stride(from: n - 1, through: 0, by: -1) {
677 var s = x[c]
678 for k in (c + 1)..<n { s -= m[c][k] * x[k] }
679 x[c] = s / m[c][c]
680 }
681 return x
682}
Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift added +213
@@ -0,0 +1,213 @@
1import FoldFormat
2import Folding
3import simd
4
5/// Two unit normals whose dot product's magnitude reaches this lie on one line.
6private let parallelCosine = 1 - 1e-9
7/// How far before a pair's arrival the guess looks, as a fraction of the arriving axis's window.
8private let arrivalLead = 1e-3
9/// Two layers closer than this fraction of the sheet's size at that moment are not told apart.
10private let separationTolerance = 1e-9
11
12/// Guesses `next`'s `faceOrders`, every overlapping pair once as `[f, g, s]` with `f < g`.
13///
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
16/// last axis that moves them differently finishes, the higher-indexed of axes that finish
17/// together, at the paper points that meet in the middle of their overlap. A moving set that has
18/// turned over arrives with its layers reversed. This is right for plain valley and mountain
19/// folds and wrong for a flap tucked between layers, which the script corrects with overrides.
20///
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]] {
23 var end = next
24 end.step = step
25 let draft = FoldFile(fileSpec: file.fileSpec, edgesVertices: file.edgesVertices,
26 facesVertices: file.facesVertices,
27 edgesFirstCreasedAtStep: file.edgesFirstCreasedAtStep,
28 frames: [file.frames[0], previous, end])
29 guard let folding = try? readStep(2, in: draft) else {
30 preconditionFailure("guessFaceOrders needs a step that readStep accepts")
31 }
32 return guessOrders(previous: previous, step: folding, interpolator: FoldInterpolator(file: draft, step: folding),
33 positions: next.verticesCoords, file: file, arrival: { $0.upperBound })
34}
35
36/// The guess for the faces at `positions`, a state of `step`; `arrival` gives the time within an
37/// axis's window at which its faces reach that state.
38func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpolator, positions: [SIMD3<Double>],
39 file: FoldFile, arrival: (ClosedRange<Double>) -> Double) -> [[Int]] {
40 let faces = file.facesVertices
41 let size = sheetExtent(file)
42 let normals = faceNormals(positions: positions, faces: faces)
43
44 var before: [SIMD2<Int>: Int] = [:]
45 for (pair, s) in rigidInvariantFaceOrders(previous.faceOrders, normals: faceNormals(previous, file))
46 where before[pair] == nil {
47 before[pair] = s
48 }
49 var axisOfFace: [Int: Int] = [:]
50 for (a, axis) in step.axes.enumerated() {
51 for f in axis.movingFaces { axisOfFace[f] = a }
52 }
53 func carriers(_ f: Int) -> Set<Int> {
54 var result = Set<Int>(), a = axisOfFace[f]
55 while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent }
56 return result
57 }
58
59 var sampled: [Double: [SIMD3<Double>]] = [:]
60 var orders: [[Int]] = []
61 for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) {
62 let differing = carriers(a).symmetricDifference(carriers(b))
63 let last = differing.max { (arrival(step.axes[$0].window), $0) < (arrival(step.axes[$1].window), $1) }
64 guard let last else {
65 if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) }
66 continue
67 }
68 let window = step.axes[last].window
69 let t = arrival(window) - arrivalLead * (window.upperBound - window.lowerBound)
70 let near = sampled[t] ?? interpolator.positions(at: t)
71 sampled[t] = near
72 let meeting = overlapCentre(a, b, positions, faces, normals)
73 let separation = dot(carry(meeting, on: faces[a], from: positions, to: near)
74 - carry(meeting, on: faces[b], from: positions, to: near), normals[b])
75 if abs(separation) > size * separationTolerance {
76 orders.append([a, b, separation > 0 ? 1 : -1])
77 } else if let s = before[SIMD2(a, b)] {
78 orders.append([a, b, s])
79 }
80 }
81 return orders
82}
83
84/// Replaces the order of each overridden pair, adding it when absent. Each override names its
85/// faces by points in the crease pattern and puts `above` nearer the eye than `below`; the result
86/// keeps every pair once as `[f, g, s]` with `f < g`, sorted.
87///
88/// - Throws: `CompileError.unresolvedFace` with step 0 when a point lies on no face; `compile`
89/// reports the step.
90public func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame,
91 viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]] {
92 guard !overrides.isEmpty else { return orders }
93 let normals = faceNormals(frame, file)
94 var result = orders
95 for o in overrides {
96 guard let above = face(containing: o.above, file) else {
97 throw CompileError.unresolvedFace(step: 0, point: o.above)
98 }
99 guard let below = face(containing: o.below, file) else {
100 throw CompileError.unresolvedFace(step: 0, point: o.below)
101 }
102 let s = dot(normals[below], viewpoint.eye) > 0 ? 1 : -1
103 let triple = above < below
104 ? [above, below, s]
105 : [below, above, dot(normals[above], normals[below]) > 0 ? -s : s]
106 result.removeAll { Set($0.prefix(2)) == Set([above, below]) }
107 result.append(triple)
108 }
109 return result.sorted { ($0[0], $0[1]) < ($1[0], $1[1]) }
110}
111
112/// Pairs `(a, b)`, `a < b`, of faces in one plane whose interiors overlap.
113private func overlappingPairs(_ positions: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>],
114 tolerance: Double) -> [(Int, Int)] {
115 var pairs: [(Int, Int)] = []
116 for a in faces.indices where normals[a] != .zero {
117 let corner = positions[faces[a][0]]
118 let (u, v) = planeBasis(normals[a])
119 let project = { (f: Int) in faces[f].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
120 let outline = project(a)
121 for b in faces.indices.dropFirst(a + 1) where normals[b] != .zero
122 && abs(dot(normals[a], normals[b])) >= parallelCosine
123 && faces[b].allSatisfy({ abs(dot(positions[$0] - corner, normals[a])) <= tolerance })
124 && convexPolygonsOverlap(outline, project(b), tolerance: tolerance) {
125 pairs.append((a, b))
126 }
127 }
128 return pairs
129}
130
131/// The centroid of the overlap of two coplanar faces, in their plane.
132private func overlapCentre(_ a: Int, _ b: Int, _ positions: [SIMD3<Double>], _ faces: [[Int]],
133 _ normals: [SIMD3<Double>]) -> SIMD3<Double> {
134 let n = normals[a]
135 let (u, v) = planeBasis(n)
136 let project = { (f: Int) in
137 counterclockwise(faces[f].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) })
138 }
139 var overlap = project(a)
140 let clip = project(b)
141 for i in clip.indices where !overlap.isEmpty {
142 overlap = keepLeft(of: clip[i], clip[(i + 1) % clip.count], overlap)
143 }
144 let c = centroid(overlap)
145 return c.x * u + c.y * v + dot(positions[faces[a][0]], n) * n
146}
147
148/// `point`, a point of the face with corners `corners` at `from`, where the same point of paper
149/// is at `to`. Both states must place the face rigidly.
150private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>], to: [SIMD3<Double>]) -> SIMD3<Double> {
151 // the corner triangle with the largest area gives the best-conditioned weights
152 var best = (0, 1, 2), largest = -1.0
153 for i in corners.indices {
154 for j in corners.indices where j > i {
155 for k in corners.indices where k > j {
156 let area = length(cross(from[corners[j]] - from[corners[i]], from[corners[k]] - from[corners[i]]))
157 if area > largest { (best, largest) = ((i, j, k), area) }
158 }
159 }
160 }
161 let (p, q, r) = (corners[best.0], corners[best.1], corners[best.2])
162 let e1 = from[q] - from[p], e2 = from[r] - from[p], d = point - from[p]
163 let d11 = dot(e1, e1), d12 = dot(e1, e2), d22 = dot(e2, e2)
164 let denominator = d11 * d22 - d12 * d12
165 let wq = (d22 * dot(d, e1) - d12 * dot(d, e2)) / denominator
166 let wr = (d11 * dot(d, e2) - d12 * dot(d, e1)) / denominator
167 return to[p] + wq * (to[q] - to[p]) + wr * (to[r] - to[p])
168}
169
170/// Two unit vectors spanning the plane with unit normal `n`.
171private func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) {
172 let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0)
173 let u = normalize(cross(n, helper))
174 return (u, cross(n, u))
175}
176
177private func signedArea(_ p: [SIMD2<Double>]) -> Double {
178 p.indices.reduce(0) { sum, i in
179 let a = p[i], b = p[(i + 1) % p.count]
180 return sum + (a.x * b.y - b.x * a.y) / 2
181 }
182}
183
184private func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
185 signedArea(p) < 0 ? p.reversed() : p
186}
187
188/// The area centroid of a polygon, or its corners' mean when it has no area.
189private func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> {
190 let area = signedArea(p)
191 guard abs(area) > 0 else { return p.reduce(.zero, +) / Double(max(p.count, 1)) }
192 var sum = SIMD2<Double>.zero
193 for i in p.indices {
194 let a = p[i], b = p[(i + 1) % p.count]
195 sum += (a + b) * (a.x * b.y - b.x * a.y)
196 }
197 return sum / (6 * area)
198}
199
200/// The part of convex polygon `p` to the left of the directed line from `a` to `b`.
201private func keepLeft(of a: SIMD2<Double>, _ b: SIMD2<Double>, _ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
202 let d = b - a
203 let side = p.map { d.x * ($0.y - a.y) - d.y * ($0.x - a.x) }
204 var result: [SIMD2<Double>] = []
205 for i in p.indices {
206 let j = (i + 1) % p.count
207 if side[i] >= 0 { result.append(p[i]) }
208 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
209 result.append(p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])))
210 }
211 }
212 return result
213}
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift added +307
@@ -0,0 +1,307 @@
1import FoldFormat
2import Folding
3import simd
4
5/// The spine's fold angle when the flap is open, in degrees from flat, when the script gives none.
6private let defaultOpenAngle = 30.0
7/// The boundaries of the pop on the step's t (decision 0002).
8private let phases = [1.0 / 3, 2.0 / 3]
9/// The largest relative change in a render-mesh edge's length the pop may reach (decision 0002).
10private let strainBound = 0.10
11/// Samples of the pop measured for strain.
12private let popSamples = 64
13/// Samples of the open and close phases along which end angles are unwrapped.
14private let angleSamples = 256
15
16/// Decision 0002's open, pop and close for step `n`, whose script names the `spine` its flap opens
17/// on. `before` is frame n − 1; `after` is frame n as the step's axes place it, carrying the step's
18/// record; `file` holds frames 0…n − 1.
19///
20/// The spine is the named crease and every edge on its line in `before`, each folded flat. The
21/// flap's layer nearer the viewpoint opens: the open axis turns the faces on that side of the
22/// spine, from ±180 to ±`openAngle`. The pop and close move on a tree cut along the spine and the
23/// step's creases, grown from the faces neither the opening nor the step moves, spine first. In
24/// `popped` the spine is held at ±`openAngle`, reversed where both its faces move in the step, and
25/// the other tree axes are solved to keep the paper whole, starting from `openAngle / 180` of
26/// their way. The close axes drive the named spine edge back to ±180 and solve the rest, as for a
27/// rigid step, and must arrive at `after`'s coordinates.
28///
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. A branch is caught when the close does not
31/// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the
32/// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixture's
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.
36///
37/// - Throws: `unresolvedCrease` when the spine names no edge, `invalidSpine` when it is not
38/// folded flat, `noRigidMotion` when the flap cannot open on its spine, `popped` does not close
39/// or the close does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%.
40public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame,
41 file: FoldFile) throws -> PopRecord {
42 guard let reference = script.spine, let record = after.step else {
43 preconditionFailure("compilePop needs a script step with a spine and a frame with its record")
44 }
45 let edgeFaces = edgesFaces(file)
46 let faceCount = file.facesVertices.count
47 let tolerance = sheetExtent(file) * relativeTolerance
48 let openAngle = script.openAngle ?? defaultOpenAngle
49
50 guard let named = resolve(reference, file, edgeFaces) else {
51 throw CompileError.unresolvedCrease(step: n, crease: reference)
52 }
53 let ends = file.edgesVertices[named].map { before.verticesCoords[$0] }
54 let spine = [named] + edgeFaces.indices.filter { e in
55 e != named && edgeFaces[e].count == 2
56 && file.edgesVertices[e].allSatisfy { onLine(before.verticesCoords[$0], ends[0], ends[1], tolerance) }
57 }
58 guard spine.allSatisfy({ abs(abs(before.edgesFoldAngle[$0]) - 180) <= angleSnapTolerance }) else {
59 throw CompileError.invalidSpine(step: n)
60 }
61
62 var group = Array(repeating: -1, count: faceCount)
63 for (a, axis) in record.axes.enumerated() {
64 for f in axis.movingFaces { group[f] = a }
65 }
66 let moving = group.map { $0 >= 0 }
67 let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] }
68
69 // the layer nearer the viewer opens: of the named edge's faces, the one a valley puts on the
70 // first face's normal side, or a mountain on the other
71 let (f, g) = (edgeFaces[named][0], edgeFaces[named][1])
72 let normals = faceNormals(before, file)
73 let gNearer = (before.edgesFoldAngle[named] > 0) == (dot(normals[f], record.viewpoint.eye) > 0)
74 let (near, far) = gNearer ? (g, f) : (f, g)
75 let sides = regions(cut: Set(spine), file, edgeFaces)
76 let opening = (0..<faceCount).filter { sides[$0] == sides[near] }
77 guard sides[far] != sides[near] else { throw CompileError.noRigidMotion(step: n) }
78 let openSign = before.edgesFoldAngle[named] > 0 ? 1.0 : -1.0
79 let openAxes = [AxisRecord(edge: named, movingFaces: opening, startAngle: before.edgesFoldAngle[named],
80 endAngle: openSign * openAngle, window: [0, phases[0]])]
81
82 // the tree the pop and the close move on
83 let fixed = Set((0..<faceCount).filter { !moving[$0] && !opening.contains($0) })
84 guard !fixed.isEmpty else { throw CompileError.noRigidMotion(step: n) }
85 let order = spine + record.axes.map(\.edge).filter { !spine.contains($0) }
86 + creased.filter { e in !spine.contains(e) && !record.axes.contains { $0.edge == e } }
87 let tree = growTree(order: order, fixed: fixed, file, edgeFaces)
88
89 // popped: the spine held open, reversed beyond the step's creases; the rest solved
90 func held(_ e: Int) -> Double {
91 let sign = before.edgesFoldAngle[e] > 0 ? 1.0 : -1.0
92 return (edgeFaces[e].allSatisfy { moving[$0] } ? -sign : sign) * openAngle
93 }
94 func closed(_ e: Int) -> Double {
95 spine.contains(e) ? (held(e) > 0 ? 180 : -180) : after.edgesFoldAngle[e]
96 }
97 var guess: [Int: Double] = [:]
98 for axis in tree.axes {
99 let start = before.edgesFoldAngle[axis.edge]
100 guess[axis.edge] = spine.contains(axis.edge) ? held(axis.edge)
101 : start + (closed(axis.edge) - start) * openAngle / 180
102 }
103 let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(spine), record, file)
104 var poppedFrame = before
105 poppedFrame.verticesCoords = popped.positions
106
107 let closeAxes = try closing(n, tree, from: poppedFrame, start: popped.angles, end: closed, record, file)
108 let pop = PopRecord(spine: spine, openAngle: openAngle, phases: phases, openAxes: openAxes,
109 popped: popped.positions, closeAxes: closeAxes)
110 var draft = file
111 draft.frames.append(FoldFrame(verticesCoords: after.verticesCoords, edgesAssignment: after.edgesAssignment,
112 edgesFoldAngle: after.edgesFoldAngle, faceOrders: [], step: withPop(record, pop)))
113 let interpolator = FoldInterpolator(file: draft, step: try readStep(n, in: draft))
114 guard zip(interpolator.positions(at: 1), after.verticesCoords).allSatisfy({ simd_distance($0, $1) <= tolerance }) else {
115 throw CompileError.noRigidMotion(step: n)
116 }
117 let worst = (0...popSamples).map { k in
118 let t = phases[0] + Double(k) / Double(popSamples) * (phases[1] - phases[0])
119 return strain(interpolator.meshPositions(at: t), mesh: interpolator.mesh)
120 }.max() ?? 0
121 guard worst <= strainBound else { throw CompileError.popTooStrained(step: n, strain: worst) }
122 return pop
123}
124
125/// `record`, flagged non-rigid, with `pop`.
126func withPop(_ record: StepRecord, _ pop: PopRecord) -> StepRecord {
127 StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes,
128 rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis, repeatOf: record.repeatOf,
129 nonRigid: true, pop: pop, viewpoint: record.viewpoint)
130}
131
132/// The fold angle at the end of a non-rigid step of every edge its close axes crease, measured
133/// from the faces' normals along the open phase, at `popped` and along the close phase, unwrapped
134/// from frame n − 1's angle and taken to be ±180 or 0 when within 1e-6° of one. A close axis's
135/// edge ends at its end angle exactly.
136func popEndAngles(_ step: FoldStep, _ interpolator: FoldInterpolator, previous: FoldFrame,
137 file: FoldFile) -> [Int: Double] {
138 guard let pop = step.pop else { return [:] }
139 let edgeFaces = edgesFaces(file)
140 var axisOfFace = Array(repeating: -1, count: file.facesVertices.count)
141 for (a, axis) in pop.closeAxes.enumerated() {
142 for f in axis.movingFaces { axisOfFace[f] = a }
143 }
144 let edges = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && axisOfFace[edgeFaces[$0][0]] != axisOfFace[edgeFaces[$0][1]] }
145
146 let (lower, upper) = (pop.phases.lowerBound, pop.phases.upperBound)
147 let times = (1...angleSamples).map { lower * Double($0) / Double(angleSamples) } + [upper]
148 + (1...angleSamples).map { upper + (1 - upper) * Double($0) / Double(angleSamples) }
149 var current = Dictionary(uniqueKeysWithValues: edges.map { ($0, previous.edgesFoldAngle[$0]) })
150 for t in times {
151 let positions = interpolator.positions(at: t)
152 let normals = faceNormals(positions: positions, faces: file.facesVertices)
153 for e in edges {
154 let measured = dihedral(e, edgeFaces[e], positions, normals, file)
155 current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded()
156 }
157 }
158 for (e, angle) in current {
159 current[e] = [180, -180, 0].first { abs(angle - $0) <= angleSnapTolerance } ?? angle
160 }
161 for axis in pop.closeAxes { current[axis.edge] = axis.endAngle }
162 return current
163}
164
165/// A tree of regions over the faces: the faces connected across edges not in `order`, grown from
166/// the regions holding a `fixed` face across the edges in `order`. Each tree edge is an axis
167/// moving its child region's faces; each other edge of `order` between different regions closes
168/// a loop.
169private struct RegionTree {
170 var axes: [(edge: Int, movingFaces: [Int], parent: Int?)]
171 var loops: [Int]
172}
173
174private func growTree(order: [Int], fixed: Set<Int>, _ file: FoldFile, _ edgeFaces: [[Int]]) -> RegionTree {
175 let region = regions(cut: Set(order), file, edgeFaces)
176 let regionCount = (region.max() ?? -1) + 1
177 var node = Array(repeating: -1, count: regionCount)
178 for f in fixed { node[region[f]] = 0 }
179 var nodeCount = 1
180 for r in 0..<regionCount where node[r] < 0 {
181 node[r] = nodeCount
182 nodeCount += 1
183 }
184 let nodeOfFace = region.map { node[$0] }
185
186 var component = Array(0..<nodeCount)
187 func find(_ x: Int) -> Int {
188 var x = x
189 while component[x] != x { x = component[x] }
190 return x
191 }
192 var links: [(edge: Int, ends: (Int, Int))] = []
193 var loops: [Int] = []
194 for e in order {
195 let a = nodeOfFace[edgeFaces[e][0]], b = nodeOfFace[edgeFaces[e][1]]
196 guard a != b else { continue }
197 if find(a) != find(b) {
198 component[find(a)] = find(b)
199 links.append((e, (a, b)))
200 } else {
201 loops.append(e)
202 }
203 }
204
205 var parentNode = Array<Int?>(repeating: nil, count: nodeCount)
206 var linkOfNode = Array<Int?>(repeating: nil, count: nodeCount)
207 var reached: Set<Int> = [0]
208 var queue = [0]
209 while !queue.isEmpty {
210 let a = queue.removeFirst()
211 for (k, link) in links.enumerated() where link.ends.0 == a || link.ends.1 == a {
212 let b = link.ends.0 == a ? link.ends.1 : link.ends.0
213 guard reached.insert(b).inserted else { continue }
214 parentNode[b] = a
215 linkOfNode[b] = k
216 queue.append(b)
217 }
218 }
219 let axes = links.enumerated().map { k, link in
220 let child = linkOfNode[link.ends.0] == k ? link.ends.0 : link.ends.1
221 return (edge: link.edge, movingFaces: nodeOfFace.indices.filter { nodeOfFace[$0] == child },
222 parent: parentNode[child].flatMap { linkOfNode[$0] })
223 }
224 return RegionTree(axes: axes, loops: loops)
225}
226
227/// The region of each face: faces connected across interior edges not in `cut`.
228private func regions(cut: Set<Int>, _ file: FoldFile, _ edgeFaces: [[Int]]) -> [Int] {
229 var region = Array(repeating: -1, count: file.facesVertices.count)
230 var count = 0
231 for seed in region.indices where region[seed] < 0 {
232 region[seed] = count
233 var stack = [seed]
234 while let f = stack.popLast() {
235 for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) {
236 let g = faces[0] == f ? faces[1] : faces[0]
237 if region[g] < 0 {
238 region[g] = count
239 stack.append(g)
240 }
241 }
242 }
243 count += 1
244 }
245 return region
246}
247
248/// The tree's axes as records from `start` angles to `end` angles, on `window`.
249private func records(_ tree: RegionTree, start: (Int) -> Double, end: (Int) -> Double,
250 window: [Double]?) -> [AxisRecord] {
251 tree.axes.map { axis in
252 AxisRecord(edge: axis.edge, movingFaces: axis.movingFaces, startAngle: start(axis.edge),
253 endAngle: end(axis.edge), parent: axis.parent, window: window)
254 }
255}
256
257/// `record` with `axes` in place of its own.
258private func withAxes(_ record: StepRecord, _ axes: [AxisRecord]) -> StepRecord {
259 StepRecord(kind: .fold, technique: record.technique, instruction: record.instruction, axes: axes,
260 viewpoint: record.viewpoint)
261}
262
263/// The pose with the tree's axes at `angles`, the edges in `holding` held there and the axes on a
264/// loop's cycle solved so the loops close. Returns the vertex positions and the solved angles.
265private func solvedPose(_ n: Int, _ tree: RegionTree, from before: FoldFrame, angles: [Int: Double],
266 holding: Set<Int>, _ record: StepRecord, _ file: FoldFile) throws
267 -> (positions: [SIMD3<Double>], angles: [Int: Double]) {
268 func draft(_ angles: [Int: Double]) -> FoldFile {
269 var draft = file
270 draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment,
271 edgesFoldAngle: before.edgesFoldAngle, faceOrders: [],
272 step: withAxes(record, records(tree, start: { before.edgesFoldAngle[$0] },
273 end: { angles[$0]! }, window: nil))))
274 return draft
275 }
276 var solved = angles
277 let first = draft(angles)
278 let step = try readStep(n, in: first)
279 let free = axesOnCycles(step, loops: tree.loops, first).filter { !holding.contains(step.axes[$0].edge) }.sorted()
280 var values = step.axes.map(\.endAngle)
281 let tolerance = sheetExtent(file) * relativeTolerance
282 guard LoopKinematics(step: step, file: first).solve(&values, free: free) <= tolerance else {
283 throw CompileError.noRigidMotion(step: n)
284 }
285 for (a, axis) in step.axes.enumerated() { solved[axis.edge] = values[a] }
286 let last = draft(solved)
287 return (FoldInterpolator(file: last, step: try readStep(n, in: last)).positions(at: 1), solved)
288}
289
290/// The close axes from `popped`: the named spine edge, first in the tree, linear from its popped
291/// angle to its end; the axes on a loop's cycle solved as for a rigid step; all on
292/// `[phases[1], 1]`.
293private func closing(_ n: Int, _ tree: RegionTree, from popped: FoldFrame, start: [Int: Double],
294 end: (Int) -> Double, _ record: StepRecord, _ file: FoldFile) throws -> [AxisRecord] {
295 var draft = file
296 draft.frames[n - 1] = popped
297 var close = withAxes(record, records(tree, start: { start[$0]! }, end: end, window: [phases[1], 1]))
298 draft.frames.append(FoldFrame(verticesCoords: popped.verticesCoords, edgesAssignment: popped.edgesAssignment,
299 edgesFoldAngle: popped.edgesFoldAngle, faceOrders: [], step: close))
300 var step = try readStep(n, in: draft)
301 guard !tree.loops.isEmpty else { return close.axes }
302 close = try solveLoops(n, close, step, loops: tree.loops, draft)
303 draft.frames[n].step = close
304 step = try readStep(n, in: draft)
305 try checkClosure(n, step, driver: close.axes[0].edge, draft, solved: close.axes.contains { $0.angles != nil })
306 return close.axes
307}
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +13
@@ -21,6 +21,12 @@ public enum FoldDefect: Equatable, Sendable {
21 case authorNotTraditional(String?) 21 case authorNotTraditional(String?)
22 case missingFirstCreasedAtStep(edge: Int) 22 case missingFirstCreasedAtStep(edge: Int)
23 case faceDistorted(frame: Int, face: Int) 23 case faceDistorted(frame: Int, face: Int)
24 /// A non-rigid step without a pop, or a pop whose `popped` lacks a position per vertex or
25 /// whose phases are not 0 < p0 < p1 < 1.
26 case popMalformed(step: Int)
27 /// In step `step`, the face `moving` departs toward the still face `still` it overlaps in
28 /// frame n − 1, or arrives from the side of it opposite the one frame n's order gives.
29 case movesThroughStillFace(step: Int, moving: Int, still: Int)
24} 30}
25 31
26/// Lengths are compared to within this fraction of the sheet's longer side. 32/// Lengths are compared to within this fraction of the sheet's longer side.
@@ -78,6 +84,13 @@ public func validate(_ file: FoldFile) -> [FoldDefect] {
78 if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil { 84 if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil {
79 defects.append(.foldAndUnfoldWithoutPeakOrder(step: n)) 85 defects.append(.foldAndUnfoldWithoutPeakOrder(step: n))
80 } 86 }
87 if step.nonRigid || step.pop != nil {
88 let wellFormed = step.pop.map { pop in
89 pop.popped.count == vertexCount && pop.phases.count == 2
90 && 0 < pop.phases[0] && pop.phases[0] < pop.phases[1] && pop.phases[1] < 1
91 } ?? false
92 if !wellFormed { defects.append(.popMalformed(step: n)) }
93 }
81 guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue } 94 guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue }
82 if frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) { 95 if frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) {
83 defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n)) 96 defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n))
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/angle-out-of-range.foldscript added +20
@@ -0,0 +1,20 @@
1{
2 "creasePattern": "half-cp.fold",
3 "title": "Angle out of range",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the right half to a right angle.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]],
10 "angles": [90]
11 },
12 {
13 "kind": "fold",
14 "instruction": "Fold the right half past flat.",
15 "creases": [[[1, 0], [1, 2]]],
16 "movingSide": [[1.5, 1]],
17 "angles": [200]
18 }
19 ]
20}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/half-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Half",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 2], [1, 2], [0, 2]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [1, 4]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "V"],
9 "faces_vertices": [[0, 1, 4, 5], [1, 2, 3, 4]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/half.foldscript added +22
@@ -0,0 +1,22 @@
1{
2 "creasePattern": "half-cp.fold",
3 "title": "Half",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the right half over to the left.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]]
10 },
11 {
12 "kind": "turnOver",
13 "instruction": "Turn the paper over from side to side.",
14 "turnOverAxis": "vertical"
15 },
16 {
17 "kind": "rotate",
18 "instruction": "Rotate the paper a quarter turn counterclockwise.",
19 "rotateDegrees": 90
20 }
21 ]
22}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Letter",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [3, 0], [3, 3], [2, 3], [1, 3], [0, 3]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 6], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "M"],
9 "faces_vertices": [[0, 1, 6, 7], [1, 2, 5, 6], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-sequential-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Letter, sequential",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [3, 0], [3, 3], [2, 3], [1, 3], [0, 3]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 6], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "V"],
9 "faces_vertices": [[0, 1, 6, 7], [1, 2, 5, 6], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-sequential.foldscript added +19
@@ -0,0 +1,19 @@
1{
2 "creasePattern": "letter-sequential-cp.fold",
3 "title": "Letter, sequential",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the left third over.",
8 "creases": [[[1, 0], [1, 3]]],
9 "movingSide": [[0.5, 1.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Repeat on the right: valley fold the right third over the top.",
14 "creases": [[[2, 0], [2, 3]]],
15 "movingSide": [[2.5, 1.5]],
16 "repeatOf": 1
17 }
18 ]
19}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-staggered-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Letter, staggered",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [3, 0], [3, 3], [2, 3], [1, 3], [0, 3]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 6], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "V"],
9 "faces_vertices": [[0, 1, 6, 7], [1, 2, 5, 6], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-staggered.foldscript added +13
@@ -0,0 +1,13 @@
1{
2 "creasePattern": "letter-staggered-cp.fold",
3 "title": "Letter, staggered",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the left third over, then the right third over the top.",
8 "creases": [[[1, 0], [1, 3]], [[2, 0], [2, 3]]],
9 "movingSide": [[0.5, 1.5], [2.5, 1.5]],
10 "windows": [[0, 0.5], [0.5, 1]]
11 }
12 ]
13}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter.foldscript added +12
@@ -0,0 +1,12 @@
1{
2 "creasePattern": "letter-cp.fold",
3 "title": "Letter",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the left third over and mountain fold the right third behind.",
8 "creases": [[[1, 0], [1, 3]], [[2, 0], [2, 3]]],
9 "movingSide": [[0.5, 1.5], [2.5, 1.5]]
10 }
11 ]
12}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/mountain-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Mountain",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 2], [1, 2], [0, 2]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [1, 4]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "M"],
9 "faces_vertices": [[0, 1, 4, 5], [1, 2, 3, 4]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/mountain.foldscript added +12
@@ -0,0 +1,12 @@
1{
2 "creasePattern": "mountain-cp.fold",
3 "title": "Mountain",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Mountain fold the right half behind.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]]
10 }
11 ]
12}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/occlusion-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Occlusion",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [2, 0], [2.5, 0], [4, 0], [4, 4], [2.5, 4], [0, 4], [0, 2]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [7, 1], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "V"],
9 "faces_vertices": [[0, 1, 7], [1, 2, 5, 6, 7], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/occlusion.foldscript added +23
@@ -0,0 +1,23 @@
1{
2 "creasePattern": "occlusion-cp.fold",
3 "title": "Occlusion",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the bottom left corner up to the centre.",
8 "creases": [[[0, 2], [2, 0]]],
9 "movingSide": [[0.5, 0.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Valley fold the right edge over along the crease.",
14 "creases": [[[2.5, 0], [2.5, 4]]],
15 "movingSide": [[3, 2]]
16 },
17 {
18 "kind": "turnOver",
19 "instruction": "Turn the paper over from side to side.",
20 "turnOverAxis": "vertical"
21 }
22 ]
23}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/quarters-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Quarters",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2], [1, 2], [0, 2], [0, 1], [1, 1]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 8], [8, 5], [7, 8], [8, 3]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "M", "V", "V"],
9 "faces_vertices": [[0, 1, 8, 7], [1, 2, 3, 8], [8, 3, 4, 5], [7, 8, 5, 6]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/quarters.foldscript added +24
@@ -0,0 +1,24 @@
1{
2 "creasePattern": "quarters-cp.fold",
3 "title": "Quarters",
4 "steps": [
5 {
6 "kind": "foldAndUnfold",
7 "instruction": "Valley fold in half from right to left and unfold.",
8 "creases": [[[1, 0], [1, 1]]],
9 "movingSide": [[1.5, 0.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Valley fold the top half down.",
14 "creases": [[[0, 1], [1, 1]]],
15 "movingSide": [[0.5, 1.5]]
16 },
17 {
18 "kind": "fold",
19 "instruction": "Valley fold the right half over to the left.",
20 "creases": [[[1, 0], [1, 1]]],
21 "movingSide": [[1.5, 0.5]]
22 }
23 ]
24}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-cp.fold added +11
@@ -0,0 +1,11 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Reverse fold",
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 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0],
8 [7, 8], [8, 3], [8, 1], [8, 5]],
9 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "M", "V", "V"],
10 "faces_vertices": [[0, 1, 8, 7], [1, 2, 3, 8], [8, 3, 4, 5], [7, 8, 5, 6]]
11}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse.foldscript added +21
@@ -0,0 +1,21 @@
1{
2 "creasePattern": "reverse-cp.fold",
3 "title": "Reverse fold",
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.5, 0.5]],
17 "spine": [[0, 1], [2, 1]],
18 "faceOrders": [{"above": [3.5, 1.5], "below": [3.5, 0.5]}]
19 }
20 ]
21}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/unresolved-crease.foldscript added +18
@@ -0,0 +1,18 @@
1{
2 "creasePattern": "half-cp.fold",
3 "title": "Unresolved crease",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the right half over to the left.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Fold along a crease the pattern does not have.",
14 "creases": [[[0, 1], [1, 1]]],
15 "movingSide": [[0.5, 1.5]]
16 }
17 ]
18}
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +220
@@ -1,4 +1,5 @@
1import Foundation 1import Foundation
2import FoldCompiler
2import FoldFormat 3import FoldFormat
3import Folding 4import Folding
4import simd 5import simd
@@ -88,6 +89,38 @@ public func degreeFourVertex(linear: Bool = false) -> FoldFile {
88 ) 89 )
89} 90}
90 91
92/// `degreeFourVertex()` as a crease pattern: its sheet and creases with their final assignments,
93/// no frames.
94public func degreeFourPattern() -> FoldFile {
95 let vertex = degreeFourVertex()
96 return FoldFile(
97 fileSpec: 1.2,
98 fileTitle: vertex.fileTitle,
99 fileAuthor: vertex.fileAuthor,
100 fileClasses: ["creasePattern"],
101 edgesVertices: vertex.edgesVertices,
102 facesVertices: vertex.facesVertices,
103 edgesFirstCreasedAtStep: vertex.edgesVertices.map { _ in nil },
104 frames: [FoldFrame(verticesCoords: vertex.frames[0].verticesCoords,
105 edgesAssignment: vertex.frames[1].edgesAssignment,
106 edgesFoldAngle: vertex.edgesVertices.map { _ in 0 },
107 faceOrders: [])]
108 )
109}
110
111/// `degreeFourVertex()` as a one-step script: the 140° crease drives, then the 260°, 0° and 60°
112/// creases in that order, so the 60° crease closes the loop. The 120° sector is held.
113public func degreeFourScript() -> FoldScript {
114 func inside(_ degrees: Double) -> SIMD2<Double> {
115 SIMD2(1 + 0.5 * cos(radians(degrees)), 1 + 0.5 * sin(radians(degrees)))
116 }
117 return FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
118 ScriptStep(kind: .fold, instruction: "Fold the vertex flat.",
119 creases: [.edgeIndex(10), .edgeIndex(11), .edgeIndex(8), .edgeIndex(9)],
120 movingSide: [inside(30), inside(100), inside(310)]),
121 ])
122}
123
91/// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form. 124/// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form.
92public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double { 125public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double {
93 let k = cos(radians(70)) / cos(radians(10)) 126 let k = cos(radians(70)) / cos(radians(10))
@@ -287,3 +320,190 @@ public func interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpol
287 ) 320 )
288 return (file, FoldInterpolator(file: file, step: step)) 321 return (file, FoldInterpolator(file: file, step: step))
289} 322}
323
324/// `<name>.foldscript` compiled against `<name>-cp.fold`.
325public func compiled(_ name: String) throws -> FoldFile {
326 try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
327 pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
328}
329
330/// Whether two files have the same metadata, topology, assignments, layer orders and steps, with
331/// coordinates, angles and pop phases within `tolerance`. Face orders compare as sets;
332/// `file_creator` is ignored.
333public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool {
334 guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor,
335 a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices,
336 a.facesVertices == b.facesVertices, a.edgesFirstCreasedAtStep == b.edgesFirstCreasedAtStep,
337 a.frames.count == b.frames.count else { return false }
338 return zip(a.frames, b.frames).allSatisfy { framesAgree($0, $1, tolerance) }
339}
340
341private func close(_ a: [Double], _ b: [Double], _ tolerance: Double) -> Bool {
342 a.count == b.count && zip(a, b).allSatisfy { abs($0 - $1) <= tolerance }
343}
344
345private func close(_ a: Double?, _ b: Double?, _ tolerance: Double) -> Bool {
346 switch (a, b) {
347 case (nil, nil): true
348 case let (x?, y?): abs(x - y) <= tolerance
349 default: false
350 }
351}
352
353private func framesAgree(_ a: FoldFrame, _ b: FoldFrame, _ tolerance: Double) -> Bool {
354 let flatten = { (points: [SIMD3<Double>]) in points.flatMap { [$0.x, $0.y, $0.z] } }
355 let orders = { (list: [[Int]]?) in list.map(Set.init) }
356 guard close(flatten(a.verticesCoords), flatten(b.verticesCoords), tolerance),
357 a.edgesAssignment == b.edgesAssignment,
358 close(a.edgesFoldAngle, b.edgesFoldAngle, tolerance),
359 a.faceOrders.count == b.faceOrders.count, Set(a.faceOrders) == Set(b.faceOrders),
360 orders(a.faceOrdersMidFold) == orders(b.faceOrdersMidFold) else { return false }
361 switch (a.step, b.step) {
362 case (nil, nil): return true
363 case let (x?, y?): return stepsAgree(x, y, tolerance)
364 default: return false
365 }
366}
367
368private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) -> Bool {
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,
371 close(a.rotateDegrees, b.rotateDegrees, tolerance), a.turnOverAxis == b.turnOverAxis,
372 a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid,
373 close(view(a.viewpoint), view(b.viewpoint), tolerance) else { return false }
374 switch (a.pop, b.pop) {
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
391 x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent
392 && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance)
393 && close(x.peakAngle, y.peakAngle, tolerance)
394 && close(x.window ?? [0, 1], y.window ?? [0, 1], tolerance)
395 && (x.angles == nil) == (y.angles == nil) && close(x.angles ?? [], y.angles ?? [], tolerance)
396 }
397}
398
399/// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point
400/// (2.75, 0.75) lies strictly between the body's two layers: the planes of the faces containing
401/// 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
402/// not over both layers.
403public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool {
404 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
405 func face(containing p: SIMD2<Double>) -> Int? {
406 file.facesVertices.indices.first { f in
407 let corners = file.facesVertices[f].map { flat[$0] }
408 return corners.indices.allSatisfy { i in
409 let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = p - a
410 return side.x * offset.y - side.y * offset.x >= 0
411 }
412 }
413 }
414 // the sheet point p of face f, where f's corners are at `positions`
415 func place(_ p: SIMD2<Double>, on f: Int) -> SIMD3<Double> {
416 let c = file.facesVertices[f]
417 let (a, b, d) = (flat[c[0]], flat[c[1]], flat[c[2]])
418 let u = b - a, v = d - a, w = p - a
419 let det = u.x * v.y - u.y * v.x
420 let s = (w.x * v.y - w.y * v.x) / det, r = (u.x * w.y - u.y * w.x) / det
421 return positions[c[0]] + s * (positions[c[1]] - positions[c[0]]) + r * (positions[c[2]] - positions[c[0]])
422 }
423 // the height of face f's plane above (x, y), when (x, y) lies over the face
424 func height(of f: Int, at q: SIMD2<Double>) -> Double? {
425 let corners = file.facesVertices[f].map { positions[$0] }
426 let n = faceNormals(positions: positions, faces: [file.facesVertices[f]])[0]
427 guard abs(n.z) > 1e-12 else { return nil }
428 let outline = corners.map { SIMD2($0.x, $0.y) }
429 let turn = n.z > 0 ? 1.0 : -1.0
430 let inside = outline.indices.allSatisfy { i in
431 let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = q - a
432 return turn * (side.x * offset.y - side.y * offset.x) >= 0
433 }
434 guard inside else { return nil }
435 return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z
436 }
437 guard let tip = face(containing: SIMD2(2.75, 0.75)), let lower = face(containing: SIMD2(0.5, 0.5)),
438 let upper = face(containing: SIMD2(0.5, 1.5)) else { return false }
439 let probe = place(SIMD2(2.75, 0.75), on: tip)
440 let q = SIMD2(probe.x, probe.y)
441 guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false }
442 return probe.z > min(a, b) && probe.z < max(a, b)
443}
444
445extension FoldScript {
446 /// This script with step `step`'s `openAngle` set to `degrees`. Steps count from 1.
447 public func withOpenAngle(_ degrees: Double, step: Int) -> FoldScript {
448 editing(step) { replacing($0, spine: $0.spine, openAngle: degrees) }
449 }
450
451 /// This script with step `step`'s `spine` removed. Steps count from 1.
452 public func withoutSpine(step: Int) -> FoldScript {
453 editing(step) { replacing($0, spine: nil, openAngle: $0.openAngle) }
454 }
455
456 private func editing(_ step: Int, _ change: (ScriptStep) -> ScriptStep) -> FoldScript {
457 var list = steps
458 list[step - 1] = change(list[step - 1])
459 return FoldScript(creasePattern: creasePattern, title: title, steps: list)
460 }
461}
462
463private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -> ScriptStep {
464 ScriptStep(kind: s.kind, technique: s.technique, instruction: s.instruction, creases: s.creases,
465 movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees,
466 turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders,
467 faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine,
468 openAngle: openAngle)
469}
470
471/// The repository's `Models/` directory: this file's path with its last five components, up to
472/// and including `Packages`, replaced by `Models`.
473private let modelsDirectory = URL(fileURLWithPath: #filePath)
474 .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
475 .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models")
476
477/// `Models/<name>.foldscript`.
478public func script(_ name: String) -> URL {
479 modelsDirectory.appendingPathComponent("\(name).foldscript")
480}
481
482/// `Models/<name>-cp.fold`.
483public func pattern(_ name: String) -> URL {
484 modelsDirectory.appendingPathComponent("\(name)-cp.fold")
485}
486
487#if os(macOS)
488/// Runs the built `foldlint` on `url`, returning its exit status and its standard output and
489/// error together. The executable is beside the test bundle, which may hold this module's
490/// resource bundle, or beside the resource bundle itself.
491public func runFoldlint(on url: URL) throws -> (exitCode: Int32, output: String) {
492 let beside = Bundle.module.bundleURL.deletingLastPathComponent()
493 var testBundle = beside
494 while testBundle.pathComponents.count > 1 && testBundle.pathExtension != "xctest" {
495 testBundle.deleteLastPathComponent()
496 }
497 let products = testBundle.pathExtension == "xctest" ? testBundle.deletingLastPathComponent() : beside
498 let process = Process()
499 process.executableURL = products.appendingPathComponent("foldlint")
500 process.arguments = [url.path]
501 let pipe = Pipe()
502 process.standardOutput = pipe
503 process.standardError = pipe
504 try process.run()
505 let output = pipe.fileHandleForReading.readDataToEndOfFile()
506 process.waitUntilExit()
507 return (process.terminationStatus, String(decoding: output, as: UTF8.self))
508}
509#endif
Packages/FoldKit/Sources/Folding/Bending.swift added +133
@@ -0,0 +1,133 @@
1import Accelerate
2import simd
3
4/// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces
5/// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by
6/// `s` of its face's rotation from the first pose to the second (slerp), and the mesh vertices
7/// are the least-squares fit to those edges, with the vertices of held faces kept where the first
8/// pose has them. At `s = 0` and `s = 1` the fit is exact, so it reproduces both poses.
9struct Bending: Sendable {
10 /// The mesh vertices in the first pose.
11 private let rest: [SIMD3<Double>]
12 /// Per FOLD face, its rotation from the first pose to the second.
13 private let turns: [simd_quatd]
14 /// The mesh vertices that move, in the solve's row order.
15 private let free: [Int]
16 /// Per row and FOLD face, the signed sum of the rest edge vectors of that face's triangles at
17 /// the row's vertex; the right-hand side adds each turned by `s` of the face's turn.
18 private let terms: [(row: Int, face: Int, vector: SIMD3<Double>)]
19 /// Per row, what the held vertices contribute to the normal equation's right-hand side.
20 private let held: [SIMD3<Double>]
21 private let factor: SparseCholesky
22
23 /// - Parameters:
24 /// - first, second: the FOLD vertex positions of two rigid poses.
25 /// - heldFaces: FOLD faces placed alike in both poses, whose mesh vertices stay put.
26 init(mesh: RenderMesh, faces: [[Int]], from first: [SIMD3<Double>], to second: [SIMD3<Double>],
27 heldFaces: Set<Int>) {
28 rest = mesh.pose(first)
29 turns = faces.map { corners in
30 // one corner triple for both poses, chosen on the flat sheet so ties cannot split
31 let flat = corners.map { mesh.vertices[mesh.meshVertexOf[$0]] }
32 let c = widestCorners(flat).map { corners[$0] }
33 var q = simd_quatd(frame(c.map { second[$0] }) * frame(c.map { first[$0] }).transpose)
34 if q.real < 0 { q = simd_quatd(vector: -q.vector) }
35 return q
36 }
37
38 var isHeld = Array(repeating: false, count: mesh.vertices.count)
39 for (t, (a, b, c)) in mesh.triangles.enumerated() where heldFaces.contains(mesh.faceOf[t]) {
40 (isHeld[a], isHeld[b], isHeld[c]) = (true, true, true)
41 }
42 free = mesh.vertices.indices.filter { !isHeld[$0] }
43 var row = Array(repeating: -1, count: mesh.vertices.count)
44 for (r, v) in free.enumerated() { row[v] = r }
45
46 // Σ over triangle edges (i, j) of |x_j − x_i − d_ij|²: the normal matrix is the edge
47 // Laplacian; held vertices move to the right-hand side.
48 var matrix: [SIMD2<Int>: Double] = [:]
49 var sums: [SIMD2<Int>: SIMD3<Double>] = [:]
50 var held = Array(repeating: SIMD3<Double>.zero, count: free.count)
51 for (t, (a, b, c)) in mesh.triangles.enumerated() {
52 let face = mesh.faceOf[t]
53 for (i, j) in [(a, b), (b, c), (c, a)] {
54 let d = rest[j] - rest[i]
55 for (v, other, sign) in [(i, j, -1.0), (j, i, 1.0)] where row[v] >= 0 {
56 matrix[SIMD2(row[v], row[v]), default: 0] += 1
57 sums[SIMD2(row[v], face), default: .zero] += sign * d
58 if row[other] >= 0 {
59 if row[other] < row[v] { matrix[SIMD2(row[v], row[other]), default: 0] -= 1 }
60 } else {
61 held[row[v]] += rest[other]
62 }
63 }
64 }
65 }
66 terms = sums.keys.sorted { ($0.x, $0.y) < ($1.x, $1.y) }.map { ($0.x, $0.y, sums[$0]!) }
67 self.held = held
68 factor = SparseCholesky(size: free.count, lower: matrix)
69 }
70
71 /// The mesh vertex positions at `s` in 0...1.
72 func positions(at s: Double) -> [SIMD3<Double>] {
73 let identity = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
74 let turned = turns.map { simd_slerp(identity, $0, s) }
75 let n = free.count
76 var rhs = [Double](repeating: 0, count: 3 * n)
77 for (r, h) in held.enumerated() {
78 rhs[r] = h.x
79 rhs[n + r] = h.y
80 rhs[2 * n + r] = h.z
81 }
82 for (r, face, vector) in terms {
83 let d = turned[face].act(vector)
84 rhs[r] += d.x
85 rhs[n + r] += d.y
86 rhs[2 * n + r] += d.z
87 }
88 factor.solve(&rhs, columns: 3)
89 var result = rest
90 for (r, v) in free.enumerated() { result[v] = SIMD3(rhs[r], rhs[n + r], rhs[2 * n + r]) }
91 return result
92 }
93}
94
95/// An orthonormal frame fixed to the triangle `p`: along its first side, across it in its plane,
96/// and along its normal.
97private func frame(_ p: [SIMD3<Double>]) -> simd_double3x3 {
98 let along = normalize(p[1] - p[0]), normal = normalize(cross(p[1] - p[0], p[2] - p[0]))
99 return simd_double3x3(columns: (along, cross(normal, along), normal))
100}
101
102/// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. Only read after
103/// `init`, so sharing it across threads is safe.
104private final class SparseCholesky: @unchecked Sendable {
105 private let factor: SparseOpaqueFactorization_Double
106 private let size: Int
107
108 /// `lower` holds the entries on and below the diagonal, keyed by (row, column).
109 init(size: Int, lower: [SIMD2<Int>: Double]) {
110 self.size = size
111 let keys = lower.keys.sorted { ($0.y, $0.x) < ($1.y, $1.x) }
112 let rows = keys.map { Int32($0.x) }, columns = keys.map { Int32($0.y) }, values = keys.map { lower[$0]! }
113 var attributes = SparseAttributes_t()
114 attributes.triangle = SparseLowerTriangle
115 attributes.kind = SparseSymmetric
116 let matrix = SparseConvertFromCoordinate(Int32(size), Int32(size), keys.count, 1, attributes,
117 rows, columns, values)
118 defer { SparseCleanup(matrix) }
119 factor = SparseFactor(SparseFactorizationCholesky, matrix)
120 precondition(factor.status == SparseStatusOK, "the pop's normal matrix is not positive definite")
121 }
122
123 deinit { SparseCleanup(factor) }
124
125 /// Solves in place for `columns` right-hand sides of `size` values each, one after another.
126 func solve(_ values: inout [Double], columns: Int) {
127 values.withUnsafeMutableBufferPointer { buffer in
128 let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size),
129 attributes: SparseAttributes_t(), data: buffer.baseAddress!)
130 SparseSolve(factor, b)
131 }
132 }
133}
Packages/FoldKit/Sources/Folding/FoldInterpolator.swift +97 −44
@@ -1,60 +1,109 @@
1import FoldFormat 1import FoldFormat
2import simd 2import simd
3 3
4/// Interpolates a rigid step from frame `step.index − 1` to frame `step.index`. 4/// Interpolates step `step.index` from frame `step.index − 1` to frame `step.index`.
5/// 5///
6/// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an 6/// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an
7/// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates 7/// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates
8/// the whole of the start frame about its bounding-box centre. Steps flagged `nonRigid` are not 8/// the whole of the start frame about its bounding-box centre. A step flagged `nonRigid` moves by
9/// handled here. 9/// its pop (decision 0002): `openAxes` rigidly on `[0, phases.lowerBound]`, the render mesh bent
10/// from the open pose to `popped` on the phases, and `closeAxes` rigidly from `popped` on
11/// `[phases.upperBound, 1]`.
10public struct FoldInterpolator: Sendable { 12public struct FoldInterpolator: Sendable {
13 /// Rigid motions of the faces about a step's axes, from `start`.
11 private struct Motion: Sendable { 14 private struct Motion: Sendable {
12 let step: FoldStep 15 let axes: [FoldAxis]
16 let kind: StepKind
17 let start: [SIMD3<Double>]
13 /// Per axis, the vertices that take their position from that axis's face group. 18 /// Per axis, the vertices that take their position from that axis's face group.
14 let vertices: [[Int]] 19 let vertices: [[Int]]
20
21 init(axes: [FoldAxis], kind: StepKind, start: [SIMD3<Double>], faces: [[Int]]) {
22 self.axes = axes
23 self.kind = kind
24 self.start = start
25 var axisOfFace: [Int: Int] = [:]
26 for (a, axis) in axes.enumerated() {
27 for f in axis.movingFaces { axisOfFace[f] = a }
28 }
29 // a vertex takes its position from the first face containing it
30 var owner = Array<Int?>(repeating: nil, count: start.count)
31 var seen = Array(repeating: false, count: start.count)
32 for (f, face) in faces.enumerated() {
33 for v in face where !seen[v] {
34 seen[v] = true
35 owner[v] = axisOfFace[f]
36 }
37 }
38 var groups = Array(repeating: [Int](), count: axes.count)
39 for (v, a) in owner.enumerated() {
40 if let a { groups[a].append(v) }
41 }
42 vertices = groups
43 }
44
45 func positions(at t: Double) -> [SIMD3<Double>] {
46 // each axis's full transform: its own rotation, then its parent's
47 var full: [Transform] = []
48 full.reserveCapacity(axes.count)
49 for axis in axes {
50 let degrees = axis.angle(at: t, kind: kind) - axis.startAngle
51 let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction)
52 let own = Transform(rotation: simd_double3x3(q), about: axis.origin)
53 full.append(axis.parent.map { full[$0].after(own) } ?? own)
54 }
55 var result = start
56 for (a, group) in vertices.enumerated() {
57 for v in group { result[v] = full[a].apply(start[v]) }
58 }
59 return result
60 }
15 } 61 }
16 62
17 private struct Reorientation: Sendable { 63 private struct Reorientation: Sendable {
64 let start: [SIMD3<Double>]
18 let centre: SIMD3<Double> 65 let centre: SIMD3<Double>
19 let axis: SIMD3<Double> 66 let axis: SIMD3<Double>
20 /// Radians at t = 1. 67 /// Radians at t = 1.
21 let angle: Double 68 let angle: Double
22 } 69 }
23 70
71 private struct NonRigid: Sendable {
72 let open: Motion
73 let close: Motion
74 let phases: ClosedRange<Double>
75 let bending: Bending
76 }
77
24 private enum Mode: Sendable { 78 private enum Mode: Sendable {
25 case folds(Motion) 79 case folds(Motion)
26 case reorient(Reorientation) 80 case reorient(Reorientation)
81 case nonRigid(NonRigid)
27 } 82 }
28 83
29 private let start: [SIMD3<Double>] 84 /// The render mesh of the file's frame 0, at `RenderMesh.spacing(for:)`.
30 private let kind: StepKind 85 public let mesh: RenderMesh
31 private let mode: Mode 86 private let mode: Mode
32 87
33 public init(file: FoldFile, step: FoldStep) { 88 public init(file: FoldFile, step: FoldStep) {
34 precondition(!step.nonRigid, "FoldInterpolator handles rigid steps only; the non-rigid path is added by Task 7b") 89 let start = file.frames[step.index - 1].verticesCoords
35 start = file.frames[step.index - 1].verticesCoords 90 mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
36 kind = step.kind 91
92 if step.nonRigid {
93 guard let pop = step.pop else { preconditionFailure("a non-rigid step has a pop; readStep checks it") }
94 let open = Motion(axes: pop.openAxes, kind: .fold, start: start, faces: file.facesVertices)
95 let close = Motion(axes: pop.closeAxes, kind: .fold, start: pop.popped, faces: file.facesVertices)
96 let moving = step.movingFaceUnion
97 let bending = Bending(mesh: mesh, faces: file.facesVertices,
98 from: open.positions(at: pop.phases.lowerBound), to: pop.popped,
99 heldFaces: Set(file.facesVertices.indices.filter { !moving.contains($0) }))
100 mode = .nonRigid(NonRigid(open: open, close: close, phases: pop.phases, bending: bending))
101 return
102 }
37 103
38 switch step.kind { 104 switch step.kind {
39 case .fold, .foldAndUnfold: 105 case .fold, .foldAndUnfold:
40 var axisOfFace: [Int: Int] = [:] 106 mode = .folds(Motion(axes: step.axes, kind: step.kind, start: start, faces: file.facesVertices))
41 for (a, axis) in step.axes.enumerated() {
42 for f in axis.movingFaces { axisOfFace[f] = a }
43 }
44 // a vertex takes its position from the first face containing it
45 var owner = Array<Int?>(repeating: nil, count: start.count)
46 var seen = Array(repeating: false, count: start.count)
47 for (f, face) in file.facesVertices.enumerated() {
48 for v in face where !seen[v] {
49 seen[v] = true
50 owner[v] = axisOfFace[f]
51 }
52 }
53 var groups = Array(repeating: [Int](), count: step.axes.count)
54 for (v, a) in owner.enumerated() {
55 if let a { groups[a].append(v) }
56 }
57 mode = .folds(Motion(step: step, vertices: groups))
58 107
59 case .turnOver, .rotate: 108 case .turnOver, .rotate:
60 var lower = start[0], upper = start[0] 109 var lower = start[0], upper = start[0]
@@ -71,34 +120,38 @@ public struct FoldInterpolator: Sendable {
71 axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up 120 axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up
72 degrees = 180 121 degrees = 180
73 } 122 }
74 mode = .reorient(Reorientation(centre: (lower + upper) / 2, axis: axis, 123 mode = .reorient(Reorientation(start: start, centre: (lower + upper) / 2, axis: axis,
75 angle: degrees * .pi / 180)) 124 angle: degrees * .pi / 180))
76 } 125 }
77 } 126 }
78 127
79 /// The vertex positions at `t` of the step, `t` in 0...1. 128 /// The vertex positions at `t` of the step, `t` in 0...1. During a pop, the mesh positions of
129 /// the FOLD vertices.
80 public func positions(at t: Double) -> [SIMD3<Double>] { 130 public func positions(at t: Double) -> [SIMD3<Double>] {
81 switch mode { 131 switch mode {
82 case .reorient(let r): 132 case .reorient(let r):
83 let q = simd_quatd(angle: r.angle * t, axis: r.axis) 133 let q = simd_quatd(angle: r.angle * t, axis: r.axis)
84 return start.map { r.centre + q.act($0 - r.centre) } 134 return r.start.map { r.centre + q.act($0 - r.centre) }
85 135
86 case .folds(let motion): 136 case .folds(let motion):
87 // each axis's full transform: its own rotation, then its parent's 137 return motion.positions(at: t)
88 var full: [Transform] = [] 138
89 full.reserveCapacity(motion.step.axes.count) 139 case .nonRigid(let p):
90 for axis in motion.step.axes { 140 if t <= p.phases.lowerBound { return p.open.positions(at: t) }
91 let degrees = axis.angle(at: t, kind: kind) - axis.startAngle 141 if t >= p.phases.upperBound { return p.close.positions(at: t) }
92 let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction) 142 let points = meshPositions(at: t)
93 let own = Transform(rotation: simd_double3x3(q), about: axis.origin) 143 return mesh.meshVertexOf.map { points[$0] }
94 full.append(axis.parent.map { full[$0].after(own) } ?? own) 144 }
95 } 145 }
96 var result = start 146
97 for (a, group) in motion.vertices.enumerated() { 147 /// The render mesh's vertex positions at `t` of the step: each face's rigid placement applied
98 for v in group { result[v] = full[a].apply(start[v]) } 148 /// to its mesh vertices, or during a pop the bent mesh.
99 } 149 public func meshPositions(at t: Double) -> [SIMD3<Double>] {
100 return result 150 if case .nonRigid(let p) = mode, t > p.phases.lowerBound, t < p.phases.upperBound {
151 let s = (t - p.phases.lowerBound) / (p.phases.upperBound - p.phases.lowerBound)
152 return p.bending.positions(at: s)
101 } 153 }
154 return mesh.pose(positions(at: t))
102 } 155 }
103} 156}
104 157
Packages/FoldKit/Sources/Folding/Interpenetration.swift +35 −12
@@ -31,30 +31,53 @@ private let coplanarOffset = 1e-6
31/// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's. 31/// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's.
32/// The sheet's size is the longest side of the bounding box of the positions at `t = 0`. 32/// The sheet's size is the longest side of the bounding box of the positions at `t = 0`.
33public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] { 33public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] {
34 intersections(polygons: faces, faceOf: Array(faces.indices), samples: samples, at: interpolator.positions(at:))
35}
36
37/// `interpenetrations` on the render mesh's triangles at `meshPositions(at:)`, reporting the FOLD
38/// faces they lie in. Triangles of one face are not tested against each other. For non-rigid
39/// steps, whose faces bend during the pop.
40public func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection] {
41 let mesh = interpolator.mesh
42 return intersections(polygons: mesh.triangles.map { [$0.0, $0.1, $0.2] }, faceOf: mesh.faceOf,
43 samples: samples, at: interpolator.meshPositions(at:))
44}
45
46/// The pairs of faces, `faceOf` each polygon, whose polygons pass through each other at some
47/// sample, each reported once at the first such sample, in face order within a sample.
48private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: Int,
49 at positions: (Double) -> [SIMD3<Double>]) -> [Intersection] {
34 precondition(samples > 0, "interpenetrations needs at least one sample") 50 precondition(samples > 0, "interpenetrations needs at least one sample")
35 let size = boundingExtent(interpolator.positions(at: 0)).max() 51 let size = boundingExtent(positions(0)).max()
36 let usable = faces.indices.filter { faces[$0].count >= 3 } 52 let usable = corners.indices.filter { corners[$0].count >= 3 }
37 53
38 var found: [Intersection] = [] 54 var found: [Intersection] = []
39 var reported = Set<SIMD2<Int>>() 55 var reported = Set<SIMD2<Int>>()
40 for k in 0...samples { 56 for k in 0...samples {
41 let t = Double(k) / Double(samples) 57 let t = Double(k) / Double(samples)
42 let positions = interpolator.positions(at: t) 58 let points = positions(t)
43 let normals = faceNormals(positions: positions, faces: faces) 59 let normals = faceNormals(positions: points, faces: corners)
44 let polygons = faces.map { $0.map { positions[$0] } } 60 let polygons = corners.map { $0.map { points[$0] } }
45 let boxes = polygons.map(bounds) 61 let boxes = polygons.map(bounds)
46 62 // sweep along x: a pair can meet only when their boxes' x-ranges do
47 for (n, a) in usable.enumerated() where normals[a] != .zero { 63 let order = usable.filter { normals[$0] != .zero }.sorted { boxes[$0].lower.x < boxes[$1].lower.x }
48 for b in usable[(n + 1)...] where normals[b] != .zero { 64
49 let pair = SIMD2(a, b) 65 var hits = Set<SIMD2<Int>>()
50 guard !reported.contains(pair), boxesMeet(boxes[a], boxes[b]), 66 for (n, a) in order.enumerated() {
67 for b in order[(n + 1)...] {
68 guard boxes[b].lower.x - contactTolerance <= boxes[a].upper.x else { break }
69 let pair = SIMD2(min(faceOf[a], faceOf[b]), max(faceOf[a], faceOf[b]))
70 guard pair.x != pair.y, boxesMeet(boxes[a], boxes[b]), !reported.contains(pair), !hits.contains(pair),
51 !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size), 71 !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size),
52 passThrough(polygons[a], normals[a], polygons[b], normals[b]) 72 passThrough(polygons[a], normals[a], polygons[b], normals[b])
53 else { continue } 73 else { continue }
54 reported.insert(pair) 74 hits.insert(pair)
55 found.append(Intersection(faceA: a, faceB: b, t: t))
56 } 75 }
57 } 76 }
77 for pair in hits.sorted(by: { ($0.x, $0.y) < ($1.x, $1.y) }) {
78 reported.insert(pair)
79 found.append(Intersection(faceA: pair.x, faceB: pair.y, t: t))
80 }
58 } 81 }
59 return found 82 return found
60} 83}
Packages/FoldKit/Sources/Folding/LayerMotion.swift added +180
@@ -0,0 +1,180 @@
1import FoldFormat
2import simd
3
4/// How long after a face starts moving, and before it stops, its side of a still face is read, as
5/// a fraction of the window of the axis that starts or stops it. The compiler's layer-order guess
6/// reads arrivals at the same moment.
7private let lead = 1e-3
8/// Two unit normals whose dot product's magnitude reaches this lie on one line.
9private let parallelCosine = 1 - 1e-9
10/// Lengths are compared to within this fraction of the sheet's longer side.
11private let relativeTolerance = 1e-6
12/// A face closer than this fraction of the sheet's size to a still face's plane is on neither side.
13private let separationTolerance = 1e-9
14
15/// Faces that pass through a still face as they start or finish moving: the coplanar contact that
16/// the validator, which reads one frame at a time, and the interpenetration checker, which skips
17/// coplanar faces, cannot see.
18///
19/// In step n, a moving face that overlaps a still face in frame n − 1 may not leave toward the
20/// side of it opposite the one frame n − 1's `faceOrders` give, read just after the face starts
21/// moving; a moving face that overlaps a still face in frame n may not arrive from the side
22/// opposite the one frame n's `faceOrders` give, read just before it stops. Pairs the orders do
23/// not relate are not checked. A face is still when none of the step's axes moves it, counting a
24/// non-rigid step's open and close axes, so the faces that open on the spine are moving.
25/// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the
26/// pop between is not. Turn-over and rotate steps move every face together and have no still face.
27///
28/// 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///
33/// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped.
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 }
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 }
52 var defects: [FoldDefect] = []
53 var reported = Set<SIMD2<Int>>()
54 for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false)
55 where reported.insert(SIMD2(m, s)).inserted {
56 defects.append(.movesThroughStillFace(step: n, moving: m, still: s))
57 }
58 return defects
59}
60
61/// The pairs `(moving, still)` in which a face `axes` move is, just after it starts moving
62/// (`departure`) or just before it stops, on the side of a still face it overlaps in `frame`
63/// opposite the one `frame`'s orders give.
64private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, still: (Int) -> Bool,
65 interpolator: FoldInterpolator, file: FoldFile, size: Double) -> [(Int, Int)] {
66 let tolerance = size * relativeTolerance
67 let faces = file.facesVertices
68 let points = frame.verticesCoords
69 let normals = faceNormals(positions: points, faces: faces)
70 var axisOfFace: [Int: Int] = [:]
71 for (a, axis) in axes.enumerated() {
72 for f in axis.movingFaces { axisOfFace[f] = a }
73 }
74
75 var sampled: [Double: [SIMD3<Double>]] = [:]
76 var result: [(Int, Int)] = []
77 for m in axisOfFace.keys.sorted() where normals[m] != .zero {
78 var carriers: [Int] = [], a = axisOfFace[m]
79 while let axis = a, !carriers.contains(axis) {
80 carriers.append(axis)
81 a = axes[axis].parent
82 }
83 let t: Double
84 if departure {
85 let w = carriers.map { axes[$0].window }.min { $0.lowerBound < $1.lowerBound }!
86 t = w.lowerBound + lead * (w.upperBound - w.lowerBound)
87 } else {
88 let w = axes[carriers.max { (axes[$0].window.upperBound, $0) < (axes[$1].window.upperBound, $1) }!].window
89 t = w.upperBound - lead * (w.upperBound - w.lowerBound)
90 }
91 let near = sampled[t] ?? interpolator.positions(at: t)
92 sampled[t] = near
93
94 for s in faces.indices where s != m && still(s) && normals[s] != .zero
95 && overlap(m, s, points, faces, normals, tolerance: tolerance) {
96 guard let side = side(of: m, from: s, frame.faceOrders, normals) else { continue }
97 let centre = overlapCentre(m, s, points, faces, normals)
98 let offset = dot(carry(centre, on: faces[m], from: points, to: near) - centre, normals[s])
99 if abs(offset) > size * separationTolerance && (offset > 0) != (side > 0) {
100 result.append((m, s))
101 }
102 }
103 }
104 return result
105}
106
107/// The side of face `s` along its normal on which `orders` put face `m`: +1 the side the normal
108/// points toward, −1 the other, nil when no triple relates them.
109private func side(of m: Int, from s: Int, _ orders: [[Int]], _ normals: [SIMD3<Double>]) -> Int? {
110 for t in orders where t.count == 3 && (t[2] == 1 || t[2] == -1) {
111 if t[0] == m && t[1] == s { return t[2] }
112 if t[0] == s && t[1] == m { return dot(normals[m], normals[s]) > 0 ? -t[2] : t[2] }
113 }
114 return nil
115}
116
117/// Whether faces `a` and `b` lie in one plane and their interiors overlap.
118private func overlap(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>],
119 tolerance: Double) -> Bool {
120 guard abs(dot(normals[a], normals[b])) >= parallelCosine else { return false }
121 let corner = points[faces[b][0]]
122 guard faces[a].allSatisfy({ abs(dot(points[$0] - corner, normals[b])) <= tolerance }) else { return false }
123 let (u, v) = planeBasis(normals[b])
124 let project = { (f: Int) in faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) } }
125 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
126}
127
128/// The centroid of the overlap of two coplanar faces, in the plane of `b`.
129private func overlapCentre(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]],
130 _ normals: [SIMD3<Double>]) -> SIMD3<Double> {
131 let n = normals[b]
132 let (u, v) = planeBasis(n)
133 let project = { (f: Int) in counterclockwise(faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) }) }
134 var common = project(a)
135 let clip = project(b)
136 for i in clip.indices where !common.isEmpty {
137 common = keepLeft(of: clip[i], clip[(i + 1) % clip.count], common)
138 }
139 let c = centroid(common)
140 return c.x * u + c.y * v + dot(points[faces[b][0]], n) * n
141}
142
143/// `point`, a point of the face with corners `corners` at `from`, where the same point of paper
144/// is at `to`. Both states place the face rigidly.
145private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>],
146 to: [SIMD3<Double>]) -> SIMD3<Double> {
147 let first = corners[0]
148 let far = corners.max { distance(from[$0], from[first]) < distance(from[$1], from[first]) }!
149 func frame(_ p: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>) {
150 let u = normalize(p[far] - p[first])
151 let n = faceNormals(positions: p, faces: [corners])[0]
152 return (u, cross(n, u), n)
153 }
154 let (u, v, n) = frame(from), (u2, v2, n2) = frame(to)
155 let d = point - from[first]
156 return to[first] + dot(d, u) * u2 + dot(d, v) * v2 + dot(d, n) * n2
157}
158
159/// The part of convex polygon `p` to the left of the directed line from `a` to `b`.
160private func keepLeft(of a: SIMD2<Double>, _ b: SIMD2<Double>, _ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
161 let d = b - a
162 let side = p.map { d.x * ($0.y - a.y) - d.y * ($0.x - a.x) }
163 var result: [SIMD2<Double>] = []
164 for i in p.indices {
165 let j = (i + 1) % p.count
166 if side[i] >= 0 { result.append(p[i]) }
167 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
168 result.append(p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])))
169 }
170 }
171 return result
172}
173
174/// The longer side of frame 0's bounding box.
175private func sheetExtent(_ file: FoldFile) -> Double {
176 let points = file.frames[0].verticesCoords
177 let lower = points.dropFirst().reduce(points[0], simd_min)
178 let upper = points.dropFirst().reduce(points[0], simd_max)
179 return (upper - lower).max()
180}
Packages/FoldKit/Sources/Folding/LayerOrder.swift +3 −3
@@ -245,7 +245,7 @@ private func boundingBoxDiagonal(_ points: [SIMD3<Double>]) -> Double {
245} 245}
246 246
247/// Two unit vectors spanning the plane with unit normal `n`. 247/// Two unit vectors spanning the plane with unit normal `n`.
248private func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) { 248func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) {
249 let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0) 249 let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0)
250 let u = normalize(cross(n, helper)) 250 let u = normalize(cross(n, helper))
251 return (u, cross(n, u)) 251 return (u, cross(n, u))
@@ -260,11 +260,11 @@ private func signedArea(_ p: [SIMD2<Double>]) -> Double {
260 260
261private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) } 261private func area(_ p: [SIMD2<Double>]) -> Double { abs(signedArea(p)) }
262 262
263private func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] { 263func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
264 signedArea(p) < 0 ? p.reversed() : p 264 signedArea(p) < 0 ? p.reversed() : p
265} 265}
266 266
267private func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> { 267func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> {
268 var sum = SIMD2<Double>.zero 268 var sum = SIMD2<Double>.zero
269 for i in p.indices { 269 for i in p.indices {
270 let a = p[i], b = p[(i + 1) % p.count] 270 let a = p[i], b = p[(i + 1) % p.count]
Packages/FoldKit/Sources/Folding/RenderMesh.swift added +199
@@ -0,0 +1,199 @@
1import FoldFormat
2import simd
3
4/// The triangles the renderer draws, finer than the FOLD faces: frame 0's faces cut by lines
5/// every `spacing` in x and in y, each resulting convex cell fanned into triangles. Cells on both
6/// sides of an edge share its vertices, so the mesh is one connected sheet. The FOLD topology is
7/// unchanged; a non-rigid step bends this mesh, not the FOLD faces.
8public struct RenderMesh: Sendable {
9 /// Frame 0 positions in its plane.
10 public let vertices: [SIMD2<Double>]
11 public let triangles: [(Int, Int, Int)]
12 /// The FOLD face each triangle lies in.
13 public let faceOf: [Int]
14 /// The mesh vertex at each FOLD vertex.
15 public let meshVertexOf: [Int]
16 /// Each mesh vertex as a point of one FOLD face, for placing it in a rigid pose.
17 private let anchors: [Anchor]
18
19 /// A point of a face: `corners[0] + a·(corners[1] − corners[0]) + b·(corners[2] − corners[0])`.
20 private struct Anchor: Sendable {
21 let corners: SIMD3<Int>
22 let a: Double
23 let b: Double
24 }
25
26 public init(file: FoldFile, spacing: Double) {
27 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
28 let lower = flat.dropFirst().reduce(flat[0], simd_min)
29 let upper = flat.dropFirst().reduce(flat[0], simd_max)
30 let size = (upper - lower).max()
31 let tolerance = size * 1e-9
32 let xs = lines(from: lower.x, to: upper.x, spacing: spacing, tolerance: tolerance)
33 let ys = lines(from: lower.y, to: upper.y, spacing: spacing, tolerance: tolerance)
34
35 var points = PointSet(tolerance: tolerance)
36 var triangles: [(Int, Int, Int)] = []
37 var faceOf: [Int] = []
38 var anchors: [Int: Anchor] = [:]
39 for (f, face) in file.facesVertices.enumerated() {
40 var cells = [face.map { flat[$0] }]
41 for x in xs { cells = cells.flatMap { split($0, at: x, axis: 0, tolerance: tolerance) } }
42 for y in ys { cells = cells.flatMap { split($0, at: y, axis: 1, tolerance: tolerance) } }
43 let corners = widestCorners(face.map { flat[$0] })
44 let origin = flat[face[corners[0]]]
45 let u = flat[face[corners[1]]] - origin, v = flat[face[corners[2]]] - origin
46 let det = u.x * v.y - u.y * v.x
47 func point(_ p: SIMD2<Double>) -> Int {
48 let id = points.index(of: p)
49 if anchors[id] == nil {
50 let w = points.points[id] - origin
51 anchors[id] = Anchor(corners: SIMD3(face[corners[0]], face[corners[1]], face[corners[2]]),
52 a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det)
53 }
54 return id
55 }
56 for cell in cells {
57 var ids: [Int] = []
58 for p in cell {
59 let id = point(p)
60 if ids.last != id && ids.first != id { ids.append(id) }
61 }
62 guard ids.count >= 3 else { continue }
63 var fanned = fan(ids, points.points, minimumArea: tolerance * size)
64 if fanned == nil {
65 let centre = ids.reduce(SIMD2<Double>.zero) { $0 + points.points[$1] } / Double(ids.count)
66 fanned = fan(ids, around: point(centre))
67 }
68 for triangle in fanned! {
69 triangles.append(triangle)
70 faceOf.append(f)
71 }
72 }
73 }
74 meshVertexOf = flat.map { points.index(of: $0) }
75 vertices = points.points
76 self.triangles = triangles
77 self.faceOf = faceOf
78 self.anchors = vertices.indices.map { anchors[$0]! }
79 }
80
81 /// Frame 0's bounding box's longer side / 32.
82 public static func spacing(for file: FoldFile) -> Double {
83 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
84 let lower = flat.dropFirst().reduce(flat[0], simd_min)
85 let upper = flat.dropFirst().reduce(flat[0], simd_max)
86 return (upper - lower).max() / 32
87 }
88
89 /// The mesh vertices when the FOLD vertices are at `positions`, each face placed rigidly.
90 func pose(_ positions: [SIMD3<Double>]) -> [SIMD3<Double>] {
91 anchors.map { anchor in
92 let o = positions[anchor.corners.x]
93 return o + anchor.a * (positions[anchor.corners.y] - o) + anchor.b * (positions[anchor.corners.z] - o)
94 }
95 }
96}
97
98/// The largest relative change in a mesh edge's length against frame 0.
99public func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double {
100 var worst = 0.0
101 for (a, b, c) in mesh.triangles {
102 for (i, j) in [(a, b), (b, c), (c, a)] {
103 let rest = simd_distance(mesh.vertices[i], mesh.vertices[j])
104 worst = max(worst, abs(simd_distance(positions[i], positions[j]) - rest) / rest)
105 }
106 }
107 return worst
108}
109
110/// The grid lines strictly inside `low...high`: `low + k·spacing` for k ≥ 1.
111private func lines(from low: Double, to high: Double, spacing: Double, tolerance: Double) -> [Double] {
112 var result: [Double] = []
113 var k = 1.0
114 while low + k * spacing < high - tolerance {
115 result.append(low + k * spacing)
116 k += 1
117 }
118 return result
119}
120
121/// A convex polygon cut by the line where coordinate `axis` equals `value`, or the polygon itself
122/// when the line does not cross it. Crossing points lie exactly on the line.
123private func split(_ polygon: [SIMD2<Double>], at value: Double, axis: Int, tolerance: Double) -> [[SIMD2<Double>]] {
124 let d = polygon.map { $0[axis] - value }
125 guard d.contains(where: { $0 < -tolerance }), d.contains(where: { $0 > tolerance }) else { return [polygon] }
126 var below: [SIMD2<Double>] = [], above: [SIMD2<Double>] = []
127 for i in polygon.indices {
128 let j = (i + 1) % polygon.count
129 if d[i] <= tolerance { below.append(polygon[i]) }
130 if d[i] >= -tolerance { above.append(polygon[i]) }
131 if (d[i] < -tolerance && d[j] > tolerance) || (d[i] > tolerance && d[j] < -tolerance) {
132 var crossing = polygon[i] + (polygon[j] - polygon[i]) * (d[i] / (d[i] - d[j]))
133 crossing[axis] = value
134 below.append(crossing)
135 above.append(crossing)
136 }
137 }
138 return [below, above]
139}
140
141/// A convex cell, its corners counterclockwise, fanned from the first corner whose fan has no
142/// triangle of `minimumArea` or less; nil when every corner's fan does. A corner on a straight
143/// side would otherwise be left out of every triangle.
144private func fan(_ ids: [Int], _ points: [SIMD2<Double>], minimumArea: Double) -> [(Int, Int, Int)]? {
145 for apex in ids.indices {
146 let ring = (0..<ids.count).map { ids[(apex + $0) % ids.count] }
147 let triangles = (1..<(ring.count - 1)).map { (ring[0], ring[$0], ring[$0 + 1]) }
148 let flat = triangles.contains { a, b, c in
149 let (p, q, r) = (points[a], points[b], points[c])
150 return ((q - p).x * (r - p).y - (q - p).y * (r - p).x) / 2 <= minimumArea
151 }
152 if !flat { return triangles }
153 }
154 return nil
155}
156
157/// A convex cell fanned around an added point `centre` inside it.
158private func fan(_ ids: [Int], around centre: Int) -> [(Int, Int, Int)] {
159 ids.indices.map { (centre, ids[$0], ids[($0 + 1) % ids.count]) }
160}
161
162/// The indices of the three corners spanning the largest triangle, the first such in index order.
163func widestCorners(_ corners: [SIMD2<Double>]) -> [Int] {
164 var best = [0, 1, 2], largest = -1.0
165 for i in corners.indices {
166 for j in corners.indices where j > i {
167 for k in corners.indices where k > j {
168 let u = corners[j] - corners[i], v = corners[k] - corners[i]
169 let area = abs(u.x * v.y - u.y * v.x)
170 if area > largest { (best, largest) = ([i, j, k], area) }
171 }
172 }
173 }
174 return best
175}
176
177/// Points merged within a tolerance, found through a grid of buckets one tolerance wide.
178private struct PointSet {
179 let tolerance: Double
180 private(set) var points: [SIMD2<Double>] = []
181 private var buckets: [SIMD2<Int64>: [Int]] = [:]
182
183 init(tolerance: Double) { self.tolerance = tolerance }
184
185 /// The index of the point within the tolerance of `p`, added when there is none.
186 mutating func index(of p: SIMD2<Double>) -> Int {
187 let key = SIMD2(Int64((p.x / tolerance).rounded(.down)), Int64((p.y / tolerance).rounded(.down)))
188 for dx in -1...1 {
189 for dy in -1...1 {
190 for i in buckets[key &+ SIMD2(Int64(dx), Int64(dy))] ?? [] where simd_distance(points[i], p) <= tolerance {
191 return i
192 }
193 }
194 }
195 points.append(p)
196 buckets[key, default: []].append(points.count - 1)
197 return points.count - 1
198 }
199}
Packages/FoldKit/Sources/Folding/StepReader.swift +11 −5
@@ -6,11 +6,17 @@ import simd
6/// - Precondition: `validate(file)` is empty. On a file it rejects, this may trap on an 6/// - Precondition: `validate(file)` is empty. On a file it rejects, this may trap on an
7/// out-of-range index. 7/// out-of-range index.
8public func readSteps(_ file: FoldFile) throws -> [FoldStep] { 8public func readSteps(_ file: FoldFile) throws -> [FoldStep] {
9 let edgeFaces = edgesFaces(file) 9 try file.frames.indices.dropFirst().map { n in try readStep(n, in: file) }
10 return try file.frames.indices.dropFirst().map { n in 10}
11 guard let record = file.frames[n].step else { throw FoldError.missingStepRecord(step: n) } 11
12 return try readStep(n, record, file, edgeFaces) 12/// Reads step `n` from frame n's `krz:step`, directing its axes against frame n − 1's
13 } 13/// coordinates. Only frames 0…n are read, so frames after n need not exist.
14///
15/// - Precondition: frames 0…n are well formed: frame n − 1 has a coordinate for every vertex
16/// and the topology's indices are in range.
17public func readStep(_ n: Int, in file: FoldFile) throws -> FoldStep {
18 guard let record = file.frames[n].step else { throw FoldError.missingStepRecord(step: n) }
19 return try readStep(n, record, file, edgesFaces(file))
14} 20}
15 21
16private func readStep(_ n: Int, _ record: StepRecord, _ file: FoldFile, _ edgeFaces: [[Int]]) throws -> FoldStep { 22private func readStep(_ n: Int, _ record: StepRecord, _ file: FoldFile, _ edgeFaces: [[Int]]) throws -> FoldStep {
Packages/FoldKit/Sources/Models/ModelLibrary.swift added +34
@@ -0,0 +1,34 @@
1import FoldFormat
2import Foundation
3
4public enum ModelLibraryError: Error, Equatable, Sendable {
5 case noModel(named: String)
6}
7
8/// The shipped models: `Resources/<name>.fold`, each generated by `foldc` from
9/// `Models/<name>.foldscript` and `Models/<name>-cp.fold`.
10public enum ModelLibrary {
11 /// Every model, in the order of `names()`.
12 public static func all() throws -> [FoldFile] {
13 try names().map(model(named:))
14 }
15
16 /// The models' names, sorted.
17 public static func names() throws -> [String] {
18 try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
19 .filter { $0.pathExtension == "fold" }
20 .map { $0.deletingPathExtension().lastPathComponent }
21 .sorted()
22 }
23
24 public static func model(named name: String) throws -> FoldFile {
25 let url = directory.appendingPathComponent("\(name).fold")
26 guard FileManager.default.fileExists(atPath: url.path) else { throw ModelLibraryError.noModel(named: name) }
27 return try FoldFile(contentsOf: url)
28 }
29
30 /// The resource directory the package copies in.
31 private static var directory: URL {
32 Bundle.module.url(forResource: "Resources", withExtension: nil)!
33 }
34}
Packages/FoldKit/Sources/Models/Resources/cup.fold added +1469
@@ -0,0 +1,1469 @@
1{
2 "edges_assignment" : [
3 "B",
4 "B",
5 "B",
6 "B",
7 "B",
8 "B",
9 "B",
10 "B",
11 "F",
12 "F",
13 "F",
14 "F",
15 "F",
16 "F",
17 "F",
18 "F",
19 "F"
20 ],
21 "edges_foldAngle" : [
22 0,
23 0,
24 0,
25 0,
26 0,
27 0,
28 0,
29 0,
30 0,
31 0,
32 0,
33 0,
34 0,
35 0,
36 0,
37 0,
38 0
39 ],
40 "edges_krz:firstCreasedAtStep" : [
41 null,
42 null,
43 null,
44 null,
45 null,
46 null,
47 null,
48 null,
49 1,
50 1,
51 1,
52 2,
53 2,
54 3,
55 3,
56 4,
57 6
58 ],
59 "edges_vertices" : [
60 [
61 0,
62 1
63 ],
64 [
65 1,
66 2
67 ],
68 [
69 2,
70 3
71 ],
72 [
73 3,
74 4
75 ],
76 [
77 4,
78 5
79 ],
80 [
81 5,
82 6
83 ],
84 [
85 6,
86 7
87 ],
88 [
89 7,
90 0
91 ],
92 [
93 6,
94 8
95 ],
96 [
97 8,
98 9
99 ],
100 [
101 9,
102 2
103 ],
104 [
105 9,
106 3
107 ],
108 [
109 9,
110 1
111 ],
112 [
113 8,
114 5
115 ],
116 [
117 8,
118 7
119 ],
120 [
121 7,
122 1
123 ],
124 [
125 5,
126 3
127 ]
128 ],
129 "faceOrders" : [
130
131 ],
132 "faces_vertices" : [
133 [
134 7,
135 0,
136 1
137 ],
138 [
139 7,
140 1,
141 9,
142 8
143 ],
144 [
145 1,
146 2,
147 9
148 ],
149 [
150 6,
151 7,
152 8
153 ],
154 [
155 6,
156 8,
157 5
158 ],
159 [
160 8,
161 9,
162 3,
163 5
164 ],
165 [
166 9,
167 2,
168 3
169 ],
170 [
171 5,
172 3,
173 4
174 ]
175 ],
176 "file_author" : "Traditional",
177 "file_classes" : [
178 "diagrams"
179 ],
180 "file_frames" : [
181 {
182 "edges_assignment" : [
183 "B",
184 "B",
185 "B",
186 "B",
187 "B",
188 "B",
189 "B",
190 "B",
191 "V",
192 "V",
193 "V",
194 "F",
195 "F",
196 "F",
197 "F",
198 "F",
199 "F"
200 ],
201 "edges_foldAngle" : [
202 0,
203 0,
204 0,
205 0,
206 0,
207 0,
208 0,
209 0,
210 180,
211 180,
212 180,
213 0,
214 0,
215 0,
216 0,
217 0,
218 0
219 ],
220 "faceOrders" : [
221 [
222 0,
223 7,
224 1
225 ],
226 [
227 1,
228 5,
229 1
230 ],
231 [
232 2,
233 6,
234 1
235 ],
236 [
237 3,
238 4,
239 1
240 ]
241 ],
242 "frame_inherit" : true,
243 "frame_parent" : 0,
244 "krz:step" : {
245 "axes" : [
246 {
247 "edge" : 9,
248 "endAngle" : 180,
249 "movingFaces" : [
250 0,
251 1,
252 2,
253 3
254 ],
255 "startAngle" : 0
256 }
257 ],
258 "instruction" : "Valley fold in half along the diagonal, bottom corner up to the top corner.",
259 "kind" : "fold",
260 "nonRigid" : false,
261 "technique" : "plain",
262 "viewpoint" : {
263 "eye" : [
264 0,
265 0,
266 1
267 ],
268 "up" : [
269 0,
270 1,
271 0
272 ]
273 }
274 },
275 "vertices_coords" : [
276 [
277 1,
278 2,
279 1.2246467991473532e-16
280 ],
281 [
282 1.4142135623730951,
283 1.5857864376269049,
284 7.173814858237197e-17
285 ],
286 [
287 2,
288 1,
289 0
290 ],
291 [
292 1.4142135623730951,
293 1.5857864376269049,
294 0
295 ],
296 [
297 1,
298 2,
299 0
300 ],
301 [
302 0.5857864376269049,
303 1.5857864376269049,
304 0
305 ],
306 [
307 0,
308 1,
309 0
310 ],
311 [
312 0.5857864376269049,
313 1.5857864376269049,
314 7.173814858237197e-17
315 ],
316 [
317 0.8284271247461903,
318 1,
319 0
320 ],
321 [
322 1.1715728752538097,
323 1,
324 0
325 ]
326 ]
327 },
328 {
329 "edges_assignment" : [
330 "B",
331 "B",
332 "B",
333 "B",
334 "B",
335 "B",
336 "B",
337 "B",
338 "V",
339 "V",
340 "V",
341 "V",
342 "M",
343 "F",
344 "F",
345 "F",
346 "F"
347 ],
348 "edges_foldAngle" : [
349 0,
350 0,
351 0,
352 0,
353 0,
354 0,
355 0,
356 0,
357 180,
358 180,
359 180,
360 180,
361 -180,
362 0,
363 0,
364 0,
365 0
366 ],
367 "faceOrders" : [
368 [
369 0,
370 7,
371 1
372 ],
373 [
374 1,
375 2,
376 -1
377 ],
378 [
379 1,
380 5,
381 1
382 ],
383 [
384 1,
385 6,
386 1
387 ],
388 [
389 2,
390 5,
391 1
392 ],
393 [
394 2,
395 6,
396 1
397 ],
398 [
399 3,
400 4,
401 1
402 ],
403 [
404 5,
405 6,
406 1
407 ]
408 ],
409 "frame_inherit" : true,
410 "frame_parent" : 0,
411 "krz:step" : {
412 "axes" : [
413 {
414 "edge" : 11,
415 "endAngle" : 180,
416 "movingFaces" : [
417 2,
418 6
419 ],
420 "startAngle" : 0
421 }
422 ],
423 "instruction" : "Valley fold the right corner across to touch the left edge, so that the top edge of the flap is level.",
424 "kind" : "fold",
425 "nonRigid" : false,
426 "technique" : "plain",
427 "viewpoint" : {
428 "eye" : [
429 0,
430 0,
431 1
432 ],
433 "up" : [
434 0,
435 1,
436 0
437 ]
438 }
439 },
440 "vertices_coords" : [
441 [
442 1,
443 2,
444 1.2246467991473532e-16
445 ],
446 [
447 1.4142135623730951,
448 1.5857864376269049,
449 7.173814858237197e-17
450 ],
451 [
452 0.5857864376269052,
453 1.5857864376269053,
454 9.373040810652596e-17
455 ],
456 [
457 1.4142135623730951,
458 1.5857864376269049,
459 0
460 ],
461 [
462 1,
463 2,
464 0
465 ],
466 [
467 0.5857864376269049,
468 1.5857864376269049,
469 0
470 ],
471 [
472 0,
473 1,
474 0
475 ],
476 [
477 0.5857864376269049,
478 1.5857864376269049,
479 7.173814858237197e-17
480 ],
481 [
482 0.8284271247461903,
483 1,
484 0
485 ],
486 [
487 1.1715728752538097,
488 1,
489 0
490 ]
491 ]
492 },
493 {
494 "edges_assignment" : [
495 "B",
496 "B",
497 "B",
498 "B",
499 "B",
500 "B",
501 "B",
502 "B",
503 "V",
504 "V",
505 "V",
506 "V",
507 "M",
508 "V",
509 "M",
510 "F",
511 "F"
512 ],
513 "edges_foldAngle" : [
514 0,
515 0,
516 0,
517 0,
518 0,
519 0,
520 0,
521 0,
522 180,
523 180,
524 180,
525 180,
526 -180,
527 180,
528 -180,
529 0,
530 0
531 ],
532 "faceOrders" : [
533 [
534 0,
535 7,
536 1
537 ],
538 [
539 1,
540 2,
541 -1
542 ],
543 [
544 1,
545 3,
546 -1
547 ],
548 [
549 1,
550 4,
551 1
552 ],
553 [
554 1,
555 5,
556 1
557 ],
558 [
559 1,
560 6,
561 1
562 ],
563 [
564 2,
565 3,
566 -1
567 ],
568 [
569 2,
570 4,
571 1
572 ],
573 [
574 2,
575 5,
576 1
577 ],
578 [
579 2,
580 6,
581 1
582 ],
583 [
584 3,
585 4,
586 1
587 ],
588 [
589 3,
590 5,
591 1
592 ],
593 [
594 3,
595 6,
596 -1
597 ],
598 [
599 4,
600 5,
601 1
602 ],
603 [
604 4,
605 6,
606 -1
607 ],
608 [
609 5,
610 6,
611 1
612 ]
613 ],
614 "frame_inherit" : true,
615 "frame_parent" : 0,
616 "krz:step" : {
617 "axes" : [
618 {
619 "edge" : 13,
620 "endAngle" : 180,
621 "movingFaces" : [
622 3,
623 4
624 ],
625 "startAngle" : 0
626 }
627 ],
628 "instruction" : "Valley fold the left corner across to touch the right edge, over the first flap.",
629 "kind" : "fold",
630 "nonRigid" : false,
631 "technique" : "plain",
632 "viewpoint" : {
633 "eye" : [
634 0,
635 0,
636 1
637 ],
638 "up" : [
639 0,
640 1,
641 0
642 ]
643 }
644 },
645 "vertices_coords" : [
646 [
647 1,
648 2,
649 1.2246467991473532e-16
650 ],
651 [
652 1.4142135623730951,
653 1.5857864376269049,
654 7.173814858237197e-17
655 ],
656 [
657 0.5857864376269052,
658 1.5857864376269053,
659 9.373040810652596e-17
660 ],
661 [
662 1.4142135623730951,
663 1.5857864376269049,
664 0
665 ],
666 [
667 1,
668 2,
669 0
670 ],
671 [
672 0.5857864376269046,
673 1.5857864376269049,
674 0
675 ],
676 [
677 1.4142135623730945,
678 1.5857864376269055,
679 9.373040810652596e-17
680 ],
681 [
682 0.5857864376269049,
683 1.5857864376269049,
684 7.173814858237197e-17
685 ],
686 [
687 0.8284271247461903,
688 1,
689 0
690 ],
691 [
692 1.1715728752538097,
693 1,
694 0
695 ]
696 ]
697 },
698 {
699 "edges_assignment" : [
700 "B",
701 "B",
702 "B",
703 "B",
704 "B",
705 "B",
706 "B",
707 "B",
708 "V",
709 "V",
710 "V",
711 "V",
712 "M",
713 "V",
714 "M",
715 "M",
716 "F"
717 ],
718 "edges_foldAngle" : [
719 0,
720 0,
721 0,
722 0,
723 0,
724 0,
725 0,
726 0,
727 180,
728 180,
729 180,
730 180,
731 -180,
732 180,
733 -180,
734 -180,
735 0
736 ],
737 "faceOrders" : [
738 [
739 0,
740 1,
741 -1
742 ],
743 [
744 0,
745 2,
746 1
747 ],
748 [
749 0,
750 3,
751 1
752 ],
753 [
754 0,
755 4,
756 -1
757 ],
758 [
759 0,
760 5,
761 1
762 ],
763 [
764 0,
765 6,
766 -1
767 ],
768 [
769 1,
770 2,
771 -1
772 ],
773 [
774 1,
775 3,
776 -1
777 ],
778 [
779 1,
780 4,
781 1
782 ],
783 [
784 1,
785 5,
786 1
787 ],
788 [
789 1,
790 6,
791 1
792 ],
793 [
794 2,
795 3,
796 -1
797 ],
798 [
799 2,
800 4,
801 1
802 ],
803 [
804 2,
805 5,
806 1
807 ],
808 [
809 2,
810 6,
811 1
812 ],
813 [
814 3,
815 4,
816 1
817 ],
818 [
819 3,
820 5,
821 1
822 ],
823 [
824 3,
825 6,
826 -1
827 ],
828 [
829 4,
830 5,
831 1
832 ],
833 [
834 4,
835 6,
836 -1
837 ],
838 [
839 5,
840 6,
841 1
842 ]
843 ],
844 "frame_inherit" : true,
845 "frame_parent" : 0,
846 "krz:step" : {
847 "axes" : [
848 {
849 "edge" : 15,
850 "endAngle" : -180,
851 "movingFaces" : [
852 0
853 ],
854 "startAngle" : 0
855 }
856 ],
857 "instruction" : "Valley fold the front top flap down over the front.",
858 "kind" : "fold",
859 "nonRigid" : false,
860 "technique" : "plain",
861 "viewpoint" : {
862 "eye" : [
863 0,
864 0,
865 1
866 ],
867 "up" : [
868 0,
869 1,
870 0
871 ]
872 }
873 },
874 "vertices_coords" : [
875 [
876 1,
877 1.1715728752538097,
878 7.1738148582372e-17
879 ],
880 [
881 1.4142135623730951,
882 1.5857864376269049,
883 7.173814858237197e-17
884 ],
885 [
886 0.5857864376269052,
887 1.5857864376269053,
888 9.373040810652596e-17
889 ],
890 [
891 1.4142135623730951,
892 1.5857864376269049,
893 0
894 ],
895 [
896 1,
897 2,
898 0
899 ],
900 [
901 0.5857864376269046,
902 1.5857864376269049,
903 0
904 ],
905 [
906 1.4142135623730945,
907 1.5857864376269055,
908 9.373040810652596e-17
909 ],
910 [
911 0.5857864376269049,
912 1.5857864376269049,
913 7.173814858237197e-17
914 ],
915 [
916 0.8284271247461903,
917 1,
918 0
919 ],
920 [
921 1.1715728752538097,
922 1,
923 0
924 ]
925 ]
926 },
927 {
928 "edges_assignment" : [
929 "B",
930 "B",
931 "B",
932 "B",
933 "B",
934 "B",
935 "B",
936 "B",
937 "V",
938 "V",
939 "V",
940 "V",
941 "M",
942 "V",
943 "M",
944 "M",
945 "F"
946 ],
947 "edges_foldAngle" : [
948 0,
949 0,
950 0,
951 0,
952 0,
953 0,
954 0,
955 0,
956 180,
957 180,
958 180,
959 180,
960 -180,
961 180,
962 -180,
963 -180,
964 0
965 ],
966 "faceOrders" : [
967 [
968 0,
969 1,
970 -1
971 ],
972 [
973 0,
974 2,
975 1
976 ],
977 [
978 0,
979 3,
980 1
981 ],
982 [
983 0,
984 4,
985 -1
986 ],
987 [
988 0,
989 5,
990 1
991 ],
992 [
993 0,
994 6,
995 -1
996 ],
997 [
998 1,
999 2,
1000 -1
1001 ],
1002 [
1003 1,
1004 3,
1005 -1
1006 ],
1007 [
1008 1,
1009 4,
1010 1
1011 ],
1012 [
1013 1,
1014 5,
1015 1
1016 ],
1017 [
1018 1,
1019 6,
1020 1
1021 ],
1022 [
1023 2,
1024 3,
1025 -1
1026 ],
1027 [
1028 2,
1029 4,
1030 1
1031 ],
1032 [
1033 2,
1034 5,
1035 1
1036 ],
1037 [
1038 2,
1039 6,
1040 1
1041 ],
1042 [
1043 3,
1044 4,
1045 1
1046 ],
1047 [
1048 3,
1049 5,
1050 1
1051 ],
1052 [
1053 3,
1054 6,
1055 -1
1056 ],
1057 [
1058 4,
1059 5,
1060 1
1061 ],
1062 [
1063 4,
1064 6,
1065 -1
1066 ],
1067 [
1068 5,
1069 6,
1070 1
1071 ]
1072 ],
1073 "frame_inherit" : true,
1074 "frame_parent" : 0,
1075 "krz:step" : {
1076 "axes" : [
1077
1078 ],
1079 "instruction" : "Turn over.",
1080 "kind" : "turnOver",
1081 "nonRigid" : false,
1082 "technique" : "plain",
1083 "turnOverAxis" : "vertical",
1084 "viewpoint" : {
1085 "eye" : [
1086 0,
1087 0,
1088 1
1089 ],
1090 "up" : [
1091 0,
1092 1,
1093 0
1094 ]
1095 }
1096 },
1097 "vertices_coords" : [
1098 [
1099 0.9999999999999998,
1100 1.1715728752538097,
1101 2.199225952415395e-17
1102 ],
1103 [
1104 0.5857864376269046,
1105 1.5857864376269049,
1106 -2.8734271808209374e-17
1107 ],
1108 [
1109 1.4142135623730945,
1110 1.5857864376269053,
1111 5.07265313323633e-17
1112 ],
1113 [
1114 0.5857864376269046,
1115 1.5857864376269049,
1116 4.300387677416259e-17
1117 ],
1118 [
1119 0.9999999999999998,
1120 2,
1121 9.373040810652595e-17
1122 ],
1123 [
1124 1.4142135623730951,
1125 1.5857864376269049,
1126 1.4445693943888932e-16
1127 ],
1128 [
1129 0.5857864376269053,
1130 1.5857864376269055,
1131 -5.072653133236329e-17
1132 ],
1133 [
1134 1.414213562373095,
1135 1.5857864376269049,
1136 7.271879085651732e-17
1137 ],
1138 [
1139 1.1715728752538095,
1140 1,
1141 1.1474202535653456e-16
1142 ],
1143 [
1144 0.8284271247461901,
1145 1,
1146 7.271879085651732e-17
1147 ]
1148 ]
1149 },
1150 {
1151 "edges_assignment" : [
1152 "B",
1153 "B",
1154 "B",
1155 "B",
1156 "B",
1157 "B",
1158 "B",
1159 "B",
1160 "V",
1161 "V",
1162 "V",
1163 "V",
1164 "M",
1165 "V",
1166 "M",
1167 "M",
1168 "M"
1169 ],
1170 "edges_foldAngle" : [
1171 0,
1172 0,
1173 0,
1174 0,
1175 0,
1176 0,
1177 0,
1178 0,
1179 180,
1180 180,
1181 180,
1182 180,
1183 -180,
1184 180,
1185 -180,
1186 -180,
1187 -180
1188 ],
1189 "faceOrders" : [
1190 [
1191 0,
1192 1,
1193 -1
1194 ],
1195 [
1196 0,
1197 2,
1198 1
1199 ],
1200 [
1201 0,
1202 3,
1203 1
1204 ],
1205 [
1206 0,
1207 4,
1208 -1
1209 ],
1210 [
1211 0,
1212 5,
1213 1
1214 ],
1215 [
1216 0,
1217 6,
1218 -1
1219 ],
1220 [
1221 0,
1222 7,
1223 -1
1224 ],
1225 [
1226 1,
1227 2,
1228 -1
1229 ],
1230 [
1231 1,
1232 3,
1233 -1
1234 ],
1235 [
1236 1,
1237 4,
1238 1
1239 ],
1240 [
1241 1,
1242 5,
1243 1
1244 ],
1245 [
1246 1,
1247 6,
1248 1
1249 ],
1250 [
1251 1,
1252 7,
1253 -1
1254 ],
1255 [
1256 2,
1257 3,
1258 -1
1259 ],
1260 [
1261 2,
1262 4,
1263 1
1264 ],
1265 [
1266 2,
1267 5,
1268 1
1269 ],
1270 [
1271 2,
1272 6,
1273 1
1274 ],
1275 [
1276 2,
1277 7,
1278 -1
1279 ],
1280 [
1281 3,
1282 4,
1283 1
1284 ],
1285 [
1286 3,
1287 5,
1288 1
1289 ],
1290 [
1291 3,
1292 6,
1293 -1
1294 ],
1295 [
1296 3,
1297 7,
1298 -1
1299 ],
1300 [
1301 4,
1302 5,
1303 1
1304 ],
1305 [
1306 4,
1307 6,
1308 -1
1309 ],
1310 [
1311 4,
1312 7,
1313 -1
1314 ],
1315 [
1316 5,
1317 6,
1318 1
1319 ],
1320 [
1321 5,
1322 7,
1323 -1
1324 ],
1325 [
1326 6,
1327 7,
1328 -1
1329 ]
1330 ],
1331 "frame_inherit" : true,
1332 "frame_parent" : 0,
1333 "krz:step" : {
1334 "axes" : [
1335 {
1336 "edge" : 16,
1337 "endAngle" : -180,
1338 "movingFaces" : [
1339 7
1340 ],
1341 "startAngle" : 0
1342 }
1343 ],
1344 "instruction" : "Valley fold the remaining top flap down.",
1345 "kind" : "fold",
1346 "nonRigid" : false,
1347 "technique" : "plain",
1348 "viewpoint" : {
1349 "eye" : [
1350 0,
1351 0,
1352 1
1353 ],
1354 "up" : [
1355 0,
1356 1,
1357 0
1358 ]
1359 }
1360 },
1361 "vertices_coords" : [
1362 [
1363 0.9999999999999998,
1364 1.1715728752538097,
1365 2.199225952415395e-17
1366 ],
1367 [
1368 0.5857864376269046,
1369 1.5857864376269049,
1370 -2.8734271808209374e-17
1371 ],
1372 [
1373 1.4142135623730945,
1374 1.5857864376269053,
1375 5.07265313323633e-17
1376 ],
1377 [
1378 0.5857864376269046,
1379 1.5857864376269049,
1380 4.300387677416259e-17
1381 ],
1382 [
1383 0.9999999999999998,
1384 1.1715728752538097,
1385 1.444569394388892e-16
1386 ],
1387 [
1388 1.4142135623730951,
1389 1.5857864376269049,
1390 1.4445693943888932e-16
1391 ],
1392 [
1393 0.5857864376269053,
1394 1.5857864376269055,
1395 -5.072653133236329e-17
1396 ],
1397 [
1398 1.414213562373095,
1399 1.5857864376269049,
1400 7.271879085651732e-17
1401 ],
1402 [
1403 1.1715728752538095,
1404 1,
1405 1.1474202535653456e-16
1406 ],
1407 [
1408 0.8284271247461901,
1409 1,
1410 7.271879085651732e-17
1411 ]
1412 ]
1413 }
1414 ],
1415 "file_spec" : 1.2,
1416 "file_title" : "Cup",
1417 "vertices_coords" : [
1418 [
1419 1,
1420 0,
1421 0
1422 ],
1423 [
1424 1.4142135623730951,
1425 0.41421356237309515,
1426 0
1427 ],
1428 [
1429 2,
1430 1,
1431 0
1432 ],
1433 [
1434 1.4142135623730951,
1435 1.5857864376269049,
1436 0
1437 ],
1438 [
1439 1,
1440 2,
1441 0
1442 ],
1443 [
1444 0.5857864376269049,
1445 1.5857864376269049,
1446 0
1447 ],
1448 [
1449 0,
1450 1,
1451 0
1452 ],
1453 [
1454 0.5857864376269049,
1455 0.41421356237309515,
1456 0
1457 ],
1458 [
1459 0.8284271247461903,
1460 1,
1461 0
1462 ],
1463 [
1464 1.1715728752538097,
1465 1,
1466 0
1467 ]
1468 ]
1469}\ No newline at end of file
Packages/FoldKit/Sources/foldc/main.swift added +28
@@ -0,0 +1,28 @@
1import FoldCompiler
2import FoldFormat
3import Foundation
4
5// foldc <script.foldscript> -o <model.fold>
6
7func fail(_ message: String, status: Int32) -> Never {
8 FileHandle.standardError.write(Data("foldc: \(message)\n".utf8))
9 exit(status)
10}
11
12let arguments = Array(CommandLine.arguments.dropFirst())
13guard arguments.count == 3, arguments[1] == "-o" else {
14 fail("usage: foldc <script.foldscript> -o <model.fold>", status: 2)
15}
16let scriptURL = URL(fileURLWithPath: arguments[0])
17let outputURL = URL(fileURLWithPath: arguments[2])
18
19do {
20 let script = try FoldScript(contentsOf: scriptURL)
21 let patternURL = URL(fileURLWithPath: script.creasePattern, relativeTo: scriptURL.deletingLastPathComponent())
22 let model = try compile(script, pattern: FoldFile(contentsOf: patternURL))
23 let encoder = JSONEncoder()
24 encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
25 try encoder.encode(model).write(to: outputURL)
26} catch {
27 fail("\(error)", status: 1)
28}
Packages/FoldKit/Sources/foldlint/main.swift added +33
@@ -0,0 +1,33 @@
1import FoldFormat
2import Folding
3import Foundation
4
5// foldlint <model.fold>...
6//
7// Prints each defect as `<path>: <defect>`, one per line, and exits 1 when there is one. A file
8// that validates has its steps read and its layer motion checked.
9
10let paths = Array(CommandLine.arguments.dropFirst())
11guard !paths.isEmpty else {
12 FileHandle.standardError.write(Data("usage: foldlint <model.fold>...\n".utf8))
13 exit(2)
14}
15
16var clean = true
17for path in paths {
18 func report(_ defect: Any) {
19 print("\(path): \(defect)")
20 clean = false
21 }
22 do {
23 let file = try FoldFile(contentsOf: URL(fileURLWithPath: path))
24 let defects = validate(file)
25 defects.forEach(report)
26 guard defects.isEmpty else { continue }
27 _ = try readSteps(file)
28 layerMotionDefects(file).forEach(report)
29 } catch {
30 report(error)
31 }
32}
33exit(clean ? 0 : 1)
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift added +310
@@ -0,0 +1,310 @@
1import Foundation
2import Testing
3import FoldCompiler
4import FoldFormat
5import Folding
6import FoldKitTestSupport
7
8@Test(arguments: ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"])
9func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws {
10 let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
11 pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
12 #expect(structurallyEqual(out, try FoldFile(contentsOf: fixture("\(name).fold")), tolerance: 1e-12))
13 #expect(validate(out).isEmpty)
14}
15
16@Test func aCreaseThroughTwoLayersChangesBothEdges() throws {
17 let out = try compiled("quarters")
18 #expect(out.frames[3].edgesFoldAngle[8] == 180)
19 #expect(out.frames[3].edgesFoldAngle[9] == -180)
20 #expect(out.frames[3].edgesAssignment[9] == .mountain)
21}
22
23@Test func firstCreasedAtStepIsTheFirstStepThatMakesTheCrease() throws {
24 // x = 1 is made by the fold-and-unfold in step 1 and refolded in step 3
25 #expect(try compiled("quarters").edgesFirstCreasedAtStep
26 == [nil, nil, nil, nil, nil, nil, nil, nil, 1, 1, 2, 2])
27}
28
29@Test func movingSideIsResolvedFromAContainedPoint() throws {
30 #expect(try compiled("half").frames[1].step?.axes[0].movingFaces == [1])
31}
32
33@Test func creaseGivenByEndpointsResolvesToAnEdgeIndex() throws {
34 #expect(try compiled("half").frames[1].step?.axes[0].edge == 6)
35}
36
37@Test func anOverrideReplacesTheGuessForThatPair() throws {
38 let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
39 let frame = file.frames[2]
40 // the guess puts f2 (folded last) above f0; the override puts f0 above f2
41 let swapped = try applyOrderOverrides([OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))],
42 to: frame.faceOrders, frame: frame,
43 viewpoint: frame.step!.viewpoint, file: file)
44 #expect(swapped != frame.faceOrders)
45 #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) }
46}
47
48@Test func aCoupledStepIsSolvedIntoCurves() throws {
49 // decision 0001's case 3 as a script: the 140° crease drives, the 260° crease
50 // gets a curve, the 0° crease rides on it, the 60° crease closes the loop
51 let out = try compile(degreeFourScript(), pattern: degreeFourPattern())
52 let axes = try #require(out.frames[1].step?.axes)
53 #expect(axes.contains { $0.angles != nil })
54 #expect(axes.contains { $0.parent != nil })
55 for axis in axes where axis.angles != nil {
56 #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6)
57 }
58}
59
60@Test func anUnresolvedCreaseNamesItsStepAndReference() {
61 #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
62 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
63 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
64 }
65}
66
67@Test func aStepThatFailsValidationNamesItsStep() {
68 #expect {
69 try compile(FoldScript(contentsOf: fixture("angle-out-of-range.foldscript")),
70 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
71 } throws: { if case CompileError.stepFailed(step: 2, _) = $0 { true } else { false } }
72}
73
74@Test func guessedFaceOrdersAreAcyclic() throws {
75 let out = try compiled("occlusion")
76 for frame in out.frames { #expect(throws: Never.self) {
77 try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, out)) } }
78}
79
80@Test func aClockwiseFaceIsRejected() throws {
81 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
82 pattern.facesVertices[1].reverse()
83 #expect(throws: CompileError.clockwiseFace(face: 1)) {
84 try compile(FoldScript(contentsOf: fixture("half.foldscript")), pattern: pattern)
85 }
86}
87
88@Test func aCoupledStepReproducesTheClosedForm() throws {
89 #expect(structurallyEqual(try compile(degreeFourScript(), pattern: degreeFourPattern()), degreeFourVertex(),
90 tolerance: 1e-9))
91}
92
93private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind: StepKind = .fold,
94 movingSide: SIMD2<Double> = SIMD2(1.5, 1), faceOrders: [OrderOverride]? = nil,
95 spine: CreaseRef? = nil) -> FoldScript {
96 FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
97 ScriptStep(kind: kind, instruction: "Fold the right half.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 2))],
98 movingSide: [movingSide], angles: angles, peakAngles: peakAngles, faceOrders: faceOrders,
99 spine: spine),
100 ])
101}
102
103@Test func aCreaseFoldedAgainstThePatternIsRejected() throws {
104 #expect(throws: CompileError.assignmentDisagreesWithPattern(edge: 6)) {
105 try compile(halfFold(angles: [-180]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
106 }
107}
108
109@Test func aMovingSideOffTheSheetIsRejected() throws {
110 #expect(throws: CompileError.unresolvedMovingSide(step: 1)) {
111 try compile(halfFold(movingSide: SIMD2(5, 5)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
112 }
113}
114
115@Test func anOverrideOffTheSheetNamesItsStep() throws {
116 let override = OrderOverride(above: SIMD2(0.5, 1), below: SIMD2(5, 5))
117 #expect(throws: CompileError.unresolvedFace(step: 1, point: SIMD2(5, 5))) {
118 try compile(halfFold(faceOrders: [override]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
119 }
120}
121
122@Test func anUnassignedCreaseNeedsAnAngle() throws {
123 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
124 pattern.frames[0].edgesAssignment[6] = .flat
125 #expect(throws: CompileError.missingAngle(step: 1, crease: .betweenVertices(SIMD2(1, 0), SIMD2(1, 2)))) {
126 try compile(halfFold(kind: .foldAndUnfold), pattern: pattern)
127 }
128}
129
130@Test func anglesPairWithCreases() throws {
131 #expect(throws: CompileError.creaseListMismatch(step: 1)) {
132 try compile(halfFold(angles: [180, 180]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
133 }
134}
135
136@Test func aSpineThatIsNotFoldedIsRejected() throws {
137 // a flap opens on a spine folded flat in the frame the step starts from
138 #expect(throws: CompileError.invalidSpine(step: 1)) {
139 try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
140 }
141}
142
143@Test func aLoopCreaseScriptedAtTheWrongAngleHasNoRigidMotion() throws {
144 let step = degreeFourScript().steps[0]
145 let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
146 ScriptStep(kind: .fold, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
147 angles: [180, 180, 180, 180]),
148 ])
149 #expect(throws: CompileError.noRigidMotion(step: 1)) { try compile(script, pattern: degreeFourPattern()) }
150}
151
152@Test func twoFlapsFoldedIntoEachOtherAreRejected() throws {
153 let script = FoldScript(creasePattern: "letter-sequential-cp.fold", title: "Letter", steps: [
154 ScriptStep(kind: .fold, instruction: "Valley fold both thirds over at once.",
155 creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 3)), .betweenVertices(SIMD2(2, 0), SIMD2(2, 3))],
156 movingSide: [SIMD2(0.5, 1.5), SIMD2(2.5, 1.5)]),
157 ])
158 #expect {
159 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
160 } throws: { if case CompileError.interpenetration(step: 1, _) = $0 { true } else { false } }
161}
162
163@Test func aCreaseNamedTwiceIsUnresolved() throws {
164 let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
165 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)],
166 movingSide: [SIMD2(1.5, 1)]),
167 ])
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)) {
194 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
195 }
196}
197
198/// `letter-sequential-cp.fold`'s sheet with the x = 1 crease split at (1, 1.5) into e8 (lower)
199/// and e10 (upper), so folding along it closes a loop of two coincident edges.
200private func splitLetterPattern() -> FoldFile {
201 let points: [SIMD3<Double>] = [
202 SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(3, 0, 0),
203 SIMD3(3, 3, 0), SIMD3(2, 3, 0), SIMD3(1, 3, 0), SIMD3(0, 3, 0), SIMD3(1, 1.5, 0),
204 ]
205 let assignment = Array(repeating: EdgeAssignment.boundary, count: 8) + [.valley, .valley, .valley]
206 return FoldFile(fileSpec: 1.2, fileTitle: "Split letter", fileAuthor: "Traditional",
207 fileClasses: ["creasePattern"],
208 edgesVertices: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0],
209 [1, 8], [2, 5], [8, 6]],
210 facesVertices: [[0, 1, 8, 6, 7], [1, 2, 5, 6, 8], [2, 3, 4, 5]],
211 edgesFirstCreasedAtStep: Array(repeating: nil, count: 11),
212 frames: [FoldFrame(verticesCoords: points, edgesAssignment: assignment,
213 edgesFoldAngle: Array(repeating: 0, count: 11), faceOrders: [])])
214}
215
216@Test func anAxisOffEveryLoopKeepsItsWindowAndStaysLinear() throws {
217 let script = FoldScript(creasePattern: "", title: "Split letter", steps: [
218 ScriptStep(kind: .fold, instruction: "Valley fold the left third over, then the right third over the top.",
219 creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1.5)), .betweenVertices(SIMD2(2, 0), SIMD2(2, 3))],
220 movingSide: [SIMD2(0.5, 1.5), SIMD2(2.5, 1.5)], windows: [[0, 0.5], [0.5, 1]]),
221 ])
222 let axes = try #require(try compile(script, pattern: splitLetterPattern()).frames[1].step?.axes)
223 let flap = try #require(axes.first { $0.edge == 9 })
224 #expect(flap.window == [0.5, 1])
225 #expect(flap.angles == nil)
226}
227
228@Test func aSolvedAxisScriptedOnAnotherWindowIsRejected() throws {
229 let step = degreeFourScript().steps[0]
230 let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
231 ScriptStep(kind: .fold, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
232 windows: [[0, 1], [0, 0.5], [0, 1], [0, 1]]),
233 ])
234 #expect(throws: CompileError.solvedAxisWindowConflict(step: 1, edge: 11)) {
235 try compile(script, pattern: degreeFourPattern())
236 }
237}
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
281@Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws {
282 // step 2's flap folds over the top, so it cannot end under f0
283 var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
284 let step = script.steps[1]
285 script = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [
286 script.steps[0],
287 ScriptStep(kind: step.kind, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
288 repeatOf: step.repeatOf,
289 faceOrders: [OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))]),
290 ])
291 #expect(throws: CompileError.stepFailed(step: 2, defects: [.movesThroughStillFace(step: 2, moving: 2, still: 0)])) {
292 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
293 }
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 added +119
@@ -0,0 +1,119 @@
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 == 30)
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 theStepEndsOnItsEndFrame() throws {
46 let file = try compiled("reverse")
47 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
48 #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 })
49}
50
51@Test func nothingPassesThroughAnything() throws {
52 let file = try compiled("reverse")
53 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
54 #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty)
55}
56
57@Test func theTipLandsBetweenTheFlapsLayers() throws {
58 // 97% of the way through the closing phase, a point of the tip lies between the body's two layers
59 let file = try compiled("reverse")
60 let step = try readSteps(file)[1]
61 let i = FoldInterpolator(file: file, step: step)
62 let upper = step.pop!.phases.upperBound
63 #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file))
64}
65
66@Test func aFlapOpenedOnlyTo60DegreesIsRejected() {
67 #expect {
68 try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2),
69 pattern: FoldFile(contentsOf: fixture("reverse-cp.fold")))
70 } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } }
71}
72
73@Test func thePopFitsInAFrameBudget() throws {
74 let file = try compiled("reverse")
75 let step = try readSteps(file)[1]
76 let i = FoldInterpolator(file: file, step: step)
77 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
78 let elapsed = ContinuousClock().measure {
79 for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) }
80 }
81 #expect(elapsed / 100 < .milliseconds(4))
82}
83
84@Test func theRenderMeshIsTheSpikes() throws {
85 // decision 0002's mesh at spacing 0.125 on this sheet: 561 vertices, 1024 triangles
86 let file = try FoldFile(contentsOf: fixture("reverse-cp.fold"))
87 let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
88 #expect(RenderMesh.spacing(for: file) == 0.125)
89 #expect(mesh.vertices.count == 561)
90 #expect(mesh.triangles.count == 1024)
91 #expect(mesh.meshVertexOf.enumerated().allSatisfy { v, m in
92 mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y)
93 })
94}
95
96@Test func theReverseFoldMovesThroughNoStillFace() throws {
97 // the open phase departs from frame 1 and the close phase arrives at frame 2
98 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)
99}
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/FoldFormatTests/ValidatorTests.swift +20
@@ -134,3 +134,23 @@ func acceptsAValidModel(_ name: String) throws {
134 == [SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) 134 == [SIMD3(0, 0, 1), SIMD3(0, 0, -1)])
135 #expect(edgesFaces(file) == [[0], [1], [1], [1], [0], [0], [0, 1]]) 135 #expect(edgesFaces(file) == [[0], [1], [1], [1], [0], [0], [0, 1]])
136} 136}
137
138@Test func rejectsAMalformedPop() throws {
139 #expect(validate(try FoldFile(contentsOf: fixture("nonrigid-no-pop.fold"))).contains(.popMalformed(step: 1)))
140
141 var file = try FoldFile(contentsOf: fixture("nonrigid-no-pop.fold"))
142 let record = file.frames[1].step!
143 func withPop(popped: Int, phases: [Double]) -> StepRecord {
144 StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes,
145 nonRigid: true,
146 pop: PopRecord(spine: [6], openAngle: 30, phases: phases, openAxes: [],
147 popped: Array(file.frames[0].verticesCoords.prefix(popped)), closeAxes: []),
148 viewpoint: record.viewpoint)
149 }
150 file.frames[1].step = withPop(popped: 5, phases: [1.0 / 3, 2.0 / 3])
151 #expect(validate(file).contains(.popMalformed(step: 1)))
152 file.frames[1].step = withPop(popped: 6, phases: [2.0 / 3, 1.0 / 3])
153 #expect(validate(file).contains(.popMalformed(step: 1)))
154 file.frames[1].step = withPop(popped: 6, phases: [1.0 / 3, 2.0 / 3])
155 #expect(!validate(file).contains(.popMalformed(step: 1)))
156}
Packages/FoldKit/Tests/FoldingTests/LayerMotionTests.swift added +47
@@ -0,0 +1,47 @@
1import Testing
2import FoldFormat
3import Folding
4import FoldKitTestSupport
5
6@Test func aFlapArrivingFromTheSideOppositeItsOrderIsFlagged() throws {
7 // frame 2 puts f2 between f0 and f1; f2 folds over the top, so it arrives from above f0
8 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
9 file.frames[2].faceOrders = [[0, 1, 1], [0, 2, -1], [1, 2, 1]]
10 // x = 1 is f2's edge, not its interior, so the taco rules do not catch it
11 #expect(validate(file).isEmpty)
12 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)])
13}
14
15@Test func 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
24@Test func aFlapDepartingTowardALayerAboveItIsFlagged() throws {
25 // step 3 unfolds f0 from under f2, which covers f0's hinge at x = 1
26 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
27 var points = file.frames[2].verticesCoords
28 points[0] = SIMD3(0, 0, 0)
29 points[7] = SIMD3(0, 3, 0)
30 var assignment = file.frames[2].edgesAssignment
31 assignment[8] = .flat
32 var angles = file.frames[2].edgesFoldAngle
33 angles[8] = 0
34 let step = StepRecord(kind: .fold, instruction: "Unfold the left third.",
35 axes: [AxisRecord(edge: 8, movingFaces: [0], startAngle: 180, endAngle: 0)],
36 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)))
37 file.frames.append(FoldFrame(verticesCoords: points, edgesAssignment: assignment, edgesFoldAngle: angles,
38 faceOrders: [[1, 2, 1]], step: step))
39 #expect(validate(file).isEmpty)
40 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 3, moving: 0, still: 2)])
41}
42
43@Test(arguments: ["square", "half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters",
44 "occlusion"])
45func noSyntheticModelMovesThroughAStillFace(_ name: String) throws {
46 #expect(layerMotionDefects(try FoldFile(contentsOf: fixture("\(name).fold"))).isEmpty)
47}
Packages/FoldKit/Tests/FoldingTests/RenderMeshTests.swift added +67
@@ -0,0 +1,67 @@
1import Foundation
2import Testing
3import simd
4import FoldFormat
5import Folding
6
7/// A flat 2 × 1 sheet with `points` as its vertices and `faces` as its faces; edges are not read
8/// by the mesh and are left empty.
9private func sheet(_ points: [SIMD2<Double>], _ faces: [[Int]]) -> FoldFile {
10 FoldFile(fileSpec: 1.2, fileAuthor: "Traditional", edgesVertices: [], facesVertices: faces,
11 edgesFirstCreasedAtStep: [],
12 frames: [FoldFrame(verticesCoords: points.map { SIMD3($0.x, $0.y, 0) }, edgesAssignment: [],
13 edgesFoldAngle: [], faceOrders: [])])
14}
15
16/// A crease along y = 0.5 split at M = (1, 0.5), and a crease from M to the top edge. M is a
17/// 180° corner of the bottom face, listed so that a fan from the face's first corner meets it
18/// collinearly.
19private func tJunction() -> FoldFile {
20 sheet([SIMD2(0, 0), SIMD2(2, 0), SIMD2(2, 0.5), SIMD2(2, 1), SIMD2(1, 1), SIMD2(0, 1), SIMD2(0, 0.5),
21 SIMD2(1, 0.5)],
22 [[2, 7, 6, 0, 1], [6, 7, 4, 5], [7, 2, 3, 4]])
23}
24
25/// Whether every mesh vertex in or on a face's outline is a corner of one of that face's triangles.
26private func everyFaceUsesItsVertices(_ file: FoldFile, _ mesh: RenderMesh) -> Bool {
27 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
28 return file.facesVertices.indices.allSatisfy { f in
29 let outline = file.facesVertices[f].map { flat[$0] }
30 var used = Set<Int>()
31 for (t, (a, b, c)) in mesh.triangles.enumerated() where mesh.faceOf[t] == f { used.formUnion([a, b, c]) }
32 return mesh.vertices.indices.allSatisfy { v in
33 let p = mesh.vertices[v]
34 let inside = outline.indices.allSatisfy { i in
35 let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = p - a
36 return side.x * offset.y - side.y * offset.x >= -1e-12
37 }
38 return !inside || used.contains(v)
39 }
40 }
41}
42
43@Test(arguments: [10.0, 0.3, 2.0 / 32])
44func aStraightCornerIsInItsFacesTriangles(_ spacing: Double) {
45 let file = tJunction()
46 #expect(everyFaceUsesItsVertices(file, RenderMesh(file: file, spacing: spacing)))
47}
48
49@Test func aNonRigidStepOverAStraightCornerBuilds() {
50 // a crease along y = 0.5 split at M, straight in both faces that hold it, and a crease at
51 // x = 1.5; the right top face is held, the rest move, so M is a free vertex of the pop
52 let m = SIMD2(1.03, 0.5)
53 let file = sheet([SIMD2(0, 0), SIMD2(1.5, 0), SIMD2(2, 0), SIMD2(2, 0.5), SIMD2(2, 1), SIMD2(1.5, 1),
54 SIMD2(0, 1), SIMD2(0, 0.5), m, SIMD2(1.5, 0.5)],
55 [[9, 8, 7, 0, 1], [7, 8, 9, 5, 6], [1, 2, 3, 9], [9, 3, 4, 5]])
56 let start = file.frames[0].verticesCoords
57 let step = FoldStep(index: 1, kind: .fold, instruction: "Pop.",
58 axes: [FoldAxis(edge: 0, origin: .zero, direction: SIMD3(1, 0, 0), movingFaces: [0, 1, 2],
59 startAngle: 0, endAngle: 0)],
60 nonRigid: true,
61 pop: Pop(spine: [], openAngle: 30, phases: (1.0 / 3)...(2.0 / 3), openAxes: [],
62 popped: start, closeAxes: []),
63 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)))
64 let i = FoldInterpolator(file: file, step: step)
65 #expect(everyFaceUsesItsVertices(file, i.mesh))
66 #expect(zip(i.positions(at: 0.5), start).allSatisfy { simd_distance($0, $1) < 1e-9 })
67}
Packages/FoldKit/Tests/FoldingTests/StepReadingTests.swift +7
@@ -137,3 +137,10 @@ func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws {
137 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))) 137 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)))
138 #expect(step.movingFaceUnion == [1]) 138 #expect(step.movingFaceUnion == [1])
139} 139}
140
141@Test func aStepReadsWithoutTheFramesAfterIt() throws {
142 var file = try FoldFile(contentsOf: fixture("quarters.fold"))
143 let whole = try readSteps(file)
144 file.frames.removeLast()
145 #expect(try readStep(2, in: file) == whole[1])
146}
Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift added +94
@@ -0,0 +1,94 @@
1import Foundation
2import Testing
3import simd
4import FoldCompiler
5import FoldFormat
6import Folding
7import FoldKitTestSupport
8import Models
9
10@Test func everyShippedStepEndsOnItsEndFrame() throws {
11 // the step records and the frames must agree: interpolating a step to t = 1 reproduces frame n
12 for file in try ModelLibrary.all() {
13 for step in try readSteps(file) {
14 let i = FoldInterpolator(file: file, step: step)
15 #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords)
16 .allSatisfy { simd_distance($0, $1) < 1e-6 * sheetSize(file) }, "\(file.fileTitle ?? "?") step \(step.index)")
17 }
18 }
19}
20
21@Test func everyShippedModelValidates() throws {
22 for file in try ModelLibrary.all() { #expect(validate(file).isEmpty, "\(file.fileTitle ?? "?")") }
23}
24
25@Test func everyShippedModelReadsItsSteps() throws {
26 for file in try ModelLibrary.all() {
27 #expect(try readSteps(file).count == file.stepCount)
28 }
29}
30
31@Test func noShippedModelStretchesAtAnyStep() throws {
32 // flagged non-rigid steps are held to Task 0b's bound instead
33 for file in try ModelLibrary.all() {
34 for step in try readSteps(file) where !step.nonRigid {
35 let i = FoldInterpolator(file: file, step: step)
36 for t in stride(from: 0.0, through: 1.0, by: 1.0 / 256) {
37 #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6,
38 "\(file.fileTitle ?? "?") step \(step.index) t \(t)")
39 }
40 }
41 }
42}
43
44@Test func noShippedModelInterpenetratesAtAnyStep() throws {
45 // non-rigid steps bend their faces; everyFlaggedStepStaysWithinTheBound checks them on the mesh
46 for file in try ModelLibrary.all() {
47 for step in try readSteps(file) where !step.nonRigid {
48 let i = FoldInterpolator(file: file, step: step)
49 #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty,
50 "\(file.fileTitle ?? "?") step \(step.index)")
51 }
52 }
53}
54
55@Test func noShippedModelMovesThroughAStillFace() throws {
56 for file in try ModelLibrary.all() { #expect(layerMotionDefects(file).isEmpty, "\(file.fileTitle ?? "?")") }
57}
58
59@Test func everyModelIsAttributedAsTraditional() throws {
60 for file in try ModelLibrary.all() { #expect(file.fileAuthor == "Traditional") }
61}
62
63@Test func everyShippedModelRegeneratesFromItsScript() throws {
64 for name in try ModelLibrary.names() {
65 let recompiled = try compile(FoldScript(contentsOf: script(name)),
66 pattern: FoldFile(contentsOf: pattern(name)))
67 #expect(structurallyEqual(recompiled, try ModelLibrary.model(named: name), tolerance: 1e-12), "\(name)")
68 }
69}
70
71@Test func everyFlaggedStepStaysWithinTheBound() throws {
72 // decision 0002: 10% largest edge strain on the render mesh, and nothing passes through anything
73 for file in try ModelLibrary.all() {
74 for step in try readSteps(file) where step.nonRigid {
75 let i = FoldInterpolator(file: file, step: step)
76 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
77 let worst = (0...128).map { strain(i.meshPositions(at: lo + Double($0) / 128 * (hi - lo)), mesh: i.mesh) }.max()!
78 #expect(worst <= 0.10, "\(file.fileTitle ?? "?") step \(step.index)")
79 #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty)
80 }
81 }
82}
83
84@Test func theCatalogueContainsTheCup() throws {
85 #expect(try ModelLibrary.names() == ["cup"])
86}
87
88@Test func theCupContainsATurnOverStep() throws {
89 #expect(try readSteps(ModelLibrary.model(named: "cup")).contains { $0.kind == .turnOver })
90}
91
92@Test func foldlintExitsNonZeroOnADefectiveFile() throws {
93 #expect(try runFoldlint(on: fixture("bad-index.fold")).exitCode == 1)
94}
docs/authoring/cup.md added +96
@@ -0,0 +1,96 @@
1# Cup
2
3Traditional. Six steps: five folds of one axis each and a turn-over. No coupled
4steps (no solved curves) and no non-rigid steps.
5
6`Models/cup-cp.fold` and `Models/cup.foldscript` compile to
7`Packages/FoldKit/Sources/Models/Resources/cup.fold`:
8
9```bash
10swift run --package-path Packages/FoldKit foldc Models/cup.foldscript \
11 -o Packages/FoldKit/Sources/Models/Resources/cup.fold
12```
13
14`everyShippedModelRegeneratesFromItsScript` checks that the shipped file is
15what the script compiles to.
16
17## Crease pattern
18
19Constructed from the traditional folding sequence, not taken from a published
20crease pattern. The sheet is a square of side √2 set as a diamond, corners
21S (1, 0), E (2, 1), N (1, 2), W (0, 1), its top side up (+z).
22
23Step 1 folds S up to N along the diagonal y = 1, giving a triangle with its
24folded edge W–E at the bottom and apex N. Step 2 folds corner E to the left
25edge W–N so that the flap's top edge, part of the former right edge E–N, is
26level. Reflecting E–N (direction 135°) onto a horizontal line needs a crease
27at 67.5°; the one that also puts E on W–N runs from Q = (4 − 2√2, 1) on the
28fold to R = (√2, 3 − √2) on the right edge, and E lands on
29P = (2 − √2, 3 − √2). Step 3 is its mirror image: the crease from
30Q′ = (2√2 − 2, 1) to P, and W lands on R. The apex flaps fold down along the
31level line through P and R. Each crease through both layers of the triangle
32is two creases in the pattern, one in each half of the diamond, mirrored in
33y = 1.
34
35| Vertex | Point | Coordinates |
36|---|---|---|
37| v0 | S | (1, 0) |
38| v1 | R′ | (√2, √2 − 1) |
39| v2 | E | (2, 1) |
40| v3 | R | (√2, 3 − √2) |
41| v4 | N | (1, 2) |
42| v5 | P | (2 − √2, 3 − √2) |
43| v6 | W | (0, 1) |
44| v7 | P′ | (2 − √2, √2 − 1) |
45| v8 | Q′ | (2√2 − 2, 1) |
46| v9 | Q | (4 − 2√2, 1) |
47
48| Edges | Crease | Assignment | Step |
49|---|---|---|---|
50| e0–e7 | boundary, S → R′ → E → R → N → P → W → P′ → S | B | — |
51| e8, e9, e10 | the diagonal: W–Q′, Q′–Q, Q–E | V | 1 |
52| e11, e12 | Q–R (top half), Q–R′ (bottom half) | V, M | 2 |
53| e13, e14 | Q′–P (top half), Q′–P′ (bottom half) | V, M | 3 |
54| e15 | P′–R′, the front apex flap | M | 4 |
55| e16 | P–R, the back apex flap | M | 6 |
56
57Faces, counterclockwise: f0 [P′, S, R′] (front apex flap), f1 [P′, R′, Q, Q′]
58(front body), f2 [R′, E, Q] and f6 [Q, E, R] (the right corner flap, front and
59back layers), f3 [W, P′, Q′] and f4 [W, Q′, P] (the left corner flap), f5
60[Q′, Q, R, P] (back body), f7 [P, R, N] (back apex flap).
61
62Every crease ends on the boundary or at Q or Q′ on the diagonal, so no
63subdivision edges are needed. Q and Q′ are degree-4 vertices with sectors
6467.5°, 112.5°, 112.5°, 67.5° and three valleys to one mountain.
65
66The bottom half's creases are mountains because that half is turned face-down
67by step 1: steps 2–4 fold toward the viewer, which is a valley seen from the
68front and a mountain on the bottom half's own top side. Step 6 folds the back
69apex flap toward the viewer after the turn-over, when its top side faces away.
70
71## Sequence
72
731. Valley fold S up to N along the diagonal (named crease e9; e8 and e10 lie
74 on its line and fold with it).
752. Valley fold the right corner E across to P, through both layers (e11; e12
76 folds with it). The right corner goes first.
773. Valley fold the left corner W across to R, over the first flap (e13 and
78 e14). Six layers where the corner flaps cross.
794. Valley fold the front apex flap f0 down over the front along P–R (e15).
80 S lands on (1, 4 − 2√2). Seven layers.
815. Turn over, about the vertical axis.
826. Valley fold the back apex flap f7 down (e16). N lands on (1, 4 − 2√2).
83 Eight layers in the triangle P, R, (1, 4 − 2√2).
84
85The apex flaps are folded down over the outside, not tucked into the pocket.
86The model ends flat. Viewpoint: eye (0, 0, 1), up (0, 1, 0) throughout.
87
88## Layer-order overrides
89
90None. Every step is a plain valley fold of one moving set onto the outside of
91the stack, which is the case the compiler's guess (the moving set lands on the
92side it arrives from, its own layers reversed) gets right. `foldc`'s
93validation, the interpenetration check and `layerMotionDefects` pass with the
94guessed orders, and the guessed stacks were checked by hand against the sequence:
95after step 3, bottom to top along +z, f5, f1, f2, f6, f3, f4; step 4 puts f0
96on top of all of them; step 6 puts f7 on top of the turned-over stack.
docs/superpowers/plans/2026-10-19-fold.md +14 −8
@@ -1068,14 +1068,14 @@ git commit -m "Facet interpenetration checker"
1068 - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile` 1068 - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile`
1069 - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]` 1069 - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]`
1070 - `func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]]` 1070 - `func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]]`
1071 - `enum CompileError: Error, Equatable, Sendable { case unresolvedCrease(step: Int); case unresolvedMovingSide(step: Int); case unresolvedFace(step: Int, point: SIMD2<Double>); case stepFailed(step: Int, defects: [FoldDefect]); case interpenetration(step: Int, [Intersection]); case assignmentDisagreesWithPattern(edge: Int); case noRigidMotion(step: Int); case curveTooCoarse(step: Int) }` 1071 - `enum CompileError: Error, Equatable, Sendable { case unresolvedCrease(step: Int, crease: CreaseRef); case noCreases(step: Int); case unresolvedMovingSide(step: Int); case unresolvedFace(step: Int, point: SIMD2<Double>); case stepFailed(step: Int, defects: [FoldDefect]); case interpenetration(step: Int, [Intersection]); case assignmentDisagreesWithPattern(edge: Int); case noRigidMotion(step: Int); case curveTooCoarse(step: Int); case clockwiseFace(face: Int); case missingAngle(step: Int, crease: CreaseRef); case creaseListMismatch(step: Int); case solvedAxisWindowConflict(step: Int, edge: Int); case coincidentAxisAngle(step: Int, edge: Int) }` — Task 7b adds `popTooStrained`, `missingSpine` and `invalidSpine`
1072 - `foldc <script.foldscript> -o <model.fold>` — exits 0 on success, 1 naming the first failing step and its defects 1072 - `foldc <script.foldscript> -o <model.fold>` — exits 0 on success, 1 naming the first failing step and its defects
1073 1073
1074**This task is the reason the project is buildable.** No existing FOLD tool authors a multi-frame sequence with folded coordinates, per-frame layer order and per-step moving sets; hand-writing them is hundreds of exact numbers per frame. `foldc` takes a crease pattern exported from an existing editor plus a short script that names each step's creases (by the points they run between), which side moves (by a point inside it), and the step kind, and **computes** every frame by applying the rotations in order. It guesses `faceOrders`, applies the script's overrides, and runs the Task 2 validator and the Task 6 checker after each step (Task 7b's mesh checker for a non-rigid step). 1074**This task is the reason the project is buildable.** No existing FOLD tool authors a multi-frame sequence with folded coordinates, per-frame layer order and per-step moving sets; hand-writing them is hundreds of exact numbers per frame. `foldc` takes a crease pattern exported from an existing editor plus a short script that names each step's creases (by the points they run between), which side moves (by a point inside it), and the step kind, and **computes** every frame by applying the rotations in order. It guesses `faceOrders`, applies the script's overrides, and runs the Task 2 validator and the Task 6 checker after each step (Task 7b's mesh checker for a non-rigid step).
1075 1075
1076Defaults: `angles` are each crease's end fold angle, ±180 by the pattern's assignment; `viewpoint` is the previous step's, or `[0, 0, 1]` / `[0, 1, 0]` for step 1; `technique` is `plain`; `driver` is the first crease; `windows` are all `[0, 1]`. 1076Defaults: `angles` are each crease's end fold angle, ±180 by the pattern's assignment; `viewpoint` is the previous step's, or `[0, 0, 1]` / `[0, 1, 0]` for step 1; `technique` is `plain`; `driver` is the first crease; `windows` are all `[0, 1]`.
1077 1077
1078**Coupled steps (decision 0001).** The step's creases cut the sheet into regions, each connected across edges this step does not fold. The fixed region is the one no `movingSide` point lies in. A spanning tree of regions, grown from the fixed region across the step's creases, gives each moving region its axis and each axis its parent. A step crease left off that tree closes a loop. If there is none, every axis is linear on its window. If there are some, `foldc` holds the driver linear on its window and solves the other tree axes as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. It writes each solved axis's curve at 257 points. A solved angle that is linear to within 1e-9° is written without a curve. Each curve is checked at four times its sample density; if the gap exceeds 1e-6 × the sheet's size between samples, the step fails with `curveTooCoarse` (257 samples is fixed, and decision 0001 measured it sufficient). Regions are grown in the order the script lists the step's creases, driver first, so which crease closes a loop is determined by the script. A loop that does not close (the solver's gap stays above the tolerance) fails the step with `noRigidMotion`. The step then needs a decision (decision 0002); a solver that does not converge is not proof that no rigid motion exists, so check the script first. Reverse folds and sinks never reach this: they name a `spine` and are compiled by Task 7b. The last sample of every step is set to the end frame exactly. 1078**Coupled steps (decision 0001).** The step's creases cut the sheet into regions, each connected across edges this step does not fold. The fixed region is the one no `movingSide` point lies in. A spanning tree of regions, grown from the fixed region across the step's creases, gives each moving region its axis and each axis its parent. A step crease left off that tree closes a loop. If there is none, every axis is linear on its window. If there are some, `foldc` holds the driver linear on its window and solves the tree axes on some loop's cycle (the tree path between the two regions a loop crease joins), excluding the driver, as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. Every other axis stays linear on its scripted window. A solved axis whose scripted window differs from the driver's is rejected rather than ignored. It writes each solved axis's curve at 257 points. A solved angle that is linear to within 1e-9° is written without a curve. Each curve is checked at four times its sample density; if the gap exceeds 1e-6 × the sheet's size between samples, the step fails with `curveTooCoarse` (257 samples is fixed, and decision 0001 measured it sufficient). Regions are grown in the order the script lists the step's creases, driver first, so which crease closes a loop is determined by the script. A loop that does not close (the solver's gap stays above the tolerance) fails the step with `noRigidMotion`. The step then needs a decision (decision 0002); a solver that does not converge is not proof that no rigid motion exists, so check the script first. Reverse folds and sinks never reach this: they name a `spine` and are compiled by Task 7b. The last sample of every step is set to the end frame exactly.
1079 1079
1080Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it. 1080Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it.
1081 1081
@@ -1137,7 +1137,7 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th
1137} 1137}
1138 1138
1139@Test func anUnresolvedCreaseNamesItsStep() { 1139@Test func anUnresolvedCreaseNamesItsStep() {
1140 #expect(throws: CompileError.unresolvedCrease(step: 2)) { 1140 #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
1141 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), 1141 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
1142 pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) 1142 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
1143 } 1143 }
@@ -1164,7 +1164,7 @@ Expected: FAIL.
1164 1164
1165- [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point** 1165- [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point**
1166 1166
1167Every face of the crease pattern must be counterclockwise with the sheet's top side up; rewind clockwise faces, or reject a pattern exported y-down, so that valley and mountain keep their meaning. Every solved curve has exactly 257 samples. Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Produce each step's end frame by building the step and calling `FoldInterpolator.positions(at: 1)` on it, so vertex ownership, carried axes and reorientation have one implementation; this needs a per-step axis reader that does not require a fully validated file. Add a validator rule: a moving face may not have an overlapping still face on the side it departs toward in frame n − 1, or on the side it arrives from in frame n (a flap leaving from under a layer that covers its hinge, which the interpenetration checker cannot see). Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly. 1167Every face of the crease pattern must be counterclockwise with the sheet's top side up; reject a pattern with a clockwise face (`clockwiseFace`) rather than rewinding it, since rewinding a y-down export also swaps which side is up and so swaps valley and mountain. Every solved curve has exactly 257 samples. Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Produce each step's end frame by building the step and calling `FoldInterpolator.positions(at: 1)` on it, so vertex ownership, carried axes and reorientation have one implementation; Folding's `readStep(_ n: Int, in file: FoldFile) throws -> FoldStep` reads one step from frames 0…n and `readSteps` calls it for each n. The departure/arrival rule (a moving face may not have an overlapping still face on the side it departs toward in frame n − 1, or on the side it arrives from in frame n) needs the interpolator, so it is Folding's `layerMotionDefects`, built in Task 8; `foldc` runs it per step from then on. A crease found on a named crease's line through another layer takes its angle from the pattern's assignment, so `foldc` rejects such an edge (`coincidentAxisAngle`) when it becomes an axis while the named crease's scripted angle is not ±180; deriving its angle is left until a model needs it. Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. Write `faceOrders` and the mid-fold order as every overlapping pair once, `[f, g, s]` with `f < g`, as the fixtures do. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly.
1168 1168
1169- [ ] **Step 4: Run tests to verify they pass** 1169- [ ] **Step 4: Run tests to verify they pass**
1170 1170
@@ -1202,20 +1202,21 @@ git commit -m "foldc: compile a fold script and crease pattern into a FOLD seque
1202 - `func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double` — the largest relative change in a mesh edge's length 1202 - `func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double` — the largest relative change in a mesh edge's length
1203 - `func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection]` — Task 6's test on mesh triangles, reporting FOLD faces; used for non-rigid steps, whose faces bend 1203 - `func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection]` — Task 6's test on mesh triangles, reporting FOLD faces; used for non-rigid steps, whose faces bend
1204 - `func compilePop(step: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, file: FoldFile) throws -> PopRecord` 1204 - `func compilePop(step: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, file: FoldFile) throws -> PopRecord`
1205 - `CompileError` gains `popTooStrained(step: Int, strain: Double)` and `missingSpine(step: Int)` 1205 - `CompileError` gains `popTooStrained(step: Int, strain: Double)`, `missingSpine(step: Int)` and `invalidSpine(step: Int)` (a spine on a step that is not a fold, or not folded flat)
1206 1206
1207Decision 0002: an inside reverse fold has no rigid motion with the flap closed. Flagged steps move in three phases on *t*: 1207Decision 0002: an inside reverse fold has no rigid motion with the flap closed. Flagged steps move in three phases on *t*:
1208 1208
12091. **Open**, `[0, phases[0]]`: the flap opens rigidly on its spine from 180° to `openAngle` (default 30°, measured from flat), carrying everything on that side of the spine. 12091. **Open**, `[0, phases[0]]`: the flap opens rigidly on its spine from 180° to `openAngle` (default 30°, measured from flat), carrying everything on that side of the spine. The layer nearer the step's viewpoint opens; the other holds. A script field to choose the other layer is added when a model needs it.
12102. **Pop**, `[phases[0], phases[1]]`: as-rigid-as-possible interpolation on the render mesh, from the open pose to `popped`. Each triangle's rotation is slerped from one pose to the other, the mesh positions are solved by least squares, and the faces that do not move in the step are held. 12102. **Pop**, `[phases[0], phases[1]]`: as-rigid-as-possible interpolation on the render mesh, from the open pose to `popped`. Each triangle's rotation is slerped from one pose to the other, the mesh positions are solved by least squares, and the faces that do not move in the step are held.
12113. **Close**, `[phases[1], 1]`: rigid, on the reverse-fold branch, from `popped` to frame n. `closeAxes` are an ordinary axis tree with solved curves, relative to `popped`. 12113. **Close**, `[phases[1], 1]`: rigid, on the reverse-fold branch, from `popped` to frame n. `closeAxes` are an ordinary axis tree with solved curves, relative to `popped`.
1212 1212
1213**What makes a step non-rigid is its script, not the solver.** A step with technique `insideReverse`, `outsideReverse` or `sink` must name a `spine`, and `foldc` fails it with `missingSpine` otherwise. Closure cannot decide this: with the flap closed, the solver finds a rigid motion to the reverse fold's coordinates with the tip swung outside (decision 0001, case 4(a)), which is the wrong fold. For a step with a spine, `foldc`: 1213**What makes a step non-rigid is its script, not the solver.** A step with technique `insideReverse`, `outsideReverse` or `sink` must name a `spine`, and `foldc` fails it with `missingSpine` otherwise. Closure cannot decide this: with the flap closed, the solver finds a rigid motion to the reverse fold's coordinates with the tip swung outside (decision 0001, case 4(a)), which is the wrong fold. For a step with a spine, `foldc`:
1214 1214
1215- builds `openAxes` (the spine as one linear axis); 1215- builds `openAxes` (the spine as one linear axis);
1216- builds `popped` (the reverse-fold branch with the spine held at `openAngle`, solved as in Task 7); 1216- builds `popped` (the reverse-fold branch with the spine held at `openAngle`, solved as in Task 7, starting each other crease at `openAngle`/180 of its travel, as the spike does). Closing the loops does not show which branch was found; a wrong branch is caught by the close reaching frame n's coordinates, the final assignment check and the validator's layer rules;
1217- builds `closeAxes` (from `popped` to the end frame, with the spine driven and the rest solved); 1217- builds `closeAxes` (from `popped` to the end frame, with the spine driven and the rest solved);
1218- checks `popped` has one position per vertex; 1218- checks `popped` has one position per vertex;
1219- writes `openAngle` and `phases` into the file explicitly: 30° and [⅓, ⅔] are the script's defaults, and the decoder requires both. The validator rejects a pop record with the wrong number of positions, phases outside 0 < p₀ < p₁ < 1, or a non-rigid step without one (`popMalformed`);
1219- measures the pop's strain on the step's render mesh, and fails the step above **10%**. 1220- measures the pop's strain on the step's render mesh, and fails the step above **10%**.
1220 1221
1221Decision 0002 measured 7.9% at 30° and 29% at 60° on this flap, at a mesh spacing of 1/32 of its longer side. Only the inside reverse fold was measured. Outside reverse folds and sinks use the same model until a model of theirs fails the bound; if one does, stop for a decision. 1222Decision 0002 measured 7.9% at 30° and 29% at 60° on this flap, at a mesh spacing of 1/32 of its longer side. Only the inside reverse fold was measured. Outside reverse folds and sinks use the same model until a model of theirs fails the bound; if one does, stop for a decision.
@@ -1338,8 +1339,9 @@ git commit -m "Non-rigid steps: open, pop, close"
1338- Produces: 1339- Produces:
1339 - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }` 1340 - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }`
1340 - `foldlint <path>...` — runs `validate` and then `readSteps`, which rejects step records the validator does not check; exits 0 when clean, 1 with one defect per line 1341 - `foldlint <path>...` — runs `validate` and then `readSteps`, which rejects step records the validator does not check; exits 0 when clean, 1 with one defect per line
1342 - `func layerMotionDefects(_ file: FoldFile) -> [FoldDefect]` in Folding, and `FoldDefect.movesThroughStillFace(step:moving:still:)` — the departure/arrival rule. Departure is read just after a face starts moving, against frame n − 1's order; arrival just before it stops, against frame n's. A non-rigid step uses its open axes for departure and its close axes for arrival, and the faces that open on the spine count as moving. `layerMotionDefects(step:in:)` checks one step on frames 0…n; `foldlint`, the catalogue gate and `foldc` (per step, as a `stepFailed`) run it. The arrival read time is the one the layer guess uses, so for a step without overrides the arrival check cannot disagree with the guess; it checks overrides and departures
1341 1343
1342**The cup is the model authored here, not the crane.** Six steps — five folds of one axis each and a turn-over — no reverse folds, at most six layers where the corner flaps cross. It exercises script, compile, validate, interpolate and the catalogue gate end to end without exercising coupled steps or deep stacks at the same time. The version authored folds the top flaps down — the front one, then after the turn-over the back one — rather than tucking them into the pocket, and it ends flat. Step 1's instruction starts "Valley fold"; Task 14's accessibility test reads it. 1344**The cup is the model authored here, not the crane.** Six steps — five folds of one axis each and a turn-over — no reverse folds, six layers where the corner flaps cross and eight in the centre once both top flaps are down. It exercises script, compile, validate, interpolate and the catalogue gate end to end without exercising coupled steps or deep stacks at the same time. The version authored folds the top flaps down — the front one, then after the turn-over the back one — rather than tucking them into the pocket, and it ends flat. Step 1's instruction starts "Valley fold"; Task 14's accessibility test reads it.
1343 1345
1344Its crease pattern and `.foldscript` are committed next to the generated `.fold`, so the model regenerates rather than only being editable. `docs/authoring/cup.md` records the crease pattern's provenance and every layer-order override and why. 1346Its crease pattern and `.foldscript` are committed next to the generated `.fold`, so the model regenerates rather than only being editable. `docs/authoring/cup.md` records the crease pattern's provenance and every layer-order override and why.
1345 1347
@@ -1621,6 +1623,8 @@ Depth handling is **hybrid**. `faceOrders` is defined only for faces that overla
1621 1623
1622Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3. 1624Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3.
1623 1625
1626During a non-rigid step the faces that open on the spine move, but `FoldStep.movingFaceUnion` holds only the main axes' faces (the pop's held faces depend on that). `LayerOrder.active`'s rewrite of mixed moving/still pairs must use the set `layerMotionDefects` uses — the main, open and close axes' faces — made a named `FoldStep` property here rather than a second copy. The pop's `SparseCholesky` factor is `@unchecked Sendable`; confirm concurrent solves on one factor are safe, or serialise them, before the renderer calls the interpolator from more than one thread.
1627
1624SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4. 1628SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4.
1625 1629
1626- [ ] **Step 1: Write the failing tests** 1630- [ ] **Step 1: Write the failing tests**
@@ -2069,6 +2073,8 @@ git commit -m "Orbit and zoom, accessibility pass and release assets"
2069 2073
2070Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source. 2074Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source.
2071 2075
2076Carried from batch D, to settle before or while authoring these models: a crease on a named crease's line through another layer with a scripted angle other than ±180 is rejected (the masu's 90° walls need its angle derived instead); `curveTooCoarse` is reported where an unreachable scripted angle is the real cause; the cycle computation has no test for several loops sharing axes (the petal fold); `compilePop` does not assert that held faces sit identically in the open pose and `popped`; a flap whose two layers also join through the body (the crane's neck and tail) fails with `noRigidMotion`, because the opening faces are found by cutting only the spine — rule on "that side of the spine" then; `structurallyEqual` must tolerate solver noise in `pop`.
2077
2072The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault. 2078The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault.
2073 2079
2074Each `docs/authoring/*.md` records the crease pattern's provenance, which guessed layer orders had to be overridden and why, which steps are coupled (solved curves, decision 0001) and which are flagged non-rigid with their `openAngle` and measured pop strain (decision 0002), and that the model regenerates from its script. 2080Each `docs/authoring/*.md` records the crease pattern's provenance, which guessed layer orders had to be overridden and why, which steps are coupled (solved curves, decision 0001) and which are flagged non-rigid with their `openAngle` and measured pop strain (decision 0002), and that the model regenerates from its script.
docs/superpowers/specs/2026-10-19-fold-design.md +2 −2
@@ -558,8 +558,8 @@ the compiler's own tests check that it reproduces those fixtures.
558### The cup first, the crane last 558### The cup first, the crane last
559 559
560The first model compiled is **the cup**: six steps — five folds of one 560The first model compiled is **the cup**: six steps — five folds of one
561axis each and a turn-over — no reverse folds, and a stack of at most six layers where the 561axis each and a turn-over — no reverse folds, six layers where the two corner flaps cross and
562two corner flaps cross. It exercises the entire chain — script, compile, 562eight in the centre once both top flaps are down. It exercises the entire chain — script, compile,
563validate, interpolate, diagram, render, fold under a finger — without 563validate, interpolate, diagram, render, fold under a finger — without
564exercising any of the hard parts at the same time. The version authored 564exercising any of the hard parts at the same time. The version authored
565folds the top flaps down, the front one in front and the back one after the 565folds the top flaps down, the front one in front and the back one after the