Commit 44618d4ea0
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +85 −24
| @@ -20,6 +20,7 @@ public enum FoldDefect: Equatable, Sendable { | ||
| 20 | 20 | case missingInstruction(step: Int) |
| 21 | 21 | case authorNotTraditional(String?) |
| 22 | 22 | case missingFirstCreasedAtStep(edge: Int) |
| 23 | case faceDistorted(frame: Int, face: Int) | |
| 23 | 24 | } |
| 24 | 25 | |
| 25 | 26 | /// Lengths are compared to within this fraction of the sheet's longer side. |
| @@ -57,7 +58,7 @@ public func validate(_ file: FoldFile) -> [FoldDefect] { | ||
| 57 | 58 | let tolerance = sheetSize(file) * relativeTolerance |
| 58 | 59 | let edgeFaces = edgesFaces(file) |
| 59 | 60 | defects += nonConvexFaces(file) |
| 60 | defects += missingFirstCreasedAtStep(file) | |
| 61 | defects += missingFirstCreasedAtStep(file, edgeFaces: edgeFaces) | |
| 61 | 62 | |
| 62 | 63 | var geometryIsSound: [Bool] = [] |
| 63 | 64 | for (n, frame) in file.frames.enumerated() { |
| @@ -67,6 +68,7 @@ public func validate(_ file: FoldFile) -> [FoldDefect] { | ||
| 67 | 68 | defects += angleDefects(frame, n, edgeCount: file.edgesVertices.count) |
| 68 | 69 | if sound { |
| 69 | 70 | defects += layerOrderDefects(frame, n, file, edgeFaces: edgeFaces, tolerance: tolerance) |
| 71 | defects += faceShapeDefects(frame, n, file, tolerance: tolerance) | |
| 70 | 72 | } |
| 71 | 73 | } |
| 72 | 74 | |
| @@ -121,14 +123,36 @@ public func movingSetsOverlapInProjection(step n: Int, _ file: FoldFile) -> Bool | ||
| 121 | 123 | /// Each face's unit normal in `frame`, from the counterclockwise order of `faces_vertices`. |
| 122 | 124 | /// A degenerate face, or one naming a vertex the frame lacks, has a zero normal. |
| 123 | 125 | public func faceNormals(_ frame: FoldFrame, _ file: FoldFile) -> [SIMD3<Double>] { |
| 124 | file.facesVertices.map { corners in | |
| 125 | guard corners.allSatisfy({ $0 >= 0 && $0 < frame.verticesCoords.count }) else { return .zero } | |
| 126 | let n = newellNormal(corners.map { frame.verticesCoords[$0] }) | |
| 126 | faceNormals(positions: frame.verticesCoords, faces: file.facesVertices) | |
| 127 | } | |
| 128 | ||
| 129 | /// Each face's unit normal with its vertices at `positions`, from the counterclockwise order of | |
| 130 | /// `faces`. A degenerate face, or one naming a vertex `positions` lacks, has a zero normal. | |
| 131 | public func faceNormals(positions: [SIMD3<Double>], faces: [[Int]]) -> [SIMD3<Double>] { | |
| 132 | faces.map { corners in | |
| 133 | guard corners.allSatisfy({ $0 >= 0 && $0 < positions.count }) else { return .zero } | |
| 134 | let n = newellNormal(corners.map { positions[$0] }) | |
| 127 | 135 | let size = length(n) |
| 128 | 136 | return size > 0 ? n / size : .zero |
| 129 | 137 | } |
| 130 | 138 | } |
| 131 | 139 | |
| 140 | /// The faces on each side of each edge, from consecutive corners of `faces_vertices`. An edge | |
| 141 | /// without two ends has none. | |
| 142 | public func edgesFaces(_ file: FoldFile) -> [[Int]] { | |
| 143 | var byEnds: [SIMD2<Int>: [Int]] = [:] | |
| 144 | for (f, corners) in file.facesVertices.enumerated() { | |
| 145 | for i in corners.indices { | |
| 146 | let u = corners[i], v = corners[(i + 1) % corners.count] | |
| 147 | byEnds[SIMD2(min(u, v), max(u, v)), default: []].append(f) | |
| 148 | } | |
| 149 | } | |
| 150 | return file.edgesVertices.map { ends in | |
| 151 | guard ends.count == 2 else { return [] } | |
| 152 | return byEnds[SIMD2(min(ends[0], ends[1]), max(ends[0], ends[1]))] ?? [] | |
| 153 | } | |
| 154 | } | |
| 155 | ||
| 132 | 156 | /// Each triple `[f, g, s]` with `s ≠ 0` as a pair ordered along the canonical normal of the two |
| 133 | 157 | /// faces' common plane, the one of `g`'s normal and its negation whose first nonzero component is |
| 134 | 158 | /// positive. Triples with `s = 0`, a repeated face or a face outside `normals` are skipped. |
| @@ -150,18 +174,6 @@ private func sheetSize(_ file: FoldFile) -> Double { | ||
| 150 | 174 | return (high - low).max() |
| 151 | 175 | } |
| 152 | 176 | |
| 153 | /// The faces on each side of each edge, from consecutive corners of `faces_vertices`. | |
| 154 | private func edgesFaces(_ file: FoldFile) -> [[Int]] { | |
| 155 | var byEnds: [SIMD2<Int>: [Int]] = [:] | |
| 156 | for (f, corners) in file.facesVertices.enumerated() { | |
| 157 | for i in corners.indices { | |
| 158 | let u = corners[i], v = corners[(i + 1) % corners.count] | |
| 159 | byEnds[SIMD2(min(u, v), max(u, v)), default: []].append(f) | |
| 160 | } | |
| 161 | } | |
| 162 | return file.edgesVertices.map { byEnds[SIMD2(min($0[0], $0[1]), max($0[0], $0[1]))] ?? [] } | |
| 163 | } | |
| 164 | ||
| 165 | 177 | private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] { |
| 166 | 178 | let points = file.frames[0].verticesCoords |
| 167 | 179 | var defects: [FoldDefect] = [] |
| @@ -182,16 +194,14 @@ private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] { | ||
| 182 | 194 | } |
| 183 | 195 | |
| 184 | 196 | /// A non-boundary edge without `edges_krz:firstCreasedAtStep` is a defect unless it is a |
| 185 | /// subdivision edge: `F` and flat in every frame, and never the axis of a step. | |
| 186 | private func missingFirstCreasedAtStep(_ file: FoldFile) -> [FoldDefect] { | |
| 187 | let axisEdges = Set(file.frames.compactMap(\.step).flatMap { step in | |
| 188 | (step.axes + (step.pop?.openAxes ?? []) + (step.pop?.closeAxes ?? [])).map(\.edge) | |
| 189 | }) | |
| 197 | /// subdivision edge: `F` and flat in every frame, and creased by no step. | |
| 198 | private func missingFirstCreasedAtStep(_ file: FoldFile, edgeFaces: [[Int]]) -> [FoldDefect] { | |
| 199 | let creased = creasedEdges(file, edgeFaces: edgeFaces) | |
| 190 | 200 | return file.edgesVertices.indices.compactMap { e in |
| 191 | 201 | let assignment = file.frames[0].edgesAssignment |
| 192 | 202 | guard e < assignment.count, assignment[e] != .boundary else { return nil } |
| 193 | 203 | if e < file.edgesFirstCreasedAtStep.count, file.edgesFirstCreasedAtStep[e] != nil { return nil } |
| 194 | let subdivision = !axisEdges.contains(e) && file.frames.allSatisfy { frame in | |
| 204 | let subdivision = !creased.contains(e) && file.frames.allSatisfy { frame in | |
| 195 | 205 | e < frame.edgesAssignment.count && e < frame.edgesFoldAngle.count |
| 196 | 206 | && frame.edgesAssignment[e] == .flat && frame.edgesFoldAngle[e] == 0 |
| 197 | 207 | } |
| @@ -199,8 +209,58 @@ private func missingFirstCreasedAtStep(_ file: FoldFile) -> [FoldDefect] { | ||
| 199 | 209 | } |
| 200 | 210 | } |
| 201 | 211 | |
| 212 | /// The edges some step creases: those whose two faces the step moves differently. In each of a | |
| 213 | /// step's axis lists (`axes`, and a pop's `openAxes` and `closeAxes`), a face moves with the | |
| 214 | /// deepest axis whose `movingFaces` contains it, or stays fixed when none does. | |
| 215 | private func creasedEdges(_ file: FoldFile, edgeFaces: [[Int]]) -> Set<Int> { | |
| 216 | let lists = file.frames.compactMap(\.step).flatMap { step in | |
| 217 | [step.axes] + (step.pop.map { [$0.openAxes, $0.closeAxes] } ?? []) | |
| 218 | } | |
| 219 | let groupings = lists.map(movementGroups) | |
| 220 | return Set(edgeFaces.indices.filter { e in | |
| 221 | let faces = edgeFaces[e] | |
| 222 | return faces.count == 2 && groupings.contains { $0[faces[0]] != $0[faces[1]] } | |
| 223 | }) | |
| 224 | } | |
| 225 | ||
| 226 | /// Each moved face's axis: the deepest in the parent tree whose `movingFaces` contains it, the | |
| 227 | /// first listed among equals. A face absent from the result is fixed. | |
| 228 | private func movementGroups(_ axes: [AxisRecord]) -> [Int: Int] { | |
| 229 | func depth(_ i: Int) -> Int { | |
| 230 | var d = 0, j = i | |
| 231 | while d < axes.count, let p = axes[j].parent, axes.indices.contains(p) { | |
| 232 | d += 1 | |
| 233 | j = p | |
| 234 | } | |
| 235 | return d | |
| 236 | } | |
| 237 | var group: [Int: (axis: Int, depth: Int)] = [:] | |
| 238 | for (i, axis) in axes.enumerated() { | |
| 239 | let d = depth(i) | |
| 240 | for f in axis.movingFaces where group[f].map({ d > $0.depth }) ?? true { | |
| 241 | group[f] = (i, d) | |
| 242 | } | |
| 243 | } | |
| 244 | return group.mapValues(\.axis) | |
| 245 | } | |
| 246 | ||
| 202 | 247 | // MARK: - Frame rules |
| 203 | 248 | |
| 249 | /// Every pair of a face's vertices must be as far apart as in frame 0. | |
| 250 | private func faceShapeDefects(_ frame: FoldFrame, _ n: Int, _ file: FoldFile, tolerance: Double) -> [FoldDefect] { | |
| 251 | let flat = file.frames[0].verticesCoords, points = frame.verticesCoords | |
| 252 | return file.facesVertices.indices.compactMap { f in | |
| 253 | let corners = file.facesVertices[f] | |
| 254 | let distorted = corners.indices.contains { i in | |
| 255 | corners[(i + 1)...].contains { v in | |
| 256 | let u = corners[i] | |
| 257 | return abs(distance(points[u], points[v]) - distance(flat[u], flat[v])) > tolerance | |
| 258 | } | |
| 259 | } | |
| 260 | return distorted ? .faceDistorted(frame: n, face: f) : nil | |
| 261 | } | |
| 262 | } | |
| 263 | ||
| 204 | 264 | private func angleDefects(_ frame: FoldFrame, _ n: Int, edgeCount: Int) -> [FoldDefect] { |
| 205 | 265 | var defects: [FoldDefect] = [] |
| 206 | 266 | for e in 0..<min(edgeCount, frame.edgesAssignment.count, frame.edgesFoldAngle.count) { |
| @@ -374,7 +434,8 @@ private func newellNormal(_ polygon: [SIMD3<Double>]) -> SIMD3<Double> { | ||
| 374 | 434 | return n |
| 375 | 435 | } |
| 376 | 436 | |
| 377 | /// The first cycle a depth-first search of the below → above graph meets, as the faces along it. | |
| 437 | /// The first cycle a depth-first search of the below → above graph meets, as the faces along it, | |
| 438 | /// each above the next. | |
| 378 | 439 | private func firstCycle(_ graph: [[Int]]) -> [Int]? { |
| 379 | 440 | var state = Array(repeating: 0, count: graph.count) // 0 unvisited, 1 on the path, 2 finished |
| 380 | 441 | var path: [Int] = [] |
| @@ -382,7 +443,7 @@ private func firstCycle(_ graph: [[Int]]) -> [Int]? { | ||
| 382 | 443 | state[u] = 1 |
| 383 | 444 | path.append(u) |
| 384 | 445 | for v in graph[u] { |
| 385 | if state[v] == 1, let start = path.lastIndex(of: v) { return Array(path[start...]) } | |
| 446 | if state[v] == 1, let start = path.lastIndex(of: v) { return Array(path[start...].reversed()) } | |
| 386 | 447 | if state[v] == 0, let cycle = visit(v) { return cycle } |
| 387 | 448 | } |
| 388 | 449 | path.removeLast() |
Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift +30 −1
| @@ -103,5 +103,34 @@ func acceptsAValidModel(_ name: String) throws { | ||
| 103 | 103 | file.frames.removeLast() |
| 104 | 104 | file.edgesFirstCreasedAtStep[8] = nil |
| 105 | 105 | file.edgesFirstCreasedAtStep[9] = nil |
| 106 | #expect(validate(file).contains(.missingFirstCreasedAtStep(edge: 8))) | |
| 106 | // step 1 moves f1 and f2 and holds f0 and f3, so it creases e9 (f2 | f3) as well as e8 (f0 | f1) | |
| 107 | #expect(validate(file) == [.missingFirstCreasedAtStep(edge: 8), .missingFirstCreasedAtStep(edge: 9)]) | |
| 108 | } | |
| 109 | ||
| 110 | @Test func rejectsAShearedFaceWhoseEdgesKeepTheirLengths() throws { | |
| 111 | // f1 = [v1, v2, v3, v4] in half.fold's frame 1, sheared into a parallelogram on e6 = v1–v4 | |
| 112 | var file = try FoldFile(contentsOf: fixture("half.fold")) | |
| 113 | let slant = SIMD3<Double>(-0.6, 0.8, 0) | |
| 114 | file.frames[1].verticesCoords[2] = file.frames[1].verticesCoords[1] + slant | |
| 115 | file.frames[1].verticesCoords[3] = file.frames[1].verticesCoords[4] + slant | |
| 116 | let defects = validate(file) | |
| 117 | #expect(defects.contains(.faceDistorted(frame: 1, face: 1))) | |
| 118 | #expect(!defects.contains { if case .nonIsometricTransition = $0 { return true }; return false }) | |
| 119 | } | |
| 120 | ||
| 121 | @Test func aReportedCycleListsEachFaceAboveTheNext() throws { | |
| 122 | // frame 2 puts f0 above f1, f1 above f2 and f2 above f0 | |
| 123 | let defects = validate(try FoldFile(contentsOf: fixture("cyclic-order.fold"))) | |
| 124 | let cycle = try #require(defects.lazy.compactMap { d -> [Int]? in | |
| 125 | if case .cyclicFaceOrder(frame: 2, let cycle) = d { return cycle }; return nil | |
| 126 | }.first) | |
| 127 | let rotations = [[0, 1, 2], [1, 2, 0], [2, 0, 1]] | |
| 128 | #expect(rotations.contains(cycle)) | |
| 129 | } | |
| 130 | ||
| 131 | @Test func normalsAtGivenPositionsAndTheFacesOfEachEdge() throws { | |
| 132 | let file = try FoldFile(contentsOf: fixture("half.fold")) | |
| 133 | #expect(faceNormals(positions: file.frames[1].verticesCoords, faces: file.facesVertices) | |
| 134 | == [SIMD3(0, 0, 1), SIMD3(0, 0, -1)]) | |
| 135 | #expect(edgesFaces(file) == [[0], [1], [1], [1], [0], [0], [0, 1]]) | |
| 107 | 136 | } |