是什么导致我的绘制数组调用无效操作?

What is causing invalid operation on my draw arrays call?

我正在尝试使用 WebGL 从头开始​​绘制一个简单的三角形。

我有使用 C++ 编写 openGL 应用程序的经验,并且看过 webGL 参考卡来翻译我的代码。

但是,我在调试应用程序时遇到困难。 我收到的特定错误消息是:

GL ERROR :GL_INVALID_OPERATION : glDrawArrays: attempt to access out of range vertices in attribute 0

完整代码在这里:https://github.com/gheshu/webGL_experiments

顶点数据布局为 3 个向量,每个向量包含 3 个浮点数。 存在三个属性:位置、法线和颜色,应绑定在索引 0、1、2 上。

一些重要的片段:

网格class:

class Mesh{
    constructor(){
        this.num_vertices = 0;  
        this.vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
        gl.enableVertexAttribArray(0);
        gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 4*3*3, 0);
        gl.enableVertexAttribArray(1);
        gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 4*3*3, 4*3);
        gl.enableVertexAttribArray(2);
        gl.vertexAttribPointer(2, 3, gl.FLOAT, false, 4*3*3, 4*3*2);
    }
    upload(buffer){
        console.log(buffer);
        gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
        gl.bufferData(gl.ARRAY_BUFFER, buffer, gl.STATIC_DRAW);
        this.num_vertices = buffer.length / 9;
    }
    draw(){
        gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
        gl.drawArrays(gl.TRIANGLES, 0, this.num_vertices);
    }
    destroy(){
        gl.deleteBuffer(this.vbo);
    }
}

程序class:

class GLProgram{
    constructor(vertShader, fragShader){
        this.prog = gl.createProgram();
        gl.attachShader(this.prog, vertShader.id);
        gl.attachShader(this.prog, fragShader.id);
        gl.bindAttribLocation(this.prog, 0, "position");
        gl.bindAttribLocation(this.prog, 1, "normal");
        gl.bindAttribLocation(this.prog, 2, "color");
        gl.linkProgram(this.prog);
        var log = gl.getProgramInfoLog(this.prog);
        if(log.length){
            console.log();
        }
        gl.detachShader(this.prog, vertShader.id);
        vertShader.destroy();
        gl.detachShader(this.prog, fragShader.id);
        fragShader.destroy();
    }
    bind(){
        gl.useProgram(this.prog);
    }
    destroy(){
        gl.deleteProgram(this.prog);
    }
}

顶点着色器:

attribute vec3 position; 
attribute vec3 normal; 
attribute vec3 color; 

varying vec3 vColor;

void main(){    
    gl_Position = vec4(position, 1.0);  
    vColor = color; 
}   

片段着色器:

precision mediump float;    

varying vec3 vColor;    

void main(){    
    gl_FragColor = vec4(vColor, 1.0);   
}

如果您能提供解决此问题的任何帮助或提示,我将不胜感激。

在你的 draw.js 文件的底部,你销毁了 meshprog:

mesh.destroy();
prog.destroy();

In JavaScript window.requestAnimationFrame(onFrame); 将在调用那些 destroy 方法之后实际调用 onFrame。因此,在执行 onFrame 时,meshprog 都不存在。我建议阅读更多关于 requestAnimationFrame 的内容,这样你就可以稍后销毁它们(即在你的动画循环停止后 运行)。

您可以通过删除那些 destroy 行来验证行为,它会呈现良好。