0

Loading a .dae file as a scene element

This code works, loading the file as the scene:

let scene = SCNScene(named: "art.scnassets/base-wall-tile_sample.dae")!

This code, loading the file as SCNGeometry, doesn't:

let url = Bundle.main.url(forResource: "art.scnassets/base-wall-tile_sample", withExtension: "dae")
let source = SCNSceneSource(url: url! )
let geo = source!.entryWithIdentifier("Geo", withClass: SCNGeometry.self)!

url and source are ok, but it crashes trying to produce geo. Bad instruction.

This code, like several examples offered on the web, was in Swift 2 (load a collada (dae) file into SCNNode (Swift - SceneKit). I had to juggle it to Swift 3, and something seems to have been lost in translation. Can someone tell me how to do this stuff right?

Joymaker
  • 813
  • 1
  • 9
  • 23

2 Answers2

1

A .dae file is always loaded as a SCNScene. You need to name the node containing the geometry you want to add. Than you can load the scene, filter it for the node with the given name and add it to your scene.

func addNode(named nodeName, fromSceneNamed: sceneName, to scene: SCNScene) {
    if let loadedScene = SCNScene(named: sceneName),
       let node = loadedScene.rootNode.childNode(withName: nodeName, recursivly: true) {
        scene.rootNode.addChildNode(node)
    }
}
jlsiewert
  • 3,494
  • 18
  • 41
  • Works nicely, but I'm surprised at the answer. Loading such a file as a "scene" seems awfully heavy for just getting a node. – Joymaker Jul 21 '17 at 15:30
  • 1
    Thats just how SceneKit interpets those files. For optimal performance you should place them in an `.scnassets` folder and Xcode will optimise them for you on compile time. Check [`SCNSceneSource`](https://developer.apple.com/documentation/scenekit/scnscenesource) for more information and options. – jlsiewert Jul 21 '17 at 16:44
  • Thanks, orangenkopf. That looks very promising. Now, I've been having trouble understanding these "URL" things which are not always real URLs. How would I initialize the URL to access a file that is in my .scnassets folder as they recommend? And if there's some basic place I should be reading to understand these URLs, please point me to it. – Joymaker Jul 24 '17 at 18:09
  • For URLs (and every question regrading the SDK) I recommend the [Apple documentation](https://developer.apple.com/documentation/foundation/url). For a Scene just use `init(named: "myScene", inDirectory: "myAssets.scnassets")` – jlsiewert Jul 24 '17 at 18:16
0
guard let shipScene = SCNScene(named: "ship.dae") else { return }
let shipNode = SCNNode()
let shipSceneChildNodes = shipScene.rootNode.childNodes
for childNode in shipSceneChildNodes {
    shipNode.addChildNode(childNode)
}
node.addChildNode(shipNode)
Aayushi
  • 787
  • 10
  • 14