WebGL:如何绑定一组采样器

时间:2013-06-13 17:34:17

标签: javascript opengl-es-2.0 webgl fragment-shader

如上所述here,可以“将所需的所有纹理绑定到着色器中的采样器数组,然后使用顶点属性”对其进行索引。我该怎么做绑定?目前我像这样绑定我的纹理(如果这首先是正确的;它至少起作用):

sampler[i] = gl.getUniformLocation(program, "u_sampler" + i);
...
for (var i = 0, len = textures.length; i < len; i++) {
    gl.activeTexture(gl.TEXTURE0 + i);
    gl.bindTexture(gl.TEXTURE_2D, textures[i]);
    gl.uniform1i(sampler[i], i);
}

现在要绑定一个采样器数组,我会丢弃activeTexturebindTexture并使用类似的内容吗?

gl.uniform1iv(sampler, [0,...,len-1]);

2 个答案:

答案 0 :(得分:1)

没关系,我想我找到了解决方案。我的代码如下:

var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(...
gl.bindTexture(gl.TEXTURE_2D, null);
textures[i] = texture;

...compose texture images...

gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, textures[i]);
gl.texSubImage2D(gl.TEXTURE_2D, 0, xoffset, yoffset, gl.RGBA, gl.UNSIGNED_BYTE, image);

...fill all textures...

var sampler = gl.getUniformLocation(program, "u_sampler");
var samplerArray = new Int32Array(textures.length);
var len = samplerArray.length;
while (len--) {
    samplerArray[len] = len;
}
gl.uniform1iv(sampler, samplerArray);

现在,我可以通过u_sampler[i]正确访问片段着色器中的采样器。

答案 1 :(得分:0)

如果我理解您正确链接的问题,则提案会保留API代码,并在着色器中指定一个采样器数组。然后通过属性索引该数组。类似的东西:

uniform sampler2D samplers[8];
uniform int index;
..
vec4 color = texture2D(samplers[index], coord);

这种技术应该适用于OpenGL。但是,WebGL规范支持,该规范声明不支持采样器的动态索引(即,使用非常量变量进行索引)。请参阅WebGL规范here