spikes/bending/Sources/Bending/Reverse.swift
202 lines · 10053 bytes
11 symbols in this file
1import simd
2
3/// An inside reverse fold of a multi-layer flap on a flat-folded frame, set up for bending.
4///
5/// The flap is folded on its spine (a straight line in the frame), its layers split into a near
6/// half (toward `normal`, the viewer) and a far half. The reverse crease runs from `vertex`, on the
7/// spine, along `crease` in the paper's plane; the tip is beyond it. The near layers open by
8/// turning about the spine toward the viewer by α; at the vertex the four creases (body spine, tip
9/// spine and the two layers' reverse creases) form decision 0001's degree-4 vertex, rigid on two
10/// branches: the tip opened with its layers (unreversed) and the tip reversed between them.
11struct ReverseFold {
12 var model: Model
13 let frame: Int
14 let vertex: V3
15 /// Along the spine from the vertex toward the body.
16 let spine: V3
17 /// Along the reverse crease from the vertex, in the paper's plane.
18 let crease: V3
19 /// The paper's normal toward the viewer, the side the near layers open to.
20 let normal: V3
21 let tipNear: Set<Int>
22 let tipFar: Set<Int>
23 /// Near faces on the flap's side of the spine's line, not in the tip.
24 let nearSide: Set<Int>
25 /// Near faces across the spine's line (they must bend or crease along it to open).
26 let across: Set<Int>
27 /// Everything else: the far half and the near faces beyond the spine's line.
28 let rest: Set<Int>
29
30 /// Rotation turning the near layers by α toward the viewer about the spine.
31 func opening(_ alpha: Double) -> simd_quatd {
32 // the sign that lifts the crease's in-plane offset from the spine toward the viewer
33 let side = normalize(crease - dot(crease, spine) * spine)
34 let q = simd_quatd(angle: alpha * .pi / 180, axis: spine)
35 return dot(q.act(side), normal) >= 0 || alpha == 0 ? q : simd_quatd(angle: -alpha * .pi / 180, axis: spine)
36 }
37
38 /// The tip's two rigid motions with the near layers opened by α: unreversed (the tip turns with
39 /// its layers) or reversed (each layer of the tip turned about its own reverse crease so that
40 /// the tip's spine meets in the plane bisecting the opened layers).
41 func tip(alpha: Double, reversed: Bool) -> (near: (V3) -> V3, far: (V3) -> V3) {
42 let open = opening(alpha)
43 let v = vertex
44 guard reversed else { return ({ v + open.act($0 - v) }, { $0 }) }
45 let cn = open.act(crease), c = crease
46 let w = -spine
47 let gamma: Double
48 if alpha < 1e-9 {
49 gamma = .pi
50 } else {
51 let wPerp = w - dot(w, cn) * cn
52 let p = dot(wPerp, c), q = dot(cross(cn, wPerp), c)
53 gamma = 2 * atan2(q, p)
54 }
55 let turnNear = simd_quatd(angle: gamma, axis: cn) * open
56 let u = turnNear.act(w)
57 // the far layer turns about its crease to bring the tip spine to u
58 let a = w - dot(w, c) * c, b = u - dot(u, c) * c
59 let gammaFar = atan2(dot(cross(a, b), c), dot(a, b))
60 let turnFar = simd_quatd(angle: gammaFar, axis: c)
61 return ({ v + turnNear.act($0 - v) }, { v + turnFar.act($0 - v) })
62 }
63}
64
65/// The reverse fold's measurements on one mesh, for one choice of what bends.
66struct ReverseRun {
67 var openStrain = 0.0, popStrain = 0.0, closeStrain = 0.0
68 var openPrincipal = 0.0, popPrincipal = 0.0, closePrincipal = 0.0
69 var openCollisions = 0, popCollisions = 0, closeCollisions = 0
70 var firstCollision: (phase: String, s: Double, faces: (Int, Int))?
71 var tipInside = false
72 var endError = 0.0
73 var worst: (strain: Double, rest: Double, at: V2) = (0, 0, .zero)
74 var arapChange = 0.0
75}
76
77/// Open by α_max over the first third, pop the tip between the layers over the second (decision
78/// 0002's per-face slerp, the rest held), close on the reversed branch over the last. Faces in
79/// `free` bend by as-rigid-as-possible solves at every sample; the tip's faces follow the rigid
80/// branch for the current α; every other face holds frame n − 1's place.
81func runReverse(_ r: ReverseFold, mesh: Mesh, alphaMax: Double, free: Set<Int>, samples: Int = 24,
82 collisionDepth: Double, iterations: Int = 60) -> ReverseRun {
83 let model = r.model
84 let x0 = mesh.pose(model.positions(r.frame))
85 let tipNear = mesh.vertices(of: r.tipNear), tipFar = mesh.vertices(of: r.tipFar)
86 let freeVertices = mesh.vertices(of: free).subtracting(tipNear).subtracting(tipFar)
87 .subtracting(mesh.vertices(of: Set(model.faces.indices).subtracting(free).subtracting(r.tipNear).subtracting(r.tipFar)))
88 let fixed = Set(mesh.rest.indices).subtracting(freeVertices)
89 let fit = EdgeFit(mesh: mesh, fixed: fixed)
90 let edges = mesh.edges
91 let size = model.size
92 var run = ReverseRun()
93
94 func handles(_ alpha: Double, reversed: Bool, onto x: [V3]) -> [V3] {
95 let (near, far) = r.tip(alpha: alpha, reversed: reversed)
96 var out = x
97 for v in fixed { out[v] = x0[v] }
98 for v in tipFar { out[v] = far(x0[v]) }
99 for v in tipNear { out[v] = near(x0[v]) }
100 return out
101 }
102 // the free vertices' guess: turned with the opening, about the spine
103 func predict(_ x: [V3], from a0: Double, to a1: Double) -> [V3] {
104 let q = r.opening(a1) * r.opening(a0).inverse
105 var out = x
106 let nearSide = mesh.vertices(of: r.nearSide)
107 for v in freeVertices where nearSide.contains(v) { out[v] = r.vertex + q.act(x[v] - r.vertex) }
108 return out
109 }
110 func measure(_ x: [V3], phase: String, s: Double, strain s0: inout Double, principal p0: inout Double, collisions c0: inout Int) {
111 let e = strain(x, mesh, edges: edges)
112 if e > run.worst.strain { run.worst = worstEdge(x, mesh, edges: edges) }
113 s0 = max(s0, e)
114 p0 = max(p0, principalStrain(x, mesh))
115 let hits = meshCollisions(x, mesh, size: size, depth: collisionDepth)
116 c0 += hits.count
117 if let h = hits.first, run.firstCollision == nil {
118 run.firstCollision = (phase, s, (mesh.faceOf[h.0], mesh.faceOf[h.1]))
119 }
120 }
121
122 // open
123 var x = x0
124 var alpha = 0.0
125 for k in 1...samples {
126 let a = alphaMax * Double(k) / Double(samples)
127 x = handles(a, reversed: false, onto: predict(x, from: alpha, to: a))
128 let solved = fit.arap(x, iterations: iterations, tolerance: 1e-10 * size)
129 x = solved.x
130 run.arapChange = max(run.arapChange, solved.change)
131 alpha = a
132 measure(x, phase: "open", s: Double(k) / Double(samples), strain: &run.openStrain, principal: &run.openPrincipal,
133 collisions: &run.openCollisions)
134 }
135 let opened = x
136 // pop: the tip's faces turn by slerp, everything else held as opened
137 let popped = handles(alphaMax, reversed: true, onto: opened)
138 let popFit = EdgeFit(mesh: mesh, fixed: Set(mesh.rest.indices).subtracting(tipNear.union(tipFar)
139 .subtracting(mesh.vertices(of: Set(model.faces.indices).subtracting(r.tipNear).subtracting(r.tipFar)))))
140 let blend = Blend(popFit, from: opened, to: popped)
141 for k in 1..<samples {
142 let s = Double(k) / Double(samples)
143 measure(blend.at(s), phase: "pop", s: s, strain: &run.popStrain, principal: &run.popPrincipal, collisions: &run.popCollisions)
144 }
145 // close
146 x = popped
147 alpha = alphaMax
148 var beforeLanding = x
149 for k in 1...samples {
150 let a = alphaMax * (1 - Double(k) / Double(samples))
151 x = handles(a, reversed: true, onto: predict(x, from: alpha, to: a))
152 let solved = fit.arap(x, iterations: iterations, tolerance: 1e-10 * size)
153 x = solved.x
154 run.arapChange = max(run.arapChange, solved.change)
155 alpha = a
156 if k < samples {
157 measure(x, phase: "close", s: Double(k) / Double(samples), strain: &run.closeStrain, principal: &run.closePrincipal,
158 collisions: &run.closeCollisions)
159 }
160 if k == samples - 1 { beforeLanding = x }
161 }
162 // the end must be frame n − 1 with the tip reflected in its crease (frame n)
163 let end = handles(0, reversed: true, onto: x)
164 run.endError = zip(x, end).map { simd_distance($0, $1) }.max() ?? 0
165 run.tipInside = tipBetweenLayers(beforeLanding, mesh, tip: r.tipNear.union(r.tipFar), upper: r.nearSide.union(r.across),
166 lower: r.rest, normal: r.normal)
167 return run
168}
169
170/// Whether a point of the tip lies above the far layers and below the near layers, along
171/// `normal`: some tip triangle's centroid has a far triangle under it and every near triangle over
172/// that point is above it.
173func tipBetweenLayers(_ x: [V3], _ mesh: Mesh, tip: Set<Int>, upper: Set<Int>, lower: Set<Int>, normal: V3) -> Bool {
174 let n = normalize(normal)
175 let a = normalize(abs(n.x) < 0.9 ? cross(n, V3(1, 0, 0)) : cross(n, V3(0, 1, 0))), b = cross(n, a)
176 func flat(_ p: V3) -> V2 { V2(dot(p, a), dot(p, b)) }
177 func height(_ t: SIMD3<Int>, over q: V2) -> Double? {
178 let p = [x[t.x], x[t.y], x[t.z]]
179 let f = p.map(flat)
180 let d = cross2(f[1] - f[0], f[2] - f[0])
181 guard abs(d) > 1e-14 else { return nil }
182 let l1 = cross2(q - f[0], f[2] - f[0]) / d, l2 = cross2(f[1] - f[0], q - f[0]) / d
183 guard l1 >= 0, l2 >= 0, l1 + l2 <= 1 else { return nil }
184 return dot(p[0] + l1 * (p[1] - p[0]) + l2 * (p[2] - p[0]), n)
185 }
186 var inside = 0
187 for (k, t) in mesh.triangles.enumerated() where tip.contains(mesh.faceOf[k]) {
188 let c = (x[t.x] + x[t.y] + x[t.z]) / 3
189 let q = flat(c), h = dot(c, n)
190 var below = false, aboveOK = true, sawAbove = false
191 for (j, u) in mesh.triangles.enumerated() {
192 let f = mesh.faceOf[j]
193 if lower.contains(f), let z = height(u, over: q), z < h { below = true }
194 if upper.contains(f), let z = height(u, over: q) {
195 sawAbove = true
196 if z <= h { aboveOK = false }
197 }
198 }
199 if below && sawAbove && aboveOK { inside += 1 }
200 }
201 return inside > 0
202}