-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
110 lines (86 loc) · 2.71 KB
/
main.cpp
File metadata and controls
110 lines (86 loc) · 2.71 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
#include <assert.h>
#include <iostream>
#include <cstdint>
#include <set>
#include <map>
#include <vector>
class World
{
uint32_t NextEntityID = 0;
std::set<uint32_t> EntityIDs;
public:
uint32_t CreateEntity()
{
const uint32_t ID = NextEntityID;
NextEntityID++;
EntityIDs.insert(ID);
return ID;
}
[[nodiscard]] bool IsEntityValid(uint32_t entityID) const
{
return EntityIDs.contains(entityID);
}
template<typename T>
std::map<uint32_t, T>& GetComponentMap()
{
static std::map<uint32_t, T> componentMap;
return componentMap;
}
template<typename T>
T& GetComponent(uint32_t entityID)
{
assert(IsEntityValid(entityID));
auto& Map = GetComponentMap<T>();
assert(Map.contains(entityID));
return Map.at(entityID);
}
template<typename T>
void AddComponent(uint32_t entityID, const T& component)
{
assert(IsEntityValid(entityID));
GetComponentMap<T>().insert({ entityID, component });
}
template<typename T1, typename T2>
std::vector<uint32_t> Query()
{
std::vector<uint32_t> result;
auto& map1 = GetComponentMap<T1>();
auto& map2 = GetComponentMap<T2>();
for (auto& Pair : map1)
{
if (map2.contains(Pair.first))
result.push_back(Pair.first);
}
return result;
}
};
struct Position { float x, y; };
struct Velocity { float vx, vy; };
struct Health { float hp; };
int main()
{
World TestWorld;
constexpr Health HealthComp = {100.f};
constexpr Position PosComp1 = {0.f, 0.f};
constexpr Position PosComp2 = {5.f, 5.f};
constexpr Position PosComp3 = {10.f, 10.f};
constexpr Velocity VelComp1 = {1.f, 1.f};
constexpr Velocity VelComp2 = {2.f, 0.f};
// Create entities with different components
const uint32_t Entity1 = TestWorld.CreateEntity();
TestWorld.AddComponent<Position>(Entity1, PosComp1);
TestWorld.AddComponent<Velocity>(Entity1, VelComp1);
const uint32_t Entity2 = TestWorld.CreateEntity();
TestWorld.AddComponent<Position>(Entity2, PosComp2);
TestWorld.AddComponent<Health>(Entity2, HealthComp); // <-No Velocity component
const uint32_t Entity3 = TestWorld.CreateEntity();
TestWorld.AddComponent<Position>(Entity3, PosComp3);
TestWorld.AddComponent<Velocity>(Entity3, VelComp2);
//Which entities have [BOTH] Position [AND] Velocity?
const auto MovingEntities = TestWorld.Query<Position, Velocity>();
std::cout << "Entities with Position + Velocity: " << std::endl;
for (uint32_t ID : MovingEntities) {
std::cout << "Entity Index: " << ID << std::endl;
}
return 0;
}