I am using the following code to reconstruct usdz (apple 3d) object to obj files.
// Extension to transform SCNGeometry with a matrix
extension SCNGeometry {
func applyingTransform(_ transform: SCNMatrix4) -> SCNGeometry {
let vertexSources = sources(for: .vertex)
guard let vertexSource = vertexSources.first else { return self }
var vertices = [SCNVector3](repeating: SCNVector3Zero, count: vertexSource.vectorCount)
vertexSource.data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
for i in 0..<vertexSource.vectorCount {
let ptr = buffer.baseAddress!.advanced(by: i * vertexSource.dataStride)
vertices[i] = ptr.load(as: SCNVector3.self)
vertices[i] = SCNVector3FromGLKVector3(GLKMatrix4MultiplyVector3(SCNMatrix4ToGLKMatrix4(transform), SCNVector3ToGLKVector3(vertices[i])))
}
}
let newGeometrySource = SCNGeometrySource(vertices: vertices)
return SCNGeometry(sources: [newGeometrySource], elements: self.elements)
}
}
// Function to recursively export nodes, applying transformations
private func exportNode(_ node: SCNNode, to asset: MDLAsset, applying worldTransform: SCNMatrix4 = SCNMatrix4Identity) {
let localTransform = node.transform
let combinedTransform = SCNMatrix4Mult(localTransform, worldTransform)
if let geometry = node.geometry {
let transformedGeometry = geometry.applyingTransform(combinedTransform)
if let mdlMesh = MDLMesh(scnGeometry: transformedGeometry) {
asset.add(mdlMesh)
}
}
for childNode in node.childNodes {
exportNode(childNode, to: asset, applying: combinedTransform)
}
}
However in the results I see that all the objects are centered at origin. I think this is an issue with the matrices and it is losing all the translations when recreating vertices in obj. Any insights will be helpful on how I can tackle this. Also, not sure if this is an issue with the matrices as this is my guess. Messed up 3D objects after recreation