spikes/bending/Sources/Bending/Model.swift
121 lines · 4741 bytes
19 symbols in this file
1import FoldFormat
2import Foundation
3import simd
4
5typealias V2 = SIMD2<Double>
6typealias V3 = SIMD3<Double>
7
8/// The directory holding this package's `Data`.
9let dataDirectory = URL(fileURLWithPath: #filePath)
10 .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
11 .appendingPathComponent("Data")
12
13/// A compiled FOLD file: the crease pattern (frame 0, flat) and each frame's positions.
14struct Model {
15 var file: FoldFile
16 let flat: [V2]
17 let edgeFaces: [[Int]]
18
19 init(_ file: FoldFile) {
20 self.file = file
21 flat = file.frames[0].verticesCoords.map { V2($0.x, $0.y) }
22 edgeFaces = edgesFaces(file)
23 }
24
25 init(named name: String) throws {
26 self.init(try FoldFile(contentsOf: dataDirectory.appendingPathComponent(name)))
27 }
28
29 var faces: [[Int]] { file.facesVertices }
30 var edges: [[Int]] { file.edgesVertices }
31 func positions(_ k: Int) -> [V3] { file.frames[k].verticesCoords }
32
33 var size: Double {
34 let lo = flat.reduce(flat[0], simd_min), hi = flat.reduce(flat[0], simd_max)
35 return (hi - lo).max()
36 }
37
38 /// The face whose crease-pattern polygon contains `p`.
39 func face(containing p: V2) -> Int? {
40 faces.indices.first { f in contains(faces[f].map { flat[$0] }, p, tolerance: 1e-12) }
41 }
42
43 func centroid(_ f: Int) -> V2 { faces[f].map { flat[$0] }.reduce(.zero, +) / Double(faces[f].count) }
44
45 /// The image of crease-pattern point `p` of face `f` when the FOLD vertices are at `x`.
46 func place(_ p: V2, face f: Int, _ x: [V3]) -> V3 {
47 let c = widest(faces[f].map { flat[$0] }).map { faces[f][$0] }
48 let u = flat[c[1]] - flat[c[0]], v = flat[c[2]] - flat[c[0]], w = p - flat[c[0]]
49 let det = u.x * v.y - u.y * v.x
50 let a = (w.x * v.y - w.y * v.x) / det, b = (u.x * w.y - u.y * w.x) / det
51 return x[c[0]] + a * (x[c[1]] - x[c[0]]) + b * (x[c[2]] - x[c[0]])
52 }
53
54 func normals(_ x: [V3]) -> [V3] { faces.map { polygonNormal($0.map { x[$0] }) } }
55
56 /// The faces connected to `seed` across interior edges not in `cut`.
57 func component(from seeds: [Int], cut: Set<Int>, within allowed: Set<Int>? = nil) -> Set<Int> {
58 var seen = Set(seeds)
59 var stack = seeds
60 while let f = stack.popLast() {
61 for v in faces[f].indices {
62 let a = faces[f][v], b = faces[f][(v + 1) % faces[f].count]
63 guard let e = edgeIndex[SIMD2(min(a, b), max(a, b))], !cut.contains(e), edgeFaces[e].count == 2 else { continue }
64 let g = edgeFaces[e][0] == f ? edgeFaces[e][1] : edgeFaces[e][0]
65 if let allowed, !allowed.contains(g) { continue }
66 if seen.insert(g).inserted { stack.append(g) }
67 }
68 }
69 return seen
70 }
71
72 var edgeIndex: [SIMD2<Int>: Int] {
73 Dictionary(uniqueKeysWithValues: edges.enumerated().map { (SIMD2(min($1[0], $1[1]), max($1[0], $1[1])), $0) })
74 }
75}
76
77func polygonNormal(_ p: [V3]) -> V3 {
78 var n = V3.zero
79 for k in p.indices { n += cross(p[k], p[(k + 1) % p.count]) }
80 let l = length(n)
81 return l > 0 ? n / l : .zero
82}
83
84func contains(_ polygon: [V2], _ p: V2, tolerance: Double) -> Bool {
85 let n = polygon.count
86 let s = (0..<n).map { k -> Double in
87 let a = polygon[k], b = polygon[(k + 1) % n]
88 return (b - a).x * (p - a).y - (b - a).y * (p - a).x
89 }
90 return s.allSatisfy { $0 >= -tolerance } || s.allSatisfy { $0 <= tolerance }
91}
92
93/// The three corners spanning the largest triangle.
94func widest(_ corners: [V2]) -> [Int] {
95 var best = [0, 1, 2], largest = -1.0
96 for i in corners.indices {
97 for j in corners.indices where j > i {
98 for k in corners.indices where k > j {
99 let u = corners[j] - corners[i], v = corners[k] - corners[i]
100 let area = abs(u.x * v.y - u.y * v.x)
101 if area > largest { (best, largest) = ([i, j, k], area) }
102 }
103 }
104 }
105 return best
106}
107
108func cross2(_ a: V2, _ b: V2) -> Double { a.x * b.y - a.y * b.x }
109
110/// Rotation by `degrees` about the line through `origin` along `axis`.
111func rotate(_ p: V3, about origin: V3, axis: V3, degrees: Double) -> V3 {
112 origin + simd_quatd(angle: degrees * .pi / 180, axis: normalize(axis)).act(p - origin)
113}
114
115/// Reflection of `p` in the plane through `origin` with unit `normal`.
116func reflect(_ p: V3, origin: V3, normal: V3) -> V3 { p - 2 * dot(p - origin, normal) * normal }
117
118func pct(_ x: Double) -> String { String(format: "%.2f%%", 100 * x) }
119func sci(_ x: Double) -> String { String(format: "%.2e", x) }
120func f3(_ x: Double) -> String { String(format: "%.3f", x) }
121func f1(_ x: Double) -> String { String(format: "%.1f", x) }