import FoldFormat import simd /// Interpolates step `step.index` from frame `step.index − 1` to frame `step.index`. /// /// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an /// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates /// the whole of the start frame about its bounding-box centre. A step flagged `nonRigid` moves by /// its pop (decision 0002): `openAxes` rigidly on `[0, phases.lowerBound]`, the render mesh bent /// from the open pose to `popped` on the phases, and `closeAxes` rigidly from `popped` on /// `[phases.upperBound, 1]`. public struct FoldInterpolator: Sendable { /// Rigid motions of the faces about a step's axes, from `start`. private struct Motion: Sendable { let axes: [FoldAxis] let kind: StepKind let start: [SIMD3] /// Per axis, the vertices that take their position from that axis's face group. let vertices: [[Int]] init(axes: [FoldAxis], kind: StepKind, start: [SIMD3], faces: [[Int]]) { self.axes = axes self.kind = kind self.start = start var axisOfFace: [Int: Int] = [:] for (a, axis) in axes.enumerated() { for f in axis.movingFaces { axisOfFace[f] = a } } // a vertex takes its position from the first face containing it var owner = Array(repeating: nil, count: start.count) var seen = Array(repeating: false, count: start.count) for (f, face) in faces.enumerated() { for v in face where !seen[v] { seen[v] = true owner[v] = axisOfFace[f] } } var groups = Array(repeating: [Int](), count: axes.count) for (v, a) in owner.enumerated() { if let a { groups[a].append(v) } } vertices = groups } func positions(at t: Double) -> [SIMD3] { // each axis's full transform: its own rotation, then its parent's var full: [Transform] = [] full.reserveCapacity(axes.count) for axis in axes { let degrees = axis.angle(at: t, kind: kind) - axis.startAngle let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction) let own = Transform(rotation: simd_double3x3(q), about: axis.origin) full.append(axis.parent.map { full[$0].after(own) } ?? own) } var result = start for (a, group) in vertices.enumerated() { for v in group { result[v] = full[a].apply(start[v]) } } return result } } private struct Reorientation: Sendable { let start: [SIMD3] let centre: SIMD3 let axis: SIMD3 /// Radians at t = 1. let angle: Double } private struct NonRigid: Sendable { let open: Motion let close: Motion let phases: ClosedRange let bending: Bending } private enum Mode: Sendable { case folds(Motion) case reorient(Reorientation) case nonRigid(NonRigid) } /// The render mesh of the file's frame 0, at `RenderMesh.spacing(for:)`. public let mesh: RenderMesh /// The file's faces. let faces: [[Int]] private let mode: Mode /// The pop's phases, for a non-rigid step. var popPhases: ClosedRange? { if case .nonRigid(let p) = mode { return p.phases } return nil } public init(file: FoldFile, step: FoldStep) { let start = file.frames[step.index - 1].verticesCoords mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file)) faces = file.facesVertices if step.nonRigid { guard let pop = step.pop else { preconditionFailure("a non-rigid step has a pop; readStep checks it") } let open = Motion(axes: pop.openAxes, kind: .fold, start: start, faces: file.facesVertices) let close = Motion(axes: pop.closeAxes, kind: .fold, start: pop.popped, faces: file.facesVertices) let moving = step.movingFaceUnion let opened = open.positions(at: pop.phases.lowerBound) let bending = Bending(mesh: mesh, faces: file.facesVertices, from: opened, to: pop.popped, heldFaces: Set(file.facesVertices.indices.filter { !moving.contains($0) }), blends: band(mesh: mesh, file: file, tip: moving, spine: pop.spine, start: start), ties: spineTies(mesh: mesh, file: file, tip: moving, spine: pop.spine, start: start, poses: [opened, pop.popped])) mode = .nonRigid(NonRigid(open: open, close: close, phases: pop.phases, bending: bending)) return } switch step.kind { case .fold, .foldAndUnfold: mode = .folds(Motion(axes: step.axes, kind: step.kind, start: start, faces: file.facesVertices)) case .turnOver, .rotate: var lower = start[0], upper = start[0] for p in start { lower = simd_min(lower, p) upper = simd_max(upper, p) } let eye = normalize(step.viewpoint.eye), up = normalize(step.viewpoint.up) let axis: SIMD3, degrees: Double if step.kind == .rotate { axis = eye degrees = step.rotateDegrees ?? 0 } else { axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up degrees = 180 } mode = .reorient(Reorientation(start: start, centre: (lower + upper) / 2, axis: axis, angle: degrees * .pi / 180)) } } /// The vertex positions at `t` of the step, `t` in 0...1. During a pop, the mesh positions of /// the FOLD vertices. public func positions(at t: Double) -> [SIMD3] { switch mode { case .reorient(let r): let q = simd_quatd(angle: r.angle * t, axis: r.axis) return r.start.map { r.centre + q.act($0 - r.centre) } case .folds(let motion): return motion.positions(at: t) case .nonRigid(let p): if t <= p.phases.lowerBound { return p.open.positions(at: t) } if t >= p.phases.upperBound { return p.close.positions(at: t) } let points = meshPositions(at: t) return mesh.meshVertexOf.map { points[$0] } } } /// The render mesh's vertex positions at `t` of the step: each face's rigid placement applied /// to its mesh vertices, or during a pop the bent mesh. public func meshPositions(at t: Double) -> [SIMD3] { if case .nonRigid(let p) = mode, t > p.phases.lowerBound, t < p.phases.upperBound { let s = (t - p.phases.lowerBound) / (p.phases.upperBound - p.phases.lowerBound) return p.bending.positions(at: s) } return mesh.pose(positions(at: t)) } } /// Decision 0003's band: the tip's triangles within the tip's width of its spine, each blended /// toward the layer across the spine. The tip is `tip`; its spine is the edges of `spine` with both /// faces in it. A tip face's partner is the face across the spine from the faces it joins without /// crossing the spine. A triangle at distance d from the spine's line in `start` (frame n − 1), /// its centroid's, has weight d / b, b being the largest such distance of a tip triangle; one /// with weight 1 or more is not blended. /// /// Limitations: each tip layer takes one partner face, the first met across the spine, so a /// layer facing several faces across it blends toward only one of them; and the spine's line is /// the first tip-spine edge's, so a tip spine that is not straight is measured from that edge. private func band(mesh: RenderMesh, file: FoldFile, tip: Set, spine: [Int], start: [SIMD3]) -> [Bending.Blend] { let edgeFaces = edgesFaces(file) let tipSpine = spine.filter { edgeFaces[$0].count == 2 && edgeFaces[$0].allSatisfy(tip.contains) } guard let first = tipSpine.first else { return [] } // the tip's layers: its faces joined across edges off the spine var layer: [Int: Int] = [:] for seed in tip.sorted() where layer[seed] == nil { layer[seed] = seed var stack = [seed] while let f = stack.popLast() { for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !tipSpine.contains(e) { let g = faces[0] == f ? faces[1] : faces[0] if tip.contains(g) && layer[g] == nil { layer[g] = seed stack.append(g) } } } } var partnerOfLayer: [Int: Int] = [:] for e in tipSpine { let (f, g) = (edgeFaces[e][0], edgeFaces[e][1]) if partnerOfLayer[layer[f]!] == nil { partnerOfLayer[layer[f]!] = g } if partnerOfLayer[layer[g]!] == nil { partnerOfLayer[layer[g]!] = f } } let ends = file.edgesVertices[first].map { start[$0] } let direction = normalize(ends[1] - ends[0]) let points = mesh.pose(start) let distances = mesh.triangles.map { a, b, c in let offset = (points[a] + points[b] + points[c]) / 3 - ends[0] return length(offset - dot(offset, direction) * direction) } let banded = mesh.triangles.indices.filter { tip.contains(mesh.faceOf[$0]) && partnerOfLayer[layer[mesh.faceOf[$0]]!] != nil } guard let width = banded.map({ distances[$0] }).max(), width > 0 else { return [] } return banded.compactMap { t in let weight = distances[t] / width return weight < 1 ? Bending.Blend(triangle: t, partner: partnerOfLayer[layer[mesh.faceOf[t]]!]!, weight: weight) : nil } } /// Decision 0003's ruling R78: the tip's mesh vertices on its spine's line in `start` (frame /// n − 1), grouped where they coincide in `start` and in every pose of `poses`, so that the /// halves' coincident fold edges on that line move together during the pop. As for the band, the /// line is the first tip-spine edge's. private func spineTies(mesh: RenderMesh, file: FoldFile, tip: Set, spine: [Int], start: [SIMD3], poses: [[SIMD3]]) -> [[Int]] { let edgeFaces = edgesFaces(file) guard let first = spine.first(where: { edgeFaces[$0].count == 2 && edgeFaces[$0].allSatisfy(tip.contains) }) else { return [] } let points = mesh.pose(start) let lower = points.dropFirst().reduce(points[0], simd_min), upper = points.dropFirst().reduce(points[0], simd_max) let tolerance = length(upper - lower) * 1e-9 let ends = file.edgesVertices[first].map { start[$0] } let direction = normalize(ends[1] - ends[0]) var inTip = Array(repeating: false, count: points.count) for (t, (a, b, c)) in mesh.triangles.enumerated() where tip.contains(mesh.faceOf[t]) { (inTip[a], inTip[b], inTip[c]) = (true, true, true) } let onLine = points.indices.filter { v in let offset = points[v] - ends[0] return inTip[v] && length(offset - dot(offset, direction) * direction) <= tolerance } let placed = poses.map(mesh.pose) var groups: [[Int]] = [] for v in onLine { if let g = groups.firstIndex(where: { group in ([points] + placed).allSatisfy { simd_distance($0[group[0]], $0[v]) <= tolerance } }) { groups[g].append(v) } else { groups.append([v]) } } return groups.filter { $0.count > 1 } } /// p ↦ linear · p + offset private struct Transform { var linear: simd_double3x3 var offset: SIMD3 /// The rotation `linear` about the point `centre`. init(rotation linear: simd_double3x3, about centre: SIMD3) { self.linear = linear offset = centre - linear * centre } private init(linear: simd_double3x3, offset: SIMD3) { self.linear = linear self.offset = offset } func apply(_ p: SIMD3) -> SIMD3 { linear * p + offset } /// This transform applied after `inner`. func after(_ inner: Transform) -> Transform { Transform(linear: linear * inner.linear, offset: linear * inner.offset + offset) } }