VertexSet.hpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/PlayRho
3  *
4  * This software is provided 'as-is', without any express or implied
5  * warranty. In no event will the authors be held liable for any damages
6  * arising from the use of this software.
7  * Permission is granted to anyone to use this software for any purpose,
8  * including commercial applications, and to alter it and redistribute it
9  * freely, subject to the following restrictions:
10  * 1. The origin of this software must not be misrepresented; you must not
11  * claim that you wrote the original software. If you use this software
12  * in a product, an acknowledgment in the product documentation would be
13  * appreciated but is not required.
14  * 2. Altered source versions must be plainly marked as such, and must not be
15  * misrepresented as being the original software.
16  * 3. This notice may not be removed or altered from any source distribution.
17  */
18 
19 #ifndef PLAYRHO_COMMON_VERTEXSET_HPP
20 #define PLAYRHO_COMMON_VERTEXSET_HPP
21 
22 #include <PlayRho/Common/Math.hpp>
23 
24 #include <vector>
25 #include <algorithm>
26 
27 namespace playrho {
28 namespace d2 {
29 
35 class VertexSet
36 {
37 public:
38 
40  using const_pointer = const Length2*;
41 
44  {
45  return sqrt(std::numeric_limits<Vec2::value_type>::min()) * SquareMeter;
46  }
47 
49  explicit VertexSet(Area minSepSquared = GetDefaultMinSeparationSquared()):
50  m_minSepSquared{minSepSquared}
51  {
52  assert(minSepSquared >= 0_m2);
53  }
54 
56  Area GetMinSeparationSquared() const noexcept { return m_minSepSquared; }
57 
59  bool add(Length2 value)
60  {
61  if (find(value) != end())
62  {
63  return false;
64  }
65  m_elements.push_back(value);
66  return true;
67  }
68 
70  void clear() noexcept
71  {
72  m_elements.clear();
73  }
74 
76  std::size_t size() const noexcept
77  {
78  return detail::Size(m_elements);
79  }
80 
82  const_pointer data() const { return detail::Data(m_elements); }
83 
85  const_pointer begin() const { return data(); }
86 
88  const_pointer end() const { return data() + size(); }
89 
92  const_pointer find(Length2 value) const
93  {
94  // squaring anything smaller than the sqrt(std::numeric_limits<Vec2::data_type>::min())
95  // won't be reversible.
96  // i.e. won't obey the property that square(sqrt(a)) == a and sqrt(square(a)) == a.
97  return std::find_if(begin(), end(), [&](Length2 elem) {
98  // length squared must be large enough to have a reasonable enough unit vector.
99  return GetMagnitudeSquared(value - elem) <= m_minSepSquared;
100  });
101  }
102 
104  Length2 operator[](std::size_t index) const noexcept
105  {
106  return m_elements[index];
107  }
108 
109 private:
110  std::vector<Length2> m_elements;
111  const Area m_minSepSquared;
112 };
113 
114 } // namespace d2
115 } // namespace playrho
116 
117 #endif // PLAYRHO_COMMON_VERTEXSET_HPP