What is wrong with this opengl code


#1

Hi I just started learning sdl and opengl and I’m migrating all the code in my book programming linux games from sdl1 to sdl2. Can anyone tell me why the code that follows is just creating a blank screen and not a shape? Thanks.

#include<SDL2/SDL.h>
#include<GL/gl.h>
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{

    (void)(argc);
    (void)(argv);

    SDL_Window * window;

/*Inintialize SDL as usual */
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        printf("Error: %s\n", SDL_GetError());
        return 1;
    }

    atexit(SDL_Quit);

/* Enable OpenGL double buffering */
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

/*Set the colour depth (16 bit 565). */
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);

/* Create a 640 x 480, 16 bit window with support for
   Open GL rendering. Unfortunately we won't know whether
   this is hardware accelerated. */
    window = SDL_CreateWindow("SDL2 Window",0,0,640,480,SDL_WINDOW_OPENGL);
    if(window=NULL){printf("Error Creating Window!%s\n",SDL_GetError());}

/* We can now use any OpenGL rendering commands */

    glClearColor(0.0,0.0,0.0,0.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0,1.0,1.0);
    glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0);
    glBegin(GL_POLYGON);
    glVertex2f(-0.5,-0.5);
    glVertex2f(-0.5,0.5);
    glVertex2f(0.5,0.5);
    glVertex2f(0.5,-0.5);
    glEnd();
    glFlush();

/*Display the back buffer to the screen */
    SDL_GL_SwapWindow(window);

/*Wait a few seconds. */
    SDL_Delay(10000);

    return 0;

}

#2

Just play with it a bit and see what you find. You can figure this out.

I’d recommend that you start with a working SDL2 example and then compare with yours.

A few thoughts for you to check into.

  1. Is your clearcolor and clear working?
  2. Looks like you’re specifying your polygon clockwise (GL_CW), however the default glFrontFace() setting is GL_CCW. Try disabling GL_CULL_FACE or flip front face to GL_CW.
  3. I’m no SDL guru, but it looks like you’re creating an compatibility context here. IIRC from the old fixed-function pipeline days, you probably want to disable GL_LIGHTING so that your vertex colors are used as-is.
  4. Are you sure you want a color format of 5/6/5? 8/8/8 is more common nowadays.