SPB Git

Repository Public License

Support.swift 21.5 KB 490 lines swift

1// ORIX Convert — Packages/EngineModel3D/Tests/EngineModel3DTests/Support.swift2// Description: Fixtures of the 3D engine tests: meshes generated in code, hand-written files of every text format,3//              a hand-assembled 3MF package, and files of the binary formats produced by the available writers.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import CoreGraphics7import ImageIO8import UniformTypeIdentifiers9import ModelIO10import simd11import ConvertCore12@testable import EngineModel3D1314enum Fixtures {15    /// A fresh temporary directory, removed by the caller.16    static func directory(_ label: String = "fixture") -> URL {17        let url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-m3d-tests/\(label)-\(UUID().uuidString)", isDirectory: true)18        try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)19        return url20    }2122    // MARK: Meshes generated in code2324    /// Unit cube [0,1]³: 8 vertices, 12 triangles, outward winding.25    static func cube(name: String = "cube", size: Float = 1, origin: SIMD3<Float> = .zero) -> Mesh3D {26        let p: [SIMD3<Float>] = [SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0), SIMD3(0, 0, 1), SIMD3(1, 0, 1), SIMD3(1, 1, 1), SIMD3(0, 1, 1)]27        let i: [UInt32] = [0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7]28        return Mesh3D(name: name, positions: p.map { $0 * size + origin }, indices: i)29    }3031    /// UV sphere with normals and texture coordinates (seam duplicated).32    static func sphere(segments: Int = 32, rings: Int = 16, radius: Float = 1) -> Mesh3D {33        var positions: [SIMD3<Float>] = [], normals: [SIMD3<Float>] = [], uvs: [SIMD2<Float>] = []34        var indices: [UInt32] = []35        for r in 0...rings {36            let v = Float(r) / Float(rings), phi = v * .pi37            for s in 0...segments {38                // The last column repeats the first one exactly, and the poles are single points, so the sphere is closed.39                let u = Float(s) / Float(segments), theta = (s == segments ? 0 : u) * 2 * .pi40                let n: SIMD3<Float> = r == 0 ? SIMD3(0, 1, 0) : (r == rings ? SIMD3(0, -1, 0) : SIMD3(sin(phi) * cos(theta), cos(phi), sin(phi) * sin(theta)))41                positions.append(n * radius); normals.append(n); uvs.append(SIMD2(u, 1 - v))42            }43        }44        let row = UInt32(segments + 1)45        for r in 0..<UInt32(rings) {46            for s in 0..<UInt32(segments) {47                let a = r * row + s, b = a + row48                if r != 0 { indices += [a, a + 1, b] }49                if r != UInt32(rings) - 1 { indices += [a + 1, b + 1, b] }50            }51        }52        return Mesh3D(name: "sphere", positions: positions, indices: indices, normals: normals, uvSets: [uvs])53    }5455    /// Flat open grid in the XY plane with a gentle bump, n × n cells.56    static func grid(_ n: Int, size: Float = 1) -> Mesh3D {57        var positions: [SIMD3<Float>] = []58        var indices: [UInt32] = []59        for y in 0...n { for x in 0...n {60            let fx = Float(x) / Float(n), fy = Float(y) / Float(n)61            positions.append(SIMD3(fx * size, fy * size, 0.05 * size * sin(fx * 6) * cos(fy * 6)))62        } }63        let row = UInt32(n + 1)64        for y in 0..<UInt32(n) { for x in 0..<UInt32(n) {65            let a = y * row + x66            indices += [a, a + 1, a + row, a + 1, a + row + 1, a + row]67        } }68        return Mesh3D(name: "grid", positions: positions, indices: indices)69    }7071    static func png(width: Int = 8, height: Int = 8, seed: UInt8 = 0) -> Data {72        var pixels = [UInt8](repeating: 255, count: width * height * 4)73        for y in 0..<height { for x in 0..<width {74            let o = (y * width + x) * 475            pixels[o] = UInt8((x * 255) / max(1, width - 1)); pixels[o + 1] = UInt8((y * 255) / max(1, height - 1)); pixels[o + 2] = seed &+ UInt8((x ^ y) & 1) * 12076        } }77        let context = CGContext(data: &pixels, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!,78                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!79        let image = context.makeImage()!80        let data = NSMutableData()81        let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!82        CGImageDestinationAddImage(destination, image, nil)83        CGImageDestinationFinalize(destination)84        return data as Data85    }8687    /// Quad with UVs, normals and a material carrying a PNG base-colour texture.88    static func texturedQuadScene() -> Scene3D {89        let mesh = Mesh3D(name: "quad", positions: [SIMD3(0, 0, 0), SIMD3(2, 0, 0), SIMD3(2, 1, 0), SIMD3(0, 1, 0)], indices: [0, 1, 2, 0, 2, 3],90                          normals: [SIMD3<Float>](repeating: SIMD3(0, 0, 1), count: 4), uvSets: [[SIMD2(0, 0), SIMD2(1, 0), SIMD2(1, 1), SIMD2(0, 1)]], material: 0)91        var scene = Scene3D(mesh: mesh, name: "quad")92        var material = Material3D(name: "painted")93        material.sourceModel = .pbr94        material.baseColor = SIMD4(1, 1, 1, 1); material.metallic = 0.25; material.roughness = 0.7595        material.baseColorTexture = TextureRef(texture: 0)96        scene.materials = [material]97        scene.textures = [Texture3D(name: "checker.png", origin: .embedded, sourcePath: "checker.png", data: png())]98        scene.metadata.unit = .meter; scene.metadata.upAxis = .y99        return scene100    }101102    /// Root node holding a cube, with a child node (translated, rotated, scaled) holding the same cube.103    static func hierarchyScene() -> Scene3D {104        var scene = Scene3D()105        scene.meshes = [cube()]106        let rotation = simd_double4x4(simd_quatd(angle: .pi / 2, axis: SIMD3(0, 0, 1)))107        var child = matrix_identity_double4x4108        child[3] = SIMD4(3, 0.5, -1, 1)109        child = child * rotation * simd_double4x4(diagonal: SIMD4(2, 2, 2, 1))110        scene.nodes = [Node3D(name: "root", meshes: [0], children: [1]), Node3D(name: "child", transform: child, meshes: [0])]111        scene.roots = [0]112        scene.metadata.unit = .meter; scene.metadata.upAxis = .y113        return scene114    }115116    static func vertexColorScene() -> Scene3D {117        var mesh = cube(name: "painted")118        mesh.colors = mesh.positions.map { SIMD4($0.x, $0.y, $0.z, 1) }119        var scene = Scene3D(mesh: mesh, name: "painted")120        scene.metadata.unit = .meter; scene.metadata.upAxis = .y121        return scene122    }123124    static func multiMaterialScene() -> Scene3D {125        var a = cube(name: "red"); a.material = 0126        var b = cube(name: "blue", origin: SIMD3(2, 0, 0)); b.material = 1127        var scene = Scene3D()128        scene.meshes = [a, b]129        var red = Material3D(name: "red"); red.baseColor = SIMD4(1, 0, 0, 1); red.sourceModel = .pbr130        var blue = Material3D(name: "blue"); blue.baseColor = SIMD4(0, 0, 1, 1); blue.sourceModel = .pbr; blue.metallic = 1131        scene.materials = [red, blue]132        scene.nodes = [Node3D(name: "pair", meshes: [0, 1])]133        scene.roots = [0]134        scene.metadata.unit = .meter; scene.metadata.upAxis = .y135        return scene136    }137138    /// The scene used to produce the binary-format fixtures: hierarchy + textured, coloured content.139    static func richScene() -> Scene3D {140        var scene = hierarchyScene()141        let quad = texturedQuadScene()142        var mesh = quad.meshes[0]143        mesh.material = 0144        scene.meshes.append(mesh)145        scene.materials = quad.materials146        scene.textures = quad.textures147        scene.nodes.append(Node3D(name: "quadNode", transform: simd_double4x4(columns: (SIMD4(1, 0, 0, 0), SIMD4(0, 1, 0, 0), SIMD4(0, 0, 1, 0), SIMD4(0, 2, 0, 1))), meshes: [1]))148        scene.nodes[0].children.append(2)149        return scene150    }151152    // MARK: Hand-written text files153154    static let objText = """155    # hand-written cube with quads156    mtllib cube.mtl157    o cube158    v 0 0 0159    v 1 0 0160    v 1 1 0161    v 0 1 0162    v 0 0 1163    v 1 0 1164    v 1 1 1165    v 0 1 1166    vt 0 0167    vt 1 0168    vt 1 1169    vt 0 1170    vn 0 0 -1171    vn 0 0 1172    vn 0 -1 0173    vn 1 0 0174    vn 0 1 0175    vn -1 0 0176    usemtl painted177    f 1/1/1 4/4/1 3/3/1 2/2/1178    f 5/1/2 6/2/2 7/3/2 8/4/2179    f 1/1/3 2/2/3 6/3/3 5/4/3180    f 2/1/4 3/2/4 7/3/4 6/4/4181    f 3/1/5 4/2/5 8/3/5 7/4/5182    f 4/1/6 1/2/6 5/3/6 8/4/6183184    """185    static let mtlText = """186    newmtl painted187    Kd 0.8 0.4 0.2188    Ks 0.1 0.1 0.1189    Ns 50190    d 1191    illum 2192    map_Kd checker.png193194    """195196    static let stlText = """197    solid tetra198    facet normal 0 0 -1199     outer loop200      vertex 0 0 0201      vertex 0 1 0202      vertex 1 0 0203     endloop204    endfacet205    facet normal 0 -1 0206     outer loop207      vertex 0 0 0208      vertex 1 0 0209      vertex 0 0 1210     endloop211    endfacet212    facet normal -1 0 0213     outer loop214      vertex 0 0 0215      vertex 0 0 1216      vertex 0 1 0217     endloop218    endfacet219    facet normal 0.57735 0.57735 0.57735220     outer loop221      vertex 1 0 0222      vertex 0 1 0223      vertex 0 0 1224     endloop225    endfacet226    endsolid tetra227228    """229230    static let plyText = """231    ply232    format ascii 1.0233    comment hand-written pyramid234    element vertex 5235    property float x236    property float y237    property float z238    property uchar red239    property uchar green240    property uchar blue241    element face 5242    property list uchar int vertex_indices243    end_header244    0 0 0 255 0 0245    1 0 0 0 255 0246    1 1 0 0 0 255247    0 1 0 255 255 0248    0.5 0.5 1 255 255 255249    4 0 3 2 1250    3 0 1 4251    3 1 2 4252    3 2 3 4253    3 3 0 4254255    """256257    /// The minimal triangle of the glTF tutorial: one buffer embedded as base64 (3 indices, 3 positions).258    static let gltfText = """259    {260      "scene": 0,261      "scenes": [ { "nodes": [ 0 ] } ],262      "nodes": [ { "mesh": 0, "name": "triangle" } ],263      "meshes": [ { "primitives": [ { "attributes": { "POSITION": 1 }, "indices": 0 } ] } ],264      "buffers": [ { "uri": "data:application/octet-stream;base64,AAABAAIAAAAAAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAAAAAACAPwAAAAA=", "byteLength": 44 } ],265      "bufferViews": [266        { "buffer": 0, "byteOffset": 0, "byteLength": 6, "target": 34963 },267        { "buffer": 0, "byteOffset": 8, "byteLength": 36, "target": 34962 }268      ],269      "accessors": [270        { "bufferView": 0, "byteOffset": 0, "componentType": 5123, "count": 3, "type": "SCALAR", "max": [ 2 ], "min": [ 0 ] },271        { "bufferView": 1, "byteOffset": 0, "componentType": 5126, "count": 3, "type": "VEC3", "max": [ 1.0, 1.0, 0.0 ], "min": [ 0.0, 0.0, 0.0 ] }272      ],273      "asset": { "version": "2.0", "generator": "hand-written" }274    }275276    """277278    static let daeText = """279    <?xml version="1.0" encoding="utf-8"?>280    <COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">281      <asset>282        <contributor><authoring_tool>hand-written</authoring_tool></contributor>283        <unit name="centimeter" meter="0.01"/>284        <up_axis>Z_UP</up_axis>285      </asset>286      <library_geometries>287        <geometry id="quad-mesh" name="quad">288          <mesh>289            <source id="quad-positions">290              <float_array id="quad-positions-array" count="12">0 0 0 2 0 0 2 1 0 0 1 0</float_array>291              <technique_common><accessor source="#quad-positions-array" count="4" stride="3">292                <param name="X" type="float"/><param name="Y" type="float"/><param name="Z" type="float"/>293              </accessor></technique_common>294            </source>295            <vertices id="quad-vertices"><input semantic="POSITION" source="#quad-positions"/></vertices>296            <triangles count="2">297              <input semantic="VERTEX" source="#quad-vertices" offset="0"/>298              <p>0 1 2 0 2 3</p>299            </triangles>300          </mesh>301        </geometry>302      </library_geometries>303      <library_visual_scenes>304        <visual_scene id="Scene" name="Scene">305          <node id="quad" name="quad" type="NODE">306            <matrix sid="transform">1 0 0 5 0 1 0 0 0 0 1 0 0 0 0 1</matrix>307            <instance_geometry url="#quad-mesh"/>308          </node>309        </visual_scene>310      </library_visual_scenes>311      <scene><instance_visual_scene url="#Scene"/></scene>312    </COLLADA>313314    """315316    static let usdaText = """317    #usda 1.0318    (319        defaultPrim = "Root"320        metersPerUnit = 0.01321        upAxis = "Z"322    )323324    def Xform "Root"325    {326        def Xform "Child"327        {328            double3 xformOp:translate = (10, 0, 0)329            uniform token[] xformOpOrder = ["xformOp:translate"]330            def Mesh "Quad" (331                prepend apiSchemas = ["MaterialBindingAPI"]332            )333            {334                int[] faceVertexCounts = [4]335                int[] faceVertexIndices = [0, 1, 2, 3]336                point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 2, 0), (0, 2, 0)]337                normal3f[] normals = [(0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1)] (interpolation = "vertex")338                texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 1)] (interpolation = "vertex")339                rel material:binding = </Root/Mat>340            }341        }342        def Material "Mat"343        {344            token outputs:surface.connect = </Root/Mat/S.outputs:surface>345            def Shader "S"346            {347                uniform token info:id = "UsdPreviewSurface"348                color3f inputs:diffuseColor = (0.8, 0.2, 0.1)349                float inputs:metallic = 0.25350                float inputs:roughness = 0.6351                token outputs:surface352            }353        }354    }355356    """357358    static let threeMFModel = """359    <?xml version="1.0" encoding="UTF-8"?>360    <model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">361      <resources>362        <basematerials id="1"><base name="orange" displaycolor="#FF8000"/></basematerials>363        <object id="2" type="model" pid="1" pindex="0">364          <mesh>365            <vertices>366              <vertex x="0" y="0" z="0"/><vertex x="10" y="0" z="0"/><vertex x="0" y="10" z="0"/><vertex x="0" y="0" z="10"/>367            </vertices>368            <triangles>369              <triangle v1="0" v2="2" v3="1"/><triangle v1="0" v2="1" v3="3"/><triangle v1="0" v2="3" v3="2"/><triangle v1="1" v2="2" v3="3"/>370            </triangles>371          </mesh>372        </object>373      </resources>374      <build><item objectid="2" transform="1 0 0 0 1 0 0 0 1 20 0 0"/></build>375    </model>376377    """378379    // MARK: Independent ZIP assembly (stored entries, CRC-32 computed here)380381    static func crc32(_ data: Data) -> UInt32 {382        var table = [UInt32](repeating: 0, count: 256)383        for i in 0..<256 { var c = UInt32(i); for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 }; table[i] = c }384        var crc: UInt32 = 0xFFFF_FFFF385        for byte in data { crc = table[Int((crc ^ UInt32(byte)) & 0xFF)] ^ (crc >> 8) }386        return crc ^ 0xFFFF_FFFF387    }388389    static func storedZip(_ entries: [(String, Data)]) -> Data {390        var out = Data(), central = Data()391        func le16(_ v: Int) -> [UInt8] { [UInt8(v & 0xFF), UInt8((v >> 8) & 0xFF)] }392        func le32(_ v: UInt32) -> [UInt8] { [UInt8(v & 0xFF), UInt8((v >> 8) & 0xFF), UInt8((v >> 16) & 0xFF), UInt8((v >> 24) & 0xFF)] }393        for (name, data) in entries {394            let offset = UInt32(out.count), crc = crc32(data), size = UInt32(data.count), nameBytes = Array(name.utf8)395            out.append(contentsOf: [0x50, 0x4B, 0x03, 0x04] + le16(20) + le16(0) + le16(0) + le16(0) + le16(0x21) + le32(crc) + le32(size) + le32(size) + le16(nameBytes.count) + le16(0))396            out.append(contentsOf: nameBytes); out.append(data)397            central.append(contentsOf: [0x50, 0x4B, 0x01, 0x02] + le16(20) + le16(20) + le16(0) + le16(0) + le16(0) + le16(0x21) + le32(crc) + le32(size) + le32(size)398                           + le16(nameBytes.count) + le16(0) + le16(0) + le16(0) + le16(0) + le32(0) + le32(offset))399            central.append(contentsOf: nameBytes)400        }401        let start = UInt32(out.count)402        out.append(central)403        out.append(contentsOf: [0x50, 0x4B, 0x05, 0x06] + le16(0) + le16(0) + le16(entries.count) + le16(entries.count) + le32(UInt32(central.count)) + le32(start) + le16(0))404        return out405    }406407    static func threeMFPackage() -> Data {408        let types = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/></Types>"409        let rels = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/></Relationships>"410        return storedZip([("[Content_Types].xml", Data(types.utf8)), ("_rels/.rels", Data(rels.utf8)), ("3D/3dmodel.model", Data(threeMFModel.utf8))])411    }412413    // MARK: One fixture file per source format414415    struct Source { let url: URL; let format: FormatID; let triangles: Int; let handWritten: Bool }416417    /// Writes the fixture of `format` into `directory` and returns it with its known triangle count.418    static func source(_ format: FormatID, in directory: URL) throws -> Source {419        func write(_ text: String, _ name: String) throws -> URL {420            let url = directory.appendingPathComponent(name)421            try Data(text.utf8).write(to: url)422            return url423        }424        switch format {425        case .obj:426            _ = try write(mtlText, "cube.mtl")427            try png().write(to: directory.appendingPathComponent("checker.png"))428            return Source(url: try write(objText, "cube.obj"), format: format, triangles: 12, handWritten: true)429        case .stl: return Source(url: try write(stlText, "tetra.stl"), format: format, triangles: 4, handWritten: true)430        case .ply: return Source(url: try write(plyText, "pyramid.ply"), format: format, triangles: 6, handWritten: true)431        case .gltf: return Source(url: try write(gltfText, "triangle.gltf"), format: format, triangles: 1, handWritten: true)432        case .dae: return Source(url: try write(daeText, "quad.dae"), format: format, triangles: 2, handWritten: true)433        case .usda: return Source(url: try write(usdaText, "quad.usda"), format: format, triangles: 2, handWritten: true)434        case .threeMF:435            let url = directory.appendingPathComponent("tetra.3mf")436            try threeMFPackage().write(to: url)437            return Source(url: url, format: format, triangles: 4, handWritten: true)438        case .glb:439            let out = try GLTFWriter.write(richScene(), directory: directory, baseName: "rich", container: .glb)440            return Source(url: out.files[0], format: format, triangles: 26, handWritten: false)441        case .usdz:442            let url = directory.appendingPathComponent("rich.usdz")443            _ = try USDWriter.writeUSDZ(richScene(), to: url, baseName: "rich", unit: .meter, upAxis: .y)444            return Source(url: url, format: format, triangles: 26, handWritten: false)445        case .usdc, .usd:446            // Crate files written by Model I/O from the hand-written text layer.447            let text = try write(usdaText, "quad-source.usda")448            let url = directory.appendingPathComponent("quad.\(format.rawValue)")449            try MDLAsset(url: text).export(to: url)450            try FileManager.default.removeItem(at: text)451            return Source(url: url, format: format, triangles: 2, handWritten: false)452        case .fbx:453            // No FBX encoder or third-party FBX file exists on this Mac: the fixture comes from Assimp's exporter.454            let url = directory.appendingPathComponent("rich.fbx")455            var scene = richScene()456            scene.textures = []457            scene.materials[0].baseColorTexture = nil458            try AssimpBridge.export(scene, formatID: "fbx", to: url, textureNames: [:])459            return Source(url: url, format: format, triangles: 26, handWritten: false)460        default:461            throw ConversionError.unsupportedPath(source: format, destination: format)462        }463    }464}465466/// Collects what an engine reports while converting.467final class Recorder: @unchecked Sendable {468    private let lock = NSLock()469    private var _warnings: [ConversionWarning] = []470    private var _fractions: [Double?] = []471    var warnings: [ConversionWarning] { lock.lock(); defer { lock.unlock() }; return _warnings }472    var fractions: [Double?] { lock.lock(); defer { lock.unlock() }; return _fractions }473    func context(_ directory: URL) -> ConversionContext {474        ConversionContext(workDirectory: directory,475                          progress: { [self] update in lock.lock(); _fractions.append(update.fraction); lock.unlock() },476                          warn: { [self] warning in lock.lock(); _warnings.append(warning); lock.unlock() })477    }478    func codes() -> Set<String> { Set(warnings.map(\.code)) }479}480481extension Model3DEngine {482    /// Converts and returns (output, recorder), writing into a new work directory.483    func run(_ source: URL, from: FormatID, to: FormatID, operation: String? = nil, options: [String: OptionValue] = [:], work: URL) async throws -> (ConversionOutput, Recorder, ConversionRequest) {484        let request = ConversionRequest(source: source, sourceFormat: from, destinationFormat: to, operation: operation, options: ConversionOptions(options))485        let recorder = Recorder()486        let output = try await convert(request, context: recorder.context(work))487        return (output, recorder, request)488    }489}490
Files main
Menu

Theme