如何使用 2 个或更多具有不同位置和 texCoords 的纹理?

How do I use 2 or more textures with different positions and texCoords?

在学习Webgl-2-textures的题目时,发现这两个纹理共享相同的a_positionsa_texCoord,它们在屏幕上显示为相同的大小,使用一个drawArrays 打电话。 是否可能有不同的 a_positiona_texCoord,但仍然可以像这样处理两个图像:(假设 u_image0 是背景,u_image1 是前面可以和背景有画面效果的图片如下。)

precision mediump float;

// our textures
uniform sampler2D u_image0;
uniform sampler2D u_image1;

// the texCoords passed in from the vertex shader.
varying vec2 v_texCoord0;
varying vec2 v_texCoord1;

void main() {
   vec4 color0 = texture2D(u_image0, v_texCoord0);
   vec4 color1 = texture2D(u_image1, v_texCoord1);
   gl_FragColor = color0 * color1;
}

不可能有不同的位置,因为 WebGL 一次只绘制一个像素。只能设置一个gl_Position

每个纹理可以有不同的纹理坐标,或者在片段着色器中计算不同的纹理坐标。例如

   vec4 color0 = texture2D(u_image0, v_texCoord0);
   vec4 color1 = texture2D(u_image1, v_texCoord0 * 2.0);

现在第二张图片使用了不同的纹理坐标。该示例可能很愚蠢,但关键是它是您的代码。你可以输入任何你想要的数学。

   uniform vec2 offset1;
   uniform vec2 offset2;
   uniform vec2 scale1;
   uniform vec2 scale2;

   vec4 color0 = texture2D(u_image0, v_texCoord0 * scale1 + offset1);
   vec4 color1 = texture2D(u_image1, v_texCoord0 * scale2 + offset2);

否则你也可以制作一个顶点着色器,为每个纹理传递不同的纹理坐标。

attribute vec2 texcoord0;
attribute vec2 texcoord1;

varying vec2 v_texCoord0;
varying vec2 v_texCoord1;

void main() {
  v_texcoord0 = v_texCoord0;
  v_texcoord1 = v_texCoord1;
}

与上面的方法一样,你包含的数学由你决定。添加偏移量、比例或完整矩阵或您想要的任何内容。

允许全矩阵是很常见的。

  vec2 uv = (some4x4Matrix * vec4(texcoord, 0, 1)).xy;

这使您可以平移(偏移)、缩放甚至旋转纹理坐标。

这是an article that uses that style