Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift
276 lines · 13998 bytes
15 symbols in this file
1import FoldFormat
2import simd
3
4/// Maps a drag on the paper view to the fold parameter of a step, so the moving faces follow the
5/// finger. Screen points are UIKit's: origin top left, y down, in a viewport of `viewportSize`.
6///
7/// The step is split into segments at the ends of every axis's window, at the middle of each
8/// window of a fold-and-unfold (its peak), and at a non-rigid step's phases. Within a segment the
9/// drag follows the area centroid of one axis's moving faces: of the axes whose window covers the
10/// segment, the one whose centroid travels furthest on screen, keeping the previous segment's
11/// axis on a tie. A non-rigid step's axes all count as covering every segment. The centroid is
12/// projected at the depth of the camera's target, so that a face nearing the eye as it lands flat
13/// does not overshoot its end on screen and leave t = 1 unreachable by a finger dragged past it.
14public struct FoldParameterMapping: Sendable {
15 /// The drag's path at 129 evenly spaced values of t: the followed centroids, each segment's
16 /// translated to begin where the segment before it ended. A segment along which no covering
17 /// axis's centroid travels 8 points is instead a straight line down, `fallbackThrow` points per
18 /// unit of t.
19 public let path: [SIMD2<Double>]
20 /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere.
21 public let isDegenerate: Bool
22
23 /// Where a drag is on the path: its parameter and the segment it is in. At a boundary `t`
24 /// alone does not say which: a drag that reaches a boundary has crossed it.
25 public struct Position: Sendable, Equatable {
26 public let t: Double
27 let segment: Int
28 }
29
30 /// The search polyline: `path`'s samples with the segment boundaries added.
31 private let ts: [Double]
32 private let points: [SIMD2<Double>]
33 /// Index ranges of `ts`, one per segment, in order.
34 private let segments: [ClosedRange<Int>]
35 /// Per segment, whether a drag can cross back over its start: not at a fold-and-unfold's peak.
36 private let reversible: [Bool]
37
38 private static let samples = 129
39 private static let minimumLength = 8.0
40 /// Points dragged down for the whole step where a segment's path is under `minimumLength`: 160,
41 /// or half the view's height when that is less. A stretch that starts in the upper half of the
42 /// view then ends inside it; one that starts lower can run past its bottom edge, as the crane's
43 /// head pop does on iPhone (it starts at y ≈ 316 of 362 points). Its direction stays down
44 /// pending a check on a device (ruling R84).
45 private let fallbackThrow: Double
46 /// How much further, in points, another axis's centroid must travel to replace the previous
47 /// segment's axis.
48 private static let preference = 0.5
49 /// How far past the best point so far the search continues, in points.
50 private static let slack = 8.0
51 /// How near the path's end, measured along it, a point counts as the end, in points.
52 private static let endTolerance = 0.5
53
54 public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) {
55 fallbackThrow = min(160, viewportSize.y / 2)
56 var followed: [(faces: [Int], window: ClosedRange<Double>)]
57 var boundaries: Set<Double> = [0, 1], peaks: Set<Double> = []
58 if step.nonRigid, let pop = step.pop {
59 followed = step.axes.map { (Array($0.movingFaces), 0...1) }
60 boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound])
61 } else {
62 followed = step.axes.map { (Array($0.movingFaces), $0.window) }
63 for w in step.axes.map(\.window) {
64 boundaries.formUnion([w.lowerBound, w.upperBound])
65 if step.kind == .foldAndUnfold { peaks.insert((w.lowerBound + w.upperBound) / 2) }
66 }
67 }
68 if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] }
69 let bounds = boundaries.union(peaks).sorted()
70 reversible = bounds.dropLast().map { $0 > 0 && !peaks.contains($0) }
71
72 let n = Double(Self.samples - 1)
73 let grid = (0..<Self.samples).map { Double($0) / n }
74 let ts = Array(Set(grid + bounds)).sorted()
75 self.ts = ts
76 segments = zip(bounds, bounds.dropFirst()).map { ts.firstIndex(of: $0)!...ts.firstIndex(of: $1)! }
77
78 let projection = Projection(camera: camera, viewportSize: viewportSize)
79 let interpolator = FoldInterpolator(file: file, step: step)
80 let centroids = Centroids(file: file, sets: followed.map(\.faces))
81 let screen = ts.map { t in centroids.points(interpolator.positions(at: t)).map(projection.point) }
82
83 var points = ts.map { _ in SIMD2<Double>.zero }
84 var previous: Int?
85 var fallbacks = 0
86 for segment in segments {
87 func travel(_ c: Int) -> Double {
88 segment.dropLast().reduce(0) { $0 + distance(screen[$1][c], screen[$1 + 1][c]) }
89 }
90 let (a, b) = (ts[segment.lowerBound], ts[segment.upperBound])
91 let covering = followed.indices.filter { followed[$0].window.lowerBound <= a && b <= followed[$0].window.upperBound }
92 var choice: Int?
93 for c in (previous.map { [$0] } ?? []) + covering where covering.contains(c) && travel(c) >= Self.minimumLength {
94 if choice.map({ travel(c) > travel($0) + Self.preference }) ?? true { choice = c }
95 }
96 let start = segment.lowerBound == 0 ? screen[0][choice ?? 0] : points[segment.lowerBound]
97 for i in segment {
98 points[i] = choice.map { start + screen[i][$0] - screen[segment.lowerBound][$0] }
99 ?? start + SIMD2(0, (ts[i] - a) * fallbackThrow)
100 }
101 if choice == nil { fallbacks += 1 }
102 previous = choice ?? previous
103 }
104 self.points = points
105 isDegenerate = fallbacks == segments.count
106 path = grid.map { t in points[ts.firstIndex(of: t)!] }
107 }
108
109 /// The point of `path` at `t`.
110 public func point(at t: Double) -> SIMD2<Double> {
111 let t = min(max(t, 0), 1)
112 let i = min(ts.lastIndex { $0 <= t }!, ts.count - 2)
113 let u = (t - ts[i]) / (ts[i + 1] - ts[i])
114 return points[i] + u * (points[i + 1] - points[i])
115 }
116
117 /// The position at `t`, clamped to 0...1; at a boundary, in the later segment.
118 public func position(at t: Double) -> Position {
119 let t = min(max(t, 0), 1)
120 return Position(t: t, segment: segments.lastIndex { ts[$0.lowerBound] <= t }!)
121 }
122
123 /// The parameter `position(grabbedAt:translation:current:)` gives from `position(at: current)`.
124 public func parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double {
125 position(grabbedAt: grabbedAt, translation: translation, current: position(at: current)).t
126 }
127
128 /// The position whose point of `path` is nearest `grabbedAt + translation`, where `grabbedAt`
129 /// is `point(at:)` of t when the drag began.
130 ///
131 /// The search walks the path outward from `current` within its segment. It also searches the
132 /// segment beyond a boundary when `current` is within one sample of the boundary, or when the
133 /// nearest point is the boundary itself, so that the finger has reached it. A neighbour's point
134 /// is taken only if strictly nearer. So where the path doubles back on screen at a boundary, a
135 /// finger moving along the retraced stretch stays in the segment the drag is in, and changes
136 /// segment only at the turnaround. A drag that reaches a boundary crosses it, so the next
137 /// movement along a retraced stretch continues into the segment beyond. Boundaries are crossed
138 /// both ways, except a fold-and-unfold's peak, which is crossed only forward. A point within
139 /// half a point of the path's end, measured along the path, is the end.
140 ///
141 /// When the path is degenerate the drag's downward component advances the fold over
142 /// `fallbackThrow` points from `current`, which is then the position when the drag began.
143 public func position(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Position) -> Position {
144 if isDegenerate { return position(at: current.t + translation.y / fallbackThrow) }
145
146 let target = grabbedAt + translation
147 let s = current.segment
148 // the polyline edge from point i to point i + 1 holding current
149 var start = segments[s].lowerBound
150 while start + 1 < segments[s].upperBound && ts[start + 1] <= current.t { start += 1 }
151
152 let own = nearest(target, in: s, from: start, directions: [1, -1])
153 var best = own
154 for direction in [1, -1] {
155 let edge = direction > 0 ? segments[s].upperBound - 1 : segments[s].lowerBound + 1
156 var near = direction > 0 ? current.t >= ts[edge] : current.t <= ts[edge]
157 var from = own
158 while near || from.toBoundary(direction) == 0 {
159 let n = from.segment + direction
160 guard n >= 0 && n < segments.count && (direction > 0 || reversible[from.segment]) else { break }
161 let candidate = nearest(target, in: n, from: direction > 0 ? segments[n].lowerBound : segments[n].upperBound - 1,
162 directions: [direction])
163 guard candidate.distance < best.distance else { break }
164 best = candidate
165 from = candidate
166 near = false
167 }
168 }
169
170 if best.segment == segments.count - 1 && best.toBoundary(1) <= Self.endTolerance {
171 return Position(t: 1, segment: best.segment)
172 }
173 let t = (1 - best.u) * ts[best.edge] + best.u * ts[best.edge + 1]
174 var segment = best.segment
175 if t != current.t {
176 if best.toBoundary(1) == 0 && segment + 1 < segments.count {
177 segment += 1
178 } else if best.toBoundary(-1) == 0 && reversible[segment] {
179 segment -= 1
180 }
181 }
182 return Position(t: t, segment: segment)
183 }
184
185 /// A point of the search polyline: `u` of the way along edge `edge` of segment `segment`.
186 private struct Nearest {
187 let segment: Int
188 let edge: Int
189 let u: Double
190 let distance: Double
191 /// Distance along the path to the segment's end (`direction` 1) or start (−1).
192 let toEnd: Double
193 let toStart: Double
194
195 func toBoundary(_ direction: Int) -> Double { direction > 0 ? toEnd : toStart }
196 }
197
198 /// The point of segment `s` nearest `target`, walking outward from edge `start` in each of
199 /// `directions` until an edge is `slack` farther than the best so far.
200 private func nearest(_ target: SIMD2<Double>, in s: Int, from start: Int, directions: [Int]) -> Nearest {
201 let segment = segments[s]
202 func onEdge(_ i: Int) -> (edge: Int, u: Double, distance: Double) {
203 let a = points[i], d = points[i + 1] - points[i]
204 let lengthSquared = dot(d, d)
205 let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0
206 return (i, u, distance(a + u * d, target))
207 }
208 var best = onEdge(start)
209 for direction in directions {
210 var i = start + direction
211 while i >= segment.lowerBound && i < segment.upperBound {
212 let candidate = onEdge(i)
213 if candidate.distance < best.distance {
214 best = candidate
215 } else if candidate.distance > best.distance + Self.slack {
216 break
217 }
218 i += direction
219 }
220 }
221 let length = distance(points[best.edge], points[best.edge + 1])
222 var toEnd = (1 - best.u) * length, toStart = best.u * length
223 for i in best.edge + 1 ..< segment.upperBound { toEnd += distance(points[i], points[i + 1]) }
224 for i in segment.lowerBound ..< best.edge { toStart += distance(points[i], points[i + 1]) }
225 return Nearest(segment: s, edge: best.edge, u: best.u, distance: best.distance, toEnd: toEnd, toStart: toStart)
226 }
227}
228
229/// The area centroids of sets of faces.
230private struct Centroids {
231 /// Per set, fan triangles of its faces with their areas in frame 0.
232 let triangles: [[(SIMD3<Int>, Double)]]
233
234 init(file: FoldFile, sets: [[Int]]) {
235 let flat = file.frames[0].verticesCoords
236 triangles = sets.map { faces in
237 faces.flatMap { f in
238 let face = file.facesVertices[f]
239 return (1..<face.count - 1).map { i in
240 (SIMD3(face[0], face[i], face[i + 1]),
241 length(cross(flat[face[i]] - flat[face[0]], flat[face[i + 1]] - flat[face[0]])) / 2)
242 }
243 }
244 }
245 }
246
247 func points(_ positions: [SIMD3<Double>]) -> [SIMD3<Double>] {
248 triangles.map { set in
249 var sum = SIMD3<Double>.zero, area = 0.0
250 for (v, a) in set {
251 sum += a * (positions[v.x] + positions[v.y] + positions[v.z]) / 3
252 area += a
253 }
254 return sum / area
255 }
256 }
257}
258
259/// Projects to screen points at the depth of the camera's target.
260private struct Projection {
261 let viewProjection: simd_double4x4
262 /// Clip-space w of the camera's target.
263 let depth: Double
264 let viewportSize: SIMD2<Double>
265
266 init(camera: Camera, viewportSize: SIMD2<Double>) {
267 viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y)
268 depth = (viewProjection * SIMD4(camera.target, 1)).w
269 self.viewportSize = viewportSize
270 }
271
272 func point(_ p: SIMD3<Double>) -> SIMD2<Double> {
273 let clip = viewProjection * SIMD4(p, 1)
274 return SIMD2((clip.x / depth + 1) / 2 * viewportSize.x, (1 - clip.y / depth) / 2 * viewportSize.y)
275 }
276}