Search code examples
opengl-esglslopengl-es-2.0fragment-shadervertex-shader

Vertex and Fragment shaders for lighting effect in OpenGL ES20


I want to add a very simply lighting effect in my models via shaders. I found out there a vertex and a fragment shaders that make the work on OpenGL:

static const char* vertSource = {
    "uniform vec3 lightPosition;\n"
    "varying vec3 normal, eyeVec, lightDir;\n"
    "void main()\n"
    "{\n"
    "    vec4 vertexInEye = gl_ModelViewMatrix * gl_Vertex;\n"
    "    eyeVec = -vertexInEye.xyz;\n"
    "    lightDir = vec3(lightPosition - vertexInEye.xyz);\n"
    "    normal = gl_NormalMatrix * gl_Normal;\n"
    "    gl_Position = ftransform();\n"
    "}\n"
};

static const char* fragSource = {
    "uniform vec4 lightDiffuse;\n"
    "uniform vec4 lightSpecular;\n"
    "uniform float shininess;\n"
    "varying vec3 normal, eyeVec, lightDir;\n"
    "void main (void)\n"
    "{\n"
    "  vec4 finalColor = gl_FrontLightModelProduct.sceneColor;\n"
    "  vec3 N = normalize(normal);\n"
    "  vec3 L = normalize(lightDir);\n"
    "  float lambert = dot(N,L);\n"
    "  if (lambert > 0.0)\n"
    "  {\n"
    "    finalColor += lightDiffuse * lambert;\n"
    "    vec3 E = normalize(eyeVec);\n"
    "    vec3 R = reflect(-L, N);\n"
    "    float specular = pow(max(dot(R, E), 0.0), shininess);\n"
    "    finalColor += lightSpecular * specular;\n"
    "  }\n"
    "  gl_FragColor = finalColor;\n"
    "}\n"
};

The problem is that I am working in OpenGL ES2, because I am developing an Android app. And it seems that the in-built variable gl_FrontLightModelProduct is not available for GLES20, because I am having compilation fails in this line.

My question therefore is: How I can modify the above shaders to make them work in a OpenGL ES20 context?


Solution

  • gl_FrontLightModelProduct.sceneColor gives the Ambient colour of the scene which can be 0 if you want the area which is not affected by light to be fully black. You can replace that with a vec4(0.0, 0.0, 0.0, 1.0);

    You should also remove these variables and send them as uniforms.

    1. gl_ModelViewMatrix (send as uniform)
    2. gl_Vertex (read this from attributes)
    3. gl_NormalMatrix (send as uniform)
    4. gl_Normal (read this from attributes)

    Or instead of fighting in converting OpenGL shader, you can search for Simple OpenGL ES 2.0 shaders