spikes/interpolation/Sources/Spike/main.swift

475 lines · 31187 bytes

17 symbols in this file
  • rect function, line 3
  • line function, line 7
  • set function, line 17
  • lin function, line 49
  • sampled function, line 73
  • cubic function, line 76
  • angles function, line 90
  • row function, line 125
  • row function, line 198
  • r function, line 199
  • end function, line 200
  • e function, line 267
  • check function, line 290
  • r function, line 320
  • pose function, line 380
  • side function, line 393
  • run function, line 414
  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    // 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
111if 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
164if 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}
248
249// MARK: 7 — petal fold on the bird base read from a crane
250
251if only == nil || only == "petal2" {
252    // The bird base inside Origami Simulator's assets/Origami/flat_crane.svg, made
253    // exact: the midline cross from the centre to the four kite ends, the
254    // diagonal the preliminary base folds, the eight 22.5° kite creases, and the
255    // two petal hinges. The outer midline segments and the other diagonal are
256    // not creases of the bird base; the preliminary base folds the outer
257    // segments, so the petal fold unfolds them.
258    let h = 0.5 * (2.0.squareRoot() - 1)
259    let L = V2(h, 0.5), B = V2(0.5, h), R = V2(1 - h, 0.5), T = V2(0.5, 1 - h), O = V2(0.5, 0.5)
260    let c00 = V2(0, 0), c10 = V2(1, 0), c11 = V2(1, 1), c01 = V2(0, 1)
261    let mL = V2(0, 0.5), mB = V2(0.5, 0), mR = V2(1, 0.5), mT = V2(0.5, 1)
262    let sheet = Sheet(boundary: rect(0, 0, 1, 1), creases: [
263        (mL, L), (L, O), (O, R), (R, mR), (mB, B), (B, O), (O, T), (T, mT), (c10, c01),
264        (c00, B), (c00, L), (c10, B), (c10, R), (c11, R), (c11, T), (c01, T), (c01, L),
265        (L, B), (R, T),
266    ])
267    func e(_ p: V2, _ q: V2) -> Int { sheet.edges(on: p, q)[0] }
268    let outer = [e(mL, L), e(mB, B)], backOuter = [e(R, mR), e(T, mT)]
269    let cross = [e(L, O), e(O, R), e(B, O), e(O, T)]
270    let diagonal = sheet.edges(on: c10, c01)
271    let hinge = e(L, B)
272    let kites = [e(c00, B), e(c00, L)], innerKites = [e(c10, B), e(c01, L)]
273    var start = [Double](repeating: 0, count: sheet.edges.count)
274    for x in outer + backOuter + cross { start[x] = -180 }       // mountain
275    for x in diagonal { start[x] = 180 }                         // valley
276    var end = start
277    end[hinge] = 180
278    for x in kites + innerKites { end[x] = -180 }
279    for x in outer { end[x] = 0 }
280    let root = sheet.face(containing: V2(0.6, 0.6))
281    // Static creases go on the tree first, so the regions they join are held
282    // still by the tree, not only by closure; the moving creases fill the rest.
283    let moving = Set([hinge] + kites + innerKites + outer)
284    let fixed = sheet.interiorEdges.filter { !moving.contains($0) }
285    let k = Kinematics(sheet, root: root, prefer: fixed + [hinge] + kites + innerKites + outer)
286    precondition(k.treeEdges.contains(hinge))
287    line("## Case 7 — petal fold on the bird base from Origami Simulator's flat crane")
288    line("- tree: \(fixed.filter(k.treeEdges.contains).count) of \(fixed.count) static creases, \((kites + innerKites + outer).filter(k.treeEdges.contains).count) of 6 moving creases solved, the rest measured")
289    // Flat-foldability of both end states, vertex by vertex.
290    func check(_ a: [Double]) -> String {
291        var bad: [String] = []
292        for v in sheet.verts.indices {
293            let es = sheet.interiorEdges.filter { [sheet.edges[$0].0, sheet.edges[$0].1].contains(v) }
294            let onBoundary = sheet.edges.indices.contains { sheet.edgeFaces[$0].count == 1 && [sheet.edges[$0].0, sheet.edges[$0].1].contains(v) }
295            if onBoundary { continue }
296            let folded = es.filter { abs(abs(a[$0]) - 180) < 1e-9 }
297            guard !folded.isEmpty else { continue }
298            let dirs = folded.map { x -> Double in
299                let w = sheet.edges[x].0 == v ? sheet.edges[x].1 : sheet.edges[x].0
300                let d = sheet.verts[w] - sheet.verts[v]
301                return atan2(d.y, d.x) * 180 / .pi
302            }.sorted()
303            let sectors = dirs.indices.map { i in i + 1 < dirs.count ? dirs[i + 1] - dirs[i] : dirs[0] + 360 - dirs[i] }
304            let alt = stride(from: 0, to: sectors.count, by: 2).map { sectors[$0] }.reduce(0, +)
305            let m = folded.filter { a[$0] < 0 }.count, vv = folded.count - m
306            if folded.count % 2 != 0 || abs(alt - 180) > 1e-9 || abs(m - vv) != 2 {
307                bad.append("(\(fmt(sheet.verts[v].x, 3)), \(fmt(sheet.verts[v].y, 3))) degree \(folded.count), M \(m) V \(vv), alternate sum \(fmt(alt, 3))")
308            }
309        }
310        return bad.isEmpty ? "Kawasaki and Maekawa hold at every interior vertex" : bad.joined(separator: "; ")
311    }
312    line("- preliminary base: gap \(sci(k.gap(start))); \(check(start))")
313    line("- after the front petal fold: gap \(sci(k.gap(end))); \(check(end))")
314    let free = (kites + innerKites + outer).filter(k.treeEdges.contains)
315    for (name, seedSign) in [("kites seeded mountain", -1.0), ("kites seeded valley", 1.0)] {
316        var seed: [Int: Double] = [:]
317        for x in kites + innerKites where free.contains(x) { seed[x] = 180 * seedSign }
318        for x in outer where free.contains(x) { seed[x] = 180 }
319        let s = continuation(k, start: start, drivers: [hinge: { 180 * $0 }], free: free, seed: seed, steps: 400)
320        func r(_ es: [Int]) -> String { es.map { let (lo, hi) = s.range($0); return "\(fmt(lo))…\(fmt(hi))" }.joined(separator: ", ") }
321        var details: [String] = []
322        let reached = sheet.interiorEdges.allSatisfy { x in
323            let d = (s.end[x] - end[x]).truncatingRemainder(dividingBy: 360)
324            return min(abs(d), 360 - abs(d)) < 1e-3
325        }
326        let away = s.samples.filter { $0.t >= 0.05 && $0.t <= 0.95 }.first { sample in
327            var a = start
328            for x in k.treeEdges { a[x] = sample.angles[x] }
329            return !intersectingPairs(k.positions(a)).isEmpty
330        }
331        details.append("  - collisions with t in 0.05…0.95, away from the coincident start and end: \(away.map { "first at t = \(fmt($0.t, 3))" } ?? "none")")
332        if let t0 = s.firstCollision {
333            var a = start
334            let sample = s.samples.min { abs($0.t - t0) < abs($1.t - t0) }!
335            for x in k.treeEdges { a[x] = sample.angles[x] }
336            let centroid = { (f: Int) -> String in
337                let c = sheet.faces[f].map { sheet.verts[$0] }.reduce(V2.zero, +) / Double(sheet.faces[f].count)
338                return "(\(fmt(c.x, 2)), \(fmt(c.y, 2)))"
339            }
340            let pairs = intersectingPairs(k.positions(a)).map { "\(centroid($0.0))×\(centroid($0.1))" }
341            details.append("  - first colliding faces at t = \(fmt(t0, 3)), by centroid on the sheet: \(pairs.joined(separator: ", "))")
342        }
343        line("- M2, hinge 0 → 180 driven, \(free.count) creases solved (\(name)): max gap \(sci(s.maxGap)); collision \(s.firstCollision.map { "at t = \(fmt($0, 3))" } ?? "none"); front kites \(r(kites)); inner kites \(r(innerKites)); outer midline segments \(r(outer)); reaches the bird base: \(reached)")
344        details.forEach(line)
345        let at = { (t: Double) in [kites[0], innerKites[0], outer[0]].map { fmt(s.angle($0, at: t)) }.joined(separator: ", ") }
346        line("  - front kite, inner kite, outer segment at t = 0.25: \(at(0.25)); 0.5: \(at(0.5)); 0.75: \(at(0.75))")
347        let linear = prescribed(k, steps: 400, collisions: false) { t in
348            var a = start
349            for x in k.treeEdges { a[x] = start[x] + t * (s.end[x] - start[x]) }
350            return a
351        }
352        line("  - M1, every angle linear to the same end: max gap \(sci(linear.maxGap))")
353        if reached {
354            for (pname, p) in [("front point (0,0)", c00), ("side corner (0.5,0)", mB), ("leg corner (1,0)", c10)] {
355                let f = sheet.faces.indices.first { sheet.faces[$0].contains { simd_distance(sheet.verts[$0], p) < 1e-9 } }!
356                let i = sheet.faces[f].firstIndex { simd_distance(sheet.verts[$0], p) < 1e-9 }!
357                let path = [0.0, 0.5, 1.0].map { t -> String in
358                    var a = start
359                    let sample = s.samples.min { abs($0.t - t) < abs($1.t - t) }!
360                    for x in k.treeEdges { a[x] = sample.angles[x] }
361                    let q = k.positions(a)[f][i]
362                    return "(\(fmt(q.x, 3)), \(fmt(q.y, 3)), \(fmt(q.z, 3)))"
363                }
364                line("  - \(pname): \(path.joined(separator: " → "))")
365            }
366        }
367    }
368    line("")
369}
370
371// MARK: 6 — inside reverse fold with bending
372
373if only == nil || only == "bending" {
374    let creases = [(V2(0, 1), V2(2, 1)), (V2(2, 1), V2(4, 1)), (V2(2, 1), V2(3, 2)), (V2(2, 1), V2(3, 0))]
375    let sheet = Sheet(boundary: rect(0, 0, 4, 2), creases: creases)
376    let root = sheet.face(containing: V2(0.5, 0.5)), bodyTop = sheet.face(containing: V2(0.5, 1.5))
377    let body = sheet.edges(on: V2(0, 1), V2(2, 1))[0], tip = sheet.edges(on: V2(2, 1), V2(4, 1))[0]
378    let b = sheet.edges(on: V2(2, 1), V2(3, 0))[0]
379    let k = Kinematics(sheet, root: root, prefer: [body, tip, b])
380    func pose(_ bodyAngle: Double, _ tipAngle: Double, _ bAngle: Double) -> [Double] {
381        var a = [Double](repeating: 0, count: sheet.edges.count)
382        a[body] = bodyAngle; a[tip] = tipAngle; a[b] = bAngle
383        return a
384    }
385    let start = pose(180, 180, 0), end = pose(180, -180, 180)
386    line("## Case 6 — inside reverse fold with bending (as-rigid-as-possible interpolation)")
387    line("- end pose gap \(sci(k.gap(end))): the reverse fold's coordinates; inside, outside and folded-over share them, so the path decides which")
388    for spacing in [0.25, 0.125] {
389        let mesh = Bending(sheet, k, spacing: spacing, creases: creases, pinFace: root)
390        line("- mesh spacing \(spacing): \(mesh.fine.verts.count) vertices, \(mesh.triangles.count) triangles")
391        // Which layer is the tip between, just before it lands? Compare a tip point's
392        // height with the body's two layers at the same place.
393        func side(_ x: [V3]) -> String {
394            let probe = mesh.fine.verts.indices.min { simd_distance(mesh.fine.verts[$0], V2(2.75, 0.75)) < simd_distance(mesh.fine.verts[$1], V2(2.75, 0.75)) }!
395            let p = x[probe]
396            var zTop: Double? = nil
397            var t = 0
398            for (f, face) in mesh.fine.faces.enumerated() {
399                for kk in 1..<(face.count - 1) {
400                    defer { t += 1 }
401                    guard mesh.parent[f] == bodyTop else { continue }
402                    let (a0, b0, c0) = (x[face[0]], x[face[kk]], x[face[kk + 1]])
403                    let v0 = V2(b0.x - a0.x, b0.y - a0.y), v1 = V2(c0.x - a0.x, c0.y - a0.y), v2 = V2(p.x - a0.x, p.y - a0.y)
404                    let d = v0.x * v1.y - v0.y * v1.x
405                    guard abs(d) > 1e-12 else { continue }
406                    let u = (v2.x * v1.y - v2.y * v1.x) / d, w = (v0.x * v2.y - v0.y * v2.x) / d
407                    if u >= 0, w >= 0, u + w <= 1 { zTop = a0.z + u * (b0.z - a0.z) + w * (c0.z - a0.z) }
408                }
409            }
410            guard let top = zTop else { return "tip not over the body yet" }
411            if p.z > min(0, top) && p.z < max(0, top) { return "between the body's layers (inside)" }
412            return "outside the body's layers (z \(fmt(p.z, 3)), layers at 0 and \(fmt(top, 3)))"
413        }
414        func run(_ name: String, from a: [Double], to bPose: [Double]) {
415            var worst = 0.0
416            var collision: Double? = nil
417            for i in 0...60 {
418                let s = Double(i) / 60
419                let x = mesh.interpolate(from: a, to: bPose, at: s)
420                worst = max(worst, mesh.strain(x))
421                if collision == nil, s > 0.02, s < 0.98, !intersectingPairs(mesh.triangleSoup(x)).isEmpty { collision = s }
422            }
423            let near = mesh.interpolate(from: a, to: bPose, at: 0.97)
424            line("  - \(name): max strain \(fmt(100 * worst, 2))%; collision \(collision.map { "at s = \(fmt($0, 3))" } ?? "none"); at s = 0.97 the tip is \(side(near))")
425        }
426        run("direct, closed flap → reverse fold", from: start, to: end)
427        // Open, pop, close: open the flap rigidly to φ with the tip still pointing
428        // out; pop the tip inside with the flap held at φ (the only bending); close
429        // rigidly along the reverse-fold branch. At φ = 0 the pop is free: that is
430        // the fully unfolded rigid path.
431        for phi in [170.0, 150, 120, 90, 60, 30, 10] {
432            var popped = pose(phi, -phi, phi)
433            k.solve(&popped, free: [b])
434            let closing = continuation(k, start: popped,
435                                       drivers: [body: { phi + (180 - phi) * $0 }, tip: { -(phi + (180 - phi) * $0) }],
436                                       free: [b], collisions: false)
437            var worst = 0.0, beyondQuarter = 0.0, beyondHalf = 0.0
438            var collision: Double? = nil
439            for i in 0...60 {
440                let s = Double(i) / 60
441                let x = mesh.interpolate(from: pose(phi, phi, 0), to: popped, at: s)
442                worst = max(worst, mesh.strain(x))
443                beyondQuarter = max(beyondQuarter, mesh.strain(x, outside: 0.25, center: V2(2, 1)))
444                beyondHalf = max(beyondHalf, mesh.strain(x, outside: 0.5, center: V2(2, 1)))
445                if collision == nil, s > 0.02, s < 0.98, !intersectingPairs(mesh.triangleSoup(x)).isEmpty { collision = s }
446            }
447            let closeCollision = closing.samples.dropLast(3).first { sample in
448                var a = sample.angles
449                a[body] = sample.angles[body]
450                return !intersectingPairs(mesh.triangleSoup(mesh.pose(a))).isEmpty
451            }
452            // The same pop with iterative ARAP: the body held at φ, only the tip's
453            // far corners moved along the pop, everything else left to the solver.
454            var bent = 0.0
455            if spacing == 0.25 {
456                let bodyFaces = Set([root, bodyTop])
457                let held = Set(mesh.fine.faces.indices.filter { bodyFaces.contains(mesh.parent[$0]) }.flatMap { mesh.fine.faces[$0] })
458                let corners = mesh.fine.verts.indices.filter { mesh.fine.verts[$0].x > 4 - 1e-9 }
459                var x = mesh.pose(pose(phi, phi, 0))
460                for i in 1...12 {
461                    let s = Double(i) / 12
462                    let guide = mesh.interpolate(from: pose(phi, phi, 0), to: popped, at: s)
463                    var handles: [Int: V3] = [:]
464                    for h in held { handles[h] = guide[h] }
465                    for c in corners { handles[c] = guide[c] }
466                    x = mesh.deform(start: x, handles: handles)
467                    bent = max(bent, mesh.strain(x))
468                }
469            }
470            let nearEnd = closing.samples.min { abs($0.t - 0.97) < abs($1.t - 0.97) }!.angles
471            line("  - open to \(fmt(phi, 0))°, pop, close: \(spacing == 0.25 ? "iterative ARAP pop strain \(fmt(100 * bent, 2))%; " : "")pop strain \(fmt(100 * worst, 2))% (beyond 0.25 of the vertex \(fmt(100 * beyondQuarter, 2))%, beyond 0.5 \(fmt(100 * beyondHalf, 2))%), pop collision \(collision.map { "at s = \(fmt($0, 3))" } ?? "none"); closing gap \(sci(closing.maxGap)), collision \(closeCollision.map { "at t = \(fmt($0.t, 3))" } ?? "none"), reaches the end pose \(abs(closing.end[b] - 180) < 1e-3); just before landing the tip is \(side(mesh.pose(nearEnd)))")
472        }
473    }
474    line("")
475}