Skip to content

Instantly share code, notes, and snippets.

@ishikawash
Created August 7, 2012 16:46
Show Gist options
  • Save ishikawash/3287209 to your computer and use it in GitHub Desktop.
Save ishikawash/3287209 to your computer and use it in GitHub Desktop.
bump mapping example ( calculating tangent vector by vertex shader )
// vertex shader
#version 120
uniform vec3 light_position; // in eye space
varying vec3 light_dir;
varying vec3 eye_dir;
varying vec2 uv;
vec3 calculate_tangent(vec3 n) {
vec3 v = vec3(1.0, 0.0, 0.0);
float d = dot(v, n);
if (abs(d) < 1.0e-3) {
v = vec3(0.0, 1.0, 0.0);
d = dot(v, n);
}
return normalize(v - d * n);
}
void main()
{
vec3 p = (gl_ModelViewMatrix * gl_Vertex).xyz;
// calculate bases to transform position from eye space to tangent space
vec3 n = normalize(gl_NormalMatrix * gl_Normal);
vec3 t = calculate_tangent(n);
vec3 b = cross(n, t);
vec3 l;
l.x = dot(t, light_position);
l.y = dot(b, light_position);
l.z = dot(n, light_position);
light_dir = normalize(l);
vec3 e;
e.x = dot(t, p);
e.y = dot(b, p);
e.z = dot(n, p);
eye_dir = normalize(e);
uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
// fragment shader
#version 120
uniform sampler2D tex0; // normal texture
uniform sampler2D tex1; // image texture
uniform float specular_power;
varying vec3 light_dir;
varying vec3 eye_dir;
varying vec2 uv;
void main()
{
vec3 l = normalize(light_dir);
vec3 e = normalize(-eye_dir);
vec3 n = 2.0 * texture2D(tex0, uv).rgb - 1.0;
float kd = clamp(dot(l, n), 0.0, 1.0);
vec3 h = normalize(l + e);
float ks = pow(clamp(dot(h, n), 0.0, 1.0), specular_power);
vec3 tex_color = texture2D(tex1, uv).rgb;
vec3 color = kd * tex_color + vec3(ks);
gl_FragColor = vec4(color, 1.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment