版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/artisans/article/details/74614732
完整的程序
https://github.com/WaldenPonder/opengl-test/tree/master/t005
顶点着色器
#version 330 core
layout (location = 0) in vec3 aPosition;
layout (location = 1) in vec2 aCoor;
layout (location = 1) in vec3 aNormal;
uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;
out vec2 vTexCoor;
out vec3 vNormal;
out vec3 vPos;
void main()
{
gl_Position = uProjection * uView * uModel * vec4(aPosition.x, aPosition.y, aPosition.z, 1.0);
//gl_Position = model * vec4(aPosition.x, aPosition.y, aPosition.z, 1.0);
vTexCoor = vec2(aCoor.x, aCoor.y);
vNormal = mat3(transpose(inverse(uModel))) * aNormal;
vPos = (uModel * vec4(aPosition, 1.0f)).xyz;
}
片段着色器
#version 330 core
uniform sampler2D uSAMP;
uniform vec3 uLightPos;
uniform vec3 uViewPos;
uniform vec3 uLightColor;
out vec4 fColor;
in vec2 vTexCoor;
in vec3 vNormal;
in vec3 vPos;
void main()
{
//vec4 color = texture(uSAMP, vTexCoor);
vec4 color = vec4(0.3, 0.3, 0.6, 1);
//ambient
float factor = 0.4f;
vec3 ambient = factor * uLightColor;
//diffuse
vec3 n = normalize(vNormal);
vec3 lightDir = normalize(uLightPos - vPos);
float factor2 = max(dot(n, lightDir), 0);
vec3 diffuse = factor2 * uLightColor;
//specular
float strength = 0.6f;
vec3 viewDir = normalize(uViewPos - vPos);
vec3 reflectDir = reflect(-lightDir, n);
float factor4 =pow(max(dot(reflectDir, viewDir), 0), 128);
vec3 specular = factor4 * strength * uLightColor;
vec3 result = (ambient + diffuse + specular) * color.xyz;
//fColor = color;
fColor = vec4(result, 1.0);
}