提示:Shader属于GPU编程,难写难调试,阅读本文需有一定的OpenGL基础,可以写简单的Shader,不适合不会OpenGL的朋友
Blinn-Phong光照模型,又称为Blinn-phong反射模型(Blinn–Phong reflection model)或者 phong 修正模型(modified Phong reflection model),是由 Jim Blinn于 1977 年在文章中对传统 phong 光照模型基础上进行修改提出的。它是一个经验模型,并不完全符合真实世界中的光照现象,但由于实现起来简单方便,并且计算速度和得到的效果都还不错,因此在早期被广泛的使用。
相对于Phong模型,Blinn-Phong是对高光部分进行简化计算,对于环境光、漫反射计算是一样的。环境光、漫反射一般处理如下:
直接上结论,因为这个模型资料很多,大家可以参考https://zhuanlan.zhihu.com/p/442023993
h = l + v ∣ l ∣ + ∣ v ∣ h=\frac{l+v}{\left | l \right | + \left | v \right | } h=∣l∣+∣v∣l+v
L s = k s I ∗ m a x ( 0 , c o s ( α ) ) p = k s I ∗ m a x ( 0 , n ⋅ h ) p L_{s}=k_{s}I*max(0, cos(\alpha))^{p}=k_{s}I*max(0, n\cdot h)^{p} Ls=ksI∗max(0,cos(α))p=ksI∗max(0,n⋅h)p
h——半程向量
Ls——高光颜色
k s k_{s} ks—— 高光反射系数
n——反光度因子
Overload中计算Blinn-Phong光照模型的shader代码如下:
/*
* BlinnPhong模型,只计算漫反射与高光
* p_LightColor: 光强
* p_LightDir:光源方向
* p_Luminosity:衰减系数
*/
vec3 BlinnPhong(vec3 p_LightDir, vec3 p_LightColor, float p_Luminosity)
{
// 半程向量
const vec3 halfwayDir = normalize(p_LightDir + g_ViewDir); // 计算半程向量
const float diffuseCoefficient = max(dot(g_Normal, p_LightDir), 0.0); // Lambert余弦
const float specularCoefficient = pow(max(dot(g_Normal, halfwayDir), 0.0), u_Shininess * 2.0);
// 片元颜色:光强 * 漫反射系数 * cos(theta) * 衰减因子 + 光强 * 高光反射系数 * 高光指数 * 衰减因子
return p_LightColor * g_DiffuseTexel.rgb * diffuseCoefficient * p_Luminosity + ((p_Luminosity > 0.0) ? (p_LightColor * g_SpecularTexel.rgb * specularCoefficient * p_Luminosity) : vec3(0.0));
}
常见的光源有:平行光、点光源、聚光灯,他们的具体定义及计算可参考:https://learnopengl-cn.readthedocs.io/zh/latest/02%20Lighting/05%20Light%20casters/,里面讲的比较详细。
不同的光源有不同的数据,而且场景中光源数量也是不确定的,所以这种情况了Overload使用OpenGL的SSBO传递数据。光源数据转换成一个矩阵,转换代码如下:
OvMaths::FMatrix4 OvRendering::Entities::Light::GenerateMatrix() const
{
OvMaths::FMatrix4 result;
// 存放光源位置(对应平行光存放的是方向)
auto position = m_transform.GetWorldPosition();
result.data[0] = position.x;
result.data[1] = position.y;
result.data[2] = position.z;
// 光源朝向
auto forward = m_transform.GetWorldForward();
result.data[4] = forward.x;
result.data[5] = forward.y;
result.data[6] = forward.z;
// 光源颜色
result.data[8] = static_cast(Pack(color));
// 聚光灯参数
result.data[12] = type;
result.data[13] = cutoff;
result.data[14] = outerCutoff;
// 光源的衰减参数
result.data[3] = constant;
result.data[7] = linear;
result.data[11] = quadratic;
// 光源强度
result.data[15] = intensity;
return result;
}
Pack函数是将光颜色RGBA变成一个32位无符号整数,感兴趣可以看看,这种做法经常会见到。要想具体查看每种光源数据,可以使用RenderDoc进行查看,加深对每种光源数据的认识。RenderDoc是Shader编写利器,而且学起来也不难。
Overload的材质如何创建就不再讲了,上节已经讲过的。打开一个材料例子,编辑可看到其可设置漫反射、高度、mask、法线、高光贴图,以及其他shader中使用的参数。
Shader是实现材质的核心,下面分析其代码。Standard材质的Shader在Standard.glsl文件中。
其Vertext shader代码如下:
#shader vertex
#version 430 core
/*顶点着色器的入参*/
layout (location = 0) in vec3 geo_Pos; // 顶点坐标
layout (location = 1) in vec2 geo_TexCoords; // 顶点纹理坐标
layout (location = 2) in vec3 geo_Normal; // 顶点法线
layout (location = 3) in vec3 geo_Tangent; // 顶点的切线
layout (location = 4) in vec3 geo_Bitangent; // 顶点切线与法线的叉乘,三者组成一个本地坐标系
/* Global information sent by the engine */
layout (std140) uniform EngineUBO
{
mat4 ubo_Model; // 模型矩阵
mat4 ubo_View; // 视图矩阵
mat4 ubo_Projection; // 投影矩阵
vec3 ubo_ViewPos; // 摄像机位置
float ubo_Time;
};
/* Information passed to the fragment shader */
out VS_OUT
{
vec3 FragPos; // 顶点的全局坐标
vec3 Normal; // 顶点法线
vec2 TexCoords; // 纹理坐标
mat3 TBN;
flat vec3 TangentViewPos;
vec3 TangentFragPos;
} vs_out;
void main()
{
vs_out.TBN = mat3 // 全局坐标系到本地坐标系的旋转矩阵
(
normalize(vec3(ubo_Model * vec4(geo_Tangent, 0.0))),
normalize(vec3(ubo_Model * vec4(geo_Bitangent, 0.0))),
normalize(vec3(ubo_Model * vec4(geo_Normal, 0.0)))
);
mat3 TBNi = transpose(vs_out.TBN); // 为什么要转置?
vs_out.FragPos = vec3(ubo_Model * vec4(geo_Pos, 1.0)); // 全局坐标系的下的坐标
vs_out.Normal = normalize(mat3(transpose(inverse(ubo_Model))) * geo_Normal); // 全局坐标系下的法线
vs_out.TexCoords = geo_TexCoords; // 纹理坐标,不用变
vs_out.TangentViewPos = TBNi * ubo_ViewPos;
vs_out.TangentFragPos = TBNi * vs_out.FragPos;
gl_Position = ubo_Projection * ubo_View * vec4(vs_out.FragPos, 1.0);
}
其输入是顶点信息,包括顶点的坐标、法线、纹理、切线、切线与法线的叉乘。其实一般如无需特殊需求,模型只需坐标、法线、纹理即可。这里的geo_Bitangent看着像是切线与法线的叉乘,但使用RenderDoc获取顶点着色器的输入发现geo_Bitangent与切线与法线的叉乘很接近,但并不完全相等。所以geo_Bitangent究竟是不是切线与法线的叉乘不是完全肯定,但对我们看源码影响不大,暂且认为他们三个正好组成一个本地坐标系吧。
看其main函数,计算顶点全局坐标、法线、NDC坐标。注意,法线是用模型矩阵 ( M − 1 ) T (M^{-1})^{T} (M−1)T转换得到。VS_OUT中的输出量会插值,最后输给片元着色器。
再来看片元Shader:
#shader fragment
#version 430 core
/* Global information sent by the engine */
layout (std140) uniform EngineUBO
{
mat4 ubo_Model;
mat4 ubo_View;
mat4 ubo_Projection;
vec3 ubo_ViewPos;
float ubo_Time;
};
/* Information passed from the fragment shader */
in VS_OUT
{
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
mat3 TBN;
flat vec3 TangentViewPos;
vec3 TangentFragPos;
} fs_in;
/* Light information sent by the engine */
layout(std430, binding = 0) buffer LightSSBO
{
mat4 ssbo_Lights[];
};
/* Uniforms (Tweakable from the material editor) */
uniform vec2 u_TextureTiling = vec2(1.0, 1.0);
uniform vec2 u_TextureOffset = vec2(0.0, 0.0);
uniform vec4 u_Diffuse = vec4(1.0, 1.0, 1.0, 1.0);
uniform vec3 u_Specular = vec3(1.0, 1.0, 1.0);
uniform float u_Shininess = 100.0;
uniform float u_HeightScale = 0.0;
uniform bool u_EnableNormalMapping = false;
uniform sampler2D u_DiffuseMap;
uniform sampler2D u_SpecularMap;
uniform sampler2D u_NormalMap;
uniform sampler2D u_HeightMap;
uniform sampler2D u_MaskMap;
/* Global variables */
vec3 g_Normal;
vec2 g_TexCoords;
vec3 g_ViewDir;
vec4 g_DiffuseTexel;
vec4 g_SpecularTexel;
vec4 g_HeightTexel;
vec4 g_NormalTexel;
out vec4 FRAGMENT_COLOR;
vec3 UnPack(float p_Target)
{
return vec3
(
float((uint(p_Target) >> 24) & 0xff) * 0.003921568627451,
float((uint(p_Target) >> 16) & 0xff) * 0.003921568627451,
float((uint(p_Target) >> 8) & 0xff) * 0.003921568627451
);
}
bool PointInAABB(vec3 p_Point, vec3 p_AabbCenter, vec3 p_AabbHalfSize)
{
return
(
p_Point.x > p_AabbCenter.x - p_AabbHalfSize.x && p_Point.x < p_AabbCenter.x + p_AabbHalfSize.x &&
p_Point.y > p_AabbCenter.y - p_AabbHalfSize.y && p_Point.y < p_AabbCenter.y + p_AabbHalfSize.y &&
p_Point.z > p_AabbCenter.z - p_AabbHalfSize.z && p_Point.z < p_AabbCenter.z + p_AabbHalfSize.z
);
}
vec2 ParallaxMapping(vec3 p_ViewDir)
{
const vec2 parallax = p_ViewDir.xy * u_HeightScale * texture(u_HeightMap, g_TexCoords).r;
return g_TexCoords - vec2(parallax.x, 1.0 - parallax.y);
}
/*
* BlinnPhong模型,只计算漫反射与高光
* p_LightColor: 光强
* p_LightDir:光源方向
* p_Luminosity:衰减系数
*/
vec3 BlinnPhong(vec3 p_LightDir, vec3 p_LightColor, float p_Luminosity)
{
// 半程向量
const vec3 halfwayDir = normalize(p_LightDir + g_ViewDir);
const float diffuseCoefficient = max(dot(g_Normal, p_LightDir), 0.0); // Lambert余弦
const float specularCoefficient = pow(max(dot(g_Normal, halfwayDir), 0.0), u_Shininess * 2.0);
// 片元颜色:光强 * 漫反射系数 * cos(theta) * 衰减因子 + 光强 * 高光反射系数 * 高光指数 * 衰减因子
return p_LightColor * g_DiffuseTexel.rgb * diffuseCoefficient * p_Luminosity + ((p_Luminosity > 0.0) ? (p_LightColor * g_SpecularTexel.rgb * specularCoefficient * p_Luminosity) : vec3(0.0));
}
// 计算衰减因子,跟LearnOpenGL中的公式一致
float LuminosityFromAttenuation(mat4 p_Light)
{
const vec3 lightPosition = p_Light[0].rgb;
const float constant = p_Light[0][3];
const float linear = p_Light[1][3];
const float quadratic = p_Light[2][3];
const float distanceToLight = length(lightPosition - fs_in.FragPos);
const float attenuation = (constant + linear * distanceToLight + quadratic * (distanceToLight * distanceToLight));
return 1.0 / attenuation;
}
vec3 CalcPointLight(mat4 p_Light)
{
/* Extract light information from light mat4 */
const vec3 lightPosition = p_Light[0].rgb; // 光源位置
const vec3 lightColor = UnPack(p_Light[2][0]); // 光源颜色
const float intensity = p_Light[3][3]; // 光强
const vec3 lightDirection = normalize(lightPosition - fs_in.FragPos); // 光源方向
const float luminosity = LuminosityFromAttenuation(p_Light); // 衰减因子
return BlinnPhong(lightDirection, lightColor, intensity * luminosity);
}
vec3 CalcDirectionalLight(mat4 light)
{
return BlinnPhong(-light[1].rgb, UnPack(light[2][0]), light[3][3]);
}
vec3 CalcSpotLight(mat4 p_Light)
{
/* Extract light information from light mat4 */
const vec3 lightPosition = p_Light[0].rgb; // 聚光灯位置
const vec3 lightForward = p_Light[1].rgb; // 聚光灯朝向
const vec3 lightColor = UnPack(p_Light[2][0]); // 光源颜色
const float intensity = p_Light[3][3]; // 光强
const float cutOff = cos(radians(p_Light[3][1])); // 内圆锥角
const float outerCutOff = cos(radians(p_Light[3][1] + p_Light[3][2])); // 内圆锥角 + 外圆锥角
const vec3 lightDirection = normalize(lightPosition - fs_in.FragPos); // 光方向
const float luminosity = LuminosityFromAttenuation(p_Light); // 衰减因子
/* Calculate the spot intensity */
const float theta = dot(lightDirection, normalize(-lightForward)); // cos(theta)
const float epsilon = cutOff - outerCutOff; // 内部圆锥角与外部圆锥角之差
const float spotIntensity = clamp((theta - outerCutOff) / epsilon, 0.0, 1.0); // 边缘软化
return BlinnPhong(lightDirection, lightColor, intensity * spotIntensity * luminosity);
}
vec3 CalcAmbientBoxLight(mat4 p_Light)
{
const vec3 lightPosition = p_Light[0].rgb;
const vec3 lightColor = UnPack(p_Light[2][0]);
const float intensity = p_Light[3][3];
const vec3 size = vec3(p_Light[0][3], p_Light[1][3], p_Light[2][3]);
return PointInAABB(fs_in.FragPos, lightPosition, size) ? g_DiffuseTexel.rgb * lightColor * intensity : vec3(0.0);
}
vec3 CalcAmbientSphereLight(mat4 p_Light)
{
const vec3 lightPosition = p_Light[0].rgb;
const vec3 lightColor = UnPack(p_Light[2][0]);
const float intensity = p_Light[3][3];
const float radius = p_Light[0][3];
return distance(lightPosition, fs_in.FragPos) <= radius ? g_DiffuseTexel.rgb * lightColor * intensity : vec3(0.0);
}
void main()
{
g_TexCoords = u_TextureOffset + vec2(mod(fs_in.TexCoords.x * u_TextureTiling.x, 1), mod(fs_in.TexCoords.y * u_TextureTiling.y, 1)); // 计算纹理贴图坐标
/* Apply parallax mapping */
if (u_HeightScale > 0) // 使用高度贴图
g_TexCoords = ParallaxMapping(normalize(fs_in.TangentViewPos - fs_in.TangentFragPos));
/* Apply color mask */
if (texture(u_MaskMap, g_TexCoords).r != 0.0) // 可以通过u_MaskMap屏蔽部分区域
{
g_ViewDir = normalize(ubo_ViewPos - fs_in.FragPos); // 视线方向(视点坐标-片元坐标)
g_DiffuseTexel = texture(u_DiffuseMap, g_TexCoords) * u_Diffuse; // 漫反射颜色
g_SpecularTexel = texture(u_SpecularMap, g_TexCoords) * vec4(u_Specular, 1.0); // 高光项的颜色
if (u_EnableNormalMapping) // 使用法线贴图
{
g_Normal = texture(u_NormalMap, g_TexCoords).rgb;
g_Normal = normalize(g_Normal * 2.0 - 1.0);
g_Normal = normalize(fs_in.TBN * g_Normal);
}
else
{
g_Normal = normalize(fs_in.Normal);
}
vec3 lightSum = vec3(0.0);
// 对灯光进行循环,计算每盏灯的贡献
for (int i = 0; i < ssbo_Lights.length(); ++i)
{
switch(int(ssbo_Lights[i][3][0]))
{
case 0: lightSum += CalcPointLight(ssbo_Lights[i]); break; // 计算点光源
case 1: lightSum += CalcDirectionalLight(ssbo_Lights[i]); break; // 计算
case 2: lightSum += CalcSpotLight(ssbo_Lights[i]); break; // 计算聚光灯
case 3: lightSum += CalcAmbientBoxLight(ssbo_Lights[i]); break;
case 4: lightSum += CalcAmbientSphereLight(ssbo_Lights[i]); break;
}
}
FRAGMENT_COLOR = vec4(lightSum, g_DiffuseTexel.a);
}
else
{
FRAGMENT_COLOR = vec4(0.0);
}
}
Fragment Sahder代码看着很多,拆解一下就是分别计算各个灯光的贡献,进行累加。计算每种灯光时,最终都是使用Blinn-Phonge模型计算的。每种类型的灯光基本与LearnOpenGL中的描述一致。UnPack函数可以学习一下,看看如何float如何变成RGB。