import simd /// Two convex faces interpenetrate when the segment where their planes cut both /// of them passes through the interior of each. Contact along a boundary or /// at a vertex does not count, and coplanar faces are left to the layer order. func intersectingPairs(_ faces: [[V3]], eps: Double = 1e-7) -> [(Int, Int)] { func normal(_ f: [V3]) -> V3 { var n = V3.zero for k in f.indices { n += simd_cross(f[k], f[(k + 1) % f.count]) } return simd_normalize(n) } let normals = faces.map(normal) /// Signed distance of x from each edge line of f, inward positive. func inwardDistances(_ f: [V3], _ n: V3, _ x: V3) -> [Double] { f.indices.map { j in let e0 = f[j], e1 = f[(j + 1) % f.count] return simd_dot(simd_cross(e1 - e0, x - e0), n) / simd_length(e1 - e0) } } /// The interval of s for which p0 + s·d lies in f. func clip(_ f: [V3], _ n: V3, _ p0: V3, _ d: V3) -> (Double, Double)? { var lo = -Double.infinity, hi = Double.infinity for j in f.indices { let e0 = f[j], e1 = f[(j + 1) % f.count] let m = simd_cross(n, e1 - e0) // inward normal of the edge, in f's plane let a = simd_dot(m, p0 - e0), b = simd_dot(m, d) if abs(b) < 1e-15 { if a < -1e-12 { return nil }; continue } let s = -a / b if b > 0 { lo = max(lo, s) } else { hi = min(hi, s) } } return lo < hi ? (lo, hi) : nil } var found: [(Int, Int)] = [] for i in faces.indices { for j in faces.indices where j > i { let (a, b, na, nb) = (faces[i], faces[j], normals[i], normals[j]) var d = simd_cross(na, nb) guard simd_length(d) > 1e-9 else { continue } // parallel or coplanar d = simd_normalize(d) // A point on both planes: minimise distance to a's first vertex. let ca = simd_dot(na, a[0]), cb = simd_dot(nb, b[0]) let n12 = simd_dot(na, nb) let det = 1 - n12 * n12 let p0 = na * ((ca - cb * n12) / det) + nb * ((cb - ca * n12) / det) guard let (la, ha) = clip(a, na, p0, d), let (lb, hb) = clip(b, nb, p0, d) else { continue } let lo = max(la, lb), hi = min(ha, hb) guard hi - lo > eps else { continue } let mid = p0 + d * ((lo + hi) / 2) if inwardDistances(a, na, mid).allSatisfy({ $0 > eps }) && inwardDistances(b, nb, mid).allSatisfy({ $0 > eps }) { found.append((i, j)) } } } return found }