import FoldFormat import Folding import simd /// Two unit normals whose dot product's magnitude reaches this lie on one line. private let parallelCosine = 1 - 1e-9 /// How far before a pair's arrival the guess looks, as a fraction of the arriving axis's window. private let arrivalLead = 1e-3 /// Two layers closer than this fraction of the sheet's size at that moment are not told apart. private let separationTolerance = 1e-9 /// Guesses `next`'s `faceOrders`, every overlapping pair once as `[f, g, s]` with `f < g`. /// /// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face /// that arrives last is placed on the side it arrives from: the pair is compared just before the /// last axis that moves them differently finishes, the higher-indexed of axes that finish /// together, at the paper points that meet in the middle of their overlap. A moving set that has /// turned over arrives with its layers reversed. This is right for plain valley and mountain /// folds and wrong for a flap tucked between layers, which the script corrects with overrides. /// /// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame. public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] { var end = next end.step = step let draft = FoldFile(fileSpec: file.fileSpec, edgesVertices: file.edgesVertices, facesVertices: file.facesVertices, edgesFirstCreasedAtStep: file.edgesFirstCreasedAtStep, frames: [file.frames[0], previous, end]) guard let folding = try? readStep(2, in: draft) else { preconditionFailure("guessFaceOrders needs a step that readStep accepts") } return guessOrders(previous: previous, step: folding, interpolator: FoldInterpolator(file: draft, step: folding), positions: next.verticesCoords, file: file, arrival: { $0.upperBound }) } /// The guess for the faces at `positions`, a state of `step`; `arrival` gives the time within an /// axis's window at which its faces reach that state. func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpolator, positions: [SIMD3], file: FoldFile, arrival: (ClosedRange) -> Double) -> [[Int]] { let faces = file.facesVertices let size = sheetExtent(file) let normals = faceNormals(positions: positions, faces: faces) var before: [SIMD2: Int] = [:] for (pair, s) in rigidInvariantFaceOrders(previous.faceOrders, normals: faceNormals(previous, file)) where before[pair] == nil { before[pair] = s } var axisOfFace: [Int: Int] = [:] for (a, axis) in step.axes.enumerated() { for f in axis.movingFaces { axisOfFace[f] = a } } func carriers(_ f: Int) -> Set { var result = Set(), a = axisOfFace[f] while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent } return result } var sampled: [Double: [SIMD3]] = [:] var orders: [[Int]] = [] for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) { let differing = carriers(a).symmetricDifference(carriers(b)) let last = differing.max { (arrival(step.axes[$0].window), $0) < (arrival(step.axes[$1].window), $1) } guard let last else { if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) } continue } let window = step.axes[last].window let t = arrival(window) - arrivalLead * (window.upperBound - window.lowerBound) let near = sampled[t] ?? interpolator.positions(at: t) sampled[t] = near let meeting = overlapCentre(a, b, inPlaneOf: a, positions, faces, normals) let separation = dot(carry(meeting, on: faces[a], from: positions, to: near) - carry(meeting, on: faces[b], from: positions, to: near), normals[b]) if abs(separation) > size * separationTolerance { orders.append([a, b, separation > 0 ? 1 : -1]) } else if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) } } return orders } /// Replaces the order of each overridden pair, adding it when absent. Each override names its /// faces by points in the crease pattern and puts `above` nearer the eye than `below`; the result /// keeps every pair once as `[f, g, s]` with `f < g`, sorted. /// /// - Throws: `CompileError.unresolvedFace` with step 0 when a point lies on no face; `compile` /// reports the step. public func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame, viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]] { guard !overrides.isEmpty else { return orders } let normals = faceNormals(frame, file) var result = orders for o in overrides { guard let above = face(containing: o.above, file) else { throw CompileError.unresolvedFace(step: 0, point: o.above) } guard let below = face(containing: o.below, file) else { throw CompileError.unresolvedFace(step: 0, point: o.below) } let s = dot(normals[below], viewpoint.eye) > 0 ? 1 : -1 let triple = above < below ? [above, below, s] : [below, above, dot(normals[above], normals[below]) > 0 ? -s : s] result.removeAll { Set($0.prefix(2)) == Set([above, below]) } result.append(triple) } return result.sorted { ($0[0], $0[1]) < ($1[0], $1[1]) } } /// Pairs `(a, b)`, `a < b`, of faces in one plane whose interiors overlap. private func overlappingPairs(_ positions: [SIMD3], _ faces: [[Int]], _ normals: [SIMD3], tolerance: Double) -> [(Int, Int)] { var pairs: [(Int, Int)] = [] for a in faces.indices where normals[a] != .zero { let corner = positions[faces[a][0]] let (u, v) = planeBasis(normals[a]) let project = { (f: Int) in faces[f].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } } let outline = project(a) for b in faces.indices.dropFirst(a + 1) where normals[b] != .zero && abs(dot(normals[a], normals[b])) >= parallelCosine && faces[b].allSatisfy({ abs(dot(positions[$0] - corner, normals[a])) <= tolerance }) && convexPolygonsOverlap(outline, project(b), tolerance: tolerance) { pairs.append((a, b)) } } return pairs } /// `point`, a point of the face with corners `corners` at `from`, where the same point of paper /// is at `to`. Both states must place the face rigidly. private func carry(_ point: SIMD3, on corners: [Int], from: [SIMD3], to: [SIMD3]) -> SIMD3 { // the corner triangle with the largest area gives the best-conditioned weights var best = (0, 1, 2), largest = -1.0 for i in corners.indices { for j in corners.indices where j > i { for k in corners.indices where k > j { let area = length(cross(from[corners[j]] - from[corners[i]], from[corners[k]] - from[corners[i]])) if area > largest { (best, largest) = ((i, j, k), area) } } } } let (p, q, r) = (corners[best.0], corners[best.1], corners[best.2]) let e1 = from[q] - from[p], e2 = from[r] - from[p], d = point - from[p] let d11 = dot(e1, e1), d12 = dot(e1, e2), d22 = dot(e2, e2) let denominator = d11 * d22 - d12 * d12 let wq = (d22 * dot(d, e1) - d12 * dot(d, e2)) / denominator let wr = (d11 * dot(d, e2) - d12 * dot(d, e1)) / denominator return to[p] + wq * (to[q] - to[p]) + wr * (to[r] - to[p]) }