一个简单的雾效果可以通过混合每个片元的颜色和一个常量的雾颜色来实现,雾的密度量由顶点到相机的距离确定(离观察者尽雾浓度小,而越远浓度越大)。 我们可以用线性关系或者非线性关系来来表达在顶点到相机之间的雾量。
如下图所示:用线性关系模拟 ![](http://image98.360doc.com/DownloadImg/2016/06/2513/74607400_1)
线性关系可以用下列表达: ![](http://image98.360doc.com/DownloadImg/2016/06/2513/74607400_2)
dmin 是距离眼睛最近的距离(即没有雾的地方),dmax是距离 眼睛最远的距离(即雾最大的地方),z是当前距离眼睛的距离。值f是雾的因子(fog factor)。 注意: 由于雾的实现在片元shader中,这个效果只会影响被渲染的物体,在没有场景的地方不会看到雾效(如场景的background),为了显示真实情况,需要在没有被渲染的地方也要有对应的雾效果,此时可以用最大的雾量作为场景的background颜色。 顶点shader - #version 430
-
- layout (location = 0) in vec3 VertexPosition;
- layout (location = 1) in vec3 VertexNormal;
-
- out vec3 Position;
- out vec3 Normal;
-
- uniform mat4 ModelViewMatrix;
- uniform mat3 NormalMatrix;
- uniform mat4 ProjectionMatrix;
- uniform mat4 MVP;
-
- void main()
- {
- Normal = normalize( NormalMatrix * VertexNormal);
- Position = vec3( ModelViewMatrix * vec4(VertexPosition,1.0) );
-
- gl_Position = MVP * vec4(VertexPosition,1.0);
- }
片元shader- #version 430
-
- in vec3 Position;
- in vec3 Normal;
-
- struct LightInfo {
- vec4 position;
- vec3 intensity;
- };
- uniform LightInfo Light;
-
- struct FogInfo {
- float maxDist;
- float minDist;
- vec3 color;
- };
- uniform FogInfo Fog;
-
- uniform vec3 Kd;
- uniform vec3 Ka;
- uniform vec3 Ks;
- uniform float Shininess;
-
- layout( location = 0 ) out vec4 FragColor;
-
- vec3 ads( )
- {
- vec3 s = normalize( Light.position.xyz - Position.xyz );
- vec3 v = normalize(vec3(-Position));
- vec3 h = normalize( v + s );
-
- vec3 ambient = Ka;
- vec3 diffuse = Kd * max(0.0, dot(s, Normal) );
- vec3 spec = Ks * pow( max( 0.0, dot( h, Normal) ), Shininess );
-
- return Light.intensity * (ambient + diffuse + spec);
- }
-
- void main() {
- float dist = abs( Position.z );
- float fogFactor = (Fog.maxDist - dist) /
- (Fog.maxDist - Fog.minDist);
- fogFactor = clamp( fogFactor, 0.0, 1.0 );
- vec3 shadeColor = ads();
- vec3 color = mix( Fog.color, shadeColor, fogFactor );
-
- FragColor = vec4(color, 1.0);
- }
注意: 在上面的shader代码中,我们用float dist = abs( Position.z ); 来求到camera的距离,但有时候这种方法可能会引起一些雾效不真实(在某些情况下),为了计算更准确一些,我们可以用下列算式: float dist = length( Position.xyz ); 当然,这种情况的计算时间复杂度要稍微高于上面的计算方式。
当然,我们也可以采用非线性关系求f,看下公式: ![](http://image98.360doc.com/DownloadImg/2016/06/2513/74607400_4)
d是雾的浓度,我们也可以把此公式简化为: ![](http://image98.360doc.com/DownloadImg/2016/06/2513/74607400_5)
|