Commit 679bb3fc48

679bb3fc48a1ac075338684ca4545d2828907fdb

parent: a23f485bbc

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-19 21:32 UTC

Read authored fold steps, including multi-axis and reorientation kinds

Ref #2

Layout: unified · split

Packages/FoldKit/Package.swift +3
@@ -6,15 +6,18 @@ let package = Package(
66 platforms: [.iOS(.v26), .macOS(.v26)],
77 products: [
88 .library(name: "FoldFormat", targets: ["FoldFormat"]),
9 .library(name: "Folding", targets: ["Folding"]),
910 ],
1011 targets: [
1112 .target(name: "FoldFormat"),
13 .target(name: "Folding", dependencies: ["FoldFormat"]),
1214 .target(
1315 name: "FoldKitTestSupport",
1416 dependencies: ["FoldFormat"],
1517 resources: [.copy("Fixtures")]
1618 ),
1719 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]),
20 .testTarget(name: "FoldingTests", dependencies: ["Folding", "FoldFormat", "FoldKitTestSupport"]),
1821 ],
1922 swiftLanguageModes: [.v6]
2023)
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift added +101
@@ -0,0 +1,101 @@
1import Foundation
2import FoldFormat
3
4/// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases
5/// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step.
6///
7/// Vertices: v0 the centre, v1 (2, 1) the 0° crease's end, v2 (2, 2), v3 the 60° crease's end,
8/// v4 (0, 2), v5 the 140° crease's end, v6 (0, 0), v7 the 260° crease's end, v8 (2, 0).
9/// Edges: e0–e7 the boundary from v1 counterclockwise, e8 the 0° crease, e9 60°, e10 140°,
10/// e11 260°. Faces: f0 the 60° sector, f1 the 80°, f2 the 120° (held), f3 the 100°.
11///
12/// The 140° crease is driven linearly 0 → 180, the 0° crease follows it exactly, and the 260° and
13/// 60° creases are ρ and −ρ, `ρ = 2·atan(k·tan(90°·u))`, `k = cos 70° / cos 10°`. The 260° axis
14/// carries the 0° axis; the 60° crease is off the tree. With `linear` the 260° axis is a straight
15/// line 0 → 180 instead of the curve, which tears the vertex.
16public func degreeFourVertex(linear: Bool = false) -> FoldFile {
17 let c = SIMD3<Double>(1, 1, 0)
18 let flat: [SIMD3<Double>] = [
19 c,
20 SIMD3(2, 1, 0),
21 SIMD3(2, 2, 0),
22 SIMD3(1 + 1 / tan(radians(60)), 2, 0),
23 SIMD3(0, 2, 0),
24 SIMD3(0, 1 + tan(radians(40)), 0),
25 SIMD3(0, 0, 0),
26 SIMD3(1 - tan(radians(10)), 0, 0),
27 SIMD3(2, 0, 0),
28 ]
29
30 // Flat-folded, each 180° fold is a reflection across its crease line in the held face's plane.
31 func reflect(_ p: SIMD3<Double>, across degrees: Double) -> SIMD3<Double> {
32 let d = p - c, a = 2 * radians(degrees)
33 return c + SIMD3(d.x * cos(a) + d.y * sin(a), d.x * sin(a) - d.y * cos(a), 0)
34 }
35 let folded: [SIMD3<Double>] = [
36 c,
37 reflect(flat[1], across: 260), // f3
38 reflect(reflect(flat[2], across: 0), across: 260), // f0, carried by f3
39 reflect(flat[3], across: 140), // f1
40 reflect(flat[4], across: 140), // f1
41 flat[5], flat[6], flat[7], // f2, held
42 reflect(flat[8], across: 260), // f3
43 ]
44
45 let creases = 8..<12
46 let boundary = Array(repeating: EdgeAssignment.boundary, count: 8)
47 // the last sample is the end frame's angle exactly, as foldc writes it
48 let curve = (0..<256).map { degreeFourExactAngle(11, at: Double($0) / 256) } + [180]
49 let step = StepRecord(
50 kind: .fold,
51 technique: .plain,
52 instruction: "Fold the vertex flat.",
53 axes: [
54 AxisRecord(edge: 10, movingFaces: [1], startAngle: 0, endAngle: 180),
55 AxisRecord(edge: 11, movingFaces: [3], startAngle: 0, endAngle: 180,
56 angles: linear ? nil : curve),
57 AxisRecord(edge: 8, movingFaces: [0], startAngle: 0, endAngle: 180, parent: 1),
58 ],
59 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
60 )
61 // Bottom to top along +z: f2, f1, f0, f3. f2 and f0 face +z, f1 and f3 face −z, and s is
62 // read on the side g's normal points toward.
63 let orders = [[0, 1, -1], [0, 2, 1], [0, 3, 1], [1, 2, 1], [1, 3, 1], [2, 3, 1]]
64
65 return FoldFile(
66 fileSpec: 1.2,
67 fileTitle: "Degree-4 vertex",
68 fileAuthor: "Traditional",
69 fileClasses: ["diagrams"],
70 edgesVertices: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 1],
71 [0, 1], [0, 3], [0, 5], [0, 7]],
72 facesVertices: [[0, 1, 2, 3], [0, 3, 4, 5], [0, 5, 6, 7], [0, 7, 8, 1]],
73 edgesFirstCreasedAtStep: Array(repeating: nil, count: 8) + creases.map { _ in 1 },
74 frames: [
75 FoldFrame(verticesCoords: flat,
76 edgesAssignment: boundary + creases.map { _ in .flat },
77 edgesFoldAngle: Array(repeating: 0, count: 12),
78 faceOrders: []),
79 FoldFrame(verticesCoords: folded,
80 edgesAssignment: boundary + [.valley, .mountain, .valley, .valley],
81 edgesFoldAngle: Array(repeating: 0, count: 8) + [180, -180, 180, 180],
82 faceOrders: orders,
83 faceOrdersMidFold: orders,
84 step: step),
85 ]
86 )
87}
88
89/// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form.
90public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double {
91 let k = cos(radians(70)) / cos(radians(10))
92 let rho = 2 * atan2(k * sin(radians(90 * t)), cos(radians(90 * t))) * 180 / .pi
93 switch edge {
94 case 8, 10: return 180 * t
95 case 11: return rho
96 case 9: return -rho
97 default: preconditionFailure("edge \(edge) is not a crease of the degree-4 vertex")
98 }
99}
100
101private func radians(_ degrees: Double) -> Double { degrees * .pi / 180 }
Packages/FoldKit/Sources/Folding/FoldStep.swift added +96
@@ -0,0 +1,96 @@
1import FoldFormat
2
3/// One crease of a step. `origin` and `direction` (a unit vector) are in the coordinates of the
4/// frame the step starts from, directed as the moving face adjacent to `edge` traverses it, so a
5/// positive rotation by the right-hand rule is a valley. `parent` is the index, in the step's
6/// `axes`, of the axis whose motion carries this one. `curve` is the fold angle at evenly spaced
7/// points of `window`; without it the angle is linear on the window.
8public struct FoldAxis: Equatable, Sendable {
9 public let edge: Int
10 public let origin: SIMD3<Double>
11 public let direction: SIMD3<Double>
12 public let movingFaces: Set<Int>
13 public let startAngle: Double
14 public let endAngle: Double
15 public let peakAngle: Double?
16 public let parent: Int?
17 public let window: ClosedRange<Double>
18 public let curve: [Double]?
19
20 /// The fold angle in degrees at `t` of the step. Before its window the axis waits at the
21 /// start and after it holds at the end.
22 public func angle(at t: Double, kind: StepKind) -> Double {
23 let u = min(max((t - window.lowerBound) / (window.upperBound - window.lowerBound), 0), 1)
24 if let curve { return hermite(curve, at: u) }
25 if kind == .foldAndUnfold {
26 return startAngle + (peakAngle! - startAngle) * (1 - abs(2 * u - 1))
27 }
28 return startAngle + u * (endAngle - startAngle)
29 }
30}
31
32/// The open, pop and close of a non-rigid step. `openAxes` are in the coordinates of the frame
33/// the step starts from; `closeAxes` are in the coordinates of `popped`.
34public struct Pop: Equatable, Sendable {
35 public let spine: [Int]
36 public let openAngle: Double
37 public let phases: ClosedRange<Double>
38 public let openAxes: [FoldAxis]
39 public let popped: [SIMD3<Double>]
40 public let closeAxes: [FoldAxis]
41}
42
43/// Step `index`, taking frame `index − 1` to frame `index`. `axes` lists every parent before
44/// its children.
45public struct FoldStep: Equatable, Sendable {
46 public let index: Int
47 public let kind: StepKind
48 public let technique: StepTechnique
49 public let instruction: String
50 public let axes: [FoldAxis]
51 public let rotateDegrees: Double?
52 public let turnOverAxis: TurnOverAxis?
53 public let repeatOf: Int?
54 public let nonRigid: Bool
55 public let pop: Pop?
56 public let viewpoint: Viewpoint
57
58 public var movingFaceUnion: Set<Int> {
59 axes.reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
60 }
61}
62
63public enum StepError: Error, Equatable, Sendable {
64 case axisNotAnEdge(step: Int, edge: Int)
65 case axisNotOnMovingSetBoundary(step: Int, edge: Int)
66 case movingFacesOutOfRange(step: Int)
67 case overlappingMovingSetsWithinAStep(step: Int)
68 case rotateWithoutDegrees(step: Int)
69 case turnOverWithoutAxis(step: Int)
70 case foldAndUnfoldWithoutPeak(step: Int)
71 case missingInstruction(step: Int)
72 case axisParentCycle(step: Int)
73 case axisWindowOutOfRange(step: Int)
74 case curveTooShort(step: Int)
75 case nonRigidWithoutPop(step: Int)
76 case popPhasesOutOfOrder(step: Int)
77}
78
79/// Cubic Hermite interpolation of evenly spaced samples over 0...1, with central-difference
80/// tangents inside and one-sided differences at the ends.
81private func hermite(_ samples: [Double], at u: Double) -> Double {
82 let n = samples.count - 1
83 let s = u * Double(n)
84 let i = min(Int(s), n - 1)
85 let f = s - Double(i)
86 func tangent(_ j: Int) -> Double {
87 switch j {
88 case 0: samples[1] - samples[0]
89 case n: samples[n] - samples[n - 1]
90 default: (samples[j + 1] - samples[j - 1]) / 2
91 }
92 }
93 let f2 = f * f, f3 = f2 * f
94 return (2 * f3 - 3 * f2 + 1) * samples[i] + (f3 - 2 * f2 + f) * tangent(i)
95 + (3 * f2 - 2 * f3) * samples[i + 1] + (f3 - f2) * tangent(i + 1)
96}
Packages/FoldKit/Sources/Folding/StepReader.swift added +134
@@ -0,0 +1,134 @@
1import FoldFormat
2import simd
3
4/// Reads every frame's authored `krz:step`. `result[k]` is step `k + 1`.
5public func readSteps(_ file: FoldFile) throws -> [FoldStep] {
6 let edgeFaces = edgesFaces(file)
7 return try file.frames.indices.dropFirst().map { n in
8 guard let record = file.frames[n].step else { throw FoldError.missingStepRecord(step: n) }
9 return try readStep(n, record, file, edgeFaces)
10 }
11}
12
13private func readStep(_ n: Int, _ record: StepRecord, _ file: FoldFile, _ edgeFaces: [[Int]]) throws -> FoldStep {
14 guard let instruction = record.instruction, !instruction.allSatisfy(\.isWhitespace) else {
15 throw StepError.missingInstruction(step: n)
16 }
17 if record.kind == .rotate && record.rotateDegrees == nil {
18 throw StepError.rotateWithoutDegrees(step: n)
19 }
20 if record.kind == .turnOver && record.turnOverAxis == nil {
21 throw StepError.turnOverWithoutAxis(step: n)
22 }
23 if record.kind == .foldAndUnfold && record.axes.contains(where: { $0.peakAngle == nil }) {
24 throw StepError.foldAndUnfoldWithoutPeak(step: n)
25 }
26 if record.nonRigid && record.pop == nil {
27 throw StepError.nonRigidWithoutPop(step: n)
28 }
29
30 let start = file.frames[n - 1].verticesCoords
31 let axes = try readAxes(record.axes, step: n, points: start, file, edgeFaces)
32
33 var pop: Pop?
34 if let p = record.pop {
35 guard p.phases.count == 2, 0 < p.phases[0], p.phases[0] < p.phases[1], p.phases[1] < 1 else {
36 throw StepError.popPhasesOutOfOrder(step: n)
37 }
38 pop = Pop(spine: p.spine, openAngle: p.openAngle, phases: p.phases[0]...p.phases[1],
39 openAxes: try readAxes(p.openAxes, step: n, points: start, file, edgeFaces),
40 popped: p.popped,
41 closeAxes: try readAxes(p.closeAxes, step: n, points: p.popped, file, edgeFaces))
42 }
43
44 return FoldStep(index: n, kind: record.kind, technique: record.technique, instruction: instruction,
45 axes: axes, rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis,
46 repeatOf: record.repeatOf, nonRigid: record.nonRigid, pop: pop,
47 viewpoint: record.viewpoint)
48}
49
50/// One step's axes, directed against `points`, reordered so every parent precedes its children.
51private func readAxes(_ records: [AxisRecord], step n: Int, points: [SIMD3<Double>], _ file: FoldFile,
52 _ edgeFaces: [[Int]]) throws -> [FoldAxis] {
53 var lines: [(origin: SIMD3<Double>, direction: SIMD3<Double>)] = []
54 var moved = Set<Int>()
55 for r in records {
56 guard file.edgesVertices.indices.contains(r.edge) else {
57 throw StepError.axisNotAnEdge(step: n, edge: r.edge)
58 }
59 guard r.movingFaces.allSatisfy(file.facesVertices.indices.contains) else {
60 throw StepError.movingFacesOutOfRange(step: n)
61 }
62 let sides = edgeFaces[r.edge]
63 let movingSides = sides.filter(r.movingFaces.contains)
64 guard sides.count == 2, movingSides.count == 1 else {
65 throw StepError.axisNotOnMovingSetBoundary(step: n, edge: r.edge)
66 }
67 let window = r.window ?? [0, 1]
68 guard window.count == 2, 0 <= window[0], window[0] < window[1], window[1] <= 1 else {
69 throw StepError.axisWindowOutOfRange(step: n)
70 }
71 if let curve = r.angles, curve.count < 2 {
72 throw StepError.curveTooShort(step: n)
73 }
74 let faceSet = Set(r.movingFaces)
75 guard moved.isDisjoint(with: faceSet) else {
76 throw StepError.overlappingMovingSetsWithinAStep(step: n)
77 }
78 moved.formUnion(faceSet)
79 lines.append(traversal(of: file.edgesVertices[r.edge], by: file.facesVertices[movingSides[0]], points))
80 }
81
82 // place each axis after its parent, keeping the authored order otherwise
83 var state = Array(repeating: 0, count: records.count) // 0 unplaced, 1 placing, 2 placed
84 var order: [Int] = []
85 func place(_ i: Int) throws {
86 if state[i] == 2 { return }
87 guard state[i] == 0 else { throw StepError.axisParentCycle(step: n) }
88 state[i] = 1
89 if let p = records[i].parent {
90 guard records.indices.contains(p) else { throw StepError.axisParentCycle(step: n) }
91 try place(p)
92 }
93 state[i] = 2
94 order.append(i)
95 }
96 for i in records.indices { try place(i) }
97
98 var position = Array(repeating: 0, count: records.count)
99 for (k, i) in order.enumerated() { position[i] = k }
100 return order.map { i in
101 let r = records[i]
102 let window = r.window ?? [0, 1]
103 return FoldAxis(edge: r.edge, origin: lines[i].origin, direction: lines[i].direction,
104 movingFaces: Set(r.movingFaces), startAngle: r.startAngle, endAngle: r.endAngle,
105 peakAngle: r.peakAngle, parent: r.parent.map { position[$0] },
106 window: window[0]...window[1], curve: r.angles)
107 }
108}
109
110/// The edge as `face` traverses it in `faces_vertices` order: the corner it leaves from and the
111/// unit direction toward the next.
112private func traversal(of edge: [Int], by face: [Int], _ points: [SIMD3<Double>])
113 -> (origin: SIMD3<Double>, direction: SIMD3<Double>) {
114 let i = face.indices.first { i in
115 Set([face[i], face[(i + 1) % face.count]]) == Set(edge)
116 }!
117 let origin = points[face[i]]
118 return (origin, normalize(points[face[(i + 1) % face.count]] - origin))
119}
120
121/// The faces on each side of each edge, from consecutive corners of `faces_vertices`.
122private func edgesFaces(_ file: FoldFile) -> [[Int]] {
123 var byEnds: [SIMD2<Int>: [Int]] = [:]
124 for (f, corners) in file.facesVertices.enumerated() {
125 for i in corners.indices {
126 let u = corners[i], v = corners[(i + 1) % corners.count]
127 byEnds[SIMD2(min(u, v), max(u, v)), default: []].append(f)
128 }
129 }
130 return file.edgesVertices.map { ends in
131 guard ends.count == 2 else { return [] }
132 return byEnds[SIMD2(min(ends[0], ends[1]), max(ends[0], ends[1]))] ?? []
133 }
134}
Packages/FoldKit/Tests/FoldingTests/StepReadingTests.swift added +116
@@ -0,0 +1,116 @@
1import Foundation
2import Testing
3import FoldFormat
4import Folding
5import FoldKitTestSupport
6
7@Test func stepIndicesCountFromOne() throws {
8 let steps = try readSteps(FoldFile(contentsOf: fixture("half.fold")))
9 #expect(steps.map(\.index) == [1, 2, 3])
10}
11
12@Test func simpleValleyFoldReadsOneAxis() throws {
13 let step = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0]
14 #expect(step.axes.count == 1)
15 #expect(step.axes[0].endAngle == 180)
16}
17
18@Test func letterFoldReadsTwoSimultaneousAxes() throws {
19 let step = try readSteps(FoldFile(contentsOf: fixture("letter.fold")))[0]
20 #expect(step.axes.count == 2)
21}
22
23@Test(arguments: ["half.fold", "letter.fold", "letter-sequential.fold", "quarters.fold", "occlusion.fold"])
24func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws {
25 for step in try readSteps(FoldFile(contentsOf: fixture(name))) {
26 let union = step.axes.reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
27 #expect(union.count == step.axes.reduce(0) { $0 + $1.movingFaces.count })
28 }
29}
30
31@Test func turnOverStepHasNoAxesAndAnAxisToTurnAbout() throws {
32 let turn = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[1]
33 #expect(turn.kind == .turnOver)
34 #expect(turn.axes.isEmpty)
35 #expect(turn.turnOverAxis == .vertical)
36}
37
38@Test func rotateStepCarriesItsDegrees() throws {
39 #expect(try readSteps(FoldFile(contentsOf: fixture("half.fold")))[2].rotateDegrees == 90)
40}
41
42@Test func foldAndUnfoldPeaksMidwayAndReturns() throws {
43 let s = try readSteps(FoldFile(contentsOf: fixture("quarters.fold")))[0]
44 #expect(s.kind == .foldAndUnfold)
45 #expect(s.axes[0].angle(at: 0.5, kind: s.kind) == 180)
46 #expect(s.axes[0].angle(at: 1, kind: s.kind) == 0)
47}
48
49@Test func axisIsDirectedAsTheMovingFaceTraversesIt() throws {
50 // f1 = [v1, v2, v3, v4] traverses e6 = [v1, v4] from v4 to v1
51 let axis = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0].axes[0]
52 #expect(axis.origin == SIMD3(1, 2, 0))
53 #expect(axis.direction == SIMD3(0, -1, 0))
54}
55
56@Test func instructionIsReadVerbatim() throws {
57 let f = try FoldFile(contentsOf: fixture("half.fold"))
58 #expect(try readSteps(f)[0].instruction == f.frames[1].step?.instruction)
59}
60
61@Test func aWindowedAxisWaitsAndThenHolds() throws {
62 let s = try readSteps(FoldFile(contentsOf: fixture("letter-staggered.fold")))[0]
63 #expect(s.axes[0].angle(at: 0.25, kind: s.kind) == 90)
64 #expect(s.axes[1].angle(at: 0.25, kind: s.kind) == 0)
65 #expect(s.axes[0].angle(at: 0.75, kind: s.kind) == 180)
66 #expect(s.axes[1].angle(at: 0.75, kind: s.kind) == 90)
67}
68
69@Test func aCurveIsInterpolatedBetweenItsSamples() throws {
70 let axis = try readSteps(degreeFourVertex()).first!.axes.first { $0.curve != nil }!
71 let t = 0.5 + 0.5 / 256 // halfway between two samples
72 #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6)
73}
74
75@Test func aNonRigidStepNeedsItsPop() {
76 #expect(throws: StepError.nonRigidWithoutPop(step: 1)) {
77 try readSteps(FoldFile(contentsOf: fixture("nonrigid-no-pop.fold")))
78 }
79}
80
81@Test func rotateWithoutDegreesThrows() {
82 #expect(throws: StepError.rotateWithoutDegrees(step: 3)) {
83 try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold")))
84 }
85}
86
87@Test func movingFaceOutOfRangeThrows() {
88 #expect(throws: StepError.movingFacesOutOfRange(step: 1)) {
89 try readSteps(FoldFile(contentsOf: fixture("bad-moving-face.fold")))
90 }
91}
92
93@Test func parentsComeBeforeTheirChildren() throws {
94 // list the carried 0° axis first; readSteps must move its parent ahead of it
95 var file = degreeFourVertex()
96 let record = file.frames[1].step!
97 let reordered = [record.axes[2], record.axes[0], record.axes[1]].map { a in
98 AxisRecord(edge: a.edge, movingFaces: a.movingFaces, startAngle: a.startAngle,
99 endAngle: a.endAngle, peakAngle: a.peakAngle, parent: a.parent.map { _ in 2 },
100 window: a.window, angles: a.angles)
101 }
102 file.frames[1].step = StepRecord(kind: record.kind, technique: record.technique,
103 instruction: record.instruction, axes: reordered,
104 viewpoint: record.viewpoint)
105 let axes = try readSteps(file)[0].axes
106 for (i, axis) in axes.enumerated() {
107 if let parent = axis.parent { #expect(parent < i) }
108 }
109 let child = try #require(axes.first { $0.parent != nil })
110 #expect(axes[child.parent!].edge == record.axes[record.axes[2].parent!].edge)
111}
112
113@Test func theDegreeFourVertexIsAValidModel() {
114 #expect(validate(degreeFourVertex()) == [])
115 #expect(validate(degreeFourVertex(linear: true)) == [])
116}