背景
我在看 this example code来自 WebGL2 库 PicoGL.js .
它描述了一个三角形(三个顶点:(-0.5, -0.5), (0.5, -0.5), (0.0, 0.5)
),顶点着色器为每个三角形分配了一种颜色(红色、绿色、蓝色):
#version 300 es
layout(location=0) in vec4 position;
layout(location=1) in vec3 color;
out vec3 vColor;
void main() {
vColor = color;
gl_Position = position;
}
vColor
输出传递给片段着色器: #version 300 es
precision highp float;
in vec3 vColor;
out vec4 fragColor;
void main() {
fragColor = vec4(vColor, 1.0);
}
它们一起呈现以下图像:
问题)
我的理解是每个顶点调用一次顶点着色器,而每个像素调用一次片段着色器。
但是,片段着色器引用了
vColor
变量,每次调用只分配一次给每个顶点,但像素比顶点多得多!生成的图像清楚地显示了颜色渐变 - 为什么?
WebGL 是否会自动插入
vColor
的值?对于顶点之间的像素?如果是这样,插值是如何完成的?
最佳答案
是的,WebGL 会自动在提供给 3 个顶点的值之间进行插值。
复制自 this site
A linear interpolation from one value to another would be this formula
result = (1 - t) * a + t * b
Where
t
is a value from 0 to 1 representing some position betweena
andb
. 0 ata
and 1 atb
.For varyings though WebGL uses this formula
result = (1 - t) * a / aW + t * b / bW ----------------------------- (1 - t) / aW + t / bW
Where
aW
is theW
that was set ongl_Position.w
when the varying was as set toa
andbW
is theW
that was set ongl_Position.w
when the varying was set tob
.
上面链接的站点显示了该公式如何生成 perspective correct texture mapping coordinates when interpolating varyings
它还shows an animation of the varyings changing
关于opengl-es - 这个 WebGL 程序中的顶点着色器和片段着色器什么时候发生插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029386/