Tatooine
separating_axis_theorem.h
Go to the documentation of this file.
1#ifndef TATOOINE_SEPARATING_AXIS_THEOREM_H
2#define TATOOINE_SEPARATING_AXIS_THEOREM_H
3//==============================================================================
4#include <tatooine/vec.h>
5
6#include <vector>
7//==============================================================================
8namespace tatooine {
9//==============================================================================
11template <typename Real>
13 std::vector<vec<Real, 2>> const& polygon0,
14 std::vector<vec<Real, 2>> const& polygon1) {
15 Real min0, min1, max0, max1;
16 min0 = min1 = std::numeric_limits<Real>::infinity();
17 max0 = max1 = -std::numeric_limits<Real>::infinity();
18
19 for (auto const& v : polygon0) {
20 auto const projection = dot(v, n);
21 min0 = std::min(min0, projection);
22 max0 = std::max(max0, projection);
23 }
24 for (auto const& v : polygon1) {
25 auto const projection = dot(v, n);
26 min1 = std::min(min1, projection);
27 max1 = std::max(max1, projection);
28 }
29 return !(max0 >= min1 && max1 >= min0);
30}
31//------------------------------------------------------------------------------
34template <typename Real>
35auto has_separating_axis(std::vector<vec<Real, 2>> const& polygon0,
36 std::vector<vec<Real, 2>> const& polygon1) -> bool {
37 using vec_t = vec<Real, 2>;
38 using vec_list = std::vector<vec_t>;
39 vec_list normals;
40 normals.reserve(size(polygon0) + size(polygon1));
41
42 vec_t e;
43 for (size_t i = 0; i < size(polygon0) - 1; ++i) {
44 e = polygon0[i + 1] - polygon0[i];
45 normals.push_back(vec_t{-e(1), e(0)});
46 }
47 for (size_t i = 0; i < size(polygon1) - 1; ++i) {
48 e = polygon1[i + 1] - polygon1[i];
49 normals.push_back(vec_t{-e(1), e(0)});
50 }
51 e = polygon0.front() - polygon0.back();
52 normals.push_back(vec_t{-e(1), e(0)});
53 e = polygon1.front() - polygon1.back();
54 normals.push_back(vec_t{-e(1), e(0)});
55
56 for (auto const& n : normals) {
57 if (is_separating_axis(n, polygon0, polygon1)) {
58 return true;
59 }
60 }
61 return false;
62}
63//==============================================================================
64} // namespace tatooine
65//==============================================================================
66#endif
Definition: algorithm.h:6
auto is_separating_axis(vec< Real, 2 > const &n, std::vector< vec< Real, 2 > > const &polygon0, std::vector< vec< Real, 2 > > const &polygon1)
Return true if n is a separating axis of polygon0 and polygon1.
Definition: separating_axis_theorem.h:12
auto size(vec< ValueType, N > const &v)
Definition: vec.h:148
constexpr auto dot(base_tensor< Tensor0, T0, N > const &lhs, base_tensor< Tensor1, T1, N > const &rhs)
Definition: tensor_operations.h:120
auto has_separating_axis(std::vector< vec< Real, 2 > > const &polygon0, std::vector< vec< Real, 2 > > const &polygon1) -> bool
Definition: separating_axis_theorem.h:35
Definition: vec.h:12