/* Copyright (C) 2007  Mikko Sysikaski <mikko.sysikaski@gmail.com>
 * This program is free software distributed under GNU General Public License
 * version 3 or (at your option) any later version.
 * No warranty of any kind is provided. See the accompanying file COPYING for details.
 */

#include <GL/glu.h>
#include <GL/gl.h>
#include <cstdlib>
#include <algorithm>
#include "glscreen.h"
#include "gameapp.h"
#include "renderer.h"

bool GLScreen::m_2D;
SDL_Surface* GLScreen::m_screen;
std::vector<Coord<int> > GLScreen::m_resolutions;

int Mutex2D::used;

void GLScreen::init(int w, int h, bool fullscreen)
{
	SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO);
	doInit(w, h, fullscreen);
}
void GLScreen::init(bool fullscreen)
{
	SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK);
	doInit(640, 480, fullscreen);
}
void GLScreen::doInit(int w, int h, bool fullscreen)
{
	SDL_WM_SetCaption("Kuula", 0);
	
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
//	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
//	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	
	resize(w, h, fullscreen);
	
	int dbuf, depth, stencil, alpha, r, g, b;
	SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dbuf);
	SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depth);
	SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &stencil);
	SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &alpha);
	SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &r);
	SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &g);
	SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &b);
	printf("GL attributes: double: %i, depth: %i, stencil: %i, alpha: %i, r: %i, g: %i, b: %i\n",
		   dbuf, depth, stencil, alpha, r, g, b);

	// list acceptable resolutions
	SDL_Rect** modes = SDL_ListModes(0, SDL_OPENGL | SDL_FULLSCREEN);
	for(int i=0; modes[i]; ++i) {
		Coord<int> mode(modes[i]->w, modes[i]->h);
		m_resolutions.push_back(mode);
	}
}

void GLScreen::resize(int w, int h, bool fullscreen)
{
	m_screen = SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE | (fullscreen?SDL_FULLSCREEN:0));
	if (!m_screen) {
		fprintf(stderr, "Fatal error: couldn't initialize SDL screen!\n");
		exit(200);
	}
	glViewport(0, 0, w, h);

	GameApp::getInstance().getRenderer().resetGL();
}

void GLScreen::set2D()
{
	m_2D = 1;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW);
}
void GLScreen::set3D()
{
	m_2D = 0;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45, double(m_screen->w)/m_screen->h, 0.1, 1000);
	glMatrixMode(GL_MODELVIEW);
}
