【问题标题】:Deferred rendering and moving point light延迟渲染和移动点光源
【发布时间】:2011-11-05 12:38:09
【问题描述】:

我知道网上有几个关于同一问题的线程,但我没有从这些线程中获得帮助,因为我的实现不同。

我正在将视图空间中的颜色、法线和深度渲染到纹理中。在第二个中,我将纹理与全屏四边形绑定并计算照明。定向光似乎可以正常工作,但点光源会随着相机移动。

我分享对应的shader代码:

光照步骤顶点着色器

in vec2 inVertex;
in vec2 inTexCoord;
out vec2 texCoord;
void main() {
    gl_Position = vec4(inVertex, 0, 1.0);
    texCoord = inTexCoord;
}

光照步骤片段着色器

float depth = texture2D(depthBuffer, texCoord).r;
vec3 normal = texture2D(normalBuffer, texCoord).rgb;
vec3 color = texture2D(colorBuffer, texCoord).rgb;

vec3 position;
position.z = -nearPlane / (farPlane - (depth * (farPlane - nearPlane))) * farPlane;
position.x = ((gl_FragCoord.x / width) * 2.0) - 1.0;
position.y = (((gl_FragCoord.y / height) * 2.0) - 1.0) * (height / width);
position.x *= -position.z;
position.y *= -position.z;

normal = normalize(normal);
vec3 lightVector = lightPosition.xyz - position;
float dist = length(lightVector);
lightVector = normalize(lightVector);

float nDotL = max(dot(normal, lightVector), 0.0);
vec3 halfVector = normalize(lightVector - position);
float nDotHV = max(dot(normal, halfVector), 0.0);

vec3 lightColor = lightAmbient;
vec3 diffuse =  lightDiffuse * nDotL;
vec3 specular = lightSpecular * pow(nDotHV, 1.0) * nDotL;
lightColor += diffuse + specular;
float attenuation = clamp(1.0 / (lightAttenuation.x + lightAttenuation.y * dist + lightAttenuation.z * dist * dist), 0.0, 1.0);

gl_FragColor =  vec4(vec3(color * lightColor * attenuation), 1.0);

我将光照属性作为制服发送到着色器:

shader->set("lightPosition", (viewMatrix * modelMatrix).inverse().transpose() * vec4(0, 10, 0, 1.0));

viewmatrix 是相机矩阵,modelmatrix 在这里只是身份。

为什么点光源用相机而不是模型平移?

欢迎提出任何建议!

【问题讨论】:

  • 要使vec3 halfVector = normalize(lightVector - position); 工作,矢量position 必须具有单位长度(或至少与lightVector 相同),否则您将不会得到一半,而是由矢量加权的解决方案长度。

标签: opengl shader lighting deferred-rendering


【解决方案1】:

除了没有人说你计算的所有向量都必须归一化之外,你还必须确保它们都在同一个空间中。如果您使用视图空间位置作为视图向量,则法线向量也必须在视图空间中(在第一遍中写入 G 缓冲区之前必须通过逆转置模型视图矩阵进行转换)。并且光矢量也必须在视图空间中。因此,您必须通过视图矩阵(或模型视图矩阵,如果灯光位置不在世界空间中)来转换灯光位置,而不是通过其逆转置。

shader->set("lightPosition", viewMatrix * modelMatrix * vec4(0, 10, 0, 1.0));

编辑:对于定向光,如果您将光的方向指定为光的方向(如 vec4(0, 1, 0, 0) 用于指向 -z 方向的光,则反向转置实际上是一个好主意)。

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多