Skip to content
Advertisement

Using mat4 attribute in WebGL2

I am trying to pass a 4×4 matrix as an attribute to WebGL2 vertex shader. After following closely this SO answer, I am stuck with wrapping my head around why I can’t successfully render and get a glDrawArrays: attempt to access out of range vertices in attribute 0 error in my console.

It is my understanding that mat4 is represented as 4 times vec4 in WebGL. When I query a_modelMatrix position on the GPU I can see it occupies location from 0 to 3, so this seems okay. I break up the assignments into 4 parts like this:

JavaScript

But still get an error.

Here is my code:

JavaScript
JavaScript

Advertisement

Answer

You must specify 1 attribute for each vertex coordinate. The vertices cannot share 1 matrix attribute. Each vertex coordinate must have its own model matrix attribute:

JavaScript

JavaScript
JavaScript

If you use WebGL 1.0, I recommend to use a Uniform variable instead of the matrix attribute. A uniform is a global Shader variable:

JavaScript
JavaScript

JavaScript
JavaScript

However, If you create a WebGL 2.0 context:

const gl = canvas.getContext('webgl')

JavaScript

and a Vertex Array Object:

JavaScript

You can use Instancing. The matix attribute is an instance attribute:

JavaScript

gl.drawArrays(gl.LINE_LOOP, 0, 3)

JavaScript

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement