-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollisionDetection_QuadTrees.cpp
More file actions
392 lines (308 loc) · 9.47 KB
/
CollisionDetection_QuadTrees.cpp
File metadata and controls
392 lines (308 loc) · 9.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
#include "defGameEngine.hpp"
#define DEF_GEOMETRY2D_IMPL
#include "../Include/defGeometry2D.hpp"
#define DGE_AFFINE_TRANSFORMS
#include "../Extensions/DGE_AffineTransforms.hpp"
#include <array>
bool overlaps(const def::rectf& r1, const def::rectf& r2)
{
return r1.pos < r2.pos + r2.size && r1.pos + r1.size >= r2.pos;
}
template <class T>
class QuadTree
{
public:
using Storage = std::list<std::pair<T, def::rectf>>;
struct ItemLocation
{
typename Storage::iterator iterator;
Storage* container = nullptr;
};
public:
QuadTree(const def::rectf& area = { {0.0f, 0.0f}, {128.0f, 128.0f} }, size_t level = 0)
{
create(area, level);
}
void create(const def::rectf& area, size_t level = 0)
{
m_Level = level;
resize(area);
}
void resize(const def::rectf& area)
{
clear();
m_Area = area;
def::vf2d childSize = area.size * 0.5f;
m_ChildrenAreas =
{
def::rectf(area.pos, childSize),
def::rectf({ area.pos.x + childSize.x, area.pos.y }, childSize),
def::rectf({ area.pos.x, area.pos.y + childSize.y }, childSize),
def::rectf(area.pos + childSize, childSize)
};
}
void clear()
{
m_Items.clear();
for (auto& child : m_Children)
{
if (child) child->clear();
child.reset();
}
}
size_t size() const
{
size_t count = m_Items.size();
for (auto& child : m_Children)
{
if (child)
count += child.size();
}
return count;
}
ItemLocation insert(const T& item, const def::rectf& area)
{
for (size_t i = 0; i < 4; i++)
{
if (def::contains(m_ChildrenAreas[i], area))
{
if (!m_Children[i])
m_Children[i] = std::make_shared<QuadTree<T>>(m_ChildrenAreas[i], m_Level + 1);
return m_Children[i]->insert(item, area);
}
}
// It fits within the area of the current child
// but it doesn't fit within any area of the children
// so stop here
m_Items.push_back({ item, area });
return { std::prev(m_Items.end()), &m_Items };
}
void find(const def::rectf& area, std::list<T>& data)
{
for (const auto& item : m_Items)
{
if (overlaps(area, item.second))
data.push_back(item.first);
}
for (size_t i = 0; i < 4; i++)
{
if (m_Children[i])
{
if (def::contains(area, m_ChildrenAreas[i]))
m_Children[i]->collect_items(data);
else if (overlaps(m_ChildrenAreas[i], area))
m_Children[i]->find(area, data);
}
}
}
bool remove(const T& item)
{
auto it = std::find_if(m_Items.begin(), m_Items.end(),
[&](const std::pair<T, def::rectf>& i) { return i.first == item; });
if (it != m_Items.end())
{
m_Items.erase(it);
return true;
}
for (size_t i = 0; i < 4; i++)
{
if (m_Children[i])
{
if (m_Children[i]->remove(item))
return true;
}
}
return false;
}
void collect_items(std::list<T>& items)
{
for (const auto& item : m_Items)
items.push_back(item.first);
for (auto& child : m_Children)
{
if (child)
child->collect_items(items);
}
}
void collect_areas(std::list<def::rectf>& areas)
{
areas.push_back(m_Area);
for (size_t i = 0; i < 4; i++)
{
if (m_Children[i])
m_Children[i]->collect_areas(areas);
}
}
private:
size_t m_Level;
def::rectf m_Area;
// All 4 children of a current quad
std::array<std::shared_ptr<QuadTree<T>>, 4> m_Children;
// Cached areas of each item from the m_Children array
std::array<def::rectf, 4> m_ChildrenAreas;
// Items in the current quad
Storage m_Items;
};
template <class T>
class QuadTreeContainer
{
public:
struct Item
{
T data;
typename QuadTree<typename std::list<Item>::iterator>::ItemLocation location;
};
using Storage = std::list<Item>;
QuadTreeContainer(const def::rectf& area = { {0.0f, 0.0f}, {128.0f, 128.0f} }, size_t level = 0)
{
create(area, level);
}
void create(const def::rectf& area = { {0.0f, 0.0f}, {128.0f, 128.0f} }, size_t level = 0)
{
m_Root.create(area, level);
}
void clear()
{
m_Root.clear();
}
size_t size() const
{
return m_Root.size();
}
void insert(const T& item, const def::rectf& area)
{
m_Items.push_back({ item });
m_Items.back().location = m_Root.insert(std::prev(m_Items.end()), area);
}
void find(const def::rectf& area, std::list<typename Storage::iterator>& data)
{
m_Root.find(area, data);
}
void remove(typename Storage::iterator item)
{
item->location.container->erase(item->location.iterator);
m_Items.erase(item);
}
void collect_items(Storage& items)
{
m_Root.collect_items(items);
}
void collect_areas(std::list<def::rectf>& areas)
{
m_Root.collect_areas(areas);
}
private:
Storage m_Items;
QuadTree<typename Storage::iterator> m_Root;
};
class App : public def::GameEngine
{
public:
App()
{
GetWindow()->SetTitle("Quad trees");
UseOnlyTextures(true);
}
enum class PlantID
{
LargeTree,
LargeBush,
SmallTree,
SmallBush
};
struct Object
{
def::rectf area;
PlantID id;
};
QuadTreeContainer<Object> tree;
def::AffineTransforms at;
float worldSize = 25000.0f;
float searchAreaSize = 100.0f;
def::Graphic plants;
protected:
bool OnUserCreate() override
{
tree.create({ {0.0f, 0.0f}, {worldSize, worldSize} });
at.SetViewArea(GetWindow()->GetScreenSize());
auto rand_float = [](float min, float max)
{
return min + (float)rand() / (float)RAND_MAX * (max - min);
};
for (size_t i = 0; i < 1000000; i++)
{
Object o;
o.area.pos = { rand_float(0.0f, worldSize), rand_float(0.0f, worldSize) };
o.id = PlantID(rand() % 4);
o.area.size.x = 16.0f;
if (o.id == PlantID::LargeTree || o.id == PlantID::LargeBush)
o.area.size.y = 32.0f;
else
o.area.size.x = 16.0f;
tree.insert(o, o.area);
}
plants.Load("plants.png");
return true;
}
bool OnUserUpdate(float) override
{
auto i = GetInput();
if (i->GetButtonState(def::Button::WHEEL).pressed)
at.StartPan(GetInput()->GetMousePosition());
if (i->GetButtonState(def::Button::WHEEL).held)
at.UpdatePan(GetInput()->GetMousePosition());
if (i->GetScrollDelta() > 0)
{
if (i->GetKeyState(def::Key::LEFT_CONTROL).held)
searchAreaSize *= 0.9f;
else
at.Zoom(1.1f, i->GetMousePosition());
}
if (i->GetScrollDelta() < 0)
{
if (i->GetKeyState(def::Key::LEFT_CONTROL).held)
searchAreaSize *= 1.1f;
else
at.Zoom(0.9f, i->GetMousePosition());
}
def::Vector2f mouse = at.ScreenToWorld(i->GetMousePosition());
def::rectf selectedArea({ mouse.x - searchAreaSize * 0.5f, mouse.y - searchAreaSize * 0.5f }, { searchAreaSize, searchAreaSize });
if (i->GetButtonState(def::Button::LEFT).held)
{
std::list<std::list<QuadTreeContainer<Object>::Item>::iterator> selected;
tree.find(selectedArea, selected);
for (auto& item : selected)
tree.remove(item);
}
def::Vector2f origin = at.GetOrigin();
def::Vector2f size = at.GetEnd() - origin;
def::rectf searchArea = { { origin.x, origin.y }, { size.x, size.y } };
std::list<std::list<QuadTreeContainer<Object>::Item>::iterator> objects;
tree.find(searchArea, objects);
ClearTexture(def::GREEN);
for (const auto& obj : objects)
{
def::Vector2f pos = { obj->data.area.pos.x, obj->data.area.pos.y };
switch (obj->data.id)
{
case PlantID::LargeTree: at.DrawPartialTexture(pos, plants.texture, { 0.0f, 0.0f }, { 16.0f, 32.0f }); break;
case PlantID::LargeBush: at.DrawPartialTexture(pos, plants.texture, { 16.0f, 0.0f }, { 16.0f, 32.0f }); break;
case PlantID::SmallTree: at.DrawPartialTexture(pos, plants.texture, { 32.0f, 7.0f }, { 16.0f, 25.0f }); break;
case PlantID::SmallBush: at.DrawPartialTexture(pos, plants.texture, { 48.0f, 16.0f }, { 16.0f, 16.0f }); break;
}
}
DrawTextureString({ 0, 0 }, std::to_string(objects.size()));
at.FillTextureRectangle(
{ selectedArea.pos.x, selectedArea.pos.y },
{ selectedArea.size.x, selectedArea.size.y },
def::Pixel(255, 255, 255, 100));
return true;
}
};
int main()
{
App app;
if (app.Construct(1280, 960, 1, 1, false, true))
app.Run();
return 0;
}