Home > AI > Uncategorized

Swift – ModelIO

初步: 导入obj格式模型

import UIKit
import ModelIO
import SceneKit

class ModelIOViewController: UIViewController {

    var gameView: SCNView!
    
    override func loadView() {
       self.view = SCNView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        
        //load model
        guard let url = Bundle.main.url(forResource: "Corridor_Left", withExtension: "obj") else {
            fatalError("Failed to load model")
        }
        let model = MDLAsset(url: url)
        let corridor = model[0] as! MDLMesh
        
        //set material
        let scatteringFunc = MDLScatteringFunction()
        let material = MDLMaterial(name: "corridor_m", scatteringFunction: scatteringFunc)
        material.setTextures(textures: [
            MDLMaterialSemantic.bump: "Corridor_Normal.jpg",
            MDLMaterialSemantic.emission: "Corridor_Illumination.jpg",
            MDLMaterialSemantic.baseColor: "Corridor_Diffuse.jpg",
            MDLMaterialSemantic.specular: "Corridor_Specular.jpg"
            ])
        
        for mesh in corridor.submeshes! {
            if let m = mesh as? MDLSubmesh { //convert type
                m.material = material
            }
        }
        
        //put in scene
        let corridorNode = SCNNode(mdlObject: corridor)
        corridorNode.scale = SCNVector3(0.1, 0.1, 0.1)
        let scene = SCNScene()
        scene.rootNode.addChildNode(corridorNode)

        //4 camera
        let cameraNode = SCNNode()
        cameraNode.camera = SCNCamera()
        scene.rootNode.addChildNode(cameraNode)
        cameraNode.position = SCNVector3(0, 0, 25)
    
        gameView = self.view as! SCNView
        gameView.scene = scene
        gameView.pointOfView = cameraNode
        
        /* you can have a cup of coffee here */
        //others
        gameView.allowsCameraControl = true
        gameView.showsStatistics = true

        //ambient light
        let ambientNode = SCNNode()
        ambientNode.light = SCNLight()
        ambientNode.light?.type = .ambient
        scene.rootNode.addChildNode(ambientNode)
        

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    //helper funcs
    override var prefersStatusBarHidden: Bool {
        return true
    }

}

extension MDLMaterial {
    func setTextures(textures: [MDLMaterialSemantic: String]){
        for (key, value) in textures {
            guard let url = Bundle.main.url(forResource: value, withExtension: nil) else {
                fatalError("Failed to find texture \(value)")
            }
            self.setProperty(MDLMaterialProperty(name: value, semantic: key, url: url))
        }
    }
}

用到的模型文件需要的话,可以给我发邮件。

Related posts:

Leave a Reply