1
votes

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
Did you try using a float instead of vec2? By the way, using branches that depend on attributes inside your shader is a major performance hit, I always try to use a mathematical statement instead of branches. - Marius
@Marius, Thanks! I changed vec2 to float, but the problem is still there. INVALID_OPERATION ... - WoooHaaaa
Your code looks correct, the fault has to be somewhere else. - Marius
@Marius, I don't know but it seems to be something is wrong with attribs. - WoooHaaaa
@Marius, My variable is float, can I use enableVertexAttribArray ? - WoooHaaaa

1 Answers

1
votes

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.