import Accelerate import simd import Synchronization /// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces /// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by /// its target, and the mesh vertices are the least-squares fit to those edges, with the vertices of /// held faces kept where the first pose has them. A triangle's target is `s` of its face's /// rotation from the first pose to the second (slerp); for a triangle in `blends` (decision 0003's /// band) it is slerp(mid, own, w), where own is that slerp, mid = slerp(own, other, ½), other is /// the slerp of the partner face's rotation, and w = weight + (1 − weight)(1 − 4s(1 − s)). At /// `s = 0` and `s = 1` every target is the face's own rotation and the fit is exact, so it /// reproduces both poses. Tied vertices are one unknown, so they move together. struct Bending: Sendable { /// A triangle whose turn is blended toward its partner face's. struct Blend: Sendable { let triangle: Int let partner: Int /// 1 where the triangle keeps its own turn throughout. let weight: Double } /// The mesh vertices in the first pose. private let rest: [SIMD3] /// Per FOLD face, its rotation from the first pose to the second. private let turns: [simd_quatd] /// The blended triangles' faces, partners and weights; the k-th takes target `turns.count + k`. private let blends: [(face: Int, partner: Int, weight: Double)] /// The mesh vertices that move, in the solve's row order, one per tied group. private let free: [Int] /// Per mesh vertex, its row in the solve, or −1 when held. private let rows: [Int] /// Per row and target, the signed sum of the rest edge vectors of that target's triangles at /// the row's vertex; the right-hand side adds each turned by the target at `s`. Targets are the /// FOLD faces, then the blended triangles. private let terms: [(row: Int, target: Int, vector: SIMD3)] /// Per row, what the held vertices contribute to the normal equation's right-hand side. private let held: [SIMD3] private let factor: SparseCholesky /// - Parameters: /// - first, second: the FOLD vertex positions of two rigid poses. /// - heldFaces: FOLD faces placed alike in both poses, whose mesh vertices stay put. /// - blends: triangles whose turns blend toward a partner face's. /// - ties: groups of mesh vertices solved as one unknown; a group with a held vertex is held. init(mesh: RenderMesh, faces: [[Int]], from first: [SIMD3], to second: [SIMD3], heldFaces: Set, blends: [Blend] = [], ties: [[Int]] = []) { rest = mesh.pose(first) turns = faces.map { corners in // one corner triple for both poses, chosen on the flat sheet so ties cannot split let flat = corners.map { mesh.vertices[mesh.meshVertexOf[$0]] } let c = widestCorners(flat).map { corners[$0] } var q = simd_quatd(frame(c.map { second[$0] }) * frame(c.map { first[$0] }).transpose) if q.real < 0 { q = simd_quatd(vector: -q.vector) } return q } self.blends = blends.map { (mesh.faceOf[$0.triangle], $0.partner, $0.weight) } var target = mesh.faceOf for (k, blend) in blends.enumerated() { target[blend.triangle] = faces.count + k } var isHeld = Array(repeating: false, count: mesh.vertices.count) for (t, (a, b, c)) in mesh.triangles.enumerated() where heldFaces.contains(mesh.faceOf[t]) { (isHeld[a], isHeld[b], isHeld[c]) = (true, true, true) } for group in ties where group.contains(where: { isHeld[$0] }) { for v in group { isHeld[v] = true } } var representative = Array(mesh.vertices.indices) for group in ties { for v in group { representative[v] = group[0] } } free = mesh.vertices.indices.filter { !isHeld[$0] && representative[$0] == $0 } var row = Array(repeating: -1, count: mesh.vertices.count) for (r, v) in free.enumerated() { row[v] = r } for v in mesh.vertices.indices where !isHeld[v] { row[v] = row[representative[v]] } rows = row // Σ over triangle edges (i, j) of |x_j − x_i − d_ij|²: the normal matrix is the edge // Laplacian; held vertices move to the right-hand side. var matrix: [SIMD2: Double] = [:] var sums: [SIMD2: SIMD3] = [:] var held = Array(repeating: SIMD3.zero, count: free.count) for (t, (a, b, c)) in mesh.triangles.enumerated() { for (i, j) in [(a, b), (b, c), (c, a)] where row[i] < 0 || row[i] != row[j] { let d = rest[j] - rest[i] for (v, other, sign) in [(i, j, -1.0), (j, i, 1.0)] where row[v] >= 0 { matrix[SIMD2(row[v], row[v]), default: 0] += 1 sums[SIMD2(row[v], target[t]), default: .zero] += sign * d if row[other] >= 0 { if row[other] < row[v] { matrix[SIMD2(row[v], row[other]), default: 0] -= 1 } } else { held[row[v]] += rest[other] } } } } terms = sums.keys.sorted { ($0.x, $0.y) < ($1.x, $1.y) }.map { ($0.x, $0.y, sums[$0]!) } self.held = held factor = SparseCholesky(size: free.count, lower: matrix) } /// The mesh vertex positions at `s` in 0...1. func positions(at s: Double) -> [SIMD3] { let identity = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1) var turned = turns.map { simd_slerp(identity, $0, s) } let middle = 1 - 4 * s * (1 - s) turned += blends.map { face, partner, weight in let own = turned[face] return simd_slerp(simd_slerp(own, turned[partner], 0.5), own, weight + (1 - weight) * middle) } let n = free.count var rhs = [Double](repeating: 0, count: 3 * n) for (r, h) in held.enumerated() { rhs[r] = h.x rhs[n + r] = h.y rhs[2 * n + r] = h.z } for (r, target, vector) in terms { let d = turned[target].act(vector) rhs[r] += d.x rhs[n + r] += d.y rhs[2 * n + r] += d.z } factor.solve(&rhs, columns: 3) var result = rest for (v, r) in rows.enumerated() where r >= 0 { result[v] = SIMD3(rhs[r], rhs[n + r], rhs[2 * n + r]) } return result } } /// An orthonormal frame fixed to the triangle `p`: along its first side, across it in its plane, /// and along its normal. private func frame(_ p: [SIMD3]) -> simd_double3x3 { let along = normalize(p[1] - p[0]), normal = normalize(cross(p[1] - p[0], p[2] - p[0])) return simd_double3x3(columns: (along, cross(normal, along), normal)) } /// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. Solves are /// serialised: Accelerate does not document concurrent `SparseSolve` calls on one factor as safe. private final class SparseCholesky: @unchecked Sendable { private let factor: SparseOpaqueFactorization_Double private let size: Int private let lock = Mutex(()) /// `lower` holds the entries on and below the diagonal, keyed by (row, column). init(size: Int, lower: [SIMD2: Double]) { self.size = size let keys = lower.keys.sorted { ($0.y, $0.x) < ($1.y, $1.x) } let rows = keys.map { Int32($0.x) }, columns = keys.map { Int32($0.y) }, values = keys.map { lower[$0]! } var attributes = SparseAttributes_t() attributes.triangle = SparseLowerTriangle attributes.kind = SparseSymmetric let matrix = SparseConvertFromCoordinate(Int32(size), Int32(size), keys.count, 1, attributes, rows, columns, values) defer { SparseCleanup(matrix) } factor = SparseFactor(SparseFactorizationCholesky, matrix) precondition(factor.status == SparseStatusOK, "the pop's normal matrix is not positive definite") } deinit { SparseCleanup(factor) } /// Solves in place for `columns` right-hand sides of `size` values each, one after another. func solve(_ values: inout [Double], columns: Int) { values.withUnsafeMutableBufferPointer { buffer in let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size), attributes: SparseAttributes_t(), data: buffer.baseAddress!) lock.withLock { _ in SparseSolve(factor, b) } } } }