# 2. 详论

## 2.1. 原理

$\vec{P} = (1 - u - v) \vec{V_0} + u \vec{V_1} + v \vec{V_2}$

$\vec{V_0P} = u(\vec{V_0V_1}) + v(\vec{V_0V_2})$

$\begin{cases} \vec{V_0P} \cdot \vec{V_0V_1} = u(\vec{V_0V_1 \cdot \vec{V_0V_1}}) + v(\vec{V_0V_2} \cdot \vec{V_0V_1}) \\ \vec{V_0P} \cdot \vec{V_0V_2} = u(\vec{V_0V_1} \cdot \vec{V_0V_2}) + v(\vec{V_0V_2} \cdot \vec{V_0V_2}) \\ \end{cases}$

$\begin{cases} D = (\vec{V_0V_1 \cdot \vec{V_0V_1}}) * (\vec{V_0V_2} \cdot \vec{V_0V_2}) - (\vec{V_0V_2} \cdot \vec{V_0V_1}) * (\vec{V_0V_1} \cdot \vec{V_0V_2}) \\ D1 = (\vec{V_0P} \cdot \vec{V_0V_1}) * (\vec{V_0V_2} \cdot \vec{V_0V_2}) - (\vec{V_0V_2} \cdot \vec{V_0V_1}) * (\vec{V_0P} \cdot \vec{V_0V_2}) \\ D2 = (\vec{V_0V_1 \cdot \vec{V_0V_1}}) * (\vec{V_0P} \cdot \vec{V_0V_2}) - (\vec{V_0P} \cdot \vec{V_0V_1}) * (\vec{V_0V_1} \cdot \vec{V_0V_2}) \\ \end{cases}$

$\begin{cases} u = D1 / D \\ v = D2 / D \\ \end{cases}$

## 2.2. 实现

//空间三角形
//按照逆时针顺序插入值并计算法向量
template <class T>
class Triangle
{
public:
Vec3<T> v0;
Vec3<T> v1;
Vec3<T> v2;

Triangle()
{

}

Triangle(Vec3<T> v0, Vec3<T> v1, Vec3<T> v2)
{
this->v0 = v0;
this->v1 = v1;
this->v2 = v2;
}

void Set(Vec3<T> v0, Vec3<T> v1, Vec3<T> v2)
{
this->v0 = v0;
this->v1 = v1;
this->v2 = v2;
}

// 判断平面点P是否在平面三角形内(重心法)
bool PointInTriangle2D(Vec3<T>& P)
{
auto v01 = v1 - v0 ;
auto v02 = v2 - v0 ;
auto v0p = P - v0 ;

double dot00 = v01 * v01 ;
double dot01 = v01 * v02 ;
double dot02 = v01 * v0p ;
double dot11 = v02 * v02 ;
double dot12 = v02 * v0p ;

double D = (dot00 * dot11 - dot01 * dot01);
if(D == 0.0)
{
return false;
}
double inverDeno = 1 / D ;

double u = (dot11 * dot02 - dot01 * dot12) * inverDeno ;
if (u < 0 || u > 1)
{
return false ;
}

double v = (dot00 * dot12 - dot01 * dot02) * inverDeno ;
if (v < 0 || v > 1)
{
return false ;
}

return u + v <= 1 ;
}

};


# 3. 参考

posted @ 2021-06-12 20:25  charlee44  阅读(53)  评论(0编辑  收藏  举报