🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2198 lines
87 KiB

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