Repository Public License
1// ORIX Convert — Packages/EngineModel3D/Tests/EngineModel3DTests/OutputTests.swift2// Description: Texture bundling (GLB, USDZ), multi-file outputs, material mapping, data-loss warnings, encodings,3// validation of tampered outputs, and safe handling of file references found in models.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import Testing7import SceneKit8import Metal9import simd10import ConvertCore11@testable import EngineModel3D1213func workDirectories(_ label: String = "out") throws -> (root: URL, input: URL, work: URL) {14 let root = Fixtures.directory(label)15 let input = root.appendingPathComponent("in", isDirectory: true), work = root.appendingPathComponent("work", isDirectory: true)16 try FileManager.default.createDirectory(at: input, withIntermediateDirectories: true)17 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)18 return (root, input, work)19}2021func fileNames(in directory: URL) -> [String] {22 ((try? FileManager.default.contentsOfDirectory(atPath: directory.path)) ?? []).sorted()23}2425@Suite("Textures, materials and multi-file outputs")26struct OutputTests {27 let engine = Model3DEngine()2829 @Test func texturesAreEmbeddedInGLB() async throws {30 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }31 let source = try Fixtures.source(.obj, in: input)32 let (output, recorder, request) = try await engine.run(source.url, from: .obj, to: .glb, work: work)33 #expect(output.files.count == 1 && output.files[0].pathExtension == "glb")34 #expect(output.facts["textures"] == "1" && output.facts["materials"] == "1")35 let document = try GLTFDocument.load(output.files[0], limits: ModelLimits())36 let images = try #require(document.json["images"] as? [[String: Any]])37 #expect(images.count == 1 && images[0]["mimeType"] as? String == "image/png" && images[0]["uri"] == nil)38 let views = try #require(document.json["bufferViews"] as? [[String: Any]])39 let view = views[try #require(images[0]["bufferView"] as? Int)]40 let buffer = try #require(document.buffers[0])41 let offset = try #require(view["byteOffset"] as? Int), length = try #require(view["byteLength"] as? Int)42 #expect(buffer.subdata(in: (buffer.startIndex + offset)..<(buffer.startIndex + offset + length)) == Fixtures.png())43 // The material refers to the texture, and UVs are written with glTF's top-left origin.44 let materials = try #require(document.json["materials"] as? [[String: Any]])45 let pbr = try #require(materials[0]["pbrMetallicRoughness"] as? [String: Any])46 #expect(pbr["baseColorTexture"] != nil)47 #expect(recorder.codes().contains("materials-approximated"))48 for check in try await engine.validate(output, request: request, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }49 }5051 @Test func texturesAreEmbeddedInUSDZ() async throws {52 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }53 let source = try Fixtures.source(.obj, in: input)54 let (output, _, request) = try await engine.run(source.url, from: .obj, to: .usdz, options: ["unit.source": .string("cm"), "axis.source": .string("y")], work: work)55 let data = try Data(contentsOf: output.files[0])56 let zip = try ZipReader(data)57 #expect(zip.entries.map(\.name) == ["cube.usda", "textures/checker.png"])58 #expect(try zip.contents(of: zip.entries[1], maxSize: 1 << 20) == Fixtures.png())59 #expect(zip.entries.allSatisfy { $0.method == 0 })60 let layer = String(decoding: try zip.contents(of: zip.entries[0], maxSize: 1 << 20), as: UTF8.self)61 #expect(layer.contains("metersPerUnit = 0.01") && layer.contains("@textures/checker.png@") && layer.contains("UsdPreviewSurface"))62 // Model I/O (independent of the writer) finds the texture inside the package.63 let reread = try ModelIOBridge.load(output.files[0], format: .usdz, limits: ModelLimits())64 #expect(reread.textures.count == 1 && reread.textures[0].origin == .embedded && reread.textures[0].data == Fixtures.png())65 #expect(reread.metadata.unit == .centimeter)66 for check in try await engine.validate(output, request: request, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }67 }6869 @Test func multiFileOutputsAreFoldersWithNothingOrphaned() async throws {70 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }71 let source = try Fixtures.source(.glb, in: input)7273 let (gltf, _, gltfRequest) = try await engine.run(source.url, from: .glb, to: .gltf, work: work)74 var isDirectory: ObjCBool = false75 #expect(FileManager.default.fileExists(atPath: gltf.files[0].path, isDirectory: &isDirectory) && isDirectory.boolValue)76 #expect(fileNames(in: gltf.files[0]) == ["checker.png", "rich.bin", "rich.gltf"])77 let document = try GLTFDocument.load(gltf.files[0].appendingPathComponent("rich.gltf"), limits: ModelLimits())78 #expect((document.json["buffers"] as? [[String: Any]])?.first?["uri"] as? String == "rich.bin")79 #expect((document.json["images"] as? [[String: Any]])?.first?["uri"] as? String == "checker.png")80 #expect(document.check().problems.isEmpty)81 for check in OutputValidator.validate(gltf, destinationFormat: .gltf, workDirectory: work) { #expect(check.passed, "\(check.detail)") }82 for check in try await engine.validate(gltf, request: gltfRequest, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }8384 let (obj, _, objRequest) = try await engine.run(source.url, from: .glb, to: .obj, work: root.appendingPathComponent("w2"))85 #expect(fileNames(in: obj.files[0]) == ["checker.png", "rich.mtl", "rich.obj"])86 let mtl = try String(contentsOf: obj.files[0].appendingPathComponent("rich.mtl"), encoding: .utf8)87 #expect(mtl.contains("map_Kd checker.png") && mtl.contains("Pr 0.75") && mtl.contains("Pm 0.25"))88 #expect(try String(contentsOf: obj.files[0].appendingPathComponent("rich.obj"), encoding: .utf8).contains("mtllib rich.mtl"))89 #expect(try Data(contentsOf: obj.files[0].appendingPathComponent("checker.png")) == Fixtures.png())90 for check in try await engine.validate(obj, request: objRequest, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }9192 for (format, names) in [(FormatID.dae, ["checker.png", "rich.dae"]), (.usda, ["checker.png", "rich.usda"]), (.usdc, ["checker.png", "rich.usdc"]), (.usd, ["checker.png", "rich.usd"])] {93 let (out, _, _) = try await engine.run(source.url, from: .glb, to: format, work: root.appendingPathComponent("w-\(format.rawValue)"))94 #expect(fileNames(in: out.files[0]) == names, "\(format)")95 }96 }9798 @Test func singleFileWhenNothingAccompaniesTheModel() async throws {99 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }100 let source = try Fixtures.source(.glb, in: input)101 // Self-contained .gltf (base64 buffer and image).102 let (embedded, _, request) = try await engine.run(source.url, from: .glb, to: .gltf, options: ["gltf.embed": .bool(true)], work: work)103 #expect(embedded.files.count == 1 && embedded.files[0].lastPathComponent == "rich.gltf")104 #expect(fileNames(in: work) == ["rich.gltf"])105 for check in try await engine.validate(embedded, request: request, source: nil) { #expect(check.passed, "\(check.name): \(check.detail)") }106 // OBJ without materials is one file; so is USDA without textures.107 let w2 = root.appendingPathComponent("w2")108 let (obj, recorder, _) = try await engine.run(source.url, from: .glb, to: .obj, options: ["materials.write": .bool(false)], work: w2)109 #expect(obj.files[0].lastPathComponent == "rich.obj" && fileNames(in: w2) == ["rich.obj"])110 #expect(recorder.codes().contains("materials-dropped"))111 let w3 = root.appendingPathComponent("w3")112 let (usda, recorder3, _) = try await engine.run(source.url, from: .glb, to: .usda, options: ["textures.write": .bool(false)], work: w3)113 #expect(fileNames(in: w3) == ["rich.usda"] && usda.facts["textures"] == "0")114 #expect(recorder3.codes().contains("textures-dropped"))115 }116117 @Test func dataLossIsReported() async throws {118 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }119 let source = try Fixtures.source(.glb, in: input)120 let (stl, recorder, _) = try await engine.run(source.url, from: .glb, to: .stl, work: work)121 #expect(recorder.codes().isSuperset(of: ["materials-dropped", "textures-dropped", "uv-dropped", "hierarchy-flattened", "not-watertight"]))122 #expect(recorder.warnings.contains { $0.code == "materials-dropped" && $0.severity == .dataLoss })123 #expect(stl.facts["topology.watertight"] == "no")124 // Vertex colours: kept by PLY and glTF, dropped (with a warning) by OBJ.125 let colored = input.appendingPathComponent("colored.glb")126 _ = try GLTFWriter.write(Fixtures.vertexColorScene(), directory: input, baseName: "colored", container: .glb)127 let (ply, plyRecorder, _) = try await engine.run(colored, from: .glb, to: .ply, work: work)128 #expect(!plyRecorder.codes().contains("vertex-colors-dropped"))129 let back = try PLYCodec.read(ply.files[0], limits: ModelLimits())130 let colors = try #require(back.meshes[0].colors)131 for (p, c) in zip(back.meshes[0].positions, colors) { #expect(c.x == p.x && c.y == p.y && c.z == p.z && c.w == 1) }132 let (_, objRecorder, _) = try await engine.run(colored, from: .glb, to: .obj, work: work)133 #expect(objRecorder.codes().contains("vertex-colors-dropped"))134 // A closed cube is reported watertight for printing formats.135 let (threeMF, cubeRecorder, _) = try await engine.run(colored, from: .glb, to: .threeMF, work: work)136 #expect(threeMF.facts["topology.watertight"] == "yes" && threeMF.facts["topology.boundary-edges"] == "0")137 #expect(!cubeRecorder.codes().contains("not-watertight"))138 }139140 @Test func materialsSurviveBetweenPBRFormats() async throws {141 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }142 let glb = input.appendingPathComponent("pair.glb")143 _ = try GLTFWriter.write(Fixtures.multiMaterialScene(), directory: input, baseName: "pair", container: .glb)144 for destination in [FormatID.usda, .usdz, .glb, .gltf] {145 let (output, _, request) = try await engine.run(glb, from: .glb, to: destination, operation: destination == .glb ? Model3DCatalog.reprocessOperation : nil, work: work.appendingPathComponent(destination.rawValue))146 let main = try #require(Model3DEngine.mainFile(of: output, format: destination))147 let backend: ImportBackend = [.usda, .usdz].contains(destination) ? .modelIO : .assimp148 let scene = try Importers.loadInProcess(main, format: destination, backend: backend, limits: ModelLimits())149 let used = scene.usedMaterialIndices().map { scene.materials[$0] }150 #expect(used.count == 2, "\(destination)")151 let red = try #require(used.first { $0.name == "red" }), blue = try #require(used.first { $0.name == "blue" })152 #expect(simd_distance(red.baseColor, SIMD4(1, 0, 0, 1)) < 1e-5 && red.metallic == 0)153 #expect(simd_distance(blue.baseColor, SIMD4(0, 0, 1, 1)) < 1e-5 && blue.metallic == 1)154 #expect(abs(red.roughness - 0.5) < 1e-6)155 for check in try await engine.validate(output, request: request, source: nil) { #expect(check.passed, "\(destination) \(check.name): \(check.detail)") }156 }157 // 3MF keeps only the colour (sRGB display colour).158 let (threeMF, recorder, _) = try await engine.run(glb, from: .glb, to: .threeMF, work: work)159 #expect(recorder.codes().contains("materials-reduced"))160 let scene = try ThreeMF.read(threeMF.files[0], limits: ModelLimits())161 #expect(scene.materials.map(\.name) == ["red", "blue"])162 #expect(simd_distance(scene.materials[0].baseColor, SIMD4(1, 0, 0, 1)) < 1e-3)163 #expect(scene.metadata.unit == .meter && scene.metadata.upAxis == .z)164 }165166 @Test func encodingOptionForSTLAndPLY() async throws {167 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }168 let source = try Fixtures.source(.obj, in: input)169 for (format, key) in [(FormatID.stl, "binary"), (.stl, "ascii"), (.ply, "binary"), (.ply, "ascii")] {170 let (output, _, request) = try await engine.run(source.url, from: .obj, to: format, options: ["encoding": .string(key)], work: work.appendingPathComponent("\(format.rawValue)-\(key)"))171 let data = try Data(contentsOf: output.files[0])172 let head = String(decoding: data.prefix(64), as: UTF8.self)173 if format == .stl {174 #expect(STLCodec.isBinary(data) == (key == "binary"))175 if key == "binary" { #expect(data.count == 84 + 12 * 50) } else { #expect(head.hasPrefix("solid ")) }176 } else {177 #expect(head.contains(key == "binary" ? "format binary_little_endian 1.0" : "format ascii 1.0"))178 }179 let scene = try Importers.loadInProcess(output.files[0], format: format, backend: .native, limits: ModelLimits())180 #expect(scene.triangleCount == 12)181 for check in try await engine.validate(output, request: request, source: nil) { #expect(check.passed, "\(format) \(key) \(check.name): \(check.detail)") }182 }183 }184185 @Test func hierarchyIsKeptOrFlattened() async throws {186 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }187 let glb = input.appendingPathComponent("tree.glb")188 _ = try GLTFWriter.write(Fixtures.hierarchyScene(), directory: input, baseName: "tree", container: .glb)189 let expected = Geometry.worldPositions(of: Fixtures.hierarchyScene())190 // Kept: the child node and its transform are still there, and the cube mesh is stored once.191 let (kept, _, _) = try await engine.run(glb, from: .glb, to: .glb, operation: Model3DCatalog.reprocessOperation, work: work)192 let document = try GLTFDocument.load(kept.files[0], limits: ModelLimits())193 let nodes = try #require(document.json["nodes"] as? [[String: Any]])194 #expect(nodes.contains { ($0["name"] as? String) == "child" && $0["matrix"] != nil })195 #expect((document.json["meshes"] as? [Any])?.count == 1)196 #expect(containsAll(document.check().geometry.positions, expected, tolerance: 1e-5))197 // Flattened on request.198 let (flat, recorder, _) = try await engine.run(glb, from: .glb, to: .glb, operation: Model3DCatalog.reprocessOperation, options: ["hierarchy.flatten": .bool(true)], work: root.appendingPathComponent("w2"))199 let flatDocument = try GLTFDocument.load(flat.files[0], limits: ModelLimits())200 #expect((flatDocument.json["nodes"] as? [[String: Any]])?.allSatisfy { $0["matrix"] == nil } == true)201 #expect(recorder.codes().contains("hierarchy-flattened"))202 #expect(containsAll(flatDocument.check().geometry.positions, expected, tolerance: 1e-5))203 // STL has no hierarchy: world coordinates, with a warning.204 let (stl, stlRecorder, _) = try await engine.run(glb, from: .glb, to: .stl, work: root.appendingPathComponent("w3"))205 #expect(stlRecorder.codes().contains("hierarchy-flattened"))206 let scene = try STLCodec.read(stl.files[0], limits: ModelLimits())207 #expect(scene.triangleCount == 24)208 var welded = scene.meshes[0]; Welding.weld(&welded)209 #expect(containsAll(welded.positions, expected, tolerance: 1e-5))210 }211212 @Test func validationDetectsATamperedOutput() async throws {213 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }214 let source = try Fixtures.source(.obj, in: input)215 // A different model in place of the output: geometry checks fail.216 let (ply, _, plyRequest) = try await engine.run(source.url, from: .obj, to: .ply, work: work)217 try PLYCodec.write(Scene3D(mesh: Fixtures.cube(size: 1.5)), to: ply.files[0], binary: true)218 let plyChecks = try await engine.validate(ply, request: plyRequest, source: nil)219 #expect(plyChecks.contains { $0.name == "model.positions" && !$0.passed })220 #expect(plyChecks.contains { $0.name == "model.bounding-box" && !$0.passed })221 // One triangle removed.222 let (stl, _, stlRequest) = try await engine.run(source.url, from: .obj, to: .stl, work: work)223 var bytes = try Data(contentsOf: stl.files[0])224 bytes.removeLast(50)225 bytes.replaceSubrange(80..<84, with: [11, 0, 0, 0])226 try bytes.write(to: stl.files[0])227 #expect(try await engine.validate(stl, request: stlRequest, source: nil).contains { $0.name == "model.triangles" && !$0.passed })228 // A GLB whose accessor reads past its buffer view: the structural check fails.229 let (glb, _, glbRequest) = try await engine.run(source.url, from: .obj, to: .glb, work: work)230 var glbBytes = try Data(contentsOf: glb.files[0])231 let jsonLength = Int(glbBytes.subdata(in: 12..<16).withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) })232 var json = String(decoding: glbBytes.subdata(in: 20..<(20 + jsonLength)), as: UTF8.self)233 let range = try #require(json.range(of: "\"count\":36"))234 json.replaceSubrange(range, with: "\"count\":96")235 #expect(json.utf8.count == jsonLength)236 glbBytes.replaceSubrange(20..<(20 + jsonLength), with: Data(json.utf8))237 try glbBytes.write(to: glb.files[0])238 var glbChecks: [ValidationCheck]239 do { glbChecks = try await engine.validate(glb, request: glbRequest, source: nil) } catch { glbChecks = [ValidationCheck("gltf.structure", passed: false, "\(error)")] }240 #expect(glbChecks.contains { $0.name == "gltf.structure" && !$0.passed })241 }242}243244@Suite("File references inside models are confined to the model's folder")245struct PathSafetyTests {246 let engine = Model3DEngine()247 static let secret = Data("TOP-SECRET-MARKER-0123456789".utf8)248249 @Test func referenceRules() {250 func rejected(_ s: String, encoded: Bool = false) -> SafePath.Rejection? { if case .failure(let r) = SafePath.components(of: s, percentEncoded: encoded) { return r }; return nil }251 #expect(rejected("../secret.png") == .escapes)252 #expect(rejected("textures/../../secret.png") == .escapes)253 #expect(rejected("..\\..\\secret.png") == .escapes)254 #expect(rejected("%2e%2e/secret.png", encoded: true) == .escapes)255 #expect(rejected("/etc/hosts") == .absolute)256 #expect(rejected("~/Library/x.png") == .absolute)257 #expect(rejected("C:\\Users\\me\\tex.png") == .absolute)258 #expect(rejected("http://example.com/a.png") == .remote)259 #expect(rejected("https://example.com/a.png") == .remote)260 #expect(rejected("file:///etc/hosts") == .remote)261 #expect(rejected("ftp://host/a.png") == .remote)262 #expect(rejected("") == .empty)263 #expect(rejected("textures/wood.png") == nil)264 #expect(rejected("./a b/wood%20grain.png", encoded: true) == nil)265 #expect(SafePath.sanitizedFileName("../../evil.png", fallback: "t") == "_.._evil.png")266 #expect(SafePath.sanitizedFileName("...", fallback: "t") == "t")267 }268269 /// Lays out `root/secret.*` (outside) and `root/model/` (the model's folder).270 func layout() throws -> (root: URL, model: URL, work: URL) {271 let root = Fixtures.directory("escape")272 let model = root.appendingPathComponent("model", isDirectory: true), work = root.appendingPathComponent("work", isDirectory: true)273 try FileManager.default.createDirectory(at: model, withIntermediateDirectories: true)274 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)275 // A real PNG with the marker appended, so that a leak would be visible in any output.276 try (Fixtures.png() + Self.secret).write(to: root.appendingPathComponent("secret.png"))277 try Data("newmtl leaked\nKd 1 0 1\n".utf8).write(to: root.appendingPathComponent("outside.mtl"))278 return (root, model, work)279 }280281 func outputContainsSecret(_ work: URL) -> Bool {282 guard let enumerator = FileManager.default.enumerator(at: work, includingPropertiesForKeys: nil) else { return false }283 for case let url as URL in enumerator { if let data = try? Data(contentsOf: url), data.range(of: Self.secret) != nil { return true } }284 return false285 }286287 @Test func mtlTextureEscapesAreRefused() async throws {288 let (root, model, work) = try layout(); defer { try? FileManager.default.removeItem(at: root) }289 try Data(Fixtures.objText.utf8).write(to: model.appendingPathComponent("cube.obj"))290 for reference in ["../secret.png", root.appendingPathComponent("secret.png").path, "http://127.0.0.1:9/secret.png", "..\\secret.png", "sub/../../secret.png"] {291 try Data(Fixtures.mtlText.replacingOccurrences(of: "checker.png", with: reference).utf8).write(to: model.appendingPathComponent("cube.mtl"))292 for destination in [FormatID.glb, .usdz, .gltf, .obj] {293 let w = work.appendingPathComponent(UUID().uuidString)294 let (output, recorder, _) = try await engine.run(model.appendingPathComponent("cube.obj"), from: .obj, to: destination, operation: destination == .obj ? Model3DCatalog.reprocessOperation : nil, work: w)295 #expect(output.facts["textures"] == "0", "\(reference) → \(destination)")296 #expect(recorder.codes().contains("texture-missing"), "\(reference) → \(destination)")297 #expect(!outputContainsSecret(w), "\(reference) → \(destination)")298 }299 let summary = try await engine.summary(of: model.appendingPathComponent("cube.obj"), format: .obj)300 #expect(summary.texturesMissing == 1 && summary.texturesExternal == 0)301 }302 }303304 @Test func mtllibOutsideTheFolderIsNotOpened() async throws {305 let (root, model, work) = try layout(); defer { try? FileManager.default.removeItem(at: root) }306 try Data(Fixtures.objText.replacingOccurrences(of: "mtllib cube.mtl", with: "mtllib ../outside.mtl").replacingOccurrences(of: "usemtl painted", with: "usemtl leaked").utf8)307 .write(to: model.appendingPathComponent("cube.obj"))308 let (output, recorder, _) = try await engine.run(model.appendingPathComponent("cube.obj"), from: .obj, to: .gltf, work: work)309 #expect(recorder.codes().contains("reference-blocked"))310 let main = try #require(Model3DEngine.mainFile(of: output, format: .gltf))311 let text = try String(contentsOf: main, encoding: .utf8)312 // The colour of the outside library (magenta) never reaches the output.313 #expect(!text.contains("[1,0,1,1]"))314 #expect(output.facts["triangles"] == "12")315 }316317 @Test func gltfURIEscapesAreRefused() async throws {318 let (root, model, work) = try layout(); defer { try? FileManager.default.removeItem(at: root) }319 // The quad of the textured scene, written as .gltf + .bin + image, then the image URI is redirected.320 _ = try GLTFWriter.write(Fixtures.texturedQuadScene(), directory: model, baseName: "quad", container: .gltfSeparate)321 let gltf = model.appendingPathComponent("quad.gltf")322 let original = try String(contentsOf: gltf, encoding: .utf8)323 for reference in ["../secret.png", "%2e%2e/secret.png", "https://example.invalid/secret.png", "file://" + root.appendingPathComponent("secret.png").path] {324 try Data(original.replacingOccurrences(of: "\"uri\":\"checker.png\"", with: "\"uri\":\"\(reference)\"").utf8).write(to: gltf)325 let w = work.appendingPathComponent(UUID().uuidString)326 let (output, recorder, _) = try await engine.run(gltf, from: .gltf, to: .glb, work: w)327 #expect(output.facts["textures"] == "0", "\(reference)")328 #expect(recorder.codes().contains("texture-missing") || recorder.codes().contains("reference-blocked"), "\(reference)")329 #expect(!outputContainsSecret(w), "\(reference)")330 }331 // A buffer outside the folder: the geometry cannot be read, and nothing is read from outside.332 try FileManager.default.copyItem(at: model.appendingPathComponent("quad.bin"), to: root.appendingPathComponent("outside.bin"))333 try Data(original.replacingOccurrences(of: "\"uri\":\"quad.bin\"", with: "\"uri\":\"../outside.bin\"").utf8).write(to: gltf)334 await #expect(throws: ConversionError.self) { _ = try await engine.run(gltf, from: .gltf, to: .glb, work: work) }335 let document = try GLTFDocument.load(gltf, limits: ModelLimits())336 #expect(document.buffers[0] == nil && document.bufferProblems.count == 1)337 }338339 @Test func symbolicLinksOutOfTheFolderAreRefused() async throws {340 let (root, model, work) = try layout(); defer { try? FileManager.default.removeItem(at: root) }341 try Data(Fixtures.objText.utf8).write(to: model.appendingPathComponent("cube.obj"))342 try Data(Fixtures.mtlText.utf8).write(to: model.appendingPathComponent("cube.mtl"))343 try FileManager.default.createSymbolicLink(at: model.appendingPathComponent("checker.png"), withDestinationURL: root.appendingPathComponent("secret.png"))344 let (output, recorder, _) = try await engine.run(model.appendingPathComponent("cube.obj"), from: .obj, to: .glb, work: work)345 #expect(output.facts["textures"] == "0")346 #expect(recorder.warnings.contains { $0.code == "texture-missing" && $0.message.contains("outside the model's folder") })347 #expect(!outputContainsSecret(work))348 }349350 @Test func usdLayersReferringOutsideAreRefused() async throws {351 let (root, model, work) = try layout(); defer { try? FileManager.default.removeItem(at: root) }352 try Data(Fixtures.usdaText.utf8).write(to: root.appendingPathComponent("outside.usda"))353 let layer = model.appendingPathComponent("ref.usda")354 for reference in ["../outside.usda", root.appendingPathComponent("outside.usda").path, "https://example.invalid/a.usd"] {355 try Data("#usda 1.0\n(\n defaultPrim = \"Root\"\n)\n\ndef Xform \"Root\" (\n references = @\(reference)@</Root>\n)\n{\n}\n".utf8).write(to: layer)356 await #expect(throws: ConversionError.self) { _ = try await engine.run(layer, from: .usda, to: .glb, work: work) }357 #expect(USDLayerInfo.read(layer, limits: ModelLimits()).escapingAssetPaths() == [reference])358 }359 // A reference inside the folder is fine.360 try Data(Fixtures.usdaText.utf8).write(to: model.appendingPathComponent("inside.usda"))361 try Data("#usda 1.0\n(\n defaultPrim = \"Root\"\n metersPerUnit = 1\n upAxis = \"Y\"\n)\n\ndef Xform \"Root\" (\n references = @./inside.usda@</Root>\n)\n{\n}\n".utf8).write(to: layer)362 let (output, _, _) = try await engine.run(layer, from: .usda, to: .glb, work: work)363 #expect(output.facts["triangles"] == "2")364 }365}366367@Suite("Attributes and texture orientation")368struct AttributeTests {369 let engine = Model3DEngine()370371 /// A quad whose four corners have distinct UVs, normals tilted per vertex and distinct colours.372 static func markedQuad() -> Scene3D {373 var scene = Fixtures.texturedQuadScene()374 scene.meshes[0].uvSets = [[SIMD2(0.1, 0.2), SIMD2(0.9, 0.25), SIMD2(0.85, 0.7), SIMD2(0.15, 0.8)]]375 scene.meshes[0].normals = [SIMD3(0, 0, 1), simd_normalize(SIMD3(0.2, 0, 1)), simd_normalize(SIMD3(0, 0.2, 1)), simd_normalize(SIMD3(-0.2, -0.2, 1))]376 scene.meshes[0].colors = [SIMD4(1, 0, 0, 1), SIMD4(0, 1, 0, 1), SIMD4(0, 0, 1, 1), SIMD4(1, 1, 0, 1)]377 return scene378 }379380 @Test("UVs, normals and colours keep their values and orientation", arguments: ["glb", "gltf", "obj", "ply", "usda", "usdz", "usdc", "dae"])381 func attributesRoundTrip(destination raw: String) async throws {382 let destination = FormatID(raw)383 let (root, input, work) = try workDirectories(); defer { try? FileManager.default.removeItem(at: root) }384 let quad = Self.markedQuad()385 _ = try GLTFWriter.write(quad, directory: input, baseName: "marked", container: .glb)386 let (output, _, _) = try await engine.run(input.appendingPathComponent("marked.glb"), from: .glb, to: destination, operation: destination == .glb ? Model3DCatalog.reprocessOperation : nil,387 options: ["unit.target": .string("m")], work: work)388 let main = try #require(Model3DEngine.mainFile(of: output, format: destination))389 // Read back with the engine's importer for that format (Assimp, Model I/O or the own PLY reader).390 let scene = try Importers.loadInProcess(main, format: destination, backend: try #require(Importers.backend(for: destination)), limits: ModelLimits())391 let mesh = try #require(scene.meshes.first { $0.triangleCount == 2 })392 let source = quad.meshes[0]393 #expect(!mesh.uvSets.isEmpty)394 for i in 0..<mesh.vertexCount {395 // Match vertices by position (readers reorder and duplicate them).396 let k = try #require(source.positions.firstIndex { simd_distance($0, mesh.positions[i]) < 1e-5 })397 if let uv = mesh.uvSets.first { #expect(simd_distance(uv[i], source.uvSets[0][k]) < 1e-5, "\(raw) uv \(uv[i]) vs \(source.uvSets[0][k])") }398 if let normals = mesh.normals { #expect(simd_distance(normals[i], source.normals![k]) < 1e-4, "\(raw) normal") } else { Issue.record("\(raw): normals were lost") }399 if destination != .obj {400 if let colors = mesh.colors { #expect(simd_reduce_max(simd_abs(SIMD3(colors[i].x, colors[i].y, colors[i].z) - SIMD3(source.colors![k].x, source.colors![k].y, source.colors![k].z))) < 0.01, "\(raw) colour") }401 else if destination != .usdc { Issue.record("\(raw): vertex colours were lost") }402 }403 }404 }405406 @Test func previewShowsTheTextureTheRightWayUp() async throws {407 // Texture: red grows to the right, green grows downwards in the image. With UV (0,0) at the bottom-left408 // of the image, the bottom of the quad must be greener than its top, and its right side redder.409 let scene = Fixtures.texturedQuadScene()410 let scn = Model3DPreviewLoader.makeSCNScene(from: scene)411 scn.rootNode.enumerateHierarchy { node, _ in node.geometry?.firstMaterial?.lightingModel = .constant }412 let camera = SCNNode()413 camera.camera = SCNCamera()414 camera.camera?.usesOrthographicProjection = true415 camera.camera?.orthographicScale = 0.5416 camera.position = SCNVector3(1, 0.5, 5)417 scn.rootNode.addChildNode(camera)418 guard let device = MTLCreateSystemDefaultDevice() else { return } // no GPU in this environment: nothing to check419 let renderer = SCNRenderer(device: device, options: nil)420 renderer.scene = scn421 renderer.pointOfView = camera422 let image = renderer.snapshot(atTime: 0, with: CGSize(width: 200, height: 100), antialiasingMode: .none)423 guard let cg = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { Issue.record("no snapshot"); return }424 var pixels = [UInt8](repeating: 0, count: cg.width * cg.height * 4)425 let context = try #require(CGContext(data: &pixels, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: cg.width * 4,426 space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))427 context.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height))428 func pixel(_ fx: Double, _ fyFromTop: Double) -> (r: Int, g: Int) {429 let x = Int(fx * Double(cg.width - 1)), y = Int(fyFromTop * Double(cg.height - 1))430 return (Int(pixels[(y * cg.width + x) * 4]), Int(pixels[(y * cg.width + x) * 4 + 1]))431 }432 let topLeft = pixel(0.1, 0.1), bottomLeft = pixel(0.1, 0.9), topRight = pixel(0.9, 0.1)433 print("PREVIEW-RENDER-CHECKED top-left \(topLeft) bottom-left \(bottomLeft) top-right \(topRight)")434 #expect(bottomLeft.g > topLeft.g + 60, "green top \(topLeft.g) bottom \(bottomLeft.g)")435 #expect(topRight.r > topLeft.r + 60, "red left \(topLeft.r) right \(topRight.r)")436 }437}438