diff --git a/simgear/math/SGVec2.hxx b/simgear/math/SGVec2.hxx index 93655cb1..0979c0a0 100644 --- a/simgear/math/SGVec2.hxx +++ b/simgear/math/SGVec2.hxx @@ -375,6 +375,29 @@ interpolate(T tau, const SGVec2& v1, const SGVec2& v2) return r; } +// Is the first point inside the triangle formed by the other three points? +// Helper function +template +inline +T +pt_determine(const SGVec2& pt1, const SGVec2& pt2, const SGVec2& pt3) +{ + return (pt1.x()-pt3.x()) * (pt2.y()-pt3.y()) - (pt2.x() - pt3.x()) * (pt1.y() - pt3.y()); +} + +template +inline +bool +point_in_triangle(const SGVec2& testpt, const SGVec2& pt1, const SGVec2& pt2, const SGVec2& pt3) +{ + T d1 = pt_determine(testpt,pt1,pt2); + T d2 = pt_determine(testpt,pt2,pt3); + T d3 = pt_determine(testpt,pt3,pt1); + bool has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0); + bool has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0); + return !(has_neg && has_pos); +} + #ifndef NDEBUG template inline