/*
 * A demonstration of using the VGL functions.
 */
#include <v_lib.h>

GLfloat a = 0, b = 0;

static void rect(void)
{
	glBegin(GL_QUADS);
		glColor4f(1,1,0,.5f);
		glVertex2f(-1,-1);
		glColor4f(0,1,1,.5f);
		glVertex2f(-1,1);
		glColor4f(1,0,1,.5f);
		glVertex2f(1,1);
		glColor4f(1,1,1,.5f);
		glVertex2f(1,-1);
	glEnd();
}
		
static void redraw()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glScalef(.5f,.5f,.5f);
	glRotatef(a,1,0,0);
	glRotatef(b,0,1,0);

	rect();
	glRotatef(90,1,0,0);
	rect();
	glRotatef(90,0,1,0);
	rect();
	
	glDisable(GL_DEPTH_TEST);
	glLoadIdentity();
	glScalef(0.1f,0.1f,0.1f);
	glTranslatef(-13,-9.7f,0);
	glScalef(1,2,1);
/*
	glColor3f(0,0,0.4f);
	glPushMatrix();
	vglPuts("Нажмите F10 для выхода");
	glPopMatrix();
	glTranslatef(0.05f,0.05f,0);
	glColor3f(0,0,0.7f);
	glPushMatrix();
	vglPuts("Нажмите F10 для выхода");
	glPopMatrix();
	glTranslatef(0.05f,0.05f,0);
	glColor3f(1,1,1);
	*/
	vglPuts("Нажмите F10 для выхода");
	glEnable(GL_DEPTH_TEST);

	vglSwapBuffers();
	a+=1;
	b+=.2f;
}

/*
static void resize( unsigned int width, unsigned int height )
{
   printf("Resize event\n");
   glViewport( 0, 0, width, height );
   glMatrixMode( GL_PROJECTION );
   glLoadIdentity();
   glOrtho( -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 );
}
*/

static void event_loop()
{
	int done=0;
	input_record_t event;
	while(!done)
	{
		if(!vglPending())
		{
			redraw();
			timeDelay(30);
			continue;
		}
		vglNextEvent(&event);
		switch(event.event)
		{
			case ev_key_down:
				printf("KeyPress: %s (%d:%d = '%c')\n",
					keycodeGetName(event.first_code),
					event.first_code,
					event.second_code, event.second_code);
				if(event.first_code==key_f10)
					done=1;
				break;
			case ev_key_up:
				printf("KeyRelease: %s\n",
					keycodeGetName(event.first_code));
				break;
			case ev_mouse_move:
				printf("Mouse moved: (%d,%d)\n",
					event.first_code,
					event.second_code);
				a+=0.1f * event.first_code;
				b+=0.1f * event.second_code;
				break;
			default:
				break;
		}
	}
}

int main()
{
	void_p win;
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	/* win = vglCreateWindow("OpenGL test",0,0,400,300); */
	win = vglCreateFullscreenWindow("OpenGL test",640,480,16,0);
	if(!win)
		return -1;
	
	vglCapturePointer(true);
	
	{
		vhandle_t fnt=vglLoadBGIFont("../../samples/media/bgi-fonts/arus.chr",false);
		vglSelectFont(fnt);
		vglDestroyFont(fnt);
	}
	if(!win)
		return -1;
		
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1.333,1.333,-1,1,-1,1);
	glShadeModel(GL_SMOOTH);
	glEnable(GL_DEPTH_TEST);
	glClearColor(0,0,0.5f,1);
	glClear(GL_COLOR_BUFFER_BIT);

	event_loop();

	
	vglDestroyWindow(win);
	
	memPrintStats();
	return 0;
}
