Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift

669 lines · 33026 bytes

57 symbols in this file
  1import CoreGraphics
  2import Foundation
  3import FoldCompiler
  4import FoldFormat
  5import Folding
  6import ImageIO
  7import Notation
  8import simd
  9import Testing
 10
 11/// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases
 12/// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step.
 13///
 14/// Vertices: v0 the centre, v1 (2, 1) the 0° crease's end, v2 (2, 2), v3 the 60° crease's end,
 15/// v4 (0, 2), v5 the 140° crease's end, v6 (0, 0), v7 the 260° crease's end, v8 (2, 0).
 16/// Edges: e0–e7 the boundary from v1 counterclockwise, e8 the 0° crease, e9 60°, e10 140°,
 17/// e11 260°. Faces: f0 the 60° sector, f1 the 80°, f2 the 120° (held), f3 the 100°.
 18///
 19/// The 140° crease is driven linearly 0 → 180, the 0° crease follows it exactly, and the 260° and
 20/// 60° creases are ρ and −ρ, `ρ = 2·atan(k·tan(90°·u))`, `k = cos 70° / cos 10°`. The 260° axis
 21/// carries the 0° axis; the 60° crease is off the tree. With `linear` the 260° axis is a straight
 22/// line 0 → 180 instead of the curve, which tears the vertex.
 23public func degreeFourVertex(linear: Bool = false) -> FoldFile {
 24    let c = SIMD3<Double>(1, 1, 0)
 25    let flat: [SIMD3<Double>] = [
 26        c,
 27        SIMD3(2, 1, 0),
 28        SIMD3(2, 2, 0),
 29        SIMD3(1 + 1 / tan(radians(60)), 2, 0),
 30        SIMD3(0, 2, 0),
 31        SIMD3(0, 1 + tan(radians(40)), 0),
 32        SIMD3(0, 0, 0),
 33        SIMD3(1 - tan(radians(10)), 0, 0),
 34        SIMD3(2, 0, 0),
 35    ]
 36
 37    // Flat-folded, each 180° fold is a reflection across its crease line in the held face's plane.
 38    func reflect(_ p: SIMD3<Double>, across degrees: Double) -> SIMD3<Double> {
 39        let d = p - c, a = 2 * radians(degrees)
 40        return c + SIMD3(d.x * cos(a) + d.y * sin(a), d.x * sin(a) - d.y * cos(a), 0)
 41    }
 42    let folded: [SIMD3<Double>] = [
 43        c,
 44        reflect(flat[1], across: 260),                       // f3
 45        reflect(reflect(flat[2], across: 0), across: 260),   // f0, carried by f3
 46        reflect(flat[3], across: 140),                       // f1
 47        reflect(flat[4], across: 140),                       // f1
 48        flat[5], flat[6], flat[7],                           // f2, held
 49        reflect(flat[8], across: 260),                       // f3
 50    ]
 51
 52    let creases = 8..<12
 53    let boundary = Array(repeating: EdgeAssignment.boundary, count: 8)
 54    // the last sample is the end frame's angle exactly, as foldc writes it
 55    let curve = (0..<256).map { degreeFourExactAngle(11, at: Double($0) / 256) } + [180]
 56    let step = StepRecord(
 57        kind: .fold,
 58        technique: .plain,
 59        instruction: "Fold the vertex flat.",
 60        axes: [
 61            AxisRecord(edge: 10, movingFaces: [1], startAngle: 0, endAngle: 180),
 62            AxisRecord(edge: 11, movingFaces: [3], startAngle: 0, endAngle: 180,
 63                       angles: linear ? nil : curve),
 64            AxisRecord(edge: 8, movingFaces: [0], startAngle: 0, endAngle: 180, parent: 1),
 65        ],
 66        viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
 67    )
 68    // Bottom to top along +z: f2, f1, f0, f3. f2 and f0 face +z, f1 and f3 face −z, and s is
 69    // read on the side g's normal points toward.
 70    let orders = [[0, 1, -1], [0, 2, 1], [0, 3, 1], [1, 2, 1], [1, 3, 1], [2, 3, 1]]
 71
 72    return FoldFile(
 73        fileSpec: 1.2,
 74        fileTitle: "Degree-4 vertex",
 75        fileAuthor: "Traditional",
 76        fileClasses: ["diagrams"],
 77        edgesVertices: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 1],
 78                        [0, 1], [0, 3], [0, 5], [0, 7]],
 79        facesVertices: [[0, 1, 2, 3], [0, 3, 4, 5], [0, 5, 6, 7], [0, 7, 8, 1]],
 80        edgesFirstCreasedAtStep: Array(repeating: nil, count: 8) + creases.map { _ in 1 },
 81        frames: [
 82            FoldFrame(verticesCoords: flat,
 83                      edgesAssignment: boundary + creases.map { _ in .flat },
 84                      edgesFoldAngle: Array(repeating: 0, count: 12),
 85                      faceOrders: []),
 86            FoldFrame(verticesCoords: folded,
 87                      edgesAssignment: boundary + [.valley, .mountain, .valley, .valley],
 88                      edgesFoldAngle: Array(repeating: 0, count: 8) + [180, -180, 180, 180],
 89                      faceOrders: orders,
 90                      faceOrdersMidFold: orders,
 91                      step: step),
 92        ]
 93    )
 94}
 95
 96/// `degreeFourVertex()` as a crease pattern: its sheet and creases with their final assignments,
 97/// no frames.
 98public func degreeFourPattern() -> FoldFile {
 99    let vertex = degreeFourVertex()
100    return FoldFile(
101        fileSpec: 1.2,
102        fileTitle: vertex.fileTitle,
103        fileAuthor: vertex.fileAuthor,
104        fileClasses: ["creasePattern"],
105        edgesVertices: vertex.edgesVertices,
106        facesVertices: vertex.facesVertices,
107        edgesFirstCreasedAtStep: vertex.edgesVertices.map { _ in nil },
108        frames: [FoldFrame(verticesCoords: vertex.frames[0].verticesCoords,
109                           edgesAssignment: vertex.frames[1].edgesAssignment,
110                           edgesFoldAngle: vertex.edgesVertices.map { _ in 0 },
111                           faceOrders: [])]
112    )
113}
114
115/// `degreeFourVertex()` as a one-step script: the 140° crease drives, then the 260°, 0° and 60°
116/// creases in that order, so the 60° crease closes the loop. The 120° sector is held.
117public func degreeFourScript() -> FoldScript {
118    func inside(_ degrees: Double) -> SIMD2<Double> {
119        SIMD2(1 + 0.5 * cos(radians(degrees)), 1 + 0.5 * sin(radians(degrees)))
120    }
121    return FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
122        ScriptStep(kind: .fold, instruction: "Fold the vertex flat.",
123                   creases: [.edgeIndex(10), .edgeIndex(11), .edgeIndex(8), .edgeIndex(9)],
124                   movingSide: [inside(30), inside(100), inside(310)]),
125    ])
126}
127
128/// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form.
129public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double {
130    let k = cos(radians(70)) / cos(radians(10))
131    let rho = 2 * atan2(k * sin(radians(90 * t)), cos(radians(90 * t))) * 180 / .pi
132    switch edge {
133    case 8, 10: return 180 * t
134    case 11: return rho
135    case 9: return -rho
136    default: preconditionFailure("edge \(edge) is not a crease of the degree-4 vertex")
137    }
138}
139
140private func radians(_ degrees: Double) -> Double { degrees * .pi / 180 }
141
142/// A fixture file, and the interpolator for its step `step` (counted from 1).
143public func interpolator(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldInterpolator) {
144    let file = try FoldFile(contentsOf: fixture(fixtureName))
145    return (file, FoldInterpolator(file: file, step: try readSteps(file)[step - 1]))
146}
147
148/// The largest change, against frame 0, in the length of any FOLD edge.
149public func maxEdgeLengthDrift(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Double {
150    let flat = file.frames[0].verticesCoords
151    return file.edgesVertices.map { e in
152        abs(simd_distance(positions[e[0]], positions[e[1]]) - simd_distance(flat[e[0]], flat[e[1]]))
153    }.max() ?? 0
154}
155
156/// Whether every pairwise distance between the points agrees, within 1e-9, across both arrays.
157public func pairwiseDistancesAgree(_ a: [SIMD3<Double>], _ b: [SIMD3<Double>]) -> Bool {
158    guard a.count == b.count else { return false }
159    for i in a.indices {
160        for j in a.indices where j > i {
161            if abs(simd_distance(a[i], a[j]) - simd_distance(b[i], b[j])) > 1e-9 { return false }
162        }
163    }
164    return true
165}
166
167/// The longer side of frame 0's bounding box.
168public func sheetSize(_ 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    let extent = upper - lower
173    return max(extent.x, extent.y, extent.z)
174}
175
176/// A `cells` × `cells` grid of unit cells, with one step folding the right half over the left
177/// about the vertical line through the middle. Cells are faces, numbered row by row from the
178/// bottom left; `cells` must be even.
179public func gridSheet(cells: Int) -> FoldFile {
180    precondition(cells >= 2 && cells.isMultiple(of: 2), "gridSheet needs an even number of cells")
181    let n = cells, half = n / 2
182    func vertex(_ i: Int, _ j: Int) -> Int { j * (n + 1) + i }
183
184    var flat: [SIMD3<Double>] = []
185    for j in 0...n { for i in 0...n { flat.append(SIMD3(Double(i), Double(j), 0)) } }
186    let folded = flat.map { p in SIMD3(p.x > Double(half) ? Double(n) - p.x : p.x, p.y, 0) }
187
188    var edges: [[Int]] = [], assignment: [EdgeAssignment] = [], angle: [Double] = []
189    var created: [Int?] = []
190    func addEdge(_ a: Int, _ b: Int, boundary: Bool, crease: Bool) {
191        edges.append([a, b])
192        assignment.append(boundary ? .boundary : crease ? .valley : .flat)
193        angle.append(crease ? 180 : 0)
194        created.append(crease ? 1 : nil)
195    }
196    var axisEdge = 0
197    for j in 0...n {
198        for i in 0..<n {
199            addEdge(vertex(i, j), vertex(i + 1, j), boundary: j == 0 || j == n, crease: false)
200        }
201    }
202    for j in 0..<n {
203        for i in 0...n {
204            let crease = i == half
205            if crease && j == 0 { axisEdge = edges.count }
206            addEdge(vertex(i, j), vertex(i, j + 1), boundary: i == 0 || i == n, crease: crease)
207        }
208    }
209
210    var faces: [[Int]] = []
211    for j in 0..<n {
212        for i in 0..<n {
213            faces.append([vertex(i, j), vertex(i + 1, j), vertex(i + 1, j + 1), vertex(i, j + 1)])
214        }
215    }
216    let right = faces.indices.filter { $0 % n >= half }
217    // each right cell lies flipped on top of its mirror image in the left half
218    let orders = right.map { f in [f, f - 2 * (f % n - half) - 1, 1] }
219
220    let step = StepRecord(
221        kind: .fold,
222        technique: .plain,
223        instruction: "Valley fold the right half over to the left.",
224        axes: [AxisRecord(edge: axisEdge, movingFaces: right, startAngle: 0, endAngle: 180)],
225        viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
226    )
227    return FoldFile(
228        fileSpec: 1.2,
229        fileTitle: "Grid",
230        fileAuthor: "Traditional",
231        fileClasses: ["diagrams"],
232        edgesVertices: edges,
233        facesVertices: faces,
234        edgesFirstCreasedAtStep: created,
235        frames: [
236            FoldFrame(verticesCoords: flat,
237                      edgesAssignment: assignment.map { $0 == .valley ? .flat : $0 },
238                      edgesFoldAngle: Array(repeating: 0, count: edges.count),
239                      faceOrders: []),
240            FoldFrame(verticesCoords: folded, edgesAssignment: assignment, edgesFoldAngle: angle,
241                      faceOrders: orders, step: step),
242        ]
243    )
244}
245
246/// A fixture file, its step `step` (counted from 1), and the interpolator for that step.
247public func interpolatorWithStep(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator) {
248    let file = try FoldFile(contentsOf: fixture(fixtureName))
249    let s = try readSteps(file)[step - 1]
250    return (file, s, FoldInterpolator(file: file, step: s))
251}
252
253/// The corners of a unit square in the plane z = `z`, counterclockwise seen from +z.
254private func unitSquare(z: Double) -> [SIMD3<Double>] {
255    [SIMD3(0, 0, z), SIMD3(1, 0, z), SIMD3(1, 1, z), SIMD3(0, 1, z)]
256}
257
258/// Two unit squares, both at z = 0.
259public func stackedSquarePositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 0) }
260
261/// Two unit squares, at z = 0 and z = 1.
262public func separatedSquarePositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 1) }
263
264/// Three unit squares, all at z = 0.
265public func threeStackedPositions() -> [SIMD3<Double>] { unitSquare(z: 0) + unitSquare(z: 0) + unitSquare(z: 0) }
266
267/// The faces of two squares of four vertices each, facing +z.
268public func twoSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7]] }
269
270/// The faces of three squares of four vertices each, facing +z.
271public func threeSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] }
272
273/// `letter.fold`'s sheet with both outer thirds valley-folded in front of the middle one on one
274/// window of t, linear 0 → 180°. The flaps meet at 120°, t = 2/3, and pass through each other
275/// after.
276public func interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator) {
277    let file = try FoldFile(contentsOf: fixture("letter.fold"))
278    let step = FoldStep(
279        index: 1,
280        kind: .fold,
281        instruction: "Valley fold both thirds in front.",
282        axes: [
283            // f0 traverses e8 from v1 up the sheet, f2 traverses e9 from v5 down it
284            FoldAxis(edge: 8, origin: SIMD3(1, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [0],
285                     startAngle: 0, endAngle: 180),
286            FoldAxis(edge: 9, origin: SIMD3(2, 3, 0), direction: SIMD3(0, -1, 0), movingFaces: [2],
287                     startAngle: 0, endAngle: 180),
288        ],
289        viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
290    )
291    return (file, FoldInterpolator(file: file, step: step))
292}
293
294/// A fixed triangle (0,0,0), (1,1.2,0.4), (-1,1.2,0.4) and a moving triangle (0,0,0), (0,2,0),
295/// (-1,1,0) hinged on its edge along the y-axis, folding toward +z from 0 to 180°. They share
296/// vertex 0 only. The fixed triangle is tilted, so this is not a flat frame 0 and the file is
297/// built directly.
298public func interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator) {
299    let start: [SIMD3<Double>] = [
300        SIMD3(0, 0, 0), SIMD3(1, 1.2, 0.4), SIMD3(-1, 1.2, 0.4), SIMD3(0, 2, 0), SIMD3(-1, 1, 0),
301    ]
302    var end = start
303    end[4] = SIMD3(1, 1, 0)
304    let assignment: [EdgeAssignment] = [.boundary, .boundary, .boundary, .valley, .boundary, .boundary]
305    func frame(_ points: [SIMD3<Double>], angle: Double) -> FoldFrame {
306        FoldFrame(verticesCoords: points, edgesAssignment: assignment,
307                  edgesFoldAngle: [0, 0, 0, angle, 0, 0], faceOrders: [])
308    }
309    let file = FoldFile(
310        fileSpec: 1.2,
311        fileAuthor: "Traditional",
312        edgesVertices: [[0, 1], [1, 2], [2, 0], [0, 3], [3, 4], [4, 0]],
313        facesVertices: [[0, 1, 2], [0, 3, 4]],
314        edgesFirstCreasedAtStep: [nil, nil, nil, 1, nil, nil],
315        frames: [frame(start, angle: 0), frame(end, angle: 180)]
316    )
317    let step = FoldStep(
318        index: 1,
319        kind: .fold,
320        instruction: "Fold the flap up.",
321        axes: [FoldAxis(edge: 3, origin: SIMD3(0, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [1],
322                        startAngle: 0, endAngle: 180)],
323        viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
324    )
325    return (file, FoldInterpolator(file: file, step: step))
326}
327
328/// `<name>.foldscript` compiled against `<name>-cp.fold`.
329public func compiled(_ name: String) throws -> FoldFile {
330    try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
331                pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
332}
333
334/// `compiled(name)` with step `step`'s `openAngle` set to `degrees`. Steps count from 1.
335public func compiled(_ name: String, openAngle degrees: Double, step: Int) throws -> FoldFile {
336    try compile(FoldScript(contentsOf: fixture("\(name).foldscript")).withOpenAngle(degrees, step: step),
337                pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
338}
339
340/// Whether two files have the same metadata, topology, assignments, layer orders and steps, with
341/// coordinates, angles and pop phases within `tolerance`. Face orders compare as sets;
342/// `file_creator` is ignored.
343public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool {
344    guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor,
345          a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices,
346          a.facesVertices == b.facesVertices, a.edgesFirstCreasedAtStep == b.edgesFirstCreasedAtStep,
347          a.frames.count == b.frames.count else { return false }
348    return zip(a.frames, b.frames).allSatisfy { framesAgree($0, $1, tolerance) }
349}
350
351private func close(_ a: [Double], _ b: [Double], _ tolerance: Double) -> Bool {
352    a.count == b.count && zip(a, b).allSatisfy { abs($0 - $1) <= tolerance }
353}
354
355private func close(_ a: Double?, _ b: Double?, _ tolerance: Double) -> Bool {
356    switch (a, b) {
357    case (nil, nil): true
358    case let (x?, y?): abs(x - y) <= tolerance
359    default: false
360    }
361}
362
363private func framesAgree(_ a: FoldFrame, _ b: FoldFrame, _ tolerance: Double) -> Bool {
364    let flatten = { (points: [SIMD3<Double>]) in points.flatMap { [$0.x, $0.y, $0.z] } }
365    let orders = { (list: [[Int]]?) in list.map(Set.init) }
366    guard close(flatten(a.verticesCoords), flatten(b.verticesCoords), tolerance),
367          a.edgesAssignment == b.edgesAssignment,
368          close(a.edgesFoldAngle, b.edgesFoldAngle, tolerance),
369          a.faceOrders.count == b.faceOrders.count, Set(a.faceOrders) == Set(b.faceOrders),
370          orders(a.faceOrdersMidFold) == orders(b.faceOrdersMidFold) else { return false }
371    switch (a.step, b.step) {
372    case (nil, nil): return true
373    case let (x?, y?): return stepsAgree(x, y, tolerance)
374    default: return false
375    }
376}
377
378private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) -> Bool {
379    let view = { (v: Viewpoint) in [v.eye.x, v.eye.y, v.eye.z, v.up.x, v.up.y, v.up.z] }
380    guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction,
381          close(a.rotateDegrees, b.rotateDegrees, tolerance), a.turnOverAxis == b.turnOverAxis,
382          a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid,
383          close(view(a.viewpoint), view(b.viewpoint), tolerance) else { return false }
384    switch (a.pop, b.pop) {
385    case (nil, nil): break
386    case let (x?, y?): guard popsAgree(x, y, tolerance) else { return false }
387    default: return false
388    }
389    return axesAgree(a.axes, b.axes, tolerance)
390}
391
392private func popsAgree(_ a: PopRecord, _ b: PopRecord, _ tolerance: Double) -> Bool {
393    let flatten = { (points: [SIMD3<Double>]) in points.flatMap { [$0.x, $0.y, $0.z] } }
394    return a.spine == b.spine && close(a.openAngle, b.openAngle, tolerance) && close(a.phases, b.phases, tolerance)
395        && close(flatten(a.popped), flatten(b.popped), tolerance)
396        && axesAgree(a.openAxes, b.openAxes, tolerance) && axesAgree(a.closeAxes, b.closeAxes, tolerance)
397}
398
399private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double) -> Bool {
400    a.count == b.count && zip(a, b).allSatisfy { x, y in
401        x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent
402            && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance)
403            && close(x.peakAngle, y.peakAngle, tolerance)
404            && close(x.window ?? [0, 1], y.window ?? [0, 1], tolerance)
405            && (x.angles == nil) == (y.angles == nil) && close(x.angles ?? [], y.angles ?? [], tolerance)
406    }
407}
408
409/// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point
410/// (2.75, 0.75) lies strictly between the body's two layers: the faces containing sheet points
411/// (0.5, 0.5) and (0.5, 1.5).
412public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool {
413    pointIsBetweenLayers(positions, file, point: SIMD2(2.75, 0.75), lower: SIMD2(0.5, 0.5), upper: SIMD2(0.5, 1.5))
414}
415
416/// Whether, at `positions`, sheet point `point` lies strictly between the planes of the faces
417/// containing sheet points `lower` and `upper`, at its x and y. False when it is not over both.
418public func pointIsBetweenLayers(_ positions: [SIMD3<Double>], _ file: FoldFile, point: SIMD2<Double>,
419                                 lower lowerPoint: SIMD2<Double>, upper upperPoint: SIMD2<Double>) -> Bool {
420    let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
421    func face(containing p: SIMD2<Double>) -> Int? {
422        file.facesVertices.indices.first { f in
423            let corners = file.facesVertices[f].map { flat[$0] }
424            return corners.indices.allSatisfy { i in
425                let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = p - a
426                return side.x * offset.y - side.y * offset.x >= 0
427            }
428        }
429    }
430    // the sheet point p of face f, where f's corners are at `positions`
431    func place(_ p: SIMD2<Double>, on f: Int) -> SIMD3<Double> {
432        let c = file.facesVertices[f]
433        let (a, b, d) = (flat[c[0]], flat[c[1]], flat[c[2]])
434        let u = b - a, v = d - a, w = p - a
435        let det = u.x * v.y - u.y * v.x
436        let s = (w.x * v.y - w.y * v.x) / det, r = (u.x * w.y - u.y * w.x) / det
437        return positions[c[0]] + s * (positions[c[1]] - positions[c[0]]) + r * (positions[c[2]] - positions[c[0]])
438    }
439    // the height of face f's plane above (x, y), when (x, y) lies over the face
440    func height(of f: Int, at q: SIMD2<Double>) -> Double? {
441        let corners = file.facesVertices[f].map { positions[$0] }
442        let n = faceNormals(positions: positions, faces: [file.facesVertices[f]])[0]
443        guard abs(n.z) > 1e-12 else { return nil }
444        let outline = corners.map { SIMD2($0.x, $0.y) }
445        let turn = n.z > 0 ? 1.0 : -1.0
446        let inside = outline.indices.allSatisfy { i in
447            let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = q - a
448            return turn * (side.x * offset.y - side.y * offset.x) >= 0
449        }
450        guard inside else { return nil }
451        return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z
452    }
453    guard let tip = face(containing: point), let lower = face(containing: lowerPoint),
454          let upper = face(containing: upperPoint) else { return false }
455    let probe = place(point, on: tip)
456    let q = SIMD2(probe.x, probe.y)
457    guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false }
458    return probe.z > min(a, b) && probe.z < max(a, b)
459}
460
461extension FoldScript {
462    /// This script with step `step`'s `openAngle` set to `degrees`. Steps count from 1.
463    public func withOpenAngle(_ degrees: Double, step: Int) -> FoldScript {
464        editing(step) { replacing($0, spine: $0.spine, openAngle: degrees) }
465    }
466
467    /// This script with step `step`'s `spine` removed. Steps count from 1.
468    public func withoutSpine(step: Int) -> FoldScript {
469        editing(step) { replacing($0, spine: nil, openAngle: $0.openAngle) }
470    }
471
472    private func editing(_ step: Int, _ change: (ScriptStep) -> ScriptStep) -> FoldScript {
473        var list = steps
474        list[step - 1] = change(list[step - 1])
475        return FoldScript(creasePattern: creasePattern, title: title, steps: list)
476    }
477}
478
479private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -> ScriptStep {
480    ScriptStep(kind: s.kind, technique: s.technique, instruction: s.instruction, creases: s.creases,
481               movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees,
482               turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders,
483               faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine,
484               openAngle: openAngle, openOn: s.openOn)
485}
486
487/// The repository's `Models/` directory: this file's path with its last five components, up to
488/// and including `Packages`, replaced by `Models`.
489private let modelsDirectory = URL(fileURLWithPath: #filePath)
490    .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
491    .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models")
492
493/// `Models/<name>.foldscript`.
494public func script(_ name: String) -> URL {
495    modelsDirectory.appendingPathComponent("\(name).foldscript")
496}
497
498/// `Models/<name>-cp.fold`.
499public func pattern(_ name: String) -> URL {
500    modelsDirectory.appendingPathComponent("\(name)-cp.fold")
501}
502
503/// `docs/authoring/<name>.md`.
504public func authoringDoc(_ name: String) -> URL {
505    modelsDirectory.deletingLastPathComponent().appendingPathComponent("docs/authoring/\(name).md")
506}
507
508#if os(macOS)
509/// Runs the built `foldlint` on `url`, returning its exit status and its standard output and
510/// error together. The executable is beside the test bundle, which may hold this module's
511/// resource bundle, or beside the resource bundle itself.
512public func runFoldlint(on url: URL) throws -> (exitCode: Int32, output: String) {
513    let beside = Bundle.module.bundleURL.deletingLastPathComponent()
514    var testBundle = beside
515    while testBundle.pathComponents.count > 1 && testBundle.pathExtension != "xctest" {
516        testBundle.deleteLastPathComponent()
517    }
518    let products = testBundle.pathExtension == "xctest" ? testBundle.deletingLastPathComponent() : beside
519    let process = Process()
520    process.executableURL = products.appendingPathComponent("foldlint")
521    process.arguments = [url.path]
522    let pipe = Pipe()
523    process.standardOutput = pipe
524    process.standardError = pipe
525    try process.run()
526    let output = pipe.fileHandleForReading.readDataToEndOfFile()
527    process.waitUntilExit()
528    return (process.terminationStatus, String(decoding: output, as: UTF8.self))
529}
530#endif
531
532/// The diagram for step `step` (counted from 1) of a fixture.
533public func diagram(_ fixtureName: String, step: Int) throws -> Diagram {
534    let file = try FoldFile(contentsOf: fixture(fixtureName))
535    return buildDiagram(file: file, step: try readStep(step, in: file))
536}
537
538/// `visibleSegments` of a fixture's edge in frame `n`, with frame n's order and step n + 1's
539/// viewpoint (the default one after the last step).
540public func visibleSegmentsOf(_ fixtureName: String, edge: Int, inFrame n: Int) throws -> [(SIMD2<Double>, SIMD2<Double>)] {
541    let file = try FoldFile(contentsOf: fixture(fixtureName))
542    let frame = file.frames[n]
543    let order = try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, file))
544    let viewpoint = n + 1 < file.frames.count
545        ? try readStep(n + 1, in: file).viewpoint
546        : Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
547    return visibleSegments(of: edge, frame: frame, file: file, order: order, viewpoint: viewpoint)
548}
549
550public func segmentLength(_ segment: (SIMD2<Double>, SIMD2<Double>)) -> Double {
551    simd_distance(segment.0, segment.1)
552}
553
554/// The canvas is square, this many pixels a side, white.
555private let canvasSide = 480
556
557/// `diagram` drawn by `drawDiagram` with `DiagramStyle.standard` on a white canvas.
558public func render(_ diagram: Diagram) -> CGImage {
559    let side = Double(canvasSide)
560    let context = CGContext(data: nil, width: canvasSide, height: canvasSide, bitsPerComponent: 8, bytesPerRow: 0,
561                            space: CGColorSpace(name: CGColorSpace.sRGB)!,
562                            bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
563    context.setFillColor(gray: 1, alpha: 1)
564    context.fill(CGRect(x: 0, y: 0, width: side, height: side))
565    drawDiagram(diagram, style: .standard, in: context, size: CGSize(width: side, height: side))
566    return context.makeImage()!
567}
568
569/// The number of the image's pixels darker than mid-grey in any channel.
570public func inkedPixels(_ image: CGImage) -> Int {
571    let bytes = rgba(image)
572    return (0..<(image.width * image.height)).count { p in (0..<3).contains { bytes[4 * p + $0] < 128 } }
573}
574
575/// Golden images differ from a render when any channel of any pixel differs by more than this,
576/// out of 255.
577private let snapshotTolerance = 24
578
579public enum SnapshotError: Error {
580    case unreadable(String)
581}
582
583/// Compares `image` with `Snapshots/<name>.png` beside the calling test file. Records the image
584/// there, and fails saying so, when the golden is missing or `FOLD_RECORD_SNAPSHOTS=1`.
585public func expectSnapshot(_ image: CGImage, named name: String, filePath: String = #filePath,
586                           sourceLocation: SourceLocation = #_sourceLocation) throws {
587    let url = URL(fileURLWithPath: filePath).deletingLastPathComponent()
588        .appendingPathComponent("Snapshots").appendingPathComponent("\(name).png")
589    let recording = ProcessInfo.processInfo.environment["FOLD_RECORD_SNAPSHOTS"] == "1"
590    if recording || !FileManager.default.fileExists(atPath: url.path) {
591        try writePNG(image, to: url)
592        Issue.record("recorded \(url.path); inspect it and run again", sourceLocation: sourceLocation)
593        return
594    }
595    guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
596          let golden = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw SnapshotError.unreadable(url.path) }
597    guard golden.width == image.width, golden.height == image.height else {
598        Issue.record("\(name): \(image.width)×\(image.height), golden \(golden.width)×\(golden.height)",
599                     sourceLocation: sourceLocation)
600        return
601    }
602    let (rendered, expected) = (rgba(image), rgba(golden))
603    var pixels = 0, first: Int?
604    for p in 0..<(image.width * image.height) {
605        let differs = (0..<4).contains { abs(Int(rendered[4 * p + $0]) - Int(expected[4 * p + $0])) > snapshotTolerance }
606        if differs {
607            pixels += 1
608            first = first ?? p
609        }
610    }
611    if let first {
612        let actual = FileManager.default.temporaryDirectory.appendingPathComponent("\(name).png")
613        try writePNG(image, to: actual)
614        let x = first % image.width, y = first / image.width
615        Issue.record("\(name): \(pixels) pixels differ from the golden image, first at (\(x), \(y)); this render is at \(actual.path)",
616                     sourceLocation: sourceLocation)
617    }
618}
619
620private func writePNG(_ image: CGImage, to url: URL) throws {
621    guard let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else {
622        throw SnapshotError.unreadable(url.path)
623    }
624    CGImageDestinationAddImage(destination, image, nil)
625    guard CGImageDestinationFinalize(destination) else { throw SnapshotError.unreadable(url.path) }
626}
627
628/// The image's pixels as 8-bit premultiplied RGBA in sRGB, row by row from the top.
629private func rgba(_ image: CGImage) -> [UInt8] {
630    var bytes = [UInt8](repeating: 0, count: image.width * image.height * 4)
631    bytes.withUnsafeMutableBytes { buffer in
632        let context = CGContext(data: buffer.baseAddress, width: image.width, height: image.height, bitsPerComponent: 8,
633                                bytesPerRow: image.width * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,
634                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
635        context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
636    }
637    return bytes
638}
639
640/// The fold parameter mapping for step `step` (counted from 1) of a fixture, looking at the step's
641/// start frame from its viewpoint, two sheet sizes away, in an 800 × 600 viewport.
642public func mapping(_ fixtureName: String, step: Int) throws -> FoldParameterMapping {
643    let file = try FoldFile(contentsOf: fixture(fixtureName))
644    let s = try readStep(step, in: file)
645    let points = file.frames[step - 1].verticesCoords
646    let centre = (points.dropFirst().reduce(points[0], simd_min) + points.dropFirst().reduce(points[0], simd_max)) / 2
647    let camera = Camera(eye: centre + normalize(s.viewpoint.eye) * 2 * sheetSize(file), target: centre,
648                        up: s.viewpoint.up, fieldOfView: .pi / 4)
649    return FoldParameterMapping(file: file, step: s, camera: camera, viewportSize: SIMD2(800, 600))
650}
651
652/// `half.fold`'s step 1 stopped at 30°, seen along the chord of its moving face's centroid, so the
653/// centroid travels almost along the view direction.
654public func mappingForFoldTowardTheCamera() throws -> FoldParameterMapping {
655    let file = try FoldFile(contentsOf: fixture("half.fold"))
656    let full = try readStep(1, in: file)
657    let a = full.axes[0]
658    let step = FoldStep(index: 1, kind: .fold, instruction: full.instruction,
659                        axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction,
660                                        movingFaces: a.movingFaces, startAngle: 0, endAngle: 30)],
661                        viewpoint: full.viewpoint)
662    // f1's centroid turns about x = 1 from (1.5, 1, 0) to (1 + 0.5 cos 30°, 1, 0.5 sin 30°)
663    let start = SIMD3(1.5, 1, 0.0)
664    let end = SIMD3(1 + 0.5 * cos(Double.pi / 6), 1, 0.5 * sin(Double.pi / 6))
665    let middle = (start + end) / 2
666    let camera = Camera(eye: middle + normalize(end - start) * 4, target: middle, up: SIMD3(0, 1, 0),
667                        fieldOfView: .pi / 4)
668    return FoldParameterMapping(file: file, step: step, camera: camera, viewportSize: SIMD2(800, 600))
669}