import FoldFormat import Folding import simd public enum CompileError: Error, Equatable, Sendable { /// A crease, driver or spine names no edge or a boundary edge, a crease names an edge already /// named in the step, or the driver is not one of the step's creases. `crease` is the /// reference as the script gives it. case unresolvedCrease(step: Int, crease: CreaseRef) /// A fold or fold-and-unfold step names no crease. case noCreases(step: Int) /// A `movingSide` point lies on no face, every region has one, or a crease does not separate /// a moving region from the rest. case unresolvedMovingSide(step: Int) /// An order override's point lies on no face. case unresolvedFace(step: Int, point: SIMD2) case stepFailed(step: Int, defects: [FoldDefect]) case interpenetration(step: Int, [Intersection]) /// A crease folded in the last frame has a different assignment in the crease pattern. case assignmentDisagreesWithPattern(edge: Int) /// The step's creases close a loop that does not stay closed. case noRigidMotion(step: Int) /// A solved curve, rebuilt from its samples, opens a gap between them. case curveTooCoarse(step: Int) /// A face of the crease pattern is clockwise seen from +z. case clockwiseFace(face: Int) /// `crease`, or an edge on its line, has no angle in the script and is neither `V` nor `M` in /// the crease pattern. case missingAngle(step: Int, crease: CreaseRef) /// `angles`, `peakAngles` or `windows` does not have one entry per crease. case creaseListMismatch(step: Int) /// An axis the step solves to close a loop has a scripted window other than the driver's. case solvedAxisWindowConflict(step: Int, edge: Int) /// The pop's largest relative change in a render-mesh edge's length exceeds 10%. case popTooStrained(step: Int, strain: Double) /// A reverse fold or sink, or a step naming `openOn`, names no `spine`. case missingSpine(step: Int) /// A `spine` is given on a step that is not a fold, or is not folded flat in frame n − 1. case invalidSpine(step: Int) /// An edge on a named crease's line, in another layer, becomes an axis of its own while the /// named crease's scripted angle is not ±180; its angle is not derived. case coincidentAxisAngle(step: Int, edge: Int) /// An axis's angle leaves the range between its start angle and its end angle, or its peak /// angle for a fold-and-unfold. case angleOutsideTravel(step: Int, edge: Int) /// A step's `openOn` names a crease that no earlier reverse fold holding the step's flap /// opened on. case noEarlierOpening(step: Int) } /// Samples in a solved curve, evenly spaced over its window. private let curveSamples = 257 /// Lengths are compared to within this fraction of the sheet's longer side. let relativeTolerance = 1e-6 /// A crease's named endpoints match an edge's within this distance in crease-pattern units. private let creaseMatchTolerance = 1e-6 /// A solved angle within this many degrees of linear at every sample is written without a curve. private let linearTolerance = 1e-9 /// A measured end angle within this many degrees of an expected one is taken to be it. let angleSnapTolerance = 1e-6 /// Samples of a step checked for interpenetration. private let interpenetrationSamples = 64 /// Compiles a fold script against its crease pattern into a FOLD sequence. /// /// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the /// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed /// and overridden, and the file so far validated and checked with `layerMotionDefects` and for /// interpenetration. A step that names a `spine` is a reverse fold or sink and moves by /// `compilePop`'s open, pop and close. public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile { let flat = pattern.frames[0] for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 { throw CompileError.clockwiseFace(face: f) } let finalAssignment = flat.edgesAssignment let keyFrame = FoldFrame(verticesCoords: flat.verticesCoords, edgesAssignment: finalAssignment.map { $0 == .boundary ? .boundary : .flat }, edgesFoldAngle: finalAssignment.map { _ in 0 }, faceOrders: []) var file = FoldFile(fileSpec: 1.2, fileTitle: script.title, fileAuthor: pattern.fileAuthor, fileClasses: ["diagrams"], edgesVertices: pattern.edgesVertices, facesVertices: pattern.facesVertices, edgesFirstCreasedAtStep: pattern.edgesVertices.map { _ in nil }, frames: [keyFrame]) var viewpoint = Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) for (i, step) in script.steps.enumerated() { viewpoint = step.viewpoint ?? viewpoint try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment) } let last = file.frames[file.frames.count - 1] for e in file.edgesVertices.indices where last.edgesFoldAngle[e] != 0 && last.edgesAssignment[e] != finalAssignment[e] { throw CompileError.assignmentDisagreesWithPattern(edge: e) } return file } /// Compiles step `n` and appends frame n to `file`. private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile, finalAssignment: [EdgeAssignment]) throws { let technique = script.technique ?? .plain if script.spine == nil && ([.insideReverse, .outsideReverse, .sink].contains(technique) || script.openOn != nil) { throw CompileError.missingSpine(step: n) } if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) } let previous = file.frames[n - 1] var plan: FoldPlan? if script.kind == .fold || script.kind == .foldAndUnfold { plan = try planFolds(n, script, file, finalAssignment) } var record = StepRecord(kind: script.kind, technique: technique, instruction: script.instruction, axes: plan?.axes ?? [], rotateDegrees: script.rotateDegrees, turnOverAxis: script.turnOverAxis, repeatOf: script.repeatOf, viewpoint: viewpoint) // frame n with the start's coordinates, enough for readStep var draft = file draft.frames.append(FoldFrame(verticesCoords: previous.verticesCoords, edgesAssignment: previous.edgesAssignment, edgesFoldAngle: previous.edgesFoldAngle, faceOrders: [], step: record)) var step = try readStep(n, in: draft) if let plan, !plan.loops.isEmpty { record = try solveLoops(n, record, step, loops: plan.loops, draft) draft.frames[n].step = record step = try readStep(n, in: draft) try checkClosure(n, step, driver: record.axes[0].edge, draft, solved: record.axes.contains { $0.angles != nil }) } var interpolator = FoldInterpolator(file: draft, step: step) var angles = previous.edgesFoldAngle var assignment = previous.edgesAssignment if let plan { for axis in record.axes { angles[axis.edge] = axis.endAngle } if script.kind == .fold { for (e, angle) in try loopEndAngles(n, plan, previous, interpolator, file) { angles[e] = angle } } for e in plan.creased { assignment[e] = angles[e] > 0 ? .valley : angles[e] < 0 ? .mountain : .flat if file.edgesFirstCreasedAtStep[e] == nil { file.edgesFirstCreasedAtStep[e] = n } } } var frame = FoldFrame(verticesCoords: interpolator.positions(at: 1), edgesAssignment: assignment, edgesFoldAngle: angles, faceOrders: [], step: record) if script.spine != nil { // the step's axes give frame n's coordinates; the pop is how the paper gets there let pop = try compilePop(step: n, script: script, before: previous, after: frame, file: file) record = withPop(record, pop) draft.frames[n].step = record step = try readStep(n, in: draft) interpolator = FoldInterpolator(file: draft, step: step) frame.verticesCoords = interpolator.positions(at: 1) frame.step = record // a bend line on the spine bends and flattens again, and is not creased for (e, angle) in popEndAngles(step, interpolator, previous: previous, file: file) { frame.edgesFoldAngle[e] = angle frame.edgesAssignment[e] = angle > 0 ? .valley : angle < 0 ? .mountain : .flat if file.edgesFirstCreasedAtStep[e] == nil && angle != 0 { file.edgesFirstCreasedAtStep[e] = n } } } let guess = guessFaceOrders(previous: previous, next: frame, step: record, file: file) frame.faceOrders = try naming(n) { try applyOrderOverrides(script.faceOrders ?? [], to: guess, frame: frame, viewpoint: viewpoint, file: file) } file.frames.append(frame) if script.kind == .foldAndUnfold { var peak = frame peak.verticesCoords = interpolator.positions(at: 0.5) let peakGuess = guessOrders(previous: previous, step: step, interpolator: interpolator, positions: peak.verticesCoords, file: file, arrival: { ($0.lowerBound + $0.upperBound) / 2 }) file.frames[n].faceOrdersMidFold = try naming(n) { try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: peakGuess, frame: peak, viewpoint: viewpoint, file: file) } } else if script.kind == .fold && (script.faceOrdersMidFold != nil || movingSetsOverlapInProjection(step: n, file)) { file.frames[n].faceOrdersMidFold = try naming(n) { try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: frame.faceOrders, frame: frame, viewpoint: viewpoint, file: file) } } let defects = validate(file) guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) } try checkTravel(n, step) let motion = layerMotionDefects(step: n, in: file) guard motion.isEmpty else { throw CompileError.stepFailed(step: n, defects: motion) } let collisions = step.nonRigid ? meshInterpenetrations(interpolator, samples: interpenetrationSamples) : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples) guard collisions.isEmpty else { throw CompileError.interpenetration(step: n, collisions) } } /// Runs `body`, giving an `unresolvedFace` error the step number `n`. private func naming(_ n: Int, _ body: () throws -> T) throws -> T { do { return try body() } catch CompileError.unresolvedFace(_, let point) { throw CompileError.unresolvedFace(step: n, point: point) } } // MARK: - Planning a fold /// A fold or fold-and-unfold step's axes and the edges it creases. private struct FoldPlan { /// One per edge of the region tree, driver first, without curves. var axes: [AxisRecord] /// Every edge whose two faces the step moves differently. var creased: [Int] /// Creased edges off the region tree, each closing a loop. var loops: [Int] /// The scripted end angle of each crease in `loops` that the script names with an angle. var expected: [Int: Double] } /// Resolves the step's creases and moving side, cuts the sheet into regions along the creases /// and grows a tree of regions from the fixed one, across the creases in script order, driver /// first. Each tree edge is an axis; each other crease between different regions closes a loop. /// /// Every edge that lies on a named crease's line in the start frame is cut too, so a crease /// through several layers folds each of them; one whose faces end up in the same region is not /// creased. One that becomes an axis of its own takes ±180 by the pattern's assignment, so its /// named crease must be scripted at ±180 or not at all. private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile, _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan { let start = file.frames[n - 1] let edgeFaces = edgesFaces(file) let count = script.creases.count for list in [script.angles?.count, script.peakAngles?.count, script.windows?.count] where list != nil && list != count { throw CompileError.creaseListMismatch(step: n) } guard count > 0 else { throw CompileError.noCreases(step: n) } let named = try script.creases.map { ref in guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) } return e } if let repeated = named.indices.first(where: { named[..<$0].contains(named[$0]) }) { throw CompileError.unresolvedCrease(step: n, crease: script.creases[repeated]) } var driver = 0 if let ref = script.driver { guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else { throw CompileError.unresolvedCrease(step: n, crease: ref) } driver = i } let order = [driver] + named.indices.filter { $0 != driver } // each crease with the index of the script crease it belongs to var creases = order.map { (edge: named[$0], source: $0) } let tolerance = sheetExtent(file) * relativeTolerance for i in order { let ends = file.edgesVertices[named[i]].map { start.verticesCoords[$0] } for e in edgeFaces.indices where edgeFaces[e].count == 2 && !creases.contains(where: { $0.edge == e }) && file.edgesVertices[e].allSatisfy({ onLine(start.verticesCoords[$0], ends[0], ends[1], tolerance) }) { creases.append((e, i)) } } // regions: faces connected across edges the step does not cut let cut = Set(creases.map(\.edge)) var region = Array(repeating: -1, count: file.facesVertices.count) var regionCount = 0 for seed in region.indices where region[seed] < 0 { region[seed] = regionCount var stack = [seed] while let f = stack.popLast() { for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) { let g = faces[0] == f ? faces[1] : faces[0] if region[g] < 0 { region[g] = regionCount stack.append(g) } } } regionCount += 1 } // nodes: 0 for the fixed regions, then each moving region in the order its point appears guard !script.movingSide.isEmpty else { throw CompileError.unresolvedMovingSide(step: n) } var nodeOfRegion = Array(repeating: 0, count: regionCount) var nodeCount = 1 for point in script.movingSide { guard let f = face(containing: point, file) else { throw CompileError.unresolvedMovingSide(step: n) } if nodeOfRegion[region[f]] == 0 { nodeOfRegion[region[f]] = nodeCount nodeCount += 1 } } guard nodeOfRegion.contains(0) else { throw CompileError.unresolvedMovingSide(step: n) } let node = region.map { nodeOfRegion[$0] } // the tree, by union-find over the creases in order var component = Array(0.. Int { var x = x while component[x] != x { x = component[x] } return x } var tree: [(edge: Int, source: Int, ends: (Int, Int))] = [] var creased: [Int] = [], loops: [Int] = [] for (e, source) in creases { let a = node[edgeFaces[e][0]], b = node[edgeFaces[e][1]] if a == b { if e == named[source] { throw CompileError.unresolvedMovingSide(step: n) } continue } creased.append(e) if find(a) != find(b) { component[find(a)] = find(b) tree.append((e, source, (a, b))) } else { loops.append(e) } } // orient the tree from the fixed node var parentNode = Array(repeating: nil, count: nodeCount) var axisOfNode = Array(repeating: nil, count: nodeCount) var reached: Set = [0] var queue = [0] while !queue.isEmpty { let a = queue.removeFirst() for (k, t) in tree.enumerated() where t.ends.0 == a || t.ends.1 == a { let b = t.ends.0 == a ? t.ends.1 : t.ends.0 guard reached.insert(b).inserted else { continue } parentNode[b] = a axisOfNode[b] = k queue.append(b) } } let axes = try tree.enumerated().map { k, t -> AxisRecord in let child = axisOfNode[t.ends.0] == k ? t.ends.0 : t.ends.1 let parent = parentNode[child].flatMap { axisOfNode[$0] } let isNamed = t.edge == named[t.source] let movingFaces = node.indices.filter { node[$0] == child } let startAngle = start.edgesFoldAngle[t.edge] let window = script.windows?[t.source] let written = window == [0, 1] ? nil : window func endAngle(_ list: [Double]?) throws -> Double { if let list { if isNamed { return list[t.source] } if abs(list[t.source]) != 180 { throw CompileError.coincidentAxisAngle(step: n, edge: t.edge) } } switch finalAssignment[t.edge] { case .valley: return 180 case .mountain: return -180 default: throw CompileError.missingAngle(step: n, crease: script.creases[t.source]) } } if script.kind == .foldAndUnfold { return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle, endAngle: startAngle, peakAngle: try endAngle(script.peakAngles), parent: parent, window: written) } return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle, endAngle: try endAngle(script.angles), parent: parent, window: written) } var expected: [Int: Double] = [:] if let angles = script.angles { for (e, source) in creases where loops.contains(e) && e == named[source] { expected[e] = angles[source] } } return FoldPlan(axes: axes, creased: creased, loops: loops, expected: expected) } /// The edge a crease reference names: by index, or the edge whose endpoints in the crease /// pattern are nearest the named points, within 1e-6. Boundary edges are not creases. func resolve(_ ref: CreaseRef, _ file: FoldFile, _ edgeFaces: [[Int]]) -> Int? { switch ref { case .edgeIndex(let e): return edgeFaces.indices.contains(e) && edgeFaces[e].count == 2 ? e : nil case .betweenVertices(let p, let q): let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } let nearest = file.edgesVertices.indices.map { e -> (edge: Int, distance: Double) in let u = flat[file.edgesVertices[e][0]], v = flat[file.edgesVertices[e][1]] return (e, min(max(distance(u, p), distance(v, q)), max(distance(u, q), distance(v, p)))) }.min { $0.distance < $1.distance } guard let nearest, nearest.distance <= creaseMatchTolerance, edgeFaces[nearest.edge].count == 2 else { return nil } return nearest.edge } } /// The first face of the crease pattern whose closed outline contains `point`. func face(containing point: SIMD2, _ file: FoldFile) -> Int? { let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } return file.facesVertices.indices.first { f in let corners = file.facesVertices[f].map { flat[$0] } return corners.indices.allSatisfy { i in let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = point - a return side.x * offset.y - side.y * offset.x >= 0 } } } func onLine(_ p: SIMD3, _ a: SIMD3, _ b: SIMD3, _ tolerance: Double) -> Bool { length(cross(p - a, normalize(b - a))) <= tolerance } /// The longer side of frame 0's bounding box. func sheetExtent(_ file: FoldFile) -> Double { let points = file.frames[0].verticesCoords let lower = points.dropFirst().reduce(points[0], simd_min) let upper = points.dropFirst().reduce(points[0], simd_max) return (upper - lower).max() } // MARK: - Loops /// Holds the driver (the first axis in `record`) linear on its window and solves the other axes /// on a loop's cycle, the tree path between the two sides of a loop crease, so the loops stay /// closed: damped Gauss–Newton on the gap between vertex copies, continued along the window from /// the previous samples. Where closure leaves the solved axes free, each sample is then moved /// toward the linear angles within those free directions (`LoopKinematics.settle`). Each solved /// axis takes the driver's window and a curve of 257 samples, or none when it is linear to within /// 1e-9°; the last sample is the end angle exactly. Axes on no cycle stay linear on their own /// windows. /// /// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window. func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int], _ file: FoldFile) throws -> StepRecord { guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record } let free = axesOnCycles(step, loops: loops, file).subtracting([driver]).sorted() guard !free.isEmpty else { return record } for a in free where step.axes[a].window != step.axes[driver].window { throw CompileError.solvedAxisWindowConflict(step: n, edge: step.axes[a].edge) } let kinematics = LoopKinematics(step: step, file: file) let tolerance = sheetExtent(file) * relativeTolerance let fraction = { (k: Int) in Double(k) / Double(curveSamples - 1) } func linear(_ axis: FoldAxis, _ u: Double) -> Double { step.kind == .foldAndUnfold ? axis.startAngle + ((axis.peakAngle ?? axis.endAngle) - axis.startAngle) * (1 - abs(2 * u - 1)) : axis.startAngle + u * (axis.endAngle - axis.startAngle) } var samples: [[Double]] = [] for k in 0.. Set { 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 } let edgeFaces = edgesFaces(file) let start = file.frames[step.index - 1].verticesCoords let tolerance = sheetExtent(file) * relativeTolerance return loops.reduce(into: Set()) { cycle, e in let path = carriers(edgeFaces[e][0]).symmetricDifference(carriers(edgeFaces[e][1])) let coaxial = path.allSatisfy { a in file.edgesVertices[e].allSatisfy { onLine(start[$0], step.axes[a].origin, step.axes[a].origin + step.axes[a].direction, tolerance) } } if !coaxial { cycle.formUnion(path) } } } /// Checks every axis's angle stays within ±180°, and a linear axis's within the range of its start, /// end and, for a fold-and-unfold, peak angles, to within 1e-6°, at four times the curve sample /// density over its window. A fold-and-unfold's end angle equals its start angle, so its range runs /// from the start to the peak. A solved curve may turn back within ±180°. A non-rigid step is /// checked on its pop's open and close axes, which are what move it. func checkTravel(_ n: Int, _ step: FoldStep) throws { let moving = step.pop.map { ($0.openAxes + $0.closeAxes, StepKind.fold) } ?? (step.axes, step.kind) let intervals = 4 * (curveSamples - 1) for axis in moving.0 { let scripted = [axis.startAngle, axis.endAngle] + (moving.1 == .foldAndUnfold ? [axis.peakAngle ?? axis.endAngle] : []) let linear = axis.curve == nil let low = (linear ? max(scripted.min()!, -180) : -180) - angleSnapTolerance let high = (linear ? min(scripted.max()!, 180) : 180) + angleSnapTolerance let w = axis.window for k in 0...intervals { let angle = axis.angle(at: w.lowerBound + Double(k) / Double(intervals) * (w.upperBound - w.lowerBound), kind: moving.1) if angle < low || angle > high { throw CompileError.angleOutsideTravel(step: n, edge: axis.edge) } } } } /// Checks the step's loops stay closed as its axes move, at four times the curve sample density /// over the window of the axis on `driver` and over the whole step. func checkClosure(_ n: Int, _ step: FoldStep, driver: Int, _ file: FoldFile, solved: Bool) throws { let kinematics = LoopKinematics(step: step, file: file) let tolerance = sheetExtent(file) * relativeTolerance let intervals = 4 * (curveSamples - 1) let window = step.axes.first { $0.edge == driver }?.window ?? 0...1 let times = (0...intervals).flatMap { k -> [Double] in let u = Double(k) / Double(intervals) return [u, window.lowerBound + u * (window.upperBound - window.lowerBound)] } for t in times where kinematics.gap(step.axes.map { $0.angle(at: t, kind: step.kind) }) > tolerance { throw solved ? CompileError.curveTooCoarse(step: n) : CompileError.noRigidMotion(step: n) } } /// The end angle of each loop crease, measured from the faces' normals along the step and /// unwrapped from its start angle, then taken to be its scripted angle, ±180 or 0 when within /// 1e-6° of one. private func loopEndAngles(_ n: Int, _ plan: FoldPlan, _ previous: FoldFrame, _ interpolator: FoldInterpolator, _ file: FoldFile) throws -> [Int: Double] { let edgeFaces = edgesFaces(file) var current = Dictionary(uniqueKeysWithValues: plan.loops.map { ($0, previous.edgesFoldAngle[$0]) }) let intervals = curveSamples - 1 for k in 1...intervals { let positions = interpolator.positions(at: Double(k) / Double(intervals)) let normals = faceNormals(positions: positions, faces: file.facesVertices) for e in plan.loops { let measured = dihedral(e, edgeFaces[e], positions, normals, file) current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded() } } var result: [Int: Double] = [:] for (e, angle) in current { let candidates = (plan.expected[e].map { [$0] } ?? []) + [180, -180, 0] let snapped = candidates.first { abs(angle - $0) <= angleSnapTolerance } ?? angle if let expected = plan.expected[e], snapped != expected { throw CompileError.noRigidMotion(step: n) } result[e] = snapped } return result } /// The fold angle in degrees of an interior edge between faces `faces`, positive for a valley: /// the turn from the first face's normal to the second's about the edge, directed as the second /// face traverses it. func dihedral(_ e: Int, _ faces: [Int], _ positions: [SIMD3], _ normals: [SIMD3], _ file: FoldFile) -> Double { let corners = file.facesVertices[faces[1]], ends = Set(file.edgesVertices[e]) let i = corners.indices.first { ends == Set([corners[$0], corners[($0 + 1) % corners.count]]) }! let d = normalize(positions[corners[(i + 1) % corners.count]] - positions[corners[i]]) let a = normals[faces[0]], b = normals[faces[1]] return atan2(dot(cross(a, b), d), dot(a, b)) * 180 / .pi } /// p ↦ q·p + t private struct Rigid { var q = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1) var t = SIMD3.zero func apply(_ p: SIMD3) -> SIMD3 { q.act(p) + t } /// This transform applied after `inner`. func after(_ inner: Rigid) -> Rigid { Rigid(q: q * inner.q, t: q.act(inner.t) + t) } static func rotation(about origin: SIMD3, direction: SIMD3, degrees: Double) -> Rigid { let q = simd_quatd(angle: degrees * .pi / 180, axis: direction) return Rigid(q: q, t: origin - q.act(origin)) } } /// A step's axes as functions of their angles, and the gap between the copies of each vertex /// that faces moving with different axes carry. struct LoopKinematics { let axes: [FoldAxis] let start: [SIMD3] /// Each vertex shared by faces that move differently, with the axes that move them, −1 for /// a still face. let copies: [(vertex: Int, axes: [Int])] init(step: FoldStep, file: FoldFile) { axes = step.axes start = file.frames[step.index - 1].verticesCoords var axisOfFace = Array(repeating: -1, count: file.facesVertices.count) for (a, axis) in step.axes.enumerated() { for f in axis.movingFaces { axisOfFace[f] = a } } var movers = Array(repeating: [Int](), count: start.count) for (f, corners) in file.facesVertices.enumerated() { for v in corners where !movers[v].contains(axisOfFace[f]) { movers[v].append(axisOfFace[f]) } } copies = movers.indices.filter { movers[$0].count > 1 }.map { ($0, movers[$0]) } } func residual(_ angles: [Double]) -> [Double] { var full: [Rigid] = [] for (a, axis) in axes.enumerated() { let own = Rigid.rotation(about: axis.origin, direction: axis.direction, degrees: angles[a] - axis.startAngle) full.append(axis.parent.map { full[$0].after(own) } ?? own) } func place(_ a: Int, _ p: SIMD3) -> SIMD3 { a < 0 ? p : full[a].apply(p) } var r: [Double] = [] for (v, movers) in copies { let base = place(movers[0], start[v]) for a in movers.dropFirst() { let d = place(a, start[v]) - base r += [d.x, d.y, d.z] } } return r } /// The largest distance between two copies of one vertex. func gap(_ angles: [Double]) -> Double { let r = residual(angles) return stride(from: 0, to: r.count, by: 3).map { length(SIMD3(r[$0], r[$0 + 1], r[$0 + 2])) }.max() ?? 0 } /// Damped Gauss–Newton on the angles of the axes in `free`, holding the rest. Returns the gap /// it reaches. func solve(_ angles: inout [Double], free: [Int], iterations: Int = 60) -> Double { var lambda = 1e-6 var r = residual(angles) var cost = r.reduce(0) { $0 + $1 * $1 } for _ in 0.. [[Double]] { let h = 1e-6 var jacobian: [[Double]] = [] for (k, a) in free.enumerated() { var probe = angles probe[a] += h let plus = residual(probe) probe[a] -= 2 * h let minus = residual(probe) if k == 0 { jacobian = Array(repeating: [Double](repeating: 0, count: free.count), count: plus.count) } for i in plus.indices { jacobian[i][k] = (plus[i] - minus[i]) / (2 * h) } } return jacobian } /// Moves the angles in `free` toward `target` within the null space of the closure Jacobian J, /// by δ = ε(JᵀJ + εI)⁻¹(target − angles) three times, then solves again. ε is 1e-6 of JᵀJ's /// largest eigenvalue, so δ takes the null space's part of the difference and almost none of /// the rest. When JᵀJ has no eigenvalue below 1e-10 of its largest (closure fixes every free /// axis, as at a vertex with one degree of freedom) or the solve does not close to `tolerance`, /// `angles` is left as it was. func settle(_ angles: inout [Double], toward target: [Double], free: [Int], tolerance: Double) { var x = angles for _ in 0..<3 { let j = jacobian(x, free: free) var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count) for row in j { for a in free.indices { for b in free.indices { normal[a][b] += row[a] * row[b] } } } let (values, vectors) = symmetricEigen(normal) guard let largest = values.max(), largest > 0, values.contains(where: { $0 < 1e-10 * largest }) else { return } let epsilon = 1e-6 * largest let difference = free.map { target[$0] - x[$0] } for (value, vector) in zip(values, vectors) { let along = zip(vector, difference).reduce(0) { $0 + $1.0 * $1.1 } * epsilon / (value + epsilon) for (k, a) in free.enumerated() { x[a] += along * vector[k] } } } guard solve(&x, free: free) <= tolerance else { return } angles = x } } /// The eigenvalues of a symmetric matrix and a unit eigenvector for each, by cyclic Jacobi /// rotations. private func symmetricEigen(_ matrix: [[Double]]) -> (values: [Double], vectors: [[Double]]) { let n = matrix.count var a = matrix var v = (0..= 0 ? 1.0 : -1.0) / (abs(theta) + (theta * theta + 1).squareRoot()) let c = 1 / (t * t + 1).squareRoot(), s = t * c for k in 0.. [Double]? { var m = a, x = b let n = b.count for c in 0.. 1e-300 else { return nil } m.swapAt(c, p) x.swapAt(c, p) for r in (c + 1)..