kovac
kovac

Reputation: 5389

Drawing a square using OpenGL ES glDrawElements is not working

I'm trying to draw a square on Android using the code below:

void drawSquare()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    GLfloat vertices[] =
    {
        -0.5f, -0.5f,
        0.5f, -0.5f,
        0.5f, 0.5f,
        -0.5f, 0.5f
    };

    GLubyte indices[] = { 0, 1, 2, 3 };

    glVertexPointer(2, GL_FLOAT, 0, vertices);
    glDrawElements(GL_TRIANGLES, 4, GL_UNSIGNED_BYTE, indices);
}

Before, I call the above method I set up the display like:

bool initDisplay()
{
    const EGLint attribs[] =
    {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_BLUE_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_RED_SIZE, 8,
        EGL_NONE
    };

    EGLint format;
    EGLint numConfigs;
    EGLConfig config;

    EGLDisplay mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    eglInitialize(mDisplay, 0, 0);
    eglChooseConfig(mDisplay, attribs, &config, 1, &numConfigs);
    eglGetConfigAttrib(mDisplay, config, EGL_NATIVE_VISUAL_ID, &format);
    ANativeWindow_setBuffersGeometry(mApp->window, 0, 0, format);

    EGLSurface mSurface = eglCreateWindowSurface(mDisplay, config, mApp->window, NULL);
    EGLContext mContext = eglCreateContext(mDisplay, config, NULL, NULL);

    eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
    eglQuerySurface(mDisplay, mSurface, EGL_WIDTH, &mWidth);
    eglQuerySurface(mDisplay, mSurface, EGL_HEIGHT, &mHeight);

    return true;
}

And setup OpenGL like:

bool initGL()
{
    glDisable(GL_DITHER);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
    glClearColor(0.f, 0.f, 0.f, 1.0f);
    glShadeModel(GL_SMOOTH);

    glViewport(0, 0, mWidth, mHeight);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    return true;
}

However, I do not see the square on the screen. Just see a black screen. Thanks in advance for your help.

Upvotes: 1

Views: 871

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

The indices

GLubyte indices[] = { 0, 1, 2, 3 };

don't specify a triangle Primitive. The specify a quad. Use the primitive type GL_QUADS respectively GL_TRIANGLE_FAN:

GLubyte indices[] = { 0, 1, 2, 3 };

glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, indices);

or form the square by 2 triangles with the indices (0 - 1 - 2) and (0 - 2 - 3):

3           2
 +------+  +
 |     / / |
 |   / /   |
 | / /     |
 + +-------+
0           1
GLubyte indices[] = { 0, 1, 2, 0, 2, 3 };

glVertexPointer(2, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices);

Upvotes: 1

Related Questions