Flecs v4.0
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
16namespace flecs {
17
18namespace _ {
19
20// Trick to obtain typename from type, as described here
21// https://blog.molecular-matters.com/2015/12/11/getting-the-type-of-a-template-argument-as-string-without-rtti/
22//
23// The code from the link has been modified to work with more types, and across
24// multiple compilers. The resulting string should be the same on all platforms
25// for all compilers.
26//
27
28#if defined(__GNUC__) || defined(_WIN32)
29template <typename T>
30inline const char* type_name() {
31 static const size_t len = ECS_FUNC_TYPE_LEN(const char*, type_name, ECS_FUNC_NAME);
32 static char result[len + 1] = {};
33 static const size_t front_len = ECS_FUNC_NAME_FRONT(const char*, type_name);
34 static const char* cppTypeName = ecs_cpp_get_type_name(result, ECS_FUNC_NAME, len, front_len);
35 return cppTypeName;
36}
37#else
38#error "implicit component registration not supported"
39#endif
40
41// Translate a typename into a language-agnostic identifier. This allows for
42// registration of components/modules across language boundaries.
43template <typename T>
44inline const char* symbol_name() {
45 static const size_t len = ECS_FUNC_TYPE_LEN(const char*, symbol_name, ECS_FUNC_NAME);
46 static char result[len + 1] = {};
47 static const char* cppSymbolName = ecs_cpp_get_symbol_name(result, type_name<T>(), len);
48 return cppSymbolName;
49}
50
51template <> inline const char* symbol_name<uint8_t>() {
52 return "u8";
53}
54template <> inline const char* symbol_name<uint16_t>() {
55 return "u16";
56}
57template <> inline const char* symbol_name<uint32_t>() {
58 return "u32";
59}
60template <> inline const char* symbol_name<uint64_t>() {
61 return "u64";
62}
63template <> inline const char* symbol_name<int8_t>() {
64 return "i8";
65}
66template <> inline const char* symbol_name<int16_t>() {
67 return "i16";
68}
69template <> inline const char* symbol_name<int32_t>() {
70 return "i32";
71}
72template <> inline const char* symbol_name<int64_t>() {
73 return "i64";
74}
75template <> inline const char* symbol_name<float>() {
76 return "f32";
77}
78template <> inline const char* symbol_name<double>() {
79 return "f64";
80}
81
82// If type is trivial, don't register lifecycle actions. While the functions
83// that obtain the lifecycle callback do detect whether the callback is required
84// adding a special case for trivial types eases the burden a bit on the
85// compiler as it reduces the number of templates to evaluate.
86template<typename T, enable_if_t<
87 std::is_trivial<T>::value == true
88 >* = nullptr>
89void register_lifecycle_actions(ecs_world_t*, ecs_entity_t) { }
90
91// If the component is non-trivial, register component lifecycle actions.
92// Depending on the type not all callbacks may be available.
93template<typename T, enable_if_t<
94 std::is_trivial<T>::value == false
95 >* = nullptr>
96void register_lifecycle_actions(
99{
100 ecs_type_hooks_t cl{};
101 cl.ctor = ctor<T>(cl.flags);
102 cl.dtor = dtor<T>(cl.flags);
103
104 cl.copy = copy<T>(cl.flags);
105 cl.copy_ctor = copy_ctor<T>(cl.flags);
106 cl.move = move<T>(cl.flags);
107 cl.move_ctor = move_ctor<T>(cl.flags);
108
109 cl.ctor_move_dtor = ctor_move_dtor<T>(cl.flags);
110 cl.move_dtor = move_dtor<T>(cl.flags);
111
112 cl.flags &= ECS_TYPE_HOOKS_ILLEGAL;
114
115 if (cl.flags & (ECS_TYPE_HOOK_MOVE_ILLEGAL|ECS_TYPE_HOOK_MOVE_CTOR_ILLEGAL))
116 {
117 ecs_add_id(world, component, flecs::Sparse);
118 }
119}
120
121template <typename T>
122struct type_impl {
123 static_assert(is_pointer<T>::value == false,
124 "pointer types are not allowed for components");
125
126 // Initialize component identifier
127 static void init(
128 bool allow_tag = true)
129 {
130 s_index = flecs_component_ids_index_get();
131 s_allow_tag = allow_tag;
132 s_size = sizeof(T);
133 s_alignment = alignof(T);
134 if (is_empty<T>::value && allow_tag) {
135 s_size = 0;
136 s_alignment = 0;
137 }
138 }
139
140 static void init_builtin(
141 flecs::world_t *world,
142 flecs::entity_t id,
143 bool allow_tag = true)
144 {
145 init(allow_tag);
146 flecs_component_ids_set(world, s_index, id);
147 }
148
149 // Register component id.
150 static entity_t register_id(
151 world_t *world, // The world
152 const char *name = nullptr, // User provided name (overrides typename)
153 bool allow_tag = true, // Register empty types as zero-sized components
154 bool is_component = true, // Add flecs::Component to result
155 bool explicit_registration = false, // Entered from world.component<T>()?
156 flecs::id_t id = 0) // User provided component id
157 {
158 if (!s_index) {
159 // This is the first time (in this binary image) that this type is
160 // being used. Generate a static index that will identify the type
161 // across worlds.
162 init(allow_tag);
163 ecs_assert(s_index != 0, ECS_INTERNAL_ERROR, NULL);
164 }
165
166 bool registered = false, existing = false;
167
168 flecs::entity_t c = ecs_cpp_component_register(
169 world, id, s_index, name, type_name<T>(),
170 symbol_name<T>(), size(), alignment(),
171 is_component, explicit_registration, &registered, &existing);
172
173 ecs_assert(c != 0, ECS_INTERNAL_ERROR, NULL);
174
175 if (registered) {
176 // Register lifecycle callbacks, but only if the component has a
177 // size. Components that don't have a size are tags, and tags don't
178 // require construction/destruction/copy/move's.
179 if (size() && !existing) {
180 register_lifecycle_actions<T>(world, c);
181 }
182
183 // If component is enum type, register constants. Make sure to do
184 // this after setting the component id, because the enum code will
185 // be calling type<T>::id().
186 #if FLECS_CPP_ENUM_REFLECTION_SUPPORT
187 _::init_enum<T>(world, c);
188 #endif
189 }
190
191 return c;
192 }
193
194 // Get type (component) id.
195 // If type was not yet registered and automatic registration is allowed,
196 // this function will also register the type.
197 static entity_t id(world_t *world)
198 {
199#ifdef FLECS_CPP_NO_AUTO_REGISTRATION
200 ecs_assert(registered(world), ECS_INVALID_OPERATION,
201 "component '%s' must be registered before use",
202 type_name<T>());
203
204 flecs::entity_t c = flecs_component_ids_get(world, s_index);
205 ecs_assert(c != 0, ECS_INTERNAL_ERROR, NULL);
206 ecs_assert(ecs_is_alive(world, c), ECS_INVALID_OPERATION,
207 "component '%s' was deleted, reregister before using",
208 type_name<T>());
209#else
210 flecs::entity_t c = flecs_component_ids_get_alive(world, s_index);
211 if (!c) {
212 c = register_id(world);
213 }
214#endif
215 return c;
216 }
217
218 // Return the size of a component.
219 static size_t size() {
220 ecs_assert(s_index != 0, ECS_INTERNAL_ERROR, NULL);
221 return s_size;
222 }
223
224 // Return the alignment of a component.
225 static size_t alignment() {
226 ecs_assert(s_index != 0, ECS_INTERNAL_ERROR, NULL);
227 return s_alignment;
228 }
229
230 // Was the component already registered.
231 static bool registered(flecs::world_t *world) {
232 ecs_assert(world != nullptr, ECS_INVALID_PARAMETER, NULL);
233
234 if (s_index == 0) {
235 return false;
236 }
237
238 if (!flecs_component_ids_get(world, s_index)) {
239 return false;
240 }
241
242 return true;
243 }
244
245 // This function is only used to test cross-translation unit features. No
246 // code other than test cases should invoke this function.
247 static void reset() {
248 s_index = 0;
249 s_size = 0;
250 s_alignment = 0;
251 s_allow_tag = true;
252 }
253
254 static int32_t s_index;
255 static size_t s_size;
256 static size_t s_alignment;
257 static bool s_allow_tag;
258};
259
260// Global templated variables that hold component identifier and other info
261template <typename T> int32_t type_impl<T>::s_index;
262template <typename T> size_t type_impl<T>::s_size;
263template <typename T> size_t type_impl<T>::s_alignment;
264template <typename T> bool type_impl<T>::s_allow_tag( true );
265
266// Front facing class for implicitly registering a component & obtaining
267// static component data
268
269// Regular type
270template <typename T>
271struct type<T, if_not_t< is_pair<T>::value >>
272 : type_impl<base_type_t<T>> { };
273
274// Pair type
275template <typename T>
276struct type<T, if_t< is_pair<T>::value >>
277{
278 // Override id method to return id of pair
279 static id_t id(world_t *world = nullptr) {
280 return ecs_pair(
281 type< pair_first_t<T> >::id(world),
282 type< pair_second_t<T> >::id(world));
283 }
284};
285
286} // namespace _
287
294 using entity::entity;
295
296 untyped_component() : entity() { }
297 explicit untyped_component(flecs::world_t *world, flecs::entity_t id) : entity(world, id) { }
298 explicit untyped_component(flecs::entity_t id) : entity(id) { }
299
300 explicit untyped_component(flecs::world_t *world, const char *name)
301 {
302 world_ = world;
303
304 ecs_entity_desc_t desc = {};
305 desc.name = name;
306 desc.sep = "::";
307 desc.root_sep = "::";
308 desc.use_low_id = true;
309 id_ = ecs_entity_init(world, &desc);
310 }
311
312 explicit untyped_component(world_t *world, const char *name, const char *sep, const char *root_sep)
313 {
314 world_ = world;
315
316 ecs_entity_desc_t desc = {};
317 desc.name = name;
318 desc.sep = sep;
319 desc.root_sep = root_sep;
320 desc.use_low_id = true;
321 id_ = ecs_entity_init(world, &desc);
322 }
323
324protected:
325
326flecs::type_hooks_t get_hooks() const {
327 const flecs::type_hooks_t* h = ecs_get_hooks_id(world_, id_);
328 if (h) {
329 return *h;
330 } else {
331 return {};
332 }
333}
334
335void set_hooks(flecs::type_hooks_t &h) {
336 h.flags &= ECS_TYPE_HOOKS_ILLEGAL;
337 ecs_set_hooks_id(world_, id_, &h);
338}
339
340public:
341
343 ecs_cmp_t compare_callback)
344{
345 ecs_assert(compare_callback, ECS_INVALID_PARAMETER, NULL);
346 flecs::type_hooks_t h = get_hooks();
347 h.cmp = compare_callback;
348 h.flags &= ~ECS_TYPE_HOOK_CMP_ILLEGAL;
349 if(h.flags & ECS_TYPE_HOOK_EQUALS_ILLEGAL) {
350 h.flags &= ~ECS_TYPE_HOOK_EQUALS_ILLEGAL;
351 h.equals = NULL;
352 }
353 set_hooks(h);
354 return *this;
355}
356
358 ecs_equals_t equals_callback)
359{
360 ecs_assert(equals_callback, ECS_INVALID_PARAMETER, NULL);
361 flecs::type_hooks_t h = get_hooks();
362 h.equals = equals_callback;
363 h.flags &= ~ECS_TYPE_HOOK_EQUALS_ILLEGAL;
364 set_hooks(h);
365 return *this;
366}
367
368# ifdef FLECS_META
370# endif
371# ifdef FLECS_METRICS
372# include "mixins/metrics/untyped_component.inl"
373# endif
374};
375
381template <typename T>
393 flecs::world_t *world,
394 const char *name = nullptr,
395 bool allow_tag = true,
396 flecs::id_t id = 0)
397 {
398 world_ = world;
399 id_ = _::type<T>::register_id(world, name, allow_tag, true, true, id);
400 }
401
403 template <typename Func>
404 component<T>& on_add(Func&& func) {
405 using Delegate = typename _::each_delegate<typename std::decay<Func>::type, T>;
406 flecs::type_hooks_t h = get_hooks();
407 ecs_assert(h.on_add == nullptr, ECS_INVALID_OPERATION,
408 "on_add hook is already set");
409 BindingCtx *ctx = get_binding_ctx(h);
410 h.on_add = Delegate::run_add;
411 ctx->on_add = FLECS_NEW(Delegate)(FLECS_FWD(func));
412 ctx->free_on_add = _::free_obj<Delegate>;
413 set_hooks(h);
414 return *this;
415 }
416
418 template <typename Func>
419 component<T>& on_remove(Func&& func) {
420 using Delegate = typename _::each_delegate<
421 typename std::decay<Func>::type, T>;
422 flecs::type_hooks_t h = get_hooks();
423 ecs_assert(h.on_remove == nullptr, ECS_INVALID_OPERATION,
424 "on_remove hook is already set");
425 BindingCtx *ctx = get_binding_ctx(h);
426 h.on_remove = Delegate::run_remove;
427 ctx->on_remove = FLECS_NEW(Delegate)(FLECS_FWD(func));
428 ctx->free_on_remove = _::free_obj<Delegate>;
429 set_hooks(h);
430 return *this;
431 }
432
434 template <typename Func>
435 component<T>& on_set(Func&& func) {
436 using Delegate = typename _::each_delegate<
437 typename std::decay<Func>::type, T>;
438 flecs::type_hooks_t h = get_hooks();
439 ecs_assert(h.on_set == nullptr, ECS_INVALID_OPERATION,
440 "on_set hook is already set");
441 BindingCtx *ctx = get_binding_ctx(h);
442 h.on_set = Delegate::run_set;
443 ctx->on_set = FLECS_NEW(Delegate)(FLECS_FWD(func));
444 ctx->free_on_set = _::free_obj<Delegate>;
445 set_hooks(h);
446 return *this;
447 }
448
450 using untyped_component::on_compare;
451 component<T>& on_compare() {
452 ecs_cmp_t handler = _::compare<T>();
453 ecs_assert(handler != NULL, ECS_INVALID_OPERATION,
454 "Type does not have operator> or operator< const or is inaccessible");
455 on_compare(handler);
456 return *this;
457 }
458
460 using cmp_hook = int(*)(const T* a, const T* b, const ecs_type_info_t *ti);
461 component<T>& on_compare(cmp_hook callback) {
462 on_compare(reinterpret_cast<ecs_cmp_t>(callback));
463 return *this;
464 }
465
467 using untyped_component::on_equals;
468 component<T>& on_equals() {
469 ecs_equals_t handler = _::equals<T>();
470 ecs_assert(handler != NULL, ECS_INVALID_OPERATION,
471 "Type does not have operator== const or is inaccessible");
472 on_equals(handler);
473 return *this;
474 }
475
477 using equals_hook = bool(*)(const T* a, const T* b, const ecs_type_info_t *ti);
478 component<T>& on_equals(equals_hook callback) {
479 on_equals(reinterpret_cast<ecs_equals_t>(callback));
480 return *this;
481 }
482
483# ifdef FLECS_META
484# include "mixins/meta/component.inl"
485# endif
486
487private:
488 using BindingCtx = _::component_binding_ctx;
489
490 BindingCtx* get_binding_ctx(flecs::type_hooks_t& h){
491 BindingCtx *result = static_cast<BindingCtx*>(h.binding_ctx);
492 if (!result) {
493 result = FLECS_NEW(BindingCtx);
494 h.binding_ctx = result;
495 h.binding_ctx_free = _::free_obj<BindingCtx>;
496 }
497 return result;
498 }
499};
500
501}
502
void ecs_add_id(ecs_world_t *world, ecs_entity_t entity, ecs_id_t id)
Add a (component) id to an entity.
#define ecs_assert(condition, error_code,...)
Assert.
Definition log.h:368
void ecs_set_hooks_id(ecs_world_t *world, ecs_entity_t id, const ecs_type_hooks_t *hooks)
Register hooks for component.
const ecs_type_hooks_t * ecs_get_hooks_id(const ecs_world_t *world, ecs_entity_t id)
Get hooks for component.
ecs_id_t ecs_entity_t
An entity identifier.
Definition flecs.h:381
struct ecs_world_t ecs_world_t
A world is the container for all ECS data and supporting features.
Definition flecs.h:425
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
ecs_entity_t ecs_entity_init(ecs_world_t *world, const ecs_entity_desc_t *desc)
Find or create an entity.
int(* ecs_cmp_t)(const void *a_ptr, const void *b_ptr, const ecs_type_info_t *type_info)
Compare hook to compare component instances.
Definition flecs.h:657
bool(* ecs_equals_t)(const void *a_ptr, const void *b_ptr, const ecs_type_info_t *type_info)
Equals operator hook.
Definition flecs.h:663
bool ecs_is_alive(const ecs_world_t *world, ecs_entity_t e)
Test whether an entity is alive.
Meta component mixin.
Used with ecs_entity_init().
Definition flecs.h:1012
const char * sep
Optional custom separator for hierarchical names.
Definition flecs.h:1024
const char * root_sep
Optional, used for identifiers relative to root.
Definition flecs.h:1028
const char * name
Name of the entity.
Definition flecs.h:1019
bool use_low_id
When set to true, a low id (typically reserved for components) will be used to create the entity,...
Definition flecs.h:1040
ecs_iter_action_t on_remove
Callback that is invoked when an instance of the component is removed.
Definition flecs.h:974
void * binding_ctx
Language binding context.
Definition flecs.h:977
ecs_flags32_t flags
Hook flags.
Definition flecs.h:959
ecs_cmp_t cmp
Compare hook.
Definition flecs.h:950
ecs_iter_action_t on_set
Callback that is invoked when an instance of the component is set.
Definition flecs.h:969
ecs_xtor_t ctor
ctor
Definition flecs.h:926
ecs_iter_action_t on_add
Callback that is invoked when an instance of a component is added.
Definition flecs.h:964
ecs_ctx_free_t binding_ctx_free
Callback to free binding_ctx.
Definition flecs.h:981
ecs_equals_t equals
Equals hook.
Definition flecs.h:953
Type that contains component information (passed to ctors/dtors/...)
Definition flecs.h:989
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.
bool(*)(const T *a, const T *b, const ecs_type_info_t *ti) equals_hook
Type safe variant of equals op function.
component< T > & on_add(Func &&func)
Register on_add hook.
component< T > & on_set(Func &&func)
Register on_set hook.
int(*)(const T *a, const T *b, const ecs_type_info_t *ti) cmp_hook
Type safe variant of compare op function.
flecs::string_view name() const
Return the entity name.
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:137