我正在实现瓦片式延迟渲染,并且需要计算瓦片的最小/最大深度值。我每个瓦片只渲染一个像素,并在嵌套的for循环中收集深度值,代码如下:
float minDepth = 1.0;
float maxDepth = 0.0;
ivec2 clampMax = ivec2(screenSize) - 1;
// Iterate over each pixel in this tile
for (int x = 0; x < 32; x++) {
for (int y = 0; y < 32; y++) {
ivec2 newCoord = screenCoord + ivec2(x,y);
newCoord = min(newCoord, clampMax);
// Fetch the depth for that coordinate
float currentDepth = texelFetch(depth, newCoord, 0).r;
minDepth = min(minDepth, currentDepth);
maxDepth = max(maxDepth, currentDepth);
}
}
到目前为止,这个工作得很好,但是查看生成的汇编代码,纹理查找会变成这样:
// R2.xy contains 'newCoord'
MOV.S R2.z, {0, 0, 0, 0}.x;
TXF.F R1.x, R2.xyzz, handle(D0.x), 2D;
这基本上等于:
vec3 coordinate;
coordinate.xy = newCoord;
coordinate.z = 0;
result = texelFetch(depth, coordinate);
因此,在纹理查找中会产生一个多余的指令,这在循环中会累加很多。我的猜测是,NVIDIA在内部实现了texelFetch作为
texelFetch(sampler2D sampler, ivec3 coord)
回到问题:如何优化这个循环?
我正在使用带有最新驱动程序的GTX 670在Windows上运行。