SPB Git

Repository Public License

GeometryTests.swift 24.0 KB 385 lines swift

1// ORIX Convert — Packages/EngineModel3D/Tests/EngineModel3DTests/GeometryTests.swift2// Description: Unit and axis conversion exactness on known vertex positions, normal generation, welding, topology,3//              and simplification (target, error bounds, border and seam preservation).4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import Testing7import simd8import ConvertCore9@testable import EngineModel3D1011/// World-space positions of a glTF/GLB file read with the engine's independent checker.12func gltfPositions(_ url: URL) throws -> (positions: [SIMD3<Float>], triangles: Int, problems: [String], json: [String: Any]) {13    let document = try GLTFDocument.load(url, limits: ModelLimits())14    let (problems, geometry) = document.check()15    return (geometry.positions, geometry.triangles, problems, document.json)16}1718func containsAll(_ positions: [SIMD3<Float>], _ expected: [SIMD3<Float>], tolerance: Float = 1e-7) -> Bool {19    expected.allSatisfy { e in positions.contains { simd_distance($0, e) <= tolerance } } && positions.allSatisfy { p in expected.contains { simd_distance($0, p) <= tolerance } }20}2122@Suite("Units and axes")23struct UnitAxisTests {24    let engine = Model3DEngine()2526    @Test func millimetreZUpSTLBecomesMetreYUpGLB() async throws {27        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }28        let source = try Fixtures.source(.stl, in: dir)29        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)30        let (output, recorder, _) = try await engine.run(source.url, from: .stl, to: .glb, options: ["unit.source": .string("mm"), "axis.source": .string("z")], work: work)31        #expect(output.facts["unit.factor"] == "0.001")32        #expect(output.facts["unit.output"] == "m")33        #expect(output.facts["axis.output"] == "Y-up")34        let read = try gltfPositions(output.files[0])35        #expect(read.problems.isEmpty)36        // (x, y, z) mm Z-up → (x, z, −y) / 1000 m Y-up.37        #expect(containsAll(read.positions, [SIMD3(0, 0, 0), SIMD3(0.001, 0, 0), SIMD3(0, 0, -0.001), SIMD3(0, 0.001, 0)], tolerance: 1e-9))38        #expect(recorder.codes().contains("unit-converted"))39        #expect(recorder.codes().contains("axis-converted"))40    }4142    @Test func unknownUnitIsNeverRescaledSilently() async throws {43        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }44        let source = try Fixtures.source(.stl, in: dir)45        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)46        let (output, recorder, _) = try await engine.run(source.url, from: .stl, to: .glb, work: work)47        #expect(output.facts["unit.factor"] == "1.0")48        #expect(output.facts["unit.source"] == "not stated")49        #expect(recorder.codes().contains("unit-unknown"))50        #expect(recorder.codes().contains("axis-unknown"))51        let read = try gltfPositions(output.files[0])52        #expect(containsAll(read.positions, [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(0, 1, 0), SIMD3(0, 0, 1)]))53        // Asking for an output unit without knowing the source unit is refused, not guessed.54        await #expect(throws: ConversionError.self) {55            _ = try await engine.run(source.url, from: .stl, to: .ply, options: ["unit.target": .string("mm")], work: work)56        }57        await #expect(throws: ConversionError.self) {58            _ = try await engine.run(source.url, from: .stl, to: .ply, options: ["axis.target": .string("y")], work: work)59        }60    }6162    @Test func inchesToMillimetresIsExact() async throws {63        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }64        let source = try Fixtures.source(.obj, in: dir)65        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)66        let (output, _, _) = try await engine.run(source.url, from: .obj, to: .stl, options: ["unit.source": .string("in"), "unit.target": .string("mm")], work: work)67        #expect(output.facts["unit.factor"] == "25.4")68        let scene = try STLCodec.read(output.files[0], limits: ModelLimits())69        let box = try #require(Geometry.boundingBox(of: scene))70        #expect(box.min == SIMD3<Double>(0, 0, 0))71        #expect(abs(box.max.x - 25.4) < 1e-5 && abs(box.max.y - 25.4) < 1e-5 && abs(box.max.z - 25.4) < 1e-5)72        #expect(scene.triangleCount == 12)73    }7475    @Test func usdMetadataIsReadAndHonoured() async throws {76        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }77        let source = try Fixtures.source(.usda, in: dir)78        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)79        let (output, _, _) = try await engine.run(source.url, from: .usda, to: .glb, work: work)80        #expect(output.facts["unit.source"] == "cm")81        #expect(output.facts["unit.factor"] == "0.01")82        #expect(output.facts["axis.source"] == "Z-up")83        let read = try gltfPositions(output.files[0])84        // Quad (0..1, 0..2, 0) cm, translated by 10 cm in X, Z-up → metres, Y-up: (x, z, −y) / 100.85        #expect(containsAll(read.positions, [SIMD3(0.10, 0, 0), SIMD3(0.11, 0, 0), SIMD3(0.11, 0, -0.02), SIMD3(0.10, 0, -0.02)], tolerance: 1e-7))86        #expect(read.triangles == 2)87    }8889    @Test func rootTransformOptionKeepsVerticesAndAddsANode() async throws {90        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }91        let source = try Fixtures.source(.usda, in: dir)92        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)93        let (output, _, _) = try await engine.run(source.url, from: .usda, to: .glb, options: ["transform.apply": .string("root")], work: work)94        let read = try gltfPositions(output.files[0])95        #expect(containsAll(read.positions, [SIMD3(0.10, 0, 0), SIMD3(0.11, 0, 0), SIMD3(0.11, 0, -0.02), SIMD3(0.10, 0, -0.02)], tolerance: 1e-7))96        let nodes = try #require(read.json["nodes"] as? [[String: Any]])97        #expect(nodes.contains { ($0["name"] as? String) == "ORIX_coordinate_conversion" && $0["matrix"] != nil })98    }99100    @Test func threeMFUnitIsRecordedInUSD() async throws {101        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }102        let source = try Fixtures.source(.threeMF, in: dir)103        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)104        let (output, _, _) = try await engine.run(source.url, from: .threeMF, to: .usda, work: work)105        let text = try String(contentsOf: output.files[0], encoding: .utf8)106        #expect(text.contains("metersPerUnit = 0.001"))107        #expect(text.contains("upAxis = \"Z\""))108        #expect(output.facts["unit.factor"] == "1.0")109        let info = USDLayerInfo.read(output.files[0], limits: ModelLimits())110        #expect(info.metersPerUnit == 0.001)111        #expect(info.upAxis == .z)112        // The build item translation (20 mm in X) is kept.113        let scene = try ModelIOBridge.load(output.files[0], format: .usda, limits: ModelLimits())114        let box = try #require(Geometry.boundingBox(of: scene))115        #expect(box.min == SIMD3<Double>(20, 0, 0) && box.max == SIMD3<Double>(30, 10, 10))116    }117118    @Test func crateOutputIsConvertedToCentimetres() async throws {119        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }120        let source = try Fixtures.source(.gltf, in: dir)121        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)122        let (output, recorder, _) = try await engine.run(source.url, from: .gltf, to: .usdc, work: work)123        #expect(output.facts["unit.factor"] == "100.0")124        #expect(output.facts["unit.output"] == "cm")125        #expect(recorder.codes().contains("unit-converted"))126        let info = USDLayerInfo.read(output.files[0], limits: ModelLimits())127        #expect(info.metadataReadable)128        #expect(info.metersPerUnit == nil)       // Model I/O does not author it: USD's default (0.01) applies.129        #expect(info.upAxis == .y)130        let g = try SceneKitBridge.readGeometry(output.files[0])131        #expect(containsAll(g.positions, [SIMD3(0, 0, 0), SIMD3(100, 0, 0), SIMD3(0, 100, 0)], tolerance: 1e-4))132    }133134    @Test func colladaUnitAndAxisRoundTrip() async throws {135        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }136        let source = try Fixtures.source(.dae, in: dir)137        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)138        let (output, _, _) = try await engine.run(source.url, from: .dae, to: .dae, operation: Model3DCatalog.reprocessOperation, work: work)139        let read = try ColladaCheck.read(output.files[0], limits: ModelLimits())140        #expect(read.unitMeter == 0.01)141        #expect(read.upAxis == "Z_UP")142        #expect(containsAll(read.positions, [SIMD3(5, 0, 0), SIMD3(7, 0, 0), SIMD3(7, 1, 0), SIMD3(5, 1, 0)], tolerance: 1e-5))143        // To glTF: centimetres → metres, Z-up → Y-up.144        let (glb, _, _) = try await engine.run(source.url, from: .dae, to: .glb, work: work)145        #expect(glb.facts["unit.factor"] == "0.01")146        let g = try gltfPositions(glb.files[0])147        #expect(containsAll(g.positions, [SIMD3(0.05, 0, 0), SIMD3(0.07, 0, 0), SIMD3(0.07, 0, -0.01), SIMD3(0.05, 0, -0.01)], tolerance: 1e-7))148    }149150    @Test func mirroringKeepsFacesOutward() async throws {151        var mesh = Fixtures.cube()152        func signedVolume(_ m: Mesh3D) -> Float {153            var v: Float = 0154            for t in 0..<m.triangleCount { v += simd_dot(m.positions[Int(m.indices[t * 3])], simd_cross(m.positions[Int(m.indices[t * 3 + 1])], m.positions[Int(m.indices[t * 3 + 2])])) / 6 }155            return v156        }157        #expect(abs(signedVolume(mesh) - 1) < 1e-6)158        Geometry.transform(&mesh, by: simd_double4x4(diagonal: SIMD4(1, 1, -1, 1)))159        #expect(abs(signedVolume(mesh) - 1) < 1e-6)160        #expect(mesh.positions.contains(SIMD3(1, 1, -1)))161    }162163    @Test func axisConversionMatricesAreRotations() {164        for from in [UpAxis.x, .y, .z] { for to in [UpAxis.x, .y, .z] {165            let m = Geometry.axisConversion(from: from, to: to)166            #expect(abs(simd_determinant(Geometry.upper3x3(m)) - 1) < 1e-12)167            let up: SIMD4<Double> = from == .x ? SIMD4(1, 0, 0, 0) : (from == .y ? SIMD4(0, 1, 0, 0) : SIMD4(0, 0, 1, 0))168            let expected: SIMD4<Double> = to == .x ? SIMD4(1, 0, 0, 0) : (to == .y ? SIMD4(0, 1, 0, 0) : SIMD4(0, 0, 1, 0))169            #expect(simd_distance(m * up, expected) < 1e-12)170        } }171    }172173    @Test func bakedCoordinateChangeKeepsWorldPositionsOfAHierarchy() {174        var scene = Fixtures.hierarchyScene()175        let before = Geometry.worldPositions(of: scene)176        let c = Geometry.axisConversion(from: .z, to: .y) * Geometry.scale(0.001)177        Geometry.changeCoordinates(&scene, by: c, bake: true)178        let after = Geometry.worldPositions(of: scene)179        #expect(scene.nodes.count == 2)180        for (a, b) in zip(before, after) {181            let expected = c * SIMD4<Double>(Double(a.x), Double(a.y), Double(a.z), 1)182            #expect(simd_distance(SIMD3<Double>(b), expected.xyz) < 1e-8)183        }184    }185}186187@Suite("Normals, welding, topology")188struct MeshProcessingTests {189    @Test func flatNormalsOnACube() {190        var mesh = Fixtures.cube()191        Normals.generate(&mesh, creaseAngleDegrees: 0)192        #expect(mesh.vertexCount == 24)193        #expect(mesh.triangleCount == 12)194        let normals = try! #require(mesh.normals)195        for n in normals { #expect(abs(abs(n.x) + abs(n.y) + abs(n.z) - 1) < 1e-6 && abs(simd_length(n) - 1) < 1e-6) }196        // Outward: the normal of a vertex points away from the cube centre.197        for (p, n) in zip(mesh.positions, normals) { #expect(simd_dot(n, p - SIMD3(0.5, 0.5, 0.5)) > 0) }198    }199200    @Test func smoothNormalsWithCreaseAngle() {201        var smooth = Fixtures.cube()202        Normals.generate(&smooth, creaseAngleDegrees: 180)203        #expect(smooth.vertexCount == 8)204        for (p, n) in zip(smooth.positions, smooth.normals!) {205            #expect(abs(simd_length(n) - 1) < 1e-5)206            #expect(simd_dot(n, simd_normalize(p - SIMD3(0.5, 0.5, 0.5))) > 0.8)207        }208        // A cube's faces meet at 90°: with a 60° crease angle every edge stays hard.209        var creased = Fixtures.cube()210        Normals.generate(&creased, creaseAngleDegrees: 60)211        #expect(creased.vertexCount == 24)212        // A sphere is smooth everywhere at 60°: one normal per position, close to the radial direction.213        var sphere = Fixtures.sphere(segments: 24, rings: 12)214        sphere.normals = nil; sphere.uvSets = []215        Welding.weld(&sphere)216        let positions = sphere.vertexCount217        Normals.generate(&sphere, creaseAngleDegrees: 60)218        #expect(sphere.vertexCount == positions)219        for (p, n) in zip(sphere.positions, sphere.normals!) { #expect(simd_dot(n, simd_normalize(p)) > 0.95) }220    }221222    @Test func exactAndToleranceWelding() {223        // Triangle soup of a cube: 36 vertices → 8.224        let cube = Fixtures.cube()225        var soup = Mesh3D(name: "soup", positions: cube.indices.map { cube.positions[Int($0)] }, indices: (0..<36).map { UInt32($0) })226        #expect(Welding.weld(&soup) == 28)227        #expect(soup.vertexCount == 8 && soup.triangleCount == 12)228        // Attributes keep vertices apart.229        var colored = Mesh3D(name: "c", positions: [SIMD3(0, 0, 0), SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(0, 1, 0)], indices: [0, 2, 3, 1, 3, 2],230                             colors: [SIMD4(1, 0, 0, 1), SIMD4(0, 1, 0, 1), SIMD4(1, 1, 1, 1), SIMD4(1, 1, 1, 1)])231        #expect(Welding.weld(&colored) == 0)232        // Tolerance: nearly coincident positions merge, and the degenerate triangle disappears.233        var near = Mesh3D(name: "n", positions: [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(0, 1, 0), SIMD3(1.00001, 0, 0), SIMD3(1, 1, 0), SIMD3(0.00001, 0, 0)], indices: [0, 1, 2, 3, 4, 2, 0, 5, 2])234        #expect(Welding.weld(&near, tolerance: 0) == 0)235        #expect(Welding.weld(&near, tolerance: 0.001) == 2)236        #expect(near.vertexCount == 4 && near.triangleCount == 2)237    }238239    @Test func topologyReports() {240        let closed = Topology.analyze(Scene3D(mesh: Fixtures.cube()))241        #expect(closed.isWatertight && closed.boundaryEdges == 0 && closed.nonManifoldEdges == 0)242        var open = Fixtures.cube()243        open.indices.removeLast(3)244        let report = Topology.analyze(Scene3D(mesh: open))245        #expect(!report.isWatertight && report.boundaryEdges == 3)246        // Three triangles on one edge.247        let fan = Mesh3D(name: "fan", positions: [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(0, 1, 0), SIMD3(0, -1, 0), SIMD3(0, 0, 1)], indices: [0, 1, 2, 1, 0, 3, 0, 1, 4])248        #expect(Topology.analyze(Scene3D(mesh: fan)).nonManifoldEdges == 1)249        // Triangle soup of a closed cube is still watertight (positions are merged for the check).250        let cube = Fixtures.cube()251        let soup = Mesh3D(name: "soup", positions: cube.indices.map { cube.positions[Int($0)] }, indices: (0..<36).map { UInt32($0) })252        #expect(Topology.analyze(Scene3D(mesh: soup)).isWatertight)253    }254255    @Test func sanitizeDropsInvalidData() {256        var scene = Scene3D(mesh: Mesh3D(name: "bad", positions: [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(0, 1, 0), SIMD3(.nan, 0, 0)], indices: [0, 1, 2, 0, 1, 9, 0, 1, 3],257                                         normals: [SIMD3(0, 0, 1)], material: 5))258        scene.nodes[0].children = [0, 7]259        scene.sanitize()260        #expect(scene.meshes[0].triangleCount == 1)261        #expect(scene.meshes[0].normals == nil)262        #expect(scene.meshes[0].material == nil)263        #expect(scene.nodes[0].children.isEmpty)264        #expect(Set(scene.notes.map(\.code)).isSuperset(of: ["invalid-triangles", "invalid-attributes", "invalid-hierarchy"]))265    }266}267268@Suite("Simplification")269struct SimplifyTests {270    @Test func closedSphereReachesTargetWithinErrorBound() throws {271        var mesh = Fixtures.sphere(segments: 64, rings: 32)272        mesh.normals = nil; mesh.uvSets = []273        Welding.weld(&mesh)274        let reference = (mesh.positions, mesh.indices)275        let before = mesh.triangleCount276        let result = try Simplifier.simplify(&mesh, options: SimplifyOptions(targetTriangles: 800))277        #expect(result.trianglesBefore == before)278        #expect(result.targetReached)279        #expect(mesh.triangleCount <= 800 && mesh.triangleCount >= 780)280        #expect(Topology.analyze(Scene3D(mesh: mesh)).isWatertight)281        let error = try #require(try SurfaceDistance.measure(reference: reference, modified: (mesh.positions, mesh.indices), samplesPerSide: 6000))282        // 800 triangles on a unit sphere: the chord error stays well under 2 % of the diagonal.283        #expect(error.max < 0.02 * error.referenceDiagonal, "max \(error.max)")284        #expect(error.mean < 0.005 * error.referenceDiagonal, "mean \(error.mean)")285        #expect(error.mean > 0)286        // Half-edge collapses: every surviving vertex is a source vertex.287        let source = Set(reference.0.map { [$0.x.bitPattern, $0.y.bitPattern, $0.z.bitPattern] })288        #expect(mesh.positions.allSatisfy { source.contains([$0.x.bitPattern, $0.y.bitPattern, $0.z.bitPattern]) })289    }290291    @Test func openBorderIsPreserved() throws {292        var mesh = Fixtures.grid(40)293        let reference = (mesh.positions, mesh.indices)294        let result = try Simplifier.simplify(&mesh, options: SimplifyOptions(targetTriangles: 400))295        #expect(result.trianglesAfter <= 400)296        var lo = SIMD3<Float>(repeating: .infinity), hi = SIMD3<Float>(repeating: -.infinity)297        for p in mesh.positions { lo = simd_min(lo, p); hi = simd_max(hi, p) }298        #expect(lo.x == 0 && lo.y == 0 && hi.x == 1 && hi.y == 1)299        // The four corners survive and the outline is still the unit square: border edges only on the border.300        for corner in [SIMD2<Float>(0, 0), SIMD2(1, 0), SIMD2(0, 1), SIMD2(1, 1)] { #expect(mesh.positions.contains { $0.x == corner.x && $0.y == corner.y }) }301        let (pid, count) = Welding.positionIDs(mesh.positions)302        var position = [SIMD3<Float>](repeating: .zero, count: count)303        for (i, id) in pid.enumerated() { position[Int(id)] = mesh.positions[i] }304        var uses: [UInt64: Int] = [:]305        for t in 0..<mesh.triangleCount { for k in 0..<3 {306            let a = pid[Int(mesh.indices[t * 3 + k])], b = pid[Int(mesh.indices[t * 3 + (k + 1) % 3])]307            uses[UInt64(min(a, b)) << 32 | UInt64(max(a, b)), default: 0] += 1308        } }309        var borderLength: Float = 0310        for (key, n) in uses where n == 1 {311            let a = position[Int(key >> 32)], b = position[Int(key & 0xFFFF_FFFF)]312            let onBorder = (a.x == 0 && b.x == 0) || (a.x == 1 && b.x == 1) || (a.y == 0 && b.y == 0) || (a.y == 1 && b.y == 1)313            #expect(onBorder)314            borderLength += simd_distance(SIMD2(a.x, a.y), SIMD2(b.x, b.y))315        }316        #expect(abs(borderLength - 4) < 1e-4)317        let error = try #require(try SurfaceDistance.measure(reference: reference, modified: (mesh.positions, mesh.indices), samplesPerSide: 4000))318        #expect(error.max < 0.03 * error.referenceDiagonal, "max \(error.max)")319    }320321    @Test func seamsAndAttributesArePreserved() throws {322        var mesh = Fixtures.sphere(segments: 48, rings: 24)323        let sourceVertices = Set(zip(mesh.positions, mesh.uvSets[0]).map { [$0.x.bitPattern, $0.y.bitPattern, $0.z.bitPattern, $1.x.bitPattern, $1.y.bitPattern] })324        let result = try Simplifier.simplify(&mesh, options: SimplifyOptions(targetTriangles: 600))325        #expect(result.trianglesAfter < result.trianglesBefore / 2)326        #expect(mesh.uvSets[0].count == mesh.vertexCount && mesh.normals?.count == mesh.vertexCount)327        // Surviving vertices keep their exact position + UV pair (no attribute was invented or moved across the seam).328        for (p, uv) in zip(mesh.positions, mesh.uvSets[0]) { #expect(sourceVertices.contains([p.x.bitPattern, p.y.bitPattern, p.z.bitPattern, uv.x.bitPattern, uv.y.bitPattern])) }329        // No triangle spans the seam: within a triangle, U never jumps by more than half the texture.330        for t in 0..<mesh.triangleCount {331            let u = (0..<3).map { mesh.uvSets[0][Int(mesh.indices[t * 3 + $0])].x }332            #expect(u.max()! - u.min()! <= 0.5)333        }334        #expect(Topology.analyze(Scene3D(mesh: mesh)).isWatertight)335    }336337    @Test func nothingToDoAndCancellation() throws {338        var cube = Fixtures.cube()339        let untouched = try Simplifier.simplify(&cube, options: SimplifyOptions(targetTriangles: 100))340        #expect(untouched.collapses == 0 && cube.triangleCount == 12)341        var mesh = Fixtures.grid(120)342        let flag = CancelFlag()343        flag.cancel()344        #expect(throws: CancellationError.self) { _ = try Simplifier.simplify(&mesh, options: SimplifyOptions(targetTriangles: 10), cancel: flag) }345    }346347    @Test func distanceGridMatchesBruteForce() throws {348        let sphere = Fixtures.sphere(segments: 16, rings: 8)349        let grid = try #require(TriangleGrid(positions: sphere.positions, indices: sphere.indices))350        for p in [SIMD3<Float>(0, 0, 0), SIMD3(2, 0.3, -1), SIMD3(0.5, 0.5, 0.5), SIMD3(-0.9, 0.1, 0.2), SIMD3(10, 10, 10)] {351            var brute = Float.infinity352            for t in 0..<sphere.triangleCount {353                brute = min(brute, TriangleGrid.distanceSquared(p, sphere.positions[Int(sphere.indices[t * 3])], sphere.positions[Int(sphere.indices[t * 3 + 1])], sphere.positions[Int(sphere.indices[t * 3 + 2])]))354            }355            #expect(abs(grid.distance(to: p) - brute.squareRoot()) < 1e-5)356        }357        // A surface compared with itself has no error.358        let zero = try #require(try SurfaceDistance.measure(reference: (sphere.positions, sphere.indices), modified: (sphere.positions, sphere.indices), samplesPerSide: 500))359        #expect(zero.max < 1e-6)360    }361362    @Test func engineSimplifiesMeasuresAndValidates() async throws {363        let dir = Fixtures.directory(); defer { try? FileManager.default.removeItem(at: dir) }364        let work = dir.appendingPathComponent("w"); try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)365        let input = dir.appendingPathComponent("sphere.stl")366        try STLCodec.write(Scene3D(mesh: Fixtures.sphere(segments: 64, rings: 32)), to: input, binary: true)367        let engine = Model3DEngine()368        let (output, recorder, request) = try await engine.run(input, from: .stl, to: .ply, options: ["simplify.enabled": .bool(true), "simplify.ratio": .double(0.25)], work: work)369        let before = try #require(Int(output.facts["simplify.triangles-before"] ?? "")), after = try #require(Int(output.facts["simplify.triangles-after"] ?? ""))370        #expect(before == 3968)371        #expect(after <= 992 && after > 900)372        let worst = try #require(Double(output.facts["simplify.error.max"] ?? "")), relative = try #require(Double(output.facts["simplify.error.max-relative"] ?? ""))373        #expect(worst > 0 && relative < 0.02)374        #expect(output.facts["triangles"] == "\(after)")375        #expect(recorder.codes().contains("simplified"))376        // Progress during simplification is measured (fractions between 0 and 1, increasing).377        let fractions = recorder.fractions.compactMap { $0 }378        #expect(fractions.allSatisfy { $0 >= 0 && $0 <= 1 })379        for check in try await engine.validate(output, request: request, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }380        // An absolute target is honoured too.381        let (second, _, _) = try await engine.run(input, from: .stl, to: .obj, options: ["simplify.enabled": .bool(true), "simplify.target-triangles": .int(500)], work: work)382        #expect(Int(second.facts["triangles"] ?? "")! <= 500)383    }384}385
Files main
Menu

Theme