在这个WebGL程序中,顶点着色器和片元着色器之间的插值是在何时发生的?

9

背景

我正在查看 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);
    }

它们一起呈现以下图像:

a multicoloured triangle

问题

我理解顶点着色器每个顶点只调用一次,而片元着色器每个像素只调用一次。

然而,片元着色器引用了vColor变量,该变量仅在每个顶点调用时分配一次,但是像素比顶点多得多!

生成的图像清楚地显示出颜色渐变-为什么? WebGL自动插值vColor的值以填充顶点之间的像素吗?如果是这样,插值是如何完成的?

2个回答

6
是的,WebGL会自动在3个顶点之间插值提供的值。
该内容摘自此网站

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 between a and b. 0 at a and 1 at b.

For varyings though WebGL uses this formula

result = (1 - t) * a / aW + t * b / bW
         -----------------------------
            (1 - t) / aW + t / bW

Where aW is the W that was set on gl_Position.w when the varying was as set to a and bW is the W that was set on gl_Position.w when the varying was set to b.

该网站展示了这个公式如何在插值varyings时生成透视正确的纹理映射坐标。点击链接可以查看详细内容。
此外,该网站还展示了varyings变化的动画

3
khronos OpenGL wiki - 片段着色器 给出了答案,即:

每个片段都有一个窗口空间位置、几个其他值,并且它包含了上一个顶点处理阶段的插值每个顶点输出值

(强调是我的)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接