import simd /// The geometry's fold angles, unwrapped against the previous sample (or, on /// the first, against `ref`), so a crease that keeps turning past ±180 reads /// as beyond the range: one face has gone through the other at the hinge. func unwrap(_ m: [Double], toward ref: [Double]) -> [Double] { zip(m, ref).map { x, r in x + 360 * ((r - x) / 360).rounded() } } struct Sweep { var maxGap = 0.0 var firstCollision: Double? var samples: [(t: Double, angles: [Double])] = [] var end: [Double] { samples.last!.angles } func angle(_ e: Int, at t: Double) -> Double { samples.min { abs($0.t - t) < abs($1.t - t) }!.angles[e] } func range(_ e: Int) -> (Double, Double) { let xs = samples.map { $0.angles[e] } return (xs.min()!, xs.max()!) } } /// Every angle prescribed as a function of t: no solving, so any tearing shows as gap. func prescribed(_ k: Kinematics, steps: Int = 400, collisions: Bool = true, _ angles: (Double) -> [Double]) -> Sweep { var s = Sweep() for i in 0...steps { let t = Double(i) / Double(steps) let a = angles(t) s.maxGap = max(s.maxGap, k.gap(a)) if collisions, s.firstCollision == nil, !intersectingPairs(k.positions(a)).isEmpty { s.firstCollision = t } s.samples.append((t, unwrap(k.measured(a), toward: s.samples.last?.angles ?? a))) } return s } /// Drivers prescribed, free angles solved so the paper stays whole; continued /// from the previous sample with a secant predictor. `seed` is the direction /// to leave the start in, for starts where several branches meet. func continuation(_ k: Kinematics, start: [Double], drivers: [Int: (Double) -> Double], free: [Int], seed: [Int: Double] = [:], steps: Int = 400, collisions: Bool = true) -> Sweep { var s = Sweep() var a = start var last: [Double]? = nil for i in 0...steps { let t = Double(i) / Double(steps) var guess = a if let l = last { for e in free { guess[e] += a[e] - l[e] } } else if i == 1 { for (e, d) in seed { guess[e] += d / Double(steps) } } for (e, f) in drivers { guess[e] = f(t) } let g = k.solve(&guess, free: free) s.maxGap = max(s.maxGap, g) if collisions, s.firstCollision == nil, !intersectingPairs(k.positions(guess)).isEmpty { s.firstCollision = t } s.samples.append((t, unwrap(k.measured(guess), toward: s.samples.last?.angles ?? start))) if i > 0 { last = a } a = guess } return s } func fmt(_ x: Double, _ digits: Int = 1) -> String { let p = pow(10.0, Double(digits)) let r = (x * p).rounded() / p return r == 0 ? "0" : String(r) } func sci(_ x: Double) -> String { if x == 0 { return "0" } let e = Int(floor(log10(abs(x)))) let m = x / pow(10.0, Double(e)) return "\(fmt(m, 2))e\(e)" }