WebGL2 不写入 `out int[2]` 结果的第二个输出

WebGL2 not writing second output of `out int[2]` result

当我从片段着色器读取输出时:

#version 300 es
precision highp float;
precision highp int;
out int outColor[2];
void main() {
    outColor[0] = 5;
    outColor[1] = 2;
}

渲染成32位整型RG贴图,发现只写了5,没写2。大概我在某处弄错了一些格式说明符。或者我可能将帧缓冲区附加到错误的东西 (gl.COLOR_ATTACHMENT0)。我尝试了各种不同的论点,但由于格式不一致,我所做的大多数更改都没有结果。可能是我需要串联更改3个常量。

这是我的独立资源。我想要的输出是一个在 5 和 2 之间交替的数组。相反,我得到一个在 5 和半随机大常量和 0 之间交替的数组。

let canvas /** @type {HTMLCanvasElement} */ = document.createElement('canvas');
let gl = canvas.getContext("webgl2");

let vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, `#version 300 es
in vec4 a_position;
void main() {
    gl_Position = a_position;
}
`);
gl.compileShader(vertexShader);
console.assert(gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS), "Vertex shader compile failed.");

let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, `#version 300 es
precision highp float;
precision highp int;
out int outColor[2];
void main() {
    outColor[0] = 5;
    outColor[1] = 2;
}
`);
gl.compileShader(fragmentShader);

let program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);

let positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-3, -1, 1, 3, 1, -1]), gl.STATIC_DRAW);
let positionAttributeLocation = gl.getAttribLocation(program, "a_position");
let vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);

let w = 4;
let h = 4;

let texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RG32I, w, h, 0, gl.RG_INTEGER, gl.INT, null);
let frameBuffer = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

gl.useProgram(program);
gl.viewport(0, 0, w, h);
gl.drawArrays(gl.TRIANGLES, 0, 3);
let outputBuffer = new Int32Array(w*h*2);
gl.readPixels(0, 0, w, h, gl.RG_INTEGER, gl.INT, outputBuffer);
console.log(outputBuffer);

out int outColor[2];这样的数组输出用于输出到多个渲染目标。在您的情况下,两个渲染目标各有一个通道,因为您使用了标量类型。

要用两个通道表达单个渲染目标,请尝试 out ivec2 outColor;