-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathentitymanager.h
785 lines (725 loc) · 24 KB
/
entitymanager.h
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
#ifndef COMPONENTMANAGER_H
#define COMPONENTMANAGER_H
#include "componentdata.h"
#include <typeinfo>
#include <vector>
#include "resourcemanager.h"
#include <QObject>
#include <QDebug>
#include <queue>
/** Precompiler directives
* We had to instance some template functions,
* so then we templated the instanced functions
* with a precompiler directive.
* These defines replace some codes with their
* respective instanced typename K.
* This removed a lot of bloat and copy pasting of code.
*/
/** Registers the component in the manager
* 1. Constructs the vector container for the components of type K.
* 2. Creates a getter of the vector used in the corresponding systems that needs them.
* 3. Creates a getter for a given entity.
* 4. Creates a remove component function for a given entity.
* 5. Creates an add component function for a given entity.
*/
#define REGISTER(K) \
private: \
std::vector<K> CONCATENATE(m, K, s); \
public: \
std::vector<K>& CONCATENATE(get, K, s)() { return CONCATENATE(m, K, s); } \
GETCOMPONENT(K) \
REMOVECOMPONENT(K) \
private: \
ADDCOMPONENT(K) \
#define GETCOMPONENT(K) \
template<class T, \
typename std::enable_if<(std::is_same<K, T>::value)>::type* = nullptr> \
T* getComponent(unsigned int entity) \
{ \
auto result = find(CONCATENATE(m, K, s).begin(), CONCATENATE(m, K, s).end(), entity); \
return result == CONCATENATE(m, K, s).end() ? nullptr : &(*result); \
} \
#define REMOVECOMPONENT(K) \
template<class T, \
typename std::enable_if<(std::is_same<K, T>::value)>::type* = nullptr> \
bool removeComponent(unsigned int entity) \
{ return removeComponent(CONCATENATE(m, K, s), entity); } \
#define ADDCOMPONENT(K) \
template<class T, \
typename std::enable_if<(std::is_same<K, T>::value)>::type* = nullptr> \
T& addComponents(unsigned int entity) \
{ return addComponent(CONCATENATE(m, K, s), entity); } \
#define CONCATENATE( x, y, z) x##y##z
/** Manages all entities and their components.
* Constructs and destructs entities and manages
* component data for each entity.
*
* @brief Manages all entities and their components.
*
* @author andesyv, Skau
*/
class EntityManager : public QObject
{
Q_OBJECT
REGISTER(TransformComponent)
REGISTER(MeshComponent)
REGISTER(PhysicsComponent)
REGISTER(CameraComponent)
REGISTER(InputComponent)
REGISTER(SoundComponent)
REGISTER(DirectionalLightComponent)
REGISTER(SpotLightComponent)
REGISTER(PointLightComponent)
REGISTER(ScriptComponent)
REGISTER(ColliderComponent)
REGISTER(ParticleComponent)
REGISTER(EntityInfo)
private:
// ------------------------------ Member Variables -----------------------------
std::vector<unsigned> entitiesToDestroy;
unsigned int idCounter{0};
void removeEntity(unsigned entity)
{
for(auto& comp : getAllComponents(entity))
{
comp->valid = false;
// comp->reset();
}
for(unsigned i = 0; i < mEntityInfos.size(); ++i)
{
if(mEntityInfos[i].entityId == entity)
{
mEntityInfos.erase(mEntityInfos.begin() + i);
break;
}
}
}
signals:
void updateUI(const std::vector<EntityInfo>& entityData);
// ------------------------- Member functions ---------------
public:
EntityManager()
{
}
/** Resets all components to be "empty" while keeping memory allocation.
* @brief Clears the entitymanager.
*/
void clear()
{
for(auto info : mEntityInfos)
{
for(auto& comp : getAllComponents(info.entityId))
{
comp->valid = false;
comp->reset();
}
}
idCounter = 0;
mEntityInfos.clear();
updateUI({});
}
/**
* @brief Creates an object based on the index.
* @param Index 0: Empty entity, index 1: Cube, index 2: Monkey.
*/
void createObject(int index)
{
switch (index)
{
case 0:
{
createEntity();
break;
}
case 1:
{
createCube();
break;
}
case 2:
{
createMonkey();
break;
}
}
}
/**
* @brief Sets up and returns a new entity with an optional name.
*/
unsigned int createEntity(std::string name = "")
{
auto id = ++idCounter;
EntityInfo entityInfo;
entityInfo.entityId = id;
entityInfo.valid = true;
if(!name.size())
{
name = "Entity" + std::to_string(id);
}
entityInfo.name = name;
mEntityInfos.push_back(entityInfo);
updateUI(mEntityInfos);
return id;
}
/**
* @brief Sets up a new cube. Automatically sets all needed components and meshdata.
*/
unsigned createCube()
{
auto id = createEntity();
addComponent<MeshComponent, TransformComponent>(id);
auto render = getComponent<MeshComponent>(id);
if(auto mesh = ResourceManager::instance().getMesh("box2"))
{
render->meshData = *mesh;
render->isVisible = true;
}
return id;
}
/**
* @brief Sets up a new monkey. Automatically sets all needed components and meshdata.
*/
unsigned createMonkey()
{
auto id = createEntity();
addComponent<MeshComponent, TransformComponent>(id);
auto render = getComponent<MeshComponent>(id);
if(auto mesh = ResourceManager::instance().getMesh("suzanne"))
{
render->meshData = *mesh;
render->isVisible = true;
}
return id;
}
/**
* @brief Marks an entity for deletion at the end of the frame (deferred destruction).
*/
void removeEntityLater(unsigned entity)
{
entitiesToDestroy.push_back(entity);
}
/**
* @brief Removes all entities marked for destruction. Called at the end of the update loop.
*/
void removeEntitiesMarked()
{
if(entitiesToDestroy.empty())
return;
for(auto& entity : entitiesToDestroy)
{
removeEntity(entity);
}
entitiesToDestroy.clear();
}
/** Runs a function on a entity component based on components in template.
* Uses variadic template packing and std::function to take in a varying number
* of parameters, attempts to get the components specified and sends them as
* parameters to the function.
* @param componentTypes - the different component types to get
* @param eID - entityID
* @param f - std::function wrapper object of function with equal parameter count
* as the count of componentTypes.
*/
template <typename... componentTypes>
void transform(unsigned int eID, const std::function<void(componentTypes*...)>& f)
{
auto comps = getComponents<componentTypes...>(eID);
std::apply(f, comps);
}
/** Runs a function on a entity component based on components in template.
* Similar to other version, but takes a lambda instead of a std::function,
* but lambda type needs to be sent in as first template parameter for
* compiler to understand. (use decltype on lambda to get type)
* @param FT - Lambda Type
* @param componentTypes - the different component types to get
* @param eID - entityID
* @param f - lambda for function with equal parameter count
*/
template <typename FT, typename... componentTypes>
void transform(unsigned int eID, FT f)
{
auto comps = getComponents<componentTypes...>(eID);
std::apply(f, comps);
}
/**
* @brief Variadic template function that adds all components types given to an entity
*/
template<typename... componentTypes>
std::tuple<componentTypes&...> addComponent(unsigned int entity)
{
return {addComponents<componentTypes>(entity)...};
}
/**
* @brief Variadic template function that returns all component types given for an entity.
* @return Returns a tuple containing the components. If the entity does not have the respective component
* the variable will be null.
*
*/
template<typename... componentTypes>
std::tuple<componentTypes*...> getComponents(unsigned int entity)
{
return {getComponent<componentTypes>(entity)...};
}
/**
* @brief Adds a component to a given entity using the ComponentType enum.
*/
Component* addComponent(unsigned int entity, ComponentType type)
{
Component* returnComp{nullptr};
switch (type)
{
case ComponentType::Mesh:
{
auto [component] = addComponent<MeshComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Transform:
{
auto [component] = addComponent<TransformComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Physics:
{
auto [component] = addComponent<PhysicsComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Camera:
{
auto [component] = addComponent<CameraComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Input:
{
auto [component] = addComponent<InputComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Sound:
{
auto [component] = addComponent<SoundComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::LightSpot:
{
auto [component] = addComponent<SpotLightComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::LightDirectional:
{
auto [component] = addComponent<DirectionalLightComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::LightPoint:
{
auto [component] = addComponent<PointLightComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Script:
{
auto [component] = addComponent<ScriptComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Collider:
{
auto [component] = addComponent<ColliderComponent>(entity);
returnComp = &component;
break;
}
case ComponentType::Particle:
{
auto [component] = addComponent<ParticleComponent>(entity);
returnComp = &component;
break;
}
default:
break;
}
return returnComp;
}
/**
* @brief Gets a component to a given entity using the ComponentType enum.
*/
Component* getComponent(unsigned int entity, ComponentType type)
{
Component* returnComp{nullptr};
switch (type)
{
case ComponentType::Mesh:
{
returnComp = getComponent<MeshComponent>(entity);
break;
}
case ComponentType::Transform:
{
returnComp = getComponent<TransformComponent>(entity);
break;
}
case ComponentType::Physics:
{
returnComp = getComponent<PhysicsComponent>(entity);
break;
}
case ComponentType::Camera:
{
returnComp = getComponent<CameraComponent>(entity);
break;
}
case ComponentType::Input:
{
returnComp = getComponent<InputComponent>(entity);
break;
}
case ComponentType::Sound:
{
returnComp = getComponent<SoundComponent>(entity);
break;
}
case ComponentType::LightSpot:
{
returnComp = getComponent<SpotLightComponent>(entity);
break;
}
case ComponentType::LightDirectional:
{
returnComp = getComponent<DirectionalLightComponent>(entity);
break;
}
case ComponentType::LightPoint:
{
returnComp = getComponent<PointLightComponent>(entity);
break;
}
case ComponentType::Script:
{
returnComp = getComponent<ScriptComponent>(entity);
break;
}
case ComponentType::Collider:
{
returnComp = getComponent<ColliderComponent>(entity);
break;
}
case ComponentType::Particle:
{
returnComp = getComponent<ParticleComponent>(entity);
break;
}
default:
break;
}
return returnComp;
}
/**
* @brief Returns all components for a given entity.
*/
std::vector<Component*> getAllComponents(unsigned int entity)
{
std::vector<Component*> components;
if(auto comp = getComponent<TransformComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<MeshComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<PhysicsComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<CameraComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<InputComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<SoundComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<DirectionalLightComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<SpotLightComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<PointLightComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<ScriptComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
if(auto comp = getComponent<ColliderComponent>(entity))
{
if(comp->valid)
{
components.push_back(comp);
}
}
return components;
}
public:
// ---------------------------- Helper functions ---------------------------
void print() {
std::cout << "transforms: ";
for (auto comp : mTransformComponents)
std::cout << "{id: " << comp.entityId << ", valid: " << comp.valid << "} ";
std::cout << std::endl << "renders: ";
for (auto comp : mMeshComponents)
std::cout << "{id: " << comp.entityId << ", valid: " << comp.valid << "} ";
std::cout << std::endl;
}
/** Finds a component for a given entity.
* Searches from begin to end in a certain component array to find
* a component with the specified entityID and returns a iterator
* to it if found and end iterator otherwise.
* @param begin - startpos to search from. Inclusive.
* @param end - endpos to search to. Exclusive.
* @param eID - entityID for component to find.
* @return iterator to object or iterator to end otherwise
*/
template <typename iterator>
static iterator find(const iterator& begin, const iterator& end, unsigned int eID)
{
auto result = std::lower_bound(begin, end, eID, [](const typename iterator::value_type& a, const unsigned int& b)
{
return a.entityId < b;
});
return (result != end && result->valid && result->entityId == eID) ? result : end;
}
/** Implementation of binary search to use in other functions.
* This function should be more of a guideline in how to use
* binary search and usage should just copy this function.
*/
template <typename iterator, typename comp = std::less<typename iterator::value_type>>
static iterator binarySearch(const iterator& begin, const iterator& end, const typename iterator::value_type& value, comp compare = comp())
{
auto result = std::lower_bound(begin, end, value, compare);
// If lower_bound found something and it's not lower or higher, then it found it. Return position.
return (result != end && !(compare(*result, value) || compare(value, *result))) ? result : end;
}
/** Adds a component to the a specified component vector.
* Searches first through the component array for a unvalid component,
* and if found uses that one instead of allocating room for more.
* If none is found then it resizes the vector and emblaces the component
* at the end.
*
* This function also sorts the array after adding a component.
* @param list - vector of components. Type must be T = std::vector<T>
* @param entity - entityId for component to add.
* @return the new component that was added to the entity
*/
template<class T>
typename T::value_type& addComponent(T& list, unsigned int entity)
{
typedef typename T::value_type VT;
// Check if object already exist and if so just return that one instead.
auto obj = find(list.begin(), list.end(), entity);
if (obj != list.end())
return *obj;
for (auto it{list.begin()}; it != list.end(); ++it)
{
if (!it->valid)
{
it->~VT();
new (&(*it)) VT{entity, true};
std::sort(it, list.end(),[](const VT& t1, const VT& t2)
{
return t1.entityId < t2.entityId;
});
if (it->entityId == entity)
return *it;
else
{
return *std::lower_bound(it, list.end(), entity, [](const VT& a, const unsigned int& b){
return a.entityId < b;
});
}
}
}
list.emplace_back(entity, true);
auto &comp = list.back();
std::sort(list.begin(), list.end(),[](const VT& t1, const VT& t2)
{
return t1.entityId < t2.entityId;
});
if (comp.entityId == entity)
return comp;
else
return *std::lower_bound(list.begin(), list.end(), entity, [](const VT& a, const unsigned int& b){
return a.entityId < b;
});
}
/** Removes a component from the specified component vector.
* This function just marks the component as unvalid so that
* the next addComponent call can use the spot instead of
* allocating new storage.
* @param list - vector of components. Type must be T = std::vector<T>
* @param entity - entityId for component to add.
* @param true if component was removed and false if operation failed.
*/
template<class T>
bool removeComponent(T& list, unsigned int entity)
{
typedef typename T::value_type VT;
auto it = std::lower_bound(list.begin(), list.end(), entity, [](const VT& a, const unsigned int& b){
return a.entityId < b;
});
if (it != list.end() && it->entityId == entity)
{
if (it->valid)
{
it->valid = false;
return true;
}
}
return false;
}
/** Breadth first search iterator for iterating through entity children
* in a tree-like fashion.
* @brief Parent-child breadth first search iterator
*/
class TreeIterator
{
private:
struct ChildInfo
{
unsigned int eID;
int parentID{-1};
} currentChild;
EntityManager *EM;
TransformComponent* mCurrent;
std::queue<ChildInfo> mNext{};
std::queue<ChildInfo> mNextNext{};
unsigned int mLevel{0};
void findChilds()
{
for (auto eID{mCurrent->children.begin()}; eID != mCurrent->children.end(); ++eID)
{
mNextNext.push({*eID, static_cast<int>(mCurrent->entityId)});
}
}
public:
TreeIterator(EntityManager* entityManager, unsigned int startId)
: currentChild{startId}, EM{entityManager}, mCurrent{EM->getComponent<TransformComponent>(startId)}
{
if (mCurrent != nullptr)
findChilds();
}
TreeIterator(EntityManager* entityManager, TransformComponent* current)
: EM{entityManager}, mCurrent{current}
{
}
TreeIterator& operator++()
{
if (mNext.empty() && !mNextNext.empty())
{
mNext.swap(mNextNext);
++mLevel;
}
if (mNext.empty())
{
mCurrent = nullptr;
}
else
{
while (!mNext.empty())
{
currentChild = mNext.front();
mCurrent = EM->getComponent<TransformComponent>(currentChild.eID);
mNext.pop();
if (mCurrent != nullptr)
{
findChilds();
break;
}
}
}
return *this;
}
bool operator!= (const TreeIterator& it) { return mCurrent != it.mCurrent; }
TransformComponent& operator* () { return *mCurrent; }
TransformComponent* operator-> () { return mCurrent; }
unsigned int getLevel() const { return mLevel; }
int getParentId() const { return currentChild.parentID; }
TransformComponent* getParent()
{
return (currentChild.parentID != -1)
? EM->getComponent<TransformComponent>(static_cast<unsigned int>(currentChild.parentID))
: nullptr;
}
};
// Returns a begin iterator pointing to eID's transform component
TreeIterator treeBegin(unsigned int eID) { return TreeIterator{this, eID}; }
// Returns an end iterator pointing to nothing
TreeIterator treeEnd() { return TreeIterator{this, nullptr}; }
/** Helper functions to add and set position rotation and scale for transforms.
* These functions works just like the components themselves, but does take
* children of entities into account, which component transforms does not.
* @brief transform setters
*/
/// Add transform position with inheritance
void addTransformPos(unsigned int eID, const gsl::vec3& pos);
/// Add transform rotation with inheritance
void addTransformRot(unsigned int eID, const gsl::quat& rot);
/// Add transform scale with inheritance
void addTransformScale(unsigned int eID, const gsl::vec3& scale);
/// Set transform position with inheritance
void setTransformPos(unsigned int eID, const gsl::vec3& pos);
/// Set transform rotation with inheritance
void setTransformRot(unsigned int eID, const gsl::quat& rot);
/// Set transform scale with inheritance
void setTransformScale(unsigned int eID, const gsl::vec3& scale);
gsl::vec3 getTransformPos(unsigned int eID);
gsl::quat getTransformRot(unsigned int eID);
gsl::vec3 getTransformScale(unsigned int eID);
// Updates all transformcomponents bounds
void UpdateBounds();
// static MeshData::Bounds CalculateBounds(const std::vector<Vertex> &vertices);
};
#endif // COMPONENTMANAGER_H