From 81a9ccc24fa979a10187970d71e8aa993454af4c Mon Sep 17 00:00:00 2001 From: Michele Caini Date: Tue, 10 Jul 2018 16:36:42 +0200 Subject: [PATCH] API reference v2.7.0 --- README_8md_source.html | 2 +- actor_8hpp_source.html | 8 +- algorithm_8hpp_source.html | 8 +- annotated.html | 57 +- ...ate_3_01Ret_07Args_8_8_8_08_4-members.html | 7 +- ...1_1Delegate_3_01Ret_07Args_8_8_8_08_4.html | 45 +- classentt_1_1Identifier-members.html | 83 +++ classentt_1_1Identifier.html | 161 ++++++ classentt_1_1PersistentView-members.html | 9 +- classentt_1_1PersistentView.html | 98 +++- classentt_1_1Prototype-members.html | 4 + classentt_1_1Prototype.html | 161 +++++- classentt_1_1RawView-members.html | 2 + classentt_1_1RawView.html | 144 ++++- classentt_1_1Registry-members.html | 128 +++-- classentt_1_1Registry.html | 439 ++++++++++---- classentt_1_1ResourceHandle.html | 4 +- classentt_1_1RuntimeView-members.html | 96 ++++ classentt_1_1RuntimeView.html | 540 ++++++++++++++++++ classentt_1_1Scheduler.html | 16 +- ..._8_8_8_08_00_01Collector_01_4-members.html | 2 +- ...t_07Args_8_8_8_08_00_01Collector_01_4.html | 10 +- classentt_1_1SparseSet.html | 2 +- ...Set_3_01Entity_00_01Type_01_4-members.html | 50 +- ..._1SparseSet_3_01Entity_00_01Type_01_4.html | 168 ++++-- ..._1_1SparseSet_3_01Entity_01_4-members.html | 57 +- classentt_1_1SparseSet_3_01Entity_01_4.html | 145 +++-- classentt_1_1View.html | 52 +- ..._01Entity_00_01Component_01_4-members.html | 13 +- ..._1View_3_01Entity_00_01Component_01_4.html | 104 +++- classes.html | 47 +- config_8h_source.html | 2 +- delegate_8hpp_source.html | 15 +- entity_8hpp_source.html | 81 +++ entt_8hpp_source.html | 2 +- entt__traits_8hpp_source.html | 11 +- files.html | 22 +- functions_b.html | 3 +- functions_c.html | 15 +- functions_d.html | 9 +- functions_e.html | 11 +- functions_func_b.html | 3 +- functions_func_c.html | 12 +- functions_func_d.html | 4 +- functions_func_e.html | 14 +- functions_func_g.html | 9 +- functions_func_m.html | 2 +- functions_func_o.html | 28 +- functions_func_p.html | 2 +- functions_func_r.html | 2 +- functions_func_s.html | 15 +- functions_func_v.html | 2 +- functions_g.html | 9 +- functions_i.html | 4 + functions_m.html | 2 +- functions_o.html | 20 +- functions_p.html | 6 +- functions_r.html | 13 +- functions_rela.html | 1 + functions_s.html | 16 +- functions_type.html | 20 +- handle_8hpp_source.html | 2 +- hashed__string_8hpp_source.html | 2 +- helper_8hpp_source.html | 2 +- hierarchy.html | 63 +- ident_8hpp_source.html | 5 +- index.html | 223 +++++--- inherit_graph_14.map | 2 +- inherit_graph_14.md5 | 2 +- inherit_graph_14.png | Bin 1281 -> 1672 bytes inherit_graph_15.map | 2 +- inherit_graph_15.md5 | 2 +- inherit_graph_15.png | Bin 1138 -> 1281 bytes inherit_graph_16.map | 2 +- inherit_graph_16.md5 | 2 +- inherit_graph_16.png | Bin 2696 -> 2122 bytes inherit_graph_17.map | 2 +- inherit_graph_17.md5 | 2 +- inherit_graph_17.png | Bin 2274 -> 1138 bytes inherit_graph_18.map | 3 +- inherit_graph_18.md5 | 2 +- inherit_graph_18.png | Bin 7482 -> 2696 bytes inherit_graph_19.map | 2 +- inherit_graph_19.md5 | 2 +- inherit_graph_19.png | Bin 1637 -> 2274 bytes inherit_graph_20.map | 3 +- inherit_graph_20.md5 | 2 +- inherit_graph_20.png | Bin 1090 -> 7482 bytes inherit_graph_21.map | 2 +- inherit_graph_21.md5 | 2 +- inherit_graph_21.png | Bin 2626 -> 1637 bytes inherit_graph_22.map | 2 +- inherit_graph_22.md5 | 2 +- inherit_graph_22.png | Bin 1730 -> 1090 bytes inherit_graph_23.map | 2 +- inherit_graph_23.md5 | 2 +- inherit_graph_23.png | Bin 2193 -> 2626 bytes inherit_graph_24.map | 2 +- inherit_graph_24.md5 | 2 +- inherit_graph_24.png | Bin 2056 -> 1730 bytes inherit_graph_25.map | 2 +- inherit_graph_25.md5 | 2 +- inherit_graph_25.png | Bin 2161 -> 2193 bytes inherit_graph_26.map | 2 +- inherit_graph_26.md5 | 2 +- inherit_graph_26.png | Bin 1819 -> 2056 bytes inherit_graph_27.map | 2 +- inherit_graph_27.md5 | 2 +- inherit_graph_27.png | Bin 2059 -> 2161 bytes inherit_graph_28.map | 2 +- inherit_graph_28.md5 | 2 +- inherit_graph_28.png | Bin 2332 -> 2062 bytes inherit_graph_29.map | 2 +- inherit_graph_29.md5 | 2 +- inherit_graph_29.png | Bin 3872 -> 1819 bytes inherit_graph_30.map | 2 +- inherit_graph_30.md5 | 2 +- inherit_graph_30.png | Bin 2675 -> 2059 bytes inherit_graph_31.map | 2 +- inherit_graph_31.md5 | 2 +- inherit_graph_31.png | Bin 1767 -> 2332 bytes inherit_graph_32.map | 2 +- inherit_graph_32.md5 | 2 +- inherit_graph_32.png | Bin 2140 -> 3872 bytes inherit_graph_33.map | 2 +- inherit_graph_33.md5 | 2 +- inherit_graph_33.png | Bin 1954 -> 2675 bytes inherit_graph_34.map | 2 +- inherit_graph_34.md5 | 2 +- inherit_graph_34.png | Bin 2414 -> 1767 bytes inherit_graph_35.map | 3 +- inherit_graph_35.md5 | 2 +- inherit_graph_35.png | Bin 3584 -> 2140 bytes inherit_graph_36.map | 2 +- inherit_graph_36.md5 | 2 +- inherit_graph_36.png | Bin 1551 -> 1954 bytes inherit_graph_37.map | 2 +- inherit_graph_37.md5 | 2 +- inherit_graph_37.png | Bin 1250 -> 2414 bytes inherit_graph_38.map | 3 +- inherit_graph_38.md5 | 2 +- inherit_graph_38.png | Bin 965 -> 3584 bytes inherit_graph_39.map | 2 +- inherit_graph_39.md5 | 2 +- inherit_graph_39.png | Bin 2384 -> 1551 bytes inherit_graph_40.map | 2 +- inherit_graph_40.md5 | 2 +- inherit_graph_40.png | Bin 2384 -> 1250 bytes inherit_graph_41.map | 3 + inherit_graph_41.md5 | 1 + inherit_graph_41.png | Bin 0 -> 965 bytes inherit_graph_42.map | 3 + inherit_graph_42.md5 | 1 + inherit_graph_42.png | Bin 0 -> 2384 bytes inherit_graph_43.map | 3 + inherit_graph_43.md5 | 1 + inherit_graph_43.png | Bin 0 -> 2384 bytes inherit_graph_7.md5 | 2 +- inherits.html | 69 ++- menudata.js | 1 - monostate_8hpp_source.html | 81 +++ namespaceentt.html | 57 +- namespacemembers.html | 6 +- namespacemembers_type.html | 2 +- namespacemembers_vars.html | 4 +- prototype_8hpp_source.html | 41 +- registry_8hpp_source.html | 124 ++-- scheduler_8hpp_source.html | 18 +- search/all_1.js | 2 +- search/all_10.js | 10 +- search/all_11.js | 9 +- search/all_12.js | 12 +- search/{typedefs_c.html => all_13.html} | 2 +- search/all_13.js | 9 + search/all_2.js | 12 +- search/all_3.js | 5 +- search/all_4.js | 8 +- search/all_6.js | 2 +- search/all_8.js | 5 +- search/all_a.js | 3 +- search/all_b.js | 16 +- search/all_c.js | 28 +- search/all_d.js | 31 +- search/all_e.js | 44 +- search/all_f.js | 29 +- search/classes_7.js | 1 + search/classes_8.js | 7 +- search/classes_9.js | 12 +- search/classes_a.js | 20 +- search/classes_b.js | 14 +- search/classes_c.js | 3 +- search/classes_d.html | 26 + search/classes_d.js | 5 + search/functions_1.js | 2 +- search/functions_10.js | 2 +- search/functions_2.js | 10 +- search/functions_3.js | 2 +- search/functions_4.js | 6 +- search/functions_6.js | 2 +- search/functions_9.js | 2 +- search/functions_a.js | 6 +- search/functions_b.js | 2 +- search/functions_c.js | 2 +- search/functions_d.js | 10 +- search/related_1.js | 2 +- search/searchdata.js | 8 +- search/typedefs_0.js | 2 +- search/typedefs_1.js | 5 +- search/typedefs_2.js | 2 +- search/typedefs_5.js | 3 +- search/typedefs_8.js | 4 +- search/typedefs_9.js | 6 +- search/typedefs_a.js | 4 +- search/typedefs_b.js | 2 +- search/typedefs_c.js | 4 - search/variables_1.js | 2 +- sigh_8hpp_source.html | 4 +- snapshot_8hpp_source.html | 4 +- sparse__set_8hpp_source.html | 86 +-- structentt_1_1InsertionSort.html | 4 +- structentt_1_1Monostate-members.html | 83 +++ structentt_1_1Monostate.html | 197 +++++++ structentt_1_1StdSort-members.html | 2 +- structentt_1_1StdSort.html | 26 +- ...its_3_01std_1_1uint16__t_01_4-members.html | 11 +- ...ntt__traits_3_01std_1_1uint16__t_01_4.html | 4 + ...its_3_01std_1_1uint32__t_01_4-members.html | 11 +- ...ntt__traits_3_01std_1_1uint32__t_01_4.html | 10 +- ...its_3_01std_1_1uint64__t_01_4-members.html | 11 +- ...ntt__traits_3_01std_1_1uint64__t_01_4.html | 16 +- view_8hpp_source.html | 197 ++++--- 231 files changed, 3603 insertions(+), 1311 deletions(-) create mode 100644 classentt_1_1Identifier-members.html create mode 100644 classentt_1_1Identifier.html create mode 100644 classentt_1_1RuntimeView-members.html create mode 100644 classentt_1_1RuntimeView.html create mode 100644 entity_8hpp_source.html create mode 100644 inherit_graph_41.map create mode 100644 inherit_graph_41.md5 create mode 100644 inherit_graph_41.png create mode 100644 inherit_graph_42.map create mode 100644 inherit_graph_42.md5 create mode 100644 inherit_graph_42.png create mode 100644 inherit_graph_43.map create mode 100644 inherit_graph_43.md5 create mode 100644 inherit_graph_43.png create mode 100644 monostate_8hpp_source.html rename search/{typedefs_c.html => all_13.html} (94%) create mode 100644 search/all_13.js create mode 100644 search/classes_d.html create mode 100644 search/classes_d.js delete mode 100644 search/typedefs_c.js create mode 100644 structentt_1_1Monostate-members.html create mode 100644 structentt_1_1Monostate.html diff --git a/README_8md_source.html b/README_8md_source.html index 37914cd87..7d188c118 100644 --- a/README_8md_source.html +++ b/README_8md_source.html @@ -63,7 +63,7 @@ $(function() {
README.md
-
1 # EnTT Framework
2 
3 [![Build Status](https://travis-ci.org/skypjack/entt.svg?branch=master)](https://travis-ci.org/skypjack/entt)
4 [![Build status](https://ci.appveyor.com/api/projects/status/rvhaabjmghg715ck?svg=true)](https://ci.appveyor.com/project/skypjack/entt)
5 [![Coverage Status](https://coveralls.io/repos/github/skypjack/entt/badge.svg?branch=master)](https://coveralls.io/github/skypjack/entt?branch=master)
6 [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
7 
8 # Table of Contents
9 
10 * [Introduction](#introduction)
11 * [Build Instructions](#build-instructions)
12 * [Crash Course: entity-component system](#crash-course-entity-component-system)
13  * [Design choices](#design-choices)
14  * [A bitset-free entity-component system](#a-bitset-free-entity-component-system)
15  * [Pay per use](#pay-per-use)
16  * [Vademecum](#vademecum)
17  * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component)
18  * [Single instance components](#single-instance-components)
19  * [Observe changes](#observe-changes)
20  * [Who let the tags out?](#who-let-the-tags-out)
21  * [Runtime components](#runtime-components)
22  * [A journey through a plugin](#a-journey-through-a-plugin)
23  * [Sorting: is it possible?](#sorting-is-it-possible)
24  * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous)
25  * [Snapshot loader](#snapshot-loader)
26  * [Continuous loader](#continuous-loader)
27  * [Archives](#archives)
28  * [One example to rule them all](#one-example-to-rule-them-all)
29  * [Prototype](#prototype)
30  * [Helpers](#helpers)
31  * [Dependency function](#dependency-function)
32  * [View: to persist or not to persist?](#view-to-persist-or-not-to-persist)
33  * [Standard View](#standard-view)
34  * [Single component standard view](#single-component-standard-view)
35  * [Multi component standard view](#multi-component-standard-view)
36  * [Persistent View](#persistent-view)
37  * [Raw View](#raw-view)
38  * [Give me everything](#give-me-everything)
39  * [Side notes](#side-notes)
40 * [Crash Course: core functionalities](#crash-course-core-functionalities)
41  * [Compile-time identifiers](#compile-time-identifiers)
42  * [Runtime identifiers](#runtime-identifiers)
43  * [Hashed strings](#hashed-strings)
44 * [Crash Course: service locator](#crash-course-service-locator)
45 * [Crash Course: cooperative scheduler](#crash-course-cooperative-scheduler)
46  * [The process](#the-process)
47  * [The scheduler](#the-scheduler)
48 * [Crash Course: resource management](#crash-course-resource-management)
49  * [The resource, the loader and the cache](#the-resource-the-loader-and-the-cache)
50 * [Crash Course: events, signals and everything in between](#crash-course-events-signals-and-everything-in-between)
51  * [Signals](#signals)
52  * [Delegate](#delegate)
53  * [Event dispatcher](#event-dispatcher)
54  * [Event emitter](#event-emitter)
55 * [Packaging Tools](#packaging-tools)
56 * [EnTT in Action](#entt-in-action)
57 * [License](#license)
58 * [Support](#support)
59  * [Donation](#donation)
60  * [Hire me](#hire-me)
61 
62 # Introduction
63 
64 `EnTT` is a header-only, tiny and easy to use framework written in modern
65 C++.<br/>
66 It was originally designed entirely around an architectural pattern called _ECS_
67 that is used mostly in game development. For further details:
68 
69 * [Entity Systems Wiki](http://entity-systems.wikidot.com/)
70 * [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/)
71 * [ECS on Wikipedia](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system)
72 
73 A long time ago, the sole entity-component system was part of the project. After
74 a while the codebase has grown and more and more classes have become part of the
75 repository.<br/>
76 That's why today it's called _the EnTT Framework_.
77 
78 Currently, `EnTT` is tested on Linux, Microsoft Windows and OS X. It has proven
79 to work also on both Android and iOS.<br/>
80 Most likely it will not be problematic on other systems as well, but has not
81 been sufficiently tested so far.
82 
83 ## The framework
84 
85 `EnTT` was written initially as a faster alternative to other well known and
86 open source entity-component systems. Nowadays the `EnTT` framework is moving
87 its first steps. Much more will come in the future and hopefully I'm going to
88 work on it for a long time.<br/>
89 Requests for feature, PR, suggestions ad feedback are highly appreciated.
90 
91 If you find you can help me and want to contribute to the `EnTT` framework with
92 your experience or you do want to get part of the project for some other
93 reasons, feel free to contact me directly (you can find the mail in the
94 [profile](https://github.com/skypjack)).<br/>
95 I can't promise that each and every contribution will be accepted, but I can
96 assure that I'll do my best to take them all seriously.
97 
98 ### State of the art
99 
100 Here is a brief list of what it offers today:
101 
102 * Statically generated integer identifiers for types (assigned either at
103  compile-time or at runtime).
104 * A constexpr utility for human readable resource identifiers.
105 * An incredibly fast entity-component system based on sparse sets, with its own
106  views and a _pay for what you use_ policy to adjust performance and memory
107  usage according to users' requirements.
108 * Actor class for those who aren't confident with entity-component systems.
109 * The smallest and most basic implementation of a service locator ever seen.
110 * A cooperative scheduler for processes of any type.
111 * All what is needed for resource management (cache, loaders, handles).
112 * Delegates, signal handlers (with built-in support for collectors) and a tiny
113  event dispatcher.
114 * A general purpose event emitter, that is a CRTP idiom based class template.
115 * An event dispatcher for immediate and delayed events to integrate in loops.
116 * ...
117 * Any other business.
118 
119 Consider it a work in progress. For more details and an updated list, please
120 refer to the [online documentation](https://skypjack.github.io/entt/). It
121 probably contains much more. Moreover, the whole API is fully documented in-code
122 for those who are brave enough to read it.<br/>
123 Continue reading to know how the different parts of the project work or follow
124 the link above to take a look at the API reference.
125 
126 ## Code Example
127 
128 ```cpp
129 #include <entt/entt.hpp>
130 #include <cstdint>
131 
132 struct Position {
133  float x;
134  float y;
135 };
136 
137 struct Velocity {
138  float dx;
139  float dy;
140 };
141 
142 void update(entt::DefaultRegistry &registry) {
143  auto view = registry.view<Position, Velocity>();
144 
145  for(auto entity: view) {
146  // gets only the components that are going to be used ...
147 
148  auto &velocity = view.get<Velocity>(entity);
149 
150  velocity.dx = 0.;
151  velocity.dy = 0.;
152 
153  // ...
154  }
155 }
156 
157 void update(std::uint64_t dt, entt::DefaultRegistry &registry) {
158  registry.view<Position, Velocity>().each([dt](auto entity, auto &position, auto &velocity) {
159  // gets all the components of the view at once ...
160 
161  position.x += velocity.dx * dt;
162  position.y += velocity.dy * dt;
163 
164  // ...
165  });
166 }
167 
168 int main() {
169  entt::DefaultRegistry registry;
170  std::uint64_t dt = 16;
171 
172  for(auto i = 0; i < 10; ++i) {
173  auto entity = registry.create();
174  registry.assign<Position>(entity, i * 1.f, i * 1.f);
175  if(i % 2 == 0) { registry.assign<Velocity>(entity, i * .1f, i * .1f); }
176  }
177 
178  update(dt, registry);
179  update(registry);
180 
181  // ...
182 }
183 ```
184 
185 ## Motivation
186 
187 I started working on `EnTT` because of the wrong reason: my goal was to design
188 an entity-component system that beated another well known open source solution
189 in terms of performance and used (possibly) less memory in the average
190 case.<br/>
191 In the end, I did it, but it wasn't much satisfying. Actually it wasn't
192 satisfying at all. The fastest and nothing more, fairly little indeed. When I
193 realized it, I tried hard to keep intact the great performance of `EnTT` and to
194 add all the features I wanted to see in *my own library* at the same time.
195 
196 Today `EnTT` is finally what I was looking for: still faster than its
197 _competitors_, lower memory usage in the average case, a really good API and an
198 amazing set of features. And even more, of course.
199 
200 ## Performance
201 
202 As it stands right now, `EnTT` is just fast enough for my requirements if
203 compared to my first choice (it was already amazingly fast actually).<br/>
204 Below is a comparison between the two (both of them compiled with GCC 7.3.0 on a
205 Dell XPS 13 out of the mid 2014):
206 
207 | Benchmark | EntityX (compile-time) | EnTT |
208 |-----------|-------------|-------------|
209 | Create 1M entities | 0.0147s | **0.0046s** |
210 | Destroy 1M entities | 0.0053s | **0.0045s** |
211 | Standard view, 1M entities, one component | 0.0012s | **1.9e-07s** |
212 | Standard view, 1M entities, two components | 0.0012s | **3.8e-07s** |
213 | Standard view, 1M entities, two components<br/>Half of the entities have all the components | 0.0009s | **3.8e-07s** |
214 | Standard view, 1M entities, two components<br/>One of the entities has all the components | 0.0008s | **1.0e-06s** |
215 | Persistent view, 1M entities, two components | 0.0012s | **2.8e-07s** |
216 | Standard view, 1M entities, five components | 0.0010s | **7.0e-07s** |
217 | Persistent view, 1M entities, five components | 0.0010s | **2.8e-07s** |
218 | Standard view, 1M entities, ten components | 0.0011s | **1.2e-06s** |
219 | Standard view, 1M entities, ten components<br/>Half of the entities have all the components | 0.0010s | **1.2e-06s** |
220 | Standard view, 1M entities, ten components<br/>One of the entities has all the components | 0.0008s | **1.2e-06s** |
221 | Persistent view, 1M entities, ten components | 0.0011s | **3.0e-07s** |
222 | Raw view, 1M entities | - | **2.2e-07s** |
223 | Sort 150k entities, one component<br/>Arrays are in reverse order | - | **0.0036s** |
224 | Sort 150k entities, enforce permutation<br/>Arrays are in reverse order | - | **0.0005s** |
225 | Sort 150k entities, one component<br/>Arrays are almost sorted, std::sort | - | **0.0035s** |
226 | Sort 150k entities, one component<br/>Arrays are almost sorted, insertion sort | - | **0.0007s** |
227 
228 Note: The default version of `EntityX` (`master` branch) wasn't added to the
229 comparison because it's already much slower than its compile-time counterpart.
230 
231 Pretty interesting, aren't them? In fact, these benchmarks are the same used by
232 `EntityX` to show _how fast it is_. To be honest, they aren't so good and these
233 results shouldn't be taken much seriously (they are completely unrealistic
234 indeed).<br/>
235 The proposed entity-component system is incredibly fast to iterate entities,
236 this is a fact. The compiler can make a lot of optimizations because of how
237 `EnTT` works, even more when components aren't used at all. This is exactly the
238 case for these benchmarks. On the other hand and if we consider real world
239 cases, `EnTT` is in the middle between a bit and much faster than the other
240 solutions around when users also access the components and not just the
241 entities, although it is not as fast as reported by these benchmarks.<br/>
242 This is why they are completely wrong and cannot be used to evaluate any of the
243 entity-component systems.
244 
245 If you decide to use `EnTT`, choose it because of its API, features and
246 performance, not because there is a benchmark somewhere that makes it seem the
247 fastest.
248 
249 Probably I'll try to get out of `EnTT` more features and even better performance
250 in the future, mainly for fun.<br/>
251 If you want to contribute and/or have any suggestion, feel free to make a PR or
252 open an issue to discuss your idea.
253 
254 # Build Instructions
255 
256 ## Requirements
257 
258 To be able to use `EnTT`, users must provide a full-featured compiler that
259 supports at least C++14.<br/>
260 The requirements below are mandatory to compile the tests and to extract the
261 documentation:
262 
263 * CMake version 3.2 or later.
264 * Doxygen version 1.8 or later.
265 
266 ## Library
267 
268 `EnTT` is a header-only library. This means that including the `entt.hpp`
269 header is enough to include the whole framework and use it. For those who are
270 interested only in the entity-component system, consider to include the sole
271 `entity/registry.hpp` header instead.<br/>
272 It's a matter of adding the following line to the top of a file:
273 
274 ```cpp
275 #include <entt/entt.hpp>
276 ```
277 
278 Use the line below to include only the entity-component system instead:
279 
280 ```cpp
281 #include <entt/entity/registry.hpp>
282 ```
283 
284 Then pass the proper `-I` argument to the compiler to add the `src` directory to
285 the include paths.
286 
287 ## Documentation
288 
289 The documentation is based on [doxygen](http://www.stack.nl/~dimitri/doxygen/).
290 To build it:
291 
292  $ cd build
293  $ cmake ..
294  $ make docs
295 
296 The API reference will be created in HTML format within the directory
297 `build/docs/html`. To navigate it with your favorite browser:
298 
299  $ cd build
300  $ your_favorite_browser docs/html/index.html
301 
302 The API reference is also available [online](https://skypjack.github.io/entt/)
303 for the latest version.
304 
305 ## Tests
306 
307 To compile and run the tests, `EnTT` requires *googletest*.<br/>
308 `cmake` will download and compile the library before to compile anything else.
309 
310 To build the most basic set of tests:
311 
312 * `$ cd build`
313 * `$ cmake ..`
314 * `$ make`
315 * `$ make test`
316 
317 Note that benchmarks are not part of this set.
318 
319 # Crash Course: entity-component system
320 
321 ## Design choices
322 
323 ### A bitset-free entity-component system
324 
325 `EnTT` is a _bitset-free_ entity-component system that doesn't require users to
326 specify the component set at compile-time.<br/>
327 This is why users can instantiate the core class simply like:
328 
329 ```cpp
330 entt::DefaultRegistry registry;
331 ```
332 
333 In place of its more annoying and error-prone counterpart:
334 
335 ```cpp
336 entt::DefaultRegistry<Comp0, Comp1, ..., CompN> registry;
337 ```
338 
339 ### Pay per use
340 
341 `EnTT` is entirely designed around the principle that users have to pay only for
342 what they want.
343 
344 When it comes to using an entity-component system, the tradeoff is usually
345 between performance and memory usage. The faster it is, the more memory it uses.
346 However, slightly worse performance along non-critical paths are the right price
347 to pay to reduce memory usage and I've always wondered why this kind of tools do
348 not leave me the choice.<br/>
349 `EnTT` follows a completely different approach. It squeezes the best from the
350 basic data structures and gives users the possibility to pay more for higher
351 performance where needed.<br/>
352 The disadvantage of this approach is that users need to know the systems they
353 are working on and the tools they are using. Otherwise, the risk to ruin the
354 performance along critical paths is high.
355 
356 So far, this choice has proven to be a good one and I really hope it can be for
357 many others besides me.
358 
359 ## Vademecum
360 
361 The `Registry` to store, the views to iterate. That's all.
362 
363 An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
364 use as-is and store around if needed. Do not try to inspect an entity
365 identifier, its format can change in future and a registry offers all the
366 functionalities to query them out-of-the-box. The underlying type of an entity
367 (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
368 when defining a registry (actually the `DefaultRegistry` is nothing more than a
369 `Registry` where the type of the entities is `std::uint32_t`).<br/>
370 Components (the _C_ of an _ECS_) should be plain old data structures or more
371 complex and movable data structures with a proper constructor. Actually, the
372 sole requirement of a component type is that it must be both move constructible
373 and move assignable. They are list initialized by using the parameters provided
374 to construct the component itself. No need to register components or their types
375 neither with the registry nor with the entity-component system at all.<br/>
376 Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
377 whatever users want. They can accept a `Registry` or a view of any type and use
378 them the way they prefer. No need to register systems or their types neither
379 with the registry nor with the entity-component system at all.
380 
381 The following sections will explain in short how to use the entity-component
382 system, the core part of the whole framework.<br/>
383 In fact, the framework is composed of many other classes in addition to those
384 describe below. For more details, please refer to the inline documentation.
385 
386 ## The Registry, the Entity and the Component
387 
388 A registry can store and manage entities, as well as create views to iterate the
389 underlying data structures.<br/>
390 `Registry` is a class template that lets users decide what's the preferred type
391 to represent an entity. Because `std::uint32_t` is large enough for almost all
392 the cases, there exists also an alias named `DefaultRegistry` for
393 `Registry<std::uint32_t>`.
394 
395 Entities are represented by _entity identifiers_. An entity identifier is an
396 opaque type that users should not inspect or modify in any way. It carries
397 information about the entity itself and its version.
398 
399 A registry can be used both to construct and destroy entities:
400 
401 ```cpp
402 // constructs a naked entity with no components and returns its identifier
403 auto entity = registry.create();
404 
405 // destroys an entity and all its components
406 registry.destroy(entity);
407 ```
408 
409 When an entity is destroyed, the registry can freely reuse it internally with a
410 slightly different identifier. In particular, the version of an entity is
411 increased each and every time it's discarded.<br/>
412 In case entity identifiers are stored around, the registry offers all the
413 functionalities required to test them and get out of the them all the
414 information they carry:
415 
416 ```cpp
417 // returns true if the entity is still valid, false otherwise
418 bool b = registry.valid(entity);
419 
420 // gets the version contained in the entity identifier
421 auto version = registry.version(entity);
422 
423 // gets the actual version for the given entity
424 auto curr = registry.current(entity);
425 ```
426 
427 Finally, there is also a sort of _null identifier_ made available to users. It's
428 treated as if it were a _null pointer_ that doesn't identify any entity. A
429 registry will reject this identifier in all cases because it isn't considered
430 valid.<br/>
431 The rules that define a _null identifier_ are a bit tricky to explain. However,
432 being `Entity` the type of the entities (for example, `std::uint32_t`), users
433 can easily construct a _null identifier_ by flipping all the bits of the _zero_:
434 
435 ```cpp
436 using Entity = std::uint32_t;
437 const auto null = ~Entity{};
438 ```
439 
440 Components can be assigned to or removed from entities at any time with a few
441 calls to member functions of the registry. As for the entities, the registry
442 offers also a set of functionalities users can use to work with the components.
443 
444 The `assign` member function template creates, initializes and assigns to an
445 entity the given component. It accepts a variable number of arguments to
446 construct the component itself if present:
447 
448 ```cpp
449 registry.assign<Position>(entity, 0., 0.);
450 
451 // ...
452 
453 Velocity &velocity = registry.assign<Velocity>(entity);
454 velocity.dx = 0.;
455 velocity.dy = 0.;
456 ```
457 
458 If an entity already has the given component, the `replace` member function
459 template can be used to replace it:
460 
461 ```cpp
462 registry.replace<Position>(entity, 0., 0.);
463 
464 // ...
465 
466 Velocity &velocity = registry.replace<Velocity>(entity);
467 velocity.dx = 0.;
468 velocity.dy = 0.;
469 ```
470 
471 In case users want to assign a component to an entity, but it's unknown whether
472 the entity already has it or not, `accommodate` does the work in a single call
473 (there is a performance penalty to pay for this mainly due to the fact that it
474 has to check if the entity already has the given component or not):
475 
476 ```cpp
477 registry.accommodate<Position>(entity, 0., 0.);
478 
479 // ...
480 
481 Velocity &velocity = registry.accommodate<Velocity>(entity);
482 velocity.dx = 0.;
483 velocity.dy = 0.;
484 ```
485 
486 Note that `accommodate` is a slightly faster alternative for the following
487 `if/else` statement and nothing more:
488 
489 ```cpp
490 if(registry.has<Comp>(entity)) {
491  registry.replace<Comp>(entity, arg1, argN);
492 } else {
493  registry.assign<Comp>(entity, arg1, argN);
494 }
495 ```
496 
497 As already shown, if in doubt about whether or not an entity has one or more
498 components, the `has` member function template may be useful:
499 
500 ```cpp
501 bool b = registry.has<Position, Velocity>(entity);
502 ```
503 
504 On the other side, if the goal is to delete a single component, the `remove`
505 member function template is the way to go when it's certain that the entity owns
506 a copy of the component:
507 
508 ```cpp
509 registry.remove<Position>(entity);
510 ```
511 
512 Otherwise consider to use the `reset` member function. It behaves similarly to
513 `remove` but with a strictly defined behavior (and a performance penalty is the
514 price to pay for this). In particular it removes the component if and only if it
515 exists, otherwise it returns safely to the caller:
516 
517 ```cpp
518 registry.reset<Position>(entity);
519 ```
520 
521 There exist also two other _versions_ of the `reset` member function:
522 
523 * If no entity is passed to it, `reset` will remove the given component from
524  each entity that has it:
525 
526  ```cpp
527  registry.reset<Position>();
528  ```
529 
530 * If neither the entity nor the component are specified, all the entities still
531  in use and their components are destroyed:
532 
533  ```cpp
534  registry.reset();
535  ```
536 
537 Finally, references to components can be retrieved simply by doing this:
538 
539 ```cpp
540 const auto &cregistry = registry;
541 
542 // const and non-const reference
543 const Position &position = cregistry.get<Position>(entity);
544 Position &position = registry.get<Position>(entity);
545 
546 // const and non-const references
547 std::tuple<const Position &, const Velocity &> tup = cregistry.get<Position, Velocity>(entity);
548 std::tuple<Position &, Velocity &> tup = registry.get<Position, Velocity>(entity);
549 ```
550 
551 The `get` member function template gives direct access to the component of an
552 entity stored in the underlying data structures of the registry.
553 
554 ### Single instance components
555 
556 In those cases where all what is needed is a single instance component, tags are
557 the right tool to achieve the purpose.<br/>
558 Tags undergo the same requirements of components. They can be either plain old
559 data structures or more complex and movable data structures with a proper
560 constructor.<br/>
561 Actually, the same type can be used both as a tag and as a component and the
562 registry will not complain about it. It is up to users to properly manage their
563 own types. In some cases, the tag `tag_t` must also be used in order to
564 disambiguate overloads of member functions.
565 
566 Attaching tags to entities and removing them is trivial:
567 
568 ```cpp
569 auto player = registry.create();
570 auto camera = registry.create();
571 
572 // attaches a default-initialized tag to an entity
573 registry.assign<PlayingCharacter>(entt::tag_t{}, player);
574 
575 // attaches a tag to an entity and initializes it
576 registry.assign<Camera>(entt::tag_t{}, camera, player);
577 
578 // removes tags from their owners
579 registry.remove<PlayingCharacter>();
580 registry.remove<Camera>();
581 ```
582 
583 In case a tag already has an owner, its content can be updated by means of the
584 `replace` member function template and the ownership of the tag can be
585 transferred to another entity using the `move` member function template:
586 
587 ```
588 // replaces the content of the given tag
589 Point &point = registry.replace<Point>(entt::tag_t{}, 1.f, 1.f);
590 
591 // transfers the ownership of the tag to another entity
592 entity_type prev = registry.move<Point>(next);
593 ```
594 
595 If in doubt about whether or not a tag already has an owner, the `has` member
596 function template may be useful:
597 
598 ```cpp
599 bool b = registry.has<PlayingCharacter>();
600 ```
601 
602 References to tags can be retrieved simply by doing this:
603 
604 ```cpp
605 const auto &cregistry = registry;
606 
607 // either a non-const reference ...
608 PlayingCharacter &player = registry.get<PlayingCharacter>();
609 
610 // ... or a const one
611 const Camera &camera = cregistry.get<Camera>();
612 ```
613 
614 The `get` member function template gives direct access to the tag as stored in
615 the underlying data structures of the registry.
616 
617 As shown above, in almost all the cases the entity identifier isn't required.
618 Since a single instance component can have only one associated entity, it
619 doesn't make much sense to mention it explicitly.<br/>
620 To find out who the owner is, just do the following:
621 
622 ```cpp
623 auto player = registry.attachee<PlayingCharacter>();
624 ```
625 
626 Note that iterating tags isn't possible for obvious reasons. Tags give direct
627 access to single entities and nothing more.
628 
629 ### Observe changes
630 
631 Because of how the registry works internally, it stores a couple of signal
632 handlers for each pool in order to notify some of its data structures on the
633 construction and destruction of components.<br/>
634 These signal handlers are also exposed and made available to users. This is the
635 basic brick to build fancy things like dependencies and reactive systems.
636 
637 To get a sink to be used to connect and disconnect listeners so as to be
638 notified on the creation of a component, use the `construction` member function:
639 
640 ```cpp
641 // connects a free function
642 registry.construction<Position>().connect<&MyFreeFunction>();
643 
644 // connects a member function
645 registry.construction<Position>().connect<MyClass, &MyClass::member>(&instance);
646 
647 // disconnects a free function
648 registry.construction<Position>().disconnect<&MyFreeFunction>();
649 
650 // disconnects a member function
651 registry.construction<Position>().disconnect<MyClass, &MyClass::member>(&instance);
652 ```
653 
654 To be notified when components are destroyed, use the `destruction` member
655 function instead.
656 
657 The function type of a listener is the same in both cases:
658 
659 ```cpp
660 void(Registry<Entity> &, Entity);
661 ```
662 
663 In other terms, a listener is provided with the registry that triggered the
664 notification and the entity affected by the change. Note also that:
665 
666 * Listeners are invoked **after** components have been assigned to entities.
667 * Listeners are invoked **before** components have been removed from entities.
668 * The order of invocation of the listeners isn't guaranteed in any case.
669 
670 There are also some limitations on what a listener can and cannot do. In
671 particular:
672 
673 * Connecting and disconnecting other functions from within the body of a
674  listener should be avoided. It can lead to undefined behavior in some cases.
675 * Assigning and removing components and tags from within the body of a listener
676  that observes the destruction of instances of a given type should be avoided.
677  It can lead to undefined behavior in some cases. This type of listeners is
678  intended to provide users with an easy way to perform cleanup and nothing
679  more.
680 
681 To a certain extent, these limitations do not apply. However, it is risky to try
682 to force them and users should respect the limitations unless they know exactly
683 what they are doing. Subtle bugs are the price to pay in case of errors
684 otherwise.
685 
686 In general, events and therefore listeners must not be used as replacements for
687 systems. They should not contain much logic and interactions with a registry
688 should be kept to a minimum, if possible. Note also that the greater the number
689 of listeners, the greater the performance hit when components are created or
690 destroyed.
691 
692 #### Who let the tags out?
693 
694 As an extension, signals are also provided with tags. Although they are not
695 strictly required internally, it makes sense that a user expects signal support
696 even when it comes to tags actually.<br/>
697 Signals for tags undergo exactly the same requirements of those introduced for
698 components. Also the function type for a listener is the same and it's invoked
699 with the same guarantees discussed above.
700 
701 To get the sinks for a tag just use tag `tag_t` to disambiguate overloads of
702 member functions as in the following example:
703 
704 ```cpp
705 registry.construction<MyTag>(entt::tag_t{}).connect<&MyFreeFunction>();
706 registry.destruction<MyTag>(entt::tag_t{}).connect<MyClass, &MyClass::member>(&instance);
707 ```
708 
709 Listeners for tags and components are managed separately and do not influence
710 each other in any case. Therefore, note that the greater the number of listeners
711 for a type, the greater the performance hit when a tag of the given type is
712 created or destroyed.
713 
714 ### Runtime components
715 
716 Defining components at runtime is useful to support plugins and mods in general.
717 However, it seems impossible with a tool designed around a bunch of templates.
718 Indeed it's not that difficult.<br/>
719 Of course, some features cannot be easily exported into a runtime
720 environment. As an example, sorting a group of components defined at runtime
721 isn't for free if compared to most of the other operations. However, the basic
722 functionalities of an entity-component system such as `EnTT` fit the problem
723 perfectly and can also be used to manage runtime components if required.<br/>
724 All that is necessary to do it is to know the identifiers of the components. An
725 identifier is nothing more than a number or similar that can be used at runtime
726 to work with the type system.
727 
728 In `EnTT`, identifiers are easily accessible:
729 
730 ```cpp
731 entt::DefaultRegistry registry;
732 
733 // standard component identifier
734 auto ctype = registry.component<Position>();
735 
736 // single instance component identifier
737 auto ttype = registry.tag<PlayingCharacter>();
738 ```
739 
740 Once the identifiers are made available, almost everything becomes pretty
741 simple.
742 
743 #### A journey through a plugin
744 
745 `EnTT` comes with an example (actually a test) that shows how to integrate
746 compile-time and runtime components in a stack based JavaScript environment. It
747 uses [`Duktape`](https://github.com/svaarala/duktape) under the hood, mainly
748 because I wanted to learn how it works at the time I was writing the code.
749 
750 The code is not production-ready and overall performance can be highly improved.
751 However, I sacrificed optimizations in favor of a more readable piece of code. I
752 hope I succeeded.<br/>
753 Note also that this isn't neither the only nor (probably) the best way to do it.
754 In fact, the right way depends on the scripting language and the problem one is
755 facing in general.<br/>
756 That being said, feel free to use it at your own risk.
757 
758 The basic idea is that of creating a compile-time component aimed to map all the
759 runtime components assigned to an entity.<br/>
760 Identifiers come in use to address the right function from a map when invoked
761 from the runtime environment and to filter entities when iterating.<br/>
762 With a bit of gymnastic, one can narrow views and improve the performance to
763 some extent but it was not the goal of the example.
764 
765 ### Sorting: is it possible?
766 
767 It goes without saying that sorting entities and components is possible with
768 `EnTT`.<br/>
769 In fact, there are two functions that respond to slightly different needs:
770 
771 * Components can be sorted directly:
772 
773  ```cpp
774  registry.sort<Renderable>([](const auto &lhs, const auto &rhs) {
775  return lhs.z < rhs.z;
776 
777  });
778  ```
779 
780  There exists also the possibility to use a custom sort function object, as
781  long as it adheres to the requirements described in the inline
782  documentation.<br/>
783  This is possible mainly because users can get much more with a custom sort
784  function object if the pattern of usage is known. As an example, in case of an
785  almost sorted pool, quick sort could be much, much slower than insertion sort.
786 
787 * Components can be sorted according to the order imposed by another component:
788 
789  ```cpp
790  registry.sort<Movement, Physics>();
791  ```
792 
793  In this case, instances of `Movement` are arranged in memory so that cache
794  misses are minimized when the two components are iterated together.
795 
796 ### Snapshot: complete vs continuous
797 
798 The `Registry` class offers basic support to serialization.<br/>
799 It doesn't convert components and tags to bytes directly, there wasn't the need
800 of another tool for serialization out there. Instead, it accepts an opaque
801 object with a suitable interface (namely an _archive_) to serialize its internal
802 data structures and restore them later. The way types and instances are
803 converted to a bunch of bytes is completely in charge to the archive and thus to
804 final users.
805 
806 The goal of the serialization part is to allow users to make both a dump of the
807 entire registry or a narrower snapshot, that is to select only the components
808 and the tags in which they are interested.<br/>
809 Intuitively, the use cases are different. As an example, the first approach is
810 suitable for local save/restore functionalities while the latter is suitable for
811 creating client-server applications and for transferring somehow parts of the
812 representation side to side.
813 
814 To take a snapshot of the registry, use the `snapshot` member function. It
815 returns a temporary object properly initialized to _save_ the whole registry or
816 parts of it.
817 
818 Example of use:
819 
820 ```cpp
821 OutputArchive output;
822 
823 registry.snapshot()
824  .entities(output)
825  .destroyed(output)
826  .component<AComponent, AnotherComponent>(output)
827  .tag<MyTag>(output);
828 ```
829 
830 It isn't necessary to invoke all these functions each and every time. What
831 functions to use in which case mostly depends on the goal and there is not a
832 golden rule to do that.
833 
834 The `entities` member function asks the registry to serialize all the entities
835 that are still in use along with their versions. On the other side, the
836 `destroyed` member function tells to the registry to serialize the entities that
837 have been destroyed and are no longer in use.<br/>
838 These two functions can be used to save and restore the whole set of entities
839 with the versions they had during serialization.
840 
841 The `component` member function is a function template the aim of which is to
842 store aside components. The presence of a template parameter list is a
843 consequence of a couple of design choices from the past and in the present:
844 
845 * First of all, there is no reason to force a user to serialize all the
846  components at once and most of the times it isn't desiderable. As an example,
847  in case the stuff for the HUD in a game is put into the registry for some
848  reasons, its components can be freely discarded during a serialization step
849  because probably the software already knows how to reconstruct the HUD
850  correctly from scratch.
851 
852 * Furthermore, the registry makes heavy use of _type-erasure_ techniques
853  internally and doesn't know at any time what types of components it contains.
854  Therefore being explicit at the call point is mandatory.
855 
856 There exists also another version of the `component` member function that
857 accepts a range of entities to serialize. This version is a bit slower than the
858 other one, mainly because it iterates the range of entities more than once for
859 internal purposes. However, it can be used to filter out those entities that
860 shouldn't be serialized for some reasons.<br/>
861 As an example:
862 
863 ```cpp
864 const auto view = registry.view<Serialize>();
865 OutputArchive output;
866 
867 registry.snapshot()
868  .component<AComponent, AnotherComponent>(output, view.cbegin(), view.cend());
869 ```
870 
871 The `tag` member function is similar to the previous one, apart from the fact
872 that it works with tags and not with components.<br/>
873 Note also that both `component` and `tag` store items along with entities. It
874 means that they work properly without a call to the `entities` member function.
875 
876 Once a snapshot is created, there exist mainly two _ways_ to load it: as a whole
877 and in a kind of _continuous mode_.<br/>
878 The following sections describe both loaders and archives in details.
879 
880 #### Snapshot loader
881 
882 A snapshot loader requires that the destination registry be empty and loads all
883 the data at once while keeping intact the identifiers that the entities
884 originally had.<br/>
885 To do that, the registry offers a member function named `restore` that returns a
886 temporary object properly initialized to _restore_ a snapshot.
887 
888 Example of use:
889 
890 ```cpp
891 InputArchive input;
892 
893 registry.restore()
894  .entities(input)
895  .destroyed(input)
896  .component<AComponent, AnotherComponent>(input)
897  .tag<MyTag>(input)
898  .orphans();
899 ```
900 
901 It isn't necessary to invoke all these functions each and every time. What
902 functions to use in which case mostly depends on the goal and there is not a
903 golden rule to do that. For obvious reasons, what is important is that the data
904 are restored in exactly the same order in which they were serialized.
905 
906 The `entities` and `destroyed` member functions restore the sets of entities and
907 the versions that the entities originally had at the source.
908 
909 The `component` member function restores all and only the components specified
910 and assigns them to the right entities. Note that the template parameter list
911 must be exactly the same used during the serialization. The same applies to the
912 `tag` member function.
913 
914 The `orphans` member function literally destroys those entities that have
915 neither components nor tags. It's usually useless if the snapshot is a full dump
916 of the source. However, in case all the entities are serialized but only few
917 components and tags are saved, it could happen that some of the entities have
918 neither components nor tags once restored. The best users can do to deal with
919 them is to destroy those entities and thus update their versions.
920 
921 #### Continuous loader
922 
923 A continuous loader is designed to load data from a source registry to a
924 (possibly) non-empty destination. The loader can accommodate in a registry more
925 than one snapshot in a sort of _continuous loading_ that updates the
926 destination one step at a time.<br/>
927 Identifiers that entities originally had are not transferred to the target.
928 Instead, the loader maps remote identifiers to local ones while restoring a
929 snapshot. Because of that, this kind of loader offers a way to update
930 automatically identifiers that are part of components or tags (as an example, as
931 data members or gathered in a container).<br/>
932 Another difference with the snapshot loader is that the continuous loader does
933 not need to work with the private data structures of a registry. Furthermore, it
934 has an internal state that must persist over time. Therefore, there is no reason
935 to create it by means of a registry, or to limit its lifetime to that of a
936 temporary object.
937 
938 Example of use:
939 
940 ```cpp
941 entt::ContinuousLoader<entity_type> loader{registry};
942 InputArchive input;
943 
944 loader.entities(input)
945  .destroyed(input)
946  .component<AComponent, AnotherComponent, DirtyComponent>(input, &DirtyComponent::parent, &DirtyComponent::child)
947  .tag<MyTag, DirtyTag>(input, &DirtyTag::container)
948  .orphans()
949  .shrink();
950 ```
951 
952 It isn't necessary to invoke all these functions each and every time. What
953 functions to use in which case mostly depends on the goal and there is not a
954 golden rule to do that. For obvious reasons, what is important is that the data
955 are restored in exactly the same order in which they were serialized.
956 
957 The `entities` and `destroyed` member functions restore groups of entities and
958 map each entity to a local counterpart when required. In other terms, for each
959 remote entity identifier not yet registered by the loader, the latter creates a
960 local identifier so that it can keep the local entity in sync with the remote
961 one.
962 
963 The `component` and `tag` member functions restore all and only the components
964 and the tags specified and assign them to the right entities.<br/>
965 In case the component or the tag contains entities itself (either as data
966 members of type `entity_type` or as containers of entities), the loader can
967 update them automatically. To do that, it's enough to specify the data members
968 to update as shown in the example.
969 
970 The `orphans` member function literally destroys those entities that have
971 neither components nor tags after a restore. It has exactly the same purpose
972 described in the previous section and works the same way.
973 
974 Finally, `shrink` helps to purge local entities that no longer have a remote
975 conterpart. Users should invoke this member function after restoring each
976 snapshot, unless they know exactly what they are doing.
977 
978 #### Archives
979 
980 Archives must publicly expose a predefined set of member functions. The API is
981 straightforward and consists only of a group of function call operators that
982 are invoked by the snapshot class and the loaders.
983 
984 In particular:
985 
986 * An output archive, the one used when creating a snapshot, must expose a
987  function call operator with the following signature to store entities:
988 
989  ```cpp
990  void operator()(Entity);
991  ```
992 
993  Where `Entity` is the type of the entities used by the registry. Note that all
994  the member functions of the snapshot class make also an initial call to this
995  endpoint to save the _size_ of the set they are going to store.<br/>
996  In addition, an archive must accept a pair of entity and either component or
997  tag for each type to be serialized. Therefore, given a type `T`, the archive
998  must contain a function call operator with the following signature:
999 
1000  ```cpp
1001  void operator()(Entity, const T &);
1002  ```
1003 
1004  The output archive can freely decide how to serialize the data. The register
1005  is not affected at all by the decision.
1006 
1007 * An input archive, the one used when restoring a snapshot, must expose a
1008  function call operator with the following signature to load entities:
1009 
1010  ```cpp
1011  void operator()(Entity &);
1012  ```
1013 
1014  Where `Entity` is the type of the entities used by the registry. Each time the
1015  function is invoked, the archive must read the next element from the
1016  underlying storage and copy it in the given variable. Note that all the member
1017  functions of a loader class make also an initial call to this endpoint to read
1018  the _size_ of the set they are going to load.<br/>
1019  In addition, the archive must accept a pair of entity and either component or
1020  tag for each type to be restored. Therefore, given a type `T`, the archive
1021  must contain a function call operator with the following signature:
1022 
1023  ```cpp
1024  void operator()(Entity &, T &);
1025  ```
1026 
1027  Every time such an operator is invoked, the archive must read the next
1028  elements from the underlying storage and copy them in the given variables.
1029 
1030 #### One example to rule them all
1031 
1032 `EnTT` comes with some examples (actually some tests) that show how to integrate
1033 a well known library for serialization as an archive. It uses
1034 [`Cereal C++`](https://uscilab.github.io/cereal/) under the hood, mainly
1035 because I wanted to learn how it works at the time I was writing the code.
1036 
1037 The code is not production-ready and it isn't neither the only nor (probably)
1038 the best way to do it. However, feel free to use it at your own risk.
1039 
1040 The basic idea is to store everything in a group of queues in memory, then bring
1041 everything back to the registry with different loaders.
1042 
1043 ### Prototype
1044 
1045 A prototype defines a type of an application in terms of its parts. They can be
1046 used to assign components to entities of a registry at once.<br/>
1047 Roughly speaking, in most cases prototypes can be considered just as templates
1048 to use to initialize entities according to _concepts_. In fact, users can create
1049 how many prototypes they want, each one initialized differently from the others.
1050 
1051 The following is an example of use of a prototype:
1052 
1053 ```cpp
1054 entt::DefaultRegistry registry;
1055 entt::DefaultPrototype prototype{registry};
1056 
1057 prototype.set<Position>(100.f, 100.f);
1058 prototype.set<Velocity>(0.f, 0.f);
1059 
1060 // ...
1061 
1062 const auto entity = prototype();
1063 ```
1064 
1065 To assign and remove components from a prototype, it offers two dedicated member
1066 functions named `set` and `unset`. The `has` member function can be used to know
1067 if a given prototype contains one or more components and the `get` member
1068 function can be used to retrieve the components.
1069 
1070 Creating an entity from a prototype is straightforward:
1071 
1072 * To create a new entity from scratch and assign it a prototype, this is the way
1073  to go:
1074  ```cpp
1075  const auto entity = prototype();
1076  ```
1077  It is equivalent to the following invokation:
1078  ```cpp
1079  const auto entity = prototype.create();
1080  ```
1081 
1082 * In case we want to initialize an already existing entity, we can provide the
1083  `operator()` directly with the entity identifier:
1084  ```cpp
1085  prototype(entity);
1086  ```
1087  It is equivalent to the following invokation:
1088  ```cpp
1089  prototype.assign(entity);
1090  ```
1091  Note that existing components aren't overwritten in this case. Only those
1092  components that the entity doesn't own yet are copied over. All the other
1093  components remain unchanged.
1094 
1095 * Finally, to assign or replace all the components for an entity, thus
1096  overwriting existing ones:
1097  ```cpp
1098  prototype.accommodate(entity);
1099  ```
1100 
1101 In the examples above, the prototype uses its underlying registry to create
1102 entities and components both for its purposes and when it's cloned. To use a
1103 different repository to clone a prototype, all the member functions accept also
1104 a reference to a valid registry as a first argument.
1105 
1106 Prototypes are a very useful tool that can save a lot of typing sometimes.
1107 Furthermore, the codebase may be easier to maintain, since updating a prototype
1108 is much less error prone than jumping around in the codebase to update all the
1109 snippets copied and pasted around to initialize entities and components.
1110 
1111 ### Helpers
1112 
1113 The so called _helpers_ are small classes and functions mainly designed to offer
1114 built-in support for the most basic functionalities.<br/>
1115 The list of helpers will grow longer as time passes and new ideas come out.
1116 
1117 #### Dependency function
1118 
1119 A _dependency function_ is a predefined listener, actually a function template
1120 to use to automatically assign components to an entity when a type has a
1121 dependency on some other types.<br/>
1122 The following adds components `AType` and `AnotherType` whenever `MyType` is
1123 assigned to an entity:
1124 
1125 ```cpp
1126 entt::dependency<AType, AnotherType>(registry.construction<MyType>());
1127 ```
1128 
1129 A component is assigned to an entity and thus default initialized only in case
1130 the entity itself hasn't it yet. It means that already existent components won't
1131 be overriden.<br/>
1132 A dependency can easily be broken by means of the same function template:
1133 
1134 ```cpp
1135 entt::dependency<AType, AnotherType>(entt::break_t{}, registry.construction<MyType>());
1136 ```
1137 
1138 ## View: to persist or not to persist?
1139 
1140 First of all, it is worth answering an obvious question: why views?<br/>
1141 Roughly speaking, they are a good tool to enforce single responsibility. A
1142 system that has access to a registry can create and destroy entities, as well as
1143 assign and remove components. On the other side, a system that has access to a
1144 view can only iterate entities and their components, then read or update the
1145 data members of the latter.<br/>
1146 It is a subtle difference that can help designing a better software sometimes.
1147 
1148 There are mainly three kinds of views: standard (also known as `View`),
1149 persistent (also known as `PersistentView`) and raw (also known as
1150 `RawView`).<br/>
1151 All of them have pros and cons to take in consideration. In particular:
1152 
1153 * Standard views:
1154 
1155  Pros:
1156 
1157  * They work out-of-the-box and don't require any dedicated data structure.
1158  * Creating and destroying them isn't expensive at all because they don't have
1159  any type of initialization.
1160  * They are the best tool for iterating entities for a single component.
1161  * They are the best tool for iterating entities for multiple components when
1162  one of the components is assigned to a significantly low number of entities.
1163  * They don't affect any other operations of the registry.
1164 
1165  Cons:
1166 
1167  * Their performance tend to degenerate when the number of components to
1168  iterate grows up and the most of the entities have all of them.
1169 
1170 * Persistent views:
1171 
1172  Pros:
1173 
1174  * Once prepared, creating and destroying them isn't expensive at all because
1175  they don't have any type of initialization.
1176  * They are the best tool for iterating entities for multiple components when
1177  most entities have them all.
1178 
1179  Cons:
1180 
1181  * They have dedicated data structures and thus affect the memory usage to a
1182  minimal extent.
1183  * If not previously prepared, the first time they are used they go through an
1184  initialization step that could take a while.
1185  * They affect to a minimum the creation and destruction of entities and
1186  components. In other terms: the more persistent views there will be, the
1187  less performing will be creating and destroying entities and components.
1188 
1189 * Raw views:
1190 
1191  Pros:
1192 
1193  * They work out-of-the-box and don't require any dedicated data structure.
1194  * Creating and destroying them isn't expensive at all because they don't have
1195  any type of initialization.
1196  * They are the best tool for iterating components when it is not necessary to
1197  know which entities they belong to.
1198  * They don't affect any other operations of the registry.
1199 
1200  Cons:
1201 
1202  * They can be used to iterate only one type of component at a time.
1203  * They don't return the entity to which a component belongs to the caller.
1204 
1205 To sum up and as a rule of thumb:
1206 
1207 * Use a raw view to iterate components only (no entities) for a given type.
1208 * Use a standard view to iterate entities and components for a single type.
1209 * Use a standard view to iterate entities and components for multiple types when
1210  the number of types is low. Standard views are really optimized and persistent
1211  views won't add much in this case.
1212 * Use a standard view to iterate entities and components for multiple types when
1213  a significantly low number of entities have one of the components.
1214 * Use a standard view in all those cases where a persistent view would give a
1215  boost to performance but the iteration isn't performed frequently.
1216 * Prepare and use a persistent view when you want to iterate only entities for
1217  multiple components.
1218 * Prepare and use a persistent view when you want to iterate entities for
1219  multiple components and each component is assigned to a great number of
1220  entities but the intersection between the sets of entities is small.
1221 * Prepare and use a persistent view in all the cases where a standard view
1222  wouldn't fit well otherwise.
1223 
1224 To easily iterate entities and components, all the views offer the common
1225 `begin` and `end` member functions that allow users to use a view in a typical
1226 range-for loop. Almost all the views offer also a *more functional* `each`
1227 member function that accepts a callback for convenience.<br/>
1228 Continue reading for more details or refer to the inline documentation.
1229 
1230 ### Standard View
1231 
1232 A standard view behaves differently if it's constructed for a single component
1233 or if it has been requested to iterate multiple components. Even the API is
1234 different in the two cases.<br/>
1235 All that they share is the way they are created by means of a registry:
1236 
1237 ```cpp
1238 // single component standard view
1239 auto single = registry.view<Position>();
1240 
1241 // multi component standard view
1242 auto multi = registry.view<Position, Velocity>();
1243 ```
1244 
1245 For all that remains, it's worth discussing them separately.<br/>
1246 
1247 #### Single component standard view
1248 
1249 Single component standard views are specialized in order to give a boost in
1250 terms of performance in all the situation. This kind of views can access the
1251 underlying data structures directly and avoid superfluous checks.<br/>
1252 They offer a bunch of functionalities to get the number of entities they are
1253 going to return and a raw access to the entity list as well as to the component
1254 list. It's also possible to ask a view if it contains a given entity.<br/>
1255 Refer to the inline documentation for all the details.
1256 
1257 There is no need to store views around for they are extremely cheap to
1258 construct, even though they can be copied without problems and reused freely. In
1259 fact, they return newly created and correctly initialized iterators whenever
1260 `begin` or `end` are invoked.<br/>
1261 To iterate a single component standard view, either use it in range-for loop:
1262 
1263 ```cpp
1264 auto view = registry.view<Renderable>();
1265 
1266 for(auto entity: view) {
1267  Renderable &renderable = view.get(entity);
1268 
1269  // ...
1270 }
1271 ```
1272 
1273 Or rely on the `each` member function to iterate entities and get all their
1274 components at once:
1275 
1276 ```cpp
1277 registry.view<Renderable>().each([](auto entity, auto &renderable) {
1278  // ...
1279 });
1280 ```
1281 
1282 Performance are more or less the same. The best approach depends mainly on
1283 whether all the components have to be accessed or not.
1284 
1285 **Note**: prefer the `get` member function of a view instead of the `get` member
1286 function template of a registry during iterations, if possible. However, keep in
1287 mind that it works only with the components of the view itself.
1288 
1289 #### Multi component standard view
1290 
1291 Multi component standard views iterate entities that have at least all the given
1292 components in their bags. During construction, these views look at the number of
1293 entities available for each component and pick up a reference to the smallest
1294 set of candidates in order to speed up iterations.<br/>
1295 They offer fewer functionalities than their companion views for single
1296 component. In particular, a multi component standard view exposes utility
1297 functions to get the estimated number of entities it is going to return and to
1298 know whether it's empty or not. It's also possible to ask a view if it contains
1299 a given entity.<br/>
1300 Refer to the inline documentation for all the details.
1301 
1302 There is no need to store views around for they are extremely cheap to
1303 construct, even though they can be copied without problems and reused freely. In
1304 fact, they return newly created and correctly initialized iterators whenever
1305 `begin` or `end` are invoked.<br/>
1306 To iterate a multi component standard view, either use it in range-for loop:
1307 
1308 ```cpp
1309 auto view = registry.view<Position, Velocity>();
1310 
1311 for(auto entity: view) {
1312  // a component at a time ...
1313  Position &position = view.get<Position>(entity);
1314  Velocity &velocity = view.get<Velocity>(entity);
1315 
1316  // ... or multiple components at once
1317  std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1318 
1319  // ...
1320 }
1321 ```
1322 
1323 Or rely on the `each` member function to iterate entities and get all their
1324 components at once:
1325 
1326 ```cpp
1327 registry.view<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
1328  // ...
1329 });
1330 ```
1331 
1332 Performance are more or less the same. The best approach depends mainly on
1333 whether all the components have to be accessed or not.
1334 
1335 **Note**: prefer the `get` member function of a view instead of the `get` member
1336 function template of a registry during iterations, if possible. However, keep in
1337 mind that it works only with the components of the view itself.
1338 
1339 ### Persistent View
1340 
1341 A persistent view returns all the entities and only the entities that have at
1342 least the given components. Moreover, it's guaranteed that the entity list is
1343 tightly packed in memory for fast iterations.<br/>
1344 In general, persistent views don't stay true to the order of any set of
1345 components unless users explicitly sort them.
1346 
1347 Persistent views can be used only to iterate multiple components. To create this
1348 kind of views, the tag `persistent_t` must also be used in order to disambiguate
1349 overloads of the `view` member function:
1350 
1351 ```cpp
1352 auto view = registry.view<Position, Velocity>(entt::persistent_t{});
1353 ```
1354 
1355 There is no need to store views around for they are extremely cheap to
1356 construct, even though they can be copied without problems and reused freely. In
1357 fact, they return newly created and correctly initialized iterators whenever
1358 `begin` or `end` are invoked.<br/>
1359 That being said, persistent views perform an initialization step the very first
1360 time they are constructed and this could be quite costly. To avoid it, consider
1361 asking to the registry to _prepare_ them when no entities have been created yet:
1362 
1363 ```cpp
1364 registry.prepare<Position, Velocity>();
1365 ```
1366 
1367 If the registry is empty, preparation is extremely fast. Moreover the `prepare`
1368 member function template is idempotent. Feel free to invoke it even more than
1369 once: if the view has been already prepared before, the function returns
1370 immediately and does nothing.
1371 
1372 A persistent view offers a bunch of functionalities to get the number of
1373 entities it's going to return, a raw access to the entity list and the
1374 possibility to sort the underlying data structures according to the order of one
1375 of the components for which it has been constructed. It's also possible to ask a
1376 view if it contains a given entity.<br/>
1377 Refer to the inline documentation for all the details.
1378 
1379 To iterate a persistent view, either use it in range-for loop:
1380 
1381 ```cpp
1382 auto view = registry.view<Position, Velocity>(entt::persistent_t{});
1383 
1384 for(auto entity: view) {
1385  // a component at a time ...
1386  Position &position = view.get<Position>(entity);
1387  Velocity &velocity = view.get<Velocity>(entity);
1388 
1389  // ... or multiple components at once
1390  std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1391 
1392  // ...
1393 }
1394 ```
1395 
1396 Or rely on the `each` member function to iterate entities and get all their
1397 components at once:
1398 
1399 ```cpp
1400 registry.view<Position, Velocity>(entt::persistent_t{}).each([](auto entity, auto &position, auto &velocity) {
1401  // ...
1402 });
1403 ```
1404 
1405 Performance are more or less the same. The best approach depends mainly on
1406 whether all the components have to be accessed or not.
1407 
1408 **Note**: prefer the `get` member function of a view instead of the `get` member
1409 function template of a registry during iterations, if possible. However, keep in
1410 mind that it works only with the components of the view itself.
1411 
1412 ### Raw View
1413 
1414 Raw views return all the components of a given type. This kind of views can
1415 access components directly and avoid extra indirections like when components are
1416 accessed via an entity identifier.<br/>
1417 They offer a bunch of functionalities to get the number of instances they are
1418 going to return and a raw access to the entity list as well as to the component
1419 list.<br/>
1420 Refer to the inline documentation for all the details.
1421 
1422 Raw views can be used only to iterate components for a single type. To create
1423 this kind of views, the tag `raw_t` must also be used in order to disambiguate
1424 overloads of the `view` member function:
1425 
1426 ```cpp
1427 auto view = registry.view<Renderable>(entt::raw_t{});
1428 ```
1429 
1430 There is no need to store views around for they are extremely cheap to
1431 construct, even though they can be copied without problems and reused freely. In
1432 fact, they return newly created and correctly initialized iterators whenever
1433 `begin` or `end` are invoked.<br/>
1434 To iterate a raw view, use it in range-for loop:
1435 
1436 ```cpp
1437 auto view = registry.view<Renderable>(entt::raw_t{});
1438 
1439 for(auto &&component: raw) {
1440  // ...
1441 }
1442 ```
1443 
1444 **Note**: raw views don't have the `each` nor the `get` member function for
1445 obvious reasons. The former would only return the components and therefore it
1446 would be redundant, the latter isn't required at all.
1447 
1448 ### Give me everything
1449 
1450 Views are narrow windows on the entire list of entities. They work by filtering
1451 entities according to their components.<br/>
1452 In some cases there may be the need to iterate all the entities still in use
1453 regardless of their components. The registry offers a specific member function
1454 to do that:
1455 
1456 ```cpp
1457 registry.each([](auto entity) {
1458  // ...
1459 });
1460 ```
1461 
1462 It returns to the caller all the entities that are still in use by means of the
1463 given function.<br/>
1464 As a rule of thumb, consider using a view if the goal is to iterate entities
1465 that have a determinate set of components. A view is usually much faster than
1466 combining this function with a bunch of custom tests.<br/>
1467 In all the other cases, this is the way to go.
1468 
1469 There exists also another member function to use to retrieve orphans. An orphan
1470 is an entity that is still in use and has neither assigned components nor
1471 tags.<br/>
1472 The signature of the function is the same of `each`:
1473 
1474 ```cpp
1475 registry.orphans([](auto entity) {
1476  // ...
1477 });
1478 ```
1479 
1480 To test the _orphanity_ of a single entity, use the member function `orphan`
1481 instead. It accepts a valid entity identifer as an argument and returns true in
1482 case the entity is an orphan, false otherwise.
1483 
1484 In general, all these functions can result in poor performance.<br/>
1485 `each` is fairly slow because of some checks it performs on each and every
1486 entity. For similar reasons, `orphans` can be even slower. Both functions should
1487 not be used frequently to avoid the risk of a performance hit.
1488 
1489 ## Side notes
1490 
1491 * Entity identifiers are numbers and nothing more. They are not classes and they
1492  have no member functions at all. As already mentioned, do no try to inspect or
1493  modify an entity descriptor in any way.
1494 
1495 * As shown in the examples above, the preferred way to get references to the
1496  components while iterating a view is by using the view itself. It's a faster
1497  alternative to the `get` member function template that is part of the API of
1498  the `Registry`. This is because the registry must ensure that a pool for the
1499  given component exists before to use it; on the other side, views force the
1500  construction of the pools for all their components and access them directly,
1501  thus avoiding all the checks.
1502 
1503 * Most of the _ECS_ available out there have some annoying limitations (at least
1504  from my point of view): entities and components cannot be created and/or
1505  destroyed during iterations.<br/>
1506  `EnTT` partially solves the problem with a few limitations:
1507 
1508  * Creating entities and components is allowed during iterations.
1509  * Deleting an entity or removing its components is allowed during iterations
1510  if it's the one currently returned by a view. For all the other entities,
1511  destroying them or removing their components isn't allowed and it can result
1512  in undefined behavior.
1513 
1514  Iterators are invalidated and the behavior is undefined if an entity is
1515  modified or destroyed and it's not the one currently returned by the
1516  view.<br/>
1517  To work around it, possible approaches are:
1518 
1519  * Store aside the entities and the components to be removed and perform the
1520  operations at the end of the iteration.
1521  * Mark entities and components with a proper tag component that indicates
1522  they must be purged, then perform a second iteration to clean them up one
1523  by one.
1524 
1525 * Views and thus their iterators aren't thread safe. Do no try to iterate a set
1526  of components and modify the same set concurrently.<br/>
1527  That being said, as long as a thread iterates the entities that have the
1528  component `X` or assign and removes that component from a set of entities,
1529  another thread can safely do the same with components `Y` and `Z` and
1530  everything will work like a charm.<br/>
1531  As a trivial example, users can freely execute the rendering system and
1532  iterate the renderable entities while updating a physic component concurrently
1533  on a separate thread.
1534 
1535 * In general, the entire registry isn't thread safe as it is. Thread safety
1536  isn't something that users should want out of the box for several reasons.
1537  Just to mention one of them: performance.<br/>
1538  This kind of entity-component systems can be used in single threaded
1539  applications as well as along with async stuff. Moreover, typical thread based
1540  models for ECS don't require a fully thread safe registry to work. Actually
1541  one could reach the goal with the registry as it is while working with most of
1542  the common models, after all.<br/>
1543  Because of the few reasons mentioned above and many others not mentioned,
1544  users are completely responsible for synchronization whether required.
1545 
1546 # Crash Course: core functionalities
1547 
1548 The `EnTT` framework comes with a bunch of core functionalities mostly used by
1549 the other parts of the library itself.<br/>
1550 Hardly users of the framework will include these features in their code, but
1551 it's worth describing what `EnTT` offers so as not to reinvent the wheel in case
1552 of need.
1553 
1554 ## Compile-time identifiers
1555 
1556 Sometimes it's useful to be able to give unique identifiers to types at
1557 compile-time.<br/>
1558 There are plenty of different solutions out there and I could have used one of
1559 them. However, I decided to spend my time to define a compact and versatile tool
1560 that fully embraces what the modern C++ has to offer.
1561 
1562 The _result of my efforts_ is the `ident` `constexpr` variable:
1563 
1564 ```cpp
1565 #include <ident.hpp>
1566 
1567 // defines the identifiers for the given types
1568 constexpr auto identifiers = entt::ident<AType, AnotherType>;
1569 
1570 // ...
1571 
1572 switch(aTypeIdentifier) {
1573 case identifers.get<AType>():
1574  // ...
1575  break;
1576 case identifers.get<AnotherType>():
1577  // ...
1578  break;
1579 default:
1580  // ...
1581 }
1582 ```
1583 
1584 This is all what the variable has to offer: a `get` member function that returns
1585 a numerical identifier for the given type. It can be used in any context where
1586 constant expressions are required.
1587 
1588 As long as the list remains unchanged, identifiers are also guaranteed to be the
1589 same for every run. In case they have been used in a production environment and
1590 a type has to be removed, one can just use a placeholder to left the other
1591 identifiers unchanged:
1592 
1593 ```cpp
1594 template<typename> struct IgnoreType {};
1595 
1596 constexpr auto identifiers = entt::ident<
1597  ATypeStillValid,
1598  IgnoreType<ATypeNoLongerValid>,
1599  AnotherTypeStillValid
1600 >;
1601 ```
1602 
1603 A bit ugly to see, but it works at least.
1604 
1605 ## Runtime identifiers
1606 
1607 Sometimes it's useful to be able to give unique identifiers to types at
1608 runtime.<br/>
1609 There are plenty of different solutions out there and I could have used one of
1610 them. In fact, I adapted the most common one to my requirements and used it
1611 extensively within the entire framework.
1612 
1613 It's the `Family` class. Here is an example of use directly from the
1614 entity-component system:
1615 
1616 ```cpp
1617 using component_family = entt::Family<struct InternalRegistryComponentFamily>;
1618 
1619 // ...
1620 
1621 template<typename Component>
1622 component_type component() const noexcept {
1623  return component_family::type<Component>();
1624 }
1625 ```
1626 
1627 This is all what a _family_ has to offer: a `type` member function that returns
1628 a numerical identifier for the given type.
1629 
1630 Please, note that identifiers aren't guaranteed to be the same for every run.
1631 Indeed it mostly depends on the flow of execution.
1632 
1633 ## Hashed strings
1634 
1635 A hashed string is a zero overhead resource identifier. Users can use
1636 human-readable identifiers in the codebase while using their numeric
1637 counterparts at runtime, thus without affecting performance.<br/>
1638 The class has an implicit `constexpr` constructor that chews a bunch of
1639 characters. Once created, all what one can do with it is getting back the
1640 original string or converting it into a number.<br/>
1641 The good part is that a hashed string can be used wherever a constant expression
1642 is required and no _string-to-number_ conversion will take place at runtime if
1643 used carefully.
1644 
1645 Example of use:
1646 
1647 ```cpp
1648 auto load(entt::HashedString::hash_type resource) {
1649  // uses the numeric representation of the resource to load and return it
1650 }
1651 
1652 auto resource = load(entt::HashedString{"gui/background"});
1653 ```
1654 
1655 ### Conflicts
1656 
1657 The hashed string class uses internally FNV-1a to compute the numeric
1658 counterpart of a string. Because of the _pigeonhole principle_, conflicts are
1659 possible. This is a fact.<br/>
1660 There is no silver bullet to solve the problem of conflicts when dealing with
1661 hashing functions. In this case, the best solution seemed to be to give up.
1662 That's all.<br/>
1663 After all, human-readable resource identifiers aren't something strictly defined
1664 and over which users have not the control. Choosing a slightly different
1665 identifier is probably the best solution to make the conflict disappear in this
1666 case.
1667 
1668 # Crash Course: service locator
1669 
1670 Usually service locators are tightly bound to the services they expose and it's
1671 hard to define a general purpose solution. This template based implementation
1672 tries to fill the gap and to get rid of the burden of defining a different
1673 specific locator for each application.<br/>
1674 This class is tiny, partially unsafe and thus risky to use. Moreover it doesn't
1675 fit probably most of the scenarios in which a service locator is required. Look
1676 at it as a small tool that can sometimes be useful if the user knows how to
1677 handle it.
1678 
1679 The API is straightforward. The basic idea is that services are implemented by
1680 means of interfaces and rely on polymorphism.<br/>
1681 The locator is instantiated with the base type of the service if any and a
1682 concrete implementation is provided along with all the parameters required to
1683 initialize it. As an example:
1684 
1685 ```cpp
1686 // the service has no base type, a locator is used to treat it as a kind of singleton
1687 entt::ServiceLocator<MyService>::set(params...);
1688 
1689 // sets up an opaque service
1690 entt::ServiceLocator<AudioInterface>::set<AudioImplementation>(params...);
1691 
1692 // resets (destroys) the service
1693 entt::ServiceLocator<AudioInterface>::reset();
1694 ```
1695 
1696 The locator can also be queried to know if an active service is currently set
1697 and to retrieve it if necessary (either as a pointer or as a reference):
1698 
1699 ```cpp
1700 // no service currently set
1701 auto empty = entt::ServiceLocator<AudioInterface>::empty();
1702 
1703 // gets a (possibly empty) shared pointer to the service ...
1704 std::shared_ptr<AudioInterface> ptr = entt::ServiceLocator<AudioInterface>::get();
1705 
1706 // ... or a reference, but it's undefined behaviour if the service isn't set yet
1707 AudioInterface &ref = entt::ServiceLocator<AudioInterface>::ref();
1708 ```
1709 
1710 A common use is to wrap the different locators in a container class, creating
1711 aliases for the various services:
1712 
1713 ```cpp
1714 struct Locator {
1715  using Camera = entt::ServiceLocator<CameraInterface>;
1716  using Audio = entt::ServiceLocator<AudioInterface>;
1717  // ...
1718 };
1719 
1720 // ...
1721 
1722 void init() {
1723  Locator::Camera::set<CameraNull>();
1724  Locator::Audio::set<AudioImplementation>(params...);
1725  // ...
1726 }
1727 ```
1728 
1729 # Crash Course: cooperative scheduler
1730 
1731 Sometimes processes are a useful tool to work around the strict definition of a
1732 system and introduce logic in a different way, usually without resorting to the
1733 introduction of other components.
1734 
1735 The `EnTT` framework offers a minimal support to this paradigm by introducing a
1736 few classes that users can use to define and execute cooperative processes.
1737 
1738 ## The process
1739 
1740 A typical process must inherit from the `Process` class template that stays true
1741 to the CRTP idiom. Moreover, derived classes must specify what's the intended
1742 type for elapsed times.
1743 
1744 A process should expose publicly the following member functions whether
1745 required (note that it isn't required to define a function unless the derived
1746 class wants to _override_ the default behavior):
1747 
1748 * `void update(Delta, void *);`
1749 
1750  It's invoked once per tick until a process is explicitly aborted or it
1751  terminates either with or without errors. Even though it's not mandatory to
1752  declare this member function, as a rule of thumb each process should at
1753  least define it to work properly. The `void *` parameter is an opaque pointer
1754  to user data (if any) forwarded directly to the process during an update.
1755 
1756 * `void init(void *);`
1757 
1758  It's invoked at the first tick, immediately before an update. The `void *`
1759  parameter is an opaque pointer to user data (if any) forwarded directly to the
1760  process during an update.
1761 
1762 * `void succeeded();`
1763 
1764  It's invoked in case of success, immediately after an update and during the
1765  same tick.
1766 
1767 * `void failed();`
1768 
1769  It's invoked in case of errors, immediately after an update and during the
1770  same tick.
1771 
1772 * `void aborted();`
1773 
1774  It's invoked only if a process is explicitly aborted. There is no guarantee
1775  that it executes in the same tick, this depends solely on whether the
1776  process is aborted immediately or not.
1777 
1778 Derived classes can also change the internal state of a process by invoking
1779 `succeed` and `fail`, as well as `pause` and `unpause` the process itself. All
1780 these are protected member functions made available to be able to manage the
1781 life cycle of a process from a derived class.
1782 
1783 Here is a minimal example for the sake of curiosity:
1784 
1785 ```cpp
1786 struct MyProcess: entt::Process<MyProcess, std::uint32_t> {
1787  using delta_type = std::uint32_t;
1788 
1789  void update(delta_type delta, void *) {
1790  remaining = delta > remaining ? delta_type{] : (remaining - delta);
1791 
1792  // ...
1793 
1794  if(!remaining) {
1795  succeed();
1796  }
1797  }
1798 
1799  void init(void *data) {
1800  remaining = *static_cast<delta_type *>(data);
1801  }
1802 
1803 private:
1804  delta_type remaining;
1805 };
1806 ```
1807 
1808 ### Adaptor
1809 
1810 Lambdas and functors can't be used directly with a scheduler for they are not
1811 properly defined processes with managed life cycles.<br/>
1812 This class helps in filling the gap and turning lambdas and functors into
1813 full featured processes usable by a scheduler.
1814 
1815 The function call operator has a signature similar to the one of the `update`
1816 function of a process but for the fact that it receives two extra arguments to
1817 call whenever a process is terminated with success or with an error:
1818 
1819 ```cpp
1820 void(Delta delta, void *data, auto succeed, auto fail);
1821 ```
1822 
1823 Parameters have the following meaning:
1824 
1825 * `delta` is the elapsed time.
1826 * `data` is an opaque pointer to user data if any, `nullptr` otherwise.
1827 * `succeed` is a function to call when a process terminates with success.
1828 * `fail` is a function to call when a process terminates with errors.
1829 
1830 Both `succeed` and `fail` accept no parameters at all.
1831 
1832 Note that usually users shouldn't worry about creating adaptors at all. A
1833 scheduler creates them internally each and every time a lambda or a functor is
1834 used as a process.
1835 
1836 ## The scheduler
1837 
1838 A cooperative scheduler runs different processes and helps managing their life
1839 cycles.
1840 
1841 Each process is invoked once per tick. If it terminates, it's removed
1842 automatically from the scheduler and it's never invoked again. Otherwise it's
1843 a good candidate to run once more the next tick.<br/>
1844 A process can also have a child. In this case, the process is replaced with
1845 its child when it terminates if it returns with success. In case of errors,
1846 both the process and its child are discarded. This way, it's easy to create
1847 chain of processes to run sequentially.
1848 
1849 Using a scheduler is straightforward. To create it, users must provide only the
1850 type for the elapsed times and no arguments at all:
1851 
1852 ```cpp
1853 Scheduler<std::uint32_t> scheduler;
1854 ```
1855 
1856 It has member functions to query its internal data structures, like `empty` or
1857 `size`, as well as a `clear` utility to reset it to a clean state:
1858 
1859 ```cpp
1860 // checks if there are processes still running
1861 bool empty = scheduler.empty();
1862 
1863 // gets the number of processes still running
1864 Scheduler<std::uint32_t>::size_type size = scheduler.size();
1865 
1866 // resets the scheduler to its initial state and discards all the processes
1867 scheduler.clear();
1868 ```
1869 
1870 To attach a process to a scheduler there are mainly two ways:
1871 
1872 * If the process inherits from the `Process` class template, it's enough to
1873  indicate its type and submit all the parameters required to construct it to
1874  the `attach` member function:
1875 
1876  ```cpp
1877  scheduler.attach<MyProcess>("foobar");
1878  ```
1879 
1880 * Otherwise, in case of a lambda or a functor, it's enough to provide an
1881  instance of the class to the `attach` member function:
1882 
1883  ```cpp
1884  scheduler.attach([](auto...){ /* ... */ });
1885  ```
1886 
1887 In both cases, the return value is an opaque object that offers a `then` member
1888 function to use to create chains of processes to run sequentially.<br/>
1889 As a minimal example of use:
1890 
1891 ```cpp
1892 // schedules a task in the form of a lambda function
1893 scheduler.attach([](auto delta, void *, auto succeed, auto fail) {
1894  // ...
1895 })
1896 // appends a child in the form of another lambda function
1897 .then([](auto delta, void *, auto succeed, auto fail) {
1898  // ...
1899 })
1900 // appends a child in the form of a process class
1901 .then<MyProcess>();
1902 ```
1903 
1904 To update a scheduler and thus all its processes, the `update` member function
1905 is the way to go:
1906 
1907 ```cpp
1908 // updates all the processes, no user data are provided
1909 scheduler.update(delta);
1910 
1911 // updates all the processes and provides them with custom data
1912 scheduler.update(delta, &data);
1913 ```
1914 
1915 In addition to these functions, the scheduler offers an `abort` member function
1916 that can be used to discard all the running processes at once:
1917 
1918 ```cpp
1919 // aborts all the processes abruptly ...
1920 scheduler.abort(true);
1921 
1922 // ... or gracefully during the next tick
1923 scheduler.abort();
1924 ```
1925 
1926 # Crash Course: resource management
1927 
1928 Resource management is usually one of the most critical part of a software like
1929 a game. Solutions are often tuned to the particular application. There exist
1930 several approaches and all of them are perfectly fine as long as they fit the
1931 requirements of the piece of software in which they are used.<br/>
1932 Examples are loading everything on start, loading on request, predictive
1933 loading, and so on.
1934 
1935 The `EnTT` framework doesn't pretend to offer a _one-fits-all_ solution for the
1936 different cases. Instead, it offers a minimal and perhaps trivial cache that can
1937 be useful most of the time during prototyping and sometimes even in a production
1938 environment.<br/>
1939 For those interested in the subject, the plan is to improve it considerably over
1940 time in terms of performance, memory usage and functionalities. Hoping to make
1941 it, of course, one step at a time.
1942 
1943 ## The resource, the loader and the cache
1944 
1945 There are three main actors in the model: the resource, the loader and the
1946 cache.
1947 
1948 The _resource_ is whatever the user wants it to be. An image, a video, an audio,
1949 whatever. There are no limits.<br/>
1950 As a minimal example:
1951 
1952 ```cpp
1953 struct MyResource { const int value; };
1954 ```
1955 
1956 A _loader_ is a class the aim of which is to load a specific resource. It has to
1957 inherit directly from the dedicated base class as in the following example:
1958 
1959 ```cpp
1960 struct MyLoader final: entt::ResourceLoader<MyLoader, MyResource> {
1961  // ...
1962 };
1963 ```
1964 
1965 Where `MyResource` is the type of resources it creates.<br/>
1966 A resource loader must also expose a public const member function named `load`
1967 that accepts a variable number of arguments and returns a shared pointer to a
1968 resource.<br/>
1969 As an example:
1970 
1971 ```cpp
1972 struct MyLoader: entt::ResourceLoader<MyLoader, MyResource> {
1973  std::shared_ptr<MyResource> load(int value) const {
1974  // ...
1975  return std::shared_ptr<MyResource>(new MyResource{ value });
1976  }
1977 };
1978 ```
1979 
1980 In general, resource loaders should not have a state or retain data of any type.
1981 They should let the cache manage their resources instead.<br/>
1982 As a side note, base class and CRTP idiom aren't strictly required with the
1983 current implementation. One could argue that a cache can easily work with
1984 loaders of any type. However, future changes won't be breaking ones by forcing
1985 the use of a base class today and that's why the model is already in its place.
1986 
1987 Finally, a cache is a specialization of a class template tailored to a specific
1988 resource:
1989 
1990 ```cpp
1991 using MyResourceCache = entt::ResourceCache<MyResource>;
1992 
1993 // ...
1994 
1995 MyResourceCache cache{};
1996 ```
1997 
1998 The idea is to create different caches for different types of resources and to
1999 manage each one independently and in the most appropriate way.<br/>
2000 As a (very) trivial example, audio tracks can survive in most of the scenes of
2001 an application while meshes can be associated with a single scene and then
2002 discarded when the user leaves it.
2003 
2004 A cache offers a set of basic functionalities to query its internal state and to
2005 _organize_ it:
2006 
2007 ```cpp
2008 // gets the number of resources managed by a cache
2009 auto size = cache.size();
2010 
2011 // checks if a cache contains at least a valid resource
2012 auto empty = cache.empty();
2013 
2014 // clears a cache and discards its content
2015 cache.clear();
2016 ```
2017 
2018 Besides these member functions, it contains what is needed to load, use and
2019 discard resources of the given type.<br/>
2020 Before to explore this part of the interface, it makes sense to mention how
2021 resources are identified. The type of the identifiers to use is defined as:
2022 
2023 ```cpp
2024 entt::ResourceCache<Resource>::resource_type
2025 ```
2026 
2027 Where `resource_type` is an alias for `entt::HashedString`. Therefore, resource
2028 identifiers are created explicitly as in the following example:
2029 
2030 ```cpp
2031 constexpr auto identifier = entt::ResourceCache<Resource>::resource_type{"my/resource/identifier"};
2032 // this is equivalent to the following
2033 constexpr auto hs = entt::HashedString{"my/resource/identifier"};
2034 ```
2035 
2036 The class `HashedString` is described in a dedicated section, so I won't do in
2037 details here.
2038 
2039 Resources are loaded and thus stored in a cache through the `load` member
2040 function. It accepts the loader to use as a template parameter, the resource
2041 identifier and the parameters used to construct the resource as arguments:
2042 
2043 ```cpp
2044 // uses the identifier declared above
2045 cache.load<MyLoader>(identifier, 0);
2046 
2047 // uses a const char * directly as an identifier
2048 cache.load<MyLoader>("another/identifier", 42);
2049 ```
2050 
2051 The return value can be used to know if the resource has been loaded correctly.
2052 In case the loader returns an invalid pointer or the resource already exists in
2053 the cache, a false value is returned:
2054 
2055 ```cpp
2056 if(!cache.load<MyLoader>("another/identifier", 42)) {
2057  // ...
2058 }
2059 ```
2060 
2061 Unfortunately, in this case there is no way to know what was the problem
2062 exactly. However, before trying to load a resource or after an error, one can
2063 use the `contains` member function to know if a cache already contains a
2064 specific resource:
2065 
2066 ```cpp
2067 auto exists = cache.contains("my/identifier");
2068 ```
2069 
2070 There exists also a member function to use to force a reload of an already
2071 existing resource if needed:
2072 
2073 ```cpp
2074 auto result = cache.reload<MyLoader>("another/identifier", 42);
2075 ```
2076 
2077 As above, the function returns true in case of success, false otherwise. The
2078 sole difference in this case is that an error necessarily means that the loader
2079 has failed for some reasons to load the resource.<br/>
2080 Note that the `reload` member function is a kind of alias of the following
2081 snippet:
2082 
2083 ```cpp
2084 cache.discard(identifier);
2085 cache.load<MyLoader>(identifier, 42);
2086 ```
2087 
2088 Where the `discard` member function is used to get rid of a resource if loaded.
2089 In case the cache doesn't contain a resource for the given identifier, the
2090 function does nothing and returns immediately.
2091 
2092 So far, so good. Resources are finally loaded and stored within the cache.<br/>
2093 They are returned to users in the form of handles. To get one of them:
2094 
2095 ```cpp
2096 auto handle = cache.handle("my/identifier");
2097 ```
2098 
2099 The idea behind a handle is the same of the flyweight pattern. In other terms,
2100 resources aren't copied around. Instead, instances are shared between handles.
2101 Users of a resource owns a handle and it guarantees that a resource isn't
2102 destroyed until all the handles are destroyed, even if the resource itself is
2103 removed from the cache.<br/>
2104 Handles are tiny objects both movable and copyable. They returns the contained
2105 resource as a const reference on request:
2106 
2107 * By means of the `get` member function:
2108 
2109  ```cpp
2110  const auto &resource = handle.get();
2111  ```
2112 
2113 * Using the proper cast operator:
2114 
2115  ```cpp
2116  const auto &resource = handle;
2117  ```
2118 
2119 * Through the dereference operator:
2120 
2121  ```cpp
2122  const auto &resource = *handle;
2123  ```
2124 
2125 The resource can also be accessed directly using the arrow operator if required:
2126 
2127 ```cpp
2128 auto value = handle->value;
2129 ```
2130 
2131 To test if a handle is still valid, the cast operator to `bool` allows users to
2132 use it in a guard:
2133 
2134 ```cpp
2135 if(handle) {
2136  // ...
2137 }
2138 ```
2139 
2140 Finally, in case there is the need to load a resource and thus to get a handle
2141 without storing the resource itself in the cache, users can rely on the `temp`
2142 member function template.<br/>
2143 The declaration is similar to the one of `load` but for the fact that it doesn't
2144 return a boolean value. Instead, it returns a (possibly invalid) handle for the
2145 resource:
2146 
2147 ```cpp
2148 auto handle = cache.temp<MyLoader>("another/identifier", 42);
2149 ```
2150 
2151 Do not forget to test the handle for validity. Otherwise, getting the reference
2152 to the resource it points may result in undefined behavior.
2153 
2154 # Crash Course: events, signals and everything in between
2155 
2156 Signals are usually a core part of games and software architectures in
2157 general.<br/>
2158 Roughly speaking, they help to decouple the various parts of a system while
2159 allowing them to communicate with each other somehow.
2160 
2161 The so called _modern C++_ comes with a tool that can be useful in these terms,
2162 the `std::function`. As an example, it can be used to create delegates.<br/>
2163 However, there is no guarantee that an `std::function` does not perform
2164 allocations under the hood and this could be problematic sometimes. Furthermore,
2165 it solves a problem but may not adapt well to other requirements that may arise
2166 from time to time.
2167 
2168 In case that the flexibility and potential of an `std::function` are not
2169 required or where you are looking for something different, the `EnTT` framework
2170 offers a full set of classes to solve completely different problems.
2171 
2172 ## Signals
2173 
2174 Signal handlers work with naked pointers, function pointers and pointers to
2175 member functions. Listeners can be any kind of objects and the user is in charge
2176 of connecting and disconnecting them from a signal to avoid crashes due to
2177 different lifetimes. On the other side, performance shouldn't be affected that
2178 much by the presence of such a signal handler.<br/>
2179 A signal handler can be used as a private data member without exposing any
2180 _publish_ functionality to the clients of a class. The basic idea is to impose a
2181 clear separation between the signal itself and its _sink_ class, that is a tool
2182 to be used to connect and disconnect listeners on the fly.
2183 
2184 The API of a signal handler is straightforward. The most important thing is that
2185 it comes in two forms: with and without a collector. In case a signal is
2186 associated with a collector, all the values returned by the listeners can be
2187 literally _collected_ and used later by the caller. Otherwise it works just like
2188 a plain signal that emits events from time to time.<br/>
2189 
2190 **Note**: collectors are allowed only in case of function types whose the return
2191 type isn't `void` for obvious reasons.
2192 
2193 To create instances of signal handlers there exist mainly two ways:
2194 
2195 ```cpp
2196 // no collector type
2197 entt::SigH<void(int, char)> signal;
2198 
2199 // explicit collector type
2200 entt::SigH<void(int, char), MyCollector<bool>> collector;
2201 ```
2202 
2203 As expected, they offer all the basic functionalities required to know how many
2204 listeners they contain (`size`) or if they contain at least a listener (`empty`)
2205 and even to swap two signal handlers (`swap`).
2206 
2207 Besides them, there are member functions to use both to connect and disconnect
2208 listeners in all their forms by means of a sink::
2209 
2210 ```cpp
2211 void foo(int, char) { /* ... */ }
2212 
2213 struct S {
2214  void bar(int, char) { /* ... */ }
2215 };
2216 
2217 // ...
2218 
2219 S instance;
2220 
2221 signal.sink().connect<&foo>();
2222 signal.sink().connect<S, &S::bar>(&instance);
2223 
2224 // ...
2225 
2226 // disconnects a free function
2227 signal.sink().disconnect<&foo>();
2228 
2229 // disconnect a specific member function of an instance ...
2230 signal.sink().disconnect<S, &S::bar>(&instance);
2231 
2232 // ... or an instance as a whole
2233 signal.sink().disconnect(&instance);
2234 
2235 // discards all the listeners at once
2236 signal.sink().disconnect();
2237 ```
2238 
2239 Once listeners are attached (or even if there are no listeners at all), events
2240 and data in general can be published through a signal by means of the `publish`
2241 member function:
2242 
2243 ```cpp
2244 signal.publish(42, 'c');
2245 ```
2246 
2247 To collect data, the `collect` member function should be used instead. Below is
2248 a minimal example to show how to use it:
2249 
2250 ```cpp
2251 struct MyCollector {
2252  std::vector<int> vec{};
2253 
2254  bool operator()(int v) noexcept {
2255  vec.push_back(v);
2256  return true;
2257  }
2258 };
2259 
2260 int f() { return 0; }
2261 int g() { return 1; }
2262 
2263 // ...
2264 
2265 entt::SigH<int(), MyCollector<int>> signal;
2266 
2267 signal.sink().connect<&f>();
2268 signal.sink().connect<&g>();
2269 
2270 MyCollector collector = signal.collect();
2271 
2272 assert(collector.vec[0] == 0);
2273 assert(collector.vec[1] == 1);
2274 ```
2275 
2276 As shown above, a collector must expose a function operator that accepts as an
2277 argument a type to which the return type of the listeners can be converted.
2278 Moreover, it has to return a boolean value that is false to stop collecting
2279 data, true otherwise. This way one can avoid calling all the listeners in case
2280 it isn't necessary.
2281 
2282 ## Delegate
2283 
2284 A delegate can be used as general purpose invoker with no memory overhead for
2285 free functions and member functions provided along with an instance on which
2286 to invoke them.<br/>
2287 It does not claim to be a drop-in replacement for an `std::function`, so do not
2288 expect to use it whenever an `std::function` fits well. However, it can be used
2289 to send opaque delegates around to be used to invoke functions as needed.
2290 
2291 The interface is trivial. It offers a default constructor to create empty
2292 delegates:
2293 
2294 ```cpp
2295 entt::Delegate<int(int)> delegate{};
2296 ```
2297 
2298 All what is needed to create an instance is to specify the type of the function
2299 the delegate will _contain_, that is the signature of the free function or the
2300 member function one wants to assign to it.
2301 
2302 Attempting to use an empty delegate by invoking its function call operator
2303 results in undefined behavior, most likely a crash actually. Before to use a
2304 delegate, it must be initialized.<br/>
2305 There exist two functions to do that, both named `connect`:
2306 
2307 ```cpp
2308 int f(int i) { return i; }
2309 
2310 struct MyStruct {
2311  int f(int i) { return i }
2312 };
2313 
2314 // bind a free function to the delegate
2315 delegate.connect<&f>();
2316 
2317 // bind a member function to the delegate
2318 MyStruct instance;
2319 delegate.connect<MyStruct, &MyStruct::f>(&instance);
2320 ```
2321 
2322 It hasn't a `disconnect` counterpart. Instead, there exists a `reset` member
2323 function to clear it.<br/>
2324 Finally, to invoke a delegate, the function call operator is the way to go as
2325 usual:
2326 
2327 ```cpp
2328 auto ret = delegate(42);
2329 ```
2330 
2331 Probably too much small and pretty poor of functionalities, but the delegate
2332 class can help in a lot of cases and it has shown that it is worth keeping it
2333 within the framework.
2334 
2335 ## Event dispatcher
2336 
2337 The event dispatcher class is designed so as to be used in a loop. It allows
2338 users both to trigger immediate events or to queue events to be published all
2339 together once per tick.<br/>
2340 This class shares part of its API with the one of the signal handler, but it
2341 doesn't require that all the types of events are specified when declared:
2342 
2343 ```cpp
2344 // define a general purpose dispatcher that works with naked pointers
2345 entt::Dispatcher dispatcher{};
2346 ```
2347 
2348 In order to register an instance of a class to a dispatcher, its type must
2349 expose one or more member functions of which the return types are `void` and the
2350 argument lists are `const E &`, for each type of event `E`.<br/>
2351 To ease the development, member functions that are named `receive` are
2352 automatically detected and have not to be explicitly specified when registered.
2353 In all the other cases, the name of the member function aimed to receive the
2354 event must be provided to the `connect` member function of the sink bound to the
2355 specific event:
2356 
2357 ```cpp
2358 struct AnEvent { int value; };
2359 struct AnotherEvent {};
2360 
2361 struct Listener
2362 {
2363  void receive(const AnEvent &) { /* ... */ }
2364  void method(const AnotherEvent &) { /* ... */ }
2365 };
2366 
2367 // ...
2368 
2369 Listener listener;
2370 dispatcher.sink<AnEvent>().connect(&listener);
2371 dispatcher.sink<AnotherEvent>().connect<Listener, &Listener::method>(&listener);
2372 ```
2373 
2374 The `disconnect` member function follows the same pattern and can be used to
2375 selectively remove listeners:
2376 
2377 ```cpp
2378 dispatcher.sink<AnEvent>().disconnect(&listener);
2379 dispatcher.sink<AnotherEvent>().disconnect<Listener, &Listener::method>(&listener);
2380 ```
2381 
2382 The `trigger` member function serves the purpose of sending an immediate event
2383 to all the listeners registered so far. It offers a convenient approach that
2384 relieves the user from having to create the event itself. Instead, it's enough
2385 to specify the type of event and provide all the parameters required to
2386 construct it.<br/>
2387 As an example:
2388 
2389 ```cpp
2390 dispatcher.trigger<AnEvent>(42);
2391 dispatcher.trigger<AnotherEvent>();
2392 ```
2393 
2394 Listeners are invoked immediately, order of execution isn't guaranteed. This
2395 method can be used to push around urgent messages like an _is terminating_
2396 notification on a mobile app.
2397 
2398 On the other hand, the `enqueue` member function queues messages together and
2399 allows to maintain control over the moment they are sent to listeners. The
2400 signature of this method is more or less the same of `trigger`:
2401 
2402 ```cpp
2403 dispatcher.enqueue<AnEvent>(42);
2404 dispatcher.enqueue<AnotherEvent>();
2405 ```
2406 
2407 Events are stored aside until the `update` member function is invoked, then all
2408 the messages that are still pending are sent to the listeners at once:
2409 
2410 ```cpp
2411 // emits all the events of the given type at once
2412 dispatcher.update<MyEvent>();
2413 
2414 // emits all the events queued so far at once
2415 dispatcher.update();
2416 ```
2417 
2418 This way users can embed the dispatcher in a loop and literally dispatch events
2419 once per tick to their systems.
2420 
2421 ## Event emitter
2422 
2423 A general purpose event emitter thought mainly for those cases where it comes to
2424 working with asynchronous stuff.<br/>
2425 Originally designed to fit the requirements of
2426 [`uvw`](https://github.com/skypjack/uvw) (a wrapper for `libuv` written in
2427 modern C++), it was adapted later to be included in this library.
2428 
2429 To create a custom emitter type, derived classes must inherit directly from the
2430 base class as:
2431 
2432 ```cpp
2433 struct MyEmitter: Emitter<MyEmitter> {
2434  // ...
2435 }
2436 ```
2437 
2438 The full list of accepted types of events isn't required. Handlers are created
2439 internally on the fly and thus each type of event is accepted by default.
2440 
2441 Whenever an event is published, an emitter provides the listeners with a
2442 reference to itself along with a const reference to the event. Therefore
2443 listeners have an handy way to work with it without incurring in the need of
2444 capturing a reference to the emitter itself.<br/>
2445 In addition, an opaque object is returned each time a connection is established
2446 between an emitter and a listener, allowing the caller to disconnect them at a
2447 later time.<br/>
2448 The opaque object used to handle connections is both movable and copyable. On
2449 the other side, an event emitter is movable but not copyable by default.
2450 
2451 To create new instances of an emitter, no arguments are required:
2452 
2453 ```cpp
2454 MyEmitter emitter{};
2455 ```
2456 
2457 Listeners must be movable and callable objects (free functions, lambdas,
2458 functors, `std::function`s, whatever) whose function type is:
2459 
2460 ```cpp
2461 void(const Event &, MyEmitter &)
2462 ```
2463 
2464 Where `Event` is the type of event they want to listen.<br/>
2465 There are two ways to attach a listener to an event emitter that differ
2466 slightly from each other:
2467 
2468 * To register a long-lived listener, use the `on` member function. It is meant
2469  to register a listener designed to be invoked more than once for the given
2470  event type.<br/>
2471  As an example:
2472 
2473  ```cpp
2474  auto conn = emitter.on<MyEvent>([](const MyEvent &event, MyEmitter &emitter) {
2475  // ...
2476  });
2477  ```
2478 
2479  The connection object can be freely discarded. Otherwise, it can be used later
2480  to disconnect the listener if required.
2481 
2482 * To register a short-lived listener, use the `once` member function. It is
2483  meant to register a listener designed to be invoked only once for the given
2484  event type. The listener is automatically disconnected after the first
2485  invocation.<br/>
2486  As an example:
2487 
2488  ```cpp
2489  auto conn = emitter.once<MyEvent>([](const MyEvent &event, MyEmitter &emitter) {
2490  // ...
2491  });
2492  ```
2493 
2494  The connection object can be freely discarded. Otherwise, it can be used later
2495  to disconnect the listener if required.
2496 
2497 In both cases, the connection object can be used with the `erase` member
2498 function:
2499 
2500 ```cpp
2501 emitter.erase(conn);
2502 ```
2503 
2504 There are also two member functions to use either to disconnect all the
2505 listeners for a given type of event or to clear the emitter:
2506 
2507 ```cpp
2508 // removes all the listener for the specific event
2509 emitter.clear<MyEvent>();
2510 
2511 // removes all the listeners registered so far
2512 emitter.clear();
2513 ```
2514 
2515 To send an event to all the listeners that are interested in it, the `publish`
2516 member function offers a convenient approach that relieves the user from having
2517 to create the event:
2518 
2519 ```cpp
2520 struct MyEvent { int i; };
2521 
2522 // ...
2523 
2524 emitter.publish<MyEvent>(42);
2525 ```
2526 
2527 Finally, the `empty` member function tests if there exists at least either a
2528 listener registered with the event emitter or to a given type of event:
2529 
2530 ```cpp
2531 bool empty;
2532 
2533 // checks if there is any listener registered for the specific event
2534 empty = emitter.empty<MyEvent>();
2535 
2536 // checks it there are listeners registered with the event emitter
2537 empty = emitter.empty();
2538 ```
2539 
2540 In general, the event emitter is a handy tool when the derived classes _wrap_
2541 asynchronous operations, because it introduces a _nice-to-have_ model based on
2542 events and listeners that kindly hides the complexity behind the scenes. However
2543 it is not limited to such uses.
2544 
2545 # Packaging Tools
2546 
2547 `EnTT` is available for some of the most known packaging tools. In particular:
2548 
2549 * [`vcpkg`](https://github.com/Microsoft/vcpkg/tree/master/ports/entt),
2550  Microsoft VC++ Packaging Tool.
2551 * [`Homebrew`](https://github.com/skypjack/homebrew-entt), the missing package
2552  manager for macOS.<br/>
2553  Available as a homebrew formula. Just type the following to install it:
2554  ```
2555  brew install skypjack/entt/entt
2556  ```
2557 
2558 Consider this list a work in progress and help me to make it longer.
2559 
2560 # EnTT in Action
2561 
2562 `EnTT` is widely used in private and commercial applications. I cannot even
2563 mention most of them because of some signatures I put on some documents time
2564 ago.<br/>
2565 Fortunately, there are also people who took the time to implement open source
2566 projects based on EnTT and did not hold back when it came to documenting them.
2567 
2568 Below an incomplete list of projects and articles:
2569 
2570 * [EnttPong](https://github.com/reworks/EnttPong): example game for `EnTT`
2571  framework.
2572 * [ECS_SpaceBattle](https://github.com/vblanco20-1/ECS_SpaceBattle): huge space
2573  battle built on `UE4`.
2574 * [Experimenting with ECS in UE4](http://victor.madtriangles.com/code%20experiment/2018/03/25/post-ue4-ecs-battle.html):
2575  interesting article about `UE4` and `EnTT`.
2576 * [Implementing ECS architecture in UE4](https://forums.unrealengine.com/development-discussion/c-gameplay-programming/1449913-implementing-ecs-architecture-in-ue4-giant-space-battle):
2577  giant space battle.
2578 * [MatchOneEntt](https://github.com/mhaemmerle/MatchOneEntt): port of
2579  [Match One](https://github.com/sschmid/Match-One) for `Entitas-CSharp`.
2580 * [Randballs](https://github.com/gale93/randballs): simple `SFML` and `EnTT`
2581  playground.
2582 * ...
2583 
2584 If you know of other resources out there that are about `EnTT`, feel free to
2585 open an issue or a PR and I'll be glad to add them to the list.
2586 
2587 # Contributors
2588 
2589 If you want to participate, please see the guidelines for
2590 [contributing](https://github.com/skypjack/entt/blob/master/CONTRIBUTING)
2591 before to create issues or pull requests.<br/>
2592 Take also a look at the
2593 [contributors list](https://github.com/skypjack/entt/blob/master/AUTHORS) to
2594 know who has participated so far.
2595 
2596 # License
2597 
2598 Code and documentation Copyright (c) 2018 Michele Caini.<br/>
2599 Code released under
2600 [the MIT license](https://github.com/skypjack/entt/blob/master/LICENSE).
2601 Docs released under
2602 [Creative Commons](https://github.com/skypjack/entt/blob/master/docs/LICENSE).
2603 
2604 # Support
2605 
2606 ## Donation
2607 
2608 Developing and maintaining `EnTT` takes some time and lots of coffee. I'd like
2609 to add more and more functionalities in future and turn it in a full-featured
2610 framework.<br/>
2611 If you want to support this project, you can offer me an espresso. I'm from
2612 Italy, we're used to turning the best coffee ever in code. If you find that
2613 it's not enough, feel free to support me the way you prefer.<br/>
2614 Take a look at the donation button at the top of the page for more details or
2615 just click [here](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted).
2616 
2617 ## Hire me
2618 
2619 If you start using `EnTT` and need help, if you want a new feature and want me
2620 to give it the highest priority, if you have any other reason to contact me:
2621 do not hesitate. I'm available for hiring.<br/>
2622 Feel free to take a look at my [profile](https://github.com/skypjack) and
2623 contact me by mail.
+
1 # EnTT Framework
2 
3 [![Build Status](https://travis-ci.org/skypjack/entt.svg?branch=master)](https://travis-ci.org/skypjack/entt)
4 [![Build status](https://ci.appveyor.com/api/projects/status/rvhaabjmghg715ck?svg=true)](https://ci.appveyor.com/project/skypjack/entt)
5 [![Coverage Status](https://coveralls.io/repos/github/skypjack/entt/badge.svg?branch=master)](https://coveralls.io/github/skypjack/entt?branch=master)
6 [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)
7 
8 # Table of Contents
9 
10 * [Introduction](#introduction)
11 * [Build Instructions](#build-instructions)
12 * [Crash Course: entity-component system](#crash-course-entity-component-system)
13  * [Design choices](#design-choices)
14  * [A bitset-free entity-component system](#a-bitset-free-entity-component-system)
15  * [Pay per use](#pay-per-use)
16  * [Vademecum](#vademecum)
17  * [The Registry, the Entity and the Component](#the-registry-the-entity-and-the-component)
18  * [Single instance components](#single-instance-components)
19  * [Observe changes](#observe-changes)
20  * [Who let the tags out?](#who-let-the-tags-out)
21  * [Runtime components](#runtime-components)
22  * [A journey through a plugin](#a-journey-through-a-plugin)
23  * [Sorting: is it possible?](#sorting-is-it-possible)
24  * [Snapshot: complete vs continuous](#snapshot-complete-vs-continuous)
25  * [Snapshot loader](#snapshot-loader)
26  * [Continuous loader](#continuous-loader)
27  * [Archives](#archives)
28  * [One example to rule them all](#one-example-to-rule-them-all)
29  * [Prototype](#prototype)
30  * [Helpers](#helpers)
31  * [Dependency function](#dependency-function)
32  * [Null entity](#null-entity)
33  * [View: to persist or not to persist?](#view-to-persist-or-not-to-persist)
34  * [Standard View](#standard-view)
35  * [Single component standard view](#single-component-standard-view)
36  * [Multi component standard view](#multi-component-standard-view)
37  * [Persistent View](#persistent-view)
38  * [Raw View](#raw-view)
39  * [Runtime View](#runtime-view)
40  * [Give me everything](#give-me-everything)
41  * [Iterations: what is allowed and what is not](#iterations-what-is-allowed-and-what-is-not)
42  * [Multithreading](#multithreading)
43 * [Crash Course: core functionalities](#crash-course-core-functionalities)
44  * [Compile-time identifiers](#compile-time-identifiers)
45  * [Runtime identifiers](#runtime-identifiers)
46  * [Hashed strings](#hashed-strings)
47  * [Monostate](#monostate)
48 * [Crash Course: service locator](#crash-course-service-locator)
49 * [Crash Course: cooperative scheduler](#crash-course-cooperative-scheduler)
50  * [The process](#the-process)
51  * [The scheduler](#the-scheduler)
52 * [Crash Course: resource management](#crash-course-resource-management)
53  * [The resource, the loader and the cache](#the-resource-the-loader-and-the-cache)
54 * [Crash Course: events, signals and everything in between](#crash-course-events-signals-and-everything-in-between)
55  * [Signals](#signals)
56  * [Delegate](#delegate)
57  * [Event dispatcher](#event-dispatcher)
58  * [Event emitter](#event-emitter)
59 * [Packaging Tools](#packaging-tools)
60 * [EnTT in Action](#entt-in-action)
61 * [License](#license)
62 * [Support](#support)
63  * [Donation](#donation)
64  * [Hire me](#hire-me)
65 
66 # Introduction
67 
68 `EnTT` is a header-only, tiny and easy to use framework written in modern
69 C++.<br/>
70 It was originally designed entirely around an architectural pattern called _ECS_
71 that is used mostly in game development. For further details:
72 
73 * [Entity Systems Wiki](http://entity-systems.wikidot.com/)
74 * [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/)
75 * [ECS on Wikipedia](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system)
76 
77 A long time ago, the sole entity-component system was part of the project. After
78 a while the codebase has grown and more and more classes have become part of the
79 repository.<br/>
80 That's why today it's called _the EnTT Framework_.
81 
82 Currently, `EnTT` is tested on Linux, Microsoft Windows and OS X. It has proven
83 to work also on both Android and iOS.<br/>
84 Most likely it will not be problematic on other systems as well, but has not
85 been sufficiently tested so far.
86 
87 ## The framework
88 
89 `EnTT` was written initially as a faster alternative to other well known and
90 open source entity-component systems. Nowadays the `EnTT` framework is moving
91 its first steps. Much more will come in the future and hopefully I'm going to
92 work on it for a long time.<br/>
93 Requests for feature, PR, suggestions ad feedback are highly appreciated.
94 
95 If you find you can help me and want to contribute to the `EnTT` framework with
96 your experience or you do want to get part of the project for some other
97 reasons, feel free to contact me directly (you can find the mail in the
98 [profile](https://github.com/skypjack)).<br/>
99 I can't promise that each and every contribution will be accepted, but I can
100 assure that I'll do my best to take them all seriously.
101 
102 ### State of the art
103 
104 Here is a brief list of what it offers today:
105 
106 * Statically generated integer identifiers for types (assigned either at
107  compile-time or at runtime).
108 * A constexpr utility for human readable resource identifiers.
109 * An incredibly fast entity-component system based on sparse sets, with its own
110  views and a _pay for what you use_ policy to adjust performance and memory
111  usage according to users' requirements.
112 * Actor class for those who aren't confident with entity-component systems.
113 * The smallest and most basic implementation of a service locator ever seen.
114 * A cooperative scheduler for processes of any type.
115 * All what is needed for resource management (cache, loaders, handles).
116 * Delegates, signal handlers (with built-in support for collectors) and a tiny
117  event dispatcher.
118 * A general purpose event emitter, that is a CRTP idiom based class template.
119 * An event dispatcher for immediate and delayed events to integrate in loops.
120 * ...
121 * Any other business.
122 
123 Consider it a work in progress. For more details and an updated list, please
124 refer to the [online documentation](https://skypjack.github.io/entt/). It
125 probably contains much more. Moreover, the whole API is fully documented in-code
126 for those who are brave enough to read it.<br/>
127 Continue reading to know how the different parts of the project work or follow
128 the link above to take a look at the API reference.
129 
130 ## Code Example
131 
132 ```cpp
133 #include <entt/entt.hpp>
134 #include <cstdint>
135 
136 struct Position {
137  float x;
138  float y;
139 };
140 
141 struct Velocity {
142  float dx;
143  float dy;
144 };
145 
146 void update(entt::DefaultRegistry &registry) {
147  auto view = registry.view<Position, Velocity>();
148 
149  for(auto entity: view) {
150  // gets only the components that are going to be used ...
151 
152  auto &velocity = view.get<Velocity>(entity);
153 
154  velocity.dx = 0.;
155  velocity.dy = 0.;
156 
157  // ...
158  }
159 }
160 
161 void update(std::uint64_t dt, entt::DefaultRegistry &registry) {
162  registry.view<Position, Velocity>().each([dt](auto entity, auto &position, auto &velocity) {
163  // gets all the components of the view at once ...
164 
165  position.x += velocity.dx * dt;
166  position.y += velocity.dy * dt;
167 
168  // ...
169  });
170 }
171 
172 int main() {
173  entt::DefaultRegistry registry;
174  std::uint64_t dt = 16;
175 
176  for(auto i = 0; i < 10; ++i) {
177  auto entity = registry.create();
178  registry.assign<Position>(entity, i * 1.f, i * 1.f);
179  if(i % 2 == 0) { registry.assign<Velocity>(entity, i * .1f, i * .1f); }
180  }
181 
182  update(dt, registry);
183  update(registry);
184 
185  // ...
186 }
187 ```
188 
189 ## Motivation
190 
191 I started working on `EnTT` because of the wrong reason: my goal was to design
192 an entity-component system that beated another well known open source solution
193 in terms of performance and used (possibly) less memory in the average
194 case.<br/>
195 In the end, I did it, but it wasn't much satisfying. Actually it wasn't
196 satisfying at all. The fastest and nothing more, fairly little indeed. When I
197 realized it, I tried hard to keep intact the great performance of `EnTT` and to
198 add all the features I wanted to see in *my own library* at the same time.
199 
200 Today `EnTT` is finally what I was looking for: still faster than its
201 _competitors_, lower memory usage in the average case, a really good API and an
202 amazing set of features. And even more, of course.
203 
204 ## Performance
205 
206 As it stands right now, `EnTT` is just fast enough for my requirements if
207 compared to my first choice (it was already amazingly fast actually).<br/>
208 Below is a comparison between the two (both of them compiled with GCC 7.3.0 on a
209 Dell XPS 13 out of the mid 2014):
210 
211 | Benchmark | EntityX (compile-time) | EnTT |
212 |-----------|-------------|-------------|
213 | Create 1M entities | 0.0147s | **0.0046s** |
214 | Destroy 1M entities | 0.0053s | **0.0045s** |
215 | 1M entities, one component | 0.0012s | **1.9e-07s** |
216 | 1M entities, two components | 0.0012s | **3.8e-07s** |
217 | 1M entities, two components<br/>Half of the entities have all the components | 0.0009s | **3.8e-07s** |
218 | 1M entities, two components<br/>One of the entities has all the components | 0.0008s | **1.0e-06s** |
219 | 1M entities, five components | 0.0010s | **7.0e-07s** |
220 | 1M entities, ten components | 0.0011s | **1.2e-06s** |
221 | 1M entities, ten components<br/>Half of the entities have all the components | 0.0010s | **1.2e-06s** |
222 | 1M entities, ten components<br/>One of the entities has all the components | 0.0008s | **1.2e-06s** |
223 | Sort 150k entities, one component<br/>Arrays are in reverse order | - | **0.0036s** |
224 | Sort 150k entities, enforce permutation<br/>Arrays are in reverse order | - | **0.0005s** |
225 | Sort 150k entities, one component<br/>Arrays are almost sorted, std::sort | - | **0.0035s** |
226 | Sort 150k entities, one component<br/>Arrays are almost sorted, insertion sort | - | **0.0007s** |
227 
228 Note: The default version of `EntityX` (`master` branch) wasn't added to the
229 comparison because it's already much slower than its compile-time counterpart.
230 
231 Pretty interesting, aren't them? In fact, these benchmarks are the same used by
232 `EntityX` to show _how fast it is_. To be honest, they aren't so good and these
233 results shouldn't be taken much seriously (they are completely unrealistic
234 indeed).<br/>
235 The proposed entity-component system is incredibly fast to iterate entities,
236 this is a fact. The compiler can make a lot of optimizations because of how
237 `EnTT` works, even more when components aren't used at all. This is exactly the
238 case for these benchmarks. On the other hand and if we consider real world
239 cases, `EnTT` is in the middle between a bit and much faster than the other
240 solutions around when users also access the components and not just the
241 entities, although it is not as fast as reported by these benchmarks.<br/>
242 This is why they are completely wrong and cannot be used to evaluate any of the
243 entity-component systems.
244 
245 If you decide to use `EnTT`, choose it because of its API, features and
246 performance, not because there is a benchmark somewhere that makes it seem the
247 fastest.
248 
249 Probably I'll try to get out of `EnTT` more features and even better performance
250 in the future, mainly for fun.<br/>
251 If you want to contribute and/or have any suggestion, feel free to make a PR or
252 open an issue to discuss your idea.
253 
254 # Build Instructions
255 
256 ## Requirements
257 
258 To be able to use `EnTT`, users must provide a full-featured compiler that
259 supports at least C++14.<br/>
260 The requirements below are mandatory to compile the tests and to extract the
261 documentation:
262 
263 * CMake version 3.2 or later.
264 * Doxygen version 1.8 or later.
265 
266 ## Library
267 
268 `EnTT` is a header-only library. This means that including the `entt.hpp`
269 header is enough to include the whole framework and use it. For those who are
270 interested only in the entity-component system, consider to include the sole
271 `entity/registry.hpp` header instead.<br/>
272 It's a matter of adding the following line to the top of a file:
273 
274 ```cpp
275 #include <entt/entt.hpp>
276 ```
277 
278 Use the line below to include only the entity-component system instead:
279 
280 ```cpp
281 #include <entt/entity/registry.hpp>
282 ```
283 
284 Then pass the proper `-I` argument to the compiler to add the `src` directory to
285 the include paths.
286 
287 ## Documentation
288 
289 The documentation is based on [doxygen](http://www.stack.nl/~dimitri/doxygen/).
290 To build it:
291 
292  $ cd build
293  $ cmake .. -DBUILD_DOCS=ON
294  $ make
295 
296 The API reference will be created in HTML format within the directory
297 `build/docs/html`. To navigate it with your favorite browser:
298 
299  $ cd build
300  $ your_favorite_browser docs/html/index.html
301 
302 The API reference is also available [online](https://skypjack.github.io/entt/)
303 for the latest version.
304 
305 ## Tests
306 
307 To compile and run the tests, `EnTT` requires *googletest*.<br/>
308 `cmake` will download and compile the library before compiling anything else.
309 In order to build without tests set CMake option `BUILD_TESTING=OFF`.
310 
311 To build the most basic set of tests:
312 
313 * `$ cd build`
314 * `$ cmake ..`
315 * `$ make`
316 * `$ make test`
317 
318 Note that benchmarks are not part of this set.
319 
320 # Crash Course: entity-component system
321 
322 ## Design choices
323 
324 ### A bitset-free entity-component system
325 
326 `EnTT` is a _bitset-free_ entity-component system that doesn't require users to
327 specify the component set at compile-time.<br/>
328 This is why users can instantiate the core class simply like:
329 
330 ```cpp
331 entt::DefaultRegistry registry;
332 ```
333 
334 In place of its more annoying and error-prone counterpart:
335 
336 ```cpp
337 entt::DefaultRegistry<Comp0, Comp1, ..., CompN> registry;
338 ```
339 
340 ### Pay per use
341 
342 `EnTT` is entirely designed around the principle that users have to pay only for
343 what they want.
344 
345 When it comes to using an entity-component system, the tradeoff is usually
346 between performance and memory usage. The faster it is, the more memory it uses.
347 However, slightly worse performance along non-critical paths are the right price
348 to pay to reduce memory usage and I've always wondered why this kind of tools do
349 not leave me the choice.<br/>
350 `EnTT` follows a completely different approach. It squeezes the best from the
351 basic data structures and gives users the possibility to pay more for higher
352 performance where needed.<br/>
353 The disadvantage of this approach is that users need to know the systems they
354 are working on and the tools they are using. Otherwise, the risk to ruin the
355 performance along critical paths is high.
356 
357 So far, this choice has proven to be a good one and I really hope it can be for
358 many others besides me.
359 
360 ## Vademecum
361 
362 The `Registry` to store, the views to iterate. That's all.
363 
364 An entity (the _E_ of an _ECS_) is an opaque identifier that users should just
365 use as-is and store around if needed. Do not try to inspect an entity
366 identifier, its format can change in future and a registry offers all the
367 functionalities to query them out-of-the-box. The underlying type of an entity
368 (either `std::uint16_t`, `std::uint32_t` or `std::uint64_t`) can be specified
369 when defining a registry (actually the `DefaultRegistry` is nothing more than a
370 `Registry` where the type of the entities is `std::uint32_t`).<br/>
371 Components (the _C_ of an _ECS_) should be plain old data structures or more
372 complex and movable data structures with a proper constructor. Actually, the
373 sole requirement of a component type is that it must be both move constructible
374 and move assignable. They are list initialized by using the parameters provided
375 to construct the component itself. No need to register components or their types
376 neither with the registry nor with the entity-component system at all.<br/>
377 Systems (the _S_ of an _ECS_) are just plain functions, functors, lambdas or
378 whatever users want. They can accept a `Registry` or a view of any type and use
379 them the way they prefer. No need to register systems or their types neither
380 with the registry nor with the entity-component system at all.
381 
382 The following sections will explain in short how to use the entity-component
383 system, the core part of the whole framework.<br/>
384 In fact, the framework is composed of many other classes in addition to those
385 describe below. For more details, please refer to the inline documentation.
386 
387 ## The Registry, the Entity and the Component
388 
389 A registry can store and manage entities, as well as create views to iterate the
390 underlying data structures.<br/>
391 `Registry` is a class template that lets users decide what's the preferred type
392 to represent an entity. Because `std::uint32_t` is large enough for almost all
393 the cases, there exists also an alias named `DefaultRegistry` for
394 `Registry<std::uint32_t>`.
395 
396 Entities are represented by _entity identifiers_. An entity identifier is an
397 opaque type that users should not inspect or modify in any way. It carries
398 information about the entity itself and its version.
399 
400 A registry can be used both to construct and destroy entities:
401 
402 ```cpp
403 // constructs a naked entity with no components and returns its identifier
404 auto entity = registry.create();
405 
406 // destroys an entity and all its components
407 registry.destroy(entity);
408 ```
409 
410 Entities can also be destroyed _by type_, that is by specifying the types of the
411 tags or components that identify them:
412 
413 ```cpp
414 // destroys the entity that owns the given tag, if any
415 registry.destroy<MyTag>(entt::tag_t{});
416 
417 // destroys the entities that own the given components, if any
418 registry.destroy<AComponent, AnotherComponent>();
419 ```
420 
421 When an entity is destroyed, the registry can freely reuse it internally with a
422 slightly different identifier. In particular, the version of an entity is
423 increased each and every time it's discarded.<br/>
424 In case entity identifiers are stored around, the registry offers all the
425 functionalities required to test them and get out of the them all the
426 information they carry:
427 
428 ```cpp
429 // returns true if the entity is still valid, false otherwise
430 bool b = registry.valid(entity);
431 
432 // gets the version contained in the entity identifier
433 auto version = registry.version(entity);
434 
435 // gets the actual version for the given entity
436 auto curr = registry.current(entity);
437 ```
438 
439 Components can be assigned to or removed from entities at any time with a few
440 calls to member functions of the registry. As for the entities, the registry
441 offers also a set of functionalities users can use to work with the components.
442 
443 The `assign` member function template creates, initializes and assigns to an
444 entity the given component. It accepts a variable number of arguments to
445 construct the component itself if present:
446 
447 ```cpp
448 registry.assign<Position>(entity, 0., 0.);
449 
450 // ...
451 
452 Velocity &velocity = registry.assign<Velocity>(entity);
453 velocity.dx = 0.;
454 velocity.dy = 0.;
455 ```
456 
457 If an entity already has the given component, the `replace` member function
458 template can be used to replace it:
459 
460 ```cpp
461 registry.replace<Position>(entity, 0., 0.);
462 
463 // ...
464 
465 Velocity &velocity = registry.replace<Velocity>(entity);
466 velocity.dx = 0.;
467 velocity.dy = 0.;
468 ```
469 
470 In case users want to assign a component to an entity, but it's unknown whether
471 the entity already has it or not, `accommodate` does the work in a single call
472 (there is a performance penalty to pay for this mainly due to the fact that it
473 has to check if the entity already has the given component or not):
474 
475 ```cpp
476 registry.accommodate<Position>(entity, 0., 0.);
477 
478 // ...
479 
480 Velocity &velocity = registry.accommodate<Velocity>(entity);
481 velocity.dx = 0.;
482 velocity.dy = 0.;
483 ```
484 
485 Note that `accommodate` is a slightly faster alternative for the following
486 `if/else` statement and nothing more:
487 
488 ```cpp
489 if(registry.has<Comp>(entity)) {
490  registry.replace<Comp>(entity, arg1, argN);
491 } else {
492  registry.assign<Comp>(entity, arg1, argN);
493 }
494 ```
495 
496 As already shown, if in doubt about whether or not an entity has one or more
497 components, the `has` member function template may be useful:
498 
499 ```cpp
500 bool b = registry.has<Position, Velocity>(entity);
501 ```
502 
503 On the other side, if the goal is to delete a single component, the `remove`
504 member function template is the way to go when it's certain that the entity owns
505 a copy of the component:
506 
507 ```cpp
508 registry.remove<Position>(entity);
509 ```
510 
511 Otherwise consider to use the `reset` member function. It behaves similarly to
512 `remove` but with a strictly defined behavior (and a performance penalty is the
513 price to pay for this). In particular it removes the component if and only if it
514 exists, otherwise it returns safely to the caller:
515 
516 ```cpp
517 registry.reset<Position>(entity);
518 ```
519 
520 There exist also two other _versions_ of the `reset` member function:
521 
522 * If no entity is passed to it, `reset` will remove the given component from
523  each entity that has it:
524 
525  ```cpp
526  registry.reset<Position>();
527  ```
528 
529 * If neither the entity nor the component are specified, all the entities still
530  in use and their components are destroyed:
531 
532  ```cpp
533  registry.reset();
534  ```
535 
536 Finally, references to components can be retrieved simply by doing this:
537 
538 ```cpp
539 const auto &cregistry = registry;
540 
541 // const and non-const reference
542 const Position &position = cregistry.get<Position>(entity);
543 Position &position = registry.get<Position>(entity);
544 
545 // const and non-const references
546 std::tuple<const Position &, const Velocity &> tup = cregistry.get<Position, Velocity>(entity);
547 std::tuple<Position &, Velocity &> tup = registry.get<Position, Velocity>(entity);
548 ```
549 
550 The `get` member function template gives direct access to the component of an
551 entity stored in the underlying data structures of the registry.
552 
553 ### Single instance components
554 
555 In those cases where all what is needed is a single instance component, tags are
556 the right tool to achieve the purpose.<br/>
557 Tags undergo the same requirements of components. They can be either plain old
558 data structures or more complex and movable data structures with a proper
559 constructor.<br/>
560 Actually, the same type can be used both as a tag and as a component and the
561 registry will not complain about it. It is up to users to properly manage their
562 own types. In some cases, the tag `tag_t` must also be used in order to
563 disambiguate overloads of member functions.
564 
565 Attaching tags to entities and removing them is trivial:
566 
567 ```cpp
568 auto player = registry.create();
569 auto camera = registry.create();
570 
571 // attaches a default-initialized tag to an entity
572 registry.assign<PlayingCharacter>(entt::tag_t{}, player);
573 
574 // attaches a tag to an entity and initializes it
575 registry.assign<Camera>(entt::tag_t{}, camera, player);
576 
577 // removes tags from their owners
578 registry.remove<PlayingCharacter>();
579 registry.remove<Camera>();
580 ```
581 
582 In case a tag already has an owner, its content can be updated by means of the
583 `replace` member function template and the ownership of the tag can be
584 transferred to another entity using the `move` member function template:
585 
586 ```
587 // replaces the content of the given tag
588 Point &point = registry.replace<Point>(entt::tag_t{}, 1.f, 1.f);
589 
590 // transfers the ownership of the tag to another entity
591 entity_type prev = registry.move<Point>(next);
592 ```
593 
594 If in doubt about whether or not a tag already has an owner, the `has` member
595 function template may be useful:
596 
597 ```cpp
598 bool b = registry.has<PlayingCharacter>();
599 ```
600 
601 References to tags can be retrieved simply by doing this:
602 
603 ```cpp
604 const auto &cregistry = registry;
605 
606 // either a non-const reference ...
607 PlayingCharacter &player = registry.get<PlayingCharacter>();
608 
609 // ... or a const one
610 const Camera &camera = cregistry.get<Camera>();
611 ```
612 
613 The `get` member function template gives direct access to the tag as stored in
614 the underlying data structures of the registry.
615 
616 As shown above, in almost all the cases the entity identifier isn't required.
617 Since a single instance component can have only one associated entity, it
618 doesn't make much sense to mention it explicitly.<br/>
619 To find out who the owner is, just do the following:
620 
621 ```cpp
622 auto player = registry.attachee<PlayingCharacter>();
623 ```
624 
625 Note that iterating tags isn't possible for obvious reasons. Tags give direct
626 access to single entities and nothing more.
627 
628 ### Observe changes
629 
630 Because of how the registry works internally, it stores a couple of signal
631 handlers for each pool in order to notify some of its data structures on the
632 construction and destruction of components.<br/>
633 These signal handlers are also exposed and made available to users. This is the
634 basic brick to build fancy things like dependencies and reactive systems.
635 
636 To get a sink to be used to connect and disconnect listeners so as to be
637 notified on the creation of a component, use the `construction` member function:
638 
639 ```cpp
640 // connects a free function
641 registry.construction<Position>().connect<&MyFreeFunction>();
642 
643 // connects a member function
644 registry.construction<Position>().connect<MyClass, &MyClass::member>(&instance);
645 
646 // disconnects a free function
647 registry.construction<Position>().disconnect<&MyFreeFunction>();
648 
649 // disconnects a member function
650 registry.construction<Position>().disconnect<MyClass, &MyClass::member>(&instance);
651 ```
652 
653 To be notified when components are destroyed, use the `destruction` member
654 function instead.
655 
656 The function type of a listener is the same in both cases:
657 
658 ```cpp
659 void(Registry<Entity> &, Entity);
660 ```
661 
662 In other terms, a listener is provided with the registry that triggered the
663 notification and the entity affected by the change. Note also that:
664 
665 * Listeners are invoked **after** components have been assigned to entities.
666 * Listeners are invoked **before** components have been removed from entities.
667 * The order of invocation of the listeners isn't guaranteed in any case.
668 
669 There are also some limitations on what a listener can and cannot do. In
670 particular:
671 
672 * Connecting and disconnecting other functions from within the body of a
673  listener should be avoided. It can lead to undefined behavior in some cases.
674 * Assigning and removing components and tags from within the body of a listener
675  that observes the destruction of instances of a given type should be avoided.
676  It can lead to undefined behavior in some cases. This type of listeners is
677  intended to provide users with an easy way to perform cleanup and nothing
678  more.
679 
680 To a certain extent, these limitations do not apply. However, it is risky to try
681 to force them and users should respect the limitations unless they know exactly
682 what they are doing. Subtle bugs are the price to pay in case of errors
683 otherwise.
684 
685 In general, events and therefore listeners must not be used as replacements for
686 systems. They should not contain much logic and interactions with a registry
687 should be kept to a minimum, if possible. Note also that the greater the number
688 of listeners, the greater the performance hit when components are created or
689 destroyed.
690 
691 #### Who let the tags out?
692 
693 As an extension, signals are also provided with tags. Although they are not
694 strictly required internally, it makes sense that a user expects signal support
695 even when it comes to tags actually.<br/>
696 Signals for tags undergo exactly the same requirements of those introduced for
697 components. Also the function type for a listener is the same and it's invoked
698 with the same guarantees discussed above.
699 
700 To get the sinks for a tag just use tag `tag_t` to disambiguate overloads of
701 member functions as in the following example:
702 
703 ```cpp
704 registry.construction<MyTag>(entt::tag_t{}).connect<&MyFreeFunction>();
705 registry.destruction<MyTag>(entt::tag_t{}).connect<MyClass, &MyClass::member>(&instance);
706 ```
707 
708 Listeners for tags and components are managed separately and do not influence
709 each other in any case. Therefore, note that the greater the number of listeners
710 for a type, the greater the performance hit when a tag of the given type is
711 created or destroyed.
712 
713 ### Runtime components
714 
715 Defining components at runtime is useful to support plugin systems and mods in
716 general. However, it seems impossible with a tool designed around a bunch of
717 templates. Indeed it's not that difficult.<br/>
718 Of course, some features cannot be easily exported into a runtime
719 environment. As an example, sorting a group of components defined at runtime
720 isn't for free if compared to most of the other operations. However, the basic
721 functionalities of an entity-component system such as `EnTT` fit the problem
722 perfectly and can also be used to manage runtime components if required.<br/>
723 All that is necessary to do it is to know the identifiers of the components. An
724 identifier is nothing more than a number or similar that can be used at runtime
725 to work with the type system.
726 
727 In `EnTT`, identifiers are easily accessible:
728 
729 ```cpp
730 entt::DefaultRegistry registry;
731 
732 // standard component identifier
733 auto ctype = registry.component<Position>();
734 
735 // single instance component identifier
736 auto ttype = registry.tag<PlayingCharacter>();
737 ```
738 
739 Once the identifiers are made available, almost everything becomes pretty
740 simple.
741 
742 #### A journey through a plugin
743 
744 `EnTT` comes with an example (actually a test) that shows how to integrate
745 compile-time and runtime components in a stack based JavaScript environment. It
746 uses [`Duktape`](https://github.com/svaarala/duktape) under the hood, mainly
747 because I wanted to learn how it works at the time I was writing the code.
748 
749 The code is not production-ready and overall performance can be highly improved.
750 However, I sacrificed optimizations in favor of a more readable piece of code. I
751 hope I succeeded.<br/>
752 Note also that this isn't neither the only nor (probably) the best way to do it.
753 In fact, the right way depends on the scripting language and the problem one is
754 facing in general.<br/>
755 That being said, feel free to use it at your own risk.
756 
757 The basic idea is that of creating a compile-time component aimed to map all the
758 runtime components assigned to an entity.<br/>
759 Identifiers come in use to address the right function from a map when invoked
760 from the runtime environment and to filter entities when iterating.<br/>
761 With a bit of gymnastic, one can narrow views and improve the performance to
762 some extent but it was not the goal of the example.
763 
764 ### Sorting: is it possible?
765 
766 It goes without saying that sorting entities and components is possible with
767 `EnTT`.<br/>
768 In fact, there are two functions that respond to slightly different needs:
769 
770 * Components can be sorted directly:
771 
772  ```cpp
773  registry.sort<Renderable>([](const auto &lhs, const auto &rhs) {
774  return lhs.z < rhs.z;
775 
776  });
777  ```
778 
779  There exists also the possibility to use a custom sort function object, as
780  long as it adheres to the requirements described in the inline
781  documentation.<br/>
782  This is possible mainly because users can get much more with a custom sort
783  function object if the pattern of usage is known. As an example, in case of an
784  almost sorted pool, quick sort could be much, much slower than insertion sort.
785 
786 * Components can be sorted according to the order imposed by another component:
787 
788  ```cpp
789  registry.sort<Movement, Physics>();
790  ```
791 
792  In this case, instances of `Movement` are arranged in memory so that cache
793  misses are minimized when the two components are iterated together.
794 
795 ### Snapshot: complete vs continuous
796 
797 The `Registry` class offers basic support to serialization.<br/>
798 It doesn't convert components and tags to bytes directly, there wasn't the need
799 of another tool for serialization out there. Instead, it accepts an opaque
800 object with a suitable interface (namely an _archive_) to serialize its internal
801 data structures and restore them later. The way types and instances are
802 converted to a bunch of bytes is completely in charge to the archive and thus to
803 final users.
804 
805 The goal of the serialization part is to allow users to make both a dump of the
806 entire registry or a narrower snapshot, that is to select only the components
807 and the tags in which they are interested.<br/>
808 Intuitively, the use cases are different. As an example, the first approach is
809 suitable for local save/restore functionalities while the latter is suitable for
810 creating client-server applications and for transferring somehow parts of the
811 representation side to side.
812 
813 To take a snapshot of the registry, use the `snapshot` member function. It
814 returns a temporary object properly initialized to _save_ the whole registry or
815 parts of it.
816 
817 Example of use:
818 
819 ```cpp
820 OutputArchive output;
821 
822 registry.snapshot()
823  .entities(output)
824  .destroyed(output)
825  .component<AComponent, AnotherComponent>(output)
826  .tag<MyTag>(output);
827 ```
828 
829 It isn't necessary to invoke all these functions each and every time. What
830 functions to use in which case mostly depends on the goal and there is not a
831 golden rule to do that.
832 
833 The `entities` member function asks the registry to serialize all the entities
834 that are still in use along with their versions. On the other side, the
835 `destroyed` member function tells to the registry to serialize the entities that
836 have been destroyed and are no longer in use.<br/>
837 These two functions can be used to save and restore the whole set of entities
838 with the versions they had during serialization.
839 
840 The `component` member function is a function template the aim of which is to
841 store aside components. The presence of a template parameter list is a
842 consequence of a couple of design choices from the past and in the present:
843 
844 * First of all, there is no reason to force a user to serialize all the
845  components at once and most of the times it isn't desiderable. As an example,
846  in case the stuff for the HUD in a game is put into the registry for some
847  reasons, its components can be freely discarded during a serialization step
848  because probably the software already knows how to reconstruct the HUD
849  correctly from scratch.
850 
851 * Furthermore, the registry makes heavy use of _type-erasure_ techniques
852  internally and doesn't know at any time what types of components it contains.
853  Therefore being explicit at the call point is mandatory.
854 
855 There exists also another version of the `component` member function that
856 accepts a range of entities to serialize. This version is a bit slower than the
857 other one, mainly because it iterates the range of entities more than once for
858 internal purposes. However, it can be used to filter out those entities that
859 shouldn't be serialized for some reasons.<br/>
860 As an example:
861 
862 ```cpp
863 const auto view = registry.view<Serialize>();
864 OutputArchive output;
865 
866 registry.snapshot()
867  .component<AComponent, AnotherComponent>(output, view.cbegin(), view.cend());
868 ```
869 
870 The `tag` member function is similar to the previous one, apart from the fact
871 that it works with tags and not with components.<br/>
872 Note also that both `component` and `tag` store items along with entities. It
873 means that they work properly without a call to the `entities` member function.
874 
875 Once a snapshot is created, there exist mainly two _ways_ to load it: as a whole
876 and in a kind of _continuous mode_.<br/>
877 The following sections describe both loaders and archives in details.
878 
879 #### Snapshot loader
880 
881 A snapshot loader requires that the destination registry be empty and loads all
882 the data at once while keeping intact the identifiers that the entities
883 originally had.<br/>
884 To do that, the registry offers a member function named `restore` that returns a
885 temporary object properly initialized to _restore_ a snapshot.
886 
887 Example of use:
888 
889 ```cpp
890 InputArchive input;
891 
892 registry.restore()
893  .entities(input)
894  .destroyed(input)
895  .component<AComponent, AnotherComponent>(input)
896  .tag<MyTag>(input)
897  .orphans();
898 ```
899 
900 It isn't necessary to invoke all these functions each and every time. What
901 functions to use in which case mostly depends on the goal and there is not a
902 golden rule to do that. For obvious reasons, what is important is that the data
903 are restored in exactly the same order in which they were serialized.
904 
905 The `entities` and `destroyed` member functions restore the sets of entities and
906 the versions that the entities originally had at the source.
907 
908 The `component` member function restores all and only the components specified
909 and assigns them to the right entities. Note that the template parameter list
910 must be exactly the same used during the serialization. The same applies to the
911 `tag` member function.
912 
913 The `orphans` member function literally destroys those entities that have
914 neither components nor tags. It's usually useless if the snapshot is a full dump
915 of the source. However, in case all the entities are serialized but only few
916 components and tags are saved, it could happen that some of the entities have
917 neither components nor tags once restored. The best users can do to deal with
918 them is to destroy those entities and thus update their versions.
919 
920 #### Continuous loader
921 
922 A continuous loader is designed to load data from a source registry to a
923 (possibly) non-empty destination. The loader can accommodate in a registry more
924 than one snapshot in a sort of _continuous loading_ that updates the
925 destination one step at a time.<br/>
926 Identifiers that entities originally had are not transferred to the target.
927 Instead, the loader maps remote identifiers to local ones while restoring a
928 snapshot. Because of that, this kind of loader offers a way to update
929 automatically identifiers that are part of components or tags (as an example, as
930 data members or gathered in a container).<br/>
931 Another difference with the snapshot loader is that the continuous loader does
932 not need to work with the private data structures of a registry. Furthermore, it
933 has an internal state that must persist over time. Therefore, there is no reason
934 to create it by means of a registry, or to limit its lifetime to that of a
935 temporary object.
936 
937 Example of use:
938 
939 ```cpp
940 entt::ContinuousLoader<entity_type> loader{registry};
941 InputArchive input;
942 
943 loader.entities(input)
944  .destroyed(input)
945  .component<AComponent, AnotherComponent, DirtyComponent>(input, &DirtyComponent::parent, &DirtyComponent::child)
946  .tag<MyTag, DirtyTag>(input, &DirtyTag::container)
947  .orphans()
948  .shrink();
949 ```
950 
951 It isn't necessary to invoke all these functions each and every time. What
952 functions to use in which case mostly depends on the goal and there is not a
953 golden rule to do that. For obvious reasons, what is important is that the data
954 are restored in exactly the same order in which they were serialized.
955 
956 The `entities` and `destroyed` member functions restore groups of entities and
957 map each entity to a local counterpart when required. In other terms, for each
958 remote entity identifier not yet registered by the loader, the latter creates a
959 local identifier so that it can keep the local entity in sync with the remote
960 one.
961 
962 The `component` and `tag` member functions restore all and only the components
963 and the tags specified and assign them to the right entities.<br/>
964 In case the component or the tag contains entities itself (either as data
965 members of type `entity_type` or as containers of entities), the loader can
966 update them automatically. To do that, it's enough to specify the data members
967 to update as shown in the example.
968 
969 The `orphans` member function literally destroys those entities that have
970 neither components nor tags after a restore. It has exactly the same purpose
971 described in the previous section and works the same way.
972 
973 Finally, `shrink` helps to purge local entities that no longer have a remote
974 conterpart. Users should invoke this member function after restoring each
975 snapshot, unless they know exactly what they are doing.
976 
977 #### Archives
978 
979 Archives must publicly expose a predefined set of member functions. The API is
980 straightforward and consists only of a group of function call operators that
981 are invoked by the snapshot class and the loaders.
982 
983 In particular:
984 
985 * An output archive, the one used when creating a snapshot, must expose a
986  function call operator with the following signature to store entities:
987 
988  ```cpp
989  void operator()(Entity);
990  ```
991 
992  Where `Entity` is the type of the entities used by the registry. Note that all
993  the member functions of the snapshot class make also an initial call to this
994  endpoint to save the _size_ of the set they are going to store.<br/>
995  In addition, an archive must accept a pair of entity and either component or
996  tag for each type to be serialized. Therefore, given a type `T`, the archive
997  must contain a function call operator with the following signature:
998 
999  ```cpp
1000  void operator()(Entity, const T &);
1001  ```
1002 
1003  The output archive can freely decide how to serialize the data. The register
1004  is not affected at all by the decision.
1005 
1006 * An input archive, the one used when restoring a snapshot, must expose a
1007  function call operator with the following signature to load entities:
1008 
1009  ```cpp
1010  void operator()(Entity &);
1011  ```
1012 
1013  Where `Entity` is the type of the entities used by the registry. Each time the
1014  function is invoked, the archive must read the next element from the
1015  underlying storage and copy it in the given variable. Note that all the member
1016  functions of a loader class make also an initial call to this endpoint to read
1017  the _size_ of the set they are going to load.<br/>
1018  In addition, the archive must accept a pair of entity and either component or
1019  tag for each type to be restored. Therefore, given a type `T`, the archive
1020  must contain a function call operator with the following signature:
1021 
1022  ```cpp
1023  void operator()(Entity &, T &);
1024  ```
1025 
1026  Every time such an operator is invoked, the archive must read the next
1027  elements from the underlying storage and copy them in the given variables.
1028 
1029 #### One example to rule them all
1030 
1031 `EnTT` comes with some examples (actually some tests) that show how to integrate
1032 a well known library for serialization as an archive. It uses
1033 [`Cereal C++`](https://uscilab.github.io/cereal/) under the hood, mainly
1034 because I wanted to learn how it works at the time I was writing the code.
1035 
1036 The code is not production-ready and it isn't neither the only nor (probably)
1037 the best way to do it. However, feel free to use it at your own risk.
1038 
1039 The basic idea is to store everything in a group of queues in memory, then bring
1040 everything back to the registry with different loaders.
1041 
1042 ### Prototype
1043 
1044 A prototype defines a type of an application in terms of its parts. They can be
1045 used to assign components to entities of a registry at once.<br/>
1046 Roughly speaking, in most cases prototypes can be considered just as templates
1047 to use to initialize entities according to _concepts_. In fact, users can create
1048 how many prototypes they want, each one initialized differently from the others.
1049 
1050 The following is an example of use of a prototype:
1051 
1052 ```cpp
1053 entt::DefaultRegistry registry;
1054 entt::DefaultPrototype prototype{registry};
1055 
1056 prototype.set<Position>(100.f, 100.f);
1057 prototype.set<Velocity>(0.f, 0.f);
1058 
1059 // ...
1060 
1061 const auto entity = prototype();
1062 ```
1063 
1064 To assign and remove components from a prototype, it offers two dedicated member
1065 functions named `set` and `unset`. The `has` member function can be used to know
1066 if a given prototype contains one or more components and the `get` member
1067 function can be used to retrieve the components.
1068 
1069 Creating an entity from a prototype is straightforward:
1070 
1071 * To create a new entity from scratch and assign it a prototype, this is the way
1072  to go:
1073  ```cpp
1074  const auto entity = prototype();
1075  ```
1076  It is equivalent to the following invokation:
1077  ```cpp
1078  const auto entity = prototype.create();
1079  ```
1080 
1081 * In case we want to initialize an already existing entity, we can provide the
1082  `operator()` directly with the entity identifier:
1083  ```cpp
1084  prototype(entity);
1085  ```
1086  It is equivalent to the following invokation:
1087  ```cpp
1088  prototype.assign(entity);
1089  ```
1090  Note that existing components aren't overwritten in this case. Only those
1091  components that the entity doesn't own yet are copied over. All the other
1092  components remain unchanged.
1093 
1094 * Finally, to assign or replace all the components for an entity, thus
1095  overwriting existing ones:
1096  ```cpp
1097  prototype.accommodate(entity);
1098  ```
1099 
1100 In the examples above, the prototype uses its underlying registry to create
1101 entities and components both for its purposes and when it's cloned. To use a
1102 different repository to clone a prototype, all the member functions accept also
1103 a reference to a valid registry as a first argument.
1104 
1105 Prototypes are a very useful tool that can save a lot of typing sometimes.
1106 Furthermore, the codebase may be easier to maintain, since updating a prototype
1107 is much less error prone than jumping around in the codebase to update all the
1108 snippets copied and pasted around to initialize entities and components.
1109 
1110 ### Helpers
1111 
1112 The so called _helpers_ are small classes and functions mainly designed to offer
1113 built-in support for the most basic functionalities.<br/>
1114 The list of helpers will grow longer as time passes and new ideas come out.
1115 
1116 #### Dependency function
1117 
1118 A _dependency function_ is a predefined listener, actually a function template
1119 to use to automatically assign components to an entity when a type has a
1120 dependency on some other types.<br/>
1121 The following adds components `AType` and `AnotherType` whenever `MyType` is
1122 assigned to an entity:
1123 
1124 ```cpp
1125 entt::dependency<AType, AnotherType>(registry.construction<MyType>());
1126 ```
1127 
1128 A component is assigned to an entity and thus default initialized only in case
1129 the entity itself hasn't it yet. It means that already existent components won't
1130 be overriden.<br/>
1131 A dependency can easily be broken by means of the same function template:
1132 
1133 ```cpp
1134 entt::dependency<AType, AnotherType>(entt::break_t{}, registry.construction<MyType>());
1135 ```
1136 
1137 ### Null entity
1138 
1139 In `EnTT`, there exists a sort of _null entity_ made available to users that is
1140 accessible via the `entt::null` variable.<br/>
1141 The framework guarantees that the following expression always returns false:
1142 
1143 ```cpp
1144 registry.valid(entt::null);
1145 ```
1146 
1147 In other terms, a registry will reject the null entity in all cases because it
1148 isn't considered valid. It means that the null entity cannot own components or
1149 tags for obvious reasons.<br/>
1150 The type of the null entity is internal and should not be used for any purpose
1151 other than defining the null entity itself. However, there exist implicit
1152 conversions from the null entity to identifiers of any allowed type:
1153 
1154 ```cpp
1155 typename entt::DefaultRegistry::entity_type null = entt::null;
1156 ```
1157 
1158 Similarly, the null entity can be compared to any other identifier:
1159 
1160 ```cpp
1161 const auto entity = registry.create();
1162 const bool null = (entity == entt::null);
1163 ```
1164 
1165 ## View: to persist or not to persist?
1166 
1167 First of all, it is worth answering an obvious question: why views?<br/>
1168 Roughly speaking, they are a good tool to enforce single responsibility. A
1169 system that has access to a registry can create and destroy entities, as well as
1170 assign and remove components. On the other side, a system that has access to a
1171 view can only iterate entities and their components, then read or update the
1172 data members of the latter.<br/>
1173 It is a subtle difference that can help designing a better software sometimes.
1174 
1175 There are mainly four kinds of views: standard (also known as `View`),
1176 persistent (also known as `PersistentView`), raw (also known as `RawView`) and
1177 runtime (also known as `RuntimeView`).<br/>
1178 All of them have pros and cons to take in consideration. In particular:
1179 
1180 * Standard views:
1181 
1182  Pros:
1183 
1184  * They work out-of-the-box and don't require any dedicated data structure.
1185  * Creating and destroying them isn't expensive at all because they don't have
1186  any type of initialization.
1187  * They are the best tool for iterating entities for a single component.
1188  * They are the best tool for iterating entities for multiple components when
1189  one of the components is assigned to a significantly low number of entities.
1190  * They don't affect any other operations of the registry.
1191 
1192  Cons:
1193 
1194  * Their performance tend to degenerate when the number of components to
1195  iterate grows up and the most of the entities have all of them.
1196 
1197 * Persistent views:
1198 
1199  Pros:
1200 
1201  * Once prepared, creating and destroying them isn't expensive at all because
1202  they don't have any type of initialization.
1203  * They are the best tool for iterating entities for multiple components when
1204  most entities have them all.
1205 
1206  Cons:
1207 
1208  * They have dedicated data structures and thus affect the memory usage to a
1209  minimal extent.
1210  * If not previously prepared, the first time they are used they go through an
1211  initialization step that could take a while.
1212  * They affect to a minimum the creation and destruction of entities and
1213  components. In other terms: the more persistent views there will be, the
1214  less performing will be creating and destroying entities and components.
1215 
1216 * Raw views:
1217 
1218  Pros:
1219 
1220  * They work out-of-the-box and don't require any dedicated data structure.
1221  * Creating and destroying them isn't expensive at all because they don't have
1222  any type of initialization.
1223  * They are the best tool for iterating components when it is not necessary to
1224  know which entities they belong to.
1225  * They don't affect any other operations of the registry.
1226 
1227  Cons:
1228 
1229  * They can be used to iterate only one type of component at a time.
1230  * They don't return the entity to which a component belongs to the caller.
1231 
1232 * Runtime views:
1233 
1234  Pros:
1235 
1236  * Their lists of components are defined at runtime and not at compile-time.
1237  * Creating and destroying them isn't expensive at all because they don't have
1238  any type of initialization.
1239  * They are the best tool for things like plugin systems and mods in general.
1240  * They don't affect any other operations of the registry.
1241 
1242  Cons:
1243 
1244  * Their performances are definitely lower than those of all the other views,
1245  although they are still usable and sufficient for most of the purposes.
1246 
1247 To sum up and as a rule of thumb:
1248 
1249 * Use a raw view to iterate components only (no entities) for a given type.
1250 * Use a standard view to iterate entities and components for a single type.
1251 * Use a standard view to iterate entities and components for multiple types when
1252  the number of types is low. Standard views are really optimized and persistent
1253  views won't add much in this case.
1254 * Use a standard view to iterate entities and components for multiple types when
1255  a significantly low number of entities have one of the components.
1256 * Use a standard view in all those cases where a persistent view would give a
1257  boost to performance but the iteration isn't performed frequently.
1258 * Prepare and use a persistent view when you want to iterate only entities for
1259  multiple components.
1260 * Prepare and use a persistent view when you want to iterate entities for
1261  multiple components and each component is assigned to a great number of
1262  entities but the intersection between the sets of entities is small.
1263 * Prepare and use a persistent view in all the cases where a standard view
1264  wouldn't fit well otherwise.
1265 * Finally, in case you don't know at compile-time what are the components to
1266  use, choose a runtime view and set them during execution.
1267 
1268 To easily iterate entities and components, all the views offer the common
1269 `begin` and `end` member functions that allow users to use a view in a typical
1270 range-for loop. Almost all the views offer also a *more functional* `each`
1271 member function that accepts a callback for convenience.<br/>
1272 Continue reading for more details or refer to the inline documentation.
1273 
1274 ### Standard View
1275 
1276 A standard view behaves differently if it's constructed for a single component
1277 or if it has been requested to iterate multiple components. Even the API is
1278 different in the two cases.<br/>
1279 All that they share is the way they are created by means of a registry:
1280 
1281 ```cpp
1282 // single component standard view
1283 auto single = registry.view<Position>();
1284 
1285 // multi component standard view
1286 auto multi = registry.view<Position, Velocity>();
1287 ```
1288 
1289 For all that remains, it's worth discussing them separately.<br/>
1290 
1291 #### Single component standard view
1292 
1293 Single component standard views are specialized in order to give a boost in
1294 terms of performance in all the situation. This kind of views can access the
1295 underlying data structures directly and avoid superfluous checks.<br/>
1296 They offer a bunch of functionalities to get the number of entities they are
1297 going to return and a raw access to the entity list as well as to the component
1298 list. It's also possible to ask a view if it contains a given entity.<br/>
1299 Refer to the inline documentation for all the details.
1300 
1301 There is no need to store views around for they are extremely cheap to
1302 construct, even though they can be copied without problems and reused freely. In
1303 fact, they return newly created and correctly initialized iterators whenever
1304 `begin` or `end` are invoked.<br/>
1305 To iterate a single component standard view, either use it in a range-for loop:
1306 
1307 ```cpp
1308 auto view = registry.view<Renderable>();
1309 
1310 for(auto entity: view) {
1311  Renderable &renderable = view.get(entity);
1312 
1313  // ...
1314 }
1315 ```
1316 
1317 Or rely on the `each` member function to iterate entities and get all their
1318 components at once:
1319 
1320 ```cpp
1321 registry.view<Renderable>().each([](auto entity, auto &renderable) {
1322  // ...
1323 });
1324 ```
1325 
1326 The `each` member function is highly optimized. Unless users want to iterate
1327 only entities, using `each` should be the preferred approach.
1328 
1329 **Note**: prefer the `get` member function of a view instead of the `get` member
1330 function template of a registry during iterations, if possible. However, keep in
1331 mind that it works only with the components of the view itself.
1332 
1333 #### Multi component standard view
1334 
1335 Multi component standard views iterate entities that have at least all the given
1336 components in their bags. During construction, these views look at the number of
1337 entities available for each component and pick up a reference to the smallest
1338 set of candidates in order to speed up iterations.<br/>
1339 They offer fewer functionalities than their companion views for single
1340 component. In particular, a multi component standard view exposes utility
1341 functions to get the estimated number of entities it is going to return and to
1342 know whether it's empty or not. It's also possible to ask a view if it contains
1343 a given entity.<br/>
1344 Refer to the inline documentation for all the details.
1345 
1346 There is no need to store views around for they are extremely cheap to
1347 construct, even though they can be copied without problems and reused freely. In
1348 fact, they return newly created and correctly initialized iterators whenever
1349 `begin` or `end` are invoked.<br/>
1350 To iterate a multi component standard view, either use it in a range-for loop:
1351 
1352 ```cpp
1353 auto view = registry.view<Position, Velocity>();
1354 
1355 for(auto entity: view) {
1356  // a component at a time ...
1357  Position &position = view.get<Position>(entity);
1358  Velocity &velocity = view.get<Velocity>(entity);
1359 
1360  // ... or multiple components at once
1361  std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1362 
1363  // ...
1364 }
1365 ```
1366 
1367 Or rely on the `each` member function to iterate entities and get all their
1368 components at once:
1369 
1370 ```cpp
1371 registry.view<Position, Velocity>().each([](auto entity, auto &position, auto &velocity) {
1372  // ...
1373 });
1374 ```
1375 
1376 The `each` member function is highly optimized. Unless users want to iterate
1377 only entities or get only some of the components, using `each` should be the
1378 preferred approach.
1379 
1380 **Note**: prefer the `get` member function of a view instead of the `get` member
1381 function template of a registry during iterations, if possible. However, keep in
1382 mind that it works only with the components of the view itself.
1383 
1384 ### Persistent View
1385 
1386 A persistent view returns all the entities and only the entities that have at
1387 least the given components. Moreover, it's guaranteed that the entity list is
1388 tightly packed in memory for fast iterations.<br/>
1389 In general, persistent views don't stay true to the order of any set of
1390 components unless users explicitly sort them.
1391 
1392 Persistent views can be used only to iterate multiple components. To create this
1393 kind of views, the tag `persistent_t` must also be used in order to disambiguate
1394 overloads of the `view` member function:
1395 
1396 ```cpp
1397 auto view = registry.view<Position, Velocity>(entt::persistent_t{});
1398 ```
1399 
1400 There is no need to store views around for they are extremely cheap to
1401 construct, even though they can be copied without problems and reused freely. In
1402 fact, they return newly created and correctly initialized iterators whenever
1403 `begin` or `end` are invoked.<br/>
1404 That being said, persistent views perform an initialization step the very first
1405 time they are constructed and this could be quite costly. To avoid it, consider
1406 asking to the registry to _prepare_ them when no entities have been created yet:
1407 
1408 ```cpp
1409 registry.prepare<Position, Velocity>();
1410 ```
1411 
1412 If the registry is empty, preparation is extremely fast. Moreover the `prepare`
1413 member function template is idempotent. Feel free to invoke it even more than
1414 once: if the view has been already prepared before, the function returns
1415 immediately and does nothing.
1416 
1417 A persistent view offers a bunch of functionalities to get the number of
1418 entities it's going to return, a raw access to the entity list and the
1419 possibility to sort the underlying data structures according to the order of one
1420 of the components for which it has been constructed. It's also possible to ask a
1421 view if it contains a given entity.<br/>
1422 Refer to the inline documentation for all the details.
1423 
1424 To iterate a persistent view, either use it in a range-for loop:
1425 
1426 ```cpp
1427 auto view = registry.view<Position, Velocity>(entt::persistent_t{});
1428 
1429 for(auto entity: view) {
1430  // a component at a time ...
1431  Position &position = view.get<Position>(entity);
1432  Velocity &velocity = view.get<Velocity>(entity);
1433 
1434  // ... or multiple components at once
1435  std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1436 
1437  // ...
1438 }
1439 ```
1440 
1441 Or rely on the `each` member function to iterate entities and get all their
1442 components at once:
1443 
1444 ```cpp
1445 registry.view<Position, Velocity>(entt::persistent_t{}).each([](auto entity, auto &position, auto &velocity) {
1446  // ...
1447 });
1448 ```
1449 
1450 Performance are more or less the same. The best approach depends mainly on
1451 whether all the components have to be accessed or not.
1452 
1453 **Note**: prefer the `get` member function of a view instead of the `get` member
1454 function template of a registry during iterations, if possible. However, keep in
1455 mind that it works only with the components of the view itself.
1456 
1457 ### Raw View
1458 
1459 Raw views return all the components of a given type. This kind of views can
1460 access components directly and avoid extra indirections like when components are
1461 accessed via an entity identifier.<br/>
1462 They offer a bunch of functionalities to get the number of instances they are
1463 going to return and a raw access to the entity list as well as to the component
1464 list.<br/>
1465 Refer to the inline documentation for all the details.
1466 
1467 Raw views can be used only to iterate components for a single type. To create
1468 this kind of views, the tag `raw_t` must also be used in order to disambiguate
1469 overloads of the `view` member function:
1470 
1471 ```cpp
1472 auto view = registry.view<Renderable>(entt::raw_t{});
1473 ```
1474 
1475 There is no need to store views around for they are extremely cheap to
1476 construct, even though they can be copied without problems and reused freely. In
1477 fact, they return newly created and correctly initialized iterators whenever
1478 `begin` or `end` are invoked.<br/>
1479 To iterate a raw view, use it in a range-for loop:
1480 
1481 ```cpp
1482 auto view = registry.view<Renderable>(entt::raw_t{});
1483 
1484 for(auto &&component: raw) {
1485  // ...
1486 }
1487 ```
1488 
1489 Or rely on the `each` member function:
1490 
1491 ```cpp
1492 registry.view<Renderable>(entt::raw_t{}).each([](auto &renderable) {
1493  // ...
1494 });
1495 ```
1496 
1497 Performance are exactly the same in both cases.
1498 
1499 **Note**: raw views don't have a `get` member function for obvious reasons.
1500 
1501 ### Runtime View
1502 
1503 Runtime views iterate entities that have at least all the given components in
1504 their bags. During construction, these views look at the number of entities
1505 available for each component and pick up a reference to the smallest
1506 set of candidates in order to speed up iterations.<br/>
1507 They offer more or less the same functionalities of a multi component standard
1508 view. However, they don't expose a `get` member function and users should refer
1509 to the registry that generated the view to access components. In particular, a
1510 runtime view exposes utility functions to get the estimated number of entities
1511 it is going to return and to know whether it's empty or not. It's also possible
1512 to ask a view if it contains a given entity.<br/>
1513 Refer to the inline documentation for all the details.
1514 
1515 Runtime view are extremely cheap to construct and should not be stored around in
1516 any case. They should be used immediately after creation and then they should be
1517 thrown away. The reasons for this go far beyond the scope of this document.<br/>
1518 To iterate a runtime view, either use it in a range-for loop:
1519 
1520 ```cpp
1521 using component_type = typename decltype(registry)::component_type;
1522 component_type types[] = { registry.type<Position>(), registry.type<Velocity>() };
1523 
1524 auto view = registry.view(std::cbegin(types), std::cend(types));
1525 
1526 for(auto entity: view) {
1527  // a component at a time ...
1528  Position &position = registry.get<Position>(entity);
1529  Velocity &velocity = registry.get<Velocity>(entity);
1530 
1531  // ... or multiple components at once
1532  std::tuple<Position &, Velocity &> tup = view.get<Position, Velocity>(entity);
1533 
1534  // ...
1535 }
1536 ```
1537 
1538 Or rely on the `each` member function to iterate entities:
1539 
1540 ```cpp
1541 using component_type = typename decltype(registry)::component_type;
1542 component_type types[] = { registry.type<Position>(), registry.type<Velocity>() };
1543 
1544 auto view = registry.view(std::cbegin(types), std::cend(types)).each([](auto entity) {
1545  // ...
1546 });
1547 ```
1548 
1549 Performance are exactly the same in both cases.
1550 
1551 **Note**: runtime views are meant for all those cases where users don't know at
1552 compile-time what components to use to iterate entities. This is particularly
1553 well suited to plugin systems and mods in general. Where possible, don't use
1554 runtime views, as their performance are slightly inferior to those of the other
1555 views.
1556 
1557 
1558 ### Give me everything
1559 
1560 Views are narrow windows on the entire list of entities. They work by filtering
1561 entities according to their components.<br/>
1562 In some cases there may be the need to iterate all the entities still in use
1563 regardless of their components. The registry offers a specific member function
1564 to do that:
1565 
1566 ```cpp
1567 registry.each([](auto entity) {
1568  // ...
1569 });
1570 ```
1571 
1572 It returns to the caller all the entities that are still in use by means of the
1573 given function.<br/>
1574 As a rule of thumb, consider using a view if the goal is to iterate entities
1575 that have a determinate set of components. A view is usually much faster than
1576 combining this function with a bunch of custom tests.<br/>
1577 In all the other cases, this is the way to go.
1578 
1579 There exists also another member function to use to retrieve orphans. An orphan
1580 is an entity that is still in use and has neither assigned components nor
1581 tags.<br/>
1582 The signature of the function is the same of `each`:
1583 
1584 ```cpp
1585 registry.orphans([](auto entity) {
1586  // ...
1587 });
1588 ```
1589 
1590 To test the _orphanity_ of a single entity, use the member function `orphan`
1591 instead. It accepts a valid entity identifer as an argument and returns true in
1592 case the entity is an orphan, false otherwise.
1593 
1594 In general, all these functions can result in poor performance.<br/>
1595 `each` is fairly slow because of some checks it performs on each and every
1596 entity. For similar reasons, `orphans` can be even slower. Both functions should
1597 not be used frequently to avoid the risk of a performance hit.
1598 
1599 ## Iterations: what is allowed and what is not
1600 
1601 Most of the _ECS_ available out there have some annoying limitations (at least
1602 from my point of view): entities and components cannot be created nor destroyed
1603 during iterations.<br/>
1604 `EnTT` partially solves the problem with a few limitations:
1605 
1606 * Creating entities and components is allowed during iterations.
1607 * Deleting an entity or removing its components is allowed during iterations if
1608  it's the one currently returned by the view. For all the other entities,
1609  destroying them or removing their components isn't allowed and it can result
1610  in undefined behavior.
1611 
1612 Iterators are invalidated and the behavior is undefined if an entity is modified
1613 or destroyed and it's not the one currently returned by the view nor a newly
1614 created one.<br/>
1615 To work around it, possible approaches are:
1616 
1617 * Store aside the entities and the components to be removed and perform the
1618  operations at the end of the iteration.
1619 * Mark entities and components with a proper tag component that indicates they
1620  must be purged, then perform a second iteration to clean them up one by one.
1621 
1622 A notable side effect of this feature is that the number of required allocations
1623 is further reduced in most of the cases.
1624 
1625 ## Multithreading
1626 
1627 In general, the entire registry isn't thread safe as it is. Thread safety isn't
1628 something that users should want out of the box for several reasons. Just to
1629 mention one of them: performance.<br/>
1630 Views and consequently the approach adopted by `EnTT` are the great exception to
1631 the rule. It's true that views and thus their iterators aren't thread safe by
1632 themselves. Because of this users shouldn't try to iterate a set of components
1633 and modify the same set concurrently. However:
1634 
1635 * As long as a thread iterates the entities that have the component `X` or
1636  assign and removes that component from a set of entities, another thread can
1637  safely do the same with components `Y` and `Z` and everything will work like a
1638  charm. As a trivial example, users can freely execute the rendering system and
1639  iterate the renderable entities while updating a physic component concurrently
1640  on a separate thread.
1641 
1642 * Similarly, a single set of components can be iterated by multiple threads as
1643  long as the components are neither assigned nor removed in the meantime. In
1644  other words, a hypothetical movement system can start multiple threads, each
1645  of which will access the components that carry information about velocity and
1646  position for its entities.
1647 
1648 This kind of entity-component systems can be used in single threaded
1649 applications as well as along with async stuff or multiple threads. Moreover,
1650 typical thread based models for _ECS_ don't require a fully thread safe registry
1651 to work. Actually, users can reach the goal with the registry as it is while
1652 working with most of the common models.
1653 
1654 Because of the few reasons mentioned above and many others not mentioned, users
1655 are completely responsible for synchronization whether required. On the other
1656 hand, they could get away with it without having to resort to particular
1657 expedients.
1658 
1659 # Crash Course: core functionalities
1660 
1661 The `EnTT` framework comes with a bunch of core functionalities mostly used by
1662 the other parts of the library itself.<br/>
1663 Hardly users of the framework will include these features in their code, but
1664 it's worth describing what `EnTT` offers so as not to reinvent the wheel in case
1665 of need.
1666 
1667 ## Compile-time identifiers
1668 
1669 Sometimes it's useful to be able to give unique identifiers to types at
1670 compile-time.<br/>
1671 There are plenty of different solutions out there and I could have used one of
1672 them. However, I decided to spend my time to define a compact and versatile tool
1673 that fully embraces what the modern C++ has to offer.
1674 
1675 The _result of my efforts_ is the `Identifier` class template:
1676 
1677 ```cpp
1678 #include <ident.hpp>
1679 
1680 // defines the identifiers for the given types
1681 using ID = entt::Identifier<AType, AnotherType>;
1682 
1683 // ...
1684 
1685 switch(aTypeIdentifier) {
1686 case ID::get<AType>():
1687  // ...
1688  break;
1689 case ID::get<AnotherType>():
1690  // ...
1691  break;
1692 default:
1693  // ...
1694 }
1695 ```
1696 
1697 This is all what the class template has to offer: a static `get` member function
1698 that returns a numerical identifier for the given type. It can be used in any
1699 context where constant expressions are required.
1700 
1701 As long as the list remains unchanged, identifiers are also guaranteed to be the
1702 same for every run. In case they have been used in a production environment and
1703 a type has to be removed, one can just use a placeholder to left the other
1704 identifiers unchanged:
1705 
1706 ```cpp
1707 template<typename> struct IgnoreType {};
1708 
1709 using ID = entt::Identifier<
1710  ATypeStillValid,
1711  IgnoreType<ATypeNoLongerValid>,
1712  AnotherTypeStillValid
1713 >;
1714 ```
1715 
1716 A bit ugly to see, but it works at least.
1717 
1718 ## Runtime identifiers
1719 
1720 Sometimes it's useful to be able to give unique identifiers to types at
1721 runtime.<br/>
1722 There are plenty of different solutions out there and I could have used one of
1723 them. In fact, I adapted the most common one to my requirements and used it
1724 extensively within the entire framework.
1725 
1726 It's the `Family` class. Here is an example of use directly from the
1727 entity-component system:
1728 
1729 ```cpp
1730 using component_family = entt::Family<struct InternalRegistryComponentFamily>;
1731 
1732 // ...
1733 
1734 template<typename Component>
1735 component_type component() const noexcept {
1736  return component_family::type<Component>();
1737 }
1738 ```
1739 
1740 This is all what a _family_ has to offer: a `type` member function that returns
1741 a numerical identifier for the given type.
1742 
1743 Please, note that identifiers aren't guaranteed to be the same for every run.
1744 Indeed it mostly depends on the flow of execution.
1745 
1746 ## Hashed strings
1747 
1748 A hashed string is a zero overhead resource identifier. Users can use
1749 human-readable identifiers in the codebase while using their numeric
1750 counterparts at runtime, thus without affecting performance.<br/>
1751 The class has an implicit `constexpr` constructor that chews a bunch of
1752 characters. Once created, all what one can do with it is getting back the
1753 original string or converting it into a number.<br/>
1754 The good part is that a hashed string can be used wherever a constant expression
1755 is required and no _string-to-number_ conversion will take place at runtime if
1756 used carefully.
1757 
1758 Example of use:
1759 
1760 ```cpp
1761 auto load(entt::HashedString::hash_type resource) {
1762  // uses the numeric representation of the resource to load and return it
1763 }
1764 
1765 auto resource = load(entt::HashedString{"gui/background"});
1766 ```
1767 
1768 ### Conflicts
1769 
1770 The hashed string class uses internally FNV-1a to compute the numeric
1771 counterpart of a string. Because of the _pigeonhole principle_, conflicts are
1772 possible. This is a fact.<br/>
1773 There is no silver bullet to solve the problem of conflicts when dealing with
1774 hashing functions. In this case, the best solution seemed to be to give up.
1775 That's all.<br/>
1776 After all, human-readable resource identifiers aren't something strictly defined
1777 and over which users have not the control. Choosing a slightly different
1778 identifier is probably the best solution to make the conflict disappear in this
1779 case.
1780 
1781 ## Monostate
1782 
1783 The monostate pattern is often presented as an alternative to a singleton based
1784 configuration system. This is exactly its purpose in `EnTT`. Moreover, this
1785 implementation is thread safe by design (hopefully).<br/>
1786 Keys are represented by hashed strings, values are basic types like `int`s or
1787 `bool`s. Values of different types can be associated to each key, even more than
1788 one at a time. Because of this, users must pay attention to use the same type
1789 both during an assignment and when they try to read back their data. Otherwise,
1790 they will probably incur in unexpected results.
1791 
1792 Example of use:
1793 
1794 ```cpp
1795 entt::Monostate<entt::HashedString{"mykey"}>{} = true;
1796 entt::Monostate<"mykey"_hs>{} = 42;
1797 
1798 // ...
1799 
1800 const bool b = entt::Monostate<"mykey"_hs>{};
1801 const int i = entt::Monostate<entt::HashedString{"mykey"}>{};
1802 ```
1803 
1804 # Crash Course: service locator
1805 
1806 Usually service locators are tightly bound to the services they expose and it's
1807 hard to define a general purpose solution. This template based implementation
1808 tries to fill the gap and to get rid of the burden of defining a different
1809 specific locator for each application.<br/>
1810 This class is tiny, partially unsafe and thus risky to use. Moreover it doesn't
1811 fit probably most of the scenarios in which a service locator is required. Look
1812 at it as a small tool that can sometimes be useful if the user knows how to
1813 handle it.
1814 
1815 The API is straightforward. The basic idea is that services are implemented by
1816 means of interfaces and rely on polymorphism.<br/>
1817 The locator is instantiated with the base type of the service if any and a
1818 concrete implementation is provided along with all the parameters required to
1819 initialize it. As an example:
1820 
1821 ```cpp
1822 // the service has no base type, a locator is used to treat it as a kind of singleton
1823 entt::ServiceLocator<MyService>::set(params...);
1824 
1825 // sets up an opaque service
1826 entt::ServiceLocator<AudioInterface>::set<AudioImplementation>(params...);
1827 
1828 // resets (destroys) the service
1829 entt::ServiceLocator<AudioInterface>::reset();
1830 ```
1831 
1832 The locator can also be queried to know if an active service is currently set
1833 and to retrieve it if necessary (either as a pointer or as a reference):
1834 
1835 ```cpp
1836 // no service currently set
1837 auto empty = entt::ServiceLocator<AudioInterface>::empty();
1838 
1839 // gets a (possibly empty) shared pointer to the service ...
1840 std::shared_ptr<AudioInterface> ptr = entt::ServiceLocator<AudioInterface>::get();
1841 
1842 // ... or a reference, but it's undefined behaviour if the service isn't set yet
1843 AudioInterface &ref = entt::ServiceLocator<AudioInterface>::ref();
1844 ```
1845 
1846 A common use is to wrap the different locators in a container class, creating
1847 aliases for the various services:
1848 
1849 ```cpp
1850 struct Locator {
1851  using Camera = entt::ServiceLocator<CameraInterface>;
1852  using Audio = entt::ServiceLocator<AudioInterface>;
1853  // ...
1854 };
1855 
1856 // ...
1857 
1858 void init() {
1859  Locator::Camera::set<CameraNull>();
1860  Locator::Audio::set<AudioImplementation>(params...);
1861  // ...
1862 }
1863 ```
1864 
1865 # Crash Course: cooperative scheduler
1866 
1867 Sometimes processes are a useful tool to work around the strict definition of a
1868 system and introduce logic in a different way, usually without resorting to the
1869 introduction of other components.
1870 
1871 The `EnTT` framework offers a minimal support to this paradigm by introducing a
1872 few classes that users can use to define and execute cooperative processes.
1873 
1874 ## The process
1875 
1876 A typical process must inherit from the `Process` class template that stays true
1877 to the CRTP idiom. Moreover, derived classes must specify what's the intended
1878 type for elapsed times.
1879 
1880 A process should expose publicly the following member functions whether
1881 required (note that it isn't required to define a function unless the derived
1882 class wants to _override_ the default behavior):
1883 
1884 * `void update(Delta, void *);`
1885 
1886  It's invoked once per tick until a process is explicitly aborted or it
1887  terminates either with or without errors. Even though it's not mandatory to
1888  declare this member function, as a rule of thumb each process should at
1889  least define it to work properly. The `void *` parameter is an opaque pointer
1890  to user data (if any) forwarded directly to the process during an update.
1891 
1892 * `void init(void *);`
1893 
1894  It's invoked at the first tick, immediately before an update. The `void *`
1895  parameter is an opaque pointer to user data (if any) forwarded directly to the
1896  process during an update.
1897 
1898 * `void succeeded();`
1899 
1900  It's invoked in case of success, immediately after an update and during the
1901  same tick.
1902 
1903 * `void failed();`
1904 
1905  It's invoked in case of errors, immediately after an update and during the
1906  same tick.
1907 
1908 * `void aborted();`
1909 
1910  It's invoked only if a process is explicitly aborted. There is no guarantee
1911  that it executes in the same tick, this depends solely on whether the
1912  process is aborted immediately or not.
1913 
1914 Derived classes can also change the internal state of a process by invoking
1915 `succeed` and `fail`, as well as `pause` and `unpause` the process itself. All
1916 these are protected member functions made available to be able to manage the
1917 life cycle of a process from a derived class.
1918 
1919 Here is a minimal example for the sake of curiosity:
1920 
1921 ```cpp
1922 struct MyProcess: entt::Process<MyProcess, std::uint32_t> {
1923  using delta_type = std::uint32_t;
1924 
1925  void update(delta_type delta, void *) {
1926  remaining = delta > remaining ? delta_type{] : (remaining - delta);
1927 
1928  // ...
1929 
1930  if(!remaining) {
1931  succeed();
1932  }
1933  }
1934 
1935  void init(void *data) {
1936  remaining = *static_cast<delta_type *>(data);
1937  }
1938 
1939 private:
1940  delta_type remaining;
1941 };
1942 ```
1943 
1944 ### Adaptor
1945 
1946 Lambdas and functors can't be used directly with a scheduler for they are not
1947 properly defined processes with managed life cycles.<br/>
1948 This class helps in filling the gap and turning lambdas and functors into
1949 full featured processes usable by a scheduler.
1950 
1951 The function call operator has a signature similar to the one of the `update`
1952 function of a process but for the fact that it receives two extra arguments to
1953 call whenever a process is terminated with success or with an error:
1954 
1955 ```cpp
1956 void(Delta delta, void *data, auto succeed, auto fail);
1957 ```
1958 
1959 Parameters have the following meaning:
1960 
1961 * `delta` is the elapsed time.
1962 * `data` is an opaque pointer to user data if any, `nullptr` otherwise.
1963 * `succeed` is a function to call when a process terminates with success.
1964 * `fail` is a function to call when a process terminates with errors.
1965 
1966 Both `succeed` and `fail` accept no parameters at all.
1967 
1968 Note that usually users shouldn't worry about creating adaptors at all. A
1969 scheduler creates them internally each and every time a lambda or a functor is
1970 used as a process.
1971 
1972 ## The scheduler
1973 
1974 A cooperative scheduler runs different processes and helps managing their life
1975 cycles.
1976 
1977 Each process is invoked once per tick. If it terminates, it's removed
1978 automatically from the scheduler and it's never invoked again. Otherwise it's
1979 a good candidate to run once more the next tick.<br/>
1980 A process can also have a child. In this case, the process is replaced with
1981 its child when it terminates if it returns with success. In case of errors,
1982 both the process and its child are discarded. This way, it's easy to create
1983 chain of processes to run sequentially.
1984 
1985 Using a scheduler is straightforward. To create it, users must provide only the
1986 type for the elapsed times and no arguments at all:
1987 
1988 ```cpp
1989 Scheduler<std::uint32_t> scheduler;
1990 ```
1991 
1992 It has member functions to query its internal data structures, like `empty` or
1993 `size`, as well as a `clear` utility to reset it to a clean state:
1994 
1995 ```cpp
1996 // checks if there are processes still running
1997 const auto empty = scheduler.empty();
1998 
1999 // gets the number of processes still running
2000 Scheduler<std::uint32_t>::size_type size = scheduler.size();
2001 
2002 // resets the scheduler to its initial state and discards all the processes
2003 scheduler.clear();
2004 ```
2005 
2006 To attach a process to a scheduler there are mainly two ways:
2007 
2008 * If the process inherits from the `Process` class template, it's enough to
2009  indicate its type and submit all the parameters required to construct it to
2010  the `attach` member function:
2011 
2012  ```cpp
2013  scheduler.attach<MyProcess>("foobar");
2014  ```
2015 
2016 * Otherwise, in case of a lambda or a functor, it's enough to provide an
2017  instance of the class to the `attach` member function:
2018 
2019  ```cpp
2020  scheduler.attach([](auto...){ /* ... */ });
2021  ```
2022 
2023 In both cases, the return value is an opaque object that offers a `then` member
2024 function to use to create chains of processes to run sequentially.<br/>
2025 As a minimal example of use:
2026 
2027 ```cpp
2028 // schedules a task in the form of a lambda function
2029 scheduler.attach([](auto delta, void *, auto succeed, auto fail) {
2030  // ...
2031 })
2032 // appends a child in the form of another lambda function
2033 .then([](auto delta, void *, auto succeed, auto fail) {
2034  // ...
2035 })
2036 // appends a child in the form of a process class
2037 .then<MyProcess>();
2038 ```
2039 
2040 To update a scheduler and thus all its processes, the `update` member function
2041 is the way to go:
2042 
2043 ```cpp
2044 // updates all the processes, no user data are provided
2045 scheduler.update(delta);
2046 
2047 // updates all the processes and provides them with custom data
2048 scheduler.update(delta, &data);
2049 ```
2050 
2051 In addition to these functions, the scheduler offers an `abort` member function
2052 that can be used to discard all the running processes at once:
2053 
2054 ```cpp
2055 // aborts all the processes abruptly ...
2056 scheduler.abort(true);
2057 
2058 // ... or gracefully during the next tick
2059 scheduler.abort();
2060 ```
2061 
2062 # Crash Course: resource management
2063 
2064 Resource management is usually one of the most critical part of a software like
2065 a game. Solutions are often tuned to the particular application. There exist
2066 several approaches and all of them are perfectly fine as long as they fit the
2067 requirements of the piece of software in which they are used.<br/>
2068 Examples are loading everything on start, loading on request, predictive
2069 loading, and so on.
2070 
2071 The `EnTT` framework doesn't pretend to offer a _one-fits-all_ solution for the
2072 different cases. Instead, it offers a minimal and perhaps trivial cache that can
2073 be useful most of the time during prototyping and sometimes even in a production
2074 environment.<br/>
2075 For those interested in the subject, the plan is to improve it considerably over
2076 time in terms of performance, memory usage and functionalities. Hoping to make
2077 it, of course, one step at a time.
2078 
2079 ## The resource, the loader and the cache
2080 
2081 There are three main actors in the model: the resource, the loader and the
2082 cache.
2083 
2084 The _resource_ is whatever the user wants it to be. An image, a video, an audio,
2085 whatever. There are no limits.<br/>
2086 As a minimal example:
2087 
2088 ```cpp
2089 struct MyResource { const int value; };
2090 ```
2091 
2092 A _loader_ is a class the aim of which is to load a specific resource. It has to
2093 inherit directly from the dedicated base class as in the following example:
2094 
2095 ```cpp
2096 struct MyLoader final: entt::ResourceLoader<MyLoader, MyResource> {
2097  // ...
2098 };
2099 ```
2100 
2101 Where `MyResource` is the type of resources it creates.<br/>
2102 A resource loader must also expose a public const member function named `load`
2103 that accepts a variable number of arguments and returns a shared pointer to a
2104 resource.<br/>
2105 As an example:
2106 
2107 ```cpp
2108 struct MyLoader: entt::ResourceLoader<MyLoader, MyResource> {
2109  std::shared_ptr<MyResource> load(int value) const {
2110  // ...
2111  return std::shared_ptr<MyResource>(new MyResource{ value });
2112  }
2113 };
2114 ```
2115 
2116 In general, resource loaders should not have a state or retain data of any type.
2117 They should let the cache manage their resources instead.<br/>
2118 As a side note, base class and CRTP idiom aren't strictly required with the
2119 current implementation. One could argue that a cache can easily work with
2120 loaders of any type. However, future changes won't be breaking ones by forcing
2121 the use of a base class today and that's why the model is already in its place.
2122 
2123 Finally, a cache is a specialization of a class template tailored to a specific
2124 resource:
2125 
2126 ```cpp
2127 using MyResourceCache = entt::ResourceCache<MyResource>;
2128 
2129 // ...
2130 
2131 MyResourceCache cache{};
2132 ```
2133 
2134 The idea is to create different caches for different types of resources and to
2135 manage each one independently and in the most appropriate way.<br/>
2136 As a (very) trivial example, audio tracks can survive in most of the scenes of
2137 an application while meshes can be associated with a single scene and then
2138 discarded when the user leaves it.
2139 
2140 A cache offers a set of basic functionalities to query its internal state and to
2141 _organize_ it:
2142 
2143 ```cpp
2144 // gets the number of resources managed by a cache
2145 const auto size = cache.size();
2146 
2147 // checks if a cache contains at least a valid resource
2148 const auto empty = cache.empty();
2149 
2150 // clears a cache and discards its content
2151 cache.clear();
2152 ```
2153 
2154 Besides these member functions, it contains what is needed to load, use and
2155 discard resources of the given type.<br/>
2156 Before to explore this part of the interface, it makes sense to mention how
2157 resources are identified. The type of the identifiers to use is defined as:
2158 
2159 ```cpp
2160 entt::ResourceCache<Resource>::resource_type
2161 ```
2162 
2163 Where `resource_type` is an alias for `entt::HashedString`. Therefore, resource
2164 identifiers are created explicitly as in the following example:
2165 
2166 ```cpp
2167 constexpr auto identifier = entt::ResourceCache<Resource>::resource_type{"my/resource/identifier"};
2168 // this is equivalent to the following
2169 constexpr auto hs = entt::HashedString{"my/resource/identifier"};
2170 ```
2171 
2172 The class `HashedString` is described in a dedicated section, so I won't do in
2173 details here.
2174 
2175 Resources are loaded and thus stored in a cache through the `load` member
2176 function. It accepts the loader to use as a template parameter, the resource
2177 identifier and the parameters used to construct the resource as arguments:
2178 
2179 ```cpp
2180 // uses the identifier declared above
2181 cache.load<MyLoader>(identifier, 0);
2182 
2183 // uses a const char * directly as an identifier
2184 cache.load<MyLoader>("another/identifier", 42);
2185 ```
2186 
2187 The return value can be used to know if the resource has been loaded correctly.
2188 In case the loader returns an invalid pointer or the resource already exists in
2189 the cache, a false value is returned:
2190 
2191 ```cpp
2192 if(!cache.load<MyLoader>("another/identifier", 42)) {
2193  // ...
2194 }
2195 ```
2196 
2197 Unfortunately, in this case there is no way to know what was the problem
2198 exactly. However, before trying to load a resource or after an error, one can
2199 use the `contains` member function to know if a cache already contains a
2200 specific resource:
2201 
2202 ```cpp
2203 auto exists = cache.contains("my/identifier");
2204 ```
2205 
2206 There exists also a member function to use to force a reload of an already
2207 existing resource if needed:
2208 
2209 ```cpp
2210 auto result = cache.reload<MyLoader>("another/identifier", 42);
2211 ```
2212 
2213 As above, the function returns true in case of success, false otherwise. The
2214 sole difference in this case is that an error necessarily means that the loader
2215 has failed for some reasons to load the resource.<br/>
2216 Note that the `reload` member function is a kind of alias of the following
2217 snippet:
2218 
2219 ```cpp
2220 cache.discard(identifier);
2221 cache.load<MyLoader>(identifier, 42);
2222 ```
2223 
2224 Where the `discard` member function is used to get rid of a resource if loaded.
2225 In case the cache doesn't contain a resource for the given identifier, the
2226 function does nothing and returns immediately.
2227 
2228 So far, so good. Resources are finally loaded and stored within the cache.<br/>
2229 They are returned to users in the form of handles. To get one of them:
2230 
2231 ```cpp
2232 auto handle = cache.handle("my/identifier");
2233 ```
2234 
2235 The idea behind a handle is the same of the flyweight pattern. In other terms,
2236 resources aren't copied around. Instead, instances are shared between handles.
2237 Users of a resource owns a handle and it guarantees that a resource isn't
2238 destroyed until all the handles are destroyed, even if the resource itself is
2239 removed from the cache.<br/>
2240 Handles are tiny objects both movable and copyable. They returns the contained
2241 resource as a const reference on request:
2242 
2243 * By means of the `get` member function:
2244 
2245  ```cpp
2246  const auto &resource = handle.get();
2247  ```
2248 
2249 * Using the proper cast operator:
2250 
2251  ```cpp
2252  const auto &resource = handle;
2253  ```
2254 
2255 * Through the dereference operator:
2256 
2257  ```cpp
2258  const auto &resource = *handle;
2259  ```
2260 
2261 The resource can also be accessed directly using the arrow operator if required:
2262 
2263 ```cpp
2264 auto value = handle->value;
2265 ```
2266 
2267 To test if a handle is still valid, the cast operator to `bool` allows users to
2268 use it in a guard:
2269 
2270 ```cpp
2271 if(handle) {
2272  // ...
2273 }
2274 ```
2275 
2276 Finally, in case there is the need to load a resource and thus to get a handle
2277 without storing the resource itself in the cache, users can rely on the `temp`
2278 member function template.<br/>
2279 The declaration is similar to the one of `load` but for the fact that it doesn't
2280 return a boolean value. Instead, it returns a (possibly invalid) handle for the
2281 resource:
2282 
2283 ```cpp
2284 auto handle = cache.temp<MyLoader>("another/identifier", 42);
2285 ```
2286 
2287 Do not forget to test the handle for validity. Otherwise, getting the reference
2288 to the resource it points may result in undefined behavior.
2289 
2290 # Crash Course: events, signals and everything in between
2291 
2292 Signals are usually a core part of games and software architectures in
2293 general.<br/>
2294 Roughly speaking, they help to decouple the various parts of a system while
2295 allowing them to communicate with each other somehow.
2296 
2297 The so called _modern C++_ comes with a tool that can be useful in these terms,
2298 the `std::function`. As an example, it can be used to create delegates.<br/>
2299 However, there is no guarantee that an `std::function` does not perform
2300 allocations under the hood and this could be problematic sometimes. Furthermore,
2301 it solves a problem but may not adapt well to other requirements that may arise
2302 from time to time.
2303 
2304 In case that the flexibility and potential of an `std::function` are not
2305 required or where you are looking for something different, the `EnTT` framework
2306 offers a full set of classes to solve completely different problems.
2307 
2308 ## Signals
2309 
2310 Signal handlers work with naked pointers, function pointers and pointers to
2311 member functions. Listeners can be any kind of objects and the user is in charge
2312 of connecting and disconnecting them from a signal to avoid crashes due to
2313 different lifetimes. On the other side, performance shouldn't be affected that
2314 much by the presence of such a signal handler.<br/>
2315 A signal handler can be used as a private data member without exposing any
2316 _publish_ functionality to the clients of a class. The basic idea is to impose a
2317 clear separation between the signal itself and its _sink_ class, that is a tool
2318 to be used to connect and disconnect listeners on the fly.
2319 
2320 The API of a signal handler is straightforward. The most important thing is that
2321 it comes in two forms: with and without a collector. In case a signal is
2322 associated with a collector, all the values returned by the listeners can be
2323 literally _collected_ and used later by the caller. Otherwise it works just like
2324 a plain signal that emits events from time to time.<br/>
2325 
2326 **Note**: collectors are allowed only in case of function types whose the return
2327 type isn't `void` for obvious reasons.
2328 
2329 To create instances of signal handlers there exist mainly two ways:
2330 
2331 ```cpp
2332 // no collector type
2333 entt::SigH<void(int, char)> signal;
2334 
2335 // explicit collector type
2336 entt::SigH<void(int, char), MyCollector<bool>> collector;
2337 ```
2338 
2339 As expected, they offer all the basic functionalities required to know how many
2340 listeners they contain (`size`) or if they contain at least a listener (`empty`)
2341 and even to swap two signal handlers (`swap`).
2342 
2343 Besides them, there are member functions to use both to connect and disconnect
2344 listeners in all their forms by means of a sink:
2345 
2346 ```cpp
2347 void foo(int, char) { /* ... */ }
2348 
2349 struct S {
2350  void bar(int, char) { /* ... */ }
2351 };
2352 
2353 // ...
2354 
2355 S instance;
2356 
2357 signal.sink().connect<&foo>();
2358 signal.sink().connect<S, &S::bar>(&instance);
2359 
2360 // ...
2361 
2362 // disconnects a free function
2363 signal.sink().disconnect<&foo>();
2364 
2365 // disconnect a specific member function of an instance ...
2366 signal.sink().disconnect<S, &S::bar>(&instance);
2367 
2368 // ... or an instance as a whole
2369 signal.sink().disconnect(&instance);
2370 
2371 // discards all the listeners at once
2372 signal.sink().disconnect();
2373 ```
2374 
2375 Once listeners are attached (or even if there are no listeners at all), events
2376 and data in general can be published through a signal by means of the `publish`
2377 member function:
2378 
2379 ```cpp
2380 signal.publish(42, 'c');
2381 ```
2382 
2383 To collect data, the `collect` member function should be used instead. Below is
2384 a minimal example to show how to use it:
2385 
2386 ```cpp
2387 struct MyCollector {
2388  std::vector<int> vec{};
2389 
2390  bool operator()(int v) noexcept {
2391  vec.push_back(v);
2392  return true;
2393  }
2394 };
2395 
2396 int f() { return 0; }
2397 int g() { return 1; }
2398 
2399 // ...
2400 
2401 entt::SigH<int(), MyCollector<int>> signal;
2402 
2403 signal.sink().connect<&f>();
2404 signal.sink().connect<&g>();
2405 
2406 MyCollector collector = signal.collect();
2407 
2408 assert(collector.vec[0] == 0);
2409 assert(collector.vec[1] == 1);
2410 ```
2411 
2412 As shown above, a collector must expose a function operator that accepts as an
2413 argument a type to which the return type of the listeners can be converted.
2414 Moreover, it has to return a boolean value that is false to stop collecting
2415 data, true otherwise. This way one can avoid calling all the listeners in case
2416 it isn't necessary.
2417 
2418 ## Delegate
2419 
2420 A delegate can be used as general purpose invoker with no memory overhead for
2421 free functions and member functions provided along with an instance on which
2422 to invoke them.<br/>
2423 It does not claim to be a drop-in replacement for an `std::function`, so do not
2424 expect to use it whenever an `std::function` fits well. However, it can be used
2425 to send opaque delegates around to be used to invoke functions as needed.
2426 
2427 The interface is trivial. It offers a default constructor to create empty
2428 delegates:
2429 
2430 ```cpp
2431 entt::Delegate<int(int)> delegate{};
2432 ```
2433 
2434 All what is needed to create an instance is to specify the type of the function
2435 the delegate will _contain_, that is the signature of the free function or the
2436 member function one wants to assign to it.
2437 
2438 Attempting to use an empty delegate by invoking its function call operator
2439 results in undefined behavior, most likely a crash actually. Before to use a
2440 delegate, it must be initialized.<br/>
2441 There exist two functions to do that, both named `connect`:
2442 
2443 ```cpp
2444 int f(int i) { return i; }
2445 
2446 struct MyStruct {
2447  int f(int i) { return i }
2448 };
2449 
2450 // bind a free function to the delegate
2451 delegate.connect<&f>();
2452 
2453 // bind a member function to the delegate
2454 MyStruct instance;
2455 delegate.connect<MyStruct, &MyStruct::f>(&instance);
2456 ```
2457 
2458 It hasn't a `disconnect` counterpart. Instead, there exists a `reset` member
2459 function to clear it.<br/>
2460 The `empty` member function can be used to know if a delegate is empty:
2461 
2462 ```cpp
2463 const auto empty = delegate.empty();
2464 ```
2465 
2466 Finally, to invoke a delegate, the function call operator is the way to go as
2467 usual:
2468 
2469 ```cpp
2470 auto ret = delegate(42);
2471 ```
2472 
2473 Probably too much small and pretty poor of functionalities, but the delegate
2474 class can help in a lot of cases and it has shown that it is worth keeping it
2475 within the framework.
2476 
2477 ## Event dispatcher
2478 
2479 The event dispatcher class is designed so as to be used in a loop. It allows
2480 users both to trigger immediate events or to queue events to be published all
2481 together once per tick.<br/>
2482 This class shares part of its API with the one of the signal handler, but it
2483 doesn't require that all the types of events are specified when declared:
2484 
2485 ```cpp
2486 // define a general purpose dispatcher that works with naked pointers
2487 entt::Dispatcher dispatcher{};
2488 ```
2489 
2490 In order to register an instance of a class to a dispatcher, its type must
2491 expose one or more member functions of which the return types are `void` and the
2492 argument lists are `const E &`, for each type of event `E`.<br/>
2493 To ease the development, member functions that are named `receive` are
2494 automatically detected and have not to be explicitly specified when registered.
2495 In all the other cases, the name of the member function aimed to receive the
2496 event must be provided to the `connect` member function of the sink bound to the
2497 specific event:
2498 
2499 ```cpp
2500 struct AnEvent { int value; };
2501 struct AnotherEvent {};
2502 
2503 struct Listener
2504 {
2505  void receive(const AnEvent &) { /* ... */ }
2506  void method(const AnotherEvent &) { /* ... */ }
2507 };
2508 
2509 // ...
2510 
2511 Listener listener;
2512 dispatcher.sink<AnEvent>().connect(&listener);
2513 dispatcher.sink<AnotherEvent>().connect<Listener, &Listener::method>(&listener);
2514 ```
2515 
2516 The `disconnect` member function follows the same pattern and can be used to
2517 selectively remove listeners:
2518 
2519 ```cpp
2520 dispatcher.sink<AnEvent>().disconnect(&listener);
2521 dispatcher.sink<AnotherEvent>().disconnect<Listener, &Listener::method>(&listener);
2522 ```
2523 
2524 The `trigger` member function serves the purpose of sending an immediate event
2525 to all the listeners registered so far. It offers a convenient approach that
2526 relieves the user from having to create the event itself. Instead, it's enough
2527 to specify the type of event and provide all the parameters required to
2528 construct it.<br/>
2529 As an example:
2530 
2531 ```cpp
2532 dispatcher.trigger<AnEvent>(42);
2533 dispatcher.trigger<AnotherEvent>();
2534 ```
2535 
2536 Listeners are invoked immediately, order of execution isn't guaranteed. This
2537 method can be used to push around urgent messages like an _is terminating_
2538 notification on a mobile app.
2539 
2540 On the other hand, the `enqueue` member function queues messages together and
2541 allows to maintain control over the moment they are sent to listeners. The
2542 signature of this method is more or less the same of `trigger`:
2543 
2544 ```cpp
2545 dispatcher.enqueue<AnEvent>(42);
2546 dispatcher.enqueue<AnotherEvent>();
2547 ```
2548 
2549 Events are stored aside until the `update` member function is invoked, then all
2550 the messages that are still pending are sent to the listeners at once:
2551 
2552 ```cpp
2553 // emits all the events of the given type at once
2554 dispatcher.update<MyEvent>();
2555 
2556 // emits all the events queued so far at once
2557 dispatcher.update();
2558 ```
2559 
2560 This way users can embed the dispatcher in a loop and literally dispatch events
2561 once per tick to their systems.
2562 
2563 ## Event emitter
2564 
2565 A general purpose event emitter thought mainly for those cases where it comes to
2566 working with asynchronous stuff.<br/>
2567 Originally designed to fit the requirements of
2568 [`uvw`](https://github.com/skypjack/uvw) (a wrapper for `libuv` written in
2569 modern C++), it was adapted later to be included in this library.
2570 
2571 To create a custom emitter type, derived classes must inherit directly from the
2572 base class as:
2573 
2574 ```cpp
2575 struct MyEmitter: Emitter<MyEmitter> {
2576  // ...
2577 }
2578 ```
2579 
2580 The full list of accepted types of events isn't required. Handlers are created
2581 internally on the fly and thus each type of event is accepted by default.
2582 
2583 Whenever an event is published, an emitter provides the listeners with a
2584 reference to itself along with a const reference to the event. Therefore
2585 listeners have an handy way to work with it without incurring in the need of
2586 capturing a reference to the emitter itself.<br/>
2587 In addition, an opaque object is returned each time a connection is established
2588 between an emitter and a listener, allowing the caller to disconnect them at a
2589 later time.<br/>
2590 The opaque object used to handle connections is both movable and copyable. On
2591 the other side, an event emitter is movable but not copyable by default.
2592 
2593 To create new instances of an emitter, no arguments are required:
2594 
2595 ```cpp
2596 MyEmitter emitter{};
2597 ```
2598 
2599 Listeners must be movable and callable objects (free functions, lambdas,
2600 functors, `std::function`s, whatever) whose function type is:
2601 
2602 ```cpp
2603 void(const Event &, MyEmitter &)
2604 ```
2605 
2606 Where `Event` is the type of event they want to listen.<br/>
2607 There are two ways to attach a listener to an event emitter that differ
2608 slightly from each other:
2609 
2610 * To register a long-lived listener, use the `on` member function. It is meant
2611  to register a listener designed to be invoked more than once for the given
2612  event type.<br/>
2613  As an example:
2614 
2615  ```cpp
2616  auto conn = emitter.on<MyEvent>([](const MyEvent &event, MyEmitter &emitter) {
2617  // ...
2618  });
2619  ```
2620 
2621  The connection object can be freely discarded. Otherwise, it can be used later
2622  to disconnect the listener if required.
2623 
2624 * To register a short-lived listener, use the `once` member function. It is
2625  meant to register a listener designed to be invoked only once for the given
2626  event type. The listener is automatically disconnected after the first
2627  invocation.<br/>
2628  As an example:
2629 
2630  ```cpp
2631  auto conn = emitter.once<MyEvent>([](const MyEvent &event, MyEmitter &emitter) {
2632  // ...
2633  });
2634  ```
2635 
2636  The connection object can be freely discarded. Otherwise, it can be used later
2637  to disconnect the listener if required.
2638 
2639 In both cases, the connection object can be used with the `erase` member
2640 function:
2641 
2642 ```cpp
2643 emitter.erase(conn);
2644 ```
2645 
2646 There are also two member functions to use either to disconnect all the
2647 listeners for a given type of event or to clear the emitter:
2648 
2649 ```cpp
2650 // removes all the listener for the specific event
2651 emitter.clear<MyEvent>();
2652 
2653 // removes all the listeners registered so far
2654 emitter.clear();
2655 ```
2656 
2657 To send an event to all the listeners that are interested in it, the `publish`
2658 member function offers a convenient approach that relieves the user from having
2659 to create the event:
2660 
2661 ```cpp
2662 struct MyEvent { int i; };
2663 
2664 // ...
2665 
2666 emitter.publish<MyEvent>(42);
2667 ```
2668 
2669 Finally, the `empty` member function tests if there exists at least either a
2670 listener registered with the event emitter or to a given type of event:
2671 
2672 ```cpp
2673 bool empty;
2674 
2675 // checks if there is any listener registered for the specific event
2676 empty = emitter.empty<MyEvent>();
2677 
2678 // checks it there are listeners registered with the event emitter
2679 empty = emitter.empty();
2680 ```
2681 
2682 In general, the event emitter is a handy tool when the derived classes _wrap_
2683 asynchronous operations, because it introduces a _nice-to-have_ model based on
2684 events and listeners that kindly hides the complexity behind the scenes. However
2685 it is not limited to such uses.
2686 
2687 # Packaging Tools
2688 
2689 `EnTT` is available for some of the most known packaging tools. In particular:
2690 
2691 * [`vcpkg`](https://github.com/Microsoft/vcpkg/tree/master/ports/entt),
2692  Microsoft VC++ Packaging Tool.
2693 * [`Homebrew`](https://github.com/skypjack/homebrew-entt), the missing package
2694  manager for macOS.<br/>
2695  Available as a homebrew formula. Just type the following to install it:
2696  ```
2697  brew install skypjack/entt/entt
2698  ```
2699 
2700 Consider this list a work in progress and help me to make it longer.
2701 
2702 # EnTT in Action
2703 
2704 `EnTT` is widely used in private and commercial applications. I cannot even
2705 mention most of them because of some signatures I put on some documents time
2706 ago.<br/>
2707 Fortunately, there are also people who took the time to implement open source
2708 projects based on EnTT and did not hold back when it came to documenting them.
2709 
2710 Below an incomplete list of projects and articles:
2711 
2712 * [EnttPong](https://github.com/reworks/EnttPong): example game for `EnTT`
2713  framework.
2714 * [Space Battle: Huge edition](http://victor.madtriangles.com/code%20experiment/2018/06/11/post-ecs-battle-huge.html):
2715  huge space battle built entirely from scratch.
2716 * [Space Battle](https://github.com/vblanco20-1/ECS_SpaceBattle): huge space
2717  battle built on `UE4`.
2718 * [Experimenting with ECS in UE4](http://victor.madtriangles.com/code%20experiment/2018/03/25/post-ue4-ecs-battle.html):
2719  interesting article about `UE4` and `EnTT`.
2720 * [Implementing ECS architecture in UE4](https://forums.unrealengine.com/development-discussion/c-gameplay-programming/1449913-implementing-ecs-architecture-in-ue4-giant-space-battle):
2721  giant space battle.
2722 * [MatchOneEntt](https://github.com/mhaemmerle/MatchOneEntt): port of
2723  [Match One](https://github.com/sschmid/Match-One) for `Entitas-CSharp`.
2724 * [Randballs](https://github.com/gale93/randballs): simple `SFML` and `EnTT`
2725  playground.
2726 * ...
2727 
2728 If you know of other resources out there that are about `EnTT`, feel free to
2729 open an issue or a PR and I'll be glad to add them to the list.
2730 
2731 # Contributors
2732 
2733 If you want to participate, please see the guidelines for
2734 [contributing](https://github.com/skypjack/entt/blob/master/CONTRIBUTING)
2735 before to create issues or pull requests.<br/>
2736 Take also a look at the
2737 [contributors list](https://github.com/skypjack/entt/blob/master/AUTHORS) to
2738 know who has participated so far.
2739 
2740 # License
2741 
2742 Code and documentation Copyright (c) 2018 Michele Caini.<br/>
2743 Code released under
2744 [the MIT license](https://github.com/skypjack/entt/blob/master/LICENSE).
2745 Docs released under
2746 [Creative Commons](https://github.com/skypjack/entt/blob/master/docs/LICENSE).
2747 
2748 # Support
2749 
2750 ## Donation
2751 
2752 Developing and maintaining `EnTT` takes some time and lots of coffee. I'd like
2753 to add more and more functionalities in future and turn it in a full-featured
2754 framework.<br/>
2755 If you want to support this project, you can offer me an espresso. I'm from
2756 Italy, we're used to turning the best coffee ever in code. If you find that
2757 it's not enough, feel free to support me the way you prefer.<br/>
2758 Take a look at the donation button at the top of the page for more details or
2759 just click [here](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=W2HF9FESD5LJY&lc=IT&item_name=Michele%20Caini&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted).
2760 
2761 ## Hire me
2762 
2763 If you start using `EnTT` and need help, if you want a new feature and want me
2764 to give it the highest priority, if you have any other reason to contact me:
2765 do not hesitate. I'm available for hiring.<br/>
2766 Feel free to take a look at my [profile](https://github.com/skypjack) and
2767 contact me by mail.