
#include "Quad.h"
#include <stdio.h>

#ifndef M_2PI
#define M_2PI 6.28318
#endif

int Quad::IsInside(Vector s)
{
	float angle=0;
	Vector d1,d2;
	
	d1=s-v1;
	d2=s-v2;
	angle+=d1%d2;
	d1=s-v3;
	angle+=d1%d2;	
	d2=s-v4;
	angle+=d1%d2;	
	d1=s-v1;
	angle+=d1%d2;	

	if(angle>0.99f*M_2PI){
/*		printf("Quad::IsInside: angle=%f\n",angle);
		printf("Quad::IsInside: I think that\n");
		printf("\t%f,%f,%f is inside\n",s.x,s.y,s.z);
		printf("\t%f,%f,%f\n",v1.x,v1.y,v1.z);
		printf("\t%f,%f,%f\n",v2.x,v2.y,v2.z);
		printf("\t%f,%f,%f\n",v3.x,v3.y,v3.z);
		printf("\t%f,%f,%f\n",v4.x,v4.y,v4.z);
*/
		return 1;
	}

	return 0;
}

int Quad::PlaneIntersection(Vector p1,Vector p2)
{
  float d1,d2,dp;
	Vector linedir;

	linedir=p2-p1;
	if((linedir|n) > 0)
		return 0;
	
	dp=-n|v1;//where v1 is some arbitrary point on the plane

	d1=(p1|n)+dp;
	d2=(p2|n)+dp;

	if(d1*d2>=0)
		return 0;
	else
		return 1;
	
}


int Quad::PlaneIntersection2Way(Vector p1,Vector p2)
{
  float d1,d2,dp;
	
	dp=-n|v1;//where v1 is some arbitrary point on the plane

	d1=(p1|n)+dp;
	d2=(p2|n)+dp;

	if(d1*d2>=0)
		return 0;
	else
		return 1;
	
}

Vector Quad::PlaneIntersectionPoint(Vector p1,Vector p2)
{
	Vector linedir;
	Vector retval;

	linedir=p2-p1;
	linedir.Unitize();

	float numerator=-((n|p1)-(n|v1));
	float denominator=n|linedir;
	if(denominator==0.0)
		return p1;
	float dist=numerator/denominator;

	retval=p1+dist*linedir;

	return retval;
}

Vector Quad::SlideVector(Vector v)
{
	Vector retval;
	float	vdotn=v|n;
	retval=v;
	retval=v-n*vdotn;

	return retval;
}

Vector Quad::BounceVector(Vector v)
{
	Vector retval;
	float	vdotn=v|n;
	retval=v;
	retval=v-2*n*vdotn;

	return retval;
}

Vector Quad::BounceVector(Vector v,float res)
{
	Vector retval;
	float	vdotn=v|n;
	retval=v;
	retval=v-n*vdotn-n*vdotn*res;

	return retval;
}
