-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEntityManager.h
372 lines (308 loc) · 12.6 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
#pragma once
#include "_Plugin.h"
#include <Urho3D/Core/Signal.h>
#include <Urho3D/Scene/LogicComponent.h>
#include <Urho3D/Scene/TrackedComponent.h>
#include <entt/entt.hpp>
#include <EASTL/unique_ptr.h>
// Support formatting for entt::entity.
template <> struct fmt::formatter<entt::entity>
{
constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator
{
// TODO: Support formatting specifiers
return ctx.begin();
}
auto format(const entt::entity& value, format_context& ctx) const -> format_context::iterator
{
return fmt::format_to(
ctx.out(), "{}:{}", static_cast<unsigned>(entt::to_entity(value)), entt::to_version(value));
}
};
namespace Urho3D
{
class EntityReference;
/// Component that is used to tag currently materialized entities.
/// EntityReference is expected to be valid.
struct EntityMaterialized
{
WeakPtr<EntityReference> entityReference_;
};
/// Component that is used to tag entities with updated transforms.
/// It is up to the user to clear this component when it's not needed anymore.
struct EntityTransformDirty
{
static constexpr unsigned Version = 1;
void SerializeInBlock(Archive& archive, unsigned version) {}
bool RenderInspector() { return false; }
};
/// Interface to manage EnTT components.
class PLUGIN_CORE_ENTITYMANAGER_API EntityComponentFactory
{
public:
EntityComponentFactory(const ea::string& name);
const ea::string& GetName() const { return name_; }
virtual bool IsEmpty() const = 0;
virtual unsigned GetVersion() const = 0;
virtual bool HasComponent(entt::registry& registry, entt::entity entity) = 0;
virtual void CreateComponent(entt::registry& registry, entt::entity entity) = 0;
virtual void DestroyComponent(entt::registry& registry, entt::entity entity) = 0;
virtual void SerializeComponent(
Archive& archive, entt::registry& registry, entt::entity entity, unsigned version) = 0;
virtual void SerializeComponents(Archive& archive, entt::registry& registry, unsigned version) = 0;
virtual bool RenderUI(entt::registry& registry, entt::entity entity) = 0;
virtual void CommitActions(entt::registry& registry) = 0;
private:
ea::string name_;
};
/// Subsystem that stores and manages EnTT entities.
/// Don't remove this component from the scene if you have any entities!
class PLUGIN_CORE_ENTITYMANAGER_API EntityManager : public TrackedComponentRegistryBase
{
URHO3D_OBJECT(EntityManager, TrackedComponentRegistryBase);
public:
Signal<void(entt::registry& registry, entt::entity entity, EntityReference* reference)> OnEntityMaterialized;
Signal<void(entt::registry& registry, entt::entity entity, EntityReference* reference)> OnEntityDematerialized;
Signal<void(entt::registry& registry)> OnPostUpdateSynchronized;
EntityManager(Context* context);
static void RegisterObject(Context* context);
void ApplyAttributes() override;
bool HasAuxiliaryData() const override { return true; }
void SerializeAuxiliaryData(Archive& archive) override;
/// Support inspector UI.
/// @{
bool RenderManagerInspector();
bool RenderEntityInspector(entt::entity entity);
void CommitActions();
/// @}
/// Synchronize pending EntityReference additions with the registry.
void Synchronize();
/// Register new EnTT component type.
/// It should be done as soon as possible, preferably in the constructor of derived class.
void AddComponentType(ea::unique_ptr<EntityComponentFactory> factory);
template <class T> void AddComponentType(const ea::string& name);
EntityComponentFactory* FindComponentType(ea::string_view name) const;
bool IsEntityValid(entt::entity entity) const;
EntityReference* EntityToReference(entt::entity entity) const;
Node* EntityToNode(entt::entity entity) const;
entt::entity NodeToEntity(Node* node) const;
static Variant EntityToVariant(entt::entity entity);
static entt::entity VariantToEntity(const Variant& variant);
bool IsEntityMaterialized(entt::entity entity) const;
EntityReference* MaterializeEntity(entt::entity entity);
void DematerializeEntity(entt::entity entity);
/// Per-entity serialization. Use with caution.
/// @{
ByteVector EncodeEntity(entt::registry& registry, entt::entity entity);
void DecodeEntity(entt::registry& registry, entt::entity entity, const ByteVector& data);
ea::vector<entt::entity> GetEntities() const;
ByteVector EncodeEntity(entt::entity entity);
void DecodeEntity(entt::entity entity, const ByteVector& data);
void QueueDecodeEntity(EntityReference* entityReference, const ByteVector& data);
/// @}
/// Getters.
/// @{
entt::registry& Registry() { return registry_; }
/// @}
/// Attributes.
/// @{
void SetDataAttr(const ByteVector& data);
ByteVector GetDataAttr() const;
bool GetPlaceholderAttr() const { return false; }
void SetPlaceholderAttr(bool placeholder);
/// @}
/// Utilities.
/// @{
static unsigned GetEntityVersion(entt::entity entity);
static unsigned GetEntityIndex(entt::entity entity);
template <class T>
static void SerializeComponents(Archive& archive, const char* name, entt::registry& registry, unsigned version);
/// @}
protected:
/// Implement TrackedComponentRegistryBase.
/// @{
void OnComponentAdded(TrackedComponentBase* baseComponent) override;
void OnComponentRemoved(TrackedComponentBase* baseComponent) override;
void OnAddedToScene(Scene* scene) override;
void OnRemovedFromScene() override;
/// @}
/// Return display label for the entity.
virtual ea::string GetEntityLabel(entt::entity entity) const;
/// Post-update synchronization. Executed even if the Scene is paused.
virtual void ForcedPostUpdate();
entt::registry registry_;
private:
/// Comparator to sort entities by their index.
struct EntityIndexComparator
{
bool operator()(entt::entity lhs, entt::entity rhs) const
{
return EntityManager::GetEntityIndex(lhs) < EntityManager::GetEntityIndex(rhs);
}
};
void EnsureComponentTypesSorted();
void EnsureEntitiesMaterialized();
void SerializeRegistry(Archive& archive);
void SerializeEntities(Archive& archive);
void SerializeUserComponents(Archive& archive);
void SerializeStandaloneEntity(Archive& archive, entt::registry& registry, entt::entity entity);
void RenderEntityHeader(entt::entity entity);
EntityComponentFactory* RenderCreateComponent(entt::entity entity);
bool RenderExistingComponents(entt::entity entity);
ea::string entitiesContainerName_;
WeakPtr<Node> entitiesContainer_;
ea::vector<ea::unique_ptr<EntityComponentFactory>> componentFactories_;
bool componentTypesSorted_{};
bool registryDirty_{};
ea::unordered_set<WeakPtr<EntityReference>> pendingEntitiesAdded_;
ea::vector<ea::pair<WeakPtr<EntityReference>, ByteVector>> pendingEntityDecodes_;
bool synchronizationInProgress_{};
bool suppressComponentEvents_{};
struct EditorUI
{
ea::vector<ea::pair<entt::entity, bool>> pendingMaterializations_;
ea::vector<ea::pair<entt::entity, EntityComponentFactory*>> pendingCreateComponents_;
ea::vector<ea::pair<entt::entity, EntityComponentFactory*>> pendingDestroyComponents_;
ea::vector<EntityComponentFactory*> pendingEditComponents_;
} ui_;
};
/// Default implementation of EntityComponentFactory.
/// T is expected to have certain functions and static members.
template <class T> class DefaultEntityComponentFactory : public EntityComponentFactory
{
public:
using EntityComponentFactory::EntityComponentFactory;
/// Implement EntityComponentFactory.
/// @{
bool IsEmpty() const override { return std::is_empty_v<T>; }
unsigned GetVersion() const override { return T::Version; }
bool HasComponent(entt::registry& registry, entt::entity entity) override;
void CreateComponent(entt::registry& registry, entt::entity entity) override;
void DestroyComponent(entt::registry& registry, entt::entity entity) override;
void SerializeComponent(Archive& archive, entt::registry& registry, entt::entity entity, unsigned version) override;
void SerializeComponents(Archive& archive, entt::registry& registry, unsigned version) override;
bool RenderUI(entt::registry& registry, entt::entity entity) override;
void CommitActions(entt::registry& registry) override;
/// @}
private:
ea::string name_;
struct PendingEditAction
{
entt::entity entity_;
T newValue_;
};
ea::vector<PendingEditAction> pendingEditActions_;
};
} // namespace Urho3D
namespace Urho3D
{
template <class T> void EntityManager::AddComponentType(const ea::string& name)
{
AddComponentType(ea::make_unique<DefaultEntityComponentFactory<T>>(name));
}
template <class T>
void EntityManager::SerializeComponents(Archive& archive, const char* name, entt::registry& registry, unsigned version)
{
auto& storage = registry.storage<T>();
const auto numComponents = static_cast<unsigned>(storage.size());
const auto block = archive.OpenArrayBlock(name, numComponents);
if (archive.IsInput())
{
for (unsigned i = 0; i < block.GetSizeHint(); ++i)
{
const auto elementBlock = archive.OpenUnorderedBlock("component");
unsigned entityData = 0;
archive.Serialize("_entity", entityData);
const auto entity = static_cast<entt::entity>(entityData);
if constexpr (!std::is_empty_v<T>)
{
auto& component = registry.emplace_or_replace<T>(entity);
component.SerializeInBlock(archive, version);
}
else
{
registry.emplace_or_replace<T>(entity);
}
}
}
else
{
static thread_local ea::vector<entt::entity> entitiesBuffer;
auto& entities = entitiesBuffer;
const auto view = registry.view<T>();
entities.assign(view.begin(), view.end());
ea::sort(entities.begin(), entities.end(), EntityIndexComparator{});
for (const entt::entity entity : entities)
{
const auto elementBlock = archive.OpenUnorderedBlock("component");
auto entityData = static_cast<unsigned>(entity);
archive.Serialize("_entity", entityData);
if constexpr (!std::is_empty_v<T>)
{
auto& component = registry.get<T>(entity);
component.SerializeInBlock(archive, version);
}
};
}
}
template <class T> bool DefaultEntityComponentFactory<T>::HasComponent(entt::registry& registry, entt::entity entity)
{
const auto& storage = registry.storage<T>();
return storage.contains(entity);
}
template <class T> void DefaultEntityComponentFactory<T>::CreateComponent(entt::registry& registry, entt::entity entity)
{
(void)registry.emplace<T>(entity);
}
template <class T>
void DefaultEntityComponentFactory<T>::DestroyComponent(entt::registry& registry, entt::entity entity)
{
registry.remove<T>(entity);
}
template <class T>
void DefaultEntityComponentFactory<T>::SerializeComponent(
Archive& archive, entt::registry& registry, entt::entity entity, unsigned version)
{
if constexpr (!std::is_empty_v<T>)
{
auto& component = registry.get<T>(entity);
component.SerializeInBlock(archive, version);
}
}
template <class T>
void DefaultEntityComponentFactory<T>::SerializeComponents(Archive& archive, entt::registry& registry, unsigned version)
{
EntityManager::SerializeComponents<T>(archive, "components", registry, version);
}
template <class T> bool DefaultEntityComponentFactory<T>::RenderUI(entt::registry& registry, entt::entity entity)
{
if constexpr (!std::is_empty_v<T>)
{
T& component = registry.get<T>(entity);
const T backup = component;
if (component.RenderInspector())
{
PendingEditAction action;
action.entity_ = entity;
action.newValue_ = component;
component = backup;
pendingEditActions_.push_back(action);
return true;
}
}
return false;
}
template <class T> void DefaultEntityComponentFactory<T>::CommitActions(entt::registry& registry)
{
for (const PendingEditAction& action : pendingEditActions_)
{
if (!registry.valid(action.entity_))
{
URHO3D_LOGERROR("Cannot edit component '{}' in entity {}", GetName(), action.entity_);
continue;
}
registry.replace<T>(action.entity_, action.newValue_);
}
pendingEditActions_.clear();
}
} // namespace Urho3D