/***************************************************************************/
/** @file       game_gl.cpp
    @brief      
    @author     shom
****************************************************************************/

#include "pch.h"

#include "game.h"

#include "glut/glut.h"

#include "window_def.h"
#include "window.h"

#include "service/service_input.h"
#include "graphic/render_gl.h"
#include "service/service_frontend.h"
#include "service/service_sequence.h"

#include "core/input/raw/input_raw_mouse.h"


/***************************************************************************
	game( namespace )
****************************************************************************/

namespace game
{
	u32 tm_start = get_time();
	void	CallbackIdle()
	{
		const u32 tm_start_tmp = tm_start;
		const u32 tm_exec_elapsed = get_time() - tm_start;

		DEBUG_OUTPUT_FORMAT( _T( "%d\n" ), tm_start_tmp );
		UNUSED( tm_start_tmp );
		DEBUG_OUTPUT_FORMAT( _T( "%d\n" ), tm_exec_elapsed );

		if( 1000 / 60 > tm_exec_elapsed )
		{
			return;
		}

		glutPostRedisplay();

		tm_start = get_time();
	}
	
	void	CallbackKeyboard( unsigned char key, int x, int y )
	{
		UNUSED( x );
		UNUSED( y );

		switch( key )
		{
			case '\033'/*ESC*/: exit(0); break;

			default: break;
		}
	}

	void	CallbackWindowResizing( int width, int height )
	{
		window::SetClientWidth( width );
		window::SetClientHeight( height );
	}
}

void	game::GameInit( int argc, char *argv[] )
{
	glutInit( &argc, argv );
	glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE/*double buffering*/ );

	using namespace window;
	glutInitWindowPosition( GetWindowPosX(), GetWindowPosY() );
	glutInitWindowSize( GetClientWidth(), GetClientHeight() );

	glutCreateWindow( window_def::sc_sz_wnd_name );

	///--
/**---------------------------------------------------------------------**/
#define GLOBAL_VARIABLES__PCH_mb( _class, _instance, _args ) \
	_instance = new _class##( _args );

GLOBAL_VARIABLES__PCH_list
#undef GLOBAL_VARIABLES__PCH_mb
/**---------------------------------------------------------------------**/

	g_p_service_input->Initialize();
	g_p_render->Initialize();
	g_p_service_sequence->Initialize();
	///--

	///--
	glutIdleFunc( game::CallbackIdle );
	glutKeyboardFunc( game::CallbackKeyboard );
	glutReshapeFunc( game::CallbackWindowResizing );

	glutDisplayFunc( crender::CallbackRender );
	glutMouseFunc( cinput_raw_mouse::CallbackInput );
	///--
}

void	game::GameFin()
{
	///--
	g_p_render->Finalize();

/**---------------------------------------------------------------------**/
#define GLOBAL_VARIABLES__PCH_mb( _1, _instance, _3 ) \
	my_safe_del( _instance );

GLOBAL_VARIABLES__PCH_list
#undef GLOBAL_VARIABLES__PCH_mb
/**---------------------------------------------------------------------**/
	///--
}

void	game::GameLoop()
{
	glutMainLoop();
}

