Repository Public License
1// ORIX Convert — Packages/EngineModel3D/Sources/EngineModel3DBench/main.swift2// Description: Command-line driver of the 3D engine for development and benchmarks: inspect a file, convert one,3// or run the recorded benchmarks (generated 1 M and 5 M triangle meshes, simplification).4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import ConvertCore7import EngineModel3D89func peakRSSMegabytes() -> Double {10 var usage = rusage()11 getrusage(RUSAGE_SELF, &usage)12 return Double(usage.ru_maxrss) / 1_048_57613}1415func childrenPeakRSSMegabytes() -> Double {16 var usage = rusage()17 getrusage(RUSAGE_CHILDREN, &usage)18 return Double(usage.ru_maxrss) / 1_048_57619}2021func format(of url: URL) -> FormatID {22 FileTypeDetector.detect(url).format ?? FormatCatalog.formats(forExtension: url.pathExtension).first?.id ?? FormatID(url.pathExtension)23}2425func parseOptions(_ arguments: ArraySlice<String>) -> ConversionOptions {26 var options = ConversionOptions()27 for argument in arguments {28 let parts = argument.split(separator: "=", maxSplits: 1).map(String.init)29 guard parts.count == 2 else { continue }30 if parts[1] == "true" || parts[1] == "false" { options[parts[0]] = .bool(parts[1] == "true") }31 else if let i = Int(parts[1]) { options[parts[0]] = .int(i) }32 else if let d = Double(parts[1]) { options[parts[0]] = .double(d) }33 else { options[parts[0]] = .string(parts[1]) }34 }35 return options36}3738let arguments = CommandLine.arguments39let isolation: ImportIsolation = ProcessInfo.processInfo.environment["ORIX_M3D_INPROCESS"] == "1" ? .inProcess : .automatic40let engine = Model3DEngine(isolation: isolation)4142func convert(_ input: URL, to destination: FormatID, options: ConversionOptions, work: URL, validate: Bool) async throws -> (ConversionOutput, Double, [ValidationCheck]) {43 let source = format(of: input)44 let request = ConversionRequest(source: input, sourceFormat: source, destinationFormat: destination, operation: source == destination ? "model.reprocess" : nil, options: options)45 let context = ConversionContext(workDirectory: work, warn: { w in FileHandle.standardError.write(Data(" [\(w.severity.rawValue)] \(w.code): \(w.message)\n".utf8)) })46 let start = Date()47 let output = try await engine.convert(request, context: context)48 let seconds = Date().timeIntervalSince(start)49 let checks = validate ? try await engine.validate(output, request: request, source: nil) : []50 return (output, seconds, checks)51}5253do {54 switch arguments.count > 1 ? arguments[1] : "" {55 case "inspect":56 let url = URL(fileURLWithPath: arguments[2])57 let inspection = try await engine.inspect(url, format: format(of: url))58 for field in inspection.fields { print("\(field.group) / \(field.key): \(field.value)") }59 for note in inspection.notes { print("note: \(note)") }60 case "convert":61 let input = URL(fileURLWithPath: arguments[2])62 let destination = FormatID(arguments[3])63 let work = URL(fileURLWithPath: arguments[4], isDirectory: true)64 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)65 let (output, seconds, checks) = try await convert(input, to: destination, options: parseOptions(arguments.dropFirst(5)), work: work, validate: true)66 print("output: \(output.files.map(\.path).joined(separator: ", "))")67 for (key, value) in output.facts.sorted(by: { $0.key < $1.key }) { print(" \(key) = \(value)") }68 for check in checks { print(" \(check.passed ? "PASS" : "FAIL") \(check.name): \(check.detail)") }69 print(String(format: "seconds %.3f, peak RSS %.0f MB, helper peak RSS %.0f MB", seconds, peakRSSMegabytes(), childrenPeakRSSMegabytes()))70 case "generate":71 // generate <triangles> <output.{obj,stl,glb,ply}>: a displaced sphere with about that many triangles.72 let triangles = Int(arguments[2]) ?? 1_000_00073 let url = URL(fileURLWithPath: arguments[3])74 try BenchmarkMeshes.write(triangles: triangles, to: url)75 print("generated \(url.lastPathComponent)")76 case "simplify":77 // simplify <input> <target triangles>78 let input = URL(fileURLWithPath: arguments[2])79 let target = Int(arguments[3]) ?? 100_00080 let report = try await BenchmarkMeshes.simplify(input, format: format(of: input), target: target)81 print(report)82 print(String(format: "peak RSS %.0f MB", peakRSSMegabytes()))83 case "paths":84 // Markdown table of every declared path, with the limitations factored into numbered notes.85 var notes: [String] = []86 func note(_ text: String) -> Int { if let i = notes.firstIndex(of: text) { return i + 1 }; notes.append(text); return notes.count }87 print("| Source | Destination | Operation | Status | Fidelity | Preserves | Decoder → writer → validator | Limitations (notes) | Test |")88 print("|---|---|---|---|---|---|---|---|---|")89 for path in engine.paths {90 let backend = path.limitations.first.map { $0.replacingOccurrences(of: "Decoded by ", with: "").replacingOccurrences(of: ", written by ", with: " → ")91 .replacingOccurrences(of: ", verified by re-reading with ", with: " → ").replacingOccurrences(of: ".", with: "") } ?? ""92 let numbers = path.limitations.dropFirst().map { "\(note($0))" }.joined(separator: ", ")93 print("| \(path.source.rawValue) | \(path.destination.rawValue) | \(path.operation ?? "—") | \(path.status.rawValue) | \(path.fidelity.rawValue) | \(path.preserves.map(\.rawValue).sorted().joined(separator: ", ")) | \(backend) | \(numbers) | `declaredPath(id:)` with `\(path.id)` |")94 }95 print("")96 for (i, text) in notes.enumerated() { print("\(i + 1). \(text)") }97 default:98 print("usage: EngineModel3DBench inspect <file> | convert <file> <format> <work-dir> [key=value…] | generate <triangles> <file> | simplify <file> <target>")99 }100} catch {101 FileHandle.standardError.write(Data("error: \((error as? LocalizedError)?.errorDescription ?? "\(error)")\n".utf8))102 exit(1)103}104