#include <stdio.h>
#include <time.h>

#include "../common/objects.h"
#include "../common/debug.h"
#include "../common/structs.h"
#include "../common/buffer.h"
//#include "../shader/shaders.h"
#include "../common/vector.h"
#include "./intersect/intersect.h"
#include "tracer.h"
#include "ray_common.h"



#include <pthread.h>
extern pthread_mutex_t mutexor;



vector* get_proj_ray(int x, int y, vector* v);
void calc_ray(int x, int y);

extern scene_data* main_scene;
#define CAMERA1 main_scene->camera

/* {{{ get_proj_ray */
/* this is much slower than generating the rays in the main function */
/* adds about 6% to render time (16.8 sec to 17.8 sec) */
inline vector* get_proj_ray(int x, int y, vector* v)
{
	double ratio_y = y*main_scene->stretch_y - main_scene->cons_y;
	double ratio_x = x*main_scene->stretch_x - main_scene->cons_x;

	v->x = CAMERA1->look.x + ratio_x*CAMERA1->horz.x + ratio_y*CAMERA1->vert.x;
	v->y = CAMERA1->look.y + ratio_x*CAMERA1->horz.y + ratio_y*CAMERA1->vert.y;
	v->z = CAMERA1->look.z + ratio_x*CAMERA1->horz.z + ratio_y*CAMERA1->vert.z;

	return v;
} //}}}

/* {{{ calc_ray */
/* calculates the ray at given point, writes color to buffer */
void calc_ray(int x, int y)
{
	intersect_data* i_data;
	color new_color;
	
	printd(INSANE, "{calc_ray @ %i %i\n", x, y);


	//FIXME: this is a hack.  structs are weird
	new_color.r = 0;
	new_color.g = 0;
	new_color.b = 0;

	i_data = get_idata(x, y);
	copy_vector(&CAMERA1->pos, &i_data->start);
	i_data->step=0;
	i_data->pos.x = x;
	i_data->pos.y = y;

	get_proj_ray(x, y, &i_data->proj);
//pthread_mutex_lock (&mutexor);
	i_data->obj_num = 
		trace(&i_data->start, &i_data->intersect, &i_data->proj, 0);
//pthread_mutex_unlock (&mutexor);
	i_data->obj = main_scene->models[i_data->obj_num];

	//FIXME: two calls to this (one in shader code, one here) kill one of them
	get_normal(&i_data->intersect, i_data->obj, &i_data->normal);
	normalize(&i_data->normal);

	print_idata(INSANE, "", i_data);

	printd(INSANE, "}calc_ray\n");

} //}}}
