我正在尝试生成一个三角形,它将被递归细分。我在每次递归后将点推到数组。退出递归后,我正在渲染三角形。但是我收到了以下警告
[.WebGLRenderingContext-008E98C8] GL错误:GL_INVALID_OPERATION:glDrawArrays:尝试访问属性0中超出范围的顶点
这是我在javascript中的代码
var canvas=document.getElementById("painter");
var gl;
var points = [];
var NumTimesToSubdivide = 5;
try
{
gl=canvas.getContext("experimental-webgl");
}catch(e)
{
alert("WebGL not supported");
}
// Create Shaders
var shader_vertex_source="\n\
attribute vec4 vPosition;\n\
void main(void)\n\
{\n\
gl_Position=vPosition;\n\
}\n\
";
var shader_fragment_source="\n\
precision mediump float;\n\
void main(void)\n\
{\n\
gl_FragColor=vec4(1.0,0,0.0,1);\n\
}\n\
";
var vertices = [
[-1, -1],
[0, 1],
[1, -1]
];
divideTriangle( vertices[0], vertices[1], vertices[2],
NumTimesToSubdivide);
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.0, .5, .5, 1.0 );
var get_shader=function(shadersource,shadertype)
{
var shader=gl.createShader(shadertype);
gl.shaderSource(shader,shadersource);
gl.compileShader(shader);
return shader;
}
var vertex_shader=get_shader(shader_vertex_source,gl.VERTEX_SHADER);
var fragment_shader=get_shader(shader_fragment_source,gl.FRAGMENT_SHADER);
var program=gl.createProgram();
gl.attachShader(program,vertex_shader);
gl.attachShader(program,fragment_shader);
gl.linkProgram(program);
gl.useProgram(program);
var buffer=gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,buffer);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(points),gl.STATIC_DRAW);
var position=gl.getAttribLocation(program,"vPosition");
gl.vertexAttribPointer(position,2,gl.FLOAT,false,0,0);
gl.enableVertexAttribArray(position);
console.log(points);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.POINTS,0,points.length);
function triangle( a, b, c )
{
points.push( a, b, c );
}
function divideTriangle( a, b, c, count )
{
// check for end of recursion
if ( count === 0 ) {
// console.log(a[0]+" \t"+b[0]+"\n");
triangle( a[0], a[1], b[0] );
triangle( b[1], c[0], c[1] );
}
else {
//bisect the sides
var ab = [(a[0]+b[0])/2,(a[1]+b[1])/2];
var ac = [(a[0]+c[0])/2,(a[1]+c[1])/2];
var bc = [(b[0]+c[0])/2,(b[1]+c[1])/2];
// console.log(ac[0]+" "+ac[1]+" "+"\n" )
--count;
// three new triangles
divideTriangle( a, ab, ac, count );
divideTriangle( c, ac, bc, count );
divideTriangle( b, bc, ab, count );
}
}
以下是我正在使用的jsfiddle。任何人都可以帮我找到问题吗?