Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #ifndef INCLUDED_SPATIAL
19 : #define INCLUDED_SPATIAL
20 :
21 : #include "lib/debug.h"
22 : #include "maths/Fixed.h"
23 : #include "maths/FixedVector2D.h"
24 : #include "maths/MathUtil.h"
25 : #include "simulation2/helpers/Position.h"
26 : #include "simulation2/serialization/SerializeTemplates.h"
27 : #include "simulation2/system/Component.h"
28 : #include "simulation2/system/Entity.h"
29 :
30 : #include <algorithm>
31 : #include <cstddef>
32 : #include <cstdint>
33 : #include <utility>
34 : #include <vector>
35 :
36 : /**
37 : * A very basic subdivision scheme for finding items in ranges.
38 : * Items are stored in lists in dynamic-sized divisions.
39 : * Items have a size (min/max values of their axis-aligned bounding box)
40 : * and are stored in all divisions overlapping that area.
41 : *
42 : * It is the caller's responsibility to ensure items are only added
43 : * once, aren't removed unless they've been added, etc, and that
44 : * Move/Remove are called with the same coordinates originally passed
45 : * to Add (since this class doesn't remember which divisions an item
46 : * occupies).
47 : */
48 : class SpatialSubdivision
49 : {
50 109312 : struct SubDivisionGrid
51 : {
52 : std::vector<uint32_t> items;
53 :
54 1440 : inline void push_back(uint32_t value)
55 : {
56 1440 : items.push_back(value);
57 : }
58 :
59 1230 : inline void erase(int index)
60 : {
61 : // Delete by swapping with the last element then popping
62 1230 : if ((int)items.size() > 1) // but only if we have more than 1 elements
63 954 : items[index] = items.back();
64 1230 : items.pop_back();
65 1230 : }
66 :
67 94618 : void copy_items_at_end(std::vector<uint32_t>& out) const
68 : {
69 189236 : out.insert(out.end(), items.begin(), items.end());
70 : }
71 : };
72 :
73 :
74 : entity_pos_t m_DivisionSize;
75 : SubDivisionGrid* m_Divisions;
76 : uint32_t m_DivisionsW;
77 : uint32_t m_DivisionsH;
78 :
79 : friend struct SerializeHelper<SpatialSubdivision>;
80 :
81 : public:
82 : SpatialSubdivision() : m_Divisions(NULL), m_DivisionsW(0), m_DivisionsH(0)
83 : {
84 : }
85 32 : ~SpatialSubdivision()
86 : {
87 30112 : delete[] m_Divisions;
88 32 : }
89 : SpatialSubdivision(const SpatialSubdivision& rhs)
90 : {
91 : m_DivisionSize = rhs.m_DivisionSize;
92 : m_DivisionsW = rhs.m_DivisionsW;
93 : m_DivisionsH = rhs.m_DivisionsH;
94 : size_t n = m_DivisionsW * m_DivisionsH;
95 : m_Divisions = new SubDivisionGrid[n];
96 : for (size_t i = 0; i < n; ++i)
97 : m_Divisions[i] = rhs.m_Divisions[i]; // just fall back to piecemeal copy
98 : }
99 : SpatialSubdivision& operator=(const SpatialSubdivision& rhs)
100 : {
101 : if (this != &rhs)
102 : {
103 : m_DivisionSize = rhs.m_DivisionSize;
104 : size_t n = rhs.m_DivisionsW * rhs.m_DivisionsH;
105 : if (m_DivisionsW != rhs.m_DivisionsW || m_DivisionsH != rhs.m_DivisionsH)
106 : Create(n); // size changed, recreate
107 :
108 : m_DivisionsW = rhs.m_DivisionsW;
109 : m_DivisionsH = rhs.m_DivisionsH;
110 : for (size_t i = 0; i < n; ++i)
111 : m_Divisions[i] = rhs.m_Divisions[i]; // just fall back to piecemeal copy
112 : }
113 : return *this;
114 : }
115 :
116 : inline entity_pos_t GetDivisionSize() const { return m_DivisionSize; }
117 : inline uint32_t GetWidth() const { return m_DivisionsW; }
118 : inline uint32_t GetHeight() const { return m_DivisionsH; }
119 :
120 56 : void Create(size_t count)
121 : {
122 24632 : delete[] m_Divisions;
123 54712 : m_Divisions = new SubDivisionGrid[count];
124 56 : }
125 :
126 : /**
127 : * Equivalence test (ignoring order of items within each subdivision)
128 : */
129 : bool operator==(const SpatialSubdivision& rhs) const
130 : {
131 : if (m_DivisionSize != rhs.m_DivisionSize || m_DivisionsW != rhs.m_DivisionsW || m_DivisionsH != rhs.m_DivisionsH)
132 : return false;
133 :
134 : uint32_t n = m_DivisionsH * m_DivisionsW;
135 : for (uint32_t i = 0; i < n; ++i)
136 : {
137 : if (m_Divisions[i].items.size() != rhs.m_Divisions[i].items.size())
138 : return false;
139 :
140 : // don't bother optimizing this, this is only used in the TESTING SUITE
141 : std::vector<uint32_t> a = m_Divisions[i].items;
142 : std::vector<uint32_t> b = rhs.m_Divisions[i].items;
143 : std::sort(a.begin(), a.end());
144 : std::sort(b.begin(), b.end());
145 : if (a != b)
146 : return false;
147 : }
148 : return true;
149 : }
150 :
151 : inline bool operator!=(const SpatialSubdivision& rhs) const
152 : {
153 : return !(*this == rhs);
154 : }
155 :
156 56 : void Reset(entity_pos_t maxX, entity_pos_t maxZ, entity_pos_t divisionSize)
157 : {
158 56 : m_DivisionSize = divisionSize;
159 56 : m_DivisionsW = (maxX / m_DivisionSize).ToInt_RoundToInfinity();
160 56 : m_DivisionsH = (maxZ / m_DivisionSize).ToInt_RoundToInfinity();
161 :
162 56 : Create(m_DivisionsW * m_DivisionsH);
163 56 : }
164 :
165 :
166 : /**
167 : * Add an item with the given 'to' size.
168 : * The item must not already be present.
169 : */
170 1056 : void Add(uint32_t item, CFixedVector2D toMin, CFixedVector2D toMax)
171 : {
172 1056 : ENSURE(toMin.X <= toMax.X && toMin.Y <= toMax.Y);
173 :
174 2112 : std::uint32_t i0 = GetI0(toMin.X);
175 2112 : std::uint32_t j0 = GetJ0(toMin.Y);
176 2112 : std::uint32_t i1 = GetI1(toMax.X);
177 2112 : std::uint32_t j1 = GetJ1(toMax.Y);
178 2403 : for (std::uint32_t j = j0; j <= j1; ++j)
179 : {
180 2787 : for (std::uint32_t i = i0; i <= i1; ++i)
181 : {
182 1440 : m_Divisions[i + j*m_DivisionsW].push_back(item);
183 : }
184 : }
185 1056 : }
186 :
187 : /**
188 : * Remove an item with the given 'from' size.
189 : * The item should already be present.
190 : * The size must match the size that was last used when adding the item.
191 : */
192 870 : void Remove(uint32_t item, CFixedVector2D fromMin, CFixedVector2D fromMax)
193 : {
194 870 : ENSURE(fromMin.X <= fromMax.X && fromMin.Y <= fromMax.Y);
195 :
196 1740 : std::uint32_t i0 = GetI0(fromMin.X);
197 1740 : std::uint32_t j0 = GetJ0(fromMin.Y);
198 1740 : std::uint32_t i1 = GetI1(fromMax.X);
199 1740 : std::uint32_t j1 = GetJ1(fromMax.Y);
200 2025 : for (std::uint32_t j = j0; j <= j1; ++j)
201 : {
202 2385 : for (std::uint32_t i = i0; i <= i1; ++i)
203 : {
204 1230 : SubDivisionGrid& div = m_Divisions[i + j*m_DivisionsW];
205 1230 : int size = div.items.size();
206 1785 : for (int n = 0; n < size; ++n)
207 : {
208 1785 : if (div.items[n] == item)
209 : {
210 2460 : div.erase(n);
211 : break;
212 : }
213 : }
214 : }
215 : }
216 870 : }
217 :
218 : /**
219 : * Equivalent to Remove() then Add(), but potentially faster.
220 : */
221 7716 : void Move(uint32_t item, CFixedVector2D fromMin, CFixedVector2D fromMax, CFixedVector2D toMin, CFixedVector2D toMax)
222 : {
223 : // Skip the work if we're staying in the same divisions
224 7716 : if (GetIndex0(fromMin) == GetIndex0(toMin) && GetIndex1(fromMax) == GetIndex1(toMax))
225 : return;
226 :
227 840 : Remove(item, fromMin, fromMax);
228 840 : Add(item, toMin, toMax);
229 : }
230 :
231 : /**
232 : * Convenience function for Add() of individual points.
233 : * (Note that points on a boundary may occupy multiple divisions.)
234 : */
235 : void Add(uint32_t item, CFixedVector2D to)
236 : {
237 : Add(item, to, to);
238 : }
239 :
240 : /**
241 : * Convenience function for Remove() of individual points.
242 : */
243 : void Remove(uint32_t item, CFixedVector2D from)
244 : {
245 : Remove(item, from, from);
246 : }
247 :
248 : /**
249 : * Convenience function for Move() of individual points.
250 : */
251 : void Move(uint32_t item, CFixedVector2D from, CFixedVector2D to)
252 : {
253 : Move(item, from, from, to, to);
254 : }
255 :
256 : /**
257 : * Returns a sorted list of unique items that includes all items
258 : * within the given axis-aligned square range.
259 : */
260 26065 : void GetInRange(std::vector<uint32_t>& out, CFixedVector2D posMin, CFixedVector2D posMax) const
261 : {
262 26065 : out.clear();
263 26065 : ENSURE(posMin.X <= posMax.X && posMin.Y <= posMax.Y);
264 :
265 52130 : std::uint32_t i0 = GetI0(posMin.X);
266 52130 : std::uint32_t j0 = GetJ0(posMin.Y);
267 52130 : std::uint32_t i1 = GetI1(posMax.X);
268 52130 : std::uint32_t j1 = GetJ1(posMax.Y);
269 112823 : for (std::uint32_t j = j0; j <= j1; ++j)
270 : {
271 181376 : for (std::uint32_t i = i0; i <= i1; ++i)
272 : {
273 94618 : m_Divisions[i + j*m_DivisionsW].copy_items_at_end(out);
274 : }
275 : }
276 : // some buildings span several tiles, so we need to make it unique
277 26065 : std::sort(out.begin(), out.end());
278 26065 : out.erase(std::unique(out.begin(), out.end()), out.end());
279 26065 : }
280 :
281 : /**
282 : * Returns a sorted list of unique items that includes all items
283 : * within the given circular distance of the given point.
284 : */
285 0 : void GetNear(std::vector<uint32_t>& out, CFixedVector2D pos, entity_pos_t range) const
286 : {
287 : // TODO: be cleverer and return a circular pattern of divisions,
288 : // not this square over-approximation
289 0 : CFixedVector2D r(range, range);
290 0 : GetInRange(out, pos - r, pos + r);
291 0 : }
292 :
293 : private:
294 : // Helper functions for translating coordinates into division indexes
295 : // (avoiding out-of-bounds accesses, and rounding correctly so that
296 : // points precisely between divisions are counted in both):
297 :
298 43423 : uint32_t GetI0(entity_pos_t x) const
299 : {
300 27991 : return Clamp((x / m_DivisionSize).ToInt_RoundToInfinity()-1, 0, (int)m_DivisionsW-1);
301 : }
302 :
303 43423 : uint32_t GetJ0(entity_pos_t z) const
304 : {
305 27991 : return Clamp((z / m_DivisionSize).ToInt_RoundToInfinity()-1, 0, (int)m_DivisionsH-1);
306 : }
307 :
308 42331 : uint32_t GetI1(entity_pos_t x) const
309 : {
310 27991 : return Clamp((x / m_DivisionSize).ToInt_RoundToNegInfinity(), 0, (int)m_DivisionsW-1);
311 : }
312 :
313 42331 : uint32_t GetJ1(entity_pos_t z) const
314 : {
315 55888 : return Clamp((z / m_DivisionSize).ToInt_RoundToNegInfinity(), 0, (int)m_DivisionsH-1);
316 : }
317 :
318 15432 : uint32_t GetIndex0(CFixedVector2D pos) const
319 : {
320 30864 : return GetI0(pos.X) + GetJ0(pos.Y)*m_DivisionsW;
321 : }
322 :
323 14340 : uint32_t GetIndex1(CFixedVector2D pos) const
324 : {
325 35850 : return GetI1(pos.X) + GetJ1(pos.Y)*m_DivisionsW;
326 : }
327 : };
328 :
329 : /**
330 : * Serialization helper template for SpatialSubdivision
331 : */
332 : template<>
333 : struct SerializeHelper<SpatialSubdivision>
334 : {
335 36 : void operator()(ISerializer& serialize, const char* /*name*/, SpatialSubdivision& value)
336 : {
337 36 : serialize.NumberFixed_Unbounded("div size", value.m_DivisionSize);
338 36 : serialize.NumberU32_Unbounded("divs w", value.m_DivisionsW);
339 36 : serialize.NumberU32_Unbounded("divs h", value.m_DivisionsH);
340 :
341 36 : size_t count = value.m_DivisionsH * value.m_DivisionsW;
342 20772 : for (size_t i = 0; i < count; ++i)
343 20736 : Serializer(serialize, "subdiv items", value.m_Divisions[i].items);
344 36 : }
345 :
346 0 : void operator()(IDeserializer& serialize, const char* /*name*/, SpatialSubdivision& value)
347 : {
348 0 : serialize.NumberFixed_Unbounded("div size", value.m_DivisionSize);
349 0 : serialize.NumberU32_Unbounded("divs w", value.m_DivisionsW);
350 0 : serialize.NumberU32_Unbounded("divs h", value.m_DivisionsH);
351 :
352 0 : size_t count = value.m_DivisionsW * value.m_DivisionsH;
353 0 : value.Create(count);
354 0 : for (size_t i = 0; i < count; ++i)
355 0 : Serializer(serialize, "subdiv items", value.m_Divisions[i].items);
356 0 : }
357 : };
358 :
359 :
360 : /**
361 : * A basic square subdivision scheme for finding entities in range
362 : * More efficient than SpatialSubdivision, but a bit less precise
363 : * (so the querier will get more entities to perform tests on).
364 : *
365 : * Items are stored in vectors in fixed-size divisions.
366 : *
367 : * Items have a size (min/max values of their axis-aligned bounding box).
368 : * If that size is higher than a subdivision's size, they're stored in the "general" vector
369 : * This means that if too many objects have a size that's big, it'll end up being slow
370 : * We want subdivisions to be as small as possible yet contain as many items as possible.
371 : *
372 : * It is the caller's responsibility to ensure items are only added once, aren't removed
373 : * unless they've been added, etc, and that Move/Remove are called with the same coordinates
374 : * originally passed to Add (since this class doesn't remember which divisions an item
375 : * occupies).
376 : *
377 : * TODO: If a unit size were to change, it would need to be updated (that doesn't happen for now)
378 : */
379 : class FastSpatialSubdivision
380 : {
381 : private:
382 : static const int SUBDIVISION_SIZE = 20; // bigger than most buildings and entities
383 :
384 : std::vector<entity_id_t> m_OverSizedData;
385 : std::vector<entity_id_t>* m_SpatialDivisionsData; // fixed size array of subdivisions
386 : size_t m_ArrayWidth; // number of columns in m_SpatialDivisionsData
387 :
388 39244 : inline size_t Index(fixed position) const
389 : {
390 39244 : return Clamp((position / SUBDIVISION_SIZE).ToInt_RoundToZero(), 0, (int)m_ArrayWidth-1);
391 : }
392 :
393 18800 : inline size_t SubdivisionIdx(CFixedVector2D position) const
394 : {
395 37600 : return Index(position.X) + Index(position.Y)*m_ArrayWidth;
396 : }
397 :
398 : /**
399 : * Efficiently erase from a vector by swapping with the last element and popping it.
400 : * Returns true if the element was found and erased, else returns false.
401 : */
402 1800 : bool EraseFrom(std::vector<entity_id_t>& vector, entity_id_t item)
403 : {
404 1800 : std::vector<entity_id_t>::iterator it = std::find(vector.begin(), vector.end(), item);
405 1800 : if (it == vector.end())
406 : return false;
407 :
408 1800 : *it = vector.back();
409 1800 : vector.pop_back();
410 1800 : return true;
411 : }
412 :
413 : public:
414 : FastSpatialSubdivision() :
415 : m_SpatialDivisionsData(NULL), m_ArrayWidth(0)
416 : {
417 : }
418 :
419 1041 : FastSpatialSubdivision(const FastSpatialSubdivision& other) :
420 1041 : m_SpatialDivisionsData(NULL), m_ArrayWidth(0)
421 : {
422 1041 : Reset(other.m_ArrayWidth);
423 1041 : std::copy(&other.m_SpatialDivisionsData[0], &other.m_SpatialDivisionsData[m_ArrayWidth*m_ArrayWidth], m_SpatialDivisionsData);
424 1041 : }
425 :
426 1057 : ~FastSpatialSubdivision()
427 : {
428 732320 : delete[] m_SpatialDivisionsData;
429 1057 : }
430 :
431 2109 : void Reset(size_t arrayWidth)
432 : {
433 730499 : delete[] m_SpatialDivisionsData;
434 :
435 2109 : m_ArrayWidth = arrayWidth;
436 1461762 : m_SpatialDivisionsData = new std::vector<entity_id_t>[m_ArrayWidth*m_ArrayWidth];
437 2109 : m_OverSizedData.clear();
438 2109 : }
439 :
440 1068 : void Reset(fixed w, fixed h)
441 : {
442 1068 : ENSURE(w >= fixed::Zero() && h >= fixed::Zero());
443 3204 : size_t arrayWidth = std::max((w / SUBDIVISION_SIZE).ToInt_RoundToZero(), (h / SUBDIVISION_SIZE).ToInt_RoundToZero()) + 1;
444 1068 : Reset(arrayWidth);
445 1068 : }
446 :
447 : FastSpatialSubdivision& operator=(const FastSpatialSubdivision& other)
448 : {
449 : if (this != &other)
450 : {
451 : Reset(other.m_ArrayWidth);
452 : std::copy(&other.m_SpatialDivisionsData[0], &other.m_SpatialDivisionsData[m_ArrayWidth*m_ArrayWidth], m_SpatialDivisionsData);
453 : }
454 : return *this;
455 : }
456 :
457 1041 : bool operator==(const FastSpatialSubdivision& other) const
458 : {
459 1041 : if (m_ArrayWidth != other.m_ArrayWidth)
460 : return false;
461 1041 : if (m_OverSizedData != other.m_OverSizedData)
462 : return false;
463 703236 : for (size_t idx = 0; idx < m_ArrayWidth*m_ArrayWidth; ++idx)
464 702195 : if (m_SpatialDivisionsData[idx] != other.m_SpatialDivisionsData[idx])
465 : return false;
466 : return true;
467 : }
468 :
469 1041 : inline bool operator!=(const FastSpatialSubdivision& rhs) const
470 : {
471 1041 : return !(*this == rhs);
472 : }
473 :
474 : /**
475 : * Add an item.
476 : */
477 1226 : void Add(entity_id_t item, CFixedVector2D position, std::uint32_t size)
478 : {
479 1226 : if (size > SUBDIVISION_SIZE)
480 : {
481 0 : if (std::find(m_OverSizedData.begin(), m_OverSizedData.end(), item) == m_OverSizedData.end())
482 0 : m_OverSizedData.push_back(item);
483 : }
484 : else
485 : {
486 1226 : std::vector<entity_id_t>& subdivision = m_SpatialDivisionsData[SubdivisionIdx(position)];
487 1226 : if (std::find(subdivision.begin(), subdivision.end(), item) == subdivision.end())
488 1226 : subdivision.push_back(item);
489 : }
490 1226 : }
491 :
492 : /**
493 : * Remove an item.
494 : * Position must be where we expect to find it, or we won't find it.
495 : */
496 30 : void Remove(entity_id_t item, CFixedVector2D position, std::uint32_t size)
497 : {
498 30 : if (size > SUBDIVISION_SIZE)
499 0 : EraseFrom(m_OverSizedData, item);
500 : else
501 : {
502 30 : std::vector<entity_id_t>& subdivision = m_SpatialDivisionsData[SubdivisionIdx(position)];
503 30 : EraseFrom(subdivision, item);
504 : }
505 30 : }
506 :
507 : /**
508 : * Equivalent to Remove() then Add(), but slightly faster.
509 : * In particular for big objects nothing needs to be done.
510 : */
511 8772 : void Move(entity_id_t item, CFixedVector2D oldPosition, CFixedVector2D newPosition, std::uint32_t size)
512 : {
513 8772 : if (size > SUBDIVISION_SIZE)
514 : return;
515 8772 : if (SubdivisionIdx(newPosition) == SubdivisionIdx(oldPosition))
516 : return;
517 :
518 1770 : std::vector<entity_id_t>& oldSubdivision = m_SpatialDivisionsData[SubdivisionIdx(oldPosition)];
519 1770 : if (EraseFrom(oldSubdivision, item))
520 : {
521 1770 : std::vector<entity_id_t>& newSubdivision = m_SpatialDivisionsData[SubdivisionIdx(newPosition)];
522 1770 : newSubdivision.push_back(item);
523 : }
524 : }
525 :
526 : /**
527 : * Returns a (non sorted) list of items that are either in the square or close to it.
528 : * It's the responsibility of the querier to do proper distance checking and entity sorting.
529 : */
530 411 : void GetInRange(std::vector<entity_id_t>& out, CFixedVector2D posMin, CFixedVector2D posMax) const
531 : {
532 411 : size_t minX = Index(posMin.X);
533 411 : size_t minY = Index(posMin.Y);
534 411 : size_t maxX = Index(posMax.X) + 1;
535 411 : size_t maxY = Index(posMax.Y) + 1;
536 :
537 : // Now expand the subdivisions by one so we make sure we've got all elements potentially in range.
538 : // Also make sure min >= 0 and max <= width
539 411 : minX = minX > 0 ? minX-1 : 0;
540 411 : minY = minY > 0 ? minY-1 : 0;
541 411 : maxX = maxX < m_ArrayWidth ? maxX+1 : m_ArrayWidth;
542 411 : maxY = maxY < m_ArrayWidth ? maxY+1 : m_ArrayWidth;
543 :
544 411 : ENSURE(out.empty() && "GetInRange: out is not clean");
545 :
546 : // Add oversized items, they can be anywhere
547 411 : out.insert(out.end(), m_OverSizedData.begin(), m_OverSizedData.end());
548 :
549 2036 : for (size_t Y = minY; Y < maxY; ++Y)
550 : {
551 6916 : for (size_t X = minX; X < maxX; ++X)
552 : {
553 5291 : std::vector<entity_id_t>& subdivision = m_SpatialDivisionsData[X + Y*m_ArrayWidth];
554 5291 : if (!subdivision.empty())
555 2056 : out.insert(out.end(), subdivision.begin(), subdivision.end());
556 : }
557 : }
558 411 : }
559 :
560 : /**
561 : * Returns a (non sorted) list of items that are either in the circle or close to it.
562 : * It's the responsibility of the querier to do proper distance checking and entity sorting.
563 : */
564 411 : void GetNear(std::vector<entity_id_t>& out, CFixedVector2D pos, entity_pos_t range) const
565 : {
566 : // Because the subdivision size is rather big wrt typical ranges,
567 : // this square over-approximation is hopefully not too bad.
568 411 : CFixedVector2D r(range, range);
569 411 : GetInRange(out, pos - r, pos + r);
570 411 : }
571 :
572 : size_t GetDivisionSize() const
573 : {
574 : return SUBDIVISION_SIZE;
575 : }
576 :
577 0 : size_t GetWidth() const
578 : {
579 0 : return m_ArrayWidth;
580 : }
581 : };
582 :
583 : #endif // INCLUDED_SPATIAL
|