uniform 和 attribute 的区别见:ch02/05-ColoredPoints.html
在 WebGL/GLSL 中,uniform
、attribute
和 varying
是三种关键变量类型,它们的区别如下:
const positionLocation = gl.getAttribLocation(program, 'a_position');
gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0);
const matrixLocation = gl.getUniformLocation(program, 'u_matrix');
gl.uniformMatrix4fv(matrixLocation, false, matrix);
out
,在片元着色器中声明为 in
(GLSL ES 3.0+)。示例:
// 顶点着色器
out vec3 v_color; // 输出到片元着色器
void main() {
v_color = vec3(1.0, 0.0, 0.0); // 顶点颜色
}
// 片元着色器
in vec3 v_color; // 接收插值后的颜色
void main() {
gl_FragColor = vec4(v_color, 1.0);
}
类型 | 作用域 | 数据变化频率 | 典型用途 |
---|---|---|---|
attribute |
顶点着色器 | 每个顶点不同 | 顶点位置、颜色、UV坐标 |
uniform |
全局 | 一次绘制调用中不变 | 变换矩阵、时间、全局光照参数 |
varying |
顶点→片元 | 插值后的值 | 颜色渐变、纹理坐标插值 |
<!-- 顶点着色器 -->
<script id="vertexShader" type="x-shader/x-vertex">
attribute vec3 a_position; // 顶点位置(attribute)
uniform mat4 u_matrix; // 变换矩阵(uniform)
out vec3 v_color; // 传递给片元的颜色(varying)
void main() {
gl_Position = u_matrix * vec4(a_position, 1.0);
v_color = a_position * 0.5 + 0.5; // 生成颜色
}
</script>
<!-- 片元着色器 -->
<script id="fragmentShader" type="x-shader/x-fragment">
precision mediump float;
in vec3 v_color; // 接收插值后的颜色(varying)
void main() {
gl_FragColor = vec4(v_color, 1.0);
}
</script>
attribute
改为 in
,varying
被拆分为 out
(顶点着色器)和 in
(片元着色器)。uniform
在顶点和片元着色器中需分别声明,且类型必须一致。