Simple Directional Lighting

I have combined per-vertex and per-pixel lighting effects in one program, so that we can have good look at what is the difference in output. This lighting is very basic and does not involve shadows and specular lighting.

Output looks like




if observe in above screens, per-pixel shading is much smoother than per-vertex.

Directional Lighting, illuminates all objects equally from a given direction, like an area light of infinite size and infinite distance from the scene; there is shading, but cannot be any distance falloff

For detailed theory, you can refer here and here which offers great theoretical part of lightings. I have nothing new to explain.

In this post I’ll try to show coding difference between per-vertex and per-pixel shading.

First we’ll look at shader code and then remaining rendering part

Vertex Shader



String strVShaderPV = 
"attribute vec4 a_position;" +
"attribute vec3 a_normals;" +
"attribute vec2 a_texCoords;" +
"uniform mat4 u_ModelViewMatrix;" +
"uniform mat3 u_MVNormalsMatrix;" +
"uniform vec3 u_LightDir;" +
"uniform vec3 u_LightColor;" +
"varying vec3 v_colorWeight;" +
"varying vec2 v_texCoords;" +
"void main()" +
"{" +
       "gl_Position = u_ModelViewMatrix * a_position;" +
      "v_texCoords = a_texCoords;" +
	"vec3 normal = normalize(u_MVNormalsMatrix * a_normals);" +
	"vec3 lightNorm = normalize(u_LightDir);" +
	"float lightWeight = max(dot(normal,lightNorm),0.0);" +
	"v_colorWeight = vec3(0.2,0.2,0.2) + (lightWeight * u_LightColor);" +
String strVShaderPP =
 "attribute vec4 a_position;" +
"attribute vec3 a_normals;" +
"attribute vec2 a_texCoords;" +
"uniform mat4 u_ModelViewMatrix;" +
"uniform mat3 u_MVNormalsMatrix;" +
"varying vec3 u_Normals;" +
"varying vec2 v_texCoords;" +
"void main()" +
"{" +
	"v_texCoords = a_texCoords;" +
	"u_Normals = u_MVNormalsMatrix * a_normals;" +
	"gl_Position = u_ModelViewMatrix * a_position;" +

In Per-Vertex approach we are calculating color weight based in the object normals and light normal. but in Per-Pixel approach we are transforming normals and passing to Fragment shader. we need to transform the normals as we are transforming position vertices co-ordinates.

For vertex shader, we are taking vertex normals of Sphere along with vertices as input. As usual passing model-view matrix for calculating object vertex position with respective to current projection.

We also need normals for model view matrix for transforming vertex normals, which we will use for calculating lighting brightness. I’ll explain how to calculate this normals later in below sections.

We need two more variable for lighting parameters such as light direction, light color. I assumed ambience color as (r:0.2, g:0,2, b:0,2) for calculations.

A varying variable, v_colorWeight, for passing the calculated result to fragment shader.

Calculations are very simple, we are here transforming normals and calculating the light color weight for modifying objects’s color.

Fragment Shader



String strFShaderPV = 
"precision mediump float;" +
"varying vec3 v_colorWeight;" +
"varying vec2 v_texCoords;" +
"uniform sampler2D u_texId;" +
"void main()" +
"{" +
	"vec4 texColor = texture2D(u_texId, v_texCoords);" +
	"gl_FragColor = vec4(texColor.rgb * v_colorWeight, texColor.a);" +
String strFShaderPP =
 "precision mediump float;" +
"uniform vec3 u_LightDir;" +
"uniform vec3 u_LightColor;" +
"uniform sampler2D u_texId;" +
"varying vec2 v_texCoords;" +
"varying vec3 u_Normals;" +
"void main()" +
"{" +
	"vec3 LNorm = normalize(u_LightDir);" +
	"vec3 normal = normalize(u_Normals);" +
	"float intensity = max(dot(LNorm, normal),0.0);" +
	"vec4 texColor = texture2D(u_texId, v_texCoords);" +
	"vec3 calcColor = vec3(0.2,0.2,0.2) + u_LightColor * intensity;" +
	"gl_FragColor = vec4(texColor.rgb * calcColor, texColor.a);" +

in Per-Vertex approach we are combining calculated color weight from vertex shader. but in Per-Pixel approach we taking the normals and performing all the calculations in Fragment Shader.

Let’s look at remaining code part.

Two new classes I have created in common package for Mat3 for 3X3 matrix calculation and Mesh class for creating sphere and cube (as of now, will add loading 3DS, OBJ and other file support on the go).


Mesh sphere;
Mat3 normalMat;	
public LightRenderer(ES2SurfaceView view) 
	sphere = new Mesh();
	sphere.Sphere(4, 10);
	curView = view;
	normalMat = new Mat3();
	cubeBuffer = sphere.getVertexBuffer();
	normalsBuffer = sphere.getNormalsBuffer();
	indexBuffer = sphere.getIndecesBuffer();
	texBuffer = sphere.getTextureBuffer();

in constructor of renderer we are creating a sphere and getting vertex, texture coordinates and index buffers for local reference.

public void onDrawFrame(GL10 gl) {
	GLES20.glVertexAttribPointer(iPosition, 3, GLES20.GL_FLOAT, false, 0, cubeBuffer);
	GLES20.glVertexAttribPointer(iTexCoords, 2, GLES20.GL_FLOAT, false, 0,texBuffer);
	GLES20.glVertexAttribPointer(iNormals, 3, GLES20.GL_FLOAT, false, 0, normalsBuffer);
	GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, iTexId);
	GLES20.glUniform1i(iTexLoc, 0);
	GLES20.glUniform3fv(iLightColor, 1, m_fLightColor, 0);
	GLES20.glUniform3fv(iLightDirection, 1, m_fLightDir, 0);
	Matrix.setIdentityM(m_fIdentity, 0);
	Matrix.rotateM(m_fIdentity, 0, -xAngle, 0, 1, 0);
	Matrix.rotateM(m_fIdentity, 0, -yAngle, 1, 0, 0);
	Matrix.multiplyMM(m_fVPMatrix, 0, m_fViewMatrix, 0, m_fIdentity, 0);
	Matrix.multiplyMM(m_fVPMatrix, 0, m_fProjMatrix, 0, m_fVPMatrix, 0);
	GLES20.glUniformMatrix3fv(iVNormMat, 1, false, normalMat.values, 0);
	GLES20.glUniformMatrix4fv(iVPMatrix, 1, false, m_fVPMatrix, 0);
	GLES20.glDrawElements(GLES20.GL_TRIANGLES, sphere.m_nIndeces, GLES20.GL_UNSIGNED_SHORT, indexBuffer);


highlighted code is the only difference part compared to previous posts. which creates a 3X3 normals matrix for Model View projection matrix, which is used in shaders for transforming sphere normals.

Normals are calculated for top- left 3X3 matrix.

SetFrom4X4 function will copy 3X3 matrix from passed 4X4 matrix

Inverse this 3X3 matrix and then transpose will give us normals matrix.

If you like to know how to mathematically calculate, refer here.

A Little bit of Android, Creating Options Menu

There are two ways of loading menus. One from coding and other from resource.

Here I have done in code, as we have only two items for menu

We have to override two methods in activity.

  • public boolean onCreateOptionsMenu(Menu menu)
  • public boolean onOptionsItemSelected(MenuItem item)

onCreateOptionMenu method will be called when menu button is pressed on phone. We will create menu in this function.

public boolean onCreateOptionsMenu(Menu menu) {
     menu.add(Menu.NONE, 0, Menu.NONE, "Per Vertex");
     menu.add(Menu.NONE, 1, Menu.NONE, "Per Pixel");
      return super.onCreateOptionsMenu(menu);


With this we create menu with two items “Per-Pixel” and “Per-Vertex” with ids 0 and 1 respectively.

To handle menu event we have to implement onOptionsItemSelected method.

public boolean onOptionsItemSelected(MenuItem item) {
     if (item.getItemId() == 0)
     } else if (item.getItemId() == 1)
     } else {
      return super.onOptionsItemSelected(item);
     return true;

In this method I’m calling view’s LoadProgram function to switch between Per-Vertex and Per-Pixel shader programs.

That’s it in this post. next come point lights.

leave a comment if you have any thing to say Smile


5 thoughts on “Simple Directional Lighting

  1. Good document indeed. But, I am facing some issues while writing the same for Linux OpenGL ES 2.0 platform, keeping the ‘vertex shader’ & ‘fragment shader’ the same. I am getting GL_INVALID_OPERATION errors. How does the ‘Renderer’ code look like in that case?

    Kindly help.

      • Thank you for your time. Please see the code below.

        const char *vshSource = “\
        uniform mediump mat4 mvp;\
        uniform mediump vec3 myLightDirection;\
        uniform mediump mat3 myModelViewIT;\
        attribute highp vec4 av4position;\
        attribute vec3 av3colour;\
        attribute mediump vec3 myNormal;\
        attribute mediump vec2 myTexCoor;\
        varying mediump float varDot;\
        varying vec3 vv3colour;\
        varying mediump vec2 varCoord;\
        void main(void)\
        vv3colour = av3colour;\
        gl_Position = mvp * av4position;\
        mediump vec3 transNormal = normalize(myModelViewIT * myNormal); \
        varDot = max(dot(transNormal, myLightDirection), 0.0 ); \
        varCoord =; \

        const char *fshSource = “\
        precision lowp float;\
        varying vec3 highp vv3colour;\
        varying mediump float varDot;\
        varying mediump vec2 varCoord;\
        uniform sampler2D sTexture;\
        void main (void)\
        lowp vec4 texColour = texture2D(sTexture, varCoord); \
        gl_FragColor = texColour * varDot;\

        Renderer Code:

        iLocPosition = GL_CHECK(glGetAttribLocation(uiProgram, “av4position”));
        iLocColour = GL_CHECK(glGetAttribLocation(uiProgram, “av3colour”));
        iLocNorm = GL_CHECK(glGetAttribLocation(uiProgram, “myNormal”));
        iLocTex = GL_CHECK(glGetAttribLocation(uiProgram, “myTexCoor”));

        /* Get uniform locations */
        iLocMVP = GL_CHECK(glGetUniformLocation(uiProgram, “mvp”));
        iLocView = GL_CHECK(glGetUniformLocation(uiProgram, “myModelViewIT”));
        glUniformMatrix3fv( iLocView, 1, GL_FALSE, aModelViewIT);

        iLocLight = GL_CHECK(glGetUniformLocation(uiProgram, “myLightDirection”));
        glUniform3fv(iLocLight, 1, pLightDir);

        GL_CHECK(glUniform1i(glGetUniformLocation(uiProgram, “sTexture”), 0));

        /* Enable attributes for position, colour and texture coordinates etc. */

        /* Populate attributes for position, colour and texture coordinates etc.*/
        GL_CHECK(glVertexAttribPointer(iLocPosition, 3, GL_FLOAT, GL_FALSE, 0, pmodel->vertices));
        GL_CHECK(glVertexAttribPointer(iLocColour, 4, GL_FLOAT, GL_FALSE, 0, p_dbVertexColBuff));
        GL_CHECK(glVertexAttribPointer(iLocNorm, 3, GL_FLOAT, GL_FALSE, 0, pmodel->normals));
        GL_CHECK(glVertexAttribPointer(iLocTex, 2, GL_FLOAT, GL_FALSE, 0, pmodel->texcoords));

        while (done)
        matrixRotateX(iXangle, aModelView);
        matrixRotateY(iYangle, aRotate);
        matrixMultiply(aRotate, aModelView, aModelView);
        matrixRotateZ(iZangle, aRotate);
        matrixMultiply(aRotate, aModelView, aModelView);
        aModelView[14] -= 20.5;
        matrixPerspective(45.0, (double)uiWidth/(double)uiHeight, 0.01, 1000.0, aPerspective);
        matrixMultiply(aPerspective, aModelView, aMVP);
        GL_CHECK(glUniformMatrix4fv(iLocMVP, 1, GL_FALSE, aMVP));

        glClearColor (0.0f, 0.0f, 0.0f, 0.5f);
        glClearDepthf (1.0f);

        glDepthFunc (GL_LEQUAL);

        glDrawElements(GL_TRIANGLES, pmodel->numtriangles * 3, GL_UNSIGNED_SHORT, triObjIx);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s