gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:50:56 25 4
gpt4 key购买 nike

背景

我在看 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com