Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift history · blame · raw

800 lines · 39073 bytes

33 symbols in this file
  1import FoldFormat
  2import Folding
  3import simd
  4
  5public enum CompileError: Error, Equatable, Sendable {
  6    /// A crease, driver or spine names no edge or a boundary edge, a crease names an edge already
  7    /// named in the step, or the driver is not one of the step's creases. `crease` is the
  8    /// reference as the script gives it.
  9    case unresolvedCrease(step: Int, crease: CreaseRef)
 10    /// A fold or fold-and-unfold step names no crease.
 11    case noCreases(step: Int)
 12    /// A `movingSide` point lies on no face, every region has one, or a crease does not separate
 13    /// a moving region from the rest.
 14    case unresolvedMovingSide(step: Int)
 15    /// An order override's point lies on no face.
 16    case unresolvedFace(step: Int, point: SIMD2<Double>)
 17    case stepFailed(step: Int, defects: [FoldDefect])
 18    case interpenetration(step: Int, [Intersection])
 19    /// A crease folded in the last frame has a different assignment in the crease pattern.
 20    case assignmentDisagreesWithPattern(edge: Int)
 21    /// The step's creases close a loop that does not stay closed.
 22    case noRigidMotion(step: Int)
 23    /// A solved curve, rebuilt from its samples, opens a gap between them.
 24    case curveTooCoarse(step: Int)
 25    /// A face of the crease pattern is clockwise seen from +z.
 26    case clockwiseFace(face: Int)
 27    /// `crease`, or an edge on its line, has no angle in the script and is neither `V` nor `M` in
 28    /// the crease pattern.
 29    case missingAngle(step: Int, crease: CreaseRef)
 30    /// `angles`, `peakAngles` or `windows` does not have one entry per crease.
 31    case creaseListMismatch(step: Int)
 32    /// An axis the step solves to close a loop has a scripted window other than the driver's.
 33    case solvedAxisWindowConflict(step: Int, edge: Int)
 34    /// The pop's largest relative change in a render-mesh edge's length exceeds 10%.
 35    case popTooStrained(step: Int, strain: Double)
 36    /// A reverse fold or sink, or a step naming `openOn`, names no `spine`.
 37    case missingSpine(step: Int)
 38    /// A `spine` is given on a step that is not a fold, or is not folded flat in frame n − 1.
 39    case invalidSpine(step: Int)
 40    /// An edge on a named crease's line, in another layer, becomes an axis of its own while the
 41    /// named crease's scripted angle is not ±180; its angle is not derived.
 42    case coincidentAxisAngle(step: Int, edge: Int)
 43    /// An axis's angle leaves the range between its start angle and its end angle, or its peak
 44    /// angle for a fold-and-unfold.
 45    case angleOutsideTravel(step: Int, edge: Int)
 46    /// A step's `openOn` names a crease that no earlier reverse fold holding the step's flap
 47    /// opened on.
 48    case noEarlierOpening(step: Int)
 49}
 50
 51/// Samples in a solved curve, evenly spaced over its window.
 52private let curveSamples = 257
 53/// Lengths are compared to within this fraction of the sheet's longer side.
 54let relativeTolerance = 1e-6
 55/// A crease's named endpoints match an edge's within this distance in crease-pattern units.
 56private let creaseMatchTolerance = 1e-6
 57/// A solved angle within this many degrees of linear at every sample is written without a curve.
 58private let linearTolerance = 1e-9
 59/// A measured end angle within this many degrees of an expected one is taken to be it.
 60let angleSnapTolerance = 1e-6
 61/// Samples of a step checked for interpenetration.
 62private let interpenetrationSamples = 64
 63
 64/// Compiles a fold script against its crease pattern into a FOLD sequence.
 65///
 66/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the
 67/// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed
 68/// and overridden, and the file so far validated and checked with `layerMotionDefects` and for
 69/// interpenetration. A step that names a `spine` is a reverse fold or sink and moves by
 70/// `compilePop`'s open, pop and close.
 71public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile {
 72    let flat = pattern.frames[0]
 73    for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 {
 74        throw CompileError.clockwiseFace(face: f)
 75    }
 76    let finalAssignment = flat.edgesAssignment
 77    let keyFrame = FoldFrame(verticesCoords: flat.verticesCoords,
 78                             edgesAssignment: finalAssignment.map { $0 == .boundary ? .boundary : .flat },
 79                             edgesFoldAngle: finalAssignment.map { _ in 0 },
 80                             faceOrders: [])
 81    var file = FoldFile(fileSpec: 1.2, fileTitle: script.title, fileAuthor: pattern.fileAuthor,
 82                        fileClasses: ["diagrams"], edgesVertices: pattern.edgesVertices,
 83                        facesVertices: pattern.facesVertices,
 84                        edgesFirstCreasedAtStep: pattern.edgesVertices.map { _ in nil },
 85                        frames: [keyFrame])
 86
 87    var viewpoint = Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
 88    for (i, step) in script.steps.enumerated() {
 89        viewpoint = step.viewpoint ?? viewpoint
 90        try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment)
 91    }
 92
 93    let last = file.frames[file.frames.count - 1]
 94    for e in file.edgesVertices.indices
 95    where last.edgesFoldAngle[e] != 0 && last.edgesAssignment[e] != finalAssignment[e] {
 96        throw CompileError.assignmentDisagreesWithPattern(edge: e)
 97    }
 98    return file
 99}
100
101/// Compiles step `n` and appends frame n to `file`.
102private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile,
103                        finalAssignment: [EdgeAssignment]) throws {
104    let technique = script.technique ?? .plain
105    if script.spine == nil && ([.insideReverse, .outsideReverse, .sink].contains(technique) || script.openOn != nil) {
106        throw CompileError.missingSpine(step: n)
107    }
108    if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) }
109    let previous = file.frames[n - 1]
110
111    var plan: FoldPlan?
112    if script.kind == .fold || script.kind == .foldAndUnfold {
113        plan = try planFolds(n, script, file, finalAssignment)
114    }
115    var record = StepRecord(kind: script.kind, technique: technique,
116                            instruction: script.instruction, axes: plan?.axes ?? [],
117                            rotateDegrees: script.rotateDegrees, turnOverAxis: script.turnOverAxis,
118                            repeatOf: script.repeatOf, viewpoint: viewpoint)
119
120    // frame n with the start's coordinates, enough for readStep
121    var draft = file
122    draft.frames.append(FoldFrame(verticesCoords: previous.verticesCoords,
123                                  edgesAssignment: previous.edgesAssignment,
124                                  edgesFoldAngle: previous.edgesFoldAngle, faceOrders: [], step: record))
125    var step = try readStep(n, in: draft)
126    if let plan, !plan.loops.isEmpty {
127        record = try solveLoops(n, record, step, loops: plan.loops, draft)
128        draft.frames[n].step = record
129        step = try readStep(n, in: draft)
130        try checkClosure(n, step, driver: record.axes[0].edge, draft, solved: record.axes.contains { $0.angles != nil })
131    }
132    var interpolator = FoldInterpolator(file: draft, step: step)
133
134    var angles = previous.edgesFoldAngle
135    var assignment = previous.edgesAssignment
136    if let plan {
137        for axis in record.axes { angles[axis.edge] = axis.endAngle }
138        if script.kind == .fold {
139            for (e, angle) in try loopEndAngles(n, plan, previous, interpolator, file) { angles[e] = angle }
140        }
141        for e in plan.creased {
142            assignment[e] = angles[e] > 0 ? .valley : angles[e] < 0 ? .mountain : .flat
143            if file.edgesFirstCreasedAtStep[e] == nil { file.edgesFirstCreasedAtStep[e] = n }
144        }
145    }
146
147    var frame = FoldFrame(verticesCoords: interpolator.positions(at: 1), edgesAssignment: assignment,
148                          edgesFoldAngle: angles, faceOrders: [], step: record)
149    if script.spine != nil {
150        // the step's axes give frame n's coordinates; the pop is how the paper gets there
151        let pop = try compilePop(step: n, script: script, before: previous, after: frame, file: file)
152        record = withPop(record, pop)
153        draft.frames[n].step = record
154        step = try readStep(n, in: draft)
155        interpolator = FoldInterpolator(file: draft, step: step)
156        frame.verticesCoords = interpolator.positions(at: 1)
157        frame.step = record
158        // a bend line on the spine bends and flattens again, and is not creased
159        for (e, angle) in popEndAngles(step, interpolator, previous: previous, file: file) {
160            frame.edgesFoldAngle[e] = angle
161            frame.edgesAssignment[e] = angle > 0 ? .valley : angle < 0 ? .mountain : .flat
162            if file.edgesFirstCreasedAtStep[e] == nil && angle != 0 { file.edgesFirstCreasedAtStep[e] = n }
163        }
164    }
165    let guess = guessFaceOrders(previous: previous, next: frame, step: record, file: file)
166    frame.faceOrders = try naming(n) {
167        try applyOrderOverrides(script.faceOrders ?? [], to: guess, frame: frame, viewpoint: viewpoint, file: file)
168    }
169    file.frames.append(frame)
170
171    if script.kind == .foldAndUnfold {
172        var peak = frame
173        peak.verticesCoords = interpolator.positions(at: 0.5)
174        let peakGuess = guessOrders(previous: previous, step: step, interpolator: interpolator,
175                                    positions: peak.verticesCoords, file: file,
176                                    arrival: { ($0.lowerBound + $0.upperBound) / 2 })
177        file.frames[n].faceOrdersMidFold = try naming(n) {
178            try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: peakGuess, frame: peak,
179                                    viewpoint: viewpoint, file: file)
180        }
181    } else if script.kind == .fold
182        && (script.faceOrdersMidFold != nil || movingSetsOverlapInProjection(step: n, file)) {
183        file.frames[n].faceOrdersMidFold = try naming(n) {
184            try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: frame.faceOrders, frame: frame,
185                                    viewpoint: viewpoint, file: file)
186        }
187    }
188
189    let defects = validate(file)
190    guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) }
191    try checkTravel(n, step)
192    let motion = layerMotionDefects(step: n, in: file)
193    guard motion.isEmpty else { throw CompileError.stepFailed(step: n, defects: motion) }
194    let collisions = step.nonRigid
195        ? meshInterpenetrations(interpolator, samples: interpenetrationSamples)
196        : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples)
197    guard collisions.isEmpty else { throw CompileError.interpenetration(step: n, collisions) }
198}
199
200/// Runs `body`, giving an `unresolvedFace` error the step number `n`.
201private func naming<T>(_ n: Int, _ body: () throws -> T) throws -> T {
202    do {
203        return try body()
204    } catch CompileError.unresolvedFace(_, let point) {
205        throw CompileError.unresolvedFace(step: n, point: point)
206    }
207}
208
209// MARK: - Planning a fold
210
211/// A fold or fold-and-unfold step's axes and the edges it creases.
212private struct FoldPlan {
213    /// One per edge of the region tree, driver first, without curves.
214    var axes: [AxisRecord]
215    /// Every edge whose two faces the step moves differently.
216    var creased: [Int]
217    /// Creased edges off the region tree, each closing a loop.
218    var loops: [Int]
219    /// The scripted end angle of each crease in `loops` that the script names with an angle.
220    var expected: [Int: Double]
221}
222
223/// Resolves the step's creases and moving side, cuts the sheet into regions along the creases
224/// and grows a tree of regions from the fixed one, across the creases in script order, driver
225/// first. Each tree edge is an axis; each other crease between different regions closes a loop.
226///
227/// Every edge that lies on a named crease's line in the start frame is cut too, so a crease
228/// through several layers folds each of them; one whose faces end up in the same region is not
229/// creased. One that becomes an axis of its own takes ±180 by the pattern's assignment, so its
230/// named crease must be scripted at ±180 or not at all.
231private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
232                       _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan {
233    let start = file.frames[n - 1]
234    let edgeFaces = edgesFaces(file)
235    let count = script.creases.count
236    for list in [script.angles?.count, script.peakAngles?.count, script.windows?.count] where list != nil && list != count {
237        throw CompileError.creaseListMismatch(step: n)
238    }
239
240    guard count > 0 else { throw CompileError.noCreases(step: n) }
241    let named = try script.creases.map { ref in
242        guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) }
243        return e
244    }
245    if let repeated = named.indices.first(where: { named[..<$0].contains(named[$0]) }) {
246        throw CompileError.unresolvedCrease(step: n, crease: script.creases[repeated])
247    }
248    var driver = 0
249    if let ref = script.driver {
250        guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else {
251            throw CompileError.unresolvedCrease(step: n, crease: ref)
252        }
253        driver = i
254    }
255    let order = [driver] + named.indices.filter { $0 != driver }
256
257    // each crease with the index of the script crease it belongs to
258    var creases = order.map { (edge: named[$0], source: $0) }
259    let tolerance = sheetExtent(file) * relativeTolerance
260    for i in order {
261        let ends = file.edgesVertices[named[i]].map { start.verticesCoords[$0] }
262        for e in edgeFaces.indices where edgeFaces[e].count == 2 && !creases.contains(where: { $0.edge == e })
263            && file.edgesVertices[e].allSatisfy({ onLine(start.verticesCoords[$0], ends[0], ends[1], tolerance) }) {
264            creases.append((e, i))
265        }
266    }
267
268    // regions: faces connected across edges the step does not cut
269    let cut = Set(creases.map(\.edge))
270    var region = Array(repeating: -1, count: file.facesVertices.count)
271    var regionCount = 0
272    for seed in region.indices where region[seed] < 0 {
273        region[seed] = regionCount
274        var stack = [seed]
275        while let f = stack.popLast() {
276            for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) {
277                let g = faces[0] == f ? faces[1] : faces[0]
278                if region[g] < 0 {
279                    region[g] = regionCount
280                    stack.append(g)
281                }
282            }
283        }
284        regionCount += 1
285    }
286
287    // nodes: 0 for the fixed regions, then each moving region in the order its point appears
288    guard !script.movingSide.isEmpty else { throw CompileError.unresolvedMovingSide(step: n) }
289    var nodeOfRegion = Array(repeating: 0, count: regionCount)
290    var nodeCount = 1
291    for point in script.movingSide {
292        guard let f = face(containing: point, file) else { throw CompileError.unresolvedMovingSide(step: n) }
293        if nodeOfRegion[region[f]] == 0 {
294            nodeOfRegion[region[f]] = nodeCount
295            nodeCount += 1
296        }
297    }
298    guard nodeOfRegion.contains(0) else { throw CompileError.unresolvedMovingSide(step: n) }
299    let node = region.map { nodeOfRegion[$0] }
300
301    // the tree, by union-find over the creases in order
302    var component = Array(0..<nodeCount)
303    func find(_ x: Int) -> Int {
304        var x = x
305        while component[x] != x { x = component[x] }
306        return x
307    }
308    var tree: [(edge: Int, source: Int, ends: (Int, Int))] = []
309    var creased: [Int] = [], loops: [Int] = []
310    for (e, source) in creases {
311        let a = node[edgeFaces[e][0]], b = node[edgeFaces[e][1]]
312        if a == b {
313            if e == named[source] { throw CompileError.unresolvedMovingSide(step: n) }
314            continue
315        }
316        creased.append(e)
317        if find(a) != find(b) {
318            component[find(a)] = find(b)
319            tree.append((e, source, (a, b)))
320        } else {
321            loops.append(e)
322        }
323    }
324
325    // orient the tree from the fixed node
326    var parentNode = Array<Int?>(repeating: nil, count: nodeCount)
327    var axisOfNode = Array<Int?>(repeating: nil, count: nodeCount)
328    var reached: Set<Int> = [0]
329    var queue = [0]
330    while !queue.isEmpty {
331        let a = queue.removeFirst()
332        for (k, t) in tree.enumerated() where t.ends.0 == a || t.ends.1 == a {
333            let b = t.ends.0 == a ? t.ends.1 : t.ends.0
334            guard reached.insert(b).inserted else { continue }
335            parentNode[b] = a
336            axisOfNode[b] = k
337            queue.append(b)
338        }
339    }
340
341    let axes = try tree.enumerated().map { k, t -> AxisRecord in
342        let child = axisOfNode[t.ends.0] == k ? t.ends.0 : t.ends.1
343        let parent = parentNode[child].flatMap { axisOfNode[$0] }
344        let isNamed = t.edge == named[t.source]
345        let movingFaces = node.indices.filter { node[$0] == child }
346        let startAngle = start.edgesFoldAngle[t.edge]
347        let window = script.windows?[t.source]
348        let written = window == [0, 1] ? nil : window
349        func endAngle(_ list: [Double]?) throws -> Double {
350            if let list {
351                if isNamed { return list[t.source] }
352                if abs(list[t.source]) != 180 { throw CompileError.coincidentAxisAngle(step: n, edge: t.edge) }
353            }
354            switch finalAssignment[t.edge] {
355            case .valley: return 180
356            case .mountain: return -180
357            default: throw CompileError.missingAngle(step: n, crease: script.creases[t.source])
358            }
359        }
360        if script.kind == .foldAndUnfold {
361            return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle, endAngle: startAngle,
362                              peakAngle: try endAngle(script.peakAngles), parent: parent, window: written)
363        }
364        return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle,
365                          endAngle: try endAngle(script.angles), parent: parent, window: written)
366    }
367
368    var expected: [Int: Double] = [:]
369    if let angles = script.angles {
370        for (e, source) in creases where loops.contains(e) && e == named[source] {
371            expected[e] = angles[source]
372        }
373    }
374    return FoldPlan(axes: axes, creased: creased, loops: loops, expected: expected)
375}
376
377/// The edge a crease reference names: by index, or the edge whose endpoints in the crease
378/// pattern are nearest the named points, within 1e-6. Boundary edges are not creases.
379func resolve(_ ref: CreaseRef, _ file: FoldFile, _ edgeFaces: [[Int]]) -> Int? {
380    switch ref {
381    case .edgeIndex(let e):
382        return edgeFaces.indices.contains(e) && edgeFaces[e].count == 2 ? e : nil
383    case .betweenVertices(let p, let q):
384        let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
385        let nearest = file.edgesVertices.indices.map { e -> (edge: Int, distance: Double) in
386            let u = flat[file.edgesVertices[e][0]], v = flat[file.edgesVertices[e][1]]
387            return (e, min(max(distance(u, p), distance(v, q)), max(distance(u, q), distance(v, p))))
388        }.min { $0.distance < $1.distance }
389        guard let nearest, nearest.distance <= creaseMatchTolerance, edgeFaces[nearest.edge].count == 2 else {
390            return nil
391        }
392        return nearest.edge
393    }
394}
395
396/// The first face of the crease pattern whose closed outline contains `point`.
397func face(containing point: SIMD2<Double>, _ file: FoldFile) -> Int? {
398    let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
399    return file.facesVertices.indices.first { f in
400        let corners = file.facesVertices[f].map { flat[$0] }
401        return corners.indices.allSatisfy { i in
402            let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = point - a
403            return side.x * offset.y - side.y * offset.x >= 0
404        }
405    }
406}
407
408func onLine(_ p: SIMD3<Double>, _ a: SIMD3<Double>, _ b: SIMD3<Double>, _ tolerance: Double) -> Bool {
409    length(cross(p - a, normalize(b - a))) <= tolerance
410}
411
412/// The longer side of frame 0's bounding box.
413func sheetExtent(_ file: FoldFile) -> Double {
414    let points = file.frames[0].verticesCoords
415    let lower = points.dropFirst().reduce(points[0], simd_min)
416    let upper = points.dropFirst().reduce(points[0], simd_max)
417    return (upper - lower).max()
418}
419
420// MARK: - Loops
421
422/// Holds the driver (the first axis in `record`) linear on its window and solves the other axes
423/// on a loop's cycle, the tree path between the two sides of a loop crease, so the loops stay
424/// closed: damped Gauss–Newton on the gap between vertex copies, continued along the window from
425/// the previous samples. Where closure leaves the solved axes free, each sample is then moved
426/// toward the linear angles within those free directions (`LoopKinematics.settle`). Each solved
427/// axis takes the driver's window and a curve of 257 samples, or none when it is linear to within
428/// 1e-9°; the last sample is the end angle exactly. Axes on no cycle stay linear on their own
429/// windows.
430///
431/// - Throws: `solvedAxisWindowConflict` when a solved axis is scripted on another window.
432func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, loops: [Int],
433                _ file: FoldFile) throws -> StepRecord {
434    guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record }
435    let free = axesOnCycles(step, loops: loops, file).subtracting([driver]).sorted()
436    guard !free.isEmpty else { return record }
437    for a in free where step.axes[a].window != step.axes[driver].window {
438        throw CompileError.solvedAxisWindowConflict(step: n, edge: step.axes[a].edge)
439    }
440
441    let kinematics = LoopKinematics(step: step, file: file)
442    let tolerance = sheetExtent(file) * relativeTolerance
443    let fraction = { (k: Int) in Double(k) / Double(curveSamples - 1) }
444    func linear(_ axis: FoldAxis, _ u: Double) -> Double {
445        step.kind == .foldAndUnfold
446            ? axis.startAngle + ((axis.peakAngle ?? axis.endAngle) - axis.startAngle) * (1 - abs(2 * u - 1))
447            : axis.startAngle + u * (axis.endAngle - axis.startAngle)
448    }
449
450    var samples: [[Double]] = []
451    for k in 0..<curveSamples {
452        let u = fraction(k)
453        var guess = switch k {
454        case 0: step.axes.map(\.startAngle)
455        case 1: step.axes.map { linear($0, u) }
456        default: zip(samples[k - 1], samples[k - 2]).map { 2 * $0 - $1 }
457        }
458        guess[driver] = linear(step.axes[driver], u)
459        guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) }
460        kinematics.settle(&guess, toward: step.axes.map { linear($0, u) }, free: free, tolerance: tolerance)
461        samples.append(guess)
462    }
463
464    var axes = record.axes
465    for a in free {
466        let axis = step.axes[a]
467        var curve = samples.map { $0[a] }
468        curve[curveSamples - 1] = axis.endAngle
469        let isLinear = curve.indices.allSatisfy { abs(curve[$0] - linear(axis, fraction($0))) <= linearTolerance }
470        guard let i = axes.firstIndex(where: { $0.edge == axis.edge }) else { continue }
471        let r = axes[i]
472        axes[i] = AxisRecord(edge: r.edge, movingFaces: r.movingFaces, startAngle: r.startAngle,
473                             endAngle: r.endAngle, peakAngle: r.peakAngle, parent: r.parent,
474                             window: r.window,
475                             angles: isLinear ? nil : curve)
476    }
477    return StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
478                      axes: axes, rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis,
479                      repeatOf: record.repeatOf, nonRigid: record.nonRigid, pop: record.pop,
480                      viewpoint: record.viewpoint)
481}
482
483/// The indices in `step.axes` of the axes on some loop's cycle: the tree path between the two
484/// faces of a loop crease. A loop crease that lies on the line of every axis on its path, such as
485/// a collinear edge of one crease, is turned about its own line and closes for any angles, so it
486/// puts no axis on a cycle.
487func axesOnCycles(_ step: FoldStep, loops: [Int], _ file: FoldFile) -> Set<Int> {
488    var axisOfFace: [Int: Int] = [:]
489    for (a, axis) in step.axes.enumerated() {
490        for f in axis.movingFaces { axisOfFace[f] = a }
491    }
492    func carriers(_ f: Int) -> Set<Int> {
493        var result = Set<Int>(), a = axisOfFace[f]
494        while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent }
495        return result
496    }
497    let edgeFaces = edgesFaces(file)
498    let start = file.frames[step.index - 1].verticesCoords
499    let tolerance = sheetExtent(file) * relativeTolerance
500    return loops.reduce(into: Set<Int>()) { cycle, e in
501        let path = carriers(edgeFaces[e][0]).symmetricDifference(carriers(edgeFaces[e][1]))
502        let coaxial = path.allSatisfy { a in
503            file.edgesVertices[e].allSatisfy {
504                onLine(start[$0], step.axes[a].origin, step.axes[a].origin + step.axes[a].direction, tolerance)
505            }
506        }
507        if !coaxial { cycle.formUnion(path) }
508    }
509}
510
511/// Checks every axis's angle stays within ±180°, and a linear axis's within the range of its start,
512/// end and, for a fold-and-unfold, peak angles, to within 1e-6°, at four times the curve sample
513/// density over its window. A fold-and-unfold's end angle equals its start angle, so its range runs
514/// from the start to the peak. A solved curve may turn back within ±180°. A non-rigid step is
515/// checked on its pop's open and close axes, which are what move it.
516func checkTravel(_ n: Int, _ step: FoldStep) throws {
517    let moving = step.pop.map { ($0.openAxes + $0.closeAxes, StepKind.fold) } ?? (step.axes, step.kind)
518    let intervals = 4 * (curveSamples - 1)
519    for axis in moving.0 {
520        let scripted = [axis.startAngle, axis.endAngle]
521            + (moving.1 == .foldAndUnfold ? [axis.peakAngle ?? axis.endAngle] : [])
522        let linear = axis.curve == nil
523        let low = (linear ? max(scripted.min()!, -180) : -180) - angleSnapTolerance
524        let high = (linear ? min(scripted.max()!, 180) : 180) + angleSnapTolerance
525        let w = axis.window
526        for k in 0...intervals {
527            let angle = axis.angle(at: w.lowerBound + Double(k) / Double(intervals) * (w.upperBound - w.lowerBound),
528                                   kind: moving.1)
529            if angle < low || angle > high { throw CompileError.angleOutsideTravel(step: n, edge: axis.edge) }
530        }
531    }
532}
533
534/// Checks the step's loops stay closed as its axes move, at four times the curve sample density
535/// over the window of the axis on `driver` and over the whole step.
536func checkClosure(_ n: Int, _ step: FoldStep, driver: Int, _ file: FoldFile, solved: Bool) throws {
537    let kinematics = LoopKinematics(step: step, file: file)
538    let tolerance = sheetExtent(file) * relativeTolerance
539    let intervals = 4 * (curveSamples - 1)
540    let window = step.axes.first { $0.edge == driver }?.window ?? 0...1
541    let times = (0...intervals).flatMap { k -> [Double] in
542        let u = Double(k) / Double(intervals)
543        return [u, window.lowerBound + u * (window.upperBound - window.lowerBound)]
544    }
545    for t in times where kinematics.gap(step.axes.map { $0.angle(at: t, kind: step.kind) }) > tolerance {
546        throw solved ? CompileError.curveTooCoarse(step: n) : CompileError.noRigidMotion(step: n)
547    }
548}
549
550/// The end angle of each loop crease, measured from the faces' normals along the step and
551/// unwrapped from its start angle, then taken to be its scripted angle, ±180 or 0 when within
552/// 1e-6° of one.
553private func loopEndAngles(_ n: Int, _ plan: FoldPlan, _ previous: FoldFrame, _ interpolator: FoldInterpolator,
554                           _ file: FoldFile) throws -> [Int: Double] {
555    let edgeFaces = edgesFaces(file)
556    var current = Dictionary(uniqueKeysWithValues: plan.loops.map { ($0, previous.edgesFoldAngle[$0]) })
557    let intervals = curveSamples - 1
558    for k in 1...intervals {
559        let positions = interpolator.positions(at: Double(k) / Double(intervals))
560        let normals = faceNormals(positions: positions, faces: file.facesVertices)
561        for e in plan.loops {
562            let measured = dihedral(e, edgeFaces[e], positions, normals, file)
563            current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded()
564        }
565    }
566    var result: [Int: Double] = [:]
567    for (e, angle) in current {
568        let candidates = (plan.expected[e].map { [$0] } ?? []) + [180, -180, 0]
569        let snapped = candidates.first { abs(angle - $0) <= angleSnapTolerance } ?? angle
570        if let expected = plan.expected[e], snapped != expected { throw CompileError.noRigidMotion(step: n) }
571        result[e] = snapped
572    }
573    return result
574}
575
576/// The fold angle in degrees of an interior edge between faces `faces`, positive for a valley:
577/// the turn from the first face's normal to the second's about the edge, directed as the second
578/// face traverses it.
579func dihedral(_ e: Int, _ faces: [Int], _ positions: [SIMD3<Double>], _ normals: [SIMD3<Double>],
580              _ file: FoldFile) -> Double {
581    let corners = file.facesVertices[faces[1]], ends = Set(file.edgesVertices[e])
582    let i = corners.indices.first { ends == Set([corners[$0], corners[($0 + 1) % corners.count]]) }!
583    let d = normalize(positions[corners[(i + 1) % corners.count]] - positions[corners[i]])
584    let a = normals[faces[0]], b = normals[faces[1]]
585    return atan2(dot(cross(a, b), d), dot(a, b)) * 180 / .pi
586}
587
588/// p ↦ q·p + t
589private struct Rigid {
590    var q = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
591    var t = SIMD3<Double>.zero
592
593    func apply(_ p: SIMD3<Double>) -> SIMD3<Double> { q.act(p) + t }
594
595    /// This transform applied after `inner`.
596    func after(_ inner: Rigid) -> Rigid { Rigid(q: q * inner.q, t: q.act(inner.t) + t) }
597
598    static func rotation(about origin: SIMD3<Double>, direction: SIMD3<Double>, degrees: Double) -> Rigid {
599        let q = simd_quatd(angle: degrees * .pi / 180, axis: direction)
600        return Rigid(q: q, t: origin - q.act(origin))
601    }
602}
603
604/// A step's axes as functions of their angles, and the gap between the copies of each vertex
605/// that faces moving with different axes carry.
606struct LoopKinematics {
607    let axes: [FoldAxis]
608    let start: [SIMD3<Double>]
609    /// Each vertex shared by faces that move differently, with the axes that move them, −1 for
610    /// a still face.
611    let copies: [(vertex: Int, axes: [Int])]
612
613    init(step: FoldStep, file: FoldFile) {
614        axes = step.axes
615        start = file.frames[step.index - 1].verticesCoords
616        var axisOfFace = Array(repeating: -1, count: file.facesVertices.count)
617        for (a, axis) in step.axes.enumerated() {
618            for f in axis.movingFaces { axisOfFace[f] = a }
619        }
620        var movers = Array(repeating: [Int](), count: start.count)
621        for (f, corners) in file.facesVertices.enumerated() {
622            for v in corners where !movers[v].contains(axisOfFace[f]) { movers[v].append(axisOfFace[f]) }
623        }
624        copies = movers.indices.filter { movers[$0].count > 1 }.map { ($0, movers[$0]) }
625    }
626
627    func residual(_ angles: [Double]) -> [Double] {
628        var full: [Rigid] = []
629        for (a, axis) in axes.enumerated() {
630            let own = Rigid.rotation(about: axis.origin, direction: axis.direction,
631                                     degrees: angles[a] - axis.startAngle)
632            full.append(axis.parent.map { full[$0].after(own) } ?? own)
633        }
634        func place(_ a: Int, _ p: SIMD3<Double>) -> SIMD3<Double> { a < 0 ? p : full[a].apply(p) }
635        var r: [Double] = []
636        for (v, movers) in copies {
637            let base = place(movers[0], start[v])
638            for a in movers.dropFirst() {
639                let d = place(a, start[v]) - base
640                r += [d.x, d.y, d.z]
641            }
642        }
643        return r
644    }
645
646    /// The largest distance between two copies of one vertex.
647    func gap(_ angles: [Double]) -> Double {
648        let r = residual(angles)
649        return stride(from: 0, to: r.count, by: 3).map { length(SIMD3(r[$0], r[$0 + 1], r[$0 + 2])) }.max() ?? 0
650    }
651
652    /// Damped Gauss–Newton on the angles of the axes in `free`, holding the rest. Returns the gap
653    /// it reaches.
654    func solve(_ angles: inout [Double], free: [Int], iterations: Int = 60) -> Double {
655        var lambda = 1e-6
656        var r = residual(angles)
657        var cost = r.reduce(0) { $0 + $1 * $1 }
658        for _ in 0..<iterations {
659            if cost < 1e-26 { break }
660            let jacobian = self.jacobian(angles, free: free)
661            var improved = false
662            for _ in 0..<20 {
663                var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count)
664                var gradient = [Double](repeating: 0, count: free.count)
665                for i in r.indices {
666                    for a in free.indices {
667                        gradient[a] -= jacobian[i][a] * r[i]
668                        for b in free.indices { normal[a][b] += jacobian[i][a] * jacobian[i][b] }
669                    }
670                }
671                for a in free.indices { normal[a][a] += lambda * (1 + normal[a][a]) }
672                guard let delta = solveLinear(normal, gradient) else {
673                    lambda *= 10
674                    continue
675                }
676                var trial = angles
677                for (k, a) in free.enumerated() { trial[a] += delta[k] }
678                let rt = residual(trial)
679                let ct = rt.reduce(0) { $0 + $1 * $1 }
680                if ct < cost {
681                    angles = trial
682                    r = rt
683                    cost = ct
684                    lambda = max(lambda / 10, 1e-12)
685                    improved = true
686                    break
687                }
688                lambda *= 10
689            }
690            if !improved { break }
691        }
692        return gap(angles)
693    }
694
695    /// The residual's derivatives by the angles in `free`, by central differences: one row per
696    /// residual entry, one column per free axis.
697    func jacobian(_ angles: [Double], free: [Int]) -> [[Double]] {
698        let h = 1e-6
699        var jacobian: [[Double]] = []
700        for (k, a) in free.enumerated() {
701            var probe = angles
702            probe[a] += h
703            let plus = residual(probe)
704            probe[a] -= 2 * h
705            let minus = residual(probe)
706            if k == 0 { jacobian = Array(repeating: [Double](repeating: 0, count: free.count), count: plus.count) }
707            for i in plus.indices { jacobian[i][k] = (plus[i] - minus[i]) / (2 * h) }
708        }
709        return jacobian
710    }
711
712    /// Moves the angles in `free` toward `target` within the null space of the closure Jacobian J,
713    /// by δ = ε(JᵀJ + εI)⁻¹(target − angles) three times, then solves again. ε is 1e-6 of JᵀJ's
714    /// largest eigenvalue, so δ takes the null space's part of the difference and almost none of
715    /// the rest. When JᵀJ has no eigenvalue below 1e-10 of its largest (closure fixes every free
716    /// axis, as at a vertex with one degree of freedom) or the solve does not close to `tolerance`,
717    /// `angles` is left as it was.
718    func settle(_ angles: inout [Double], toward target: [Double], free: [Int], tolerance: Double) {
719        var x = angles
720        for _ in 0..<3 {
721            let j = jacobian(x, free: free)
722            var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count)
723            for row in j {
724                for a in free.indices {
725                    for b in free.indices { normal[a][b] += row[a] * row[b] }
726                }
727            }
728            let (values, vectors) = symmetricEigen(normal)
729            guard let largest = values.max(), largest > 0, values.contains(where: { $0 < 1e-10 * largest }) else { return }
730            let epsilon = 1e-6 * largest
731            let difference = free.map { target[$0] - x[$0] }
732            for (value, vector) in zip(values, vectors) {
733                let along = zip(vector, difference).reduce(0) { $0 + $1.0 * $1.1 } * epsilon / (value + epsilon)
734                for (k, a) in free.enumerated() { x[a] += along * vector[k] }
735            }
736        }
737        guard solve(&x, free: free) <= tolerance else { return }
738        angles = x
739    }
740}
741
742/// The eigenvalues of a symmetric matrix and a unit eigenvector for each, by cyclic Jacobi
743/// rotations.
744private func symmetricEigen(_ matrix: [[Double]]) -> (values: [Double], vectors: [[Double]]) {
745    let n = matrix.count
746    var a = matrix
747    var v = (0..<n).map { i in (0..<n).map { $0 == i ? 1.0 : 0.0 } }
748    for _ in 0..<100 {
749        var off = 0.0
750        for p in 0..<n { for q in (p + 1)..<n { off += a[p][q] * a[p][q] } }
751        let scale = (0..<n).reduce(0) { $0 + a[$1][$1] * a[$1][$1] }
752        if off <= 1e-30 * scale { break }
753        for p in 0..<n {
754            for q in (p + 1)..<n where a[p][q] != 0 {
755                let theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
756                let t = (theta >= 0 ? 1.0 : -1.0) / (abs(theta) + (theta * theta + 1).squareRoot())
757                let c = 1 / (t * t + 1).squareRoot(), s = t * c
758                for k in 0..<n {
759                    let (akp, akq) = (a[k][p], a[k][q])
760                    a[k][p] = c * akp - s * akq
761                    a[k][q] = s * akp + c * akq
762                }
763                for k in 0..<n {
764                    let (apk, aqk) = (a[p][k], a[q][k])
765                    a[p][k] = c * apk - s * aqk
766                    a[q][k] = s * apk + c * aqk
767                }
768                for k in 0..<n {
769                    let (vkp, vkq) = (v[k][p], v[k][q])
770                    v[k][p] = c * vkp - s * vkq
771                    v[k][q] = s * vkp + c * vkq
772                }
773            }
774        }
775    }
776    return ((0..<n).map { a[$0][$0] }, (0..<n).map { i in (0..<n).map { v[$0][i] } })
777}
778
779/// Gaussian elimination with partial pivoting; nil when `a` is singular.
780private func solveLinear(_ a: [[Double]], _ b: [Double]) -> [Double]? {
781    var m = a, x = b
782    let n = b.count
783    for c in 0..<n {
784        guard let p = (c..<n).max(by: { abs(m[$0][c]) < abs(m[$1][c]) }), abs(m[p][c]) > 1e-300 else { return nil }
785        m.swapAt(c, p)
786        x.swapAt(c, p)
787        for r in (c + 1)..<n {
788            let f = m[r][c] / m[c][c]
789            if f == 0 { continue }
790            for k in c..<n { m[r][k] -= f * m[c][k] }
791            x[r] -= f * x[c]
792        }
793    }
794    for c in stride(from: n - 1, through: 0, by: -1) {
795        var s = x[c]
796        for k in (c + 1)..<n { s -= m[c][k] * x[k] }
797        x[c] = s / m[c][c]
798    }
799    return x
800}