Search code examples
c++copenglsdlglew

OpenGL/SDL - Can't make line load


I've been trying to make a code so that a line appears across the window. I've been using c and opengl/sdl. But for some reason the code is not making a line in the window. I can't figure out what I'm doing wrong:

#include <SDL.h> 
#include <stdio.h>
#include <GL/glew.h> 
#include <SDL_opengl.h>  


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

    SDL_Window* window;


    SDL_Init(SDL_INIT_EVERYTHING);


    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
    SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);;


    window = SDL_CreateWindow("Breakout!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 400, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN);

    SDL_GLContext context = SDL_GL_CreateContext(window);
    SDL_GL_MakeCurrent(window, context);


    SDL_GL_SetSwapInterval(1);

    glClearColor(1.f, 1.f, 1.f, 1.f);

    glViewport(0, 0, 800, 400);
    
    glShadeModel(GL_SMOOTH);

    glMatrixMode(GL_PROJECTION);

    glLoadIdentity();

    glDisable(GL_DEPTH_TEST);

    

    // Check that the window was successfully created
    if (window == NULL) {
        // In the case window was not made
        printf("Could not create window: %s\n", SDL_GetError());
        return 1;
    }


    SDL_Event windowEvent;

    while (1)
    {
        
        

        // Get the next event
        SDL_Event event;


        if (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                // Break out of the loop on quit
                break;
            }

            
        }



        //Rendering to the screen
        glClear(GL_COLOR_BUFFER_BIT);


        glOrtho(0.0, 800, 400, 0.0, -1, 1);   // setup a 10x10x2 viewing world

        glColor4ub(255, 0, 0, 255);

        glBegin(GL_LINES);

        glVertex2f(0, 0);
        glVertex2f(800, 400);
    
        glEnd();

        //Render
        SDL_GL_SwapWindow(window);

    }

    // Close and destroy the window
    SDL_DestroyWindow(window);
    SDL_GL_DeleteContext(window);


    // Clean up
    SDL_Quit();  
    return 0;
}

Solution

  • glOrtho doesn't just set a matrix. The function creates an orthographic projection matrix and multiplies the current matrix with the new matrix.

    If you call glOrtho in the application loop, you must first load the identity matrix with glLoadIdentity:

    glLoadIdentity();
    glOrtho(0.0, 800, 400, 0.0, -1, 1);