
#include "Video.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <SDL.h>
#include <iostream>
using namespace std;

Video::Video()
{
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER))
    {
        cerr << "SDL_Init() returned error!" << endl;
        exit(3);
    }

    const SDL_VideoInfo * vidInfo = SDL_GetVideoInfo();
    if (vidInfo != NULL)
    {
        m_defaultWidth = vidInfo->current_w;
        m_defaultHeight = vidInfo->current_h;
    }
    else
    {
        cerr << "Warning: SDL_GetVideoInfo() returned NULL!" << endl;
        m_defaultWidth = 1024;
        m_defaultHeight = 768;
    }

    m_surface = NULL;
    m_inputGrabbed = false;
    m_width = 0;
    m_height = 0;
}

void Video::start(int width, int height, bool fullscreen, bool grab_input,
        int samples)
{
    if (m_surface == NULL)
    {
        if (width == 0)
            width = m_defaultWidth;
        if (height == 0)
            height = m_defaultHeight;
        int flags = SDL_HWSURFACE | SDL_OPENGL;
        if (fullscreen)
            flags |= SDL_FULLSCREEN;

        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
        if (samples > 1)
        {
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, samples);
        }
        m_surface = SDL_SetVideoMode(width, height, 32, flags);
        if (grab_input)
        {
            SDL_ShowCursor(SDL_DISABLE);
            SDL_WM_GrabInput(SDL_GRAB_ON);
        }
        m_inputGrabbed = grab_input;
        m_fullscreen = fullscreen;
        m_width = width;
        m_height = height;

        glEnable(GL_DEPTH_TEST);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        glShadeModel(GL_SMOOTH);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(60.0, (double) width / (double) height, 0.01, 10000.0);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    }
}

void Video::stop()
{
    if (m_surface != NULL)
    {
        SDL_FreeSurface(m_surface);
        m_surface = NULL;
    }
}
