import FoldFormat import simd /// Two faces that pass through each other. `t` is the first sample, `k / samples`, at which they /// do; `faceA < faceB`. public struct Intersection: Equatable, Sendable { public let faceA: Int public let faceB: Int public let t: Double public init(faceA: Int, faceB: Int, t: Double) { self.faceA = faceA self.faceB = faceB self.t = t } } /// Contact this close to a face's boundary does not count. private let contactTolerance = 1e-9 /// Coplanar faces: normals within this many radians (as lines), planes within this fraction of /// the sheet's size. private let coplanarAngle = 1e-6 private let coplanarOffset = 1e-6 /// The pairs of faces that interpenetrate at some sample `t = k / samples`, `k` in 0...samples, /// each reported once at the first such sample. /// /// Faces are convex. A pair interpenetrates when the line where their planes meet cuts both and /// the stretch common to both has its midpoint more than 1e-9 inside every edge of each. Contact /// along an edge or at a vertex, shared or coincident, does not count, but pairs that share a /// vertex or an edge are tested. Coplanar pairs are skipped; their overlap is the layer order's. /// The sheet's size is the longest side of the bounding box of the positions at `t = 0`. public func interpenetrations(_ interpolator: FoldInterpolator, faces: [[Int]], samples: Int) -> [Intersection] { intersections(polygons: faces, faceOf: Array(faces.indices), samples: samples, at: interpolator.positions(at:)) } /// `interpenetrations` on the render mesh's triangles at `meshPositions(at:)`, reporting the FOLD /// faces they lie in. Triangles of one face are not tested against each other. For non-rigid /// steps, whose faces bend during the pop. During the pop, strictly between its phases, faces in /// one near-coplanar cluster (`LayerOrder.clusters`' rule, at the FOLD vertices' positions) are /// not tested against each other: their overlap is the layer order's. public func meshInterpenetrations(_ interpolator: FoldInterpolator, samples: Int) -> [Intersection] { let mesh = interpolator.mesh return meshIntersections(triangles: mesh.triangles, faceOf: mesh.faceOf, faces: interpolator.faces, samples: samples, meshAt: interpolator.meshPositions(at:), foldAt: interpolator.positions(at:), pop: interpolator.popPhases) } /// `meshInterpenetrations` for triangles at `meshAt(t)` lying in the FOLD faces `faceOf`, whose /// vertices are at `foldAt(t)`; `pop` is the bent phase, if any. func meshIntersections(triangles: [(Int, Int, Int)], faceOf: [Int], faces: [[Int]], samples: Int, meshAt: (Double) -> [SIMD3], foldAt: (Double) -> [SIMD3], pop: ClosedRange?) -> [Intersection] { intersections(polygons: triangles.map { [$0.0, $0.1, $0.2] }, faceOf: faceOf, samples: samples, at: meshAt) { t in guard let pop, t > pop.lowerBound, t < pop.upperBound else { return nil } var cluster = Array(repeating: 0, count: faces.count) for (c, members) in clusterMembers(positions: foldAt(t), faces: faces).enumerated() { for f in members { cluster[f] = c } } return cluster } } /// The pairs of faces, `faceOf` each polygon, whose polygons pass through each other at some /// sample, each reported once at the first such sample, in face order within a sample. /// `clusters(t)`, when not nil, gives each face's cluster at `t`; faces in one cluster are not tested. private func intersections(polygons corners: [[Int]], faceOf: [Int], samples: Int, at positions: (Double) -> [SIMD3], clusters: (Double) -> [Int]? = { _ in nil }) -> [Intersection] { precondition(samples > 0, "interpenetrations needs at least one sample") let size = boundingExtent(positions(0)).max() let usable = corners.indices.filter { corners[$0].count >= 3 } var found: [Intersection] = [] var reported = Set>() for k in 0...samples { let t = Double(k) / Double(samples) let points = positions(t) let normals = faceNormals(positions: points, faces: corners) let polygons = corners.map { $0.map { points[$0] } } let boxes = polygons.map(bounds) let cluster = clusters(t) // sweep along x: a pair can meet only when their boxes' x-ranges do let order = usable.filter { normals[$0] != .zero }.sorted { boxes[$0].lower.x < boxes[$1].lower.x } var hits = Set>() for (n, a) in order.enumerated() { for b in order[(n + 1)...] { guard boxes[b].lower.x - contactTolerance <= boxes[a].upper.x else { break } let pair = SIMD2(min(faceOf[a], faceOf[b]), max(faceOf[a], faceOf[b])) guard pair.x != pair.y, cluster.map({ $0[pair.x] != $0[pair.y] }) ?? true, boxesMeet(boxes[a], boxes[b]), !reported.contains(pair), !hits.contains(pair), !coplanar(polygons[a], normals[a], polygons[b], normals[b], size: size), passThrough(polygons[a], normals[a], polygons[b], normals[b]) else { continue } hits.insert(pair) } } for pair in hits.sorted(by: { ($0.x, $0.y) < ($1.x, $1.y) }) { reported.insert(pair) found.append(Intersection(faceA: pair.x, faceB: pair.y, t: t)) } } return found } private typealias Box = (lower: SIMD3, upper: SIMD3) private func bounds(_ points: [SIMD3]) -> Box { guard let first = points.first else { return (.zero, .zero) } return points.dropFirst().reduce((first, first)) { (simd_min($0.0, $1), simd_max($0.1, $1)) } } private func boundingExtent(_ points: [SIMD3]) -> SIMD3 { let box = bounds(points) return box.upper - box.lower } /// Whether the boxes, grown by the contact tolerance, meet. Faces whose boxes do not meet cannot /// pass through each other. private func boxesMeet(_ a: Box, _ b: Box) -> Bool { all(a.lower - contactTolerance .<= b.upper) && all(b.lower - contactTolerance .<= a.upper) } private func coplanar(_ a: [SIMD3], _ na: SIMD3, _ b: [SIMD3], _ nb: SIMD3, size: Double) -> Bool { guard length(cross(na, nb)) <= coplanarAngle else { return false } let centre = b.reduce(.zero, +) / Double(b.count) return abs(dot(na, centre - a[0])) <= coplanarOffset * size } /// The inward unit normal of each edge of a counterclockwise polygon, in its plane, with a corner /// on that edge. private func edgeInwardNormals(_ polygon: [SIMD3], _ normal: SIMD3) -> [(corner: SIMD3, inward: SIMD3)] { polygon.indices.compactMap { i in let corner = polygon[i], edge = polygon[(i + 1) % polygon.count] - corner let size = length(edge) return size > 0 ? (corner, cross(normal, edge) / size) : nil } } /// The interval of `s` for which `p + s·d` lies in the polygon, `p` and `d` being in its plane. private func clip(_ edges: [(corner: SIMD3, inward: SIMD3)], _ p: SIMD3, _ d: SIMD3) -> ClosedRange? { var low = -Double.infinity, high = Double.infinity for (corner, inward) in edges { let distance = dot(inward, p - corner), rate = dot(inward, d) if abs(rate) < 1e-15 { if distance < 0 { return nil } continue } let s = -distance / rate if rate > 0 { low = max(low, s) } else { high = min(high, s) } } return low <= high ? low...high : nil } private func passThrough(_ a: [SIMD3], _ na: SIMD3, _ b: [SIMD3], _ nb: SIMD3) -> Bool { let along = cross(na, nb) let squared = dot(along, along) guard squared > 0 else { return false } let d = along / sqrt(squared) // a point on both planes let p = (dot(na, a[0]) * cross(nb, along) + dot(nb, b[0]) * cross(along, na)) / squared let edgesA = edgeInwardNormals(a, na), edgesB = edgeInwardNormals(b, nb) guard let inA = clip(edgesA, p, d), let inB = clip(edgesB, p, d) else { return false } let low = max(inA.lowerBound, inB.lowerBound), high = min(inA.upperBound, inB.upperBound) guard low < high else { return false } // A convex chord whose midpoint is on a face's boundary lies on it, so the midpoint decides. let middle = p + d * ((low + high) / 2) return [edgesA, edgesB].allSatisfy { edges in edges.allSatisfy { dot($0.inward, middle - $0.corner) > contactTolerance } } }