Loading .mtl file from documents directory with .obj in scenekit for texture

Viewed 1152

i'm trying to load downloaded 3d objects from documents directory. i've successfully loaded 3d object file and .mtl file in scenekit but images that are named inside .mtl file are not renderd to apply texture on 3d model which are also placed inside documents directory with same name as in .mtl file.

below is the code used

func loadObjToScene() {
    let scene = SCNScene()

    let cameraNode = SCNNode()
    cameraNode.camera = SCNCamera()
    scene.rootNode.addChildNode(cameraNode)

    cameraNode.position = SCNVector3.init(0, 0, 15)

    // create and add a light to the scene
    let lightNode = SCNNode()
    lightNode.light = SCNLight()
    lightNode.light?.type = .omni
    lightNode.position = SCNVector3.init(0, 0, 10)
    scene.rootNode.addChildNode(lightNode)

    // create and add an ambient light to the scene
    let ambientLightNode = SCNNode()
    ambientLightNode.light = SCNLight()
    ambientLightNode.light?.type = .ambient
    ambientLightNode.light?.color = UIColor.darkGray
    scene.rootNode.addChildNode(ambientLightNode)


    scnView.scene = scene
    scnView.allowsCameraControl = true
    scnView.showsStatistics = false
    scnView.backgroundColor = UIColor.white


    let mdlAsset = MDLAsset(url: URL(fileURLWithPath: "\(MZUtility.baseFilePath)/\(/obj?.objectUrl?.fileName)"))


    let scatteringFunction = MDLScatteringFunction.init()
    let material = MDLMaterial.init(name: "baseMaterial", scatteringFunction: scatteringFunction)


    let textureFileName = "Ford_Explorer_(Mk5f)_(U502)_Police_Interceptor_Utility_HQinterior_2016.mtl"

    material.setTextureProperties(textures: [MDLMaterialSemantic.baseColor : textureFileName])

    for mesh in ((mdlAsset.object(at: 0) as? MDLMesh)?.submeshes as? [MDLSubmesh]) ?? [] {
      print("Mesh Name: \(mesh.name)")
      mesh.material = material
    }






    mdlAsset.loadTextures()




    let objectNode = SCNNode(mdlObject: mdlAsset.object(at: 0))
    objectNode.scale = SCNVector3(2, 2, 2)
    objectNode.position = SCNVector3(0, 0, 0)

    scene.rootNode.addChildNode(objectNode)
  }

}


extension MDLMaterial {
  func setTextureProperties(textures: [MDLMaterialSemantic:String]) -> Void {
    for (key,value) in textures {
      let url = URL(fileURLWithPath: "\(MZUtility.baseFilePath)/\(value)")
      let property = MDLMaterialProperty(name:value, semantic: key, url: url)
      self.setProperty(property)
    }
  }
}
0 Answers
Related