| @@ -0,0 +1,1781 @@ |
| 1 | # Fold Implementation Plan |
| 2 | |
| 3 | > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| 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. |
| 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; how coupled multi-axis steps move is decided by measurement in Task 0 before anything encodes it. 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 | |
| 9 | **Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app. |
| 10 | |
| 11 | **Spec:** `docs/superpowers/specs/2026-10-19-fold-design.md` |
| 12 | |
| 13 | ## Global Constraints |
| 14 | |
| 15 | - iOS 26 deployment target; Swift 6 language mode. |
| 16 | - `TARGETED_DEVICE_FAMILY = "1,2"`; `PRODUCT_BUNDLE_IDENTIFIER = sh.krz.fold`; `DEVELOPMENT_TEAM = ZCNAX3VL9D`; `bundleIdPrefix: sh.krz`. |
| 17 | - `FoldKit` targets must not import UIKit or SwiftUI. `Renderer` may import Metal and MetalKit. `foldc` and `foldlint` are macOS executables and never ship in the app. |
| 18 | - Models are FOLD 1.2 files (Demaine, Ku and Lang, 2016; `github.com/edemaine/fold`). Standard keys used: `vertices_coords`, `edges_vertices`, `edges_assignment`, `edges_foldAngle`, `faces_vertices`, `faceOrders`, `file_frames`, `frame_parent`, `frame_inherit`, `file_spec`, `file_creator`, `file_classes`, `file_title`, `file_author`. |
| 19 | - `edges_assignment` codes: `B` boundary, `M` mountain, `V` valley, `F` flat, `U` unassigned. `C` and `J` are rejected. |
| 20 | - `edges_foldAngle` is degrees in −180...180, positive for valley, negative for mountain, 0 for `F`, `U` and `B`. |
| 21 | - `faceOrders` triples are `[f, g, s]`; `s = +1` means `f` is above `g` **on the side `g`'s normal points toward**, so the sign is evaluated against the current view direction, not absolutely, and two triples can only be compared after normalising each by its `g`'s folded-state normal. Cycles (after normalising) are rejected. |
| 22 | - Faces are convex. FOLD's alternative, splitting faces with `J` edges, is not supported. A crease that ends inside the sheet (a pinch or partial crease) leaves a nonconvex face around its end; split that face with a **subdivision edge** — assigned `F`, flat in every frame, `edges_krz:firstCreasedAtStep` null, never drawn. |
| 23 | - Extension keys: `edges_krz:firstCreasedAtStep` (key frame, inherited), `krz:step` (frames 1…N), `krz:faceOrders_midFold` (frames 1…N). |
| 24 | - **Step numbering.** Frame 0 is the key frame (the unfolded sheet); `file_frames[i]` is frame `i + 1`. Step n, counting from 1, takes frame n − 1 to frame n and is recorded in frame n's `krz:step`. Every index called a step — in the format, the validator's defects, `FoldStep.index`, the UI — is this n. Defects about one frame's state say `frame:`; defects about a transition or a step record say `step:`; frame n and step n share the number. |
| 25 | - Every frame in `file_frames` carries `frame_parent: 0` and `frame_inherit: true`, and never overrides `edges_vertices` or `faces_vertices`. |
| 26 | - **One topology across every frame.** Enforced by the decoder and the validator. |
| 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. |
| 29 | - Paper is rigid flat facets hinged at straight creases. No bending, stiffness, self-collision response or crumpling. |
| 30 | - Layer order is authored, never computed. Corrections to the compiler's guess live in the fold script. |
| 31 | - v1 ships **four** traditional models: the cup, the crane, the boat and the box (the masu). Every `file_author` is exactly `"Traditional"`, enforced by the validator. |
| 32 | - 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 | - The **cup is compiled first**, the crane last. Before the cup exists, tests use the synthetic fixtures below; model-level assertions live in Tasks 8 and 15. |
| 34 | - The app never advances the fold parameter on its own. |
| 35 | - No network calls. No analytics. No accounts. |
| 36 | - Ships on the App Store: privacy manifest, screenshots, and every screen passing Xcode's accessibility audit at the default and largest text size. |
| 37 | - Work lands through gitbay merge requests, one per batch of tasks; see *Setup*. |
| 38 | |
| 39 | ## Review Focus |
| 40 | |
| 41 | 1. **A step with several simultaneous axes.** A petal fold and a reverse fold move several facet sets about several creases at once on one shared parameter, and their faces form closed loops around interior vertices. The interpolation model for these is measured in Task 0 and implemented in Task 4; the axis records are read in Task 3. |
| 42 | 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 | 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 | 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 | 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 | 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 | |
| 48 | ## Synthetic fixtures |
| 49 | |
| 50 | The engine is tested before the compiler exists, so its fixtures are small sheets whose folded coordinates are integers or halves and can be typed exactly. They live in `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/`, alongside the `fixture(_:)` helper, in a target that only test targets depend on. Task 7 compiles a script for each of the model fixtures and checks the output matches the hand-written file, which pins the compiler's conventions to them. |
| 51 | |
| 52 | Every fixture except where noted has `file_author: "Traditional"`, an `instruction` on every step, and the default viewpoint `eye [0, 0, 1]`, `up [0, 1, 0]`. Vertex, edge and face numbering below is the numbering in the file. |
| 53 | |
| 54 | | Fixture | Sheet and creases | Steps | |
| 55 | |---|---|---| |
| 56 | | `square.fold` | unit square; v0–v3 with 2-element coords; edges e0–e3 all `B`; one face; no frames; no `faceOrders` key; `edges_krz:firstCreasedAtStep` four nulls | none | |
| 57 | | `half.fold` | 2×2; v0 (0,0), v1 (1,0), v2 (2,0), v3 (2,2), v4 (1,2), v5 (0,2); e0–e5 the boundary in that order, e6 = v1–v4; f0 = [v0,v1,v4,v5], f1 = [v1,v2,v3,v4] | 1: valley fold f1 over f0 about e6, 0 → 180. 2: `turnOver`, vertical. 3: `rotate` 90 | |
| 58 | | `mountain.fold` | as `half.fold` | 1: mountain fold f1 behind f0 about e6, 0 → −180 | |
| 59 | | `letter.fold` | 3×3; v0 (0,0), v1 (1,0), v2 (2,0), v3 (3,0), v4 (3,3), v5 (2,3), v6 (1,3), v7 (0,3); e0–e7 the boundary, e8 = v1–v6 (x = 1, valley), e9 = v2–v5 (x = 2, mountain); f0 = [v0,v1,v6,v7], f1 = [v1,v2,v5,v6], f2 = [v2,v3,v4,v5] | 1: one step, two axes: f0 valley folds in front of f1, f2 mountain folds behind it. The sets overlap in projection on opposite sides of f1, so frame 1 carries `krz:faceOrders_midFold` | |
| 60 | | `letter-sequential.fold` | as `letter.fold`, both creases valley | 1: f0 over f1. 2: f2 over both, `repeatOf: 1` | |
| 61 | | `quarters.fold` | 2×2; v0 (0,0), v1 (1,0), v2 (2,0), v3 (2,1), v4 (2,2), v5 (1,2), v6 (0,2), v7 (0,1), v8 (1,1); e0–e7 the boundary, e8 = v1–v8, e9 = v8–v5 (x = 1), e10 = v7–v8, e11 = v8–v3 (y = 1); f0 = [v0,v1,v8,v7], f1 = [v1,v2,v3,v8], f2 = [v8,v3,v4,v5], f3 = [v7,v8,v5,v6] | 1: `foldAndUnfold` on e8, moving f1 and f2, peak 180; frame 1 carries `krz:faceOrders_midFold` with the order at the peak (f1 on f0, f2 on f3). 2: valley fold the top half (f2, f3) down about e10. 3: valley fold the right half of both layers (f1, f2) over about e8 — e8 and e9 are now coincident; e9 is on the flipped layer and ends at −180, `M` | |
| 62 | | `occlusion.fold` | 4×4; v0 (0,0), v1 (2,0), v2 (2.5,0), v3 (4,0), v4 (4,4), v5 (2.5,4), v6 (0,4), v7 (0,2); e0–e7 the boundary, e8 = v7–v1 (diagonal), e9 = v2–v5; f0 = [v0,v1,v7], f1 = [v1,v2,v5,v6,v7], f2 = [v2,v3,v4,v5] | 1: valley fold the corner f0 up about e8 (v0 lands on (2,2)). 2: valley fold the strip f2 over about e9 (it lands on x ∈ [1, 2.5], covering part of f0). 3: `turnOver`, vertical, so that step 3's diagram draws frame 2 | |
| 63 | |
| 64 | Defect fixtures, each a copy of one above with one change: |
| 65 | |
| 66 | | Fixture | Change | |
| 67 | |---|---| |
| 68 | | `bad-index.fold` | `square.fold`, e0 references vertex 9 | |
| 69 | | `designed-model.fold` | `square.fold`, `file_author: "A. Designer"` | |
| 70 | | `topology-in-frame.fold` | `half.fold`, frame 1 carries `edges_vertices` | |
| 71 | | `retopologised.fold` | `half.fold`, frame 2 has a seventh vertex | |
| 72 | | `stretched-step.fold` | `half.fold`, frame 1's v2 moved to (0.01, 0, 0) | |
| 73 | | `angle-200.fold` | `half.fold`, frame 1's e6 at 200 | |
| 74 | | `angle-sign.fold` | `half.fold`, frame 1's e6 assigned `V` at −180 | |
| 75 | | `folded-boundary.fold` | `half.fold`, frame 1's e0 at 90 | |
| 76 | | `no-instruction.fold` | `half.fold`, step 1 without `instruction` | |
| 77 | | `rotate-no-degrees.fold` | `half.fold`, step 3 without `rotateDegrees` | |
| 78 | | `bad-moving-face.fold` | `half.fold`, step 1's `movingFaces` is `[7]` | |
| 79 | | `letter-no-midfold.fold` | `letter.fold` without `krz:faceOrders_midFold` | |
| 80 | | `letter-technique.fold` | `letter.fold` with `technique: "insideReverse"` (notation test only) | |
| 81 | | `still-face-reorder.fold` | `letter-sequential.fold`, frame 2 reverses the f0–f1 order (both still in step 2) | |
| 82 | | `cyclic-order.fold` | `letter-sequential.fold`, frame 2's orders form a cycle over f0, f1, f2 **after normalising** for their normals (f0 and f2 face −z, f1 faces +z in frame 2; `[0,1,1],[1,2,1],[2,0,1]` is not a cycle there) | |
| 83 | | `order-against-crease.fold` | `half.fold`, frame 1 puts f0 above f1, which the valley at e6 makes impossible | |
| 84 | | `interleaved-folds.fold` | `quarters.fold`, frame 3 swaps f1 and f2, so the folds at e8 (f0, f1) and e9 (f3, f2), coincident on x = 1, interleave instead of nesting | |
| 85 | | `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 | |
| 86 | | `nonconvex.fold` | an L-shaped sheet as one face, no frames | |
| 87 | |
| 88 | --- |
| 89 | |
| 90 | ### Setup: repository |
| 91 | |
| 92 | Done once, before Task 0. |
| 93 | |
| 94 | 1. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`. |
| 95 | 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. |
| 96 | 3. Work is batched into seven merge requests, each with one gitbay issue: |
| 97 | |
| 98 | | Batch | Tasks | Branch | |
| 99 | |---|---|---| |
| 100 | | A | 0 — interpolation spike | `spike-interpolation` | |
| 101 | | B | 1–3 — decoding, validator, steps | `format-and-steps` | |
| 102 | | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` | |
| 103 | | D | 7–8 — `foldc`, `foldlint`, the cup | `compiler-and-cup` | |
| 104 | | E | 9–10 — diagram, renderer | `diagram-and-renderer` | |
| 105 | | F | 11–14 — the app | `app` | |
| 106 | | G | 15 — crane, boat, box | `models` | |
| 107 | |
| 108 | Batch A merges alone, since Task 0 can stop the plan. Each batch commits task by task on its branch, ends with `gitbay mr create --source <branch> --target main`, merges when `swift test --package-path Packages/FoldKit` (and, from batch F, the `xcodebuild` test) is green, and the branch is then deleted locally and remotely. Commit messages end with `Ref #N` for the batch's issue; the batch's last commit uses `Closes #N`. |
| 109 | 4. If `xcrun metal --version` fails, run `xcodebuild -downloadComponent MetalToolchain`. SwiftPM invokes `metal` for the `.metal` file in Task 10; on 2026-10-19 this machine had no Metal toolchain. |
| 110 | |
| 111 | --- |
| 112 | |
| 113 | ### Task 0: Interpolation model spike |
| 114 | |
| 115 | **Files:** |
| 116 | - Create: `spikes/interpolation/Package.swift` — a macOS executable using `simd` only; not part of FoldKit and never linked into anything |
| 117 | - Create: `spikes/interpolation/Sources/Spike/main.swift` and whatever else it needs |
| 118 | - Create: `docs/decisions/0001-interpolation-model.md` |
| 119 | - Modify at the end: the design doc's *Interpolation* section, this plan's Tasks 1, 3, 4 and 7 and Review Focus item 1, and `CLAUDE.md` |
| 120 | |
| 121 | **Why first.** The design's interpolation — each axis rotates a disjoint moving set about its crease line in the start frame by a linearly interpolated angle — is exact for independent flaps. It is not exact for steps whose faces form closed loops around interior vertices: squash, petal and reverse folds, and the masu's wall-raising step. There the fold angles at a vertex are coupled nonlinearly (at a flat-foldable degree-4 vertex, tan(ρ₁/2) = k·tan(ρ₂/2)), some axes are carried by other moving faces, and vertices shared between moving sets off any axis tear apart partway through the fold even though both end frames are exact. Task 1's `AxisRecord`, Task 3's `FoldAxis`, Task 4's interpolator and Task 7's compiler all encode the answer, so it is measured before any of them exists. The isometry sweep in Task 4 would otherwise only find this in Task 15, on the crane, after everything else is built. |
| 122 | |
| 123 | **Cases**, each built in code with exact coordinates: |
| 124 | |
| 125 | 1. **Letter fold, both flaps valley.** 3×3 sheet, creases x = 1 and x = 2, both outer thirds folded in front in one step. Under a linear shared parameter, two flaps of equal reach folding toward each other meet at the midline from about 120° on and pass through each other. Draw order cannot fix a collision; this is the control for per-axis scheduling. |
| 126 | 2. **Letter fold, one valley, one mountain** (`letter.fold`'s geometry). The control for the case the current model handles: expected exact and clean. |
| 127 | 3. **Generic flat-foldable degree-4 vertex**, sector angles 60°, 80°, 120°, 100° in order, folded from flat to flat-folded in one step. Expected: independent linear angles drift; angles solved for loop closure are exact. |
| 128 | 4. **Inside reverse fold of a two-layer flap.** A 4×2 rectangle folded in half along y = 1 (the spine), with reverse-fold creases from (2, 1) to (3, 0) and from (2, 1) to (3, 2), the part left of them held still. Question: does any rigid motion take the tip inside the flap with the left part fixed? Hypothesis: none does. With the spine held at 180° the two layers' creases coincide, and the only rigid motion of the tip is to swing about that line as one closed unit, outside the flap. That ends at the same coordinates as the reverse fold, with the wrong layer order. Getting the tip inside requires the flap's layers to open — the "still" part moves. Measure the smallest spine opening for which a rigid path exists, and the peak strain of a non-rigid path if the spine may not open. |
| 129 | 5. **Petal fold** of the front flap of a preliminary base, built in code by applying the base's folds to a unit square. Measure the drift of independent linear angles, whether solved angles close every loop, and whether the side flaps' axes are carried by the lifted flap. |
| 130 | |
| 131 | **Candidate models:** |
| 132 | |
| 133 | - **M1** — the current design: disjoint moving sets, each rotated about its axis in the start frame by a linear angle (a tent for `foldAndUnfold`). |
| 134 | - **M2** — a kinematic tree with solved angle curves: an axis may name a parent axis whose motion carries it; each axis's angle is a monotone function of *t*, with its own start and end window on *t* so axes can be staggered; `foldc` solves the curves so every loop of faces around an interior vertex closes, and stores them sampled. |
| 135 | - **M3** — decomposition: the script splits the step into sub-steps, each M1 or M2, driven by one continuous drag. |
| 136 | - **M4** — non-rigid: per-face rigid transforms at solved sub-keyframes, interpolated between them; isometry is exact only at the sub-keyframes. |
| 137 | |
| 138 | **Measure**, for every case under every model that applies: the maximum edge-length drift over 1,001 samples of *t*; for M2, the maximum loop-closure residual; the minimum distance between faces that share no edge (negative means they intersect); and for case 4, the answer to the rigid-path question. |
| 139 | |
| 140 | **Also record:** |
| 141 | |
| 142 | - For each v1 model, every step that is not a single independent fold — the crane's preliminary-base collapse or squash folds, its petal folds and its inside reverse folds (neck, tail, head); the masu's wall-raising; the boat's, once the boat is chosen; the cup has none — with the case above that stands in for it and the model that covers it. |
| 143 | - Whether the overlapping-moving-sets rule for `krz:faceOrders_midFold` covers anything the end frame's ordering and the near-coplanar clusters (design, *Rendering*) do not. Case 1 suggests the problem with overlapping moving sets is that they collide, which ordering cannot fix. The key's other use, the peak order of a `foldAndUnfold`, is not in question. If the rule has no remaining consumer, recommend removing it, with the evidence; that changes a settled decision and goes to the author. |
| 144 | |
| 145 | **Exit criteria:** |
| 146 | |
| 147 | - `docs/decisions/0001-interpolation-model.md` holds the measurements, the model chosen and why. |
| 148 | - If every v1 step is covered by a rigid model (M1, M2 or M3): in the same merge request, rewrite the design doc's *Interpolation* section; amend Task 1's `AxisRecord` and tests, Task 3's `FoldAxis`, Task 4's interface and tests (add cases 3–5 to the isometry sweep as fixtures), Task 7's script fields and outputs, and Review Focus item 1; and add the result to `CLAUDE.md`'s *Settled* list. |
| 149 | - If some v1 step is covered only by M4, or by nothing: **stop**. Splitting the step, dropping it, shipping a different model and relaxing `CLAUDE.md`'s isometry rule for that step are the author's choices. Do not start Task 1. |
| 150 | |
| 151 | This is a measurement, not TDD. |
| 152 | |
| 153 | - [ ] **Step 1: Build the spike package and the five cases** |
| 154 | - [ ] **Step 2: Implement M1 and M2, and M3 and M4 as far as case 4 needs them** |
| 155 | - [ ] **Step 3: Run and record** |
| 156 | |
| 157 | Run: `swift run --package-path spikes/interpolation` |
| 158 | |
| 159 | - [ ] **Step 4: Write the decision record and apply the exit criteria** |
| 160 | - [ ] **Step 5: Commit** |
| 161 | |
| 162 | ```bash |
| 163 | git add spikes docs |
| 164 | git commit -m "Interpolation model spike and decision record" |
| 165 | ``` |
| 166 | |
| 167 | --- |
| 168 | |
| 169 | ### Task 1: FOLD decoding, including the extension keys |
| 170 | |
| 171 | **Files:** |
| 172 | - Create: `Packages/FoldKit/Package.swift` |
| 173 | - Create: `Packages/FoldKit/Sources/FoldFormat/FoldFile.swift` |
| 174 | - Create: `Packages/FoldKit/Sources/FoldFormat/FoldFrame.swift` |
| 175 | - Create: `Packages/FoldKit/Sources/FoldFormat/EdgeAssignment.swift` |
| 176 | - Create: `Packages/FoldKit/Sources/FoldFormat/StepRecord.swift` |
| 177 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixture.swift` |
| 178 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/` — every fixture in *Synthetic fixtures* |
| 179 | - Test: `Packages/FoldKit/Tests/FoldFormatTests/DecodingTests.swift` |
| 180 | |
| 181 | **Interfaces:** |
| 182 | - Consumes: nothing. |
| 183 | - Produces: |
| 184 | - `enum EdgeAssignment: String, Codable, Sendable { case boundary = "B", mountain = "M", valley = "V", flat = "F", unassigned = "U" }` |
| 185 | - `enum StepKind: String, Codable, Sendable { case fold, foldAndUnfold, turnOver, rotate }` |
| 186 | - `enum StepTechnique: String, Codable, Sendable { case plain, insideReverse, outsideReverse, squash, petal, sink }` |
| 187 | - `enum TurnOverAxis: String, Codable, Sendable { case vertical, horizontal }` |
| 188 | - `struct AxisRecord: Codable, Equatable, Sendable { let edge: Int; let movingFaces: [Int]; let startAngle: Double; let endAngle: Double; let peakAngle: Double? }` |
| 189 | - `struct Viewpoint: Codable, Equatable, Sendable { let eye: SIMD3<Double>; let up: SIMD3<Double> }` — `eye` is the unit direction toward the viewer |
| 190 | - `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 viewpoint: Viewpoint }` |
| 191 | - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3<Double>]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }` |
| 192 | - `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 |
| 193 | - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1` |
| 194 | - `init (FoldFile).init(contentsOf url: URL) throws` |
| 195 | - `enum FoldError: Error, Equatable, Sendable { case unsupportedAssignment(String); case malformedCoordinate(vertex: Int); case missingStepRecord(step: Int); case topologyInFrame(frame: Int); case missingFrameInheritance(frame: Int) }` |
| 196 | - `func fixture(_ name: String) -> URL` in `FoldKitTestSupport` |
| 197 | |
| 198 | `edgesVertices` and `facesVertices` live on `FoldFile`, not `FoldFrame`, because the spec fixes one topology for every frame. Decoding them per-frame would make the invariant expressible-but-violable; hoisting them makes it structural, and a frame that carries either is a decoding error. `vertices_coords` entries may be 2- or 3-element arrays; decode 2-element as z = 0. |
| 199 | |
| 200 | The key frame is FOLD's top level, mixed with the `file_` keys, so `FoldFile` needs a hand-written `init(from:)` and `encode(to:)`: frame 0 from the top level, frames 1…N from `file_frames`, each of which must carry `frame_parent: 0` and `frame_inherit: true` and is written with them. Keys an exported crease pattern may lack decode to defaults: `edges_foldAngle` to zeros, `faceOrders` to empty, `edges_krz:firstCreasedAtStep` to nulls, `file_title` and `file_author` to nil, `file_classes` to empty. That lets `foldc` read crease patterns with the same decoder; the validator, not the decoder, decides what a shipped model must have. |
| 201 | |
| 202 | Package manifest: swift-tools-version 6.2, platforms `.iOS(.v26)`, `.macOS(.v26)`. Library products `FoldFormat`, `Folding`, `Notation`, `Renderer`, `Models`; executables `foldlint` and `foldc`; a test target per library; and `FoldKitTestSupport`, a plain target with `resources: [.copy("Fixtures")]` that only test targets depend on. |
| 203 | |
| 204 | - [ ] **Step 1: Write the failing tests** |
| 205 | |
| 206 | ```swift |
| 207 | @Test func decodesUnitSquareWithFourBoundaryEdges() throws { |
| 208 | let f = try FoldFile(contentsOf: fixture("square.fold")) |
| 209 | #expect(f.frames[0].verticesCoords.count == 4) |
| 210 | #expect(f.frames[0].edgesAssignment.allSatisfy { $0 == .boundary }) |
| 211 | #expect(f.stepCount == 0) |
| 212 | } |
| 213 | |
| 214 | @Test func topologyLivesOnTheFileNotTheFrame() throws { |
| 215 | let f = try FoldFile(contentsOf: fixture("square.fold")) |
| 216 | #expect(f.edgesVertices.count == 4) |
| 217 | #expect(f.facesVertices.count == 1) |
| 218 | } |
| 219 | |
| 220 | @Test func aFrameCarryingTopologyIsRejected() { |
| 221 | #expect(throws: FoldError.topologyInFrame(frame: 1)) { |
| 222 | try FoldFile(contentsOf: fixture("topology-in-frame.fold")) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | @Test func decodesTwoElementCoordsAsZeroZ() throws { |
| 227 | #expect(try FoldFile(contentsOf: fixture("square.fold")).frames[0].verticesCoords |
| 228 | .allSatisfy { $0.z == 0 }) |
| 229 | } |
| 230 | |
| 231 | @Test func frameNIsTheResultOfStepN() throws { |
| 232 | let f = try FoldFile(contentsOf: fixture("half.fold")) |
| 233 | #expect(f.stepCount == 3) |
| 234 | #expect(f.frames[0].step == nil) |
| 235 | #expect(f.frames[1].step?.kind == .fold) |
| 236 | #expect(f.frames[2].step?.kind == .turnOver) |
| 237 | #expect(f.frames[3].step?.rotateDegrees == 90) |
| 238 | } |
| 239 | |
| 240 | @Test func decodesTheStepRecordIncludingItsInstructionAndViewpoint() throws { |
| 241 | let step = try FoldFile(contentsOf: fixture("half.fold")).frames[1].step |
| 242 | #expect(step?.axes.count == 1) |
| 243 | #expect(step?.technique == .plain) |
| 244 | #expect(step?.instruction?.isEmpty == false) |
| 245 | #expect(step?.viewpoint == Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))) |
| 246 | } |
| 247 | |
| 248 | @Test func decodesFirstCreasedAtStepWithNullForBoundaries() throws { |
| 249 | let f = try FoldFile(contentsOf: fixture("half.fold")) |
| 250 | #expect(f.edgesFirstCreasedAtStep == [nil, nil, nil, nil, nil, nil, 1]) |
| 251 | } |
| 252 | |
| 253 | @Test func roundTripsThroughEncodingUnchanged() throws { |
| 254 | let f = try FoldFile(contentsOf: fixture("half.fold")) |
| 255 | let again = try JSONDecoder().decode(FoldFile.self, from: JSONEncoder().encode(f)) |
| 256 | #expect(again.edgesVertices == f.edgesVertices) |
| 257 | #expect(again.frames.map(\.verticesCoords) == f.frames.map(\.verticesCoords)) |
| 258 | #expect(again.frames.map(\.step) == f.frames.map(\.step)) |
| 259 | } |
| 260 | |
| 261 | @Test func encodedFramesInheritFromTheKeyFrame() throws { |
| 262 | let f = try FoldFile(contentsOf: fixture("half.fold")) |
| 263 | let json = try JSONSerialization.jsonObject(with: JSONEncoder().encode(f)) as! [String: Any] |
| 264 | let frames = json["file_frames"] as! [[String: Any]] |
| 265 | #expect(frames.allSatisfy { $0["frame_parent"] as? Int == 0 && $0["frame_inherit"] as? Bool == true }) |
| 266 | #expect(frames.allSatisfy { $0["edges_vertices"] == nil }) |
| 267 | } |
| 268 | |
| 269 | @Test(arguments: ["C", "J"]) |
| 270 | func rejectsCutAndJoinAssignments(_ code: String) { |
| 271 | #expect(throws: FoldError.unsupportedAssignment(code)) { |
| 272 | try JSONDecoder().decode(EdgeAssignment.self, from: Data("\"\(code)\"".utf8)) |
| 273 | } |
| 274 | } |
| 275 | ``` |
| 276 | |
| 277 | - [ ] **Step 2: Run tests to verify they fail** |
| 278 | |
| 279 | Run: `swift test --package-path Packages/FoldKit --filter DecodingTests` |
| 280 | Expected: FAIL — no such module `FoldFormat`. |
| 281 | |
| 282 | - [ ] **Step 3: Write the fixtures, implement the types and `FoldFile`'s coding** |
| 283 | |
| 284 | `CodingKeys` map the format's spelling exactly: snake_case for standard keys, `faceOrders` camelCase, `edges_krz:firstCreasedAtStep`, `krz:step`, `krz:faceOrders_midFold`. `EdgeAssignment` needs its own `init(from:)` to throw `FoldError` rather than `DecodingError`. Write the fixtures from the tables in *Synthetic fixtures*; their coordinates are exact. |
| 285 | |
| 286 | - [ ] **Step 4: Run tests to verify they pass** |
| 287 | |
| 288 | Run: `swift test --package-path Packages/FoldKit --filter DecodingTests` |
| 289 | Expected: PASS. |
| 290 | |
| 291 | - [ ] **Step 5: Commit** |
| 292 | |
| 293 | ```bash |
| 294 | git add Packages/FoldKit |
| 295 | git commit -m "FOLD decoding with krz extension keys and synthetic fixtures" |
| 296 | ``` |
| 297 | |
| 298 | --- |
| 299 | |
| 300 | ### Task 2: The validator |
| 301 | |
| 302 | **Files:** |
| 303 | - Create: `Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift` |
| 304 | - Test: `Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift` |
| 305 | |
| 306 | **Interfaces:** |
| 307 | - Consumes: Task 1 types. |
| 308 | - Produces: |
| 309 | - `enum FoldDefect: Equatable, Sendable { case vertexIndexOutOfRange(edge: Int); case faceVertexOutOfRange(face: Int); case vertexCountChanged(frame: Int); case foldAngleOutOfRange(frame: Int, edge: Int, degrees: Double); case foldAngleSignDisagreesWithAssignment(frame: Int, edge: Int); case boundaryEdgeFolded(frame: Int, edge: Int); case faceOrderNotAntisymmetric(frame: Int, f: Int, g: Int); case cyclicFaceOrder(frame: Int, cycle: [Int]); case nonIsometricTransition(step: Int, edge: Int, from: Double, to: Double); case overlappingMovingSetsWithoutMidFoldOrder(step: Int); case startAndEndOrderDisagreeOnStillFaces(step: Int, f: Int, g: Int); case foldAndUnfoldWithoutPeakOrder(step: Int); case orderDisagreesWithCrease(frame: Int, edge: Int); case interleavedFolds(frame: Int, edges: [Int]); case faceInsideFold(frame: Int, face: Int, edge: Int); case nonConvexFace(face: Int); case missingInstruction(step: Int); case authorNotTraditional(String?); case missingFirstCreasedAtStep(edge: Int) }` |
| 310 | - `func validate(_ file: FoldFile) -> [FoldDefect]` |
| 311 | - `func movingSetsOverlapInProjection(step: Int, _ file: FoldFile) -> Bool` |
| 312 | - `func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>]` |
| 313 | - `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) |
| 314 | |
| 315 | 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. |
| 316 | |
| 317 | 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`: |
| 318 | |
| 319 | - **crease:** two faces joined at a crease folded to ±180 are ordered as its `edges_assignment` requires — for a valley each face's normal points toward the other, for a mountain away; |
| 320 | - **nesting:** where two folded creases coincide, their face pairs nest or are disjoint in the stack, never interleave (FOLD's "taco-taco"); |
| 321 | - **inside:** a face whose interior crosses a folded crease's line does not lie between that crease's two faces ("taco-tortilla"). |
| 322 | |
| 323 | - [ ] **Step 1: Write the failing tests** |
| 324 | |
| 325 | ```swift |
| 326 | @Test(arguments: ["square.fold", "half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", |
| 327 | "quarters.fold", "occlusion.fold"]) |
| 328 | func acceptsAValidModel(_ name: String) throws { |
| 329 | #expect(validate(try FoldFile(contentsOf: fixture(name))).isEmpty) |
| 330 | } |
| 331 | |
| 332 | @Test func oppositeNormalsMakeAMutualAboveValid() { |
| 333 | // [f, g, +1] and [g, f, +1] agree when the faces face opposite ways |
| 334 | let pairs = normalisedFaceOrders([[0, 1, 1], [1, 0, 1]], |
| 335 | normals: [SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) |
| 336 | #expect(Set(pairs.map { [$0.below, $0.above] }) == [[0, 1]]) |
| 337 | } |
| 338 | |
| 339 | @Test func rejectsAnOrderTheCreaseMakesImpossible() throws { |
| 340 | #expect(validate(try FoldFile(contentsOf: fixture("order-against-crease.fold"))) |
| 341 | .contains(.orderDisagreesWithCrease(frame: 1, edge: 6))) |
| 342 | } |
| 343 | |
| 344 | @Test func rejectsInterleavedFolds() throws { |
| 345 | let defects = validate(try FoldFile(contentsOf: fixture("interleaved-folds.fold"))) |
| 346 | #expect(defects.contains { if case .interleavedFolds(frame: 3, _) = $0 { return true }; return false }) |
| 347 | } |
| 348 | |
| 349 | @Test func rejectsAFaceInsideAFoldItCrosses() throws { |
| 350 | let defects = validate(try FoldFile(contentsOf: fixture("face-inside-fold.fold"))) |
| 351 | #expect(defects.contains(.faceInsideFold(frame: 2, face: 2, edge: 8))) |
| 352 | } |
| 353 | |
| 354 | @Test func rejectsAFoldAndUnfoldWithoutItsPeakOrder() throws { |
| 355 | var file = try FoldFile(contentsOf: fixture("quarters.fold")) |
| 356 | file.frames[1].faceOrdersMidFold = nil |
| 357 | #expect(validate(file).contains(.foldAndUnfoldWithoutPeakOrder(step: 1))) |
| 358 | } |
| 359 | |
| 360 | @Test func rejectsANonConvexFace() throws { |
| 361 | #expect(validate(try FoldFile(contentsOf: fixture("nonconvex.fold"))) == [.nonConvexFace(face: 0)]) |
| 362 | } |
| 363 | |
| 364 | @Test func rejectsAFrameThatChangesTheVertexCount() throws { |
| 365 | let defects = validate(try FoldFile(contentsOf: fixture("retopologised.fold"))) |
| 366 | #expect(defects.contains(.vertexCountChanged(frame: 2))) |
| 367 | } |
| 368 | |
| 369 | @Test func rejectsOverlappingMovingSetsWithNoMidFoldOrder() throws { |
| 370 | let defects = validate(try FoldFile(contentsOf: fixture("letter-no-midfold.fold"))) |
| 371 | #expect(defects == [.overlappingMovingSetsWithoutMidFoldOrder(step: 1)]) |
| 372 | } |
| 373 | |
| 374 | @Test func rejectsStartAndEndOrderDisagreementOnStillFaces() throws { |
| 375 | let defects = validate(try FoldFile(contentsOf: fixture("still-face-reorder.fold"))) |
| 376 | #expect(defects.contains { |
| 377 | if case .startAndEndOrderDisagreeOnStillFaces(step: 2, _, _) = $0 { return true }; return false }) |
| 378 | } |
| 379 | |
| 380 | @Test func rejectsCyclicFaceOrder() throws { |
| 381 | let defects = validate(try FoldFile(contentsOf: fixture("cyclic-order.fold"))) |
| 382 | #expect(defects.contains { if case .cyclicFaceOrder(frame: 2, _) = $0 { return true }; return false }) |
| 383 | } |
| 384 | |
| 385 | @Test func rejectsNonIsometricTransition() throws { |
| 386 | let defects = validate(try FoldFile(contentsOf: fixture("stretched-step.fold"))) |
| 387 | #expect(defects.contains { if case .nonIsometricTransition(step: 1, _, _, _) = $0 { return true }; return false }) |
| 388 | } |
| 389 | |
| 390 | @Test func rejectsFoldAngleOutsideRange() throws { |
| 391 | #expect(validate(try FoldFile(contentsOf: fixture("angle-200.fold"))) |
| 392 | == [.foldAngleOutOfRange(frame: 1, edge: 6, degrees: 200)]) |
| 393 | } |
| 394 | |
| 395 | @Test func rejectsAFoldAngleWhoseSignDisagreesWithItsAssignment() throws { |
| 396 | #expect(validate(try FoldFile(contentsOf: fixture("angle-sign.fold"))) |
| 397 | == [.foldAngleSignDisagreesWithAssignment(frame: 1, edge: 6)]) |
| 398 | } |
| 399 | |
| 400 | @Test func rejectsAFoldedBoundaryEdge() throws { |
| 401 | let defects = validate(try FoldFile(contentsOf: fixture("folded-boundary.fold"))) |
| 402 | #expect(defects.contains(.boundaryEdgeFolded(frame: 1, edge: 0))) |
| 403 | } |
| 404 | |
| 405 | @Test func rejectsAStepWithoutAnInstruction() throws { |
| 406 | #expect(validate(try FoldFile(contentsOf: fixture("no-instruction.fold"))) |
| 407 | == [.missingInstruction(step: 1)]) |
| 408 | } |
| 409 | |
| 410 | @Test func rejectsANonTraditionalAuthor() throws { |
| 411 | #expect(validate(try FoldFile(contentsOf: fixture("designed-model.fold"))) |
| 412 | == [.authorNotTraditional("A. Designer")]) |
| 413 | } |
| 414 | |
| 415 | @Test func rejectsEdgeReferencingMissingVertex() throws { |
| 416 | #expect(validate(try FoldFile(contentsOf: fixture("bad-index.fold"))) |
| 417 | == [.vertexIndexOutOfRange(edge: 0)]) |
| 418 | } |
| 419 | ``` |
| 420 | |
| 421 | - [ ] **Step 2: Run tests to verify they fail** |
| 422 | |
| 423 | Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests` |
| 424 | Expected: FAIL. |
| 425 | |
| 426 | - [ ] **Step 3: Implement `validate` and `movingSetsOverlapInProjection`** |
| 427 | |
| 428 | Normals come from the frame's coordinates and the counterclockwise `faces_vertices` order. For cycle detection and the three consistency rules, normalise every triple with `normalisedFaceOrders` first; cycle detection is depth-first search over the resulting below → above graph. The still-face rule must not use normalised pairs, because a turn-over flips every normal and would invert every pair: it compares each pair's relation in a form a rigid motion leaves unchanged — the triple rewritten with the lower face index first, `s` negated when swapping faces whose normals agree (the spec's reverse-triple rule). A raw `s = +1` graph is wrong both ways: `[f, g, +1]` with `[g, f, +1]` is valid for opposite normals, and a raw cycle can be acyclic once normalised. Antisymmetry follows the spec: a present reverse triple `[g, f, t]` has `t = -s` when the two faces' normals agree in the folded state and `t = s` when they oppose. Sign: `V` requires a positive angle, `M` negative, `F`, `U` and `B` zero. Every `foldAndUnfold` needs `krz:faceOrders_midFold`, the order at its peak, since neither end frame orders the moving faces against what they lie on there; the validator checks it is present, and Task 5's `LayerOrder.active`, which can compute the peak positions, checks it for cycles. Every non-boundary edge needs a `edges_krz:firstCreasedAtStep` except a subdivision edge (`F` and flat in every frame). Overlap in projection is tested by polygon intersection of the moving sets' projected outlines at the step's viewpoint, in frame n (where both sets have arrived). |
| 429 | |
| 430 | - [ ] **Step 4: Run tests to verify they pass** |
| 431 | |
| 432 | Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests` |
| 433 | Expected: PASS. |
| 434 | |
| 435 | - [ ] **Step 5: Commit** |
| 436 | |
| 437 | ```bash |
| 438 | git add Packages/FoldKit |
| 439 | git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold ordering" |
| 440 | ``` |
| 441 | |
| 442 | --- |
| 443 | |
| 444 | ### Task 3: Reading authored steps |
| 445 | |
| 446 | **Files:** |
| 447 | - Create: `Packages/FoldKit/Sources/Folding/FoldStep.swift` |
| 448 | - Create: `Packages/FoldKit/Sources/Folding/StepReader.swift` |
| 449 | - Test: `Packages/FoldKit/Tests/FoldingTests/StepReadingTests.swift` |
| 450 | |
| 451 | **Interfaces:** |
| 452 | - Consumes: Task 1 types. |
| 453 | - Produces: |
| 454 | - `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? }` |
| 455 | - `func (FoldAxis).angle(at t: Double, kind: StepKind) -> Double` |
| 456 | - `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 viewpoint: Viewpoint }` |
| 457 | - `var (FoldStep).movingFaceUnion: Set<Int> { get }` |
| 458 | - `func readSteps(_ file: FoldFile) throws -> [FoldStep]` — `result[k].index == k + 1` |
| 459 | - `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) }` |
| 460 | |
| 461 | `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. |
| 462 | |
| 463 | `FoldAxis.origin` and `direction` come from the axis edge's endpoints in frame `index − 1`. The direction is the way the moving face adjacent to the edge traverses it in `faces_vertices` order, and the origin is the vertex that traversal starts from, so that a positive rotation about it (right-hand rule) turns the moving face toward its normal — a valley — and the rotation for any step is `angle(t) − startAngle` with FOLD's own sign. `angle(at:)` is `startAngle + t·(endAngle − startAngle)` for `fold`, and `startAngle + (peakAngle − startAngle)·(1 − |2t − 1|)` for `foldAndUnfold`. |
| 464 | |
| 465 | - [ ] **Step 1: Write the failing tests** |
| 466 | |
| 467 | ```swift |
| 468 | @Test func stepIndicesCountFromOne() throws { |
| 469 | let steps = try readSteps(FoldFile(contentsOf: fixture("half.fold"))) |
| 470 | #expect(steps.map(\.index) == [1, 2, 3]) |
| 471 | } |
| 472 | |
| 473 | @Test func simpleValleyFoldReadsOneAxis() throws { |
| 474 | let step = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0] |
| 475 | #expect(step.axes.count == 1) |
| 476 | #expect(step.axes[0].endAngle == 180) |
| 477 | } |
| 478 | |
| 479 | @Test func letterFoldReadsTwoSimultaneousAxes() throws { |
| 480 | let step = try readSteps(FoldFile(contentsOf: fixture("letter.fold")))[0] |
| 481 | #expect(step.axes.count == 2) |
| 482 | } |
| 483 | |
| 484 | @Test(arguments: ["half.fold", "letter.fold", "letter-sequential.fold", "quarters.fold", "occlusion.fold"]) |
| 485 | func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws { |
| 486 | for step in try readSteps(FoldFile(contentsOf: fixture(name))) { |
| 487 | let union = step.axes.reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) } |
| 488 | #expect(union.count == step.axes.reduce(0) { $0 + $1.movingFaces.count }) |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | @Test func turnOverStepHasNoAxesAndAnAxisToTurnAbout() throws { |
| 493 | let turn = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[1] |
| 494 | #expect(turn.kind == .turnOver) |
| 495 | #expect(turn.axes.isEmpty) |
| 496 | #expect(turn.turnOverAxis == .vertical) |
| 497 | } |
| 498 | |
| 499 | @Test func rotateStepCarriesItsDegrees() throws { |
| 500 | #expect(try readSteps(FoldFile(contentsOf: fixture("half.fold")))[2].rotateDegrees == 90) |
| 501 | } |
| 502 | |
| 503 | @Test func foldAndUnfoldPeaksMidwayAndReturns() throws { |
| 504 | let s = try readSteps(FoldFile(contentsOf: fixture("quarters.fold")))[0] |
| 505 | #expect(s.kind == .foldAndUnfold) |
| 506 | #expect(s.axes[0].angle(at: 0.5, kind: s.kind) == 180) |
| 507 | #expect(s.axes[0].angle(at: 1, kind: s.kind) == 0) |
| 508 | } |
| 509 | |
| 510 | @Test func axisIsDirectedAsTheMovingFaceTraversesIt() throws { |
| 511 | // f1 = [v1, v2, v3, v4] traverses e6 = [v1, v4] from v4 to v1 |
| 512 | let axis = try readSteps(FoldFile(contentsOf: fixture("half.fold")))[0].axes[0] |
| 513 | #expect(axis.origin == SIMD3(1, 2, 0)) |
| 514 | #expect(axis.direction == SIMD3(0, -1, 0)) |
| 515 | } |
| 516 | |
| 517 | @Test func instructionIsReadVerbatim() throws { |
| 518 | let f = try FoldFile(contentsOf: fixture("half.fold")) |
| 519 | #expect(try readSteps(f)[0].instruction == f.frames[1].step?.instruction) |
| 520 | } |
| 521 | |
| 522 | @Test func rotateWithoutDegreesThrows() { |
| 523 | #expect(throws: StepError.rotateWithoutDegrees(step: 3)) { |
| 524 | try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold"))) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | @Test func movingFaceOutOfRangeThrows() { |
| 529 | #expect(throws: StepError.movingFacesOutOfRange(step: 1)) { |
| 530 | try readSteps(FoldFile(contentsOf: fixture("bad-moving-face.fold"))) |
| 531 | } |
| 532 | } |
| 533 | ``` |
| 534 | |
| 535 | - [ ] **Step 2: Run tests to verify they fail** |
| 536 | |
| 537 | Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests` |
| 538 | Expected: FAIL. |
| 539 | |
| 540 | - [ ] **Step 3: Implement `FoldAxis`, `FoldStep` and `readSteps`** |
| 541 | |
| 542 | - [ ] **Step 4: Run tests to verify they pass** |
| 543 | |
| 544 | Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests` |
| 545 | Expected: PASS. |
| 546 | |
| 547 | - [ ] **Step 5: Commit** |
| 548 | |
| 549 | ```bash |
| 550 | git add Packages/FoldKit |
| 551 | git commit -m "Read authored fold steps, including multi-axis and reorientation kinds" |
| 552 | ``` |
| 553 | |
| 554 | --- |
| 555 | |
| 556 | ### Task 4: Rigid interpolation |
| 557 | |
| 558 | **Files:** |
| 559 | - Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` |
| 560 | - Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift` |
| 561 | |
| 562 | **Interfaces** (as of before Task 0; Task 0 amends them for coupled steps): |
| 563 | - Consumes: Task 1 and Task 3 types. |
| 564 | - Produces: |
| 565 | - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index` |
| 566 | - `func (FoldInterpolator).positions(at t: Double) -> [SIMD3<Double>]` — `t` in 0...1 |
| 567 | |
| 568 | There is no separate orientation output: a `turnOver` or `rotate` step's end frame already has rotated coordinates, so `positions(at:)` rotates the start frame about its bounding-box centre by `t` times the step's angle — 180° about the viewpoint's up vector or its right vector (`up × eye`) for `turnOver`, `rotateDegrees` about `eye` for `rotate` (right-hand rule, so positive is counterclockwise as seen). |
| 569 | |
| 570 | - [ ] **Step 1: Write the failing tests** |
| 571 | |
| 572 | ```swift |
| 573 | let modelFixtures = ["half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", |
| 574 | "quarters.fold", "occlusion.fold"] |
| 575 | |
| 576 | @Test func tZeroReproducesTheStartFrame() throws { |
| 577 | let (file, i) = try interpolator("half.fold", step: 1) |
| 578 | #expect(zip(i.positions(at: 0), file.frames[0].verticesCoords) |
| 579 | .allSatisfy { simd_distance($0, $1) < 1e-12 }) |
| 580 | } |
| 581 | |
| 582 | @Test(arguments: modelFixtures) |
| 583 | func tOneReproducesTheEndFrameForEveryStep(_ name: String) throws { |
| 584 | let file = try FoldFile(contentsOf: fixture(name)) |
| 585 | for step in try readSteps(file) { |
| 586 | let i = FoldInterpolator(file: file, step: step) |
| 587 | #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords) |
| 588 | .allSatisfy { simd_distance($0, $1) < 1e-9 }, "\(name) step \(step.index)") |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | @Test(arguments: modelFixtures) |
| 593 | func everyEdgeLengthIsPreservedThroughoutEveryStep(_ name: String) throws { |
| 594 | let file = try FoldFile(contentsOf: fixture(name)) |
| 595 | for step in try readSteps(file) { |
| 596 | let i = FoldInterpolator(file: file, step: step) |
| 597 | for t in stride(from: 0.0, through: 1.0, by: 0.05) { |
| 598 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-9, |
| 599 | "\(name) step \(step.index) t \(t)") |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | @Test func verticesOnTheAxisDoNotMove() throws { |
| 605 | let (file, i) = try interpolator("half.fold", step: 1) |
| 606 | for v in [1, 4] { |
| 607 | #expect(simd_distance(i.positions(at: 0.37)[v], file.frames[0].verticesCoords[v]) < 1e-12) |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | @Test func aValleyFoldRisesTowardTheViewerAndAMountainFoldFallsAway() throws { |
| 612 | let (_, valley) = try interpolator("half.fold", step: 1) |
| 613 | let (_, mountain) = try interpolator("mountain.fold", step: 1) |
| 614 | #expect(valley.positions(at: 0.5)[2].z > 0) |
| 615 | #expect(mountain.positions(at: 0.5)[2].z < 0) |
| 616 | } |
| 617 | |
| 618 | @Test func multiAxisStepMovesEverySetOnTheSharedParameter() throws { |
| 619 | let (file, i) = try interpolator("letter.fold", step: 1) |
| 620 | let start = file.frames[0].verticesCoords, mid = i.positions(at: 0.5) |
| 621 | #expect(simd_distance(mid[0], start[0]) > 0.1) // left flap |
| 622 | #expect(simd_distance(mid[3], start[3]) > 0.1) // right flap |
| 623 | } |
| 624 | |
| 625 | @Test func foldAndUnfoldPassesThroughThePeakAndReturns() throws { |
| 626 | let (file, i) = try interpolator("quarters.fold", step: 1) |
| 627 | #expect(simd_distance(i.positions(at: 0.5)[2], SIMD3(0, 0, 0)) < 1e-9) |
| 628 | #expect(zip(i.positions(at: 1), file.frames[0].verticesCoords) |
| 629 | .allSatisfy { simd_distance($0, $1) < 1e-9 }) |
| 630 | } |
| 631 | |
| 632 | @Test func turnOverRotatesTheModelRigidly() throws { |
| 633 | let (_, i) = try interpolator("half.fold", step: 2) |
| 634 | #expect(pairwiseDistancesAgree(i.positions(at: 0.5), i.positions(at: 0))) |
| 635 | #expect(i.positions(at: 0.5).contains { $0.z != 0 }) |
| 636 | } |
| 637 | |
| 638 | @Test func interpolationFitsInAFrameBudget() throws { |
| 639 | let file = gridSheet(cells: 12) // built in code: a 12×12 grid, one fold down the middle |
| 640 | let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) |
| 641 | let elapsed = ContinuousClock().measure { |
| 642 | for n in 0..<1000 { _ = i.positions(at: Double(n) / 1000) } |
| 643 | } |
| 644 | #expect(elapsed / 1000 < .milliseconds(1)) |
| 645 | } |
| 646 | ``` |
| 647 | |
| 648 | - [ ] **Step 2: Run tests to verify they fail** |
| 649 | |
| 650 | Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests` |
| 651 | Expected: FAIL. |
| 652 | |
| 653 | - [ ] **Step 3: Implement `positions(at:)`** |
| 654 | |
| 655 | For each axis, rotate its moving faces' vertices about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, with `simd_quatd(angle:axis:)` about the origin-shifted axis. A vertex in no moving set is unchanged. Reorientation steps rotate every vertex as described above. |
| 656 | |
| 657 | - [ ] **Step 4: Run tests to verify they pass** |
| 658 | |
| 659 | Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests` |
| 660 | Expected: PASS. |
| 661 | |
| 662 | - [ ] **Step 5: Commit** |
| 663 | |
| 664 | ```bash |
| 665 | git add Packages/FoldKit |
| 666 | git commit -m "Rigid interpolation, including reorientation steps" |
| 667 | ``` |
| 668 | |
| 669 | --- |
| 670 | |
| 671 | ### Task 5: Layer order resolution |
| 672 | |
| 673 | **Files:** |
| 674 | - Create: `Packages/FoldKit/Sources/Folding/LayerOrder.swift` |
| 675 | - Test: `Packages/FoldKit/Tests/FoldingTests/LayerOrderTests.swift` |
| 676 | |
| 677 | **Interfaces:** |
| 678 | - Consumes: Task 1–4 types; `faceNormals` and `normalisedFaceOrders` from Task 2. |
| 679 | - Produces: |
| 680 | - `struct LayerOrder: Sendable { init(sources: [(faceOrders: [[Int]], normals: [SIMD3<Double>])]) throws }` — each source is a set of triples with the face normals of the state it describes; earlier sources win for a pair present in several. Triples are stored raw; normals are used only to check each source for cycles |
| 681 | - `init (LayerOrder).init(faceOrders: [[Int]], normals: [SIMD3<Double>]) throws` — one source |
| 682 | - `static func (LayerOrder).active(for step: FoldStep, in file: FoldFile) throws -> LayerOrder` — first source frame n's `krz:faceOrders_midFold` (with the normals at the peak, from Task 4's interpolator at `t = 0.5`, for a `foldAndUnfold`, else frame n's) or, without one, frame n's `faceOrders` with frame n's normals; second source frame n − 1's `faceOrders` with frame n − 1's normals, for pairs the first lacks |
| 683 | - `struct CoplanarCluster: Equatable, Sendable { let faces: [Int] }` — faces already sorted back-to-front for the given view |
| 684 | - `func (LayerOrder).clusters(positions: [SIMD3<Double>], faces: [[Int]], viewDirection: SIMD3<Double>) -> [CoplanarCluster]` |
| 685 | - `func (LayerOrder).agreesWith(_ other: LayerOrder, ignoring movingFaces: Set<Int>) -> Bool` |
| 686 | - `func stackDepth(positions: [SIMD3<Double>], faces: [[Int]]) -> Int` — the most faces whose open interiors cover one point, over coincident faces; a flat sheet is 1 |
| 687 | - `enum LayerError: Error, Equatable, Sendable { case cyclic(cycle: [Int]) }` |
| 688 | |
| 689 | The output is **clusters**, not one global draw order, because the renderer is hybrid: the depth buffer separates clusters and the active ordering orders within them. Two faces are linked when they overlap in projection, their normals are within 2° of each other's line, and each one's vertices lie within sin 2° × the model's bounding-box diagonal of the other's plane — the distance tolerance follows the angular one, since a flap hinged at the edge of a stack and 2° off it rises that far. A cluster is a connected group of linked faces. The tolerance is wide on purpose: a facet just leaving or just arriving on a stack is nearly coplanar with it, and the depth buffer alone would z-fight there. |
| 690 | |
| 691 | Each triple's `s` is resolved against `viewDirection` using `g`'s normal **at the given positions**, since "above" in FOLD means "on the side `g`'s normal points toward", that reverses when the view crosses `g`'s plane, and a moving stack's normals turn with it. The fallback to frame n − 1 covers a flap leaving a stack, whose pairs exist only in the start frame; `foldAndUnfold` carries its peak order in `krz:faceOrders_midFold` (Task 2 requires it). |
| 692 | |
| 693 | - [ ] **Step 1: Write the failing tests** |
| 694 | |
| 695 | ```swift |
| 696 | let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)] |
| 697 | let up3 = up2 + [SIMD3(0, 0, 1)] |
| 698 | |
| 699 | @Test func twoStackedCoplanarFacesFormOneClusterOrderedFarthestFirst() throws { |
| 700 | let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) // 0 above 1 |
| 701 | let c = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), |
| 702 | viewDirection: SIMD3(0, 0, -1)) |
| 703 | #expect(c.count == 1) |
| 704 | #expect(c[0].faces == [1, 0]) |
| 705 | } |
| 706 | |
| 707 | @Test func orbitingUnderneathReversesTheClusterOrder() throws { |
| 708 | let order = try LayerOrder(faceOrders: [[0, 1, 1]], normals: up2) |
| 709 | let above = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), |
| 710 | viewDirection: SIMD3(0, 0, -1)) |
| 711 | let below = order.clusters(positions: stackedSquarePositions(), faces: twoSquares(), |
| 712 | viewDirection: SIMD3(0, 0, 1)) |
| 713 | #expect(above[0].faces == below[0].faces.reversed()) |
| 714 | } |
| 715 | |
| 716 | @Test func facesSeparatedInSpaceFormSeparateClusters() throws { |
| 717 | let order = try LayerOrder(faceOrders: [], normals: up2) |
| 718 | #expect(order.clusters(positions: separatedSquarePositions(), faces: twoSquares(), |
| 719 | viewDirection: SIMD3(0, 0, -1)).count == 2) |
| 720 | } |
| 721 | |
| 722 | @Test func unorderedCoplanarFacesKeepIndexOrder() throws { |
| 723 | let order = try LayerOrder(faceOrders: [], normals: up3) |
| 724 | #expect(order.clusters(positions: threeStackedPositions(), faces: threeSquares(), |
| 725 | viewDirection: SIMD3(0, 0, -1))[0].faces == [0, 1, 2]) |
| 726 | } |
| 727 | |
| 728 | @Test func anArrivingFlapJoinsTheStackItLandsOn() throws { |
| 729 | // letter-sequential step 2 at 179.5°: f2 is half a degree above f0 and f1 |
| 730 | let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2) |
| 731 | let c = try LayerOrder.active(for: step, in: file) |
| 732 | .clusters(positions: i.positions(at: 179.5 / 180), faces: file.facesVertices, |
| 733 | viewDirection: SIMD3(0, 0, -1)) |
| 734 | #expect(c.contains { Set($0.faces) == [0, 1, 2] && $0.faces.last == 2 }) |
| 735 | } |
| 736 | |
| 737 | @Test func aFlapAtThirtyDegreesIsItsOwnCluster() throws { |
| 738 | let (file, step, i) = try interpolatorWithStep("letter-sequential.fold", step: 2) |
| 739 | let c = try LayerOrder.active(for: step, in: file) |
| 740 | .clusters(positions: i.positions(at: 150.0 / 180), faces: file.facesVertices, |
| 741 | viewDirection: SIMD3(0, 0, -1)) |
| 742 | #expect(c.contains { $0.faces == [2] }) |
| 743 | } |
| 744 | |
| 745 | @Test func aFoldAndUnfoldPeakIsOrderedByItsMidFoldOrder() throws { |
| 746 | // quarters step 1 at the peak: f2 lies on f3 and f1 on f0, the moving faces on top |
| 747 | let (file, step, i) = try interpolatorWithStep("quarters.fold", step: 1) |
| 748 | let c = try LayerOrder.active(for: step, in: file) |
| 749 | .clusters(positions: i.positions(at: 0.5), faces: file.facesVertices, |
| 750 | viewDirection: SIMD3(0, 0, -1)) |
| 751 | let left = try #require(c.first { $0.faces.contains(3) }) |
| 752 | #expect(left.faces.firstIndex(of: 2)! > left.faces.firstIndex(of: 3)!) |
| 753 | } |
| 754 | |
| 755 | @Test func cyclicOrderThrows() { |
| 756 | #expect(throws: LayerError.cyclic(cycle: [0, 1, 2])) { |
| 757 | try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], normals: up3) |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | @Test func aRawCycleThatNormalisesAwayIsAccepted() { |
| 762 | // f0 and f2 face down: these triples say f1 < f0, f1 < f2, f2 < f0 |
| 763 | #expect(throws: Never.self) { |
| 764 | try LayerOrder(faceOrders: [[0, 1, 1], [1, 2, 1], [2, 0, 1]], |
| 765 | normals: [SIMD3(0, 0, -1), SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | @Test func consecutiveOrderingsAgreeAwayFromTheMovingFaces() throws { |
| 770 | let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) |
| 771 | for step in try readSteps(file) { |
| 772 | let start = try LayerOrder(faceOrders: file.frames[step.index - 1].faceOrders, |
| 773 | normals: faceNormals(file.frames[step.index - 1], file)) |
| 774 | let end = try LayerOrder(faceOrders: file.frames[step.index].faceOrders, |
| 775 | normals: faceNormals(file.frames[step.index], file)) |
| 776 | #expect(start.agreesWith(end, ignoring: step.movingFaceUnion), "step \(step.index)") |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | @Test func stackDepthCountsTheLayersOverOnePoint() throws { |
| 781 | let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) |
| 782 | #expect(stackDepth(positions: file.frames[2].verticesCoords, faces: file.facesVertices) == 3) |
| 783 | } |
| 784 | ``` |
| 785 | |
| 786 | - [ ] **Step 2: Run tests to verify they fail** |
| 787 | |
| 788 | Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests` |
| 789 | Expected: FAIL. |
| 790 | |
| 791 | - [ ] **Step 3: Implement `LayerOrder`, `CoplanarCluster` and `clusters`** |
| 792 | |
| 793 | `init` normalises each source's triples with that source's normals and throws on a cycle within it, then keeps the raw triples. `agreesWith` compares pairs in the rigid-motion-invariant form Task 2's still-face rule uses. `clusters` links faces by the rule above, then topologically sorts each cluster against `viewDirection`, resolving each triple with `g`'s normal at `positions`, stably on unordered pairs. `stackDepth` overlays the projected outlines of each group of coincident faces, takes one interior point of each cell of that arrangement (its centroid), counts the faces whose open interior contains it, and returns the maximum. Counting at the arrangement's vertices instead would count every face meeting at a crease vertex, so a flat sheet would score its vertex degree. |
| 794 | |
| 795 | - [ ] **Step 4: Run tests to verify they pass** |
| 796 | |
| 797 | Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests` |
| 798 | Expected: PASS. |
| 799 | |
| 800 | - [ ] **Step 5: Commit** |
| 801 | |
| 802 | ```bash |
| 803 | git add Packages/FoldKit |
| 804 | git commit -m "Near-coplanar clustering and view-relative layer order" |
| 805 | ``` |
| 806 | |
| 807 | --- |
| 808 | |
| 809 | ### Task 6: The interpenetration checker |
| 810 | |
| 811 | **Files:** |
| 812 | - Create: `Packages/FoldKit/Sources/Folding/Interpenetration.swift` |
| 813 | - Test: `Packages/FoldKit/Tests/FoldingTests/InterpenetrationTests.swift` |
| 814 | |
| 815 | **Interfaces:** |
| 816 | - Consumes: Task 1–5 types. |
| 817 | - Produces: |
| 818 | - `struct Intersection: Equatable, Sendable { let faceA: Int; let faceB: Int; let t: Double }` |
| 819 | - `func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection]` — one result per intersecting pair, at the first sample `t = k / samples` where they intersect |
| 820 | |
| 821 | "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. |
| 822 | |
| 823 | - [ ] **Step 1: Write the failing tests** |
| 824 | |
| 825 | ```swift |
| 826 | @Test func aCleanFoldHasNoIntersections() throws { |
| 827 | let (file, i) = try interpolator("half.fold", step: 1) |
| 828 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) |
| 829 | } |
| 830 | |
| 831 | @Test func twoFlapsFoldingIntoEachOtherAreDetected() throws { |
| 832 | // both thirds of the letter sheet valley-folded at once: they meet at the midline from ~120° |
| 833 | let (file, i) = try interpolatorForBothThirdsInFront() |
| 834 | #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) |
| 835 | } |
| 836 | |
| 837 | @Test func aFaceSwingingThroughAFaceItSharesAVertexWithIsDetected() throws { |
| 838 | // built in code: fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4); moving triangle |
| 839 | // (0,0,0), (0,2,0), (-1,1,0) hinged on its edge along the y-axis, folding toward +z |
| 840 | let (file, i) = try interpolatorForSharedVertexSweep() |
| 841 | #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) |
| 842 | } |
| 843 | |
| 844 | @Test func coplanarFacesAreNotReportedAsIntersecting() throws { |
| 845 | let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) |
| 846 | let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) |
| 847 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty) |
| 848 | } |
| 849 | |
| 850 | @Test func edgeAdjacentFacesAreNotReportedAsIntersecting() throws { |
| 851 | let (file, i) = try interpolator("quarters.fold", step: 3) |
| 852 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty) |
| 853 | } |
| 854 | |
| 855 | @Test func theReportedParameterIsWhereTheIntersectionBegins() throws { |
| 856 | let (file, i) = try interpolatorForBothThirdsInFront() |
| 857 | let found = interpenetrations(i, faces: file.facesVertices, samples: 64) |
| 858 | #expect(!found.isEmpty) |
| 859 | #expect(found.allSatisfy { abs($0.t - 2.0 / 3) <= 1.0 / 64 }) // the flaps meet at 120° |
| 860 | } |
| 861 | ``` |
| 862 | |
| 863 | - [ ] **Step 2: Run tests to verify they fail** |
| 864 | |
| 865 | Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests` |
| 866 | Expected: FAIL. |
| 867 | |
| 868 | - [ ] **Step 3: Implement `interpenetrations`** |
| 869 | |
| 870 | At each sample of `t`, triangulate the facets and test triangle-triangle intersection pairwise, skipping coplanar pairs. Discard an intersection that lies within 1e-9 of either face's boundary (the face's, not a triangle's, so the fan's internal edges do not count as boundary). An AABB pre-pass keeps the pairwise cost down; the models are small enough that nothing cleverer is needed. |
| 871 | |
| 872 | - [ ] **Step 4: Run tests to verify they pass** |
| 873 | |
| 874 | Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests` |
| 875 | Expected: PASS. |
| 876 | |
| 877 | - [ ] **Step 5: Commit** |
| 878 | |
| 879 | ```bash |
| 880 | git add Packages/FoldKit |
| 881 | git commit -m "Facet interpenetration checker" |
| 882 | ``` |
| 883 | |
| 884 | --- |
| 885 | |
| 886 | ### Task 7: `foldc`, the fold-script compiler |
| 887 | |
| 888 | **Files:** |
| 889 | - Create: `Packages/FoldKit/Sources/foldc/main.swift` |
| 890 | - Create: `Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift` |
| 891 | - Create: `Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift` |
| 892 | - Create: `Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift` |
| 893 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,quarters,occlusion}-cp.fold` — each model fixture's sheet and creases as an editor would export them: no frames, every crease carrying its **final** `M`/`V` assignment from the fixture's last frame (`F` for a crease that ends flat). `compile` resets frame 0 to `F` and 0 |
| 894 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,quarters,occlusion}.foldscript` |
| 895 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{unresolved-crease,angle-out-of-range}.foldscript` |
| 896 | - Test: `Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift` |
| 897 | |
| 898 | **Interfaces:** |
| 899 | - Consumes: Task 1–6 types. |
| 900 | - Produces: |
| 901 | - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script |
| 902 | - `init (FoldScript).init(contentsOf url: URL) throws` |
| 903 | - `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]? }` |
| 904 | - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2<Double>, SIMD2<Double>); case edgeIndex(Int) }` |
| 905 | - `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 |
| 906 | - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile` |
| 907 | - `func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]]` |
| 908 | - `func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]]` |
| 909 | - `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) }` |
| 910 | - `foldc <script.foldscript> -o <model.fold>` — exits 0 on success, 1 naming the first failing step and its defects |
| 911 | |
| 912 | **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. |
| 913 | |
| 914 | 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`. |
| 915 | |
| 916 | Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it. |
| 917 | |
| 918 | macOS only. Never linked into the app. |
| 919 | |
| 920 | - [ ] **Step 1: Write the failing tests** |
| 921 | |
| 922 | ```swift |
| 923 | @Test(arguments: ["half", "mountain", "letter", "letter-sequential", "quarters", "occlusion"]) |
| 924 | func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws { |
| 925 | let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")), |
| 926 | pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold"))) |
| 927 | #expect(structurallyEqual(out, try FoldFile(contentsOf: fixture("\(name).fold")), tolerance: 1e-12)) |
| 928 | #expect(validate(out).isEmpty) |
| 929 | } |
| 930 | |
| 931 | @Test func aCreaseThroughTwoLayersChangesBothEdges() throws { |
| 932 | let out = try compiled("quarters") |
| 933 | #expect(out.frames[3].edgesFoldAngle[8] == 180) |
| 934 | #expect(out.frames[3].edgesFoldAngle[9] == -180) |
| 935 | #expect(out.frames[3].edgesAssignment[9] == .mountain) |
| 936 | } |
| 937 | |
| 938 | @Test func firstCreasedAtStepIsTheFirstStepThatMakesTheCrease() throws { |
| 939 | // x = 1 is made by the fold-and-unfold in step 1 and refolded in step 3 |
| 940 | #expect(try compiled("quarters").edgesFirstCreasedAtStep |
| 941 | == [nil, nil, nil, nil, nil, nil, nil, nil, 1, 1, 2, 2]) |
| 942 | } |
| 943 | |
| 944 | @Test func movingSideIsResolvedFromAContainedPoint() throws { |
| 945 | #expect(try compiled("half").frames[1].step?.axes[0].movingFaces == [1]) |
| 946 | } |
| 947 | |
| 948 | @Test func creaseGivenByEndpointsResolvesToAnEdgeIndex() throws { |
| 949 | #expect(try compiled("half").frames[1].step?.axes[0].edge == 6) |
| 950 | } |
| 951 | |
| 952 | @Test func anOverrideReplacesTheGuessForThatPair() throws { |
| 953 | let file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) |
| 954 | let frame = file.frames[2] |
| 955 | // the guess puts f2 (folded last) above f0; the override puts f0 above f2 |
| 956 | let swapped = try applyOrderOverrides([OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))], |
| 957 | to: frame.faceOrders, frame: frame, |
| 958 | viewpoint: frame.step!.viewpoint, file: file) |
| 959 | #expect(swapped != frame.faceOrders) |
| 960 | #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) } |
| 961 | } |
| 962 | |
| 963 | @Test func anUnresolvedCreaseNamesItsStep() { |
| 964 | #expect(throws: CompileError.unresolvedCrease(step: 2)) { |
| 965 | try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), |
| 966 | pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | @Test func aStepThatFailsValidationNamesItsStep() { |
| 971 | #expect { |
| 972 | try compile(FoldScript(contentsOf: fixture("angle-out-of-range.foldscript")), |
| 973 | pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) |
| 974 | } throws: { if case CompileError.stepFailed(step: 2, _) = $0 { true } else { false } } |
| 975 | } |
| 976 | |
| 977 | @Test func guessedFaceOrdersAreAcyclic() throws { |
| 978 | let out = try compiled("occlusion") |
| 979 | for frame in out.frames { #expect(throws: Never.self) { |
| 980 | try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, out)) } } |
| 981 | } |
| 982 | ``` |
| 983 | |
| 984 | - [ ] **Step 2: Run tests to verify they fail** |
| 985 | |
| 986 | Run: `swift test --package-path Packages/FoldKit --filter CompilerTests` |
| 987 | Expected: FAIL. |
| 988 | |
| 989 | - [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point** |
| 990 | |
| 991 | Resolve each `CreaseRef` to an edge by nearest-endpoint match in crease-pattern coordinates with a 1e-6 tolerance. Resolve `movingSide` to a face by point-in-polygon in the crease pattern, then grow it to its connected component across edges that are not folded this step; the axis edge must lie on that set's boundary. A crease through several layers: every edge that lies on the axis line in the start frame and bounds the moving set is part of the fold, and each gets its own resulting fold angle and assignment. Apply each step's rotations in order to produce the next frame. Guess layer order by placing the moving set on the side of the existing stack it arrived from, its own layers reversed because it has turned over; this is right for plain valley and mountain folds and wrong for anything tucked between layers, which the script corrects with overrides — and the validator's consistency rules (Task 2) report the cases it gets wrong. For a `foldAndUnfold`, compute the order at the peak the same way and write it to `krz:faceOrders_midFold`. After the last step, every crease folded in the last frame must carry the crease pattern's assignment; a mismatch means the script folded something the wrong way. Write JSON with sorted keys so regenerated files diff cleanly. |
| 992 | |
| 993 | - [ ] **Step 4: Run tests to verify they pass** |
| 994 | |
| 995 | Run: `swift test --package-path Packages/FoldKit --filter CompilerTests` |
| 996 | Expected: PASS. |
| 997 | |
| 998 | - [ ] **Step 5: Commit** |
| 999 | |
| 1000 | ```bash |
| 1001 | git add Packages/FoldKit |
| 1002 | git commit -m "foldc: compile a fold script and crease pattern into a FOLD sequence" |
| 1003 | ``` |
| 1004 | |
| 1005 | --- |
| 1006 | |
| 1007 | ### Task 8: `foldlint` and the model catalogue gate |
| 1008 | |
| 1009 | **Files:** |
| 1010 | - Create: `Packages/FoldKit/Sources/foldlint/main.swift` |
| 1011 | - Create: `Packages/FoldKit/Sources/Models/ModelLibrary.swift` |
| 1012 | - Create: `Packages/FoldKit/Sources/Models/Resources/cup.fold` |
| 1013 | - Create: `Models/cup.foldscript` |
| 1014 | - Create: `Models/cup-cp.fold` |
| 1015 | - Create: `docs/authoring/cup.md` |
| 1016 | - Test: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` |
| 1017 | |
| 1018 | **Interfaces:** |
| 1019 | - Consumes: Task 1–7. |
| 1020 | - Produces: |
| 1021 | - `enum ModelLibrary { static func all() throws -> [FoldFile]; static func names() throws -> [String]; static func model(named: String) throws -> FoldFile }` |
| 1022 | - `foldlint <path>...` — exits 0 when clean, 1 with one defect per line |
| 1023 | |
| 1024 | **The cup is the model authored here, not the crane.** Six steps — five folds of one axis each and a turn-over — no reverse folds, at most six layers where the corner flaps cross. It exercises script, compile, validate, interpolate and the catalogue gate end to end without exercising coupled steps or deep stacks at the same time. The version authored folds the top flaps down — the front one, then after the turn-over the back one — rather than tucking them into the pocket, and it ends flat. Step 1's instruction starts "Valley fold"; Task 14's accessibility test reads it. |
| 1025 | |
| 1026 | Its crease pattern and `.foldscript` are committed next to the generated `.fold`, so the model regenerates rather than only being editable. `docs/authoring/cup.md` records the crease pattern's provenance and every layer-order override and why. |
| 1027 | |
| 1028 | - [ ] **Step 1: Write the failing tests** |
| 1029 | |
| 1030 | ```swift |
| 1031 | @Test func everyShippedModelValidates() throws { |
| 1032 | for file in try ModelLibrary.all() { #expect(validate(file).isEmpty, "\(file.fileTitle ?? "?")") } |
| 1033 | } |
| 1034 | |
| 1035 | @Test func everyShippedModelReadsItsSteps() throws { |
| 1036 | for file in try ModelLibrary.all() { |
| 1037 | #expect(try readSteps(file).count == file.stepCount) |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | @Test func noShippedModelStretchesAtAnyStep() throws { |
| 1042 | for file in try ModelLibrary.all() { |
| 1043 | for step in try readSteps(file) { |
| 1044 | let i = FoldInterpolator(file: file, step: step) |
| 1045 | for t in stride(from: 0.0, through: 1.0, by: 1.0 / 64) { |
| 1046 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-9, |
| 1047 | "\(file.fileTitle ?? "?") step \(step.index) t \(t)") |
| 1048 | } |
| 1049 | } |
| 1050 | } |
| 1051 | } |
| 1052 | |
| 1053 | @Test func noShippedModelInterpenetratesAtAnyStep() throws { |
| 1054 | for file in try ModelLibrary.all() { |
| 1055 | for step in try readSteps(file) { |
| 1056 | let i = FoldInterpolator(file: file, step: step) |
| 1057 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty, |
| 1058 | "\(file.fileTitle ?? "?") step \(step.index)") |
| 1059 | } |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | @Test func everyModelIsAttributedAsTraditional() throws { |
| 1064 | for file in try ModelLibrary.all() { #expect(file.fileAuthor == "Traditional") } |
| 1065 | } |
| 1066 | |
| 1067 | @Test func everyShippedModelRegeneratesFromItsScript() throws { |
| 1068 | for name in try ModelLibrary.names() { |
| 1069 | let recompiled = try compile(FoldScript(contentsOf: script(name)), |
| 1070 | pattern: FoldFile(contentsOf: pattern(name))) |
| 1071 | #expect(structurallyEqual(recompiled, try ModelLibrary.model(named: name), tolerance: 1e-12), "\(name)") |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | @Test func theCatalogueContainsTheCup() throws { |
| 1076 | #expect(try ModelLibrary.names() == ["cup"]) |
| 1077 | } |
| 1078 | |
| 1079 | @Test func theCupContainsATurnOverStep() throws { |
| 1080 | #expect(try readSteps(ModelLibrary.model(named: "cup")).contains { $0.kind == .turnOver }) |
| 1081 | } |
| 1082 | |
| 1083 | @Test func foldlintExitsNonZeroOnADefectiveFile() throws { |
| 1084 | #expect(try runFoldlint(on: fixture("bad-index.fold")).exitCode == 1) |
| 1085 | } |
| 1086 | ``` |
| 1087 | |
| 1088 | - [ ] **Step 2: Run tests to verify they fail** |
| 1089 | |
| 1090 | Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests` |
| 1091 | Expected: FAIL. |
| 1092 | |
| 1093 | - [ ] **Step 3: Implement `ModelLibrary`, `foldlint`, and author the cup's crease pattern and script** |
| 1094 | |
| 1095 | Iterate the cup against `foldc` and `foldlint` until clean, adding `faceOrders` overrides to the script where the interpenetration checker or the validator's layer-order rules object. The cup's turn-over step is what Task 13's gesture will be built against, so it must be present and correct here. |
| 1096 | |
| 1097 | - [ ] **Step 4: Run tests to verify they pass** |
| 1098 | |
| 1099 | Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests` |
| 1100 | Expected: PASS. |
| 1101 | |
| 1102 | - [ ] **Step 5: Commit** |
| 1103 | |
| 1104 | ```bash |
| 1105 | git add Packages/FoldKit Models docs/authoring |
| 1106 | git commit -m "Model library, foldlint and the cup" |
| 1107 | ``` |
| 1108 | |
| 1109 | --- |
| 1110 | |
| 1111 | ### Task 9: Diagram generation with layer-aware occlusion |
| 1112 | |
| 1113 | **Files:** |
| 1114 | - Create: `Packages/FoldKit/Sources/Notation/DiagramStyle.swift` |
| 1115 | - Create: `Packages/FoldKit/Sources/Notation/DiagramBuilder.swift` |
| 1116 | - Create: `Packages/FoldKit/Sources/Notation/EdgeOcclusion.swift` |
| 1117 | - Test: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift` |
| 1118 | - Test: `Packages/FoldKit/Tests/NotationTests/Snapshots/` (golden images, and `NOTATION.md` recording each symbol choice and its source) |
| 1119 | |
| 1120 | **Interfaces:** |
| 1121 | - Consumes: Task 1–5 and Task 8 (the cup). |
| 1122 | - Produces: |
| 1123 | - `enum DiagramLine: Equatable, Sendable { case solid, light, dashed, dashDot }` |
| 1124 | - `enum DiagramArrow: Equatable, Sendable { case valleyFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>); case mountainFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>); case foldAndUnfold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>, mountain: Bool); case technique(StepTechnique, at: SIMD2<Double>, toward: SIMD2<Double>); case turnOver(TurnOverAxis); case rotate(degrees: Double); case repeatMark(of: Int) }` |
| 1125 | - `struct DiagramEdge: Equatable, Sendable { let edge: Int; let from: SIMD2<Double>; let to: SIMD2<Double>; let style: DiagramLine }` |
| 1126 | - `struct Diagram: Equatable, Sendable { let edges: [DiagramEdge]; let arrows: [DiagramArrow] }` |
| 1127 | - `func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram` — draws frame `step.index − 1` with step `step.index`'s creases and arrows |
| 1128 | - `func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) -> [(SIMD2<Double>, SIMD2<Double>)]` |
| 1129 | - `struct DiagramStyle: Sendable` |
| 1130 | |
| 1131 | The view is orthographic from the step's authored `viewpoint` and does **not** rotate when the model is orbited. This task owns Review Focus item 5. |
| 1132 | |
| 1133 | Edge classes, for the diagram of step n drawing frame n − 1: `B` edges and creases folded in frame n − 1 are solid; creases made earlier and flat again are light; step n's creases (every edge coincident with an axis) are dashed for a valley and dash-dot for a mountain **as seen from the viewpoint**: the axis's turn `Δ` (`endAngle − startAngle`, or `peakAngle − startAngle` for `foldAndUnfold`) moves the moving face toward its own normal, so the fold is a valley as seen when `sign(Δ) · sign(n · eye) > 0`, with `n` the moving face's normal in frame n − 1. FOLD's assignment is relative to each face's own normal and cannot be used: on a flipped layer, or after a turn-over, it names the opposite fold, and coincident edges on different layers disagree; creases whose `edges_krz:firstCreasedAtStep` is later than n are not drawn. Arrows: a `plain` step gets one valley-fold or mountain-fold arrow per axis, by the same as-seen rule; a named technique gets that technique's arrows from the reference and no per-axis arrows; reorientation and repeat steps get their symbols. |
| 1134 | |
| 1135 | Reference, per the spec: Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by OrigamiUSA; where they differ OrigamiUSA's is used, and the choice is recorded in `Snapshots/NOTATION.md`. |
| 1136 | |
| 1137 | - [ ] **Step 1: Write the failing tests** |
| 1138 | |
| 1139 | ```swift |
| 1140 | @Test func valleyCreaseOfThisStepIsDashed() throws { |
| 1141 | #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .dashed }.map(\.edge) == [6]) |
| 1142 | } |
| 1143 | |
| 1144 | @Test func mountainCreaseOfThisStepIsDashDot() throws { |
| 1145 | #expect(try diagram("mountain.fold", step: 1).edges.filter { $0.style == .dashDot }.map(\.edge) == [6]) |
| 1146 | } |
| 1147 | |
| 1148 | @Test func valleyAndMountainAreAsSeenNotAsAssigned() throws { |
| 1149 | // quarters step 3 folds both layers; the top layer is flipped, so its edge e9 is |
| 1150 | // assigned M, but the fold is a valley as seen and nothing is dash-dot |
| 1151 | let d = try diagram("quarters.fold", step: 3) |
| 1152 | #expect(d.edges.contains { $0.style == .dashed }) |
| 1153 | #expect(!d.edges.contains { $0.style == .dashDot }) |
| 1154 | #expect(d.arrows.contains { if case .valleyFold = $0 { true } else { false } }) |
| 1155 | } |
| 1156 | |
| 1157 | @Test func anEdgeUnderASeamIsHidden() throws { |
| 1158 | // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2 |
| 1159 | #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 }) |
| 1160 | } |
| 1161 | |
| 1162 | @Test func boundaryEdgesAreSolid() throws { |
| 1163 | #expect(try diagram("half.fold", step: 1).edges.filter { $0.style == .solid }.count == 6) |
| 1164 | } |
| 1165 | |
| 1166 | @Test func aCreaseMadeEarlierAndFlatAgainIsLight() throws { |
| 1167 | // quarters step 2 draws frame 1, after the fold-and-unfold on x = 1 |
| 1168 | #expect(Set(try diagram("quarters.fold", step: 2).edges.filter { $0.style == .light }.map(\.edge)) == [8, 9]) |
| 1169 | } |
| 1170 | |
| 1171 | @Test func creasesNotYetMetAreNotDrawnAtAll() throws { |
| 1172 | // frame 0 carries the y = 1 creases too; step 1's diagram must not show them |
| 1173 | #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) }) |
| 1174 | } |
| 1175 | |
| 1176 | @Test func edgesOccludedByLayersAboveThemAreOmitted() throws { |
| 1177 | // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip |
| 1178 | #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 }) |
| 1179 | } |
| 1180 | |
| 1181 | @Test func anEdgePartlyOccludedIsClippedNotDropped() throws { |
| 1182 | // f0's raw edge from (0,2) to (2,2) is covered for x in [1, 2] |
| 1183 | let segments = try visibleSegmentsOf("occlusion.fold", edge: 7, inFrame: 2) |
| 1184 | #expect(segments.count == 1) |
| 1185 | #expect(abs(segmentLength(segments[0]) - 1) < 1e-9) |
| 1186 | } |
| 1187 | |
| 1188 | @Test func aPlainMultiAxisStepGetsOneArrowPerAxis() throws { |
| 1189 | let arrows = try diagram("letter.fold", step: 1).arrows |
| 1190 | #expect(arrows.filter { if case .valleyFold = $0 { true } else { false } }.count == 1) |
| 1191 | #expect(arrows.filter { if case .mountainFold = $0 { true } else { false } }.count == 1) |
| 1192 | } |
| 1193 | |
| 1194 | @Test func aTechniqueStepGetsItsOwnArrowsNotOnePerAxis() throws { |
| 1195 | let arrows = try diagram("letter-technique.fold", step: 1).arrows |
| 1196 | #expect(arrows.filter { if case .technique(.insideReverse, _, _) = $0 { true } else { false } }.count == 1) |
| 1197 | #expect(!arrows.contains { if case .valleyFold = $0 { true } else if case .mountainFold = $0 { true } else { false } }) |
| 1198 | } |
| 1199 | |
| 1200 | @Test func foldAndUnfoldStepGetsTheReturnHead() throws { |
| 1201 | #expect(try diagram("quarters.fold", step: 1).arrows |
| 1202 | .contains { if case .foldAndUnfold = $0 { true } else { false } }) |
| 1203 | } |
| 1204 | |
| 1205 | @Test func turnOverStepCarriesTheTurnOverSymbol() throws { |
| 1206 | #expect(try diagram("half.fold", step: 2).arrows.contains(.turnOver(.vertical))) |
| 1207 | } |
| 1208 | |
| 1209 | @Test func rotateStepCarriesItsDegrees() throws { |
| 1210 | #expect(try diagram("half.fold", step: 3).arrows.contains(.rotate(degrees: 90))) |
| 1211 | } |
| 1212 | |
| 1213 | @Test func aRepeatedStepCarriesTheRepeatMark() throws { |
| 1214 | #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1))) |
| 1215 | } |
| 1216 | |
| 1217 | @Test func everyStepMatchesItsGoldenImage() throws { |
| 1218 | for name in ["half", "mountain", "letter", "letter-sequential", "quarters", "occlusion"] { |
| 1219 | let file = try FoldFile(contentsOf: fixture("\(name).fold")) |
| 1220 | for step in try readSteps(file) { |
| 1221 | try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)") |
| 1222 | } |
| 1223 | } |
| 1224 | let cup = try ModelLibrary.model(named: "cup") |
| 1225 | for step in try readSteps(cup) { |
| 1226 | try expectSnapshot(render(buildDiagram(file: cup, step: step)), named: "cup-\(step.index)") |
| 1227 | } |
| 1228 | } |
| 1229 | ``` |
| 1230 | |
| 1231 | - [ ] **Step 2: Run tests to verify they fail** |
| 1232 | |
| 1233 | Run: `swift test --package-path Packages/FoldKit --filter DiagramTests` |
| 1234 | Expected: FAIL. |
| 1235 | |
| 1236 | - [ ] **Step 3: Implement the types, `buildDiagram` and `visibleSegments`** |
| 1237 | |
| 1238 | Project through the viewpoint's orthographic matrix. Classify each edge as above. Clip each edge against the **union** of the projected faces `order` places above either of the edge's incident faces, and emit the surviving segments, drawing coincident segments once. Clipping against each face separately would keep an edge lying under the seam between two adjacent upper faces — e8 in quarters frame 2 lies on the boundary of f3 and of f2 but inside their union. An edge on the outer boundary of that union is not hidden. Subdivision edges are never drawn. Golden images are generated once, inspected by eye against the reference, then committed. |
| 1239 | |
| 1240 | - [ ] **Step 4: Run tests to verify they pass** |
| 1241 | |
| 1242 | Run: `swift test --package-path Packages/FoldKit --filter DiagramTests` |
| 1243 | Expected: PASS. |
| 1244 | |
| 1245 | - [ ] **Step 5: Commit** |
| 1246 | |
| 1247 | ```bash |
| 1248 | git add Packages/FoldKit |
| 1249 | git commit -m "Diagram generation with layer-aware edge occlusion" |
| 1250 | ``` |
| 1251 | |
| 1252 | --- |
| 1253 | |
| 1254 | ### Task 10: The Metal paper renderer |
| 1255 | |
| 1256 | **Files:** |
| 1257 | - Create: `Packages/FoldKit/Sources/Folding/Camera.swift` |
| 1258 | - Create: `Packages/FoldKit/Sources/Renderer/PaperRenderer.swift` |
| 1259 | - Create: `Packages/FoldKit/Sources/Renderer/Shaders.metal` |
| 1260 | - Test: `Packages/FoldKit/Tests/FoldingTests/CameraTests.swift` |
| 1261 | - Test: `Packages/FoldKit/Tests/RendererTests/PaperRendererTests.swift` |
| 1262 | |
| 1263 | **Interfaces:** |
| 1264 | - Consumes: Task 1–5. |
| 1265 | - Produces: |
| 1266 | - `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` |
| 1267 | - `func (Camera).viewProjection(aspect: Double) -> simd_double4x4` — view and perspective projection combined, to clip space |
| 1268 | - `var (Camera).viewDirection: SIMD3<Double> { get }` — unit vector from `eye` toward `target` |
| 1269 | - `final class PaperRenderer { init(device: MTLDevice) throws }` |
| 1270 | - `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 |
| 1271 | |
| 1272 | 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: |
| 1273 | |
| 1274 | - clusters come from Task 5, already resolved against `camera.viewDirection`; |
| 1275 | - each cluster is drawn back-to-front in its order with depth test on (less-or-equal) and depth **writes off**, so stacked faces resolve by order rather than by z; |
| 1276 | - then the same cluster is drawn again **depth-only** (colour writes off), so that clusters drawn after it are hidden behind it. Without this pass a cluster writes no depth and anything drawn later draws over it. |
| 1277 | |
| 1278 | Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3. |
| 1279 | |
| 1280 | SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4. |
| 1281 | |
| 1282 | - [ ] **Step 1: Write the failing tests** |
| 1283 | |
| 1284 | 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]]`). |
| 1285 | |
| 1286 | ```swift |
| 1287 | @Test func viewProjectionMapsTheTargetToTheCentreOfClipSpace() { |
| 1288 | let c = Camera(eye: SIMD3(0, 0, 5), target: .zero, up: SIMD3(0, 1, 0), fieldOfView: .pi / 4) |
| 1289 | let p = c.viewProjection(aspect: 1.5) * SIMD4(0, 0, 0, 1) |
| 1290 | #expect(abs(p.x / p.w) < 1e-12 && abs(p.y / p.w) < 1e-12) |
| 1291 | #expect(c.viewDirection == SIMD3(0, 0, -1)) |
| 1292 | } |
| 1293 | |
| 1294 | @Test func coplanarStackedFacesDoNotZFight() throws { |
| 1295 | let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [1, 0])], |
| 1296 | camera: cameraAbove(), faceColours: [red, green]) |
| 1297 | #expect(uniqueColours(pixels) == [red]) |
| 1298 | } |
| 1299 | |
| 1300 | @Test func clusterOrderDeterminesWhichCoplanarFaceIsVisible() throws { |
| 1301 | let pixels = try renderToPixels(stackedCoplanarSquares(), clusters: [CoplanarCluster(faces: [0, 1])], |
| 1302 | camera: cameraAbove(), faceColours: [red, green]) |
| 1303 | #expect(uniqueColours(pixels) == [green]) |
| 1304 | } |
| 1305 | |
| 1306 | @Test func nearlyCoplanarFacesDoNotZFight() throws { |
| 1307 | // face 0 tilted 1° about its left edge, resting on face 1, in one cluster |
| 1308 | let pixels = try renderToPixels(squareOverATiltedSquare(degrees: 1), clusters: [CoplanarCluster(faces: [1, 0])], |
| 1309 | camera: cameraAbove(), faceColours: [red, green]) |
| 1310 | #expect(uniqueColours(pixels) == [red]) |
| 1311 | } |
| 1312 | |
| 1313 | @Test func facesSeparatedInSpaceAreResolvedByDepthNotByOrder() throws { |
| 1314 | // face 0 is nearer the camera but drawn first |
| 1315 | let pixels = try renderToPixels(separatedSquares(), |
| 1316 | clusters: [CoplanarCluster(faces: [0]), CoplanarCluster(faces: [1])], |
| 1317 | camera: cameraAbove(), faceColours: [red, green]) |
| 1318 | #expect(dominantColour(pixels) == red) |
| 1319 | } |
| 1320 | |
| 1321 | @Test func aStackDrawnFirstStillHidesAFaceBehindItDrawnLater() throws { |
| 1322 | // faces 0 and 1 stacked near the camera, face 2 farther away and drawn last |
| 1323 | let pixels = try renderToPixels(nearStackAndFarSquare(), |
| 1324 | clusters: [CoplanarCluster(faces: [1, 0]), CoplanarCluster(faces: [2])], |
| 1325 | camera: cameraAbove(), faceColours: [red, green, blue]) |
| 1326 | #expect(dominantColour(pixels) == red) |
| 1327 | } |
| 1328 | |
| 1329 | @Test func orbitingUnderneathShowsTheBottomOfTheStack() throws { |
| 1330 | // clusters computed by Task 5 for each camera, as the app does |
| 1331 | let above = try renderStackWithComputedClusters(camera: cameraAbove(), faceColours: [red, green]) |
| 1332 | let below = try renderStackWithComputedClusters(camera: cameraBelow(), faceColours: [red, green]) |
| 1333 | #expect(uniqueColours(above) == [red]) |
| 1334 | #expect(uniqueColours(below) == [green]) |
| 1335 | } |
| 1336 | |
| 1337 | @Test func backOfPaperRendersInTheBackColour() throws { |
| 1338 | let pixels = try renderToPixels(singleSquareFacingAway(), clusters: [CoplanarCluster(faces: [0])], |
| 1339 | camera: cameraAbove()) |
| 1340 | #expect(uniqueColours(pixels) == [backColour]) |
| 1341 | } |
| 1342 | ``` |
| 1343 | |
| 1344 | These require a Metal device; the target skips when `MTLCreateSystemDefaultDevice()` is nil. `uniqueColours` ignores the background. |
| 1345 | |
| 1346 | - [ ] **Step 2: Run tests to verify they fail** |
| 1347 | |
| 1348 | Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"` |
| 1349 | Expected: FAIL. |
| 1350 | |
| 1351 | - [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders** |
| 1352 | |
| 1353 | 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. |
| 1354 | |
| 1355 | - [ ] **Step 4: Run tests to verify they pass** |
| 1356 | |
| 1357 | Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"` |
| 1358 | Expected: PASS. |
| 1359 | |
| 1360 | - [ ] **Step 5: Commit** |
| 1361 | |
| 1362 | ```bash |
| 1363 | git add Packages/FoldKit |
| 1364 | git commit -m "Metal paper renderer with hybrid depth and cluster ordering" |
| 1365 | ``` |
| 1366 | |
| 1367 | --- |
| 1368 | |
| 1369 | ### Task 11: App shell, model list and the step layout |
| 1370 | |
| 1371 | **Files:** |
| 1372 | - Create: `App/project.yml` |
| 1373 | - Create: `App/Sources/FoldApp.swift` |
| 1374 | - Create: `App/Sources/ModelListView.swift` |
| 1375 | - Create: `App/Sources/StepView.swift` |
| 1376 | - Create: `App/Sources/DiagramCanvas.swift` |
| 1377 | - Create: `App/Sources/PaperView.swift` |
| 1378 | - Create: `App/Sources/Info.plist` |
| 1379 | - Test: `App/UITests/StepNavigationTests.swift` |
| 1380 | |
| 1381 | **Interfaces:** |
| 1382 | - Consumes: `ModelLibrary`, `readSteps`, `FoldInterpolator`, `LayerOrder`, `buildDiagram`, `PaperRenderer`. |
| 1383 | - Produces: |
| 1384 | - `struct ModelListView: View` |
| 1385 | - `struct StepView: View` — `init(model: FoldFile, step: Int)`, step counted from 1 |
| 1386 | - `struct DiagramCanvas: View` — `init(diagram: Diagram, style: DiagramStyle)` |
| 1387 | - `struct PaperView: View` — `init(positions: [SIMD3<Double>], faces: [[Int]], clusters: [CoplanarCluster], camera: Camera)`, an `MTKView` wrapped for SwiftUI |
| 1388 | |
| 1389 | `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`. |
| 1390 | |
| 1391 | - [ ] **Step 1: Write the failing UI tests** |
| 1392 | |
| 1393 | ```swift |
| 1394 | func testCupOpensAtStepOne() { |
| 1395 | let app = XCUIApplication(); app.launch() |
| 1396 | app.buttons["Cup"].tap() |
| 1397 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") |
| 1398 | } |
| 1399 | |
| 1400 | func testStepNeverAdvancesWithoutTheUserCompletingTheFold() { |
| 1401 | let app = XCUIApplication(); app.launch() |
| 1402 | app.buttons["Cup"].tap() |
| 1403 | sleep(3) |
| 1404 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") |
| 1405 | } |
| 1406 | |
| 1407 | func testTheDiagramIsCaptionedWithTheStepsInstruction() { |
| 1408 | let app = XCUIApplication(); app.launch() |
| 1409 | app.buttons["Cup"].tap() |
| 1410 | XCTAssertTrue(app.staticTexts["diagram.caption"].label.hasPrefix("Valley fold")) |
| 1411 | } |
| 1412 | ``` |
| 1413 | |
| 1414 | Completing a step needs Task 12's gesture and orbiting needs Task 14's; their tests are written there. |
| 1415 | |
| 1416 | - [ ] **Step 2: Run tests to verify they fail** |
| 1417 | |
| 1418 | Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test` |
| 1419 | Expected: FAIL — no such project. |
| 1420 | |
| 1421 | - [ ] **Step 3: Generate the project and implement the shell, list, step layout and both canvases** |
| 1422 | |
| 1423 | - [ ] **Step 4: Run tests to verify they pass** |
| 1424 | |
| 1425 | Run: `xcodegen generate --spec App/project.yml`, then as above. |
| 1426 | Expected: PASS. |
| 1427 | |
| 1428 | - [ ] **Step 5: Commit** |
| 1429 | |
| 1430 | ```bash |
| 1431 | git add App |
| 1432 | git commit -m "App shell, model list and step layout" |
| 1433 | ``` |
| 1434 | |
| 1435 | --- |
| 1436 | |
| 1437 | ### Task 12: The fold gesture |
| 1438 | |
| 1439 | **Files:** |
| 1440 | - Create: `App/Sources/FoldGesture.swift` |
| 1441 | - Create: `Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift` |
| 1442 | - Test: `Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift` |
| 1443 | - Test: `App/UITests/FoldGestureTests.swift` |
| 1444 | |
| 1445 | **Interfaces:** |
| 1446 | - Consumes: Task 3, 4 types; `Camera` (in `Folding`) from Task 10. |
| 1447 | - Produces: |
| 1448 | - `struct FoldParameterMapping: Sendable { init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) }` |
| 1449 | - `func (FoldParameterMapping).parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double` — clamped to 0...1 |
| 1450 | - `var (FoldParameterMapping).path: [SIMD2<Double>] { get }` — the first moving set's centroid in screen points at 129 samples of `t` |
| 1451 | - `var (FoldParameterMapping).isDegenerate: Bool { get }` — path under 8 points long |
| 1452 | |
| 1453 | This task owns Review Focus item 4. |
| 1454 | |
| 1455 | 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). |
| 1456 | |
| 1457 | - [ ] **Step 1: Write the failing tests** |
| 1458 | |
| 1459 | ```swift |
| 1460 | @Test func theFacetTracksTheFinger() throws { |
| 1461 | let m = try mapping("half.fold", step: 1) // viewed from above |
| 1462 | let target = m.path[32] // t = 0.25 |
| 1463 | let t = m.parameter(grabbedAt: m.path[0], translation: target - m.path[0], current: 0) |
| 1464 | #expect(abs(t - 0.25) < 0.01) |
| 1465 | } |
| 1466 | |
| 1467 | @Test func dragPerpendicularToThePathDoesNotAdvanceTheFold() throws { |
| 1468 | let m = try mapping("half.fold", step: 1) |
| 1469 | let along = simd_normalize(m.path[1] - m.path[0]) |
| 1470 | let perp = SIMD2(-along.y, along.x) |
| 1471 | #expect(m.parameter(grabbedAt: m.path[0], translation: perp * 50, current: 0) < 0.01) |
| 1472 | } |
| 1473 | |
| 1474 | @Test func parameterIsClampedToUnitRange() throws { |
| 1475 | let m = try mapping("half.fold", step: 1) |
| 1476 | let along = simd_normalize(m.path[128] - m.path[0]) |
| 1477 | #expect(m.parameter(grabbedAt: m.path[0], translation: along * 100_000, current: 0) == 1) |
| 1478 | #expect(m.parameter(grabbedAt: m.path[0], translation: along * -100_000, current: 0) == 0) |
| 1479 | } |
| 1480 | |
| 1481 | @Test func headOnFoldIsReportedDegenerate() throws { |
| 1482 | #expect(try mappingForFoldTowardTheCamera().isDegenerate) |
| 1483 | } |
| 1484 | |
| 1485 | @Test func degenerateMappingFallsBackToVerticalDrag() throws { |
| 1486 | let m = try mappingForFoldTowardTheCamera() |
| 1487 | #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 50), current: 0) > 0.1) |
| 1488 | } |
| 1489 | |
| 1490 | @Test func theMappingIsNeverInfinitelySensitive() throws { |
| 1491 | let m = try mappingForFoldTowardTheCamera() |
| 1492 | #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2) |
| 1493 | } |
| 1494 | |
| 1495 | @Test func foldAndUnfoldGoesOutThenBack() throws { |
| 1496 | let m = try mapping("quarters.fold", step: 1) |
| 1497 | let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0) |
| 1498 | #expect(abs(atPeak - 0.5) < 0.01) |
| 1499 | let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak) |
| 1500 | #expect(back > 0.99) |
| 1501 | } |
| 1502 | ``` |
| 1503 | |
| 1504 | `App/UITests/FoldGestureTests.swift`: |
| 1505 | |
| 1506 | ```swift |
| 1507 | func testCompletingAStepAdvancesToTheNext() { |
| 1508 | let app = XCUIApplication(); app.launch() |
| 1509 | app.buttons["Cup"].tap() |
| 1510 | completeCurrentFold(app) // drag along the moving facet's path to t = 1, then lift |
| 1511 | XCTAssertEqual(app.staticTexts["step.index"].label, "2") |
| 1512 | } |
| 1513 | |
| 1514 | func testReleasingPartwayLeavesTheStepWhereItIs() { |
| 1515 | let app = XCUIApplication(); app.launch() |
| 1516 | app.buttons["Cup"].tap() |
| 1517 | dragCurrentFold(app, to: 0.5) |
| 1518 | let released = app.otherElements["fold.paper"].value as? String |
| 1519 | sleep(2) |
| 1520 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") |
| 1521 | XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released) |
| 1522 | XCTAssertNotEqual(released, "0%") |
| 1523 | } |
| 1524 | ``` |
| 1525 | |
| 1526 | The paper view's accessibility value is the fold parameter as a percentage. |
| 1527 | |
| 1528 | - [ ] **Step 2: Run tests to verify they fail** |
| 1529 | |
| 1530 | Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests` |
| 1531 | Expected: FAIL. |
| 1532 | |
| 1533 | - [ ] **Step 3: Implement `FoldParameterMapping` and `FoldGesture`** |
| 1534 | |
| 1535 | The step completes when the parameter is 1 and the finger lifts. Releasing below 1 leaves the paper where it is. |
| 1536 | |
| 1537 | - [ ] **Step 4: Run tests to verify they pass** |
| 1538 | |
| 1539 | Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`, then `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/FoldGestureTests` |
| 1540 | Expected: PASS. |
| 1541 | |
| 1542 | - [ ] **Step 5: Commit** |
| 1543 | |
| 1544 | ```bash |
| 1545 | git add App Packages |
| 1546 | git commit -m "Fold gesture tracking the moving facet's screen path" |
| 1547 | ``` |
| 1548 | |
| 1549 | --- |
| 1550 | |
| 1551 | ### Task 13: The drag for turn-over and rotate steps |
| 1552 | |
| 1553 | **Files:** |
| 1554 | - Create: `App/Sources/ReorientGesture.swift` |
| 1555 | - Test: `App/UITests/ReorientGestureTests.swift` |
| 1556 | |
| 1557 | **Interfaces:** |
| 1558 | - Consumes: `FoldStep.kind`, `FoldInterpolator.positions(at:)`. |
| 1559 | - Produces: |
| 1560 | - `struct ReorientGesture` — a one-finger horizontal drag across the model drives `t` of a `turnOver` or `rotate` step as the drag's horizontal distance over the model's on-screen width, clamped to 0...1 |
| 1561 | |
| 1562 | A `turnOver` has no crease and no fold angle, so the fold drag has nothing to drive — and every one of the v1 models needs turn-overs, the crane most of all. The model reorients, not the camera: the diagram's viewpoint is fixed and the reader's mental model is of turning the paper over in their hands. The parameter follows the finger like a fold does; a flick does not complete the step, because the app never advances `t` on its own. |
| 1563 | |
| 1564 | - [ ] **Step 1: Write the failing tests** |
| 1565 | |
| 1566 | ```swift |
| 1567 | func testDraggingAcrossTheModelCompletesATurnOverStep() { |
| 1568 | let app = XCUIApplication(); app.launch() |
| 1569 | app.buttons["Cup"].tap() |
| 1570 | advanceToFirstTurnOverStep(app) |
| 1571 | let before = app.staticTexts["step.index"].label |
| 1572 | dragAcross(app.otherElements["fold.paper"]) |
| 1573 | XCTAssertNotEqual(before, app.staticTexts["step.index"].label) |
| 1574 | } |
| 1575 | |
| 1576 | func testFoldDragDoesNothingOnATurnOverStep() { |
| 1577 | // a fold drag on a turnOver step must leave step.index unchanged |
| 1578 | } |
| 1579 | |
| 1580 | func testReorientDragDoesNothingOnAFoldStep() { |
| 1581 | // a horizontal drag that does not follow the fold path must leave step.index unchanged |
| 1582 | } |
| 1583 | |
| 1584 | func testTurnOverReorientsTheModelNotTheCamera() { |
| 1585 | // midway through the turn-over drag the diagram is unchanged; after it, the paper |
| 1586 | // shows its back colour |
| 1587 | } |
| 1588 | ``` |
| 1589 | |
| 1590 | - [ ] **Step 2: Run tests to verify they fail** |
| 1591 | |
| 1592 | Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/ReorientGestureTests` |
| 1593 | Expected: FAIL. |
| 1594 | |
| 1595 | - [ ] **Step 3: Implement `ReorientGesture`** |
| 1596 | |
| 1597 | Gate the gesture on the current step's `kind`, so a fold drag and a reorient drag are never both live. |
| 1598 | |
| 1599 | - [ ] **Step 4: Run tests to verify they pass** |
| 1600 | |
| 1601 | Run: as above. |
| 1602 | Expected: PASS. |
| 1603 | |
| 1604 | - [ ] **Step 5: Commit** |
| 1605 | |
| 1606 | ```bash |
| 1607 | git add App |
| 1608 | git commit -m "Drag gesture for turn-over and rotate steps" |
| 1609 | ``` |
| 1610 | |
| 1611 | --- |
| 1612 | |
| 1613 | ### Task 14: Orbit, zoom, accessibility and release assets |
| 1614 | |
| 1615 | **Files:** |
| 1616 | - Create: `App/Sources/OrbitGesture.swift` |
| 1617 | - Create: `App/Resources/PrivacyInfo.xcprivacy` |
| 1618 | - Create: `App/UITests/AccessibilityAuditTests.swift` |
| 1619 | - Create: `AppStore/rights-basis.md` |
| 1620 | - Create: `scripts/take-screenshots.sh` |
| 1621 | |
| 1622 | **Interfaces:** |
| 1623 | - Consumes: `Camera`, `PaperView`, `FoldStep.instruction`. |
| 1624 | - Produces: |
| 1625 | - `struct OrbitGesture` — two-finger drag to `Camera` orbit, pinch to field of view |
| 1626 | |
| 1627 | A folding model cannot be described by a static label, so the paper view's accessibility label is the step's authored `instruction`. `AppStore/rights-basis.md` records that every shipped model is traditional and why that matters. |
| 1628 | |
| 1629 | - [ ] **Step 1: Write the failing tests** |
| 1630 | |
| 1631 | ```swift |
| 1632 | func testEveryScreenPassesTheAccessibilityAuditAtDefaultTextSize() throws { |
| 1633 | let app = XCUIApplication(); app.launch() |
| 1634 | try app.performAccessibilityAudit() |
| 1635 | app.buttons["Cup"].tap() |
| 1636 | try app.performAccessibilityAudit() |
| 1637 | } |
| 1638 | |
| 1639 | func testEveryScreenPassesTheAuditAtTheLargestTextSize() throws { |
| 1640 | let app = XCUIApplication() |
| 1641 | app.launchArguments += ["-UIPreferredContentSizeCategoryName", |
| 1642 | "UICTContentSizeCategoryAccessibilityXXXL"] |
| 1643 | app.launch() |
| 1644 | try app.performAccessibilityAudit() |
| 1645 | app.buttons["Cup"].tap() |
| 1646 | try app.performAccessibilityAudit() |
| 1647 | } |
| 1648 | |
| 1649 | func testPaperViewDescribesTheCurrentStepInWords() { |
| 1650 | let app = XCUIApplication(); app.launch() |
| 1651 | app.buttons["Cup"].tap() |
| 1652 | XCTAssertTrue(app.otherElements["fold.paper"].label.hasPrefix("Valley fold")) |
| 1653 | } |
| 1654 | |
| 1655 | func testTwoFingerDragOrbitsWithoutAdvancingTheFold() { |
| 1656 | let app = XCUIApplication(); app.launch() |
| 1657 | app.buttons["Cup"].tap() |
| 1658 | let paper = app.otherElements["fold.paper"] |
| 1659 | let before = paper.value as? String |
| 1660 | twoFingerDrag(paper) |
| 1661 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") |
| 1662 | XCTAssertEqual(paper.value as? String, before) |
| 1663 | } |
| 1664 | |
| 1665 | func testDiagramDoesNotRotateWhenTheModelIsOrbited() { |
| 1666 | let app = XCUIApplication(); app.launch() |
| 1667 | app.buttons["Cup"].tap() |
| 1668 | let diagram = app.otherElements["diagram"].screenshot().pngRepresentation |
| 1669 | twoFingerDrag(app.otherElements["fold.paper"]) |
| 1670 | XCTAssertEqual(app.otherElements["diagram"].screenshot().pngRepresentation, diagram) |
| 1671 | } |
| 1672 | ``` |
| 1673 | |
| 1674 | - [ ] **Step 2: Run tests to verify they fail** |
| 1675 | |
| 1676 | Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/AccessibilityAuditTests` |
| 1677 | Expected: FAIL. |
| 1678 | |
| 1679 | - [ ] **Step 3: Implement `OrbitGesture`, the accessibility labels, the privacy manifest, the rights note and the screenshot script** |
| 1680 | |
| 1681 | `take-screenshots.sh` follows `krz/daybyday/scripts/take-screenshots.sh`. `PrivacyInfo.xcprivacy` declares no tracking and no collected data. |
| 1682 | |
| 1683 | - [ ] **Step 4: Run tests to verify they pass** |
| 1684 | |
| 1685 | Run: as above. |
| 1686 | Expected: PASS. |
| 1687 | |
| 1688 | - [ ] **Step 5: Commit** |
| 1689 | |
| 1690 | ```bash |
| 1691 | git add App scripts AppStore |
| 1692 | git commit -m "Orbit and zoom, accessibility pass and release assets" |
| 1693 | ``` |
| 1694 | |
| 1695 | --- |
| 1696 | |
| 1697 | ### Task 15: The crane, the boat and the box |
| 1698 | |
| 1699 | **Files:** |
| 1700 | - Create: `Models/crane.foldscript`, `Models/crane-cp.fold` |
| 1701 | - Create: `Models/boat.foldscript`, `Models/boat-cp.fold` |
| 1702 | - Create: `Models/box.foldscript`, `Models/box-cp.fold` |
| 1703 | - Create: `Packages/FoldKit/Sources/Models/Resources/{crane,boat,box}.fold` |
| 1704 | - Create: `docs/authoring/{crane,boat,box}.md` |
| 1705 | - Modify: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` — delete `theCatalogueContainsTheCup`; `theCatalogueContainsFourModels` below replaces it |
| 1706 | - Modify: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift` — golden images for every step of the three new models |
| 1707 | - Test: `Packages/FoldKit/Tests/ModelsTests/FourModelTests.swift` |
| 1708 | |
| 1709 | **Interfaces:** |
| 1710 | - Consumes: everything from Tasks 0–14. No new API. |
| 1711 | |
| 1712 | Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Which boat is the author's choice (design, *Open decisions*); do not start the boat until it is made. |
| 1713 | |
| 1714 | 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. |
| 1715 | |
| 1716 | 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. |
| 1717 | |
| 1718 | - [ ] **Step 1: Write the failing tests** |
| 1719 | |
| 1720 | ```swift |
| 1721 | @Test func theCatalogueContainsFourModels() throws { |
| 1722 | #expect(try Set(ModelLibrary.names()) == ["cup", "crane", "boat", "box"]) |
| 1723 | } |
| 1724 | |
| 1725 | @Test func theCraneContainsAMultiAxisStep() throws { |
| 1726 | #expect(try readSteps(ModelLibrary.model(named: "crane")).contains { $0.axes.count > 1 }) |
| 1727 | } |
| 1728 | |
| 1729 | @Test func theCraneStacksAtLeastEightLayersSomewhere() throws { |
| 1730 | let crane = try ModelLibrary.model(named: "crane") |
| 1731 | let deepest = (0...crane.stepCount).map { |
| 1732 | stackDepth(positions: crane.frames[$0].verticesCoords, faces: crane.facesVertices) |
| 1733 | }.max() ?? 0 |
| 1734 | #expect(deepest >= 8) |
| 1735 | } |
| 1736 | |
| 1737 | @Test func everyModelWithOverlappingMovingSetsCarriesAMidFoldOrder() throws { |
| 1738 | for file in try ModelLibrary.all() { |
| 1739 | for n in 1...file.stepCount where movingSetsOverlapInProjection(step: n, file) { |
| 1740 | #expect(file.frames[n].faceOrdersMidFold != nil, "\(file.fileTitle ?? "?") step \(n)") |
| 1741 | } |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | @Test func everyModelHasAnAuthoringRecord() throws { |
| 1746 | for name in try ModelLibrary.names() { |
| 1747 | #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path)) |
| 1748 | } |
| 1749 | } |
| 1750 | ``` |
| 1751 | |
| 1752 | The catalogue tests from Task 8 — validation, step reading, isometry, interpenetration, traditional attribution, regeneration from script — now run over four models instead of one and must stay green. |
| 1753 | |
| 1754 | - [ ] **Step 2: Run tests to verify they fail** |
| 1755 | |
| 1756 | Run: `swift test --package-path Packages/FoldKit --filter ModelsTests` |
| 1757 | Expected: FAIL — only the cup is in the catalogue. |
| 1758 | |
| 1759 | - [ ] **Step 3: Author the three models** |
| 1760 | |
| 1761 | Box and boat first, then the crane. Neither the box nor the boat is shallow: the masu's wall-raising step is a coupled 3D step, and the boat depends on which one is chosen; both use whatever Task 0 decided for coupled steps. 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. |
| 1762 | |
| 1763 | - [ ] **Step 4: Run tests to verify they pass** |
| 1764 | |
| 1765 | Run: `swift test --package-path Packages/FoldKit --filter ModelsTests` |
| 1766 | Expected: PASS. |
| 1767 | |
| 1768 | - [ ] **Step 5: Commit** |
| 1769 | |
| 1770 | ```bash |
| 1771 | git add Models Packages/FoldKit docs/authoring |
| 1772 | git commit -m "The crane, the boat and the box" |
| 1773 | ``` |
| 1774 | |
| 1775 | --- |
| 1776 | |
| 1777 | ## After the plan |
| 1778 | |
| 1779 | The plan delivers v1 complete: the engine, the compiler, the notation, the renderer, the app and four traditional models. Growing the catalogue needs no further engineering — the frog base, fish base, flapping bird and preliminary base are each a crease pattern, a script and a correction pass, gated by machinery that already exists. |
| 1780 | |
| 1781 | What would need new engineering: designed models, which is a permissions project before it is a code one; curved creases and wet folding, which break the rigid-flat-facet premise the whole engine rests on; and deriving layer order rather than authoring it, which is the one place this design knowingly trades authoring effort for runtime correctness and should stay that way. |