Friday, 30 August 2013

OpenGL ES 2.0 Scene Lighting iOS

OpenGL ES 2.0 Scene Lighting iOS

I have been looking online and cannot find an example of scene lighting.
Scene lighting meaning there is a light on the wall and all objects which
pass this light get lighted appropriately on the faces which face the
light. Can anyone provide me with an example of such? Or some good reading
on how to do such. I would like to get to the point of using multiple
lights and shadows and possibly lights such as fire which flicker? Is this
possible?
My code below is shading my character but as he rotates (the model view
matrix is rotating), the faces are not changing any lighting.
Vertex Shader precision highp float;
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord;
uniform mat4 u_mvMatrix;
uniform mat4 u_mvpMatrix;
varying lowp vec2 v_texCoord;
varying vec3 v_ecNormal;
varying vec4 v_position;
void main()
{
vec4 mcPosition = a_position;
vec3 mcNormal = a_normal;
vec3 ecNormal = vec3(u_mvMatrix * vec4(mcNormal, 0.0));
v_ecNormal = ecNormal;
v_position = a_position;
v_texCoord = vec2(a_texCoord.x, 1.0 - a_texCoord.y);
gl_Position = u_mvpMatrix * mcPosition;
}
Frag Shader
precision highp float;
uniform sampler2D u_texture;
varying lowp vec2 v_texCoord;
struct DirectionalLight {
vec3 position;
vec3 halfplane;
vec4 ambientColor;
vec4 diffuseColor;
vec4 specularColor;
};
struct Material {
vec4 ambientFactor;
vec4 diffuseFactor;
vec4 specularFactor;
float shininess;
};
uniform DirectionalLight u_directionalLight;
uniform Material u_material;
varying vec3 v_ecNormal;
varying vec4 v_position;
void main()
{
//gl_FragColor = colorVarying * texture2D(texture, texCoordOut);
// normalize
vec3 ecNormal = v_ecNormal / length(v_ecNormal);
vec3 lightPosition = u_directionalLight.position;
vec3 lightDirection;
lightDirection.x = v_position.x - lightPosition.x;
lightDirection.y = v_position.y - lightPosition.y;
lightDirection.z = v_position.z - lightPosition.z;
float ecNormalDotLightDirection = max(0.0, dot(ecNormal,
lightDirection));
float ecNormalDotLightHalfplane = max(0.0, dot(ecNormal,
u_directionalLight.halfplane));
// calc ambient light
vec4 ambientLight = u_directionalLight.ambientColor *
u_material.ambientFactor;
// calc diffuse light
vec4 diffuseLight = ecNormalDotLightDirection *
u_directionalLight.diffuseColor * u_material.diffuseFactor;
// calc specular light
vec4 specularLight = vec4(0.0);
if (ecNormalDotLightHalfplane > 0.0) {
specularLight = pow(ecNormalDotLightHalfplane,
u_material.shininess) * u_directionalLight.specularColor *
u_material.specularFactor;
}
vec4 light = ambientLight + diffuseLight + specularLight;
gl_FragColor = light * texture2D(u_texture, v_texCoord);
}

No comments:

Post a Comment