Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift
420 lines · 23763 bytes
21 symbols in this file
1import FoldFormat
2import Folding
3import simd
4
5/// The spine's fold angle when the flap is open, in degrees from flat, when the script gives none
6/// (decision 0003).
7private let defaultOpenAngle = 20.0
8/// The boundaries of the pop on the step's t (decision 0002).
9private let phases = [1.0 / 3, 2.0 / 3]
10/// The largest relative change in a render-mesh edge's length the pop may reach (decision 0002).
11private let strainBound = 0.10
12/// Samples of the pop measured for strain.
13private let popSamples = 64
14/// Samples of the open and close phases along which end angles are unwrapped.
15private let angleSamples = 256
16
17/// Decision 0002's open, pop and close for step `n`, whose script names the `spine` its flap opens
18/// on, with decision 0003's opening. `before` is frame n − 1; `after` is frame n as the step's axes
19/// place it, carrying the step's record; `file` holds frames 0…n − 1.
20///
21/// The flap opens on the opening crease: `openOn`, or the named spine crease. Both are folded flat.
22/// The paper is cut along every edge on either crease's line in `before`, and, with `openOn`, along
23/// the creases of the earlier reverse fold that opened on `openOn` and whose flap holds this
24/// step's. Of the opening crease's line, the edges whose faces then fall on different sides are
25/// kept; of the spine's, those whose faces fall on different sides of the two lines alone, the
26/// paper's halves. Each kept edge is folded flat or flat; a flat one is a bend line, which bends
27/// while the flap is open and is never creased. The side of the opening crease nearer the viewpoint
28/// opens, with the earlier fold's flap: the open axes are a tree grown from the other faces across
29/// the kept edges, the opening crease first and driven from ±180 to ±`openAngle`, the earlier
30/// fold's creases and the spine solved to keep the paper whole. The pop and close move on a tree
31/// cut along those edges and the step's creases, grown from the faces neither the opening nor the
32/// step moves, the opening crease first. In `popped` the opening crease and the spine's edges in
33/// the flap are held as the open phase leaves them, the latter reversed, and the other tree axes
34/// are solved, starting where the open phase leaves them or `openAngle / 180` of their way. The
35/// close axes drive the opening crease back to ±180 and solve the rest, as for a rigid step, and
36/// must arrive at `after`'s coordinates. The record's `spine` holds the kept edges of both lines.
37///
38/// The starting guess can lead the solver to another branch of the vertex's motion. Closing the
39/// loops does not catch that: every branch is closed. A branch is caught when the close does not
40/// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the
41/// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixtures'
42/// tests that the tip lands between the flap's layers cover them. `layerMotionDefects` does not
43/// add a check here: frame n's orders for the faces the step's axes move are guessed from the same
44/// close, read near the same moment.
45///
46/// - Throws: `unresolvedCrease` when the spine or `openOn` names no edge, `invalidSpine` when one
47/// of them is not folded flat or a kept edge is neither folded flat nor flat, `noRigidMotion`
48/// when the flap cannot open, `popped` does not close or the close does not reach `after`, and
49/// `popTooStrained` when the pop's strain exceeds 10%, `noEarlierOpening` when no earlier reverse
50/// fold holding the flap opened on `openOn`.
51public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame,
52 file: FoldFile) throws -> PopRecord {
53 guard let reference = script.spine, let record = after.step else {
54 preconditionFailure("compilePop needs a script step with a spine and a frame with its record")
55 }
56 let edgeFaces = edgesFaces(file)
57 let faceCount = file.facesVertices.count
58 let tolerance = sheetExtent(file) * relativeTolerance
59 let openAngle = script.openAngle ?? defaultOpenAngle
60 func foldedFlat(_ e: Int) -> Bool { abs(abs(before.edgesFoldAngle[e]) - 180) <= angleSnapTolerance }
61 func edge(_ ref: CreaseRef) throws -> Int {
62 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) }
63 guard foldedFlat(e) else { throw CompileError.invalidSpine(step: n) }
64 return e
65 }
66 let named = try edge(reference)
67 let opener = try script.openOn.map(edge) ?? named
68
69 var group = Array(repeating: -1, count: faceCount)
70 for (a, axis) in record.axes.enumerated() {
71 for f in axis.movingFaces { group[f] = a }
72 }
73 let moving = group.map { $0 >= 0 }
74 let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] }
75
76 // the earlier reverse fold this step's flap is in, which opened on the opening crease
77 let tip = Set((0..<faceCount).filter { moving[$0] })
78 let earlier = script.openOn == nil ? nil : (1..<n).reversed().lazy.compactMap { file.frames[$0].step }.first { s in
79 s.nonRigid && s.pop?.spine.contains(opener) == true && tip.isSubset(of: s.axes.flatMap(\.movingFaces))
80 }
81 if script.openOn != nil && earlier == nil { throw CompileError.noEarlierOpening(step: n) }
82 let earlierFlap = Set(earlier?.axes.flatMap(\.movingFaces) ?? [])
83 let earlierCreases = edgeFaces.indices.filter { e in
84 edgeFaces[e].count == 2 && earlierFlap.contains(edgeFaces[e][0]) != earlierFlap.contains(edgeFaces[e][1])
85 }
86
87 // edges on a line whose faces stay connected without it lie within one side
88 let openerLine = onLine(opener, before, file, edgeFaces, tolerance)
89 let spineLine = onLine(named, before, file, edgeFaces, tolerance)
90 let sides = regions(cut: Set(openerLine + earlierCreases + spineLine), file, edgeFaces)
91 func across(_ e: Int) -> Bool { sides[edgeFaces[e][0]] != sides[edgeFaces[e][1]] }
92 let openLine = openerLine.filter(across)
93 // the spine joins the paper's two halves, split by the two lines alone: an edge on the spine's
94 // line inside the earlier fold's flap can be cut off by its creases yet join layers of one half
95 let halves = regions(cut: Set(openerLine + spineLine), file, edgeFaces)
96 let spine = spineLine.filter { halves[edgeFaces[$0][0]] != halves[edgeFaces[$0][1]] }
97 guard (openLine + spine).allSatisfy({ foldedFlat($0) || abs(before.edgesFoldAngle[$0]) <= angleSnapTolerance }) else {
98 throw CompileError.invalidSpine(step: n)
99 }
100 let tipSpine = Set(spine.filter { edgeFaces[$0].allSatisfy(tip.contains) })
101
102 // the layer nearer the viewer opens: of the opening crease's faces, the one a valley puts on
103 // the first face's normal side, or a mountain on the other
104 let (f, g) = (edgeFaces[opener][0], edgeFaces[opener][1])
105 let normals = faceNormals(before, file)
106 let gNearer = (before.edgesFoldAngle[opener] > 0) == (dot(normals[f], record.viewpoint.eye) > 0)
107 let (near, far) = gNearer ? (g, f) : (f, g)
108 guard sides[far] != sides[near], !earlierFlap.contains(far) else { throw CompileError.noRigidMotion(step: n) }
109 let opening = Set((0..<faceCount).filter { sides[$0] == sides[near] || earlierFlap.contains($0) })
110 let openEdges = unique(openLine + earlierCreases + spine)
111 let openTree = growTree(order: openEdges, fixed: Set((0..<faceCount).filter { !opening.contains($0) }),
112 file, edgeFaces)
113 guard openTree.axes.first?.edge == opener else { throw CompileError.noRigidMotion(step: n) }
114 let openSign = before.edgesFoldAngle[opener] > 0 ? 1.0 : -1.0
115 let openAxes = try openingAxes(n, openTree, end: openSign * openAngle, before: before, record, file)
116 let opened = try openEndAngles(n, openAxes, edges: openEdges, before: before, record, file)
117
118 // the tree the pop and the close move on
119 let fixed = Set((0..<faceCount).filter { !moving[$0] && !opening.contains($0) })
120 guard !fixed.isEmpty else { throw CompileError.noRigidMotion(step: n) }
121 let order = unique(openEdges + record.axes.map(\.edge) + creased)
122 let tree = growTree(order: order, fixed: fixed, file, edgeFaces)
123
124 // popped: the open edges as the opening leaves them, the spine reversed in the flap; the rest
125 // solved. The close returns the open edges to where they were, the spine reversed in the flap.
126 func closed(_ e: Int) -> Double {
127 opened[e] == nil ? after.edgesFoldAngle[e] : (tipSpine.contains(e) ? -1 : 1) * before.edgesFoldAngle[e]
128 }
129 var guess: [Int: Double] = [:]
130 for axis in tree.axes {
131 let start = before.edgesFoldAngle[axis.edge]
132 guess[axis.edge] = opened[axis.edge].map { tipSpine.contains(axis.edge) ? -$0 : $0 }
133 ?? start + (closed(axis.edge) - start) * openAngle / 180
134 }
135 let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(openLine).union(tipSpine),
136 record, file)
137 var poppedFrame = before
138 poppedFrame.verticesCoords = popped.positions
139
140 let closeAxes = try closing(n, tree, from: poppedFrame, start: popped.angles, end: closed, record, file)
141 let pop = PopRecord(spine: unique(spine + openLine), openAngle: openAngle, phases: phases, openAxes: openAxes,
142 popped: popped.positions, closeAxes: closeAxes)
143 var draft = file
144 draft.frames.append(FoldFrame(verticesCoords: after.verticesCoords, edgesAssignment: after.edgesAssignment,
145 edgesFoldAngle: after.edgesFoldAngle, faceOrders: [], step: withPop(record, pop)))
146 let interpolator = FoldInterpolator(file: draft, step: try readStep(n, in: draft))
147 guard zip(interpolator.positions(at: 1), after.verticesCoords).allSatisfy({ simd_distance($0, $1) <= tolerance }) else {
148 throw CompileError.noRigidMotion(step: n)
149 }
150 let worst = (0...popSamples).map { k in
151 let t = phases[0] + Double(k) / Double(popSamples) * (phases[1] - phases[0])
152 return strain(interpolator.meshPositions(at: t), mesh: interpolator.mesh)
153 }.max() ?? 0
154 guard worst <= strainBound else { throw CompileError.popTooStrained(step: n, strain: worst) }
155 return pop
156}
157
158/// `edges` without repeats, in order.
159private func unique(_ edges: [Int]) -> [Int] {
160 var seen = Set<Int>()
161 return edges.filter { seen.insert($0).inserted }
162}
163
164/// The open axes on `[0, phases[0]]`: the tree's first axis, the opening crease, linear from its
165/// angle in `before` to `end`; the axes on a loop's cycle solved so the loops close, continued
166/// from `before` along the window to find where they end and then solved as for a rigid step; the
167/// rest held.
168private func openingAxes(_ n: Int, _ tree: RegionTree, end: Double, before: FoldFrame, _ record: StepRecord,
169 _ file: FoldFile) throws -> [AxisRecord] {
170 let opener = tree.axes[0].edge
171 func draft(_ ends: [Int: Double]) -> (StepRecord, FoldFile) {
172 let axes = records(tree, start: { before.edgesFoldAngle[$0] }, end: { ends[$0] ?? before.edgesFoldAngle[$0] },
173 window: [0, phases[0]])
174 let open = withAxes(record, axes)
175 var draft = file
176 draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment,
177 edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], step: open))
178 return (open, draft)
179 }
180 let (held, heldFile) = draft([opener: end])
181 guard !tree.loops.isEmpty else { return held.axes }
182 let step = try readStep(n, in: heldFile)
183 let driver = step.axes.firstIndex { $0.edge == opener }!
184 let free = axesOnCycles(step, loops: tree.loops, heldFile).subtracting([driver]).sorted()
185 guard !free.isEmpty else { return held.axes }
186
187 let kinematics = LoopKinematics(step: step, file: heldFile)
188 let tolerance = sheetExtent(file) * relativeTolerance
189 var previous = step.axes.map(\.startAngle), angles = previous
190 for k in 1...angleSamples {
191 var guess = zip(angles, previous).map { 2 * $0 - $1 }
192 guess[driver] = step.axes[driver].startAngle + Double(k) / Double(angleSamples) * (end - step.axes[driver].startAngle)
193 guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) }
194 (previous, angles) = (angles, guess)
195 }
196 let (open, openFile) = draft(Dictionary(uniqueKeysWithValues: zip(step.axes.map(\.edge), angles)))
197 let solved = try solveLoops(n, open, try readStep(n, in: openFile), loops: tree.loops, openFile)
198 var solvedFile = openFile
199 solvedFile.frames[n].step = solved
200 try checkClosure(n, try readStep(n, in: solvedFile), driver: opener, solvedFile,
201 solved: solved.axes.contains { $0.angles != nil })
202 return solved.axes
203}
204
205/// `named` and every other interior edge on its line in `frame`.
206private func onLine(_ named: Int, _ frame: FoldFrame, _ file: FoldFile, _ edgeFaces: [[Int]],
207 _ tolerance: Double) -> [Int] {
208 let ends = file.edgesVertices[named].map { frame.verticesCoords[$0] }
209 return [named] + edgeFaces.indices.filter { e in
210 e != named && edgeFaces[e].count == 2
211 && file.edgesVertices[e].allSatisfy { onLine(frame.verticesCoords[$0], ends[0], ends[1], tolerance) }
212 }
213}
214
215/// The fold angle of each of `edges` where `openAxes` leave the paper at the end of the open
216/// phase, measured from the faces' normals along it and unwrapped from `before`'s angle.
217private func openEndAngles(_ n: Int, _ openAxes: [AxisRecord], edges: [Int], before: FoldFrame,
218 _ record: StepRecord, _ file: FoldFile) throws -> [Int: Double] {
219 var draft = file
220 draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment,
221 edgesFoldAngle: before.edgesFoldAngle, faceOrders: [],
222 step: withAxes(record, openAxes)))
223 let interpolator = FoldInterpolator(file: draft, step: try readStep(n, in: draft))
224 let edgeFaces = edgesFaces(file)
225 var current = Dictionary(uniqueKeysWithValues: edges.map { ($0, before.edgesFoldAngle[$0]) })
226 for k in 1...angleSamples {
227 let positions = interpolator.positions(at: phases[0] * Double(k) / Double(angleSamples))
228 let normals = faceNormals(positions: positions, faces: file.facesVertices)
229 for e in edges {
230 let measured = dihedral(e, edgeFaces[e], positions, normals, file)
231 current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded()
232 }
233 }
234 for axis in openAxes { current[axis.edge] = axis.endAngle }
235 return current
236}
237
238/// `record`, flagged non-rigid, with `pop`.
239func withPop(_ record: StepRecord, _ pop: PopRecord) -> StepRecord {
240 StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes,
241 rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis, repeatOf: record.repeatOf,
242 nonRigid: true, pop: pop, viewpoint: record.viewpoint)
243}
244
245/// The fold angle at the end of a non-rigid step of every edge its close axes crease, measured
246/// from the faces' normals along the open phase, at `popped` and along the close phase, unwrapped
247/// from frame n − 1's angle and taken to be ±180 or 0 when within 1e-6° of one. A close axis's
248/// edge ends at its end angle exactly.
249func popEndAngles(_ step: FoldStep, _ interpolator: FoldInterpolator, previous: FoldFrame,
250 file: FoldFile) -> [Int: Double] {
251 guard let pop = step.pop else { return [:] }
252 let edgeFaces = edgesFaces(file)
253 var axisOfFace = Array(repeating: -1, count: file.facesVertices.count)
254 for (a, axis) in pop.closeAxes.enumerated() {
255 for f in axis.movingFaces { axisOfFace[f] = a }
256 }
257 let edges = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && axisOfFace[edgeFaces[$0][0]] != axisOfFace[edgeFaces[$0][1]] }
258
259 let (lower, upper) = (pop.phases.lowerBound, pop.phases.upperBound)
260 let times = (1...angleSamples).map { lower * Double($0) / Double(angleSamples) } + [upper]
261 + (1...angleSamples).map { upper + (1 - upper) * Double($0) / Double(angleSamples) }
262 var current = Dictionary(uniqueKeysWithValues: edges.map { ($0, previous.edgesFoldAngle[$0]) })
263 for t in times {
264 let positions = interpolator.positions(at: t)
265 let normals = faceNormals(positions: positions, faces: file.facesVertices)
266 for e in edges {
267 let measured = dihedral(e, edgeFaces[e], positions, normals, file)
268 current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded()
269 }
270 }
271 for (e, angle) in current {
272 current[e] = [180, -180, 0].first { abs(angle - $0) <= angleSnapTolerance } ?? angle
273 }
274 for axis in pop.closeAxes { current[axis.edge] = axis.endAngle }
275 return current
276}
277
278/// A tree of regions over the faces: the faces connected across edges not in `order`, grown from
279/// the regions holding a `fixed` face across the edges in `order`. Each tree edge is an axis
280/// moving its child region's faces; each other edge of `order` between different regions closes
281/// a loop.
282private struct RegionTree {
283 var axes: [(edge: Int, movingFaces: [Int], parent: Int?)]
284 var loops: [Int]
285}
286
287private func growTree(order: [Int], fixed: Set<Int>, _ file: FoldFile, _ edgeFaces: [[Int]]) -> RegionTree {
288 let region = regions(cut: Set(order), file, edgeFaces)
289 let regionCount = (region.max() ?? -1) + 1
290 var node = Array(repeating: -1, count: regionCount)
291 for f in fixed { node[region[f]] = 0 }
292 var nodeCount = 1
293 for r in 0..<regionCount where node[r] < 0 {
294 node[r] = nodeCount
295 nodeCount += 1
296 }
297 let nodeOfFace = region.map { node[$0] }
298
299 var component = Array(0..<nodeCount)
300 func find(_ x: Int) -> Int {
301 var x = x
302 while component[x] != x { x = component[x] }
303 return x
304 }
305 var links: [(edge: Int, ends: (Int, Int))] = []
306 var loops: [Int] = []
307 for e in order {
308 let a = nodeOfFace[edgeFaces[e][0]], b = nodeOfFace[edgeFaces[e][1]]
309 guard a != b else { continue }
310 if find(a) != find(b) {
311 component[find(a)] = find(b)
312 links.append((e, (a, b)))
313 } else {
314 loops.append(e)
315 }
316 }
317
318 var parentNode = Array<Int?>(repeating: nil, count: nodeCount)
319 var linkOfNode = Array<Int?>(repeating: nil, count: nodeCount)
320 var reached: Set<Int> = [0]
321 var queue = [0]
322 while !queue.isEmpty {
323 let a = queue.removeFirst()
324 for (k, link) in links.enumerated() where link.ends.0 == a || link.ends.1 == a {
325 let b = link.ends.0 == a ? link.ends.1 : link.ends.0
326 guard reached.insert(b).inserted else { continue }
327 parentNode[b] = a
328 linkOfNode[b] = k
329 queue.append(b)
330 }
331 }
332 let axes = links.enumerated().map { k, link in
333 let child = linkOfNode[link.ends.0] == k ? link.ends.0 : link.ends.1
334 return (edge: link.edge, movingFaces: nodeOfFace.indices.filter { nodeOfFace[$0] == child },
335 parent: parentNode[child].flatMap { linkOfNode[$0] })
336 }
337 return RegionTree(axes: axes, loops: loops)
338}
339
340/// The region of each face: faces connected across interior edges not in `cut`.
341private func regions(cut: Set<Int>, _ file: FoldFile, _ edgeFaces: [[Int]]) -> [Int] {
342 var region = Array(repeating: -1, count: file.facesVertices.count)
343 var count = 0
344 for seed in region.indices where region[seed] < 0 {
345 region[seed] = count
346 var stack = [seed]
347 while let f = stack.popLast() {
348 for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) {
349 let g = faces[0] == f ? faces[1] : faces[0]
350 if region[g] < 0 {
351 region[g] = count
352 stack.append(g)
353 }
354 }
355 }
356 count += 1
357 }
358 return region
359}
360
361/// The tree's axes as records from `start` angles to `end` angles, on `window`.
362private func records(_ tree: RegionTree, start: (Int) -> Double, end: (Int) -> Double,
363 window: [Double]?) -> [AxisRecord] {
364 tree.axes.map { axis in
365 AxisRecord(edge: axis.edge, movingFaces: axis.movingFaces, startAngle: start(axis.edge),
366 endAngle: end(axis.edge), parent: axis.parent, window: window)
367 }
368}
369
370/// `record` with `axes` in place of its own.
371private func withAxes(_ record: StepRecord, _ axes: [AxisRecord]) -> StepRecord {
372 StepRecord(kind: .fold, technique: record.technique, instruction: record.instruction, axes: axes,
373 viewpoint: record.viewpoint)
374}
375
376/// The pose with the tree's axes at `angles`, the edges in `holding` held there and the axes on a
377/// loop's cycle solved so the loops close. Returns the vertex positions and the solved angles.
378private func solvedPose(_ n: Int, _ tree: RegionTree, from before: FoldFrame, angles: [Int: Double],
379 holding: Set<Int>, _ record: StepRecord, _ file: FoldFile) throws
380 -> (positions: [SIMD3<Double>], angles: [Int: Double]) {
381 func draft(_ angles: [Int: Double]) -> FoldFile {
382 var draft = file
383 draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment,
384 edgesFoldAngle: before.edgesFoldAngle, faceOrders: [],
385 step: withAxes(record, records(tree, start: { before.edgesFoldAngle[$0] },
386 end: { angles[$0]! }, window: nil))))
387 return draft
388 }
389 var solved = angles
390 let first = draft(angles)
391 let step = try readStep(n, in: first)
392 let free = axesOnCycles(step, loops: tree.loops, first).filter { !holding.contains(step.axes[$0].edge) }.sorted()
393 var values = step.axes.map(\.endAngle)
394 let tolerance = sheetExtent(file) * relativeTolerance
395 guard LoopKinematics(step: step, file: first).solve(&values, free: free) <= tolerance else {
396 throw CompileError.noRigidMotion(step: n)
397 }
398 for (a, axis) in step.axes.enumerated() { solved[axis.edge] = values[a] }
399 let last = draft(solved)
400 return (FoldInterpolator(file: last, step: try readStep(n, in: last)).positions(at: 1), solved)
401}
402
403/// The close axes from `popped`: the named spine edge, first in the tree, linear from its popped
404/// angle to its end; the axes on a loop's cycle solved as for a rigid step; all on
405/// `[phases[1], 1]`.
406private func closing(_ n: Int, _ tree: RegionTree, from popped: FoldFrame, start: [Int: Double],
407 end: (Int) -> Double, _ record: StepRecord, _ file: FoldFile) throws -> [AxisRecord] {
408 var draft = file
409 draft.frames[n - 1] = popped
410 var close = withAxes(record, records(tree, start: { start[$0]! }, end: end, window: [phases[1], 1]))
411 draft.frames.append(FoldFrame(verticesCoords: popped.verticesCoords, edgesAssignment: popped.edgesAssignment,
412 edgesFoldAngle: popped.edgesFoldAngle, faceOrders: [], step: close))
413 var step = try readStep(n, in: draft)
414 guard !tree.loops.isEmpty else { return close.axes }
415 close = try solveLoops(n, close, step, loops: tree.loops, draft)
416 draft.frames[n].step = close
417 step = try readStep(n, in: draft)
418 try checkClosure(n, step, driver: close.axes[0].edge, draft, solved: close.axes.contains { $0.angles != nil })
419 return close.axes
420}