Commit 6793c5e4d7

6793c5e4d77e8496ad4d080a04961ecc10d9a46f

parent: 5bfc2f5fbe

Verified · cmc

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

Interpolation model spike and decision record

Measures linear and solved crease angles on a letter fold, a degree-4
vertex, an inside reverse fold and a petal fold. Reverse folds have no
rigid motion with the flap closed; the decision record lists the options.

Ref #1

Layout: unified · split

docs/decisions/0001-interpolation-model.md added +226
@@ -0,0 +1,226 @@
1# 0001 — Interpolation model
2
3**Status:** measured. Task 0's stop condition is met (the crane's reverse
4folds have no rigid model that matches the fold), so the choice below is the
5author's. Task 1 does not start until it is made.
6
7## Question
8
9How does a step's geometry move between its two frames? Specifically, which
10of these covers each kind of step the four v1 models need:
11
12- **M1** — the design as written: disjoint moving sets, each rotated about its
13 crease in the start frame by a linearly interpolated angle.
14- **M2** — a kinematic tree with solved angle curves: an axis may be carried by
15 another moving face, each axis's angle is a function of *t* (possibly on its
16 own window of *t*), and `foldc` solves the curves so every loop of faces
17 around an interior vertex closes.
18- **M3** — decomposition into sub-steps, each M1 or M2, on one drag.
19- **M4** — non-rigid: per-face transforms between solved poses, exact only at
20 the poses.
21
22## Method
23
24`spikes/interpolation` (`swift run -c release --package-path spikes/interpolation`).
25Each case is a crease pattern built in code. Faces are placed by composing
26rotations about creases along a spanning tree of faces; only creases on the
27tree carry an angle, and every other crease's angle is measured from the
28geometry. The **gap** is the largest distance between two copies of one
29vertex placed through different faces: zero when the paper is whole, the size
30of the tear otherwise. M1 prescribes every angle; M2 drives one crease and
31solves the others by damped Gauss–Newton, continued along *t*. Collisions are
32transversal face–face intersections, ignoring coplanar pairs and boundary
33contact.
34
35## Results
36
37| Case | M1 | M2 / other | Collisions |
38|---|---|---|---|
39| 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 |
40| 2. Letter fold, one valley, one mountain | exact | — | none |
41| 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) = 0.347·tan(ρ₂/2): at the driven crease's 45°, 90°, 135° the other pair is at 16.4°, 38.3°, 80.0° | — |
42| 4. Inside reverse fold, two-layer flap, rest of the flap held | — | no rigid motion reaches it with the flap closed (below) | — |
43| 5. Petal fold of a preliminary base | inconclusive (below) | inconclusive | — |
44
45### Case 4 in detail
46
47Sheet 4×2 folded on its spine y = 1; reverse-fold creases from (2, 1) to
48(3, 0) and (3, 2). Body spine and tip spine start at 180°.
49
50- **Flap held closed** (body spine fixed at 180°): the only rigid motion is the
51 tip swinging about the two coincident reverse creases as one closed unit
52 (tip spine stays 180°, the creases go to ∓180°). That ends at the reverse
53 fold's coordinates with the wrong layering — the tip folded over outside,
54 not between the layers. Gap 8e-14.
55- **Flap free, reverse creases driven:** the solver stays on that same motion.
56- **Flap free, tip spine driven through 0:** the whole flap unfolds and refolds
57 the other way (body spine follows the tip spine to −180°). Not a reverse fold.
58- **Two phases:** open the flap completely flat (body and tip spines 180° → 0°),
59 then fold on the reverse-fold branch (tip spine → −180°, body spine and both
60 reverse creases → 180°). Rigid, gap 1e-13. **This is the only rigid path
61 found, and it requires the flap to open fully flat.**
62- **Forced without opening** (M4, body held, tip spine linear 180° → −180°,
63 one reverse crease least-squares): gap 2.0 on a flap 1 high — the paper
64 tears completely.
65- **Partial opening** (body spine opens to φ at mid-fold and closes, tip spine
66 linear, least-squares): gap 1.6 at φ = 150°, 1.16 at 120°, 0.73 at 90°, 0.36
67 at 60°, 0.24 at 30°. A naive schedule; it shows that a partial opening does
68 not make the motion rigid, not the least strain a designed motion could
69 reach.
70
71The vertex is degree 4 with a straight pair (the spine) and a mirror pair
72(the reverse creases). The runs found three families of rigid motion: the
73spine folding as one line, the tip swinging as a closed unit (only with the
74spine at 180°), and the reverse-fold branch from the flat sheet. Every path
75found from the folded flap to the reverse fold passed through the flat
76sheet.
77
78### Case 5 in detail
79
80The crease pattern is Origami Simulator's `assets/Bases/birdBase.svg`
81(midlines, the diagonal the preliminary base folds, eight 22.5° kite
82creases), made exact, plus the petal hinge between the kite creases' ends.
83That pattern is not the bird base:
84
85- Origami Simulator's file has no petal hinge. Adding the hinge leaves five
86 creases at each kite end, which no flat fold allows. With the inner square
87 added as well, the solver finds a rigid, collision-free motion (gap 1e-15),
88 but tracing points shows the inner layers' corners lifting with the front
89 point. In a petal fold those corners stay down and become the legs.
90- With Origami Simulator's pattern as given, each kite end is a degree-4
91 vertex with the same structure as case 4's: a straight pair (the midline)
92 and a mirror pair (the two kite creases), sectors 112.5° and 67.5°. If the
93 petal fold reverses the outer midline segment there, case 4's result
94 applies; if the side flaps swing as closed units, it is rigid.
95
96Settling this needs a verified bird-base crease pattern with its mountain and
97valley assignment (e.g. from Lang, *Origami Design Secrets*). No published
98FOLD file was found.
99
100### Not measured
101
102- The sampan's last step, turning the model inside out.
103- The masu's wall-raising.
104
105## What this means
106
1071. **M1 is right for independent folds, with one addition:** axes need their
108 own window on *t*. Case 1 shows two flaps of equal reach folding toward
109 each other on one linear parameter always collide; staggering them is
110 clean.
1112. **Coupled vertices need M2's solved curves.** Linear angles tear a
112 degree-4 vertex by more than half the sheet. The angles are not
113 choosable — they follow the tan relation — which is more work for
114 `foldc`, not for the author.
1153. **Reverse folds have no rigid motion that matches how they are folded.**
116 The rigid path unfolds the flap flat and refolds it. On the crane the
117 neck, tail and head flaps are narrowed, several layers deep; unfolding
118 one flat would undo earlier steps' folds on screen. Not measured on the
119 crane's geometry.
1204. **The petal fold is open** pending a verified crease pattern.
1215. **The overlapping-moving-sets rule for `krz:faceOrders_midFold` has no
122 case left.** The problem it addressed is a collision (case 1), which
123 ordering cannot fix and staggering does. A staggered second flap arrives
124 on a stack that is already flat, where the end frame's order and the
125 near-coplanar clusters apply. Its other use, the peak order of a
126 `foldAndUnfold`, is unaffected.
127
128## Exit criterion
129
130The crane's three inside reverse folds are covered only by M3 with the flap
131fully unfolded, or by M4 — met. Per the plan, the choice is the author's.
132
133## Options
134
135**A. Scoped non-rigid steps (recommended).** Rigid steps use M2 with per-axis
136windows. Steps whose technique has no rigid path — inside and outside reverse
137folds, sinks, inversions — are flagged in `krz:step` and animated by a
138designed non-rigid motion: the flap's layers open partway and the tip swings
139through, with faces near the vertex allowed to bend. For those steps the
140isometry gate becomes a stated strain bound, and the interpenetration check
141still applies. This needs:
142
143- a second spike (Task 0b) on a bending model for the reverse fold, to find a
144 strain bound worth promising;
145- the verified bird-base pattern for case 5;
146- the sampan's inversion and the masu's wall-raising as cases.
147
148It also changes `CLAUDE.md`'s rule that an isometry failure is never a
149tolerance to widen, for flagged steps only.
150
151**B. Rigid via unfolding (M3).** Animate a reverse fold as unfold-flat, then
152refold. Exact and isometric, but it does not show how a reverse fold is made,
153and on the crane it unfolds earlier steps on screen.
154
155**C. Don't animate those steps.** The step jumps or crossfades. This breaks
156the anti-goal "a fold that snaps".
157
158**D. Drop the crane.** Replace it with a traditional model without reverse
159folds or sinks. Most traditional animals use reverse folds; the crane is the
160model most people will open the app for.
161
162## If A is chosen: plan changes
163
164- **Task 0b** (new, before Task 1): bending model for reverse folds; verified
165 bird base; sampan inversion; masu raise. Its decision record sets the
166 strain bound.
167- **Task 1:** `AxisRecord` gains `parent: Int?` (the axis whose motion carries
168 it), `window: [Double]?` (its span of *t*, default `[0, 1]`) and
169 `angles: [Double]?` (a solved curve sampled on its window; absent means
170 linear). `StepRecord` gains `nonRigid: Bool`.
171- **Task 3:** `FoldAxis` carries the same; `readSteps` builds the tree.
172- **Task 4:** `positions(at:)` composes rotations down the tree, using each
173 axis's curve. Add case 3 as a fixture to the isometry sweep, and a
174 staggered letter fold to the interpenetration tests.
175- **Task 7:** `foldc` solves each coupled step's curves by the same method as
176 the spike and writes them; the script names a step's driving crease.
177- **Task 2:** the overlapping-moving-sets rule is removed, if the author
178 agrees.
179
180## Appendix: spike output
181
182See `spikes/interpolation`; the run that produced the numbers above:
183
184```
185## Case 1 — letter fold, both flaps valley
186- M1, one linear parameter: max gap 8.88e-16; first collision at t = 0.668 (120.2°)
187- M1 staggered (left on t 0–0.5, right on 0.5–1): max gap 8.88e-16; first collision none
188## Case 2 — letter fold, left valley, right mountain
189- M1: max gap 8.88e-16; first collision none
190
191## Case 3 — flat-foldable degree-4 vertex, sectors 60°, 80°, 120°, 100°
192- M1, all four angles linear to the assignment with the odd crease at 0°: max gap 1.38e0 on a sheet of side 2
193- M1, all four angles linear to the assignment with the odd crease at 60°: max gap 1.08e0 on a sheet of side 2
194- 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
195- 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
196
197## Case 4 — inside reverse fold, 4×2 sheet folded on its spine y = 1
198- 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.
199- (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
200- (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
201- (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
202- (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
203- (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
204- (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
205- (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
206- (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
207- (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
208- (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
209- (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
210- (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)
211- (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
212
213## Case 5 — petal fold of a preliminary base's front flap
214- 20 faces, 26 creases, 14 free on the spanning tree, 4 measured off it; preliminary base start gap 2.48e-16
215- the petal fold's own creases only (hinge driven; 4 of the 4 kite creases on the tree, the rest measured):
216 - 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
217 - M1, the same end state with every angle linear: max gap 1.11e-15
218 - 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
219 - M1, the same end state with every angle linear: max gap 1.31e-15
220 - front point (0,0): (1.0, 1.0, 0) → (0.646, 0.646, -0.5) → (0.293, 0.293, 0)
221 - side corner (0.5,0): (1.0, 0.5, 0) → (0.907, 0.657, -0.073) → (0.646, 0.646, 0)
222 - inner corner (1,0): (1.0, 1.0, 0) → (0.646, 0.646, -0.5) → (0.293, 0.293, 0)
223 - hinge end B: (0.793, 0.5, 0) → (0.793, 0.5, 0) → (0.793, 0.5, 0)
224- 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
225
226```
spikes/interpolation/Package.swift added +10
@@ -0,0 +1,10 @@
1// swift-tools-version: 6.2
2import PackageDescription
3
4let 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 @@
1import 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.
6func 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 @@
1import simd
2
3infix operator ∘: MultiplicationPrecedence
4
5/// p ↦ q·p + t
6struct 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.
21struct 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
180func 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 @@
1import 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.
6func unwrap(_ m: [Double], toward ref: [Double]) -> [Double] {
7 zip(m, ref).map { x, r in x + 360 * ((r - x) / 360).rounded() }
8}
9
10struct 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.
25func 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.
40func 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
64func 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
70func 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 @@
1import simd
2
3typealias V2 = SIMD2<Double>
4typealias 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.
8struct 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 +207
@@ -0,0 +1,207 @@
1import simd
2
3func 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
7func line(_ s: String) { print(s) }
8
9let only = CommandLine.arguments.dropFirst().first
10
11// MARK: 1 and 2 — letter fold
12
13if 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
36if 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 line("")
67}
68
69// MARK: 4 — inside reverse fold of a two-layer flap
70
71if only == nil || only == "reverse" {
72 let sheet = Sheet(boundary: rect(0, 0, 4, 2), creases: [
73 (V2(0, 1), V2(2, 1)), (V2(2, 1), V2(4, 1)), (V2(2, 1), V2(3, 2)), (V2(2, 1), V2(3, 0)),
74 ])
75 let root = sheet.face(containing: V2(0.5, 0.5))
76 let body = sheet.edges(on: V2(0, 1), V2(2, 1))[0], tip = sheet.edges(on: V2(2, 1), V2(4, 1))[0]
77 let a = sheet.edges(on: V2(2, 1), V2(3, 2))[0], b = sheet.edges(on: V2(2, 1), V2(3, 0))[0]
78 var start = [Double](repeating: 0, count: sheet.edges.count)
79 start[body] = 180; start[tip] = 180
80 // Tree without the tip spine (driving the reverse creases), or without A (driving the tip spine).
81 let byCreases = Kinematics(sheet, root: root, prefer: [body, b, a])
82 let bySpine = Kinematics(sheet, root: root, prefer: [body, tip, b])
83 line("## Case 4 — inside reverse fold, 4×2 sheet folded on its spine y = 1")
84 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.")
85 func row(_ s: Sweep) -> String {
86 let r = [body, tip, a, b].map { e in let (lo, hi) = s.range(e); return "\(fmt(lo))…\(fmt(hi))" }
87 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]))"
88 }
89 for sb in [1.0, -1.0] {
90 for sa in [1.0, -1.0] {
91 let s = continuation(byCreases, start: start, drivers: [b: { 180 * $0 * sb }], free: [a], seed: [a: 180 * sa], collisions: false)
92 line("- (a) body held at 180, B → \(fmt(180 * sb)), A solved (seed \(sa > 0 ? "+" : "−")): \(row(s))")
93 }
94 let s = continuation(byCreases, start: start, drivers: [b: { 180 * $0 * sb }], free: [body, a], seed: [a: -180 * sb], collisions: false)
95 line("- (b) body free, B → \(fmt(180 * sb)), body and A solved: \(row(s))")
96 }
97 for st in [1.0, -1.0] {
98 let s = continuation(bySpine, start: start, drivers: [tip: { 180 - 360 * $0 }], free: [body, b], seed: [b: 180 * st], collisions: false)
99 line("- (c) body free, tip spine driven 180 → −180, body and B solved (seed B \(st > 0 ? "+" : "−")): \(row(s))")
100 }
101 let phase1 = continuation(bySpine, start: start, drivers: [tip: { 180 * (1 - $0) }], free: [body, b], collisions: false)
102 line("- (c′) phase 1, tip spine 180 → 0: \(row(phase1))")
103 for st in [1.0, -1.0] {
104 let s = continuation(bySpine, start: phase1.end, drivers: [tip: { -180 * $0 }], free: [body, b], seed: [body: 180, b: 180 * st], collisions: false)
105 line("- (c′) phase 2, tip spine 0 → −180 (seed B \(st > 0 ? "+" : "−")): \(row(s))")
106 }
107 let forced = continuation(bySpine, start: start, drivers: [tip: { 180 - 360 * $0 }], free: [b], seed: [b: 180], collisions: false)
108 line("- (d) M4, body held at 180, tip spine forced 180 → −180, B least-squares: \(row(forced)) (flap height 1)")
109 // (e) How much must the flap open? The body spine opens to φ at mid-fold and
110 // closes again, the tip spine is driven through, B is least-squares.
111 var curve: [String] = []
112 for phi in [180.0, 150, 120, 90, 60, 30, 10, 0] {
113 let s = continuation(bySpine, start: start,
114 drivers: [tip: { 180 - 360 * $0 }, body: { 180 - (180 - phi) * sin(.pi * $0) }],
115 free: [b], seed: [b: 180], collisions: false)
116 curve.append("φ \(fmt(phi, 0))° → gap \(sci(s.maxGap))")
117 }
118 line("- (e) body spine opened to φ at mid-fold, tip spine driven through, B least-squares: " + curve.joined(separator: "; "))
119 line("")
120}
121
122// MARK: 5 — petal fold of the front flap of a preliminary base
123
124if only == nil || only == "petal" {
125 // The bird base's crease pattern on the unit square (after Origami Simulator's
126 // birdBase.svg, made exact): midlines, the diagonal through the two quadrants
127 // the preliminary base folds in half, the eight 22.5° kite creases, and the
128 // square joining their ends on the midlines.
129 let h = 0.5 * (2.0.squareRoot() - 1) // 0.5·tan 22.5°
130 let L = V2(h, 0.5), B = V2(0.5, h), R = V2(1 - h, 0.5), T = V2(0.5, 1 - h)
131 let c00 = V2(0, 0), c10 = V2(1, 0), c11 = V2(1, 1), c01 = V2(0, 1)
132 let sheet = Sheet(boundary: rect(0, 0, 1, 1), creases: [
133 (V2(0.5, 0), V2(0.5, 1)), (V2(0, 0.5), V2(1, 0.5)), (c10, c01),
134 (c00, B), (c00, L), (c10, B), (c10, R), (c11, R), (c11, T), (c01, T), (c01, L),
135 (L, B), (B, R), (R, T), (T, L),
136 ])
137 let midlines = sheet.edges(on: V2(0.5, 0), V2(0.5, 1)) + sheet.edges(on: V2(0, 0.5), V2(1, 0.5))
138 let diagonal = sheet.edges(on: c10, c01)
139 var start = [Double](repeating: 0, count: sheet.edges.count)
140 for e in midlines { start[e] = -180 }
141 for e in diagonal { start[e] = 180 }
142 let hinge = sheet.edges(on: L, B)[0]
143 // Everything outside the back quadrant may move; the back quadrant holds still.
144 let back: (Int) -> Bool = { e in
145 let (u, v) = sheet.edges[e]
146 let m = (sheet.verts[u] + sheet.verts[v]) / 2
147 return m.x > 0.5 - 1e-9 && m.y > 0.5 - 1e-9
148 }
149 let movable = sheet.interiorEdges.filter { !back($0) && $0 != hinge }
150 let k = Kinematics(sheet, root: sheet.face(containing: V2(0.55, 0.55)), prefer: [hinge] + movable)
151 let free = movable.filter(k.treeEdges.contains)
152 let kites = [sheet.edges(on: c00, B)[0], sheet.edges(on: c00, L)[0]]
153 let innerKites = [sheet.edges(on: c10, B)[0], sheet.edges(on: c01, L)[0]]
154 let outerMidlines = [sheet.edges(on: V2(0.5, 0), B)[0], sheet.edges(on: V2(0, 0.5), L)[0]]
155 let innerTilted = sheet.edges(on: B, R) + sheet.edges(on: T, L)
156 line("## Case 5 — petal fold of a preliminary base's front flap")
157 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)))")
158 func row(_ s: Sweep) -> String {
159 func r(_ es: [Int]) -> String { es.map { let (lo, hi) = s.range($0); return "\(fmt(lo))…\(fmt(hi))" }.joined(separator: ", ") }
160 func end(_ es: [Int]) -> String { es.map { fmt(s.end[$0]) }.joined(separator: ", ") }
161 let moved = sheet.interiorEdges.filter { abs(s.end[$0] - start[$0]) > 1 }.count
162 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)"
163 }
164 // Intended as the petal fold: the front point lifts on the hinge, and each
165 // side — the front layer's side and the inner layer behind it, still joined
166 // along the midline — swings in on its two kite creases. The traced points
167 // show the inner layers' corners lifting too, which a petal fold does not
168 // do, so this crease pattern is not the bird base; see the decision record.
169 let petalKinematics = Kinematics(sheet, root: sheet.face(containing: V2(0.55, 0.55)), prefer: [hinge] + kites + innerKites)
170 let petalFree = (kites + innerKites).filter(petalKinematics.treeEdges.contains)
171 line("- the petal fold's own creases only (hinge driven; \(petalFree.count) of the 4 kite creases on the tree, the rest measured):")
172 for sk in [1.0, -1.0] {
173 var seed: [Int: Double] = [:]
174 for e in kites where petalFree.contains(e) { seed[e] = 180 * sk }
175 for e in innerKites where petalFree.contains(e) { seed[e] = -180 * sk }
176 let s = continuation(petalKinematics, start: start, drivers: [hinge: { 180 * $0 }], free: petalFree, seed: seed, steps: 200)
177 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: ", "))")
178 let linear = prescribed(petalKinematics, steps: 200, collisions: false) { t in
179 var a = start
180 for e in petalKinematics.treeEdges { a[e] = start[e] + t * (s.end[e] - start[e]) }
181 return a
182 }
183 line(" - M1, the same end state with every angle linear: max gap \(sci(linear.maxGap))")
184 if sk < 0 {
185 // Where the front point, the front layer's side corner and the inner layer's corner go.
186 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)] {
187 let f = sheet.faces.indices.first { sheet.faces[$0].contains { simd_distance(sheet.verts[$0], p) < 1e-9 } }!
188 let v = sheet.faces[f].first { simd_distance(sheet.verts[$0], p) < 1e-9 }!
189 let i = sheet.faces[f].firstIndex(of: v)!
190 let path = [0.0, 0.5, 1.0].map { t -> String in
191 let a = s.samples.min { abs($0.t - t) < abs($1.t - t) }!
192 var angles = start
193 for e in petalKinematics.treeEdges { angles[e] = a.angles[e] }
194 let q = petalKinematics.positions(angles)[f][i]
195 return "(\(fmt(q.x, 3)), \(fmt(q.y, 3)), \(fmt(q.z, 3)))"
196 }
197 line(" - \(name): \(path.joined(separator: " → "))")
198 }
199 }
200 }
201 // With every crease outside the back quadrant free, the solver is
202 // underdetermined and finds other mechanisms; the step has to say which
203 // creases move, which is what krz:step's axes are for.
204 let loose = continuation(k, start: start, drivers: [hinge: { 180 * $0 }], free: free, steps: 200, collisions: false)
205 line("- control, every crease outside the back quadrant free (\(free.count) unknowns): \(row(loose))")
206 line("")
207}