Interpolation model spike (Task 0) and the sampan !1
9 files changed, +1213 −78
Layout: unified · split
docs/decisions/0001-interpolation-model.md added +255
| @@ -0,0 +1,255 @@ | ||
| 1 | # 0001 — Interpolation model | |
| 2 | ||
| 3 | **Status:** decided 2026-10-19 — **option A**. Rigid steps use M2 with | |
| 4 | per-axis windows on *t*. Reverse folds, sinks and inversions are flagged | |
| 5 | non-rigid and animated by a model Task 0b chooses, which also settles the | |
| 6 | petal fold, the sampan's inversion and the masu's wall-raising. Task 0's stop | |
| 7 | condition was met (the crane's reverse folds have no rigid model that matches | |
| 8 | the fold); this choice resolves it. | |
| 9 | ||
| 10 | ## Question | |
| 11 | ||
| 12 | How does a step's geometry move between its two frames? Specifically, which | |
| 13 | of these covers each kind of step the four v1 models need: | |
| 14 | ||
| 15 | - **M1** — the design as written: disjoint moving sets, each rotated about its | |
| 16 | crease in the start frame by a linearly interpolated angle. | |
| 17 | - **M2** — a kinematic tree with solved angle curves: an axis may be carried by | |
| 18 | another moving face, each axis's angle is a function of *t* (possibly on its | |
| 19 | own window of *t*), and `foldc` solves the curves so every loop of faces | |
| 20 | around an interior vertex closes. | |
| 21 | - **M3** — decomposition into sub-steps, each M1 or M2, on one drag. | |
| 22 | - **M4** — non-rigid: per-face transforms between solved poses, exact only at | |
| 23 | the poses. | |
| 24 | ||
| 25 | ## Method | |
| 26 | ||
| 27 | `spikes/interpolation` (`swift run -c release --package-path spikes/interpolation`). | |
| 28 | Each case is a crease pattern built in code. Faces are placed by composing | |
| 29 | rotations about creases along a spanning tree of faces; only creases on the | |
| 30 | tree carry an angle, and every other crease's angle is measured from the | |
| 31 | geometry. The **gap** is the largest distance between two copies of one | |
| 32 | vertex placed through different faces: zero when the paper is whole, the size | |
| 33 | of the tear otherwise. M1 prescribes every angle; M2 drives one crease and | |
| 34 | solves the others by damped Gauss–Newton, continued along *t*. Collisions are | |
| 35 | transversal face–face intersections, ignoring coplanar pairs and boundary | |
| 36 | contact. | |
| 37 | ||
| 38 | ## Results | |
| 39 | ||
| 40 | | Case | M1 | M2 / other | Collisions | | |
| 41 | |---|---|---|---| | |
| 42 | | 1. Letter fold, both thirds valley, one step | exact (gap 9e-16) | — | flaps meet at 120.2°. Staggered (one flap on *t* 0–0.5, the other on 0.5–1): none | | |
| 43 | | 2. Letter fold, one valley, one mountain | exact | — | none | | |
| 44 | | 3. Flat-foldable degree-4 vertex (60°, 80°, 120°, 100°) | tears: gap 1.08–1.38 on a sheet of side 2 | M2 exact (4e-12). Opposite creases pair up; the pairs follow tan(ρ₁/2) = k·tan(ρ₂/2) with k = cos((α+β)/2) / cos((α−β)/2) = 0.3473: at the driven crease's 45°, 90°, 135° the other pair is at 16.4°, 38.3°, 80.0° | — | | |
| 45 | | 4. Inside reverse fold, two-layer flap, rest of the flap held | — | no rigid motion reaches it with the flap closed (below) | — | | |
| 46 | | 5. Petal fold of a preliminary base | inconclusive (below) | inconclusive | — | | |
| 47 | ||
| 48 | ### Sampling a solved curve | |
| 49 | ||
| 50 | `foldc` writes a solved curve as samples. Rebuilding case 3's curves from | |
| 51 | N + 1 samples and measuring the tear between them (sheet of side 2): | |
| 52 | ||
| 53 | | N | linear | cubic Hermite, central-difference tangents | | |
| 54 | |---|---|---| | |
| 55 | | 16 | 1.0e-2 | 1.1e-3 | | |
| 56 | | 32 | 2.5e-3 | 1.2e-4 | | |
| 57 | | 64 | 6.3e-4 | 1.5e-5 | | |
| 58 | | 128 | 1.6e-4 | 1.8e-6 | | |
| 59 | | 256 | 3.9e-5 | 2.3e-7 | | |
| 60 | ||
| 61 | Cubic converges about eight times per halving. 257 samples keep the tear | |
| 62 | under 1e-6 on this sheet; `foldc` checks each curve at four times its sample | |
| 63 | density and refines a curve that does not. | |
| 64 | ||
| 65 | ### Case 4 in detail | |
| 66 | ||
| 67 | Sheet 4×2 folded on its spine y = 1; reverse-fold creases from (2, 1) to | |
| 68 | (3, 0) and (3, 2). Body spine and tip spine start at 180°. | |
| 69 | ||
| 70 | - **Flap held closed** (body spine fixed at 180°): the only rigid motion is the | |
| 71 | tip swinging about the two coincident reverse creases as one closed unit | |
| 72 | (tip spine stays 180°, the creases go to ∓180°). That ends at the reverse | |
| 73 | fold's coordinates with the wrong layering — the tip folded over outside, | |
| 74 | not between the layers. Gap 8e-14. | |
| 75 | - **Flap free, reverse creases driven:** the solver stays on that same motion. | |
| 76 | - **Flap free, tip spine driven through 0:** the whole flap unfolds and refolds | |
| 77 | the other way (body spine follows the tip spine to −180°). Not a reverse fold. | |
| 78 | - **Two phases:** open the flap completely flat (body and tip spines 180° → 0°), | |
| 79 | then fold on the reverse-fold branch (tip spine → −180°, body spine and both | |
| 80 | reverse creases → 180°). Rigid, gap 1e-13. **This is the only rigid path | |
| 81 | found, and it requires the flap to open fully flat.** | |
| 82 | - **Forced without opening** (M4, body held, tip spine linear 180° → −180°, | |
| 83 | one reverse crease least-squares): gap 2.0 on a flap 1 high — the paper | |
| 84 | tears completely. | |
| 85 | - **Partial opening** (body spine opens to φ at mid-fold and closes, tip spine | |
| 86 | linear, least-squares): gap 1.6 at φ = 150°, 1.16 at 120°, 0.73 at 90°, 0.36 | |
| 87 | at 60°, 0.24 at 30°. A naive schedule; it shows that a partial opening does | |
| 88 | not make the motion rigid, not the least strain a designed motion could | |
| 89 | reach. | |
| 90 | ||
| 91 | The vertex is degree 4 with a straight pair (the spine) and a mirror pair | |
| 92 | (the reverse creases). The runs found three families of rigid motion: the | |
| 93 | spine folding as one line, the tip swinging as a closed unit (only with the | |
| 94 | spine at 180°), and the reverse-fold branch from the flat sheet. Every path | |
| 95 | found from the folded flap to the reverse fold passed through the flat | |
| 96 | sheet. | |
| 97 | ||
| 98 | ### Case 5 in detail | |
| 99 | ||
| 100 | The crease pattern is Origami Simulator's `assets/Bases/birdBase.svg` | |
| 101 | (midlines, the diagonal the preliminary base folds, eight 22.5° kite | |
| 102 | creases), made exact, plus the petal hinge between the kite creases' ends. | |
| 103 | That pattern is not the bird base: | |
| 104 | ||
| 105 | - Origami Simulator's file has no petal hinge. Adding the hinge leaves five | |
| 106 | creases at each kite end, which no flat fold allows. With the inner square | |
| 107 | added as well, the solver finds a rigid, collision-free motion (gap 1e-15), | |
| 108 | but tracing points shows the inner layers' corners lifting with the front | |
| 109 | point. In a petal fold those corners stay down and become the legs. | |
| 110 | - With Origami Simulator's pattern as given, each kite end is a degree-4 | |
| 111 | vertex with the same structure as case 4's: a straight pair (the midline) | |
| 112 | and a mirror pair (the two kite creases), sectors 112.5° and 67.5°. If the | |
| 113 | petal fold reverses the outer midline segment there, case 4's result | |
| 114 | applies; if the side flaps swing as closed units, it is rigid. | |
| 115 | ||
| 116 | Settling this needs a verified bird-base crease pattern with its mountain and | |
| 117 | valley assignment (e.g. from Lang, *Origami Design Secrets*). No published | |
| 118 | FOLD file was found. | |
| 119 | ||
| 120 | ### Not measured | |
| 121 | ||
| 122 | - The sampan's last step, turning the model inside out. | |
| 123 | - The masu's wall-raising. | |
| 124 | ||
| 125 | ## What this means | |
| 126 | ||
| 127 | 1. **M1 is right for independent folds, with one addition:** axes need their | |
| 128 | own window on *t*. Case 1 shows two flaps of equal reach folding toward | |
| 129 | each other on one linear parameter always collide; staggering them is | |
| 130 | clean. | |
| 131 | 2. **Coupled vertices need M2's solved curves.** Linear angles tear a | |
| 132 | degree-4 vertex by more than half the sheet. The angles are not | |
| 133 | choosable — they follow the tan relation — which is more work for | |
| 134 | `foldc`, not for the author. | |
| 135 | 3. **Reverse folds have no rigid motion that matches how they are folded.** | |
| 136 | The rigid path unfolds the flap flat and refolds it. On the crane the | |
| 137 | neck, tail and head flaps are narrowed, several layers deep; unfolding | |
| 138 | one flat would undo earlier steps' folds on screen. Not measured on the | |
| 139 | crane's geometry. | |
| 140 | 4. **The petal fold is open** pending a verified crease pattern. | |
| 141 | 5. **The overlapping-moving-sets rule for `krz:faceOrders_midFold` has no | |
| 142 | case left.** The problem it addressed is a collision (case 1), which | |
| 143 | ordering cannot fix and staggering does. A staggered second flap arrives | |
| 144 | on a stack that is already flat, where the end frame's order and the | |
| 145 | near-coplanar clusters apply. Its other use, the peak order of a | |
| 146 | `foldAndUnfold`, is unaffected. | |
| 147 | ||
| 148 | ## Exit criterion | |
| 149 | ||
| 150 | The crane's three inside reverse folds are covered only by M3 with the flap | |
| 151 | fully unfolded, or by M4 — met. Per the plan, the choice is the author's. | |
| 152 | ||
| 153 | ## Options | |
| 154 | ||
| 155 | **A. Scoped non-rigid steps (recommended).** Rigid steps use M2 with per-axis | |
| 156 | windows. Steps whose technique has no rigid path — inside and outside reverse | |
| 157 | folds, sinks, inversions — are flagged in `krz:step` and animated by a | |
| 158 | designed non-rigid motion: the flap's layers open partway and the tip swings | |
| 159 | through, with faces near the vertex allowed to bend. For those steps the | |
| 160 | isometry gate becomes a stated strain bound, and the interpenetration check | |
| 161 | still applies. This needs: | |
| 162 | ||
| 163 | - a second spike (Task 0b) on a bending model for the reverse fold, to find a | |
| 164 | strain bound worth promising; | |
| 165 | - the verified bird-base pattern for case 5; | |
| 166 | - the sampan's inversion and the masu's wall-raising as cases. | |
| 167 | ||
| 168 | It also changes `CLAUDE.md`'s rule that an isometry failure is never a | |
| 169 | tolerance to widen, for flagged steps only. | |
| 170 | ||
| 171 | **B. Rigid via unfolding (M3).** Animate a reverse fold as unfold-flat, then | |
| 172 | refold. Exact and isometric, but it does not show how a reverse fold is made, | |
| 173 | and on the crane it unfolds earlier steps on screen. | |
| 174 | ||
| 175 | **C. Don't animate those steps.** The step jumps or crossfades. This breaks | |
| 176 | the anti-goal "a fold that snaps". | |
| 177 | ||
| 178 | **D. Drop the crane.** Replace it with a traditional model without reverse | |
| 179 | folds or sinks. Most traditional animals use reverse folds; the crane is the | |
| 180 | model most people will open the app for. | |
| 181 | ||
| 182 | ## Plan changes made for option A | |
| 183 | ||
| 184 | - **Task 0b** (new, before Task 1, batch A2): a model for non-rigid steps and | |
| 185 | its strain bound, a verified bird base for the petal fold, the sampan's | |
| 186 | inversion and the masu's wall-raising. Record 0002. | |
| 187 | - **Task 1:** `AxisRecord` gains `parent: Int?` (the axis whose motion carries | |
| 188 | it), `window: [Double]?` (its span of *t*, default `[0, 1]`) and | |
| 189 | `angles: [Double]?` (a solved curve, 257 samples over its window; absent | |
| 190 | means linear). `StepRecord` gains `nonRigid: Bool`; Task 0b adds what a | |
| 191 | non-rigid step needs beyond the flag. | |
| 192 | - **Task 3:** `FoldAxis` carries the same; `readSteps` builds the tree and | |
| 193 | rejects a parent cycle or a window outside 0…1. | |
| 194 | - **Task 4:** `positions(at:)` composes rotations down the tree, using each | |
| 195 | axis's window and curve (cubic Hermite between samples). The isometry | |
| 196 | sweep adds case 3's vertex, built in code with curves from the closed form. | |
| 197 | - **Task 6:** a staggered letter fold is clean where the simultaneous one | |
| 198 | collides. | |
| 199 | - **Task 7:** `foldc` solves each coupled step's curves by the spike's method | |
| 200 | and writes them; the script may name a step's driving crease and give | |
| 201 | creases windows. | |
| 202 | - **Task 8:** the catalogue's isometry sweep exempts flagged steps, which are | |
| 203 | held to Task 0b's bound instead. | |
| 204 | - **Task 2:** unchanged. Removing the overlapping-moving-sets rule (point 5 | |
| 205 | above) is a separate decision, still open. | |
| 206 | ||
| 207 | ## Appendix: spike output | |
| 208 | ||
| 209 | `swift run -c release --package-path spikes/interpolation`: | |
| 210 | ||
| 211 | ``` | |
| 212 | ## Case 1 — letter fold, both flaps valley | |
| 213 | - M1, one linear parameter: max gap 8.88e-16; first collision at t = 0.668 (120.2°) | |
| 214 | - M1 staggered (left on t 0–0.5, right on 0.5–1): max gap 8.88e-16; first collision none | |
| 215 | ## Case 2 — letter fold, left valley, right mountain | |
| 216 | - M1: max gap 8.88e-16; first collision none | |
| 217 | ||
| 218 | ## Case 3 — flat-foldable degree-4 vertex, sectors 60°, 80°, 120°, 100° | |
| 219 | - M1, all four angles linear to the assignment with the odd crease at 0°: max gap 1.38e0 on a sheet of side 2 | |
| 220 | - M1, all four angles linear to the assignment with the odd crease at 60°: max gap 1.08e0 on a sheet of side 2 | |
| 221 | - M2, 140° crease driven 0 → 180, 0° and 260° creases solved, 60° crease measured (seed for 0°: −): max gap 4.19e-12; angles (0°, 60°, 140°, 260°) at t = 0.25: 45.0, -16.4, 45.0, 16.4; 0.5: 90.0, -38.3, 90.0, 38.3; 0.75: 135.0, -80.0, 135.0, 80.0; 1: 180.0, -180.0, 180.0, 180.0 | |
| 222 | - M2, 140° crease driven 0 → 180, 0° and 260° creases solved, 60° crease measured (seed for 0°: +): max gap 4.19e-12; angles (0°, 60°, 140°, 260°) at t = 0.25: 45.0, -16.4, 45.0, 16.4; 0.5: 90.0, -38.3, 90.0, 38.3; 0.75: 135.0, -80.0, 135.0, 80.0; 1: 180.0, -180.0, 180.0, 180.0 | |
| 223 | - closed form tan(ρ₁/2) = k·tan(ρ₂/2), k = cos((α+β)/2) / cos((α−β)/2) = 0.3473 for α = 60°, β = 80° | |
| 224 | - solved curves sampled at N + 1 points and interpolated, max gap on a sheet of side 2: N = 16: linear 1.0e-2, cubic 1.07e-3; N = 32: linear 2.49e-3, cubic 1.22e-4; N = 64: linear 6.27e-4, cubic 1.49e-5; N = 128: linear 1.57e-4, cubic 1.83e-6; N = 256: linear 3.92e-5, cubic 2.25e-7 | |
| 225 | ||
| 226 | ## Case 4 — inside reverse fold, 4×2 sheet folded on its spine y = 1 | |
| 227 | - start gap 0. Body spine and tip spine start at 180, reverse creases A (upper layer) and B (lower layer) at 0. Angles below are measured from the geometry and unwrapped, so a value past ±180 means a face went through its neighbour at the hinge. | |
| 228 | - (a) body held at 180, B → 180.0, A solved (seed +): max gap 8.06e-14; ranges body 180.0…180.0, tip 180.0…180.0, A -180.0…0, B 0…180.0; end body 180.0, tip 180.0, A -180.0, B 180.0 | |
| 229 | - (a) body held at 180, B → 180.0, A solved (seed −): max gap 8.19e-14; ranges body 180.0…180.0, tip 180.0…180.0, A -180.0…0, B 0…180.0; end body 180.0, tip 180.0, A -180.0, B 180.0 | |
| 230 | - (b) body free, B → 180.0, body and A solved: max gap 8.19e-14; ranges body 180.0…180.0, tip 180.0…180.0, A -180.0…0, B 0…180.0; end body 180.0, tip 180.0, A -180.0, B 180.0 | |
| 231 | - (a) body held at 180, B → -180.0, A solved (seed +): max gap 8.14e-14; ranges body 180.0…180.0, tip 180.0…180.0, A 0…180.0, B -180.0…0; end body 180.0, tip 180.0, A 180.0, B -180.0 | |
| 232 | - (a) body held at 180, B → -180.0, A solved (seed −): max gap 6.37e-14; ranges body 180.0…180.0, tip 180.0…180.0, A 0…180.0, B -180.0…0; end body 180.0, tip 180.0, A 180.0, B -180.0 | |
| 233 | - (b) body free, B → -180.0, body and A solved: max gap 8.14e-14; ranges body 180.0…180.0, tip 180.0…180.0, A 0…180.0, B -180.0…0; end body 180.0, tip 180.0, A 180.0, B -180.0 | |
| 234 | - (c) body free, tip spine driven 180 → −180, body and B solved (seed B +): max gap 9.93e-14; ranges body -180.0…180.0, tip -180.0…180.0, A 0…0, B 0…0; end body -180.0, tip -180.0, A 0, B 0 | |
| 235 | - (c) body free, tip spine driven 180 → −180, body and B solved (seed B −): max gap 9.99e-14; ranges body -180.0…180.0, tip -180.0…180.0, A 0…0, B 0…0; end body -180.0, tip -180.0, A 0, B 0 | |
| 236 | - (c′) phase 1, tip spine 180 → 0: max gap 10.0e-14; ranges body 0…180.0, tip 0…180.0, A 0…0, B 0…0; end body 0, tip 0, A 0, B 0 | |
| 237 | - (c′) phase 2, tip spine 0 → −180 (seed B +): max gap 9.68e-14; ranges body 0…180.0, tip -180.0…0, A 0…180.0, B 0…180.0; end body 180.0, tip -180.0, A 180.0, B 180.0 | |
| 238 | - (c′) phase 2, tip spine 0 → −180 (seed B −): max gap 9.96e-14; ranges body -180.0…0, tip -180.0…0, A 0…0, B 0…0; end body -180.0, tip -180.0, A 0, B 0 | |
| 239 | - (d) M4, body held at 180, tip spine forced 180 → −180, B least-squares: max gap 2.0e0; ranges body 180.0…180.0, tip -180.0…180.0, A 0…180.0, B 0…180.0; end body 180.0, tip -180.0, A 180.0, B 180.0 (flap height 1) | |
| 240 | - (e) body spine opened to φ at mid-fold, tip spine driven through, B least-squares: φ 180.0° → gap 2.0e0; φ 150.0° → gap 1.6e0; φ 120.0° → gap 1.16e0; φ 90.0° → gap 7.32e-1; φ 60.0° → gap 3.56e-1; φ 30.0° → gap 2.42e-1; φ 10.0° → gap 4.05e-1; φ 0° → gap 4.81e-1 | |
| 241 | ||
| 242 | ## Case 5 — petal fold of a preliminary base's front flap | |
| 243 | - 20 faces, 26 creases, 14 free on the spanning tree, 4 measured off it; preliminary base start gap 2.48e-16 | |
| 244 | - the petal fold's own creases only (hinge driven; 4 of the 4 kite creases on the tree, the rest measured): | |
| 245 | - kite seed +: max gap 1.1e-15; collision at t = 0.735; hinge 0…180.0; front kites 0…180.0, 0…180.0 → 180.0, 180.0; inner kites -180.0…0, -180.0…0 → -180.0, -180.0; outer midline segments -180.0…-180.0, -180.0…-180.0 → -180.0, -180.0; inner square sides -180.0…0, 0…180.0, 0…180.0, -180.0…0 → -180.0, 180.0, 180.0, -180.0; creases changed: 10; front kite at t = 0.25, 0.5, 0.75: 45.0, 90.0, 135.0 | |
| 246 | - M1, the same end state with every angle linear: max gap 1.11e-15 | |
| 247 | - kite seed −: max gap 1.27e-15; collision none; hinge 0…180.0; front kites -180.0…0, -180.0…0 → -180.0, -180.0; inner kites 0…180.0, 0…180.0 → 180.0, 180.0; outer midline segments -180.0…-180.0, -180.0…-180.0 → -180.0, -180.0; inner square sides -180.0…0, 0…180.0, 0…180.0, -180.0…0 → -180.0, 180.0, 180.0, -180.0; creases changed: 10; front kite at t = 0.25, 0.5, 0.75: -45.0, -90.0, -135.0 | |
| 248 | - M1, the same end state with every angle linear: max gap 1.31e-15 | |
| 249 | - front point (0,0): (1.0, 1.0, 0) → (0.646, 0.646, -0.5) → (0.293, 0.293, 0) | |
| 250 | - side corner (0.5,0): (1.0, 0.5, 0) → (0.907, 0.657, -0.073) → (0.646, 0.646, 0) | |
| 251 | - inner corner (1,0): (1.0, 1.0, 0) → (0.646, 0.646, -0.5) → (0.293, 0.293, 0) | |
| 252 | - hinge end B: (0.793, 0.5, 0) → (0.793, 0.5, 0) → (0.793, 0.5, 0) | |
| 253 | - control, every crease outside the back quadrant free (14 unknowns): max gap 9.57e-16; collision none; hinge 0…180.0; front kites 0…0, 0…0 → 0, 0; inner kites 0…0, 0…0 → 0, 0; outer midline segments -180.0…-180.0, -180.0…-180.0 → -180.0, -180.0; inner square sides -180.0…0, 0…180.0, 0…180.0, -180.0…0 → -180.0, 180.0, 180.0, -180.0; creases changed: 6 | |
| 254 | ||
| 255 | ``` | |
docs/superpowers/plans/2026-10-19-fold.md +173 −39
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | **Goal:** An iOS app that folds traditional origami models under your finger and generates their Yoshizawa–Randlett diagrams from the same data, so the diagram and the model cannot disagree. |
| 6 | 6 | |
| 7 | **Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives; 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. | |
| 7 | **Architecture:** A model is one FOLD file whose `file_frames` are its steps, sharing one topology: frame 0 is the sheet already subdivided by every crease the sequence will use. Each frame carries an authored `krz:step` naming its kind, technique, instruction, axes, moving sets and viewpoint. Intermediate geometry is rigid rotation of the moving facets on one parameter the finger drives: a step's axes form a tree, each with its own window on that parameter and, where faces form loops, an angle curve `foldc` solves (decision 0001). Reverse folds, sinks and inversions have no rigid path and are flagged non-rigid, moving by the model Task 0b chooses. Draw order is hybrid — the depth buffer between clusters of near-coplanar overlapping faces, the active `faceOrders` within each. The frames are produced by a macOS fold-script compiler that ships with the repo but not in the app. | |
| 8 | 8 | |
| 9 | 9 | **Tech Stack:** Swift 6, iOS 26, SwiftUI, Metal, `simd`, Swift Testing, XcodeGen. No third-party runtime dependencies in the app. |
| 10 | 10 | |
| @@ -26,9 +26,10 @@ | ||
| 26 | 26 | - **One topology across every frame.** Enforced by the decoder and the validator. |
| 27 | 27 | - **Steps are authored, never derived from a frame diff.** That includes `instruction`, which is the accessibility label. |
| 28 | 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. | |
| 29 | - Paper is rigid flat facets hinged at straight creases, except during a step flagged `nonRigid`. No stiffness, self-collision response or crumpling. | |
| 30 | - **Interpolation (decision 0001, option A).** A step's axes form a tree: an axis may name a parent axis whose motion carries it. Each axis has a window on *t* (default 0…1) and either a linear angle or a solved curve of 257 samples, rebuilt by cubic Hermite interpolation. Steps whose technique has no rigid path — inside and outside reverse folds, sinks, inversions — carry `nonRigid: true`; the isometry gate does not apply to them and Task 0b's strain bound does. | |
| 30 | 31 | - 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 | - v1 ships **four** traditional models: the cup, the crane, the sampan and the box (the masu). Every `file_author` is exactly `"Traditional"`, enforced by the validator. | |
| 32 | 33 | - Every shipped model is produced by `foldc` from a committed crease pattern and fold script, and recompiling them reproduces the shipped file (structurally, coordinates within 1e-12). Hand-edited `.fold` files are not shipped. |
| 33 | 34 | - 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 | 35 | - The app never advances the fold parameter on its own. |
| @@ -38,7 +39,7 @@ | ||
| 38 | 39 | |
| 39 | 40 | ## Review Focus |
| 40 | 41 | |
| 41 | 1. **A step with several simultaneous axes.** A petal fold and a reverse fold move several facet sets about several creases at once on one shared parameter, and their faces form closed loops around interior vertices. The interpolation model for these is measured in Task 0 and implemented in Task 4; the axis records are read in Task 3. | |
| 42 | 1. **A step with several simultaneous axes.** A petal fold moves several facet sets about several creases at once on one shared parameter; where faces form closed loops around interior vertices the angles are coupled nonlinearly, and some axes are carried by others. Decision 0001 settled the model; the axis tree, windows and curves are read in Task 3, applied in Task 4 and solved in Task 7. Steps with no rigid path are Task 0b's. | |
| 42 | 43 | 2. **Two facets that are both moving.** The end frame's ordering does not order two simultaneously moving sets against each other during the motion. Such a step must carry `krz:faceOrders_midFold` or be rejected. Test in Task 2. Task 0 also reports whether this rule has a consumer the clusters do not already cover. |
| 43 | 44 | 3. **Coplanar stacked facets, and orbiting underneath.** The depth buffer cannot order coplanar or nearly coplanar facets, and `faceOrders`'s `s` sign reverses when the view crosses `g`'s plane. Stacked facets must not z-fight at any orbit angle or at the start and end of a fold, and the stack must not invert when you orbit under it. Test in Tasks 5 and 10. |
| 44 | 45 | 4. **A degenerate drag direction.** When the moving facet's centroid travels nearly along the view direction the drag projection approaches zero and the fold becomes uncontrollable. Test in Task 12. |
| @@ -58,6 +59,7 @@ Every fixture except where noted has `file_author: "Traditional"`, an `instructi | ||
| 58 | 59 | | `mountain.fold` | as `half.fold` | 1: mountain fold f1 behind f0 about e6, 0 → −180 | |
| 59 | 60 | | `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 | 61 | | `letter-sequential.fold` | as `letter.fold`, both creases valley | 1: f0 over f1. 2: f2 over both, `repeatOf: 1` | |
| 62 | | `letter-staggered.fold` | as `letter.fold`, both creases valley | 1: one step, two axes: f0 over f1 on window 0…0.5, then f2 over both on 0.5…1. The sets overlap in projection, so frame 1 carries `krz:faceOrders_midFold`, equal to its `faceOrders`. Frame 1 is `letter-sequential.fold`'s frame 2 | | |
| 61 | 63 | | `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 | 64 | | `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 | 65 | |
| @@ -98,14 +100,15 @@ Done once, before Task 0. | ||
| 98 | 100 | | Batch | Tasks | Branch | |
| 99 | 101 | |---|---|---| |
| 100 | 102 | | A | 0 — interpolation spike | `spike-interpolation` | |
| 103 | | A2 | 0b — non-rigid steps, petal fold, sampan, masu | `spike-non-rigid` | | |
| 101 | 104 | | B | 1–3 — decoding, validator, steps | `format-and-steps` | |
| 102 | 105 | | C | 4–6 — interpolation, layer order, interpenetration | `folding-engine` | |
| 103 | 106 | | D | 7–8 — `foldc`, `foldlint`, the cup | `compiler-and-cup` | |
| 104 | 107 | | E | 9–10 — diagram, renderer | `diagram-and-renderer` | |
| 105 | 108 | | F | 11–14 — the app | `app` | |
| 106 | | G | 15 — crane, boat, box | `models` | | |
| 109 | | G | 15 — crane, sampan, box | `models` | | |
| 107 | 110 | |
| 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`. | |
| 111 | Batches A and A2 merge alone, since Tasks 0 and 0b can stop the plan. Each batch commits task by task on its branch, ends with `gitbay mr create --source <branch> --target main`, merges when `swift test --package-path Packages/FoldKit` (and, from batch F, the `xcodebuild` test) is green, and the branch is then deleted locally and remotely. Commit messages end with `Ref #N` for the batch's issue; the batch's last commit uses `Closes #N`. | |
| 109 | 112 | 4. If `xcrun metal --version` fails, run `xcodebuild -downloadComponent MetalToolchain`. SwiftPM invokes `metal` for the `.metal` file in Task 10; on 2026-10-19 this machine had no Metal toolchain. |
| 110 | 113 | |
| 111 | 114 | --- |
| @@ -139,7 +142,7 @@ Done once, before Task 0. | ||
| 139 | 142 | |
| 140 | 143 | **Also record:** |
| 141 | 144 | |
| 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. | |
| 145 | - 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 sampan's final turn inside out; the cup has none — with the case above that stands in for it and the model that covers it. | |
| 143 | 146 | - 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 | 147 | |
| 145 | 148 | **Exit criteria:** |
| @@ -150,18 +153,69 @@ Done once, before Task 0. | ||
| 150 | 153 | |
| 151 | 154 | This is a measurement, not TDD. |
| 152 | 155 | |
| 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 | - [x] **Step 1: Build the spike package and the five cases** | |
| 157 | - [x] **Step 2: Implement M1 and M2, and M3 and M4 as far as case 4 needs them** | |
| 158 | - [x] **Step 3: Run and record** | |
| 156 | 159 | |
| 157 | 160 | Run: `swift run --package-path spikes/interpolation` |
| 158 | 161 | |
| 162 | - [x] **Step 4: Write the decision record and apply the exit criteria** | |
| 163 | - [x] **Step 5: Commit** | |
| 164 | ||
| 165 | ```bash | |
| 166 | git add spikes docs | |
| 167 | git commit -m "Interpolation model spike and decision record" | |
| 168 | ``` | |
| 169 | ||
| 170 | --- | |
| 171 | ||
| 172 | ### Task 0b: Non-rigid steps and the remaining coupled steps | |
| 173 | ||
| 174 | **Files:** | |
| 175 | - Modify: `spikes/interpolation` — cases 6–9 | |
| 176 | - Create: `docs/decisions/0002-non-rigid-steps.md` | |
| 177 | - Modify at the end: the design doc's *Interpolation* section, this plan's Tasks 1, 3, 4, 7, 8 and 15, and `CLAUDE.md` | |
| 178 | ||
| 179 | **Why.** Decision 0001 found no rigid motion that makes an inside reverse fold with the flap closed, and chose option A: such steps are flagged `nonRigid` and move by a designed non-rigid motion held to a stated strain bound. This task chooses that motion and the bound, and measures the coupled steps 0001 left open. Task 1 encodes the result, so it comes first. | |
| 180 | ||
| 181 | **Cases**, continuing 0001's numbering: | |
| 182 | ||
| 183 | 6. **Reverse fold with bending**, on case 4's flap. Candidates: | |
| 184 | - **virtual creases** — extra edges in the flap's layers near the vertex (a fan from it), never drawn, flat in every frame and free to fold during the step. If some number of them gives a rigid path that keeps the flap mostly closed, the step is rigid on a finer mesh: zero gap, and the bend shows as their largest angle. They are subdivision edges in the format, which already allows them. | |
| 185 | - **pose interpolation** — per-face transforms through solved intermediate poses (the flap opened to φ, the tip swung through), interpolated between them; strain is the gap. | |
| 186 | ||
| 187 | Measure for each: the largest gap, the largest opening of the flap, the largest virtual-crease angle, and collisions, across φ and the number of virtual creases. 0001 measured naive schedules at 0.24–1.6 of the flap's height; the question is how far a designed motion gets below that. | |
| 188 | 7. **Petal fold, verified.** A bird-base crease pattern with its mountain–valley assignment from a citable source — Lang, *Origami Design Secrets*, or the base folded in Oriedita and exported — recorded with its source. Check it is flat-foldable at every vertex (Kawasaki, and Maekawa against the assignment). Then measure the petal fold as 0001's case 5 did, and check that the inner layers' corners stay down. | |
| 189 | 8. **Sampan, turning inside out.** The crease pattern of the sequence Task 15 will author, with its source. Does any rigid path exist? Rigid (M2), or flagged. | |
| 190 | 9. **Masu, raising the walls.** The traditional masu's crease pattern, walls ending at 90°. Does M2 find a rigid path? Rigid, or flagged. | |
| 191 | ||
| 192 | **Exit criteria:** | |
| 193 | ||
| 194 | - `docs/decisions/0002-non-rigid-steps.md` holds: the non-rigid model and the data it adds to `krz:step`; the strain metric and the bound the app promises; and, for every v1 step that is not a single independent fold, whether it is rigid (M2) or flagged, with the case that stands in for it. | |
| 195 | - In the same merge request, apply the result: | |
| 196 | - the design doc's *Interpolation* section; | |
| 197 | - Task 1 (the non-rigid step's data) and Task 3; | |
| 198 | - Task 4 (the non-rigid path and its tests); | |
| 199 | - Task 7 (how `foldc` produces a non-rigid step); | |
| 200 | - Task 8 (the bound's test for flagged steps); | |
| 201 | - Task 15 (which steps are flagged); | |
| 202 | - `CLAUDE.md`. | |
| 203 | - If a v1 step is neither rigid nor within a bound worth promising: **stop**. The author decides, as after Task 0. | |
| 204 | ||
| 205 | This is a measurement, not TDD. | |
| 206 | ||
| 207 | - [ ] **Step 1: Find the bird base and the sampan's crease patterns, and record their sources** | |
| 208 | - [ ] **Step 2: Add cases 6–9 to the spike** | |
| 209 | - [ ] **Step 3: Run and record** | |
| 210 | ||
| 211 | Run: `swift run -c release --package-path spikes/interpolation` | |
| 212 | ||
| 159 | 213 | - [ ] **Step 4: Write the decision record and apply the exit criteria** |
| 160 | 214 | - [ ] **Step 5: Commit** |
| 161 | 215 | |
| 162 | 216 | ```bash |
| 163 | 217 | git add spikes docs |
| 164 | git commit -m "Interpolation model spike and decision record" | |
| 218 | git commit -m "Non-rigid steps: model, bound and the remaining coupled steps" | |
| 165 | 219 | ``` |
| 166 | 220 | |
| 167 | 221 | --- |
| @@ -185,9 +239,9 @@ git commit -m "Interpolation model spike and decision record" | ||
| 185 | 239 | - `enum StepKind: String, Codable, Sendable { case fold, foldAndUnfold, turnOver, rotate }` |
| 186 | 240 | - `enum StepTechnique: String, Codable, Sendable { case plain, insideReverse, outsideReverse, squash, petal, sink }` |
| 187 | 241 | - `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? }` | |
| 242 | - `struct AxisRecord: Codable, Equatable, Sendable { let edge: Int; let movingFaces: [Int]; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: [Double]?; let angles: [Double]? }` — `parent` is the index, in the same step's `axes`, of the axis whose motion carries this one; `window` is `[t0, t1]`, default `[0, 1]`; `angles` is a solved curve, the fold angle at 257 evenly spaced points of the window, absent for a linear axis | |
| 189 | 243 | - `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 }` | |
| 244 | - `struct StepRecord: Codable, Equatable, Sendable { let kind: StepKind; let technique: StepTechnique; let instruction: String?; let axes: [AxisRecord]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let viewpoint: Viewpoint }` — `nonRigid` decodes to `false` when absent; Task 0b adds the data a non-rigid step carries | |
| 191 | 245 | - `struct FoldFrame: Codable, Sendable { var verticesCoords: [SIMD3<Double>]; var edgesAssignment: [EdgeAssignment]; var edgesFoldAngle: [Double]; var faceOrders: [[Int]]; var faceOrdersMidFold: [[Int]]?; var step: StepRecord? }` |
| 192 | 246 | - `struct FoldFile: Codable, Sendable { var fileSpec: Double; var fileCreator: String?; var fileTitle: String?; var fileAuthor: String?; var fileClasses: [String]; var edgesVertices: [[Int]]; var facesVertices: [[Int]]; var edgesFirstCreasedAtStep: [Int?]; var frames: [FoldFrame] }` — `frames[0]` is the key frame, `frames[n]` is frame n |
| 193 | 247 | - `var (FoldFile).stepCount: Int { get }` — `frames.count − 1` |
| @@ -245,6 +299,21 @@ Package manifest: swift-tools-version 6.2, platforms `.iOS(.v26)`, `.macOS(.v26) | ||
| 245 | 299 | #expect(step?.viewpoint == Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))) |
| 246 | 300 | } |
| 247 | 301 | |
| 302 | @Test func decodesAnAxisTreeWithWindowsAndACurve() throws { | |
| 303 | let json = #"{"edge": 3, "movingFaces": [2], "startAngle": 0, "endAngle": 180, "parent": 0,"# + | |
| 304 | #" "window": [0.25, 1], "angles": [0, 90, 180]}"# | |
| 305 | let axis = try JSONDecoder().decode(AxisRecord.self, from: Data(json.utf8)) | |
| 306 | #expect(axis.parent == 0) | |
| 307 | #expect(axis.window == [0.25, 1]) | |
| 308 | #expect(axis.angles == [0, 90, 180]) | |
| 309 | } | |
| 310 | ||
| 311 | @Test func windowsDecodeOnAStaggeredStep() throws { | |
| 312 | let step = try FoldFile(contentsOf: fixture("letter-staggered.fold")).frames[1].step | |
| 313 | #expect(step?.axes.map(\.window) == [[0, 0.5], [0.5, 1]]) | |
| 314 | #expect(step?.nonRigid == false) | |
| 315 | } | |
| 316 | ||
| 248 | 317 | @Test func decodesFirstCreasedAtStepWithNullForBoundaries() throws { |
| 249 | 318 | let f = try FoldFile(contentsOf: fixture("half.fold")) |
| 250 | 319 | #expect(f.edgesFirstCreasedAtStep == [nil, nil, nil, nil, nil, nil, 1]) |
| @@ -324,7 +393,7 @@ The interpenetration checker (Task 6) finds faces that collide in motion. It can | ||
| 324 | 393 | |
| 325 | 394 | ```swift |
| 326 | 395 | @Test(arguments: ["square.fold", "half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", |
| 327 | "quarters.fold", "occlusion.fold"]) | |
| 396 | "letter-staggered.fold", "quarters.fold", "occlusion.fold"]) | |
| 328 | 397 | func acceptsAValidModel(_ name: String) throws { |
| 329 | 398 | #expect(validate(try FoldFile(contentsOf: fixture(name))).isEmpty) |
| 330 | 399 | } |
| @@ -446,21 +515,26 @@ git commit -m "FOLD validator: topology, angles, isometry, cycles and mid-fold o | ||
| 446 | 515 | **Files:** |
| 447 | 516 | - Create: `Packages/FoldKit/Sources/Folding/FoldStep.swift` |
| 448 | 517 | - Create: `Packages/FoldKit/Sources/Folding/StepReader.swift` |
| 518 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/DegreeFourVertex.swift` | |
| 449 | 519 | - Test: `Packages/FoldKit/Tests/FoldingTests/StepReadingTests.swift` |
| 450 | 520 | |
| 451 | 521 | **Interfaces:** |
| 452 | 522 | - Consumes: Task 1 types. |
| 453 | 523 | - 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? }` | |
| 524 | - `struct FoldAxis: Equatable, Sendable { let edge: Int; let origin: SIMD3<Double>; let direction: SIMD3<Double>; let movingFaces: Set<Int>; let startAngle: Double; let endAngle: Double; let peakAngle: Double?; let parent: Int?; let window: ClosedRange<Double>; let curve: [Double]? }` | |
| 455 | 525 | - `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 }` | |
| 526 | - `struct FoldStep: Equatable, Sendable { let index: Int; let kind: StepKind; let technique: StepTechnique; let instruction: String; let axes: [FoldAxis]; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let nonRigid: Bool; let viewpoint: Viewpoint }` — `axes` is ordered so every parent comes before its children | |
| 457 | 527 | - `var (FoldStep).movingFaceUnion: Set<Int> { get }` |
| 458 | 528 | - `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) }` | |
| 529 | - `enum StepError: Error, Equatable, Sendable { case axisNotAnEdge(step: Int, edge: Int); case axisNotOnMovingSetBoundary(step: Int, edge: Int); case movingFacesOutOfRange(step: Int); case overlappingMovingSetsWithinAStep(step: Int); case rotateWithoutDegrees(step: Int); case turnOverWithoutAxis(step: Int); case foldAndUnfoldWithoutPeak(step: Int); case missingInstruction(step: Int); case axisParentCycle(step: Int); case axisWindowOutOfRange(step: Int); case curveTooShort(step: Int) }` | |
| 460 | 530 | |
| 461 | 531 | `readSteps` **reads** the authored `krz:step`; it does not infer axes or moving sets from a frame diff. Deriving a multi-axis decomposition has genuine ambiguities — which side moved, whether a reorientation is a fold, how to partition simultaneous axes — and the author already knows the answer. This task and Task 4 own Review Focus item 1, in the form Task 0 settles. |
| 462 | 532 | |
| 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`. | |
| 533 | `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:)` first maps `t` onto the axis's window, `u = clamp((t − t0) / (t1 − t0), 0, 1)`, so an axis waits before its window and holds after it. Then it is `startAngle + u·(endAngle − startAngle)` for `fold`, `startAngle + (peakAngle − startAngle)·(1 − |2u − 1|)` for `foldAndUnfold`, or, when the axis has a curve, the curve at `u` by cubic Hermite interpolation with central-difference tangents (one-sided at the ends). Decision 0001 measured that 257 samples rebuilt this way keep a coupled vertex's tear under 1e-6. | |
| 534 | ||
| 535 | For an axis with a parent, `origin` and `direction` are still in frame `index − 1`'s coordinates: Task 4 applies the axis's own rotation first and its ancestors' after, so the parent's motion carries it. | |
| 536 | ||
| 537 | `degreeFourVertex()` builds decision 0001's case 3 in code, since its curves cannot be typed: a 2×2 sheet with creases from the centre at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), and one `fold` step from flat to flat-folded. The face between the 140° and 260° creases holds still. Its axes are the 140° crease, linear 0 → 180; the 260° crease, a curve; and the 0° crease, carried by the 260° axis, linear 0 → 180. The 60° crease is off the tree. The curve is the closed form for a flat-foldable degree-4 vertex, `ρ = 2·atan(k·tan(90°·u))` with `k = cos 70° / cos 10°`, sampled at 257 points; the 60° crease follows as `−ρ`. Frame 1 is the flat-folded sheet. `degreeFourExactAngle(_:at:)` evaluates the closed form directly. | |
| 464 | 538 | |
| 465 | 539 | - [ ] **Step 1: Write the failing tests** |
| 466 | 540 | |
| @@ -519,6 +593,20 @@ func movingFaceSetsWithinOneStepAreDisjoint(_ name: String) throws { | ||
| 519 | 593 | #expect(try readSteps(f)[0].instruction == f.frames[1].step?.instruction) |
| 520 | 594 | } |
| 521 | 595 | |
| 596 | @Test func aWindowedAxisWaitsAndThenHolds() throws { | |
| 597 | let s = try readSteps(FoldFile(contentsOf: fixture("letter-staggered.fold")))[0] | |
| 598 | #expect(s.axes[0].angle(at: 0.25, kind: s.kind) == 90) | |
| 599 | #expect(s.axes[1].angle(at: 0.25, kind: s.kind) == 0) | |
| 600 | #expect(s.axes[0].angle(at: 0.75, kind: s.kind) == 180) | |
| 601 | #expect(s.axes[1].angle(at: 0.75, kind: s.kind) == 90) | |
| 602 | } | |
| 603 | ||
| 604 | @Test func aCurveIsInterpolatedBetweenItsSamples() throws { | |
| 605 | let axis = try readSteps(degreeFourVertex()).first!.axes.first { $0.curve != nil }! | |
| 606 | let t = 0.5 + 0.5 / 256 // halfway between two samples | |
| 607 | #expect(abs(axis.angle(at: t, kind: .fold) - degreeFourExactAngle(axis.edge, at: t)) < 1e-6) | |
| 608 | } | |
| 609 | ||
| 522 | 610 | @Test func rotateWithoutDegreesThrows() { |
| 523 | 611 | #expect(throws: StepError.rotateWithoutDegrees(step: 3)) { |
| 524 | 612 | try readSteps(FoldFile(contentsOf: fixture("rotate-no-degrees.fold"))) |
| @@ -559,7 +647,7 @@ git commit -m "Read authored fold steps, including multi-axis and reorientation | ||
| 559 | 647 | - Create: `Packages/FoldKit/Sources/Folding/FoldInterpolator.swift` |
| 560 | 648 | - Test: `Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift` |
| 561 | 649 | |
| 562 | **Interfaces** (as of before Task 0; Task 0 amends them for coupled steps): | |
| 650 | **Interfaces** (decision 0001; Task 0b adds the path for `nonRigid` steps): | |
| 563 | 651 | - Consumes: Task 1 and Task 3 types. |
| 564 | 652 | - Produces: |
| 565 | 653 | - `struct FoldInterpolator: Sendable { init(file: FoldFile, step: FoldStep) }` — interpolates from frame `step.index − 1` to frame `step.index` |
| @@ -571,7 +659,7 @@ There is no separate orientation output: a `turnOver` or `rotate` step's end fra | ||
| 571 | 659 | |
| 572 | 660 | ```swift |
| 573 | 661 | let modelFixtures = ["half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", |
| 574 | "quarters.fold", "occlusion.fold"] | |
| 662 | "letter-staggered.fold", "quarters.fold", "occlusion.fold"] | |
| 575 | 663 | |
| 576 | 664 | @Test func tZeroReproducesTheStartFrame() throws { |
| 577 | 665 | let (file, i) = try interpolator("half.fold", step: 1) |
| @@ -629,6 +717,31 @@ func everyEdgeLengthIsPreservedThroughoutEveryStep(_ name: String) throws { | ||
| 629 | 717 | .allSatisfy { simd_distance($0, $1) < 1e-9 }) |
| 630 | 718 | } |
| 631 | 719 | |
| 720 | @Test func aCoupledVertexStaysWholeThroughout() throws { | |
| 721 | // decision 0001, case 3: curves from the closed form, sampled at 257 points | |
| 722 | let file = degreeFourVertex() | |
| 723 | let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) | |
| 724 | for n in 0...1024 { | |
| 725 | #expect(maxEdgeLengthDrift(i.positions(at: Double(n) / 1024), file) < 1e-6) | |
| 726 | } | |
| 727 | #expect(zip(i.positions(at: 1), file.frames[1].verticesCoords) | |
| 728 | .allSatisfy { simd_distance($0, $1) < 1e-9 }) | |
| 729 | } | |
| 730 | ||
| 731 | @Test func theSameVertexWithLinearAnglesTears() throws { | |
| 732 | // the control: drop the curve and the paper does not hold together | |
| 733 | let file = degreeFourVertex(linear: true) | |
| 734 | let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) | |
| 735 | #expect(maxEdgeLengthDrift(i.positions(at: 0.5), file) > 0.1) | |
| 736 | } | |
| 737 | ||
| 738 | @Test func aStaggeredAxisMovesOnlyInItsWindow() throws { | |
| 739 | let (file, i) = try interpolator("letter-staggered.fold", step: 1) | |
| 740 | let start = file.frames[0].verticesCoords | |
| 741 | #expect(simd_distance(i.positions(at: 0.25)[3], start[3]) < 1e-12) // right flap waits | |
| 742 | #expect(simd_distance(i.positions(at: 0.5)[0], SIMD3(2, 0, 0)) < 1e-9) // left flap down | |
| 743 | } | |
| 744 | ||
| 632 | 745 | @Test func turnOverRotatesTheModelRigidly() throws { |
| 633 | 746 | let (_, i) = try interpolator("half.fold", step: 2) |
| 634 | 747 | #expect(pairwiseDistancesAgree(i.positions(at: 0.5), i.positions(at: 0))) |
| @@ -652,7 +765,7 @@ Expected: FAIL. | ||
| 652 | 765 | |
| 653 | 766 | - [ ] **Step 3: Implement `positions(at:)`** |
| 654 | 767 | |
| 655 | For each axis, rotate its moving faces' vertices about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, with `simd_quatd(angle:axis:)` about the origin-shifted axis. A vertex in no moving set is unchanged. Reorientation steps rotate every vertex as described above. | |
| 768 | Each axis's own transform is the rotation about the line through `origin` along `direction` by `angle(t) − startAngle`, converted to radians, built with `simd_quatd(angle:axis:)` about the origin-shifted axis. A moving face's transform is its axis's own transform followed by its parent's full transform, and so on up the tree, so a carried axis moves with its parent. A vertex in no moving set is unchanged. A vertex shared by faces of different sets takes its position from the first face in `faces_vertices` order that contains it. `foldc`'s curves keep the copies within the isometry tolerance, and the catalogue test (Task 8) checks this. Reorientation steps rotate every vertex as described above. `degreeFourVertex(linear:)` gains a `linear` flag that replaces the curves with straight lines, for the control test. | |
| 656 | 769 | |
| 657 | 770 | - [ ] **Step 4: Run tests to verify they pass** |
| 658 | 771 | |
| @@ -663,7 +776,7 @@ Expected: PASS. | ||
| 663 | 776 | |
| 664 | 777 | ```bash |
| 665 | 778 | git add Packages/FoldKit |
| 666 | git commit -m "Rigid interpolation, including reorientation steps" | |
| 779 | git commit -m "Rigid interpolation on an axis tree with windows and solved curves" | |
| 667 | 780 | ``` |
| 668 | 781 | |
| 669 | 782 | --- |
| @@ -834,6 +947,12 @@ git commit -m "Near-coplanar clustering and view-relative layer order" | ||
| 834 | 947 | #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) |
| 835 | 948 | } |
| 836 | 949 | |
| 950 | @Test func staggeredFlapsDoNotCollide() throws { | |
| 951 | // the same two flaps on separate windows of t | |
| 952 | let (file, i) = try interpolator("letter-staggered.fold", step: 1) | |
| 953 | #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty) | |
| 954 | } | |
| 955 | ||
| 837 | 956 | @Test func aFaceSwingingThroughAFaceItSharesAVertexWithIsDetected() throws { |
| 838 | 957 | // built in code: fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4); moving triangle |
| 839 | 958 | // (0,0,0), (0,2,0), (-1,1,0) hinged on its edge along the y-axis, folding toward +z |
| @@ -890,9 +1009,10 @@ git commit -m "Facet interpenetration checker" | ||
| 890 | 1009 | - Create: `Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift` |
| 891 | 1010 | - Create: `Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift` |
| 892 | 1011 | - 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` | |
| 1012 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,letter-staggered,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 | |
| 1013 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{half,mountain,letter,letter-sequential,letter-staggered,quarters,occlusion}.foldscript` | |
| 895 | 1014 | - Create: `Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/{unresolved-crease,angle-out-of-range}.foldscript` |
| 1015 | - Modify: `Packages/FoldKit/Sources/FoldKitTestSupport/DegreeFourVertex.swift` — `degreeFourPattern()` and `degreeFourScript()`, the same vertex as a crease pattern and a one-step script driven by the 140° crease | |
| 896 | 1016 | - Test: `Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift` |
| 897 | 1017 | |
| 898 | 1018 | **Interfaces:** |
| @@ -900,7 +1020,7 @@ git commit -m "Facet interpenetration checker" | ||
| 900 | 1020 | - Produces: |
| 901 | 1021 | - `struct FoldScript: Codable, Sendable { let creasePattern: String; let title: String; let steps: [ScriptStep] }` — `creasePattern` is relative to the script |
| 902 | 1022 | - `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]? }` | |
| 1023 | - `struct ScriptStep: Codable, Sendable { let kind: StepKind; let technique: StepTechnique?; let instruction: String; let creases: [CreaseRef]; let movingSide: [SIMD2<Double>]; let angles: [Double]?; let peakAngles: [Double]?; let rotateDegrees: Double?; let turnOverAxis: TurnOverAxis?; let repeatOf: Int?; let viewpoint: Viewpoint?; let faceOrders: [OrderOverride]?; let faceOrdersMidFold: [OrderOverride]?; let driver: CreaseRef?; let windows: [[Double]]? }` — `windows` pairs with `creases` | |
| 904 | 1024 | - `enum CreaseRef: Codable, Sendable { case betweenVertices(SIMD2<Double>, SIMD2<Double>); case edgeIndex(Int) }` |
| 905 | 1025 | - `struct OrderOverride: Codable, Sendable { let above: SIMD2<Double>; let below: SIMD2<Double> }` — points in crease-pattern coordinates naming two faces, "above" as seen from the step's viewpoint |
| 906 | 1026 | - `func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile` |
| @@ -911,7 +1031,9 @@ git commit -m "Facet interpenetration checker" | ||
| 911 | 1031 | |
| 912 | 1032 | **This task is the reason the project is buildable.** No existing FOLD tool authors a multi-frame sequence with folded coordinates, per-frame layer order and per-step moving sets; hand-writing them is hundreds of exact numbers per frame. `foldc` takes a crease pattern exported from an existing editor plus a short script that names each step's creases (by the points they run between), which side moves (by a point inside it), and the step kind, and **computes** every frame by applying the rotations in order. It guesses `faceOrders`, applies the script's overrides, and runs the Task 2 validator and the Task 6 checker after each step. |
| 913 | 1033 | |
| 914 | Defaults: `angles` are each crease's end fold angle, ±180 by the pattern's assignment; `viewpoint` is the previous step's, or `[0, 0, 1]` / `[0, 1, 0]` for step 1; `technique` is `plain`. | |
| 1034 | Defaults: `angles` are each crease's end fold angle, ±180 by the pattern's assignment; `viewpoint` is the previous step's, or `[0, 0, 1]` / `[0, 1, 0]` for step 1; `technique` is `plain`; `driver` is the first crease; `windows` are all `[0, 1]`. | |
| 1035 | ||
| 1036 | **Coupled steps (decision 0001).** The step's creases cut the sheet into regions, each connected across edges this step does not fold. The fixed region is the one no `movingSide` point lies in. A spanning tree of regions, grown from the fixed region across the step's creases, gives each moving region its axis and each axis its parent. A step crease left off that tree closes a loop. If there is none, every axis is linear on its window. If there are some, `foldc` holds the driver linear on its window and solves the other tree axes as the spike does: damped Gauss–Newton on the gap between vertex copies, continued along *t*. It writes each solved axis's curve at 257 points. Each curve is then checked at four times that density, and its samples are doubled until the gap stays under 1e-6 × the sheet's size. A loop that does not close (the solver's gap stays above that) fails the step: the step has no rigid motion and needs `nonRigid` (Task 0b). | |
| 915 | 1037 | |
| 916 | 1038 | Layer-order corrections are `faceOrders` overrides **in the script**. The generated file is never edited; Task 8 checks that recompiling reproduces it. |
| 917 | 1039 | |
| @@ -920,7 +1042,7 @@ macOS only. Never linked into the app. | ||
| 920 | 1042 | - [ ] **Step 1: Write the failing tests** |
| 921 | 1043 | |
| 922 | 1044 | ```swift |
| 923 | @Test(arguments: ["half", "mountain", "letter", "letter-sequential", "quarters", "occlusion"]) | |
| 1045 | @Test(arguments: ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"]) | |
| 924 | 1046 | func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws { |
| 925 | 1047 | let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")), |
| 926 | 1048 | pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold"))) |
| @@ -960,6 +1082,17 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th | ||
| 960 | 1082 | #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) } |
| 961 | 1083 | } |
| 962 | 1084 | |
| 1085 | @Test func aCoupledStepIsSolvedIntoCurves() throws { | |
| 1086 | // decision 0001's case 3 as a script: the 140° crease drives, the 260° crease | |
| 1087 | // gets a curve, the 0° crease rides on it, the 60° crease closes the loop | |
| 1088 | let out = try compile(degreeFourScript(), pattern: degreeFourPattern()) | |
| 1089 | let axes = try #require(out.frames[1].step?.axes) | |
| 1090 | #expect(axes.filter { $0.angles != nil }.count == 1) | |
| 1091 | #expect(axes.contains { $0.parent != nil }) | |
| 1092 | let curved = axes.first { $0.angles != nil }! | |
| 1093 | #expect(abs(curved.angles![128] - degreeFourExactAngle(curved.edge, at: 0.5)) < 1e-6) | |
| 1094 | } | |
| 1095 | ||
| 963 | 1096 | @Test func anUnresolvedCreaseNamesItsStep() { |
| 964 | 1097 | #expect(throws: CompileError.unresolvedCrease(step: 2)) { |
| 965 | 1098 | try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), |
| @@ -1039,11 +1172,12 @@ Its crease pattern and `.foldscript` are committed next to the generated `.fold` | ||
| 1039 | 1172 | } |
| 1040 | 1173 | |
| 1041 | 1174 | @Test func noShippedModelStretchesAtAnyStep() throws { |
| 1175 | // flagged non-rigid steps are held to Task 0b's bound instead | |
| 1042 | 1176 | for file in try ModelLibrary.all() { |
| 1043 | for step in try readSteps(file) { | |
| 1177 | for step in try readSteps(file) where !step.nonRigid { | |
| 1044 | 1178 | 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, | |
| 1179 | for t in stride(from: 0.0, through: 1.0, by: 1.0 / 256) { | |
| 1180 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6, | |
| 1047 | 1181 | "\(file.fileTitle ?? "?") step \(step.index) t \(t)") |
| 1048 | 1182 | } |
| 1049 | 1183 | } |
| @@ -1215,7 +1349,7 @@ Reference, per the spec: Randlett's conventions in *The Art of Origami* (1961) a | ||
| 1215 | 1349 | } |
| 1216 | 1350 | |
| 1217 | 1351 | @Test func everyStepMatchesItsGoldenImage() throws { |
| 1218 | for name in ["half", "mountain", "letter", "letter-sequential", "quarters", "occlusion"] { | |
| 1352 | for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"] { | |
| 1219 | 1353 | let file = try FoldFile(contentsOf: fixture("\(name).fold")) |
| 1220 | 1354 | for step in try readSteps(file) { |
| 1221 | 1355 | try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)") |
| @@ -1694,14 +1828,14 @@ git commit -m "Orbit and zoom, accessibility pass and release assets" | ||
| 1694 | 1828 | |
| 1695 | 1829 | --- |
| 1696 | 1830 | |
| 1697 | ### Task 15: The crane, the boat and the box | |
| 1831 | ### Task 15: The crane, the sampan and the box | |
| 1698 | 1832 | |
| 1699 | 1833 | **Files:** |
| 1700 | 1834 | - Create: `Models/crane.foldscript`, `Models/crane-cp.fold` |
| 1701 | - Create: `Models/boat.foldscript`, `Models/boat-cp.fold` | |
| 1835 | - Create: `Models/sampan.foldscript`, `Models/sampan-cp.fold` | |
| 1702 | 1836 | - 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` | |
| 1837 | - Create: `Packages/FoldKit/Sources/Models/Resources/{crane,sampan,box}.fold` | |
| 1838 | - Create: `docs/authoring/{crane,sampan,box}.md` | |
| 1705 | 1839 | - Modify: `Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift` — delete `theCatalogueContainsTheCup`; `theCatalogueContainsFourModels` below replaces it |
| 1706 | 1840 | - Modify: `Packages/FoldKit/Tests/NotationTests/DiagramTests.swift` — golden images for every step of the three new models |
| 1707 | 1841 | - Test: `Packages/FoldKit/Tests/ModelsTests/FourModelTests.swift` |
| @@ -1709,7 +1843,7 @@ git commit -m "Orbit and zoom, accessibility pass and release assets" | ||
| 1709 | 1843 | **Interfaces:** |
| 1710 | 1844 | - Consumes: everything from Tasks 0–14. No new API. |
| 1711 | 1845 | |
| 1712 | Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Which boat is the author's choice (design, *Open decisions*); do not start the boat until it is made. | |
| 1846 | Authoring, not engineering: three crease patterns, three scripts, and a correction pass over each model's guessed `faceOrders`, made as overrides in the script. Every gate already exists — Task 2's validator, Task 6's interpenetration checker, Task 8's catalogue tests including the isometry sweep — so this task adds no new machinery, only the models and the record of how each was verified. Published sampan sequences differ in their middle steps; `docs/authoring/sampan.md` records which sequence was authored and its source. | |
| 1713 | 1847 | |
| 1714 | 1848 | The crane is deliberately last. It is the model that proves multi-axis petal folds and eight-deep wing stacks work, and by this point the compiler, the renderer and the gestures are all known-good against the cup, so a failure here is an authoring error rather than an ambiguity about which layer is at fault. |
| 1715 | 1849 | |
| @@ -1719,7 +1853,7 @@ Each `docs/authoring/*.md` records the crease pattern's provenance, which guesse | ||
| 1719 | 1853 | |
| 1720 | 1854 | ```swift |
| 1721 | 1855 | @Test func theCatalogueContainsFourModels() throws { |
| 1722 | #expect(try Set(ModelLibrary.names()) == ["cup", "crane", "boat", "box"]) | |
| 1856 | #expect(try Set(ModelLibrary.names()) == ["cup", "crane", "sampan", "box"]) | |
| 1723 | 1857 | } |
| 1724 | 1858 | |
| 1725 | 1859 | @Test func theCraneContainsAMultiAxisStep() throws { |
| @@ -1758,7 +1892,7 @@ Expected: FAIL — only the cup is in the catalogue. | ||
| 1758 | 1892 | |
| 1759 | 1893 | - [ ] **Step 3: Author the three models** |
| 1760 | 1894 | |
| 1761 | Box and boat first, then the crane. Neither the box nor the boat is shallow: the masu's wall-raising step is a coupled 3D step, and the boat depends on which one is chosen; both use whatever Task 0 decided for coupled steps. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly. | |
| 1895 | Box and sampan first, then the crane. Neither is shallow: the masu's wall-raising and the sampan's final turn inside out are coupled 3D steps, classified by Task 0b as rigid or flagged. The crane's inside reverse folds (neck, tail, head) are flagged `nonRigid` and use Task 0b's model; its petal folds use whatever 0b found. Run `foldc`, then `foldlint`, correcting guessed orderings with script overrides where the interpenetration checker or the validator's layer-order rules object. Check each in the app before committing: the checks prove no facet passes through another and no ordering is impossible, but only your eye tells you the fold reads correctly. | |
| 1762 | 1896 | |
| 1763 | 1897 | - [ ] **Step 4: Run tests to verify they pass** |
| 1764 | 1898 | |
| @@ -1769,7 +1903,7 @@ Expected: PASS. | ||
| 1769 | 1903 | |
| 1770 | 1904 | ```bash |
| 1771 | 1905 | git add Models Packages/FoldKit docs/authoring |
| 1772 | git commit -m "The crane, the boat and the box" | |
| 1906 | git commit -m "The crane, the sampan and the box" | |
| 1773 | 1907 | ``` |
| 1774 | 1908 | |
| 1775 | 1909 | --- |
docs/superpowers/specs/2026-10-19-fold-design.md +61 −39
| @@ -39,8 +39,10 @@ angle, at your pace, stopping where you stop. | ||
| 39 | 39 | |
| 40 | 40 | ## Non-goals |
| 41 | 41 | |
| 42 | - Paper simulation. No bending, no stiffness, no self-collision response, | |
| 43 | no crumpling. Paper is rigid flat facets hinged at creases. | |
| 42 | - Paper simulation. No stiffness, no self-collision response, no | |
| 43 | crumpling. Paper is rigid flat facets hinged at creases, except during a | |
| 44 | step flagged `nonRigid` (see *Interpolation*), whose bending is designed, | |
| 45 | not simulated. | |
| 44 | 46 | - Deriving layer order from geometry. Layer order is authored and checked, |
| 45 | 47 | never computed. Computing it in general is a hard problem and getting it |
| 46 | 48 | wrong looks worse than any amount of authoring effort. |
| @@ -75,8 +77,13 @@ community, a serious breach. Every model here is traditional, long | ||
| 75 | 77 | predating any individual claim. Each model's `file_author` is |
| 76 | 78 | `"Traditional"` and the validator enforces it. |
| 77 | 79 | |
| 78 | **v1 ships four: the cup, the crane, the boat and the box.** The box is the | |
| 79 | masu. Which traditional boat is open (see *Open decisions*). The frog base, | |
| 80 | **v1 ships four: the cup, the crane, the sampan and the box.** The box is | |
| 81 | the masu. The sampan was chosen over the paper boat folded from a hat: it | |
| 82 | starts from a square, its middle steps are plain folds, and its one hard | |
| 83 | step — turning the model inside out — comes last, the same kind of 3D | |
| 84 | opening as the masu's. The paper boat needs a rectangle and two collapses | |
| 85 | mid-sequence. Published sampan sequences differ in their middle steps; the | |
| 86 | one authored is recorded in `docs/authoring/sampan.md`. The frog base, | |
| 80 | 87 | fish base, flapping bird and preliminary base are the same kind of thing |
| 81 | 88 | and come afterwards, cheaply, because the compiler will exist. Four is thin |
| 82 | 89 | for a first release but defensible; one is not, and eight is authoring work |
| @@ -212,15 +219,22 @@ Each frame's `krz:step` carries it explicitly: | ||
| 212 | 219 | | "squash" | "petal" | "sink", |
| 213 | 220 | "instruction": "Valley fold the right corner to the left edge.", |
| 214 | 221 | "axes": [ { "edge": 17, "movingFaces": [3, 4, 5], |
| 215 | "startAngle": 0, "endAngle": 180, "peakAngle": null } ], | |
| 222 | "startAngle": 0, "endAngle": 180, "peakAngle": null, | |
| 223 | "parent": null, "window": [0, 1], "angles": null } ], | |
| 216 | 224 | "rotateDegrees": 90, |
| 217 | 225 | "turnOverAxis": "vertical" | "horizontal", |
| 218 | 226 | "repeatOf": 4, |
| 227 | "nonRigid": false, | |
| 219 | 228 | "viewpoint": { "eye": [0, 0, 1], "up": [0, 1, 0] } } |
| 220 | 229 | ``` |
| 221 | 230 | |
| 222 | 231 | - `axes`: the angles are the axis edge's `edges_foldAngle` at the start, |
| 223 | 232 | at the end, and — for `foldAndUnfold` only — at the turning point. |
| 233 | `parent` is the index of the axis whose motion carries this one, | |
| 234 | `window` its span of *t*, and `angles` a solved curve (see | |
| 235 | *Interpolation*); `foldc` writes all three. | |
| 236 | - `nonRigid`: the step has no rigid motion and moves by the non-rigid model | |
| 237 | (see *Interpolation*). Reverse folds, sinks and inversions. | |
| 224 | 238 | - `technique`: drives the notation and the instruction's wording; geometry |
| 225 | 239 | ignores it. `plain` for anything that is not a named technique. |
| 226 | 240 | - `instruction`: the step in words, written by the author in the fold |
| @@ -238,8 +252,8 @@ Each frame's `krz:step` carries it explicitly: | ||
| 238 | 252 | |
| 239 | 253 | All of a step's axes share one parameter, so a petal fold or a reverse fold |
| 240 | 254 | is one step with several axes and several moving sets, driven together. |
| 241 | The traditional models need this. How those axes move together is the | |
| 242 | subject of Task 0; see *Interpolation*. | |
| 255 | The traditional models need this. How those axes move together is set out | |
| 256 | in *Interpolation*. | |
| 243 | 257 | |
| 244 | 258 | ### Step kinds |
| 245 | 259 | |
| @@ -267,12 +281,11 @@ save file size and cost correctness. | ||
| 267 | 281 | |
| 268 | 282 | ### Interpolation |
| 269 | 283 | |
| 270 | This section is the model Task 0 tests, and Task 0 rewrites it with the | |
| 271 | result. Until then it is provisional; nothing that encodes it is built | |
| 272 | before Task 0 finishes. | |
| 284 | Decided by measurement: `docs/decisions/0001-interpolation-model.md`. | |
| 273 | 285 | |
| 274 | Between frame n − 1 and frame n, each of step n's axes rotates its moving | |
| 275 | faces rigidly about its crease line, on one shared parameter *t* in 0...1: | |
| 286 | Between frame n − 1 and frame n, step n's axes form a tree. Each axis | |
| 287 | rotates its moving faces rigidly about its crease line, on one shared | |
| 288 | parameter *t* in 0...1, and carries its children with it: | |
| 276 | 289 | |
| 277 | 290 | - The crease line is the axis edge's endpoints in frame n − 1. |
| 278 | 291 | - The axis is directed the way the moving face adjacent to the edge |
| @@ -280,24 +293,33 @@ faces rigidly about its crease line, on one shared parameter *t* in 0...1: | ||
| 280 | 293 | direction (right-hand rule) turns the moving face toward the side its |
| 281 | 294 | normal points to, which is a valley — so the rotation is |
| 282 | 295 | `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. | |
| 296 | - A face's transform is its axis's rotation followed by the parent axis's | |
| 297 | transform, up the tree. | |
| 298 | - Each axis runs on its **window** `[t0, t1]` of *t*, waiting before it and | |
| 299 | holding after it. Two flaps of equal reach folding toward each other on | |
| 300 | one window collide at 120°. On separate windows they do not, and | |
| 301 | `foldc`'s scripts stagger them. | |
| 302 | - `angle` is linear on the window for `fold`, and a tent through | |
| 303 | `peakAngle` for `foldAndUnfold`, unless the axis has a **curve**. | |
| 304 | - Where the step's faces form loops around interior vertices, the angles | |
| 305 | are coupled nonlinearly — at a flat-foldable degree-4 vertex with | |
| 306 | consecutive sectors α, β, tan(ρ₁/2) = k·tan(ρ₂/2), k = cos((α+β)/2) / | |
| 307 | cos((α−β)/2). Linear angles tear such a vertex by more than half the | |
| 308 | sheet partway through. `foldc` holds one driving crease linear and solves | |
| 309 | the rest so every loop closes. It writes each solved angle as a curve of | |
| 310 | 257 samples; cubic Hermite interpolation between them keeps the tear | |
| 311 | under 1e-6. | |
| 286 | 312 | - `turnOver` and `rotate` rotate every vertex about the start frame's |
| 287 | 313 | bounding-box centre by *t* times the step's angle. |
| 288 | 314 | |
| 289 | This is exact when the moving sets are disjoint, share no vertex except on | |
| 290 | their own axes, and no axis is carried by another set's motion — the letter | |
| 291 | fold, and most single valley and mountain folds. It is **not** exact for | |
| 292 | squash, petal and reverse folds, nor the masu's wall-raising step. There the | |
| 293 | faces form closed loops around interior vertices, the fold angles at a | |
| 294 | vertex are coupled nonlinearly (at a flat-foldable degree-4 vertex, | |
| 295 | tan(ρ₁/2) = k·tan(ρ₂/2)), and some axes are carried by other moving faces. | |
| 296 | Linear, independent rotation of each set tears the paper at the shared | |
| 297 | vertices partway through the fold even though both end frames are exact. | |
| 298 | For an inside reverse fold there is a further question of whether any rigid | |
| 299 | motion exists that keeps the rest of the flap still. Task 0 measures this | |
| 300 | on synthetic cases before any type commits to an answer. | |
| 315 | **Non-rigid steps.** An inside reverse fold has no rigid motion with the flap | |
| 316 | closed. The only rigid path unfolds the flap flat and refolds it, which on | |
| 317 | the crane would undo earlier steps on screen. Reverse folds, sinks and | |
| 318 | inversions are therefore flagged `nonRigid`. They move by a designed | |
| 319 | non-rigid motion, chosen by Task 0b, and are held to a strain bound that | |
| 320 | 0b sets instead of the isometry gate. The interpenetration check still | |
| 321 | applies to them. Task 0b also settles the petal fold, the sampan's | |
| 322 | inversion and the masu's wall-raising. | |
| 301 | 323 | |
| 302 | 324 | ### Layer ordering during a fold |
| 303 | 325 | |
| @@ -500,7 +522,7 @@ overrides, and per-frame validation. Roughly a third of the task, and the | ||
| 500 | 522 | third that makes every model after the first cheap. |
| 501 | 523 | |
| 502 | 524 | **Model-level tests need the same precision.** Assertions about the cup, |
| 503 | crane, boat and box need the same exact coordinates as a shipped model, so | |
| 525 | crane, sampan and box need the same exact coordinates as a shipped model, so | |
| 504 | 526 | they run on compiled models and live with the catalogue (Tasks 8 and 15). |
| 505 | 527 | The unit tests written before the compiler exists use small synthetic |
| 506 | 528 | sheets whose folded coordinates are integers or halves and can be typed |
| @@ -569,14 +591,14 @@ The headline bars get mechanical checks rather than judgement: | ||
| 569 | 591 | 1. **Name.** "Fold" is not going to be available. The repo and bundle ID |
| 570 | 592 | use `fold` / `sh.krz.fold` as working names. |
| 571 | 593 | 2. **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. | |
| 575 | 3. **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. | |
| 579 | 4. **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. | |
| 594 | compiler, cup first, four models for v1. The plan is 17 tasks: two | |
| 595 | interpolation spikes (Tasks 0 and 0b), the engine, the compiler, the app and the | |
| 596 | cup, then the crane, sampan and box as one gated authoring task. | |
| 597 | 3. **The interpolation model for coupled steps.** Settled (decision 0001, | |
| 598 | option A): an axis tree with windows and solved curves for rigid steps, | |
| 599 | flagged non-rigid steps for reverse folds, sinks and inversions. The | |
| 600 | non-rigid model and its strain bound are Task 0b's. | |
| 601 | 4. **Which boat.** Settled: the sampan (see *Rights*). | |
| 602 | 5. **The overlapping-moving-sets rule.** Decision 0001 found no case it | |
| 603 | covers that staggered windows and the near-coplanar clusters do not. | |
| 604 | Removing it is open. | |
spikes/interpolation/Package.swift added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | // swift-tools-version: 6.2 | |
| 2 | import PackageDescription | |
| 3 | ||
| 4 | let package = Package( | |
| 5 | name: "Spike", | |
| 6 | platforms: [.macOS(.v26)], | |
| 7 | targets: [ | |
| 8 | .executableTarget(name: "Spike"), | |
| 9 | ] | |
| 10 | ) | |
spikes/interpolation/Sources/Spike/Collision.swift added +58
| @@ -0,0 +1,58 @@ | ||
| 1 | import simd | |
| 2 | ||
| 3 | /// Two convex faces interpenetrate when the segment where their planes cut both | |
| 4 | /// of them passes through the interior of each. Contact along a boundary or | |
| 5 | /// at a vertex does not count, and coplanar faces are left to the layer order. | |
| 6 | func intersectingPairs(_ faces: [[V3]], eps: Double = 1e-7) -> [(Int, Int)] { | |
| 7 | func normal(_ f: [V3]) -> V3 { | |
| 8 | var n = V3.zero | |
| 9 | for k in f.indices { n += simd_cross(f[k], f[(k + 1) % f.count]) } | |
| 10 | return simd_normalize(n) | |
| 11 | } | |
| 12 | let normals = faces.map(normal) | |
| 13 | ||
| 14 | /// Signed distance of x from each edge line of f, inward positive. | |
| 15 | func inwardDistances(_ f: [V3], _ n: V3, _ x: V3) -> [Double] { | |
| 16 | f.indices.map { j in | |
| 17 | let e0 = f[j], e1 = f[(j + 1) % f.count] | |
| 18 | return simd_dot(simd_cross(e1 - e0, x - e0), n) / simd_length(e1 - e0) | |
| 19 | } | |
| 20 | } | |
| 21 | ||
| 22 | /// The interval of s for which p0 + s·d lies in f. | |
| 23 | func clip(_ f: [V3], _ n: V3, _ p0: V3, _ d: V3) -> (Double, Double)? { | |
| 24 | var lo = -Double.infinity, hi = Double.infinity | |
| 25 | for j in f.indices { | |
| 26 | let e0 = f[j], e1 = f[(j + 1) % f.count] | |
| 27 | let m = simd_cross(n, e1 - e0) // inward normal of the edge, in f's plane | |
| 28 | let a = simd_dot(m, p0 - e0), b = simd_dot(m, d) | |
| 29 | if abs(b) < 1e-15 { if a < -1e-12 { return nil }; continue } | |
| 30 | let s = -a / b | |
| 31 | if b > 0 { lo = max(lo, s) } else { hi = min(hi, s) } | |
| 32 | } | |
| 33 | return lo < hi ? (lo, hi) : nil | |
| 34 | } | |
| 35 | ||
| 36 | var found: [(Int, Int)] = [] | |
| 37 | for i in faces.indices { | |
| 38 | for j in faces.indices where j > i { | |
| 39 | let (a, b, na, nb) = (faces[i], faces[j], normals[i], normals[j]) | |
| 40 | var d = simd_cross(na, nb) | |
| 41 | guard simd_length(d) > 1e-9 else { continue } // parallel or coplanar | |
| 42 | d = simd_normalize(d) | |
| 43 | // A point on both planes: minimise distance to a's first vertex. | |
| 44 | let ca = simd_dot(na, a[0]), cb = simd_dot(nb, b[0]) | |
| 45 | let n12 = simd_dot(na, nb) | |
| 46 | let det = 1 - n12 * n12 | |
| 47 | let p0 = na * ((ca - cb * n12) / det) + nb * ((cb - ca * n12) / det) | |
| 48 | guard let (la, ha) = clip(a, na, p0, d), let (lb, hb) = clip(b, nb, p0, d) else { continue } | |
| 49 | let lo = max(la, lb), hi = min(ha, hb) | |
| 50 | guard hi - lo > eps else { continue } | |
| 51 | let mid = p0 + d * ((lo + hi) / 2) | |
| 52 | if inwardDistances(a, na, mid).allSatisfy({ $0 > eps }) && inwardDistances(b, nb, mid).allSatisfy({ $0 > eps }) { | |
| 53 | found.append((i, j)) | |
| 54 | } | |
| 55 | } | |
| 56 | } | |
| 57 | return found | |
| 58 | } | |
spikes/interpolation/Sources/Spike/Kinematics.swift added +199
| @@ -0,0 +1,199 @@ | ||
| 1 | import simd | |
| 2 | ||
| 3 | infix operator ∘: MultiplicationPrecedence | |
| 4 | ||
| 5 | /// p ↦ q·p + t | |
| 6 | struct Rigid { | |
| 7 | var q = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1) | |
| 8 | var t = V3.zero | |
| 9 | func apply(_ p: V3) -> V3 { q.act(p) + t } | |
| 10 | static func ∘ (a: Rigid, b: Rigid) -> Rigid { Rigid(q: a.q * b.q, t: a.q.act(b.t) + a.t) } | |
| 11 | static func rotation(about p0: V3, direction d: V3, degrees: Double) -> Rigid { | |
| 12 | let q = simd_quatd(angle: degrees * .pi / 180, axis: simd_normalize(d)) | |
| 13 | return Rigid(q: q, t: p0 - q.act(p0)) | |
| 14 | } | |
| 15 | } | |
| 16 | ||
| 17 | /// Places every face from the crease pattern by composing rotations about | |
| 18 | /// creases along a spanning tree of faces. A fold angle is FOLD's: positive | |
| 19 | /// for a valley. Edges off the tree are where the paper would tear, so the | |
| 20 | /// spread between a vertex's copies is the closure residual. | |
| 21 | struct Kinematics { | |
| 22 | let sheet: Sheet | |
| 23 | let root: Int | |
| 24 | /// (child face, parent face, edge) in breadth-first order. | |
| 25 | let tree: [(child: Int, parent: Int, edge: Int)] | |
| 26 | let axes: [Int: (origin: V3, direction: V3)] | |
| 27 | let treeEdges: Set<Int> | |
| 28 | ||
| 29 | /// Only creases on the spanning tree have an angle of their own; the rest | |
| 30 | /// follow from the geometry. `prefer` puts creases on the tree first, in | |
| 31 | /// order, so a crease that is driven or solved for is one the positions | |
| 32 | /// depend on; any that would close a loop are left off. | |
| 33 | init(_ sheet: Sheet, root: Int, prefer: [Int] = []) { | |
| 34 | self.sheet = sheet | |
| 35 | self.root = root | |
| 36 | var component = Array(sheet.faces.indices) | |
| 37 | func find(_ x: Int) -> Int { var x = x; while component[x] != x { x = component[x] }; return x } | |
| 38 | var treeEdges = Set<Int>() | |
| 39 | for e in prefer + sheet.interiorEdges { | |
| 40 | let (f, g) = (find(sheet.edgeFaces[e][0]), find(sheet.edgeFaces[e][1])) | |
| 41 | if f != g { component[f] = g; treeEdges.insert(e) } | |
| 42 | } | |
| 43 | precondition(prefer.first.map(treeEdges.contains) ?? true, "the first preferred crease is not on the tree") | |
| 44 | self.treeEdges = treeEdges | |
| 45 | var seen: Set<Int> = [root] | |
| 46 | var queue = [root] | |
| 47 | var tree: [(Int, Int, Int)] = [] | |
| 48 | var axes: [Int: (V3, V3)] = [:] | |
| 49 | while !queue.isEmpty { | |
| 50 | let f = queue.removeFirst() | |
| 51 | for e in treeEdges.sorted() where sheet.edgeFaces[e].contains(f) { | |
| 52 | let c = sheet.edgeFaces[e].first { $0 != f }! | |
| 53 | guard seen.insert(c).inserted else { continue } | |
| 54 | tree.append((c, f, e)) | |
| 55 | queue.append(c) | |
| 56 | // Directed as the child traverses it, so a positive turn is a valley. | |
| 57 | let (a, b) = sheet.edges[e] | |
| 58 | let face = sheet.faces[c] | |
| 59 | let i = face.firstIndex(of: a)! | |
| 60 | let forward = face[(i + 1) % face.count] == b | |
| 61 | let (u, v) = forward ? (a, b) : (b, a) | |
| 62 | let pu = V3(sheet.verts[u], 0), pv = V3(sheet.verts[v], 0) | |
| 63 | axes[e] = (pu, pv - pu) | |
| 64 | } | |
| 65 | } | |
| 66 | self.tree = tree | |
| 67 | self.axes = axes | |
| 68 | } | |
| 69 | ||
| 70 | func transforms(_ angles: [Double]) -> [Rigid] { | |
| 71 | var T = Array(repeating: Rigid(), count: sheet.faces.count) | |
| 72 | for (c, p, e) in tree { | |
| 73 | let (o, d) = axes[e]! | |
| 74 | T[c] = T[p] ∘ Rigid.rotation(about: o, direction: d, degrees: angles[e]) | |
| 75 | } | |
| 76 | return T | |
| 77 | } | |
| 78 | ||
| 79 | /// Each face's vertices in 3D. | |
| 80 | func positions(_ angles: [Double]) -> [[V3]] { | |
| 81 | let T = transforms(angles) | |
| 82 | return sheet.faces.indices.map { f in sheet.faces[f].map { T[f].apply(V3(sheet.verts[$0], 0)) } } | |
| 83 | } | |
| 84 | ||
| 85 | /// Every interior crease's fold angle as the geometry has it, in (−180, 180]: | |
| 86 | /// the turn of edgeFaces[1] relative to edgeFaces[0] about the edge as | |
| 87 | /// edgeFaces[1] traverses it, positive for a valley. | |
| 88 | func measured(_ angles: [Double]) -> [Double] { | |
| 89 | let T = transforms(angles) | |
| 90 | func normal(_ f: Int) -> V3 { | |
| 91 | let p = sheet.faces[f].map { T[f].apply(V3(sheet.verts[$0], 0)) } | |
| 92 | var n = V3.zero | |
| 93 | for k in p.indices { n += simd_cross(p[k], p[(k + 1) % p.count]) } | |
| 94 | return simd_normalize(n) | |
| 95 | } | |
| 96 | return sheet.edges.indices.map { e in | |
| 97 | guard sheet.edgeFaces[e].count == 2 else { return 0 } | |
| 98 | let (p, c) = (sheet.edgeFaces[e][0], sheet.edgeFaces[e][1]) | |
| 99 | let (a, b) = sheet.edges[e] | |
| 100 | let face = sheet.faces[c] | |
| 101 | let i = face.firstIndex(of: a)! | |
| 102 | let (u, v) = face[(i + 1) % face.count] == b ? (a, b) : (b, a) | |
| 103 | let d = simd_normalize(T[c].apply(V3(sheet.verts[v], 0)) - T[c].apply(V3(sheet.verts[u], 0))) | |
| 104 | let (np, nc) = (normal(p), normal(c)) | |
| 105 | return atan2(simd_dot(simd_cross(np, nc), d), simd_dot(np, nc)) * 180 / .pi | |
| 106 | } | |
| 107 | } | |
| 108 | ||
| 109 | func residual(_ angles: [Double]) -> [Double] { | |
| 110 | let T = transforms(angles) | |
| 111 | var r: [Double] = [] | |
| 112 | for v in sheet.verts.indices { | |
| 113 | let p = V3(sheet.verts[v], 0) | |
| 114 | let fs = sheet.faces.indices.filter { sheet.faces[$0].contains(v) } | |
| 115 | let base = T[fs[0]].apply(p) | |
| 116 | for f in fs.dropFirst() { | |
| 117 | let d = T[f].apply(p) - base | |
| 118 | r += [d.x, d.y, d.z] | |
| 119 | } | |
| 120 | } | |
| 121 | return r | |
| 122 | } | |
| 123 | ||
| 124 | /// Largest distance between two copies of one vertex: zero when the paper is whole. | |
| 125 | func gap(_ angles: [Double]) -> Double { | |
| 126 | let r = residual(angles) | |
| 127 | return stride(from: 0, to: r.count, by: 3).map { simd_length(V3(r[$0], r[$0 + 1], r[$0 + 2])) }.max() ?? 0 | |
| 128 | } | |
| 129 | ||
| 130 | /// Damped Gauss–Newton on the free angles, holding the rest. Returns the final gap. | |
| 131 | @discardableResult | |
| 132 | func solve(_ angles: inout [Double], free: [Int], iterations: Int = 60) -> Double { | |
| 133 | guard !free.isEmpty else { return gap(angles) } | |
| 134 | var lambda = 1e-6 | |
| 135 | var r = residual(angles) | |
| 136 | var cost = r.reduce(0) { $0 + $1 * $1 } | |
| 137 | for _ in 0..<iterations { | |
| 138 | if cost < 1e-26 { break } | |
| 139 | let h = 1e-6 | |
| 140 | var J = Array(repeating: [Double](repeating: 0, count: free.count), count: r.count) | |
| 141 | for (k, e) in free.enumerated() { | |
| 142 | var a = angles | |
| 143 | a[e] += h | |
| 144 | let rp = residual(a) | |
| 145 | a[e] -= 2 * h | |
| 146 | let rm = residual(a) | |
| 147 | for i in r.indices { J[i][k] = (rp[i] - rm[i]) / (2 * h) } | |
| 148 | } | |
| 149 | var improved = false | |
| 150 | for _ in 0..<20 { | |
| 151 | let n = free.count | |
| 152 | var A = Array(repeating: [Double](repeating: 0, count: n), count: n) | |
| 153 | var g = [Double](repeating: 0, count: n) | |
| 154 | for i in r.indices { | |
| 155 | for a in 0..<n { | |
| 156 | g[a] -= J[i][a] * r[i] | |
| 157 | for b in 0..<n { A[a][b] += J[i][a] * J[i][b] } | |
| 158 | } | |
| 159 | } | |
| 160 | for a in 0..<n { A[a][a] += lambda * (1 + A[a][a]) } | |
| 161 | guard let step = solveLinear(A, g) else { lambda *= 10; continue } | |
| 162 | var trial = angles | |
| 163 | for (k, e) in free.enumerated() { trial[e] += step[k] } | |
| 164 | let rt = residual(trial) | |
| 165 | let ct = rt.reduce(0) { $0 + $1 * $1 } | |
| 166 | if ct < cost { | |
| 167 | angles = trial; r = rt; cost = ct | |
| 168 | lambda = max(lambda / 10, 1e-12) | |
| 169 | improved = true | |
| 170 | break | |
| 171 | } | |
| 172 | lambda *= 10 | |
| 173 | } | |
| 174 | if !improved { break } | |
| 175 | } | |
| 176 | return gap(angles) | |
| 177 | } | |
| 178 | } | |
| 179 | ||
| 180 | func solveLinear(_ A: [[Double]], _ b: [Double]) -> [Double]? { | |
| 181 | var M = A, x = b | |
| 182 | let n = b.count | |
| 183 | for c in 0..<n { | |
| 184 | guard let p = (c..<n).max(by: { abs(M[$0][c]) < abs(M[$1][c]) }), abs(M[p][c]) > 1e-300 else { return nil } | |
| 185 | M.swapAt(c, p); x.swapAt(c, p) | |
| 186 | for r in (c + 1)..<n { | |
| 187 | let f = M[r][c] / M[c][c] | |
| 188 | if f == 0 { continue } | |
| 189 | for k in c..<n { M[r][k] -= f * M[c][k] } | |
| 190 | x[r] -= f * x[c] | |
| 191 | } | |
| 192 | } | |
| 193 | for c in stride(from: n - 1, through: 0, by: -1) { | |
| 194 | var s = x[c] | |
| 195 | for k in (c + 1)..<n { s -= M[c][k] * x[k] } | |
| 196 | x[c] = s / M[c][c] | |
| 197 | } | |
| 198 | return x | |
| 199 | } | |
spikes/interpolation/Sources/Spike/Run.swift added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | import simd | |
| 2 | ||
| 3 | /// The geometry's fold angles, unwrapped against the previous sample (or, on | |
| 4 | /// the first, against `ref`), so a crease that keeps turning past ±180 reads | |
| 5 | /// as beyond the range: one face has gone through the other at the hinge. | |
| 6 | func unwrap(_ m: [Double], toward ref: [Double]) -> [Double] { | |
| 7 | zip(m, ref).map { x, r in x + 360 * ((r - x) / 360).rounded() } | |
| 8 | } | |
| 9 | ||
| 10 | struct Sweep { | |
| 11 | var maxGap = 0.0 | |
| 12 | var firstCollision: Double? | |
| 13 | var samples: [(t: Double, angles: [Double])] = [] | |
| 14 | var end: [Double] { samples.last!.angles } | |
| 15 | func angle(_ e: Int, at t: Double) -> Double { | |
| 16 | samples.min { abs($0.t - t) < abs($1.t - t) }!.angles[e] | |
| 17 | } | |
| 18 | func range(_ e: Int) -> (Double, Double) { | |
| 19 | let xs = samples.map { $0.angles[e] } | |
| 20 | return (xs.min()!, xs.max()!) | |
| 21 | } | |
| 22 | } | |
| 23 | ||
| 24 | /// Every angle prescribed as a function of t: no solving, so any tearing shows as gap. | |
| 25 | func prescribed(_ k: Kinematics, steps: Int = 400, collisions: Bool = true, _ angles: (Double) -> [Double]) -> Sweep { | |
| 26 | var s = Sweep() | |
| 27 | for i in 0...steps { | |
| 28 | let t = Double(i) / Double(steps) | |
| 29 | let a = angles(t) | |
| 30 | s.maxGap = max(s.maxGap, k.gap(a)) | |
| 31 | if collisions, s.firstCollision == nil, !intersectingPairs(k.positions(a)).isEmpty { s.firstCollision = t } | |
| 32 | s.samples.append((t, unwrap(k.measured(a), toward: s.samples.last?.angles ?? a))) | |
| 33 | } | |
| 34 | return s | |
| 35 | } | |
| 36 | ||
| 37 | /// Drivers prescribed, free angles solved so the paper stays whole; continued | |
| 38 | /// from the previous sample with a secant predictor. `seed` is the direction | |
| 39 | /// to leave the start in, for starts where several branches meet. | |
| 40 | func continuation(_ k: Kinematics, start: [Double], drivers: [Int: (Double) -> Double], free: [Int], | |
| 41 | seed: [Int: Double] = [:], steps: Int = 400, collisions: Bool = true) -> Sweep { | |
| 42 | var s = Sweep() | |
| 43 | var a = start | |
| 44 | var last: [Double]? = nil | |
| 45 | for i in 0...steps { | |
| 46 | let t = Double(i) / Double(steps) | |
| 47 | var guess = a | |
| 48 | if let l = last { | |
| 49 | for e in free { guess[e] += a[e] - l[e] } | |
| 50 | } else if i == 1 { | |
| 51 | for (e, d) in seed { guess[e] += d / Double(steps) } | |
| 52 | } | |
| 53 | for (e, f) in drivers { guess[e] = f(t) } | |
| 54 | let g = k.solve(&guess, free: free) | |
| 55 | s.maxGap = max(s.maxGap, g) | |
| 56 | if collisions, s.firstCollision == nil, !intersectingPairs(k.positions(guess)).isEmpty { s.firstCollision = t } | |
| 57 | s.samples.append((t, unwrap(k.measured(guess), toward: s.samples.last?.angles ?? start))) | |
| 58 | if i > 0 { last = a } | |
| 59 | a = guess | |
| 60 | } | |
| 61 | return s | |
| 62 | } | |
| 63 | ||
| 64 | func fmt(_ x: Double, _ digits: Int = 1) -> String { | |
| 65 | let p = pow(10.0, Double(digits)) | |
| 66 | let r = (x * p).rounded() / p | |
| 67 | return r == 0 ? "0" : String(r) | |
| 68 | } | |
| 69 | ||
| 70 | func sci(_ x: Double) -> String { | |
| 71 | if x == 0 { return "0" } | |
| 72 | let e = Int(floor(log10(abs(x)))) | |
| 73 | let m = x / pow(10.0, Double(e)) | |
| 74 | return "\(fmt(m, 2))e\(e)" | |
| 75 | } | |
spikes/interpolation/Sources/Spike/Sheet.swift added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | import simd | |
| 2 | ||
| 3 | typealias V2 = SIMD2<Double> | |
| 4 | typealias V3 = SIMD3<Double> | |
| 5 | ||
| 6 | /// A sheet of paper subdivided by straight creases: the planar arrangement of | |
| 7 | /// its boundary and crease segments, with convex counterclockwise faces. | |
| 8 | struct Sheet { | |
| 9 | var verts: [V2] | |
| 10 | var edges: [(Int, Int)] | |
| 11 | var faces: [[Int]] | |
| 12 | var edgeFaces: [[Int]] | |
| 13 | ||
| 14 | init(boundary: [V2], creases: [(V2, V2)]) { | |
| 15 | let eps = 1e-9 | |
| 16 | var segments: [(V2, V2)] = [] | |
| 17 | for i in boundary.indices { segments.append((boundary[i], boundary[(i + 1) % boundary.count])) } | |
| 18 | segments += creases | |
| 19 | ||
| 20 | var verts: [V2] = [] | |
| 21 | func vertex(_ p: V2) -> Int { | |
| 22 | if let i = verts.firstIndex(where: { simd_distance($0, p) < 1e-7 }) { return i } | |
| 23 | verts.append(p) | |
| 24 | return verts.count - 1 | |
| 25 | } | |
| 26 | ||
| 27 | // Points on each segment: its endpoints and every crossing with another segment. | |
| 28 | var onSegment: [[Double]] = segments.map { _ in [0, 1] } | |
| 29 | for i in segments.indices { | |
| 30 | for j in segments.indices where j != i { | |
| 31 | let (a, b) = segments[i], (c, d) = segments[j] | |
| 32 | let r = b - a, s = d - c | |
| 33 | let denom = r.x * s.y - r.y * s.x | |
| 34 | if abs(denom) < eps { | |
| 35 | // Collinear overlap: add the other segment's endpoints that lie on this one. | |
| 36 | for p in [c, d] { | |
| 37 | let t = simd_dot(p - a, r) / simd_dot(r, r) | |
| 38 | if t > -eps, t < 1 + eps, simd_distance(a + t * r, p) < 1e-7 { onSegment[i].append(t) } | |
| 39 | } | |
| 40 | continue | |
| 41 | } | |
| 42 | let q = c - a | |
| 43 | let t = (q.x * s.y - q.y * s.x) / denom | |
| 44 | let u = (q.x * r.y - q.y * r.x) / denom | |
| 45 | if t > -eps, t < 1 + eps, u > -eps, u < 1 + eps { onSegment[i].append(t) } | |
| 46 | } | |
| 47 | } | |
| 48 | ||
| 49 | var edgeSet = Set<[Int]>() | |
| 50 | var edges: [(Int, Int)] = [] | |
| 51 | for (i, (a, b)) in segments.enumerated() { | |
| 52 | let ts = onSegment[i].map { min(max($0, 0), 1) }.sorted() | |
| 53 | var ids: [Int] = [] | |
| 54 | for t in ts { | |
| 55 | let v = vertex(a + t * (b - a)) | |
| 56 | if ids.last != v { ids.append(v) } | |
| 57 | } | |
| 58 | for k in 0..<(ids.count - 1) { | |
| 59 | let key = [min(ids[k], ids[k + 1]), max(ids[k], ids[k + 1])] | |
| 60 | if edgeSet.insert(key).inserted { edges.append((ids[k], ids[k + 1])) } | |
| 61 | } | |
| 62 | } | |
| 63 | ||
| 64 | // Trace faces: each directed edge u→v has its face on the left; the next | |
| 65 | // edge leaves v as the first one clockwise from v→u. | |
| 66 | var out: [[Int]] = Array(repeating: [], count: verts.count) | |
| 67 | for (u, v) in edges { out[u].append(v); out[v].append(u) } | |
| 68 | func angle(_ u: Int, _ v: Int) -> Double { let d = verts[v] - verts[u]; return atan2(d.y, d.x) } | |
| 69 | for u in out.indices { out[u].sort { angle(u, $0) < angle(u, $1) } } | |
| 70 | var used = Set<[Int]>() | |
| 71 | var faces: [[Int]] = [] | |
| 72 | for (a, b) in edges { | |
| 73 | for (u0, v0) in [(a, b), (b, a)] where !used.contains([u0, v0]) { | |
| 74 | var face: [Int] = [] | |
| 75 | var (u, v) = (u0, v0) | |
| 76 | while used.insert([u, v]).inserted { | |
| 77 | face.append(u) | |
| 78 | let around = out[v] | |
| 79 | let k = around.firstIndex(of: u)! | |
| 80 | let w = around[(k - 1 + around.count) % around.count] | |
| 81 | (u, v) = (v, w) | |
| 82 | } | |
| 83 | var area = 0.0 | |
| 84 | for k in face.indices { | |
| 85 | let p = verts[face[k]], q = verts[face[(k + 1) % face.count]] | |
| 86 | area += p.x * q.y - p.y * q.x | |
| 87 | } | |
| 88 | if area > eps { faces.append(face) } | |
| 89 | } | |
| 90 | } | |
| 91 | ||
| 92 | var edgeFaces: [[Int]] = Array(repeating: [], count: edges.count) | |
| 93 | for (f, face) in faces.enumerated() { | |
| 94 | for k in face.indices { | |
| 95 | let (p, q) = (face[k], face[(k + 1) % face.count]) | |
| 96 | if let e = edges.firstIndex(where: { ($0.0 == p && $0.1 == q) || ($0.0 == q && $0.1 == p) }) { | |
| 97 | edgeFaces[e].append(f) | |
| 98 | } | |
| 99 | } | |
| 100 | } | |
| 101 | self.verts = verts | |
| 102 | self.edges = edges | |
| 103 | self.faces = faces | |
| 104 | self.edgeFaces = edgeFaces | |
| 105 | } | |
| 106 | ||
| 107 | var interiorEdges: [Int] { edges.indices.filter { edgeFaces[$0].count == 2 } } | |
| 108 | ||
| 109 | func face(containing p: V2) -> Int { | |
| 110 | faces.indices.first { f in | |
| 111 | let poly = faces[f].map { verts[$0] } | |
| 112 | return poly.indices.allSatisfy { k in | |
| 113 | let a = poly[k], b = poly[(k + 1) % poly.count] | |
| 114 | return (b - a).x * (p - a).y - (b - a).y * (p - a).x > 1e-12 | |
| 115 | } | |
| 116 | }! | |
| 117 | } | |
| 118 | ||
| 119 | /// Interior edges lying on the segment p–q. | |
| 120 | func edges(on p: V2, _ q: V2) -> [Int] { | |
| 121 | interiorEdges.filter { e in | |
| 122 | let (a, b) = edges[e] | |
| 123 | return [verts[a], verts[b]].allSatisfy { x in | |
| 124 | let r = q - p | |
| 125 | let t = simd_dot(x - p, r) / simd_dot(r, r) | |
| 126 | return t > -1e-9 && t < 1 + 1e-9 && simd_distance(p + t * r, x) < 1e-7 | |
| 127 | } | |
| 128 | } | |
| 129 | } | |
| 130 | ||
| 131 | var size: Double { | |
| 132 | let xs = verts.map(\.x), ys = verts.map(\.y) | |
| 133 | return simd_length(V2(xs.max()! - xs.min()!, ys.max()! - ys.min()!)) | |
| 134 | } | |
| 135 | } | |
spikes/interpolation/Sources/Spike/main.swift added +247
| @@ -0,0 +1,247 @@ | ||
| 1 | import simd | |
| 2 | ||
| 3 | func rect(_ x0: Double, _ y0: Double, _ x1: Double, _ y1: Double) -> [V2] { | |
| 4 | [V2(x0, y0), V2(x1, y0), V2(x1, y1), V2(x0, y1)] | |
| 5 | } | |
| 6 | ||
| 7 | func line(_ s: String) { print(s) } | |
| 8 | ||
| 9 | let only = CommandLine.arguments.dropFirst().first | |
| 10 | ||
| 11 | // MARK: 1 and 2 — letter fold | |
| 12 | ||
| 13 | if only == nil || only == "letter" { | |
| 14 | let sheet = Sheet(boundary: rect(0, 0, 3, 3), creases: [(V2(1, 0), V2(1, 3)), (V2(2, 0), V2(2, 3))]) | |
| 15 | let k = Kinematics(sheet, root: sheet.face(containing: V2(1.5, 1.5))) | |
| 16 | let left = sheet.edges(on: V2(1, 0), V2(1, 3)), right = sheet.edges(on: V2(2, 0), V2(2, 3)) | |
| 17 | func set(_ l: Double, _ r: Double) -> [Double] { | |
| 18 | var a = [Double](repeating: 0, count: sheet.edges.count) | |
| 19 | for e in left { a[e] = l } | |
| 20 | for e in right { a[e] = r } | |
| 21 | return a | |
| 22 | } | |
| 23 | let bothValley = prescribed(k) { t in set(180 * t, 180 * t) } | |
| 24 | let staggered = prescribed(k) { t in set(180 * min(1, 2 * t), 180 * max(0, 2 * t - 1)) } | |
| 25 | let valleyMountain = prescribed(k) { t in set(180 * t, -180 * t) } | |
| 26 | line("## Case 1 — letter fold, both flaps valley") | |
| 27 | line("- M1, one linear parameter: max gap \(sci(bothValley.maxGap)); first collision at t = \(bothValley.firstCollision.map { fmt($0, 3) } ?? "none") (\(bothValley.firstCollision.map { fmt($0 * 180, 1) } ?? "-")°)") | |
| 28 | line("- M1 staggered (left on t 0–0.5, right on 0.5–1): max gap \(sci(staggered.maxGap)); first collision \(staggered.firstCollision.map { fmt($0, 3) } ?? "none")") | |
| 29 | line("## Case 2 — letter fold, left valley, right mountain") | |
| 30 | line("- M1: max gap \(sci(valleyMountain.maxGap)); first collision \(valleyMountain.firstCollision.map { fmt($0, 3) } ?? "none")") | |
| 31 | line("") | |
| 32 | } | |
| 33 | ||
| 34 | // MARK: 3 — generic flat-foldable degree-4 vertex | |
| 35 | ||
| 36 | if only == nil || only == "degree4" { | |
| 37 | let rays = [0.0, 60, 140, 260] // sectors 60, 80, 120, 100 | |
| 38 | let ends = rays.map { deg -> V2 in | |
| 39 | let d = V2(cos(deg * .pi / 180), sin(deg * .pi / 180)) | |
| 40 | return d / max(abs(d.x), abs(d.y)) | |
| 41 | } | |
| 42 | let sheet = Sheet(boundary: rect(-1, -1, 1, 1), creases: ends.map { (V2.zero, $0) }) | |
| 43 | let e = ends.map { sheet.edges(on: .zero, $0)[0] } | |
| 44 | // The 60° crease is the one left off the tree: its angle is measured. | |
| 45 | let k = Kinematics(sheet, root: sheet.face(containing: V2(cos(200 * .pi / 180), sin(200 * .pi / 180)) * 0.5), | |
| 46 | prefer: [e[2], e[0], e[3]]) | |
| 47 | line("## Case 3 — flat-foldable degree-4 vertex, sectors 60°, 80°, 120°, 100°") | |
| 48 | // Maekawa and big-little-big: the odd crease bounds the 60° sector, so it is the 0° or the 60° crease. | |
| 49 | func lin(_ signs: [Double]) -> (Double) -> [Double] { | |
| 50 | { t in | |
| 51 | var a = [Double](repeating: 0, count: sheet.edges.count) | |
| 52 | for i in 0..<4 { a[e[i]] = 180 * t * signs[i] } | |
| 53 | return a | |
| 54 | } | |
| 55 | } | |
| 56 | for (name, signs) in [("odd crease at 0°", [-1.0, 1, 1, 1]), ("odd crease at 60°", [1.0, -1, 1, 1])] { | |
| 57 | let m1 = prescribed(k, collisions: false, lin(signs)) | |
| 58 | line("- M1, all four angles linear to the assignment with the \(name): max gap \(sci(m1.maxGap)) on a sheet of side 2") | |
| 59 | } | |
| 60 | for s0 in [-1.0, 1.0] { | |
| 61 | let m2 = continuation(k, start: lin([0, 0, 0, 0])(0), drivers: [e[2]: { 180 * $0 }], free: [e[0], e[3]], | |
| 62 | seed: [e[0]: 180 * s0, e[3]: 180], collisions: false) | |
| 63 | let at = { (t: Double) in [0, 1, 2, 3].map { fmt(m2.angle(e[$0], at: t)) }.joined(separator: ", ") } | |
| 64 | line("- M2, 140° crease driven 0 → 180, 0° and 260° creases solved, 60° crease measured (seed for 0°: \(s0 > 0 ? "+" : "−")): max gap \(sci(m2.maxGap)); angles (0°, 60°, 140°, 260°) at t = 0.25: \(at(0.25)); 0.5: \(at(0.5)); 0.75: \(at(0.75)); 1: \(at(1))") | |
| 65 | } | |
| 66 | // The closed form for a flat-foldable degree-4 vertex with consecutive sectors α, β. | |
| 67 | let k4 = cos((60.0 + 80) / 2 * .pi / 180) / cos((60.0 - 80) / 2 * .pi / 180) | |
| 68 | line("- closed form tan(ρ₁/2) = k·tan(ρ₂/2), k = cos((α+β)/2) / cos((α−β)/2) = \(fmt(k4, 4)) for α = 60°, β = 80°") | |
| 69 | // How densely must foldc sample a solved curve? Sample the solved angles at | |
| 70 | // N + 1 points, rebuild them by linear or cubic interpolation, and measure the tear. | |
| 71 | let reference = continuation(k, start: lin([0, 0, 0, 0])(0), drivers: [e[2]: { 180 * $0 }], free: [e[0], e[3]], | |
| 72 | seed: [e[0]: 180, e[3]: 180], steps: 1024, collisions: false) | |
| 73 | func sampled(_ n: Int) -> [[Double]] { | |
| 74 | (0...n).map { i in [e[0], e[3]].map { reference.angle($0, at: Double(i) / Double(n)) } } | |
| 75 | } | |
| 76 | func cubic(_ ys: [Double], _ t: Double) -> Double { | |
| 77 | let n = ys.count - 1 | |
| 78 | let x = t * Double(n) | |
| 79 | let i = min(Int(x), n - 1), u = x - Double(i) | |
| 80 | let m = { (j: Int) -> Double in | |
| 81 | j == 0 ? ys[1] - ys[0] : j == n ? ys[n] - ys[n - 1] : (ys[j + 1] - ys[j - 1]) / 2 | |
| 82 | } | |
| 83 | let (p0, p1, m0, m1) = (ys[i], ys[i + 1], m(i), m(i + 1)) | |
| 84 | let u2 = u * u, u3 = u2 * u | |
| 85 | return (2 * u3 - 3 * u2 + 1) * p0 + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * p1 + (u3 - u2) * m1 | |
| 86 | } | |
| 87 | var rows: [String] = [] | |
| 88 | for n in [16, 32, 64, 128, 256] { | |
| 89 | let samples = sampled(n) | |
| 90 | func angles(_ interpolate: @escaping ([Double], Double) -> Double) -> (Double) -> [Double] { | |
| 91 | { t in | |
| 92 | var a = lin([0, 0, 0, 0])(0) | |
| 93 | a[e[2]] = 180 * t | |
| 94 | for (j, edge) in [e[0], e[3]].enumerated() { a[edge] = interpolate(samples.map { $0[j] }, t) } | |
| 95 | return a | |
| 96 | } | |
| 97 | } | |
| 98 | let linear = prescribed(k, steps: 2048, collisions: false, angles { ys, t in | |
| 99 | let x = t * Double(ys.count - 1), i = min(Int(x), ys.count - 2), u = x - Double(i) | |
| 100 | return ys[i] + u * (ys[i + 1] - ys[i]) | |
| 101 | }) | |
| 102 | let smooth = prescribed(k, steps: 2048, collisions: false, angles(cubic)) | |
| 103 | rows.append("N = \(n): linear \(sci(linear.maxGap)), cubic \(sci(smooth.maxGap))") | |
| 104 | } | |
| 105 | line("- solved curves sampled at N + 1 points and interpolated, max gap on a sheet of side 2: " + rows.joined(separator: "; ")) | |
| 106 | line("") | |
| 107 | } | |
| 108 | ||
| 109 | // MARK: 4 — inside reverse fold of a two-layer flap | |
| 110 | ||
| 111 | if only == nil || only == "reverse" { | |
| 112 | let sheet = Sheet(boundary: rect(0, 0, 4, 2), creases: [ | |
| 113 | (V2(0, 1), V2(2, 1)), (V2(2, 1), V2(4, 1)), (V2(2, 1), V2(3, 2)), (V2(2, 1), V2(3, 0)), | |
| 114 | ]) | |
| 115 | let root = sheet.face(containing: V2(0.5, 0.5)) | |
| 116 | let body = sheet.edges(on: V2(0, 1), V2(2, 1))[0], tip = sheet.edges(on: V2(2, 1), V2(4, 1))[0] | |
| 117 | let a = sheet.edges(on: V2(2, 1), V2(3, 2))[0], b = sheet.edges(on: V2(2, 1), V2(3, 0))[0] | |
| 118 | var start = [Double](repeating: 0, count: sheet.edges.count) | |
| 119 | start[body] = 180; start[tip] = 180 | |
| 120 | // Tree without the tip spine (driving the reverse creases), or without A (driving the tip spine). | |
| 121 | let byCreases = Kinematics(sheet, root: root, prefer: [body, b, a]) | |
| 122 | let bySpine = Kinematics(sheet, root: root, prefer: [body, tip, b]) | |
| 123 | line("## Case 4 — inside reverse fold, 4×2 sheet folded on its spine y = 1") | |
| 124 | line("- start gap \(sci(byCreases.gap(start))). Body spine and tip spine start at 180, reverse creases A (upper layer) and B (lower layer) at 0. Angles below are measured from the geometry and unwrapped, so a value past ±180 means a face went through its neighbour at the hinge.") | |
| 125 | func row(_ s: Sweep) -> String { | |
| 126 | let r = [body, tip, a, b].map { e in let (lo, hi) = s.range(e); return "\(fmt(lo))…\(fmt(hi))" } | |
| 127 | return "max gap \(sci(s.maxGap)); ranges body \(r[0]), tip \(r[1]), A \(r[2]), B \(r[3]); end body \(fmt(s.end[body])), tip \(fmt(s.end[tip])), A \(fmt(s.end[a])), B \(fmt(s.end[b]))" | |
| 128 | } | |
| 129 | for sb in [1.0, -1.0] { | |
| 130 | for sa in [1.0, -1.0] { | |
| 131 | let s = continuation(byCreases, start: start, drivers: [b: { 180 * $0 * sb }], free: [a], seed: [a: 180 * sa], collisions: false) | |
| 132 | line("- (a) body held at 180, B → \(fmt(180 * sb)), A solved (seed \(sa > 0 ? "+" : "−")): \(row(s))") | |
| 133 | } | |
| 134 | let s = continuation(byCreases, start: start, drivers: [b: { 180 * $0 * sb }], free: [body, a], seed: [a: -180 * sb], collisions: false) | |
| 135 | line("- (b) body free, B → \(fmt(180 * sb)), body and A solved: \(row(s))") | |
| 136 | } | |
| 137 | for st in [1.0, -1.0] { | |
| 138 | let s = continuation(bySpine, start: start, drivers: [tip: { 180 - 360 * $0 }], free: [body, b], seed: [b: 180 * st], collisions: false) | |
| 139 | line("- (c) body free, tip spine driven 180 → −180, body and B solved (seed B \(st > 0 ? "+" : "−")): \(row(s))") | |
| 140 | } | |
| 141 | let phase1 = continuation(bySpine, start: start, drivers: [tip: { 180 * (1 - $0) }], free: [body, b], collisions: false) | |
| 142 | line("- (c′) phase 1, tip spine 180 → 0: \(row(phase1))") | |
| 143 | for st in [1.0, -1.0] { | |
| 144 | let s = continuation(bySpine, start: phase1.end, drivers: [tip: { -180 * $0 }], free: [body, b], seed: [body: 180, b: 180 * st], collisions: false) | |
| 145 | line("- (c′) phase 2, tip spine 0 → −180 (seed B \(st > 0 ? "+" : "−")): \(row(s))") | |
| 146 | } | |
| 147 | let forced = continuation(bySpine, start: start, drivers: [tip: { 180 - 360 * $0 }], free: [b], seed: [b: 180], collisions: false) | |
| 148 | line("- (d) M4, body held at 180, tip spine forced 180 → −180, B least-squares: \(row(forced)) (flap height 1)") | |
| 149 | // (e) How much must the flap open? The body spine opens to φ at mid-fold and | |
| 150 | // closes again, the tip spine is driven through, B is least-squares. | |
| 151 | var curve: [String] = [] | |
| 152 | for phi in [180.0, 150, 120, 90, 60, 30, 10, 0] { | |
| 153 | let s = continuation(bySpine, start: start, | |
| 154 | drivers: [tip: { 180 - 360 * $0 }, body: { 180 - (180 - phi) * sin(.pi * $0) }], | |
| 155 | free: [b], seed: [b: 180], collisions: false) | |
| 156 | curve.append("φ \(fmt(phi, 0))° → gap \(sci(s.maxGap))") | |
| 157 | } | |
| 158 | line("- (e) body spine opened to φ at mid-fold, tip spine driven through, B least-squares: " + curve.joined(separator: "; ")) | |
| 159 | line("") | |
| 160 | } | |
| 161 | ||
| 162 | // MARK: 5 — petal fold of the front flap of a preliminary base | |
| 163 | ||
| 164 | if only == nil || only == "petal" { | |
| 165 | // The bird base's crease pattern on the unit square (after Origami Simulator's | |
| 166 | // birdBase.svg, made exact): midlines, the diagonal through the two quadrants | |
| 167 | // the preliminary base folds in half, the eight 22.5° kite creases, and the | |
| 168 | // square joining their ends on the midlines. | |
| 169 | let h = 0.5 * (2.0.squareRoot() - 1) // 0.5·tan 22.5° | |
| 170 | let L = V2(h, 0.5), B = V2(0.5, h), R = V2(1 - h, 0.5), T = V2(0.5, 1 - h) | |
| 171 | let c00 = V2(0, 0), c10 = V2(1, 0), c11 = V2(1, 1), c01 = V2(0, 1) | |
| 172 | let sheet = Sheet(boundary: rect(0, 0, 1, 1), creases: [ | |
| 173 | (V2(0.5, 0), V2(0.5, 1)), (V2(0, 0.5), V2(1, 0.5)), (c10, c01), | |
| 174 | (c00, B), (c00, L), (c10, B), (c10, R), (c11, R), (c11, T), (c01, T), (c01, L), | |
| 175 | (L, B), (B, R), (R, T), (T, L), | |
| 176 | ]) | |
| 177 | let midlines = sheet.edges(on: V2(0.5, 0), V2(0.5, 1)) + sheet.edges(on: V2(0, 0.5), V2(1, 0.5)) | |
| 178 | let diagonal = sheet.edges(on: c10, c01) | |
| 179 | var start = [Double](repeating: 0, count: sheet.edges.count) | |
| 180 | for e in midlines { start[e] = -180 } | |
| 181 | for e in diagonal { start[e] = 180 } | |
| 182 | let hinge = sheet.edges(on: L, B)[0] | |
| 183 | // Everything outside the back quadrant may move; the back quadrant holds still. | |
| 184 | let back: (Int) -> Bool = { e in | |
| 185 | let (u, v) = sheet.edges[e] | |
| 186 | let m = (sheet.verts[u] + sheet.verts[v]) / 2 | |
| 187 | return m.x > 0.5 - 1e-9 && m.y > 0.5 - 1e-9 | |
| 188 | } | |
| 189 | let movable = sheet.interiorEdges.filter { !back($0) && $0 != hinge } | |
| 190 | let k = Kinematics(sheet, root: sheet.face(containing: V2(0.55, 0.55)), prefer: [hinge] + movable) | |
| 191 | let free = movable.filter(k.treeEdges.contains) | |
| 192 | let kites = [sheet.edges(on: c00, B)[0], sheet.edges(on: c00, L)[0]] | |
| 193 | let innerKites = [sheet.edges(on: c10, B)[0], sheet.edges(on: c01, L)[0]] | |
| 194 | let outerMidlines = [sheet.edges(on: V2(0.5, 0), B)[0], sheet.edges(on: V2(0, 0.5), L)[0]] | |
| 195 | let innerTilted = sheet.edges(on: B, R) + sheet.edges(on: T, L) | |
| 196 | line("## Case 5 — petal fold of a preliminary base's front flap") | |
| 197 | line("- \(sheet.faces.count) faces, \(sheet.interiorEdges.count) creases, \(free.count) free on the spanning tree, \(movable.count + 1 - free.count - 1) measured off it; preliminary base start gap \(sci(k.gap(start)))") | |
| 198 | func row(_ s: Sweep) -> String { | |
| 199 | func r(_ es: [Int]) -> String { es.map { let (lo, hi) = s.range($0); return "\(fmt(lo))…\(fmt(hi))" }.joined(separator: ", ") } | |
| 200 | func end(_ es: [Int]) -> String { es.map { fmt(s.end[$0]) }.joined(separator: ", ") } | |
| 201 | let moved = sheet.interiorEdges.filter { abs(s.end[$0] - start[$0]) > 1 }.count | |
| 202 | return "max gap \(sci(s.maxGap)); collision \(s.firstCollision.map { "at t = \(fmt($0, 3))" } ?? "none"); hinge \(r([hinge])); front kites \(r(kites)) → \(end(kites)); inner kites \(r(innerKites)) → \(end(innerKites)); outer midline segments \(r(outerMidlines)) → \(end(outerMidlines)); inner square sides \(r(innerTilted)) → \(end(innerTilted)); creases changed: \(moved)" | |
| 203 | } | |
| 204 | // Intended as the petal fold: the front point lifts on the hinge, and each | |
| 205 | // side — the front layer's side and the inner layer behind it, still joined | |
| 206 | // along the midline — swings in on its two kite creases. The traced points | |
| 207 | // show the inner layers' corners lifting too, which a petal fold does not | |
| 208 | // do, so this crease pattern is not the bird base; see the decision record. | |
| 209 | let petalKinematics = Kinematics(sheet, root: sheet.face(containing: V2(0.55, 0.55)), prefer: [hinge] + kites + innerKites) | |
| 210 | let petalFree = (kites + innerKites).filter(petalKinematics.treeEdges.contains) | |
| 211 | line("- the petal fold's own creases only (hinge driven; \(petalFree.count) of the 4 kite creases on the tree, the rest measured):") | |
| 212 | for sk in [1.0, -1.0] { | |
| 213 | var seed: [Int: Double] = [:] | |
| 214 | for e in kites where petalFree.contains(e) { seed[e] = 180 * sk } | |
| 215 | for e in innerKites where petalFree.contains(e) { seed[e] = -180 * sk } | |
| 216 | let s = continuation(petalKinematics, start: start, drivers: [hinge: { 180 * $0 }], free: petalFree, seed: seed, steps: 200) | |
| 217 | line(" - kite seed \(sk > 0 ? "+" : "−"): \(row(s)); front kite at t = 0.25, 0.5, 0.75: \([0.25, 0.5, 0.75].map { fmt(s.angle(kites[0], at: $0)) }.joined(separator: ", "))") | |
| 218 | let linear = prescribed(petalKinematics, steps: 200, collisions: false) { t in | |
| 219 | var a = start | |
| 220 | for e in petalKinematics.treeEdges { a[e] = start[e] + t * (s.end[e] - start[e]) } | |
| 221 | return a | |
| 222 | } | |
| 223 | line(" - M1, the same end state with every angle linear: max gap \(sci(linear.maxGap))") | |
| 224 | if sk < 0 { | |
| 225 | // Where the front point, the front layer's side corner and the inner layer's corner go. | |
| 226 | for (name, p) in [("front point (0,0)", c00), ("side corner (0.5,0)", V2(0.5, 0)), ("inner corner (1,0)", c10), ("hinge end B", B)] { | |
| 227 | let f = sheet.faces.indices.first { sheet.faces[$0].contains { simd_distance(sheet.verts[$0], p) < 1e-9 } }! | |
| 228 | let v = sheet.faces[f].first { simd_distance(sheet.verts[$0], p) < 1e-9 }! | |
| 229 | let i = sheet.faces[f].firstIndex(of: v)! | |
| 230 | let path = [0.0, 0.5, 1.0].map { t -> String in | |
| 231 | let a = s.samples.min { abs($0.t - t) < abs($1.t - t) }! | |
| 232 | var angles = start | |
| 233 | for e in petalKinematics.treeEdges { angles[e] = a.angles[e] } | |
| 234 | let q = petalKinematics.positions(angles)[f][i] | |
| 235 | return "(\(fmt(q.x, 3)), \(fmt(q.y, 3)), \(fmt(q.z, 3)))" | |
| 236 | } | |
| 237 | line(" - \(name): \(path.joined(separator: " → "))") | |
| 238 | } | |
| 239 | } | |
| 240 | } | |
| 241 | // With every crease outside the back quadrant free, the solver is | |
| 242 | // underdetermined and finds other mechanisms; the step has to say which | |
| 243 | // creases move, which is what krz:step's axes are for. | |
| 244 | let loose = continuation(k, start: start, drivers: [hinge: { 180 * $0 }], free: free, steps: 200, collisions: false) | |
| 245 | line("- control, every crease outside the back quadrant free (\(free.count) unknowns): \(row(loose))") | |
| 246 | line("") | |
| 247 | } | |