spikes/interpolation/Sources/Spike/Collision.swift
58 lines · 2620 bytes
4 symbols in this file
1import simd
2
3/// Two convex faces interpenetrate when the segment where their planes cut both
4/// of them passes through the interior of each. Contact along a boundary or
5/// at a vertex does not count, and coplanar faces are left to the layer order.
6func intersectingPairs(_ faces: [[V3]], eps: Double = 1e-7) -> [(Int, Int)] {
7 func normal(_ f: [V3]) -> V3 {
8 var n = V3.zero
9 for k in f.indices { n += simd_cross(f[k], f[(k + 1) % f.count]) }
10 return simd_normalize(n)
11 }
12 let normals = faces.map(normal)
13
14 /// Signed distance of x from each edge line of f, inward positive.
15 func inwardDistances(_ f: [V3], _ n: V3, _ x: V3) -> [Double] {
16 f.indices.map { j in
17 let e0 = f[j], e1 = f[(j + 1) % f.count]
18 return simd_dot(simd_cross(e1 - e0, x - e0), n) / simd_length(e1 - e0)
19 }
20 }
21
22 /// The interval of s for which p0 + s·d lies in f.
23 func clip(_ f: [V3], _ n: V3, _ p0: V3, _ d: V3) -> (Double, Double)? {
24 var lo = -Double.infinity, hi = Double.infinity
25 for j in f.indices {
26 let e0 = f[j], e1 = f[(j + 1) % f.count]
27 let m = simd_cross(n, e1 - e0) // inward normal of the edge, in f's plane
28 let a = simd_dot(m, p0 - e0), b = simd_dot(m, d)
29 if abs(b) < 1e-15 { if a < -1e-12 { return nil }; continue }
30 let s = -a / b
31 if b > 0 { lo = max(lo, s) } else { hi = min(hi, s) }
32 }
33 return lo < hi ? (lo, hi) : nil
34 }
35
36 var found: [(Int, Int)] = []
37 for i in faces.indices {
38 for j in faces.indices where j > i {
39 let (a, b, na, nb) = (faces[i], faces[j], normals[i], normals[j])
40 var d = simd_cross(na, nb)
41 guard simd_length(d) > 1e-9 else { continue } // parallel or coplanar
42 d = simd_normalize(d)
43 // A point on both planes: minimise distance to a's first vertex.
44 let ca = simd_dot(na, a[0]), cb = simd_dot(nb, b[0])
45 let n12 = simd_dot(na, nb)
46 let det = 1 - n12 * n12
47 let p0 = na * ((ca - cb * n12) / det) + nb * ((cb - ca * n12) / det)
48 guard let (la, ha) = clip(a, na, p0, d), let (lb, hb) = clip(b, nb, p0, d) else { continue }
49 let lo = max(la, lb), hi = min(ha, hb)
50 guard hi - lo > eps else { continue }
51 let mid = p0 + d * ((lo + hi) / 2)
52 if inwardDistances(a, na, mid).allSatisfy({ $0 > eps }) && inwardDistances(b, nb, mid).allSatisfy({ $0 > eps }) {
53 found.append((i, j))
54 }
55 }
56 }
57 return found
58}