spikes/bending/Sources/Bending/Mesh.swift

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

429 lines · 19172 bytes

19 symbols in this file
  1import FoldFormat
  2import Folding
  3import simd
  4
  5/// A render mesh on the crease pattern: triangles finer than the FOLD faces, each inside one face,
  6/// counterclockwise on the flat sheet, sharing vertices across creases.
  7struct Mesh {
  8    var rest: [V2]
  9    var triangles: [SIMD3<Int>]
 10    /// The FOLD face each triangle lies in.
 11    var faceOf: [Int]
 12    /// The mesh vertex at each FOLD vertex.
 13    var foldVertex: [Int]
 14    /// Per mesh vertex: a face containing it and its coordinates on that face's widest corners.
 15    var anchors: [(corners: SIMD3<Int>, a: Double, b: Double)] = []
 16
 17    init(rest: [V2], triangles: [SIMD3<Int>], faceOf: [Int], foldVertex: [Int], model: Model) {
 18        self.rest = rest
 19        self.faceOf = faceOf
 20        self.foldVertex = foldVertex
 21        // counterclockwise on the sheet
 22        self.triangles = triangles.map { t in
 23            cross2(rest[t.y] - rest[t.x], rest[t.z] - rest[t.x]) >= 0 ? t : SIMD3(t.x, t.z, t.y)
 24        }
 25        var faceOfVertex = Array(repeating: -1, count: rest.count)
 26        for (k, t) in self.triangles.enumerated() {
 27            for v in [t.x, t.y, t.z] where faceOfVertex[v] < 0 { faceOfVertex[v] = faceOf[k] }
 28        }
 29        anchors = rest.indices.map { v in
 30            let f = faceOfVertex[v]
 31            precondition(f >= 0, "mesh vertex \(v) at \(rest[v]) is in no triangle; \(rest.count) vertices, \(foldVertex.count) FOLD")
 32            let c = widest(model.faces[f].map { model.flat[$0] }).map { model.faces[f][$0] }
 33            let o = model.flat[c[0]], u = model.flat[c[1]] - o, w = model.flat[c[2]] - o, p = rest[v] - o
 34            let det = cross2(u, w)
 35            return (SIMD3(c[0], c[1], c[2]), cross2(p, w) / det, cross2(u, p) / det)
 36        }
 37    }
 38
 39    /// A bare triangulation (no FOLD faces), for a proxy sheet.
 40    init(rest: [V2], triangles: [SIMD3<Int>]) {
 41        self.rest = rest
 42        self.triangles = triangles.map { t in
 43            cross2(rest[t.y] - rest[t.x], rest[t.z] - rest[t.x]) >= 0 ? t : SIMD3(t.x, t.z, t.y)
 44        }
 45        faceOf = Array(repeating: 0, count: triangles.count)
 46        foldVertex = []
 47    }
 48
 49    /// The mesh vertices when the FOLD vertices are at `x`, each face placed rigidly.
 50    func pose(_ x: [V3]) -> [V3] {
 51        anchors.map { an in
 52            let o = x[an.corners.x]
 53            return o + an.a * (x[an.corners.y] - o) + an.b * (x[an.corners.z] - o)
 54        }
 55    }
 56
 57    /// Each edge once.
 58    var edges: [SIMD2<Int>] {
 59        var set = Set<SIMD2<Int>>()
 60        for t in triangles {
 61            for (i, j) in [(t.x, t.y), (t.y, t.z), (t.z, t.x)] { set.insert(SIMD2(min(i, j), max(i, j))) }
 62        }
 63        return set.sorted { ($0.x, $0.y) < ($1.x, $1.y) }
 64    }
 65
 66    struct Stats {
 67        var vertices: Int
 68        var triangles: Int
 69        var shortestEdge: Double
 70        var smallestAngle: Double
 71    }
 72
 73    var stats: Stats {
 74        let shortest = edges.map { simd_distance(rest[$0.x], rest[$0.y]) }.min() ?? 0
 75        var smallest = 180.0
 76        for t in triangles {
 77            let p = [rest[t.x], rest[t.y], rest[t.z]]
 78            for k in 0..<3 {
 79                let a = p[(k + 1) % 3] - p[k], b = p[(k + 2) % 3] - p[k]
 80                smallest = min(smallest, acos(max(-1, min(1, dot(a, b) / (length(a) * length(b))))) * 180 / .pi)
 81            }
 82        }
 83        return Stats(vertices: rest.count, triangles: triangles.count, shortestEdge: shortest, smallestAngle: smallest)
 84    }
 85
 86    /// The mesh vertices of `faces`.
 87    func vertices(of faces: Set<Int>) -> Set<Int> {
 88        var out = Set<Int>()
 89        for (k, t) in triangles.enumerated() where faces.contains(faceOf[k]) { out.formUnion([t.x, t.y, t.z]) }
 90        return out
 91    }
 92}
 93
 94/// The largest relative change in a mesh edge's length against the flat sheet.
 95func strain(_ x: [V3], _ mesh: Mesh, edges: [SIMD2<Int>]) -> Double {
 96    var worst = 0.0
 97    for e in edges {
 98        let rest = simd_distance(mesh.rest[e.x], mesh.rest[e.y])
 99        worst = max(worst, abs(simd_distance(x[e.x], x[e.y]) - rest) / rest)
100    }
101    return worst
102}
103
104/// The largest principal strain of any triangle: the singular values σ of the map from the flat
105/// triangle to the current one, max |σ − 1|. Unlike edge strain it does not depend on which
106/// directions the mesh's edges happen to run in.
107func principalStrain(_ x: [V3], _ mesh: Mesh) -> Double {
108    var worst = 0.0
109    for t in mesh.triangles {
110        let p0 = mesh.rest[t.x], e1 = mesh.rest[t.y] - p0, e2 = mesh.rest[t.z] - p0
111        let q0 = x[t.x], f1 = x[t.y] - q0, f2 = x[t.z] - q0
112        // F = [f1 f2] [e1 e2]^-1 (3×2); singular values from FᵀF
113        let det = cross2(e1, e2)
114        let i11 = e2.y / det, i12 = -e2.x / det, i21 = -e1.y / det, i22 = e1.x / det
115        let c1 = f1 * i11 + f2 * i21, c2 = f1 * i12 + f2 * i22
116        let a = dot(c1, c1), b = dot(c1, c2), d = dot(c2, c2)
117        let mean = (a + d) / 2, diff = ((a - d) * (a - d) / 4 + b * b).squareRoot()
118        let s1 = (mean + diff).squareRoot(), s2 = max(0, mean - diff).squareRoot()
119        worst = max(worst, abs(s1 - 1), abs(s2 - 1))
120    }
121    return worst
122}
123
124/// The edge with the largest strain, its rest length and where it is on the sheet.
125func worstEdge(_ x: [V3], _ mesh: Mesh, edges: [SIMD2<Int>]) -> (strain: Double, rest: Double, at: V2) {
126    var best = (0.0, 0.0, V2.zero)
127    for e in edges {
128        let rest = simd_distance(mesh.rest[e.x], mesh.rest[e.y])
129        let s = abs(simd_distance(x[e.x], x[e.y]) - rest) / rest
130        if s > best.0 { best = (s, rest, (mesh.rest[e.x] + mesh.rest[e.y]) / 2) }
131    }
132    return best
133}
134
135// MARK: - Constructions
136
137enum MeshKind: String, CaseIterable {
138    /// Decision 0002's: frame 0's faces cut by grid lines every `spacing`, cells fanned (FoldKit's RenderMesh).
139    case grid
140    /// The grid with every edge shorter than a quarter of the spacing collapsed onto a crease-pattern
141    /// vertex or along its crease.
142    case collapsed
143    /// Per face: each crease divided evenly at about `spacing`, a triangular lattice inside the face
144    /// kept half a spacing from its boundary, triangulated Delaunay within the face.
145    case delaunay
146}
147
148func buildMesh(_ kind: MeshKind, _ model: Model, spacing h: Double) -> Mesh {
149    switch kind {
150    case .grid: return gridMesh(model, spacing: h)
151    case .collapsed: return collapsed(gridMesh(model, spacing: h), model, below: 0.25 * h)
152    case .delaunay: return delaunayMesh(model, spacing: h)
153    }
154}
155
156func gridMesh(_ model: Model, spacing h: Double) -> Mesh {
157    let r = RenderMesh(file: model.file, spacing: h)
158    // RenderMesh can hold points that no triangle uses (cells that collapse to fewer than three)
159    var used = Array(repeating: false, count: r.vertices.count)
160    for t in r.triangles { used[t.0] = true; used[t.1] = true; used[t.2] = true }
161    var index = Array(repeating: -1, count: r.vertices.count)
162    var rest: [V2] = []
163    for v in r.vertices.indices where used[v] { index[v] = rest.count; rest.append(r.vertices[v]) }
164    return Mesh(rest: rest, triangles: r.triangles.map { SIMD3(index[$0.0], index[$0.1], index[$0.2]) },
165                faceOf: r.faceOf, foldVertex: r.meshVertexOf.map { index[$0] }, model: model)
166}
167
168/// Collapses every edge shorter than `threshold`: an interior vertex moves onto the other end, a
169/// vertex on a crease moves along it onto another point of it or its end; FOLD vertices stay. A
170/// collapse that would flip or flatten a triangle is skipped.
171func collapsed(_ mesh: Mesh, _ model: Model, below threshold: Double) -> Mesh {
172    let tol = model.size * 1e-9
173    // the crease each mesh vertex lies on, -1 inside a face, -2 for a FOLD vertex
174    var onEdge = Array(repeating: -1, count: mesh.rest.count)
175    for v in mesh.foldVertex { onEdge[v] = -2 }
176    for v in mesh.rest.indices where onEdge[v] == -1 {
177        for (e, ends) in model.edges.enumerated() {
178            let a = model.flat[ends[0]], b = model.flat[ends[1]], p = mesh.rest[v]
179            let t = dot(p - a, b - a) / dot(b - a, b - a)
180            if t > 0, t < 1, simd_distance(a + t * (b - a), p) < tol { onEdge[v] = e; break }
181        }
182    }
183    var tris = mesh.triangles
184    var faceOf = mesh.faceOf
185    var alive = Array(repeating: true, count: tris.count)
186    var position = mesh.rest
187    func canMove(_ x: Int, to y: Int) -> Bool {
188        switch onEdge[x] {
189        case -2: return false
190        case -1: return true
191        default:
192            let e = onEdge[x]
193            return onEdge[y] == e || model.edges[e].contains { mesh.foldVertex[$0] == y }
194        }
195    }
196    var changed = true
197    while changed {
198        changed = false
199        var short: [(Double, Int, Int)] = []
200        for (k, t) in tris.enumerated() where alive[k] {
201            for (i, j) in [(t.x, t.y), (t.y, t.z), (t.z, t.x)] where i < j {
202                let d = simd_distance(position[i], position[j])
203                if d < threshold { short.append((d, i, j)) }
204            }
205        }
206        short.sort { $0.0 < $1.0 }
207        var touched = Set<Int>()
208        for (_, i, j) in short where !touched.contains(i) && !touched.contains(j) {
209            for (x, y) in [(i, j), (j, i)] where canMove(x, to: y) {
210                // triangles around x without y must keep their orientation and some area
211                let around = tris.indices.filter { alive[$0] && [tris[$0].x, tris[$0].y, tris[$0].z].contains(x) }
212                let ok = around.allSatisfy { k in
213                    let t = tris[k]
214                    if [t.x, t.y, t.z].contains(y) { return true }
215                    let p = [t.x, t.y, t.z].map { $0 == x ? position[y] : position[$0] }
216                    let area = cross2(p[1] - p[0], p[2] - p[0]) / 2
217                    return area > threshold * threshold * 1e-3
218                }
219                guard ok else { continue }
220                for k in around {
221                    let t = tris[k]
222                    if [t.x, t.y, t.z].contains(y) { alive[k] = false; continue }
223                    tris[k] = SIMD3(t.x == x ? y : t.x, t.y == x ? y : t.y, t.z == x ? y : t.z)
224                }
225                touched.formUnion([x, y])
226                changed = true
227                break
228            }
229        }
230    }
231    // drop unused vertices
232    var used = Array(repeating: false, count: position.count)
233    for (k, t) in tris.enumerated() where alive[k] { used[t.x] = true; used[t.y] = true; used[t.z] = true }
234    var newIndex = Array(repeating: -1, count: position.count)
235    var rest: [V2] = []
236    for v in position.indices where used[v] { newIndex[v] = rest.count; rest.append(position[v]) }
237    let keep = tris.indices.filter { alive[$0] }
238    faceOf = keep.map { faceOf[$0] }
239    position = rest
240    return Mesh(rest: rest, triangles: keep.map { SIMD3(newIndex[tris[$0].x], newIndex[tris[$0].y], newIndex[tris[$0].z]) },
241                faceOf: faceOf, foldVertex: mesh.foldVertex.map { newIndex[$0] }, model: model)
242}
243
244/// See `MeshKind.delaunay`. `lines` adds segments the mesh must have edges along (bend lines).
245func delaunayMesh(_ model: Model, spacing h: Double, margin: Double = 0.6) -> Mesh {
246    var points = model.flat
247    var key: [SIMD2<Int64>: Int] = [:]
248    let q = model.size * 1e-9
249    func id(_ p: V2) -> Int {
250        let k = SIMD2(Int64((p.x / q).rounded()), Int64((p.y / q).rounded()))
251        if let i = key[k] { return i }
252        points.append(p)
253        key[k] = points.count - 1
254        return points.count - 1
255    }
256    for (v, p) in model.flat.enumerated() { key[SIMD2(Int64((p.x / q).rounded()), Int64((p.y / q).rounded()))] = v }
257    // each crease divided evenly
258    var along: [[Int]] = []
259    for ends in model.edges {
260        let a = model.flat[ends[0]], b = model.flat[ends[1]]
261        let n = max(1, Int((simd_distance(a, b) / h).rounded()))
262        along.append([ends[0]] + (1..<n).map { id(a + Double($0) / Double(n) * (b - a)) } + [ends[1]])
263    }
264    let edgeIndex = model.edgeIndex
265    let lo = model.flat.reduce(model.flat[0], simd_min), hi = model.flat.reduce(model.flat[0], simd_max)
266    let rowStep = h * 3.0.squareRoot() / 2
267
268    var triangles: [SIMD3<Int>] = []
269    var faceOf: [Int] = []
270    for (f, face) in model.faces.enumerated() {
271        var poly = face.map { model.flat[$0] }
272        var corners = face
273        if polygonArea(poly) < 0 {
274            poly.reverse()
275            corners.reverse()
276        }
277        var boundary: [Int] = []
278        for k in corners.indices {
279            let a = corners[k], b = corners[(k + 1) % corners.count]
280            let e = edgeIndex[SIMD2(min(a, b), max(a, b))]!
281            let run = model.edges[e][0] == a ? along[e] : along[e].reversed()
282            boundary += run.dropLast()
283        }
284        var inside: [Int] = []
285        let fl = poly.reduce(poly[0], simd_min), fh = poly.reduce(poly[0], simd_max)
286        var j = Int(((fl.y - lo.y) / rowStep).rounded(.down))
287        while lo.y + Double(j) * rowStep <= fh.y {
288            let y = lo.y + Double(j) * rowStep
289            let shift = j % 2 == 0 ? 0 : 0.5
290            var i = Int(((fl.x - lo.x) / h - shift).rounded(.down))
291            while lo.x + (Double(i) + shift) * h <= fh.x {
292                let p = V2(lo.x + (Double(i) + shift) * h, y)
293                if distanceInside(poly, p) >= margin * h { inside.append(id(p)) }
294                i += 1
295            }
296            j += 1
297        }
298        _ = hi
299        let made = triangulate(boundary: boundary, inside: inside, points)
300        precondition(Set(boundary + inside).isSubset(of: Set(made.flatMap { [$0.x, $0.y, $0.z] })), "face \(f) lost a point")
301        for t in made {
302            triangles.append(t)
303            faceOf.append(f)
304        }
305    }
306    return Mesh(rest: points, triangles: triangles, faceOf: faceOf, foldVertex: Array(model.flat.indices), model: model)
307}
308
309func polygonArea(_ p: [V2]) -> Double {
310    var a = 0.0
311    for k in p.indices { a += cross2(p[k], p[(k + 1) % p.count]) }
312    return a / 2
313}
314
315/// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside.
316func distanceInside(_ poly: [V2], _ p: V2) -> Double {
317    var d = Double.infinity
318    for k in poly.indices {
319        let a = poly[k], b = poly[(k + 1) % poly.count]
320        d = min(d, cross2(b - a, p - a) / length(b - a))
321    }
322    return d
323}
324
325/// A Delaunay triangulation of a convex polygon, its boundary points counterclockwise (straight
326/// runs allowed), with `inside` points strictly inside; boundary edges are kept.
327func triangulate(boundary: [Int], inside: [Int], _ p: [V2]) -> [SIMD3<Int>] {
328    func area(_ a: Int, _ b: Int, _ c: Int) -> Double { cross2(p[b] - p[a], p[c] - p[a]) / 2 }
329    var tris: [SIMD3<Int>] = []
330    // ear clipping on the boundary, strict corners only
331    var ring = boundary
332    let scale = ring.map { simd_length_squared(p[$0] - p[ring[0]]) }.max() ?? 1
333    while ring.count > 3 {
334        var best = -1, bestArea = 0.0
335        for k in ring.indices {
336            let i = ring[(k + ring.count - 1) % ring.count], j = ring[k], l = ring[(k + 1) % ring.count]
337            let a = area(i, j, l)
338            guard a > bestArea else { continue }
339            // no other ring point on or inside the ear (a straight run along its new side)
340            let blocked = ring.contains { m in
341                m != i && m != j && m != l && area(i, j, m) >= -1e-12 * scale && area(j, l, m) >= -1e-12 * scale
342                    && area(l, i, m) >= -1e-12 * scale
343            }
344            if !blocked { (best, bestArea) = (k, a) }
345        }
346        if best < 0 || bestArea < 1e-14 * scale { break }
347        tris.append(SIMD3(ring[(best + ring.count - 1) % ring.count], ring[best], ring[(best + 1) % ring.count]))
348        ring.remove(at: best)
349    }
350    if ring.count == 3, area(ring[0], ring[1], ring[2]) > 0 { tris.append(SIMD3(ring[0], ring[1], ring[2])) }
351    precondition(!tris.isEmpty, "a face did not triangulate")
352    let constrained = Set((0..<boundary.count).map { k in
353        SIMD2(min(boundary[k], boundary[(k + 1) % boundary.count]), max(boundary[k], boundary[(k + 1) % boundary.count]))
354    })
355
356    // insert interior points
357    for v in inside {
358        var placed = false
359        for k in tris.indices {
360            let t = tris[k]
361            let w = [area(v, t.y, t.z), area(t.x, v, t.z), area(t.x, t.y, v)]
362            let total = area(t.x, t.y, t.z)
363            guard w.allSatisfy({ $0 >= -1e-12 * total }) else { continue }
364            if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) {
365                // on an edge: split both triangles
366                let c = [t.x, t.y, t.z]
367                let a = c[(zero + 1) % 3], b = c[(zero + 2) % 3], opposite = c[zero]
368                tris[k] = SIMD3(opposite, a, v)
369                tris.append(SIMD3(opposite, v, b))
370                if let n = tris.indices.first(where: { n in
371                    let u = [tris[n].x, tris[n].y, tris[n].z]
372                    return n != k && u.contains(a) && u.contains(b) && !u.contains(v)
373                }) {
374                    let u = [tris[n].x, tris[n].y, tris[n].z]
375                    let other = u.first { $0 != a && $0 != b }!
376                    tris[n] = SIMD3(other, b, v)
377                    tris.append(SIMD3(other, v, a))
378                }
379            } else {
380                tris[k] = SIMD3(t.x, t.y, v)
381                tris.append(SIMD3(t.y, t.z, v))
382                tris.append(SIMD3(t.z, t.x, v))
383            }
384            placed = true
385            break
386        }
387        precondition(placed, "an interior point is outside its face")
388    }
389
390    // Lawson flips to Delaunay
391    func inCircle(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool {
392        let pa = p[a] - p[d], pb = p[b] - p[d], pc = p[c] - p[d]
393        let det = (pa.x * pa.x + pa.y * pa.y) * cross2(pb, pc) - (pb.x * pb.x + pb.y * pb.y) * cross2(pa, pc)
394            + (pc.x * pc.x + pc.y * pc.y) * cross2(pa, pb)
395        return det > 1e-15 * scale * scale
396    }
397    var flipped = true
398    var rounds = 0
399    while flipped && rounds < 1000 {
400        flipped = false
401        rounds += 1
402        var owner: [SIMD2<Int>: [(Int, Int)]] = [:]
403        for (k, t) in tris.enumerated() {
404            let c = [t.x, t.y, t.z]
405            for i in 0..<3 {
406                let a = c[i], b = c[(i + 1) % 3]
407                owner[SIMD2(min(a, b), max(a, b)), default: []].append((k, c[(i + 2) % 3]))
408            }
409        }
410        var done = Set<Int>()
411        for (edge, sides) in owner where sides.count == 2 && !constrained.contains(edge) {
412            let (k1, c1) = sides[0], (k2, c2) = sides[1]
413            guard !done.contains(k1), !done.contains(k2) else { continue }
414            let t = tris[k1]
415            let c = [t.x, t.y, t.z]
416            let i = c.firstIndex(of: c1)!
417            let a = c[(i + 1) % 3], b = c[(i + 2) % 3]
418            guard inCircle(c1, a, b, c2) else { continue }
419            // the flip must give two counterclockwise triangles
420            guard area(c1, a, c2) > 0, area(c2, b, c1) > 0 else { continue }
421            tris[k1] = SIMD3(c1, a, c2)
422            tris[k2] = SIMD3(c2, b, c1)
423            done.formUnion([k1, k2])
424            flipped = true
425            _ = edge
426        }
427    }
428    return tris
429}