spatial_grid.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #pragma once
  2. #include "../core/entity.h"
  3. #include <cmath>
  4. #include <unordered_map>
  5. #include <vector>
  6. namespace Game::Systems {
  7. class SpatialGrid {
  8. public:
  9. explicit SpatialGrid(float cell_size = 10.0F);
  10. void clear();
  11. void insert(Engine::Core::EntityID entity_id, float x, float z);
  12. void remove(Engine::Core::EntityID entity_id);
  13. void update(Engine::Core::EntityID entity_id, float x, float z);
  14. [[nodiscard]] auto get_entities_in_range(float x, float z, float range) const
  15. -> std::vector<Engine::Core::EntityID>;
  16. [[nodiscard]] auto get_nearby_entities(float x, float z) const
  17. -> std::vector<Engine::Core::EntityID>;
  18. private:
  19. struct CellKey {
  20. int x;
  21. int z;
  22. auto operator==(const CellKey &other) const -> bool {
  23. return x == other.x && z == other.z;
  24. }
  25. };
  26. struct CellKeyHash {
  27. auto operator()(const CellKey &key) const -> std::size_t {
  28. return std::hash<int>()(key.x) ^ (std::hash<int>()(key.z) << 16);
  29. }
  30. };
  31. [[nodiscard]] auto to_cell_key(float x, float z) const -> CellKey;
  32. float m_cell_size;
  33. float m_inv_cell_size;
  34. std::unordered_map<CellKey, std::vector<Engine::Core::EntityID>, CellKeyHash>
  35. m_cells;
  36. std::unordered_map<Engine::Core::EntityID, CellKey> m_entity_cells;
  37. };
  38. } // namespace Game::Systems