MeshLib C++ Docs
Loading...
Searching...
No Matches
MRClosestPointInTriangle.h
Go to the documentation of this file.
1
16#pragma once
17
18#include "MRVector3.h"
19#include "MRTriPoint.h"
20#include "MRPch/MRBindingMacros.h"
21
22#include <cassert>
23
24namespace MR
25{
28
29
30template <typename T>
31std::pair<Vector3<T>, TriPoint<T>> closestPointInTriangle( const Vector3<T>& p, const Vector3<T>& a, const Vector3<T>& b, const Vector3<T>& c )
32{
34 const Vector3<T> ab = b - a;
35 const Vector3<T> ac = c - a;
36 const Vector3<T> ap = p - a;
37
38 const T d1 = dot( ab, ap );
39 const T d2 = dot( ac, ap );
40 if ( d1 <= 0 && d2 <= 0 )
41 return { a, { 0, 0 } };
42
43 const Vector3<T> bp = p - b;
44 const T d3 = dot( ab, bp );
45 const T d4 = dot( ac, bp );
46 if ( d3 >= 0 && d4 <= d3 )
47 return { b, { 1, 0 } };
48
49 const Vector3<T> cp = p - c;
50 const T d5 = dot( ab, cp );
51 const T d6 = dot( ac, cp );
52 if ( d6 >= 0 && d5 <= d6 )
53 return { c, { 0, 1 } };
54
55 const T vc = d1 * d4 - d3 * d2;
56 if ( vc <= 0 && d1 >= 0 && d3 <= 0 )
57 {
58 const T v = d1 / ( d1 - d3 );
59 return { a + v * ab, { v, 0 } };
60 }
61
62 const T vb = d5 * d2 - d1 * d6;
63 if ( vb <= 0 && d6 <= 0 && d2 >= 0 )
64 {
65 const T v = d2 / ( d2 - d6 );
66 return { a + v * ac, { 0, v } };
67 }
68
69 const T va = d3 * d6 - d5 * d4;
70 if ( va <= 0 )
71 {
73 if ( d4 < d3 )
74 return { b, { 1, 0 } };
75
77 if ( d5 < d6 )
78 return { c, { 0, 1 } };
79
81 const T v = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
82 return { b + v * ( c - b ), { 1 - v, v } };
83 }
84
85 assert( va > 0 && vb > 0 && vc > 0 );
86 const T denom = 1 / ( va + vb + vc );
87 const T v = vb * denom;
88 const T w = vc * denom;
89 return { a + v * ab + w * ac, { v, w } };
90}
91
92MR_BIND_TEMPLATE( std::pair<Vector3f, TriPointf> closestPointInTriangle( const Vector3f& p, const Vector3f& a, const Vector3f& b, const Vector3f& c ) );
93MR_BIND_TEMPLATE( std::pair<Vector3d, TriPointd> closestPointInTriangle( const Vector3d& p, const Vector3d& a, const Vector3d& b, const Vector3d& c ) );
94
95}
auto dot(const Matrix2< T > &a, const Matrix2< T > &b) -> decltype(dot(a.x, b.x))
double-dot product: x = a : b
Definition MRMatrix2.h:142
MR_BIND_TEMPLATE(std::pair< Vector3f, TriPointf > closestPointInTriangle(const Vector3f &p, const Vector3f &a, const Vector3f &b, const Vector3f &c))
std::pair< Vector3< T >, TriPoint< T > > closestPointInTriangle(const Vector3< T > &p, const Vector3< T > &a, const Vector3< T > &b, const Vector3< T > &c)
Definition MRClosestPointInTriangle.h:31
only for bindings generation
Definition MRCameraOrientationPlugin.h:8
encodes a point inside a triangle using barycentric coordinates
Definition MRTriPoint.h:19
Definition MRVector3.h:33