#include <v_lib.h>

#define	N	1024
vec3_t	pts[N];

vec_t alpha = 0, betta = 0;

V_LOCAL vboolean init()
{
	int i;
	assert(vglInit("test (press ESC for exit)",0,0,800,800,
		false,false,
		false,false,false));
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1,1,-1,1,-1,1);
	glMatrixMode(GL_MODELVIEW);

	for(i = 0;i < N;i++)
	{
		GLfloat t, p;
		t = (GLfloat)rand() / RAND_MAX;
		p = (GLfloat)rand() / RAND_MAX;
		t *= M_PI;
		p *= 2 * M_PI;
		vert[i][0] = (GLfloat)(sin(t) * cos(p));
		vert[i][1] = (GLfloat)(sin(t) * sin(p));
		vert[i][2] = (GLfloat)(cos(t));
	}
	
	return true;
}

vec3_t	vert[N];

static GLfloat alpha = 0, beta = 0;

static void draw()
{
	int i;
	glClear(GL_COLOR_BUFFER_BIT);
	glLoadIdentity();
	glScalef(0.7f,0.7f,0.7f);
	glRotatef(alpha,1,0,0);
	glRotatef(beta,0,1,0);
	glLineWidth(1.4f);
	glBegin(GL_LINES);
		for(i = 0;i < N;i++)
		{
			glColor4f(1,1,0,0.2f);
			glVertex3f(0,0,0);
			glColor4f(1,1,1,0.4f);
			glVertex3fv(vert[i]);
		}
	glEnd();
	glLineWidth(5.0f);
	glBegin(GL_LINES);
		glColor4f(1,.5,.5,.5f);
		glVertex3f(0,0,0);
		glVertex3f(1,0,0);
		glColor4f(.5f,1,.5f,.5f);
		glVertex3f(0,0,0);
		glVertex3f(0,1,0);
		glColor4f(.5f,.5f,1,.5f);
		glVertex3f(0,0,0);
		glVertex3f(0,0,1);
	glEnd();
	agSwap();
}

V_LOCAL void shutdown()
{
	vglDestroy();
}

V_LOCAL void draw_scene()
{
	glClearColor(0,0.5f,0.5f,0);
	glClear(GL_COLOR_BUFFER_BIT);

	glPushMatrix();

	glRotatef(alpha,1,0,0);
	glRotatef(betta,0,1,0);

    draw();

	glPopMatrix();

    vglSwap();

	alpha = (vec_t)fmod(alpha + 0.5f,360);
	betta = (vec_t)fmod(betta + 0.2f,360);
}

/*
 * Event loop
 */
V_LOCAL void main_loop()
{
	vboolean done = false;
	ui_event_t ev;
	while(!done)
	{
		while(uiPending())
		{
			uiNextEvent(&ev);
			switch(ev.type)
			{
				case ui_wm_event:
					if(ev.configure.wm_event == ui_wm_close)
						 done = true;
					break;
				case ui_key_event:
					if(ev.key.scan == sc_escape && !ev.key.press)
						 done = true;
					break;
				default:
					break;
			}
		}
		draw_scene();
		timeDelay(30);
	}
}

int main()
{
	logStartConsoleLog();
	logUpperLevel(LOG_TRACE);
	!init()
    	return -1;
	main_loop();
	shutdown();
	memPrintStats();
	return 0;
}
