## Switching from Triangles to Indexed Vertices in WebGL

From: andrew cooke <andrew@...>

Date: Tue, 13 Mar 2012 00:19:37 -0300

In WebGL you can draw data in two ways, calling drawArrays() or
drawElements().

The first of these expects you to load a buffer with a series of triangles,
described by the coordinates of their vertices.  The triangles can be in a
strip or fan, to save repeating some points, but even so, for a complex shape,
you start to need to repeat points.

So it can be more efficient to use the second approach, which uses two
buffers: the first contains *unique* vertices and the second contains indices
(think pointers) into the first to describe the triangles.  In this way, no
vertices are repeated (the issue is not so much memory, but avoiding un-needed
calls to the vertex shader, I think).

And you can find descriptions of the two approaches on the web, but it's not
clear exactly what you do to move between the two.  So here's what is
necessary:

1 - instead of storing triangle vertices in an ARRAY_BUFFER, store the unique
vertices.

2 - allocate and load an ELEMENT_ARRAY_BUFFER for the indices.

3 - don't change the use of the vertex attribute on the shader (you still
need to enable it and associate it with the ARRAY_BUFFER).

4 - bind to the ELEMENT_ARRAY_BUFFER and call drawElements.

I'm not sure how helpful the following code will be because a lot is hidden
behind my support library, but the two versions are present here (drawArrays
is commented out):

vertices = wgl.newBuffer(gl.ARRAY_BUFFER),
indices = wgl.newBuffer(gl.ELEMENT_ARRAY_BUFFER),
vertex = program.getAttribute('vertex'),

draw = function () {
wgl.clear();
//            vertices.bindIn(vertex.attrIn(
//                wgl.bindTriangleVertices,
//                wgl.drawTriangleVertices
//            ));
vertices.bindIn(vertex.attrIn(wgl.bindTriangleVertices));
indices.bindIn(vertex.attrIn(wgl.drawTriangleIndices));
};

Andrew