Commit 44618d4ea0

44618d4ea039853102cec79ea205fbe775fca4fe

parent: 42a7a0e7fc

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-19 22:00 UTC

Validator: creased edges by face motion, face shape, cycle order

A step creases an edge when it moves the edge's two faces differently;
a subdivision edge is F, flat in every frame and creased by no step.
Every face keeps its pairwise vertex distances from frame 0
(faceDistorted). A reported cycle lists each face above the next.
faceNormals(positions:faces:) and edgesFaces are public.

Ref #2

Layout: unified · split

Packages/FoldKit/Sources/FoldFormat/FoldValidator.swift +85 −24
@@ -20,6 +20,7 @@ public enum FoldDefect: Equatable, Sendable {
2020 case missingInstruction(step: Int)
2121 case authorNotTraditional(String?)
2222 case missingFirstCreasedAtStep(edge: Int)
23 case faceDistorted(frame: Int, face: Int)
2324}
2425
2526/// Lengths are compared to within this fraction of the sheet's longer side.
@@ -57,7 +58,7 @@ public func validate(_ file: FoldFile) -> [FoldDefect] {
5758 let tolerance = sheetSize(file) * relativeTolerance
5859 let edgeFaces = edgesFaces(file)
5960 defects += nonConvexFaces(file)
60 defects += missingFirstCreasedAtStep(file)
61 defects += missingFirstCreasedAtStep(file, edgeFaces: edgeFaces)
6162
6263 var geometryIsSound: [Bool] = []
6364 for (n, frame) in file.frames.enumerated() {
@@ -67,6 +68,7 @@ public func validate(_ file: FoldFile) -> [FoldDefect] {
6768 defects += angleDefects(frame, n, edgeCount: file.edgesVertices.count)
6869 if sound {
6970 defects += layerOrderDefects(frame, n, file, edgeFaces: edgeFaces, tolerance: tolerance)
71 defects += faceShapeDefects(frame, n, file, tolerance: tolerance)
7072 }
7173 }
7274
@@ -121,14 +123,36 @@ public func movingSetsOverlapInProjection(step n: Int, _ file: FoldFile) -> Bool
121123/// Each face's unit normal in `frame`, from the counterclockwise order of `faces_vertices`.
122124/// A degenerate face, or one naming a vertex the frame lacks, has a zero normal.
123125public 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.
131public 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] })
127135 let size = length(n)
128136 return size > 0 ? n / size : .zero
129137 }
130138}
131139
140/// The faces on each side of each edge, from consecutive corners of `faces_vertices`. An edge
141/// without two ends has none.
142public 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
132156/// Each triple `[f, g, s]` with `s ≠ 0` as a pair ordered along the canonical normal of the two
133157/// faces' common plane, the one of `g`'s normal and its negation whose first nonzero component is
134158/// 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 {
150174 return (high - low).max()
151175}
152176
153/// The faces on each side of each edge, from consecutive corners of `faces_vertices`.
154private 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
165177private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] {
166178 let points = file.frames[0].verticesCoords
167179 var defects: [FoldDefect] = []
@@ -182,16 +194,14 @@ private func nonConvexFaces(_ file: FoldFile) -> [FoldDefect] {
182194}
183195
184196/// 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.
186private 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.
198private func missingFirstCreasedAtStep(_ file: FoldFile, edgeFaces: [[Int]]) -> [FoldDefect] {
199 let creased = creasedEdges(file, edgeFaces: edgeFaces)
190200 return file.edgesVertices.indices.compactMap { e in
191201 let assignment = file.frames[0].edgesAssignment
192202 guard e < assignment.count, assignment[e] != .boundary else { return nil }
193203 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
195205 e < frame.edgesAssignment.count && e < frame.edgesFoldAngle.count
196206 && frame.edgesAssignment[e] == .flat && frame.edgesFoldAngle[e] == 0
197207 }
@@ -199,8 +209,58 @@ private func missingFirstCreasedAtStep(_ file: FoldFile) -> [FoldDefect] {
199209 }
200210}
201211
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.
215private 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.
228private 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
202247// MARK: - Frame rules
203248
249/// Every pair of a face's vertices must be as far apart as in frame 0.
250private 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
204264private func angleDefects(_ frame: FoldFrame, _ n: Int, edgeCount: Int) -> [FoldDefect] {
205265 var defects: [FoldDefect] = []
206266 for e in 0..<min(edgeCount, frame.edgesAssignment.count, frame.edgesFoldAngle.count) {
@@ -374,7 +434,8 @@ private func newellNormal(_ polygon: [SIMD3<Double>]) -> SIMD3<Double> {
374434 return n
375435}
376436
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.
378439private func firstCycle(_ graph: [[Int]]) -> [Int]? {
379440 var state = Array(repeating: 0, count: graph.count) // 0 unvisited, 1 on the path, 2 finished
380441 var path: [Int] = []
@@ -382,7 +443,7 @@ private func firstCycle(_ graph: [[Int]]) -> [Int]? {
382443 state[u] = 1
383444 path.append(u)
384445 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()) }
386447 if state[v] == 0, let cycle = visit(v) { return cycle }
387448 }
388449 path.removeLast()
Packages/FoldKit/Tests/FoldFormatTests/ValidatorTests.swift +30 −1
@@ -103,5 +103,34 @@ func acceptsAValidModel(_ name: String) throws {
103103 file.frames.removeLast()
104104 file.edgesFirstCreasedAtStep[8] = nil
105105 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]])
107136}