#include "Plane.h"

float Plane::Intersect( const Ray & ray ) const {
	float denom = DotProduct( this->n, ray.direction );
	if( denom == 0.0f ) {
		return std::numeric_limits< float >::infinity( );
	}
	float t = -this->Distance( ray.origin ) / denom;
	if( t < 0.0f ) {
		return std::numeric_limits< float >::infinity( );
	}
	return t;
}

float Plane::Intersect( const LineSegment & line ) const {
	float adist = this->Distance( line.a ), bdist = this->Distance( line.b );
	if( adist > 0.0f && bdist > 0.0f || adist < 0.0f && bdist < 0.0f ) {
		return std::numeric_limits< float >::infinity( );
	}
	return adist / ( adist - bdist );
}

PlaneIntersection PlanePlanePlaneIntersection( const Plane & p1, const Plane & p2, const Plane & p3 ) {
	float coeff = DotProduct( p1.n, CrossProduct( p2.n, p3.n ) );
	if( coeff == 0.0f ) {
		return PlaneIntersection( );
	}
	return PlaneIntersection( ( p1.d * CrossProduct( p2.n, p3.n ) + p2.d * CrossProduct( p3.n, p1.n ) + p3.d * CrossProduct( p1.n, p2.n ) ) * ( 1.0f / coeff ) );
}

