Commit fc04501554

fc045015545d6d983e2fa7aa191410afe27aa254

parent: b170d6099b

Unsigned

cmc <hello@cleberg.net> · 2026-10-20 08:42 UTC

Follow each axis window in the fold drag mapping

Ref #6

Layout: unified · split

Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift +108 −60
@@ -4,69 +4,106 @@ import simd
44/// Maps a drag on the paper view to the fold parameter of a step, so the moving faces follow the
55/// finger. Screen points are UIKit's: origin top left, y down, in a viewport of `viewportSize`.
66///
7/// The faces followed are the step's first moving set; in a non-rigid step that is the flap beyond
8/// the reverse creases. Their centroid is projected at the depth of the camera's target, so that a
9/// face nearing the eye as it lands flat does not overshoot its end on screen and leave t = 1
10/// unreachable by a finger dragged past it.
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.
1114public struct FoldParameterMapping: Sendable {
12 /// The centroid's screen point at 129 evenly spaced values of t.
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, 160 points per unit of t.
1318 public let path: [SIMD2<Double>]
14 /// Whether the path is under 8 points long, so a drag along it cannot control the fold.
19 /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere.
1520 public let isDegenerate: Bool
1621
1722 /// The search polyline: `path`'s samples with the segment boundaries added.
1823 private let ts: [Double]
1924 private let points: [SIMD2<Double>]
20 /// Index ranges of `ts` searched one at a time, in order: the whole step, the out and return
21 /// halves of a fold-and-unfold, or the open, pop and close phases of a non-rigid step.
25 /// Index ranges of `ts` searched one at a time, in order.
2226 private let segments: [ClosedRange<Int>]
23 private let centroid: Centroid
2427
2528 private static let samples = 129
2629 private static let minimumLength = 8.0
27 /// Points dragged down for the whole step when the path is degenerate.
30 /// Points dragged down for the whole step where a segment's path is under `minimumLength`.
2831 private static let fallbackThrow = 160.0
32 /// How much further, in points, another axis's centroid must travel to replace the previous
33 /// segment's axis.
34 private static let preference = 0.5
2935 /// How far past the best point so far the search continues, in points.
3036 private static let slack = 8.0
3137 /// How near its segment's end, along the path, a point counts as the end, in points.
3238 private static let endTolerance = 0.5
3339
3440 public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) {
35 let centroid = Centroid(file: file, step: step, camera: camera, viewportSize: viewportSize)
36 self.centroid = centroid
37
38 let boundaries: [Double]
41 var followed: [(faces: [Int], window: ClosedRange<Double>)]
42 var boundaries: Set<Double> = [0, 1]
3943 if step.nonRigid, let pop = step.pop {
40 boundaries = [0, pop.phases.lowerBound, pop.phases.upperBound, 1]
41 } else if step.kind == .foldAndUnfold {
42 boundaries = [0, 0.5, 1]
44 followed = step.axes.map { (Array($0.movingFaces), 0...1) }
45 boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound])
4346 } else {
44 boundaries = [0, 1]
47 followed = step.axes.map { (Array($0.movingFaces), $0.window) }
48 for w in step.axes.map(\.window) {
49 boundaries.formUnion([w.lowerBound, w.upperBound])
50 if step.kind == .foldAndUnfold { boundaries.insert((w.lowerBound + w.upperBound) / 2) }
51 }
4552 }
53 if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] }
54 let bounds = boundaries.sorted()
55
4656 let n = Double(Self.samples - 1)
4757 let grid = (0..<Self.samples).map { Double($0) / n }
48 ts = Array(Set(grid + boundaries)).sorted()
49 var segments: [ClosedRange<Int>] = []
50 for (a, b) in zip(boundaries, boundaries.dropFirst()) where a < b {
51 segments.append(ts.firstIndex(of: a)!...ts.firstIndex(of: b)!)
52 }
53 self.segments = segments
58 let ts = Array(Set(grid + bounds)).sorted()
59 self.ts = ts
60 segments = zip(bounds, bounds.dropFirst()).map { ts.firstIndex(of: $0)!...ts.firstIndex(of: $1)! }
5461
55 points = ts.map(centroid.point(at:))
56 path = grid.map(centroid.point(at:))
57 isDegenerate = zip(path, path.dropFirst()).reduce(0) { $0 + distance($1.0, $1.1) } < Self.minimumLength
62 let projection = Projection(camera: camera, viewportSize: viewportSize)
63 let interpolator = FoldInterpolator(file: file, step: step)
64 let centroids = Centroids(file: file, sets: followed.map(\.faces))
65 let screen = ts.map { t in centroids.points(interpolator.positions(at: t)).map(projection.point) }
66
67 var points = ts.map { _ in SIMD2<Double>.zero }
68 var previous: Int?
69 var fallbacks = 0
70 for segment in segments {
71 func travel(_ c: Int) -> Double {
72 segment.dropLast().reduce(0) { $0 + distance(screen[$1][c], screen[$1 + 1][c]) }
73 }
74 let (a, b) = (ts[segment.lowerBound], ts[segment.upperBound])
75 let covering = followed.indices.filter { followed[$0].window.lowerBound <= a && b <= followed[$0].window.upperBound }
76 var choice: Int?
77 for c in (previous.map { [$0] } ?? []) + covering where covering.contains(c) && travel(c) >= Self.minimumLength {
78 if choice.map({ travel(c) > travel($0) + Self.preference }) ?? true { choice = c }
79 }
80 let start = segment.lowerBound == 0 ? screen[0][choice ?? 0] : points[segment.lowerBound]
81 for i in segment {
82 points[i] = choice.map { start + screen[i][$0] - screen[segment.lowerBound][$0] }
83 ?? start + SIMD2(0, (ts[i] - a) * Self.fallbackThrow)
84 }
85 if choice == nil { fallbacks += 1 }
86 previous = choice ?? previous
87 }
88 self.points = points
89 isDegenerate = fallbacks == segments.count
90 path = grid.map { t in points[ts.firstIndex(of: t)!] }
5891 }
5992
60 /// The followed faces' centroid at `t`, in screen points.
61 public func point(at t: Double) -> SIMD2<Double> { centroid.point(at: t) }
93 /// The point of `path` at `t`.
94 public func point(at t: Double) -> SIMD2<Double> {
95 let t = min(max(t, 0), 1)
96 let i = min(ts.lastIndex { $0 <= t }!, ts.count - 2)
97 let u = (t - ts[i]) / (ts[i + 1] - ts[i])
98 return points[i] + u * (points[i + 1] - points[i])
99 }
62100
63 /// The parameter, in 0...1, whose centroid is nearest `grabbedAt + translation`, where
64 /// `grabbedAt` is the centroid's screen point when the drag began. The search walks the path
65 /// outward from `current`, within the segment `current` is in: a fold-and-unfold's return half
66 /// once `current` reaches 0.5, a non-rigid step's next phase once `current` reaches the end of
67 /// the one before. Segments are one way: once `current` reaches a segment's end, the segments
68 /// before it are not searched again. A point within half a point of its segment's end, measured
69 /// along the path, is the end, so a segment whose path turns back at its end can be finished.
101 /// The parameter, in 0...1, whose point of `path` is nearest `grabbedAt + translation`, where
102 /// `grabbedAt` is `point(at:)` of t when the drag began. The search walks the path outward from
103 /// `current`, within the segment `current` is in, the later one at a boundary. Segments are one
104 /// way: once `current` reaches a segment's end, the segments before it are not searched again.
105 /// A point within half a point of its segment's end, measured along the path, is the end, so a
106 /// segment whose path turns back at its end can be finished.
70107 ///
71108 /// When the path is degenerate the drag's downward component advances the fold over 160
72109 /// points from `current`, which is then the parameter when the drag began.
@@ -106,40 +143,51 @@ public struct FoldParameterMapping: Sendable {
106143 }
107144}
108145
109/// The area centroid of the followed faces, projected to screen points.
110private struct Centroid: Sendable {
111 let interpolator: FoldInterpolator
112 /// Fan triangles of the faces, with their areas in frame 0.
113 let triangles: [(SIMD3<Int>, Double)]
146/// The area centroids of sets of faces.
147private struct Centroids {
148 /// Per set, fan triangles of its faces with their areas in frame 0.
149 let triangles: [[(SIMD3<Int>, Double)]]
150
151 init(file: FoldFile, sets: [[Int]]) {
152 let flat = file.frames[0].verticesCoords
153 triangles = sets.map { faces in
154 faces.flatMap { f in
155 let face = file.facesVertices[f]
156 return (1..<face.count - 1).map { i in
157 (SIMD3(face[0], face[i], face[i + 1]),
158 length(cross(flat[face[i]] - flat[face[0]], flat[face[i + 1]] - flat[face[0]])) / 2)
159 }
160 }
161 }
162 }
163
164 func points(_ positions: [SIMD3<Double>]) -> [SIMD3<Double>] {
165 triangles.map { set in
166 var sum = SIMD3<Double>.zero, area = 0.0
167 for (v, a) in set {
168 sum += a * (positions[v.x] + positions[v.y] + positions[v.z]) / 3
169 area += a
170 }
171 return sum / area
172 }
173 }
174}
175
176/// Projects to screen points at the depth of the camera's target.
177private struct Projection {
114178 let viewProjection: simd_double4x4
115179 /// Clip-space w of the camera's target.
116180 let depth: Double
117181 let viewportSize: SIMD2<Double>
118182
119 init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) {
120 interpolator = FoldInterpolator(file: file, step: step)
121 let faces = step.axes.first.map { Array($0.movingFaces) } ?? Array(file.facesVertices.indices)
122 let flat = file.frames[0].verticesCoords
123 triangles = faces.flatMap { f in
124 let face = file.facesVertices[f]
125 return (1..<face.count - 1).map { i in
126 (SIMD3(face[0], face[i], face[i + 1]),
127 length(cross(flat[face[i]] - flat[face[0]], flat[face[i + 1]] - flat[face[0]])) / 2)
128 }
129 }
183 init(camera: Camera, viewportSize: SIMD2<Double>) {
130184 viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y)
131185 depth = (viewProjection * SIMD4(camera.target, 1)).w
132186 self.viewportSize = viewportSize
133187 }
134188
135 func point(at t: Double) -> SIMD2<Double> {
136 let positions = interpolator.positions(at: t)
137 var sum = SIMD3<Double>.zero, area = 0.0
138 for (v, a) in triangles {
139 sum += a * (positions[v.x] + positions[v.y] + positions[v.z]) / 3
140 area += a
141 }
142 let clip = viewProjection * SIMD4(sum / area, 1)
189 func point(_ p: SIMD3<Double>) -> SIMD2<Double> {
190 let clip = viewProjection * SIMD4(p, 1)
143191 return SIMD2((clip.x / depth + 1) / 2 * viewportSize.x, (1 - clip.y / depth) / 2 * viewportSize.y)
144192 }
145193}
Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift +52
@@ -74,3 +74,55 @@ import Testing
7474 #expect(abs(t - Double(k) / 128) < 0.01, "sample \(k)")
7575 }
7676}
77
78@Test func aStaggeredStepIsFollowedAcrossItsWindows() throws {
79 // two axes on windows 0...0.5 and 0.5...1; following the path's samples reaches each in turn.
80 // 0.02 allows the last sample before a slow window end, within the end tolerance, to count as it
81 let m = try mapping("letter-staggered.fold", step: 1)
82 var t = 0.0
83 for (k, p) in m.path.enumerated().dropFirst() {
84 t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
85 #expect(abs(t - Double(k) / 128) < 0.02, "sample \(k)")
86 }
87}
88
89@Test func aLateWindowIsReachedByTheVerticalDragAndThenFollowed() throws {
90 // nothing moves before 0.5, so that half of the path is the vertical fallback
91 let file = try FoldFile(contentsOf: fixture("half.fold"))
92 let full = try readStep(1, in: file)
93 let a = full.axes[0]
94 let step = FoldStep(index: 1, kind: .fold, instruction: full.instruction,
95 axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction,
96 movingFaces: a.movingFaces, startAngle: 0, endAngle: 180, window: 0.5...1)],
97 viewpoint: full.viewpoint)
98 let m = FoldParameterMapping(file: file, step: step,
99 camera: Camera(eye: SIMD3(1, 1, 4), target: SIMD3(1, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
100 viewportSize: SIMD2(800, 600))
101 #expect(!m.isDegenerate)
102 let early = m.parameter(grabbedAt: m.path[0], translation: SIMD2(0, 40), current: 0)
103 #expect(abs(early - 0.25) < 0.01)
104 var t = 0.0
105 for (k, p) in m.path.enumerated().dropFirst() {
106 t = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t)
107 #expect(abs(t - Double(k) / 128) < 0.02, "sample \(k)")
108 }
109}
110
111@Test func aFoldAndUnfoldPeaksAtTheMiddleOfItsWindow() throws {
112 let file = try FoldFile(contentsOf: fixture("quarters.fold"))
113 let full = try readStep(1, in: file)
114 let a = full.axes[0]
115 let step = FoldStep(index: 1, kind: .foldAndUnfold, instruction: full.instruction,
116 axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction, movingFaces: a.movingFaces,
117 startAngle: a.startAngle, endAngle: a.endAngle, peakAngle: a.peakAngle,
118 window: 0...0.6)],
119 viewpoint: full.viewpoint)
120 let m = FoldParameterMapping(file: file, step: step,
121 camera: Camera(eye: SIMD3(1, 1, 4), target: SIMD3(1, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4),
122 viewportSize: SIMD2(800, 600))
123 let peak = m.point(at: 0.3)
124 let atPeak = m.parameter(grabbedAt: m.path[0], translation: peak - m.path[0], current: 0)
125 #expect(abs(atPeak - 0.3) < 0.01)
126 let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak)
127 #expect(abs(back - 0.6) < 0.01)
128}