问题描述
我正在尝试研究 WebGL 中的阴影映射.我看到在实现此目的的各种库和示例中复制了相同的着色器代码.但是我没有找到关于它是如何工作的解释.
I am trying to study shadow mapping in WebGL. I see same piece of shader code copied in various libraries and examples that achieve this. However nowhere did I find the explanation of how it works.
这个想法是将深度值(单个浮点数)保存到颜色缓冲区(vec4)中.有一个将浮点数保存到 vec4 的打包函数和从 vec4 检索浮点数的解包函数.
The idea is to save a depth value (a single float) into the color buffer (vec4). There is a pack function that saves float to vec4 and unpack function that retrieves the float from vec4.
vec4 pack_depth(const in float depth)
{
const vec4 bit_shift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);
const vec4 bit_mask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);
vec4 res = fract(depth * bit_shift);
res -= res.xxyz * bit_mask;
return res;
}
float unpack_depth(const in vec4 rgba_depth)
{
const vec4 bit_shift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);
float depth = dot(rgba_depth, bit_shift);
return depth;
}
我原以为将浮点数打包到 vec4 中应该是一个小问题,只需将其复制到 vec4 的 4 个插槽之一中,其余的不使用即可.这就是为什么上面代码中的位移逻辑让我感到困惑的原因.
I would have imagined that packing a float into vec4 should be a trivial problem, just copy it into one of the 4 slots of vec4 and leave others unused. That's why the bit shifting logic in above code is puzzling to me.
谁能解释一下?
推荐答案
它没有在 GLSL vec4
中存储 GLSL float
.它所做的是在 vec4
中存储一个值,当写入 RGBA8 帧缓冲区(32 位值)时,可以将其作为 vec4
读取,然后重新组合成相同的值float
之前给出的.
It's not storing a GLSL float
in a GLSL vec4
. What it's doing is storing a value in a vec4
which, when written to an RGBA8 framebuffer (32-bit value) can be read as a vec4
and then reconstituted into the same float
that was given previously.
如果您按照您的建议进行操作,只需将浮点值写入帧缓冲区的红色通道,您将只能获得 8 位的准确度.使用这种方法,您可以让所有 32 位都为您工作.
If you did what you suggest, just writing the floating-point value to the red channel of the framebuffer, you'd only get 8 bits of accuracy. With this method, you get all 32-bits working for you.
这篇关于将 float 打包到 vec4 中——这段代码是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!