EnTT  3.1.0
docs/md/entity.md
1 # Crash Course: entity-component system
2 
3 <!--
4 @cond TURN_OFF_DOXYGEN
5 -->
6 # Table of Contents
7 
8 * [Introduction](#introduction)
9 * [Design decisions](#design-decisions)
10  * [A bitset-free entity-component system](#a-bitset-free-entity-component-system)
11  * [Pay per use](#pay-per-use)
12  * [All or nothing](#all-or-nothing)
13  * [Stateless systems](#stateless-systems)
14 * [Vademecum](#vademecum)
15 * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component)
16  * [Observe changes](#observe-changes)
17  * [They call me Reactive System](#they-call-me-reactive-system)
18  * [Runtime components](#runtime-components)
19  * [A journey through a plugin](#a-journey-through-a-plugin)
20  * [Sorting: is it possible?](#sorting-is-it-possible)
21  * [Helpers](#helpers)
22  * [Null entity](#null-entity)
23  * [Stomp and spawn](#stomp-and-spawn)
24  * [Dependencies](#dependencies)
25  * [Tags](#tags)
26  * [Actor](#actor)
27  * [Context variables](#context-variables)
28  * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous)
29  * [Snapshot loader](#snapshot-loader)
30  * [Continuous loader](#continuous-loader)
31  * [Archives](#archives)
32  * [One example to rule them all](#one-example-to-rule-them-all)
33 * [Views and Groups](#views-and-groups)
34  * [Views](#views)
35  * [Runtime views](#runtime-views)
36  * [Groups](#groups)
37  * [Full-owning groups](#full-owning-groups)
38  * [Partial-owning groups](#partial-owning-groups)
39  * [Non-owning groups](#non-owning-groups)
40  * [Types: const, non-const and all in between](#types-const-non-const-and-all-in-between)
41  * [Give me everything](#give-me-everything)
42  * [What is allowed and what is not](#what-is-allowed-and-what-is-not)
43  * [More performance, more constraints](#more-performance-more-constraints)
44 * [Empty type optimization](#empty-type-optimization)
45 * [Multithreading](#multithreading)
46  * [Iterators](#iterators)
47 * [Beyond this document](#beyond-this-document)
48 <!--
49 @endcond TURN_OFF_DOXYGEN
50 -->
51 
52 # Introduction
53 
54 `EnTT` is a header-only, tiny and easy to use entity-component system (and much
55 more) written in modern C++.<br/>
56 The entity-component-system (also known as _ECS_) is an architectural pattern
57 used mostly in game development.
58 
59 # Design decisions
60 
61 ## A bitset-free entity-component system
62 
63 `EnTT` offers a _bitset-free_ entity-component system that doesn't require users
64 to specify the set of components neither at compile-time nor at runtime before
65 being able to use the library itself.<br/>
66 This is why users can instantiate the core class simply like:
67 
68 ```cpp
69 entt::registry registry;
70 ```
71 
72 In place of its more annoying and error-prone counterpart:
73 
74 ```cpp
75 entt::registry<comp_0, comp_1, ..., comp_n> registry;
76 ```
77 
78 Furthermore, there is no need to indicate to the library in any way that a type
79 of component exists and will be used sooner or later. When the time comes, users
80 can just use it and that's all.
81 
82 ## Pay per use
83 
84 `EnTT` is entirely designed around the principle that users have to pay only for
85 what they want.
86 
87 When it comes to using an entity-component system, the tradeoff is usually
88 between performance and memory usage. The faster it is, the more memory it uses.
89 Even worse, some approaches tend to heavily affect other functionalities like
90 the construction and destruction of components to favor iterations, even when it
91 isn't strictly required. In fact, slightly worse performance along non-critical
92 paths are the right price to pay to reduce memory usage and have overall better
93 perfomance sometimes and I've always wondered why this kind of tools do not
94 leave me the choice.<br/>
95 `EnTT` follows a completely different approach. It gets the best out from the
96 basic data structures and gives users the possibility to pay more for higher
97 performance where needed.<br/>
98 The disadvantage of this approach is that users need to know the systems they
99 are working on and the tools they are using. Otherwise, the risk to ruin the
100 performance along critical paths is high.
101 
102 So far, this choice has proven to be a good one and I really hope it can be for
103 many others besides me.
104 
105 ## All or nothing
106 
107 `EnTT` is such that at every moment a pair `(T *, size)` is available to
108 directly access all the instances of a given component type `T`.<br/>
109 This was a guideline and a design decision that influenced many choices, for
110 better and for worse. I cannot say whether it will be useful or not to the
111 reader, but it's worth to mention it, because it's one of the corner stones of
112 this library.
113 
114 Many of the tools described below, from the registry to the views and up to the
115 groups give the possibility to get this information and have been designed
116 around this need, which was and remains one of my main requirements during the
117 development.<br/>
118 The rest is experimentation and the desire to invent something new, hoping to
119 have succeeded.
120 
121 ## Stateless systems
122 
123 `EnTT` is designed so that it can work with _stateless systems_. In other words,
124 all systems can be free functions and there is no need to define them as classes
125 (although nothing prevents users from doing so).<br/>
126 This is possible because the main class with which the users will work provides
127 all what is needed to act as the sole _source of truth_ of an application.
128 
129 To be honest, this point became part of the design principles at a later date,
130 but has also become one of the cornerstones of the library to date, as stateless
131 systems are widely used and appreciated in general.
132 
133 # Vademecum
134 
135 The registry to store, the views and the groups to iterate. That's all.
136 
137 An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
138 use as-is and store around if needed. Do not try to inspect an entity
139 identifier, its format can change in future and a registry offers all the
140 functionalities to query them out-of-the-box. The underlying type of an entity
141 (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
142 when defining a registry. In fact, an `entt::registry` is nothing more than an
143 alias for `entt::basic_registry<entt::entity>` and `entt::entity` is a distinct
144 type that implements the concept of _entity identifier_.<br/>
145 Components (the _C_ of an _ECS_) should be plain old data structures or more
146 complex and movable data structures with a proper constructor. Actually, the
147 sole requirement of a component type is that it must be both move constructible
148 and move assignable. They are list initialized by using the parameters provided
149 to construct the component itself. No need to register components or their types
150 neither with the registry nor with the entity-component system at all.<br/>
151 Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
152 whatever users want. They can accept a registry, a view or a group of any type
153 and use them the way they prefer. No need to register systems or their types
154 neither with the registry nor with the entity-component system at all.
155 
156 The following sections will explain in short how to use the entity-component
157 system, the core part of the whole library.<br/>
158 In fact, the project is composed of many other classes in addition to those
159 describe below. For more details, please refer to the inline documentation.
160 
161 # The Registry, the Entity and the Component
162 
163 A registry can store and manage entities, as well as create views and groups to
164 iterate the underlying data structures.<br/>
165 The class template `basic_registry` lets users decide what's the preferred type
166 to represent an entity. Because `std::uint32_t` is large enough for almost all
167 the cases, there exists also the type `entt::entity` for it, as well as the
168 alias `entt::registry` for `entt::basic_registry<entt::entity>`.
169 
170 Entities are represented by _entity identifiers_. An entity identifier is an
171 opaque type that users should not inspect or modify in any way. It carries
172 information about the entity itself and its version.<br/>
173 User defined identifiers can be introduced by means of the `ENTT_OPAQUE_TYPE`
174 macro if needed.
175 
176 A registry is used both to construct and to destroy entities:
177 
178 ```cpp
179 // constructs a naked entity with no components and returns its identifier
180 auto entity = registry.create();
181 
182 // destroys an entity and all its components
183 registry.destroy(entity);
184 ```
185 
186 There exists also an overload of the `create` and `destroy` member functions
187 that accepts two iterators, that is a range to assign or to destroy. It can be
188 used to create or destroy multiple entities at once:
189 
190 ```cpp
191 // destroys all the entities in a range
192 auto view = registry.view<a_component, another_component>();
193 registry.destroy(view.begin(), view.end());
194 ```
195 
196 In both cases, the `create` member function accepts also a list of default
197 constructible types of components to assign to the entities before to return.
198 It's a faster alternative to the creation and subsequent assignment of
199 components in separate steps.
200 
201 When an entity is destroyed, the registry can freely reuse it internally with a
202 slightly different identifier. In particular, the version of an entity is
203 increased each and every time it's discarded.<br/>
204 In case entity identifiers are stored around, the registry offers all the
205 functionalities required to test them and to get out of them the information
206 they carry:
207 
208 ```cpp
209 // returns true if the entity is still valid, false otherwise
210 bool b = registry.valid(entity);
211 
212 // gets the version contained in the entity identifier
213 auto version = registry.version(entity);
214 
215 // gets the actual version for the given entity
216 auto curr = registry.current(entity);
217 ```
218 
219 Components can be assigned to or removed from entities at any time with a few
220 calls to member functions of the registry. As for the entities, the registry
221 offers also a set of functionalities users can use to work with the components.
222 
223 The `assign` member function template creates, initializes and assigns to an
224 entity the given component. It accepts a variable number of arguments to
225 construct the component itself if present:
226 
227 ```cpp
228 registry.assign<position>(entity, 0., 0.);
229 
230 // ...
231 
232 auto &velocity = registry.assign<velocity>(entity);
233 vel.dx = 0.;
234 vel.dy = 0.;
235 ```
236 
237 If an entity already has the given component, the `replace` member function
238 template can be used to replace it:
239 
240 ```cpp
241 registry.replace<position>(entity, 0., 0.);
242 
243 // ...
244 
245 auto &velocity = registry.replace<velocity>(entity);
246 vel.dx = 0.;
247 vel.dy = 0.;
248 ```
249 
250 In case users want to assign a component to an entity, but it's unknown whether
251 the entity already has it or not, `assign_or_replace` does the work in a single
252 call (there is a performance penalty to pay for this mainly due to the fact that
253 it has to check if the entity already has the given component or not):
254 
255 ```cpp
256 registry.assign_or_replace<position>(entity, 0., 0.);
257 
258 // ...
259 
260 auto &velocity = registry.assign_or_replace<velocity>(entity);
261 vel.dx = 0.;
262 vel.dy = 0.;
263 ```
264 
265 Note that `assign_or_replace` is a slightly faster alternative for the following
266 `if/else` statement and nothing more:
267 
268 ```cpp
269 if(registry.has<comp>(entity)) {
270  registry.replace<comp>(entity, arg1, argN);
271 } else {
272  registry.assign<comp>(entity, arg1, argN);
273 }
274 ```
275 
276 As already shown, if in doubt about whether or not an entity has one or more
277 components, the `has` member function template may be useful:
278 
279 ```cpp
280 bool b = registry.has<position, velocity>(entity);
281 ```
282 
283 On the other side, if the goal is to delete a single component, the `remove`
284 member function template is the way to go when it's certain that the entity owns
285 a copy of the component:
286 
287 ```cpp
288 registry.remove<position>(entity);
289 ```
290 
291 Otherwise consider to use the `reset` member function. It behaves similarly to
292 `remove` but with a strictly defined behavior (and a performance penalty is the
293 price to pay for this). In particular it removes the component if and only if it
294 exists, otherwise it returns safely to the caller:
295 
296 ```cpp
297 registry.reset<position>(entity);
298 ```
299 
300 There exist also two other _versions_ of the `reset` member function:
301 
302 * If no entity is passed to it, `reset` will remove the given component from
303  each entity that has it:
304 
305  ```cpp
306  registry.reset<position>();
307  ```
308 
309 * If neither the entity nor the component are specified, all the entities still
310  in use and their components are destroyed:
311 
312  ```cpp
313  registry.reset();
314  ```
315 
316 Finally, references to components can be retrieved simply by doing this:
317 
318 ```cpp
319 const auto &cregistry = registry;
320 
321 // const and non-const reference
322 const auto &crenderable = cregistry.get<renderable>(entity);
323 auto &renderable = registry.get<renderable>(entity);
324 
325 // const and non-const references
326 const auto &[cpos, cvel] = cregistry.get<position, velocity>(entity);
327 auto &[pos, vel] = registry.get<position, velocity>(entity);
328 ```
329 
330 The `get` member function template gives direct access to the component of an
331 entity stored in the underlying data structures of the registry. There exists
332 also an alternative member function named `try_get` that returns a pointer to
333 the component owned by an entity if any, a null pointer otherwise.
334 
335 ## Observe changes
336 
337 Because of how the registry works internally, it stores a bunch of signal
338 handlers for each pool in order to notify some of its data structures on the
339 construction and destruction of components or when an instance of a component is
340 explicitly replaced by the user.<br/>
341 These signal handlers are also exposed and made available to users. These are
342 the basic bricks to build fancy things like dependencies and reactive systems.
343 
344 To get a sink to be used to connect and disconnect listeners so as to be
345 notified on the creation of a component, use the `on_construct` member function:
346 
347 ```cpp
348 // connects a free function
349 registry.on_construct<position>().connect<&my_free_function>();
350 
351 // connects a member function
352 registry.on_construct<position>().connect<&my_class::member>(instance);
353 
354 // disconnects a free function
355 registry.on_construct<position>().disconnect<&my_free_function>();
356 
357 // disconnects a member function
358 registry.on_construct<position>().disconnect<&my_class::member>(instance);
359 ```
360 
361 To be notified when components are destroyed, use the `on_destroy` member
362 function instead. Finally, the `on_replace` member function will return a sink
363 to which to connect listeners to observe changes on components.
364 
365 The function type of a listener for the construction signal should be equivalent
366 to the following:
367 
368 ```cpp
369 void(entt::entity, entt::registry &, Component &);
370 ```
371 
372 Where `Component` is intuitively the type of component of interest. In other
373 words, a listener is provided with the registry that triggered the notification
374 and the entity affected by the change, in addition to the newly created
375 instance.<br/>
376 The sink returned by the `on_replace` member function accepts listeners the
377 signature of which is the same of that of the construction signal. The one of
378 the destruction signal is also similar, except for the `Component` parameter:
379 
380 ```cpp
381 void(entt::entity, entt::registry &);
382 ```
383 
384 This is mainly due to performance reasons. While the component is made available
385 after the construction, it is not when destroyed. Because of that, there are no
386 reasons to get it from the underlying storage unless the user requires so. In
387 this case, the registry is made available for the purpose.
388 
389 Note also that:
390 
391 * Listeners for the construction signal are invoked **after** components have
392  been assigned to entities.
393 * Listeners designed to observe changes are invoked **before** components have
394  been replaced and therefore before newly created instances have been assigned
395  to entities.
396 * Listeners for the destruction signal are invoked **before** components have
397  been removed from entities.
398 * The order of invocation of the listeners isn't guaranteed in any case.
399 
400 There are also some limitations on what a listener can and cannot do. In
401 particular:
402 
403 * Connecting and disconnecting other functions from within the body of a
404  listener should be avoided. It can lead to undefined behavior in some cases.
405 * Assigning and removing components from within the body of a listener that
406  observes the destruction of instances of a given type should be avoided. It
407  can lead to undefined behavior in some cases. This type of listeners is
408  intended to provide users with an easy way to perform cleanup and nothing
409  more.
410 
411 To a certain extent, these limitations don't apply. However, it's risky to try
412 to force them and users should respect the limitations unless they know exactly
413 what they are doing. Subtle bugs are the price to pay in case of errors
414 otherwise.
415 
416 In general, events and therefore listeners must not be used as replacements for
417 systems. They should not contain much logic and interactions with a registry
418 should be kept to a minimum, if possible. Note also that the greater the number
419 of listeners, the greater the performance hit when components are created or
420 destroyed.
421 
422 Please, refer to the documentation of the signal class to know all the features
423 it offers.<br/>
424 There are many useful but less known functionalities that aren't described here,
425 such as the connection objects or the possibility to attach listeners with a
426 list of parameters that is shorter than that of the signal itself.
427 
428 ### They call me Reactive System
429 
430 As mentioned above, signals are the basic tools to construct reactive systems,
431 even if they are not enough on their own.<br/>
432 `EnTT` tries to take another step in that direction with the `observer` class
433 template.
434 
435 In order to explain what reactive systems are, this is a slightly revised quote
436 from the documentation of the library that first introduced this tool,
437 [Entitas](https://github.com/sschmid/Entitas-CSharp):
438 
439 >Imagine you have 100 fighting units on the battlefield but only 10 of them
440 >changed their positions. Instead of using a normal system and updating all 100
441 >entities depending on the position, you can use a reactive system which will
442 >only update the 10 changed units. So efficient.
443 
444 In `EnTT`, this means to iterating over a reduced set of entities and components
445 with respect to what would otherwise be returned from a view or a group.<br/>
446 On these words, however, the similarities with the proposal of `Entitas` also
447 end. The rules of language and the design of the library obviously impose and
448 allow different things.
449 
450 An `observer` is initialized with an instance of a registry and a set of rules
451 that describe what are the entities to intercept. As an example:
452 
453 ```cpp
454 entt::observer observer{registry, entt::collector.replace<sprite>()};
455 ```
456 
457 The class is default constructible if required and it can be reconfigured at any
458 time by means of the `connect` member function. Moreover, instances can be
459 disconnected from the underlying registries through the `disconnect` member
460 function.<br/>
461 The `observer` offers also some member functions to query its internal state and
462 to know if it's empty or how many entities it contains. Moreover, it can return
463 a raw pointer to the list of entities it contains.
464 
465 However, the most important features of this class are that:
466 
467 * It's iterable and therefore users can easily walk through the list of entities
468  by means of a range-for loop or the `each` member function.
469 * It's clearable and therefore users can consume the entities and literally
470  reset the observer after each iteration.
471 
472 These aspects make the observer an incredibly powerful tool to know at any time
473 what are the entities that matched the given rules since the last time one
474 asked:
475 
476 ```cpp
477 for(const auto entity: observer) {
478  // ...
479 }
480 
481 observer.clear();
482 ```
483 
484 Note that the snippet above is equivalent to the following:
485 
486 ```cpp
487 observer.each([](const auto entity) {
488  // ...
489 });
490 ```
491 
492 At least as long as the `observer` isn't const. This means that the non-const
493 overload of `each` does also reset the underlying data structure before to
494 return to the caller, while the const overload does not for obvious reasons.
495 
496 The `collector` is an utility aimed to generate a list of `matcher`s (the actual
497 rules) to use with an `observer` instead.<br/>
498 There are two types of `matcher`s:
499 
500 * Observing matcher: an observer will return at least all the living entities
501  for which one or more of the given components have been explicitly replaced
502  and not yet destroyed.
503 
504  ```cpp
505  entt::collector.replace<sprite>();
506  ```
507 
508 * Grouping matcher: an observer will return at least all the living entities
509  that would have entered the given group if it existed and that would have
510  not yet left it.
511 
512  ```cpp
513  entt::collector.group<position, velocity>(entt::exclude<destroyed>);
514  ```
515 
516  A grouping matcher supports also exclusion lists as well as single components.
517 
518 Roughly speaking, an observing matcher intercepts the entities for which the
519 given components are replaced (as in `registry::replace`) while a grouping
520 matcher tracks the entities that have assigned the given components since the
521 last time one asked.<br/>
522 Note that, for a grouping matcher, if an entity already has all the components
523 except one and the missing type is assigned to it, it is intercepted.
524 
525 In addition, a matcher can be filtered with a `where` clause:
526 
527 ```cpp
528 entt::collector.replace<sprite>().where<position>(entt::exclude<velocity>);
529 ```
530 
531 This clause introduces a way to intercept entities if and only if they are
532 already part of a hypothetical group. If they are not, they aren't returned by
533 the observer, no matter if they matched the given rule.<br/>
534 In the example above, whenever the component `sprite` of an entity is replaced,
535 the observer probes the entity itself to verify that it has at least `position`
536 and has not `velocity` before to store it aside. If one of the two conditions of
537 the filter isn't respected, the entity is discared, no matter what.
538 
539 A `where` clause accepts a theoretically unlimited number of types as well as
540 multiple elements in the exclusion list. Moreover, every matcher can have it's
541 own clause and multiple clauses for the same matcher are combined in a single
542 one.
543 
544 ## Runtime components
545 
546 Defining components at runtime is useful to support plugin systems and mods in
547 general. However, it seems impossible with a tool designed around a bunch of
548 templates. Indeed it's not that difficult.<br/>
549 Of course, some features cannot be easily exported into a runtime
550 environment. As an example, sorting a group of components defined at runtime
551 isn't for free if compared to most of the other operations. However, the basic
552 functionalities of an entity-component system such as `EnTT` fit the problem
553 perfectly and can also be used to manage runtime components if required.<br/>
554 All that is necessary to do it is to know the identifiers of the components. An
555 identifier is nothing more than a number or similar that can be used at runtime
556 to work with the type system.
557 
558 In `EnTT`, identifiers are easily accessible:
559 
560 ```cpp
561 entt::registry registry;
562 
563 // component identifier
564 auto type = registry.type<position>();
565 ```
566 
567 Once the identifiers are made available, almost everything becomes pretty
568 simple.
569 
570 ### A journey through a plugin
571 
572 `EnTT` comes with an example (actually a test) that shows how to integrate
573 compile-time and runtime components in a stack based JavaScript environment. It
574 uses [`Duktape`](https://github.com/svaarala/duktape) under the hood, mainly
575 because I wanted to learn how it works at the time I was writing the code.
576 
577 The code is not production-ready and overall performance can be highly improved.
578 However, I sacrificed optimizations in favor of a more readable piece of code. I
579 hope I succeeded.<br/>
580 Note also that this isn't neither the only nor (probably) the best way to do it.
581 In fact, the right way depends on the scripting language and the problem one is
582 facing in general.<br/>
583 That being said, feel free to use it at your own risk.
584 
585 The basic idea is that of creating a compile-time component aimed to map all the
586 runtime components assigned to an entity.<br/>
587 Identifiers come in use to address the right function from a map when invoked
588 from the runtime environment and to filter entities when iterating.<br/>
589 With a bit of gymnastic, one can narrow views and improve the performance to
590 some extent but it was not the goal of the example.
591 
592 ## Sorting: is it possible?
593 
594 It goes without saying that sorting entities and components is possible with
595 `EnTT`.<br/>
596 In fact, there are two functions that respond to slightly different needs:
597 
598 * Components can be sorted either directly:
599 
600  ```cpp
601  registry.sort<renderable>([](const auto &lhs, const auto &rhs) {
602  return lhs.z < rhs.z;
603 
604  });
605  ```
606 
607  Or by accessing their entities:
608 
609  ```cpp
610  registry.sort<renderable>([](const entt::entity lhs, const entt::entity rhs) {
611  return entt::registry::entity(lhs) < entt::registry::entity(rhs);
612  });
613  ```
614 
615  There exists also the possibility to use a custom sort function object, as
616  long as it adheres to the requirements described in the inline
617  documentation.<br/>
618  This is possible mainly because users can get much more with a custom sort
619  function object if the usage pattern is known. As an example, in case of an
620  almost sorted pool, quick sort could be much, much slower than insertion sort.
621 
622 * Components can be sorted according to the order imposed by another component:
623 
624  ```cpp
625  registry.sort<movement, physics>();
626  ```
627 
628  In this case, instances of `movement` are arranged in memory so that cache
629  misses are minimized when the two components are iterated together.
630 
631 As a side note, when groups are involved, the sorting functions are applied
632 separately to the elements that are part of the group and to those that are not,
633 effectively generating two partitions, both of which can be ordered
634 independently of each other.
635 
636 ## Helpers
637 
638 The so called _helpers_ are small classes and functions mainly designed to offer
639 built-in support for the most basic functionalities.<br/>
640 The list of helpers will grow longer as time passes and new ideas come out.
641 
642 ### Null entity
643 
644 In `EnTT`, there exists a sort of _null entity_ made available to users that is
645 accessible via the `entt::null` variable.<br/>
646 The library guarantees that the following expression always returns false:
647 
648 ```cpp
649 registry.valid(entt::null);
650 ```
651 
652 In other terms, a registry will reject the null entity in all cases because it
653 isn't considered valid. It means that the null entity cannot own components for
654 obvious reasons.<br/>
655 The type of the null entity is internal and should not be used for any purpose
656 other than defining the null entity itself. However, there exist implicit
657 conversions from the null entity to identifiers of any allowed type:
658 
659 ```cpp
660 entt::entity null = entt::null;
661 ```
662 
663 Similarly, the null entity can be compared to any other identifier:
664 
665 ```cpp
666 const auto entity = registry.create();
667 const bool null = (entity == entt::null);
668 ```
669 
670 ### Stomp and spawn
671 
672 The use of multiple registries is quite common. Examples of use are the
673 separation of the UI from the simulation or the loading of different scenes in
674 the background, possibly on a separate thread, without having to keep track of
675 which entity belongs to which scene.<br/>
676 In fact, with `EnTT` this is even a recommended practice, as the registry is
677 nothing more than a container and different optimizations and strategies can be
678 applied to different containers.
679 
680 Once there are multiple registries available, however, one or more methods are
681 needed to transfer information from one container to another and this results in
682 the `stomp` member function and a couple of overloads of the `create` member
683 function for the `registry` class .<br/>
684 The `stomp` function allows to take one entity from a registry and use it to
685 _stomp_ one or more entities in another registry (or even the same, actually
686 making local copies). On the other hand, the overloads of the `create` member
687 function can be used to spawn new entities from a prototype.
688 
689 These features open definitely the doors to a lot of interesting features like
690 migrating entities between registries, prototypes, shadow registry, prefabs,
691 shared components without an explicit owner and copy-on-write policies among the
692 other things.
693 
694 ### Dependencies
695 
696 The `registry` class is designed to create short circuits between its functions
697 within certain limits. This allows to easily define dependencies between
698 different operations.<br/>
699 For example, the following adds (or replaces) the component `a_type` whenever
700 `my_type` is assigned to an entity:
701 
702 ```cpp
703 registry.on_construct<my_type>().connect<&entt::registry::assign_or_replace<a_type>>(registry);
704 ```
705 
706 Similarly, the code shown below removes `a_type` from an entity whenever
707 `my_type` is assigned to it:
708 
709 ```cpp
710 registry.on_construct<my_type>().connect<&entt::registry::reset<a_type>>(registry);
711 ```
712 
713 A dependency can also be easily broken as follows:
714 
715 ```cpp
716 registry.on_construct<my_type>().disconnect<&entt::registry::assign_or_replace<a_type>>(registry);
717 ```
718 
719 There are many other types of dependencies besides those shown above. In
720 general, all functions that accept an entity as the first argument are good
721 candidates for this purpose.
722 
723 ### Tags
724 
725 There's nothing magical about the way tags can be assigned to entities while
726 avoiding a performance hit at runtime. Nonetheless, the syntax can be annoying
727 and that's why a more user-friendly shortcut is provided to do it.<br/>
728 This shortcut is the alias template `entt::tag`.
729 
730 If used in combination with hashed strings, it helps to use tags where types
731 would be required otherwise. As an example:
732 
733 ```cpp
734 registry.assign<entt::tag<"enemy"_hs>>(entity);
735 ```
736 
737 ### Actor
738 
739 The `actor` class is designed for those who don't feel immediately comfortable
740 working with components or for those who are migrating a project and want to
741 approach it one step at a time.
742 
743 This class acts as a thin wrapper for an entity and for all its components. It's
744 constructed with a registry to be used behind the scenes and is in charge of the
745 destruction of the entity when it goes out of the scope.<br/>
746 An actor offers all the functionalities required to work with components, such
747 as the `assign` and` remove` member functions, but also `has`,` get`, `try_get`
748 and so on.
749 
750 My advice isn't to use the `actor` class to hide entities and components behind
751 a more object-oriented interface. Instead, users should rely on it only where
752 strictly necessary. In all other cases, it's highly advisable to become familiar
753 with the model of `EnTT` and work directly with the registry, the views and the
754 groups, rather than with a tool that could introduce a performance degradation.
755 
756 ### Context variables
757 
758 It is often convenient to assign context variables to a registry, so as to make
759 it the only _source of truth_ of an application.<br/>
760 This is possible by means of a member function named `set` to use to create a
761 context variable from a given type. Later on, either `ctx` or `try_ctx` can be
762 used to retrieve the newly created instance and `unset` is there to literally
763 reset it if needed.
764 
765 Example of use:
766 
767 ```cpp
768 // creates a new context variable initialized with the given values
769 registry.set<my_type>(42, 'c');
770 
771 // gets the context variable
772 const auto &var = registry.ctx<my_type>();
773 
774 // if in doubts, probe the registry to avoid assertions in case of errors
775 if(auto *ptr = registry.try_ctx<my_type>(); ptr) {
776  // uses the context variable associated with the registry, if any
777 }
778 
779 // unsets the context variable
780 registry.unset<my_type>();
781 ```
782 
783 The type of a context variable must be such that it's default constructible and
784 can be moved. The `set` member function either creates a new instance of the
785 context variable or overwrites an already existing one if any. The `try_ctx`
786 member function returns a pointer to the context variable if it exists,
787 otherwise it returns a null pointer. This fits well with the `if` statement with
788 initializer.
789 
790 ## Snapshot: complete vs continuous
791 
792 The `registry` class offers basic support to serialization.<br/>
793 It doesn't convert components to bytes directly, there wasn't the need of
794 another tool for serialization out there. Instead, it accepts an opaque object
795 with a suitable interface (namely an _archive_) to serialize its internal data
796 structures and restore them later. The way types and instances are converted to
797 a bunch of bytes is completely in charge to the archive and thus to final users.
798 
799 The goal of the serialization part is to allow users to make both a dump of the
800 entire registry or a narrower snapshot, that is to select only the components in
801 which they are interested.<br/>
802 Intuitively, the use cases are different. As an example, the first approach is
803 suitable for local save/restore functionalities while the latter is suitable for
804 creating client-server applications and for transferring somehow parts of the
805 representation side to side.
806 
807 To take a snapshot of the registry, use the `snapshot` member function. It
808 returns a temporary object properly initialized to _save_ the whole registry or
809 parts of it.
810 
811 Example of use:
812 
813 ```cpp
814 output_archive output;
815 
816 registry.snapshot()
817  .entities(output)
818  .destroyed(output)
819  .component<a_component, another_component>(output);
820 ```
821 
822 It isn't necessary to invoke all these functions each and every time. What
823 functions to use in which case mostly depends on the goal and there is not a
824 golden rule to do that.
825 
826 The `entities` member function asks the registry to serialize all the entities
827 that are still in use along with their versions. On the other side, the
828 `destroyed` member function tells to the registry to serialize the entities that
829 have been destroyed and are no longer in use.<br/>
830 These two functions can be used to save and restore the whole set of entities
831 with the versions they had during serialization.
832 
833 The `component` member function is a function template the aim of which is to
834 store aside components. The presence of a template parameter list is a
835 consequence of a couple of design choices from the past and in the present:
836 
837 * First of all, there is no reason to force a user to serialize all the
838  components at once and most of the times it isn't desiderable. As an example,
839  in case the stuff for the HUD in a game is put into the registry for some
840  reasons, its components can be freely discarded during a serialization step
841  because probably the software already knows how to reconstruct the HUD
842  correctly from scratch.
843 
844 * Furthermore, the registry makes heavy use of _type-erasure_ techniques
845  internally and doesn't know at any time what types of components it contains.
846  Therefore being explicit at the call point is mandatory.
847 
848 There exists also another version of the `component` member function that
849 accepts a range of entities to serialize. This version is a bit slower than the
850 other one, mainly because it iterates the range of entities more than once for
851 internal purposes. However, it can be used to filter out those entities that
852 shouldn't be serialized for some reasons.<br/>
853 As an example:
854 
855 ```cpp
856 const auto view = registry.view<serialize>();
857 output_archive output;
858 
859 registry.snapshot().component<a_component, another_component>(output, view.cbegin(), view.cend());
860 ```
861 
862 Note that `component` stores items along with entities. It means that it works
863 properly without a call to the `entities` member function.
864 
865 Once a snapshot is created, there exist mainly two _ways_ to load it: as a whole
866 and in a kind of _continuous mode_.<br/>
867 The following sections describe both loaders and archives in details.
868 
869 ### Snapshot loader
870 
871 A snapshot loader requires that the destination registry be empty and loads all
872 the data at once while keeping intact the identifiers that the entities
873 originally had.<br/>
874 To do that, the registry offers a member function named `loader` that returns a
875 temporary object properly initialized to _restore_ a snapshot.
876 
877 Example of use:
878 
879 ```cpp
880 input_archive input;
881 
882 registry.loader()
883  .entities(input)
884  .destroyed(input)
885  .component<a_component, another_component>(input)
886  .orphans();
887 ```
888 
889 It isn't necessary to invoke all these functions each and every time. What
890 functions to use in which case mostly depends on the goal and there is not a
891 golden rule to do that. For obvious reasons, what is important is that the data
892 are restored in exactly the same order in which they were serialized.
893 
894 The `entities` and `destroyed` member functions restore the sets of entities and
895 the versions that the entities originally had at the source.
896 
897 The `component` member function restores all and only the components specified
898 and assigns them to the right entities. Note that the template parameter list
899 must be exactly the same used during the serialization.
900 
901 The `orphans` member function literally destroys those entities that have no
902 components attached. It's usually useless if the snapshot is a full dump of the
903 source. However, in case all the entities are serialized but only few components
904 are saved, it could happen that some of the entities have no components once
905 restored. The best users can do to deal with them is to destroy those entities
906 and thus update their versions.
907 
908 ### Continuous loader
909 
910 A continuous loader is designed to load data from a source registry to a
911 (possibly) non-empty destination. The loader can accommodate in a registry more
912 than one snapshot in a sort of _continuous loading_ that updates the
913 destination one step at a time.<br/>
914 Identifiers that entities originally had are not transferred to the target.
915 Instead, the loader maps remote identifiers to local ones while restoring a
916 snapshot. Because of that, this kind of loader offers a way to update
917 automatically identifiers that are part of components (as an example, as data
918 members or gathered in a container).<br/>
919 Another difference with the snapshot loader is that the continuous loader does
920 not need to work with the private data structures of a registry. Furthermore, it
921 has an internal state that must persist over time. Therefore, there is no reason
922 to create it by means of a registry, or to limit its lifetime to that of a
923 temporary object.
924 
925 Example of use:
926 
927 ```cpp
928 entt::continuous_loader<entt::entity> loader{registry};
929 input_archive input;
930 
931 loader.entities(input)
932  .destroyed(input)
933  .component<a_component, another_component, dirty_component>(input, &dirty_component::parent, &dirty_component::child)
934  .orphans()
935  .shrink();
936 ```
937 
938 It isn't necessary to invoke all these functions each and every time. What
939 functions to use in which case mostly depends on the goal and there is not a
940 golden rule to do that. For obvious reasons, what is important is that the data
941 are restored in exactly the same order in which they were serialized.
942 
943 The `entities` and `destroyed` member functions restore groups of entities and
944 map each entity to a local counterpart when required. In other terms, for each
945 remote entity identifier not yet registered by the loader, the latter creates a
946 local identifier so that it can keep the local entity in sync with the remote
947 one.
948 
949 The `component` member function restores all and only the components specified
950 and assigns them to the right entities.<br/>
951 In case the component contains entities itself (either as data members of type
952 `entt::entity` or as containers of entities), the loader can update them
953 automatically. To do that, it's enough to specify the data members to update as
954 shown in the example.
955 
956 The `orphans` member function literally destroys those entities that have no
957 components after a restore. It has exactly the same purpose described in the
958 previous section and works the same way.
959 
960 Finally, `shrink` helps to purge local entities that no longer have a remote
961 conterpart. Users should invoke this member function after restoring each
962 snapshot, unless they know exactly what they are doing.
963 
964 ### Archives
965 
966 Archives must publicly expose a predefined set of member functions. The API is
967 straightforward and consists only of a group of function call operators that
968 are invoked by the snapshot class and the loaders.
969 
970 In particular:
971 
972 * An output archive, the one used when creating a snapshot, must expose a
973  function call operator with the following signature to store entities:
974 
975  ```cpp
976  void operator()(entt::entity);
977  ```
978 
979  Where `entt::entity` is the type of the entities used by the registry. Note
980  that all the member functions of the snapshot class make also an initial call
981  to this endpoint to save the _size_ of the set they are going to store.<br/>
982  In addition, an archive must accept a pair of entity and component for each
983  type to be serialized. Therefore, given a type `T`, the archive must contain a
984  function call operator with the following signature:
985 
986  ```cpp
987  void operator()(entt::entity, const T &);
988  ```
989 
990  The output archive can freely decide how to serialize the data. The register
991  is not affected at all by the decision.
992 
993 * An input archive, the one used when restoring a snapshot, must expose a
994  function call operator with the following signature to load entities:
995 
996  ```cpp
997  void operator()(entt::entity &);
998  ```
999 
1000  Where `entt::entity` is the type of the entities used by the registry. Each
1001  time the function is invoked, the archive must read the next element from the
1002  underlying storage and copy it in the given variable. Note that all the member
1003  functions of a loader class make also an initial call to this endpoint to read
1004  the _size_ of the set they are going to load.<br/>
1005  In addition, the archive must accept a pair of entity and component for each
1006  type to be restored. Therefore, given a type `T`, the archive must contain a
1007  function call operator with the following signature:
1008 
1009  ```cpp
1010  void operator()(entt::entity &, T &);
1011  ```
1012 
1013  Every time such an operator is invoked, the archive must read the next
1014  elements from the underlying storage and copy them in the given variables.
1015 
1016 ### One example to rule them all
1017 
1018 `EnTT` comes with some examples (actually some tests) that show how to integrate
1019 a well known library for serialization as an archive. It uses
1020 [`Cereal C++`](https://uscilab.github.io/cereal/) under the hood, mainly
1021 because I wanted to learn how it works at the time I was writing the code.
1022 
1023 The code is not production-ready and it isn't neither the only nor (probably)
1024 the best way to do it. However, feel free to use it at your own risk.
1025 
1026 The basic idea is to store everything in a group of queues in memory, then bring
1027 everything back to the registry with different loaders.
1028 
1029 # Views and Groups
1030 
1031 First of all, it is worth answering an obvious question: why views and
1032 groups?<br/>
1033 Briefly, they are a good tool to enforce single responsibility. A system that
1034 has access to a registry can create and destroy entities, as well as assign and
1035 remove components. On the other side, a system that has access to a view or a
1036 group can only iterate entities and their components, then read or update the
1037 data members of the latter.<br/>
1038 It is a subtle difference that can help designing a better software sometimes.
1039 
1040 More in details, views are a non-intrusive tool to access entities and
1041 components without affecting other functionalities or increasing the memory
1042 consumption. On the other side, groups are an intrusive tool that allows to
1043 reach higher performance along critical paths but has also a price to pay for
1044 that.
1045 
1046 There are mainly two kinds of views: _compile-time_ (also known as `view`) and
1047 runtime (also known as `runtime_view`).<br/>
1048 The former require that users indicate at compile-time what are the components
1049 involved and can make several optimizations because of that. The latter can be
1050 constructed at runtime instead and are a bit slower to iterate entities and
1051 components.<br/>
1052 In both cases, creating and destroying a view isn't expensive at all because
1053 views don't have any type of initialization. Moreover, views don't affect any
1054 other functionality of the registry and keep memory usage at a minimum.
1055 
1056 Groups come in three different flavors: _full-owning groups_, _partial-owning
1057 groups_ and _non-owning groups_. The main difference between them is in terms of
1058 performance.<br/>
1059 Groups can literally _own_ one or more types of components. It means that they
1060 will be allowed to rearrange pools so as to speed up iterations. Roughly
1061 speaking: the more components a group owns, the faster it is to iterate them.
1062 On the other side, a given component can belong only to one group, so users have
1063 to define groups carefully to get the best out of them.
1064 
1065 Continue reading for more details or refer to the inline documentation.
1066 
1067 ## Views
1068 
1069 A view behaves differently if it's constructed for a single component or if it
1070 has been created to iterate multiple components. Even the API is slightly
1071 different in the two cases.
1072 
1073 Single component views are specialized in order to give a boost in terms of
1074 performance in all the situations. This kind of views can access the underlying
1075 data structures directly and avoid superfluous checks. There is nothing as fast
1076 as a single component view. In fact, they walk through a packed array of
1077 components and return them one at a time.<br/>
1078 Single component views offer a bunch of functionalities to get the number of
1079 entities they are going to return and a raw access to the entity list as well as
1080 to the component list. It's also possible to ask a view if it contains a
1081 given entity.<br/>
1082 Refer to the inline documentation for all the details.
1083 
1084 Multi component views iterate entities that have at least all the given
1085 components in their bags. During construction, these views look at the number of
1086 entities available for each component and pick up a reference to the smallest
1087 set of candidates in order to speed up iterations.<br/>
1088 They offer fewer functionalities than their companion views for single
1089 component. In particular, a multi component view exposes utility functions to
1090 get the estimated number of entities it is going to return and to know whether
1091 it's empty or not. It's also possible to ask a view if it contains a given
1092 entity.<br/>
1093 Refer to the inline documentation for all the details.
1094 
1095 There is no need to store views around for they are extremely cheap to
1096 construct, even though they can be copied without problems and reused freely.
1097 Views also return newly created and correctly initialized iterators whenever
1098 `begin` or `end` are invoked.
1099 
1100 Views share the way they are created by means of a registry:
1101 
1102 ```cpp
1103 // single component view
1104 auto single = registry.view<position>();
1105 
1106 // multi component view
1107 auto multi = registry.view<position, velocity>();
1108 ```
1109 
1110 To iterate a view, either use it in a range-for loop:
1111 
1112 ```cpp
1113 auto view = registry.view<position, velocity>();
1114 
1115 for(auto entity: view) {
1116  // a component at a time ...
1117  auto &position = view.get<position>(entity);
1118  auto &velocity = view.get<velocity>(entity);
1119 
1120  // ... or multiple components at once
1121  auto &[pos, vel] = view.get<position, velocity>(entity);
1122 
1123  // ...
1124 }
1125 ```
1126 
1127 Or rely on the `each` member function to iterate entities and get all their
1128 components at once:
1129 
1130 ```cpp
1131 registry.view<position, velocity>().each([](auto entity, auto &pos, auto &vel) {
1132  // ...
1133 });
1134 ```
1135 
1136 The `each` member function is highly optimized. Unless users want to iterate
1137 only entities or get only some of the components, this should be the preferred
1138 approach. Note that the entity can also be excluded from the parameter list if
1139 not required, but this won't improve performance for multi component views.<br/>
1140 There exists also an alternative version of `each` named `less` that works
1141 exactly as its counterpart but for the fact that it doesn't return empty
1142 components to the caller.
1143 
1144 As a side note, when using a single component view, the most common error is to
1145 invoke `get` with the type of the component as a template parameter. This is
1146 probably due to the fact that it's required for multi component views:
1147 
1148 ```cpp
1149 auto view = registry.view<position, const velocity>();
1150 
1151 for(auto entity: view) {
1152  const auto &vel = view.get<const velocity>(entity);
1153  // ...
1154 }
1155 ```
1156 
1157 However, in case of a single component view, `get` doesn't accept a template
1158 parameter, since it's implicitly defined by the view itself:
1159 
1160 ```cpp
1161 auto view = registry.view<const renderable>();
1162 
1163 for(auto entity: view) {
1164  const auto &renderable = view.get(entity);
1165  // ...
1166 }
1167 ```
1168 
1169 **Note**: prefer the `get` member function of a view instead of the `get` member
1170 function template of a registry during iterations, if possible. However, keep in
1171 mind that it works only with the components of the view itself.
1172 
1173 ## Runtime views
1174 
1175 Runtime views iterate entities that have at least all the given components in
1176 their bags. During construction, these views look at the number of entities
1177 available for each component and pick up a reference to the smallest
1178 set of candidates in order to speed up iterations.<br/>
1179 They offer more or less the same functionalities of a multi component view.
1180 However, they don't expose a `get` member function and users should refer to the
1181 registry that generated the view to access components. In particular, a runtime
1182 view exposes utility functions to get the estimated number of entities it is
1183 going to return and to know whether it's empty or not. It's also possible to ask
1184 a runtime view if it contains a given entity.<br/>
1185 Refer to the inline documentation for all the details.
1186 
1187 Runtime view are extremely cheap to construct and should not be stored around in
1188 any case. They should be used immediately after creation and then they should be
1189 thrown away. The reasons for this go far beyond the scope of this document.<br/>
1190 To iterate a runtime view, either use it in a range-for loop:
1191 
1192 ```cpp
1193 entt::component types[] = { registry.type<position>(), registry.type<velocity>() };
1194 auto view = registry.runtime_view(std::cbegin(types), std::cend(types));
1195 
1196 for(auto entity: view) {
1197  // a component at a time ...
1198  auto &position = registry.get<position>(entity);
1199  auto &velocity = registry.get<velocity>(entity);
1200 
1201  // ... or multiple components at once
1202  auto &[pos, vel] = registry.get<position, velocity>(entity);
1203 
1204  // ...
1205 }
1206 ```
1207 
1208 Or rely on the `each` member function to iterate entities:
1209 
1210 ```cpp
1211 entt::component types[] = { registry.type<position>(), registry.type<velocity>() };
1212 
1213 registry.runtime_view(std::cbegin(types), std::cend(types)).each([](auto entity) {
1214  // ...
1215 });
1216 ```
1217 
1218 Performance are exactly the same in both cases.
1219 
1220 **Note**: runtime views are meant for all those cases where users don't know at
1221 compile-time what components to use to iterate entities. This is particularly
1222 well suited to plugin systems and mods in general. Where possible, don't use
1223 runtime views, as their performance are slightly inferior to those of the other
1224 views.
1225 
1226 ## Groups
1227 
1228 Groups are meant to iterate multiple components at once and offer a faster
1229 alternative to views. Roughly speaking, they just play in another league when
1230 compared to views.<br/>
1231 Groups overcome the performance of the other tools available but require to get
1232 the ownership of components and this sets some constraints on pools. On the
1233 other side, groups aren't an automatism that increases memory consumption,
1234 affects functionalities and tries to optimize iterations for all the possible
1235 combinations of components. Users can decide when to pay for groups and to what
1236 extent.<br/>
1237 The most interesting aspect of groups is that they fit _usage patterns_. Other
1238 solutions around usually try to optimize everything, because it is known that
1239 somewhere within the _everything_ there are also our usage patterns. However
1240 this has a cost that isn't negligible, both in terms of performance and memory
1241 usage. Ironically, users pay the price also for things they don't want and this
1242 isn't something I like much. Even worse, one cannot easily disable such a
1243 behavior. Groups work differently instead and are designed to optimize only the
1244 real use cases when users find they need to.<br/>
1245 Another nice-to-have feature of groups is that they have no impact on memory
1246 consumption, put aside full non-owning groups that are pretty rare and should be
1247 avoided as long as possible.
1248 
1249 All groups affect to an extent the creation and destruction of their components.
1250 This is due to the fact that they must _observe_ changes in the pools of
1251 interest and arrange data _correctly_ when needed for the types they own.<br/>
1252 That being said, the way groups operate is beyond the scope of this document.
1253 However, it's unlikely that users will be able to appreciate the impact of
1254 groups on other functionalities of the registry.
1255 
1256 Groups offer a bunch of functionalities to get the number of entities they are
1257 going to return and a raw access to the entity list as well as to the component
1258 list for owned components. It's also possible to ask a group if it contains a
1259 given entity.<br/>
1260 Refer to the inline documentation for all the details.
1261 
1262 There is no need to store groups around for they are extremely cheap to
1263 construct, even though they can be copied without problems and reused freely.
1264 A group performs an initialization step the very first time it's requested and
1265 this could be quite costly. To avoid it, consider creating the group when no
1266 components have been assigned yet. If the registry is empty, preparation is
1267 extremely fast. Groups also return newly created and correctly initialized
1268 iterators whenever `begin` or `end` are invoked.
1269 
1270 To iterate groups, either use them in a range-for loop:
1271 
1272 ```cpp
1273 auto group = registry.group<position>(entt::get<velocity>);
1274 
1275 for(auto entity: group) {
1276  // a component at a time ...
1277  auto &position = group.get<position>(entity);
1278  auto &velocity = group.get<velocity>(entity);
1279 
1280  // ... or multiple components at once
1281  auto &[pos, vel] = group.get<position, velocity>(entity);
1282 
1283  // ...
1284 }
1285 ```
1286 
1287 Or rely on the `each` member function to iterate entities and get all their
1288 components at once:
1289 
1290 ```cpp
1291 registry.group<position>(entt::get<velocity>).each([](auto entity, auto &pos, auto &vel) {
1292  // ...
1293 });
1294 ```
1295 
1296 The `each` member function is highly optimized. Unless users want to iterate
1297 only entities, this should be the preferred approach. Note that the entity can
1298 also be excluded from the parameter list if not required and it can improve even
1299 further the performance during iterations.
1300 
1301 **Note**: prefer the `get` member function of a group instead of the `get`
1302 member function template of a registry during iterations, if possible. However,
1303 keep in mind that it works only with the components of the group itself.
1304 
1305 Let's go a bit deeper into the different types of groups made available by this
1306 library to know how they are constructed and what are the differences between
1307 them.
1308 
1309 ### Full-owning groups
1310 
1311 A full-owning group is the fastest tool an user can expect to use to iterate
1312 multiple components at once. It iterates all the components directly, no
1313 indirection required. This type of groups performs more or less as if users are
1314 accessing sequentially a bunch of packed arrays of components all sorted
1315 identically.
1316 
1317 A full-owning group is created as:
1318 
1319 ```cpp
1320 auto group = registry.group<position, velocity>();
1321 ```
1322 
1323 Filtering entities by components is also supported:
1324 
1325 ```cpp
1326 auto group = registry.group<position, velocity>(entt::exclude<renderable>);
1327 ```
1328 
1329 Once created, the group gets the ownership of all the components specified in
1330 the template parameter list and arranges their pools so as to iterate all of
1331 them as fast as possible.
1332 
1333 Sorting owned components is no longer allowed once the group has been created.
1334 However, full-owning groups can be sorted by means of their `sort` member
1335 functions, if required. Sorting a full-owning group affects all the instances of
1336 the same group (it means that users don't have to call `sort` on each instance
1337 to sort all of them because they share the underlying data structure).<br/>
1338 The elements that aren't part of the group can still be sorted separately for
1339 each pool using the `sort` member function of the registry.
1340 
1341 ### Partial-owning groups
1342 
1343 A partial-owning group works similarly to a full-owning group for the components
1344 it owns, but relies on indirection to get components owned by other groups. This
1345 isn't as fast as a full-owning group, but it's already much faster than views
1346 when there are only one or two free components to retrieve (the most common
1347 cases likely). In the worst case, it's not slower than views anyway.
1348 
1349 A partial-owning group is created as:
1350 
1351 ```cpp
1352 auto group = registry.group<position>(entt::get<velocity>);
1353 ```
1354 
1355 Filtering entities by components is also supported:
1356 
1357 ```cpp
1358 auto group = registry.group<position>(entt::get<velocity>, entt::exclude<renderable>);
1359 ```
1360 
1361 Once created, the group gets the ownership of all the components specified in
1362 the template parameter list and arranges their pools so as to iterate all of
1363 them as fast as possible. The ownership of the types provided via `entt::get`
1364 doesn't pass to the group instead.
1365 
1366 Sorting owned components is no longer allowed once the group has been created.
1367 However, partial-owning groups can be sorted by means of their `sort` member
1368 functions, if required. Sorting a partial-owning group affects all the instances
1369 of the same group (it means that users don't have to call `sort` on each
1370 instance to sort all of them because they share the underlying data
1371 structure).<br/>
1372 Regarding the owned types, the elements that aren't part of the group can still
1373 be sorted separately for each pool using the `sort` member function of the
1374 registry.
1375 
1376 ### Non-owning groups
1377 
1378 Non-owning groups are usually fast enough, for sure faster than views and well
1379 suited for most of the cases. However, they require custom data structures to
1380 work properly and they increase memory consumption. As a rule of thumb, users
1381 should avoid using non-owning groups, if possible.
1382 
1383 A non-owning group is created as:
1384 
1385 ```cpp
1386 auto group = registry.group<>(entt::get<position, velocity>);
1387 ```
1388 
1389 Filtering entities by components is also supported:
1390 
1391 ```cpp
1392 auto group = registry.group<>(entt::get<position, velocity>, entt::exclude<renderable>);
1393 ```
1394 
1395 The group doesn't receive the ownership of any type of component in this
1396 case. This type of groups is therefore the least performing in general, but also
1397 the only one that can be used in any situation to improve a performance where
1398 necessary.
1399 
1400 Non-owning groups can be sorted by means of their `sort` member functions, if
1401 required. Sorting a non-owning group affects all the instance of the same group
1402 (it means that users don't have to call `sort` on each instance to sort all of
1403 them because they share the set of entities).
1404 
1405 # Types: const, non-const and all in between
1406 
1407 The `registry` class offers two overloads when it comes to constructing views
1408 and groups: a const version and a non-const one. The former accepts both const
1409 and non-const types as template parameters, the latter accepts only const types
1410 instead.<br/>
1411 It means that views and groups can be constructed also from a const registry and
1412 they propagate the constness of the registry to the types involved. As an
1413 example:
1414 
1415 ```cpp
1416 entt::view<const position, const velocity> view = std::as_const(registry).view<const position, const velocity>();
1417 ```
1418 
1419 Consider the following definition for a non-const view instead:
1420 
1421 ```cpp
1422 entt::view<position, const velocity> view = registry.view<position, const velocity>();
1423 ```
1424 
1425 In the example above, `view` can be used to access either read-only or writable
1426 `position` components while `velocity` components are read-only in all
1427 cases.<br/>
1428 In other terms, these statements are all valid:
1429 
1430 ```cpp
1431 position &pos = view.get<position>(entity);
1432 const position &cpos = view.get<const position>(entity);
1433 const velocity &cpos = view.get<const velocity>(entity);
1434 std::tuple<position &, const velocity &> tup = view.get<position, const velocity>(entity);
1435 std::tuple<const position &, const velocity &> ctup = view.get<const position, const velocity>(entity);
1436 ```
1437 
1438 It's not possible to get non-const references to `velocity` components from the
1439 same view instead and these will result in compilation errors:
1440 
1441 ```cpp
1442 velocity &cpos = view.get<velocity>(entity);
1443 std::tuple<position &, velocity &> tup = view.get<position, velocity>(entity);
1444 std::tuple<const position &, velocity &> ctup = view.get<const position, velocity>(entity);
1445 ```
1446 
1447 Similarly, the `each` member functions will propagate constness to the type of
1448 the components returned during iterations:
1449 
1450 ```cpp
1451 view.each([](auto entity, position &pos, const velocity &vel) {
1452  // ...
1453 });
1454 ```
1455 
1456 Obviously, a caller can still refer to the `position` components through a const
1457 reference because of the rules of the language that fortunately already allow
1458 it.
1459 
1460 The same concepts apply to groups as well.
1461 
1462 ## Give me everything
1463 
1464 Views and groups are narrow windows on the entire list of entities. They work by
1465 filtering entities according to their components.<br/>
1466 In some cases there may be the need to iterate all the entities still in use
1467 regardless of their components. The registry offers a specific member function
1468 to do that:
1469 
1470 ```cpp
1471 registry.each([](auto entity) {
1472  // ...
1473 });
1474 ```
1475 
1476 It returns to the caller all the entities that are still in use by means of the
1477 given function.<br/>
1478 As a rule of thumb, consider using a view or a group if the goal is to iterate
1479 entities that have a determinate set of components. These tools are usually much
1480 faster than combining this function with a bunch of custom tests.<br/>
1481 In all the other cases, this is the way to go.
1482 
1483 There exists also another member function to use to retrieve orphans. An orphan
1484 is an entity that is still in use and has no assigned components.<br/>
1485 The signature of the function is the same of `each`:
1486 
1487 ```cpp
1488 registry.orphans([](auto entity) {
1489  // ...
1490 });
1491 ```
1492 
1493 To test the _orphanity_ of a single entity, use the member function `orphan`
1494 instead. It accepts a valid entity identifer as an argument and returns true in
1495 case the entity is an orphan, false otherwise.
1496 
1497 In general, all these functions can result in poor performance.<br/>
1498 `each` is fairly slow because of some checks it performs on each and every
1499 entity. For similar reasons, `orphans` can be even slower. Both functions should
1500 not be used frequently to avoid the risk of a performance hit.
1501 
1502 ## What is allowed and what is not
1503 
1504 Most of the _ECS_ available out there don't allow to create and destroy entities
1505 and components during iterations.<br/>
1506 `EnTT` partially solves the problem with a few limitations:
1507 
1508 * Creating entities and components is allowed during iterations in almost all
1509  cases.
1510 * Deleting the current entity or removing its components is allowed during
1511  iterations. For all the other entities, destroying them or removing their
1512  components isn't allowed and can result in undefined behavior.
1513 
1514 In these cases, iterators aren't invalidated. To be clear, it doesn't mean that
1515 also references will continue to be valid.<br/>
1516 Consider the following example:
1517 
1518 ```cpp
1519 registry.view<position>([&](const auto entity, auto &pos) {
1520  registry.assign<position>(registry.create(), 0., 0.);
1521  pos.x = 0.; // warning: dangling pointer
1522 });
1523 ```
1524 
1525 The `each` member function won't break (because iterators aren't invalidated)
1526 but there are no guarantees on references. Use a common range-for loop and get
1527 components directly from the view or move the creation of components at the end
1528 of the function to avoid dangling pointers.
1529 
1530 Iterators are invalidated instead and the behavior is undefined if an entity is
1531 modified or destroyed and it's not the one currently returned by the iterator
1532 nor a newly created one.<br/>
1533 To work around it, possible approaches are:
1534 
1535 * Store aside the entities and the components to be removed and perform the
1536  operations at the end of the iteration.
1537 * Mark entities and components with a proper tag component that indicates they
1538  must be purged, then perform a second iteration to clean them up one by one.
1539 
1540 A notable side effect of this feature is that the number of required allocations
1541 is further reduced in most of the cases.
1542 
1543 ### More performance, more constraints
1544 
1545 Groups are a (much) faster alternative to views. However, the higher the
1546 performance, the greater the constraints on what is allowed and what is
1547 not.<br/>
1548 In particular, groups add in some rare cases a limitation on the creation of
1549 components during iterations. It happens in quite particular cases. Given the
1550 nature and the scope of the groups, it isn't something in which it will happen
1551 to come across probably, but it's good to know it anyway.
1552 
1553 First of all, it must be said that creating components while iterating a group
1554 isn't a problem at all and can be done freely as it happens with the views. The
1555 same applies to the destruction of components and entities, for which the rules
1556 mentioned above apply.
1557 
1558 The additional limitation pops out instead when a given component that is owned
1559 by a group is iterated outside of it. In this case, adding components that are
1560 part of the group itself may invalidate the iterators. There are no further
1561 limitations to the destruction of components and entities.<br/>
1562 Fortunately, this isn't always true. In fact, it almost never is and this
1563 happens only under certain conditions. In particular:
1564 
1565 * Iterating a type of component that is part of a group with a single component
1566  view and adding to an entity all the components required to get it into the
1567  group may invalidate the iterators.
1568 
1569 * Iterating a type of component that is part of a group with a multi component
1570  view and adding to an entity all the components required to get it into the
1571  group can invalidate the iterators, unless users specify another type of
1572  component to use to induce the order of iteration of the view (in this case,
1573  the former is treated as a free type and isn't affected by the limitation).
1574 
1575 In other words, the limitation doesn't exist as long as a type is treated as a
1576 free type (as an example with multi component views and partial- or non-owning
1577 groups) or iterated with its own group, but it can occur if the type is used as
1578 a main type to rule on an iteration.<br/>
1579 This happens because groups own the pools of their components and organize the
1580 data internally to maximize performance. Because of that, full consistency for
1581 owned components is guaranteed only when they are iterated as part of their
1582 groups or as free types with multi component views and groups in general.
1583 
1584 # Empty type optimization
1585 
1586 An empty type `T` is such that `std::is_empty_v<T>` returns true. They are also
1587 the same types for which _empty base optimization_ (EBO) is possibile.<br/>
1588 `EnTT` handles these types in a special way, optimizing both in terms of
1589 performance and memory usage. However, this also has consequences that are worth
1590 mentioning.
1591 
1592 When an empty type is detected, it's not instantiated in any case. Therefore,
1593 only the entities to which it's assigned are made available. All the iterators
1594 as well as the `get` member functions of the registry, the views and the groups
1595 will return temporary objects. Similarly, some functions such as `try_get` or
1596 the raw access to the list of components aren't available for this kind of
1597 types.<br/>
1598 On the other hand, iterations are faster because only the entities to which the
1599 type is assigned are considered. Moreover, less memory is used, since there
1600 doesn't exist any instance of the component, no matter how many entities it is
1601 assigned to.
1602 
1603 For similar reasons, wherever a function type of a listener accepts a component,
1604 it cannot be caught by a non-const reference. Capture it by copy or by const
1605 reference instead.
1606 
1607 More in general, none of the features offered by the library is affected, but
1608 for the ones that require to return actual instances.
1609 
1610 # Multithreading
1611 
1612 In general, the entire registry isn't thread safe as it is. Thread safety isn't
1613 something that users should want out of the box for several reasons. Just to
1614 mention one of them: performance.<br/>
1615 Views, groups and consequently the approach adopted by `EnTT` are the great
1616 exception to the rule. It's true that views, groups and iterators in general
1617 aren't thread safe by themselves. Because of this users shouldn't try to iterate
1618 a set of components and modify the same set concurrently. However:
1619 
1620 * As long as a thread iterates the entities that have the component `X` or
1621  assign and removes that component from a set of entities, another thread can
1622  safely do the same with components `Y` and `Z` and everything will work like a
1623  charm. As a trivial example, users can freely execute the rendering system and
1624  iterate the renderable entities while updating a physic component concurrently
1625  on a separate thread.
1626 
1627 * Similarly, a single set of components can be iterated by multiple threads as
1628  long as the components are neither assigned nor removed in the meantime. In
1629  other words, a hypothetical movement system can start multiple threads, each
1630  of which will access the components that carry information about velocity and
1631  position for its entities.
1632 
1633 This kind of entity-component systems can be used in single threaded
1634 applications as well as along with async stuff or multiple threads. Moreover,
1635 typical thread based models for _ECS_ don't require a fully thread safe registry
1636 to work. Actually, users can reach the goal with the registry as it is while
1637 working with most of the common models.
1638 
1639 Because of the few reasons mentioned above and many others not mentioned, users
1640 are completely responsible for synchronization whether required. On the other
1641 hand, they could get away with it without having to resort to particular
1642 expedients.
1643 
1644 ## Iterators
1645 
1646 A special mention is needed for the iterators returned by the views and the
1647 groups. Most of the time they meet the requirements of random access iterators,
1648 in all cases they meet at least the requirements of forward iterators.<br/>
1649 In other terms, they are suitable for use with the parallel algorithms of the
1650 standard library. If it's not clear, this is a great thing.
1651 
1652 As an example, this kind of iterators can be used in combination with
1653 `std::for_each` and `std::execution::par` to parallelize the visit and therefore
1654 the update of the components returned by a view or a group, as long as the
1655 constraints previously discussed are respected:
1656 
1657 ```cpp
1658 auto view = registry.view<position, const velocity>();
1659 
1660 std::for_each(std::execution::par_unseq, view.begin(), view.end(), [&view](auto entity) {
1661  // ...
1662 });
1663 ```
1664 
1665 This can increase the throughput considerably, even without resorting to who
1666 knows what artifacts that are difficult to maintain over time.
1667 
1668 Unfortunately, because of the limitations of the current revision of the
1669 standard, the parallel `std::for_each` accepts only forward iterators. This
1670 means that the iterators provided by the library cannot return proxy objects as
1671 references and **must** return actual reference types instead.<br/>
1672 This may change in the future and the iterators will almost certainly return
1673 both the entities and a list of references to their components sooner or later.
1674 Multi-pass guarantee won't break in any case and the performance should even
1675 benefit from it further.
1676 
1677 # Beyond this document
1678 
1679 There are many other features and functions not listed in this document.<br/>
1680 `EnTT` and in particular its ECS part is in continuous development and some
1681 things could be forgotten, others could have been omitted on purpose to reduce
1682 the size of this file. Unfortunately, some parts may even be outdated and still
1683 to be updated.
1684 
1685 For further information, it's recommended to refer to the documentation included
1686 in the code itself or join the official channels to ask a question.