Commit 2473ec7ec3

2473ec7ec3996fe23e118482d3992720ec3b0ae7

parent: 8c3426673d

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 21:44 UTC

Leave a pop's near-coplanar clusters to the layer order

During the pop, faces in one cluster (the renderer's linking rule, at the
FOLD vertices' positions) are not tested against each other for mesh
interpenetration. Rigid steps and the rigid open and close are unchanged.

Ref #7

Layout: unified · split

Packages/FoldKit/Sources/Folding/FoldInterpolator.swift +9
@@ -83,11 +83,20 @@ public struct FoldInterpolator: Sendable {
8383
8484 /// The render mesh of the file's frame 0, at `RenderMesh.spacing(for:)`.
8585 public let mesh: RenderMesh
86 /// The file's faces.
87 let faces: [[Int]]
8688 private let mode: Mode
8789
90 /// The pop's phases, for a non-rigid step.
91 var popPhases: ClosedRange<Double>? {
92 if case .nonRigid(let p) = mode { return p.phases }
93 return nil
94 }
95
8896 public init(file: FoldFile, step: FoldStep) {
8997 let start = file.frames[step.index - 1].verticesCoords
9098 mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
99 faces = file.facesVertices
91100
92101 if step.nonRigid {
93102 guard let pop = step.pop else { preconditionFailure("a non-rigid step has a pop; readStep checks it") }
Packages/FoldKit/Sources/Folding/Interpenetration.swift +27 −5
@@ -36,17 +36,37 @@ public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]],
3636
3737/// `interpenetrations` on the render mesh's triangles at `meshPositions(at:)`, reporting the FOLD
3838/// faces they lie in. Triangles of one face are not tested against each other. For non-rigid
39/// steps, whose faces bend during the pop.
39/// steps, whose faces bend during the pop. During the pop, strictly between its phases, faces in
40/// one near-coplanar cluster (`LayerOrder.clusters`' rule, at the FOLD vertices' positions) are
41/// not tested against each other: their overlap is the layer order's.
4042public func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection] {
4143 let mesh = interpolator.mesh
42 return intersections(polygons: mesh.triangles.map { [$0.0, $0.1, $0.2] }, faceOf: mesh.faceOf,
43 samples: samples, at: interpolator.meshPositions(at:))
44 return meshIntersections(triangles: mesh.triangles, faceOf: mesh.faceOf, faces: interpolator.faces,
45 samples: samples, meshAt: interpolator.meshPositions(at:),
46 foldAt: interpolator.positions(at:), pop: interpolator.popPhases)
47}
48
49/// `meshInterpenetrations` for triangles at `meshAt(t)` lying in the FOLD faces `faceOf`, whose
50/// vertices are at `foldAt(t)`; `pop` is the bent phase, if any.
51func meshIntersections(triangles: [(Int, Int, Int)], faceOf: [Int], faces: [[Int]], samples: Int,
52 meshAt: (Double) -> [SIMD3<Double>], foldAt: (Double) -> [SIMD3<Double>],
53 pop: ClosedRange<Double>?) -> [Intersection] {
54 intersections(polygons: triangles.map { [$0.0, $0.1, $0.2] }, faceOf: faceOf, samples: samples, at: meshAt) { t in
55 guard let pop, t > pop.lowerBound, t < pop.upperBound else { return nil }
56 var cluster = Array(repeating: 0, count: faces.count)
57 for (c, members) in clusterMembers(positions: foldAt(t), faces: faces).enumerated() {
58 for f in members { cluster[f] = c }
59 }
60 return cluster
61 }
4462}
4563
4664/// The pairs of faces, `faceOf` each polygon, whose polygons pass through each other at some
4765/// sample, each reported once at the first such sample, in face order within a sample.
66/// `clusters(t)`, when not nil, gives each face's cluster at `t`; faces in one cluster are not tested.
4867private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: Int,
49 at positions: (Double) -> [SIMD3<Double>]) -> [Intersection] {
68 at positions: (Double) -> [SIMD3<Double>],
69 clusters: (Double) -> [Int]? = { _ in nil }) -> [Intersection] {
5070 precondition(samples > 0, "interpenetrations needs at least one sample")
5171 let size = boundingExtent(positions(0)).max()
5272 let usable = corners.indices.filter { corners[$0].count >= 3 }
@@ -59,6 +79,7 @@ private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: In
5979 let normals = faceNormals(positions: points, faces: corners)
6080 let polygons = corners.map { $0.map { points[$0] } }
6181 let boxes = polygons.map(bounds)
82 let cluster = clusters(t)
6283 // sweep along x: a pair can meet only when their boxes' x-ranges do
6384 let order = usable.filter { normals[$0] != .zero }.sorted { boxes[$0].lower.x < boxes[$1].lower.x }
6485
@@ -67,7 +88,8 @@ private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: In
6788 for b in order[(n + 1)...] {
6889 guard boxes[b].lower.x - contactTolerance <= boxes[a].upper.x else { break }
6990 let pair = SIMD2(min(faceOf[a], faceOf[b]), max(faceOf[a], faceOf[b]))
70 guard pair.x != pair.y, boxesMeet(boxes[a], boxes[b]), !reported.contains(pair), !hits.contains(pair),
91 guard pair.x != pair.y, cluster.map({ $0[pair.x] != $0[pair.y] }) ?? true,
92 boxesMeet(boxes[a], boxes[b]), !reported.contains(pair), !hits.contains(pair),
7193 !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size),
7294 passThrough(polygons[a], normals[a], polygons[b], normals[b])
7395 else { continue }
Packages/FoldKit/Sources/Folding/LayerOrder.swift +23 −18
@@ -111,24 +111,7 @@ public struct LayerOrder: Sendable {
111111 /// `positions`; faces the order leaves unrelated keep index order.
112112 public func clusters(positions: [SIMD3<Double>], faces: [[Int]], viewDirection: SIMD3<Double>) -> [CoplanarCluster] {
113113 let normals = faceNormals(positions: positions, faces: faces)
114 let diagonal = boundingBoxDiagonal(positions)
115 let tolerance = diagonal * relativeTolerance
116 let offPlane = diagonal * sin(clusterAngle * .pi / 180)
117 let cosine = cos(clusterAngle * .pi / 180)
118
119 func withinPlane(_ face: Int, of other: Int) -> Bool {
120 let corner = positions[faces[other][0]]
121 return faces[face].allSatisfy { abs(dot(positions[$0] - corner, normals[other])) <= offPlane }
122 }
123 func linked(_ a: Int, _ b: Int) -> Bool {
124 guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= cosine,
125 withinPlane(a, of: b), withinPlane(b, of: a) else { return false }
126 let (u, v) = planeBasis(normals[a])
127 let project = { (face: Int) in faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
128 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
129 }
130
131 return components(faces.count, linked: linked).map { members in
114 return clusterMembers(positions: positions, faces: faces).map { members in
132115 CoplanarCluster(faces: backToFront(members, normals: normals, viewDirection: viewDirection))
133116 }
134117 }
@@ -221,6 +204,28 @@ public func stackDepth(positions: [SIMD3<Double>], faces: [[Int]]) -> Int {
221204
222205/// The connected components of `linked` over `0..<count`, each in index order, ordered by their
223206/// smallest member.
207/// The faces of each near-coplanar cluster, in index order, as `LayerOrder.clusters` links them.
208func clusterMembers(positions: [SIMD3<Double>], faces: [[Int]]) -> [[Int]] {
209 let normals = faceNormals(positions: positions, faces: faces)
210 let diagonal = boundingBoxDiagonal(positions)
211 let tolerance = diagonal * relativeTolerance
212 let offPlane = diagonal * sin(clusterAngle * .pi / 180)
213 let cosine = cos(clusterAngle * .pi / 180)
214
215 func withinPlane(_ face: Int, of other: Int) -> Bool {
216 let corner = positions[faces[other][0]]
217 return faces[face].allSatisfy { abs(dot(positions[$0] - corner, normals[other])) <= offPlane }
218 }
219 func linked(_ a: Int, _ b: Int) -> Bool {
220 guard normals[a] != .zero, normals[b] != .zero, abs(dot(normals[a], normals[b])) >= cosine,
221 withinPlane(a, of: b), withinPlane(b, of: a) else { return false }
222 let (u, v) = planeBasis(normals[a])
223 let project = { (face: Int) in faces[face].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
224 return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance)
225 }
226 return components(faces.count, linked: linked)
227}
228
224229private func components(_ count: Int, linked: (Int, Int) -> Bool) -> [[Int]] {
225230 var component = Array<Int?>(repeating: nil, count: count)
226231 var result: [[Int]] = []
Packages/FoldKit/Tests/FoldingTests/InterpenetrationTests.swift +26 −1
@@ -2,7 +2,7 @@ import Foundation
22import Testing
33import simd
44import FoldFormat
5import Folding
5@testable import Folding
66import FoldKitTestSupport
77
88@Test func aCleanFoldHasNoIntersections() throws {
@@ -46,3 +46,28 @@ import FoldKitTestSupport
4646 #expect(!found.isEmpty)
4747 #expect(found.allSatisfy { abs($0.t - 2.0 / 3) <= 1.0 / 64 }) // the flaps meet at 120°
4848}
49
50/// Two unit squares, each one FOLD face of two triangles, the first flat at z = 0 and the second
51/// turned about its diagonal from (0, 1) to (1, 0) by `tilt(t)` radians, so that it crosses the first.
52private func squaresCrossing(tilt: @escaping @Sendable (Double) -> Double, pop: ClosedRange<Double>?) -> [Intersection] {
53 let square: [SIMD3<Double>] = [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0)]
54 let at = { @Sendable (t: Double) -> [SIMD3<Double>] in
55 let q = simd_quatd(angle: tilt(t), axis: normalize(SIMD3(1, -1, 0)))
56 return square + square.map { q.act($0 - SIMD3(0.5, 0.5, 0)) + SIMD3(0.5, 0.5, 0) }
57 }
58 return meshIntersections(triangles: [(0, 1, 2), (0, 2, 3), (4, 5, 6), (4, 6, 7)], faceOf: [0, 0, 1, 1],
59 faces: [[0, 1, 2, 3], [4, 5, 6, 7]], samples: 8, meshAt: at, foldAt: at, pop: pop)
60}
61
62@Test func coincidentLayersThatDriftApartDuringAPopAreTheLayerOrdersBusiness() {
63 // ~1e-5 of drift across the square, inside one near-coplanar cluster, during the pop
64 #expect(squaresCrossing(tilt: { 1e-5 * sin(.pi * $0) }, pop: 0.0...1.0).isEmpty)
65}
66
67@Test func theSameDriftOutsideAPopStillCounts() {
68 #expect(!squaresCrossing(tilt: { 1e-5 * sin(.pi * $0) }, pop: nil).isEmpty)
69}
70
71@Test func aFlapPassingThroughALayerOfAnotherClusterDuringAPopStillCounts() {
72 #expect(!squaresCrossing(tilt: { .pi / 4 * sin(.pi * $0) }, pop: 0.0...1.0).isEmpty)
73}