import simd public enum FoldDefect: Equatable, Sendable { case vertexIndexOutOfRange(edge: Int) case faceVertexOutOfRange(face: Int) case vertexCountChanged(frame: Int) case foldAngleOutOfRange(frame: Int, edge: Int, degrees: Double) case foldAngleSignDisagreesWithAssignment(frame: Int, edge: Int) case boundaryEdgeFolded(frame: Int, edge: Int) case faceOrderNotAntisymmetric(frame: Int, f: Int, g: Int) case cyclicFaceOrder(frame: Int, cycle: [Int]) case nonIsometricTransition(step: Int, edge: Int, from: Double, to: Double) case overlappingMovingSetsWithoutMidFoldOrder(step: Int) case startAndEndOrderDisagreeOnStillFaces(step: Int, f: Int, g: Int) case foldAndUnfoldWithoutPeakOrder(step: Int) case orderDisagreesWithCrease(frame: Int, edge: Int) case interleavedFolds(frame: Int, edges: [Int]) case faceInsideFold(frame: Int, face: Int, edge: Int) case nonConvexFace(face: Int) case missingInstruction(step: Int) case authorNotTraditional(String?) case missingFirstCreasedAtStep(edge: Int) case faceDistorted(frame: Int, face: Int) /// A non-rigid step without a pop, or a pop whose `popped` lacks a position per vertex or /// whose phases are not 0 < p0 < p1 < 1. case popMalformed(step: Int) /// In step `step`, the face `moving` departs toward the still face `still` it overlaps in /// frame n − 1, or arrives from the side of it opposite the one frame n's order gives. case movesThroughStillFace(step: Int, moving: Int, still: Int) /// Step `step`'s viewpoint has an `eye` or `up` of zero length, or an `up` along its `eye`, so /// it names no screen-up. case viewpointDegenerate(step: Int) } /// Lengths are compared to within this fraction of the sheet's longer side. private let relativeTolerance = 1e-6 /// A crease within this many degrees of ±180 is folded flat. private let flatAngleTolerance = 1e-6 /// Two unit normals whose dot product's magnitude reaches this lie on one line. private let parallelCosine = 1 - 1e-9 /// A normal component smaller than this is treated as zero when choosing the canonical normal. private let canonicalComponentThreshold = 1e-6 public func validate(_ file: FoldFile) -> [FoldDefect] { var defects: [FoldDefect] = [] let vertexCount = file.frames[0].verticesCoords.count let inRange = { (v: Int) in v >= 0 && v < vertexCount } for (e, ends) in file.edgesVertices.enumerated() where ends.count != 2 || !ends.allSatisfy(inRange) { defects.append(.vertexIndexOutOfRange(edge: e)) } for (f, corners) in file.facesVertices.enumerated() where !corners.allSatisfy(inRange) { defects.append(.faceVertexOutOfRange(face: f)) } let topologyIsSound = defects.isEmpty if file.fileAuthor != "Traditional" { defects.append(.authorNotTraditional(file.fileAuthor)) } for n in file.frames.indices.dropFirst() { let instruction = file.frames[n].step?.instruction ?? "" if instruction.allSatisfy(\.isWhitespace) { defects.append(.missingInstruction(step: n)) } } guard topologyIsSound else { return defects } let tolerance = sheetSize(file) * relativeTolerance let edgeFaces = edgesFaces(file) defects += nonConvexFaces(file) defects += missingFirstCreasedAtStep(file, edgeFaces: edgeFaces) var geometryIsSound: [Bool] = [] for (n, frame) in file.frames.enumerated() { let sound = frame.verticesCoords.count == vertexCount geometryIsSound.append(sound) if !sound { defects.append(.vertexCountChanged(frame: n)) } defects += angleDefects(frame, n, edgeCount: file.edgesVertices.count) if sound { defects += layerOrderDefects(frame, n, file, edgeFaces: edgeFaces, tolerance: tolerance) defects += faceShapeDefects(frame, n, file, tolerance: tolerance) } } for n in file.frames.indices.dropFirst() { guard let step = file.frames[n].step else { continue } let frame = file.frames[n] if step.kind == .foldAndUnfold && frame.faceOrdersMidFold == nil { defects.append(.foldAndUnfoldWithoutPeakOrder(step: n)) } let eye = step.viewpoint.eye, up = step.viewpoint.up let viewpointIsSound = length(eye) > 0 && length(up) > 0 && abs(dot(normalize(eye), normalize(up))) < parallelCosine if !viewpointIsSound { defects.append(.viewpointDegenerate(step: n)) } if step.nonRigid || step.pop != nil { let wellFormed = step.pop.map { pop in pop.popped.count == vertexCount && pop.phases.count == 2 && 0 < pop.phases[0] && pop.phases[0] < pop.phases[1] && pop.phases[1] < 1 } ?? false if !wellFormed { defects.append(.popMalformed(step: n)) } } guard geometryIsSound[n - 1] && geometryIsSound[n] else { continue } if viewpointIsSound && frame.faceOrdersMidFold == nil && movingSetsOverlapInProjection(step: n, file) { defects.append(.overlappingMovingSetsWithoutMidFoldOrder(step: n)) } defects += isometryDefects(file, step: n, tolerance: tolerance) defects += stillFaceDefects(file, step: n, moving: Set(step.axes.flatMap(\.movingFaces))) } return defects } /// Whether two of step `n`'s moving sets overlap in projection along the step's viewpoint, with /// both sets where they arrive, in frame `n`. public func movingSetsOverlapInProjection(step n: Int, _ file: FoldFile) -> Bool { guard n >= 1, n < file.frames.count, let step = file.frames[n].step, step.axes.count > 1 else { return false } let points = file.frames[n].verticesCoords let eye = normalize(step.viewpoint.eye) let right = normalize(cross(step.viewpoint.up, eye)) let up = cross(eye, right) let tolerance = sheetSize(file) * relativeTolerance func outline(_ face: Int) -> [SIMD2]? { guard face >= 0, face < file.facesVertices.count else { return nil } let corners = file.facesVertices[face] guard corners.allSatisfy({ $0 >= 0 && $0 < points.count }) else { return nil } return corners.map { SIMD2(dot(points[$0], right), dot(points[$0], up)) } } let sets = step.axes.map { axis in axis.movingFaces.compactMap { face in outline(face).map { (face, $0) } } } for i in sets.indices { for j in sets.indices where j > i { for (a, p) in sets[i] { for (b, q) in sets[j] where a != b && convexPolygonsOverlap(p, q, tolerance: tolerance) { return true } } } } return false } /// Each face's unit normal in `frame`, from the counterclockwise order of `faces_vertices`. /// A degenerate face, or one naming a vertex the frame lacks, has a zero normal. public func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3] { faceNormals(positions: frame.verticesCoords, faces: file.facesVertices) } /// Each face's unit normal with its vertices at `positions`, from the counterclockwise order of /// `faces`. A degenerate face, or one naming a vertex `positions` lacks, has a zero normal. public func faceNormals(positions: [SIMD3], faces: [[Int]]) -> [SIMD3] { faces.map { corners in guard corners.allSatisfy({ $0 >= 0 && $0 < positions.count }) else { return .zero } let n = newellNormal(corners.map { positions[$0] }) let size = length(n) return size > 0 ? n / size : .zero } } /// The faces on each side of each edge, from consecutive corners of `faces_vertices`. An edge /// without two ends has none. public func edgesFaces(_ file: FoldFile) -> [[Int]] { var byEnds: [SIMD2: [Int]] = [:] for (f, corners) in file.facesVertices.enumerated() { for i in corners.indices { let u = corners[i], v = corners[(i + 1) % corners.count] byEnds[SIMD2(min(u, v), max(u, v)), default: []].append(f) } } return file.edgesVertices.map { ends in guard ends.count == 2 else { return [] } return byEnds[SIMD2(min(ends[0], ends[1]), max(ends[0], ends[1]))] ?? [] } } /// Each triple `[f, g, s]` with `s ≠ 0` as a pair ordered along the canonical normal of the two /// faces' common plane, the one of `g`'s normal and its negation whose first nonzero component is /// positive. Triples with `s = 0`, a repeated face or a face outside `normals` are skipped. public func normalisedFaceOrders(_ orders: [[Int]], normals: [SIMD3]) -> [(below: Int, above: Int)] { validTriples(orders, faceCount: normals.count).map { f, g, s in let ng = normals[g] let fAbove = dot(ng, canonical(ng)) > 0 ? s > 0 : s < 0 return fAbove ? (below: g, above: f) : (below: f, above: g) } } /// Each triple `[f, g, s]` with `s ≠ 0` in a form that a rigid motion of both faces together leaves /// unchanged: rewritten with the lower face first, `s` negated when swapping two faces whose /// normals agree (the spec's rule for a reverse triple). Triples with `s = 0`, a repeated face or /// a face outside `normals` are skipped. public func rigidInvariantFaceOrders(_ orders: [[Int]], normals: [SIMD3]) -> [(pair: SIMD2, s: Int)] { validTriples(orders, faceCount: normals.count).map { f, g, s in if f < g { return (SIMD2(f, g), s) } return (SIMD2(g, f), dot(normals[f], normals[g]) > 0 ? -s : s) } } /// A cycle in the stacking relation `pairs` over faces `0.. [Int]? { guard let cycle = firstCycle(stackingGraph(pairs, faceCount: faceCount)), let start = cycle.indices.min(by: { cycle[$0] < cycle[$1] }) else { return nil } return Array(cycle[start...] + cycle[..], _ q: [SIMD2], tolerance: Double) -> Bool { var tested = false for polygon in [p, q] { for i in polygon.indices { let edge = polygon[(i + 1) % polygon.count] - polygon[i] guard length(edge) > tolerance else { continue } let axis = normalize(SIMD2(-edge.y, edge.x)) let a = p.map { dot($0, axis) }, b = q.map { dot($0, axis) } guard let aMin = a.min(), let aMax = a.max(), let bMin = b.min(), let bMax = b.max() else { return false } if min(aMax, bMax) - max(aMin, bMin) <= tolerance { return false } tested = true } } return tested } // MARK: - File-level rules private func sheetSize(_ file: FoldFile) -> Double { let points = file.frames[0].verticesCoords guard let first = points.first else { return 0 } let low = points.reduce(first) { simd_min($0, $1) } let high = points.reduce(first) { simd_max($0, $1) } return (high - low).max() } private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] { let points = file.frames[0].verticesCoords var defects: [FoldDefect] = [] for (f, corners) in file.facesVertices.enumerated() { let polygon = corners.map { points[$0] } let n = newellNormal(polygon) guard length(n) > 0 else { continue } let count = polygon.count let reflex = polygon.indices.contains { i in let into = polygon[i] - polygon[(i + count - 1) % count] let out = polygon[(i + 1) % count] - polygon[i] guard length(into) > 0, length(out) > 0 else { return false } return dot(cross(normalize(into), normalize(out)), normalize(n)) < -1e-9 } if reflex { defects.append(.nonConvexFace(face: f)) } } return defects } /// A non-boundary edge without `edges_krz:firstCreasedAtStep` is a defect unless it is a /// subdivision edge: `F` and flat in every frame, and creased by no step. private func missingFirstCreasedAtStep(_ file: FoldFile, edgeFaces: [[Int]]) -> [FoldDefect] { let creased = creasedEdges(file, edgeFaces: edgeFaces) return file.edgesVertices.indices.compactMap { e in let assignment = file.frames[0].edgesAssignment guard e < assignment.count, assignment[e] != .boundary else { return nil } if e < file.edgesFirstCreasedAtStep.count, file.edgesFirstCreasedAtStep[e] != nil { return nil } let subdivision = !creased.contains(e) && file.frames.allSatisfy { frame in e < frame.edgesAssignment.count && e < frame.edgesFoldAngle.count && frame.edgesAssignment[e] == .flat && frame.edgesFoldAngle[e] == 0 } return subdivision ? nil : .missingFirstCreasedAtStep(edge: e) } } /// The edges some step creases: those whose two faces the step moves differently. In each of a /// step's axis lists (`axes`, and a pop's `openAxes` and `closeAxes`), a face moves with the /// deepest axis whose `movingFaces` contains it, or stays fixed when none does. A pop does not /// crease its spine's edges: each was folded flat before the step or is a bend line, which bends /// while the flap is open and flattens again (decision 0003). private func creasedEdges(_ file: FoldFile, edgeFaces: [[Int]]) -> Set { let lists: [(axes: [AxisRecord], spine: Set)] = file.frames.compactMap(\.step).flatMap { step in [(step.axes, [])] + (step.pop.map { [($0.openAxes, Set($0.spine)), ($0.closeAxes, Set($0.spine))] } ?? []) } let groupings = lists.map { (groups: movementGroups($0.axes), spine: $0.spine) } return Set(edgeFaces.indices.filter { e in let faces = edgeFaces[e] return faces.count == 2 && groupings.contains { !$0.spine.contains(e) && $0.groups[faces[0]] != $0.groups[faces[1]] } }) } /// Each moved face's axis: the deepest in the parent tree whose `movingFaces` contains it, the /// first listed among equals. A face absent from the result is fixed. private func movementGroups(_ axes: [AxisRecord]) -> [Int: Int] { func depth(_ i: Int) -> Int { var d = 0, j = i while d < axes.count, let p = axes[j].parent, axes.indices.contains(p) { d += 1 j = p } return d } var group: [Int: (axis: Int, depth: Int)] = [:] for (i, axis) in axes.enumerated() { let d = depth(i) for f in axis.movingFaces where group[f].map({ d > $0.depth }) ?? true { group[f] = (i, d) } } return group.mapValues(\.axis) } // MARK: - Frame rules /// Every pair of a face's vertices must be as far apart as in frame 0. private func faceShapeDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, tolerance: Double) -> [FoldDefect] { let flat = file.frames[0].verticesCoords, points = frame.verticesCoords return file.facesVertices.indices.compactMap { f in let corners = file.facesVertices[f] let distorted = corners.indices.contains { i in corners[(i + 1)...].contains { v in let u = corners[i] return abs(distance(points[u], points[v]) - distance(flat[u], flat[v])) > tolerance } } return distorted ? .faceDistorted(frame: n, face: f) : nil } } private func angleDefects(_ frame: FoldFrame, _ n: Int, edgeCount: Int) -> [FoldDefect] { var defects: [FoldDefect] = [] for e in 0.. 180 { defects.append(.foldAngleOutOfRange(frame: n, edge: e, degrees: angle)) } switch frame.edgesAssignment[e] { case .boundary: if angle != 0 { defects.append(.boundaryEdgeFolded(frame: n, edge: e)) } case .valley: if !(angle > 0) { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) } case .mountain: if !(angle < 0) { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) } case .flat, .unassigned: if angle != 0 { defects.append(.foldAngleSignDisagreesWithAssignment(frame: n, edge: e)) } } } return defects } /// Antisymmetry, cycles, and the crease, nesting and inside rules over the frame's `faceOrders`. private func layerOrderDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, edgeFaces: [[Int]], tolerance: Double) -> [FoldDefect] { var defects: [FoldDefect] = [] let normals = faceNormals(frame, file) let faceCount = file.facesVertices.count var signs: [SIMD2: Int] = [:] var reported: Set> = [] for (f, g, s) in validTriples(frame.faceOrders, faceCount: faceCount) { if let t = signs[SIMD2(g, f)] { let expected = dot(normals[f], normals[g]) > 0 ? -t : t if s != expected && reported.insert(SIMD2(min(f, g), max(f, g))).inserted { defects.append(.faceOrderNotAntisymmetric(frame: n, f: f, g: g)) } } signs[SIMD2(f, g)] = s } let pairs = normalisedFaceOrders(frame.faceOrders, normals: normals) if let cycle = faceOrderCycle(pairs, faceCount: faceCount) { defects.append(.cyclicFaceOrder(frame: n, cycle: cycle)) } let graph = stackingGraph(pairs, faceCount: faceCount) // isAbove[x][y]: y lies above x in the stack, directly or through other faces let isAbove = reachability(graph) let geometry = FrameGeometry(points: frame.verticesCoords, faces: file.facesVertices, normals: normals, tolerance: tolerance) let edgeCount = min(file.edgesVertices.count, frame.edgesAssignment.count, frame.edgesFoldAngle.count) let flatCreases = (0.. 0) let (below, above) = gAbove ? (f, g) : (g, f) if isAbove[above][below] { defects.append(.orderDisagreesWithCrease(frame: n, edge: e)) } } // nesting: the face pairs of two coincident creases nest or are disjoint in the stack for (i, e1) in flatCreases.enumerated() { for e2 in flatCreases[(i + 1)...] { let pair1 = edgeFaces[e1], pair2 = edgeFaces[e2] let four = pair1 + pair2 guard Set(four).count == 4, four.allSatisfy({ geometry.coplanar($0, pair1[0]) }), geometry.segmentsCoincide(file.edgesVertices[e1], file.edgesVertices[e2]), geometry.onSameSide(of: file.edgesVertices[e1], pair1[0], pair2[0]) else { continue } let determined = four.allSatisfy { x in four.allSatisfy { y in x == y || isAbove[x][y] || isAbove[y][x] } } guard determined else { continue } let rank = { (x: Int) in four.filter { isAbove[$0][x] }.count } let (p, q) = (min(rank(pair1[0]), rank(pair1[1])), max(rank(pair1[0]), rank(pair1[1]))) let (r, s) = (min(rank(pair2[0]), rank(pair2[1])), max(rank(pair2[0]), rank(pair2[1]))) if (p < r && r < q && q < s) || (r < p && p < s && s < q) { defects.append(.interleavedFolds(frame: n, edges: [e1, e2])) } } } // inside: a face whose interior the crease runs through cannot lie between the crease's faces for e in flatCreases { let a = edgeFaces[e][0], b = edgeFaces[e][1] for h in 0.. [FoldDefect] { let before = file.frames[n - 1].verticesCoords, after = file.frames[n].verticesCoords return file.edgesVertices.enumerated().compactMap { e, ends in let from = distance(before[ends[0]], before[ends[1]]) let to = distance(after[ends[0]], after[ends[1]]) return abs(to - from) > tolerance ? .nonIsometricTransition(step: n, edge: e, from: from, to: to) : nil } } /// Frame n − 1 and frame n must order every pair of faces that step n leaves still the same way, /// compared with `rigidInvariantFaceOrders`. private func stillFaceDefects(_ file: FoldFile, step n: Int, moving: Set) -> [FoldDefect] { func relations(_ frame: FoldFrame) -> [(pair: SIMD2, s: Int)] { rigidInvariantFaceOrders(frame.faceOrders, normals: faceNormals(frame, file)) .filter { !moving.contains($0.pair[0]) && !moving.contains($0.pair[1]) } } var after: [SIMD2: Int] = [:] for (pair, s) in relations(file.frames[n]) where after[pair] == nil { after[pair] = s } var reported: Set> = [] var defects: [FoldDefect] = [] for (pair, s) in relations(file.frames[n - 1]) { if let t = after[pair], t != s, reported.insert(pair).inserted { defects.append(.startAndEndOrderDisagreeOnStillFaces(step: n, f: pair[0], g: pair[1])) } } return defects } // MARK: - Helpers private func validTriples(_ orders: [[Int]], faceCount: Int) -> [(Int, Int, Int)] { orders.compactMap { t in guard t.count == 3 else { return nil } let (f, g, s) = (t[0], t[1], t[2]) guard f >= 0, f < faceCount, g >= 0, g < faceCount, f != g, s == 1 || s == -1 else { return nil } return (f, g, s) } } /// `n` or `-n`, whichever has its first nonzero component positive. private func canonical(_ n: SIMD3) -> SIMD3 { for i in 0..<3 where abs(n[i]) > canonicalComponentThreshold { return n[i] > 0 ? n : -n } return n } private func newellNormal(_ polygon: [SIMD3]) -> SIMD3 { var n = SIMD3.zero for i in polygon.indices { let p = polygon[i], q = polygon[(i + 1) % polygon.count] n.x += (p.y - q.y) * (p.z + q.z) n.y += (p.z - q.z) * (p.x + q.x) n.z += (p.x - q.x) * (p.y + q.y) } return n } /// The first cycle a depth-first search of the below → above graph meets, as the faces along it, /// each above the next. private func firstCycle(_ graph: [[Int]]) -> [Int]? { var state = Array(repeating: 0, count: graph.count) // 0 unvisited, 1 on the path, 2 finished var path: [Int] = [] func visit(_ u: Int) -> [Int]? { state[u] = 1 path.append(u) for v in graph[u] { if state[v] == 1, let start = path.lastIndex(of: v) { return Array(path[start...].reversed()) } if state[v] == 0, let cycle = visit(v) { return cycle } } path.removeLast() state[u] = 2 return nil } for u in graph.indices where state[u] == 0 { if let cycle = visit(u) { return cycle } } return nil } /// For each face, the faces directly above it, in index order. private func stackingGraph(_ pairs: [(below: Int, above: Int)], faceCount: Int) -> [[Int]] { var aboveOf = Array(repeating: Set(), count: faceCount) for pair in pairs where (0.. [[Bool]] { graph.indices.map { start in var seen = Array(repeating: false, count: graph.count) var stack = graph[start] while let u = stack.popLast() { if seen[u] { continue } seen[u] = true stack += graph[u] } return seen } } private struct FrameGeometry { let points: [SIMD3] let faces: [[Int]] let normals: [SIMD3] let tolerance: Double func centroid(_ f: Int) -> SIMD3 { faces[f].reduce(.zero) { $0 + points[$1] } / Double(max(faces[f].count, 1)) } func coplanar(_ f: Int, _ g: Int) -> Bool { abs(dot(normals[f], normals[g])) >= parallelCosine && abs(dot(centroid(g) - centroid(f), normals[f])) <= tolerance } /// Whether two edges lie on one line and share a stretch longer than `tolerance`. func segmentsCoincide(_ e1: [Int], _ e2: [Int]) -> Bool { let a = points[e1[0]], b = points[e1[1]] let span = length(b - a) guard span > tolerance else { return false } let direction = (b - a) / span let along = e2.map { dot(points[$0] - a, direction) } let offLine = e2.contains { v in let d = points[v] - a return length(d - dot(d, direction) * direction) > tolerance } guard !offLine else { return false } return min(along.max()!, span) - max(along.min()!, 0) > tolerance } /// Whether faces `f` and `g` lie on the same side of the line through `edge`, within their plane. func onSameSide(of edge: [Int], _ f: Int, _ g: Int) -> Bool { let a = points[edge[0]] let across = cross(normals[f], points[edge[1]] - a) return dot(centroid(f) - a, across) * dot(centroid(g) - a, across) > 0 } /// Whether the segment `edge` runs through the interior of face `h` for longer than `tolerance`. func segmentCrossesInterior(_ edge: [Int], face h: Int) -> Bool { let a = points[edge[0]], b = points[edge[1]] let polygon = faces[h].map { points[$0] } let n = normals[h] guard let corner = polygon.first, abs(dot(a - corner, n)) <= tolerance, abs(dot(b - corner, n)) <= tolerance else { return false } let d = b - a var (t0, t1) = (0.0, 1.0) for i in polygon.indices { let p = polygon[i], side = polygon[(i + 1) % polygon.count] - p guard length(side) > tolerance else { continue } // counterclockwise about n, so cross(n, side) points inward; keep points deeper than tolerance let inward = normalize(cross(n, side)) let start = dot(a - p, inward) - tolerance, rate = dot(d, inward) if rate == 0 { if start < 0 { return false } continue } let t = -start / rate if rate > 0 { t0 = max(t0, t) } else { t1 = min(t1, t) } if t0 >= t1 { return false } } return (t1 - t0) * length(d) > tolerance } }