Implementacija shadera u GLSL-u
Primjer 1
Vertex shader:
varying vec3 LightDir;
varying vec3 EyeDir;
varying vec3 Normal;
uniform vec3 LightPosition;
uniform float Scale;
void main(void)
{
vec4 pos = gl_ModelViewMatrix * gl_Vertex;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
vec3 eyeDir = vec3(pos);
gl_TexCoord[0] = gl_MultiTexCoord0;
vec3 n = normalize(gl_NormalMatrix * gl_Normal);
vec3 t = normalize(cross(vec3(1.141, 2.78, 3.14), n));
vec3 b = cross(n, t);
vec3 v;
v.x = dot(LightPosition, t);
v.y = dot(LightPosition, b);
v.z = dot(LightPosition, n);
LightDir = normalize(v);
v.x = dot(eyeDir, t);
v.y = dot(eyeDir, b);
v.z = dot(eyeDir, n);
EyeDir = normalize(v);
}
Fragment shader:
varying vec3 LightDir;
varying vec3 EyeDir;
varying vec3 Normal;
const vec3 color = vec3(0.9, 0.8, 0.60);
const float Density = 16.0;
const float Size = 0.15;
const float SpecularFactor = 0.5;
void main (void)
{
vec3 litColor;
vec2 c = Density * vec2(gl_TexCoord[0]);
vec2 p = fract(c) - vec2(0.5);
float d;
d = p.x * p.x + p.y * p.y;
if (d >= Size)
p = vec2(0.0);
vec3 normDelta = vec3(-p.x, -p.y, 1.0);
litColor = color * max(0.0, dot(normDelta, LightDir));
float t = 2.0 * dot(LightDir, normDelta);
vec3 reflectDir = t * normDelta;
reflectDir = LightDir - reflectDir;
float spec = max(dot(EyeDir, reflectDir), 0.0);
spec = spec * spec;
spec = spec * spec;
spec *= SpecularFactor;
litColor = min(litColor + spec, vec3(1.0));
gl_FragColor = vec4(litColor, 1.0);
}
Primjer2
Vertex shader:
attribute vec3 tangent;
attribute vec3 binormal;
varying vec3 eyeVec;
void main()
{
gl_TexCoord[0] = gl_MultiTexCoord0;
mat3 TBN_Matrix;// = mat3(tangent, binormal, gl_Normal);
TBN_Matrix[0] = gl_NormalMatrix * tangent;
TBN_Matrix[1] = gl_NormalMatrix * binormal;
TBN_Matrix[2] = gl_NormalMatrix * gl_Normal;
vec4 Vertex_ModelView = gl_ModelViewMatrix * gl_Vertex;
eyeVec = vec3(-Vertex_ModelView) * TBN_Matrix ;
// Vertex transformation
gl_Position = ftransform();
}
Fragment shader:
uniform sampler2D basetex;
uniform sampler2D bumptex;
varying vec3 eyeVec;
void main()
{
vec2 texUV, srcUV = gl_TexCoord[0].xy;
float height = texture2D(bumptex, srcUV).r;
float v = height * 0.04 - 0.02;
vec3 eye = normalize(eyeVec);
texUV = srcUV + (eye.xy * v);
vec3 rgb = texture2D(basetex, texUV).rgb;
// output final color
gl_FragColor = vec4(vec3(rgb), 1.0);
// gl_FragColor = vec4(vec3(rgb)*height, 1.0);
}
Ljubo Barać | Računalna grafika