#include "Vector.h"
#include <math.h>
#include <stdlib.h>

#define PLANE_FRONT 1
#define PLANE_BACK  0

sVector directionFromAngles(sVector rotationVector)
{
    sVector direction;
    direction.x = 0 + sin(rotationVector.y * PI2) * cos(rotationVector.x * PI2); 
	direction.y = 0 + sin(rotationVector.x * PI2);
	direction.z = 0 + cos(rotationVector.y * PI2) * cos(rotationVector.x * PI2);
	
	return direction;
}

bool TriangleIntersectTest(sVector *source, sVector *dest, sVector *vec1, sVector *vec2, sVector *vec3)
{
	bool result = true;
	sVector edge1, edge2, planeNormal, tempVector;
	sVector pVector, tVector, qVector;
	sVector direction = dest->Difference(source);
	float det = 0.0f, u, v; //determinent
	
	edge1 = vec3->Difference(vec2);
	edge2 = vec1->Difference(vec2);
	planeNormal = edge1.CrossProduct(&edge2);
	
    float planeDistance = planeNormal.DotProduct(source);
	
	//first, check to be sure we actually cross the plane of the triangle
	if(planeNormal.DotProduct(dest) + planeDistance < 0)
      return false;
         
	
	//we need to be sure the vertices line up right
	float angle = planeNormal.Angle(&direction);
	if(angle < (90 * PI2)) //face is backwards
	{
		tempVector = edge1;
		edge1 = edge2;
		edge2 = tempVector;
	}
	

	pVector = direction.CrossProduct(&edge2);
	det = edge1.DotProduct(&pVector);

	if(det < 0.0001f)
		result = false; // fail!!

	tVector = source->Difference(vec2);
	u = tVector.DotProduct(&pVector);
	if(u < 0.0f || u > det)
		result = false; // fail!!

	qVector = tVector.CrossProduct(&edge1);
	v = direction.DotProduct(&qVector);
	if(v < 0.0f || u + v > det)
		result = false; // fail!!

	//ray intersects triangle
	return result;
}

int RandomNumber(int minvalue,int maxvalue)
{
	int randomnumber;
	float normal;
	normal = (float)abs(rand()) / (float)RAND_MAX;
	normal = ((float)(maxvalue - minvalue + 1) * normal) + (float)minvalue;
	randomnumber = (int)normal;
	if(randomnumber > maxvalue)
		randomnumber = maxvalue;
	if(randomnumber < minvalue)
		randomnumber = minvalue;
	return randomnumber;
}
