import Foundation import Testing import simd import FoldFormat import Folding import FoldKitTestSupport /// A flat 2 × 1 sheet with `points` as its vertices and `faces` as its faces; edges are not read /// by the mesh and are left empty. private func sheet(_ points: [SIMD2], _ faces: [[Int]]) -> FoldFile { FoldFile(fileSpec: 1.2, fileAuthor: "Traditional", edgesVertices: [], facesVertices: faces, edgesFirstCreasedAtStep: [], frames: [FoldFrame(verticesCoords: points.map { SIMD3($0.x, $0.y, 0) }, edgesAssignment: [], edgesFoldAngle: [], faceOrders: [])]) } /// A crease along y = 0.5 split at M = (1, 0.5), and a crease from M to the top edge. M is a /// 180° corner of the bottom face, listed so that a fan from the face's first corner meets it /// collinearly. private func tJunction() -> FoldFile { sheet([SIMD2(0, 0), SIMD2(2, 0), SIMD2(2, 0.5), SIMD2(2, 1), SIMD2(1, 1), SIMD2(0, 1), SIMD2(0, 0.5), SIMD2(1, 0.5)], [[2, 7, 6, 0, 1], [6, 7, 4, 5], [7, 2, 3, 4]]) } /// Whether every mesh vertex in or on a face's outline is a corner of one of that face's triangles. private func everyFaceUsesItsVertices(_ file: FoldFile, _ mesh: RenderMesh) -> Bool { let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } return file.facesVertices.indices.allSatisfy { f in let outline = file.facesVertices[f].map { flat[$0] } var used = Set() for (t, (a, b, c)) in mesh.triangles.enumerated() where mesh.faceOf[t] == f { used.formUnion([a, b, c]) } return mesh.vertices.indices.allSatisfy { v in let p = mesh.vertices[v] let inside = outline.indices.allSatisfy { i in let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = p - a return side.x * offset.y - side.y * offset.x >= -1e-12 } return !inside || used.contains(v) } } } @Test(arguments: [10.0, 0.3, 2.0 / 32]) func aStraightCornerIsInItsFacesTriangles(_ spacing: Double) { let file = tJunction() #expect(everyFaceUsesItsVertices(file, RenderMesh(file: file, spacing: spacing))) } @Test func aNonRigidStepOverAStraightCornerBuilds() { // a crease along y = 0.5 split at M, straight in both faces that hold it, and a crease at // x = 1.5; the right top face is held, the rest move, so M is a free vertex of the pop let m = SIMD2(1.03, 0.5) let file = sheet([SIMD2(0, 0), SIMD2(1.5, 0), SIMD2(2, 0), SIMD2(2, 0.5), SIMD2(2, 1), SIMD2(1.5, 1), SIMD2(0, 1), SIMD2(0, 0.5), m, SIMD2(1.5, 0.5)], [[9, 8, 7, 0, 1], [7, 8, 9, 5, 6], [1, 2, 3, 9], [9, 3, 4, 5]]) let start = file.frames[0].verticesCoords let step = FoldStep(index: 1, kind: .fold, instruction: "Pop.", axes: [FoldAxis(edge: 0, origin: .zero, direction: SIMD3(1, 0, 0), movingFaces: [0, 1, 2], startAngle: 0, endAngle: 0)], nonRigid: true, pop: Pop(spine: [], openAngle: 30, phases: (1.0 / 3)...(2.0 / 3), openAxes: [], popped: start, closeAxes: []), viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))) let i = FoldInterpolator(file: file, step: step) #expect(everyFaceUsesItsVertices(file, i.mesh)) #expect(zip(i.positions(at: 0.5), start).allSatisfy { simd_distance($0, $1) < 1e-9 }) } /// A unit square cut by one crease between irrational heights on its left and right sides; no two /// creases or sides meet at less than 80°. private func offGrid() -> FoldFile { let a = 1 / 7.0.squareRoot(), b = 1 - 1 / 5.0.squareRoot() return sheet([SIMD2(0, 0), SIMD2(1, 0), SIMD2(1, b), SIMD2(1, 1), SIMD2(0, 1), SIMD2(0, a)], [[0, 1, 2, 5], [5, 2, 3, 4]]) } /// The mesh's edges, each once, as pairs of mesh vertices. private func edges(_ mesh: RenderMesh) -> [SIMD2] { var set = Set>() for (a, b, c) in mesh.triangles { for (i, j) in [(a, b), (b, c), (c, a)] { set.insert(SIMD2(min(i, j), max(i, j))) } } return set.sorted { ($0.x, $0.y) < ($1.x, $1.y) } } private func meshTestFiles() throws -> [FoldFile] { [try FoldFile(contentsOf: fixture("reverse-cp.fold")), try FoldFile(contentsOf: fixture("preliminary-cp.fold")), offGrid()] } /// The shipped models' crease patterns, whose faces are their frame 0's. private func shippedPatterns() throws -> [FoldFile] { try ["cup", "box", "sampan", "crane"].map { try FoldFile(contentsOf: pattern($0)) } } @Test func noMeshEdgeIsMuchShorterThanTheSpacing() throws { // decision 0003: 0.15 of the spacing, except where a crease is shorter or creases meet sharply; // none of these sheets needs the exception, the shipped models' included for file in try meshTestFiles() + shippedPatterns() { let spacing = RenderMesh.spacing(for: file) let mesh = RenderMesh(file: file, spacing: spacing) let shortest = edges(mesh).map { simd_distance(mesh.vertices[$0.x], mesh.vertices[$0.y]) }.min()! #expect(shortest >= 0.15 * spacing, "\(file.fileTitle ?? "off grid"): \(shortest / spacing) of the spacing") } } @Test func eachSideOfAFaceIsDividedEvenly() throws { // round(length / spacing) equal parts, the same points in both faces that share the side for file in try meshTestFiles() { let spacing = RenderMesh.spacing(for: file) let mesh = RenderMesh(file: file, spacing: spacing) let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } for face in file.facesVertices { for k in face.indices { let a = flat[face[k]], b = flat[face[(k + 1) % face.count]] let parts = max(1, Int((simd_distance(a, b) / spacing).rounded())) let on = mesh.vertices.filter { p in abs((b - a).x * (p - a).y - (b - a).y * (p - a).x) <= 1e-9 * simd_distance(a, b) && simd_dot(p - a, b - a) >= -1e-12 && simd_dot(p - b, a - b) >= -1e-12 } #expect(on.count == parts + 1) for p in on { let u = simd_dot(p - a, b - a) / simd_length_squared(b - a) * Double(parts) #expect(abs(u - u.rounded()) < 1e-9) } } } } } @Test func theMeshIsDelaunayWithinEachFace() throws { // no edge between two triangles of one face has the opposite corner of one inside the other's circumcircle for file in try meshTestFiles() { let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file)) var opposite: [SIMD2: [Int]] = [:] for (a, b, c) in mesh.triangles { for (i, j, k) in [(a, b, c), (b, c, a), (c, a, b)] { opposite[SIMD2(min(i, j), max(i, j)), default: []].append(k) } } var violations = 0 for (edge, corners) in opposite where corners.count == 2 { let (p, q) = (mesh.vertices[edge.x], mesh.vertices[edge.y]) let (r, s) = (mesh.vertices[corners[0]], mesh.vertices[corners[1]]) // the angles opposite the edge sum to at most 180° when the edge is locally Delaunay func angle(_ o: SIMD2) -> Double { acos(max(-1, min(1, simd_dot(simd_normalize(p - o), simd_normalize(q - o))))) } if angle(r) + angle(s) > .pi + 1e-9 { violations += 1 } } #expect(violations == 0, "\(file.fileTitle ?? "off grid")") } } @Test func eachFoldVertexIsAMeshVertex() throws { for file in try meshTestFiles() { let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file)) #expect(mesh.meshVertexOf.enumerated().allSatisfy { v, m in mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y) }) } }