opengl-es - 这个 WebGL 程序中的顶点着色器和片段着色器什么时候发生插值?

标签 opengl-es glsl webgl shader webgl2

背景

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

它们一起呈现以下图像:

a multicoloured triangle

问题)

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

但是,片段着色器引用了 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 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.



上面链接的站点显示了该公式如何生成 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/

相关文章:

ios - OpenGL ES 纹理质量下降

Android 和 glOrthof

opengl - 纹素中心坐标处的textureGather()行为

java - OpenGL正确实现多种 Material

javascript - Three.js 中不受雾影响的自定义着色器

android - 将位图帧渲染到表面以进行编码

android - 不同设备上的 openGL ES 版本

opengl - 在 GLSL 中对矩阵使用预乘顺序有什么缺点吗?

javascript - Three.js - 它有顶点索引着色吗?

javascript - 在 Three.js 中,如何在相机方向上将对象直接移离相机?