Fog in GLSL (OZone3D)

本文介绍如何在像素级别实现雾效计算,利用GLSL中的gl_FragCoord变量获取像素坐标,并通过像素着色器完成从顶点到像素级雾效的过渡计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载链接  http://www.ozone3d.net/tutorials/glsl_fog/p04.php


Fog in GLSL

By Jerome 'JeGX' Guinot - jegx_AT_ozone3d(dot)net 

Initial draft: December 21, 2007


[ Index ]

Page 1 | Page 2 | Page 3 | Page 4 | Page 5

»Next Page





4 - Per-Pixel Fog Computation

We shall see here how to compute the fog at each pixel level . The principle is exactly the same as by vertex. The only difference resides in the determination of the distance between the camera and the currently processed pixel . In the per-pixel fog computation, the vertex shader is inactive, because the calculus is made in the pixel shader .

In GLSL there exists a gl_FragCoord variable. This one is an input variable of the pixel shader.gl_FragCoord contains the screen coordinates of the current pixel. For example, if the demo's window has a width of 1280 pixels, the following code :

if(gl_FragCoord.x < 700.0)
{
	gl_FragColor = vec4(0.0, 0.5, 0.0, 1.0);
}
else
{
	gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );
}

should give the following image :

Fog Factor - GL_LINEAR - GL_EXP - GL_EXP2 
DEMO_GLSL_Fog_FragCoord.xml

The distance between the camera and the current pixel (the z axis value) is obtained by the following relation :

float z = gl_FragCoord.z / gl_FragCoord.w;

It is quite easy, thanks to this relation, to show a z-buffer view from the camera's point of view:

float z = 1.0 - (gl_FragCoord.z / gl_FragCoord.w) / 4000.0;
gl_FragColor = vec4(z, z, z, 1.0);

Fog Factor - GL_LINEAR - GL_EXP - GL_EXP2 
DEMO_GLSL_Fog_DepthBuffer_Visualization.xml

The 4000.0 corresponds to the far clipping plane (zfar), initialized in the Demoniak3D demo.

That said, let's come back to the fog computation. The following code show how to implement the fog calculus per-pixel:

const float LOG2 = 1.442695;
float z = gl_FragCoord.z / gl_FragCoord.w;
float fogFactor = exp2( -gl_Fog.density * 
				   gl_Fog.density * 
				   z * 
				   z * 
				   LOG2 );
fogFactor = clamp(fogFactor, 0.0, 1.0);

gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值