WebGL: drawArrays: attribs not setup correctly

2019-07-24 17:01发布

Here's my vertex shader:

    attribute vec3 aVertexPosition;
    attribute vec4 aVertexColor;
    attribute float type;

    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;

    varying vec4 vColor;

    void main(void) {
      gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
      vColor = aVertexColor;
      if(type > 0.0) {

      } else {

      }
    }

What I want to do is pretty simple, just capture a float value named type and use it for logic operates.

The problem is, when I try to use it in Javascript, the error comes:

shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "type");
gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);


WebGL: INVALID_OPERATION: drawArrays: attribs not setup correctly main.js:253
WebGL: INVALID_OPERATION: drawArrays: attribs not setup correctly main.js:267
WebGL: INVALID_OPERATION: drawElements: attribs not setup correctly 

The output of getAttribLocation is meaningful, all of them are equal greater than 0.

================= UPDATE ===================

Here's my whole project code:

https://gist.github.com/royguo/5873503

Explanation:

  • index.html Shaders script are here.
  • main.js Start the WebGL application and draw scene.
  • shaders.js Load shaders and bind attributes.
  • buffers.js Init vertex and color buffers.
  • utils.js Common used utils.

1条回答
甜甜的少女心
2楼-- · 2019-07-24 17:08

Here is a link to a gist with the files I updated to get the type attribute working.

If you search for //ADDED CODE you should be able to view every change I had to make to get it working.

In addition to enabling the objectTypeAttribute you have to create an array buffer for each object you are drawing:

  triangleObjectTypeBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleObjectTypeBuffer);
  objectTypes = [
    1.0, 1.0, 0.0
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(objectTypes), gl.STATIC_DRAW);
  triangleObjectTypeBuffer.itemSize = 1;
  triangleObjectTypeBuffer.numItems = 3;

And bind that array buffer for each object before you draw the object:

  gl.bindBuffer(gl.ARRAY_BUFFER, triangleObjectTypeBuffer);
  gl.vertexAttribPointer(shaderProgram.objectTypeAttribute, triangleObjectTypeBuffer.itemSize, gl.FLOAT, false, 0, 0);

You probably already tried this and accidentally went wrong somewhere along the way.

查看更多
登录 后发表回答