How To Apply .MTL File on .OBJ 3d Model via SceneKit & Model I/O

拥有回忆 提交于 2019-11-30 13:55:56

问题


I am trying to apply an .mtl file texture on .obj 3d model via SceneKit & Model I/0.

My code below works fine when I try to apply .jpg of a texture on it:

       let url = NSBundle.mainBundle().URLForResource("chair", withExtension: "obj")            
       let asset = MDLAsset(URL: NSURL(string:url)!)
        guard let object = asset.objectAtIndex(0) as? MDLMesh else {
            //fatalError("Failed to get mesh from asset.")
            return
        }

        if shouldApplyTexture == true {
            var textureFileName = "chair.mtl"

            // Create a material from the various textures
            let scatteringFunction = MDLScatteringFunction()
            let material = MDLMaterial(name: "baseMaterial", scatteringFunction: scatteringFunction)

            material.setTextureProperties(textures: [
                                            .BaseColor:textureFileName])

            // Apply the texture to every submesh of the asset
            for  submesh in object.submeshes!  {
                if let submesh = submesh as? MDLSubmesh {
                    submesh.material = material
                }
            }

        }

        // Wrap the ModelIO object in a SceneKit object
        let node = SCNNode(MDLObject: object)

        if (scene.rootNode.childNodes.count > 0){
            scene.rootNode.enumerateChildNodesUsingBlock { (node, stop) -> Void in
                node.removeFromParentNode()
            }
        }
        scene.rootNode.addChildNode(node)

I am using the following MDMaterial extension for setTextureProperties:

extension MDLMaterial {
func setTextureProperties([MDLMaterialSemantic:String]) -> Void {

    for (key,value) in textures {
        var finalURL = NSBundle.mainBundle().URLForResource(value, withExtension: "")
       guard let url = finalURL else {
           // fatalError("Failed to find URL for resource \(value).")
            return
        }

        let property = MDLMaterialProperty(name:fileName!, semantic: key, URL: url)
        self.setProperty(property)
    }
  }
}

How should I load an .mtl file and apply it on my model to have texture on it? What properties of SCNMaterial should I declare for getting texture data from a .mtl file?


回答1:


It might be a bit late, but I'm facing the same issue and the way in which I could load the .mtl information was to create the object through and scene, for example, I'm loading this model

let scene = SCNScene(named: "rose.obj")

Make sure to have the .mtl and the jpg with the textures in your bundle.



来源:https://stackoverflow.com/questions/41057710/how-to-apply-mtl-file-on-obj-3d-model-via-scenekit-model-i-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!