#include "stdafx.h"
#include "PbTri.h"												// CPbHighTri


//calc mesh-ray intersection
// call ClearHitList();m_pRoot->GatherRayHits(invStart,invEnd);		before
//////////////////////////////////////////////////////////////////////
CPbHighTri *ChooseNearestAcceptableIntersection( CIntInfoHighList &inIntersections, const Vec3 &invStart, const Vec3 &invEnd, 
																											const Vec3 &refnormal, Vec3 &respoint )
{
  // find the nearest intersection point with a similar normal
  CPbHighTri *besttri=NULL;
  float bestdist=3.402823466e+38F;											// maximum possible value

	float mid=(invStart-invEnd).len()*0.5f;

	// find best hit with a good normal
  for(CIntInfoHighIt i=inIntersections.begin();i!=inIntersections.end();i++)
  {
		CIntersInfo<CPbHighTri> &ci=(*i);

		float dist=(float)(fabs(ci.m_fDist-mid));

    if(dist<bestdist)
    {
			float factor=ci.m_pTri->m_Plane.n*refnormal;

			if(factor>0)
			{
				besttri=ci.m_pTri;
				bestdist=dist;
				respoint=ci.m_Point;
			}
    }
  } //i

  return besttri;
}



	

//calc mesh-ray intersection
// call ::ClearHitList();m_pRoot->GatherRayHits(invStart,invEnd);		before
//////////////////////////////////////////////////////////////////////
CPbHighTri *ChooseNearestIntersection( CIntInfoHighList &inIntersections, const Vec3 &invStart, const Vec3 &invEnd, 
																						const Vec3 &refnormal, Vec3 &respoint )
{
  // find the nearest intersection point with a similar normal
  CPbHighTri *besttri=NULL;
  float bestdist=3.402823466e+38F;											// maximum possible value

	float mid2=(invStart-invEnd).len()*0.5f;

	// find best hit with a good normal
  for(CIntInfoHighIt i=inIntersections.begin();i!=inIntersections.end();i++)
  {
		CIntersInfo<CPbHighTri> &ci=(*i);

		float dist=(float)(fabs(ci.m_fDist-mid2));

    if(dist<bestdist)
    {
			float factor=ci.m_pTri->m_Plane.n*refnormal;

			if(factor>NORMAL_MATCH)
			{
				besttri=ci.m_pTri;
				bestdist=dist;
				respoint=ci.m_Point;
			}
    }
  } //i

  return besttri;
}



//
// call ClearHitList();m_pRoot->GatherRayHits(p1,p2);		before
// refnormal has to be normalized
CPbHighTri *ChooseLatestIntersection( CIntInfoHighList &inIntersections, const Vec3 &invStart, const Vec3 &invEnd, 
																					 const Vec3 &refnormal, Vec3 &respoint )
{
  //find the latest intersection point with a similar normal
  CPbHighTri *besttri=NULL;
  float bestdist=-1.0f;        

  for(CIntInfoHighIt i=inIntersections.begin();i!=inIntersections.end();i++)
  {
		CIntersInfo<CPbHighTri> &ci=(*i);

		assert(ci.m_fDist>=0.0f);

		if(ci.m_fDist>bestdist)
    {
      float factor=ci.m_pTri->m_Plane.n*refnormal;

			if(factor>NORMAL_MATCH)
			{
				besttri=ci.m_pTri;
				bestdist=ci.m_fDist;
				respoint=ci.m_Point;                    
			}
    }
  } //i

  return besttri;
}
