| @@ -4,7 +4,7 @@ |
| 4 | |
4 | |
| 5 | **Goal:** An iOS app that folds traditional origami models under your finger and generates their Yoshizawa–Randlett diagrams from the same data, so the diagram and the model cannot disagree. |
5 | **Goal:** An iOS app that folds traditional origami models under your finger and generates their Yoshizawa–Randlett diagrams from the same data, so the diagram and the model cannot disagree. |
| 6 | |
6 | |
| 7 | **Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives: a step's axes form a tree, each with its own window on that parameter and, where faces form loops, an angle curve `foldc` solves (decision 0001). Reverse folds, sinks and inversions have no rigid path and are flagged non-rigid, moving by the model Task 0b chooses. Draw order is hybrid — the depth buffer between clusters of near-coplanar overlapping faces, the active `faceOrders` within each. The frames are produced by a macOS fold-script compiler that ships with the repo but not in the app. |
7 | **Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives: a step's axes form a tree, each with its own window on that parameter and, where faces form loops, an angle curve `foldc` solves (decision 0001). Reverse folds and sinks have no rigid path with the flap closed; they are flagged non-rigid and open, pop and close (decision 0002), the pop held to 10% strain on a render mesh. Draw order is hybrid — the depth buffer between clusters of near-coplanar overlapping faces, the active `faceOrders` within each. The frames are produced by a macOS fold-script compiler that ships with the repo but not in the app. |
| 8 | |
8 | |
| 9 | **Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app. |
9 | **Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app. |
| 10 | |
10 | |
| @@ -27,7 +27,7 @@ |
| 27 | - **Steps are authored, never derived from a frame diff.** That includes `instruction`, which is the accessibility label. |
27 | - **Steps are authored, never derived from a frame diff.** That includes `instruction`, which is the accessibility label. |
| 28 | - **`turnOver` and `rotate` change the coordinates.** Frame n is frame n − 1 rotated about its bounding-box centre; the camera does not move. |
28 | - **`turnOver` and `rotate` change the coordinates.** Frame n is frame n − 1 rotated about its bounding-box centre; the camera does not move. |
| 29 | - Paper is rigid flat facets hinged at straight creases, except during a step flagged `nonRigid`. No stiffness, self-collision response or crumpling. |
29 | - Paper is rigid flat facets hinged at straight creases, except during a step flagged `nonRigid`. No stiffness, self-collision response or crumpling. |
| 30 | - **Interpolation (decision 0001, option A).** A step's axes form a tree: an axis may name a parent axis whose motion carries it. Each axis has a window on *t* (default 0…1) and either a linear angle or a solved curve of 257 samples, rebuilt by cubic Hermite interpolation. Steps whose technique has no rigid path — inside and outside reverse folds, sinks, inversions — carry `nonRigid: true`; the isometry gate does not apply to them and Task 0b's strain bound does. |
30 | - **Interpolation (decision 0001, option A).** A step's axes form a tree: an axis may name a parent axis whose motion carries it. Each axis has a window on *t* (default 0…1) and either a linear angle or a solved curve of 257 samples, rebuilt by cubic Hermite interpolation. Steps whose technique has no rigid path — inside and outside reverse folds, sinks — carry `nonRigid: true` and a `pop` record, and move by open, pop, close (decision 0002, Task 7b): the flap opens rigidly to 30° from flat by default, the tip pops through on the render mesh, and the flap closes rigidly. The isometry gate does not apply to the pop; the bound does: at most 10% largest edge strain on the render mesh. A step with no rigid motion that is not a reverse fold or sink stops compilation and goes to the author. |
| 31 | - Layer order is authored, never computed. Corrections to the compiler's guess live in the fold script. |
31 | - Layer order is authored, never computed. Corrections to the compiler's guess live in the fold script. |
| 32 | - v1 ships **four** traditional models: the cup, the crane, the sampan and the box (the masu). Every `file_author` is exactly `"Traditional"`, enforced by the validator. |
32 | - v1 ships **four** traditional models: the cup, the crane, the sampan and the box (the masu). Every `file_author` is exactly `"Traditional"`, enforced by the validator. |
| 33 | - Every shipped model is produced by `foldc` from a committed crease pattern and fold script, and recompiling them reproduces the shipped file (structurally, coordinates within 1e-12). Hand-edited `.fold` files are not shipped. |
33 | - Every shipped model is produced by `foldc` from a committed crease pattern and fold script, and recompiling them reproduces the shipped file (structurally, coordinates within 1e-12). Hand-edited `.fold` files are not shipped. |
| @@ -39,12 +39,13 @@ |
| 39 | |
39 | |
| 40 | ## Review Focus |
40 | ## Review Focus |
| 41 | |
41 | |
| 42 | 1. **A step with several simultaneous axes.** A petal fold moves several facet sets about several creases at once on one shared parameter; where faces form closed loops around interior vertices the angles are coupled nonlinearly, and some axes are carried by others. Decision 0001 settled the model; the axis tree, windows and curves are read in Task 3, applied in Task 4 and solved in Task 7. Steps with no rigid path are Task 0b's. |
42 | 1. **A step with several simultaneous axes.** A petal fold moves several facet sets about several creases at once on one shared parameter; where faces form closed loops around interior vertices the angles are coupled nonlinearly, and some axes are carried by others. Decision 0001 settled the model; the axis tree, windows and curves are read in Task 3, applied in Task 4 and solved in Task 7. The petal fold is one of these (decision 0002). |
| 43 | 2. **Two facets that are both moving.** The end frame's ordering does not order two simultaneously moving sets against each other during the motion. Such a step must carry `krz:faceOrders_midFold` or be rejected. Test in Task 2. Task 0 also reports whether this rule has a consumer the clusters do not already cover. |
43 | 2. **Two facets that are both moving.** The end frame's ordering does not order two simultaneously moving sets against each other during the motion. Such a step must carry `krz:faceOrders_midFold` or be rejected. Test in Task 2. Decision 0001 found no case for this rule that staggered windows and the clusters do not cover; removing it is the author's call. |
| 44 | 3. **Coplanar stacked facets, and orbiting underneath.** The depth buffer cannot order coplanar or nearly coplanar facets, and `faceOrders`'s `s` sign reverses when the view crosses `g`'s plane. Stacked facets must not z-fight at any orbit angle or at the start and end of a fold, and the stack must not invert when you orbit under it. Test in Tasks 5 and 10. |
44 | 3. **Coplanar stacked facets, and orbiting underneath.** The depth buffer cannot order coplanar or nearly coplanar facets, and `faceOrders`'s `s` sign reverses when the view crosses `g`'s plane. Stacked facets must not z-fight at any orbit angle or at the start and end of a fold, and the stack must not invert when you orbit under it. Test in Tasks 5 and 10. |
| 45 | 4. **A degenerate drag direction.** When the moving facet's centroid travels nearly along the view direction the drag projection approaches zero and the fold becomes uncontrollable. Test in Task 12. |
45 | 4. **A degenerate drag direction.** When the moving facet's centroid travels nearly along the view direction the drag projection approaches zero and the fold becomes uncontrollable. Test in Task 12. |
| 46 | 5. **A crease the reader has not met yet.** Because frame 0 carries every crease in the sequence, a crease not yet made must not be drawn, and an occluded crease must not be drawn either. Test in Task 9. |
46 | 5. **A crease the reader has not met yet.** Because frame 0 carries every crease in the sequence, a crease not yet made must not be drawn, and an occluded crease must not be drawn either. Test in Task 9. |
| 47 | 6. **A crease through several layers.** One crease in the script is several coincident edges, one per layer, possibly with opposite fold-angle signs on a flipped layer. Test in Tasks 4 and 7. |
47 | 6. **A crease through several layers.** One crease in the script is several coincident edges, one per layer, possibly with opposite fold-angle signs on a flipped layer. Test in Tasks 4 and 7. |
| |
48 | 7. **A step with no rigid motion.** An inside reverse fold cannot be made rigidly with the flap closed. It opens, pops and closes, the pop held to 10% strain, the tip landing between the flap's layers. Test in Task 7b. |
| 48 | |
49 | |
| 49 | ## Synthetic fixtures |
50 | ## Synthetic fixtures |
| 50 | |
51 | |
| @@ -77,6 +78,7 @@ Defect fixtures, each a copy of one above with one change: |
| 77 | | `folded-boundary.fold` | `half.fold`, frame 1's e0 at 90 | |
78 | | `folded-boundary.fold` | `half.fold`, frame 1's e0 at 90 | |
| 78 | | `no-instruction.fold` | `half.fold`, step 1 without `instruction` | |
79 | | `no-instruction.fold` | `half.fold`, step 1 without `instruction` | |
| 79 | | `rotate-no-degrees.fold` | `half.fold`, step 3 without `rotateDegrees` | |
80 | | `rotate-no-degrees.fold` | `half.fold`, step 3 without `rotateDegrees` | |
| |
81 | | `nonrigid-no-pop.fold` | `half.fold`, step 1 with `nonRigid: true` and no `pop` | |
| 80 | | `bad-moving-face.fold` | `half.fold`, step 1's `movingFaces` is `[7]` | |
82 | | `bad-moving-face.fold` | `half.fold`, step 1's `movingFaces` is `[7]` | |
| 81 | | `letter-no-midfold.fold` | `letter.fold` without `krz:faceOrders_midFold` | |
83 | | `letter-no-midfold.fold` | `letter.fold` without `krz:faceOrders_midFold` | |
| 82 | | `letter-technique.fold` | `letter.fold` with `technique: "insideReverse"` (notation test only) | |
84 | | `letter-technique.fold` | `letter.fold` with `technique: "insideReverse"` (notation test only) | |
| @@ -87,6 +89,28 @@ Defect fixtures, each a copy of one above with one change: |
| 87 | | `face-inside-fold.fold` | `occlusion.fold`, frame 2 puts the strip f2 between f1 and f0, inside the fold at e8 whose line crosses f2's interior | |
89 | | `face-inside-fold.fold` | `occlusion.fold`, frame 2 puts the strip f2 between f1 and f0, inside the fold at e8 whose line crosses f2's interior | |
| 88 | | `nonconvex.fold` | an L-shaped sheet as one face, no frames | |
90 | | `nonconvex.fold` | an L-shaped sheet as one face, no frames | |
| 89 | |
91 | |
| |
92 | ### Test helpers |
| |
93 | |
| |
94 | Each task adds the helpers its tests use to `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift`, and adds `FoldKitTestSupport`'s target dependencies in `Package.swift` as they appear: `FoldFormat` from Task 1, `Folding` from Task 3, `FoldCompiler` from Task 7. |
| |
95 | |
| |
96 | **Units.** Lengths are in the sheet's units. Every length tolerance below 1e-9 is absolute. The isometry tolerances (1e-6) are relative to the sheet's longer side: `sheetSize(file)` times 1e-6. |
| |
97 | |
| |
98 | | Task | Helpers | |
| |
99 | |---|---| |
| |
100 | | 1 | `fixture(_ name: String) -> URL` | |
| |
101 | | 2 | — | |
| |
102 | | 3 | `degreeFourVertex(linear: Bool = false) -> FoldFile`, `degreeFourExactAngle(_ edge: Int, at t: Double) -> Double` | |
| |
103 | | 4 | `interpolator(_ fixture: String, step: Int) throws -> (FoldFile, FoldInterpolator)`, `maxEdgeLengthDrift(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Double` (largest change in a FOLD edge's length against frame 0), `pairwiseDistancesAgree(_ a: [SIMD3<Double>], _ b: [SIMD3<Double>]) -> Bool`, `gridSheet(cells: Int) -> FoldFile`, `sheetSize(_ file: FoldFile) -> Double` | |
| |
104 | | 5 | `interpolatorWithStep(_ fixture: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator)`; `stackedSquarePositions()`, `separatedSquarePositions()`, `threeStackedPositions()` (unit squares at z = 0 and 0, 0 and 1, 0, 0 and 0); `twoSquares()`, `threeSquares()` (their faces) | |
| |
105 | | 6 | `interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator)`, `interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator)` — both built in code as the tests describe | |
| |
106 | | 7 | `compiled(_ name: String) throws -> FoldFile` (compiles `<name>.foldscript` against `<name>-cp.fold`), `structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool`, `degreeFourPattern() -> FoldFile` and `degreeFourScript() -> FoldScript` (the same vertex, edge numbering identical to `degreeFourVertex()`'s) | |
| |
107 | | 7b | `tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool` (the spike's probe at sheet point (2.75, 0.75)), `FoldScript.withOpenAngle(_:step:)`, `FoldScript.withoutSpine(step:)` | |
| |
108 | | 8 | `script(_ name: String) -> URL`, `pattern(_ name: String) -> URL` (`Models/<name>.foldscript`, `Models/<name>-cp.fold`), `runFoldlint(on: URL) throws -> (exitCode: Int32, output: String)` | |
| |
109 | | 9 | `diagram(_ fixture: String, step: Int) throws -> Diagram`, `visibleSegmentsOf(_ fixture: String, edge: Int, inFrame: Int) throws -> [(SIMD2<Double>, SIMD2<Double>)]`, `segmentLength(_:)`, `render(_ diagram: Diagram) -> CGImage`, `expectSnapshot(_ image: CGImage, named: String) throws` | |
| |
110 | | 10 | `renderToPixels(_ scene: Scene, clusters: [CoplanarCluster]? = nil, camera: Camera, faceColours: [SIMD4<Float>]? = nil) throws -> [SIMD4<Float>]`, `renderStackWithComputedClusters(camera:faceColours:)`, the scene builders the tests name (`Scene` is positions, faces, normals and their `RenderMesh`), `uniqueColours`, `dominantColour`, `cameraAbove()`, `cameraBelow()` | |
| |
111 | | 12 | `mapping(_ fixture: String, step: Int) throws -> FoldParameterMapping`, `mappingForFoldTowardTheCamera() throws -> FoldParameterMapping` | |
| |
112 | | 15 | `authoringDoc(_ name: String) -> URL` | |
| |
113 | |
| 90 | --- |
114 | --- |
| 91 | |
115 | |
| 92 | ### Setup: repository |
116 | ### Setup: repository |
| @@ -95,7 +119,7 @@ Done once, before Task 0. |
| 95 | |
119 | |
| 96 | 1. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`. |
120 | 1. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`. |
| 97 | 2. Add `.gitignore` (`.build/`, `.swiftpm/`, `App/*.xcodeproj/`, `DerivedData/`, `.DS_Store`) and `LICENSE` (0BSD). Commit them with `docs/`, and push to `main`. `CLAUDE.md` is excluded by the author's global gitignore, as in the other krz repos, and stays local; edits to it are not part of any merge request. This first push is the one direct push to `main`; every later change goes through a merge request. |
121 | 2. Add `.gitignore` (`.build/`, `.swiftpm/`, `App/*.xcodeproj/`, `DerivedData/`, `.DS_Store`) and `LICENSE` (0BSD). Commit them with `docs/`, and push to `main`. `CLAUDE.md` is excluded by the author's global gitignore, as in the other krz repos, and stays local; edits to it are not part of any merge request. This first push is the one direct push to `main`; every later change goes through a merge request. |
| 98 | 3. Work is batched into seven merge requests, each with one gitbay issue: |
122 | 3. Work is batched into eight merge requests, each with one gitbay issue: |
| 99 | |
123 | |
| 100 | | Batch | Tasks | Branch | |
124 | | Batch | Tasks | Branch | |
| 101 | |---|---|---| |
125 | |---|---|---| |
| @@ -103,7 +127,7 @@ Done once, before Task 0. |
| 103 | | A2 | 0b — non-rigid steps, petal fold, sampan, masu | `spike-non-rigid` | |
127 | | A2 | 0b — non-rigid steps, petal fold, sampan, masu | `spike-non-rigid` | |
| 104 | | B | 1–3 — decoding, validator, steps | `format-and-steps` | |
128 | | B | 1–3 — decoding, validator, steps | `format-and-steps` | |
| 105 | | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` | |
129 | | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` | |
| 106 | | D | 7–8 — `foldc`, `foldlint`, the cup | `compiler-and-cup` | |
130 | | D | 7, 7b, 8 — `foldc`, non-rigid steps, `foldlint`, the cup | `compiler-and-cup` | |
| 107 | | E | 9–10 — diagram, renderer | `diagram-and-renderer` | |
131 | | E | 9–10 — diagram, renderer | `diagram-and-renderer` | |
| 108 | | F | 11–14 — the app | `app` | |
132 | | F | 11–14 — the app | `app` | |
| 109 | | G | 15 — crane, sampan, box | `models` | |
133 | | G | 15 — crane, sampan, box | `models` | |
| @@ -195,23 +219,25 @@ git commit -m "Interpolation model spike and decision record" |
| 195 | - In the same merge request, apply the result: |
219 | - In the same merge request, apply the result: |
| 196 | - the design doc's *Interpolation* section; |
220 | - the design doc's *Interpolation* section; |
| 197 | - Task 1 (the non-rigid step's data) and Task 3; |
221 | - Task 1 (the non-rigid step's data) and Task 3; |
| 198 | - Task 4 (the non-rigid path and its tests); |
222 | - Task 4, or a task after `foldc` if the path needs its data (it became Task 7b); |
| 199 | - Task 7 (how `foldc` produces a non-rigid step); |
223 | - Task 7 (how `foldc` produces a non-rigid step); |
| 200 | - Task 8 (the bound's test for flagged steps); |
224 | - Task 8 (the bound's test for flagged steps); |
| 201 | - Task 15 (which steps are flagged); |
225 | - Task 15 (which steps are flagged); |
| 202 | - `CLAUDE.md`. |
226 | - `CLAUDE.md`. |
| 203 | - If a v1 step is neither rigid nor within a bound worth promising: **stop**. The author decides, as after Task 0. |
227 | - If a v1 step is neither rigid nor within a bound worth promising: **stop**. The author decides, as after Task 0. |
| 204 | |
228 | |
| |
229 | Applied (decision 0002): the petal fold is rigid; reverse folds and sinks use open, pop, close, which is Task 7b, with the flap opened to 30° from flat by default and a 10% strain bound; the sampan's and the masu's last steps are classified when authored (Task 15). |
| |
230 | |
| 205 | This is a measurement, not TDD. |
231 | This is a measurement, not TDD. |
| 206 | |
232 | |
| 207 | - [ ] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources** |
233 | - [x] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources** |
| 208 | - [ ] **Step 2: Add cases 6–9 to the spike** |
234 | - [x] **Step 2: Add cases 6–9 to the spike** |
| 209 | - [ ] **Step 3: Run and record** |
235 | - [x] **Step 3: Run and record** |
| 210 | |
236 | |
| 211 | Run: `swift run -c release --package-path spikes/interpolation` |
237 | Run: `swift run -c release --package-path spikes/interpolation` |
| 212 | |
238 | |
| 213 | - [ ] **Step 4: Write the decision record and apply the exit criteria** |
239 | - [x] **Step 4: Write the decision record and apply the exit criteria** |
| 214 | - [ ] **Step 5: Commit** |
240 | - [x] **Step 5: Commit** |
| 215 | |
241 | |
| 216 | ```bash |
242 | ```bash |
| 217 | git add spikes docs |
243 | git add spikes docs |
| @@ -241,7 +267,8 @@ git commit -m "Non-rigid steps: model, bound and the remaining coupled steps" |
| 241 | - `enum TurnOverAxis: String, Codable, Sendable { case vertical, horizontal }` |
267 | - `enum TurnOverAxis: String, Codable, Sendable { case vertical, horizontal }` |
| 242 | - `struct AxisRecord: Codable, Equatable, Sendable { let edge: Int; let movingFaces: [Int]; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: [Double]?; let angles: [Double]? }` — `parent` is the index, in the same step's `axes`, of the axis whose motion carries this one; `window` is `[t0, t1]`, default `[0, 1]`; `angles` is a solved curve, the fold angle at 257 evenly spaced points of the window, absent for a linear axis |
268 | - `struct AxisRecord: Codable, Equatable, Sendable { let edge: Int; let movingFaces: [Int]; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: [Double]?; let angles: [Double]? }` — `parent` is the index, in the same step's `axes`, of the axis whose motion carries this one; `window` is `[t0, t1]`, default `[0, 1]`; `angles` is a solved curve, the fold angle at 257 evenly spaced points of the window, absent for a linear axis |
| 243 | - `struct Viewpoint: Codable, Equatable, Sendable { let eye: SIMD3<Double>; let up: SIMD3<Double> }` — `eye` is the unit direction toward the viewer |
269 | - `struct Viewpoint: Codable, Equatable, Sendable { let eye: SIMD3<Double>; let up: SIMD3<Double> }` — `eye` is the unit direction toward the viewer |
| 244 | - `struct StepRecord: Codable, Equatable, Sendable { let kind: StepKind; let technique: StepTechnique; let instruction: String?; let axes: [AxisRecord]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let viewpoint: Viewpoint }` — `nonRigid` decodes to `false` when absent; Task 0b adds the data a non-rigid step carries |
270 | - `struct StepRecord: Codable, Equatable, Sendable { let kind: StepKind; let technique: StepTechnique; let instruction: String?; let axes: [AxisRecord]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let pop: PopRecord?; let viewpoint: Viewpoint }` — `nonRigid` decodes to `false` when absent; a non-rigid step's `axes` still list its creases with their start and end angles, for the diagram and the validator, and its motion is `pop` |
| |
271 | - `struct PopRecord: Codable, Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: [Double]; let openAxes: [AxisRecord]; let popped: [SIMD3<Double>]; let closeAxes: [AxisRecord] }` — decision 0002's open, pop, close: `spine` is the flap's spine edges; `openAngle` the spine's fold angle when open (default 30); `phases` the two boundaries on *t* (default `[1/3, 2/3]`); `openAxes` open the flap on `[0, phases[0]]`; `popped` is every vertex's position after the pop; `closeAxes`, relative to `popped`, close it on `[phases[1], 1]` |
| 245 | - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3<Double>]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }` |
272 | - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3<Double>]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }` |
| 246 | - `struct FoldFile: Codable, Sendable { var fileSpec: Double; var fileCreator: String?; var fileTitle: String?; var fileAuthor: String?; var fileClasses: [String]; var edgesVertices: [[Int]]; var facesVertices: [[Int]]; var edgesFirstCreasedAtStep: [Int?]; var frames: [FoldFrame] }` — `frames[0]` is the key frame, `frames[n]` is frame n |
273 | - `struct FoldFile: Codable, Sendable { var fileSpec: Double; var fileCreator: String?; var fileTitle: String?; var fileAuthor: String?; var fileClasses: [String]; var edgesVertices: [[Int]]; var facesVertices: [[Int]]; var edgesFirstCreasedAtStep: [Int?]; var frames: [FoldFrame] }` — `frames[0]` is the key frame, `frames[n]` is frame n |
| 247 | - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1` |
274 | - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1` |
| @@ -308,6 +335,14 @@ Package manifest: swift-tools-version 6.2, platforms `.iOS(.v26)`, `.macOS(.v26) |
| 308 | #expect(axis.angles == [0, 90, 180]) |
335 | #expect(axis.angles == [0, 90, 180]) |
| 309 | } |
336 | } |
| 310 | |
337 | |
| |
338 | @Test func decodesAPopRecord() throws { |
| |
339 | let json = #"{"spine": [0, 1], "openAngle": 30, "phases": [0.3333333333333333, 0.6666666666666666],"# + |
| |
340 | #" "openAxes": [], "popped": [[0, 0, 0], [1, 0, 0]], "closeAxes": []}"# |
| |
341 | let pop = try JSONDecoder().decode(PopRecord.self, from: Data(json.utf8)) |
| |
342 | #expect(pop.openAngle == 30) |
| |
343 | #expect(pop.popped.count == 2) |
| |
344 | } |
| |
345 | |
| 311 | @Test func windowsDecodeOnAStaggeredStep() throws { |
346 | @Test func windowsDecodeOnAStaggeredStep() throws { |
| 312 | let step = try FoldFile(contentsOf: fixture("letter-staggered.fold")).frames[1].step |
347 | let step = try FoldFile(contentsOf: fixture("letter-staggered.fold")).frames[1].step |
| 313 | #expect(step?.axes.map(\.window) == [[0, 0.5], [0.5, 1]]) |
348 | #expect(step?.axes.map(\.window) == [[0, 0.5], [0.5, 1]]) |
| @@ -381,7 +416,7 @@ git commit -m "FOLD decoding with krz extension keys and synthetic fixtures" |
| 381 | - `func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>]` |
416 | - `func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>]` |
| 382 | - `func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(below: Int, above: Int)]` — each triple as "above" along a canonical normal of the two faces' common plane (the one whose first nonzero component is positive) |
417 | - `func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3<Double>]) -> [(below: Int, above: Int)]` — each triple as "above" along a canonical normal of the two faces' common plane (the one whose first nonzero component is positive) |
| 383 | |
418 | |
| 384 | This task owns Review Focus item 2. Isometry tolerance is 1e-6 on edge length between consecutive frames. The validator checks shipped models; it is not run on crease patterns. |
419 | This task owns Review Focus item 2. Isometry tolerance is 1e-6 × the sheet's longer side on edge length between consecutive frames. The validator checks shipped models; it is not run on crease patterns. |
| 385 | |
420 | |
| 386 | The interpenetration checker (Task 6) finds faces that collide in motion. It cannot find an ordering that is impossible but collision-free — a flap drawn on the wrong side of a stack moves through exactly the same coordinates. The three **layer-order consistency** rules here find those, in every stack of coincident faces of every frame, and they are what catches a wrong guess from `foldc`: |
421 | The interpenetration checker (Task 6) finds faces that collide in motion. It cannot find an ordering that is impossible but collision-free — a flap drawn on the wrong side of a stack moves through exactly the same coordinates. The three **layer-order consistency** rules here find those, in every stack of coincident faces of every frame, and they are what catches a wrong guess from `foldc`: |
| 387 | |
422 | |
| @@ -523,10 +558,11 @@ git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold o |
| 523 | - Produces: |
558 | - Produces: |
| 524 | - `struct FoldAxis: Equatable, Sendable { let edge: Int; let origin: SIMD3<Double>; let direction: SIMD3<Double>; let movingFaces: Set<Int>; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: ClosedRange<Double>; let curve: [Double]? }` |
559 | - `struct FoldAxis: Equatable, Sendable { let edge: Int; let origin: SIMD3<Double>; let direction: SIMD3<Double>; let movingFaces: Set<Int>; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: ClosedRange<Double>; let curve: [Double]? }` |
| 525 | - `func (FoldAxis).angle(at t: Double, kind: StepKind) -> Double` |
560 | - `func (FoldAxis).angle(at t: Double, kind: StepKind) -> Double` |
| 526 | - `struct FoldStep: Equatable, Sendable { let index: Int; let kind: StepKind; let technique: StepTechnique; let instruction: String; let axes: [FoldAxis]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let viewpoint: Viewpoint }` — `axes` is ordered so every parent comes before its children |
561 | - `struct FoldStep: Equatable, Sendable { let index: Int; let kind: StepKind; let technique: StepTechnique; let instruction: String; let axes: [FoldAxis]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let pop: Pop?; let viewpoint: Viewpoint }` — `axes` is ordered so every parent comes before its children |
| |
562 | - `struct Pop: Equatable, Sendable { let spine: [Int]; let openAngle: Double; let phases: ClosedRange<Double>; let openAxes: [FoldAxis]; let popped: [SIMD3<Double>]; let closeAxes: [FoldAxis] }` — `closeAxes`' origins and directions come from `popped`, not from frame `index − 1` |
| 527 | - `var (FoldStep).movingFaceUnion: Set<Int> { get }` |
563 | - `var (FoldStep).movingFaceUnion: Set<Int> { get }` |
| 528 | - `func readSteps(_ file: FoldFile) throws -> [FoldStep]` — `result[k].index == k + 1` |
564 | - `func readSteps(_ file: FoldFile) throws -> [FoldStep]` — `result[k].index == k + 1` |
| 529 | - `enum StepError: Error, Equatable, Sendable { case axisNotAnEdge(step: Int, edge: Int); case axisNotOnMovingSetBoundary(step: Int, edge: Int); case movingFacesOutOfRange(step: Int); case overlappingMovingSetsWithinAStep(step: Int); case rotateWithoutDegrees(step: Int); case turnOverWithoutAxis(step: Int); case foldAndUnfoldWithoutPeak(step: Int); case missingInstruction(step: Int); case axisParentCycle(step: Int); case axisWindowOutOfRange(step: Int); case curveTooShort(step: Int) }` |
565 | - `enum StepError: Error, Equatable, Sendable { case axisNotAnEdge(step: Int, edge: Int); case axisNotOnMovingSetBoundary(step: Int, edge: Int); case movingFacesOutOfRange(step: Int); case overlappingMovingSetsWithinAStep(step: Int); case rotateWithoutDegrees(step: Int); case turnOverWithoutAxis(step: Int); case foldAndUnfoldWithoutPeak(step: Int); case missingInstruction(step: Int); case axisParentCycle(step: Int); case axisWindowOutOfRange(step: Int); case curveTooShort(step: Int); case nonRigidWithoutPop(step: Int); case popPhasesOutOfOrder(step: Int) }` |
| 530 | |
566 | |
| 531 | `readSteps` **reads** the authored `krz:step`; it does not infer axes or moving sets from a frame diff. Deriving a multi-axis decomposition has genuine ambiguities — which side moved, whether a reorientation is a fold, how to partition simultaneous axes — and the author already knows the answer. This task and Task 4 own Review Focus item 1, in the form Task 0 settles. |
567 | `readSteps` **reads** the authored `krz:step`; it does not infer axes or moving sets from a frame diff. Deriving a multi-axis decomposition has genuine ambiguities — which side moved, whether a reorientation is a fold, how to partition simultaneous axes — and the author already knows the answer. This task and Task 4 own Review Focus item 1, in the form Task 0 settles. |
| 532 | |
568 | |
| @@ -534,7 +570,7 @@ git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold o |
| 534 | |
570 | |
| 535 | For an axis with a parent, `origin` and `direction` are still in frame `index − 1`'s coordinates: Task 4 applies the axis's own rotation first and its ancestors' after, so the parent's motion carries it. |
571 | For an axis with a parent, `origin` and `direction` are still in frame `index − 1`'s coordinates: Task 4 applies the axis's own rotation first and its ancestors' after, so the parent's motion carries it. |
| 536 | |
572 | |
| 537 | `degreeFourVertex()` builds decision 0001's case 3 in code, since its curves cannot be typed: a 2×2 sheet with creases from the centre at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), and one `fold` step from flat to flat-folded. The face between the 140° and 260° creases holds still. Its axes are the 140° crease, linear 0 → 180; the 260° crease, a curve; and the 0° crease, carried by the 260° axis, linear 0 → 180. The 60° crease is off the tree. The curve is the closed form for a flat-foldable degree-4 vertex, `ρ = 2·atan(k·tan(90°·u))` with `k = cos 70° / cos 10°`, sampled at 257 points; the 60° crease follows as `−ρ`. Frame 1 is the flat-folded sheet. `degreeFourExactAngle(_:at:)` evaluates the closed form directly. |
573 | `degreeFourVertex(linear:)` builds decision 0001's case 3 in code, since its curves cannot be typed: a 2×2 sheet with creases from the centre at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), and one `fold` step from flat to flat-folded. The face between the 140° and 260° creases holds still. Its axes are the 140° crease, linear 0 → 180; the 260° crease, a curve; and the 0° crease, carried by the 260° axis, linear 0 → 180. The 60° crease is off the tree. The curve is the closed form for a flat-foldable degree-4 vertex, `ρ = 2·atan(k·tan(90°·u))` with `k = cos 70° / cos 10°`, sampled at 257 points; the 60° crease follows as `−ρ`. Frame 1 is the flat-folded sheet. `degreeFourExactAngle(_:at:)` evaluates the closed form directly for any of the four creases. With `linear: true` the curves are replaced by straight lines, for Task 4's control test. |
| 538 | |
574 | |
| 539 | - [ ] **Step 1: Write the failing tests** |
575 | - [ ] **Step 1: Write the failing tests** |
| 540 | |
576 | |
| @@ -607,6 +643,12 @@ func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws { |
| 607 | #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6) |
643 | #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6) |
| 608 | } |
644 | } |
| 609 | |
645 | |
| |
646 | @Test func aNonRigidStepNeedsItsPop() { |
| |
647 | #expect(throws: StepError.nonRigidWithoutPop(step: 1)) { |
| |
648 | try readSteps(FoldFile(contentsOf: fixture("nonrigid-no-pop.fold"))) |
| |
649 | } |
| |
650 | } |
| |
651 | |
| 610 | @Test func rotateWithoutDegreesThrows() { |
652 | @Test func rotateWithoutDegreesThrows() { |
| 611 | #expect(throws: StepError.rotateWithoutDegrees(step: 3)) { |
653 | #expect(throws: StepError.rotateWithoutDegrees(step: 3)) { |
| 612 | try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold"))) |
654 | try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold"))) |
| @@ -647,7 +689,7 @@ git commit -m "Read authored fold steps, including multi-axis and reorientation |
| 647 | - Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` |
689 | - Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` |
| 648 | - Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift` |
690 | - Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift` |
| 649 | |
691 | |
| 650 | **Interfaces** (decision 0001; Task 0b adds the path for `nonRigid` steps): |
692 | **Interfaces** (decision 0001; rigid steps only — Task 7b adds the path for `nonRigid` steps, whose data only `foldc` can produce): |
| 651 | - Consumes: Task 1 and Task 3 types. |
693 | - Consumes: Task 1 and Task 3 types. |
| 652 | - Produces: |
694 | - Produces: |
| 653 | - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index` |
695 | - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index` |
| @@ -765,7 +807,7 @@ Expected: FAIL. |
| 765 | |
807 | |
| 766 | - [ ] **Step 3: Implement `positions(at:)`** |
808 | - [ ] **Step 3: Implement `positions(at:)`** |
| 767 | |
809 | |
| 768 | Each axis's own transform is the rotation about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, built with `simd_quatd(angle:axis:)` about the origin-shifted axis. A moving face's transform is its axis's own transform followed by its parent's full transform, and so on up the tree, so a carried axis moves with its parent. A vertex in no moving set is unchanged. A vertex shared by faces of different sets takes its position from the first face in `faces_vertices` order that contains it. `foldc`'s curves keep the copies within the isometry tolerance, and the catalogue test (Task 8) checks this. Reorientation steps rotate every vertex as described above. `degreeFourVertex(linear:)` gains a `linear` flag that replaces the curves with straight lines, for the control test. |
810 | Each axis's own transform is the rotation about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, built with `simd_quatd(angle:axis:)` about the origin-shifted axis. A moving face's transform is its axis's own transform followed by its parent's full transform, and so on up the tree, so a carried axis moves with its parent. A vertex in no moving set is unchanged. A vertex shared by faces of different sets takes its position from the first face in `faces_vertices` order that contains it. `foldc`'s curves keep the copies within the isometry tolerance, and the catalogue test (Task 8) checks this. Reorientation steps rotate every vertex as described above. |
| 769 | |
811 | |
| 770 | - [ ] **Step 4: Run tests to verify they pass** |
812 | - [ ] **Step 4: Run tests to verify they pass** |
| 771 | |
813 | |
| @@ -929,9 +971,9 @@ git commit -m "Near-coplanar clustering and view-relative layer order" |
| 929 | - Consumes: Task 1–5 types. |
971 | - Consumes: Task 1–5 types. |
| 930 | - Produces: |
972 | - Produces: |
| 931 | - `struct Intersection: Equatable, Sendable { let faceA: Int; let faceB: Int; let t: Double }` |
973 | - `struct Intersection: Equatable, Sendable { let faceA: Int; let faceB: Int; let t: Double }` |
| 932 | - `func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection]` — one result per intersecting pair, at the first sample `t = k / samples` where they intersect |
974 | - `func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection]` — one result per intersecting pair, at the first sample `t = k / samples` where they intersect. Task 7b adds an overload on the render mesh for non-rigid steps, whose faces bend |
| 933 | |
975 | |
| 934 | "No facets pass through each other" is a headline anti-goal, so it gets a mechanical check rather than an eye. Coplanar faces are excluded — overlap there is the layer order's business. Otherwise a pair interpenetrates when their intersection reaches the relative interior of both faces; contact along edges or at vertices, shared or merely coincident, does not count. Pairs that share a vertex or an edge are **not** skipped: a flap that swings through a layer it shares a corner with is the error this exists to catch, and skipping every pair that shares a vertex would miss it. This is the function Task 7 runs per step and Task 8's catalogue gate runs over every model. |
976 | "No facets pass through each other" is a headline anti-goal, so it gets a mechanical check rather than an eye. Coplanar faces are excluded — overlap there is the layer order's business. Coplanar means normals within 1e-6 rad and planes within 1e-6 × the sheet's size, so that faces landing on a stack to within the solver's tolerance count as landed. Otherwise a pair interpenetrates when their intersection reaches the relative interior of both faces; contact along edges or at vertices, shared or merely coincident, does not count. Pairs that share a vertex or an edge are **not** skipped: a flap that swings through a layer it shares a corner with is the error this exists to catch, and skipping every pair that shares a vertex would miss it. This is the function Task 7 runs per rigid step and Task 8's catalogue gate runs over every rigid step; non-rigid steps use Task 7b's mesh version. |
| 935 | |
977 | |
| 936 | - [ ] **Step 1: Write the failing tests** |
978 | - [ ] **Step 1: Write the failing tests** |
| 937 | |
979 | |
| @@ -1020,20 +1062,20 @@ git commit -m "Facet interpenetration checker" |
| 1020 | - Produces: |
1062 | - Produces: |
| 1021 | - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script |
1063 | - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script |
| 1022 | - `init (FoldScript).init(contentsOf url: URL) throws` |
1064 | - `init (FoldScript).init(contentsOf url: URL) throws` |
| 1023 | - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2<Double>]; let angles: [Double]?; let peakAngles: [Double]?; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let viewpoint: Viewpoint?; let faceOrders: [OrderOverride]?; let faceOrdersMidFold: [OrderOverride]?; let driver: CreaseRef?; let windows: [[Double]]? }` — `windows` pairs with `creases` |
1065 | - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2<Double>]; let angles: [Double]?; let peakAngles: [Double]?; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let viewpoint: Viewpoint?; let faceOrders: [OrderOverride]?; let faceOrdersMidFold: [OrderOverride]?; let driver: CreaseRef?; let windows: [[Double]]?; let spine: CreaseRef?; let openAngle: Double? }` — `windows` pairs with `creases`; `spine` and `openAngle` are for a reverse fold or sink (Task 7b) |
| 1024 | - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2<Double>, SIMD2<Double>); case edgeIndex(Int) }` |
1066 | - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2<Double>, SIMD2<Double>); case edgeIndex(Int) }` |
| 1025 | - `struct OrderOverride: Codable, Sendable { let above: SIMD2<Double>; let below: SIMD2<Double> }` — points in crease-pattern coordinates naming two faces, "above" as seen from the step's viewpoint |
1067 | - `struct OrderOverride: Codable, Sendable { let above: SIMD2<Double>; let below: SIMD2<Double> }` — points in crease-pattern coordinates naming two faces, "above" as seen from the step's viewpoint |
| 1026 | - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile` |
1068 | - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile` |
| 1027 | - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]` |
1069 | - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]` |
| 1028 | - `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]]` |
| 1029 | - `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) }` |
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) }` |
| 1030 | - `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 |
| 1031 | |
1073 | |
| 1032 | **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. |
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). |
| 1033 | |
1075 | |
| 1034 | Defaults: `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]`. |
1076 | Defaults: `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]`. |
| 1035 | |
1077 | |
| 1036 | **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. Each curve is then checked at four times that density, and its samples are doubled until the gap stays under 1e-6 × the sheet's size. A loop that does not close (the solver's gap stays above that) fails the step: the step has no rigid motion and needs `nonRigid` (Task 0b). |
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. |
| 1037 | |
1079 | |
| 1038 | Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it. |
1080 | Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it. |
| 1039 | |
1081 | |
| @@ -1087,10 +1129,11 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th |
| 1087 | // gets a curve, the 0° crease rides on it, the 60° crease closes the loop |
1129 | // gets a curve, the 0° crease rides on it, the 60° crease closes the loop |
| 1088 | let out = try compile(degreeFourScript(), pattern: degreeFourPattern()) |
1130 | let out = try compile(degreeFourScript(), pattern: degreeFourPattern()) |
| 1089 | let axes = try #require(out.frames[1].step?.axes) |
1131 | let axes = try #require(out.frames[1].step?.axes) |
| 1090 | #expect(axes.filter { $0.angles != nil }.count == 1) |
1132 | #expect(axes.contains { $0.angles != nil }) |
| 1091 | #expect(axes.contains { $0.parent != nil }) |
1133 | #expect(axes.contains { $0.parent != nil }) |
| 1092 | let curved = axes.first { $0.angles != nil }! |
1134 | for axis in axes where axis.angles != nil { |
| 1093 | #expect(abs(curved.angles![128] - degreeFourExactAngle(curved.edge, at: 0.5)) < 1e-6) |
1135 | #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6) |
| |
1136 | } |
| 1094 | } |
1137 | } |
| 1095 | |
1138 | |
| 1096 | @Test func anUnresolvedCreaseNamesItsStep() { |
1139 | @Test func anUnresolvedCreaseNamesItsStep() { |
| @@ -1137,6 +1180,147 @@ git commit -m "foldc: compile a fold script and crease pattern into a FOLD seque |
| 1137 | |
1180 | |
| 1138 | --- |
1181 | --- |
| 1139 | |
1182 | |
| |
1183 | ### Task 7b: Non-rigid steps — open, pop, close |
| |
1184 | |
| |
1185 | **Files:** |
| |
1186 | - Create: `Packages/FoldKit/Sources/Folding/RenderMesh.swift` |
| |
1187 | - Create: `Packages/FoldKit/Sources/Folding/Bending.swift` |
| |
1188 | - Modify: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` |
| |
1189 | - Modify: `Packages/FoldKit/Sources/Folding/Interpenetration.swift` |
| |
1190 | - Create: `Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift` |
| |
1191 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-cp.fold`, `reverse.foldscript` — decision 0001's case 4 flap: a 4×2 sheet, spine y = 1, reverse-fold creases from (2, 1) to (3, 0) and (3, 2); step 1 folds the flap in half on the spine, step 2 is an inside reverse fold naming the spine y = 1 |
| |
1192 | - Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift` — `tipIsBetweenBodyLayers(_:_:)` and `FoldScript.withOpenAngle(_:step:)` (see *Test helpers*) |
| |
1193 | - Test: `Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift` |
| |
1194 | |
| |
1195 | **Interfaces:** |
| |
1196 | - Consumes: Tasks 1–7. |
| |
1197 | - Produces: |
| |
1198 | - `struct RenderMesh: Sendable { init(file: FoldFile, spacing: Double); let vertices: [SIMD2<Double>]; let triangles: [(Int, Int, Int)]; let faceOf: [Int]; let meshVertexOf: [Int] }` — built as the spike builds it: the planar arrangement of frame 0's edges plus lines every `spacing` in x and in y, each resulting convex cell fanned into triangles. `faceOf` maps a triangle to its FOLD face, `meshVertexOf` a FOLD vertex to its mesh vertex. The FOLD topology is unchanged; the mesh is the renderer's |
| |
1199 | - `static func (RenderMesh).spacing(for file: FoldFile) -> Double` — frame 0's bounding box's longer side / 32 |
| |
1200 | - `let (FoldInterpolator).mesh: RenderMesh` — built at `init` with `RenderMesh.spacing(for:)`; for a non-rigid step the pop's least-squares matrix is factored once, at `init` |
| |
1201 | - `func (FoldInterpolator).meshPositions(at t: Double) -> [SIMD3<Double>]` — for a rigid step, each face's transform applied to its mesh vertices; for a non-rigid step, the three phases below. On a non-rigid step `positions(at:)` returns the mesh positions of the FOLD vertices |
| |
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 |
| |
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)` |
| |
1206 | |
| |
1207 | Decision 0002: an inside reverse fold has no rigid motion with the flap closed. Flagged steps move in three phases on *t*: |
| |
1208 | |
| |
1209 | 1. **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. |
| |
1210 | 2. **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. |
| |
1211 | 3. **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 | |
| |
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 | |
| |
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); |
| |
1217 | - builds `closeAxes` (from `popped` to the end frame, with the spine driven and the rest solved); |
| |
1218 | - measures the pop's strain on the step's render mesh, and fails the step above **10%**. |
| |
1219 | |
| |
1220 | Decision 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. |
| |
1221 | |
| |
1222 | - [ ] **Step 1: Write the failing tests** |
| |
1223 | |
| |
1224 | ```swift |
| |
1225 | @Test func aReverseFoldCompilesToANonRigidStep() throws { |
| |
1226 | let out = try compiled("reverse") |
| |
1227 | let step = try #require(out.frames[2].step) |
| |
1228 | #expect(step.nonRigid) |
| |
1229 | #expect(step.pop?.openAngle == 30) |
| |
1230 | #expect(step.technique == .insideReverse) |
| |
1231 | } |
| |
1232 | |
| |
1233 | @Test func aReverseFoldWithoutASpineIsRejected() { |
| |
1234 | #expect(throws: CompileError.missingSpine(step: 2)) { |
| |
1235 | try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withoutSpine(step: 2), |
| |
1236 | pattern: FoldFile(contentsOf: fixture("reverse-cp.fold"))) |
| |
1237 | } |
| |
1238 | } |
| |
1239 | |
| |
1240 | @Test func theOpenAndCloseLegsAreRigid() throws { |
| |
1241 | // checked on the FOLD edges, as rigid steps are; mesh slivers at creases make relative mesh strain noisy |
| |
1242 | let file = try compiled("reverse") |
| |
1243 | let step = try readSteps(file)[1] |
| |
1244 | let i = FoldInterpolator(file: file, step: step) |
| |
1245 | for n in 0...256 { |
| |
1246 | let t = Double(n) / 256 |
| |
1247 | guard t <= step.pop!.phases.lowerBound || t >= step.pop!.phases.upperBound else { continue } |
| |
1248 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)") |
| |
1249 | } |
| |
1250 | } |
| |
1251 | |
| |
1252 | @Test func thePopStaysWithinTheBound() throws { |
| |
1253 | let file = try compiled("reverse") |
| |
1254 | let step = try readSteps(file)[1] |
| |
1255 | let i = FoldInterpolator(file: file, step: step) |
| |
1256 | let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) |
| |
1257 | let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()! |
| |
1258 | #expect(worst <= 0.10) |
| |
1259 | } |
| |
1260 | |
| |
1261 | @Test func theStepEndsOnItsEndFrame() throws { |
| |
1262 | let file = try compiled("reverse") |
| |
1263 | let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) |
| |
1264 | #expect(zip(i.positions(at: 1), file.frames[2].verticesCoords).allSatisfy { simd_distance($0, $1) < 1e-9 }) |
| |
1265 | } |
| |
1266 | |
| |
1267 | @Test func nothingPassesThroughAnything() throws { |
| |
1268 | let file = try compiled("reverse") |
| |
1269 | let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) |
| |
1270 | #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty) |
| |
1271 | } |
| |
1272 | |
| |
1273 | @Test func theTipLandsBetweenTheFlapsLayers() throws { |
| |
1274 | // 97% of the way through the closing phase, a point of the tip lies between the body's two layers |
| |
1275 | let file = try compiled("reverse") |
| |
1276 | let step = try readSteps(file)[1] |
| |
1277 | let i = FoldInterpolator(file: file, step: step) |
| |
1278 | let upper = step.pop!.phases.upperBound |
| |
1279 | #expect(tipIsBetweenBodyLayers(i.positions(at: upper + 0.97 * (1 - upper)), file)) |
| |
1280 | } |
| |
1281 | |
| |
1282 | @Test func aFlapOpenedOnlyTo60DegreesIsRejected() { |
| |
1283 | #expect { |
| |
1284 | try compile(FoldScript(contentsOf: fixture("reverse.foldscript")).withOpenAngle(60, step: 2), |
| |
1285 | pattern: FoldFile(contentsOf: fixture("reverse-cp.fold"))) |
| |
1286 | } throws: { if case CompileError.popTooStrained(step: 2, _) = $0 { true } else { false } } |
| |
1287 | } |
| |
1288 | |
| |
1289 | @Test func thePopFitsInAFrameBudget() throws { |
| |
1290 | let file = try compiled("reverse") |
| |
1291 | let step = try readSteps(file)[1] |
| |
1292 | let i = FoldInterpolator(file: file, step: step) |
| |
1293 | let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) |
| |
1294 | let elapsed = ContinuousClock().measure { |
| |
1295 | for n in 0..<100 { _ = i.meshPositions(at: lo + Double(n) / 100 * (hi - lo)) } |
| |
1296 | } |
| |
1297 | #expect(elapsed / 100 < .milliseconds(4)) |
| |
1298 | } |
| |
1299 | ``` |
| |
1300 | |
| |
1301 | - [ ] **Step 2: Run tests to verify they fail** |
| |
1302 | |
| |
1303 | Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests` |
| |
1304 | Expected: FAIL. |
| |
1305 | |
| |
1306 | - [ ] **Step 3: Implement `RenderMesh`, the pop in `FoldInterpolator`, `meshInterpenetrations`, and `compilePop`** |
| |
1307 | |
| |
1308 | `spikes/interpolation/Sources/Spike/Bending.swift` is the reference for the mesh and the pop; `main.swift`'s case 6 is the reference for building the popped pose and the closing branch. A dense Cholesky factor is fine at the spike's size (561 vertices); at a full model's 1/32 mesh use a sparse one, since the frame budget test runs per frame. |
| |
1309 | |
| |
1310 | - [ ] **Step 4: Run tests to verify they pass** |
| |
1311 | |
| |
1312 | Run: `swift test --package-path Packages/FoldKit --filter NonRigidTests` |
| |
1313 | Expected: PASS. |
| |
1314 | |
| |
1315 | - [ ] **Step 5: Commit** |
| |
1316 | |
| |
1317 | ```bash |
| |
1318 | git add Packages/FoldKit |
| |
1319 | git commit -m "Non-rigid steps: open, pop, close" |
| |
1320 | ``` |
| |
1321 | |
| |
1322 | --- |
| |
1323 | |
| 1140 | ### Task 8: `foldlint` and the model catalogue gate |
1324 | ### Task 8: `foldlint` and the model catalogue gate |
| 1141 | |
1325 | |
| 1142 | **Files:** |
1326 | **Files:** |
| @@ -1149,7 +1333,7 @@ git commit -m "foldc: compile a fold script and crease pattern into a FOLD seque |
| 1149 | - Test: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` |
1333 | - Test: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` |
| 1150 | |
1334 | |
| 1151 | **Interfaces:** |
1335 | **Interfaces:** |
| 1152 | - Consumes: Task 1–7. |
1336 | - Consumes: Tasks 1–7b. |
| 1153 | - Produces: |
1337 | - Produces: |
| 1154 | - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }` |
1338 | - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }` |
| 1155 | - `foldlint <path>...` — exits 0 when clean, 1 with one defect per line |
1339 | - `foldlint <path>...` — exits 0 when clean, 1 with one defect per line |
| @@ -1185,8 +1369,9 @@ Its crease pattern and `.foldscript` are committed next to the generated `.fold` |
| 1185 | } |
1369 | } |
| 1186 | |
1370 | |
| 1187 | @Test func noShippedModelInterpenetratesAtAnyStep() throws { |
1371 | @Test func noShippedModelInterpenetratesAtAnyStep() throws { |
| |
1372 | // non-rigid steps bend their faces; everyFlaggedStepStaysWithinTheBound checks them on the mesh |
| 1188 | for file in try ModelLibrary.all() { |
1373 | for file in try ModelLibrary.all() { |
| 1189 | for step in try readSteps(file) { |
1374 | for step in try readSteps(file) where !step.nonRigid { |
| 1190 | let i = FoldInterpolator(file: file, step: step) |
1375 | let i = FoldInterpolator(file: file, step: step) |
| 1191 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty, |
1376 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty, |
| 1192 | "\(file.fileTitle ?? "?") step \(step.index)") |
1377 | "\(file.fileTitle ?? "?") step \(step.index)") |
| @@ -1206,6 +1391,19 @@ Its crease pattern and `.foldscript` are committed next to the generated `.fold` |
| 1206 | } |
1391 | } |
| 1207 | } |
1392 | } |
| 1208 | |
1393 | |
| |
1394 | @Test func everyFlaggedStepStaysWithinTheBound() throws { |
| |
1395 | // decision 0002: 10% largest edge strain on the render mesh, and nothing passes through anything |
| |
1396 | for file in try ModelLibrary.all() { |
| |
1397 | for step in try readSteps(file) where step.nonRigid { |
| |
1398 | let i = FoldInterpolator(file: file, step: step) |
| |
1399 | let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound) |
| |
1400 | let worst = (0...128).map { strain(i.meshPositions(at: lo + Double($0) / 128 * (hi - lo)), mesh: i.mesh) }.max()! |
| |
1401 | #expect(worst <= 0.10, "\(file.fileTitle ?? "?") step \(step.index)") |
| |
1402 | #expect(meshInterpenetrations(i, samples: 64).filter { $0.t > 0.02 && $0.t < 0.98 }.isEmpty) |
| |
1403 | } |
| |
1404 | } |
| |
1405 | } |
| |
1406 | |
| 1209 | @Test func theCatalogueContainsTheCup() throws { |
1407 | @Test func theCatalogueContainsTheCup() throws { |
| 1210 | #expect(try ModelLibrary.names() == ["cup"]) |
1408 | #expect(try ModelLibrary.names() == ["cup"]) |
| 1211 | } |
1409 | } |
| @@ -1395,13 +1593,13 @@ git commit -m "Diagram generation with layer-aware edge occlusion" |
| 1395 | - Test: `Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift` |
1593 | - Test: `Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift` |
| 1396 | |
1594 | |
| 1397 | **Interfaces:** |
1595 | **Interfaces:** |
| 1398 | - Consumes: Task 1–5. |
1596 | - Consumes: Tasks 1–5 and 7b (`RenderMesh`). |
| 1399 | - Produces: |
1597 | - Produces: |
| 1400 | - `struct Camera: Sendable { var eye: SIMD3<Double>; var target: SIMD3<Double>; var up: SIMD3<Double>; var fieldOfView: Double }` — in `Folding`, not `Renderer`: it is plain `simd`, and Task 12's mapping in `Folding` needs it, while `Renderer` already depends on `Folding` |
1598 | - `struct Camera: Sendable { var eye: SIMD3<Double>; var target: SIMD3<Double>; var up: SIMD3<Double>; var fieldOfView: Double }` — in `Folding`, not `Renderer`: it is plain `simd`, and Task 12's mapping in `Folding` needs it, while `Renderer` already depends on `Folding` |
| 1401 | - `func (Camera).viewProjection(aspect: Double) -> simd_double4x4` — view and perspective projection combined, to clip space |
1599 | - `func (Camera).viewProjection(aspect: Double) -> simd_double4x4` — view and perspective projection combined, to clip space |
| 1402 | - `var (Camera).viewDirection: SIMD3<Double> { get }` — unit vector from `eye` toward `target` |
1600 | - `var (Camera).viewDirection: SIMD3<Double> { get }` — unit vector from `eye` toward `target` |
| 1403 | - `final class PaperRenderer { init(device: MTLDevice) throws }` |
1601 | - `final class PaperRenderer { init(device: MTLDevice) throws }` |
| 1404 | - `func (PaperRenderer).render(positions: [SIMD3<Double>], faces: [[Int]], clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4<Float>]? = nil, into: MTLTexture) throws` — `faceColours`, when given, draws face *i* in one flat unlit colour on both sides; it exists so tests can tell faces apart |
1602 | - `func (PaperRenderer).render(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera, faceColours: [SIMD4<Float>]? = nil, into: MTLTexture) throws` — draws the render mesh (Task 7b), so a bending face in a non-rigid step draws as it bends; `positions` are mesh positions, clusters are of FOLD faces and each triangle draws with its face. `faceColours`, when given, draws FOLD face *i* in one flat unlit colour on both sides; it exists so tests can tell faces apart |
| 1405 | |
1603 | |
| 1406 | Depth handling is **hybrid**. `faceOrders` is defined only for faces that overlap geometrically, so it says nothing about the facets separated in space that make up most of a folded model, and depth testing off everywhere would be wrong for them: |
1604 | Depth handling is **hybrid**. `faceOrders` is defined only for faces that overlap geometrically, so it says nothing about the facets separated in space that make up most of a folded model, and depth testing off everywhere would be wrong for them: |
| 1407 | |
1605 | |
| @@ -1415,7 +1613,7 @@ SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4. |
| 1415 | |
1613 | |
| 1416 | - [ ] **Step 1: Write the failing tests** |
1614 | - [ ] **Step 1: Write the failing tests** |
| 1417 | |
1615 | |
| 1418 | The geometry helpers return positions, faces and normals; `red`, `green` and `blue` are the debug colours of faces 0, 1 and 2. `stackedCoplanarSquares()` is two coincident unit squares facing +z with face 0 above face 1 (`[[0, 1, 1]]`). |
1616 | The geometry helpers return positions, faces, normals and a `RenderMesh` over those faces; `red`, `green` and `blue` are the debug colours of faces 0, 1 and 2. `stackedCoplanarSquares()` is two coincident unit squares facing +z with face 0 above face 1 (`[[0, 1, 1]]`). |
| 1419 | |
1617 | |
| 1420 | ```swift |
1618 | ```swift |
| 1421 | @Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() { |
1619 | @Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() { |
| @@ -1484,7 +1682,7 @@ Expected: FAIL. |
| 1484 | |
1682 | |
| 1485 | - [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders** |
1683 | - [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders** |
| 1486 | |
1684 | |
| 1487 | One vertex and one fragment function. Triangulate each face as a fan (faces are convex). Flat shading with one directional term, or the debug colour unlit. Two depth-stencil states — test on with writes off for a cluster's colour pass, test and write on for its depth pass — and a pipeline variant with colour writes masked off for the depth pass. |
1685 | One vertex and one fragment function. Draw the render mesh's triangles, grouped by FOLD face for clusters. Flat shading with one directional term, or the debug colour unlit. Two depth-stencil states — test on with writes off for a cluster's colour pass, test and write on for its depth pass — and a pipeline variant with colour writes masked off for the depth pass. |
| 1488 | |
1686 | |
| 1489 | - [ ] **Step 4: Run tests to verify they pass** |
1687 | - [ ] **Step 4: Run tests to verify they pass** |
| 1490 | |
1688 | |
| @@ -1513,12 +1711,12 @@ git commit -m "Metal paper renderer with hybrid depth and cluster ordering" |
| 1513 | - Test: `App/UITests/StepNavigationTests.swift` |
1711 | - Test: `App/UITests/StepNavigationTests.swift` |
| 1514 | |
1712 | |
| 1515 | **Interfaces:** |
1713 | **Interfaces:** |
| 1516 | - Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator`, `LayerOrder`, `buildDiagram`, `PaperRenderer`. |
1714 | - Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator` (with `mesh` and `meshPositions(at:)`), `RenderMesh`, `LayerOrder`, `buildDiagram`, `PaperRenderer`, `Camera`. |
| 1517 | - Produces: |
1715 | - Produces: |
| 1518 | - `struct ModelListView: View` |
1716 | - `struct ModelListView: View` |
| 1519 | - `struct StepView: View` — `init(model: FoldFile, step: Int)`, step counted from 1 |
1717 | - `struct StepView: View` — `init(model: FoldFile, step: Int)`, step counted from 1 |
| 1520 | - `struct DiagramCanvas: View` — `init(diagram: Diagram, style: DiagramStyle)` |
1718 | - `struct DiagramCanvas: View` — `init(diagram: Diagram, style: DiagramStyle)` |
| 1521 | - `struct PaperView: View` — `init(positions: [SIMD3<Double>], faces: [[Int]], clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI |
1719 | - `struct PaperView: View` — `init(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI; positions come from `FoldInterpolator.meshPositions(at:)` and the mesh from `FoldInterpolator.mesh` |
| 1522 | |
1720 | |
| 1523 | `project.yml` mirrors `krz/moonrise/App/project.yml`. The `.xcodeproj` is generated and ignored by git, as in moonrise: `xcodegen generate --spec App/project.yml`. On iPad the diagram and the model sit side by side; on iPhone they swap. The diagram's caption is the step's `instruction`. |
1721 | `project.yml` mirrors `krz/moonrise/App/project.yml`. The `.xcodeproj` is generated and ignored by git, as in moonrise: `xcodegen generate --spec App/project.yml`. On iPad the diagram and the model sit side by side; on iPhone they swap. The diagram's caption is the step's `instruction`. |
| 1524 | |
1722 | |
| @@ -1577,7 +1775,7 @@ git commit -m "App shell, model list and step layout" |
| 1577 | - Test: `App/UITests/FoldGestureTests.swift` |
1775 | - Test: `App/UITests/FoldGestureTests.swift` |
| 1578 | |
1776 | |
| 1579 | **Interfaces:** |
1777 | **Interfaces:** |
| 1580 | - Consumes: Task 3, 4 types; `Camera` (in `Folding`) from Task 10. |
1778 | - Consumes: Task 3, 4 and 7b types; `Camera` (in `Folding`) from Task 10. |
| 1581 | - Produces: |
1779 | - Produces: |
| 1582 | - `struct FoldParameterMapping: Sendable { init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) }` |
1780 | - `struct FoldParameterMapping: Sendable { init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) }` |
| 1583 | - `func (FoldParameterMapping).parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double` — clamped to 0...1 |
1781 | - `func (FoldParameterMapping).parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double` — clamped to 0...1 |
| @@ -1586,7 +1784,7 @@ git commit -m "App shell, model list and step layout" |
| 1586 | |
1784 | |
| 1587 | This task owns Review Focus item 4. |
1785 | This task owns Review Focus item 4. |
| 1588 | |
1786 | |
| 1589 | The finger drives the facet, not an abstract slider: the parameter is the point on the centroid's screen path nearest the centroid's position when grabbed plus the drag's translation, searched outward from `current` so the parameter cannot jump to a distant part of the path. A linear mapping onto the chord would leave the facet trailing the finger by up to a fifth of the throw on a 180° fold, because the centroid's screen speed is not constant. When the path is degenerate, fall back to vertical drag over a fixed 160-point throw so sensitivity stays bounded. For `foldAndUnfold`, search the outbound half (`t` 0...0.5) until the parameter reaches 0.5, then the return half (0.5...1). |
1787 | The finger drives the facet, not an abstract slider: the parameter is the point on the centroid's screen path nearest the centroid's position when grabbed plus the drag's translation, searched outward from `current` so the parameter cannot jump to a distant part of the path. A linear mapping onto the chord would leave the facet trailing the finger by up to a fifth of the throw on a 180° fold, because the centroid's screen speed is not constant. When the path is degenerate, fall back to vertical drag over a fixed 160-point throw so sensitivity stays bounded. For `foldAndUnfold`, search the outbound half (`t` 0...0.5) until the parameter reaches 0.5, then the return half (0.5...1). A non-rigid step's path doubles back the same way. It follows the centroid of the faces beyond the reverse creases through open, pop and close, and is searched one phase at a time, in order: the parameter enters a phase only once it has reached the end of the one before. |
| 1590 | |
1788 | |
| 1591 | - [ ] **Step 1: Write the failing tests** |
1789 | - [ ] **Step 1: Write the failing tests** |
| 1592 | |
1790 | |
| @@ -1626,6 +1824,20 @@ The finger drives the facet, not an abstract slider: the parameter is the point |
| 1626 | #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2) |
1824 | #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2) |
| 1627 | } |
1825 | } |
| 1628 | |
1826 | |
| |
1827 | @Test func aNonRigidStepIsDraggedPhaseByPhase() throws { |
| |
1828 | // following the path's own samples in order reaches t = 1 without ever going back |
| |
1829 | let m = try FoldParameterMapping(file: compiled("reverse"), step: readSteps(compiled("reverse"))[1], |
| |
1830 | camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4), |
| |
1831 | viewportSize: SIMD2(800, 600)) |
| |
1832 | var t = 0.0 |
| |
1833 | for p in m.path.dropFirst() { |
| |
1834 | let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) |
| |
1835 | #expect(next >= t - 1e-9) |
| |
1836 | t = next |
| |
1837 | } |
| |
1838 | #expect(t > 0.99) |
| |
1839 | } |
| |
1840 | |
| 1629 | @Test func foldAndUnfoldGoesOutThenBack() throws { |
1841 | @Test func foldAndUnfoldGoesOutThenBack() throws { |
| 1630 | let m = try mapping("quarters.fold", step: 1) |
1842 | let m = try mapping("quarters.fold", step: 1) |
| 1631 | let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0) |
1843 | let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0) |
| @@ -1847,7 +2059,7 @@ Authoring, not engineering: three crease patterns, three scripts, and a correcti |
| 1847 | |
2059 | |
| 1848 | The 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. |
2060 | The 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. |
| 1849 | |
2061 | |
| 1850 | Each `docs/authoring/*.md` records the crease pattern's provenance, which guessed layer orders had to be overridden and why, which steps use a coupled-step model from Task 0, and that the model regenerates from its script. |
2062 | Each `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. |
| 1851 | |
2063 | |
| 1852 | - [ ] **Step 1: Write the failing tests** |
2064 | - [ ] **Step 1: Write the failing tests** |
| 1853 | |
2065 | |
| @@ -1876,6 +2088,17 @@ Each `docs/authoring/*.md` records the crease pattern's provenance, which guesse |
| 1876 | } |
2088 | } |
| 1877 | } |
2089 | } |
| 1878 | |
2090 | |
| |
2091 | @Test func onlyTheCranesReverseFoldsAreFlagged() throws { |
| |
2092 | // decision 0002: the neck, tail and head reverse folds; nothing else, unless the |
| |
2093 | // sampan's or the masu's last step was flagged by a later decision |
| |
2094 | let crane = try readSteps(ModelLibrary.model(named: "crane")) |
| |
2095 | #expect(crane.filter(\.nonRigid).count == 3) |
| |
2096 | #expect(crane.filter(\.nonRigid).allSatisfy { $0.technique == .insideReverse }) |
| |
2097 | for name in ["cup", "box", "sampan"] { |
| |
2098 | #expect(try readSteps(ModelLibrary.model(named: name)).allSatisfy { !$0.nonRigid }, "\(name)") |
| |
2099 | } |
| |
2100 | } |
| |
2101 | |
| 1879 | @Test func everyModelHasAnAuthoringRecord() throws { |
2102 | @Test func everyModelHasAnAuthoringRecord() throws { |
| 1880 | for name in try ModelLibrary.names() { |
2103 | for name in try ModelLibrary.names() { |
| 1881 | #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path)) |
2104 | #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path)) |
| @@ -1892,7 +2115,7 @@ Expected: FAIL — only the cup is in the catalogue. |
| 1892 | |
2115 | |
| 1893 | - [ ] **Step 3: Author the three models** |
2116 | - [ ] **Step 3: Author the three models** |
| 1894 | |
2117 | |
| 1895 | Box and sampan first, then the crane. Neither is shallow: the masu's wall-raising and the sampan's final turn inside out are coupled 3D steps, classified by Task 0b as rigid or flagged. The crane's inside reverse folds (neck, tail, head) are flagged `nonRigid` and use Task 0b's model; its petal folds use whatever 0b found. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly. |
2118 | Box and sampan first, then the crane. Neither is shallow: the masu's wall-raising and the sampan's final turn inside out are coupled 3D steps, classified when authored (decision 0002). The classification uses `foldc`'s closure test, the interpenetration check, the validator's layer rules and a look in the app; closure alone can succeed on a branch with the wrong layering. Classify the crane's preliminary base the same way: fold and unfold its diagonals and midlines, then collapse it as one step from the pre-creased square, rather than through squash folds, which have the reverse fold's structure. A step that closes is rigid. One that does not, and is not a reverse fold or sink, stops compilation with `noRigidMotion`. Then stop and ask the author: open, pop, close needs a spine to open on, and an inversion has none. The crane's petal folds are rigid with solved curves (decision 0002, case 7). Its inside reverse folds (neck, tail, head) name their `spine` and use open, pop, close at the default 30°; if one exceeds the 10% bound, its `openAngle` is lowered in the script and the record says why. The bound was measured on a two-layer flap only; the crane's flaps are narrower and several layers deep, so record each flagged step's measured strain, and if opening a flap to its `openAngle` disturbs earlier layers or no `openAngle` meets the bound, stop for a decision. The bird base's crease pattern is the one decision 0002 read from Origami Simulator's flat crane; record that provenance in `docs/authoring/crane.md`. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly. |
| 1896 | |
2119 | |
| 1897 | - [ ] **Step 4: Run tests to verify they pass** |
2120 | - [ ] **Step 4: Run tests to verify they pass** |
| 1898 | |
2121 | |