iosswift3dscenekitshading

Smooth Shading in SceneKit


I'm currently working on an iPadOS app that uses SceneKit to render some 3D models, nothing too fancy but I hit a big of a snag when it comes to shading these models...

Basically what I do is just set up a SceneKit scene (using pretty much all the default settings, I don't even have a camera) and instantiate the 3D objects from some .obj files I have, like so.

let url =  <URL of my .obj file>
let asset = MDLAsset(url: url)
let object = asset.object(at: 0)
let node = SCNNode(mdlObject: object)
let texture = UIImage(data: try Data(contentsOf: <URL of the texture>))
let material = SCNMaterial()
material.diffuse.contents = texture
node.geometry!.materials = [material]
self.sceneView.scene!.rootNode.addChildNode(node)

The textures are loaded manually because unfortunately that's how the client set up the files for me to use. The code works fine and I can see the mesh and its texture, however it also looks like this

enter image description here

As you can see the shading is not smooth at all... and I have no idea how to fix it.

The client has been bothering me to implement Phong shading, and according to Apple's Documentation this is how you do it.

material.lightingModel = .phong

Unfortunately that's still what it looks like with Phong enabled. I'm an absolute beginner when it comes to 3D rendering so this might be laughably easy but I swear I cannot figure out how to get a smoother shading on this model.

I have tried looking left and right and the only thing that has had any kind of noticeable result was to use subdivisionLevel to increase the actual faces in the geometry but this does not scale well as the actual app needs to load a ton of these meshes and it runs out of memory fast even when subdivision set to just 1

Surely there must be a way to smooth those shadows without improving the actual geometry?

Thanks in advance!


Solution

  • Shading requires having correct normals for your geometry. Have you tried using Model IO to generate them?

    https://developer.apple.com/documentation/modelio/mdlmesh/1391284-addnormals