#include "StdAfx.h"
#include "CSCache.h"



namespace lib_geo
{


CSCache::CSCache(void)
{
	NumEdgeInter = 0;
	NumEdgeOnface = 0;
	IsEdgeOnface[0] = false;
	IsEdgeOnface[1] = false;
	IsEdgeOnface[2] = false;
	IsEdgeIntersect[0]= false;
	IsEdgeIntersect[1]= false;
	IsEdgeIntersect[2]= false;
}

void CSCache::GetTwoEdgeCS(int& leid0, int& leid1)
{
	leid1 = -1;
	leid0 = -1;
	if( !IsEdgeIntersect[0] ) { leid0 = 1; leid1 = 2; }
	if( !IsEdgeIntersect[1] ) { leid0 = 2; leid1 = 0; }
	if( !IsEdgeIntersect[2] ) { leid0 = 0; leid1 = 1; }
}

void CSCache::GetTriangleDisq(float& d01, float& d12, float& d20)
{
	d01 = (InterPos[0] - InterPos[1]).square_length();
	d12 = (InterPos[1] - InterPos[2]).square_length();
	d20 = (InterPos[2] - InterPos[0]).square_length();
}

void CSCache::GetCloseDist(int& base_leid, int& sub_leid0, int& sub_leid1)
{
	base_leid = -1;
	sub_leid0 = -1;
	sub_leid1 = -1;

	float d01, d12, d20;
	GetTriangleDisq(d01, d12, d20);

	float close_dst = (std::numeric_limits<float>::max)();

	if( d01 < close_dst )
	{
		close_dst = d01;
		base_leid = 2;
		sub_leid0 = 0;
		sub_leid1 = 1;
	}

	if( d12 < close_dst )
	{
		close_dst = d12;
		base_leid = 0;
		sub_leid0 = 1;
		sub_leid1 = 2;
	}

	if( d20 < close_dst )
	{
		close_dst = d20;
		base_leid = 1;
		sub_leid0 = 2;
		sub_leid1 = 0;
	}
}

void CSCache::GetLid(int& lid)
{
	lid = -1;
	if (IsEdgeOnface[0]) lid = 0;
	if (IsEdgeOnface[1]) lid = 1;
	if (IsEdgeOnface[2]) lid = 2;
}


void CSCache::CalcFace(const BaseMesh& mesh, const CSFace& cf, const Plane& cutplane)
{
	for (size_t j = 0; j < 3; ++j)
	{
		const CSEdge& e = cf.edges[j];
		const lm::vec3f& v0 = mesh.m_Verts[e.vid0];
		const lm::vec3f& v1 = mesh.m_Verts[e.vid1];

		float d0 = lm::dot( cutplane.normal , v0 - cutplane.origin );
		float d1 = lm::dot( cutplane.normal , v1 - cutplane.origin );

		if (d0 == 0.0f && d1 == 0.0f)
		{
			NumEdgeOnface++;
			IsEdgeOnface[j] = true;
		}
		else if (d0 * d1 <= 0.0f)
		{
			NumEdgeInter++;
			IsEdgeIntersect[j] = true;
			d0 = abs(d0);
			d1 = abs(d1);
			InterPos[j] = (d0 * v1 + d1 * v0) / (d0 + d1);
		}
	}
}


}
