Flecs v3.2
A fast entity component system (ECS) for C & C++
Loading...
Searching...
No Matches
component.hpp
Go to the documentation of this file.
1
6#pragma once
7
8#include <ctype.h>
9#include <stdio.h>
10
19namespace flecs {
20
21namespace _ {
22
23// Trick to obtain typename from type, as described here
24// https://blog.molecular-matters.com/2015/12/11/getting-the-type-of-a-template-argument-as-string-without-rtti/
25//
26// The code from the link has been modified to work with more types, and across
27// multiple compilers. The resulting string should be the same on all platforms
28// for all compilers.
29//
30
31#if defined(__GNUC__) || defined(_WIN32)
32template <typename T>
33inline static const char* type_name() {
34 static const size_t len = ECS_FUNC_TYPE_LEN(const char*, type_name, ECS_FUNC_NAME);
35 static char result[len + 1] = {};
36 static const size_t front_len = ECS_FUNC_NAME_FRONT(const char*, type_name);
37 return ecs_cpp_get_type_name(result, ECS_FUNC_NAME, len, front_len);
38}
39#else
40#error "implicit component registration not supported"
41#endif
42
43// Translate a typename into a language-agnostic identifier. This allows for
44// registration of components/modules across language boundaries.
45template <typename T>
46inline static const char* symbol_name() {
47 static const size_t len = ECS_FUNC_TYPE_LEN(const char*, symbol_name, ECS_FUNC_NAME);
48 static char result[len + 1] = {};
49 return ecs_cpp_get_symbol_name(result, type_name<T>(), len);
50}
51
52template <> inline const char* symbol_name<uint8_t>() {
53 return "u8";
54}
55template <> inline const char* symbol_name<uint16_t>() {
56 return "u16";
57}
58template <> inline const char* symbol_name<uint32_t>() {
59 return "u32";
60}
61template <> inline const char* symbol_name<uint64_t>() {
62 return "u64";
63}
64template <> inline const char* symbol_name<int8_t>() {
65 return "i8";
66}
67template <> inline const char* symbol_name<int16_t>() {
68 return "i16";
69}
70template <> inline const char* symbol_name<int32_t>() {
71 return "i32";
72}
73template <> inline const char* symbol_name<int64_t>() {
74 return "i64";
75}
76template <> inline const char* symbol_name<float>() {
77 return "f32";
78}
79template <> inline const char* symbol_name<double>() {
80 return "f64";
81}
82
83// If type is trivial, don't register lifecycle actions. While the functions
84// that obtain the lifecycle callback do detect whether the callback is required
85// adding a special case for trivial types eases the burden a bit on the
86// compiler as it reduces the number of templates to evaluate.
87template<typename T, enable_if_t<
88 std::is_trivial<T>::value == true
89 >* = nullptr>
90void register_lifecycle_actions(ecs_world_t*, ecs_entity_t) { }
91
92// If the component is non-trivial, register component lifecycle actions.
93// Depending on the type not all callbacks may be available.
94template<typename T, enable_if_t<
95 std::is_trivial<T>::value == false
96 >* = nullptr>
97void register_lifecycle_actions(
100{
101 ecs_type_hooks_t cl{};
102 cl.ctor = ctor<T>();
103 cl.dtor = dtor<T>();
104
105 cl.copy = copy<T>();
106 cl.copy_ctor = copy_ctor<T>();
107 cl.move = move<T>();
108 cl.move_ctor = move_ctor<T>();
109
110 cl.ctor_move_dtor = ctor_move_dtor<T>();
111 cl.move_dtor = move_dtor<T>();
112
114}
115
116// Class that manages component ids across worlds & binaries.
117// The cpp_type class stores the component id for a C++ type in a static global
118// variable that is shared between worlds. Whenever a component is used this
119// class will check if it already has been registered (has the global id been
120// set), and if not, register the component with the world.
121//
122// If the id has been set, the class will ensure it is known by the world. If it
123// is not known the component has been registered by another world and will be
124// registered with the world using the same id. If the id does exist, the class
125// will register it as a component, and verify whether the input is consistent.
126template <typename T>
128 // Initialize component identifier
129 static void init(
130 entity_t entity,
131 bool allow_tag = true)
132 {
133 if (s_reset_count != ecs_cpp_reset_count_get()) {
134 reset();
135 }
136
137 // If an identifier was already set, check for consistency
138 if (s_id) {
139 ecs_assert(s_id == entity, ECS_INCONSISTENT_COMPONENT_ID,
140 type_name<T>());
141 ecs_assert(allow_tag == s_allow_tag, ECS_INVALID_PARAMETER, NULL);
142
143 // Component was already registered and data is consistent with new
144 // identifier, so nothing else to be done.
145 return;
146 }
147
148 // Component wasn't registered yet, set the values. Register component
149 // name as the fully qualified flecs path.
150 s_id = entity;
151 s_allow_tag = allow_tag;
152 s_size = sizeof(T);
153 s_alignment = alignof(T);
154 if (is_empty<T>::value && allow_tag) {
155 s_size = 0;
156 s_alignment = 0;
157 }
158
159 s_reset_count = ecs_cpp_reset_count_get();
160 }
161
162 // Obtain a component identifier for explicit component registration.
163 static entity_t id_explicit(world_t *world = nullptr,
164 const char *name = nullptr, bool allow_tag = true, flecs::id_t id = 0,
165 bool is_component = true, bool *existing = nullptr)
166 {
167 if (!s_id) {
168 // If no world was provided the component cannot be registered
169 ecs_assert(world != nullptr, ECS_COMPONENT_NOT_REGISTERED, name);
170 } else {
171 ecs_assert(!id || s_id == id, ECS_INCONSISTENT_COMPONENT_ID, NULL);
172 }
173
174 // If no id has been registered yet for the component (indicating the
175 // component has not yet been registered, or the component is used
176 // across more than one binary), or if the id does not exists in the
177 // world (indicating a multi-world application), register it.
178 if (!s_id || (world && !ecs_exists(world, s_id))) {
179 init(s_id ? s_id : id, allow_tag);
180
181 ecs_assert(!id || s_id == id, ECS_INTERNAL_ERROR, NULL);
182
183 const char *symbol = nullptr;
184 if (id) {
185 symbol = ecs_get_symbol(world, id);
186 }
187 if (!symbol) {
188 symbol = symbol_name<T>();
189 }
190
191 entity_t entity = ecs_cpp_component_register_explicit(
192 world, s_id, id, name, type_name<T>(), symbol,
193 s_size, s_alignment, is_component, existing);
194
195 s_id = entity;
196
197 // If component is enum type, register constants
198 #if FLECS_CPP_ENUM_REFLECTION_SUPPORT
199 _::init_enum<T>(world, entity);
200 #endif
201 }
202
203 // By now the identifier must be valid and known with the world.
204 ecs_assert(s_id != 0 && ecs_exists(world, s_id),
205 ECS_INTERNAL_ERROR, NULL);
206
207 return s_id;
208 }
209
210 // Obtain a component identifier for implicit component registration. This
211 // is almost the same as id_explicit, except that this operation
212 // automatically registers lifecycle callbacks.
213 // Additionally, implicit registration temporarily resets the scope & with
214 // state of the world, so that the component is not implicitly created with
215 // the scope/with of the code it happens to be first used by.
216 static id_t id(world_t *world = nullptr, const char *name = nullptr,
217 bool allow_tag = true)
218 {
219 // If no id has been registered yet, do it now.
220#ifndef FLECS_CPP_NO_AUTO_REGISTRATION
221 if (!registered(world)) {
222 ecs_entity_t prev_scope = 0;
223 ecs_id_t prev_with = 0;
224
225 if (world) {
226 prev_scope = ecs_set_scope(world, 0);
227 prev_with = ecs_set_with(world, 0);
228 }
229
230 // This will register a component id, but will not register
231 // lifecycle callbacks.
232 bool existing;
233 id_explicit(world, name, allow_tag, 0, true, &existing);
234
235 // Register lifecycle callbacks, but only if the component has a
236 // size. Components that don't have a size are tags, and tags don't
237 // require construction/destruction/copy/move's.
238 if (size() && !existing) {
239 register_lifecycle_actions<T>(world, s_id);
240 }
241
242 if (prev_with) {
243 ecs_set_with(world, prev_with);
244 }
245 if (prev_scope) {
246 ecs_set_scope(world, prev_scope);
247 }
248 }
249#else
250 (void)world;
251 (void)name;
252 (void)allow_tag;
253
254 ecs_assert(registered(world), ECS_INVALID_OPERATION,
255 "component '%s' was not registered before use",
256 type_name<T>());
257#endif
258
259 // By now we should have a valid identifier
260 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
261
262 return s_id;
263 }
264
265 // Return the size of a component.
266 static size_t size() {
267 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
268 return s_size;
269 }
270
271 // Return the alignment of a component.
272 static size_t alignment() {
273 ecs_assert(s_id != 0, ECS_INTERNAL_ERROR, NULL);
274 return s_alignment;
275 }
276
277 // Was the component already registered.
278 static bool registered(flecs::world_t *world) {
279 if (s_reset_count != ecs_cpp_reset_count_get()) {
280 reset();
281 }
282 if (s_id == 0) {
283 return false;
284 }
285 if (world && !ecs_exists(world, s_id)) {
286 return false;
287 }
288 return true;
289 }
290
291 // This function is only used to test cross-translation unit features. No
292 // code other than test cases should invoke this function.
293 static void reset() {
294 s_id = 0;
295 s_size = 0;
296 s_alignment = 0;
297 s_allow_tag = true;
298 }
299
300 static entity_t s_id;
301 static size_t s_size;
302 static size_t s_alignment;
303 static bool s_allow_tag;
304 static int32_t s_reset_count;
305};
306
307// Global templated variables that hold component identifier and other info
308template <typename T> entity_t cpp_type_impl<T>::s_id;
309template <typename T> size_t cpp_type_impl<T>::s_size;
310template <typename T> size_t cpp_type_impl<T>::s_alignment;
311template <typename T> bool cpp_type_impl<T>::s_allow_tag( true );
312template <typename T> int32_t cpp_type_impl<T>::s_reset_count;
313
314// Front facing class for implicitly registering a component & obtaining
315// static component data
316
317// Regular type
318template <typename T>
319struct cpp_type<T, if_not_t< is_pair<T>::value >>
320 : cpp_type_impl<base_type_t<T>> { };
321
322// Pair type
323template <typename T>
324struct cpp_type<T, if_t< is_pair<T>::value >>
325{
326 // Override id method to return id of pair
327 static id_t id(world_t *world = nullptr) {
328 return ecs_pair(
331 }
332};
333
334} // namespace _
335
342 using entity::entity;
343
344# ifdef FLECS_META
346# endif
347# ifdef FLECS_METRICS
348# include "mixins/metrics/untyped_component.inl"
349# endif
350};
351
357template <typename T>
369 flecs::world_t *world,
370 const char *name = nullptr,
371 bool allow_tag = true,
372 flecs::id_t id = 0)
373 {
374 const char *n = name;
375 bool implicit_name = false;
376 if (!n) {
377 n = _::type_name<T>();
378
379 /* Keep track of whether name was explicitly set. If not, and the
380 * component was already registered, just use the registered name.
381 *
382 * The registered name may differ from the typename as the registered
383 * name includes the flecs scope. This can in theory be different from
384 * the C++ namespace though it is good practice to keep them the same */
385 implicit_name = true;
386 }
387
389 /* Obtain component id. Because the component is already registered,
390 * this operation does nothing besides returning the existing id */
391 id = _::cpp_type<T>::id_explicit(world, name, allow_tag, id);
392
393 ecs_cpp_component_validate(world, id, n, _::symbol_name<T>(),
396 implicit_name);
397 } else {
398 /* If component is registered from an existing scope, ignore the
399 * namespace in the name of the component. */
400 if (implicit_name && (ecs_get_scope(world) != 0)) {
401 /* If the type is a template type, make sure to ignore ':'
402 * inside the template parameter list. */
403 const char *start = strchr(n, '<'), *last_elem = NULL;
404 if (start) {
405 const char *ptr = start;
406 while (ptr[0] && (ptr[0] != ':') && (ptr > n)) {
407 ptr --;
408 }
409 if (ptr[0] == ':') {
410 last_elem = ptr;
411 }
412 }
413 if (last_elem) {
414 name = last_elem + 1;
415 }
416 }
417
418 /* Find or register component */
419 bool existing;
420 id = ecs_cpp_component_register(world, id, n, _::symbol_name<T>(),
421 ECS_SIZEOF(T), ECS_ALIGNOF(T), implicit_name, &existing);
422
423 /* Initialize static component data */
424 id = _::cpp_type<T>::id_explicit(world, name, allow_tag, id);
425
426 /* Initialize lifecycle actions (ctor, dtor, copy, move) */
427 if (_::cpp_type<T>::size() && !existing) {
428 _::register_lifecycle_actions<T>(world, id);
429 }
430 }
431
432 m_world = world;
433 m_id = id;
434 }
435
437 template <typename Func>
438 component<T>& on_add(Func&& func) {
439 using Delegate = typename _::each_delegate<typename std::decay<Func>::type, T>;
440 flecs::type_hooks_t h = get_hooks();
441 ecs_assert(h.on_add == nullptr, ECS_INVALID_OPERATION,
442 "on_add hook is already set");
443 BindingCtx *ctx = get_binding_ctx(h);
444 h.on_add = Delegate::run_add;
445 ctx->on_add = FLECS_NEW(Delegate)(FLECS_FWD(func));
446 ctx->free_on_add = reinterpret_cast<ecs_ctx_free_t>(
447 _::free_obj<Delegate>);
448 ecs_set_hooks_id(m_world, m_id, &h);
449 return *this;
450 }
451
453 template <typename Func>
454 component<T>& on_remove(Func&& func) {
455 using Delegate = typename _::each_delegate<
456 typename std::decay<Func>::type, T>;
457 flecs::type_hooks_t h = get_hooks();
458 ecs_assert(h.on_remove == nullptr, ECS_INVALID_OPERATION,
459 "on_remove hook is already set");
460 BindingCtx *ctx = get_binding_ctx(h);
461 h.on_remove = Delegate::run_remove;
462 ctx->on_remove = FLECS_NEW(Delegate)(FLECS_FWD(func));
463 ctx->free_on_remove = reinterpret_cast<ecs_ctx_free_t>(
464 _::free_obj<Delegate>);
465 ecs_set_hooks_id(m_world, m_id, &h);
466 return *this;
467 }
468
470 template <typename Func>
471 component<T>& on_set(Func&& func) {
472 using Delegate = typename _::each_delegate<
473 typename std::decay<Func>::type, T>;
474 flecs::type_hooks_t h = get_hooks();
475 ecs_assert(h.on_set == nullptr, ECS_INVALID_OPERATION,
476 "on_set hook is already set");
477 BindingCtx *ctx = get_binding_ctx(h);
478 h.on_set = Delegate::run_set;
479 ctx->on_set = FLECS_NEW(Delegate)(FLECS_FWD(func));
480 ctx->free_on_set = reinterpret_cast<ecs_ctx_free_t>(
481 _::free_obj<Delegate>);
482 ecs_set_hooks_id(m_world, m_id, &h);
483 return *this;
484 }
485
486# ifdef FLECS_META
487# include "mixins/meta/component.inl"
488# endif
489
490private:
491 using BindingCtx = _::component_binding_ctx;
492
493 BindingCtx* get_binding_ctx(flecs::type_hooks_t& h){
494 BindingCtx *result = static_cast<BindingCtx*>(h.binding_ctx);
495 if (!result) {
496 result = FLECS_NEW(BindingCtx);
497 h.binding_ctx = result;
498 h.binding_ctx_free = reinterpret_cast<ecs_ctx_free_t>(
499 _::free_obj<BindingCtx>);
500 }
501 return result;
502 }
503
504 flecs::type_hooks_t get_hooks() {
505 const flecs::type_hooks_t* h = ecs_get_hooks_id(m_world, m_id);
506 if (h) {
507 return *h;
508 } else {
509 return {};
510 }
511 }
512};
513
516template <typename T>
517flecs::entity_t type_id() {
518 if (_::cpp_type<T>::s_reset_count == ecs_cpp_reset_count_get()) {
520 } else {
521 return 0;
522 }
523}
524
547inline void reset() {
548 ecs_cpp_reset_count_inc();
549}
550
551}
552
flecs::entity_t type_id()
Get id currently assigned to component.
ecs_entity_t ecs_set_with(ecs_world_t *world, ecs_id_t id)
Set current with id.
#define ecs_assert(condition, error_code,...)
Assert.
Definition log.h:351
const ecs_type_hooks_t * ecs_get_hooks_id(ecs_world_t *world, ecs_entity_t id)
Get hooks for component.
void ecs_set_hooks_id(ecs_world_t *world, ecs_entity_t id, const ecs_type_hooks_t *hooks)
Register hooks for component.
ecs_id_t ecs_entity_t
An entity identifier.
Definition flecs.h:305
struct ecs_world_t ecs_world_t
A world is the container for all ECS data and supporting features.
Definition flecs.h:349
uint64_t ecs_id_t
Ids are the things that can be added to an entity.
Definition flecs.h:298
void reset()
Reset static component ids.
transcribe_cv_t< remove_reference_t< P >, typename raw_type_t< P >::second > pair_second_t
Get pair::second from pair while preserving cv qualifiers.
Definition pair.hpp:92
transcribe_cv_t< remove_reference_t< P >, typename raw_type_t< P >::first > pair_first_t
Get pair::first from pair while preserving cv qualifiers.
Definition pair.hpp:88
void(* ecs_ctx_free_t)(void *ctx)
Function to cleanup context data.
Definition flecs.h:613
bool ecs_exists(const ecs_world_t *world, ecs_entity_t entity)
Test whether an entity exists.
ecs_entity_t ecs_get_scope(const ecs_world_t *world)
Get the current scope.
const char * ecs_get_symbol(const ecs_world_t *world, ecs_entity_t entity)
Get the symbol of an entity.
ecs_entity_t ecs_set_scope(ecs_world_t *world, ecs_entity_t scope)
Set the current scope.
Meta component mixin.
Type that contains component lifecycle callbacks.
Definition flecs.h:832
ecs_iter_action_t on_remove
Callback that is invoked when an instance of the component is removed.
Definition flecs.h:868
void * binding_ctx
Language binding context.
Definition flecs.h:871
ecs_iter_action_t on_set
Callback that is invoked when an instance of the component is set.
Definition flecs.h:863
ecs_xtor_t ctor
ctor
Definition flecs.h:833
ecs_iter_action_t on_add
Callback that is invoked when an instance of a component is added.
Definition flecs.h:858
ecs_ctx_free_t binding_ctx_free
Callback to free binding_ctx.
Definition flecs.h:874
Component class.
component< T > & on_remove(Func &&func)
Register on_remove hook.
component(flecs::world_t *world, const char *name=nullptr, bool allow_tag=true, flecs::id_t id=0)
Register a component.
component< T > & on_add(Func &&func)
Register on_add hook.
component< T > & on_set(Func &&func)
Register on_set hook.
flecs::string_view name() const
Return the entity name.
entity_t id() const
Get entity id.
Entity.
Definition entity.hpp:30
Class that wraps around a flecs::id_t.
Definition decl.hpp:27
Test if type is a pair.
Definition pair.hpp:82
Untyped component class.
The world.
Definition world.hpp:132