spikes/bending/Sources/Bending/Collide.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/spikes/bending/Sources/Bending/Collide.swift history · blame · raw

83 lines · 3960 bytes

6 symbols in this file
 1import simd
 2
 3/// Pairs of mesh triangles in different FOLD faces that pass through each other: the segment where
 4/// their planes meet crosses the inside of both, its midpoint deeper than `depth` inside each.
 5/// Coplanar pairs (normals within 1e-6 rad, planes within 1e-6 of the sheet's size) are the layer
 6/// order's and skipped, as FoldKit's check does. Triangles sharing a vertex are skipped.
 7func meshCollisions(_ x: [V3], _ mesh: Mesh, size: Double, depth: Double, among subset: Set<Int>? = nil) -> [(Int, Int)] {
 8    thickness = thicknessFraction * size
 9    let tris = mesh.triangles
10    let candidates = subset.map { Array($0).sorted() } ?? Array(tris.indices)
11    let normals = tris.map { t in normalOf(x[t.x], x[t.y], x[t.z]) }
12    let boxes = tris.map { t -> (V3, V3) in
13        let p = [x[t.x], x[t.y], x[t.z]]
14        return (simd_min(simd_min(p[0], p[1]), p[2]), simd_max(simd_max(p[0], p[1]), p[2]))
15    }
16    let order = candidates.filter { normals[$0] != .zero }.sorted { boxes[$0].0.x < boxes[$1].0.x }
17    var found: [(Int, Int)] = []
18    let eps = size * 1e-9
19    for (n, a) in order.enumerated() {
20        let ta = tris[a]
21        for b in order[(n + 1)...] {
22            if boxes[b].0.x > boxes[a].1.x + eps { break }
23            guard mesh.faceOf[a] != mesh.faceOf[b],
24                  all(boxes[a].0 .<= boxes[b].1 + eps), all(boxes[b].0 .<= boxes[a].1 + eps) else { continue }
25            let tb = tris[b]
26            let va = [ta.x, ta.y, ta.z], vb = [tb.x, tb.y, tb.z]
27            if va.contains(where: vb.contains) { continue }
28            let pa = va.map { x[$0] }, pb = vb.map { x[$0] }
29            if length(cross(normals[a], normals[b])) <= 1e-6, abs(dot(normals[a], pb[0] - pa[0])) <= 1e-6 * size { continue }
30            if passThrough(pa, normals[a], pb, normals[b], depth: depth) { found.append((a, b)) }
31        }
32    }
33    return found
34}
35
36func normalOf(_ a: V3, _ b: V3, _ c: V3) -> V3 {
37    let n = cross(b - a, c - a)
38    let l = length(n)
39    return l > 0 ? n / l : .zero
40}
41
42private func passThrough(_ a: [V3], _ na: V3, _ b: [V3], _ nb: V3, depth: Double) -> Bool {
43    let along = cross(na, nb)
44    let squared = dot(along, along)
45    guard squared > 1e-24 else { return false }
46    let d = along / sqrt(squared)
47    let p = (dot(na, a[0]) * cross(nb, along) + dot(nb, b[0]) * cross(along, na)) / squared
48    func inward(_ poly: [V3], _ n: V3) -> [(V3, V3)] {
49        (0..<3).map { i in
50            let c = poly[i], e = poly[(i + 1) % 3] - c
51            return (c, cross(n, e) / length(e))
52        }
53    }
54    let ea = inward(a, na), eb = inward(b, nb)
55    func clip(_ edges: [(V3, V3)]) -> (Double, Double)? {
56        var lo = -Double.infinity, hi = Double.infinity
57        for (c, m) in edges {
58            let dist = dot(m, p - c), rate = dot(m, d)
59            if abs(rate) < 1e-15 { if dist < 0 { return nil }; continue }
60            let s = -dist / rate
61            if rate > 0 { lo = max(lo, s) } else { hi = min(hi, s) }
62        }
63        return lo <= hi ? (lo, hi) : nil
64    }
65    guard let ia = clip(ea), let ib = clip(eb) else { return false }
66    let lo = max(ia.0, ib.0), hi = min(ia.1, ib.1)
67    guard hi - lo > 2 * depth else { return false }
68    let mid = p + d * ((lo + hi) / 2)
69    guard [ea, eb].allSatisfy({ edges in edges.allSatisfy { dot($0.1, mid - $0.0) > depth } }) else { return false }
70    // how far each pokes through the other's plane: layers of one stack that cross by less than
71    // the paper's thickness are contact, not interpenetration
72    func poke(_ t: [V3], _ n: V3, _ o: V3) -> Double {
73        let s = t.map { dot($0 - o, n) }
74        return min(max(0, s.max()!), max(0, -s.min()!))
75    }
76    return min(poke(a, nb, b[0]), poke(b, na, a[0])) > thickness
77}
78
79nonisolated(unsafe) var thicknessFraction = 1e-3
80
81/// Paper thickness for the interpenetration test, as a fraction of the sheet's size (0.1 mm on a
82/// 15 cm square is 6.7e-4).
83nonisolated(unsafe) var thickness = 0.0