Packages/FoldKit/Sources/Notation/EdgeOcclusion.swift
203 lines · 10074 bytes
12 symbols in this file
1import FoldFormat
2import Folding
3import simd
4
5/// The parts of `edge`, projected orthographically along `viewpoint`, that are not inside the
6/// union of the faces above either of its faces in `frame`.
7///
8/// A face is above an edge's face when it follows that face in their cluster's back-to-front list,
9/// `order.clusters` read looking along −`eye`. A face in neither of their clusters is above the
10/// edge where it lies nearer the eye; a face seen edge-on covers nothing. An edge on the outer
11/// boundary of the union stays visible; one under the seam between two upper faces, covered on
12/// both sides, does not. Where an upper face overlying one of the edge's faces meets a neighbour
13/// across a flat edge along the edge, the neighbour covers its side of that seam.
14public func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder,
15 viewpoint: Viewpoint) -> [(SIMD2<Double>, SIMD2<Double>)] {
16 Occlusion(frame: frame, file: file, order: order, viewpoint: viewpoint).visibleSegments(of: edge)
17}
18
19/// Orthographic projection onto the screen plane of a viewpoint: x along `right`, y along `up`.
20struct ViewProjection {
21 let right: SIMD3<Double>
22 let up: SIMD3<Double>
23
24 init(_ viewpoint: Viewpoint) {
25 let eye = normalize(viewpoint.eye)
26 right = normalize(cross(viewpoint.up, eye))
27 up = cross(eye, right)
28 }
29
30 func callAsFunction(_ p: SIMD3<Double>) -> SIMD2<Double> {
31 SIMD2(dot(p, right), dot(p, up))
32 }
33}
34
35/// One frame projected for a viewpoint, with each face's occluders.
36struct Occlusion {
37 let points: [SIMD2<Double>]
38 let edgesVertices: [[Int]]
39 let edgeFaces: [[Int]]
40 /// Each face's projected outline, counterclockwise.
41 let outlines: [[SIMD2<Double>]]
42 /// Each face's followers in its cluster.
43 let above: [[Int]]
44 /// Each face's cluster.
45 let cluster: [Int]
46 /// Each face's neighbours across an interior edge flat in the frame, with that edge.
47 let flatNeighbours: [[(face: Int, edge: Int)]]
48 let positions: [SIMD3<Double>]
49 let facesVertices: [[Int]]
50 let normals: [SIMD3<Double>]
51 /// The unit vector toward the eye.
52 let eye: SIMD3<Double>
53 let tolerance: Double
54
55 init(frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) {
56 let project = ViewProjection(viewpoint)
57 let points = frame.verticesCoords.map(project.callAsFunction)
58 self.points = points
59 edgesVertices = file.edgesVertices
60 edgeFaces = edgesFaces(file)
61 outlines = file.facesVertices.map { corners in
62 let outline = corners.map { points[$0] }
63 return signedArea(outline) < 0 ? outline.reversed() : outline
64 }
65 var above = Array(repeating: [Int](), count: file.facesVertices.count)
66 var cluster = Array(repeating: 0, count: file.facesVertices.count)
67 let clusters = order.clusters(positions: frame.verticesCoords, faces: file.facesVertices,
68 viewDirection: -viewpoint.eye)
69 for (k, members) in clusters.enumerated() {
70 for (i, face) in members.faces.enumerated() {
71 above[face] = Array(members.faces[(i + 1)...])
72 cluster[face] = k
73 }
74 }
75 self.above = above
76 self.cluster = cluster
77 var flatNeighbours = Array(repeating: [(face: Int, edge: Int)](), count: file.facesVertices.count)
78 for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && abs(frame.edgesFoldAngle[e]) <= 1e-9 {
79 flatNeighbours[faces[0]].append((faces[1], e))
80 flatNeighbours[faces[1]].append((faces[0], e))
81 }
82 self.flatNeighbours = flatNeighbours
83 positions = frame.verticesCoords
84 facesVertices = file.facesVertices
85 normals = faceNormals(positions: frame.verticesCoords, faces: file.facesVertices)
86 eye = normalize(viewpoint.eye)
87 let low = points.reduce(points.first ?? .zero, simd_min)
88 let high = points.reduce(points.first ?? .zero, simd_max)
89 tolerance = max(length(high - low), 1) * 1e-9
90 }
91
92 func endpoints(of edge: Int) -> (SIMD2<Double>, SIMD2<Double>) {
93 (points[edgesVertices[edge][0]], points[edgesVertices[edge][1]])
94 }
95
96 func visibleSegments(of edge: Int) -> [(SIMD2<Double>, SIMD2<Double>)] {
97 let (a, b) = endpoints(of: edge)
98 guard length(b - a) > tolerance else { return [] }
99 let occluders = Set(edgeFaces[edge].flatMap { above[$0] })
100 var covers = occluders.sorted().compactMap { cover(a, b, by: outlines[$0]) }
101 // an occluder lying over one of the edge's faces continues across a flat edge along the
102 // edge into the same layer of paper: under that seam the neighbour covers its side too
103 let overlying = Set(edgeFaces[edge].flatMap { h in
104 above[h].filter { convexPolygonsOverlap(outlines[$0], outlines[h], tolerance: tolerance) }
105 })
106 let seamed = Set(overlying.flatMap { f in
107 flatNeighbours[f].filter { alongEdge($0.edge, edge) }.map(\.face)
108 }).subtracting(occluders).subtracting(edgeFaces[edge])
109 covers += seamed.sorted().compactMap { f in
110 cover(a, b, by: outlines[f]).flatMap { $0.side == .both ? nil : $0 }
111 }
112 let own = Set(edgeFaces[edge].map { cluster[$0] })
113 for f in outlines.indices where !own.contains(cluster[f]) {
114 guard let c = cover(a, b, by: outlines[f]), let nearer = nearer(f, than: edge) else { continue }
115 let low = max(c.range.lowerBound, nearer.lowerBound), high = min(c.range.upperBound, nearer.upperBound)
116 if high - low > tolerance / length(b - a) { covers.append((low...high, c.side)) }
117 }
118
119 // between consecutive cut points coverage is constant; test each piece's midpoint
120 let cuts = Set([0.0, 1.0] + covers.flatMap { [$0.range.lowerBound, $0.range.upperBound] }).sorted()
121 var visible: [ClosedRange<Double>] = []
122 for (t0, t1) in zip(cuts, cuts.dropFirst()) where t1 > t0 {
123 let t = (t0 + t1) / 2
124 let sides = covers.filter { $0.range.contains(t) }.map(\.side)
125 let hidden = sides.contains(.both) || (sides.contains(.left) && sides.contains(.right))
126 if hidden { continue }
127 if let last = visible.last, last.upperBound == t0 {
128 visible[visible.count - 1] = last.lowerBound...t1
129 } else {
130 visible.append(t0...t1)
131 }
132 }
133 let minimum = tolerance / length(b - a)
134 return visible.filter { $0.upperBound - $0.lowerBound > minimum }
135 .map { (a + $0.lowerBound * (b - a), a + $0.upperBound * (b - a)) }
136 }
137
138 /// Whether edge `e` lies on the line of edge `other` in the frame and shares a stretch of it.
139 private func alongEdge(_ e: Int, _ other: Int) -> Bool {
140 let a = positions[edgesVertices[other][0]], b = positions[edgesVertices[other][1]]
141 let (p, q) = (positions[edgesVertices[e][0]], positions[edgesVertices[e][1]])
142 let d = b - a, length2 = length_squared(d)
143 guard length2 > 0 else { return false }
144 let off = [p, q].map { length(cross(d, $0 - a)) / length2.squareRoot() }
145 guard off.allSatisfy({ $0 <= tolerance }) else { return false }
146 let s = dot(p - a, d) / length2, t = dot(q - a, d) / length2
147 return min(max(s, t), 1) - max(min(s, t), 0) > tolerance / length2.squareRoot()
148 }
149
150 enum Side { case left, right, both }
151
152 /// The parameters of `edge` at which face `f`'s plane lies nearer the eye along the view, or
153 /// nil where it nowhere does or `f` is seen edge-on.
154 private func nearer(_ f: Int, than edge: Int) -> ClosedRange<Double>? {
155 let n = normals[f], facing = dot(n, eye)
156 guard abs(facing) > 1e-9 else { return nil }
157 let corner = positions[facesVertices[f][0]]
158 let (p, q) = (positions[edgesVertices[edge][0]], positions[edgesVertices[edge][1]])
159 // how far toward the eye the face's plane is from the edge's point at t: d0 + (d1 − d0) t
160 let d0 = dot(n, corner - p) / facing, d1 = dot(n, corner - q) / facing
161 switch (d0 > tolerance, d1 > tolerance) {
162 case (true, true): return 0...1
163 case (false, false): return nil
164 case (true, false): return 0...((d0 - tolerance) / (d0 - d1))
165 case (false, true): return ((tolerance - d0) / (d1 - d0))...1
166 }
167 }
168
169 /// The parameters of the segment `a`–`b` the counterclockwise convex `polygon` covers, and on
170 /// which side: both sides where the segment crosses its open interior, one side where the
171 /// segment lies along one of its sides.
172 private func cover(_ a: SIMD2<Double>, _ b: SIMD2<Double>,
173 by polygon: [SIMD2<Double>]) -> (range: ClosedRange<Double>, side: Side)? {
174 let d = b - a
175 var low = 0.0, high = 1.0
176 var side = Side.both
177 for i in polygon.indices {
178 let p = polygon[i], s = polygon[(i + 1) % polygon.count] - p
179 let sideLength = length(s)
180 guard sideLength > tolerance else { continue }
181 // distance inside this side's line at parameter t: c0 + c1 t
182 let c0 = perpDot(s, a - p) / sideLength, c1 = perpDot(s, d) / sideLength
183 if abs(c0) <= tolerance && abs(c0 + c1) <= tolerance {
184 side = dot(s, d) > 0 ? .left : .right
185 continue
186 }
187 if c1 == 0 {
188 if c0 <= 0 { return nil }
189 } else if c1 > 0 {
190 low = max(low, -c0 / c1)
191 } else {
192 high = min(high, -c0 / c1)
193 }
194 }
195 return high - low > tolerance / length(d) ? (low...high, side) : nil
196 }
197}
198
199func perpDot(_ u: SIMD2<Double>, _ v: SIMD2<Double>) -> Double { u.x * v.y - u.y * v.x }
200
201func signedArea(_ p: [SIMD2<Double>]) -> Double {
202 p.indices.reduce(0) { sum, i in sum + perpDot(p[i], p[(i + 1) % p.count]) / 2 }
203}