Packages/FoldKit/Sources/Notation/DiagramBuilder.swift
254 lines · 12310 bytes
14 symbols in this file
1import FoldFormat
2import Folding
3import simd
4
5public enum DiagramLine: Equatable, Sendable {
6 /// `B` edges and creases folded in the drawn frame.
7 case solid
8 /// Creases made in an earlier step and flat again.
9 case light
10 /// The step's valley, as seen.
11 case dashed
12 /// The step's mountain, as seen.
13 case dashDot
14}
15
16/// A diagram symbol in screen coordinates, the drawn frame projected along the step's viewpoint
17/// in the sheet's units. A fold arrow curves from `from`, a point of the moving set before the
18/// step, through `over`, the apex of its arc, to `to`, the same point after the fold (at the peak
19/// for a fold-and-unfold).
20public enum DiagramArrow: Equatable, Sendable {
21 case valleyFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>)
22 case mountainFold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>)
23 case foldAndUnfold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>, mountain: Bool)
24 /// A crease folded before the step opened out again.
25 case unfold(from: SIMD2<Double>, over: SIMD2<Double>, to: SIMD2<Double>)
26 /// The technique's symbol at the midpoint of the step's first crease, pointing toward where
27 /// that axis's moving set ends.
28 case technique(StepTechnique, at: SIMD2<Double>, toward: SIMD2<Double>)
29 case turnOver(TurnOverAxis)
30 /// Counterclockwise as seen when positive.
31 case rotate(degrees: Double)
32 /// The step repeats step `of`.
33 case repeatMark(of: Int)
34}
35
36/// A visible piece of FOLD edge `edge`, in the arrows' screen coordinates.
37public struct DiagramEdge: Equatable, Sendable {
38 public let edge: Int
39 public let from: SIMD2<Double>
40 public let to: SIMD2<Double>
41 public let style: DiagramLine
42
43 public init(edge: Int, from: SIMD2<Double>, to: SIMD2<Double>, style: DiagramLine) {
44 self.edge = edge
45 self.from = from
46 self.to = to
47 self.style = style
48 }
49}
50
51/// Edges in FOLD edge order.
52public struct Diagram: Equatable, Sendable {
53 public let edges: [DiagramEdge]
54 public let arrows: [DiagramArrow]
55
56 public init(edges: [DiagramEdge], arrows: [DiagramArrow]) {
57 self.edges = edges
58 self.arrows = arrows
59 }
60}
61
62/// The arc's apex lies this fraction of the chord from the chord's midpoint.
63private let arcBulge = 0.3
64
65/// The diagram for step `step.index`: frame `step.index − 1` seen orthographically from the
66/// step's viewpoint, with the step's creases and symbols.
67///
68/// Edges whose `edges_krz:firstCreasedAtStep` is later than the step, and subdivision edges, are
69/// not drawn. An edge the step creases (its two faces move differently) is dashed for a valley as
70/// seen and dash-dot for a mountain, whatever its assignment, unless it is folded in the drawn
71/// frame; `B` edges and folded creases are solid; earlier creases flat again are light. An axis
72/// that moves toward flat gets the unfold arrow. Each edge is clipped by `visibleSegments`, and
73/// a piece coincident with one already drawn is drawn once, step creases before solid before light.
74///
75/// - Precondition: `validate(file)` is empty.
76public func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram {
77 let n = step.index
78 let frame = file.frames[n - 1]
79 let normals = faceNormals(frame, file)
80 // a validated frame's orders have no cycle
81 let order = try! LayerOrder(faceOrders: frame.faceOrders, normals: normals)
82 let occlusion = Occlusion(frame: frame, file: file, order: order, viewpoint: step.viewpoint)
83 let eye = step.viewpoint.eye
84
85 let valley = step.axes.map { axis -> Bool in
86 let face = occlusion.edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }!
87 let turn = (step.kind == .foldAndUnfold ? axis.peakAngle ?? axis.endAngle : axis.endAngle) - axis.startAngle
88 return turn * dot(normals[face], eye) > 0
89 }
90 let creasing = creasingAxes(step, faceCount: file.facesVertices.count, edgeFaces: occlusion.edgeFaces)
91
92 var candidates: [(edge: Int, style: DiagramLine, rank: Int)] = []
93 for e in file.edgesVertices.indices {
94 let created = file.edgesFirstCreasedAtStep[e]
95 if let created, created > n { continue }
96 if frame.edgesAssignment[e] == .boundary {
97 candidates.append((e, .solid, 1))
98 } else if created == nil {
99 continue
100 } else if let axis = creasing[e], abs(frame.edgesFoldAngle[e]) <= 1e-9 {
101 candidates.append((e, valley[axis] ? .dashed : .dashDot, 0))
102 } else if abs(frame.edgesFoldAngle[e]) > 1e-9 {
103 candidates.append((e, .solid, 1))
104 } else if created! < n {
105 candidates.append((e, .light, 2))
106 }
107 }
108 candidates.sort { ($0.rank, $0.edge) < ($1.rank, $1.edge) }
109
110 var drawn: [DiagramEdge] = []
111 for c in candidates {
112 for (a, b) in occlusion.visibleSegments(of: c.edge) {
113 for (p, q) in uncovered(a, b, by: drawn, tolerance: occlusion.tolerance) {
114 drawn.append(DiagramEdge(edge: c.edge, from: p, to: q, style: c.style))
115 }
116 }
117 }
118 let edges = drawn.enumerated().sorted { ($0.element.edge, $0.offset) < ($1.element.edge, $1.offset) }.map(\.element)
119 let symbols = arrows(file, step, valley: valley, project: ViewProjection(step.viewpoint),
120 edgeFaces: occlusion.edgeFaces)
121 return Diagram(edges: edges, arrows: symbols)
122}
123
124/// For each edge, the index in `step.axes` of the axis whose motion creases it, or nil. Each face
125/// belongs to the axis whose moving set holds it, or to the fixed group; an edge is creased when
126/// its faces' groups differ, by the deeper group's axis.
127private func creasingAxes(_ step: FoldStep, faceCount: Int, edgeFaces: [[Int]]) -> [Int?] {
128 var group = Array<Int?>(repeating: nil, count: faceCount)
129 for (i, axis) in step.axes.enumerated() {
130 for f in axis.movingFaces { group[f] = i }
131 }
132 func depth(_ axis: Int?) -> Int {
133 guard let axis else { return -1 }
134 return 1 + depth(step.axes[axis].parent)
135 }
136 return edgeFaces.map { faces in
137 guard faces.count == 2, group[faces[0]] != group[faces[1]] else { return nil }
138 let (a, b) = (group[faces[0]], group[faces[1]])
139 return depth(a) >= depth(b) ? a : b
140 }
141}
142
143/// The parts of `a`–`b` not lying along an edge already drawn.
144private func uncovered(_ a: SIMD2<Double>, _ b: SIMD2<Double>, by drawn: [DiagramEdge],
145 tolerance: Double) -> [(SIMD2<Double>, SIMD2<Double>)] {
146 let d = b - a, length2 = length_squared(d)
147 let normal = normalize(SIMD2(-d.y, d.x))
148 var covered: [ClosedRange<Double>] = []
149 for e in drawn where abs(dot(e.from - a, normal)) <= tolerance && abs(dot(e.to - a, normal)) <= tolerance {
150 let s = dot(e.from - a, d) / length2, t = dot(e.to - a, d) / length2
151 let low = max(min(s, t), 0), high = min(max(s, t), 1)
152 if high > low { covered.append(low...high) }
153 }
154 var pieces: [ClosedRange<Double>] = []
155 var start = 0.0
156 for range in covered.sorted(by: { $0.lowerBound < $1.lowerBound }) {
157 if range.lowerBound > start { pieces.append(start...range.lowerBound) }
158 start = max(start, range.upperBound)
159 }
160 if start < 1 { pieces.append(start...1) }
161 let minimum = tolerance / length2.squareRoot()
162 return pieces.filter { $0.upperBound - $0.lowerBound > minimum }
163 .map { (a + $0.lowerBound * d, a + $0.upperBound * d) }
164}
165
166private func arrows(_ file: FoldFile, _ step: FoldStep, valley: [Bool], project: ViewProjection,
167 edgeFaces: [[Int]]) -> [DiagramArrow] {
168 var arrows: [DiagramArrow] = []
169 let start = file.frames[step.index - 1].verticesCoords
170 switch step.kind {
171 case .turnOver:
172 if let axis = step.turnOverAxis { arrows.append(.turnOver(axis)) }
173 case .rotate:
174 if let degrees = step.rotateDegrees { arrows.append(.rotate(degrees: degrees)) }
175 case .fold, .foldAndUnfold:
176 let interpolator = step.kind == .foldAndUnfold ? FoldInterpolator(file: file, step: step) : nil
177 // a point of the axis's moving set and where it is at the end of the step, or at the peak
178 func track(_ axis: FoldAxis, _ point: SIMD3<Double>) -> (SIMD2<Double>, SIMD2<Double>) {
179 let end = interpolator?.positions(at: (axis.window.lowerBound + axis.window.upperBound) / 2)
180 ?? file.frames[step.index].verticesCoords
181 let face = edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }!
182 return (project(point), project(carried(point, with: file.facesVertices[face], from: start, to: end)))
183 }
184 if step.technique != .plain {
185 guard let axis = step.axes.first else { break }
186 let ends = file.edgesVertices[axis.edge].map { project(start[$0]) }
187 let toward = track(axis, centroid(of: axis.movingFaces, file, positions: start)).1
188 arrows.append(.technique(step.technique, at: (ends[0] + ends[1]) / 2, toward: toward))
189 break
190 }
191 // simultaneous arrows are spread along their creases, in one screen direction, so that
192 // they do not meet
193 let count = Double(step.axes.count)
194 for (i, axis) in step.axes.enumerated() {
195 let ends = file.edgesVertices[axis.edge].map { start[$0] }
196 let shift = (Double(i) - (count - 1) / 2) / (count + 1) * distance(ends[0], ends[1])
197 let along = project(axis.direction)
198 let sign = along.y < -1e-9 || (abs(along.y) <= 1e-9 && along.x < 0) ? -1.0 : 1.0
199 let point = centroid(of: axis.movingFaces, file, positions: start) + sign * shift * axis.direction
200 let (from, to) = track(axis, point)
201 let over = apex(from, to)
202 if step.kind == .foldAndUnfold {
203 arrows.append(.foldAndUnfold(from: from, over: over, to: to, mountain: !valley[i]))
204 } else if abs(axis.endAngle) < abs(axis.startAngle) - 1e-9 {
205 arrows.append(.unfold(from: from, over: over, to: to))
206 } else if valley[i] {
207 arrows.append(.valleyFold(from: from, over: over, to: to))
208 } else {
209 arrows.append(.mountainFold(from: from, over: over, to: to))
210 }
211 }
212 }
213 if let repeated = step.repeatOf { arrows.append(.repeatMark(of: repeated)) }
214 return arrows
215}
216
217/// The area-weighted mean of the faces' vertex means.
218private func centroid(of faces: Set<Int>, _ file: FoldFile, positions: [SIMD3<Double>]) -> SIMD3<Double> {
219 var sum = SIMD3<Double>.zero, total = 0.0
220 for f in faces.sorted() {
221 let corners = file.facesVertices[f].map { positions[$0] }
222 let area = length(corners.indices.reduce(SIMD3<Double>.zero) { s, i in
223 s + simd.cross(corners[i], corners[(i + 1) % corners.count])
224 }) / 2
225 sum += area * corners.reduce(.zero, +) / Double(corners.count)
226 total += area
227 }
228 return sum / total
229}
230
231/// `point` moved rigidly with the face whose corners are `corners`, from `start` to `end`.
232private func carried(_ point: SIMD3<Double>, with corners: [Int], from start: [SIMD3<Double>],
233 to end: [SIMD3<Double>]) -> SIMD3<Double> {
234 let o = start[corners[0]], u = start[corners[1]] - o
235 // the corner farthest from the line of the first two spans the face's plane best
236 let spread = { (i: Int) in length(cross(u, start[corners[i]] - o)) }
237 let k = corners.indices.dropFirst(2).max { spread($0) < spread($1) }!
238 func basis(_ x: [SIMD3<Double>]) -> simd_double3x3 {
239 let e1 = x[corners[1]] - x[corners[0]], e2 = x[corners[k]] - x[corners[0]]
240 return simd_double3x3(columns: (e1, e2, normalize(cross(e1, e2))))
241 }
242 return end[corners[0]] + basis(end) * (basis(start).inverse * (point - o))
243}
244
245/// The apex of an arc from `from` to `to`, to the side of the chord toward screen-up, or toward
246/// screen-right for a vertical chord.
247private func apex(_ from: SIMD2<Double>, _ to: SIMD2<Double>) -> SIMD2<Double> {
248 let chord = to - from
249 var side = SIMD2(-chord.y, chord.x)
250 if side.y < -1e-12 * length(chord) || (abs(side.y) <= 1e-12 * length(chord) && side.x < 0) {
251 side = -side
252 }
253 return (from + to) / 2 + arcBulge * side
254}