Commit 058a42d32c

058a42d32c09f3b778234a2a930f5e694bfba4a9

parent: 9aed562990

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 20:45 UTC

Banded pop: blend each tip layer's turn toward the other's near the spine

Ref #7

Layout: unified · split

Packages/FoldKit/Sources/Folding/Bending.swift +35 −12
@@ -4,19 +4,34 @@ import Synchronization
4 4
5/// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces 5/// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces
6/// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by 6/// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by
7/// `s` of its face's rotation from the first pose to the second (slerp), and the mesh vertices 7/// its target, and the mesh vertices are the least-squares fit to those edges, with the vertices of
8/// are the least-squares fit to those edges, with the vertices of held faces kept where the first 8/// held faces kept where the first pose has them. A triangle's target is `s` of its face's
9/// pose has them. At `s = 0` and `s = 1` the fit is exact, so it reproduces both poses. 9/// rotation from the first pose to the second (slerp); for a triangle in `blends` (decision 0003's
10/// band) it is slerp(mid, own, w), where own is that slerp, mid = slerp(own, other, ½), other is
11/// the slerp of the partner face's rotation, and w = weight + (1 − weight)(1 − 4s(1 − s)). At
12/// `s = 0` and `s = 1` every target is the face's own rotation and the fit is exact, so it
13/// reproduces both poses.
10struct Bending: Sendable { 14struct Bending: Sendable {
15 /// A triangle whose turn is blended toward its partner face's.
16 struct Blend: Sendable {
17 let triangle: Int
18 let partner: Int
19 /// 1 where the triangle keeps its own turn throughout.
20 let weight: Double
21 }
22
11 /// The mesh vertices in the first pose. 23 /// The mesh vertices in the first pose.
12 private let rest: [SIMD3<Double>] 24 private let rest: [SIMD3<Double>]
13 /// Per FOLD face, its rotation from the first pose to the second. 25 /// Per FOLD face, its rotation from the first pose to the second.
14 private let turns: [simd_quatd] 26 private let turns: [simd_quatd]
27 /// The blended triangles' faces, partners and weights; the k-th takes target `turns.count + k`.
28 private let blends: [(face: Int, partner: Int, weight: Double)]
15 /// The mesh vertices that move, in the solve's row order. 29 /// The mesh vertices that move, in the solve's row order.
16 private let free: [Int] 30 private let free: [Int]
17 /// Per row and FOLD face, the signed sum of the rest edge vectors of that face's triangles at 31 /// Per row and target, the signed sum of the rest edge vectors of that target's triangles at
18 /// the row's vertex; the right-hand side adds each turned by `s` of the face's turn. 32 /// the row's vertex; the right-hand side adds each turned by the target at `s`. Targets are the
19 private let terms: [(row: Int, face: Int, vector: SIMD3<Double>)] 33 /// FOLD faces, then the blended triangles.
34 private let terms: [(row: Int, target: Int, vector: SIMD3<Double>)]
20 /// Per row, what the held vertices contribute to the normal equation's right-hand side. 35 /// Per row, what the held vertices contribute to the normal equation's right-hand side.
21 private let held: [SIMD3<Double>] 36 private let held: [SIMD3<Double>]
22 private let factor: SparseCholesky 37 private let factor: SparseCholesky
@@ -24,8 +39,9 @@ struct Bending: Sendable {
24 /// - Parameters: 39 /// - Parameters:
25 /// - first, second: the FOLD vertex positions of two rigid poses. 40 /// - first, second: the FOLD vertex positions of two rigid poses.
26 /// - heldFaces: FOLD faces placed alike in both poses, whose mesh vertices stay put. 41 /// - heldFaces: FOLD faces placed alike in both poses, whose mesh vertices stay put.
42 /// - blends: triangles whose turns blend toward a partner face's.
27 init(mesh: RenderMesh, faces: [[Int]], from first: [SIMD3<Double>], to second: [SIMD3<Double>], 43 init(mesh: RenderMesh, faces: [[Int]], from first: [SIMD3<Double>], to second: [SIMD3<Double>],
28 heldFaces: Set<Int>) { 44 heldFaces: Set<Int>, blends: [Blend] = []) {
29 rest = mesh.pose(first) 45 rest = mesh.pose(first)
30 turns = faces.map { corners in 46 turns = faces.map { corners in
31 // one corner triple for both poses, chosen on the flat sheet so ties cannot split 47 // one corner triple for both poses, chosen on the flat sheet so ties cannot split
@@ -35,6 +51,9 @@ struct Bending: Sendable {
35 if q.real < 0 { q = simd_quatd(vector: -q.vector) } 51 if q.real < 0 { q = simd_quatd(vector: -q.vector) }
36 return q 52 return q
37 } 53 }
54 self.blends = blends.map { (mesh.faceOf[$0.triangle], $0.partner, $0.weight) }
55 var target = mesh.faceOf
56 for (k, blend) in blends.enumerated() { target[blend.triangle] = faces.count + k }
38 57
39 var isHeld = Array(repeating: false, count: mesh.vertices.count) 58 var isHeld = Array(repeating: false, count: mesh.vertices.count)
40 for (t, (a, b, c)) in mesh.triangles.enumerated() where heldFaces.contains(mesh.faceOf[t]) { 59 for (t, (a, b, c)) in mesh.triangles.enumerated() where heldFaces.contains(mesh.faceOf[t]) {
@@ -50,12 +69,11 @@ struct Bending: Sendable {
50 var sums: [SIMD2<Int>: SIMD3<Double>] = [:] 69 var sums: [SIMD2<Int>: SIMD3<Double>] = [:]
51 var held = Array(repeating: SIMD3<Double>.zero, count: free.count) 70 var held = Array(repeating: SIMD3<Double>.zero, count: free.count)
52 for (t, (a, b, c)) in mesh.triangles.enumerated() { 71 for (t, (a, b, c)) in mesh.triangles.enumerated() {
53 let face = mesh.faceOf[t]
54 for (i, j) in [(a, b), (b, c), (c, a)] { 72 for (i, j) in [(a, b), (b, c), (c, a)] {
55 let d = rest[j] - rest[i] 73 let d = rest[j] - rest[i]
56 for (v, other, sign) in [(i, j, -1.0), (j, i, 1.0)] where row[v] >= 0 { 74 for (v, other, sign) in [(i, j, -1.0), (j, i, 1.0)] where row[v] >= 0 {
57 matrix[SIMD2(row[v], row[v]), default: 0] += 1 75 matrix[SIMD2(row[v], row[v]), default: 0] += 1
58 sums[SIMD2(row[v], face), default: .zero] += sign * d 76 sums[SIMD2(row[v], target[t]), default: .zero] += sign * d
59 if row[other] >= 0 { 77 if row[other] >= 0 {
60 if row[other] < row[v] { matrix[SIMD2(row[v], row[other]), default: 0] -= 1 } 78 if row[other] < row[v] { matrix[SIMD2(row[v], row[other]), default: 0] -= 1 }
61 } else { 79 } else {
@@ -72,7 +90,12 @@ struct Bending: Sendable {
72 /// The mesh vertex positions at `s` in 0...1. 90 /// The mesh vertex positions at `s` in 0...1.
73 func positions(at s: Double) -> [SIMD3<Double>] { 91 func positions(at s: Double) -> [SIMD3<Double>] {
74 let identity = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1) 92 let identity = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
75 let turned = turns.map { simd_slerp(identity, $0, s) } 93 var turned = turns.map { simd_slerp(identity, $0, s) }
94 let middle = 1 - 4 * s * (1 - s)
95 turned += blends.map { face, partner, weight in
96 let own = turned[face]
97 return simd_slerp(simd_slerp(own, turned[partner], 0.5), own, weight + (1 - weight) * middle)
98 }
76 let n = free.count 99 let n = free.count
77 var rhs = [Double](repeating: 0, count: 3 * n) 100 var rhs = [Double](repeating: 0, count: 3 * n)
78 for (r, h) in held.enumerated() { 101 for (r, h) in held.enumerated() {
@@ -80,8 +103,8 @@ struct Bending: Sendable {
80 rhs[n + r] = h.y 103 rhs[n + r] = h.y
81 rhs[2 * n + r] = h.z 104 rhs[2 * n + r] = h.z
82 } 105 }
83 for (r, face, vector) in terms { 106 for (r, target, vector) in terms {
84 let d = turned[face].act(vector) 107 let d = turned[target].act(vector)
85 rhs[r] += d.x 108 rhs[r] += d.x
86 rhs[n + r] += d.y 109 rhs[n + r] += d.y
87 rhs[2 * n + r] += d.z 110 rhs[2 * n + r] += d.z
Packages/FoldKit/Sources/Folding/FoldInterpolator.swift +50 −1
@@ -96,7 +96,8 @@ public struct FoldInterpolator: Sendable {
96 let moving = step.movingFaceUnion 96 let moving = step.movingFaceUnion
97 let bending = Bending(mesh: mesh, faces: file.facesVertices, 97 let bending = Bending(mesh: mesh, faces: file.facesVertices,
98 from: open.positions(at: pop.phases.lowerBound), to: pop.popped, 98 from: open.positions(at: pop.phases.lowerBound), to: pop.popped,
99 heldFaces: Set(file.facesVertices.indices.filter { !moving.contains($0) })) 99 heldFaces: Set(file.facesVertices.indices.filter { !moving.contains($0) }),
100 blends: band(mesh: mesh, file: file, tip: moving, spine: pop.spine, start: start))
100 mode = .nonRigid(NonRigid(open: open, close: close, phases: pop.phases, bending: bending)) 101 mode = .nonRigid(NonRigid(open: open, close: close, phases: pop.phases, bending: bending))
101 return 102 return
102 } 103 }
@@ -155,6 +156,54 @@ public struct FoldInterpolator: Sendable {
155 } 156 }
156} 157}
157 158
159/// Decision 0003's band: the tip's triangles within the tip's width of its spine, each blended
160/// toward the layer across the spine. The tip is `tip`; its spine is the edges of `spine` with both
161/// faces in it. A tip face's partner is the face across the spine from the faces it joins without
162/// crossing the spine. A triangle at distance d from the spine's line in `start` (frame n − 1),
163/// its centroid's, has weight d / b, b being the largest such distance of a tip triangle.
164private func band(mesh: RenderMesh, file: FoldFile, tip: Set<Int>, spine: [Int],
165 start: [SIMD3<Double>]) -> [Bending.Blend] {
166 let edgeFaces = edgesFaces(file)
167 let tipSpine = spine.filter { edgeFaces[$0].count == 2 && edgeFaces[$0].allSatisfy(tip.contains) }
168 guard let first = tipSpine.first else { return [] }
169
170 // the tip's layers: its faces joined across edges off the spine
171 var layer: [Int: Int] = [:]
172 for seed in tip.sorted() where layer[seed] == nil {
173 layer[seed] = seed
174 var stack = [seed]
175 while let f = stack.popLast() {
176 for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !tipSpine.contains(e) {
177 let g = faces[0] == f ? faces[1] : faces[0]
178 if tip.contains(g) && layer[g] == nil {
179 layer[g] = seed
180 stack.append(g)
181 }
182 }
183 }
184 }
185 var partnerOfLayer: [Int: Int] = [:]
186 for e in tipSpine {
187 let (f, g) = (edgeFaces[e][0], edgeFaces[e][1])
188 if partnerOfLayer[layer[f]!] == nil { partnerOfLayer[layer[f]!] = g }
189 if partnerOfLayer[layer[g]!] == nil { partnerOfLayer[layer[g]!] = f }
190 }
191
192 let ends = file.edgesVertices[first].map { start[$0] }
193 let direction = normalize(ends[1] - ends[0])
194 let points = mesh.pose(start)
195 let distances = mesh.triangles.map { a, b, c in
196 let offset = (points[a] + points[b] + points[c]) / 3 - ends[0]
197 return length(offset - dot(offset, direction) * direction)
198 }
199 let banded = mesh.triangles.indices.filter { tip.contains(mesh.faceOf[$0]) && partnerOfLayer[layer[mesh.faceOf[$0]]!] != nil }
200 guard let width = banded.map({ distances[$0] }).max(), width > 0 else { return [] }
201 return banded.compactMap { t in
202 let weight = distances[t] / width
203 return weight < 1 ? Bending.Blend(triangle: t, partner: partnerOfLayer[layer[mesh.faceOf[t]]!]!, weight: weight) : nil
204 }
205}
206
158/// p ↦ linear · p + offset 207/// p ↦ linear · p + offset
159private struct Transform { 208private struct Transform {
160 var linear: simd_double3x3 209 var linear: simd_double3x3
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +22
@@ -42,6 +42,28 @@ import FoldKitTestSupport
42 #expect(worst <= 0.10) 42 #expect(worst <= 0.10)
43} 43}
44 44
45@Test func theBandedPopStrainsTheFixtureLessThanPerFaceTurns() throws {
46 // decision 0003 at 20° from flat: 3.08% banded, 4.36% with each face turned on its own
47 let file = try compiled("reverse")
48 let step = try readSteps(file)[1]
49 let i = FoldInterpolator(file: file, step: step)
50 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
51 let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()!
52 #expect(worst < 0.035)
53}
54
55@Test func thePopStartsAndEndsOnTheRigidPoses() throws {
56 let file = try compiled("reverse")
57 let step = try readSteps(file)[1]
58 let i = FoldInterpolator(file: file, step: step)
59 let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
60 // at the phases' ends the mesh is placed rigidly; just inside them it is bent
61 for (bent, rigid) in [(lo + 1e-12, lo), (hi - 1e-12, hi)] {
62 #expect(zip(i.meshPositions(at: bent), i.meshPositions(at: rigid)).allSatisfy { simd_distance($0, $1) < 1e-9 },
63 "t \(rigid)")
64 }
65}
66
45@Test func theStepEndsOnItsEndFrame() throws { 67@Test func theStepEndsOnItsEndFrame() throws {
46 let file = try compiled("reverse") 68 let file = try compiled("reverse")
47 let i = FoldInterpolator(file: file, step: try readSteps(file)[1]) 69 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])