PDA

View Full Version : simple example - attempt to access out of range vertices err



saruniitr
10-15-2012, 02:34 AM
Hi Everyone,

I am getting the following error in a very simple example shown below:

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




<script id='vshader' type='x-shader'>
attribute vec2 aVertexPosition;
void main() {
gl_Position = vec4(aVertexPosition, 0, 1);
}
</script>
<script id='fshader' type='x-shader'>
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 0, 1);
}
</script>

var c = document.getElementById('cv');
var gl = c.getContext('experimental-webgl');

var vertexPosBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPosBuffer);
var vertices = [-1, -1, 1, -1, -1, 1, 1, 1];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
vertexPosBuffer.itemSize = 2;
vertexPosBuffer.numItems = 4;

var vertexColorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); // adding this line causes the error
var colors = [1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1];
// gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW); // enabling this line removes the error but still nothing is rendered

var vs = document.getElementById('vshader').textContent;
var fs = document.getElementById('fshader').textContent;
var program = createProgram(vs,fs);
gl.useProgram(program);

program.vertexPosAttrib = gl.getAttribLocation(program, 'aVertexPosition');
gl.enableVertexAttribArray(program.vertexPosAttrib );
gl.vertexAttribPointer(program.vertexPosAttrib, vertexPosBuffer.itemSize, gl.FLOAT, false, 0, 0);

gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexPosBuffer.numItems);


There are no compile/link errors with the shaders.
Without color buffer related code I can see the red rectangle.
I am using Google Chrome, similar behaviour observed in Firefox.

Could someone please take a look and let me know what am I missing here?

best regards
Arun

greggman
10-15-2012, 10:30 AM
You only setup your position buffer, then setup the color buffer, then your call to gl.vertexAttribPointer is using your color buffer (since that's the last buffer bound) but you never init your color buffer (you have gl.bufferData for the color buffer commented out)


gl.vertexAttribPointer uses the buffer you last bound with gl.bindBuffer(gl.ARRAY_BUFFER, ...)

saruniitr
10-15-2012, 02:29 PM
Thanks Greggman, that helped to resolve the issue.

br
Arun