Commit cff9586b02

cff9586b0276afde7fa203a4a46486aac08ae7e2

Verified · cmc

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

Design, implementation plan and license

Layout: unified · split

.gitignore added +5
@@ -0,0 +1,5 @@
1.build/
2.swiftpm/
3App/*.xcodeproj/
4DerivedData/
5.DS_Store
LICENSE added +12
@@ -0,0 +1,12 @@
1Copyright (C) 2026 krazy warez
2
3Permission to use, copy, modify, and/or distribute this software for any
4purpose with or without fee is hereby granted.
5
6THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
7WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
8MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
9ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
10WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
11ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
12OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
docs/superpowers/plans/2026-10-19-fold.md added +1781
@@ -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
411. **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.
422. **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.
433. **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.
444. **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.
455. **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.
466. **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
50The 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
52Every 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
64Defect 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
92Done once, before Task 0.
93
941. `gitbay init fold` in this directory. The repo is public. This runs `git init`, creates the repo and sets `origin`.
952. 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.
963. 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`.
1094. 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
1251. **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.
1262. **Letter fold, one valley, one mountain** (`letter.fold`'s geometry). The control for the case the current model handles: expected exact and clean.
1273. **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.
1284. **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.
1295. **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
151This 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
157Run: `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
163git add spikes docs
164git 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
200The 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
202Package 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"])
270func 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
279Run: `swift test --package-path Packages/FoldKit --filter DecodingTests`
280Expected: 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
288Run: `swift test --package-path Packages/FoldKit --filter DecodingTests`
289Expected: PASS.
290
291- [ ] **Step 5: Commit**
292
293```bash
294git add Packages/FoldKit
295git 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
315This 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
317The 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"])
328func 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
423Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests`
424Expected: FAIL.
425
426- [ ] **Step 3: Implement `validate` and `movingSetsOverlapInProjection`**
427
428Normals 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
432Run: `swift test --package-path Packages/FoldKit --filter ValidatorTests`
433Expected: PASS.
434
435- [ ] **Step 5: Commit**
436
437```bash
438git add Packages/FoldKit
439git 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"])
485func 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
537Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests`
538Expected: FAIL.
539
540- [ ] **Step 3: Implement `FoldAxis`, `FoldStep` and `readSteps`**
541
542- [ ] **Step 4: Run tests to verify they pass**
543
544Run: `swift test --package-path Packages/FoldKit --filter StepReadingTests`
545Expected: PASS.
546
547- [ ] **Step 5: Commit**
548
549```bash
550git add Packages/FoldKit
551git 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
568There 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
573let 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)
583func 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)
593func 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
650Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests`
651Expected: FAIL.
652
653- [ ] **Step 3: Implement `positions(at:)`**
654
655For 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
659Run: `swift test --package-path Packages/FoldKit --filter InterpolationTests`
660Expected: PASS.
661
662- [ ] **Step 5: Commit**
663
664```bash
665git add Packages/FoldKit
666git 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
689The 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
691Each 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
696let up2 = [SIMD3<Double>(0, 0, 1), SIMD3(0, 0, 1)]
697let 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
788Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests`
789Expected: 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
797Run: `swift test --package-path Packages/FoldKit --filter LayerOrderTests`
798Expected: PASS.
799
800- [ ] **Step 5: Commit**
801
802```bash
803git add Packages/FoldKit
804git 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
865Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests`
866Expected: FAIL.
867
868- [ ] **Step 3: Implement `interpenetrations`**
869
870At 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
874Run: `swift test --package-path Packages/FoldKit --filter InterpenetrationTests`
875Expected: PASS.
876
877- [ ] **Step 5: Commit**
878
879```bash
880git add Packages/FoldKit
881git 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
914Defaults: `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
916Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it.
917
918macOS 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"])
924func 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
986Run: `swift test --package-path Packages/FoldKit --filter CompilerTests`
987Expected: FAIL.
988
989- [ ] **Step 3: Implement `FoldScript`, `compile`, `guessFaceOrders`, `applyOrderOverrides` and the `foldc` entry point**
990
991Resolve 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
995Run: `swift test --package-path Packages/FoldKit --filter CompilerTests`
996Expected: PASS.
997
998- [ ] **Step 5: Commit**
999
1000```bash
1001git add Packages/FoldKit
1002git 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
1026Its 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
1090Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests`
1091Expected: FAIL.
1092
1093- [ ] **Step 3: Implement `ModelLibrary`, `foldlint`, and author the cup's crease pattern and script**
1094
1095Iterate 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
1099Run: `swift test --package-path Packages/FoldKit --filter CatalogueTests`
1100Expected: PASS.
1101
1102- [ ] **Step 5: Commit**
1103
1104```bash
1105git add Packages/FoldKit Models docs/authoring
1106git 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
1131The 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
1133Edge 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
1135Reference, 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
1233Run: `swift test --package-path Packages/FoldKit --filter DiagramTests`
1234Expected: FAIL.
1235
1236- [ ] **Step 3: Implement the types, `buildDiagram` and `visibleSegments`**
1237
1238Project 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
1242Run: `swift test --package-path Packages/FoldKit --filter DiagramTests`
1243Expected: PASS.
1244
1245- [ ] **Step 5: Commit**
1246
1247```bash
1248git add Packages/FoldKit
1249git 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
1272Depth 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
1278Facets are two-sided, front and back distinguished in the fragment shader by `[[front_facing]]`. This task owns Review Focus item 3.
1279
1280SwiftPM compiles `Shaders.metal` with the Metal toolchain; see *Setup* step 4.
1281
1282- [ ] **Step 1: Write the failing tests**
1283
1284The 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
1344These 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
1348Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"`
1349Expected: FAIL.
1350
1351- [ ] **Step 3: Implement `Camera`, `PaperRenderer` and the shaders**
1352
1353One 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
1357Run: `swift test --package-path Packages/FoldKit --filter "PaperRendererTests|CameraTests"`
1358Expected: PASS.
1359
1360- [ ] **Step 5: Commit**
1361
1362```bash
1363git add Packages/FoldKit
1364git 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
1394func testCupOpensAtStepOne() {
1395 let app = XCUIApplication(); app.launch()
1396 app.buttons["Cup"].tap()
1397 XCTAssertEqual(app.staticTexts["step.index"].label, "1")
1398}
1399
1400func 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
1407func 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
1414Completing 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
1418Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test`
1419Expected: 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
1425Run: `xcodegen generate --spec App/project.yml`, then as above.
1426Expected: PASS.
1427
1428- [ ] **Step 5: Commit**
1429
1430```bash
1431git add App
1432git 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
1453This task owns Review Focus item 4.
1454
1455The 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
1507func 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
1514func 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
1526The paper view's accessibility value is the fold parameter as a percentage.
1527
1528- [ ] **Step 2: Run tests to verify they fail**
1529
1530Run: `swift test --package-path Packages/FoldKit --filter FoldParameterTests`
1531Expected: FAIL.
1532
1533- [ ] **Step 3: Implement `FoldParameterMapping` and `FoldGesture`**
1534
1535The 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
1539Run: `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`
1540Expected: PASS.
1541
1542- [ ] **Step 5: Commit**
1543
1544```bash
1545git add App Packages
1546git 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
1562A `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
1567func 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
1576func testFoldDragDoesNothingOnATurnOverStep() {
1577 // a fold drag on a turnOver step must leave step.index unchanged
1578}
1579
1580func testReorientDragDoesNothingOnAFoldStep() {
1581 // a horizontal drag that does not follow the fold path must leave step.index unchanged
1582}
1583
1584func 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
1592Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/ReorientGestureTests`
1593Expected: FAIL.
1594
1595- [ ] **Step 3: Implement `ReorientGesture`**
1596
1597Gate 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
1601Run: as above.
1602Expected: PASS.
1603
1604- [ ] **Step 5: Commit**
1605
1606```bash
1607git add App
1608git 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
1627A 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
1632func testEveryScreenPassesTheAccessibilityAuditAtDefaultTextSize() throws {
1633 let app = XCUIApplication(); app.launch()
1634 try app.performAccessibilityAudit()
1635 app.buttons["Cup"].tap()
1636 try app.performAccessibilityAudit()
1637}
1638
1639func 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
1649func testPaperViewDescribesTheCurrentStepInWords() {
1650 let app = XCUIApplication(); app.launch()
1651 app.buttons["Cup"].tap()
1652 XCTAssertTrue(app.otherElements["fold.paper"].label.hasPrefix("Valley fold"))
1653}
1654
1655func 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
1665func 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
1676Run: `xcodebuild -project App/Fold.xcodeproj -scheme Fold -destination 'platform=iOS Simulator,name=iPhone 17 Pro' test -only-testing:FoldUITests/AccessibilityAuditTests`
1677Expected: 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
1685Run: as above.
1686Expected: PASS.
1687
1688- [ ] **Step 5: Commit**
1689
1690```bash
1691git add App scripts AppStore
1692git 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
1712Authoring, 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
1714The 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
1716Each `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
1752The 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
1756Run: `swift test --package-path Packages/FoldKit --filter ModelsTests`
1757Expected: FAIL — only the cup is in the catalogue.
1758
1759- [ ] **Step 3: Author the three models**
1760
1761Box 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
1765Run: `swift test --package-path Packages/FoldKit --filter ModelsTests`
1766Expected: PASS.
1767
1768- [ ] **Step 5: Commit**
1769
1770```bash
1771git add Models Packages/FoldKit docs/authoring
1772git commit -m "The crane, the boat and the box"
1773```
1774
1775---
1776
1777## After the plan
1778
1779The 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
1781What 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.
docs/superpowers/specs/2026-10-19-fold-design.md added +582
@@ -0,0 +1,582 @@
1# Fold — design
2
3## Intent
4
5Origami instructions are written in a formal diagram language. The
6Yoshizawa–Randlett system fixes what a dashed line means (valley), what a
7dash-dot line means (mountain), what each arrowhead means (fold, fold and
8unfold, turn over, rotate, repeat), and it has been stable for sixty years.
9It is a real notation, and it is designed for paper.
10
11Every origami app treats the diagram as a picture: a sequence of
12photographs or scanned drawings you page through, with the notation reduced
13to decoration. The paper never moves, and the diagram and the model can
14disagree because nothing connects them.
15
16This app has one source of truth. A model is a folded geometry with
17labelled creases; from that data the app **generates the Yoshizawa–Randlett
18diagram** and **animates the fold**, and the two cannot contradict each
19other because they are two renderings of the same thing. You drag
20perpendicular to a crease and the paper rotates about it, through the
21angle, at your pace, stopping where you stop.
22
23## Goals
24
25- Dragging a fold moves the paper continuously from 0° to its final fold
26 angle and back, tracking the finger, with correct layer ordering at every
27 intermediate angle.
28- The diagram for a step is generated from the step's geometry: crease line
29 styles from which way each fold turns as seen, arrows from which facets
30 move, about which axis, and by which technique.
31- The notation is correct Yoshizawa–Randlett, not an approximation of it.
32- Models are data files, not code. Adding a model is adding a file.
33- Entirely offline. No account, no network.
34- Two-finger orbit and pinch zoom on the model at any point in the
35 sequence, so you can look underneath a flap.
36- Ships on the App Store, with VoiceOver and Dynamic Type support at the
37 level of `krz/daybyday` — every screen passes Xcode's accessibility audit
38 at the default and the largest text size.
39
40## Non-goals
41
42- Paper simulation. No bending, no stiffness, no self-collision response,
43 no crumpling. Paper is rigid flat facets hinged at creases.
44- Deriving layer order from geometry. Layer order is authored and checked,
45 never computed. Computing it in general is a hard problem and getting it
46 wrong looks worse than any amount of authoring effort.
47- Deriving a step's axes and moving sets from a frame diff. See *Steps are
48 authored* below.
49- Wet folding, curved creases, or anything that is not a straight crease
50 between flat facets.
51- Modern designers' models. See *Rights*.
52- Teaching origami through text. The diagram and the motion are the
53 instruction. The accessibility labels are the exception and are required.
54
55## Anti-goals
56
57- Facets that interpenetrate on screen. A flap passing through the layer
58 below it destroys the sense that this is paper, and a viewer notices
59 immediately even when they could not say why.
60- A fold that snaps. If the drag is quantised, or the last 10° completes
61 itself, the premise is gone.
62- Diagram notation that is nearly right. The audience for this app is
63 people who read diagrams, and a wrong arrowhead is as visible to them as
64 a misspelling.
65- Inventing a file format when FOLD exists.
66- Shipping an engine with nothing to fold. Models cannot be authored in
67 existing tools; see *Authoring*.
68
69## Rights
70
71**Traditional models only.** Origami models designed in the modern era are
72the intellectual property of their designers, and diagramming someone
73else's model without permission is both a legal problem and, in the origami
74community, a serious breach. Every model here is traditional, long
75predating any individual claim. Each model's `file_author` is
76`"Traditional"` and the validator enforces it.
77
78**v1 ships four: the cup, the crane, the boat and the box.** The box is the
79masu. Which traditional boat is open (see *Open decisions*). The frog base,
80fish base, flapping bird and preliminary base are the same kind of thing
81and come afterwards, cheaply, because the compiler will exist. Four is thin
82for a first release but defensible; one is not, and eight is authoring work
83better done once you know how the folding feels in the hand.
84
85A later release that includes designed models needs the designer's
86permission, per model, in writing. That is a licensing project, not an
87engineering one, and it is out of scope here.
88
89## Constraints
90
91- iOS 26, Swift 6, iPhone and iPad (`TARGETED_DEVICE_FAMILY = "1,2"`).
92 iPad is the better device for this and the layout should assume it will
93 be used there.
94- XcodeGen `project.yml`, matching the layout of `krz/moonrise`.
95- Bundle prefix `sh.krz`, `DEVELOPMENT_TEAM = ZCNAX3VL9D`.
96- Geometry, format handling and notation generation live in a SwiftPM
97 package with no UIKit or SwiftUI dependency. The renderer may import
98 Metal and MetalKit.
99- 0BSD, origin on gitbay.org.
100- No third-party runtime dependencies in the app. Authoring tooling may
101 depend on whatever is convenient; it does not ship.
102
103## The model format
104
105Models are **FOLD** files — the JSON format from Demaine, Ku and Lang
106(2016), spec v1.2 at `github.com/edemaine/fold`, `doc/spec.md`,
107MIT-licensed.
108
109Keys used from the standard:
110
111| Key | Use |
112|---|---|
113| `file_spec` | `1.2` |
114| `file_creator` | `"foldc"` |
115| `file_title`, `file_author` | the model's name; `"Traditional"` |
116| `file_classes` | `["singleModel", "diagrams"]` |
117| `vertices_coords` | 3D vertex positions in the folded state of that frame; 2-element entries mean z = 0 |
118| `edges_vertices` | `[u, v]` endpoints, defining edge orientation |
119| `edges_assignment` | `B` boundary, `M` mountain, `V` valley, `F` flat, `U` unassigned; `C` and `J` are rejected |
120| `edges_foldAngle` | degrees in [−180, 180]; positive for valley, negative for mountain, 0 for `F`, `U` and `B`. The sign must match `edges_assignment`, as the spec requires, and the validator checks it |
121| `faces_vertices` | vertex IDs counterclockwise; the order defines the face's normal |
122| `faceOrders` | `[f, g, s]` triples; `s = +1` means `f` is above `g`, on the side `g`'s normal points toward in the folded state; `s = -1` below; `s = 0` unknown |
123| `file_frames` | frames 1…N (see *Frames and step numbering*) |
124| `frame_parent`, `frame_inherit` | `0` and `true` on every frame in `file_frames` |
125
126Because `s` is relative to `g`'s normal, two triples can only be compared
127after normalising each by its faces' normals in that frame: `[f, g, +1]`
128with `[g, f, +1]` is consistent when the faces face opposite ways. Cycle
129detection and every other order check normalise first.
130
131Two places are stricter than the spec. It allows `faceOrders` cycles (a
132square twist has one); the validator rejects them, and no traditional model
133in scope needs one. It recommends `J` edges to split faces that overlap in
134several regions or are nonconvex; `J` is rejected and faces must be convex.
135A crease that ends inside the sheet (a pinch) leaves a nonconvex face around
136its end, which is split by a **subdivision edge**: assigned `F`, flat in
137every frame, with no `edges_krz:firstCreasedAtStep`, and never drawn.
138
139### Frames and step numbering
140
141FOLD's top-level frame properties describe the **key frame**, frame 0, and
142`file_frames[i]` is frame `i + 1`.
143
144- Frame 0 is the unfolded sheet.
145- **Step n**, counting from 1, takes frame n − 1 to frame n, and its record
146 is frame n's `krz:step`. A model with N steps has N + 1 frames.
147- Every index this project calls a step — in `krz:step`,
148 `edges_krz:firstCreasedAtStep`, the validator's defects, `FoldStep.index`
149 and the UI's "Step n" — is this n. The only zero-based indices are array
150 subscripts.
151- Every frame in `file_frames` carries `frame_parent: 0` and
152 `frame_inherit: true`, so tools that implement FOLD's frame inheritance
153 see the shared topology. Each frame overrides `vertices_coords`,
154 `edges_assignment`, `edges_foldAngle` and `faceOrders`, and never
155 `edges_vertices` or `faces_vertices`.
156
157### One topology, every frame
158
159**Frame 0 is the sheet already subdivided by every crease the whole
160sequence will ever use**, with the not-yet-folded ones carrying
161`edges_foldAngle` 0 and assignment `F`. Every frame therefore shares one
162`vertices_coords` length, one `edges_vertices` and one `faces_vertices`;
163only coordinates, fold angles, assignments and `faceOrders` differ between
164frames.
165
166This is what makes interpolation possible: vertex *i* in frame *k* and
167vertex *i* in frame *k+1* are the same point of paper, so rotating the
168moving facets carries one frame to the next. Without it there is no vertex
169correspondence between frames and nothing to interpolate. The validator
170enforces it.
171
172A crease that runs through several layers of a folded state is several
173edges, one per layer, coincident in space. A step that folds through those
174layers changes all of them; its axis names one.
175
176The cost of a shared topology is that a crease the reader has not met yet
177exists in the data from the start, so the diagram generator needs to know
178when each crease first becomes visible. FOLD has no key for that, so the
179models carry one.
180
181### Extension keys
182
183FOLD reserves keys without a colon. These are this app's, under `krz:`:
184
185| Key | Where | Use |
186|---|---|---|
187| `edges_krz:firstCreasedAtStep` | key frame, inherited | per edge, the step n at which the crease is first made; `null` for a boundary |
188| `krz:step` | frames 1…N | the step that produced this frame (below) |
189| `krz:faceOrders_midFold` | frames 1…N | layer order to use while this step is in motion; required when the step's moving sets overlap in projection, and on every `foldAndUnfold`, where it holds the order at the peak |
190
191The edge key follows the spec's own example, `edges_tm:structuralType`, so
192FOLD tools that select edge properties by the `edges_` prefix treat it as
193edge data and renumber it with the edges.
194
195Extension keys mean other FOLD tools ignore part of the data. FOLD is still
196the right choice for the geometry: it is a published spec with a careful
197layer-order model, and reinventing that would be worse than extending it.
198
199### Steps are authored, not derived
200
201The app does not derive a step's crease axes and moving facets by diffing
202consecutive frames. That would be an algorithm with real ambiguities —
203which side of the crease moved, whether a whole-model reorientation is a
204fold, how to partition several simultaneous axes — inferring something the
205author already knows.
206
207Each frame's `krz:step` carries it explicitly:
208
209```
210{ "kind": "fold" | "foldAndUnfold" | "turnOver" | "rotate",
211 "technique": "plain" | "insideReverse" | "outsideReverse"
212 | "squash" | "petal" | "sink",
213 "instruction": "Valley fold the right corner to the left edge.",
214 "axes": [ { "edge": 17, "movingFaces": [3, 4, 5],
215 "startAngle": 0, "endAngle": 180, "peakAngle": null } ],
216 "rotateDegrees": 90,
217 "turnOverAxis": "vertical" | "horizontal",
218 "repeatOf": 4,
219 "viewpoint": { "eye": [0, 0, 1], "up": [0, 1, 0] } }
220```
221
222- `axes`: the angles are the axis edge's `edges_foldAngle` at the start,
223 at the end, and — for `foldAndUnfold` only — at the turning point.
224- `technique`: drives the notation and the instruction's wording; geometry
225 ignores it. `plain` for anything that is not a named technique.
226- `instruction`: the step in words, written by the author in the fold
227 script. It is the paper view's accessibility label and the diagram's
228 caption. It is authored because a generator cannot know that a vertex is
229 "the right corner" or that a line is "the centre".
230- `rotateDegrees`: required for `rotate`; the rotation is about `eye`, so positive is counterclockwise as
231 seen from the viewpoint.
232- `turnOverAxis`: required for `turnOver`; the screen axis, as seen from the
233 viewpoint, the model turns about.
234- `repeatOf`: on a step expanded from a repeat, the step it repeats.
235- `viewpoint`: `eye` is the unit direction from the model toward the viewer
236 (the diagram is orthographic, so there is no eye position); `up` is
237 screen-up. Most steps use `[0, 0, 1]` and `[0, 1, 0]`.
238
239All of a step's axes share one parameter, so a petal fold or a reverse fold
240is one step with several axes and several moving sets, driven together.
241The traditional models need this. How those axes move together is the
242subject of Task 0; see *Interpolation*.
243
244### Step kinds
245
246| Kind | Geometry | How it advances |
247|---|---|---|
248| `fold` | one or more axes, start → end angle | a drag, as below |
249| `foldAndUnfold` | axes go start → peak → start | a drag out and back |
250| `turnOver` | no crease; the model turns 180° about `turnOverAxis` | a one-finger horizontal drag across the model |
251| `rotate` | no crease; the model turns in plane by `rotateDegrees` | a one-finger horizontal drag across the model |
252
253`turnOver` and `rotate` are steps in `file_frames` like any other. Their
254end frame is the start frame rotated about the centre of its bounding box —
255the coordinates change and the camera does not. The diagram's viewpoint is
256fixed and the reader's mental model is of turning the paper over in their
257hands, so the **model** reorients, not the camera. Because the coordinates
258carry the orientation, nothing else has to track it.
259
260Repeats — "repeat steps 4–6 behind" — are **expanded into explicit steps**
261in the data, each with `repeatOf` naming the step it repeats. Each expanded
262step's diagram shows its own fold (a repeat done behind is drawn as the
263fold behind that it is) plus the repeat mark. A first-class repeat would
264save file size and cost correctness.
265
266## How it works
267
268### Interpolation
269
270This section is the model Task 0 tests, and Task 0 rewrites it with the
271result. Until then it is provisional; nothing that encodes it is built
272before Task 0 finishes.
273
274Between frame n − 1 and frame n, each of step n's axes rotates its moving
275faces rigidly about its crease line, on one shared parameter *t* in 0...1:
276
277- The crease line is the axis edge's endpoints in frame n − 1.
278- The axis is directed the way the moving face adjacent to the edge
279 traverses it in `faces_vertices` order. A positive rotation about that
280 direction (right-hand rule) turns the moving face toward the side its
281 normal points to, which is a valley — so the rotation is
282 `angle(t) − startAngle`, with the sign FOLD already gives fold angles.
283- `angle(t)` is `startAngle + t·(endAngle − startAngle)` for `fold`, and
284 `startAngle + (peakAngle − startAngle)·(1 − |2t − 1|)` for
285 `foldAndUnfold`, which reaches its peak at *t* = 0.5.
286- `turnOver` and `rotate` rotate every vertex about the start frame's
287 bounding-box centre by *t* times the step's angle.
288
289This is exact when the moving sets are disjoint, share no vertex except on
290their own axes, and no axis is carried by another set's motion — the letter
291fold, and most single valley and mountain folds. It is **not** exact for
292squash, petal and reverse folds, nor the masu's wall-raising step. There the
293faces form closed loops around interior vertices, the fold angles at a
294vertex are coupled nonlinearly (at a flat-foldable degree-4 vertex,
295tan(ρ₁/2) = k·tan(ρ₂/2)), and some axes are carried by other moving faces.
296Linear, independent rotation of each set tears the paper at the shared
297vertices partway through the fold even though both end frames are exact.
298For an inside reverse fold there is a further question of whether any rigid
299motion exists that keeps the rest of the flap still. Task 0 measures this
300on synthetic cases before any type commits to an answer.
301
302### Layer ordering during a fold
303
304`faceOrders` is authored for every frame. While step n is in motion, the
305**active ordering** is `krz:faceOrders_midFold` if frame n has one, and
306otherwise frame n's `faceOrders`, applied from the moment the fold begins:
307a facet being folded over is above its destination for the whole motion,
308which is what the end frame's ordering says. A pair with no triple there
309takes frame n − 1's, which covers a flap leaving a stack. Each source is
310checked for cycles with the normals of the state it describes — the peak
311for a `foldAndUnfold`'s mid-fold order. A `foldAndUnfold`
312ends where it started, so neither end frame orders the moving faces against
313the faces they lie on at the peak; its `krz:faceOrders_midFold` is that
314order, computed by `foldc`.
315
316The orders themselves are checked in every frame by three consistency
317rules, on every stack of coincident faces: two faces joined at a crease
318folded to ±180 are ordered as its assignment requires; where two folded
319creases coincide, their face pairs nest rather than interleave; and a face
320whose interior crosses a folded crease's line does not lie between that
321crease's two faces. A guessed or overridden order that breaks one is
322impossible paper, even when no face collides with another — the
323interpenetration checker cannot see that, because a wrongly ordered flap
324moves through exactly the same coordinates.
325
326Two rules make this safe rather than merely convenient:
327
3281. The validator requires frame n − 1's and frame n's orderings to agree on
329 every pair **not involving a moving facet**. A step where this
330 simplification would be visible in the still part of the model fails
331 authoring.
3322. When a step's moving sets overlap in projection — the petal and reverse
333 fold case — the end frame's ordering does not determine their order
334 relative to each other, because both are moving. Such a step **must**
335 carry `krz:faceOrders_midFold`, and the validator rejects it if it does
336 not. Without this rule two flaps pass through each other on the models
337 v1 requires.
338
339When a traditional model has a step that cannot satisfy these, the fix is
340to split the step into sub-steps until it can. Dropping the model is the
341last resort and needs a decision, not a shrug.
342
343### Rendering
344
345Metal, with a small renderer written for this: the geometry is tens of
346triangles and a few hundred vertices, and both SceneKit (deprecated) and
347RealityKit (whose dynamic-mesh support is more than this needs) would
348contribute more risk than they remove.
349
350Depth handling is **hybrid**. `faceOrders` is defined only for faces that
351overlap geometrically; it says nothing about facets separated in 3D, which
352is most of a folded model. Depth testing off everywhere is right for a
353coplanar stack and wrong for the rest. So:
354
355- Two faces are linked when they overlap in projection, their normals are
356 within 2° of each other's line, and each one's vertices lie within
357 sin 2° × the model's bounding-box diagonal of the other's plane. A **cluster** is a
358 connected group of linked faces. The tolerance is wide on purpose: a facet just leaving or just arriving on a
359 stack is nearly coplanar with it, and the depth buffer alone would
360 z-fight there.
361- The depth buffer resolves clusters separated in space.
362- Within a cluster, faces are drawn back-to-front by the active ordering,
363 with depth test on (less-or-equal) and depth writes off; then the
364 cluster's faces are drawn again depth-only, colour writes off, so that
365 clusters drawn later are hidden behind it. Without the second pass a
366 cluster writes no depth and anything drawn after it draws over it.
367- The `s` sign is evaluated **against the current view direction**, using
368 `g`'s current normal, because "above" in FOLD means "on the side `g`'s
369 normal points toward", that reverses when you orbit underneath the model,
370 and a moving stack's normals turn with it.
371
372Facets are drawn two-sided — paper has a coloured side and a white side,
373and which side you are seeing is information.
374
375### The diagram
376
377The diagram for step n draws **frame n − 1** — the paper before the step,
378as a printed diagram does — orthographically from step n's `viewpoint`,
379with step n's creases and arrows on it. The diagram does **not** rotate when
380you orbit the model; the model view orbits and the diagram stays put,
381because a diagram is a fixed drawing and orbiting it would make it
382something else.
383
384Edges:
385
386- `B` edges, and creases folded in frame n − 1 (fold angle not 0): solid,
387 as the outline of the folded shape.
388- creases made in an earlier step and flat again in frame n − 1 (fold
389 angle 0, `edges_krz:firstCreasedAtStep` < n): solid, lighter.
390- step n's crease, including every edge coincident with an axis: dashed
391 for a valley, dash-dot for a mountain, **as seen from the viewpoint**.
392 The axis turns the moving face toward its own normal when its angle
393 increases, so the fold is a valley as seen when the sign of the turn
394 (end − start, or peak − start for `foldAndUnfold`) times the sign of the
395 moving face's normal · `eye` is positive. FOLD's assignment cannot be
396 used here: it is relative to each face's own normal, so on a flipped
397 layer or after a turn-over it names the opposite fold, and coincident
398 edges on different layers disagree.
399- creases whose `edges_krz:firstCreasedAtStep` is later than n, and
400 subdivision edges: not drawn.
401
402Arrows and symbols:
403
404- `plain` folds: one fold arrow per axis, curving from the moving facet
405 across the crease to its destination — the valley-fold arrow for a
406 valley as seen, the mountain-fold ("fold behind") arrow for a mountain.
407- `foldAndUnfold`: the fold-and-unfold arrow.
408- the named techniques (`insideReverse`, `outsideReverse`, `squash`,
409 `petal`, `sink`): the arrows the reference prescribes for that technique
410 (the push arrow for a reverse fold or sink, for example), not one fold
411 arrow per axis. The glyph for each is chosen from the reference below and
412 the choice recorded beside the snapshots.
413- the turn-over and rotate symbols for those kinds.
414- the repeat mark on a step with `repeatOf`.
415
416**Edges occluded by layers above them are omitted.** Yoshizawa–Randlett
417diagrams distinguish what you can see from what you cannot, and drawing a
418hidden crease as though it were visible is the "nearly right notation"
419failure. This means clipping each edge against the union of the faces
420`faceOrders` puts above either of its incident faces, from the diagram's
421viewpoint — the union, so that
422an edge under the seam between two adjacent upper faces is hidden — a real
423algorithm with its own tests, and in scope.
424
425### Gesture
426
427- Drag on the paper during a `fold`: drives *t*. The app samples the
428 screen path of the first moving set's centroid from *t* = 0 to 1 and
429 sets *t* to the point on that path nearest the centroid's screen
430 position when grabbed plus the drag's translation, searched outward from the current *t* so the
431 parameter cannot jump. The facet follows the finger wherever you grab it.
432 When the path is under 8 points long — travel nearly along the view
433 direction — the mapping is degenerate and falls back to a vertical drag
434 over a fixed 160-point throw.
435- `foldAndUnfold`: the same mapping over the outbound half of the path
436 (*t* 0 → 0.5), then over the return half (*t* 0.5 → 1) once the peak is
437 reached.
438- One-finger horizontal drag across the model: drives *t* for a `turnOver`
439 or `rotate` step, as the drag's distance over the model's on-screen
440 width. A flick does not complete it.
441- Two-finger drag: orbit. Pinch: zoom.
442- Only the gesture for the current step's kind is live.
443- The fold parameter is never advanced by the app. The step completes when
444 *t* reaches 1 and the finger lifts. Releasing earlier leaves the paper
445 where it is.
446
447## Authoring
448
449**Authoring is the project's main risk.**
450
451Existing FOLD tools — Oriedita, Rabbit Ear, Origami Simulator — author a
452single crease pattern. None of them produces a multi-frame sequence with
453per-frame folded coordinates, per-frame layer order, and per-step moving
454sets. Authoring in existing tools and validating with a CLI would in
455practice mean hand-writing hundreds of geometrically exact numbers per
456frame, per model. The engine can be finished and correct and still have
457nothing to show.
458
459So the tooling is part of the project. A command-line tool, `foldc`, macOS
460only, never shipped in the app, takes
461
462- a crease pattern (a FOLD file, exportable from existing tools), and
463- a fold script: an ordered list of steps, each naming its kind and
464 technique, its instruction text, its creases (by the points they run
465 between), its moving side (by a point inside it), and where they differ
466 from the defaults: fold angles, the turning-point angle of a fold and
467 unfold, the turn-over axis, the rotation, the step it repeats, the
468 viewpoint, **layer-order overrides** and the mid-fold order,
469
470and **computes** every frame: the folded coordinates by applying each
471step's rotations in order, the edges each crease covers in every layer,
472`edges_krz:firstCreasedAtStep`, and a first guess at `faceOrders` from the
473fold order, with the script's overrides applied on top. It validates as it
474goes and reports the first step that fails.
475
476Layer-order corrections live **in the script**, never in the generated
477file. A shipped `.fold` must regenerate exactly from its script and crease
478pattern, so an edit to the output would be lost on the next compile — and
479a test compares the two.
480
481That is the difference between a model being weeks of arithmetic and a
482model being an afternoon. It is also ordinary geometry code, not research.
483
484### Why there is no version of this without the compiler
485
486**The numbers are not choosable.** For the crane — roughly 35 creases
487subdividing the square into 40–60 faces, over 15–20 steps — a model file
488holds on the order of 4,000 numbers, and almost every one is the image of a
489point on the square under a specific composition of rotations. Each has one
490correct value to full precision, and the isometry check catches a 1e-6
491error. These are computed, never typed.
492
493**"Hand-authoring" is the compiler with the reusable parts removed.** To
494produce those coordinates by hand you would write a script that applies the
495rotations and prints JSON — which is the compiler, in a file you throw
496away. What `foldc` adds beyond that is crease resolution by endpoint,
497moving-set resolution by contained point, multi-layer crease resolution,
498`edges_krz:firstCreasedAtStep` assignment, the layer-order guess and
499overrides, and per-frame validation. Roughly a third of the task, and the
500third that makes every model after the first cheap.
501
502**Model-level tests need the same precision.** Assertions about the cup,
503crane, boat and box need the same exact coordinates as a shipped model, so
504they run on compiled models and live with the catalogue (Tasks 8 and 15).
505The unit tests written before the compiler exists use small synthetic
506sheets whose folded coordinates are integers or halves and can be typed
507exactly — a fold in half, a letter fold, a sheet folded in quarters — and
508the compiler's own tests check that it reproduces those fixtures.
509
510### The cup first, the crane last
511
512The first model compiled is **the cup**: six steps — five folds of one
513axis each and a turn-over — no reverse folds, and a stack of at most six layers where the
514two corner flaps cross. It exercises the entire chain — script, compile,
515validate, interpolate, diagram, render, fold under a finger — without
516exercising any of the hard parts at the same time. The version authored
517folds the top flaps down, the front one in front and the back one after the
518turn-over; it does not tuck them into the pocket, which inserts a flap
519between layers. Opening the cup into 3D at the end is not a step.
520
521The crane is **last** of the four, as the model that proves multi-axis
522steps and deep layer ordering work. Debugging a new compiler against the
523hardest traditional model, with its petal folds and eight-deep wing stacks,
524would confuse tool bugs with authoring mistakes.
525
526### Where the effort goes once the chain works
527
528Per model: export a crease pattern, write a short script, compile, then
529**correct the guessed layer orders** with overrides in the script. The
530guess — a folded flap lands on the side of the stack it arrived from — is
531right most of the time and wrong in exactly the interesting places, because
532a reverse fold or a tuck puts a flap *between* existing layers and the
533guess gets that backwards every time. The validator's layer-order rules and
534the interpenetration checker are what make the correction loop tractable:
535between them they name the pair, the step and, for a collision, the point
536in the fold. Reckon on an afternoon per model, and longer for the first.
537
538## What's left to the builder
539
540- Line weights and dash patterns for the diagram, within the notation's
541 requirements.
542- Paper colour, back colour, and the lighting model. Flat shading with a
543 single directional term is probably right; paper is not shiny.
544- How tightly the model is framed, given the authored viewpoint.
545- Whether the step list is a visible strip or revealed on demand.
546- The fold script's surface syntax beyond the JSON form the plan defines.
547
548## Evidence the quality bars are met
549
550The headline bars get mechanical checks rather than judgement:
551
552- **No interpenetration.** The catalogue test samples each step's fold
553 parameter and tests facet-facet intersection at each sample, across every
554 model. This is the only way the claim survives four models, then eight,
555 and later edits.
556- **No impossible layering.** The validator checks every frame's orders
557 against the crease, nesting and inside rules (*Layer ordering during a
558 fold*).
559- **No stretching.** The catalogue test samples every step of every model
560 and checks every edge length against frame 0.
561- **Correct notation.** The diagram generator is covered by golden-image
562 snapshot tests. The reference is Randlett's own conventions as set out in
563 *The Art of Origami* (1961) and the symbol set as summarised by
564 OrigamiUSA; where the two differ, OrigamiUSA's is used, and the choice is
565 recorded next to the snapshots.
566
567## Open decisions for the author
568
5691. **Name.** "Fold" is not going to be available. The repo and bundle ID
570 use `fold` / `sh.krz.fold` as working names.
5712. **Authoring tooling, and how many models.** Settled: build the
572 compiler, cup first, four models for v1. The plan is 16 tasks: the
573 interpolation spike (Task 0), the engine, the compiler, the app and the
574 cup, then the crane, boat and box as one gated authoring task.
5753. **The interpolation model for coupled steps.** Task 0 measures the
576 candidates and recommends one. If no rigid model covers a v1 step, the
577 choice between splitting the step, dropping it and relaxing the
578 isometry rule for it is the author's.
5794. **Which boat.** Candidates include the paper boat folded from the hat
580 and the sampan. The common paper boat starts from a rectangle; frame 0
581 does not have to be square, but the crease pattern and the validator's
582 isometry baseline then come from the rectangle.