Working with SCNShadable
I recently had to work with shaders within Apple SceneKit framework and the least I can say is that they don’t make it easy! So here are some explanations I wish I had found earlier.
Disclaimer: if you don’t know much about shaders, it’s probably not gonna be of much value for you :)
SceneKit offers two ways to write your custom shader programs: SCNProgram and SCNShadable.
- SCNProgram: I’ve not played much with it. Basically you write shaders from scratch and you have to do all the work of binding your variables, textures etc. More power more responsibilities.
- SCNShadable: You can write snippets of shader code that are going to be included in larger shaders defined by Apple. The good part is that a lot of the work is done for you. The bad part is that it’s poorly documented, there’s no good example on the web, and you have to hope what you want to do will fit within the options available.
- Apple’s doc: It tells you that there are 4 places your shader snippet can be included: one in the vertex shader and 3 in the fragment shader. It kind of tells you what variables are going to be available at those place, but you should not pay much attention to that.
- Shader code. You won’t find it online, but here’s a trick: write some failing shader code. That will make the debugger print the entire shader code and you can start digging and get a sense of what is happening. So I’d start by making the vertex and fragment shaders fail, and keep all that precious code somewhere. Now you know what’s available to you, and where your snippets will get inserted.
I’ve not found much good things out there, which is always a pain to get things started. So here is mine:
Now all I’ve to do is to write some code in the files loaded above. First Make things fail:
- make the vertex shader fail:
This will log you some errors that should give you a vertex shader that looks like https://gist.github.com/gsabran/d705d1a305908156537d2a9418c67a22#file-scnshadable-vertex-shader-vert-L169-L170
- make the fragment shader fail. Now you know how :) This will give you something like: https://gist.github.com/gsabran/4eebefffba78d692fb8fb25889ebd933
Great, now you have a (tedious) way to get an idea of what is happening!
Write some code
Assuming you know how to deal with shaders, things should get easier from here. For instance you can do:
And in your view:
That will make your colors change with time. Up to you to be more creative!
If this article has helped you, give it some love. And if there’s something you wished had been discussed here, leave a comment!