#define NO_SDL_GLEXT

#include <GL/glew.h>
#include <SDL/SDL_OpenGL.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#include "project_init_gl.h"
#include "project_shaders.h"
#include "project_screen.h"

bool HasOpenGL2;

typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALFARPROC)( int );
PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = 0;

void setVSync(int interval)
{
  const char *extensions = (const char*)glGetString( GL_EXTENSIONS );

  if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 )
    return; // Error: WGL_EXT_swap_control extension not supported on your computer.\n");
  else
  {
    wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress( "wglSwapIntervalEXT" );

    if( wglSwapIntervalEXT )
      wglSwapIntervalEXT(interval);
  }
}

void InitFuckingOpenGL()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glActiveTextureARB(GL_TEXTURE0);
	glDisable(GL_TEXTURE_1D);
	glDisable(GL_TEXTURE_2D);
	glActiveTextureARB(GL_TEXTURE1);
	glDisable(GL_TEXTURE_1D);
	glDisable(GL_TEXTURE_2D);
	glActiveTextureARB(GL_TEXTURE2);
	glDisable(GL_TEXTURE_1D);
	glDisable(GL_TEXTURE_2D);

	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);

	glActiveTextureARB(GL_TEXTURE0);
}

void InitGL_Basics()
{
    glViewport(0, 0, ScreenWidth, ScreenHeight);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, ScreenWidth/ ScreenHeight, gl_near, gl_far);
    glMatrixMode(GL_MODELVIEW);
}

void InitGL_Shaders()
{
	glewInit();
	if (glewIsSupported("GL_VERSION_2_0"))
	{
		HasOpenGL2 = true;
		printf("Ready for OpenGL 2.0\n");
	}
	else if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)
	{
		HasOpenGL2 = false;
		printf("OpenGL 2.0 not supported, using ARB extensions\n");
	}
	else
	{
		printf("No shaders here..\n");
		int ficken = _getch();
		if (ficken==32)
			HasOpenGL2 = false;
		else
			exit(1);
	}

	LoadShaders();
	InitPrograms();
}

void InitGL()
{
	InitGL_Basics();
	InitGL_Shaders();
}
