| @@ -0,0 +1,173 @@ |
| |
1 | import FoldFormat |
| |
2 | import simd |
| |
3 | |
| |
4 | /// How long after a face starts moving, and before it stops, its side of a still face is read, as |
| |
5 | /// a fraction of the window of the axis that starts or stops it. The compiler's layer-order guess |
| |
6 | /// reads arrivals at the same moment. |
| |
7 | private let lead = 1e-3 |
| |
8 | /// Two unit normals whose dot product's magnitude reaches this lie on one line. |
| |
9 | private let parallelCosine = 1 - 1e-9 |
| |
10 | /// Lengths are compared to within this fraction of the sheet's longer side. |
| |
11 | private let relativeTolerance = 1e-6 |
| |
12 | /// A face closer than this fraction of the sheet's size to a still face's plane is on neither side. |
| |
13 | private let separationTolerance = 1e-9 |
| |
14 | |
| |
15 | /// Faces that pass through a still face as they start or finish moving: the coplanar contact that |
| |
16 | /// the validator, which reads one frame at a time, and the interpenetration checker, which skips |
| |
17 | /// coplanar faces, cannot see. |
| |
18 | /// |
| |
19 | /// In step n, a moving face that overlaps a still face in frame n − 1 may not leave toward the |
| |
20 | /// side of it opposite the one frame n − 1's `faceOrders` give, read just after the face starts |
| |
21 | /// moving; a moving face that overlaps a still face in frame n may not arrive from the side |
| |
22 | /// opposite the one frame n's `faceOrders` give, read just before it stops. Pairs the orders do |
| |
23 | /// not relate are not checked. A face is still when none of the step's axes moves it, counting a |
| |
24 | /// non-rigid step's open and close axes, so the faces that open on the spine are moving. |
| |
25 | /// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the |
| |
26 | /// pop between is not. Turn-over and rotate steps move every face together and have no still face. |
| |
27 | /// |
| |
28 | /// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped. |
| |
29 | public func layerMotionDefects(_ file: FoldFile) -> [FoldDefect] { |
| |
30 | let size = sheetExtent(file) |
| |
31 | var defects: [FoldDefect] = [] |
| |
32 | for n in file.frames.indices.dropFirst() { |
| |
33 | guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else { |
| |
34 | continue |
| |
35 | } |
| |
36 | let pop = step.nonRigid ? step.pop : nil |
| |
37 | let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes |
| |
38 | let moving = (step.axes + departing + arriving).reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) } |
| |
39 | let interpolator = FoldInterpolator(file: file, step: step) |
| |
40 | let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in |
| |
41 | crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) }, |
| |
42 | interpolator: interpolator, file: file, size: size) |
| |
43 | } |
| |
44 | var reported = Set<SIMD2<Int>>() |
| |
45 | for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false) |
| |
46 | where reported.insert(SIMD2(m, s)).inserted { |
| |
47 | defects.append(.movesThroughStillFace(step: n, moving: m, still: s)) |
| |
48 | } |
| |
49 | } |
| |
50 | return defects |
| |
51 | } |
| |
52 | |
| |
53 | /// The pairs `(moving, still)` in which a face `axes` move is, just after it starts moving |
| |
54 | /// (`departure`) or just before it stops, on the side of a still face it overlaps in `frame` |
| |
55 | /// opposite the one `frame`'s orders give. |
| |
56 | private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, still: (Int) -> Bool, |
| |
57 | interpolator: FoldInterpolator, file: FoldFile, size: Double) -> [(Int, Int)] { |
| |
58 | let tolerance = size * relativeTolerance |
| |
59 | let faces = file.facesVertices |
| |
60 | let points = frame.verticesCoords |
| |
61 | let normals = faceNormals(positions: points, faces: faces) |
| |
62 | var axisOfFace: [Int: Int] = [:] |
| |
63 | for (a, axis) in axes.enumerated() { |
| |
64 | for f in axis.movingFaces { axisOfFace[f] = a } |
| |
65 | } |
| |
66 | |
| |
67 | var sampled: [Double: [SIMD3<Double>]] = [:] |
| |
68 | var result: [(Int, Int)] = [] |
| |
69 | for m in axisOfFace.keys.sorted() where normals[m] != .zero { |
| |
70 | var carriers: [Int] = [], a = axisOfFace[m] |
| |
71 | while let axis = a, !carriers.contains(axis) { |
| |
72 | carriers.append(axis) |
| |
73 | a = axes[axis].parent |
| |
74 | } |
| |
75 | let windows = carriers.map { axes[$0].window } |
| |
76 | let t: Double |
| |
77 | if departure { |
| |
78 | let w = windows.min { $0.lowerBound < $1.lowerBound }! |
| |
79 | t = w.lowerBound + lead * (w.upperBound - w.lowerBound) |
| |
80 | } else { |
| |
81 | let w = windows.max { $0.upperBound < $1.upperBound }! |
| |
82 | t = w.upperBound - lead * (w.upperBound - w.lowerBound) |
| |
83 | } |
| |
84 | let near = sampled[t] ?? interpolator.positions(at: t) |
| |
85 | sampled[t] = near |
| |
86 | |
| |
87 | for s in faces.indices where s != m && still(s) && normals[s] != .zero |
| |
88 | && overlap(m, s, points, faces, normals, tolerance: tolerance) { |
| |
89 | guard let side = side(of: m, from: s, frame.faceOrders, normals) else { continue } |
| |
90 | let centre = overlapCentre(m, s, points, faces, normals) |
| |
91 | let offset = dot(carry(centre, on: faces[m], from: points, to: near) - centre, normals[s]) |
| |
92 | if abs(offset) > size * separationTolerance && (offset > 0) != (side > 0) { |
| |
93 | result.append((m, s)) |
| |
94 | } |
| |
95 | } |
| |
96 | } |
| |
97 | return result |
| |
98 | } |
| |
99 | |
| |
100 | /// The side of face `s` along its normal on which `orders` put face `m`: +1 the side the normal |
| |
101 | /// points toward, −1 the other, nil when no triple relates them. |
| |
102 | private func side(of m: Int, from s: Int, _ orders: [[Int]], _ normals: [SIMD3<Double>]) -> Int? { |
| |
103 | for t in orders where t.count == 3 && (t[2] == 1 || t[2] == -1) { |
| |
104 | if t[0] == m && t[1] == s { return t[2] } |
| |
105 | if t[0] == s && t[1] == m { return dot(normals[m], normals[s]) > 0 ? -t[2] : t[2] } |
| |
106 | } |
| |
107 | return nil |
| |
108 | } |
| |
109 | |
| |
110 | /// Whether faces `a` and `b` lie in one plane and their interiors overlap. |
| |
111 | private func overlap(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>], |
| |
112 | tolerance: Double) -> Bool { |
| |
113 | guard abs(dot(normals[a], normals[b])) >= parallelCosine else { return false } |
| |
114 | let corner = points[faces[b][0]] |
| |
115 | guard faces[a].allSatisfy({ abs(dot(points[$0] - corner, normals[b])) <= tolerance }) else { return false } |
| |
116 | let (u, v) = planeBasis(normals[b]) |
| |
117 | let project = { (f: Int) in faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) } } |
| |
118 | return convexPolygonsOverlap(project(a), project(b), tolerance: tolerance) |
| |
119 | } |
| |
120 | |
| |
121 | /// The centroid of the overlap of two coplanar faces, in the plane of `b`. |
| |
122 | private func overlapCentre(_ a: Int, _ b: Int, _ points: [SIMD3<Double>], _ faces: [[Int]], |
| |
123 | _ normals: [SIMD3<Double>]) -> SIMD3<Double> { |
| |
124 | let n = normals[b] |
| |
125 | let (u, v) = planeBasis(n) |
| |
126 | let project = { (f: Int) in counterclockwise(faces[f].map { SIMD2(dot(points[$0], u), dot(points[$0], v)) }) } |
| |
127 | var common = project(a) |
| |
128 | let clip = project(b) |
| |
129 | for i in clip.indices where !common.isEmpty { |
| |
130 | common = keepLeft(of: clip[i], clip[(i + 1) % clip.count], common) |
| |
131 | } |
| |
132 | let c = centroid(common) |
| |
133 | return c.x * u + c.y * v + dot(points[faces[b][0]], n) * n |
| |
134 | } |
| |
135 | |
| |
136 | /// `point`, a point of the face with corners `corners` at `from`, where the same point of paper |
| |
137 | /// is at `to`. Both states place the face rigidly. |
| |
138 | private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>], |
| |
139 | to: [SIMD3<Double>]) -> SIMD3<Double> { |
| |
140 | let first = corners[0] |
| |
141 | let far = corners.max { distance(from[$0], from[first]) < distance(from[$1], from[first]) }! |
| |
142 | func frame(_ p: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>) { |
| |
143 | let u = normalize(p[far] - p[first]) |
| |
144 | let n = faceNormals(positions: p, faces: [corners])[0] |
| |
145 | return (u, cross(n, u), n) |
| |
146 | } |
| |
147 | let (u, v, n) = frame(from), (u2, v2, n2) = frame(to) |
| |
148 | let d = point - from[first] |
| |
149 | return to[first] + dot(d, u) * u2 + dot(d, v) * v2 + dot(d, n) * n2 |
| |
150 | } |
| |
151 | |
| |
152 | /// The part of convex polygon `p` to the left of the directed line from `a` to `b`. |
| |
153 | private func keepLeft(of a: SIMD2<Double>, _ b: SIMD2<Double>, _ p: [SIMD2<Double>]) -> [SIMD2<Double>] { |
| |
154 | let d = b - a |
| |
155 | let side = p.map { d.x * ($0.y - a.y) - d.y * ($0.x - a.x) } |
| |
156 | var result: [SIMD2<Double>] = [] |
| |
157 | for i in p.indices { |
| |
158 | let j = (i + 1) % p.count |
| |
159 | if side[i] >= 0 { result.append(p[i]) } |
| |
160 | if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) { |
| |
161 | result.append(p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j]))) |
| |
162 | } |
| |
163 | } |
| |
164 | return result |
| |
165 | } |
| |
166 | |
| |
167 | /// The longer side of frame 0's bounding box. |
| |
168 | private func sheetExtent(_ file: FoldFile) -> Double { |
| |
169 | let points = file.frames[0].verticesCoords |
| |
170 | let lower = points.dropFirst().reduce(points[0], simd_min) |
| |
171 | let upper = points.dropFirst().reduce(points[0], simd_max) |
| |
172 | return (upper - lower).max() |
| |
173 | } |