Commit ae72845afe

ae72845afe26986800d13c62392e2ae6d3b1fa76

parent: a3454f9ad1

Verified · cmc

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

Facet interpenetration checker

Ref #3

Layout: unified · split

Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +55
@@ -232,3 +232,58 @@ public func twoSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7]] }
232 232
233/// The faces of three squares of four vertices each, facing +z. 233/// The faces of three squares of four vertices each, facing +z.
234public func threeSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] } 234public func threeSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] }
235
236/// `letter.fold`'s sheet with both outer thirds valley-folded in front of the middle one on one
237/// window of t, linear 0 → 180°. The flaps meet at 120°, t = 2/3, and pass through each other
238/// after.
239public func interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator) {
240 let file = try FoldFile(contentsOf: fixture("letter.fold"))
241 let step = FoldStep(
242 index: 1,
243 kind: .fold,
244 instruction: "Valley fold both thirds in front.",
245 axes: [
246 // f0 traverses e8 from v1 up the sheet, f2 traverses e9 from v5 down it
247 FoldAxis(edge: 8, origin: SIMD3(1, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [0],
248 startAngle: 0, endAngle: 180),
249 FoldAxis(edge: 9, origin: SIMD3(2, 3, 0), direction: SIMD3(0, -1, 0), movingFaces: [2],
250 startAngle: 0, endAngle: 180),
251 ],
252 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
253 )
254 return (file, FoldInterpolator(file: file, step: step))
255}
256
257/// A fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4) and a moving triangle (0,0,0), (0,2,0),
258/// (-1,1,0) hinged on its edge along the y-axis, folding toward +z from 0 to 180°. They share
259/// vertex 0 only. The fixed triangle is tilted, so this is not a flat frame 0 and the file is
260/// built directly.
261public func interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator) {
262 let start: [SIMD3<Double>] = [
263 SIMD3(0, 0, 0), SIMD3(1, 1.2, 0.4), SIMD3(-1, 1.2, 0.4), SIMD3(0, 2, 0), SIMD3(-1, 1, 0),
264 ]
265 var end = start
266 end[4] = SIMD3(1, 1, 0)
267 let assignment: [EdgeAssignment] = [.boundary, .boundary, .boundary, .valley, .boundary, .boundary]
268 func frame(_ points: [SIMD3<Double>], angle: Double) -> FoldFrame {
269 FoldFrame(verticesCoords: points, edgesAssignment: assignment,
270 edgesFoldAngle: [0, 0, 0, angle, 0, 0], faceOrders: [])
271 }
272 let file = FoldFile(
273 fileSpec: 1.2,
274 fileAuthor: "Traditional",
275 edgesVertices: [[0, 1], [1, 2], [2, 0], [0, 3], [3, 4], [4, 0]],
276 facesVertices: [[0, 1, 2], [0, 3, 4]],
277 edgesFirstCreasedAtStep: [nil, nil, nil, 1, nil, nil],
278 frames: [frame(start, angle: 0), frame(end, angle: 180)]
279 )
280 let step = FoldStep(
281 index: 1,
282 kind: .fold,
283 instruction: "Fold the flap up.",
284 axes: [FoldAxis(edge: 3, origin: SIMD3(0, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [1],
285 startAngle: 0, endAngle: 180)],
286 viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
287 )
288 return (file, FoldInterpolator(file: file, step: step))
289}
Packages/FoldKit/Sources/Folding/Interpenetration.swift added +132
@@ -0,0 +1,132 @@
1import FoldFormat
2import simd
3
4/// Two faces that pass through each other. `t` is the first sample, `k / samples`, at which they
5/// do; `faceA < faceB`.
6public struct Intersection: Equatable, Sendable {
7 public let faceA: Int
8 public let faceB: Int
9 public let t: Double
10
11 public init(faceA: Int, faceB: Int, t: Double) {
12 self.faceA = faceA
13 self.faceB = faceB
14 self.t = t
15 }
16}
17
18/// Contact this close to a face's boundary does not count.
19private let contactTolerance = 1e-9
20/// Coplanar faces: normals within this many radians (as lines), planes within this fraction of
21/// the sheet's size.
22private let coplanarAngle = 1e-6
23private let coplanarOffset = 1e-6
24
25/// The pairs of faces that interpenetrate at some sample `t = k / samples`, `k` in 0...samples,
26/// each reported once at the first such sample.
27///
28/// Faces are convex. A pair interpenetrates when the line where their planes meet cuts both and
29/// the stretch common to both has its midpoint more than 1e-9 inside every edge of each. Contact
30/// along an edge or at a vertex, shared or coincident, does not count, but pairs that share a
31/// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's.
32/// The sheet's size is the longest side of the bounding box of the positions at `t = 0`.
33public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] {
34 precondition(samples > 0, "interpenetrations needs at least one sample")
35 let size = boundingExtent(interpolator.positions(at: 0)).max()
36 let usable = faces.indices.filter { faces[$0].count >= 3 }
37
38 var found: [Intersection] = []
39 var reported = Set<SIMD2<Int>>()
40 for k in 0...samples {
41 let t = Double(k) / Double(samples)
42 let positions = interpolator.positions(at: t)
43 let normals = faceNormals(positions: positions, faces: faces)
44 let polygons = faces.map { $0.map { positions[$0] } }
45 let boxes = polygons.map(bounds)
46
47 for (n, a) in usable.enumerated() where normals[a] != .zero {
48 for b in usable[(n + 1)...] where normals[b] != .zero {
49 let pair = SIMD2(a, b)
50 guard !reported.contains(pair), boxesMeet(boxes[a], boxes[b]),
51 !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size),
52 passThrough(polygons[a], normals[a], polygons[b], normals[b])
53 else { continue }
54 reported.insert(pair)
55 found.append(Intersection(faceA: a, faceB: b, t: t))
56 }
57 }
58 }
59 return found
60}
61
62private typealias Box = (lower: SIMD3<Double>, upper: SIMD3<Double>)
63
64private func bounds(_ points: [SIMD3<Double>]) -> Box {
65 guard let first = points.first else { return (.zero, .zero) }
66 return points.dropFirst().reduce((first, first)) { (simd_min($0.0, $1), simd_max($0.1, $1)) }
67}
68
69private func boundingExtent(_ points: [SIMD3<Double>]) -> SIMD3<Double> {
70 let box = bounds(points)
71 return box.upper - box.lower
72}
73
74/// Whether the boxes, grown by the contact tolerance, meet. Faces whose boxes do not meet cannot
75/// pass through each other.
76private func boxesMeet(_ a: Box, _ b: Box) -> Bool {
77 all(a.lower - contactTolerance .<= b.upper) && all(b.lower - contactTolerance .<= a.upper)
78}
79
80private func coplanar(_ a: [SIMD3<Double>], _ na: SIMD3<Double>, _ b: [SIMD3<Double>], _ nb: SIMD3<Double>,
81 size: Double) -> Bool {
82 guard length(cross(na, nb)) <= coplanarAngle else { return false }
83 let centre = b.reduce(.zero, +) / Double(b.count)
84 return abs(dot(na, centre - a[0])) <= coplanarOffset * size
85}
86
87/// The inward unit normal of each edge of a counterclockwise polygon, in its plane, with a corner
88/// on that edge.
89private func edgeInwardNormals(_ polygon: [SIMD3<Double>], _ normal: SIMD3<Double>)
90 -> [(corner: SIMD3<Double>, inward: SIMD3<Double>)] {
91 polygon.indices.compactMap { i in
92 let corner = polygon[i], edge = polygon[(i + 1) % polygon.count] - corner
93 let size = length(edge)
94 return size > 0 ? (corner, cross(normal, edge) / size) : nil
95 }
96}
97
98/// The interval of `s` for which `p + s·d` lies in the polygon, `p` and `d` being in its plane.
99private func clip(_ edges: [(corner: SIMD3<Double>, inward: SIMD3<Double>)], _ p: SIMD3<Double>,
100 _ d: SIMD3<Double>) -> ClosedRange<Double>? {
101 var low = -Double.infinity, high = Double.infinity
102 for (corner, inward) in edges {
103 let distance = dot(inward, p - corner), rate = dot(inward, d)
104 if abs(rate) < 1e-15 {
105 if distance < 0 { return nil }
106 continue
107 }
108 let s = -distance / rate
109 if rate > 0 { low = max(low, s) } else { high = min(high, s) }
110 }
111 return low <= high ? low...high : nil
112}
113
114private func passThrough(_ a: [SIMD3<Double>], _ na: SIMD3<Double>, _ b: [SIMD3<Double>], _ nb: SIMD3<Double>) -> Bool {
115 let along = cross(na, nb)
116 let squared = dot(along, along)
117 guard squared > 0 else { return false }
118 let d = along / sqrt(squared)
119 // a point on both planes
120 let p = (dot(na, a[0]) * cross(nb, along) + dot(nb, b[0]) * cross(along, na)) / squared
121
122 let edgesA = edgeInwardNormals(a, na), edgesB = edgeInwardNormals(b, nb)
123 guard let inA = clip(edgesA, p, d), let inB = clip(edgesB, p, d) else { return false }
124 let low = max(inA.lowerBound, inB.lowerBound), high = min(inA.upperBound, inB.upperBound)
125 guard low < high else { return false }
126
127 // A convex chord whose midpoint is on a face's boundary lies on it, so the midpoint decides.
128 let middle = p + d * ((low + high) / 2)
129 return [edgesA, edgesB].allSatisfy { edges in
130 edges.allSatisfy { dot($0.inward, middle - $0.corner) > contactTolerance }
131 }
132}
Packages/FoldKit/Tests/FoldingTests/InterpenetrationTests.swift added +48
@@ -0,0 +1,48 @@
1import Foundation
2import Testing
3import simd
4import FoldFormat
5import Folding
6import FoldKitTestSupport
7
8@Test func aCleanFoldHasNoIntersections() throws {
9 let (file, i) = try interpolator("half.fold", step: 1)
10 #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
11}
12
13@Test func twoFlapsFoldingIntoEachOtherAreDetected() throws {
14 // both thirds of the letter sheet valley-folded at once: they meet at the midline from ~120°
15 let (file, i) = try interpolatorForBothThirdsInFront()
16 #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
17}
18
19@Test func staggeredFlapsDoNotCollide() throws {
20 // the same two flaps on separate windows of t
21 let (file, i) = try interpolator("letter-staggered.fold", step: 1)
22 #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
23}
24
25@Test func aFaceSwingingThroughAFaceItSharesAVertexWithIsDetected() throws {
26 // built in code: fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4); moving triangle
27 // (0,0,0), (0,2,0), (-1,1,0) hinged on its edge along the y-axis, folding toward +z
28 let (file, i) = try interpolatorForSharedVertexSweep()
29 #expect(!interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty)
30}
31
32@Test func coplanarFacesAreNotReportedAsIntersecting() throws {
33 let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
34 let i = FoldInterpolator(file: file, step: try readSteps(file)[1])
35 #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty)
36}
37
38@Test func edgeAdjacentFacesAreNotReportedAsIntersecting() throws {
39 let (file, i) = try interpolator("quarters.fold", step: 3)
40 #expect(interpenetrations(i, faces: file.facesVertices, samples: 16).isEmpty)
41}
42
43@Test func theReportedParameterIsWhereTheIntersectionBegins() throws {
44 let (file, i) = try interpolatorForBothThirdsInFront()
45 let found = interpenetrations(i, faces: file.facesVertices, samples: 64)
46 #expect(!found.isEmpty)
47 #expect(found.allSatisfy { abs($0.t - 2.0 / 3) <= 1.0 / 64 }) // the flaps meet at 120°
48}