Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift

151 lines · 7802 bytes

6 symbols in this file
  1import FoldFormat
  2import Folding
  3import simd
  4
  5/// Two unit normals whose dot product's magnitude reaches this lie on one line.
  6private let parallelCosine = 1 - 1e-9
  7/// How far before a pair's arrival the guess looks, as a fraction of the arriving axis's window.
  8private let arrivalLead = 1e-3
  9/// Two layers closer than this fraction of the sheet's size at that moment are not told apart.
 10private let separationTolerance = 1e-9
 11
 12/// Guesses `next`'s `faceOrders`, every overlapping pair once as `[f, g, s]` with `f < g`.
 13///
 14/// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face
 15/// that arrives last is placed on the side it arrives from: the pair is compared just before the
 16/// last axis that moves them differently finishes, the higher-indexed of axes that finish
 17/// together, at the paper points that meet in the middle of their overlap. A moving set that has
 18/// turned over arrives with its layers reversed. This is right for plain valley and mountain
 19/// folds and wrong for a flap tucked between layers, which the script corrects with overrides.
 20///
 21/// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame.
 22public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] {
 23    var end = next
 24    end.step = step
 25    let draft = FoldFile(fileSpec: file.fileSpec, edgesVertices: file.edgesVertices,
 26                         facesVertices: file.facesVertices,
 27                         edgesFirstCreasedAtStep: file.edgesFirstCreasedAtStep,
 28                         frames: [file.frames[0], previous, end])
 29    guard let folding = try? readStep(2, in: draft) else {
 30        preconditionFailure("guessFaceOrders needs a step that readStep accepts")
 31    }
 32    return guessOrders(previous: previous, step: folding, interpolator: FoldInterpolator(file: draft, step: folding),
 33                       positions: next.verticesCoords, file: file, arrival: { $0.upperBound })
 34}
 35
 36/// The guess for the faces at `positions`, a state of `step`; `arrival` gives the time within an
 37/// axis's window at which its faces reach that state.
 38func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpolator, positions: [SIMD3<Double>],
 39                 file: FoldFile, arrival: (ClosedRange<Double>) -> Double) -> [[Int]] {
 40    let faces = file.facesVertices
 41    let size = sheetExtent(file)
 42    let normals = faceNormals(positions: positions, faces: faces)
 43
 44    var before: [SIMD2<Int>: Int] = [:]
 45    for (pair, s) in rigidInvariantFaceOrders(previous.faceOrders, normals: faceNormals(previous, file))
 46    where before[pair] == nil {
 47        before[pair] = s
 48    }
 49    var axisOfFace: [Int: Int] = [:]
 50    for (a, axis) in step.axes.enumerated() {
 51        for f in axis.movingFaces { axisOfFace[f] = a }
 52    }
 53    func carriers(_ f: Int) -> Set<Int> {
 54        var result = Set<Int>(), a = axisOfFace[f]
 55        while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent }
 56        return result
 57    }
 58
 59    var sampled: [Double: [SIMD3<Double>]] = [:]
 60    var orders: [[Int]] = []
 61    for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) {
 62        let differing = carriers(a).symmetricDifference(carriers(b))
 63        let last = differing.max { (arrival(step.axes[$0].window), $0) < (arrival(step.axes[$1].window), $1) }
 64        guard let last else {
 65            if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) }
 66            continue
 67        }
 68        let window = step.axes[last].window
 69        let t = arrival(window) - arrivalLead * (window.upperBound - window.lowerBound)
 70        let near = sampled[t] ?? interpolator.positions(at: t)
 71        sampled[t] = near
 72        let meeting = overlapCentre(a, b, inPlaneOf: a, positions, faces, normals)
 73        let separation = dot(carry(meeting, on: faces[a], from: positions, to: near)
 74            - carry(meeting, on: faces[b], from: positions, to: near), normals[b])
 75        if abs(separation) > size * separationTolerance {
 76            orders.append([a, b, separation > 0 ? 1 : -1])
 77        } else if let s = before[SIMD2(a, b)] {
 78            orders.append([a, b, s])
 79        }
 80    }
 81    return orders
 82}
 83
 84/// Replaces the order of each overridden pair, adding it when absent. Each override names its
 85/// faces by points in the crease pattern and puts `above` nearer the eye than `below`; the result
 86/// keeps every pair once as `[f, g, s]` with `f < g`, sorted.
 87///
 88/// - Throws: `CompileError.unresolvedFace` with step 0 when a point lies on no face; `compile`
 89///   reports the step.
 90public func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame,
 91                                viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]] {
 92    guard !overrides.isEmpty else { return orders }
 93    let normals = faceNormals(frame, file)
 94    var result = orders
 95    for o in overrides {
 96        guard let above = face(containing: o.above, file) else {
 97            throw CompileError.unresolvedFace(step: 0, point: o.above)
 98        }
 99        guard let below = face(containing: o.below, file) else {
100            throw CompileError.unresolvedFace(step: 0, point: o.below)
101        }
102        let s = dot(normals[below], viewpoint.eye) > 0 ? 1 : -1
103        let triple = above < below
104            ? [above, below, s]
105            : [below, above, dot(normals[above], normals[below]) > 0 ? -s : s]
106        result.removeAll { Set($0.prefix(2)) == Set([above, below]) }
107        result.append(triple)
108    }
109    return result.sorted { ($0[0], $0[1]) < ($1[0], $1[1]) }
110}
111
112/// Pairs `(a, b)`, `a < b`, of faces in one plane whose interiors overlap.
113private func overlappingPairs(_ positions: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>],
114                              tolerance: Double) -> [(Int, Int)] {
115    var pairs: [(Int, Int)] = []
116    for a in faces.indices where normals[a] != .zero {
117        let corner = positions[faces[a][0]]
118        let (u, v) = planeBasis(normals[a])
119        let project = { (f: Int) in faces[f].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
120        let outline = project(a)
121        for b in faces.indices.dropFirst(a + 1) where normals[b] != .zero
122            && abs(dot(normals[a], normals[b])) >= parallelCosine
123            && faces[b].allSatisfy({ abs(dot(positions[$0] - corner, normals[a])) <= tolerance })
124            && convexPolygonsOverlap(outline, project(b), tolerance: tolerance) {
125            pairs.append((a, b))
126        }
127    }
128    return pairs
129}
130
131/// `point`, a point of the face with corners `corners` at `from`, where the same point of paper
132/// is at `to`. Both states must place the face rigidly.
133private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>], to: [SIMD3<Double>]) -> SIMD3<Double> {
134    // the corner triangle with the largest area gives the best-conditioned weights
135    var best = (0, 1, 2), largest = -1.0
136    for i in corners.indices {
137        for j in corners.indices where j > i {
138            for k in corners.indices where k > j {
139                let area = length(cross(from[corners[j]] - from[corners[i]], from[corners[k]] - from[corners[i]]))
140                if area > largest { (best, largest) = ((i, j, k), area) }
141            }
142        }
143    }
144    let (p, q, r) = (corners[best.0], corners[best.1], corners[best.2])
145    let e1 = from[q] - from[p], e2 = from[r] - from[p], d = point - from[p]
146    let d11 = dot(e1, e1), d12 = dot(e1, e2), d22 = dot(e2, e2)
147    let denominator = d11 * d22 - d12 * d12
148    let wq = (d22 * dot(d, e1) - d12 * dot(d, e2)) / denominator
149    let wr = (d11 * dot(d, e2) - d12 * dot(d, e1)) / denominator
150    return to[p] + wq * (to[q] - to[p]) + wr * (to[r] - to[p])
151}