WebGL:INVALID_OPERATION:vertexAttribPointer:stride或offset对类型无效

时间:2015-02-26 16:19:47

标签: opengl-es webgl opengl-es-2.0

我学习WebGL。

当我尝试绘制三个点时,我会得到一些错误,每个点都有自己的位置,大小和颜色。我尝试通过相同的缓冲区来完成它。

// To draw three points. Each of this has own location, size and color.
function start(gl){
  if(!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)){
    console.log('Failes shaders initialization.');
    return;
  }
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  if(a_Position < 0){
    console.log('The "a_Position" variable was not found in the shader code.');
    return;
  }
  var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
  if(a_PointSize < 0){
    console.log('The "a_PointSize" variable was not found in the shader code.');
    return;
  }

  var a_FragColor = gl.getAttribLocation(gl.program, 'a_FragColor');
  if(a_FragColor < 0){
    console.log('The "a_FragColor" variable was not found in the shader code.');
    return;
  }

  var data = new Float32Array([
     // a_Position, a_PointSize and a_FragColor in the each record:
    -0.25, -0.25, 10.0, 1.0, 0.0, 0.0, 1.0,
     0.00,  0.25, 20.0, 0.0, 1.0, 0.0, 1.0,
     0.25, -0.25, 30.0, 0.0, 0.0, 1.0, 1.0
  ]);

  var buffer = gl.createBuffer();
  if(!buffer){
    console.log('Can not create a buffer.');
    return;
  }
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);

  var FSIZE = data.BYTES_PER_ELEMENT;  
  var RECORDSIZE = 7;

  gl.vertexAttribPointer(a_Position,  2, gl.FLOAT, false, FSIZE * RECORDSIZE, 0);
  gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, FSIZE * RECORDSIZE, 2);
  gl.vertexAttribPointer(a_FragColor, 4, gl.FLOAT, false, FSIZE * RECORDSIZE, 3);

  gl.enableVertexAttribArray(a_Position);
  gl.enableVertexAttribArray(a_PointSize);
  gl.enableVertexAttribArray(a_FragColor);

  gl.clearColor(0.0,0.0,0.0,1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.POINTS, 0, 3);
}

但我收到了一些错误:

enter image description here

我不清楚。我做错了什么?

1 个答案:

答案 0 :(得分:6)

documentation所述,抛出INVALID_OPERATION:

  • 如果步幅或偏移不是类型的倍数。

由于您使用GL_FLOAT作为类型(大小为4个字节),因此偏移量只允许为此代码中使用的4的2和3的倍数。

                                                                           ||
                                                                           \/
gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, FSIZE * RECORDSIZE, 2);
gl.vertexAttribPointer(a_FragColor, 4, gl.FLOAT, false, FSIZE * RECORDSIZE, 3);