Ramesh Singh
Ramesh Singh

Reputation: 41

Why cant we draw a square like triangle?

I found the code in android documentation.

public class Square {

private FloatBuffer vertexBuffer;
private ShortBuffer drawListBuffer;

// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float squareCoords[] = {
        -0.5f,  0.5f, 0.0f,   // top left
        -0.5f, -0.5f, 0.0f,   // bottom left
         0.5f, -0.5f, 0.0f,   // bottom right
         0.5f,  0.5f, 0.0f }; // top right

private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices

public Square() {
    // initialize vertex byte buffer for shape coordinates
    ByteBuffer bb = ByteBuffer.allocateDirect(
    // (# of coordinate values * 4 bytes per float)
            squareCoords.length * 4);
    bb.order(ByteOrder.nativeOrder());
    vertexBuffer = bb.asFloatBuffer();
    vertexBuffer.put(squareCoords);
    vertexBuffer.position(0);

    // initialize byte buffer for the draw list
    ByteBuffer dlb = ByteBuffer.allocateDirect(
    // (# of coordinate values * 2 bytes per short)
            drawOrder.length * 2);
    dlb.order(ByteOrder.nativeOrder());
    drawListBuffer = dlb.asShortBuffer();
    drawListBuffer.put(drawOrder);
    drawListBuffer.position(0);
}

}

why can't we write simply the following code to accomplish the task?

private short drawOrder[] = {0,1,2,3};

Is this written so only for performance reasons or is it the only way to do this?

Upvotes: 2

Views: 118

Answers (2)

Reto Koradi
Reto Koradi

Reputation: 54572

You can use {0,1,2,3} as the content of the index buffer. Instead of using GL_TRIANGLES as the primitive type, you'll have to specify GL_TRIANGLE_FAN as the first argument of glDrawElements() instead.

Or, if you swap the last two indices to make it {0,1,3,2}, you can draw them with the more commonly used GL_TRIANGLE_STRIP primitive type.

Both GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN are used to draw sets of connected triangles.

In fact, if your indices form just a simple sequence, you don't need them at all. You can simply get rid of the whole drawOrder stuff, and draw your square with glDrawArrays() instead of glDrawElements():

glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

Upvotes: 2

solidpixel
solidpixel

Reputation: 12069

OpenGL ES doesn't support quads as a native primitive type; only points, lines, and triangles.

Upvotes: 1

Related Questions