Skip to content
Tags

76a – making your shader portable

June 5, 2013

If you want to share your code – and your shader(s) – you have to take your shaders out of the Shader Lab and put them directly into your code. (Actually, I think most people build their shaders in the normal code editor to start with, and only use the Shader Lab for debugging). Anyway, this is how you do it.

Including the shader code

This is how you include a shader in with your code. I suggest you put it in a separate tab because it is so different. Effectively, you are defining the shader as a table with two elements, the vertex and fragment shaders – include both, even if you only change one of them.

I have coloured the actual code blue (ie the parts you can change) so you can see more clearly how everything is laid out.

myShader = {
vertexShader = [[
//
// A basic vertex shader
//

//This is the current model * view * projection matrix
// Codea sets it automatically
uniform mat4 modelViewProjection;

//This is the current mesh vertex position, color and tex coord
// Set automatically
attribute vec4 position;
attribute vec4 color;
attribute vec2 texCoord;

//This is an output variable that will be passed to the fragment shader
varying lowp vec4 vColor;
varying highp vec2 vTexCoord;

void main()
{
//Pass the mesh color to the fragment shader
vColor = color;
vTexCoord = texCoord;

//Multiply the vertex position by our combined transform
gl_Position = modelViewProjection * position;
}

]],
fragmentShader = [[
//
// A basic fragment shader
//

//Default precision qualifier
precision highp float;

//This represents the current texture on the mesh
uniform lowp sampler2D texture;

//The interpolated vertex color for this fragment
varying lowp vec4 vColor;

//The interpolated texture coordinate for this fragment
varying highp vec2 vTexCoord;

void main()
{
//Sample the texture at the interpolated coordinate
lowp vec4 col = texture2D( texture, vTexCoord ) * vColor;
//Set the output color to the texture color
gl_FragColor = col;
}

]]}

Telling Codea which shader you want for a mesh

And this is how you tell Codea to apply that shader to a mesh.

    myMesh.shader = shader(myShader.vertexShader,
                                     myShader.fragmentShader)

You will this approach in use from the next post onwards.

From → Shaders

Leave a Comment

Leave a comment