emlabcpp
modern opinionated embedded C++ library
line.h
Go to the documentation of this file.
1 
24 #pragma once
25 
26 #include "./point.h"
27 #include "./vector.h"
28 
29 #include <array>
30 
31 namespace emlabcpp
32 {
33 
34 // represents an set of two points, type alies of std::array because nothing more specific is
35 // required
36 template < std::size_t N >
37 using line = std::array< point< N >, 2 >;
38 
39 // calculate shortest distance between any point on line and point 'p'
40 template < std::size_t N >
41 constexpr float distance_of( line< N > const& l, point< N > const& p )
42 {
43  vector< N > const direction = l[1] - l[0];
44  float const length_squared = length2_of( direction );
45  if ( length_squared == 0.f )
46  return distance_of( p, l[0] );
47  float projection_dist = dot( p - l[0], direction );
48  projection_dist /= length_squared;
49  projection_dist = std::clamp( projection_dist, 0.f, 1.f );
50 
51  point< N > const closest_p = l[0] + projection_dist * direction;
52 
53  return distance_of( closest_p, p );
54 }
55 
56 template < std::size_t N >
57 constexpr float distance_of( point< N > const& p, line< N > const& line )
58 {
59  return distance_of( line, p );
60 }
61 
62 } // namespace emlabcpp
Class implementing multidimensional point in coordinate system of dimension N.
Definition: point.h:36
Definition: vector.h:33
MIT License.
Definition: impl.h:31
std::array< point< N >, 2 > line
Definition: line.h:37
constexpr float dot(quaternion const &q, quaternion const &s)
Definition: quaternion.h:101
constexpr auto length2_of(vec_point_base< Derived, N > const &a)
Returns squared distance of A from [0,0,0], this is a squared length of vector represented by A.
Definition: vec_point_base.h:192
constexpr T const & clamp(T const &x, min_max< T > const &mm, Compare &&comp)
Definition: min_max.h:69
constexpr float distance_of(line< N > const &l, point< N > const &p)
Definition: line.h:41