WebGL Simple Lighting Tutorial
Easiest Method
Introduction
This tutorial explains how to prepare very simple WebGL Lighting. In this example shaders apply lighting based on the X and Y vertex coordinates. This lesson covers the vertex and fragment shaders for the WebGL Simple Lighting on a Sphere example.
The free WebGL Earth Model & Texture
,
outlines array organization for each model including the sphere in this example.
The Vertex Shader
The vertex shader calculates values of light and dark
based on X and Y vertex coordinates.
The varyings v_light
and v_dark
then pass those calculations to the fragment shader.
The following listing includes the entire
vertex shader.
attribute vec4 a_position; attribute vec2 a_tex_coord0; varying vec2 v_tex_coord0; varying float v_light; varying float v_dark; uniform mat4 um4_matrix; uniform mat4 um4_pmatrix; void main(void) { // Multiply the current vertex // by the transformation and // perspective projection // matrices. vec4 v4_position = um4_pmatrix * um4_matrix * a_position; // Output the modified // vertex position gl_Position = v4_position; // Calculate lighting based // on both X and Y coordinates. v_light = 1.0 - (v4_position.y + 1.0) * 0.2; v_light *= 1.0 - (v4_position.x + 1.0) * 0.2; // Calculate dark based // on just the X coordinate. v_dark = (v4_position.x + 1.0) * 0.3; // Map the current vertex position in gl_Position // to the current texel. v_tex_coord0 = a_tex_coord0; }
The Fragment Shader
The fragment shader simply subtracts
from each color channel, the
dark value received through varying
v_dark
.
The shader uses the light value
passed through varying v_light
as the alpha value.
For more detailed shader lighting information
please see the
precision mediump float; uniform sampler2D u_sampler0; varying vec2 v_tex_coord0; varying float v_light; varying float v_dark; void main(void) { vec4 color0 = texture2D( u_sampler0, v_tex_coord0 ); // Reduce red, green, // and blue channels, // by the dark value. // Apply the light // as alpha. gl_FragColor = vec4( color0.r-v_dark, color0.g-v_dark, color0.b-v_dark, v_light ); }
WebGL Sphere Preparation
The sphere was created in 3ds Max, exported as a Collada DAE file,
then translated with JavaScript for use with WebGL.
The JavaScript converter slows down with large numbers of vertices.
Therefore the sphere, in this example, is modeled with just sixteen segments.
The Glowing Earth
example loads a smoother sphere converted with the free WebGL Translator
.
Summary
This tutorial explained how to prepare very simple WebGL Lighting. In this example shaders apply lighting based on X and Y vertex coordinates. This lesson covered the vertex and fragment shaders for the WebGL Simple Lighting on a Sphere example.