CPU端代码设置:
// This function does any needed initialization on the rendering
// context.
void SetupRC(void)
{
// Background
glClearColor(0.025f, 0.25f, 0.25f, 1.0f );
glEnable(GL_DEPTH_TEST);
shaderManager.InitializeStockShaders();
viewFrame.MoveForward(4.0f);
// Make the torus
gltMakeTorus(torusBatch, .80f, 0.25f, 52, 26);
toonShader = gltLoadShaderPairWithAttributes("ToonShader.vp", "ToonShader.fp", 2, GLT_ATTRIBUTE_VERTEX, "vVertex",
GLT_ATTRIBUTE_NORMAL, "vNormal");
locLight = glGetUniformLocation(toonShader, "vLightPosition");
locMVP = glGetUniformLocation(toonShader, "mvpMatrix");
locMV = glGetUniformLocation(toonShader, "mvMatrix");
locNM = glGetUniformLocation(toonShader, "normalMatrix");
locColorTable = glGetUniformLocation(toonShader, "colorTable");
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_1D, texture);
GLubyte textureData[4][3] = { 32, 0, 0,
64, 0, 0,
128, 0, 0,
255, 0, 0};
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB, 4, 0, GL_RGB, GL_UNSIGNED_BYTE, textureData);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
}
顶点着色器:
// Cell lighting Shader
// Vertex Shader
// Richard S. Wright Jr.
// OpenGL SuperBible
#version 130
// Incoming per vertex... position and normal
in vec4 vVertex;
in vec3 vNormal;
smooth out float textureCoordinate;
uniform vec3 vLightPosition;
uniform mat4 mvpMatrix;
uniform mat4 mvMatrix;
uniform mat3 normalMatrix;
void main(void)
{
// Get surface normal in eye coordinates
vec3 vEyeNormal = normalMatrix * vNormal;
// Get vertex position in eye coordinates
vec4 vPosition4 = mvMatrix * vVertex;
vec3 vPosition3 = vPosition4.xyz / vPosition4.w;
// Get vector to light source
vec3 vLightDir = normalize(vLightPosition - vPosition3);
// Dot product gives us diffuse intensity
textureCoordinate = max(0.0, dot(vEyeNormal, vLightDir)); // cos(theta), 值越大说明夹角越小, 对应的颜色越亮
// Don't forget to transform the geometry!
gl_Position = mvpMatrix * vVertex;
}
片断着色器:
// Cell lighting Shader
// Fragment Shader
// Richard S. Wright Jr.
// OpenGL SuperBible
#version 130
uniform sampler1D colorTable;
out vec4 vFragColor;
smooth in float textureCoordinate;
void main(void)
{
vFragColor = texture(colorTable, textureCoordinate);
}
截图: