| @@ -1,10 +1,12 @@ |
| 1 | 1 | import FoldFormat |
| 2 | 2 | import simd |
| 3 | 3 | |
| 4 | | /// The triangles the renderer draws, finer than the FOLD faces: frame 0's faces cut by lines |
| 5 | | /// every `spacing` in x and in y, each resulting convex cell fanned into triangles. Cells on both |
| 6 | | /// sides of an edge share its vertices, so the mesh is one connected sheet. The FOLD topology is |
| 7 | | /// unchanged; a non-rigid step bends this mesh, not the FOLD faces. |
| 4 | /// The triangles the renderer draws, finer than the FOLD faces (decision 0003). Each side of each |
| 5 | /// frame 0 face is divided into round(length / `spacing`) equal parts; inside each face, points of |
| 6 | /// a triangular lattice `spacing` apart are kept at least 0.6 `spacing` from its sides; each face |
| 7 | /// is triangulated on those points by ear clipping, point insertion and Lawson flips, so it is |
| 8 | /// Delaunay within the face. Faces sharing a side share its points, so the mesh is one connected |
| 9 | /// sheet. The FOLD topology is unchanged; a non-rigid step bends this mesh, not the FOLD faces. |
| 8 | 10 | public struct RenderMesh: Sendable { |
| 9 | 11 | /// Frame 0 positions in its plane. |
| 10 | 12 | public let vertices: [SIMD2<Double>] |
| @@ -27,51 +29,66 @@ public struct RenderMesh: Sendable { |
| 27 | 29 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } |
| 28 | 30 | let lower = flat.dropFirst().reduce(flat[0], simd_min) |
| 29 | 31 | let upper = flat.dropFirst().reduce(flat[0], simd_max) |
| 30 | | let size = (upper - lower).max() |
| 31 | | let tolerance = size * 1e-9 |
| 32 | | let xs = lines(from: lower.x, to: upper.x, spacing: spacing, tolerance: tolerance) |
| 33 | | let ys = lines(from: lower.y, to: upper.y, spacing: spacing, tolerance: tolerance) |
| 32 | let tolerance = (upper - lower).max() * 1e-9 |
| 33 | let rowSpacing = spacing * 3.0.squareRoot() / 2 |
| 34 | 34 | |
| 35 | 35 | var points = PointSet(tolerance: tolerance) |
| 36 | let meshVertexOf = flat.map { points.index(of: $0) } |
| 37 | // each side's points from its lower-numbered end, so both faces compute the same ones |
| 38 | var sides: [SIMD2<Int>: [Int]] = [:] |
| 39 | func side(_ a: Int, _ b: Int) -> [Int] { |
| 40 | let key = SIMD2(min(a, b), max(a, b)) |
| 41 | if sides[key] == nil { |
| 42 | let p = flat[key.x], q = flat[key.y] |
| 43 | let parts = max(1, Int((simd_distance(p, q) / spacing).rounded())) |
| 44 | sides[key] = [meshVertexOf[key.x]] |
| 45 | + (1..<parts).map { points.index(of: p + Double($0) / Double(parts) * (q - p)) } |
| 46 | + [meshVertexOf[key.y]] |
| 47 | } |
| 48 | return a == key.x ? sides[key]! : sides[key]!.reversed() |
| 49 | } |
| 50 | |
| 36 | 51 | var triangles: [(Int, Int, Int)] = [] |
| 37 | 52 | var faceOf: [Int] = [] |
| 38 | 53 | var anchors: [Int: Anchor] = [:] |
| 39 | 54 | for (f, face) in file.facesVertices.enumerated() { |
| 40 | | var cells = [face.map { flat[$0] }] |
| 41 | | for x in xs { cells = cells.flatMap { split($0, at: x, axis: 0, tolerance: tolerance) } } |
| 42 | | for y in ys { cells = cells.flatMap { split($0, at: y, axis: 1, tolerance: tolerance) } } |
| 43 | | let corners = widestCorners(face.map { flat[$0] }) |
| 44 | | let origin = flat[face[corners[0]]] |
| 45 | | let u = flat[face[corners[1]]] - origin, v = flat[face[corners[2]]] - origin |
| 46 | | let det = u.x * v.y - u.y * v.x |
| 47 | | func point(_ p: SIMD2<Double>) -> Int { |
| 48 | | let id = points.index(of: p) |
| 49 | | if anchors[id] == nil { |
| 50 | | let w = points.points[id] - origin |
| 51 | | anchors[id] = Anchor(corners: SIMD3(face[corners[0]], face[corners[1]], face[corners[2]]), |
| 52 | | a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det) |
| 55 | let outline = face.map { flat[$0] } |
| 56 | let corners = signedArea(outline) < 0 ? face.reversed() : face |
| 57 | let polygon = corners.map { flat[$0] } |
| 58 | var boundary: [Int] = [] |
| 59 | for k in corners.indices { boundary += side(corners[k], corners[(k + 1) % corners.count]).dropLast() } |
| 60 | |
| 61 | var inside: [Int] = [] |
| 62 | let low = polygon.dropFirst().reduce(polygon[0], simd_min) |
| 63 | let high = polygon.dropFirst().reduce(polygon[0], simd_max) |
| 64 | var row = Int(((low.y - lower.y) / rowSpacing).rounded(.down)) |
| 65 | while lower.y + Double(row) * rowSpacing <= high.y { |
| 66 | let y = lower.y + Double(row) * rowSpacing |
| 67 | let shift = row.isMultiple(of: 2) ? 0 : 0.5 |
| 68 | var column = Int(((low.x - lower.x) / spacing - shift).rounded(.down)) |
| 69 | while lower.x + (Double(column) + shift) * spacing <= high.x { |
| 70 | let p = SIMD2(lower.x + (Double(column) + shift) * spacing, y) |
| 71 | if distanceInside(polygon, p) >= 0.6 * spacing { inside.append(points.index(of: p)) } |
| 72 | column += 1 |
| 53 | 73 | } |
| 54 | | return id |
| 74 | row += 1 |
| 55 | 75 | } |
| 56 | | for cell in cells { |
| 57 | | var ids: [Int] = [] |
| 58 | | for p in cell { |
| 59 | | let id = point(p) |
| 60 | | if ids.last != id && ids.first != id { ids.append(id) } |
| 61 | | } |
| 62 | | guard ids.count >= 3 else { continue } |
| 63 | | var fanned = fan(ids, points.points, minimumArea: tolerance * size) |
| 64 | | if fanned == nil { |
| 65 | | let centre = ids.reduce(SIMD2<Double>.zero) { $0 + points.points[$1] } / Double(ids.count) |
| 66 | | fanned = fan(ids, around: point(centre)) |
| 67 | | } |
| 68 | | for triangle in fanned! { |
| 69 | | triangles.append(triangle) |
| 70 | | faceOf.append(f) |
| 71 | | } |
| 76 | |
| 77 | for triangle in triangulate(boundary: boundary, inside: inside, points.points) { |
| 78 | triangles.append(triangle) |
| 79 | faceOf.append(f) |
| 80 | } |
| 81 | let widest = widestCorners(outline) |
| 82 | let origin = outline[widest[0]] |
| 83 | let u = outline[widest[1]] - origin, v = outline[widest[2]] - origin |
| 84 | let det = u.x * v.y - u.y * v.x |
| 85 | for id in boundary + inside where anchors[id] == nil { |
| 86 | let w = points.points[id] - origin |
| 87 | anchors[id] = Anchor(corners: SIMD3(face[widest[0]], face[widest[1]], face[widest[2]]), |
| 88 | a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det) |
| 72 | 89 | } |
| 73 | 90 | } |
| 74 | | meshVertexOf = flat.map { points.index(of: $0) } |
| 91 | self.meshVertexOf = meshVertexOf |
| 75 | 92 | vertices = points.points |
| 76 | 93 | self.triangles = triangles |
| 77 | 94 | self.faceOf = faceOf |
| @@ -107,56 +124,120 @@ public func strain(_ positions: [SIMD3<Double>], mesh: RenderMesh) -> Double { |
| 107 | 124 | return worst |
| 108 | 125 | } |
| 109 | 126 | |
| 110 | | /// The grid lines strictly inside `low...high`: `low + k·spacing` for k ≥ 1. |
| 111 | | private func lines(from low: Double, to high: Double, spacing: Double, tolerance: Double) -> [Double] { |
| 112 | | var result: [Double] = [] |
| 113 | | var k = 1.0 |
| 114 | | while low + k * spacing < high - tolerance { |
| 115 | | result.append(low + k * spacing) |
| 116 | | k += 1 |
| 127 | /// Twice the signed area of a polygon, positive when its corners run counterclockwise. |
| 128 | private func signedArea(_ polygon: [SIMD2<Double>]) -> Double { |
| 129 | polygon.indices.reduce(0) { sum, k in |
| 130 | let p = polygon[k], q = polygon[(k + 1) % polygon.count] |
| 131 | return sum + p.x * q.y - p.y * q.x |
| 117 | 132 | } |
| 118 | | return result |
| 119 | 133 | } |
| 120 | 134 | |
| 121 | | /// A convex polygon cut by the line where coordinate `axis` equals `value`, or the polygon itself |
| 122 | | /// when the line does not cross it. Crossing points lie exactly on the line. |
| 123 | | private func split(_ polygon: [SIMD2<Double>], at value: Double, axis: Int, tolerance: Double) -> [[SIMD2<Double>]] { |
| 124 | | let d = polygon.map { $0[axis] - value } |
| 125 | | guard d.contains(where: { $0 < -tolerance }), d.contains(where: { $0 > tolerance }) else { return [polygon] } |
| 126 | | var below: [SIMD2<Double>] = [], above: [SIMD2<Double>] = [] |
| 127 | | for i in polygon.indices { |
| 128 | | let j = (i + 1) % polygon.count |
| 129 | | if d[i] <= tolerance { below.append(polygon[i]) } |
| 130 | | if d[i] >= -tolerance { above.append(polygon[i]) } |
| 131 | | if (d[i] < -tolerance && d[j] > tolerance) || (d[i] > tolerance && d[j] < -tolerance) { |
| 132 | | var crossing = polygon[i] + (polygon[j] - polygon[i]) * (d[i] / (d[i] - d[j])) |
| 133 | | crossing[axis] = value |
| 134 | | below.append(crossing) |
| 135 | | above.append(crossing) |
| 135 | private func cross(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x } |
| 136 | |
| 137 | /// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside. |
| 138 | private func distanceInside(_ polygon: [SIMD2<Double>], _ p: SIMD2<Double>) -> Double { |
| 139 | polygon.indices.map { k in |
| 140 | let a = polygon[k], b = polygon[(k + 1) % polygon.count] |
| 141 | return cross(b - a, p - a) / simd_distance(a, b) |
| 142 | }.min() ?? 0 |
| 143 | } |
| 144 | |
| 145 | /// A Delaunay triangulation of a convex polygon whose `boundary` points run counterclockwise |
| 146 | /// (straight runs allowed), with `inside` points strictly inside, keeping the boundary's edges. |
| 147 | /// Ear clipping on the boundary, each time the largest ear with no other boundary point on or in |
| 148 | /// it; then each inside point inserted into the triangle holding it, splitting an edge it lies |
| 149 | /// on; then Lawson flips of every edge off the boundary until each is locally Delaunay. |
| 150 | /// Triangles are counterclockwise. |
| 151 | private func triangulate(boundary: [Int], inside: [Int], _ p: [SIMD2<Double>]) -> [(Int, Int, Int)] { |
| 152 | func area(_ a: Int, _ b: Int, _ c: Int) -> Double { cross(p[b] - p[a], p[c] - p[a]) / 2 } |
| 153 | let scale = boundary.map { simd_length_squared(p[$0] - p[boundary[0]]) }.max() ?? 1 |
| 154 | var triangles: [SIMD3<Int>] = [] |
| 155 | |
| 156 | var ring = boundary |
| 157 | while ring.count > 3 { |
| 158 | var best = -1, bestArea = 0.0 |
| 159 | for k in ring.indices { |
| 160 | let i = ring[(k + ring.count - 1) % ring.count], j = ring[k], l = ring[(k + 1) % ring.count] |
| 161 | let a = area(i, j, l) |
| 162 | guard a > bestArea else { continue } |
| 163 | let blocked = ring.contains { m in |
| 164 | m != i && m != j && m != l && area(i, j, m) >= -1e-12 * scale && area(j, l, m) >= -1e-12 * scale |
| 165 | && area(l, i, m) >= -1e-12 * scale |
| 166 | } |
| 167 | if !blocked { (best, bestArea) = (k, a) } |
| 136 | 168 | } |
| 169 | if best < 0 || bestArea < 1e-14 * scale { break } |
| 170 | triangles.append(SIMD3(ring[(best + ring.count - 1) % ring.count], ring[best], ring[(best + 1) % ring.count])) |
| 171 | ring.remove(at: best) |
| 137 | 172 | } |
| 138 | | return [below, above] |
| 139 | | } |
| 173 | if ring.count == 3, area(ring[0], ring[1], ring[2]) > 0 { triangles.append(SIMD3(ring[0], ring[1], ring[2])) } |
| 140 | 174 | |
| 141 | | /// A convex cell, its corners counterclockwise, fanned from the first corner whose fan has no |
| 142 | | /// triangle of `minimumArea` or less; nil when every corner's fan does. A corner on a straight |
| 143 | | /// side would otherwise be left out of every triangle. |
| 144 | | private func fan(_ ids: [Int], _ points: [SIMD2<Double>], minimumArea: Double) -> [(Int, Int, Int)]? { |
| 145 | | for apex in ids.indices { |
| 146 | | let ring = (0..<ids.count).map { ids[(apex + $0) % ids.count] } |
| 147 | | let triangles = (1..<(ring.count - 1)).map { (ring[0], ring[$0], ring[$0 + 1]) } |
| 148 | | let flat = triangles.contains { a, b, c in |
| 149 | | let (p, q, r) = (points[a], points[b], points[c]) |
| 150 | | return ((q - p).x * (r - p).y - (q - p).y * (r - p).x) / 2 <= minimumArea |
| 175 | for v in inside { |
| 176 | // the newest triangles first: consecutive points of a lattice row lie close together |
| 177 | for k in triangles.indices.reversed() { |
| 178 | let t = triangles[k] |
| 179 | let total = area(t.x, t.y, t.z) |
| 180 | let w = [area(v, t.y, t.z), area(t.x, v, t.z), area(t.x, t.y, v)] |
| 181 | guard w.allSatisfy({ $0 >= -1e-12 * total }) else { continue } |
| 182 | if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) { |
| 183 | // on the edge opposite corner `zero`: split both triangles beside it |
| 184 | let c = [t.x, t.y, t.z] |
| 185 | let a = c[(zero + 1) % 3], b = c[(zero + 2) % 3] |
| 186 | triangles[k] = SIMD3(c[zero], a, v) |
| 187 | triangles.append(SIMD3(c[zero], v, b)) |
| 188 | if let n = triangles.indices.first(where: { n in |
| 189 | let u = triangles[n] |
| 190 | return n != k && [u.x, u.y, u.z].contains(a) && [u.x, u.y, u.z].contains(b) |
| 191 | }) { |
| 192 | let u = triangles[n] |
| 193 | let other = [u.x, u.y, u.z].first { $0 != a && $0 != b }! |
| 194 | triangles[n] = SIMD3(other, b, v) |
| 195 | triangles.append(SIMD3(other, v, a)) |
| 196 | } |
| 197 | } else { |
| 198 | triangles[k] = SIMD3(t.x, t.y, v) |
| 199 | triangles.append(SIMD3(t.y, t.z, v)) |
| 200 | triangles.append(SIMD3(t.z, t.x, v)) |
| 201 | } |
| 202 | break |
| 151 | 203 | } |
| 152 | | if !flat { return triangles } |
| 153 | 204 | } |
| 154 | | return nil |
| 155 | | } |
| 156 | 205 | |
| 157 | | /// A convex cell fanned around an added point `centre` inside it. |
| 158 | | private func fan(_ ids: [Int], around centre: Int) -> [(Int, Int, Int)] { |
| 159 | | ids.indices.map { (centre, ids[$0], ids[($0 + 1) % ids.count]) } |
| 206 | let kept = Set(boundary.indices.map { k in |
| 207 | SIMD2(min(boundary[k], boundary[(k + 1) % boundary.count]), max(boundary[k], boundary[(k + 1) % boundary.count])) |
| 208 | }) |
| 209 | // whether d lies strictly inside the circle through the counterclockwise a, b, c |
| 210 | func inCircle(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool { |
| 211 | let pa = p[a] - p[d], pb = p[b] - p[d], pc = p[c] - p[d] |
| 212 | let det = simd_length_squared(pa) * cross(pb, pc) - simd_length_squared(pb) * cross(pa, pc) |
| 213 | + simd_length_squared(pc) * cross(pa, pb) |
| 214 | return det > 1e-15 * scale * scale |
| 215 | } |
| 216 | func key(_ a: Int, _ b: Int) -> SIMD2<Int> { SIMD2(min(a, b), max(a, b)) } |
| 217 | func corners(_ k: Int) -> [Int] { [triangles[k].x, triangles[k].y, triangles[k].z] } |
| 218 | var sides: [SIMD2<Int>: [Int]] = [:] |
| 219 | for k in triangles.indices { |
| 220 | let c = corners(k) |
| 221 | for i in 0..<3 { sides[key(c[i], c[(i + 1) % 3]), default: []].append(k) } |
| 222 | } |
| 223 | var pending = sides.keys.filter { !kept.contains($0) }.sorted { ($0.x, $0.y) > ($1.x, $1.y) } |
| 224 | while let edge = pending.popLast() { |
| 225 | guard let pair = sides[edge], pair.count == 2 else { continue } |
| 226 | let (k1, k2) = (pair[0], pair[1]) |
| 227 | let first = corners(k1) |
| 228 | let i = first.firstIndex { $0 != edge.x && $0 != edge.y }! |
| 229 | let (c1, a, b) = (first[i], first[(i + 1) % 3], first[(i + 2) % 3]) |
| 230 | let c2 = corners(k2).first { $0 != edge.x && $0 != edge.y }! |
| 231 | guard inCircle(c1, a, b, c2), area(c1, a, c2) > 0, area(c2, b, c1) > 0 else { continue } |
| 232 | triangles[k1] = SIMD3(c1, a, c2) |
| 233 | triangles[k2] = SIMD3(c2, b, c1) |
| 234 | sides[edge] = nil |
| 235 | sides[key(c1, c2)] = [k1, k2] |
| 236 | sides[key(a, c2)] = sides[key(a, c2)]!.map { $0 == k2 ? k1 : $0 } |
| 237 | sides[key(b, c1)] = sides[key(b, c1)]!.map { $0 == k1 ? k2 : $0 } |
| 238 | pending += [key(c1, a), key(a, c2), key(c2, b), key(b, c1)].filter { !kept.contains($0) } |
| 239 | } |
| 240 | return triangles.map { ($0.x, $0.y, $0.z) } |
| 160 | 241 | } |
| 161 | 242 | |
| 162 | 243 | /// The indices of the three corners spanning the largest triangle, the first such in index order. |