Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/Packages/FoldKit/Tests/ModelsTests/CatalogueTests.swift history · blame · raw

162 lines · 7797 bytes

18 symbols in this file
  1import Foundation
  2import Testing
  3import simd
  4import FoldCompiler
  5import FoldFormat
  6import Folding
  7import FoldKitTestSupport
  8import Models
  9import Notation
 10
 11@Test func everyShippedStepEndsOnItsEndFrame() throws {
 12    // the step records and the frames must agree: interpolating a step to t = 1 reproduces frame n
 13    for file in try ModelLibrary.all() {
 14        for step in try readSteps(file) {
 15            let i = FoldInterpolator(file: file, step: step)
 16            #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords)
 17                .allSatisfy { simd_distance($0, $1) < 1e-6 * sheetSize(file) }, "\(file.fileTitle ?? "?") step \(step.index)")
 18        }
 19    }
 20}
 21
 22@Test func everyShippedModelValidates() throws {
 23    for file in try ModelLibrary.all() { #expect(validate(file).isEmpty, "\(file.fileTitle ?? "?")") }
 24}
 25
 26@Test func everyShippedModelReadsItsSteps() throws {
 27    for file in try ModelLibrary.all() {
 28        #expect(try readSteps(file).count == file.stepCount)
 29    }
 30}
 31
 32@Test func noShippedModelStretchesAtAnyStep() throws {
 33    // flagged non-rigid steps are held to Task 0b's bound instead
 34    for file in try ModelLibrary.all() {
 35        for step in try readSteps(file) where !step.nonRigid {
 36            let i = FoldInterpolator(file: file, step: step)
 37            for t in stride(from: 0.0, through: 1.0, by: 1.0 / 256) {
 38                #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6,
 39                        "\(file.fileTitle ?? "?") step \(step.index) t \(t)")
 40            }
 41        }
 42    }
 43}
 44
 45@Test func noShippedModelInterpenetratesAtAnyStep() throws {
 46    // non-rigid steps bend their faces; everyFlaggedStepStaysWithinTheBound checks them on the mesh
 47    for file in try ModelLibrary.all() {
 48        for step in try readSteps(file) where !step.nonRigid {
 49            let i = FoldInterpolator(file: file, step: step)
 50            #expect(interpenetrations(i, faces: file.facesVertices, samples: 64).isEmpty,
 51                    "\(file.fileTitle ?? "?") step \(step.index)")
 52        }
 53    }
 54}
 55
 56@Test func noShippedModelMovesThroughAStillFace() throws {
 57    for file in try ModelLibrary.all() { #expect(layerMotionDefects(file).isEmpty, "\(file.fileTitle ?? "?")") }
 58}
 59
 60@Test func everyModelIsAttributedAsTraditional() throws {
 61    for file in try ModelLibrary.all() { #expect(file.fileAuthor == "Traditional") }
 62}
 63
 64@Test func everyShippedModelRegeneratesFromItsScript() throws {
 65    for name in try ModelLibrary.names() {
 66        let recompiled = try compile(FoldScript(contentsOf: script(name)),
 67                                     pattern: FoldFile(contentsOf: pattern(name)))
 68        #expect(structurallyEqual(recompiled, try ModelLibrary.model(named: name), tolerance: 1e-12), "\(name)")
 69    }
 70}
 71
 72@Test func everyFlaggedStepStaysWithinTheBound() throws {
 73    // decisions 0002 and 0003: 10% largest edge strain on the render mesh, and nothing passes
 74    // through anything in any phase
 75    for file in try ModelLibrary.all() {
 76        for step in try readSteps(file) where step.nonRigid {
 77            let i = FoldInterpolator(file: file, step: step)
 78            let (lo, hi) = (step.pop!.phases.lowerBound, step.pop!.phases.upperBound)
 79            let worst = (0...128).map { strain(i.meshPositions(at: lo + Double($0) / 128 * (hi - lo)), mesh: i.mesh) }.max()!
 80            #expect(worst <= 0.10, "\(file.fileTitle ?? "?") step \(step.index)")
 81            #expect(meshInterpenetrations(i, samples: 64).isEmpty, "\(file.fileTitle ?? "?") step \(step.index)")
 82        }
 83    }
 84}
 85
 86@Test func everyShippedStepBuildsWhatTheAppShowsOfIt() throws {
 87    // per step, what the app's session builds, with its camera at the step's authored viewpoint
 88    for file in try ModelLibrary.all() {
 89        for n in 1..<file.frames.count {
 90            let label = "\(file.fileTitle ?? "?") step \(n)"
 91            let step = try readStep(n, in: file)
 92            let order = try LayerOrder.active(for: step, in: file)
 93            _ = buildDiagram(file: file, step: step)
 94            let interpolator = FoldInterpolator(file: file, step: step)
 95            let camera = sessionCamera(file, step, aspect: 400.0 / 600)
 96            for t in [0, 0.5, 1.0] {
 97                let clusters = order.clusters(positions: interpolator.positions(at: t), faces: file.facesVertices,
 98                                              viewDirection: camera.target - camera.eye)
 99                #expect(clusters.reduce(0) { $0 + $1.faces.count } == file.facesVertices.count, "\(label) t \(t)")
100            }
101            let mapping = FoldParameterMapping(file: file, step: step, camera: camera, viewportSize: SIMD2(400, 600))
102            #expect(mapping.path.allSatisfy { $0.x.isFinite && $0.y.isFinite }, "\(label)")
103        }
104    }
105}
106
107/// The camera FoldSession starts a step with: from the step's viewpoint, at the default field of
108/// view, far enough that the flat sheet's half-diagonal fits about the start frame's centre.
109func sessionCamera(_ file: FoldFile, _ step: FoldStep, aspect: Double) -> Camera {
110    func bounds(_ p: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>) {
111        (p.dropFirst().reduce(p[0], simd_min), p.dropFirst().reduce(p[0], simd_max))
112    }
113    let (low, high) = bounds(file.frames[0].verticesCoords)
114    let (startLow, startHigh) = bounds(file.frames[step.index - 1].verticesCoords)
115    let target = (startLow + startHigh) / 2
116    let fieldOfView = Double.pi / 6
117    let distance = simd_length(high - low) / 2 / sin(min(fieldOfView / 2, atan(tan(fieldOfView / 2) * aspect)))
118    let eye = simd_normalize(step.viewpoint.eye)
119    let up = simd_normalize(step.viewpoint.up - simd_dot(step.viewpoint.up, eye) * eye)
120    return Camera(eye: target + distance * eye, target: target, up: up, fieldOfView: fieldOfView)
121}
122
123@Test func everyModelHasAnAuthoringRecord() throws {
124    for name in try ModelLibrary.names() {
125        #expect(FileManager.default.fileExists(atPath: authoringDoc(name).path))
126    }
127}
128
129@Test func theBoxRaisesItsEndsOnSolvedCurvesAndEndsStanding() throws {
130    // decision 0002: the end walls are rigid, coupled steps; the box is not flat at the end
131    let box = try ModelLibrary.model(named: "box")
132    let raising = try readSteps(box).filter { $0.axes.contains { $0.curve != nil } }
133    #expect(raising.map(\.index) == [9, 11])
134    #expect(raising.allSatisfy { !$0.nonRigid })
135    let heights = box.frames[box.stepCount].verticesCoords.map(\.z)
136    #expect(heights.max()! - heights.min()! > 0.4)
137}
138
139@Test func theSampanTurnsInsideOutRigidlyAndEndsWithItsSidesUp() throws {
140    // decision 0002: the inside-out step closes, so it is rigid; at the end the floor's corners
141    // (½, 1½), (3½, 1½), (3½, 2½), (½, 2½) lie level and the sides' top corners (1, 1), (3, 1),
142    // (3, 3), (1, 3) stand at least 0.4 above them
143    let sampan = try ModelLibrary.model(named: "sampan")
144    #expect(try readSteps(sampan).allSatisfy { !$0.nonRigid })
145    let flat = sampan.frames[0].verticesCoords, last = sampan.frames[sampan.stepCount].verticesCoords
146    func height(_ x: Double, _ y: Double) throws -> Double {
147        try #require(flat.indices.first { abs(flat[$0].x - x) < 1e-9 && abs(flat[$0].y - y) < 1e-9 }.map { last[$0].z })
148    }
149    let floor = try [(0.5, 1.5), (3.5, 1.5), (3.5, 2.5), (0.5, 2.5)].map { try height($0.0, $0.1) }
150    #expect(floor.max()! - floor.min()! < 1e-9)
151    for (x, y) in [(1.0, 1.0), (3.0, 1.0), (3.0, 3.0), (1.0, 3.0)] {
152        #expect(try height(x, y) - floor[0] > 0.4, "rim corner (\(x), \(y))")
153    }
154}
155
156@Test func theCupContainsATurnOverStep() throws {
157    #expect(try readSteps(ModelLibrary.model(named: "cup")).contains { $0.kind == .turnOver })
158}
159
160@Test func foldlintExitsNonZeroOnADefectiveFile() throws {
161    #expect(try runFoldlint(on: fixture("bad-index.fold")).exitCode == 1)
162}