Search code examples
swiftaugmented-realityscenekitrealitykitusdz

How to programmatically export 3D mesh as USDZ using ModelIO?


Is it possible to programmatically export 3D mesh as .usdz file format using ModelIO and MetalKit frameworks?

Here's a code:

import ARKit
import RealityKit
import MetalKit
import ModelIO

let asset = MDLAsset(bufferAllocator: allocator)
asset.add(mesh)

let filePath = FileManager.default.urls(for: .documentDirectory, 
                                         in: .userDomainMask).first!
    
let usdz: URL = filePath.appendingPathComponent("model.usdz")

do {
    try asset.export(to: usdz)               
    let controller = UIActivityViewController(activityItems: [usdz], 
                                      applicationActivities: nil)
    controller.popoverPresentationController?.sourceView = sender
    self.present(controller, animated: true, completion: nil)
} catch let error {
    fatalError(error.localizedDescription)
}

When I press a Save button I get an error.


Solution

  • 08th January 2023

    At the moment iOS developers still can export only .usd, .usda and .usdc files; you can check this using canExportFileExtension(_:) type method:

    let usd = MDLAsset.canExportFileExtension("usd")
    let usda = MDLAsset.canExportFileExtension("usda")
    let usdc = MDLAsset.canExportFileExtension("usdc")
    let usdz = MDLAsset.canExportFileExtension("usdz")
        
    print(usd, usda, usdc, usdz)
    

    It prints:

    true true true false
    

    However, you can easily export SceneKit's scenes as .usdz files using instance method called: write(to:options:delegate:progressHandler:).

    let path = FileManager.default.urls(for: .documentDirectory,
                                         in: .userDomainMask)[0]
                                             .appendingPathComponent("file.usdz")
        
    sceneKitScene.write(to: path, 
                   options: nil, 
                  delegate: nil, 
           progressHandler: nil)