Packages/FoldKit/Sources/Folding/FoldInterpolator.swift

main
fold/Packages/FoldKit/Sources/Folding/FoldInterpolator.swift history · blame · raw

281 lines · 12616 bytes

13 symbols in this file
  1import FoldFormat
  2import simd
  3
  4/// Interpolates step `step.index` from frame `step.index − 1` to frame `step.index`.
  5///
  6/// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an
  7/// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates
  8/// the whole of the start frame about its bounding-box centre. A step flagged `nonRigid` moves by
  9/// its pop (decision 0002): `openAxes` rigidly on `[0, phases.lowerBound]`, the render mesh bent
 10/// from the open pose to `popped` on the phases, and `closeAxes` rigidly from `popped` on
 11/// `[phases.upperBound, 1]`.
 12public struct FoldInterpolator: Sendable {
 13    /// Rigid motions of the faces about a step's axes, from `start`.
 14    private struct Motion: Sendable {
 15        let axes: [FoldAxis]
 16        let kind: StepKind
 17        let start: [SIMD3<Double>]
 18        /// Per axis, the vertices that take their position from that axis's face group.
 19        let vertices: [[Int]]
 20
 21        init(axes: [FoldAxis], kind: StepKind, start: [SIMD3<Double>], faces: [[Int]]) {
 22            self.axes = axes
 23            self.kind = kind
 24            self.start = start
 25            var axisOfFace: [Int: Int] = [:]
 26            for (a, axis) in axes.enumerated() {
 27                for f in axis.movingFaces { axisOfFace[f] = a }
 28            }
 29            // a vertex takes its position from the first face containing it
 30            var owner = Array<Int?>(repeating: nil, count: start.count)
 31            var seen = Array(repeating: false, count: start.count)
 32            for (f, face) in faces.enumerated() {
 33                for v in face where !seen[v] {
 34                    seen[v] = true
 35                    owner[v] = axisOfFace[f]
 36                }
 37            }
 38            var groups = Array(repeating: [Int](), count: axes.count)
 39            for (v, a) in owner.enumerated() {
 40                if let a { groups[a].append(v) }
 41            }
 42            vertices = groups
 43        }
 44
 45        func positions(at t: Double) -> [SIMD3<Double>] {
 46            // each axis's full transform: its own rotation, then its parent's
 47            var full: [Transform] = []
 48            full.reserveCapacity(axes.count)
 49            for axis in axes {
 50                let degrees = axis.angle(at: t, kind: kind) - axis.startAngle
 51                let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction)
 52                let own = Transform(rotation: simd_double3x3(q), about: axis.origin)
 53                full.append(axis.parent.map { full[$0].after(own) } ?? own)
 54            }
 55            var result = start
 56            for (a, group) in vertices.enumerated() {
 57                for v in group { result[v] = full[a].apply(start[v]) }
 58            }
 59            return result
 60        }
 61    }
 62
 63    private struct Reorientation: Sendable {
 64        let start: [SIMD3<Double>]
 65        let centre: SIMD3<Double>
 66        let axis: SIMD3<Double>
 67        /// Radians at t = 1.
 68        let angle: Double
 69    }
 70
 71    private struct NonRigid: Sendable {
 72        let open: Motion
 73        let close: Motion
 74        let phases: ClosedRange<Double>
 75        let bending: Bending
 76    }
 77
 78    private enum Mode: Sendable {
 79        case folds(Motion)
 80        case reorient(Reorientation)
 81        case nonRigid(NonRigid)
 82    }
 83
 84    /// The render mesh of the file's frame 0, at `RenderMesh.spacing(for:)`.
 85    public let mesh: RenderMesh
 86    /// The file's faces.
 87    let faces: [[Int]]
 88    private let mode: Mode
 89
 90    /// The pop's phases, for a non-rigid step.
 91    var popPhases: ClosedRange<Double>? {
 92        if case .nonRigid(let p) = mode { return p.phases }
 93        return nil
 94    }
 95
 96    public init(file: FoldFile, step: FoldStep) {
 97        let start = file.frames[step.index - 1].verticesCoords
 98        mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
 99        faces = file.facesVertices
100
101        if step.nonRigid {
102            guard let pop = step.pop else { preconditionFailure("a non-rigid step has a pop; readStep checks it") }
103            let open = Motion(axes: pop.openAxes, kind: .fold, start: start, faces: file.facesVertices)
104            let close = Motion(axes: pop.closeAxes, kind: .fold, start: pop.popped, faces: file.facesVertices)
105            let moving = step.movingFaceUnion
106            let opened = open.positions(at: pop.phases.lowerBound)
107            let bending = Bending(mesh: mesh, faces: file.facesVertices, from: opened, to: pop.popped,
108                                  heldFaces: Set(file.facesVertices.indices.filter { !moving.contains($0) }),
109                                  blends: band(mesh: mesh, file: file, tip: moving, spine: pop.spine, start: start),
110                                  ties: spineTies(mesh: mesh, file: file, tip: moving, spine: pop.spine, start: start,
111                                                  poses: [opened, pop.popped]))
112            mode = .nonRigid(NonRigid(open: open, close: close, phases: pop.phases, bending: bending))
113            return
114        }
115
116        switch step.kind {
117        case .fold, .foldAndUnfold:
118            mode = .folds(Motion(axes: step.axes, kind: step.kind, start: start, faces: file.facesVertices))
119
120        case .turnOver, .rotate:
121            var lower = start[0], upper = start[0]
122            for p in start {
123                lower = simd_min(lower, p)
124                upper = simd_max(upper, p)
125            }
126            let eye = normalize(step.viewpoint.eye), up = normalize(step.viewpoint.up)
127            let axis: SIMD3<Double>, degrees: Double
128            if step.kind == .rotate {
129                axis = eye
130                degrees = step.rotateDegrees ?? 0
131            } else {
132                axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up
133                degrees = 180
134            }
135            mode = .reorient(Reorientation(start: start, centre: (lower + upper) / 2, axis: axis,
136                                           angle: degrees * .pi / 180))
137        }
138    }
139
140    /// The vertex positions at `t` of the step, `t` in 0...1. During a pop, the mesh positions of
141    /// the FOLD vertices.
142    public func positions(at t: Double) -> [SIMD3<Double>] {
143        switch mode {
144        case .reorient(let r):
145            let q = simd_quatd(angle: r.angle * t, axis: r.axis)
146            return r.start.map { r.centre + q.act($0 - r.centre) }
147
148        case .folds(let motion):
149            return motion.positions(at: t)
150
151        case .nonRigid(let p):
152            if t <= p.phases.lowerBound { return p.open.positions(at: t) }
153            if t >= p.phases.upperBound { return p.close.positions(at: t) }
154            let points = meshPositions(at: t)
155            return mesh.meshVertexOf.map { points[$0] }
156        }
157    }
158
159    /// The render mesh's vertex positions at `t` of the step: each face's rigid placement applied
160    /// to its mesh vertices, or during a pop the bent mesh.
161    public func meshPositions(at t: Double) -> [SIMD3<Double>] {
162        if case .nonRigid(let p) = mode, t > p.phases.lowerBound, t < p.phases.upperBound {
163            let s = (t - p.phases.lowerBound) / (p.phases.upperBound - p.phases.lowerBound)
164            return p.bending.positions(at: s)
165        }
166        return mesh.pose(positions(at: t))
167    }
168}
169
170/// Decision 0003's band: the tip's triangles within the tip's width of its spine, each blended
171/// toward the layer across the spine. The tip is `tip`; its spine is the edges of `spine` with both
172/// faces in it. A tip face's partner is the face across the spine from the faces it joins without
173/// crossing the spine. A triangle at distance d from the spine's line in `start` (frame n − 1),
174/// its centroid's, has weight d / b, b being the largest such distance of a tip triangle; one
175/// with weight 1 or more is not blended.
176///
177/// Limitations: each tip layer takes one partner face, the first met across the spine, so a
178/// layer facing several faces across it blends toward only one of them; and the spine's line is
179/// the first tip-spine edge's, so a tip spine that is not straight is measured from that edge.
180private func band(mesh: RenderMesh, file: FoldFile, tip: Set<Int>, spine: [Int],
181                  start: [SIMD3<Double>]) -> [Bending.Blend] {
182    let edgeFaces = edgesFaces(file)
183    let tipSpine = spine.filter { edgeFaces[$0].count == 2 && edgeFaces[$0].allSatisfy(tip.contains) }
184    guard let first = tipSpine.first else { return [] }
185
186    // the tip's layers: its faces joined across edges off the spine
187    var layer: [Int: Int] = [:]
188    for seed in tip.sorted() where layer[seed] == nil {
189        layer[seed] = seed
190        var stack = [seed]
191        while let f = stack.popLast() {
192            for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !tipSpine.contains(e) {
193                let g = faces[0] == f ? faces[1] : faces[0]
194                if tip.contains(g) && layer[g] == nil {
195                    layer[g] = seed
196                    stack.append(g)
197                }
198            }
199        }
200    }
201    var partnerOfLayer: [Int: Int] = [:]
202    for e in tipSpine {
203        let (f, g) = (edgeFaces[e][0], edgeFaces[e][1])
204        if partnerOfLayer[layer[f]!] == nil { partnerOfLayer[layer[f]!] = g }
205        if partnerOfLayer[layer[g]!] == nil { partnerOfLayer[layer[g]!] = f }
206    }
207
208    let ends = file.edgesVertices[first].map { start[$0] }
209    let direction = normalize(ends[1] - ends[0])
210    let points = mesh.pose(start)
211    let distances = mesh.triangles.map { a, b, c in
212        let offset = (points[a] + points[b] + points[c]) / 3 - ends[0]
213        return length(offset - dot(offset, direction) * direction)
214    }
215    let banded = mesh.triangles.indices.filter { tip.contains(mesh.faceOf[$0]) && partnerOfLayer[layer[mesh.faceOf[$0]]!] != nil }
216    guard let width = banded.map({ distances[$0] }).max(), width > 0 else { return [] }
217    return banded.compactMap { t in
218        let weight = distances[t] / width
219        return weight < 1 ? Bending.Blend(triangle: t, partner: partnerOfLayer[layer[mesh.faceOf[t]]!]!, weight: weight) : nil
220    }
221}
222
223/// Decision 0003's ruling R78: the tip's mesh vertices on its spine's line in `start` (frame
224/// n − 1), grouped where they coincide in `start` and in every pose of `poses`, so that the
225/// halves' coincident fold edges on that line move together during the pop. As for the band, the
226/// line is the first tip-spine edge's.
227private func spineTies(mesh: RenderMesh, file: FoldFile, tip: Set<Int>, spine: [Int], start: [SIMD3<Double>],
228                       poses: [[SIMD3<Double>]]) -> [[Int]] {
229    let edgeFaces = edgesFaces(file)
230    guard let first = spine.first(where: { edgeFaces[$0].count == 2 && edgeFaces[$0].allSatisfy(tip.contains) })
231    else { return [] }
232    let points = mesh.pose(start)
233    let lower = points.dropFirst().reduce(points[0], simd_min), upper = points.dropFirst().reduce(points[0], simd_max)
234    let tolerance = length(upper - lower) * 1e-9
235    let ends = file.edgesVertices[first].map { start[$0] }
236    let direction = normalize(ends[1] - ends[0])
237    var inTip = Array(repeating: false, count: points.count)
238    for (t, (a, b, c)) in mesh.triangles.enumerated() where tip.contains(mesh.faceOf[t]) {
239        (inTip[a], inTip[b], inTip[c]) = (true, true, true)
240    }
241    let onLine = points.indices.filter { v in
242        let offset = points[v] - ends[0]
243        return inTip[v] && length(offset - dot(offset, direction) * direction) <= tolerance
244    }
245    let placed = poses.map(mesh.pose)
246    var groups: [[Int]] = []
247    for v in onLine {
248        if let g = groups.firstIndex(where: { group in
249            ([points] + placed).allSatisfy { simd_distance($0[group[0]], $0[v]) <= tolerance }
250        }) {
251            groups[g].append(v)
252        } else {
253            groups.append([v])
254        }
255    }
256    return groups.filter { $0.count > 1 }
257}
258
259/// p ↦ linear · p + offset
260private struct Transform {
261    var linear: simd_double3x3
262    var offset: SIMD3<Double>
263
264    /// The rotation `linear` about the point `centre`.
265    init(rotation linear: simd_double3x3, about centre: SIMD3<Double>) {
266        self.linear = linear
267        offset = centre - linear * centre
268    }
269
270    private init(linear: simd_double3x3, offset: SIMD3<Double>) {
271        self.linear = linear
272        self.offset = offset
273    }
274
275    func apply(_ p: SIMD3<Double>) -> SIMD3<Double> { linear * p + offset }
276
277    /// This transform applied after `inner`.
278    func after(_ inner: Transform) -> Transform {
279        Transform(linear: linear * inner.linear, offset: linear * inner.offset + offset)
280    }
281}