#include <v_lib.h>

static vboolean	Animate = true;

#define	MAXPOINTS	16000
vec3_t	points[MAXPOINTS];
u32_t	num_points = 0;

static GLfloat rotmult = 1;
static GLfloat Xrot = 0, Yrot = 0, Zrot = 0.0;

static void DrawObject(void)
{
	u32_t i;
	glPointSize(3);
	glEnable(GL_POINT_SMOOTH);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glColor4f(1,1,1,.8f);
	
	glBegin(GL_POINTS);
		for(i=0;i<num_points;i++)
			VGL_VERTEX3V(points[i]);
	glEnd();
}

static void Display( void )
{
	glClear(GL_COLOR_BUFFER_BIT);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	/*
	glOrtho(-1,1,-1,1,-1,1);
	*/
	glOrtho(-1.3,1.3,-1,1,-1,1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	glRotatef(Xrot * rotmult, 1.0, 0.0, 0.0);
	glRotatef(Yrot * rotmult, 0.0, 1.0, 0.0);
	glRotatef(Zrot * rotmult, 0.0, 0.0, 1.0);

	glTranslatef(-0.5f,-0.5f,-0.5f);

	DrawObject();


	if(Animate)
	{
		Xrot += .2f;
		Yrot += .3f;
	}
	
	vglSwapBuffers();
}

static void handle_keydown(keycode_t entry,vboolean down)
{
	vec_t step = 3.0;
	switch(entry)
	{
		case key_up:
			if(!down)
				break;
			Xrot += step;
			break;
		case key_down:
			if(!down)
				break;
			Xrot -= step;
			break;
		case key_left:
			if(!down)
				break;
			Yrot += step;
			break;
		case key_right:
			if(!down)
				break;
			Yrot -= step;
			break;
		case key_space:
			if(!down)
				break;
			if(Animate)
			{
				Xrot = Yrot = Zrot = 0;
			}
			Animate = !Animate;
			break;
		case key_left_control:
			rotmult = (down) ? 10 : 1;
			break;
		case key_f10:
		case key_escape:
			vglDestroyWindow(vglGetCurrentWindow());
			exit(0);
		default:
			break;
	}
}

vboolean parse_one_line(vhandle_t in,vec3_t out)
{
	int i;
	for(i=0;lexNext(in);)
	{
		if(lexLast(in)[0] == ';')
			continue;
		out[i] = atof(lexLast(in));
		if(++i == 3)
			break;
	}
	return i==3;
}

int main()
{
	vhandle_t in;
	input_record_t ev;
	
	in = lexParseFile("out",";");
	if(!in)
		return -1;
	
	num_points=0;
	
	while(parse_one_line(in,points[num_points]))
		if(++num_points == MAXPOINTS)
			break;
	
	lexDestroy(in);

	/*
	vglCreateWindow("CSV viewer",0,0,512,512);
	*/

	vglCreateFullscreenWindow("CSV viewer",0,0,0,0);

	for(;;)
	{
		while(vglPending())
		{
			vglNextEvent(&ev);
			if(ev.event == ev_key_down)
				handle_keydown(ev.first_code,true);
			else
				handle_keydown(ev.first_code,false);
		}
		Display();
		timeDelay(10); /* reduce CPU & accel overhead */
	}
	
	return 0;
}
