libcruft-util/geom/segment.hpp
Danny Robson f6056153e3 rename root namespace from util to cruft
This places, at long last, the core library code into the same namespace
as the extended library code.
2018-08-05 14:42:02 +10:00

51 lines
1.1 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include "../point.hpp"
namespace cruft::geom {
template <size_t S, typename T>
struct segment {
cruft::point<S,T> a;
cruft::point<S,T> b;
};
using segment2f = segment<2,float>;
using segment3f = segment<3,float>;
template <size_t S, typename T>
T
distance2 (segment<S,T> s, point<S,T> p)
{
const auto dir = s.b - s.a;
const auto t1 = dot (p - s.a, dir);
if (t1 < 0)
return distance2 (p, s.a);
const auto t2 = dot (dir, dir);
if (t2 < t1)
return distance2 (p, s.b);
auto t = t1 / t2;
return distance2 (p, s.a + t * dir);
}
template <size_t S, typename T>
T
distance (segment<S,T> s, point<S,T> p)
{
return std::sqrt (distance2 (s, p));
}
};