├── .gitignore ├── COPYING.LESSER.txt ├── COPYING.txt ├── Makefile ├── README.md ├── doc ├── README.md └── public │ ├── images │ └── ddox │ │ ├── alias.png │ │ ├── class.png │ │ ├── enum.png │ │ ├── enummember.png │ │ ├── function.png │ │ ├── inherited.png │ │ ├── interface.png │ │ ├── module.png │ │ ├── package.png │ │ ├── private.png │ │ ├── property.png │ │ ├── protected.png │ │ ├── struct.png │ │ ├── template.png │ │ └── variable.png │ ├── prettify │ └── prettify.css │ ├── scripts │ ├── ddox.js │ └── jquery.js │ └── styles │ └── ddox.css ├── dub.sdl ├── example ├── dub.sdl └── source │ └── main.d └── source └── entitysysd ├── component.d ├── entity.d ├── event.d ├── exception.d ├── package.d ├── pool.d ├── stat.d └── system.d /.gitignore: -------------------------------------------------------------------------------- 1 | .dub 2 | .project 3 | entitysysd_example 4 | __test__library__ 5 | *.a 6 | out/* 7 | doc/*.html 8 | doc/*.json 9 | doc/public/*.html 10 | doc/public/*.* 11 | doc/public/entitysysd/* 12 | -------------------------------------------------------------------------------- /COPYING.LESSER.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /COPYING.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | DDOX = ../ddox/ddox 2 | 3 | help: 4 | @echo "Generate ddox documentation:" 5 | @echo " make doc" 6 | @echo "Clean all output files from doc:" 7 | @echo " make clean" 8 | 9 | doc: 10 | dmd -o- -c -D -Dddoc -X -Xfdoc/docs.json entitysysd/*.d 11 | $(DDOX) filter --min-protection=Public doc/docs.json \ 12 | --ex entitysysd.pool --ex entitysysd.exception \ 13 | --ex entitysysd.component 14 | $(DDOX) generate-html --navigation-type=ModuleTree \ 15 | doc/docs.json doc/public 16 | 17 | .PHONY: clean doc help 18 | 19 | clean: 20 | rm doc/public/*.* 2>/dev/null; true 21 | rm -rf doc/public/entitysysd 2>/dev/null; true 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EntitySysD 2 | 3 | *Component/Entity System* engine written in D. More information may be found on 4 | this [CES wiki](http://entity-systems-wiki.t-machine.org/). 5 | 6 | To quote it: 7 | > *Component/Entity Systems are an architectural pattern used mostly in game 8 | development. A CES follows the Composition over Inheritance principle to allow 9 | for greater flexibility when defining entities (anything that's part of a game's 10 | scene: enemies, doors, bullets) by building out of individual parts that can be 11 | mixed-and-matched. This eliminates the ambiguity problems of long inheritance 12 | chains and promotes clean design. However, CES systems do incur a small cost to 13 | performance.* 14 | 15 | Nevertheless, we have room to organize components in a cache-friendly manner. 16 | 17 | 18 | ## Usage 19 | 20 | ### Building 21 | 22 | This project uses the DUB build system 23 | (check [here](http://code.dlang.org/download)). 24 | 25 | To build the **EntitySysD** library, simply run in the top-level directory 26 | ``` 27 | dub 28 | ``` 29 | 30 | To build and run all the unit-tests: 31 | ``` 32 | dub test 33 | ``` 34 | 35 | To generate the documentation, see doc/README.md. 36 | 37 | 38 | ### API documentation 39 | 40 | The complete reference API is there (generated with 41 | [ddox](https://github.com/rejectedsoftware/ddox)): 42 | > [Reference API](https://claudemr.github.io/entitysysd/) 43 | 44 | 45 | ### Entities 46 | 47 | The `Entity` structure is a simple wrapper around a 64-bit unique id. 48 | 49 | Creation of an entity: 50 | ``` 51 | import entitysysd; 52 | 53 | auto ecs = new EntitySysD; 54 | 55 | auto entity = ecs.entities.create(); 56 | ``` 57 | 58 | Destruction: 59 | ``` 60 | entity.destroy(); 61 | ``` 62 | 63 | 64 | ### Components 65 | 66 | Register a `component` to an entity (the struct is tagged by the `@component` 67 | attribute): 68 | ``` 69 | @component struct Position 70 | { 71 | float x, y; 72 | } 73 | 74 | auto componentPtr = entity.register!Position(2.0, 3.0); 75 | 76 | ... 77 | 78 | // accessor 79 | entity.component!Position.y += 1.0; 80 | ``` 81 | 82 | 83 | ### Browsing 84 | 85 | Browsing through all valid entities: 86 | ``` 87 | foreach (entity; ecs.entities) 88 | { 89 | //do stuff 90 | } 91 | ``` 92 | 93 | Browsing through the instances of a type of component: 94 | ``` 95 | foreach (componentPtr; ecs.entities.components!Position) 96 | { 97 | //do stuff 98 | } 99 | ``` 100 | 101 | Browsing through entities with a certain set of components: 102 | ``` 103 | foreach (entity; ecs.entities.entitiesWith!(Position, Renderable)) 104 | { 105 | //do stuff 106 | } 107 | ``` 108 | 109 | ``` 110 | foreach (entity, pos, render; ecs.entities.entitiesWith!(Position, Renderable)) 111 | { 112 | // pos is equivalent to entity.component!Position 113 | // render is equivalent to entity.component!Renderable 114 | } 115 | ``` 116 | 117 | Browsing through the components of an entity. 118 | ``` 119 | ecs.entities.accessor!Position = (e, p) { write("Entity:%s Xpos=%f", entity.toString(), p.x); }; 120 | auto entity = ecs.entities.create(); 121 | entity.register!Position(2.0, 3.0); 122 | entity.iterate(); // call accessor delegates of the components registered to entity 123 | ``` 124 | 125 | ### Systems 126 | 127 | Create a class inheriting from the `System` interface, registering it to the 128 | system manager and running it: 129 | 130 | ``` 131 | class RenderSystem : System 132 | { 133 | override void run(EntityManager entities, EventManager events, Duration dt) 134 | { 135 | // render renderable entities 136 | } 137 | } 138 | 139 | ... 140 | 141 | ecs.systems.register(new RenderSystem); 142 | 143 | ... 144 | 145 | ecs.systems.run(dur!"msecs"(16)); 146 | ``` 147 | 148 | 149 | ### Events 150 | 151 | Subscribing to an event (tagged by the `@event` attribute) 152 | 153 | ``` 154 | @event struct MyEvent 155 | { 156 | int data; 157 | } 158 | 159 | class TestReceiver : Receiver!MyEvent 160 | { 161 | string str; 162 | 163 | void receive(MyEvent event) 164 | { 165 | str ~= event.data.toString; 166 | } 167 | } 168 | 169 | auto evtManager = new EventManager; 170 | evtManager.subscribe!MyEvent(new TestReceiver); 171 | 172 | ``` 173 | 174 | Sending events: 175 | 176 | ``` 177 | auto e = MyEvent(43); 178 | 179 | evtManager.emit(e); 180 | evtManager.emit!MyEvent(42); 181 | ``` 182 | 183 | 184 | ## Thread-safety 185 | 186 | **EntitySysD** API is NOT (and will not be) thread-safe. Events will never be 187 | natively sent accross threads. If the user wants to use EntitySysD in a 188 | multi-threaded process, he will have to do its own resource synchronization on 189 | top of it. 190 | Thread-safety adds too much complexity. And from a software architecture point 191 | of view, it makes more sense to manage resource synchronization at the highest 192 | level. **EntitySysD** is just a library. 193 | 194 | ## Contributors 195 | 196 | * [Claude Merle](https://github.com/claudemr) 197 | * [Ryan Roden-Corrent](https://github.com/rcorre) 198 | 199 | ## Credits 200 | 201 | This engine is based on a D port inspired on **EntityX** in C++ of Alec Thomas. 202 | It's been simplified a lot (using D specific features, removing component 203 | handles, etc)): 204 | > https://github.com/alecthomas/entityx/ 205 | 206 | There are many other CES engines in D out there. 207 | 208 | **Star-Entity** is very similar to **EntitySysD** (it is also based upon 209 | EntityX) and I actually came across it after the start of **EntitySysD** 210 | development (had I known about it earlier, and maybe **EntitySysD** would not 211 | have existed at all): 212 | > https://github.com/misu-pwnu/star-entity 213 | 214 | **Nitro** design is based on statically built systems and components managers. 215 | There seems to be more thoughts towards cache-efficiency. 216 | > https://github.com/Zoadian/nitro 217 | 218 | 219 | ## Licence 220 | 221 | **EntitySysD** is released under the **Lesser-GPL** *v3* licence. 222 | See COPYING.txt and COPYING.LESSER.txt for more information. 223 | 224 | 225 | ## History 226 | 227 | ### v2.4.x 228 | 229 | Changes: 230 | * `ISystem` interface deprecated. Methods added to `System` abstract class 231 | (potentilly an API breaking change, but very unlikely in practise). 232 | * Allow to register systems in a certain ordering (absolute or relative to an 233 | already registered system). 234 | 235 | Add: 236 | * Statistics added: module `stat`. 237 | 238 | ### v2.0.x 239 | 240 | Change: 241 | * `System` interface is renamed to `ISystem` and becomes an abstract class. 242 | * API break: with `std.meta` and `hasUDA`. It cannot be compiled anymore 243 | with DMD compiler with a version below **2.068.0**. 244 | 245 | Add: 246 | * `ISystem` declares 2 new methods: `prepare` and `unprepare`. `System` 247 | abstract class implements empty body for `prepare`, `run` and `unprepare`. 248 | * `SystemManager.runFull` calls `prepare`, `run` and `unprepare`. 249 | 250 | To convert 1.x.x user application to 2.0.0, prefix all your `System.run` 251 | methods with `override`, and upgrade your DMD compiler to a version 252 | **>= 2.068.0**. 253 | 254 | ### v1.x.x 255 | 256 | The 1st release puts down the base of **EntitySysD** API. 257 | 258 | It uses exceptions (removed all the assert's) 259 | 260 | It uses UDA's to tag components and events to ensure the correctness of the 261 | usage of library at compile time. 262 | 263 | No benchmarking has been performed. The cache-friendly memory management is 264 | dependant of the application use, and cannot yet be customized for specific 265 | needs at the moment. So the current implementation is pretty naive and could 266 | totally miss the point of being cache-friendly. User experience will tell. So 267 | further enhancements may be programmed. 268 | 269 | It has been tested on GNU-Linux environment using DMD64 D Compiler v2.068.x and 270 | v2.069.x. 271 | -------------------------------------------------------------------------------- /doc/README.md: -------------------------------------------------------------------------------- 1 | # EntitySysD API documentation generation 2 | 3 | Steps to upgrade doc generation. 4 | 5 | Prerequisites: 6 | * Clone ddox at the same directory level as your entitysysd work directory level `git clone git@github.com:rejectedsoftware/ddox.git`. 7 | * Clone entitysysd doc branch at the same directory level as your entitysysd work directory level `git clone git@github.com:claudemr/entitysysd.git entitysysd_doc` and `git checkout gh-pages`. 8 | * So you should have "entitysysd", "entitysysd_doc" and "ddox" at the same directory level. 9 | 10 | Upgrade: 11 | * Make sure ddox version is the last: `cd ddox ; git pull`. 12 | * Build ddox: `dub`. 13 | * Update public files from ddox to entitysysd: ``meld ./public ../entitysysd/doc/public``. 14 | * Generate EntitySysD API documentation: ``cd ../entitysysd ; make clean ; make doc``. 15 | * Update gh-pages branch from entitysysd directory to entitysysd_doc directory: ``meld ./doc/public ../entitysysd_doc`` 16 | * Commit and push modifications from both entitysysd and entitysysd_doc. 17 | -------------------------------------------------------------------------------- /doc/public/images/ddox/alias.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/alias.png -------------------------------------------------------------------------------- /doc/public/images/ddox/class.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/class.png -------------------------------------------------------------------------------- /doc/public/images/ddox/enum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/enum.png -------------------------------------------------------------------------------- /doc/public/images/ddox/enummember.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/enummember.png -------------------------------------------------------------------------------- /doc/public/images/ddox/function.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/function.png -------------------------------------------------------------------------------- /doc/public/images/ddox/inherited.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/inherited.png -------------------------------------------------------------------------------- /doc/public/images/ddox/interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/interface.png -------------------------------------------------------------------------------- /doc/public/images/ddox/module.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/module.png -------------------------------------------------------------------------------- /doc/public/images/ddox/package.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/package.png -------------------------------------------------------------------------------- /doc/public/images/ddox/private.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/private.png -------------------------------------------------------------------------------- /doc/public/images/ddox/property.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/property.png -------------------------------------------------------------------------------- /doc/public/images/ddox/protected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/protected.png -------------------------------------------------------------------------------- /doc/public/images/ddox/struct.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/struct.png -------------------------------------------------------------------------------- /doc/public/images/ddox/template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/template.png -------------------------------------------------------------------------------- /doc/public/images/ddox/variable.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/claudemr/entitysysd/7a41ba50d2c38bb0ec4ddc93a91b49b62083bb86/doc/public/images/ddox/variable.png -------------------------------------------------------------------------------- /doc/public/prettify/prettify.css: -------------------------------------------------------------------------------- 1 | /* Pretty printing styles. Used with prettify.js. */ 2 | 3 | /* SPAN elements with the classes below are added by prettyprint. */ 4 | .pln { color: #222 } /* plain text */ 5 | pre .pln, div.prototype .pln { color: #fff } /* plain text */ 6 | 7 | @media screen { 8 | pre .str { color: #ffe7b6 } /* string content */ 9 | pre .typ { color: #9ad452 } /* a type name */ 10 | pre .lit { color: #ffe7b6 } /* a literal value */ 11 | pre .pun, div.prototype .pun { color: #fff } 12 | 13 | .spc { color: #a0a } /* special token sequence */ 14 | .str { color: #842 } /* string content */ 15 | .kwd { color: #ffaa00 } /* a keyword */ 16 | .com { color: #888 } /* a comment */ 17 | .typ { color: #693 } /* a type name */ 18 | .lit { color: #875 } /* a literal value */ 19 | /* punctuation, lisp open bracket, lisp close bracket */ 20 | .pun, .opn, .clo { color: #222 } 21 | .tag { color: #ffaa00 } /* a markup tag name */ 22 | .atn { color: #9ad452 } /* a markup attribute name */ 23 | .atv { color: #ffe7b6 } /* a markup attribute value */ 24 | .dec, .var { color: #aaa } /* a declaration; a variable name */ 25 | .fun { color: red } /* a function name */ 26 | } 27 | 28 | /* Use higher contrast and text-weight for printable form. */ 29 | @media print, projection { 30 | .spc { color: #606 } /* special token sequence */ 31 | .str { color: #060 } 32 | .kwd { color: #006; font-weight: bold } 33 | .com { color: #600; font-style: italic } 34 | .typ { color: #404; font-weight: bold } 35 | .lit { color: #044 } 36 | .pun, .opn, .clo { color: #440 } 37 | .tag { color: #006; font-weight: bold } 38 | .atn { color: #404 } 39 | .atv { color: #060 } 40 | } 41 | 42 | /* Put a border around prettyprinted code snippets. */ 43 | pre.prettyprint, pre.code, div.prototype { 44 | padding: 1em 0; 45 | background-color: #222; 46 | border: 1px solid black; 47 | color: white; 48 | } 49 | 50 | /* Specify class=linenums on a pre to get line numbering */ 51 | ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */ 52 | li.L0, 53 | li.L1, 54 | li.L2, 55 | li.L3, 56 | li.L5, 57 | li.L6, 58 | li.L7, 59 | li.L8 { list-style-type: none } 60 | /* Alternate shading for lines */ 61 | li.L1, 62 | li.L3, 63 | li.L5, 64 | li.L7, 65 | li.L9 { background: #222222 } 66 | -------------------------------------------------------------------------------- /doc/public/scripts/ddox.js: -------------------------------------------------------------------------------- 1 | function setupDdox() 2 | { 3 | $(".tree-view").children(".package").click(toggleTree); 4 | $(".tree-view.collapsed").children("ul").hide(); 5 | $("#symbolSearch").attr("tabindex", "1000"); 6 | } 7 | 8 | function toggleTree() 9 | { 10 | node = $(this).parent(); 11 | node.toggleClass("collapsed"); 12 | if( node.hasClass("collapsed") ){ 13 | node.children("ul").hide(); 14 | } else { 15 | node.children("ul").show(); 16 | } 17 | return false; 18 | } 19 | 20 | var searchCounter = 0; 21 | var lastSearchString = ""; 22 | 23 | function performSymbolSearch(maxlen) 24 | { 25 | if (maxlen === 'undefined') maxlen = 26; 26 | 27 | var searchstring = $("#symbolSearch").val().toLowerCase(); 28 | 29 | if (searchstring == lastSearchString) return; 30 | lastSearchString = searchstring; 31 | 32 | var scnt = ++searchCounter; 33 | $('#symbolSearchResults').hide(); 34 | $('#symbolSearchResults').empty(); 35 | 36 | var terms = $.trim(searchstring).split(/\s+/); 37 | if (terms.length == 0 || (terms.length == 1 && terms[0].length < 2)) return; 38 | 39 | var results = []; 40 | for (i in symbols) { 41 | var sym = symbols[i]; 42 | var all_match = true; 43 | for (j in terms) 44 | if (sym.name.toLowerCase().indexOf(terms[j]) < 0) { 45 | all_match = false; 46 | break; 47 | } 48 | if (!all_match) continue; 49 | 50 | results.push(sym); 51 | } 52 | 53 | function compare(a, b) { 54 | // prefer non-deprecated matches 55 | var adep = a.attributes.indexOf("deprecated") >= 0; 56 | var bdep = b.attributes.indexOf("deprecated") >= 0; 57 | if (adep != bdep) return adep - bdep; 58 | 59 | // normalize the names 60 | var aname = a.name.toLowerCase(); 61 | var bname = b.name.toLowerCase(); 62 | 63 | var anameparts = aname.split("."); 64 | var bnameparts = bname.split("."); 65 | 66 | var asname = anameparts[anameparts.length-1]; 67 | var bsname = bnameparts[bnameparts.length-1]; 68 | 69 | // prefer exact matches 70 | var aexact = terms.indexOf(asname) >= 0; 71 | var bexact = terms.indexOf(bsname) >= 0; 72 | if (aexact != bexact) return bexact - aexact; 73 | 74 | // prefer elements with less nesting 75 | if (anameparts.length < bnameparts.length) return -1; 76 | if (anameparts.length > bnameparts.length) return 1; 77 | 78 | // prefer matches with a shorter name 79 | if (asname.length < bsname.length) return -1; 80 | if (asname.length > bsname.length) return 1; 81 | 82 | // sort the rest alphabetically 83 | if (aname < bname) return -1; 84 | if (aname > bname) return 1; 85 | return 0; 86 | } 87 | 88 | results.sort(compare); 89 | 90 | for (i = 0; i < results.length && i < 100; i++) { 91 | var sym = results[i]; 92 | 93 | var el = $(document.createElement("li")); 94 | el.addClass(sym.kind); 95 | for (j in sym.attributes) 96 | el.addClass(sym.attributes[j]); 97 | 98 | var name = sym.name; 99 | 100 | // compute a length limited representation of the full name 101 | var nameparts = name.split("."); 102 | var np = nameparts.length-1; 103 | var shortname = "." + nameparts[np]; 104 | while (np > 0 && nameparts[np-1].length + shortname.length <= maxlen) { 105 | np--; 106 | shortname = "." + nameparts[np] + shortname; 107 | } 108 | if (np > 0) shortname = ".." + shortname; 109 | else shortname = shortname.substr(1); 110 | 111 | el.append(''+shortname+''); 112 | $('#symbolSearchResults').append(el); 113 | } 114 | 115 | if (results.length > 100) { 116 | $('#symbolSearchResults').append("
  • …"+(results.length-100)+" additional results
  • "); 117 | } 118 | 119 | $('#symbolSearchResults').show(); 120 | } 121 | -------------------------------------------------------------------------------- /doc/public/styles/ddox.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: "Lucida Sans Unicode", "Lucida Grande", "Open Sans", sans-serif; 5 | font-size: 0; 6 | } 7 | 8 | h1 { margin-top: 0; } 9 | 10 | a { 11 | color: #13e; 12 | text-decoration: none; 13 | } 14 | 15 | a:hover { 16 | color: #24f; 17 | } 18 | 19 | #main-nav { 20 | -webkit-box-sizing: border-box; 21 | -moz-box-sizing: border-box; 22 | box-sizing: border-box; 23 | display: inline-block; 24 | vertical-align: top; 25 | font-size: 9.5pt; 26 | min-width: 10em; 27 | width: 20%; 28 | padding: 2em 1em; 29 | border-right: 1px solid black; 30 | border-bottom: 1px solid black; 31 | background-color: #eee; 32 | } 33 | 34 | #main-contents { 35 | -webkit-box-sizing: border-box; 36 | -moz-box-sizing: border-box; 37 | box-sizing: border-box; 38 | display: inline-block; 39 | vertical-align: top; 40 | font-size: 9.5pt; 41 | width: 80%; 42 | padding: 2em; 43 | } 44 | 45 | table { 46 | border-collapse: collapse; 47 | } 48 | 49 | th { 50 | text-align: left; 51 | } 52 | 53 | td { 54 | border-top: 1px dashed #ddd; 55 | border-bottom: 1px dashed #ddd; 56 | vertical-align: top; 57 | } 58 | 59 | col.caption { 60 | width: 150pt; 61 | } 62 | 63 | ul.tree-view a.package { 64 | background-image: url(../images/ddox/package.png); 65 | background-repeat: no-repeat; 66 | background-position: left center; 67 | padding-left: 18px; 68 | padding-right: 4px; 69 | } 70 | 71 | ul.tree-view a.module { 72 | margin-left: 14px; 73 | padding: 0 4px; 74 | } 75 | 76 | ul.tree-view a.selected { 77 | background-color: #f8f8f8; 78 | margin-left: 13px; 79 | border: 1px solid #bbb; 80 | } 81 | 82 | ul.tree-view { 83 | padding: 0; 84 | margin: 0; 85 | } 86 | 87 | ul.tree-view ul { 88 | margin: 0; 89 | padding: 0; 90 | padding-left: 10pt; 91 | } 92 | 93 | ul.tree-view li { 94 | list-style-type: none; 95 | padding: 0; 96 | margin-left: 0; 97 | } 98 | 99 | a.protected { 100 | font-style: italic; 101 | background-image: url(../images/ddox/protected.png); 102 | background-repeat: no-repeat; 103 | padding-left: 16px; 104 | } 105 | a.package { 106 | font-style: italic; 107 | background-image: url(../images/ddox/package.png); 108 | background-repeat: no-repeat; 109 | padding-left: 16px; 110 | } 111 | a.private { 112 | font-style: italic; 113 | background-image: url(../images/ddox/private.png); 114 | background-repeat: no-repeat; 115 | padding-left: 16px; 116 | } 117 | a.inherited:after { content: url(../images/ddox/inherited.png); padding-left: 2pt; } 118 | 119 | #symbolSearchResults { 120 | list-style: none; 121 | padding: 0; 122 | overflow: hidden; 123 | } 124 | #symbolSearchResults li { 125 | background-repeat: no-repeat; 126 | background-position: left center; 127 | padding-left: 18px; 128 | } 129 | 130 | #symbolSearchResults .deprecated a { color: gray; } 131 | #symbolSearchResults .module { background-image: url(../images/ddox/module.png); } 132 | #symbolSearchResults .functiondeclaration { background-image: url(../images/ddox/function.png); } 133 | #symbolSearchResults .classdeclaration { background-image: url(../images/ddox/class.png); } 134 | #symbolSearchResults .interfacedeclaration { background-image: url(../images/ddox/interface.png); } 135 | #symbolSearchResults .structdeclaration { background-image: url(../images/ddox/struct.png); } 136 | #symbolSearchResults .variabledeclaration { background-image: url(../images/ddox/variable.png); } 137 | #symbolSearchResults .property { background-image: url(../images/ddox/property.png); } 138 | #symbolSearchResults .enumdeclaration { background-image: url(../images/ddox/enum.png); } 139 | #symbolSearchResults .enummemberdeclaration { background-image: url(../images/ddox/enummember.png); } 140 | #symbolSearchResults .aliasdeclaration { background-image: url(../images/ddox/alias.png); } 141 | #symbolSearchResults .templatedeclaration { background-image: url(../images/ddox/template.png); } 142 | -------------------------------------------------------------------------------- /dub.sdl: -------------------------------------------------------------------------------- 1 | name "entitysysd" 2 | description "Entity/Component System engine" 3 | homepage "https://github.com/claudemr/entitysysd" 4 | copyright "Copyright © 2015-2018, Claude Merle" 5 | license "LGPL3" 6 | authors "Claude Merle" -------------------------------------------------------------------------------- /example/dub.sdl: -------------------------------------------------------------------------------- 1 | name "entitysys-example" 2 | description "An example showcasing EntitySysD" 3 | homepage "https://github.com/claudemr/entitysysd" 4 | copyright "Copyright © 2015-2018, Claude Merle" 5 | license "GPL3" 6 | authors "Claude Merle" 7 | dependency "entitysysd" path=".." 8 | dependency "derelict-sdl2" version="~>1.9" -------------------------------------------------------------------------------- /example/source/main.d: -------------------------------------------------------------------------------- 1 | /** 2 | System management module. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | import std.container; 23 | import std.math; 24 | import std.random; 25 | import std.stdio; 26 | 27 | import derelict.sdl2.sdl; 28 | 29 | import entitysysd; 30 | 31 | 32 | //*** Helpers *** 33 | struct Vector2f 34 | { 35 | float x, y; 36 | } 37 | 38 | struct Color 39 | { 40 | ubyte r, g, b; 41 | } 42 | 43 | 44 | //*** Component structures *** 45 | @component struct Body 46 | { 47 | Vector2f position; 48 | Vector2f direction; 49 | } 50 | 51 | @component struct Renderable 52 | { 53 | float radius; 54 | Color color; 55 | } 56 | 57 | 58 | @component struct Particle 59 | { 60 | Color color; 61 | float radius, alpha, d; 62 | } 63 | 64 | 65 | @component struct Collideable 66 | { 67 | float radius; 68 | } 69 | 70 | //*** Random-number-generator utility function *** 71 | float r(int a, float b = 0) 72 | { 73 | return cast(float)(uniform(0, a * 1000) + b * 1000) / 1000.0; 74 | } 75 | 76 | //*** Event struct *** 77 | 78 | @event struct CollisionEvent 79 | { 80 | Entity a, b; 81 | } 82 | 83 | 84 | //*** System classes *** 85 | 86 | class SpawnSystem : System 87 | { 88 | public: 89 | this(SDL_Window* window, int count) 90 | { 91 | SDL_GetWindowSize(window, &mSizeX, &mSizeY); 92 | mCount = count; 93 | } 94 | 95 | override void run(EntityManager es, EventManager events, Duration dt) 96 | { 97 | int c = 0; 98 | //ComponentHandle collideable; 99 | foreach (entity; es.entitiesWith!Collideable) 100 | c++; 101 | 102 | for (int i = 0; i < mCount - c; i++) 103 | { 104 | Entity entity = es.create(); 105 | 106 | // Mark as collideable (explosion particles will not be collideable). 107 | //todo use "assign" to merge the 2 next instructions 108 | float radius = r(10, 5); 109 | entity.register!Collideable(); 110 | entity.component!Collideable.radius = radius; 111 | //collideable = entity.assign(r(10, 5)); 112 | 113 | // "Physical" attributes. 114 | auto bod = entity.register!Body(); 115 | bod.position = Vector2f(r(mSizeX), r(mSizeY)); 116 | bod.direction = Vector2f(r(300, -150), r(300, -150)); 117 | 118 | // Shape to apply to entity. 119 | auto ren = entity.register!Renderable(); 120 | ren.radius = radius; 121 | ren.color = Color(cast(ubyte)r(128, 127), 122 | cast(ubyte)r(128, 127), 123 | cast(ubyte)r(128, 127)); 124 | } 125 | } 126 | 127 | private: 128 | int mSizeX, mSizeY; 129 | int mCount; 130 | }; 131 | 132 | 133 | // Updates a body's position and rotation. 134 | class MoveSystem : System 135 | { 136 | public: 137 | this(SDL_Window* window) 138 | { 139 | SDL_GetWindowSize(window, &mSizeX, &mSizeY); 140 | } 141 | 142 | override void run(EntityManager es, EventManager events, Duration dt) 143 | { 144 | foreach (entity, bod; es.entitiesWith!Body) 145 | { 146 | // update position 147 | bod.position.x += bod.direction.x * dt.total!"msecs" / 1000.0; 148 | bod.position.y += bod.direction.y * dt.total!"msecs" / 1000.0; 149 | 150 | // make it bounce on the edges of the window 151 | if (bod.position.x < 0.0) 152 | { 153 | bod.position.x = -bod.position.x; 154 | bod.direction.x = -bod.direction.x; 155 | } 156 | else if (bod.position.x >= mSizeX) 157 | { 158 | bod.position.x = 2 * mSizeX - bod.position.x; 159 | bod.direction.x = -bod.direction.x; 160 | } 161 | 162 | if (bod.position.y < 0.0) 163 | { 164 | bod.position.y = -bod.position.y; 165 | bod.direction.y = -bod.direction.y; 166 | } 167 | else if (bod.position.y >= mSizeY) 168 | { 169 | bod.position.y = 2 * mSizeY - bod.position.y; 170 | bod.direction.y = -bod.direction.y; 171 | } 172 | } 173 | } 174 | private: 175 | int mSizeX, mSizeY; 176 | } 177 | 178 | 179 | // Determines if two Collideable bodies have collided. If they have it emits a 180 | // CollisionEvent. This is used by ExplosionSystem to create explosion 181 | // particles, but it could be used by a SoundSystem to play an explosion 182 | // sound, etc.. 183 | // 184 | // Uses a fairly rudimentary 2D partition system, but performs reasonably well. 185 | class CollisionSystem : System 186 | { 187 | public: 188 | this(SDL_Window* window) 189 | { 190 | SDL_GetWindowSize(window, &mSizeX, &mSizeY); 191 | mGrid.length = mSizeX * mSizeY; 192 | } 193 | 194 | override void run(EntityManager es, EventManager events, Duration dt) 195 | { 196 | reset(); 197 | collect(es); 198 | collide(events); 199 | } 200 | 201 | private: 202 | enum int mPartitions = 200; 203 | 204 | struct Candidate 205 | { 206 | Vector2f position; 207 | float radius; 208 | Entity entity; 209 | }; 210 | 211 | Candidate[][] mGrid; 212 | int mSizeX, mSizeY; 213 | 214 | void reset() 215 | { 216 | foreach (ref candidates; mGrid) 217 | candidates.length = 0; 218 | } 219 | 220 | void collect(EntityManager entities) 221 | { 222 | foreach (entity, bod, col; entities.entitiesWith!(Body, Collideable)) 223 | { 224 | auto left = cast(int)(bod.position.x - col.radius) / mPartitions; 225 | auto top = cast(int)(bod.position.y - col.radius) / mPartitions; 226 | auto right = cast(int)(bod.position.x + col.radius) / mPartitions; 227 | auto bottom = cast(int)(bod.position.y + col.radius) / mPartitions; 228 | 229 | auto candidate = Candidate(bod.position, col.radius, entity); 230 | uint[4] slots = [left + top * mSizeX, right + top * mSizeX, 231 | left + bottom * mSizeX, right + bottom * mSizeX]; 232 | mGrid[slots[0]] ~= candidate; 233 | if (slots[0] != slots[1]) 234 | mGrid[slots[1]] ~= candidate; 235 | if (slots[1] != slots[2]) 236 | mGrid[slots[2]] ~= candidate; 237 | if (slots[2] != slots[3]) 238 | mGrid[slots[3]] ~= candidate; 239 | } 240 | } 241 | 242 | void collide(EventManager events) 243 | { 244 | foreach (candidates; mGrid) 245 | foreach (ref candidateA; candidates) 246 | foreach (ref candidateB; candidates) 247 | { 248 | if (candidateA.entity == candidateB.entity) 249 | continue; 250 | if (collided(candidateA, candidateB)) 251 | events.emit!CollisionEvent(candidateA.entity, 252 | candidateB.entity); 253 | } 254 | } 255 | 256 | float length2(const ref Vector2f v) 257 | { 258 | return v.x * v.x + v.y * v.y; 259 | } 260 | 261 | bool collided(in ref Candidate a, in ref Candidate b) 262 | { 263 | auto ab = Vector2f(a.position.x - b.position.x, 264 | a.position.y - b.position.y); 265 | float radius2 = a.radius + b.radius; 266 | radius2 *= radius2; 267 | return length2(ab) < radius2; 268 | } 269 | } 270 | 271 | 272 | class ParticleSystem : System 273 | { 274 | public: 275 | override void run(EntityManager es, EventManager events, Duration dt) 276 | { 277 | foreach (entity, particle; es.entitiesWith!Particle) 278 | { 279 | particle.alpha -= particle.d * dt.total!"msecs"; 280 | if (particle.alpha <= 0) 281 | entity.destroy(); 282 | } 283 | } 284 | } 285 | 286 | 287 | class ParticleRenderSystem : System 288 | { 289 | public: 290 | this(SDL_Renderer* renderer) 291 | { 292 | mpRenderer = renderer; 293 | } 294 | 295 | override void run(EntityManager es, EventManager events, Duration dt) 296 | { 297 | foreach (entity, bod, particle; es.entitiesWith!(Body, Particle)) 298 | { 299 | auto radius = particle.radius; 300 | // Change color 301 | SDL_SetRenderDrawColor(mpRenderer, 302 | particle.color.r, 303 | particle.color.g, 304 | particle.color.b, 305 | cast(ubyte)particle.alpha ); 306 | SDL_Rect rect; 307 | rect.x = cast(int)(bod.position.x - radius); 308 | rect.y = cast(int)(bod.position.y - radius); 309 | rect.w = cast(int)(radius * 2); 310 | rect.h = cast(int)(radius * 2); 311 | SDL_RenderFillRect(mpRenderer, &rect); 312 | } 313 | } 314 | 315 | private: 316 | SDL_Renderer* mpRenderer; 317 | } 318 | 319 | 320 | // For any two colliding bodies, destroys the bodies and emits a bunch of bodgy explosion particles. 321 | class ExplosionSystem : System, IReceiver!CollisionEvent 322 | { 323 | public: 324 | override void run(EntityManager es, EventManager events, Duration dt) 325 | { 326 | foreach (entity; mCollisions) 327 | { 328 | // the same entity might be detected by collision several times 329 | if (!entity.valid) 330 | continue; 331 | emitParticles(es, entity); 332 | entity.destroy(); 333 | } 334 | while (!mCollisions.empty) 335 | mCollisions.removeFront(); 336 | } 337 | 338 | void emitParticles(EntityManager es, Entity entity) 339 | { 340 | auto bod = entity.component!Body; 341 | auto ren = entity.component!Renderable; 342 | auto col = entity.component!Collideable; 343 | 344 | float area = (PI * col.radius * col.radius) / 3.0; 345 | for (int i = 0; i < area; i++) 346 | { 347 | Entity particle = es.create(); 348 | 349 | float rotationd = r(720, 180); 350 | if (uniform(0, 2) == 0) 351 | rotationd = -rotationd; 352 | 353 | float offset = r(cast(int)col.radius, 1.0); 354 | float angle = r(360) * PI / 180.0; 355 | 356 | auto partBody = particle.register!Body(); 357 | partBody.position.x = bod.position.x + offset * cos(angle); 358 | partBody.position.y = bod.position.y + offset * sin(angle); 359 | partBody.direction.x = offset * 2 * cos(angle); 360 | partBody.direction.y = offset * 2 * sin(angle); 361 | 362 | float radius = r(3, 1); 363 | auto partPart = particle.register!Particle(); 364 | partPart.color = ren.color; 365 | partPart.radius = radius; 366 | partPart.alpha = 200; 367 | partPart.d = r(3, 1) / 2; 368 | } 369 | } 370 | 371 | void receive(CollisionEvent collision) 372 | { 373 | // Events are immutable, so we can't destroy the entities here. We defer 374 | // the work until the update loop. 375 | mCollisions.insertFront(collision.a); 376 | mCollisions.insertFront(collision.b); 377 | } 378 | 379 | private: 380 | SList!Entity mCollisions; 381 | } 382 | 383 | // Render all Renderable entities 384 | class RenderSystem : System 385 | { 386 | public: 387 | this(SDL_Renderer* renderer) 388 | { 389 | mpRenderer = renderer; 390 | } 391 | 392 | override void run(EntityManager es, EventManager events, Duration dt) 393 | { 394 | foreach (entity, bod, rdr; es.entitiesWith!(Body, Renderable)) 395 | { 396 | auto radius = rdr.radius; 397 | // Change color 398 | SDL_SetRenderDrawColor(mpRenderer, 399 | rdr.color.r, 400 | rdr.color.g, 401 | rdr.color.b, 402 | 255 ); 403 | SDL_Rect rect; 404 | rect.x = cast(int)(bod.position.x - radius); 405 | rect.y = cast(int)(bod.position.y - radius); 406 | rect.w = cast(int)(radius * 2); 407 | rect.h = cast(int)(radius * 2); 408 | SDL_RenderFillRect(mpRenderer, &rect); 409 | } 410 | } 411 | 412 | private: 413 | SDL_Renderer* mpRenderer; 414 | } 415 | 416 | 417 | class Application : EntitySysD 418 | { 419 | public: 420 | this(SDL_Renderer* renderer, SDL_Window* window) 421 | { 422 | super(); 423 | systems.register(new SpawnSystem(window, 20)); 424 | systems.register(new MoveSystem(window)); 425 | systems.register(new CollisionSystem(window)); 426 | systems.register(new ExplosionSystem); 427 | systems.register(new ParticleSystem); 428 | systems.register(new RenderSystem(renderer)); 429 | systems.register(new ParticleRenderSystem(renderer)); 430 | } 431 | 432 | void run(Duration dt) 433 | { 434 | systems.runFull(dt); 435 | } 436 | } 437 | 438 | 439 | class StatReceiver : IReceiver!StatEvent 440 | { 441 | void receive(StatEvent event) 442 | { 443 | auto systems = event.systemManager; 444 | writefln("All: %d/16000µs", 445 | systems.statAll.average.total!"usecs"); 446 | foreach (sys; systems[]) 447 | writefln(" - %s: %d/16000µs", 448 | sys.name, sys.stat.average.total!"usecs"); 449 | } 450 | } 451 | 452 | void main() 453 | { 454 | DerelictSDL2.load(); 455 | scope(exit) DerelictSDL2.unload(); 456 | 457 | if (SDL_Init(SDL_INIT_EVERYTHING) == -1) 458 | return; 459 | 460 | SDL_Window* window = SDL_CreateWindow("EntitySysD example", 461 | 0, 0, 640, 480, 0); 462 | SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); 463 | SDL_RenderSetLogicalSize(renderer, 640, 480); 464 | 465 | auto app = new Application(renderer, window); 466 | 467 | bool loop = true; 468 | MonoTime timestamp = MonoTime.currTime; 469 | 470 | static if (true) 471 | { 472 | app.events.subscribe!StatEvent(new StatReceiver); 473 | } 474 | 475 | while (loop) 476 | { 477 | SDL_Event event; 478 | while (SDL_PollEvent(&event)) 479 | { 480 | if (event.type == SDL_QUIT) 481 | loop = false; 482 | } 483 | 484 | SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); 485 | SDL_RenderClear(renderer); 486 | 487 | app.run(dur!"msecs"(16)); 488 | 489 | SDL_RenderPresent(renderer); 490 | 491 | MonoTime now = MonoTime.currTime; 492 | Duration timeElapsed = now - timestamp; 493 | long delay = 16 - timeElapsed.total!"msecs"; 494 | if (delay < 0) 495 | delay = 0; 496 | 497 | // Add a 16msec delay to run at ~60 fps 498 | SDL_Delay(cast(uint)delay); 499 | timestamp = MonoTime.currTime; 500 | } 501 | } -------------------------------------------------------------------------------- /source/entitysysd/component.d: -------------------------------------------------------------------------------- 1 | /** 2 | Component facilities module. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.component; 23 | 24 | // UDA for component types 25 | enum component; 26 | 27 | /** 28 | * To be a valid component, $(D C) must: 29 | * - be a $(D struct) or $(D union) 30 | * - have the UDA $(D component) 31 | * - must contain fields without $(D shared) qualifier) 32 | */ 33 | template isComponent(C) 34 | { 35 | import std.meta : allSatisfy; 36 | import std.traits : RepresentationTypeTuple, isMutable, hasUDA; 37 | 38 | enum bool isNotShared(F) = !is(F == shared); 39 | static if (__traits(compiles, hasUDA!(C, component))) 40 | enum bool isComponent = (is(C == struct) || is(C == union)) && 41 | hasUDA!(C, component) && 42 | allSatisfy!(isNotShared, 43 | RepresentationTypeTuple!C); 44 | else 45 | enum bool isComponent = false; 46 | } 47 | 48 | template areComponents(CList...) 49 | { 50 | import std.meta : allSatisfy; 51 | enum bool areComponents = allSatisfy!(isComponent, CList); 52 | } 53 | 54 | 55 | struct BaseComponentCounter 56 | { 57 | static size_t counter = 0; 58 | } 59 | 60 | struct ComponentCounter(Derived) 61 | { 62 | public: 63 | static size_t getId() 64 | { 65 | static size_t counter = -1; 66 | if (counter == -1) 67 | { 68 | counter = mBaseComponentCounter.counter; 69 | mBaseComponentCounter.counter++; 70 | } 71 | 72 | return counter; 73 | } 74 | 75 | private: 76 | BaseComponentCounter mBaseComponentCounter; 77 | } 78 | 79 | 80 | //****************************************************************************** 81 | //***** UNIT-TESTS 82 | //****************************************************************************** 83 | 84 | /// 85 | unittest 86 | { 87 | @component struct TestComponent0 88 | { 89 | int a, b; 90 | } 91 | 92 | @component class TestComponent1 // component cannot be a class 93 | { 94 | string str; 95 | } 96 | 97 | @component union TestComponent2 98 | { 99 | float f; 100 | uint u; 101 | } 102 | 103 | static assert(!isComponent!int); 104 | static assert(isComponent!TestComponent0); 105 | static assert(!isComponent!TestComponent1); 106 | static assert(isComponent!TestComponent2); 107 | } -------------------------------------------------------------------------------- /source/entitysysd/entity.d: -------------------------------------------------------------------------------- 1 | /** 2 | Entity management module. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.entity; 23 | 24 | import std.bitmanip; 25 | import std.container; 26 | import std.string; 27 | 28 | import entitysysd.component; 29 | import entitysysd.event; 30 | import entitysysd.exception; 31 | import entitysysd.pool; 32 | 33 | /// Attribute to use uppon component struct's and union's. 34 | public import entitysysd.component : component; 35 | 36 | /** 37 | * Entity structure. 38 | * 39 | * This is the combination of two 32-bits id: a unique-id and a version-id. 40 | */ 41 | struct Entity 42 | { 43 | public: 44 | static struct Id 45 | { 46 | public: 47 | this(uint uId, uint vId) 48 | { 49 | mId = cast(ulong)uId | cast(ulong)vId << 32; 50 | } 51 | 52 | ulong id() const @property 53 | { 54 | return mId; 55 | } 56 | uint uniqueId() @property 57 | { 58 | return mId & 0xffffffffUL; 59 | } 60 | uint versionId() @property 61 | { 62 | return mId >> 32; 63 | } 64 | 65 | bool opEquals()(auto const ref Id lId) const 66 | { 67 | return id == lId.id; 68 | } 69 | 70 | string toString() 71 | { 72 | return format("#%d:%d", uniqueId, versionId); 73 | } 74 | 75 | private: 76 | ulong mId; 77 | } 78 | 79 | enum Id invalid = Id(0, 0); 80 | 81 | this(EntityManager manager, Id id) 82 | { 83 | mManager = manager; 84 | mId = id; 85 | } 86 | 87 | /** 88 | * Destroy the entity (unregister all attached components). 89 | * 90 | * Throws: EntityException if the entity is invalid. 91 | */ 92 | void destroy() 93 | { 94 | enforce!EntityException(valid); 95 | mManager.destroy(mId); 96 | invalidate(); 97 | } 98 | 99 | /** 100 | * Tells whether the entity is valid. 101 | * 102 | * Returns: true if the entity is valid, false otherwise. 103 | */ 104 | bool valid() @property 105 | { 106 | return mManager !is null && mManager.valid(mId); 107 | } 108 | 109 | /** 110 | * Invalidate the entity instance (but does not destroy it). 111 | */ 112 | void invalidate() 113 | { 114 | mId = invalid; 115 | mManager = null; 116 | } 117 | 118 | /** 119 | * Returns the id of the entity. 120 | */ 121 | Id id() const @property 122 | { 123 | return mId; 124 | } 125 | 126 | /** 127 | * Register a component C to an entity. 128 | * 129 | * Params: 130 | * C = Component to register. 131 | * args = List of arguments to initialize the component, will be passed to 132 | * its constructor. Optional. 133 | * 134 | * Returns: A pointer on the component for this entity. 135 | * 136 | * Throws: $(D EntityException) if the entity is invalid. 137 | * $(D ComponentException) if there is no room for that component or 138 | * if the component is already registered. 139 | */ 140 | C* register(C, Args...)(Args args) 141 | if (isComponent!C) 142 | { 143 | enforce!EntityException(valid); 144 | auto component = mManager.register!C(mId); 145 | static if (Args.length != 0) 146 | *component = C(args); 147 | return component; 148 | } 149 | 150 | /** 151 | * Unregister a component C from an entity. 152 | * 153 | * Params: 154 | * C = Component to unregister. 155 | * 156 | * Throws: $(D EntityException) if the entity is invalid. 157 | * $(D ComponentException) if the component is not registered. 158 | */ 159 | void unregister(C)() 160 | if (isComponent!C) 161 | { 162 | enforce!EntityException(valid); 163 | mManager.unregister!C(mId); 164 | } 165 | 166 | /** 167 | * Get a component pointer of the entity. 168 | * 169 | * Params: 170 | * C = Component for the entity. 171 | * 172 | * Returns: A pointer on the component for this entity. 173 | * 174 | * Throws: $(D EntityException) if the entity is invalid. 175 | * $(D ComponentException) if the component is not registered. 176 | */ 177 | C* component(C)() @property 178 | if (isComponent!C) 179 | { 180 | enforce!EntityException(valid); 181 | return mManager.getComponent!(C)(mId); 182 | } 183 | 184 | /** 185 | * Set the value of a component of the entity. 186 | * 187 | * Params: 188 | * C = Component to set. 189 | * 190 | * Throws: $(D EntityException) if the entity is invalid. 191 | * $(D ComponentException) if the component is not registered. 192 | */ 193 | void component(C)(auto ref C c) @property 194 | if (isComponent!C) 195 | { 196 | enforce!EntityException(valid); 197 | *mManager.getComponent!(C)(mId) = c; 198 | } 199 | 200 | /** 201 | * Tell whether a component is registered to the entity. 202 | * 203 | * Params: 204 | * C = Component to test. 205 | * 206 | * Returns: $(D true) if the component is registered to the entity, 207 | * $(D false) otherwise. 208 | * 209 | * Throws: EntityException if the entity is invalid. 210 | */ 211 | bool isRegistered(C)() 212 | if (isComponent!C) 213 | { 214 | enforce!EntityException(valid); 215 | return mManager.isRegistered!C(mId); 216 | } 217 | 218 | /** 219 | * Iterate over the components registered to the entity. It calls the 220 | * accessor delegate that has been set to each component. 221 | * 222 | * Throws: $(D EntityException) if the entity is invalid. 223 | */ 224 | void iterate() 225 | { 226 | enforce!EntityException(valid); 227 | mManager.iterate(this); 228 | } 229 | 230 | /** 231 | * Compare two entities and tells whether they are the same (same id). 232 | */ 233 | bool opEquals()(auto const ref Entity e) const 234 | { 235 | return id == e.id; 236 | } 237 | 238 | /** 239 | * Returns a string representation of an entity. 240 | * 241 | * It has the form: #uid:vid where uid is the unique-id and 242 | * vid is the version-id 243 | */ 244 | string toString() 245 | { 246 | return mId.toString(); 247 | } 248 | 249 | private: 250 | EntityManager mManager; 251 | Id mId = invalid; 252 | } 253 | 254 | /// 255 | unittest 256 | { 257 | @component struct Position 258 | { 259 | float x, y; 260 | } 261 | 262 | auto em = new EntityManager(new EventManager); 263 | auto entity = em.create(); 264 | auto posCompPtr = entity.register!Position(2.0, 3.0); 265 | 266 | assert(posCompPtr == entity.component!Position); 267 | assert(posCompPtr.x == 2.0); 268 | assert(entity.component!Position.y == 3.0); 269 | } 270 | 271 | /** 272 | * Manages entities creation and component memory management. 273 | */ 274 | class EntityManager 275 | { 276 | public: 277 | /** 278 | * Constructor of the entity-manager. 279 | * Params: 280 | * eventManager = May be used to notify about entity creation and 281 | * component registration. 282 | * maxComponent = Maximum number of components supported by the whole 283 | * manager. 284 | * poolSize = Chunk size in bytes for each components. 285 | */ 286 | this(EventManager eventManager, 287 | size_t maxComponent = 64, 288 | size_t poolSize = 8192) 289 | { 290 | mEventManager = eventManager; 291 | mMaxComponent = maxComponent; 292 | mPoolSize = poolSize; 293 | } 294 | 295 | /** 296 | * Current number of managed entities. 297 | */ 298 | size_t size() @property 299 | { 300 | return mEntityComponentMask.length - mNbFreeIds; 301 | } 302 | 303 | /** 304 | * Current capacity entity. 305 | */ 306 | size_t capacity() @property 307 | { 308 | return mEntityComponentMask.length; 309 | } 310 | 311 | /** 312 | * Return true if the given entity ID is still valid. 313 | */ 314 | bool valid(Entity.Id id) 315 | { 316 | return id != Entity.invalid && 317 | id.uniqueId-1 < mEntityVersions.length && 318 | mEntityVersions[id.uniqueId-1] == id.versionId; 319 | } 320 | 321 | /** 322 | * Create an entity. 323 | * 324 | * Returns: a new valid entity. 325 | */ 326 | Entity create() 327 | { 328 | uint uniqueId, versionId; 329 | 330 | if (mFreeIds.empty) 331 | { 332 | mIndexCounter++; 333 | uniqueId = mIndexCounter; 334 | accomodateEntity(); 335 | versionId = mEntityVersions[uniqueId-1]; 336 | } 337 | else 338 | { 339 | uniqueId = mFreeIds.front; 340 | mFreeIds.removeFront(); 341 | mNbFreeIds--; 342 | versionId = mEntityVersions[uniqueId-1]; 343 | } 344 | 345 | Entity entity = Entity(this, Entity.Id(uniqueId, versionId)); 346 | 347 | return entity; 348 | } 349 | 350 | /** 351 | * Returns an entity from an an entity-id 352 | * 353 | * Returns: the entity from the id. 354 | * 355 | * Throws: EntityException if the id is invalid. 356 | */ 357 | Entity getEntity(Entity.Id id) 358 | { 359 | enforce!EntityException(valid(id)); 360 | return Entity(this, id); 361 | } 362 | 363 | //*** Browsing features *** 364 | 365 | /** 366 | * Allows to browse through all the valid entities of the manager with 367 | * a foreach loop. 368 | * 369 | * Examples: 370 | * -------------------- 371 | * foreach (entity; entityManager) 372 | * { ... } 373 | * -------------------- 374 | */ 375 | int opApply(int delegate(Entity entity) dg) 376 | { 377 | int result = 0; 378 | 379 | // copy version-ids 380 | auto versionIds = mEntityVersions.dup; 381 | // and remove those that are free 382 | foreach (freeId; mFreeIds) 383 | versionIds[freeId-1] = uint.max; 384 | 385 | foreach (uniqueId, versionId; versionIds) 386 | { 387 | if (versionId == uint.max) 388 | continue; 389 | result = dg(Entity(this, 390 | Entity.Id(cast(uint)uniqueId+1, versionId))); 391 | if (result) 392 | break; 393 | } 394 | 395 | return result; 396 | } 397 | 398 | 399 | /** 400 | * Return a range of all the valid instances of a component. 401 | */ 402 | auto components(C)() @property 403 | if (isComponent!C) 404 | { 405 | import std.range : iota; 406 | import std.algorithm : map, filter; 407 | 408 | immutable compId = componentId!C(); 409 | 410 | // if no such component has ever been registered, no pool will exist. 411 | auto pool = cast(Pool!C)mComponentPools[compId]; 412 | assert(pool !is null, "A component pool should never be null"); 413 | 414 | return iota(0, pool.nbElements) 415 | .filter!(i => mEntityComponentMask[i][compId]) 416 | .map!(i => &pool[i]); 417 | } 418 | 419 | /** 420 | * Allows to browse through the entities that have a required set of 421 | * components. 422 | * 423 | * Examples: 424 | * -------------------- 425 | * foreach (entity; entityManager.entitiesWith!(CompA, CompB)) 426 | * { ... } 427 | * -------------------- 428 | */ 429 | auto entitiesWith(CList...)() @property 430 | if (areComponents!CList) 431 | { 432 | struct EntitiesWithView(CList...) 433 | if (areComponents!CList) 434 | { 435 | this(EntityManager em) 436 | { 437 | entityManager = em; 438 | } 439 | 440 | int opApply(int delegate(Entity entity) dg) 441 | { 442 | int result = 0; 443 | 444 | entityLoop: foreach (i, ref componentMask; 445 | entityManager.mEntityComponentMask) 446 | { 447 | foreach (C; CList) 448 | { 449 | auto compId = entityManager.componentId!C(); 450 | if (!componentMask[compId]) 451 | continue entityLoop; 452 | } 453 | 454 | auto versionId = entityManager.mEntityVersions[i]; 455 | result = dg(Entity(entityManager, 456 | Entity.Id(cast(uint)i+1, versionId))); 457 | if (result) 458 | break; 459 | } 460 | 461 | return result; 462 | } 463 | 464 | int opApply(int delegate(Entity entity, Pointers!CList components) dg) 465 | { 466 | auto withComponents(Entity ent) 467 | { 468 | auto get(T)() 469 | { 470 | return ent.component!T; 471 | } 472 | import std.meta : staticMap; 473 | return dg(ent, staticMap!(get, CList)); 474 | } 475 | 476 | return opApply(&withComponents); 477 | } 478 | 479 | EntityManager entityManager; 480 | } 481 | return EntitiesWithView!(CList)(this); 482 | } 483 | 484 | alias CompAccessor = void delegate(Entity e, void* pc); 485 | 486 | /** 487 | * Set an accessor delegate for a component. 488 | * 489 | * Params: 490 | * C = Component to which the accessor delegate will be set. 491 | * dg = Delegate that will be called when using $(D Entity.iterate). 492 | * Use $(D null) to clear the accessor. 493 | */ 494 | void accessor(C)(void delegate(Entity e, C* pc) dg) @property 495 | { 496 | immutable compId = ComponentCounter!(C).getId(); 497 | // Make sure the delegate array is large enough 498 | if (mComponentAccessors.length <= compId) 499 | { 500 | if (dg is null) 501 | return; 502 | else 503 | mComponentAccessors.length = compId + 1; 504 | } 505 | mComponentAccessors[compId] = cast(CompAccessor)dg; 506 | } 507 | 508 | /** 509 | * Get the accessor delegate assigned to a component. 510 | * 511 | * Params: 512 | * C = Component from which the accessor delegate will be retreived. 513 | * 514 | * Returns: 515 | * The accessor delegate; null if it has never been set, if it was cleared 516 | * or if the component is missing. 517 | */ 518 | void delegate(Entity e, C* pc) accessor(C)() @property 519 | { 520 | immutable compId = ComponentCounter!(C).getId(); 521 | if (mComponentAccessors.length <= compId) 522 | return null; 523 | return cast(void delegate(Entity e, C* pc))mComponentAccessors[compId]; 524 | } 525 | 526 | private: 527 | void destroy(Entity.Id id) 528 | { 529 | uint uniqueId = id.uniqueId; 530 | 531 | // reset all components for that entity 532 | foreach (ref bit; mEntityComponentMask[uniqueId-1]) 533 | bit = 0; 534 | // invalidate its version, incrementing it 535 | mEntityVersions[uniqueId-1]++; 536 | mFreeIds.insertFront(uniqueId); 537 | mNbFreeIds++; 538 | } 539 | 540 | C* register(C)(Entity.Id id) 541 | if (isComponent!C) 542 | { 543 | const auto compId = componentId!(C)(); 544 | enforce!ComponentException(compId < mMaxComponent); 545 | const auto uniqueId = id.uniqueId; 546 | enforce!ComponentException(!mEntityComponentMask[uniqueId-1][compId]); 547 | 548 | // place new component into the pools 549 | auto pool = cast(Pool!C)mComponentPools[compId]; 550 | assert(pool !is null, "A component pool should never be null"); 551 | 552 | // Set the bit for this component. 553 | mEntityComponentMask[uniqueId-1][compId] = true; 554 | 555 | pool.initN(uniqueId-1); 556 | 557 | return &pool[uniqueId-1]; 558 | } 559 | 560 | void unregister(C)(Entity.Id id) 561 | if (isComponent!C) 562 | { 563 | const auto compId = componentId!(C)(); 564 | enforce!ComponentException(compId < mMaxComponent); 565 | const auto uniqueId = id.uniqueId; 566 | enforce!ComponentException(mEntityComponentMask[uniqueId-1][compId]); 567 | 568 | // Remove component bit. 569 | mEntityComponentMask[uniqueId-1][compId] = false; 570 | } 571 | 572 | bool isRegistered(C)(Entity.Id id) 573 | if (isComponent!C) 574 | { 575 | const auto compId = componentId!(C)(); 576 | const auto uniqueId = id.uniqueId; 577 | 578 | if (compId >= mMaxComponent) 579 | return false; 580 | 581 | return mEntityComponentMask[uniqueId-1][compId]; 582 | } 583 | 584 | C* getComponent(C)(Entity.Id id) 585 | if (isComponent!C) 586 | { 587 | const auto compId = componentId!(C)(); 588 | enforce!ComponentException(compId < mMaxComponent); 589 | const auto uniqueId = id.uniqueId; 590 | enforce!ComponentException(mEntityComponentMask[uniqueId-1][compId]); 591 | 592 | // Placement new into the component pool. 593 | Pool!C pool = cast(Pool!C)mComponentPools[compId]; 594 | return &pool[uniqueId-1]; 595 | } 596 | 597 | size_t componentId(C)() 598 | { 599 | immutable compId = ComponentCounter!(C).getId(); 600 | 601 | // ensure we have a pool to hold components of this type 602 | if (mComponentPools.length <= compId) 603 | { 604 | mComponentPools.length = compId + 1; 605 | mComponentPools[compId] = new Pool!C(mIndexCounter); 606 | } 607 | 608 | return compId; 609 | } 610 | 611 | void accomodateEntity() 612 | { 613 | if (mEntityComponentMask.length < mIndexCounter) 614 | { 615 | mEntityComponentMask.length = mIndexCounter; 616 | foreach (ref mask; mEntityComponentMask) 617 | mask.length = mMaxComponent; 618 | mEntityVersions.length = mIndexCounter; 619 | foreach (ref pool; mComponentPools) 620 | pool.accomodate(mIndexCounter); 621 | } 622 | } 623 | 624 | void iterate(Entity entity) 625 | { 626 | const auto uniqueId = entity.id.uniqueId; 627 | 628 | // Iterate over all components registered to that entity 629 | foreach (compId; 0..mComponentAccessors.length) 630 | { 631 | // If the component is registered and has a delegate 632 | if (mEntityComponentMask[uniqueId-1][compId]) 633 | if (mComponentAccessors[compId] !is null) 634 | { 635 | auto compPtr = mComponentPools[compId].getPtr(uniqueId-1); 636 | mComponentAccessors[compId](entity, compPtr); 637 | } 638 | } 639 | } 640 | 641 | // Current number of Entities 642 | uint mIndexCounter = 0; 643 | size_t mMaxComponent; 644 | size_t mPoolSize; 645 | // Event Manager 646 | EventManager mEventManager; 647 | // Array of pools for each component types 648 | BasePool[] mComponentPools; 649 | // Bitmask of components for each entities 650 | // Index into the vector is the Entity.Id 651 | BitArray[] mEntityComponentMask; 652 | // Array of delegates for each component 653 | CompAccessor[] mComponentAccessors; 654 | // Vector of entity version id's 655 | // Incremented each time an entity is destroyed 656 | uint[] mEntityVersions; 657 | // List of available entity id's. 658 | SList!uint mFreeIds; 659 | uint mNbFreeIds; 660 | } 661 | 662 | // Translate a list of types to a list of pointers to those types. 663 | private template Pointers(T...) 664 | { 665 | import std.meta : staticMap; 666 | private alias PtrTo(U) = U*; 667 | alias Pointers = staticMap!(PtrTo, T); 668 | } 669 | 670 | 671 | //****************************************************************************** 672 | //***** UNIT-TESTS 673 | //****************************************************************************** 674 | 675 | import std.stdio; 676 | 677 | unittest 678 | { 679 | auto em = new EntityManager(new EventManager()); 680 | 681 | auto ent0 = em.create(); 682 | assert(em.capacity == 1); 683 | assert(em.size == 1); 684 | assert(ent0.valid); 685 | assert(ent0.id.uniqueId == 1); 686 | assert(ent0.id.versionId == 0); 687 | 688 | ent0.destroy(); 689 | assert(em.capacity == 1); 690 | assert(em.size == 0); 691 | assert(!ent0.valid); 692 | assert(ent0.id.uniqueId == 0); 693 | assert(ent0.id.versionId == 0); 694 | 695 | ent0 = em.create(); 696 | auto ent1 = em.create(); 697 | auto ent2 = em.create(); 698 | assert(em.capacity == 3); 699 | assert(em.size == 3); 700 | assert(ent0.id.uniqueId == 1); 701 | assert(ent0.id.versionId == 1); 702 | assert(ent1.id.uniqueId == 2); 703 | assert(ent1.id.versionId == 0); 704 | assert(ent2.id.uniqueId == 3); 705 | assert(ent2.id.versionId == 0); 706 | 707 | @component struct NameComponent 708 | { 709 | string name; 710 | } 711 | 712 | @component struct PosComponent 713 | { 714 | int x, y; 715 | } 716 | ent0.register!NameComponent(); 717 | ent1.register!NameComponent(); 718 | ent2.register!NameComponent(); 719 | 720 | ent0.register!PosComponent(); 721 | ent2.register!PosComponent(); 722 | 723 | ent0.component!NameComponent.name = "Hello"; 724 | ent1.component!NameComponent.name = "World"; 725 | ent2.component!NameComponent.name = "Again"; 726 | assert(ent0.component!NameComponent.name == "Hello"); 727 | assert(ent1.component!NameComponent.name == "World"); 728 | assert(ent2.component!NameComponent.name == "Again"); 729 | 730 | ent0.component!PosComponent = PosComponent(5, 6); 731 | ent2.component!PosComponent = PosComponent(2, 3); 732 | assert(ent0.component!PosComponent.x == 5); 733 | assert(ent0.component!PosComponent.y == 6); 734 | assert(ent2.component!PosComponent.x == 2); 735 | assert(ent2.component!PosComponent.y == 3); 736 | 737 | //ent1.destroy(); 738 | 739 | // List all current valid entities 740 | foreach (ent; em) 741 | { 742 | assert(ent.valid); 743 | //writeln(ent.component!NameComponent.name); 744 | } 745 | 746 | // List all name components 747 | foreach (comp; em.components!NameComponent) 748 | { 749 | //writeln(comp.name); 750 | } 751 | 752 | // List all name components 753 | foreach (ent; em.entitiesWith!(NameComponent, PosComponent)) 754 | { 755 | assert(ent.valid); 756 | //writeln(ent.component!NameComponent.name); 757 | } 758 | 759 | // Check const fields are properly handled 760 | @component struct ConstComp 761 | { 762 | int a, b; 763 | const float cFloat = 5.0; 764 | immutable int iInt = 5; 765 | } 766 | 767 | ent0.register!ConstComp(); 768 | assert(ent0.component!ConstComp.cFloat == 5.0); 769 | 770 | // Check immutable fields are not accepted 771 | @component struct ImmutableComp 772 | { 773 | int a, b; 774 | shared float sFloat = 5.0; 775 | __gshared float gsFloat = 5.0; 776 | } 777 | 778 | // Check it will NOT compile if a field is shared 779 | assert(!__traits(compiles, ent0.register!ImmutableComp())); 780 | } 781 | 782 | unittest 783 | { 784 | @component struct Velocity { int x, y; } 785 | @component struct Position { int x, y; } 786 | 787 | auto em = new EntityManager(new EventManager()); 788 | 789 | auto ent0 = em.create(); 790 | auto ent1 = em.create(); 791 | 792 | ent0.register!Position(0, 0); 793 | ent1.register!Position(4, 5); 794 | 795 | ent0.register!Velocity(1, 2); 796 | ent1.register!Velocity(3, 4); 797 | 798 | // test getting components from the opApply loop 799 | foreach(ent, pos, vel; em.entitiesWith!(Position, Velocity)) 800 | { 801 | pos.x += vel.x; 802 | pos.y += vel.y; 803 | } 804 | 805 | assert(ent0.component!Position.x == 1 && ent0.component!Position.y == 2); 806 | assert(ent1.component!Position.x == 7 && ent1.component!Position.y == 9); 807 | } 808 | 809 | // Ensure that em.components!T does not throw if no `T` has ever been registered 810 | unittest 811 | { 812 | @component struct Dummy { } 813 | 814 | auto em = new EntityManager(new EventManager()); 815 | 816 | foreach(pos ; em.components!Dummy) 817 | assert(0, "Loop should never be entered"); 818 | } 819 | 820 | // Validate fix for a bug where you could end up with uninitialized pools. 821 | // ent.isRegistered would create room for a pool without allocating it, 822 | // potentially creating null pools in the middle of the collection. 823 | // register was only checking the collection length, but did not ensure that the 824 | // pool it retrieved to store the component was non-null. 825 | unittest 826 | { 827 | @component struct Dummy1 { } 828 | @component struct Dummy2 { } 829 | 830 | auto em = new EntityManager(new EventManager()); 831 | auto ent = em.create(); 832 | 833 | assert(!ent.isRegistered!Dummy1); 834 | assert(!ent.isRegistered!Dummy2); 835 | assert(ent.register!Dummy2); 836 | assert(ent.register!Dummy1); 837 | } 838 | 839 | // Test range interface for components!T 840 | unittest 841 | { 842 | @component struct A 843 | { 844 | int a; 845 | } 846 | 847 | @component struct B 848 | { 849 | string b; 850 | } 851 | 852 | auto em = new EntityManager(new EventManager()); 853 | 854 | auto e1 = em.create(); 855 | auto e2 = em.create(); 856 | auto e3 = em.create(); 857 | 858 | e1.register!A(1); 859 | e2.register!B("2"); 860 | e3.register!A(3); 861 | e3.register!B("3"); 862 | 863 | import std.algorithm : map, equal; 864 | assert(em.components!A.map!(x => x.a).equal([1, 3])); 865 | assert(em.components!B.map!(x => x.b).equal(["2", "3"])); 866 | } 867 | 868 | 869 | // Test component accessors 870 | unittest 871 | { 872 | import std.conv; 873 | string output; 874 | 875 | @component struct A 876 | { 877 | int i; 878 | } 879 | 880 | @component struct B 881 | { 882 | string str; 883 | } 884 | 885 | auto em = new EntityManager(new EventManager()); 886 | 887 | auto e1 = em.create(); 888 | auto e2 = em.create(); 889 | auto e3 = em.create(); 890 | 891 | e1.register!A(1); 892 | e2.register!B("hello"); 893 | e3.register!A(3); 894 | e3.register!B("world"); 895 | 896 | void accessorForA(Entity e, A* a) 897 | { 898 | assert(e == e1 || e == e3); 899 | output ~= a.i.to!string; 900 | } 901 | 902 | em.accessor!A = &accessorForA; 903 | assert(em.accessor!A == &accessorForA); 904 | em.accessor!B = (e, b) { output ~= b.str; }; // use lambda 905 | 906 | e1.iterate(); 907 | assert(output == "1"); 908 | 909 | output = ""; 910 | e2.iterate(); 911 | assert(output == "hello"); 912 | 913 | output = ""; 914 | e3.iterate(); 915 | assert(output == "3world"); 916 | } -------------------------------------------------------------------------------- /source/entitysysd/event.d: -------------------------------------------------------------------------------- 1 | /** 2 | Event management module. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.event; 23 | 24 | import std.algorithm; 25 | import std.container; 26 | import std.typecons; 27 | 28 | 29 | /// UDA to use upon event struct's and union's. 30 | enum event; 31 | 32 | private alias ReceiverDelegate = void delegate(...); 33 | 34 | private template isEvent(E) 35 | { 36 | import std.traits : hasUDA; 37 | static if(__traits(compiles, hasUDA!(E, event))) 38 | enum bool isEvent = hasUDA!(E, event) && 39 | (is(E == struct) || is(E == union)); 40 | else 41 | enum bool isEvent = false; 42 | } 43 | 44 | 45 | // Used internally by the EventManager. 46 | private struct BaseEventCounter 47 | { 48 | static size_t counter = 0; 49 | } 50 | 51 | private struct EventCounter(Derived) 52 | { 53 | public: 54 | static size_t getId() 55 | { 56 | static size_t counter = -1; 57 | if (counter == -1) 58 | { 59 | counter = mBaseEventCounter.counter; 60 | mBaseEventCounter.counter++; 61 | } 62 | 63 | return counter; 64 | } 65 | 66 | private: 67 | BaseEventCounter mBaseEventCounter; 68 | } 69 | 70 | 71 | deprecated("Please, use the name `IReceiver` instead.") 72 | alias Receiver = IReceiver; 73 | 74 | /** 75 | * Any receiver class needs to derive from this interface using a specific event 76 | * type and implement receive. 77 | */ 78 | interface IReceiver(E) 79 | if (isEvent!E) 80 | { 81 | /** 82 | * Will be called each time an event of type E is emitted. 83 | */ 84 | void receive(E event); 85 | } 86 | 87 | /// 88 | unittest 89 | { 90 | @event struct MyEvent 91 | { 92 | int data; 93 | } 94 | 95 | class MySystem : IReceiver!MyEvent 96 | { 97 | this(EventManager evtManager) 98 | { 99 | evtManager.subscribe!MyEvent(this); 100 | } 101 | 102 | void receive(MyEvent event) 103 | { 104 | import std.stdio : write; 105 | // do something with event 106 | write(event.data); 107 | } 108 | } 109 | } 110 | 111 | /** 112 | * Manages events and receivers. 113 | */ 114 | class EventManager 115 | { 116 | public: 117 | /** 118 | * Check whether an event has any subscription at all. 119 | */ 120 | bool hasSubscription(E)() @property const 121 | if (isEvent!E) 122 | { 123 | auto eventId = EventCounter!E.getId(); 124 | auto handlerGroup = eventId in mHandlers; 125 | 126 | return handlerGroup !is null; 127 | } 128 | 129 | 130 | /** 131 | * Check whether a receiver class is subscribed to an event. 132 | * Returns: true if it is subscribed, false otherwise. 133 | */ 134 | bool isSubscribed(E)(IReceiver!E receiver) 135 | if (isEvent!E) 136 | { 137 | auto receive = cast(ReceiverDelegate)&receiver.receive; 138 | auto eventId = EventCounter!E.getId(); 139 | auto handlerGroup = eventId in mHandlers; 140 | 141 | if (handlerGroup is null) 142 | return false; 143 | 144 | if ((*handlerGroup).find(receive).length == 0) 145 | return false; 146 | 147 | return true; 148 | } 149 | 150 | /** 151 | * Subscribe a receiver class instance to an event. 152 | */ 153 | void subscribe(E)(IReceiver!E receiver) 154 | if (isEvent!E) 155 | { 156 | auto receive = cast(ReceiverDelegate)&receiver.receive; 157 | auto eventId = EventCounter!E.getId(); 158 | auto handlerGroup = eventId in mHandlers; 159 | 160 | // no subscriber for the event family, so create one, and we're done 161 | if (handlerGroup is null) 162 | { 163 | mHandlers[eventId] = []; 164 | mHandlers[eventId] ~= receive; 165 | return; 166 | } 167 | 168 | // already subscribed? 169 | if ((*handlerGroup).find(receive).length != 0) 170 | return; 171 | 172 | // look for empty spots 173 | foreach (ref rcv; *handlerGroup) 174 | if (rcv is null) 175 | { 176 | rcv = receive; 177 | return; 178 | } 179 | 180 | // else append the subscriber callback to the array 181 | *handlerGroup ~= receive; 182 | } 183 | 184 | /** 185 | * Unsubscribe a receiver class instance from an event. 186 | */ 187 | void unsubscribe(E)(IReceiver!E receiver) 188 | if (isEvent!E) 189 | { 190 | auto receive = cast(ReceiverDelegate)&receiver.receive; 191 | auto eventId = EventCounter!E.getId(); 192 | auto handlerGroup = eventId in mHandlers; 193 | 194 | if (handlerGroup is null) 195 | return; 196 | 197 | foreach (ref rcv; *handlerGroup) 198 | if (rcv == receive) 199 | { 200 | rcv = null; 201 | return; // there should be only one occurence of receive 202 | } 203 | } 204 | 205 | /** 206 | * Emit an event. 207 | * 208 | * It will be dispatched to all receivers that subscribed to it. 209 | */ 210 | void emit(E)(in ref E event) 211 | if (isEvent!E) 212 | { 213 | auto eventId = EventCounter!E.getId(); 214 | auto handlerGroup = eventId in mHandlers; 215 | 216 | if (handlerGroup is null) // no event-receiver registered yet 217 | return; 218 | 219 | foreach (rcv; *handlerGroup) 220 | { 221 | // already subscribed 222 | if (rcv !is null) 223 | { 224 | auto rcvE = cast(void delegate(in E))rcv; 225 | rcvE(event); 226 | } 227 | } 228 | } 229 | 230 | /** ditto */ 231 | void emit(E, Args...)(auto ref Args args) 232 | if (isEvent!E) 233 | { 234 | auto event = E(args); 235 | emit(event); 236 | } 237 | 238 | /// 239 | unittest 240 | { 241 | @event struct MyEvent 242 | { 243 | int data; 244 | } 245 | 246 | auto em = new EventManager; 247 | 248 | auto e = MyEvent(43); 249 | 250 | em.emit(e); 251 | em.emit!MyEvent(42); 252 | } 253 | 254 | private: 255 | 256 | // For each id of event, we have a list of receiver-delegates 257 | ReceiverDelegate[][size_t] mHandlers; 258 | } 259 | 260 | 261 | //****************************************************************************** 262 | //***** UNIT-TESTS 263 | //****************************************************************************** 264 | 265 | version(unittest) 266 | { 267 | 268 | import std.conv; 269 | import std.stdio; 270 | 271 | @event struct TestEvent 272 | { 273 | string data; 274 | } 275 | 276 | @event struct IntEvent 277 | { 278 | int data; 279 | } 280 | 281 | class TestReceiver0 : IReceiver!TestEvent 282 | { 283 | string str; 284 | 285 | this(EventManager evtManager) 286 | { 287 | evtManager.subscribe!TestEvent(this); 288 | } 289 | 290 | void receive(TestEvent event) 291 | { 292 | str ~= event.data; 293 | } 294 | } 295 | 296 | class TestReceiver1 : IReceiver!IntEvent 297 | { 298 | string str; 299 | 300 | this(EventManager evtManager) 301 | { 302 | evtManager.subscribe!IntEvent(this); 303 | // do it aagain, it should silently return without subscribing it 304 | // a second time 305 | evtManager.subscribe!IntEvent(this); 306 | } 307 | 308 | void receive(IntEvent event) 309 | { 310 | str ~= to!string(event.data); 311 | } 312 | } 313 | 314 | class TestReceiver2 : IReceiver!TestEvent, IReceiver!IntEvent 315 | { 316 | string str; 317 | 318 | this(EventManager evtManager) 319 | { 320 | evtManager.subscribe!TestEvent(this); 321 | assert(evtManager.isSubscribed!TestEvent(this)); 322 | assert(!evtManager.isSubscribed!IntEvent(this)); 323 | evtManager.subscribe!IntEvent(this); 324 | } 325 | 326 | void receive(TestEvent event) 327 | { 328 | str ~= event.data; 329 | } 330 | void receive(IntEvent event) 331 | { 332 | str ~= event.data.to!(string)(); 333 | } 334 | } 335 | 336 | } // version(unittest) 337 | 338 | unittest 339 | { 340 | auto strEvt0 = TestEvent("hello"); 341 | auto strEvt1 = TestEvent("world"); 342 | auto intEvt0 = IntEvent(123); 343 | auto intEvt1 = IntEvent(456); 344 | 345 | //*** create a new event manager *** 346 | auto evtManager = new EventManager; 347 | 348 | //*** test with one receiver *** 349 | auto testRcv0 = new TestReceiver0(evtManager); 350 | 351 | evtManager.emit!(TestEvent)("goodbye "); 352 | evtManager.emit(strEvt1); 353 | 354 | assert(testRcv0.str == "goodbye world"); 355 | 356 | //*** test with multiple receiver and multiple events *** 357 | auto testRcv1 = new TestReceiver1(evtManager); 358 | auto testRcv2 = new TestReceiver2(evtManager); 359 | testRcv0.str = ""; // reset string 360 | 361 | evtManager.emit(intEvt0); 362 | evtManager.emit(strEvt1); 363 | evtManager.emit(strEvt0); 364 | evtManager.emit(intEvt1); 365 | evtManager.emit(strEvt0); 366 | evtManager.emit(intEvt0); 367 | evtManager.emit(intEvt1); 368 | 369 | assert(testRcv0.str == "worldhellohello"); 370 | assert(testRcv1.str == "123456123456"); 371 | assert(testRcv2.str == "123worldhello456hello123456"); 372 | 373 | //*** test unsubscribe *** 374 | evtManager.unsubscribe!TestEvent(testRcv2); 375 | testRcv0.str = ""; // reset string 376 | testRcv1.str = ""; // reset string 377 | testRcv2.str = ""; // reset string 378 | 379 | evtManager.emit(intEvt0); 380 | evtManager.emit(strEvt0); 381 | 382 | assert(testRcv0.str == "hello"); 383 | assert(testRcv1.str == "123"); 384 | assert(testRcv2.str == "123"); 385 | 386 | evtManager.unsubscribe!TestEvent(testRcv0); 387 | evtManager.unsubscribe!IntEvent(testRcv2); 388 | evtManager.subscribe!TestEvent(testRcv2); 389 | 390 | evtManager.emit(strEvt1); 391 | evtManager.emit(intEvt1); 392 | 393 | assert(testRcv0.str == "hello"); 394 | assert(testRcv1.str == "123456"); 395 | assert(testRcv2.str == "123world"); 396 | } 397 | 398 | 399 | // validate that sending an event with no registered receivers does not crash 400 | unittest 401 | { 402 | auto evtManager = new EventManager; 403 | 404 | // registers a handler for StringEvent, but not IntEvent 405 | auto testRcv0 = new TestReceiver0(evtManager); 406 | 407 | // a bug caused this to fail when at least 1 receiver was registered but 408 | // no receivers were registered for this event type 409 | evtManager.emit!IntEvent(123); 410 | } 411 | -------------------------------------------------------------------------------- /source/entitysysd/exception.d: -------------------------------------------------------------------------------- 1 | /** 2 | Specific exception definitions for EntitySysD. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.exception; 23 | 24 | public import std.exception; 25 | 26 | class EntityException : Exception 27 | { 28 | this(string msg, string file = null, size_t line = 0) @safe pure nothrow 29 | { 30 | super(msg, file, line); 31 | } 32 | } 33 | 34 | class ComponentException : Exception 35 | { 36 | this(string msg, string file = null, size_t line = 0) @safe pure nothrow 37 | { 38 | super(msg, file, line); 39 | } 40 | } 41 | 42 | class SystemException : Exception 43 | { 44 | this(string msg, string file = null, size_t line = 0) @safe pure nothrow 45 | { 46 | super(msg, file, line); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /source/entitysysd/package.d: -------------------------------------------------------------------------------- 1 | /** 2 | Entry-point module allowing to access all EntitySysD features. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd; 23 | 24 | public import entitysysd.entity; 25 | public import entitysysd.event; 26 | public import entitysysd.exception; 27 | public import entitysysd.system; 28 | 29 | /** 30 | * Meta-class embedding entity, system and event managers. 31 | */ 32 | class EntitySysD 33 | { 34 | /** 35 | * Create entity, system and event managers. 36 | * Params: 37 | * maxComponent = Maximum number of component supported. 38 | * poolSize = Component pool chunk-size. 39 | */ 40 | this(size_t maxComponent = 64, size_t poolSize = 8192) 41 | { 42 | events = new EventManager; 43 | entities = new EntityManager(events, maxComponent, poolSize); 44 | systems = new SystemManager(entities, events); 45 | } 46 | 47 | EventManager events; 48 | EntityManager entities; 49 | SystemManager systems; 50 | } 51 | -------------------------------------------------------------------------------- /source/entitysysd/pool.d: -------------------------------------------------------------------------------- 1 | /** 2 | Memory pool for component storage. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.pool; 23 | 24 | 25 | template hasConst(C) 26 | { 27 | import std.meta : anySatisfy; 28 | import std.traits : RepresentationTypeTuple; 29 | 30 | enum bool isConst(F) = is(F == const); 31 | enum bool hasConst = anySatisfy!(isConst, RepresentationTypeTuple!C); 32 | } 33 | 34 | class BasePool 35 | { 36 | public: 37 | this(size_t elementSize, size_t chunkSize) 38 | { 39 | mElementSize = elementSize; 40 | mChunkSize = chunkSize; 41 | } 42 | 43 | void accomodate(in size_t nbElements) 44 | { 45 | while (nbElements > mMaxElements) 46 | { 47 | mNbChunks++; 48 | mMaxElements = (mNbChunks * mChunkSize) / mElementSize; 49 | } 50 | 51 | if (mData.length < mNbChunks * mChunkSize) 52 | mData.length = mNbChunks * mChunkSize; 53 | mNbElements = nbElements; 54 | } 55 | 56 | size_t nbElements() @property 57 | { 58 | return mNbElements; 59 | } 60 | 61 | size_t nbChunks() @property 62 | { 63 | return mNbChunks; 64 | } 65 | 66 | void* getPtr(size_t n) 67 | { 68 | if (n >= mNbElements) 69 | return null; 70 | size_t offset = n * mElementSize; 71 | return &mData[offset]; 72 | } 73 | 74 | private: 75 | size_t mElementSize; 76 | size_t mChunkSize; 77 | size_t mNbChunks; 78 | size_t mMaxElements; 79 | size_t mNbElements; 80 | void[] mData; 81 | } 82 | 83 | class Pool(T, size_t ChunkSize = 8192) : BasePool 84 | { 85 | this(in size_t n) 86 | { 87 | super(T.sizeof, ChunkSize); 88 | accomodate(n); 89 | } 90 | 91 | ref T opIndex(size_t n) 92 | { 93 | return *cast(T*)getPtr(n); 94 | } 95 | 96 | static if (!hasConst!T) 97 | { 98 | T opIndexAssign(T t, size_t n) 99 | { 100 | *cast(T*)getPtr(n) = t; 101 | return t; 102 | } 103 | } 104 | 105 | void initN(size_t n) 106 | { 107 | import std.conv : emplace; 108 | emplace(&this[n]); 109 | } 110 | } 111 | 112 | 113 | //****************************************************************************** 114 | //***** UNIT-TESTS 115 | //****************************************************************************** 116 | unittest 117 | { 118 | static struct TestComponent 119 | { 120 | int i; 121 | string s; 122 | } 123 | 124 | auto pool0 = new Pool!TestComponent(5); 125 | auto pool1 = new Pool!ulong(2000); 126 | 127 | assert(pool0.nbChunks == 1); 128 | assert(pool1.nbChunks == (2000 * ulong.sizeof + 8191) / 8192); 129 | assert(pool1.getPtr(1) !is null); 130 | assert(pool0.getPtr(5) is null); 131 | 132 | pool0[0].i = 10; pool0[0].s = "hello"; 133 | pool0[3] = TestComponent(5, "world"); 134 | 135 | assert(pool0[0].i == 10 && pool0[0].s == "hello"); 136 | assert(pool0[1].i == 0 && pool0[1].s is null); 137 | assert(pool0[2].i == 0 && pool0[2].s is null); 138 | assert(pool0[3].i == 5 && pool0[3].s == "world"); 139 | assert(pool0[4].i == 0 && pool0[4].s is null); 140 | 141 | pool1[1999] = 325; 142 | assert(pool1[1999] == 325); 143 | } -------------------------------------------------------------------------------- /source/entitysysd/stat.d: -------------------------------------------------------------------------------- 1 | /** 2 | System management module. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.stat; 23 | 24 | public import core.time; 25 | 26 | 27 | /** 28 | * Structure used in the system-manager to do some basic profiling. 29 | */ 30 | struct Stat 31 | { 32 | package: 33 | void start() 34 | { 35 | mLastTime = MonoTime.currTime; 36 | if (mFirstTime == MonoTime.zero) 37 | { 38 | mFirstTime = mLastTime; 39 | mMin = mMax = seconds(0); 40 | mRunCount = 0; 41 | } 42 | } 43 | 44 | void stop() 45 | { 46 | assert(mLastTime != MonoTime.zero); 47 | auto now = MonoTime.currTime; 48 | Duration dur = now - mLastTime; 49 | if (mMin == seconds(0) || dur < mMin) 50 | mMin = dur; 51 | if (mMax < dur) 52 | mMax = dur; 53 | 54 | mSum += dur; 55 | mRunCount++; 56 | } 57 | 58 | void update() 59 | { 60 | if (mRunCount != 0) 61 | mAvg = mSum / mRunCount; 62 | else 63 | mAvg = seconds(0); 64 | mSum = seconds(0); 65 | mFirstTime = MonoTime.zero; 66 | } 67 | 68 | void clear() 69 | { 70 | mMin = mMax = mSum = mAvg = seconds(0); 71 | mFirstTime = mLastTime = MonoTime.zero; 72 | mRunCount = 0; 73 | } 74 | 75 | public: 76 | /** 77 | * Elapsed time since the last update (defined by rate parameter in the 78 | * statistic enabling function of the system-manager). 79 | */ 80 | Duration elapsedTime() @property const 81 | { 82 | return mFirstTime == MonoTime.zero 83 | ? seconds(0) 84 | : MonoTime.currTime - mFirstTime; 85 | } 86 | 87 | deprecated("Please, use `average` instead.") 88 | alias averageDuration = average; 89 | deprecated("Please, use `min` instead.") 90 | alias minDuration = min; 91 | deprecated("Please, use `max` instead.") 92 | alias maxDuration = max; 93 | 94 | /** 95 | * Average duration of the profiled function (during the time defined by the 96 | * rate parameter in the statistic enabling function of the system-manager). 97 | */ 98 | Duration average() @property const 99 | { 100 | return mAvg; 101 | } 102 | 103 | /** 104 | * Minimum measured duration of the profiled function (during the time 105 | * defined by the rate parameter in the statistic enabling function of 106 | * the system-manager). 107 | */ 108 | Duration min() @property const 109 | { 110 | return mMin; 111 | } 112 | 113 | /** 114 | * Maximum measured duration of the profiled function (during the time 115 | * defined by the rate parameter in the statistic enabling function of 116 | * the system-manager). 117 | */ 118 | Duration max() @property const 119 | { 120 | return mMax; 121 | } 122 | 123 | /** 124 | * Number of times the profiled function was called (during the time 125 | * defined by the rate parameter in the statistic enabling function of 126 | * the system-manager). 127 | */ 128 | ulong runCount() @property const 129 | { 130 | return mRunCount; 131 | } 132 | 133 | private: 134 | Duration mMin; 135 | Duration mMax; 136 | Duration mSum; 137 | Duration mAvg; 138 | ulong mRunCount; 139 | MonoTime mLastTime; 140 | MonoTime mFirstTime; 141 | } -------------------------------------------------------------------------------- /source/entitysysd/system.d: -------------------------------------------------------------------------------- 1 | /** 2 | System management module. 3 | 4 | Copyright: © 2015-2016 Claude Merle 5 | Authors: Claude Merle 6 | License: This file is part of EntitySysD. 7 | 8 | EntitySysD is free software: you can redistribute it and/or modify it 9 | under the terms of the Lesser GNU General Public License as published 10 | by the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | EntitySysD is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | Lesser GNU General Public License for more details. 17 | 18 | You should have received a copy of the Lesser GNU General Public License 19 | along with EntitySysD. If not, see $(LINK http://www.gnu.org/licenses/). 20 | */ 21 | 22 | module entitysysd.system; 23 | 24 | public import entitysysd.stat; 25 | 26 | import entitysysd.entity; 27 | import entitysysd.event; 28 | import entitysysd.exception; 29 | import std.algorithm; 30 | import std.container; 31 | import std.format; 32 | import std.range; 33 | import std.typecons; 34 | 35 | 36 | /** 37 | * Default rate at which $(D StatEvent) events are sent. 38 | */ 39 | private immutable Duration defaultStatRate = seconds(5); 40 | 41 | 42 | /** 43 | * Event sent regularly (depending of statRate) to display diverse statistics 44 | * about the $(D SystemManager). 45 | */ 46 | @event struct StatEvent 47 | { 48 | SystemManager systemManager; 49 | } 50 | 51 | /** 52 | * Enum allowing to give special order of a system when registering it to the 53 | * $(D SystemManager). 54 | */ 55 | struct Order 56 | { 57 | public: 58 | /// Fisrt place in the list. 59 | static auto first() @property 60 | { 61 | return Order(true, null); 62 | } 63 | /// Last place in the list. 64 | static auto last() @property 65 | { 66 | return Order(false, null); 67 | } 68 | /// Place before $(D system) in the list. 69 | static auto before(S : System)(S system) 70 | { 71 | return Order(true, cast(System)system); 72 | } 73 | /// Place after $(D system) in the list. 74 | static auto after(S : System)(S system) 75 | { 76 | return Order(false, cast(System)system); 77 | } 78 | 79 | private: 80 | bool mIsFirstOrBefore; 81 | System mSystem; 82 | } 83 | 84 | /** 85 | * Deprecated. Alias to keep relative backward compatibility with older 86 | * interface. 87 | */ 88 | deprecated("Please, use the abstract class `System` instead.") 89 | alias ISystem = System; 90 | 91 | /** 92 | * System abstract class. System classes may derive from it and override 93 | * $(D prepare), $(D run) or $(D unprepare). 94 | */ 95 | abstract class System 96 | { 97 | protected: 98 | /** 99 | * Prepare any data for the frame before a proper run. 100 | */ 101 | void prepare(EntityManager entities, EventManager events, Duration dt) 102 | { 103 | } 104 | 105 | /** 106 | * Called by the system-manager anytime its method run is called. 107 | */ 108 | void run(EntityManager entities, EventManager events, Duration dt) 109 | { 110 | } 111 | 112 | /** 113 | * Unprepare any data for the frame after the run. 114 | */ 115 | void unprepare(EntityManager entities, EventManager events, Duration dt) 116 | { 117 | } 118 | 119 | public: 120 | /** 121 | * Change ordering of the system in the system-manager list. 122 | * 123 | * Throw: 124 | * - A $(D SystemException) if the system is not registered. 125 | */ 126 | final void reorder(Order order) 127 | { 128 | enforce!SystemException(mManager !is null); 129 | 130 | auto sr = mManager.mSystems[].find(this); 131 | enforce!SystemException(!sr.empty); 132 | 133 | mManager.mSystems.linearRemove(sr.take(1)); 134 | 135 | mManager.insert(this, order); 136 | } 137 | 138 | /** 139 | * Name of system (given once at the registration by the system-manager). 140 | */ 141 | final string name() @property const 142 | { 143 | return mName; 144 | } 145 | 146 | /** 147 | * Reference on the system statistics. 148 | */ 149 | final ref const(Stat) stat() @property const 150 | { 151 | return mStat; 152 | } 153 | 154 | private: 155 | string mName; 156 | SystemManager mManager; 157 | Stat mStat; 158 | } 159 | 160 | 161 | /** 162 | * Entry point for systems. Allow to register systems. 163 | */ 164 | class SystemManager 165 | { 166 | public: 167 | this(EntityManager entityManager, 168 | EventManager eventManager) 169 | { 170 | mEntityManager = entityManager; 171 | mEventManager = eventManager; 172 | mStatRate = defaultStatRate; 173 | } 174 | 175 | /** 176 | * Register a new system. 177 | * 178 | * If `flag` is `Yes.AutoSubscribe` (default), this will automatically 179 | * subscribe `system` to any events for which it implements `Receiver`. 180 | * Note that this will not work if `system` is passed as `System` -- it 181 | * should be passed as its full type. 182 | * 183 | * Throws: SystemException if the system was already registered. 184 | */ 185 | void register(S : System) 186 | (S system, 187 | Order order = Order.last, 188 | Flag!"AutoSubscribe" flag = Yes.AutoSubscribe) 189 | { 190 | // Check system is not already registered 191 | auto sr = mSystems[].find(system); 192 | enforce!SystemException(sr.empty); 193 | 194 | insert(system, order); 195 | 196 | auto s = cast(System)system; 197 | s.mName = S.stringof ~ format("@%04x", cast(ushort)cast(void*)system); 198 | s.mManager = this; 199 | 200 | // auto-subscribe to events 201 | if (flag) 202 | { 203 | import std.traits : InterfacesTuple; 204 | foreach (Interface ; InterfacesTuple!S) 205 | { 206 | static if (is(Interface : IReceiver!E, E)) 207 | mEventManager.subscribe!E(system); 208 | } 209 | } 210 | } 211 | 212 | /// ditto 213 | void register(S : System) 214 | (S system, Flag!"AutoSubscribe" flag) 215 | { 216 | register(system, Order.last, flag); 217 | } 218 | 219 | /** 220 | * Unregister a system. 221 | * 222 | * If `flag` is `Yes.AutoSubscribe` (default), this will automatically 223 | * unsubscribe `system` from any events for which it implements `Receiver`. 224 | * Note that this will not work if `system` is passed as `System` -- it 225 | * should be passed as its full type. 226 | * 227 | * Throws: SystemException if the system was not registered. 228 | */ 229 | void unregister(S : System)(S system, 230 | Flag!"AutoSubscribe" flag = Yes.AutoSubscribe) 231 | { 232 | auto sr = mSystems[].find(system); 233 | enforce!SystemException(!sr.empty); 234 | 235 | mSystems.linearRemove(sr.take(1)); 236 | 237 | auto s = cast(System)system; 238 | s.mManager = null; 239 | 240 | // auto-unsubscribe from events 241 | if (flag) 242 | { 243 | import std.traits : InterfacesTuple; 244 | foreach (Interface ; InterfacesTuple!S) 245 | { 246 | static if (is(Interface : IReceiver!E, E)) 247 | mEventManager.unsubscribe!E(system); 248 | } 249 | } 250 | } 251 | 252 | /** 253 | * Prepare all the registered systems. 254 | * 255 | * They are prepared in the order that they were registered. 256 | */ 257 | void prepare(Duration dt) 258 | { 259 | foreach (s; mSystems) 260 | s.prepare(mEntityManager, mEventManager, dt); 261 | } 262 | 263 | /** 264 | * Run all the registered systems. 265 | * 266 | * They are runt in the order that they were registered. 267 | */ 268 | void run(Duration dt) 269 | { 270 | if (mStatEnabled || mEventManager.hasSubscription!StatEvent) 271 | mStatRun.start(); 272 | 273 | foreach (sys; mSystems) 274 | { 275 | if (mStatEnabled || mEventManager.hasSubscription!StatEvent) 276 | sys.mStat.start(); 277 | sys.run(mEntityManager, mEventManager, dt); 278 | if (mStatEnabled || mEventManager.hasSubscription!StatEvent) 279 | sys.mStat.stop(); 280 | } 281 | 282 | if (mStatEnabled || mEventManager.hasSubscription!StatEvent) 283 | mStatRun.stop(); 284 | } 285 | 286 | /** 287 | * Unprepare all the registered systems. 288 | * 289 | * They are unprepared in the reverse order that they were registered. 290 | */ 291 | void unprepare(Duration dt) 292 | { 293 | foreach_reverse (s; mSystems) 294 | s.unprepare(mEntityManager, mEventManager, dt); 295 | } 296 | 297 | /** 298 | * Prepare, run and unprepare all the registered systems. 299 | */ 300 | void runFull(Duration dt) 301 | { 302 | if (mStatEnabled || mEventManager.hasSubscription!StatEvent) 303 | mStatAll.start(); 304 | 305 | prepare(dt); 306 | run(dt); 307 | unprepare(dt); 308 | 309 | if (mStatEnabled || mEventManager.hasSubscription!StatEvent) 310 | { 311 | mStatAll.stop(); 312 | 313 | if (mStatAll.elapsedTime >= mStatRate) 314 | { 315 | mStatRun.update(); 316 | mStatAll.update(); 317 | foreach (sys; mSystems) 318 | sys.mStat.update(); 319 | 320 | if (mStatDg !is null) 321 | mStatDg(); 322 | mEventManager.emit!StatEvent(this); 323 | } 324 | } 325 | } 326 | 327 | 328 | /** 329 | * Return a bidirectional range on the list of the registered systems. 330 | */ 331 | auto opSlice() 332 | { 333 | return mSystems[]; 334 | } 335 | 336 | /** 337 | * Reference on profiling statistics of all the system's run. 338 | */ 339 | final ref const(Stat) statRun() @property const 340 | { 341 | return mStatRun; 342 | } 343 | 344 | /** 345 | * Reference on profiling statistics of all the system's prepare, unprepare 346 | * and run. 347 | */ 348 | final ref const(Stat) statAll() @property const 349 | { 350 | return mStatAll; 351 | } 352 | 353 | /** 354 | * Enable statistics profiling on the system-manager and all its 355 | * registered systems. 356 | * A delegate $(D dg) can be given, the $(D rate) at which it will be called 357 | * to provide significant stat's. 358 | */ 359 | deprecated("Please, use `subscribe` with `StatEvent` to enable stat " ~ 360 | "notifications. And use `statRate` to control the rate.") 361 | void enableStat(Duration rate = seconds(0), void delegate() dg = null) 362 | { 363 | mStatEnabled = true; 364 | mStatRate = rate; 365 | mStatDg = dg; 366 | } 367 | 368 | /** 369 | * Disable statistics profiling on the system-manager and all its 370 | * registered systems. 371 | */ 372 | deprecated("Please, use `unsubscribe` with `StatEvent` to disable stat " ~ 373 | "notifications.") 374 | void disableStat() 375 | { 376 | mStatEnabled = false; 377 | mStatRun.clear(); 378 | mStatAll.clear(); 379 | foreach (sys; mSystems) 380 | sys.mStat.clear(); 381 | } 382 | 383 | /** 384 | * Tells whether statistics profiling is enabled or not. 385 | */ 386 | bool statEnabled() @property const 387 | { 388 | return mStatEnabled || mEventManager.hasSubscription!StatEvent; 389 | } 390 | 391 | /** 392 | * Set/get rate at which $(D StatEvent) events are sent. 393 | */ 394 | auto statRate() const @property 395 | { 396 | return mStatRate; 397 | } 398 | 399 | /// ditto 400 | void statRate(Duration rate) @property 401 | { 402 | mStatRate = rate; 403 | } 404 | 405 | private: 406 | void insert(System system, Order order) 407 | { 408 | if (order == Order.first) 409 | { 410 | mSystems.insertFront(cast(System)system); 411 | } 412 | else if (order == Order.last) 413 | { 414 | mSystems.insertBack(cast(System)system); 415 | } 416 | else if (order.mIsFirstOrBefore) 417 | { 418 | auto or = mSystems[].find(order.mSystem); 419 | enforce!SystemException(!or.empty); 420 | mSystems.insertBefore(or, cast(System)system); 421 | } 422 | else //if (!order.mIsFirstOrBefore) 423 | { 424 | auto or = mSystems[]; 425 | enforce!SystemException(!or.empty); 426 | //xxx dodgy, but DList's are tricky 427 | while (or.back != order.mSystem) 428 | { 429 | or.popBack(); 430 | enforce!SystemException(!or.empty); 431 | } 432 | mSystems.insertAfter(or, cast(System)system); 433 | } 434 | } 435 | 436 | EntityManager mEntityManager; 437 | EventManager mEventManager; 438 | DList!System mSystems; 439 | bool mStatEnabled; //todo deprecated 440 | Duration mStatRate; 441 | void delegate() mStatDg; //todo deprecated 442 | Stat mStatAll; 443 | Stat mStatRun; 444 | } 445 | 446 | 447 | //****************************************************************************** 448 | //***** UNIT-TESTS 449 | //****************************************************************************** 450 | 451 | // validate event auto-subscription/unsubscription 452 | unittest 453 | { 454 | @event struct EventA 455 | { 456 | } 457 | 458 | @event struct EventB 459 | { 460 | } 461 | 462 | class MySys : System, IReceiver!EventA, IReceiver!EventB 463 | { 464 | int eventCount; 465 | void receive(EventA ev) 466 | { 467 | ++eventCount; 468 | } 469 | void receive(EventB ev) 470 | { 471 | ++eventCount; 472 | } 473 | } 474 | 475 | auto events = new EventManager; 476 | auto entities = new EntityManager(events); 477 | auto systems = new SystemManager(entities, events); 478 | 479 | auto sys = new MySys; 480 | 481 | // registering the system should subscribe to MyEvent 482 | systems.register(sys); 483 | events.emit!EventA(); 484 | events.emit!EventB(); 485 | assert(sys.eventCount == 2); 486 | 487 | // registering the system should unsubscribe from MyEvent 488 | systems.unregister(sys); 489 | events.emit!EventA(); 490 | events.emit!EventB(); 491 | assert(sys.eventCount == 2); 492 | 493 | // explicitly disallow auto-subscription 494 | systems.register(sys, Order.last, No.AutoSubscribe); 495 | events.emit!EventA(); 496 | events.emit!EventB(); 497 | assert(sys.eventCount == 2); 498 | 499 | // unregister without unsubscribing 500 | systems.unregister(sys); 501 | systems.register(sys, Yes.AutoSubscribe); 502 | systems.unregister(sys, No.AutoSubscribe); 503 | events.emit!EventA(); 504 | events.emit!EventB(); 505 | assert(sys.eventCount == 4); 506 | } 507 | 508 | 509 | // validate ordering 510 | unittest 511 | { 512 | class MySys0 : System 513 | { 514 | } 515 | 516 | class MySys1 : System 517 | { 518 | } 519 | 520 | auto events = new EventManager; 521 | auto entities = new EntityManager(events); 522 | auto systems = new SystemManager(entities, events); 523 | 524 | auto sys0 = new MySys0; 525 | auto sys1 = new MySys1; 526 | auto sys2 = new MySys0; 527 | auto sys3 = new MySys1; 528 | auto sys4 = new MySys0; 529 | auto sys5 = new MySys1; 530 | auto sys6 = new MySys0; 531 | auto sys7 = new MySys1; 532 | 533 | // registering the systems 534 | systems.register(sys0); 535 | systems.register(sys1, Order.last); 536 | systems.register(sys2, Order.first); 537 | systems.register(sys3, Order.first); 538 | systems.register(sys4, Order.after(sys2)); 539 | systems.register(sys5, Order.before(sys3)); 540 | systems.register(sys6, Order.after(sys1)); 541 | systems.register(sys7, Order.before(sys4)); 542 | 543 | // check order is correct 544 | auto sysRange = systems[]; 545 | assert(sysRange.front == sys5); 546 | sysRange.popFront(); 547 | assert(sysRange.front == sys3); 548 | sysRange.popFront(); 549 | assert(sysRange.front == sys2); 550 | sysRange.popFront(); 551 | assert(sysRange.front == sys7); 552 | sysRange.popFront(); 553 | assert(sysRange.front == sys4); 554 | sysRange.popFront(); 555 | assert(sysRange.front == sys0); 556 | sysRange.popFront(); 557 | assert(sysRange.front == sys1); 558 | sysRange.popFront(); 559 | assert(sysRange.front == sys6); 560 | sysRange.popFront(); 561 | assert(sysRange.empty); 562 | 563 | // check re-ordering works 564 | sys3.reorder(Order.first); 565 | 566 | sysRange = systems[]; 567 | assert(sysRange.front == sys3); 568 | sysRange.popFront(); 569 | assert(sysRange.front == sys5); 570 | sysRange.popFront(); 571 | assert(sysRange.front == sys2); 572 | sysRange.popFront(); 573 | assert(!sysRange.empty); 574 | 575 | // check exceptions 576 | auto sysNA = new MySys0; 577 | auto sysNB = new MySys1; 578 | 579 | assert(collectException!SystemException( 580 | systems.register(sys1)) 581 | !is null); 582 | assert(collectException!SystemException( 583 | systems.unregister(sysNA)) 584 | !is null); 585 | assert(collectException!SystemException( 586 | systems.register(sysNA, Order.after(sysNB))) 587 | !is null); 588 | assert(collectException!SystemException( 589 | systems.register(sysNA, Order.before(sysNB))) 590 | !is null); 591 | } 592 | --------------------------------------------------------------------------------