Saga
Saga Game Engine
Loading...
Searching...
No Matches
componentReference.h
Go to the documentation of this file.
1#pragma once
2
3#include <memory>
4#include "../Entity/entity.h"
6#include <iostream>
7
8namespace Saga {
9
15template <typename Component>
17public:
28 ComponentReference(std::shared_ptr<ComponentContainer<Component>> componentContainer, Entity entity)
29 : componentContainer(componentContainer), entity(entity) {}
30
34 virtual ~ComponentReference() {};
35
42 operator Component*() { return getVolatile(); }
43
49 Component* operator->() { return getVolatile(); }
50
51private:
52 // will be wonky behaviour if you encounter the ABA problem. But if you do it's not really the engine's fault is it
53 int lastReallocated = -1;
54 Component* cachedComponent = nullptr;
55 std::shared_ptr<ComponentContainer<Component>> componentContainer;
56 Entity entity;
57
63 Component* getVolatile() {
64 if (!componentContainer) return nullptr;
65 // if reallocated, we need to fetch a new cache
66 if (componentContainer->getLastReallocated() > lastReallocated) {
67 cachedComponent = componentContainer->getComponent(entity);
68 lastReallocated = componentContainer->getLastReallocated();
69 }
70 return cachedComponent;
71 }
72};
73
74} // namespace Saga
75
Container for a specific Component type.
Definition: componentContainer.h:39
Reference to a component. Will be valid as long as that component exists on a specific Entity,...
Definition: componentReference.h:16
ComponentReference(std::shared_ptr< ComponentContainer< Component > > componentContainer, Entity entity)
Construct a new Component Reference object.
Definition: componentReference.h:28
ComponentReference()
Construct a new Component Reference object.
Definition: componentReference.h:21
virtual ~ComponentReference()
Destroy the Component Reference object.
Definition: componentReference.h:34
Component * operator->()
Automatic cast of ComponentReference to their volatile Component pointer form.
Definition: componentReference.h:49
Definition: app.cpp:8