#include <math.h>
#include <stdio.h>
#include <time.h>
#include "../../common/objects.h"
#include "../../common/vector.h"
#include "../../common/misc.h"
#include "../../common/debug.h"
//#include "../render/vector.c"
#include "plane.h"



#include <pthread.h>
extern pthread_mutex_t mutexor;



extern scene_data* main_scene;

double intersect_plane(point* origin, vector* projection, object* obj,
	point* intersection)
{
	double normDproj;
	double normDobj;
	double distance;
	vector obj_vector;

	normDproj = dot_product(&obj->norm, projection);

	if(normDproj == 0) //parallel check
		return 0;

	sub_vectors(&obj_vector, &obj->pos, origin);

	normDobj = dot_product(&obj->norm, &obj_vector);
	
	
	
//pthread_mutex_lock (&mutexor);
	distance = normDobj / normDproj;
//pthread_mutex_unlock (&mutexor);


	if(distance < 0 )
		return 0;


	//multiply_vector(intersection, projection, distance);
	//add_vectors(intersection, origin, intersection);

	return distance;
}

/*****************************************************
 Calculates the normal vector at a point, on an object
 *****************************************************/
vector* normal_plane(point* q, object* objectHit, vector* n)
{
	n->x = objectHit->norm.x;
	n->y = objectHit->norm.y;
	n->z = objectHit->norm.z;
	return n;
}


extern clock_t current_time;

vector* normal_wavey_plane(point* q, object* objectHit, vector* n)
{
	double dist = 0.0;
	vector bend;

	n->x = objectHit->norm.x;
	n->y = objectHit->norm.y;
	n->z = objectHit->norm.z;
	
	//setup the bumpy surface
	dist = distance_between(q, &objectHit->pos);
	make_vector(q, &objectHit->pos, &bend); 
	normalize(&bend);
	
	multiply_vector(&bend, &bend, sin(dist+current_time/TIME_SCALE));
	multiply_vector(&bend, &bend, 0.12);
	add_vectors(n, n, &bend);

	return n;
}
