import CoreGraphics import Foundation import FoldCompiler import FoldFormat import Folding import ImageIO import Notation import simd import Testing /// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases /// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step. /// /// Vertices: v0 the centre, v1 (2, 1) the 0° crease's end, v2 (2, 2), v3 the 60° crease's end, /// v4 (0, 2), v5 the 140° crease's end, v6 (0, 0), v7 the 260° crease's end, v8 (2, 0). /// Edges: e0–e7 the boundary from v1 counterclockwise, e8 the 0° crease, e9 60°, e10 140°, /// e11 260°. Faces: f0 the 60° sector, f1 the 80°, f2 the 120° (held), f3 the 100°. /// /// The 140° crease is driven linearly 0 → 180, the 0° crease follows it exactly, and the 260° and /// 60° creases are ρ and −ρ, `ρ = 2·atan(k·tan(90°·u))`, `k = cos 70° / cos 10°`. The 260° axis /// carries the 0° axis; the 60° crease is off the tree. With `linear` the 260° axis is a straight /// line 0 → 180 instead of the curve, which tears the vertex. public func degreeFourVertex(linear: Bool = false) -> FoldFile { let c = SIMD3(1, 1, 0) let flat: [SIMD3] = [ c, SIMD3(2, 1, 0), SIMD3(2, 2, 0), SIMD3(1 + 1 / tan(radians(60)), 2, 0), SIMD3(0, 2, 0), SIMD3(0, 1 + tan(radians(40)), 0), SIMD3(0, 0, 0), SIMD3(1 - tan(radians(10)), 0, 0), SIMD3(2, 0, 0), ] // Flat-folded, each 180° fold is a reflection across its crease line in the held face's plane. func reflect(_ p: SIMD3, across degrees: Double) -> SIMD3 { let d = p - c, a = 2 * radians(degrees) return c + SIMD3(d.x * cos(a) + d.y * sin(a), d.x * sin(a) - d.y * cos(a), 0) } let folded: [SIMD3] = [ c, reflect(flat[1], across: 260), // f3 reflect(reflect(flat[2], across: 0), across: 260), // f0, carried by f3 reflect(flat[3], across: 140), // f1 reflect(flat[4], across: 140), // f1 flat[5], flat[6], flat[7], // f2, held reflect(flat[8], across: 260), // f3 ] let creases = 8..<12 let boundary = Array(repeating: EdgeAssignment.boundary, count: 8) // the last sample is the end frame's angle exactly, as foldc writes it let curve = (0..<256).map { degreeFourExactAngle(11, at: Double($0) / 256) } + [180] let step = StepRecord( kind: .fold, technique: .plain, instruction: "Fold the vertex flat.", axes: [ AxisRecord(edge: 10, movingFaces: [1], startAngle: 0, endAngle: 180), AxisRecord(edge: 11, movingFaces: [3], startAngle: 0, endAngle: 180, angles: linear ? nil : curve), AxisRecord(edge: 8, movingFaces: [0], startAngle: 0, endAngle: 180, parent: 1), ], viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) ) // Bottom to top along +z: f2, f1, f0, f3. f2 and f0 face +z, f1 and f3 face −z, and s is // read on the side g's normal points toward. let orders = [[0, 1, -1], [0, 2, 1], [0, 3, 1], [1, 2, 1], [1, 3, 1], [2, 3, 1]] return FoldFile( fileSpec: 1.2, fileTitle: "Degree-4 vertex", fileAuthor: "Traditional", fileClasses: ["diagrams"], edgesVertices: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 1], [0, 1], [0, 3], [0, 5], [0, 7]], facesVertices: [[0, 1, 2, 3], [0, 3, 4, 5], [0, 5, 6, 7], [0, 7, 8, 1]], edgesFirstCreasedAtStep: Array(repeating: nil, count: 8) + creases.map { _ in 1 }, frames: [ FoldFrame(verticesCoords: flat, edgesAssignment: boundary + creases.map { _ in .flat }, edgesFoldAngle: Array(repeating: 0, count: 12), faceOrders: []), FoldFrame(verticesCoords: folded, edgesAssignment: boundary + [.valley, .mountain, .valley, .valley], edgesFoldAngle: Array(repeating: 0, count: 8) + [180, -180, 180, 180], faceOrders: orders, faceOrdersMidFold: orders, step: step), ] ) } /// `degreeFourVertex()` as a crease pattern: its sheet and creases with their final assignments, /// no frames. public func degreeFourPattern() -> FoldFile { let vertex = degreeFourVertex() return FoldFile( fileSpec: 1.2, fileTitle: vertex.fileTitle, fileAuthor: vertex.fileAuthor, fileClasses: ["creasePattern"], edgesVertices: vertex.edgesVertices, facesVertices: vertex.facesVertices, edgesFirstCreasedAtStep: vertex.edgesVertices.map { _ in nil }, frames: [FoldFrame(verticesCoords: vertex.frames[0].verticesCoords, edgesAssignment: vertex.frames[1].edgesAssignment, edgesFoldAngle: vertex.edgesVertices.map { _ in 0 }, faceOrders: [])] ) } /// `degreeFourVertex()` as a one-step script: the 140° crease drives, then the 260°, 0° and 60° /// creases in that order, so the 60° crease closes the loop. The 120° sector is held. public func degreeFourScript() -> FoldScript { func inside(_ degrees: Double) -> SIMD2 { SIMD2(1 + 0.5 * cos(radians(degrees)), 1 + 0.5 * sin(radians(degrees))) } return FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [ ScriptStep(kind: .fold, instruction: "Fold the vertex flat.", creases: [.edgeIndex(10), .edgeIndex(11), .edgeIndex(8), .edgeIndex(9)], movingSide: [inside(30), inside(100), inside(310)]), ]) } /// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form. public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double { let k = cos(radians(70)) / cos(radians(10)) let rho = 2 * atan2(k * sin(radians(90 * t)), cos(radians(90 * t))) * 180 / .pi switch edge { case 8, 10: return 180 * t case 11: return rho case 9: return -rho default: preconditionFailure("edge \(edge) is not a crease of the degree-4 vertex") } } private func radians(_ degrees: Double) -> Double { degrees * .pi / 180 } /// A fixture file, and the interpolator for its step `step` (counted from 1). public func interpolator(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldInterpolator) { let file = try FoldFile(contentsOf: fixture(fixtureName)) return (file, FoldInterpolator(file: file, step: try readSteps(file)[step - 1])) } /// The largest change, against frame 0, in the length of any FOLD edge. public func maxEdgeLengthDrift(_ positions: [SIMD3], _ file: FoldFile) -> Double { let flat = file.frames[0].verticesCoords return file.edgesVertices.map { e in abs(simd_distance(positions[e[0]], positions[e[1]]) - simd_distance(flat[e[0]], flat[e[1]])) }.max() ?? 0 } /// Whether every pairwise distance between the points agrees, within 1e-9, across both arrays. public func pairwiseDistancesAgree(_ a: [SIMD3], _ b: [SIMD3]) -> Bool { guard a.count == b.count else { return false } for i in a.indices { for j in a.indices where j > i { if abs(simd_distance(a[i], a[j]) - simd_distance(b[i], b[j])) > 1e-9 { return false } } } return true } /// The longer side of frame 0's bounding box. public func sheetSize(_ file: FoldFile) -> Double { let points = file.frames[0].verticesCoords let lower = points.dropFirst().reduce(points[0], simd_min) let upper = points.dropFirst().reduce(points[0], simd_max) let extent = upper - lower return max(extent.x, extent.y, extent.z) } /// A `cells` × `cells` grid of unit cells, with one step folding the right half over the left /// about the vertical line through the middle. Cells are faces, numbered row by row from the /// bottom left; `cells` must be even. public func gridSheet(cells: Int) -> FoldFile { precondition(cells >= 2 && cells.isMultiple(of: 2), "gridSheet needs an even number of cells") let n = cells, half = n / 2 func vertex(_ i: Int, _ j: Int) -> Int { j * (n + 1) + i } var flat: [SIMD3] = [] for j in 0...n { for i in 0...n { flat.append(SIMD3(Double(i), Double(j), 0)) } } let folded = flat.map { p in SIMD3(p.x > Double(half) ? Double(n) - p.x : p.x, p.y, 0) } var edges: [[Int]] = [], assignment: [EdgeAssignment] = [], angle: [Double] = [] var created: [Int?] = [] func addEdge(_ a: Int, _ b: Int, boundary: Bool, crease: Bool) { edges.append([a, b]) assignment.append(boundary ? .boundary : crease ? .valley : .flat) angle.append(crease ? 180 : 0) created.append(crease ? 1 : nil) } var axisEdge = 0 for j in 0...n { for i in 0..= half } // each right cell lies flipped on top of its mirror image in the left half let orders = right.map { f in [f, f - 2 * (f % n - half) - 1, 1] } let step = StepRecord( kind: .fold, technique: .plain, instruction: "Valley fold the right half over to the left.", axes: [AxisRecord(edge: axisEdge, movingFaces: right, startAngle: 0, endAngle: 180)], viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) ) return FoldFile( fileSpec: 1.2, fileTitle: "Grid", fileAuthor: "Traditional", fileClasses: ["diagrams"], edgesVertices: edges, facesVertices: faces, edgesFirstCreasedAtStep: created, frames: [ FoldFrame(verticesCoords: flat, edgesAssignment: assignment.map { $0 == .valley ? .flat : $0 }, edgesFoldAngle: Array(repeating: 0, count: edges.count), faceOrders: []), FoldFrame(verticesCoords: folded, edgesAssignment: assignment, edgesFoldAngle: angle, faceOrders: orders, step: step), ] ) } /// A fixture file, its step `step` (counted from 1), and the interpolator for that step. public func interpolatorWithStep(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldStep, FoldInterpolator) { let file = try FoldFile(contentsOf: fixture(fixtureName)) let s = try readSteps(file)[step - 1] return (file, s, FoldInterpolator(file: file, step: s)) } /// The corners of a unit square in the plane z = `z`, counterclockwise seen from +z. private func unitSquare(z: Double) -> [SIMD3] { [SIMD3(0, 0, z), SIMD3(1, 0, z), SIMD3(1, 1, z), SIMD3(0, 1, z)] } /// Two unit squares, both at z = 0. public func stackedSquarePositions() -> [SIMD3] { unitSquare(z: 0) + unitSquare(z: 0) } /// Two unit squares, at z = 0 and z = 1. public func separatedSquarePositions() -> [SIMD3] { unitSquare(z: 0) + unitSquare(z: 1) } /// Three unit squares, all at z = 0. public func threeStackedPositions() -> [SIMD3] { unitSquare(z: 0) + unitSquare(z: 0) + unitSquare(z: 0) } /// The faces of two squares of four vertices each, facing +z. public func twoSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7]] } /// The faces of three squares of four vertices each, facing +z. public func threeSquares() -> [[Int]] { [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] } /// `letter.fold`'s sheet with both outer thirds valley-folded in front of the middle one on one /// window of t, linear 0 → 180°. The flaps meet at 120°, t = 2/3, and pass through each other /// after. public func interpolatorForBothThirdsInFront() throws -> (FoldFile, FoldInterpolator) { let file = try FoldFile(contentsOf: fixture("letter.fold")) let step = FoldStep( index: 1, kind: .fold, instruction: "Valley fold both thirds in front.", axes: [ // f0 traverses e8 from v1 up the sheet, f2 traverses e9 from v5 down it FoldAxis(edge: 8, origin: SIMD3(1, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [0], startAngle: 0, endAngle: 180), FoldAxis(edge: 9, origin: SIMD3(2, 3, 0), direction: SIMD3(0, -1, 0), movingFaces: [2], startAngle: 0, endAngle: 180), ], viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) ) return (file, FoldInterpolator(file: file, step: step)) } /// 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), /// (-1,1,0) hinged on its edge along the y-axis, folding toward +z from 0 to 180°. They share /// vertex 0 only. The fixed triangle is tilted, so this is not a flat frame 0 and the file is /// built directly. public func interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpolator) { let start: [SIMD3] = [ SIMD3(0, 0, 0), SIMD3(1, 1.2, 0.4), SIMD3(-1, 1.2, 0.4), SIMD3(0, 2, 0), SIMD3(-1, 1, 0), ] var end = start end[4] = SIMD3(1, 1, 0) let assignment: [EdgeAssignment] = [.boundary, .boundary, .boundary, .valley, .boundary, .boundary] func frame(_ points: [SIMD3], angle: Double) -> FoldFrame { FoldFrame(verticesCoords: points, edgesAssignment: assignment, edgesFoldAngle: [0, 0, 0, angle, 0, 0], faceOrders: []) } let file = FoldFile( fileSpec: 1.2, fileAuthor: "Traditional", edgesVertices: [[0, 1], [1, 2], [2, 0], [0, 3], [3, 4], [4, 0]], facesVertices: [[0, 1, 2], [0, 3, 4]], edgesFirstCreasedAtStep: [nil, nil, nil, 1, nil, nil], frames: [frame(start, angle: 0), frame(end, angle: 180)] ) let step = FoldStep( index: 1, kind: .fold, instruction: "Fold the flap up.", axes: [FoldAxis(edge: 3, origin: SIMD3(0, 0, 0), direction: SIMD3(0, 1, 0), movingFaces: [1], startAngle: 0, endAngle: 180)], viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) ) return (file, FoldInterpolator(file: file, step: step)) } /// `.foldscript` compiled against `-cp.fold`. public func compiled(_ name: String) throws -> FoldFile { try compile(FoldScript(contentsOf: fixture("\(name).foldscript")), pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold"))) } /// `compiled(name)` with step `step`'s `openAngle` set to `degrees`. Steps count from 1. public func compiled(_ name: String, openAngle degrees: Double, step: Int) throws -> FoldFile { try compile(FoldScript(contentsOf: fixture("\(name).foldscript")).withOpenAngle(degrees, step: step), pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold"))) } /// Whether two files have the same metadata, topology, assignments, layer orders and steps, with /// coordinates, angles and pop phases within `tolerance`. Face orders compare as sets; /// `file_creator` is ignored. public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool { guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor, a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices, a.facesVertices == b.facesVertices, a.edgesFirstCreasedAtStep == b.edgesFirstCreasedAtStep, a.frames.count == b.frames.count else { return false } return zip(a.frames, b.frames).allSatisfy { framesAgree($0, $1, tolerance) } } private func close(_ a: [Double], _ b: [Double], _ tolerance: Double) -> Bool { a.count == b.count && zip(a, b).allSatisfy { abs($0 - $1) <= tolerance } } private func close(_ a: Double?, _ b: Double?, _ tolerance: Double) -> Bool { switch (a, b) { case (nil, nil): true case let (x?, y?): abs(x - y) <= tolerance default: false } } private func framesAgree(_ a: FoldFrame, _ b: FoldFrame, _ tolerance: Double) -> Bool { let flatten = { (points: [SIMD3]) in points.flatMap { [$0.x, $0.y, $0.z] } } let orders = { (list: [[Int]]?) in list.map(Set.init) } guard close(flatten(a.verticesCoords), flatten(b.verticesCoords), tolerance), a.edgesAssignment == b.edgesAssignment, close(a.edgesFoldAngle, b.edgesFoldAngle, tolerance), a.faceOrders.count == b.faceOrders.count, Set(a.faceOrders) == Set(b.faceOrders), orders(a.faceOrdersMidFold) == orders(b.faceOrdersMidFold) else { return false } switch (a.step, b.step) { case (nil, nil): return true case let (x?, y?): return stepsAgree(x, y, tolerance) default: return false } } private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) -> Bool { let view = { (v: Viewpoint) in [v.eye.x, v.eye.y, v.eye.z, v.up.x, v.up.y, v.up.z] } guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction, close(a.rotateDegrees, b.rotateDegrees, tolerance), a.turnOverAxis == b.turnOverAxis, a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid, close(view(a.viewpoint), view(b.viewpoint), tolerance) else { return false } switch (a.pop, b.pop) { case (nil, nil): break case let (x?, y?): guard popsAgree(x, y, tolerance) else { return false } default: return false } return axesAgree(a.axes, b.axes, tolerance) } private func popsAgree(_ a: PopRecord, _ b: PopRecord, _ tolerance: Double) -> Bool { let flatten = { (points: [SIMD3]) in points.flatMap { [$0.x, $0.y, $0.z] } } return a.spine == b.spine && close(a.openAngle, b.openAngle, tolerance) && close(a.phases, b.phases, tolerance) && close(flatten(a.popped), flatten(b.popped), tolerance) && axesAgree(a.openAxes, b.openAxes, tolerance) && axesAgree(a.closeAxes, b.closeAxes, tolerance) } private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double) -> Bool { a.count == b.count && zip(a, b).allSatisfy { x, y in x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance) && close(x.peakAngle, y.peakAngle, tolerance) && close(x.window ?? [0, 1], y.window ?? [0, 1], tolerance) && (x.angles == nil) == (y.angles == nil) && close(x.angles ?? [], y.angles ?? [], tolerance) } } /// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point /// (2.75, 0.75) lies strictly between the body's two layers: the faces containing sheet points /// (0.5, 0.5) and (0.5, 1.5). public func tipIsBetweenBodyLayers(_ positions: [SIMD3], _ file: FoldFile) -> Bool { pointIsBetweenLayers(positions, file, point: SIMD2(2.75, 0.75), lower: SIMD2(0.5, 0.5), upper: SIMD2(0.5, 1.5)) } /// Whether, at `positions`, sheet point `point` lies strictly between the planes of the faces /// containing sheet points `lower` and `upper`, at its x and y. False when it is not over both. public func pointIsBetweenLayers(_ positions: [SIMD3], _ file: FoldFile, point: SIMD2, lower lowerPoint: SIMD2, upper upperPoint: SIMD2) -> Bool { let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } func face(containing p: SIMD2) -> Int? { file.facesVertices.indices.first { f in let corners = file.facesVertices[f].map { flat[$0] } return corners.indices.allSatisfy { i in let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = p - a return side.x * offset.y - side.y * offset.x >= 0 } } } // the sheet point p of face f, where f's corners are at `positions` func place(_ p: SIMD2, on f: Int) -> SIMD3 { let c = file.facesVertices[f] let (a, b, d) = (flat[c[0]], flat[c[1]], flat[c[2]]) let u = b - a, v = d - a, w = p - a let det = u.x * v.y - u.y * v.x let s = (w.x * v.y - w.y * v.x) / det, r = (u.x * w.y - u.y * w.x) / det return positions[c[0]] + s * (positions[c[1]] - positions[c[0]]) + r * (positions[c[2]] - positions[c[0]]) } // the height of face f's plane above (x, y), when (x, y) lies over the face func height(of f: Int, at q: SIMD2) -> Double? { let corners = file.facesVertices[f].map { positions[$0] } let n = faceNormals(positions: positions, faces: [file.facesVertices[f]])[0] guard abs(n.z) > 1e-12 else { return nil } let outline = corners.map { SIMD2($0.x, $0.y) } let turn = n.z > 0 ? 1.0 : -1.0 let inside = outline.indices.allSatisfy { i in let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = q - a return turn * (side.x * offset.y - side.y * offset.x) >= 0 } guard inside else { return nil } return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z } guard let tip = face(containing: point), let lower = face(containing: lowerPoint), let upper = face(containing: upperPoint) else { return false } let probe = place(point, on: tip) let q = SIMD2(probe.x, probe.y) guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false } return probe.z > min(a, b) && probe.z < max(a, b) } extension FoldScript { /// This script with step `step`'s `openAngle` set to `degrees`. Steps count from 1. public func withOpenAngle(_ degrees: Double, step: Int) -> FoldScript { editing(step) { replacing($0, spine: $0.spine, openAngle: degrees) } } /// This script with step `step`'s `spine` removed. Steps count from 1. public func withoutSpine(step: Int) -> FoldScript { editing(step) { replacing($0, spine: nil, openAngle: $0.openAngle) } } private func editing(_ step: Int, _ change: (ScriptStep) -> ScriptStep) -> FoldScript { var list = steps list[step - 1] = change(list[step - 1]) return FoldScript(creasePattern: creasePattern, title: title, steps: list) } } private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -> ScriptStep { ScriptStep(kind: s.kind, technique: s.technique, instruction: s.instruction, creases: s.creases, movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees, turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders, faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine, openAngle: openAngle, openOn: s.openOn) } /// The repository's `Models/` directory: this file's path with its last five components, up to /// and including `Packages`, replaced by `Models`. private let modelsDirectory = URL(fileURLWithPath: #filePath) .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models") /// `Models/.foldscript`. public func script(_ name: String) -> URL { modelsDirectory.appendingPathComponent("\(name).foldscript") } /// `Models/-cp.fold`. public func pattern(_ name: String) -> URL { modelsDirectory.appendingPathComponent("\(name)-cp.fold") } /// `docs/authoring/.md`. public func authoringDoc(_ name: String) -> URL { modelsDirectory.deletingLastPathComponent().appendingPathComponent("docs/authoring/\(name).md") } #if os(macOS) /// Runs the built `foldlint` on `url`, returning its exit status and its standard output and /// error together. The executable is beside the test bundle, which may hold this module's /// resource bundle, or beside the resource bundle itself. public func runFoldlint(on url: URL) throws -> (exitCode: Int32, output: String) { let beside = Bundle.module.bundleURL.deletingLastPathComponent() var testBundle = beside while testBundle.pathComponents.count > 1 && testBundle.pathExtension != "xctest" { testBundle.deleteLastPathComponent() } let products = testBundle.pathExtension == "xctest" ? testBundle.deletingLastPathComponent() : beside let process = Process() process.executableURL = products.appendingPathComponent("foldlint") process.arguments = [url.path] let pipe = Pipe() process.standardOutput = pipe process.standardError = pipe try process.run() let output = pipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() return (process.terminationStatus, String(decoding: output, as: UTF8.self)) } #endif /// The diagram for step `step` (counted from 1) of a fixture. public func diagram(_ fixtureName: String, step: Int) throws -> Diagram { let file = try FoldFile(contentsOf: fixture(fixtureName)) return buildDiagram(file: file, step: try readStep(step, in: file)) } /// `visibleSegments` of a fixture's edge in frame `n`, with frame n's order and step n + 1's /// viewpoint (the default one after the last step). public func visibleSegmentsOf(_ fixtureName: String, edge: Int, inFrame n: Int) throws -> [(SIMD2, SIMD2)] { let file = try FoldFile(contentsOf: fixture(fixtureName)) let frame = file.frames[n] let order = try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, file)) let viewpoint = n + 1 < file.frames.count ? try readStep(n + 1, in: file).viewpoint : Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) return visibleSegments(of: edge, frame: frame, file: file, order: order, viewpoint: viewpoint) } public func segmentLength(_ segment: (SIMD2, SIMD2)) -> Double { simd_distance(segment.0, segment.1) } /// The canvas is square, this many pixels a side, white. private let canvasSide = 480 /// `diagram` drawn by `drawDiagram` with `DiagramStyle.standard` on a white canvas. public func render(_ diagram: Diagram) -> CGImage { let side = Double(canvasSide) let context = CGContext(data: nil, width: canvasSide, height: canvasSide, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! context.setFillColor(gray: 1, alpha: 1) context.fill(CGRect(x: 0, y: 0, width: side, height: side)) drawDiagram(diagram, style: .standard, in: context, size: CGSize(width: side, height: side)) return context.makeImage()! } /// The number of the image's pixels darker than mid-grey in any channel. public func inkedPixels(_ image: CGImage) -> Int { let bytes = rgba(image) return (0..<(image.width * image.height)).count { p in (0..<3).contains { bytes[4 * p + $0] < 128 } } } /// Golden images differ from a render when any channel of any pixel differs by more than this, /// out of 255. private let snapshotTolerance = 24 public enum SnapshotError: Error { case unreadable(String) } /// Compares `image` with `Snapshots/.png` beside the calling test file. Records the image /// there, and fails saying so, when the golden is missing or `FOLD_RECORD_SNAPSHOTS=1`. public func expectSnapshot(_ image: CGImage, named name: String, filePath: String = #filePath, sourceLocation: SourceLocation = #_sourceLocation) throws { let url = URL(fileURLWithPath: filePath).deletingLastPathComponent() .appendingPathComponent("Snapshots").appendingPathComponent("\(name).png") let recording = ProcessInfo.processInfo.environment["FOLD_RECORD_SNAPSHOTS"] == "1" if recording || !FileManager.default.fileExists(atPath: url.path) { try writePNG(image, to: url) Issue.record("recorded \(url.path); inspect it and run again", sourceLocation: sourceLocation) return } guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), let golden = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw SnapshotError.unreadable(url.path) } guard golden.width == image.width, golden.height == image.height else { Issue.record("\(name): \(image.width)×\(image.height), golden \(golden.width)×\(golden.height)", sourceLocation: sourceLocation) return } let (rendered, expected) = (rgba(image), rgba(golden)) var pixels = 0, first: Int? for p in 0..<(image.width * image.height) { let differs = (0..<4).contains { abs(Int(rendered[4 * p + $0]) - Int(expected[4 * p + $0])) > snapshotTolerance } if differs { pixels += 1 first = first ?? p } } if let first { let actual = FileManager.default.temporaryDirectory.appendingPathComponent("\(name).png") try writePNG(image, to: actual) let x = first % image.width, y = first / image.width Issue.record("\(name): \(pixels) pixels differ from the golden image, first at (\(x), \(y)); this render is at \(actual.path)", sourceLocation: sourceLocation) } } private func writePNG(_ image: CGImage, to url: URL) throws { guard let destination = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else { throw SnapshotError.unreadable(url.path) } CGImageDestinationAddImage(destination, image, nil) guard CGImageDestinationFinalize(destination) else { throw SnapshotError.unreadable(url.path) } } /// The image's pixels as 8-bit premultiplied RGBA in sRGB, row by row from the top. private func rgba(_ image: CGImage) -> [UInt8] { var bytes = [UInt8](repeating: 0, count: image.width * image.height * 4) bytes.withUnsafeMutableBytes { buffer in let context = CGContext(data: buffer.baseAddress, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) } return bytes } /// The fold parameter mapping for step `step` (counted from 1) of a fixture, looking at the step's /// start frame from its viewpoint, two sheet sizes away, in an 800 × 600 viewport. public func mapping(_ fixtureName: String, step: Int) throws -> FoldParameterMapping { let file = try FoldFile(contentsOf: fixture(fixtureName)) let s = try readStep(step, in: file) let points = file.frames[step - 1].verticesCoords let centre = (points.dropFirst().reduce(points[0], simd_min) + points.dropFirst().reduce(points[0], simd_max)) / 2 let camera = Camera(eye: centre + normalize(s.viewpoint.eye) * 2 * sheetSize(file), target: centre, up: s.viewpoint.up, fieldOfView: .pi / 4) return FoldParameterMapping(file: file, step: s, camera: camera, viewportSize: SIMD2(800, 600)) } /// `half.fold`'s step 1 stopped at 30°, seen along the chord of its moving face's centroid, so the /// centroid travels almost along the view direction. public func mappingForFoldTowardTheCamera() throws -> FoldParameterMapping { let file = try FoldFile(contentsOf: fixture("half.fold")) let full = try readStep(1, in: file) let a = full.axes[0] let step = FoldStep(index: 1, kind: .fold, instruction: full.instruction, axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction, movingFaces: a.movingFaces, startAngle: 0, endAngle: 30)], viewpoint: full.viewpoint) // f1's centroid turns about x = 1 from (1.5, 1, 0) to (1 + 0.5 cos 30°, 1, 0.5 sin 30°) let start = SIMD3(1.5, 1, 0.0) let end = SIMD3(1 + 0.5 * cos(Double.pi / 6), 1, 0.5 * sin(Double.pi / 6)) let middle = (start + end) / 2 let camera = Camera(eye: middle + normalize(end - start) * 4, target: middle, up: SIMD3(0, 1, 0), fieldOfView: .pi / 4) return FoldParameterMapping(file: file, step: step, camera: camera, viewportSize: SIMD2(800, 600)) }