spikes/bending/Sources/Bending/Solver.swift
194 lines · 8094 bytes
14 symbols in this file
1import Accelerate
2import simd
3
4/// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix.
5final class SparseCholesky {
6 private let factor: SparseOpaqueFactorization_Double
7 let size: Int
8
9 /// `lower` holds the entries on and below the diagonal, keyed by (row, column).
10 init(size: Int, lower: [SIMD2<Int>: Double]) {
11 self.size = size
12 let keys = lower.keys.sorted { ($0.y, $0.x) < ($1.y, $1.x) }
13 let rows = keys.map { Int32($0.x) }, columns = keys.map { Int32($0.y) }, values = keys.map { lower[$0]! }
14 var attributes = SparseAttributes_t()
15 attributes.triangle = SparseLowerTriangle
16 attributes.kind = SparseSymmetric
17 let matrix = SparseConvertFromCoordinate(Int32(size), Int32(size), keys.count, 1, attributes, rows, columns, values)
18 defer { SparseCleanup(matrix) }
19 factor = SparseFactor(SparseFactorizationCholesky, matrix)
20 precondition(factor.status == SparseStatusOK, "normal matrix not positive definite")
21 }
22
23 deinit { SparseCleanup(factor) }
24
25 func solve(_ values: inout [Double], columns: Int) {
26 values.withUnsafeMutableBufferPointer { buffer in
27 let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size),
28 attributes: SparseAttributes_t(), data: buffer.baseAddress!)
29 SparseSolve(factor, b)
30 }
31 }
32}
33
34/// Least squares over the mesh's triangle edges, Σ |x_j − x_i − d_ij|², with the `fixed` vertices
35/// held where the given positions have them (decision 0002's normal equations, uniform weights).
36final class EdgeFit {
37 let mesh: Mesh
38 let fixed: [Bool]
39 let row: [Int]
40 let free: [Int]
41 private let factor: SparseCholesky?
42
43 init(mesh: Mesh, fixed: Set<Int>) {
44 self.mesh = mesh
45 self.fixed = mesh.rest.indices.map { fixed.contains($0) }
46 free = mesh.rest.indices.filter { !fixed.contains($0) }
47 var row = Array(repeating: -1, count: mesh.rest.count)
48 for (r, v) in free.enumerated() { row[v] = r }
49 self.row = row
50 var matrix: [SIMD2<Int>: Double] = [:]
51 for t in mesh.triangles {
52 for (i, j) in [(t.x, t.y), (t.y, t.z), (t.z, t.x)] {
53 for (v, o) in [(i, j), (j, i)] where row[v] >= 0 {
54 matrix[SIMD2(row[v], row[v]), default: 0] += 1
55 if row[o] >= 0, row[o] < row[v] { matrix[SIMD2(row[v], row[o]), default: 0] -= 1 }
56 }
57 }
58 }
59 factor = free.isEmpty ? nil : SparseCholesky(size: free.count, lower: matrix)
60 }
61
62 /// The positions fitting per-triangle edge targets `d[t][k]` for the edge from corner k to
63 /// corner k + 1, holding fixed vertices at `x`'s positions.
64 func fit(_ x: [V3], targets d: [E3]) -> [V3] {
65 guard let factor else { return x }
66 let n = free.count
67 var rhs = [Double](repeating: 0, count: 3 * n)
68 func add(_ r: Int, _ v: V3) {
69 rhs[r] += v.x
70 rhs[n + r] += v.y
71 rhs[2 * n + r] += v.z
72 }
73 for (k, t) in mesh.triangles.enumerated() {
74 let c = [t.x, t.y, t.z], e = [d[k].e0, d[k].e1, d[k].e2]
75 for m in 0..<3 {
76 let i = c[m], j = c[(m + 1) % 3]
77 if row[i] >= 0 {
78 add(row[i], -e[m])
79 if row[j] < 0 { add(row[i], x[j]) }
80 }
81 if row[j] >= 0 {
82 add(row[j], e[m])
83 if row[i] < 0 { add(row[j], x[i]) }
84 }
85 }
86 }
87 factor.solve(&rhs, columns: 3)
88 var out = x
89 for (r, v) in free.enumerated() { out[v] = V3(rhs[r], rhs[n + r], rhs[2 * n + r]) }
90 return out
91 }
92
93 /// Rest edges of each triangle, corner k to corner k + 1, in 3D.
94 lazy var restEdges: [E3] = mesh.triangles.map { t in
95 let p = [mesh.rest[t.x], mesh.rest[t.y], mesh.rest[t.z]].map { V3($0.x, $0.y, 0) }
96 return E3(p[1] - p[0], p[2] - p[1], p[0] - p[2])
97 }
98
99 /// Iterative as-rigid-as-possible: alternate each triangle's best rotation from the flat sheet
100 /// with the least-squares fit. Returns the positions and the last change.
101 func arap(_ start: [V3], iterations: Int, tolerance: Double = 0) -> (x: [V3], change: Double) {
102 var x = start
103 var change = 0.0
104 for _ in 0..<iterations {
105 let r = rotations(x)
106 let d = zip(r, restEdges).map { q, e in E3(q * e.e0, q * e.e1, q * e.e2) }
107 let next = fit(x, targets: d)
108 change = zip(next, x).map { simd_distance($0, $1) }.max() ?? 0
109 x = next
110 if change < tolerance { break }
111 }
112 return (x, change)
113 }
114
115 /// Per triangle, the rotation taking the flat triangle to its best fit in `x`, its normal to
116 /// the triangle's normal.
117 func rotations(_ x: [V3]) -> [simd_double3x3] {
118 mesh.triangles.enumerated().map { k, t in bestRotation(rest: restEdges[k], [x[t.x], x[t.y], x[t.z]]) }
119 }
120}
121
122/// The rotation taking a flat triangle (edges `rest`, in z = 0, counterclockwise) to the best fit
123/// of the triangle `q`: its normal onto q's normal, then the in-plane angle fitted in least squares.
124func bestRotation(rest: E3, _ q: [V3]) -> simd_double3x3 {
125 let e = [q[1] - q[0], q[2] - q[1], q[0] - q[2]]
126 var n = cross(e[0], -e[2])
127 let l = length(n)
128 guard l > 1e-300 else { return matrix_identity_double3x3 }
129 n /= l
130 let u = normalize(e[0]), v = cross(n, u)
131 // 2D covariance between rest (x, y) and current (u, v) coordinates
132 var a = 0.0, b = 0.0
133 for (r, c) in zip([rest.e0, rest.e1, rest.e2], e) {
134 let cu = dot(c, u), cv = dot(c, v)
135 a += r.x * cu + r.y * cv // cos part
136 b += r.x * cv - r.y * cu // sin part
137 }
138 let theta = atan2(b, a)
139 let ex = cos(theta) * u + sin(theta) * v, ey = -sin(theta) * u + cos(theta) * v
140 return simd_double3x3(columns: (ex, ey, n))
141}
142
143/// Per-triangle rotation from pose a to pose b (both best fits from the flat sheet).
144func relativeRotations(_ fit: EdgeFit, _ a: [V3], _ b: [V3]) -> [simd_quatd] {
145 zip(fit.rotations(a), fit.rotations(b)).map { ra, rb in
146 var q = simd_quatd(rb * ra.transpose)
147 if q.real < 0 { q = simd_quatd(vector: -q.vector) }
148 return q
149 }
150}
151
152/// Decision 0002's pop generalised to bent poses: at s each triangle's edges are a blend of its
153/// edges in `a` and in `b` (turned back), turned by s of its rotation from a to b; positions by
154/// least squares with `fit`'s fixed vertices held. Exact at s = 0 and 1 when both poses agree on
155/// the fixed vertices.
156struct Blend {
157 let fit: EdgeFit
158 let a: [V3]
159 let b: [V3]
160 let turns: [simd_quatd]
161 let ea: [E3]
162 let eb: [E3]
163
164 init(_ fit: EdgeFit, from a: [V3], to b: [V3], turns: [simd_quatd]? = nil) {
165 self.fit = fit
166 self.a = a
167 self.b = b
168 self.turns = turns ?? relativeRotations(fit, a, b)
169 func edges(_ x: [V3]) -> [E3] {
170 fit.mesh.triangles.map { t in E3(x[t.y] - x[t.x], x[t.z] - x[t.y], x[t.x] - x[t.z]) }
171 }
172 ea = edges(a)
173 eb = edges(b)
174 }
175
176 func at(_ s: Double) -> [V3] {
177 let id = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
178 let d = turns.indices.map { k -> E3 in
179 let q = turns[k], qs = simd_slerp(id, q, s), back = q.inverse
180 func one(_ x: V3, _ y: V3) -> V3 { qs.act((1 - s) * x + s * back.act(y)) }
181 return E3(one(ea[k].e0, eb[k].e0), one(ea[k].e1, eb[k].e1), one(ea[k].e2, eb[k].e2))
182 }
183 // fixed vertices move linearly (they agree in both poses in every use here)
184 var x = a
185 for v in a.indices where fit.fixed[v] { x[v] = (1 - s) * a[v] + s * b[v] }
186 return fit.fit(x, targets: d)
187 }
188}
189
190/// A triangle's three edge vectors, corner k to corner k + 1.
191struct E3 {
192 var e0: V3, e1: V3, e2: V3
193 init(_ e0: V3, _ e1: V3, _ e2: V3) { (self.e0, self.e1, self.e2) = (e0, e1, e2) }
194}