Qt 3D的研究(6):Toon Shader
在上次的实验中,我们实现了Gooch Shader,并给出了通过调色板进行个性化的Gooch Shader设置。Toon Shader又称Cell Shader,是以离散的色彩来表示光照的强弱。很多动画片的渲染方式都是使用Toon Shader的。下面这样图就能够使用Toon Shader实现。
蒋彩阳原创文章,首发地址:http://blog.csdn.net/gamesdev/article/details/44084021。欢迎同行前来探讨。

下面是Toon Shader的代码:
// Toon.vert
#version 100
// Qt 3D默许提供的参数
attribute vec3 vertexPosition;
attribute vec3 vertexNormal;
uniform mat4 modelView;
uniform mat4 modelNormalMatrix;
uniform mat4 mvp;
// 自己提供的参数
uniform vec3 lightPosition;
varying vec3 reflectVec;
varying vec3 viewVec;
varying float NdotL;
void main( void )
{
vec3 ecPos = ( modelView * vec4( vertexPosition, 1.0 ) ).xyz;
vec3 normal = normalize( modelNormalMatrix * vec4( vertexNormal, 1.0 ) ).xyz;
vec3 lightVec = normalize( lightPosition - ecPos );
reflectVec = normalize( reflect( -lightVec, normal ) );
viewVec = normalize( -ecPos );
NdotL = ( dot( lightVec, normal ) + 1.0 ) * 0.5;
gl_Position = mvp * vec4( vertexPosition, 1.0 );
}
// Toon.frag
#version 100
// 自己提供的参数
varying vec3 reflectVec;
varying vec3 viewVec;
varying float NdotL;
uniform sampler2D texPalette;
float grayTexture( vec4 color )
{
return dot( color.xyz, vec3( 0.299, 0.587, 0.114 ) );
}
void main( void )
{
gl_FragColor = texture2D( texPalette, vec2( NdotL, 1.0 ) );
}
我们使用的离散纹理以下所示:

程序运行结果以下所示:
