59 lines
1.4 KiB
C++
59 lines
1.4 KiB
C++
/*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
|
|
*/
|
|
|
|
#pragma once
|
|
|
|
#include "../point.hpp"
|
|
|
|
|
|
namespace util::geom {
|
|
template <size_t S, typename T>
|
|
struct segment {
|
|
util::point<S,T> a;
|
|
util::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));
|
|
}
|
|
};
|