Making A Mesh Plane In Webgl With Triangles
I'm trying to create a triangulated plane in WebGL and I have the following code. However, when I render this in the browser, it just gives me a vertical line parallel to the y-axi
Solution 1:
There was a bug in the original answer. It should be this
varquads=200;
for (vary=0; y <= quads; ++y) {
varv= y / quads;
for (varx=0; x <= quads; ++x) {
varu= x / quads;
recipient.vertices.push( vec3(u, v, 1))
recipient.normals.push( vec3(0, 0, 1))
}
}
varrowSize= (quads + 1);
for (vary=0; y < quads; ++y) {
varrowOffset0= (y + 0) * rowSize;
varrowOffset1= (y + 1) * rowSize;
for (varx=0; x < quads; ++x) {
varoffset0= rowOffset0 + x;
varoffset1= rowOffset1 + x;
recipient.indices.push(offset0, offset0 + 1, offset1);
recipient.indices.push(offset1, offset0 + 1, offset1 + 1);
}
}
Fixed in original answer as well.
functionVec3Array() {
this.array = [];
this.push = function(v3) {
this.array.push.apply(this.array, v3);
}
}
functionvec3(x, y, z) {
return [x, y, z];
}
var recipient = {
vertices: newVec3Array(),
normals: newVec3Array(),
indices: [],
};
var quads = 200;
for (var y = 0; y <= quads; ++y) {
var v = y / quads;
for (var x = 0; x <= quads; ++x) {
var u = x / quads;
recipient.vertices.push( vec3(u, v, 1))
recipient.normals.push( vec3(0, 0, 1))
}
}
var rowSize = (quads + 1);
for (var y = 0; y < quads; ++y) {
var rowOffset0 = (y + 0) * rowSize;
var rowOffset1 = (y + 1) * rowSize;
for (var x = 0; x < quads; ++x) {
var offset0 = rowOffset0 + x;
var offset1 = rowOffset1 + x;
recipient.indices.push(offset0, offset0 + 1, offset1);
recipient.indices.push(offset1, offset0 + 1, offset1 + 1);
}
}
var gl = twgl.getWebGLContext(document.getElementById("c"));
var programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);
var arrays = {
position: recipient.vertices.array,
indices: recipient.indices,
};
var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);
functionrender(time) {
time *= 0.001;
twgl.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
var scale = 2 + (Math.sin(time) * 0.5 + 0.5) * 16;
var uniforms = {
matrix: [
scale, 0, 0, 0,
0, scale, 0, 0,
0, 0, 1, 0,
-1, -1, 0, 1,
],
};
gl.useProgram(programInfo.program);
twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
twgl.setUniforms(programInfo, uniforms);
twgl.drawBufferInfo(gl, gl.LINE_STRIP, bufferInfo);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
html, body {
width: 100%;
height: 100%;
margin: 0;
}
canvas {
width: 100%;
height: 100%;
}
<scriptsrc="https://twgljs.org/dist/twgl.min.js"></script><scriptid="vs"type="notjs">
attribute vec4 position;
uniform mat4 matrix;
voidmain() {
gl_Position = matrix * position;
}
</script><scriptid="fs"type="notjs">
precision mediump float;
voidmain() {
gl_FragColor = vec4(1,0,0,1);
}
</script><canvasid="c"></canvas>
Post a Comment for "Making A Mesh Plane In Webgl With Triangles"