From b280fecad8ad2d063616628d228e46a9881d3ad2 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Thu, 20 Apr 2017 02:15:30 -0700 Subject: [PATCH 01/11] Component Group derive macro --- .travis.yml | 1 + Cargo.toml | 5 + specs/Cargo.toml | 48 +++++ specs/LICENSE | 201 +++++++++++++++++++ specs/README.md | 71 +++++++ {benches => specs/benches}/parallel.rs | 0 {benches => specs/benches}/world.rs | 0 {examples => specs/examples}/basic.rs | 0 {examples => specs/examples}/full.rs | 0 {examples => specs/examples}/serialize.rs | 0 {src => specs/src}/join.rs | 0 {src => specs/src}/lib.rs | 0 {src => specs/src}/storage/check.rs | 0 {src => specs/src}/storage/data.rs | 0 {src => specs/src}/storage/mod.rs | 0 {src => specs/src}/storage/ser.rs | 0 {src => specs/src}/storage/storages.rs | 0 {src => specs/src}/storage/tests.rs | 0 {src => specs/src}/world.rs | 0 {tests => specs/tests}/tests.rs | 0 specs_derive/Cargo.toml | 13 ++ specs_derive/LICENSE | 201 +++++++++++++++++++ specs_derive/README.md | 71 +++++++ specs_derive/examples/derive.rs | 18 ++ specs_derive/src/component.rs | 230 ++++++++++++++++++++++ specs_derive/src/lib.rs | 23 +++ 26 files changed, 882 insertions(+) create mode 100644 specs/Cargo.toml create mode 100644 specs/LICENSE create mode 100644 specs/README.md rename {benches => specs/benches}/parallel.rs (100%) rename {benches => specs/benches}/world.rs (100%) rename {examples => specs/examples}/basic.rs (100%) rename {examples => specs/examples}/full.rs (100%) rename {examples => specs/examples}/serialize.rs (100%) rename {src => specs/src}/join.rs (100%) rename {src => specs/src}/lib.rs (100%) rename {src => specs/src}/storage/check.rs (100%) rename {src => specs/src}/storage/data.rs (100%) rename {src => specs/src}/storage/mod.rs (100%) rename {src => specs/src}/storage/ser.rs (100%) rename {src => specs/src}/storage/storages.rs (100%) rename {src => specs/src}/storage/tests.rs (100%) rename {src => specs/src}/world.rs (100%) rename {tests => specs/tests}/tests.rs (100%) create mode 100644 specs_derive/Cargo.toml create mode 100644 specs_derive/LICENSE create mode 100644 specs_derive/README.md create mode 100644 specs_derive/examples/derive.rs create mode 100644 specs_derive/src/component.rs create mode 100644 specs_derive/src/lib.rs diff --git a/.travis.yml b/.travis.yml index ee403ff95..abaca1b8b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,7 @@ branches: - master script: +- cd specs/ # enter normal specs directory - cargo build --verbose - cargo test --verbose - cargo build --verbose --no-default-features diff --git a/Cargo.toml b/Cargo.toml index 9ceb133a4..95f127dd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,4 @@ +<<<<<<< HEAD [package] name = "specs" version = "0.9.2" @@ -26,6 +27,9 @@ exclude = ["bors.toml", ".travis.yml"] [badges] travis-ci = { repository = "slide-rs/specs" } +[workspace] +members = [ "specs_derive" ] + [dependencies] atom = "0.3" crossbeam = "0.2.10" @@ -63,3 +67,4 @@ required-features = ["common"] [[example]] name = "serialize" required-features = ["serialize"] + diff --git a/specs/Cargo.toml b/specs/Cargo.toml new file mode 100644 index 000000000..1939a4c22 --- /dev/null +++ b/specs/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "specs" +version = "0.9.1" +description = """ +Specs is an Entity-Component System library written in Rust. +Unlike most other ECS libraries out there, it provides + +* easy parallelism +* high flexibility + * contains 5 different storages for components, which can be extended by the user + * it's types are mostly not coupled, so you can easily write some part yourself and + still use Specs + * `System`s may read from and write to components and resources, can depend on each + other and you can use barriers to force several stages in system execution +* high performance for real-world applications +""" +documentation = "https://docs.rs/specs/" +repository = "https://github.com/slide-rs/specs" +homepage = "https://slide-rs.github.io/specs-website/" +keywords = ["gamedev"] +categories = ["concurrency"] +license = "Apache-2.0" +authors = ["slide-rs hackers"] +exclude = ["bors.toml", ".travis.yml"] + +[badges] +travis-ci = { repository = "slide-rs/specs" } + +[dependencies] +atom = "0.3" +fnv = "1.0" +hibitset = "0.1.3" +mopa = "0.2" +shred = "0.4.2" +shred-derive = "0.3" +tuple_utils = "0.2" +rayon = "0.7.1" + +serde = { version = "1.0", optional = true } +serde_derive = { version = "1.0", optional = true } + +[features] +serialize = ["serde", "serde_derive"] + +[dev-dependencies] +cgmath = { version = "0.14", features = ["eders"] } +rand = "0.3" +serde_json = "1.0" diff --git a/specs/LICENSE b/specs/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/specs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/specs/README.md b/specs/README.md new file mode 100644 index 000000000..a23f16cbc --- /dev/null +++ b/specs/README.md @@ -0,0 +1,71 @@ +# specs +[![Build Status](https://travis-ci.org/slide-rs/specs.svg)](https://travis-ci.org/slide-rs/specs) +[![Crates.io](https://img.shields.io/crates/v/specs.svg?maxAge=2592000)](https://crates.io/crates/specs) +[![Gitter](https://badges.gitter.im/slide-rs/specs.svg)](https://gitter.im/slide-rs/specs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Specs is an Entity-Component System written in Rust. It aims for parallel systems execution with high ergonomics and flexibility. The name can be interpret in a number of ways: +- "SPECS Parallel ECS" +- "Super Powerful ECS" +- "Special ECS" + + +#### Classification +According to [ECS Design Crossroads](https://github.com/amethyst/amethyst/wiki/ECS-Design-Crossroads), `specs` fulfills all the requirements, has _In-place modification_ updates, and _Generational ID_ entities. + +#### Features +- Automatic execution of the systems in parallel. Follows Rust ownership rules, where each component storage behaves as a variable. Depends on the order, in which systems are started. +- Component storage is abstract behind the trait. One can use vectors, hashmaps, trees, or whatever else. +- New components can be registered at any point from user modules. They don't have to be POD. +- No virtual calls, low overhead. + +#### Why is it fast +- Do you know many other natively parallel ECS in Rust? +- Abstract storage means you can choose the most efficient one according to your needs. You can even roll in your own. +- No virtual calls during systems processing means you work with the data directly. + +See [ecs_bench](https://github.com/lschmierer/ecs_bench) for single- and multi-threaded performance comparisons. + +#### Why is it cool +- Your system can be as simple as a closure working on some components, no redundant info or boilerplate is needed. At the same time, you can manually fiddle with entities and components, and it would still be safe and convenient. +- Your components can be anything (as long as they implement `Component`)! Neither `Copy` or even `Clone` bounds are needed. +- Your component storages can be anything. Consider crazy stuff like a BSP tree, or a database over the network. Some storages can safely allow sharing their components between entities, some can not - but it's up to you to choose. + +## Examples + +#### Entity creation +```rust +let mut planner = { + let mut w = specs::World::new(); + // All components types should be registered before working with them + w.register::(); + w.register::(); + // create_now() of World provides with an EntityBuilder to add components to an Entity + w.create_now().with(Position(0)).with(Speed(2)).build(); + w.create_now().with(Position(-1)).with(Speed(100)).build(); + w.create_now().with(Position(127)).build(); + // Planner is used to run systems on the specified world with as many + // threads as virtual cpus + specs::Planner::new(w) +}; +``` + +#### System run +In order to run a system, you can either use a convenience-function (`runXwYr`) or a custom one (see below in the section "Custom system" and the examples in the `/examples` directory). Convencience-functions are used to request a defined number of mutable and immutable components on an entity. X and Y stand for the number of parameters respectively. `run1w1r` will allow you to use one mutable and one immutable component requirement respectively, as you can see below. Run-functions always iterate over all entities of a world with the requested components. + +```rust +planner.run1w1r(|p: &mut Position, s: &Speed| { + *p += *s; +}); +``` + +#### Custom system +```rust +impl System for MySystem { + fn run(&mut self, arg: RunArg, context: u32) { + let mut numbers = arg.fetch(|w| w.write::()); + for n in (&numbers).join() { + *n += context; + } + } +} +``` diff --git a/benches/parallel.rs b/specs/benches/parallel.rs similarity index 100% rename from benches/parallel.rs rename to specs/benches/parallel.rs diff --git a/benches/world.rs b/specs/benches/world.rs similarity index 100% rename from benches/world.rs rename to specs/benches/world.rs diff --git a/examples/basic.rs b/specs/examples/basic.rs similarity index 100% rename from examples/basic.rs rename to specs/examples/basic.rs diff --git a/examples/full.rs b/specs/examples/full.rs similarity index 100% rename from examples/full.rs rename to specs/examples/full.rs diff --git a/examples/serialize.rs b/specs/examples/serialize.rs similarity index 100% rename from examples/serialize.rs rename to specs/examples/serialize.rs diff --git a/src/join.rs b/specs/src/join.rs similarity index 100% rename from src/join.rs rename to specs/src/join.rs diff --git a/src/lib.rs b/specs/src/lib.rs similarity index 100% rename from src/lib.rs rename to specs/src/lib.rs diff --git a/src/storage/check.rs b/specs/src/storage/check.rs similarity index 100% rename from src/storage/check.rs rename to specs/src/storage/check.rs diff --git a/src/storage/data.rs b/specs/src/storage/data.rs similarity index 100% rename from src/storage/data.rs rename to specs/src/storage/data.rs diff --git a/src/storage/mod.rs b/specs/src/storage/mod.rs similarity index 100% rename from src/storage/mod.rs rename to specs/src/storage/mod.rs diff --git a/src/storage/ser.rs b/specs/src/storage/ser.rs similarity index 100% rename from src/storage/ser.rs rename to specs/src/storage/ser.rs diff --git a/src/storage/storages.rs b/specs/src/storage/storages.rs similarity index 100% rename from src/storage/storages.rs rename to specs/src/storage/storages.rs diff --git a/src/storage/tests.rs b/specs/src/storage/tests.rs similarity index 100% rename from src/storage/tests.rs rename to specs/src/storage/tests.rs diff --git a/src/world.rs b/specs/src/world.rs similarity index 100% rename from src/world.rs rename to specs/src/world.rs diff --git a/tests/tests.rs b/specs/tests/tests.rs similarity index 100% rename from tests/tests.rs rename to specs/tests/tests.rs diff --git a/specs_derive/Cargo.toml b/specs_derive/Cargo.toml new file mode 100644 index 000000000..7f670aa6b --- /dev/null +++ b/specs_derive/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "specs_derive" +version = "0.1.0" +authors = ["Aceeri "] + +[lib] +proc-macro = true + +[dependencies] +specs = { path = "../specs", version = "0.9.1" } +syn = "0.11.10" +quote = "0.3.15" +serde = "0.9.11" diff --git a/specs_derive/LICENSE b/specs_derive/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/specs_derive/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/specs_derive/README.md b/specs_derive/README.md new file mode 100644 index 000000000..a23f16cbc --- /dev/null +++ b/specs_derive/README.md @@ -0,0 +1,71 @@ +# specs +[![Build Status](https://travis-ci.org/slide-rs/specs.svg)](https://travis-ci.org/slide-rs/specs) +[![Crates.io](https://img.shields.io/crates/v/specs.svg?maxAge=2592000)](https://crates.io/crates/specs) +[![Gitter](https://badges.gitter.im/slide-rs/specs.svg)](https://gitter.im/slide-rs/specs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Specs is an Entity-Component System written in Rust. It aims for parallel systems execution with high ergonomics and flexibility. The name can be interpret in a number of ways: +- "SPECS Parallel ECS" +- "Super Powerful ECS" +- "Special ECS" + + +#### Classification +According to [ECS Design Crossroads](https://github.com/amethyst/amethyst/wiki/ECS-Design-Crossroads), `specs` fulfills all the requirements, has _In-place modification_ updates, and _Generational ID_ entities. + +#### Features +- Automatic execution of the systems in parallel. Follows Rust ownership rules, where each component storage behaves as a variable. Depends on the order, in which systems are started. +- Component storage is abstract behind the trait. One can use vectors, hashmaps, trees, or whatever else. +- New components can be registered at any point from user modules. They don't have to be POD. +- No virtual calls, low overhead. + +#### Why is it fast +- Do you know many other natively parallel ECS in Rust? +- Abstract storage means you can choose the most efficient one according to your needs. You can even roll in your own. +- No virtual calls during systems processing means you work with the data directly. + +See [ecs_bench](https://github.com/lschmierer/ecs_bench) for single- and multi-threaded performance comparisons. + +#### Why is it cool +- Your system can be as simple as a closure working on some components, no redundant info or boilerplate is needed. At the same time, you can manually fiddle with entities and components, and it would still be safe and convenient. +- Your components can be anything (as long as they implement `Component`)! Neither `Copy` or even `Clone` bounds are needed. +- Your component storages can be anything. Consider crazy stuff like a BSP tree, or a database over the network. Some storages can safely allow sharing their components between entities, some can not - but it's up to you to choose. + +## Examples + +#### Entity creation +```rust +let mut planner = { + let mut w = specs::World::new(); + // All components types should be registered before working with them + w.register::(); + w.register::(); + // create_now() of World provides with an EntityBuilder to add components to an Entity + w.create_now().with(Position(0)).with(Speed(2)).build(); + w.create_now().with(Position(-1)).with(Speed(100)).build(); + w.create_now().with(Position(127)).build(); + // Planner is used to run systems on the specified world with as many + // threads as virtual cpus + specs::Planner::new(w) +}; +``` + +#### System run +In order to run a system, you can either use a convenience-function (`runXwYr`) or a custom one (see below in the section "Custom system" and the examples in the `/examples` directory). Convencience-functions are used to request a defined number of mutable and immutable components on an entity. X and Y stand for the number of parameters respectively. `run1w1r` will allow you to use one mutable and one immutable component requirement respectively, as you can see below. Run-functions always iterate over all entities of a world with the requested components. + +```rust +planner.run1w1r(|p: &mut Position, s: &Speed| { + *p += *s; +}); +``` + +#### Custom system +```rust +impl System for MySystem { + fn run(&mut self, arg: RunArg, context: u32) { + let mut numbers = arg.fetch(|w| w.write::()); + for n in (&numbers).join() { + *n += context; + } + } +} +``` diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs new file mode 100644 index 000000000..39a3a14dd --- /dev/null +++ b/specs_derive/examples/derive.rs @@ -0,0 +1,18 @@ + +extern crate specs; +#[macro_use] +extern crate specs_derive; + +#[derive(ComponentGroup)] +struct SomeGroup { + #[group(no_serialize)] + field1: u32, + + #[group(subgroup)] + field2: f32, + field3: String, +} + +fn main() { + +} diff --git a/specs_derive/src/component.rs b/specs_derive/src/component.rs new file mode 100644 index 000000000..4aba32a95 --- /dev/null +++ b/specs_derive/src/component.rs @@ -0,0 +1,230 @@ + +use serde::{self, Serialize, Serializer, Deserialize, Deserializer}; +use serde::de::DeserializeSeed; +use specs::{self, Gate, Join}; + +use syn::{self, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field}; +use quote::{Tokens}; + +use std::marker::PhantomData; + +pub trait ComponentGroup { + /// Components defined in this group, not a subgroup. + fn local_components() -> Vec<&'static str>; + /// Components defined in this group along with subgroups. + fn components() -> Vec<&'static str>; + /// Subgroups included in this group. + fn subgroups() -> Vec<&'static str>; + /// Serializes the group of components from the world. + fn serialize_group(world: &specs::World, serializer: S) -> Result; + /// Helper method for serializing the world. + fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error>; + /// Deserializes the group of components into the world. + fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error>; + /// Helper method for deserializing the world. + fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, visitor: &mut V) -> Result, V::Error> + where V: serde::de::MapVisitor; +} + +pub fn expand_group(input: &DeriveInput) -> Result { + let name = &input.ident; + let (params, fields) = separate_fields(input); + + println!("name: {:?}", name); + println!("params: {:?}", params); + println!("fields: {:?}", fields); + + //let components = fields.zip(params).filter(|f, p| p.subgroup).collect(); + + /* + let expanded = quote! { + impl ComponentGroup for #name { + fn local_components() -> Vec<&'static str> { + vec![ #( stringify!(#component), )* ] + } + fn components() -> Vec<&'static str> { + let mut list = <$name as Group>::local_components(); + #( + for component in <#subgroup as Group>::components() { + list.push(component); + } + )* + list + } + fn subgroups() -> Vec<&'static str> { + vec![ #( stringify!(#subgroup), )* ] + } + fn serialize_group(world: &specs::World, serializer: S) -> Result { + use serde::ser::SerializeMap; + let mut map = serializer.serialize_map(None)?; + #( + map.serialize_key(stringify!(#component))?; + let storage = world.read::<#component>().pass(); + map.serialize_value(&storage)?; + )* + + #( + <#subgroup as Group>::serialize_subgroup::(world, &mut map)?; + )* + + map.end() + } + + fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { + use serde::ser::SerializeMap; + #( + map.serialize_key(stringify!(#component))?; + let storage = world.read::<#component>().pass(); + map.serialize_value(&storage)?; + )* + + #( + <#subgroup as Group>::serialize_subgroup::(world, map)?; + )* + + Ok(()) + } + + fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error> { + use std::fmt; + use specs::PackedData; + + struct ComponentVisitor<'a>(&'a mut specs::World, &'a [specs::Entity]); + impl<'a> serde::de::Visitor for ComponentVisitor<'a> { + type Value = (); + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a map of component identifiers to packed data") + } + + fn visit_map(self, mut visitor: V) -> Result<(), V::Error> + where V: serde::de::MapVisitor + { + while let Some(key) = visitor.visit_key::()? { + match &*key { + #( + stringify!(#component) => { + let mut storage = self.0.write::<#component>().pass(); + let packed = visitor.visit_value::>()?; + storage.merge(self.1, packed); + }, + )* + key @ _ => { + #( + if let Some(()) = <#subgroup as Group>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { + continue; // subgroup deserialized the components + } + )* + continue; // not in the registered component list, ignore + }, + } + } + + Ok(()) + } + } + + Ok(deserializer.deserialize_map(ComponentVisitor(world, entities))?) + } + + fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, mut visitor: &mut V) -> Result, V::Error> + where V: serde::de::MapVisitor + { + match &*key { + #( + stringify!(#component) => { + let mut storage = world.write::<#component>().pass(); + let packed = visitor.visit_value::>()?; + storage.merge(entities, packed); + Ok(Some(())) + }, + )* + key @ _ => { + #( + if let Some(()) = <#subgroup as Group>::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { + return Ok(Some(())); + } + )* + Ok(None) + }, + } + } + } + }; + */ + + let expanded = quote! { + + }; + + Ok(expanded) +} + +#[derive(Debug)] +enum ParameterType { + // Parameters relating to subgroups only + Subgroup { + + }, + // Parameters relating to components only + Component { + + }, +} + +#[derive(Debug)] +struct Parameter { + // Type of parameter + pub option: ParameterType, + + // Serialize this field + pub serialize: bool, +} + +impl Parameter { + pub fn parse(input: &Vec) -> Parameter { + use syn::NestedMetaItem::MetaItem; + use syn::MetaItem::{Word, NameValue}; + + let mut component = ParameterType::Component { }; + let mut subgroup = ParameterType::Subgroup { }; + let mut is_subgroup = false; + let mut serialize = true; + + for meta_items in input.iter().filter_map(filter_group) { + for meta_item in meta_items { + match meta_item { + MetaItem(Word(ref name)) if name == "no_serialize" => serialize = false, + MetaItem(Word(ref name)) if name == "subgroup" => { + }, + _ => println!("Unused attribute: {:?}", meta_item), + } + } + } + + Parameter { + option: parameter_type, + serialize: serialize, + } + } +} + +pub fn filter_group(attr: &Attribute) -> Option> { + match attr.value { + MetaItem::List(ref name, ref items) if name == "group" => Some(items.iter().cloned().collect()), + _ => None, + } +} + +fn separate_fields(input: &DeriveInput) -> (Vec, &Vec) { + let fields = match input.body { + Body::Enum(ref variants) => panic!("Enum cannot be a component group"), + Body::Struct(ref data) => match data { + &VariantData::Struct(ref fields) => fields, + _ => panic!("Struct must have named fields"), + }, + }; + + let parameters = fields.iter().map(|field| Parameter::parse(&field.attrs) ).collect(); + (parameters, fields) +} + diff --git a/specs_derive/src/lib.rs b/specs_derive/src/lib.rs new file mode 100644 index 000000000..eb9dbc7c2 --- /dev/null +++ b/specs_derive/src/lib.rs @@ -0,0 +1,23 @@ + +// `quote` relies on macro recursion, so it is likely to hit the normal cap. +#![recursion_limit = "512"] + +extern crate proc_macro; +extern crate syn; +#[macro_use] +extern crate quote; +extern crate specs; +extern crate serde; + +use proc_macro::TokenStream; + +mod component; + +#[proc_macro_derive(ComponentGroup, attributes(group))] +pub fn component_group(input: TokenStream) -> TokenStream { + let input = syn::parse_derive_input(&input.to_string()).unwrap(); + match component::expand_group(&input) { + Ok(tokens) => tokens.parse().unwrap(), + Err(err) => panic!("Error: {}", err), + } +} From c5c3230d3c952024ac6374e5068b877041c0f938 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Wed, 26 Apr 2017 18:50:53 -0700 Subject: [PATCH 02/11] Serialization feature, move group to specs --- specs/src/group.rs | 24 +++ specs/src/lib.rs | 4 +- specs_derive/Cargo.toml | 6 +- specs_derive/examples/derive.rs | 2 - specs_derive/src/component.rs | 230 -------------------------- specs_derive/src/component_group.rs | 240 ++++++++++++++++++++++++++++ specs_derive/src/lib.rs | 10 +- 7 files changed, 277 insertions(+), 239 deletions(-) create mode 100644 specs/src/group.rs delete mode 100644 specs_derive/src/component.rs create mode 100644 specs_derive/src/component_group.rs diff --git a/specs/src/group.rs b/specs/src/group.rs new file mode 100644 index 000000000..d028b6a14 --- /dev/null +++ b/specs/src/group.rs @@ -0,0 +1,24 @@ + +/// Group of components and subgroups containing components. +pub trait ComponentGroup { + /// Components defined in this group, not a subgroup. + fn local_components() -> Vec<&'static str>; + /// Components defined in this group along with subgroups. + fn components() -> Vec<&'static str>; + /// Subgroups included in this group. + fn subgroups() -> Vec<&'static str>; + + #[cfg(feature="serialize")] + /// Serializes the group of components from the world. + fn serialize_group(world: &specs::World, serializer: S) -> Result; + #[cfg(feature="serialize")] + /// Helper method for serializing the world. + fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error>; + #[cfg(feature="serialize")] + /// Deserializes the group of components into the world. + fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error>; + #[cfg(feature="serialize")] + /// Helper method for deserializing the world. + fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, visitor: &mut V) -> Result, V::Error> + where V: serde::de::MapVisitor; +} diff --git a/specs/src/lib.rs b/specs/src/lib.rs index 9945efdf2..eec61c254 100644 --- a/specs/src/lib.rs +++ b/specs/src/lib.rs @@ -184,6 +184,7 @@ extern crate serde; #[macro_use] extern crate serde_derive; +pub use group::ComponentGroup; pub use join::{Join, JoinIter, JoinParIter, ParJoin}; pub use shred::{ Dispatcher, DispatcherBuilder, Fetch, FetchId, FetchIdMut, FetchMut, RunNow, RunningTime, System, SystemData}; @@ -218,6 +219,3 @@ pub type Entities<'a> = Fetch<'a, EntitiesRes>; /// An index is basically the id of an `Entity`. pub type Index = u32; -mod join; -mod storage; -mod world; diff --git a/specs_derive/Cargo.toml b/specs_derive/Cargo.toml index 7f670aa6b..03f1ab3bf 100644 --- a/specs_derive/Cargo.toml +++ b/specs_derive/Cargo.toml @@ -10,4 +10,8 @@ proc-macro = true specs = { path = "../specs", version = "0.9.1" } syn = "0.11.10" quote = "0.3.15" -serde = "0.9.11" +serde = { version = "0.9.11", optional = true } + +[features] +default = [] +serialize = ["serde"] diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index 39a3a14dd..d491be675 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -7,8 +7,6 @@ extern crate specs_derive; struct SomeGroup { #[group(no_serialize)] field1: u32, - - #[group(subgroup)] field2: f32, field3: String, } diff --git a/specs_derive/src/component.rs b/specs_derive/src/component.rs deleted file mode 100644 index 4aba32a95..000000000 --- a/specs_derive/src/component.rs +++ /dev/null @@ -1,230 +0,0 @@ - -use serde::{self, Serialize, Serializer, Deserialize, Deserializer}; -use serde::de::DeserializeSeed; -use specs::{self, Gate, Join}; - -use syn::{self, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field}; -use quote::{Tokens}; - -use std::marker::PhantomData; - -pub trait ComponentGroup { - /// Components defined in this group, not a subgroup. - fn local_components() -> Vec<&'static str>; - /// Components defined in this group along with subgroups. - fn components() -> Vec<&'static str>; - /// Subgroups included in this group. - fn subgroups() -> Vec<&'static str>; - /// Serializes the group of components from the world. - fn serialize_group(world: &specs::World, serializer: S) -> Result; - /// Helper method for serializing the world. - fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error>; - /// Deserializes the group of components into the world. - fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error>; - /// Helper method for deserializing the world. - fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, visitor: &mut V) -> Result, V::Error> - where V: serde::de::MapVisitor; -} - -pub fn expand_group(input: &DeriveInput) -> Result { - let name = &input.ident; - let (params, fields) = separate_fields(input); - - println!("name: {:?}", name); - println!("params: {:?}", params); - println!("fields: {:?}", fields); - - //let components = fields.zip(params).filter(|f, p| p.subgroup).collect(); - - /* - let expanded = quote! { - impl ComponentGroup for #name { - fn local_components() -> Vec<&'static str> { - vec![ #( stringify!(#component), )* ] - } - fn components() -> Vec<&'static str> { - let mut list = <$name as Group>::local_components(); - #( - for component in <#subgroup as Group>::components() { - list.push(component); - } - )* - list - } - fn subgroups() -> Vec<&'static str> { - vec![ #( stringify!(#subgroup), )* ] - } - fn serialize_group(world: &specs::World, serializer: S) -> Result { - use serde::ser::SerializeMap; - let mut map = serializer.serialize_map(None)?; - #( - map.serialize_key(stringify!(#component))?; - let storage = world.read::<#component>().pass(); - map.serialize_value(&storage)?; - )* - - #( - <#subgroup as Group>::serialize_subgroup::(world, &mut map)?; - )* - - map.end() - } - - fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { - use serde::ser::SerializeMap; - #( - map.serialize_key(stringify!(#component))?; - let storage = world.read::<#component>().pass(); - map.serialize_value(&storage)?; - )* - - #( - <#subgroup as Group>::serialize_subgroup::(world, map)?; - )* - - Ok(()) - } - - fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error> { - use std::fmt; - use specs::PackedData; - - struct ComponentVisitor<'a>(&'a mut specs::World, &'a [specs::Entity]); - impl<'a> serde::de::Visitor for ComponentVisitor<'a> { - type Value = (); - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "a map of component identifiers to packed data") - } - - fn visit_map(self, mut visitor: V) -> Result<(), V::Error> - where V: serde::de::MapVisitor - { - while let Some(key) = visitor.visit_key::()? { - match &*key { - #( - stringify!(#component) => { - let mut storage = self.0.write::<#component>().pass(); - let packed = visitor.visit_value::>()?; - storage.merge(self.1, packed); - }, - )* - key @ _ => { - #( - if let Some(()) = <#subgroup as Group>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { - continue; // subgroup deserialized the components - } - )* - continue; // not in the registered component list, ignore - }, - } - } - - Ok(()) - } - } - - Ok(deserializer.deserialize_map(ComponentVisitor(world, entities))?) - } - - fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, mut visitor: &mut V) -> Result, V::Error> - where V: serde::de::MapVisitor - { - match &*key { - #( - stringify!(#component) => { - let mut storage = world.write::<#component>().pass(); - let packed = visitor.visit_value::>()?; - storage.merge(entities, packed); - Ok(Some(())) - }, - )* - key @ _ => { - #( - if let Some(()) = <#subgroup as Group>::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { - return Ok(Some(())); - } - )* - Ok(None) - }, - } - } - } - }; - */ - - let expanded = quote! { - - }; - - Ok(expanded) -} - -#[derive(Debug)] -enum ParameterType { - // Parameters relating to subgroups only - Subgroup { - - }, - // Parameters relating to components only - Component { - - }, -} - -#[derive(Debug)] -struct Parameter { - // Type of parameter - pub option: ParameterType, - - // Serialize this field - pub serialize: bool, -} - -impl Parameter { - pub fn parse(input: &Vec) -> Parameter { - use syn::NestedMetaItem::MetaItem; - use syn::MetaItem::{Word, NameValue}; - - let mut component = ParameterType::Component { }; - let mut subgroup = ParameterType::Subgroup { }; - let mut is_subgroup = false; - let mut serialize = true; - - for meta_items in input.iter().filter_map(filter_group) { - for meta_item in meta_items { - match meta_item { - MetaItem(Word(ref name)) if name == "no_serialize" => serialize = false, - MetaItem(Word(ref name)) if name == "subgroup" => { - }, - _ => println!("Unused attribute: {:?}", meta_item), - } - } - } - - Parameter { - option: parameter_type, - serialize: serialize, - } - } -} - -pub fn filter_group(attr: &Attribute) -> Option> { - match attr.value { - MetaItem::List(ref name, ref items) if name == "group" => Some(items.iter().cloned().collect()), - _ => None, - } -} - -fn separate_fields(input: &DeriveInput) -> (Vec, &Vec) { - let fields = match input.body { - Body::Enum(ref variants) => panic!("Enum cannot be a component group"), - Body::Struct(ref data) => match data { - &VariantData::Struct(ref fields) => fields, - _ => panic!("Struct must have named fields"), - }, - }; - - let parameters = fields.iter().map(|field| Parameter::parse(&field.attrs) ).collect(); - (parameters, fields) -} - diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs new file mode 100644 index 000000000..716578116 --- /dev/null +++ b/specs_derive/src/component_group.rs @@ -0,0 +1,240 @@ + +use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field}; +use quote::{Tokens}; + +pub fn expand_group(input: &DeriveInput) -> Result { + let name = &input.ident; + let (params, fields) = separate_fields(input); + + let (mut comp_param, mut component) = (Vec::new(), Vec::new()); + let (mut sub_param, mut subgroup) = (Vec::new(), Vec::new()); + for (field, param) in fields.iter().zip(params.iter()) { + match param.option { + ParameterType::Component { } => { comp_param.push(param); component.push(field); }, + ParameterType::Subgroup { } => { sub_param.push(param); subgroup.push(field); }, + } + } + let dummy_const = Ident::new(format!("_IMPL_COMPONENTGROUP_FOR_{}", name)); + + // Duplicate references to the components. + // `quote` currently doesn't support using the same variable binding twice in a repetition. + let ref component = component.iter().map(|field| &field.ty).collect::>(); + let component2 = component; + let component3 = component; + let ref subgroup = subgroup.iter().map(|field| &field.ty).collect::>(); + + let default = quote! { + fn local_components() -> Vec<&'static str> { + vec![ #( stringify!(#component) ),* ] + } + fn components() -> Vec<&'static str> { + let mut list = <#name as _specs::ComponentGroup>::local_components(); + #( + for component in <#subgroup as _specs::ComponentGroup>::components() { + list.push(component); + } + )* + list + } + fn subgroups() -> Vec<&'static str> { + vec![ #( stringify!(#subgroup), )* ] + } + }; + + #[cfg(feature="serialize")] + let serialize = quote! { + fn serialize_group(world: &_specs::World, serializer: S) -> Result { + use _serde::ser::SerializeMap; + let mut map = serializer.serialize_map(None)?; + #( + map.serialize_key(stringify!(#component))?; + let storage = world.read::<#component2>().pass(); + map.serialize_value(&storage)?; + )* + + #( + <#subgroup as _specs::ComponentGroup>::serialize_subgroup::(world, &mut map)?; + )* + + map.end() + } + fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { + use _serde::ser::SerializeMap; + #( + map.serialize_key(stringify!(#component))?; + let storage = world.read::<#component2>().pass(); + map.serialize_value(&storage)?; + )* + + #( + <#subgroup as _specs::ComponentGroup>::serialize_subgroup::(world, map)?; + )* + + Ok(()) + } + + fn deserialize_group(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { + use std::fmt; + use _specs::PackedData; + + struct ComponentVisitor<'a>(&'a mut _specs::World, &'a [_specs::Entity]); + impl<'a> _serde::de::Visitor for ComponentVisitor<'a> { + type Value = (); + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a map of component identifiers to packed data") + } + + fn visit_map(self, mut visitor: V) -> Result<(), V::Error> + where V: _serde::de::MapVisitor + { + while let Some(key) = visitor.visit_key::()? { + match &*key { + #( + stringify!(#component) => { + let mut storage = self.0.write::<#component2>().pass(); + let packed = visitor.visit_value::>()?; + storage.merge(self.1, packed); + }, + )* + key @ _ => { + #( + if let Some(()) = <#subgroup as _specs::ComponentGroup>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { + continue; // subgroup deserialized the components + } + )* + continue; // not in the registered component list, ignore + }, + } + } + + Ok(()) + } + } + + Ok(deserializer.deserialize_map(ComponentVisitor(world, entities))?) + } + + fn deserialize_subgroup(world: &mut _specs::World, entities: &[_specs::Entity], key: String, mut visitor: &mut V) -> Result, V::Error> + where V: _serde::de::MapVisitor + { + match &*key { + #( + stringify!(#component) => { + let mut storage = world.write::<#component2>().pass(); + let packed = visitor.visit_value::<_specs::PackedData<#component3>>()?; + storage.merge(entities, packed); + Ok(Some(())) + }, + )* + key @ _ => { + #( + if let Some(()) = <#subgroup as _specs::ComponentGroup>::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { + return Ok(Some(())); + } + )* + Ok(None) + }, + } + } + }; + + #[cfg(not(feature="serialize"))] + let expanded = quote! { + impl specs::ComponentGroup for #name { + #default + } + }; + + #[cfg(feature="serialize")] + let expanded = quote! { + extern crate serde as _serde; + impl specs::ComponentGroup for #name { + #default + #serialize + } + }; + + let wrap = quote! { + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const #dummy_const: () = { + extern crate specs as _specs; + #expanded + }; + }; + + Ok(wrap) +} + +#[derive(PartialEq, Debug)] +enum ParameterType { + // Parameters relating to subgroups only + Subgroup { + + }, + // Parameters relating to components only + Component { + + }, +} + +#[derive(Debug)] +struct Parameter { + // Type of parameter + pub option: ParameterType, + + // Serialize this field + pub serialize: bool, +} + +impl Parameter { + pub fn parse(input: &Vec) -> Parameter { + use syn::NestedMetaItem::MetaItem; + use syn::MetaItem::Word; + + let mut subgroup = false; + let mut serialize = true; + + for meta_items in input.iter().filter_map(filter_group) { + for meta_item in meta_items { + match meta_item { + MetaItem(Word(ref name)) if name == "no_serialize" => serialize = false, + MetaItem(Word(ref name)) if name == "subgroup" => subgroup = true, + _ => println!("Unused attribute: {:?}", meta_item), + } + } + } + + let parameter_type = if subgroup { + ParameterType::Subgroup { } + } + else { + ParameterType::Component { } + }; + + Parameter { + option: parameter_type, + serialize: serialize, + } + } +} + +pub fn filter_group(attr: &Attribute) -> Option> { + match attr.value { + MetaItem::List(ref name, ref items) if name == "group" => Some(items.iter().cloned().collect()), + _ => None, + } +} + +fn separate_fields(input: &DeriveInput) -> (Vec, &Vec) { + let fields = match input.body { + Body::Enum(_) => panic!("Enum cannot be a component group"), + Body::Struct(ref data) => match data { + &VariantData::Struct(ref fields) => fields, + _ => panic!("Struct must have named fields"), + }, + }; + + let parameters = fields.iter().map(|field| Parameter::parse(&field.attrs) ).collect(); + (parameters, fields) +} + diff --git a/specs_derive/src/lib.rs b/specs_derive/src/lib.rs index eb9dbc7c2..f4129fec6 100644 --- a/specs_derive/src/lib.rs +++ b/specs_derive/src/lib.rs @@ -7,16 +7,20 @@ extern crate syn; #[macro_use] extern crate quote; extern crate specs; +#[cfg(feature="serialize")] extern crate serde; use proc_macro::TokenStream; -mod component; +mod component_group; #[proc_macro_derive(ComponentGroup, attributes(group))] -pub fn component_group(input: TokenStream) -> TokenStream { +pub fn derive_component(input: TokenStream) -> TokenStream { let input = syn::parse_derive_input(&input.to_string()).unwrap(); - match component::expand_group(&input) { + + println!("Output: {:?}", component_group::expand_group(&input)); + + match component_group::expand_group(&input) { Ok(tokens) => tokens.parse().unwrap(), Err(err) => panic!("Error: {}", err), } From f52b7552a1d108607c14aa8ed04258e31592033e Mon Sep 17 00:00:00 2001 From: Aceeri Date: Sat, 29 Apr 2017 20:48:45 -0700 Subject: [PATCH 03/11] Correct paths for serde and specs, WorldDeserializer --- specs/src/group.rs | 12 ++- specs/src/world.rs | 27 +++++- specs_derive/Cargo.toml | 5 +- specs_derive/examples/derive.rs | 30 +++++- specs_derive/src/component_group.rs | 138 ++++++++++++++++++---------- specs_derive/src/group.rs | 19 ++++ 6 files changed, 176 insertions(+), 55 deletions(-) create mode 100644 specs_derive/src/group.rs diff --git a/specs/src/group.rs b/specs/src/group.rs index d028b6a14..8315da59f 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -1,4 +1,8 @@ +use ::{World, Entity}; +#[cfg(feature="serialize")] +use serde::{self, Serializer, Deserializer}; + /// Group of components and subgroups containing components. pub trait ComponentGroup { /// Components defined in this group, not a subgroup. @@ -10,15 +14,15 @@ pub trait ComponentGroup { #[cfg(feature="serialize")] /// Serializes the group of components from the world. - fn serialize_group(world: &specs::World, serializer: S) -> Result; + fn serialize_group(world: &World, serializer: S) -> Result; #[cfg(feature="serialize")] /// Helper method for serializing the world. - fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error>; + fn serialize_subgroup(world: &World, map: &mut S::SerializeMap) -> Result<(), S::Error>; #[cfg(feature="serialize")] /// Deserializes the group of components into the world. - fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error>; + fn deserialize_group(world: &mut World, entities: &[Entity], deserializer: D) -> Result<(), D::Error>; #[cfg(feature="serialize")] /// Helper method for deserializing the world. - fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, visitor: &mut V) -> Result, V::Error> + fn deserialize_subgroup(world: &mut World, entities: &[Entity], key: String, visitor: &mut V) -> Result, V::Error> where V: serde::de::MapVisitor; } diff --git a/specs/src/world.rs b/specs/src/world.rs index 7da0eddb2..b43f5ec7e 100644 --- a/specs/src/world.rs +++ b/specs/src/world.rs @@ -1,4 +1,5 @@ use std::sync::atomic::{AtomicUsize, Ordering}; +use std::marker::PhantomData; use crossbeam::sync::TreiberStack; use hibitset::{AtomicBitSet, BitSet, BitSetOr}; @@ -6,7 +7,7 @@ use mopa::Any; use shred::{Fetch, FetchMut, Resource, Resources}; use storage::{AnyStorage, MaskedStorage}; -use {Index, Join, ParJoin, ReadStorage, Storage, UnprotectedStorage, WriteStorage}; +use {ComponentGroup, Index, Join, ParJoin, ReadStorage, Storage, UnprotectedStorage, WriteStorage}; const COMPONENT_NOT_REGISTERED: &str = "No component with the given id. Did you forget to register \ the component with `World::register::()`?"; @@ -780,3 +781,27 @@ mod tests { assert!(world.read::().get(e).is_some()); } } + +#[cfg(feature="serialize")] +/// Structure used to deserialize into the world. +pub struct WorldDeserializer<'a, G, C> + where G: ComponentGroup, + C: PartialEq + Eq + Hash + 'a, +{ + world: &'a mut World, + entities: &'a [Entity], + phantom: PhantomData, +} + +#[cfg(feature="serialize")] +impl<'a, G, C> serde::de::DeserializeSeed for WorldDeserializer<'a, G, C> + where G: ComponentGroup, + C: PartialEq + Eq + Hash + 'a, +{ + type Value = (); + fn deserialize(self, deserializer: D) -> Result<(), D::Error> + where D: serde::Deserializer + { + ::deserialize_group(self.world, self.entities, deserializer) + } +} diff --git a/specs_derive/Cargo.toml b/specs_derive/Cargo.toml index 03f1ab3bf..9301cc5e8 100644 --- a/specs_derive/Cargo.toml +++ b/specs_derive/Cargo.toml @@ -12,6 +12,9 @@ syn = "0.11.10" quote = "0.3.15" serde = { version = "0.9.11", optional = true } +[dev-dependencies] +serde_derive = "0.9.11" + [features] default = [] -serialize = ["serde"] +serialize = ["serde", "specs/serialize"] diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index d491be675..0bd19f816 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -2,13 +2,37 @@ extern crate specs; #[macro_use] extern crate specs_derive; +extern crate serde; +#[macro_use] +extern crate serde_derive; + +use specs::{VecStorage, Gate, Component}; + +#[derive(Serialize, Deserialize)] +struct Comp1(String); +impl Component for Comp1 { + type Storage = VecStorage; +} + +#[derive(Serialize, Deserialize)] +struct Comp2(f32); +impl Component for Comp2 { + type Storage = VecStorage; +} + +#[derive(Serialize, Deserialize)] +struct Comp3(u32); +impl Component for Comp3 { + type Storage = VecStorage; +} #[derive(ComponentGroup)] +#[allow(dead_code)] struct SomeGroup { #[group(no_serialize)] - field1: u32, - field2: f32, - field3: String, + field1: Comp1, + field2: Comp2, + field3: Comp3, } fn main() { diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index 716578116..2cb96f6f1 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -1,32 +1,41 @@ -use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field}; -use quote::{Tokens}; +use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty}; +use quote::{ToTokens, Tokens}; +#[allow(unused_variables)] pub fn expand_group(input: &DeriveInput) -> Result { let name = &input.ident; - let (params, fields) = separate_fields(input); - - let (mut comp_param, mut component) = (Vec::new(), Vec::new()); - let (mut sub_param, mut subgroup) = (Vec::new(), Vec::new()); - for (field, param) in fields.iter().zip(params.iter()) { - match param.option { - ParameterType::Component { } => { comp_param.push(param); component.push(field); }, - ParameterType::Subgroup { } => { sub_param.push(param); subgroup.push(field); }, - } - } + let items = get_items(input); + let dummy_const = Ident::new(format!("_IMPL_COMPONENTGROUP_FOR_{}", name)); // Duplicate references to the components. // `quote` currently doesn't support using the same variable binding twice in a repetition. - let ref component = component.iter().map(|field| &field.ty).collect::>(); + + // Component fields + let ref component = items.iter().filter(|item| item.parameter.option.is_component()).collect::>(); let component2 = component; let component3 = component; - let ref subgroup = subgroup.iter().map(|field| &field.ty).collect::>(); + // Serializable components + let ref component_serialize = component.iter().filter(|item| item.parameter.serialize).collect::>(); + let component_serialize2 = component_serialize; + let component_serialize3 = component_serialize; + + // Subgroup fields + let ref subgroup = items.iter().filter(|item| item.parameter.option.is_subgroup()).collect::>(); + + // Serializable fields + let ref subgroup_serialize = subgroup.iter().filter(|item| item.parameter.serialize).collect::>(); + let subgroup_serialize2 = subgroup_serialize; + let subgroup_serialize3 = subgroup_serialize; + + // Normal group methods. let default = quote! { fn local_components() -> Vec<&'static str> { vec![ #( stringify!(#component) ),* ] } + #[allow(unused_mut)] fn components() -> Vec<&'static str> { let mut list = <#name as _specs::ComponentGroup>::local_components(); #( @@ -41,41 +50,38 @@ pub fn expand_group(input: &DeriveInput) -> Result { } }; + // Serialization methods #[cfg(feature="serialize")] let serialize = quote! { - fn serialize_group(world: &_specs::World, serializer: S) -> Result { - use _serde::ser::SerializeMap; + fn serialize_group(world: &_specs::World, serializer: S) -> Result { let mut map = serializer.serialize_map(None)?; #( - map.serialize_key(stringify!(#component))?; - let storage = world.read::<#component2>().pass(); - map.serialize_value(&storage)?; + let storage = world.read::<#component_serialize>().pass(); + _serde::ser::SerializeMap::serialize_entry(&mut map, stringify!(#component_serialize2), &storage)?; )* #( - <#subgroup as _specs::ComponentGroup>::serialize_subgroup::(world, &mut map)?; + <#subgroup_serialize as _specs::ComponentGroup>::serialize_subgroup::(world, &mut map)?; )* - map.end() + _serde::ser::SerializeMap::end(map) } - fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { - use _serde::ser::SerializeMap; + + fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { #( - map.serialize_key(stringify!(#component))?; - let storage = world.read::<#component2>().pass(); - map.serialize_value(&storage)?; + let storage = world.read::<#component_serialize>().pass(); + _serde::ser::SerializeMap::serialize_entry(map, stringify!(#component_serialize2), &storage)?; )* #( - <#subgroup as _specs::ComponentGroup>::serialize_subgroup::(world, map)?; + <#subgroup_serialize as _specs::ComponentGroup>::serialize_subgroup::(world, map)?; )* Ok(()) } - fn deserialize_group(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { + fn deserialize_group(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { use std::fmt; - use _specs::PackedData; struct ComponentVisitor<'a>(&'a mut _specs::World, &'a [_specs::Entity]); impl<'a> _serde::de::Visitor for ComponentVisitor<'a> { @@ -88,17 +94,18 @@ pub fn expand_group(input: &DeriveInput) -> Result { where V: _serde::de::MapVisitor { while let Some(key) = visitor.visit_key::()? { + #[allow(unused_variables)] match &*key { #( - stringify!(#component) => { - let mut storage = self.0.write::<#component2>().pass(); - let packed = visitor.visit_value::>()?; - storage.merge(self.1, packed); + stringify!(#component_serialize) => { + let mut storage = self.0.write::<#component_serialize2>().pass(); + let packed = visitor.visit_value::<_specs::PackedData<#component_serialize3>>()?; + let _ = storage.merge(self.1, packed); }, )* key @ _ => { #( - if let Some(()) = <#subgroup as _specs::ComponentGroup>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { + if let Some(()) = <#subgroup_serialize as _specs::ComponentGroup>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { continue; // subgroup deserialized the components } )* @@ -117,18 +124,19 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn deserialize_subgroup(world: &mut _specs::World, entities: &[_specs::Entity], key: String, mut visitor: &mut V) -> Result, V::Error> where V: _serde::de::MapVisitor { + #[allow(unused_variables)] match &*key { #( - stringify!(#component) => { - let mut storage = world.write::<#component2>().pass(); - let packed = visitor.visit_value::<_specs::PackedData<#component3>>()?; - storage.merge(entities, packed); + stringify!(#component_serialize) => { + let mut storage = world.write::<#component_serialize2>().pass(); + let packed = visitor.visit_value::<_specs::PackedData<#component_serialize3>>()?; + let _ = storage.merge(entities, packed); Ok(Some(())) }, )* key @ _ => { #( - if let Some(()) = <#subgroup as _specs::ComponentGroup>::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { + if let Some(()) = <#subgroup_serialize as _specs::ComponentGroup>::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { return Ok(Some(())); } )* @@ -138,22 +146,27 @@ pub fn expand_group(input: &DeriveInput) -> Result { } }; + // Normal expand (no serialization) #[cfg(not(feature="serialize"))] let expanded = quote! { - impl specs::ComponentGroup for #name { + #[automatically_derived] + impl _specs::ComponentGroup for #name { #default } }; + // Serialization expand #[cfg(feature="serialize")] let expanded = quote! { extern crate serde as _serde; - impl specs::ComponentGroup for #name { + #[automatically_derived] + impl _specs::ComponentGroup for #name { #default #serialize } }; + // Wrap the expanded code to prevent context conflicts. let wrap = quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] const #dummy_const: () = { @@ -166,7 +179,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { } #[derive(PartialEq, Debug)] -enum ParameterType { +pub enum ParameterType { // Parameters relating to subgroups only Subgroup { @@ -177,8 +190,23 @@ enum ParameterType { }, } +impl ParameterType { + fn is_subgroup(&self) -> bool { + match self { + &ParameterType::Subgroup { } => true, + &ParameterType::Component { } => false, + } + } + fn is_component(&self) -> bool { + match self { + &ParameterType::Subgroup { } => false, + &ParameterType::Component { } => true, + } + } +} + #[derive(Debug)] -struct Parameter { +pub struct Parameter { // Type of parameter pub option: ParameterType, @@ -225,7 +253,7 @@ pub fn filter_group(attr: &Attribute) -> Option> { } } -fn separate_fields(input: &DeriveInput) -> (Vec, &Vec) { +fn get_items(input: &DeriveInput) -> Vec { let fields = match input.body { Body::Enum(_) => panic!("Enum cannot be a component group"), Body::Struct(ref data) => match data { @@ -234,7 +262,25 @@ fn separate_fields(input: &DeriveInput) -> (Vec, &Vec) { }, }; - let parameters = fields.iter().map(|field| Parameter::parse(&field.attrs) ).collect(); - (parameters, fields) + fields + .iter() + .map(move |field| { + Item { + parameter: Parameter::parse(&field.attrs), + field: field, + } + }) + .collect::>() +} + +pub struct Item<'a> { + pub parameter: Parameter, + pub field: &'a Field, +} + +impl<'a> ToTokens for Item<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + self.field.to_tokens(tokens); + } } diff --git a/specs_derive/src/group.rs b/specs_derive/src/group.rs new file mode 100644 index 000000000..57fb13262 --- /dev/null +++ b/specs_derive/src/group.rs @@ -0,0 +1,19 @@ + +pub trait ComponentGroup { + /// Components defined in this group, not a subgroup. + fn local_components() -> Vec<&'static str>; + /// Components defined in this group along with subgroups. + fn components() -> Vec<&'static str>; + /// Subgroups included in this group. + fn subgroups() -> Vec<&'static str>; + /// Serializes the group of components from the world. + fn serialize_group(world: &specs::World, serializer: S) -> Result; + /// Helper method for serializing the world. + fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error>; + /// Deserializes the group of components into the world. + fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error>; + /// Helper method for deserializing the world. + fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, visitor: &mut V) -> Result, V::Error> + where V: serde::de::MapVisitor; +} + From d92367bbe2c8e1ef252c5a4075edca7c6a56cf1a Mon Sep 17 00:00:00 2001 From: Aceeri Date: Mon, 29 May 2017 07:33:20 -0700 Subject: [PATCH 04/11] Shred integration --- specs/.gitignore | 7 + specs/LICENSE | 201 ---------------------------- specs/src/group.rs | 24 ++-- specs/src/world.rs | 18 +-- specs_derive/examples/derive.rs | 71 ++++++---- specs_derive/src/component_group.rs | 19 ++- specs_derive/src/group.rs | 19 --- specs_derive/src/lib.rs | 6 + 8 files changed, 79 insertions(+), 286 deletions(-) create mode 100644 specs/.gitignore delete mode 100644 specs/LICENSE delete mode 100644 specs_derive/src/group.rs diff --git a/specs/.gitignore b/specs/.gitignore new file mode 100644 index 000000000..99d938f8b --- /dev/null +++ b/specs/.gitignore @@ -0,0 +1,7 @@ +# Generated by Cargo +/target/ +Cargo.lock + +# IDEs / Editor +*.iml +.idea diff --git a/specs/LICENSE b/specs/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/specs/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/specs/src/group.rs b/specs/src/group.rs index 8315da59f..18867d7bd 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -1,9 +1,11 @@ -use ::{World, Entity}; +#[cfg(feature="serialize")] +use prelude::{World, Entity}; + #[cfg(feature="serialize")] use serde::{self, Serializer, Deserializer}; -/// Group of components and subgroups containing components. +/// Group of components. Can be subgrouped into other component groups. pub trait ComponentGroup { /// Components defined in this group, not a subgroup. fn local_components() -> Vec<&'static str>; @@ -11,18 +13,18 @@ pub trait ComponentGroup { fn components() -> Vec<&'static str>; /// Subgroups included in this group. fn subgroups() -> Vec<&'static str>; - - #[cfg(feature="serialize")] +} + +/// Group of serializable components. +#[cfg(feature="serialize")] +pub trait SerializeGroup: ComponentGroup { /// Serializes the group of components from the world. - fn serialize_group(world: &World, serializer: S) -> Result; - #[cfg(feature="serialize")] + fn serialize_group(world: &World, serializer: S) -> Result; /// Helper method for serializing the world. - fn serialize_subgroup(world: &World, map: &mut S::SerializeMap) -> Result<(), S::Error>; - #[cfg(feature="serialize")] + fn serialize_subgroup(world: &World, map: &mut S::SerializeMap) -> Result<(), S::Error>; /// Deserializes the group of components into the world. - fn deserialize_group(world: &mut World, entities: &[Entity], deserializer: D) -> Result<(), D::Error>; - #[cfg(feature="serialize")] + fn deserialize_group(world: &mut World, entities: &[Entity], deserializer: D) -> Result<(), D::Error>; /// Helper method for deserializing the world. - fn deserialize_subgroup(world: &mut World, entities: &[Entity], key: String, visitor: &mut V) -> Result, V::Error> + fn deserialize_subgroup(world: &mut World, entities: &[Entity], key: String, visitor: &mut V) -> Result, V::Error> where V: serde::de::MapVisitor; } diff --git a/specs/src/world.rs b/specs/src/world.rs index b43f5ec7e..a2cb40b25 100644 --- a/specs/src/world.rs +++ b/specs/src/world.rs @@ -1,5 +1,4 @@ use std::sync::atomic::{AtomicUsize, Ordering}; -use std::marker::PhantomData; use crossbeam::sync::TreiberStack; use hibitset::{AtomicBitSet, BitSet, BitSetOr}; @@ -206,13 +205,13 @@ impl Entity { /// Returns the index of the `Entity`. #[inline] - pub fn id(&self) -> Index { + pub fn get_id(&self) -> Index { self.0 } /// Returns the `Generation` of the `Entity`. #[inline] - pub fn gen(&self) -> Generation { + pub fn get_gen(&self) -> Generation { self.1 } } @@ -792,16 +791,3 @@ pub struct WorldDeserializer<'a, G, C> entities: &'a [Entity], phantom: PhantomData, } - -#[cfg(feature="serialize")] -impl<'a, G, C> serde::de::DeserializeSeed for WorldDeserializer<'a, G, C> - where G: ComponentGroup, - C: PartialEq + Eq + Hash + 'a, -{ - type Value = (); - fn deserialize(self, deserializer: D) -> Result<(), D::Error> - where D: serde::Deserializer - { - ::deserialize_group(self.world, self.entities, deserializer) - } -} diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index 0bd19f816..f0c31bbbe 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -1,40 +1,53 @@ - extern crate specs; #[macro_use] extern crate specs_derive; + +#[cfg(feature="serialize")] extern crate serde; +#[cfg(feature="serialize")] #[macro_use] extern crate serde_derive; -use specs::{VecStorage, Gate, Component}; - -#[derive(Serialize, Deserialize)] -struct Comp1(String); -impl Component for Comp1 { - type Storage = VecStorage; -} - -#[derive(Serialize, Deserialize)] -struct Comp2(f32); -impl Component for Comp2 { - type Storage = VecStorage; -} - -#[derive(Serialize, Deserialize)] -struct Comp3(u32); -impl Component for Comp3 { - type Storage = VecStorage; -} - -#[derive(ComponentGroup)] -#[allow(dead_code)] -struct SomeGroup { - #[group(no_serialize)] - field1: Comp1, - field2: Comp2, - field3: Comp3, +#[cfg(feature="serialize")] +fn main() { + use specs::prelude::*; + + #[derive(Debug, Serialize, Deserialize)] + struct Comp1(String); + impl Component for Comp1 { + type Storage = VecStorage; + } + + #[derive(Debug, Serialize, Deserialize)] + struct Comp2(f32); + impl Component for Comp2 { + type Storage = VecStorage; + } + + #[derive(Debug, Serialize, Deserialize)] + struct Comp3(u32); + impl Component for Comp3 { + type Storage = VecStorage; + } + + #[derive(ComponentGroup)] + #[allow(dead_code)] + struct SomeGroup { + #[group(serialize)] + field1: Comp1, + + #[group(serialize)] + field2: Comp2, + + field3: Comp3, + } + + // Running + let mut world = World::new(); + world.register::(); } +#[cfg(not(feature="serialize"))] fn main() { - + println!("Requires `serialize` flag to run"); } diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index 2cb96f6f1..9a57c3a9d 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -1,7 +1,8 @@ -use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty}; +use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field}; use quote::{ToTokens, Tokens}; +/// Expands the `ComponentGroup` derive implementation. #[allow(unused_variables)] pub fn expand_group(input: &DeriveInput) -> Result { let name = &input.ident; @@ -147,7 +148,6 @@ pub fn expand_group(input: &DeriveInput) -> Result { }; // Normal expand (no serialization) - #[cfg(not(feature="serialize"))] let expanded = quote! { #[automatically_derived] impl _specs::ComponentGroup for #name { @@ -159,9 +159,8 @@ pub fn expand_group(input: &DeriveInput) -> Result { #[cfg(feature="serialize")] let expanded = quote! { extern crate serde as _serde; - #[automatically_derived] - impl _specs::ComponentGroup for #name { - #default + #expanded + impl _specs::entity::SerializeGroup for #name { #serialize } }; @@ -220,12 +219,12 @@ impl Parameter { use syn::MetaItem::Word; let mut subgroup = false; - let mut serialize = true; + let mut serialize = false; for meta_items in input.iter().filter_map(filter_group) { for meta_item in meta_items { match meta_item { - MetaItem(Word(ref name)) if name == "no_serialize" => serialize = false, + MetaItem(Word(ref name)) if name == "serialize" => serialize = true, MetaItem(Word(ref name)) if name == "subgroup" => subgroup = true, _ => println!("Unused attribute: {:?}", meta_item), } @@ -246,7 +245,7 @@ impl Parameter { } } -pub fn filter_group(attr: &Attribute) -> Option> { +fn filter_group(attr: &Attribute) -> Option> { match attr.value { MetaItem::List(ref name, ref items) if name == "group" => Some(items.iter().cloned().collect()), _ => None, @@ -273,14 +272,14 @@ fn get_items(input: &DeriveInput) -> Vec { .collect::>() } -pub struct Item<'a> { +struct Item<'a> { pub parameter: Parameter, pub field: &'a Field, } impl<'a> ToTokens for Item<'a> { fn to_tokens(&self, tokens: &mut Tokens) { - self.field.to_tokens(tokens); + self.field.ty.to_tokens(tokens); } } diff --git a/specs_derive/src/group.rs b/specs_derive/src/group.rs deleted file mode 100644 index 57fb13262..000000000 --- a/specs_derive/src/group.rs +++ /dev/null @@ -1,19 +0,0 @@ - -pub trait ComponentGroup { - /// Components defined in this group, not a subgroup. - fn local_components() -> Vec<&'static str>; - /// Components defined in this group along with subgroups. - fn components() -> Vec<&'static str>; - /// Subgroups included in this group. - fn subgroups() -> Vec<&'static str>; - /// Serializes the group of components from the world. - fn serialize_group(world: &specs::World, serializer: S) -> Result; - /// Helper method for serializing the world. - fn serialize_subgroup(world: &specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error>; - /// Deserializes the group of components into the world. - fn deserialize_group(world: &mut specs::World, entities: &[specs::Entity], deserializer: D) -> Result<(), D::Error>; - /// Helper method for deserializing the world. - fn deserialize_subgroup(world: &mut specs::World, entities: &[specs::Entity], key: String, visitor: &mut V) -> Result, V::Error> - where V: serde::de::MapVisitor; -} - diff --git a/specs_derive/src/lib.rs b/specs_derive/src/lib.rs index f4129fec6..ea45349cb 100644 --- a/specs_derive/src/lib.rs +++ b/specs_derive/src/lib.rs @@ -1,4 +1,8 @@ +//! Specs procedural derive macro library. +//! +//! Allows for easy grouping of components and systems into groups for ease of use and modularity. + // `quote` relies on macro recursion, so it is likely to hit the normal cap. #![recursion_limit = "512"] @@ -12,8 +16,10 @@ extern crate serde; use proc_macro::TokenStream; +/// Implementation of the group macros. mod component_group; +/// Sets up derive for the `ComponentGroup` trait (includes `SerializeGroup`). #[proc_macro_derive(ComponentGroup, attributes(group))] pub fn derive_component(input: TokenStream) -> TokenStream { let input = syn::parse_derive_input(&input.to_string()).unwrap(); From 370ddc2a76fcd0bbdee3a618e2668e80cb95aaf6 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Mon, 29 May 2017 14:57:18 -0700 Subject: [PATCH 05/11] World serialization and deserialization --- .travis.yml | 13 ++- specs/Cargo.toml | 3 +- specs/examples/serialize.rs | 88 +++++++++++++++++++- specs/src/group.rs | 7 +- specs/src/lib.rs | 3 + specs/src/world.rs | 83 +++++++++++++++++++ specs_derive/Cargo.toml | 1 + specs_derive/examples/derive.rs | 122 +++++++++++++++++++++++++++- specs_derive/src/component_group.rs | 60 ++++++++------ 9 files changed, 342 insertions(+), 38 deletions(-) diff --git a/.travis.yml b/.travis.yml index abaca1b8b..2981e51ae 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,15 +10,12 @@ branches: - master script: -- cd specs/ # enter normal specs directory -- cargo build --verbose -- cargo test --verbose -- cargo build --verbose --no-default-features -- cargo test --verbose --no-default-features -- cargo build --verbose --features serialize -- cargo test --verbose --features serialize +- cargo build --all --verbose +- cargo test --all --verbose +- cargo build -all --verbose --features serialize +- cargo test --all --verbose --features serialize - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then - cargo bench --verbose --no-run; + cargo bench --all --verbose --no-run; fi after_success: | diff --git a/specs/Cargo.toml b/specs/Cargo.toml index 1939a4c22..310905b8f 100644 --- a/specs/Cargo.toml +++ b/specs/Cargo.toml @@ -43,6 +43,7 @@ serde_derive = { version = "1.0", optional = true } serialize = ["serde", "serde_derive"] [dev-dependencies] -cgmath = { version = "0.14", features = ["eders"] } +cgmath = { version = "0.14", features = ["eders"] } rand = "0.3" serde_json = "1.0" +specs_derive = { path = "../specs_derive", version = "0.1" } diff --git a/specs/examples/serialize.rs b/specs/examples/serialize.rs index 83be9853c..c6cd43647 100644 --- a/specs/examples/serialize.rs +++ b/specs/examples/serialize.rs @@ -2,6 +2,8 @@ extern crate shred; #[macro_use] extern crate shred_derive; extern crate specs; +#[macro_use] +extern crate specs_derive; extern crate serde; #[macro_use] extern crate serde_derive; @@ -9,9 +11,10 @@ extern crate serde_json; fn main() { use serde::Serialize; + use serde::de::DeserializeSeed; use serde_json::{Serializer, from_str as json_from_str}; use specs::{Component, DispatcherBuilder, Entities, Join, PackedData, System, VecStorage, - World, WriteStorage}; + World, WriteStorage, WorldSerializer, WorldDeserializer}; #[derive(Debug, Serialize, Deserialize)] struct CompSerialize { @@ -22,6 +25,21 @@ fn main() { type Storage = VecStorage; } + #[derive(Debug, Serialize, Deserialize)] + struct CompFloat(f32); + impl Component for CompFloat { + type Storage = VecStorage; + } + + #[derive(ComponentGroup)] + struct SerialGroup { + #[group(serialize)] + comp_serialize: CompSerialize, + + #[group(serialize)] + comp_float: CompFloat, + } + #[derive(SystemData)] struct Data<'a> { entities: Entities<'a>, @@ -65,10 +83,34 @@ fn main() { } } + #[derive(SystemData)] + struct RemovalData<'a> { + entities: Entities<'a>, + comp_serial: WriteStorage<'a, CompSerialize>, + comp_float: WriteStorage<'a, CompFloat>, + } + + struct RemovalSystem; + impl<'a, C> System<'a, C> for RemovalSystem { + type SystemData = RemovalData<'a>; + + fn work(&mut self, mut data: RemovalData, _: C) { + // Remove all components + for (entity, _) in (&*data.entities, &data.comp_serial.check()).join() { + data.comp_serial.remove(entity); + } + for (entity, _) in (&*data.entities, &data.comp_float.check()).join() { + data.comp_float.remove(entity); + } + } + } + let mut world = World::new(); - world.register::(); + world.register_group::(); - world.create_entity().build(); + world.create_entity() + .with(CompFloat(2.71828182845)) + .build(); world.create_entity().build(); world .create_entity() @@ -85,6 +127,7 @@ fn main() { field: 5, other: true, }) + .with(CompFloat(3.14159265358979)) .build(); world .create_entity() @@ -100,6 +143,7 @@ fn main() { field: 0, other: false, }) + .with(CompFloat(5.0)) .build(); let mut dispatcher = DispatcherBuilder::new() @@ -108,4 +152,42 @@ fn main() { dispatcher.dispatch(&mut world.res); world.maintain(); + + let serialized = { + let world_serializer = WorldSerializer::::new(&world); + let serialized = serde_json::to_string_pretty(&world_serializer).unwrap(); + println!("{}", serialized); + serialized + }; + + { + let mut dispatcher = DispatcherBuilder::new() + .add(RemovalSystem, "removal", &[]) + .build(); + + dispatcher.dispatch(&mut world.res, ()); + } + + { + let world_serializer = WorldSerializer::::new(&world); + let serialized = serde_json::to_string_pretty(&world_serializer).unwrap(); + println!("before: {}", serialized); + } + + { + let entity_list: Vec<_> = { + let entities = world.read_resource::(); + entities.join().collect() + }; + + let world_deserializer = WorldDeserializer::::new(&mut world, entity_list.as_slice()); + let mut json_deserializer = serde_json::Deserializer::from_str(&serialized); + world_deserializer.deserialize(&mut json_deserializer); + } + + { + let world_serializer = WorldSerializer::::new(&world); + let serialized = serde_json::to_string_pretty(&world_serializer).unwrap(); + println!("after: {}", serialized); + } } diff --git a/specs/src/group.rs b/specs/src/group.rs index 18867d7bd..728c57ad0 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -1,7 +1,8 @@ -#[cfg(feature="serialize")] -use prelude::{World, Entity}; +use prelude::World; +#[cfg(feature="serialize")] +use prelude::Entity; #[cfg(feature="serialize")] use serde::{self, Serializer, Deserializer}; @@ -13,6 +14,8 @@ pub trait ComponentGroup { fn components() -> Vec<&'static str>; /// Subgroups included in this group. fn subgroups() -> Vec<&'static str>; + /// Registers the components into the world. + fn register(&mut World); } /// Group of serializable components. diff --git a/specs/src/lib.rs b/specs/src/lib.rs index eec61c254..0d1a12e5f 100644 --- a/specs/src/lib.rs +++ b/specs/src/lib.rs @@ -198,6 +198,9 @@ pub use storage::{BTreeStorage, CheckStorage, DenseVecStorage, DistinctStorage, pub use world::{Component, CreateIter, CreateIterAtomic, EntitiesRes, Entity, EntityBuilder, Generation, LazyInsert, LazyInsertions, World}; +#[cfg(feature="serialize")] +pub use world::{WorldSerializer, WorldDeserializer}; + #[cfg(feature = "serialize")] pub use storage::{MergeError, PackedData}; diff --git a/specs/src/world.rs b/specs/src/world.rs index a2cb40b25..4406fa53e 100644 --- a/specs/src/world.rs +++ b/specs/src/world.rs @@ -1,6 +1,20 @@ use std::sync::atomic::{AtomicUsize, Ordering}; +<<<<<<< HEAD use crossbeam::sync::TreiberStack; +======= +#[cfg(feature="serialize")] +use std::marker::PhantomData; +#[cfg(feature="serialize")] +use serde::de::DeserializeSeed; +#[cfg(feature="serialize")] +use serde::{Serialize, Serializer, Deserializer}; +#[cfg(feature="serialize")] +use group::SerializeGroup; + +use group::ComponentGroup; + +>>>>>>> e7d508b... World serialization and deserialization use hibitset::{AtomicBitSet, BitSet, BitSetOr}; use mopa::Any; use shred::{Fetch, FetchMut, Resource, Resources}; @@ -519,6 +533,11 @@ impl World { self.storages.push(&mut *storage as *mut AnyStorage); } + /// Registers a `ComponentGroup` into the world. + pub fn register_group(&mut self) { + G::register(self); + } + /// Adds a resource with the default ID (`0`). /// /// If the resource already exists it will be overwritten. @@ -751,6 +770,7 @@ impl Default for World { } } +<<<<<<< HEAD #[cfg(test)] mod tests { use storage::VecStorage; @@ -774,6 +794,55 @@ mod tests { e = entities.create(); lazy.add((e, Pos)); +======= +#[cfg(feature="serialize")] +/// Structure used to serialize a world using a component group. +pub struct WorldSerializer<'a, G> { + world: &'a World, + phantom: PhantomData, +} + +#[cfg(feature="serialize")] +impl<'a, G> WorldSerializer<'a, G> { + /// Creates a new world serializer out of a world. + pub fn new(world: &'a World) -> WorldSerializer<'a, G> { + WorldSerializer { + world: world, + phantom: PhantomData, + } + } +} + +#[cfg(feature="serialize")] +impl<'a, G> Serialize for WorldSerializer<'a, G> + where G: ComponentGroup + SerializeGroup +{ + fn serialize(&self, serializer: S) -> Result + where S: Serializer + { + G::serialize_group(self.world, serializer) + } +} + +#[cfg(feature="serialize")] +/// Structure used for stateful deserialization into the world using a component group. +pub struct WorldDeserializer<'a, G> { + world: &'a mut World, + entities: &'a [Entity], + phantom: PhantomData, +} + +#[cfg(feature="serialize")] +impl<'a, G> WorldDeserializer<'a, G> { + /// Creates a new world deserializer out of a world and a list of entities. + /// + /// The list of entities will be used to merge into the component storages. + pub fn new(world: &'a mut World, entities: &'a [Entity]) -> WorldDeserializer<'a, G> { + WorldDeserializer { + world: world, + entities: entities, + phantom: PhantomData, +>>>>>>> e7d508b... World serialization and deserialization } world.maintain(); @@ -782,6 +851,7 @@ mod tests { } #[cfg(feature="serialize")] +<<<<<<< HEAD /// Structure used to deserialize into the world. pub struct WorldDeserializer<'a, G, C> where G: ComponentGroup, @@ -791,3 +861,16 @@ pub struct WorldDeserializer<'a, G, C> entities: &'a [Entity], phantom: PhantomData, } +======= +impl<'a, G> DeserializeSeed for WorldDeserializer<'a, G> + where G: ComponentGroup + SerializeGroup, +{ + type Value = (); + fn deserialize(self, deserializer: D) -> Result<(), D::Error> + where D: Deserializer + { + G::deserialize_group(self.world, self.entities, deserializer) + } +} + +>>>>>>> e7d508b... World serialization and deserialization diff --git a/specs_derive/Cargo.toml b/specs_derive/Cargo.toml index 9301cc5e8..fb11aa84a 100644 --- a/specs_derive/Cargo.toml +++ b/specs_derive/Cargo.toml @@ -14,6 +14,7 @@ serde = { version = "0.9.11", optional = true } [dev-dependencies] serde_derive = "0.9.11" +serde_json = "0.9.9" [features] default = [] diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index f0c31bbbe..d4f72d68a 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -7,10 +7,15 @@ extern crate serde; #[cfg(feature="serialize")] #[macro_use] extern crate serde_derive; +#[cfg(feature="serialize")] +extern crate serde_json; #[cfg(feature="serialize")] fn main() { use specs::prelude::*; + use specs::{WorldDeserializer, WorldSerializer}; + use serde::{Deserialize, Serialize}; + use serde::de::DeserializeSeed; #[derive(Debug, Serialize, Deserialize)] struct Comp1(String); @@ -30,6 +35,18 @@ fn main() { type Storage = VecStorage; } + #[derive(Debug, Serialize, Deserialize)] + struct Comp4(u32); + impl Component for Comp4 { + type Storage = VecStorage; + } + + #[derive(Debug, Serialize, Deserialize)] + struct Comp5(u32); + impl Component for Comp5 { + type Storage = VecStorage; + } + #[derive(ComponentGroup)] #[allow(dead_code)] struct SomeGroup { @@ -40,11 +57,114 @@ fn main() { field2: Comp2, field3: Comp3, + + #[group(subgroup)] + test_sub: TestSub, + } + + #[derive(ComponentGroup)] + #[allow(dead_code)] + struct TestSub { + #[group(serialize)] + field4: Comp4, + + field5: Comp5, + } + + struct RemovalSystem; + impl<'a, C> System<'a, C> for RemovalSystem { + type SystemData = ( + Entities<'a>, + WriteStorage<'a, Comp1>, + WriteStorage<'a, Comp2>, + WriteStorage<'a, Comp3>, + WriteStorage<'a, Comp4>, + WriteStorage<'a, Comp5>, + ); + + fn work(&mut self, mut data: Self::SystemData, _: C) { + // Remove all components + for (entity, _) in (&*data.0, &data.1.check()).join() { + data.1.remove(entity); + } + for (entity, _) in (&*data.0, &data.2.check()).join() { + data.2.remove(entity); + } + for (entity, _) in (&*data.0, &data.3.check()).join() { + data.3.remove(entity); + } + for (entity, _) in (&*data.0, &data.4.check()).join() { + data.4.remove(entity); + } + for (entity, _) in (&*data.0, &data.5.check()).join() { + data.5.remove(entity); + } + } } // Running let mut world = World::new(); - world.register::(); + world.register_group::(); + + world.create_entity().with(Comp1("Nice".to_owned())).with(Comp4(500)).with(Comp5(501)).build(); + world.create_entity().with(Comp1("Nice".to_owned())).with(Comp2(5.0)).with(Comp3(1)).build(); + world.create_entity().with(Comp1("Nice".to_owned())).with(Comp3(2)).build(); + world.create_entity().with(Comp4(0)).with(Comp2(3.14159265358979)).build(); + + let serialized = { + let world_serializer = WorldSerializer::::new(&world); + let serialized = serde_json::to_string_pretty(&world_serializer).unwrap(); + println!("{}", serialized); + serialized + }; + + { + let mut dispatcher = DispatcherBuilder::new() + .add(RemovalSystem, "removal", &[]) + .build(); + + dispatcher.dispatch(&mut world.res, ()); + } + + { + let world_serializer = WorldSerializer::::new(&world); + let serialized = serde_json::to_string_pretty(&world_serializer).unwrap(); + println!("before: {}", serialized); + } + + { + let entity_list: Vec<_> = { + let entities = world.read_resource::(); + entities.join().collect() + }; + + let world_deserializer = WorldDeserializer::::new(&mut world, entity_list.as_slice()); + let mut json_deserializer = serde_json::Deserializer::from_str(&serialized); + world_deserializer.deserialize(&mut json_deserializer); + } + + { + let world_serializer = WorldSerializer::::new(&world); + let serialized = serde_json::to_string_pretty(&world_serializer).unwrap(); + println!("after: {}", serialized); + } + + { + use specs::entity::ComponentGroup; + + println!("locals:"); + for local in SomeGroup::local_components() { + println!("{}", local); + } + println!("all:"); + for element in SomeGroup::components() { + println!("{}", element); + } + println!("subgroups:"); + for subgroup in SomeGroup::subgroups() { + println!("{}", subgroup); + } + } } #[cfg(not(feature="serialize"))] diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index 9a57c3a9d..ca868a304 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -13,6 +13,8 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Duplicate references to the components. // `quote` currently doesn't support using the same variable binding twice in a repetition. + let items = items.iter().filter(|item| !item.parameter.ignore).collect::>(); + // Component fields let ref component = items.iter().filter(|item| item.parameter.option.is_component()).collect::>(); let component2 = component; @@ -21,16 +23,13 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Serializable components let ref component_serialize = component.iter().filter(|item| item.parameter.serialize).collect::>(); let component_serialize2 = component_serialize; - let component_serialize3 = component_serialize; + + // Serializable component names + let ref component_serialize_field = component_serialize.iter().map(|item| item.field.ident.as_ref().unwrap() ).collect::>(); // Subgroup fields let ref subgroup = items.iter().filter(|item| item.parameter.option.is_subgroup()).collect::>(); - // Serializable fields - let ref subgroup_serialize = subgroup.iter().filter(|item| item.parameter.serialize).collect::>(); - let subgroup_serialize2 = subgroup_serialize; - let subgroup_serialize3 = subgroup_serialize; - // Normal group methods. let default = quote! { fn local_components() -> Vec<&'static str> { @@ -38,9 +37,9 @@ pub fn expand_group(input: &DeriveInput) -> Result { } #[allow(unused_mut)] fn components() -> Vec<&'static str> { - let mut list = <#name as _specs::ComponentGroup>::local_components(); + let mut list = #name::local_components(); #( - for component in <#subgroup as _specs::ComponentGroup>::components() { + for component in #subgroup::components() { list.push(component); } )* @@ -49,6 +48,15 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn subgroups() -> Vec<&'static str> { vec![ #( stringify!(#subgroup), )* ] } + fn register(world: &mut _specs::World) { + #( + world.register::<#component>(); + )* + + #( + #subgroup::register(world); + )* + } }; // Serialization methods @@ -57,12 +65,12 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn serialize_group(world: &_specs::World, serializer: S) -> Result { let mut map = serializer.serialize_map(None)?; #( - let storage = world.read::<#component_serialize>().pass(); - _serde::ser::SerializeMap::serialize_entry(&mut map, stringify!(#component_serialize2), &storage)?; + let storage = world.read::<#component_serialize>(); + _serde::ser::SerializeMap::serialize_entry(&mut map, stringify!(#component_serialize_field), &storage)?; )* #( - <#subgroup_serialize as _specs::ComponentGroup>::serialize_subgroup::(world, &mut map)?; + #subgroup::serialize_subgroup::(world, &mut map)?; )* _serde::ser::SerializeMap::end(map) @@ -70,12 +78,12 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { #( - let storage = world.read::<#component_serialize>().pass(); - _serde::ser::SerializeMap::serialize_entry(map, stringify!(#component_serialize2), &storage)?; + let storage = world.read::<#component_serialize>(); + _serde::ser::SerializeMap::serialize_entry(map, stringify!(#component_serialize_field), &storage)?; )* #( - <#subgroup_serialize as _specs::ComponentGroup>::serialize_subgroup::(world, map)?; + #subgroup::serialize_subgroup::(world, map)?; )* Ok(()) @@ -98,15 +106,15 @@ pub fn expand_group(input: &DeriveInput) -> Result { #[allow(unused_variables)] match &*key { #( - stringify!(#component_serialize) => { - let mut storage = self.0.write::<#component_serialize2>().pass(); - let packed = visitor.visit_value::<_specs::PackedData<#component_serialize3>>()?; + stringify!(#component_serialize_field) => { + let mut storage = self.0.write::<#component_serialize>(); + let packed = visitor.visit_value::<_specs::PackedData<#component_serialize2>>()?; let _ = storage.merge(self.1, packed); }, )* key @ _ => { #( - if let Some(()) = <#subgroup_serialize as _specs::ComponentGroup>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { + if let Some(()) = <#subgroup as _specs::entity::SerializeGroup>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { continue; // subgroup deserialized the components } )* @@ -128,16 +136,16 @@ pub fn expand_group(input: &DeriveInput) -> Result { #[allow(unused_variables)] match &*key { #( - stringify!(#component_serialize) => { - let mut storage = world.write::<#component_serialize2>().pass(); - let packed = visitor.visit_value::<_specs::PackedData<#component_serialize3>>()?; + stringify!(#component_serialize_field) => { + let mut storage = world.write::<#component_serialize>(); + let packed = visitor.visit_value::<_specs::PackedData<#component_serialize2>>()?; let _ = storage.merge(entities, packed); Ok(Some(())) }, )* key @ _ => { #( - if let Some(()) = <#subgroup_serialize as _specs::ComponentGroup>::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { + if let Some(()) = #subgroup::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { return Ok(Some(())); } )* @@ -150,7 +158,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Normal expand (no serialization) let expanded = quote! { #[automatically_derived] - impl _specs::ComponentGroup for #name { + impl _specs::entity::ComponentGroup for #name { #default } }; @@ -211,6 +219,9 @@ pub struct Parameter { // Serialize this field pub serialize: bool, + + // Ignore this field completely + pub ignore: bool, } impl Parameter { @@ -220,12 +231,14 @@ impl Parameter { let mut subgroup = false; let mut serialize = false; + let mut ignore = false; for meta_items in input.iter().filter_map(filter_group) { for meta_item in meta_items { match meta_item { MetaItem(Word(ref name)) if name == "serialize" => serialize = true, MetaItem(Word(ref name)) if name == "subgroup" => subgroup = true, + MetaItem(Word(ref name)) if name == "ignore" => ignore = true, _ => println!("Unused attribute: {:?}", meta_item), } } @@ -241,6 +254,7 @@ impl Parameter { Parameter { option: parameter_type, serialize: serialize, + ignore: ignore, } } } From 155f672afbadc787c921a37f22e2fd557a759f1b Mon Sep 17 00:00:00 2001 From: Aceeri Date: Wed, 31 May 2017 15:33:22 -0700 Subject: [PATCH 06/11] Expand usage with generated macro --- specs/Cargo.toml | 2 +- specs/src/group.rs | 48 +++++++++ specs/src/world.rs | 4 +- specs_derive/examples/derive.rs | 87 ++++++++++++++++- specs_derive/src/component_group.rs | 145 ++++++++++++++++++++++++++-- 5 files changed, 272 insertions(+), 14 deletions(-) diff --git a/specs/Cargo.toml b/specs/Cargo.toml index 310905b8f..2e851af08 100644 --- a/specs/Cargo.toml +++ b/specs/Cargo.toml @@ -46,4 +46,4 @@ serialize = ["serde", "serde_derive"] cgmath = { version = "0.14", features = ["eders"] } rand = "0.3" serde_json = "1.0" -specs_derive = { path = "../specs_derive", version = "0.1" } +specs_derive = { path = "../specs_derive", version = "0.1", features = ["serialize"] } diff --git a/specs/src/group.rs b/specs/src/group.rs index 728c57ad0..614cc144a 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -31,3 +31,51 @@ pub trait SerializeGroup: ComponentGroup { fn deserialize_subgroup(world: &mut World, entities: &[Entity], key: String, visitor: &mut V) -> Result, V::Error> where V: serde::de::MapVisitor; } + +macro_rules! deconstruct { + ( $( $associated:tt )* ) => { + $( #[doc(hidden)] type $associated; )* + } +} + +/// Splits a tuple with recursive associated types. +pub trait Split { + /// The type split off from the tuple. + type This; + /// The rest of the tuple aside from the split off associated type. + type Next: Split; + /// Is there another split possible. + fn next() -> bool; +} + +/// Deconstructs the group. +pub trait DeconstructedGroup: ComponentGroup { + //type All: Split; + /// Locals of the group. + type Locals: Split; + /// Subgroups of the group. + type Subgroups: Split; + //fn all() -> usize; + /// Amount of local components there are in this group. + fn locals() -> usize; + /// Amount of subgroups there are in this group. + fn subgroups() -> usize; +} + +impl Split for (A, B) { + type This = A; + type Next = B; + fn next() -> bool { true } +} + +impl Split for (A,) { + type This = A; + type Next = (); + fn next() -> bool { false } +} + +impl Split for () { + type This = (); + type Next = (); + fn next() -> bool { false } +} diff --git a/specs/src/world.rs b/specs/src/world.rs index 4406fa53e..9e32eda48 100644 --- a/specs/src/world.rs +++ b/specs/src/world.rs @@ -219,13 +219,13 @@ impl Entity { /// Returns the index of the `Entity`. #[inline] - pub fn get_id(&self) -> Index { + pub fn id(&self) -> Index { self.0 } /// Returns the `Generation` of the `Entity`. #[inline] - pub fn get_gen(&self) -> Generation { + pub fn gen(&self) -> Generation { self.1 } } diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index d4f72d68a..59e35276b 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -1,3 +1,6 @@ + +#![recursion_limit="256"] + extern crate specs; #[macro_use] extern crate specs_derive; @@ -10,10 +13,76 @@ extern crate serde_derive; #[cfg(feature="serialize")] extern crate serde_json; +macro_rules! tokens { // possible idea here for feeding the call macro for iterations. + () => { // 64 tokens + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + } +} + +macro_rules! call { + // Top level calls + /* + ( $type:ident : $group:ty => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( $type : $group => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ); + } + */ + ( local: $group:ty => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( + Iter :: $group : Locals => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + }; + + // Helper methods + (Iter :: { $( $group:tt )* } [ $( $token:tt )* ] => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + $method::<$( $before, )* <$( $group )* as Split>::This $( , $after )*>( $( $args ),* ); + + if <$( $group )* as Split>::next() { + call!( + Iter :: { <$( $group )* as Split>::Next } => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + } + }; + (Iter :: $group:ty : $at:ident => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( + Iter :: { <$group as DeconstructedGroup>::$at } [ tokens!() ] => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + }; +} + #[cfg(feature="serialize")] fn main() { use specs::prelude::*; use specs::{WorldDeserializer, WorldSerializer}; + use specs::entity::{ComponentGroup, SerializeGroup, DeconstructedGroup, Split}; use serde::{Deserialize, Serialize}; use serde::de::DeserializeSeed; @@ -161,10 +230,26 @@ fn main() { println!("{}", element); } println!("subgroups:"); - for subgroup in SomeGroup::subgroups() { + for subgroup in ::subgroups() { println!("{}", subgroup); } } + + fn call_method(s: &str) -> u32 { + println!("Nice {}", s); + 42 + } + + fn call_other(s: &str) -> u32 { + println!("Static {}", s); + 3 + } + + let s = "test"; + + call!(local: SomeGroup => + fn call_method [ ] in [ ] (s) + ); } #[cfg(not(feature="serialize"))] diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index ca868a304..4174cd78d 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -1,5 +1,5 @@ -use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field}; +use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty}; use quote::{ToTokens, Tokens}; /// Expands the `ComponentGroup` derive implementation. @@ -9,26 +9,133 @@ pub fn expand_group(input: &DeriveInput) -> Result { let items = get_items(input); let dummy_const = Ident::new(format!("_IMPL_COMPONENTGROUP_FOR_{}", name)); + let macro_const = Ident::new(format!("call_{}", name)); + let macro_const_call = Ident::new(format!("{}!", macro_const)); // Duplicate references to the components. // `quote` currently doesn't support using the same variable binding twice in a repetition. - let items = items.iter().filter(|item| !item.parameter.ignore).collect::>(); + let items = items.iter() + .filter(|item| !item.parameter.ignore ) + .collect::>(); // Component fields - let ref component = items.iter().filter(|item| item.parameter.option.is_component()).collect::>(); + let ref component = items.iter() + .filter(|item| item.parameter.option.is_component() ) + .map(|item| *item) + .collect::>(); let component2 = component; let component3 = component; // Serializable components - let ref component_serialize = component.iter().filter(|item| item.parameter.serialize).collect::>(); + let ref component_serialize = component.iter() + .filter(|item| item.parameter.serialize) + .map(|item| *item) + .collect::>(); let component_serialize2 = component_serialize; // Serializable component names - let ref component_serialize_field = component_serialize.iter().map(|item| item.field.ident.as_ref().unwrap() ).collect::>(); + let ref component_serialize_field = component_serialize.iter() + .map(|item| item.field.ident.as_ref().unwrap() ) + .collect::>(); // Subgroup fields - let ref subgroup = items.iter().filter(|item| item.parameter.option.is_subgroup()).collect::>(); + let ref subgroup = items.iter() + .filter(|item| item.parameter.option.is_subgroup() ) + .map(|item| *item) + .collect::>(); + + // Subgroup macro names + let ref subgroup_macro = subgroup.iter() + .map(|item| { + let mut tokens = Tokens::new(); + item.field.ty.to_tokens(&mut tokens); + Ident::new(format!("call_{}!", tokens.as_str())) + }) + .collect::>(); + + let local_count = component.iter().count(); + let subgroup_count = subgroup.iter().count(); + + // Construct Split groups for the components and subgroups. + let local_ty = type_list(component); + let subgroup_ty = type_list(subgroup); + + let locals_impl = quote! { + impl _specs::entity::DeconstructedGroup for #name { + //type All; + type Locals = #local_ty; + type Subgroups = #subgroup_ty; + //fn all() -> usize { #all_count } + fn locals() -> usize { #local_count } + fn subgroups() -> usize { #subgroup_count } + } + }; + + // Macro for expanding usage... + let expanded_macro = quote! { + #[allow(unused_macros)] + macro_rules! #macro_const { + ($($option:ident):* => + fn $($method:ident).* + [$( $before:ty ),*] in [$( $after:ty ),*] + ($( $args:expr ),*) + ) => {{ + #macro_const_call($($option):* => IMPL + fn $($method).* + [$( $before ),*] in [$( $after ),*] + ( $( $args ),* ) + ); + }}; + // all components and subgroups + (all => IMPL + fn $($method:ident).* + [$( $before:ty ),*] in [$( $after:ty ),*] + ($( $args:expr ),*) + ) => {{ + let result = + (#( + $($method).*::<$( $before, )* #component $(, $after)* >( $( $args ),* ), + )*); + + let result = (result, (#( + #subgroup_macro(all => IMPL + fn $($method).* + [$( $before ),*] in [$( $after ),*] + ( $( $args ),* ) + ), + )*)); + + result + }}; + // only components in this subgroup + (local => IMPL + fn $($method:ident).* + [$( $before:ty ),*] in [$( $after:ty ),*] + ($( $args:expr ),*) + ) => {{ + let result = + (#( + $($method).*::<$( $before, )* #component $(, $after)* >( $( $args ),* ), + )*); + + result + }}; + // only subgroups in this subgroup (not useful on its own but useful together with local components) + (subgroups => IMPL + fn $($method:ident).* + [$( $before:ty ),*] in [$( $after:ty ),*] + ($( $args:expr ),*) + ) => {{ + let result = + (#( + $($method).*::<$( $before, )* #subgroup $(, $after)* >( $( $args ),* ), + )*); + + result + }}; + }; + }; // Normal group methods. let default = quote! { @@ -104,9 +211,9 @@ pub fn expand_group(input: &DeriveInput) -> Result { { while let Some(key) = visitor.visit_key::()? { #[allow(unused_variables)] - match &*key { + match key { #( - stringify!(#component_serialize_field) => { + #component_serialize_field => { let mut storage = self.0.write::<#component_serialize>(); let packed = visitor.visit_value::<_specs::PackedData<#component_serialize2>>()?; let _ = storage.merge(self.1, packed); @@ -134,9 +241,9 @@ pub fn expand_group(input: &DeriveInput) -> Result { where V: _serde::de::MapVisitor { #[allow(unused_variables)] - match &*key { + match key { #( - stringify!(#component_serialize_field) => { + #component_serialize_field => { let mut storage = world.write::<#component_serialize>(); let packed = visitor.visit_value::<_specs::PackedData<#component_serialize2>>()?; let _ = storage.merge(entities, packed); @@ -176,8 +283,10 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Wrap the expanded code to prevent context conflicts. let wrap = quote! { #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + #[macro_use] const #dummy_const: () = { extern crate specs as _specs; + #locals_impl #expanded }; }; @@ -286,6 +395,22 @@ fn get_items(input: &DeriveInput) -> Vec { .collect::>() } +fn type_list(list: &Vec<&Item>) -> Ty { + list.iter().rev().enumerate().fold(Ty::Tup(Vec::new()), |tup, (index, item)| { + if index == 0 { + Ty::Tup(vec![ + item.field.ty.clone(), + ]) + } + else { + Ty::Tup(vec![ + item.field.ty.clone(), + tup, + ]) + } + }) +} + struct Item<'a> { pub parameter: Parameter, pub field: &'a Field, From da747e1b72c0cfa1e24784176718d98f73882432 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Wed, 14 Jun 2017 19:45:40 -0700 Subject: [PATCH 07/11] Token feed for macro iteration break --- specs/src/group.rs | 78 +++++++- specs_derive/examples/derive.rs | 58 +++--- specs_derive/src/component_group.rs | 269 ++++++++++++++++++---------- 3 files changed, 279 insertions(+), 126 deletions(-) diff --git a/specs/src/group.rs b/specs/src/group.rs index 614cc144a..8f58808e6 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -1,4 +1,6 @@ +use std::marker::PhantomData; + use prelude::World; #[cfg(feature="serialize")] @@ -32,12 +34,6 @@ pub trait SerializeGroup: ComponentGroup { where V: serde::de::MapVisitor; } -macro_rules! deconstruct { - ( $( $associated:tt )* ) => { - $( #[doc(hidden)] type $associated; )* - } -} - /// Splits a tuple with recursive associated types. pub trait Split { /// The type split off from the tuple. @@ -46,16 +42,81 @@ pub trait Split { type Next: Split; /// Is there another split possible. fn next() -> bool; + /// Next split in the iterator. + fn split_iter(&self, ty: String) -> SplitIter { + SplitIter { + inner: None, + ty: ty, + } + } +} + +pub struct SplitConcat(PhantomData<(A, B)>); + +impl Split for SplitConcat { + type This = A::This; + type Next = Break; + fn next() -> bool { + + } +} + +pub struct Break; +impl Split for Break { + type This = A::This; + type Next = A::Next; +} + +pub fn next(s: String) -> String { + "<".to_owned() + &s + " as Split>::Next" +} + +pub fn this(s: String) -> String { + "<".to_owned() + &s + " as Split>::This" +} + +pub struct SplitIter + where S: Split, + ::Next: Split, +{ + inner: Option<::Next>, + ty: String, +} + +impl Iterator for SplitIter + where S: Split, + ::Next: Split, +{ + type Item = String; + fn next(&mut self) -> Option { + use std::mem; + if let Some(ref mut inner) = self.inner { + inner.split_iter(next(self.ty.clone())).next() + } + else { + self.inner = Some(unsafe { mem::uninitialized() }); + if ::next() { + Some(this(self.ty.clone())) + } + else { + None + } + } + } } /// Deconstructs the group. pub trait DeconstructedGroup: ComponentGroup { - //type All: Split; + /// All components of this group and all subgroups recursively. + type All: Split; /// Locals of the group. type Locals: Split; /// Subgroups of the group. type Subgroups: Split; - //fn all() -> usize; + /// Amount of components of this group and all subgroups recursively. + fn all() -> usize; + ///// Parameters associated with the components. + //fn all_params() -> &'static [Parameter]; /// Amount of local components there are in this group. fn locals() -> usize; /// Amount of subgroups there are in this group. @@ -79,3 +140,4 @@ impl Split for () { type Next = (); fn next() -> bool { false } } + diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index 59e35276b..041a085f3 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -13,34 +13,17 @@ extern crate serde_derive; #[cfg(feature="serialize")] extern crate serde_json; -macro_rules! tokens { // possible idea here for feeding the call macro for iterations. - () => { // 64 tokens - A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A - A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A - } -} +use std::mem; macro_rules! call { // Top level calls - /* - ( $type:ident : $group:ty => - fn $method:ident - [ $( $before:ty ),* ] in [ $( $after:ty ),* ] - ( $( $args:expr ),* ) - ) => { - call!( $type : $group => - fn $method - [ $( $before ),* ] in [ $( $after ),* ] - ( $( $args ),* ); - } - */ ( local: $group:ty => fn $method:ident [ $( $before:ty ),* ] in [ $( $after:ty ),* ] ( $( $args:expr ),* ) ) => { call!( - Iter :: $group : Locals => + @Iter $group: Locals => fn $method [ $( $before ),* ] in [ $( $after ),* ] ( $( $args ),* ) @@ -48,7 +31,7 @@ macro_rules! call { }; // Helper methods - (Iter :: { $( $group:tt )* } [ $( $token:tt )* ] => + (@Iter [ $( $group:tt )* ] [ A $( $token:tt )* ] => fn $method:ident [ $( $before:ty ),* ] in [ $( $after:ty ),* ] ( $( $args:expr ),* ) @@ -57,20 +40,35 @@ macro_rules! call { if <$( $group )* as Split>::next() { call!( - Iter :: { <$( $group )* as Split>::Next } => - fn $method - [ $( $before ),* ] in [ $( $after ),* ] - ( $( $args ),* ) + @Iter [ <$( $group )* as Split>::Next ] [ $( $token )* ] => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) ); } }; - (Iter :: $group:ty : $at:ident => + + // Break macro recursion + (@Iter [ $( $group:tt )* ] [ ] => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { }; + + (@Iter $group:ty: $at:ident => fn $method:ident [ $( $before:ty ),* ] in [ $( $after:ty ),* ] ( $( $args:expr ),* ) ) => { call!( - Iter :: { <$group as DeconstructedGroup>::$at } [ tokens!() ] => + @Iter [ <$group as DeconstructedGroup>::$at ] [ + // Requires tokens for recursion breaking. + // Each row has 32 tokens, totalling to 128 currently. + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + ] => fn $method [ $( $before ),* ] in [ $( $after ),* ] ( $( $args ),* ) @@ -250,6 +248,14 @@ fn main() { call!(local: SomeGroup => fn call_method [ ] in [ ] (s) ); + call!(local: SomeGroup => + fn call_other [ ] in [ ] (s) + ); + + let x: ::Locals = unsafe { mem::uninitialized() }; + for item in x.split_iter("::Locals".to_owned()) { + println!("item: {:?}", item); + } } #[cfg(not(feature="serialize"))] diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index 4174cd78d..64fe0e5c5 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -1,12 +1,19 @@ -use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty}; +use std::iter::{FromIterator, IntoIterator}; +use std::ops::{Deref, DerefMut}; +use std::marker::PhantomData; +use std::any::Any; + +use syn::{parse, Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty}; use quote::{ToTokens, Tokens}; +use specs::entity::Split; + /// Expands the `ComponentGroup` derive implementation. #[allow(unused_variables)] pub fn expand_group(input: &DeriveInput) -> Result { let name = &input.ident; - let items = get_items(input); + let items = ItemList::new(input); let dummy_const = Ident::new(format!("_IMPL_COMPONENTGROUP_FOR_{}", name)); let macro_const = Ident::new(format!("call_{}", name)); @@ -15,23 +22,21 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Duplicate references to the components. // `quote` currently doesn't support using the same variable binding twice in a repetition. - let items = items.iter() + let items = items.into_iter() .filter(|item| !item.parameter.ignore ) - .collect::>(); + .collect::(); - // Component fields + // Local component fields let ref component = items.iter() - .filter(|item| item.parameter.option.is_component() ) - .map(|item| *item) - .collect::>(); + .filter(|item| !item.parameter.subgroup ) + .collect::(); let component2 = component; let component3 = component; // Serializable components let ref component_serialize = component.iter() .filter(|item| item.parameter.serialize) - .map(|item| *item) - .collect::>(); + .collect::(); let component_serialize2 = component_serialize; // Serializable component names @@ -41,9 +46,8 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Subgroup fields let ref subgroup = items.iter() - .filter(|item| item.parameter.option.is_subgroup() ) - .map(|item| *item) - .collect::>(); + .filter(|item| item.parameter.subgroup ) + .collect::(); // Subgroup macro names let ref subgroup_macro = subgroup.iter() @@ -54,21 +58,32 @@ pub fn expand_group(input: &DeriveInput) -> Result { }) .collect::>(); + // Get all components from a subgroup let local_count = component.iter().count(); let subgroup_count = subgroup.iter().count(); - // Construct Split groups for the components and subgroups. - let local_ty = type_list(component); - let subgroup_ty = type_list(subgroup); + // Construct Split tuple groups for the components and subgroups. + let local_ty = component.type_list(); + let subgroup_ty = subgroup.type_list(); let locals_impl = quote! { impl _specs::entity::DeconstructedGroup for #name { - //type All; + type All = SplitConcat< + #local_ty, + #( + <#subgroup as DeconstructedGroup>::All, + )* + #subgroup_ty + >; type Locals = #local_ty; type Subgroups = #subgroup_ty; - //fn all() -> usize { #all_count } fn locals() -> usize { #local_count } fn subgroups() -> usize { #subgroup_count } + fn all() -> usize { + let mut count = #local_count; + #( count += <#subgroup as DeconstructedGroup>::all(); )* + count + } } }; @@ -294,47 +309,23 @@ pub fn expand_group(input: &DeriveInput) -> Result { Ok(wrap) } -#[derive(PartialEq, Debug)] -pub enum ParameterType { - // Parameters relating to subgroups only - Subgroup { - - }, - // Parameters relating to components only - Component { - - }, -} - -impl ParameterType { - fn is_subgroup(&self) -> bool { - match self { - &ParameterType::Subgroup { } => true, - &ParameterType::Component { } => false, - } - } - fn is_component(&self) -> bool { - match self { - &ParameterType::Subgroup { } => false, - &ParameterType::Component { } => true, - } - } -} - -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Parameter { - // Type of parameter - pub option: ParameterType, + // Is a subgroup. + pub subgroup: bool, // Serialize this field pub serialize: bool, // Ignore this field completely pub ignore: bool, + + // Name of item. + pub name: String, } impl Parameter { - pub fn parse(input: &Vec) -> Parameter { + pub fn parse(field: &Field) -> Parameter { use syn::NestedMetaItem::MetaItem; use syn::MetaItem::Word; @@ -342,7 +333,7 @@ impl Parameter { let mut serialize = false; let mut ignore = false; - for meta_items in input.iter().filter_map(filter_group) { + for meta_items in field.attrs.iter().filter_map(filter_group) { for meta_item in meta_items { match meta_item { MetaItem(Word(ref name)) if name == "serialize" => serialize = true, @@ -353,17 +344,11 @@ impl Parameter { } } - let parameter_type = if subgroup { - ParameterType::Subgroup { } - } - else { - ParameterType::Component { } - }; - Parameter { - option: parameter_type, + subgroup: subgroup, serialize: serialize, ignore: ignore, + name: field.ident.clone().unwrap().to_string(), } } } @@ -375,50 +360,150 @@ fn filter_group(attr: &Attribute) -> Option> { } } -fn get_items(input: &DeriveInput) -> Vec { - let fields = match input.body { - Body::Enum(_) => panic!("Enum cannot be a component group"), - Body::Struct(ref data) => match data { - &VariantData::Struct(ref fields) => fields, - _ => panic!("Struct must have named fields"), - }, - }; +#[derive(Debug, Clone)] +struct Item<'a> { + pub parameter: Parameter, + pub field: &'a Field, +} + +impl<'a> ToTokens for Item<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + self.field.ty.to_tokens(tokens); + } +} + +#[derive(Debug, Clone)] +struct ItemList<'a>(Vec>); + +impl<'a> Deref for ItemList<'a> { + type Target = Vec>; + fn deref(&self) -> &Vec> { + &self.0 + } +} + +impl<'a> DerefMut for ItemList<'a> { + fn deref_mut(&mut self) -> &mut Vec> { + &mut self.0 + } +} - fields - .iter() - .map(move |field| { - Item { - parameter: Parameter::parse(&field.attrs), - field: field, +impl<'a> IntoIterator for ItemList<'a> { + type Item = Item<'a>; + type IntoIter = > as IntoIterator>::IntoIter; + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a: 'b, 'b> IntoIterator for &'b ItemList<'a> { + type Item = &'b Item<'a>; + type IntoIter = <&'b Vec> as IntoIterator>::IntoIter; + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> FromIterator> for ItemList<'a> { + fn from_iter>>(iter: I) -> ItemList<'a> { + let list = > as FromIterator>>::from_iter(iter); + ItemList::from_list(list) + } +} + +impl<'a: 'b, 'b> FromIterator<&'b Item<'a>> for ItemList<'a> { + fn from_iter>>(iter: I) -> ItemList<'a> { + let list = iter.into_iter().cloned().collect::>>(); + ItemList::from_list(list) + } +} + +impl<'a> ItemList<'a> { + fn new<'b>(input: &'b DeriveInput) -> ItemList<'b> { + let fields = match input.body { + Body::Enum(_) => panic!("Enum cannot be a component group"), + Body::Struct(ref data) => match data { + &VariantData::Struct(ref fields) => fields, + _ => panic!("Struct must have named fields"), + }, + }; + + fields + .iter() + .map(move |field| { + Item { + parameter: Parameter::parse(&field), + field: field, + } + }) + .collect::() + } + + fn from_list<'b>(list: Vec>) -> ItemList<'b> { + ItemList(list) + } + + fn type_list(&self) -> Ty { + self.0.iter().rev().enumerate().fold(Ty::Tup(Vec::new()), |tup, (index, item)| { + if index == 0 { + Ty::Tup(vec![ + item.field.ty.clone(), + ]) + } + else { + Ty::Tup(vec![ + item.field.ty.clone(), + tup, + ]) } }) - .collect::>() + } +} + + + +/* +struct SplitIter + where S: Split, +{ + inner: Option::Next>>>, + ty: String, + phantom: PhantomData } -fn type_list(list: &Vec<&Item>) -> Ty { - list.iter().rev().enumerate().fold(Ty::Tup(Vec::new()), |tup, (index, item)| { - if index == 0 { - Ty::Tup(vec![ - item.field.ty.clone(), - ]) +impl Iterator for SplitIter + where S: Split, +{ + type Item = String; + fn next(&mut self) -> Option { + if let Some(inner) = self.inner { + inner.next() } else { - Ty::Tup(vec![ - item.field.ty.clone(), - tup, - ]) + if ::next() { + self.inner = Some(Box::new(SplitIter::<::Next> { + inner: None, + ty: next(self.ty), + phantom: PhantomData + })); + Some(this(self.ty)) + } + else { + None + } } - }) + } } -struct Item<'a> { - pub parameter: Parameter, - pub field: &'a Field, -} +struct SplitIter(Box, String); -impl<'a> ToTokens for Item<'a> { - fn to_tokens(&self, tokens: &mut Tokens) { - self.field.ty.to_tokens(tokens); +impl Iterator for SplitIter { + type Item = String; + fn next(&mut self) -> Option { + if self.0.next { + self.0 = Box::new(Next::<<::Upper as Split>::Next>(PhantomData)); + + } } } - +*/ From ce56f1eaeafd1ae913f59633fa1ed622ad9a1da6 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Sat, 17 Jun 2017 04:24:03 -0700 Subject: [PATCH 08/11] Update to 1.0 serde, clean up unnecessary code, zero copy deserialization for storages --- specs/src/group.rs | 79 +------ specs/src/lib.rs | 6 +- specs/src/world.rs | 33 +-- specs_derive/Cargo.toml | 6 +- specs_derive/examples/derive.rs | 42 ++-- specs_derive/src/component_group.rs | 320 +++++++++------------------- specs_derive/src/lib.rs | 3 - 7 files changed, 144 insertions(+), 345 deletions(-) diff --git a/specs/src/group.rs b/specs/src/group.rs index 8f58808e6..dca0879a9 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -1,10 +1,8 @@ -use std::marker::PhantomData; - -use prelude::World; +use World; #[cfg(feature="serialize")] -use prelude::Entity; +use Entity; #[cfg(feature="serialize")] use serde::{self, Serializer, Deserializer}; @@ -28,10 +26,10 @@ pub trait SerializeGroup: ComponentGroup { /// Helper method for serializing the world. fn serialize_subgroup(world: &World, map: &mut S::SerializeMap) -> Result<(), S::Error>; /// Deserializes the group of components into the world. - fn deserialize_group(world: &mut World, entities: &[Entity], deserializer: D) -> Result<(), D::Error>; + fn deserialize_group<'de, D: Deserializer<'de>>(world: &mut World, entities: &[Entity], deserializer: D) -> Result<(), D::Error>; /// Helper method for deserializing the world. - fn deserialize_subgroup(world: &mut World, entities: &[Entity], key: String, visitor: &mut V) -> Result, V::Error> - where V: serde::de::MapVisitor; + fn deserialize_subgroup<'de, M>(world: &mut World, entities: &[Entity], key: &'de str, map: &mut M) -> Result, M::Error> + where M: serde::de::MapAccess<'de>; } /// Splits a tuple with recursive associated types. @@ -42,81 +40,14 @@ pub trait Split { type Next: Split; /// Is there another split possible. fn next() -> bool; - /// Next split in the iterator. - fn split_iter(&self, ty: String) -> SplitIter { - SplitIter { - inner: None, - ty: ty, - } - } -} - -pub struct SplitConcat(PhantomData<(A, B)>); - -impl Split for SplitConcat { - type This = A::This; - type Next = Break; - fn next() -> bool { - - } -} - -pub struct Break; -impl Split for Break { - type This = A::This; - type Next = A::Next; -} - -pub fn next(s: String) -> String { - "<".to_owned() + &s + " as Split>::Next" -} - -pub fn this(s: String) -> String { - "<".to_owned() + &s + " as Split>::This" -} - -pub struct SplitIter - where S: Split, - ::Next: Split, -{ - inner: Option<::Next>, - ty: String, -} - -impl Iterator for SplitIter - where S: Split, - ::Next: Split, -{ - type Item = String; - fn next(&mut self) -> Option { - use std::mem; - if let Some(ref mut inner) = self.inner { - inner.split_iter(next(self.ty.clone())).next() - } - else { - self.inner = Some(unsafe { mem::uninitialized() }); - if ::next() { - Some(this(self.ty.clone())) - } - else { - None - } - } - } } /// Deconstructs the group. pub trait DeconstructedGroup: ComponentGroup { - /// All components of this group and all subgroups recursively. - type All: Split; /// Locals of the group. type Locals: Split; /// Subgroups of the group. type Subgroups: Split; - /// Amount of components of this group and all subgroups recursively. - fn all() -> usize; - ///// Parameters associated with the components. - //fn all_params() -> &'static [Parameter]; /// Amount of local components there are in this group. fn locals() -> usize; /// Amount of subgroups there are in this group. diff --git a/specs/src/lib.rs b/specs/src/lib.rs index 0d1a12e5f..df336929a 100644 --- a/specs/src/lib.rs +++ b/specs/src/lib.rs @@ -184,7 +184,7 @@ extern crate serde; #[macro_use] extern crate serde_derive; -pub use group::ComponentGroup; +pub use group::{ComponentGroup, DeconstructedGroup, SerializeGroup, Split}; pub use join::{Join, JoinIter, JoinParIter, ParJoin}; pub use shred::{ Dispatcher, DispatcherBuilder, Fetch, FetchId, FetchIdMut, FetchMut, RunNow, RunningTime, System, SystemData}; @@ -222,3 +222,7 @@ pub type Entities<'a> = Fetch<'a, EntitiesRes>; /// An index is basically the id of an `Entity`. pub type Index = u32; +mod group; +mod join; +mod storage; +mod world; diff --git a/specs/src/world.rs b/specs/src/world.rs index 9e32eda48..709cf27e3 100644 --- a/specs/src/world.rs +++ b/specs/src/world.rs @@ -1,8 +1,6 @@ use std::sync::atomic::{AtomicUsize, Ordering}; -<<<<<<< HEAD use crossbeam::sync::TreiberStack; -======= #[cfg(feature="serialize")] use std::marker::PhantomData; #[cfg(feature="serialize")] @@ -14,7 +12,6 @@ use group::SerializeGroup; use group::ComponentGroup; ->>>>>>> e7d508b... World serialization and deserialization use hibitset::{AtomicBitSet, BitSet, BitSetOr}; use mopa::Any; use shred::{Fetch, FetchMut, Resource, Resources}; @@ -770,7 +767,6 @@ impl Default for World { } } -<<<<<<< HEAD #[cfg(test)] mod tests { use storage::VecStorage; @@ -794,7 +790,13 @@ mod tests { e = entities.create(); lazy.add((e, Pos)); -======= + } + + world.maintain(); + assert!(world.read::().get(e).is_some()); + } +} + #[cfg(feature="serialize")] /// Structure used to serialize a world using a component group. pub struct WorldSerializer<'a, G> { @@ -842,35 +844,18 @@ impl<'a, G> WorldDeserializer<'a, G> { world: world, entities: entities, phantom: PhantomData, ->>>>>>> e7d508b... World serialization and deserialization } - - world.maintain(); - assert!(world.read::().get(e).is_some()); } } -#[cfg(feature="serialize")] -<<<<<<< HEAD -/// Structure used to deserialize into the world. -pub struct WorldDeserializer<'a, G, C> - where G: ComponentGroup, - C: PartialEq + Eq + Hash + 'a, -{ - world: &'a mut World, - entities: &'a [Entity], - phantom: PhantomData, -} -======= -impl<'a, G> DeserializeSeed for WorldDeserializer<'a, G> +impl<'a, 'de, G> DeserializeSeed<'de> for WorldDeserializer<'a, G> where G: ComponentGroup + SerializeGroup, { type Value = (); fn deserialize(self, deserializer: D) -> Result<(), D::Error> - where D: Deserializer + where D: Deserializer<'de> { G::deserialize_group(self.world, self.entities, deserializer) } } ->>>>>>> e7d508b... World serialization and deserialization diff --git a/specs_derive/Cargo.toml b/specs_derive/Cargo.toml index fb11aa84a..2de696191 100644 --- a/specs_derive/Cargo.toml +++ b/specs_derive/Cargo.toml @@ -10,11 +10,11 @@ proc-macro = true specs = { path = "../specs", version = "0.9.1" } syn = "0.11.10" quote = "0.3.15" -serde = { version = "0.9.11", optional = true } +serde = { version = "1.0", optional = true } [dev-dependencies] -serde_derive = "0.9.11" -serde_json = "0.9.9" +serde_derive = "1.0" +serde_json = "1.0" [features] default = [] diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index 041a085f3..b747e8842 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -13,8 +13,7 @@ extern crate serde_derive; #[cfg(feature="serialize")] extern crate serde_json; -use std::mem; - +/* macro_rules! call { // Top level calls ( local: $group:ty => @@ -29,6 +28,18 @@ macro_rules! call { ( $( $args ),* ) ); }; + ( subgroups: $group:ty => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( + @Iter $group: Subgroups => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + }; // Helper methods (@Iter [ $( $group:tt )* ] [ A $( $token:tt )* ] => @@ -75,12 +86,11 @@ macro_rules! call { ); }; } +*/ #[cfg(feature="serialize")] fn main() { - use specs::prelude::*; - use specs::{WorldDeserializer, WorldSerializer}; - use specs::entity::{ComponentGroup, SerializeGroup, DeconstructedGroup, Split}; + use specs::{Component, ComponentGroup, DeconstructedGroup, DispatcherBuilder, Entities, EntitiesRes, Join, SerializeGroup, System, ReadStorage, Split, VecStorage, WriteStorage, World, WorldDeserializer, WorldSerializer}; use serde::{Deserialize, Serialize}; use serde::de::DeserializeSeed; @@ -118,6 +128,7 @@ fn main() { #[allow(dead_code)] struct SomeGroup { #[group(serialize)] + #[group(id = "5")] field1: Comp1, #[group(serialize)] @@ -139,7 +150,7 @@ fn main() { } struct RemovalSystem; - impl<'a, C> System<'a, C> for RemovalSystem { + impl<'a> System<'a> for RemovalSystem { type SystemData = ( Entities<'a>, WriteStorage<'a, Comp1>, @@ -149,7 +160,7 @@ fn main() { WriteStorage<'a, Comp5>, ); - fn work(&mut self, mut data: Self::SystemData, _: C) { + fn run(&mut self, mut data: Self::SystemData) { // Remove all components for (entity, _) in (&*data.0, &data.1.check()).join() { data.1.remove(entity); @@ -190,7 +201,8 @@ fn main() { .add(RemovalSystem, "removal", &[]) .build(); - dispatcher.dispatch(&mut world.res, ()); + dispatcher.dispatch(&mut world.res); + world.maintain(); } { @@ -201,7 +213,7 @@ fn main() { { let entity_list: Vec<_> = { - let entities = world.read_resource::(); + let entities = world.read_resource::(); entities.join().collect() }; @@ -217,8 +229,6 @@ fn main() { } { - use specs::entity::ComponentGroup; - println!("locals:"); for local in SomeGroup::local_components() { println!("{}", local); @@ -243,19 +253,15 @@ fn main() { 3 } - let s = "test"; - + /* + let s = "Something"; call!(local: SomeGroup => fn call_method [ ] in [ ] (s) ); call!(local: SomeGroup => fn call_other [ ] in [ ] (s) ); - - let x: ::Locals = unsafe { mem::uninitialized() }; - for item in x.split_iter("::Locals".to_owned()) { - println!("item: {:?}", item); - } + */ } #[cfg(not(feature="serialize"))] diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index 64fe0e5c5..b25d53ad8 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -1,23 +1,16 @@ use std::iter::{FromIterator, IntoIterator}; use std::ops::{Deref, DerefMut}; -use std::marker::PhantomData; -use std::any::Any; -use syn::{parse, Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty}; -use quote::{ToTokens, Tokens}; - -use specs::entity::Split; +use syn::{Ident, VariantData, Attribute, NestedMetaItem, MetaItem, Body, DeriveInput, Field, Ty, Lit}; +use quote::Tokens; /// Expands the `ComponentGroup` derive implementation. -#[allow(unused_variables)] pub fn expand_group(input: &DeriveInput) -> Result { let name = &input.ident; let items = ItemList::new(input); let dummy_const = Ident::new(format!("_IMPL_COMPONENTGROUP_FOR_{}", name)); - let macro_const = Ident::new(format!("call_{}", name)); - let macro_const_call = Ident::new(format!("{}!", macro_const)); // Duplicate references to the components. // `quote` currently doesn't support using the same variable binding twice in a repetition. @@ -30,154 +23,63 @@ pub fn expand_group(input: &DeriveInput) -> Result { let ref component = items.iter() .filter(|item| !item.parameter.subgroup ) .collect::(); - let component2 = component; - let component3 = component; + let ref comp_ty = component.types(); // Serializable components let ref component_serialize = component.iter() .filter(|item| item.parameter.serialize) .collect::(); - let component_serialize2 = component_serialize; - - // Serializable component names - let ref component_serialize_field = component_serialize.iter() - .map(|item| item.field.ident.as_ref().unwrap() ) - .collect::>(); + #[allow(unused_variables)] + let ref comp_serialize_name = component_serialize.names(); + let ref comp_serialize_ty = component_serialize.types(); + #[allow(unused_variables)] + let comp_serialize_ty2 = comp_serialize_ty; // Subgroup fields let ref subgroup = items.iter() .filter(|item| item.parameter.subgroup ) .collect::(); - - // Subgroup macro names - let ref subgroup_macro = subgroup.iter() - .map(|item| { - let mut tokens = Tokens::new(); - item.field.ty.to_tokens(&mut tokens); - Ident::new(format!("call_{}!", tokens.as_str())) - }) - .collect::>(); + let ref subgroup_ty = subgroup.types(); // Get all components from a subgroup let local_count = component.iter().count(); let subgroup_count = subgroup.iter().count(); - // Construct Split tuple groups for the components and subgroups. + // Construct `Split` tuple groups for the components and subgroups. let local_ty = component.type_list(); - let subgroup_ty = subgroup.type_list(); + let sub_ty = subgroup.type_list(); - let locals_impl = quote! { - impl _specs::entity::DeconstructedGroup for #name { - type All = SplitConcat< - #local_ty, - #( - <#subgroup as DeconstructedGroup>::All, - )* - #subgroup_ty - >; + // Implementation for deconstructed group for the call macro to work. + let deconstructed = quote! { + impl _specs::DeconstructedGroup for #name { type Locals = #local_ty; - type Subgroups = #subgroup_ty; + type Subgroups = #sub_ty; fn locals() -> usize { #local_count } fn subgroups() -> usize { #subgroup_count } - fn all() -> usize { - let mut count = #local_count; - #( count += <#subgroup as DeconstructedGroup>::all(); )* - count - } } }; - // Macro for expanding usage... - let expanded_macro = quote! { - #[allow(unused_macros)] - macro_rules! #macro_const { - ($($option:ident):* => - fn $($method:ident).* - [$( $before:ty ),*] in [$( $after:ty ),*] - ($( $args:expr ),*) - ) => {{ - #macro_const_call($($option):* => IMPL - fn $($method).* - [$( $before ),*] in [$( $after ),*] - ( $( $args ),* ) - ); - }}; - // all components and subgroups - (all => IMPL - fn $($method:ident).* - [$( $before:ty ),*] in [$( $after:ty ),*] - ($( $args:expr ),*) - ) => {{ - let result = - (#( - $($method).*::<$( $before, )* #component $(, $after)* >( $( $args ),* ), - )*); - - let result = (result, (#( - #subgroup_macro(all => IMPL - fn $($method).* - [$( $before ),*] in [$( $after ),*] - ( $( $args ),* ) - ), - )*)); - - result - }}; - // only components in this subgroup - (local => IMPL - fn $($method:ident).* - [$( $before:ty ),*] in [$( $after:ty ),*] - ($( $args:expr ),*) - ) => {{ - let result = - (#( - $($method).*::<$( $before, )* #component $(, $after)* >( $( $args ),* ), - )*); - - result - }}; - // only subgroups in this subgroup (not useful on its own but useful together with local components) - (subgroups => IMPL - fn $($method:ident).* - [$( $before:ty ),*] in [$( $after:ty ),*] - ($( $args:expr ),*) - ) => {{ - let result = - (#( - $($method).*::<$( $before, )* #subgroup $(, $after)* >( $( $args ),* ), - )*); - - result - }}; - }; - }; - // Normal group methods. let default = quote! { fn local_components() -> Vec<&'static str> { - vec![ #( stringify!(#component) ),* ] + vec![ #( stringify!(#comp_ty), )* ] } - #[allow(unused_mut)] fn components() -> Vec<&'static str> { + #[allow(unused_mut)] let mut list = #name::local_components(); #( - for component in #subgroup::components() { + for component in #subgroup_ty::components() { list.push(component); } )* list } fn subgroups() -> Vec<&'static str> { - vec![ #( stringify!(#subgroup), )* ] + vec![ #( stringify!(#subgroup_ty), )* ] } fn register(world: &mut _specs::World) { - #( - world.register::<#component>(); - )* - - #( - #subgroup::register(world); - )* + #( world.register::<#comp_ty>(); )* + #( #subgroup_ty::register(world); )* } }; @@ -187,56 +89,49 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn serialize_group(world: &_specs::World, serializer: S) -> Result { let mut map = serializer.serialize_map(None)?; #( - let storage = world.read::<#component_serialize>(); - _serde::ser::SerializeMap::serialize_entry(&mut map, stringify!(#component_serialize_field), &storage)?; - )* - - #( - #subgroup::serialize_subgroup::(world, &mut map)?; + let storage = world.read::<#comp_serialize_ty>(); + _serde::ser::SerializeMap::serialize_entry(&mut map, #comp_serialize_name, &storage)?; )* + #( #subgroup_ty::serialize_subgroup::(world, &mut map)?; )* _serde::ser::SerializeMap::end(map) } fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { #( - let storage = world.read::<#component_serialize>(); - _serde::ser::SerializeMap::serialize_entry(map, stringify!(#component_serialize_field), &storage)?; - )* - - #( - #subgroup::serialize_subgroup::(world, map)?; + let storage = world.read::<#comp_serialize_ty>(); + _serde::ser::SerializeMap::serialize_entry(map, #comp_serialize_name, &storage)?; )* - + #( #subgroup_ty::serialize_subgroup::(world, map)?; )* Ok(()) } - fn deserialize_group(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { + fn deserialize_group<'de, D: _serde::Deserializer<'de>>(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { use std::fmt; struct ComponentVisitor<'a>(&'a mut _specs::World, &'a [_specs::Entity]); - impl<'a> _serde::de::Visitor for ComponentVisitor<'a> { + impl<'a, 'de> _serde::de::Visitor<'de> for ComponentVisitor<'a> { type Value = (); fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a map of component identifiers to packed data") } - fn visit_map(self, mut visitor: V) -> Result<(), V::Error> - where V: _serde::de::MapVisitor + fn visit_map(self, mut map: M) -> Result<(), M::Error> + where M: _serde::de::MapAccess<'de> { - while let Some(key) = visitor.visit_key::()? { - #[allow(unused_variables)] + #[allow(unused_variables)] + while let Some(key) = map.next_key::<&'de str>()? { match key { #( - #component_serialize_field => { - let mut storage = self.0.write::<#component_serialize>(); - let packed = visitor.visit_value::<_specs::PackedData<#component_serialize2>>()?; + #comp_serialize_name => { + let mut storage = self.0.write::<#comp_serialize_ty>(); + let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; let _ = storage.merge(self.1, packed); }, )* - key @ _ => { + uncaught_key @ _ => { #( - if let Some(()) = <#subgroup as _specs::entity::SerializeGroup>::deserialize_subgroup(self.0, self.1, key.to_owned(), &mut visitor)? { + if let Some(()) = <#subgroup_ty as _specs::SerializeGroup>::deserialize_subgroup(self.0, self.1, uncaught_key, &mut map)? { continue; // subgroup deserialized the components } )* @@ -252,22 +147,22 @@ pub fn expand_group(input: &DeriveInput) -> Result { Ok(deserializer.deserialize_map(ComponentVisitor(world, entities))?) } - fn deserialize_subgroup(world: &mut _specs::World, entities: &[_specs::Entity], key: String, mut visitor: &mut V) -> Result, V::Error> - where V: _serde::de::MapVisitor + fn deserialize_subgroup<'de, M>(world: &mut _specs::World, entities: &[_specs::Entity], key: &'de str, mut map: &mut M) -> Result, M::Error> + where M: _serde::de::MapAccess<'de> { #[allow(unused_variables)] match key { #( - #component_serialize_field => { - let mut storage = world.write::<#component_serialize>(); - let packed = visitor.visit_value::<_specs::PackedData<#component_serialize2>>()?; + #comp_serialize_name => { + let mut storage = world.write::<#comp_serialize_ty>(); + let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; let _ = storage.merge(entities, packed); Ok(Some(())) }, )* - key @ _ => { + uncaught_key @ _ => { #( - if let Some(()) = #subgroup::deserialize_subgroup(world, entities, key.to_owned(), visitor)? { + if let Some(()) = #subgroup_ty::deserialize_subgroup(world, entities, uncaught_key, map)? { return Ok(Some(())); } )* @@ -280,7 +175,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Normal expand (no serialization) let expanded = quote! { #[automatically_derived] - impl _specs::entity::ComponentGroup for #name { + impl _specs::ComponentGroup for #name { #default } }; @@ -290,7 +185,8 @@ pub fn expand_group(input: &DeriveInput) -> Result { let expanded = quote! { extern crate serde as _serde; #expanded - impl _specs::entity::SerializeGroup for #name { + #[automatically_derived] + impl _specs::SerializeGroup for #name { #serialize } }; @@ -301,7 +197,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { #[macro_use] const #dummy_const: () = { extern crate specs as _specs; - #locals_impl + #deconstructed #expanded }; }; @@ -322,38 +218,54 @@ pub struct Parameter { // Name of item. pub name: String, + + // Component id. + pub id: usize, } impl Parameter { + pub fn default(field: &Field) -> Self { + Parameter { + subgroup: false, + serialize: false, + ignore: false, + name: field.ident.clone().unwrap().to_string(), + id: 0usize, + } + } + pub fn parse(field: &Field) -> Parameter { use syn::NestedMetaItem::MetaItem; - use syn::MetaItem::Word; - - let mut subgroup = false; - let mut serialize = false; - let mut ignore = false; + use syn::MetaItem::{NameValue, Word}; + + let mut params = Parameter::default(field); + params.name = field.ident.clone().unwrap().to_string(); for meta_items in field.attrs.iter().filter_map(filter_group) { for meta_item in meta_items { match meta_item { - MetaItem(Word(ref name)) if name == "serialize" => serialize = true, - MetaItem(Word(ref name)) if name == "subgroup" => subgroup = true, - MetaItem(Word(ref name)) if name == "ignore" => ignore = true, - _ => println!("Unused attribute: {:?}", meta_item), + MetaItem(Word(ref name)) if name == "serialize" => params.serialize = true, + MetaItem(Word(ref name)) if name == "subgroup" => params.subgroup = true, + MetaItem(Word(ref name)) if name == "ignore" => params.ignore = true, + MetaItem(NameValue(ref name, Lit::Str(ref id, _))) if name == "id" => { + if let Ok(id) = id.parse::() { + params.id = id; + } + else { + println!("{} is not a valid id", id); + } + }, + _ => panic!("Unknown group attribute: {:?}", meta_item), } } } - Parameter { - subgroup: subgroup, - serialize: serialize, - ignore: ignore, - name: field.ident.clone().unwrap().to_string(), - } + params } } -fn filter_group(attr: &Attribute) -> Option> { +/// Get the attributes related to this derive. +pub fn filter_group(attr: &Attribute) -> Option> { match attr.value { MetaItem::List(ref name, ref items) if name == "group" => Some(items.iter().cloned().collect()), _ => None, @@ -361,19 +273,13 @@ fn filter_group(attr: &Attribute) -> Option> { } #[derive(Debug, Clone)] -struct Item<'a> { +pub struct Item<'a> { pub parameter: Parameter, pub field: &'a Field, } -impl<'a> ToTokens for Item<'a> { - fn to_tokens(&self, tokens: &mut Tokens) { - self.field.ty.to_tokens(tokens); - } -} - #[derive(Debug, Clone)] -struct ItemList<'a>(Vec>); +pub struct ItemList<'a>(Vec>); impl<'a> Deref for ItemList<'a> { type Target = Vec>; @@ -439,11 +345,11 @@ impl<'a> ItemList<'a> { .collect::() } - fn from_list<'b>(list: Vec>) -> ItemList<'b> { + pub fn from_list<'b>(list: Vec>) -> ItemList<'b> { ItemList(list) } - fn type_list(&self) -> Ty { + pub fn type_list(&self) -> Ty { self.0.iter().rev().enumerate().fold(Ty::Tup(Vec::new()), |tup, (index, item)| { if index == 0 { Ty::Tup(vec![ @@ -458,52 +364,22 @@ impl<'a> ItemList<'a> { } }) } -} - - -/* -struct SplitIter - where S: Split, -{ - inner: Option::Next>>>, - ty: String, - phantom: PhantomData -} - -impl Iterator for SplitIter - where S: Split, -{ - type Item = String; - fn next(&mut self) -> Option { - if let Some(inner) = self.inner { - inner.next() - } - else { - if ::next() { - self.inner = Some(Box::new(SplitIter::<::Next> { - inner: None, - ty: next(self.ty), - phantom: PhantomData - })); - Some(this(self.ty)) - } - else { - None - } - } + pub fn identifiers(&self) -> Vec { + self.0.iter() + .map(|item| item.field.ident.clone().unwrap() ) + .collect() } -} -struct SplitIter(Box, String); - -impl Iterator for SplitIter { - type Item = String; - fn next(&mut self) -> Option { - if self.0.next { - self.0 = Box::new(Next::<<::Upper as Split>::Next>(PhantomData)); + pub fn names(&self) -> Vec { + self.0.iter() + .map(|item| item.field.ident.clone().unwrap().to_string() ) + .collect() + } - } + pub fn types(&self) -> Vec { + self.0.iter() + .map(|item| item.field.ty.clone() ) + .collect() } } -*/ diff --git a/specs_derive/src/lib.rs b/specs_derive/src/lib.rs index ea45349cb..481ff5fe5 100644 --- a/specs_derive/src/lib.rs +++ b/specs_derive/src/lib.rs @@ -23,9 +23,6 @@ mod component_group; #[proc_macro_derive(ComponentGroup, attributes(group))] pub fn derive_component(input: TokenStream) -> TokenStream { let input = syn::parse_derive_input(&input.to_string()).unwrap(); - - println!("Output: {:?}", component_group::expand_group(&input)); - match component_group::expand_group(&input) { Ok(tokens) => tokens.parse().unwrap(), Err(err) => panic!("Error: {}", err), From 8f218126f0f7013589dcf58dbe3105b5a736b242 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Sat, 17 Jun 2017 20:28:44 -0700 Subject: [PATCH 09/11] Call macro --- .travis.yml | 2 +- specs/examples/serialize.rs | 11 +++-- specs/src/group.rs | 76 ++++++++++++++++++++++++++++++ specs/src/lib.rs | 1 + specs_derive/examples/derive.rs | 82 ++------------------------------- 5 files changed, 87 insertions(+), 85 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2981e51ae..654b5cac6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,7 @@ branches: script: - cargo build --all --verbose - cargo test --all --verbose -- cargo build -all --verbose --features serialize +- cargo build --all --verbose --features serialize - cargo test --all --verbose --features serialize - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then cargo bench --all --verbose --no-run; diff --git a/specs/examples/serialize.rs b/specs/examples/serialize.rs index c6cd43647..bfedff4fb 100644 --- a/specs/examples/serialize.rs +++ b/specs/examples/serialize.rs @@ -14,7 +14,7 @@ fn main() { use serde::de::DeserializeSeed; use serde_json::{Serializer, from_str as json_from_str}; use specs::{Component, DispatcherBuilder, Entities, Join, PackedData, System, VecStorage, - World, WriteStorage, WorldSerializer, WorldDeserializer}; + World, WorldDeserializer, WorldSerializer, WriteStorage}; #[derive(Debug, Serialize, Deserialize)] struct CompSerialize { @@ -91,10 +91,10 @@ fn main() { } struct RemovalSystem; - impl<'a, C> System<'a, C> for RemovalSystem { + impl<'a> System<'a> for RemovalSystem { type SystemData = RemovalData<'a>; - fn work(&mut self, mut data: RemovalData, _: C) { + fn run(&mut self, mut data: RemovalData) { // Remove all components for (entity, _) in (&*data.entities, &data.comp_serial.check()).join() { data.comp_serial.remove(entity); @@ -165,7 +165,8 @@ fn main() { .add(RemovalSystem, "removal", &[]) .build(); - dispatcher.dispatch(&mut world.res, ()); + dispatcher.dispatch(&mut world.res); + world.maintain(); } { @@ -176,7 +177,7 @@ fn main() { { let entity_list: Vec<_> = { - let entities = world.read_resource::(); + let entities = world.read_resource::(); entities.join().collect() }; diff --git a/specs/src/group.rs b/specs/src/group.rs index dca0879a9..69b31ff69 100644 --- a/specs/src/group.rs +++ b/specs/src/group.rs @@ -72,3 +72,79 @@ impl Split for () { fn next() -> bool { false } } +#[macro_export] +macro_rules! call { + // Top level calls + ( component: $group:ty => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( + @Iter $group: Locals => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + }; + ( subgroup: $group:ty => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( + @Iter $group: Subgroups => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + }; + + // Helper methods + + // Break macro recursion. + (@Iter [ $( $group:tt )* ] [ ] => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { }; + + // Iterate over components through associated type recursion. + (@Iter [ $( $group:tt )* ] [ A $( $token:tt )* ] => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + $method::<$( $before, )* <$( $group )* as Split>::This $( , $after )*>( $( $args ),* ); + + if <$( $group )* as Split>::next() { + call!( + @Iter [ <$( $group )* as Split>::Next ] [ $( $token )* ] => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + } + }; + + // Entrance to iteration. + (@Iter $group:ty: $at:ident => + fn $method:ident + [ $( $before:ty ),* ] in [ $( $after:ty ),* ] + ( $( $args:expr ),* ) + ) => { + call!( + @Iter [ <$group as DeconstructedGroup>::$at ] [ + // Requires tokens for recursion breaking. + // Each row has 32 tokens, totalling to 128 currently. + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A + ] => + fn $method + [ $( $before ),* ] in [ $( $after ),* ] + ( $( $args ),* ) + ); + }; +} diff --git a/specs/src/lib.rs b/specs/src/lib.rs index df336929a..a69c3b200 100644 --- a/specs/src/lib.rs +++ b/specs/src/lib.rs @@ -222,6 +222,7 @@ pub type Entities<'a> = Fetch<'a, EntitiesRes>; /// An index is basically the id of an `Entity`. pub type Index = u32; +#[macro_export] mod group; mod join; mod storage; diff --git a/specs_derive/examples/derive.rs b/specs_derive/examples/derive.rs index b747e8842..9ef37198f 100644 --- a/specs_derive/examples/derive.rs +++ b/specs_derive/examples/derive.rs @@ -1,6 +1,7 @@ #![recursion_limit="256"] +#[macro_use] extern crate specs; #[macro_use] extern crate specs_derive; @@ -13,81 +14,6 @@ extern crate serde_derive; #[cfg(feature="serialize")] extern crate serde_json; -/* -macro_rules! call { - // Top level calls - ( local: $group:ty => - fn $method:ident - [ $( $before:ty ),* ] in [ $( $after:ty ),* ] - ( $( $args:expr ),* ) - ) => { - call!( - @Iter $group: Locals => - fn $method - [ $( $before ),* ] in [ $( $after ),* ] - ( $( $args ),* ) - ); - }; - ( subgroups: $group:ty => - fn $method:ident - [ $( $before:ty ),* ] in [ $( $after:ty ),* ] - ( $( $args:expr ),* ) - ) => { - call!( - @Iter $group: Subgroups => - fn $method - [ $( $before ),* ] in [ $( $after ),* ] - ( $( $args ),* ) - ); - }; - - // Helper methods - (@Iter [ $( $group:tt )* ] [ A $( $token:tt )* ] => - fn $method:ident - [ $( $before:ty ),* ] in [ $( $after:ty ),* ] - ( $( $args:expr ),* ) - ) => { - $method::<$( $before, )* <$( $group )* as Split>::This $( , $after )*>( $( $args ),* ); - - if <$( $group )* as Split>::next() { - call!( - @Iter [ <$( $group )* as Split>::Next ] [ $( $token )* ] => - fn $method - [ $( $before ),* ] in [ $( $after ),* ] - ( $( $args ),* ) - ); - } - }; - - // Break macro recursion - (@Iter [ $( $group:tt )* ] [ ] => - fn $method:ident - [ $( $before:ty ),* ] in [ $( $after:ty ),* ] - ( $( $args:expr ),* ) - ) => { }; - - (@Iter $group:ty: $at:ident => - fn $method:ident - [ $( $before:ty ),* ] in [ $( $after:ty ),* ] - ( $( $args:expr ),* ) - ) => { - call!( - @Iter [ <$group as DeconstructedGroup>::$at ] [ - // Requires tokens for recursion breaking. - // Each row has 32 tokens, totalling to 128 currently. - A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A - A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A - A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A - A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A - ] => - fn $method - [ $( $before ),* ] in [ $( $after ),* ] - ( $( $args ),* ) - ); - }; -} -*/ - #[cfg(feature="serialize")] fn main() { use specs::{Component, ComponentGroup, DeconstructedGroup, DispatcherBuilder, Entities, EntitiesRes, Join, SerializeGroup, System, ReadStorage, Split, VecStorage, WriteStorage, World, WorldDeserializer, WorldSerializer}; @@ -253,15 +179,13 @@ fn main() { 3 } - /* let s = "Something"; - call!(local: SomeGroup => + call!(component: SomeGroup => fn call_method [ ] in [ ] (s) ); - call!(local: SomeGroup => + call!(component: SomeGroup => fn call_other [ ] in [ ] (s) ); - */ } #[cfg(not(feature="serialize"))] From 39ef52bf6efeb1780554e922f18954feb0f8f30e Mon Sep 17 00:00:00 2001 From: Aceeri Date: Sat, 17 Jun 2017 23:53:39 -0700 Subject: [PATCH 10/11] Resource ids, update READMEs --- specs/README.md | 144 +++++++++++++++++----------- specs/src/lib.rs | 7 +- specs_derive/README.md | 144 +++++++++++++++++----------- specs_derive/src/component_group.rs | 15 ++- 4 files changed, 196 insertions(+), 114 deletions(-) diff --git a/specs/README.md b/specs/README.md index a23f16cbc..359c5b964 100644 --- a/specs/README.md +++ b/specs/README.md @@ -1,71 +1,107 @@ -# specs -[![Build Status](https://travis-ci.org/slide-rs/specs.svg)](https://travis-ci.org/slide-rs/specs) -[![Crates.io](https://img.shields.io/crates/v/specs.svg?maxAge=2592000)](https://crates.io/crates/specs) -[![Gitter](https://badges.gitter.im/slide-rs/specs.svg)](https://gitter.im/slide-rs/specs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +# Specs -Specs is an Entity-Component System written in Rust. It aims for parallel systems execution with high ergonomics and flexibility. The name can be interpret in a number of ways: -- "SPECS Parallel ECS" -- "Super Powerful ECS" -- "Special ECS" +> **S**pecs **P**arallel **ECS** +[![Build Status][bi]][bl] [![Crates.io][ci]][cl] [![Gitter][gi]][gl] ![MIT/Apache][li] [![Docs.rs][di]][dl] -#### Classification -According to [ECS Design Crossroads](https://github.com/amethyst/amethyst/wiki/ECS-Design-Crossroads), `specs` fulfills all the requirements, has _In-place modification_ updates, and _Generational ID_ entities. +[bi]: https://travis-ci.org/slide-rs/specs.svg?branch=master +[bl]: https://travis-ci.org/slide-rs/specs -#### Features -- Automatic execution of the systems in parallel. Follows Rust ownership rules, where each component storage behaves as a variable. Depends on the order, in which systems are started. -- Component storage is abstract behind the trait. One can use vectors, hashmaps, trees, or whatever else. -- New components can be registered at any point from user modules. They don't have to be POD. -- No virtual calls, low overhead. +[ci]: https://img.shields.io/crates/v/specs.svg +[cl]: https://crates.io/crates/specs/ -#### Why is it fast -- Do you know many other natively parallel ECS in Rust? -- Abstract storage means you can choose the most efficient one according to your needs. You can even roll in your own. -- No virtual calls during systems processing means you work with the data directly. +[li]: https://img.shields.io/badge/license-Apache%202.0-blue.svg -See [ecs_bench](https://github.com/lschmierer/ecs_bench) for single- and multi-threaded performance comparisons. +[di]: https://docs.rs/specs/badge.svg +[dl]: https://docs.rs/specs/ -#### Why is it cool -- Your system can be as simple as a closure working on some components, no redundant info or boilerplate is needed. At the same time, you can manually fiddle with entities and components, and it would still be safe and convenient. -- Your components can be anything (as long as they implement `Component`)! Neither `Copy` or even `Clone` bounds are needed. -- Your component storages can be anything. Consider crazy stuff like a BSP tree, or a database over the network. Some storages can safely allow sharing their components between entities, some can not - but it's up to you to choose. +[gi]: https://badges.gitter.im/slide-rs/specs.svg +[gl]: https://gitter.im/slide-rs/specs -## Examples +Specs is an Entity-Component System written in Rust. +Unlike most other ECS libraries out there, it provides -#### Entity creation -```rust -let mut planner = { - let mut w = specs::World::new(); - // All components types should be registered before working with them - w.register::(); - w.register::(); - // create_now() of World provides with an EntityBuilder to add components to an Entity - w.create_now().with(Position(0)).with(Speed(2)).build(); - w.create_now().with(Position(-1)).with(Speed(100)).build(); - w.create_now().with(Position(127)).build(); - // Planner is used to run systems on the specified world with as many - // threads as virtual cpus - specs::Planner::new(w) -}; -``` +* easy parallelism +* high flexibility + * contains 5 different storages for components, which can be extended by the user + * it's types are mostly not coupled, so you can easily write some part yourself and + still use Specs + * `System`s may read from and write to components and resources, can depend on each + other and you can use barriers to force several stages in system execution +* high performance for real-world applications -#### System run -In order to run a system, you can either use a convenience-function (`runXwYr`) or a custom one (see below in the section "Custom system" and the examples in the `/examples` directory). Convencience-functions are used to request a defined number of mutable and immutable components on an entity. X and Y stand for the number of parameters respectively. `run1w1r` will allow you to use one mutable and one immutable component requirement respectively, as you can see below. Run-functions always iterate over all entities of a world with the requested components. +## Example ```rust -planner.run1w1r(|p: &mut Position, s: &Speed| { - *p += *s; -}); -``` +// A component contains data +// which is associated with an entity. +#[derive(Debug)] +struct Vel(f32); +#[derive(Debug)] +struct Pos(f32); -#### Custom system -```rust -impl System for MySystem { - fn run(&mut self, arg: RunArg, context: u32) { - let mut numbers = arg.fetch(|w| w.write::()); - for n in (&numbers).join() { - *n += context; +impl Component for Vel { + type Storage = VecStorage; +} + +impl Component for Pos { + type Storage = VecStorage; +} + +struct SysA; + +impl<'a> System<'a> for SysA { + // These are the resources required for execution. + // You can also define a struct and `#[derive(SystemData)]`, + // see the `full` example. + type SystemData = (WriteStorage<'a, Pos>, ReadStorage<'a, Vel>); + + fn run(&mut self, data: Self::SystemData) { + // The `.join()` combines multiple components, + // so we only access those entities which have + // both of them. + + let (mut pos, vel) = data; + + for (pos, vel) in (&mut pos, &vel).join() { + pos.0 += vel.0; } } } + +fn main() { + // The `World` is our + // container for components + // and other resources. + let mut world = World::new(); + world.register::(); + world.register::(); + + // An entity may or may not contain some component. + + world.create_entity().with(Vel(2.0)).with(Pos(0.0)).build(); + world.create_entity().with(Vel(4.0)).with(Pos(1.6)).build(); + world.create_entity().with(Vel(1.5)).with(Pos(5.4)).build(); + + // This entity does not have `Vel`, so it won't be dispatched. + world.create_entity().with(Pos(2.0)).build(); + + // This builds a dispatcher. + // The third parameter of `add` specifies + // logical dependencies on other systems. + // Since we only have one, we don't depend on anything. + // See the `full` example for dependencies. + let mut dispatcher = DispatcherBuilder::new().add(SysA, "sys_a", &[]).build(); + + // This dispatches all the systems in parallel (but blocking). + dispatcher.dispatch(&mut world.res); +} ``` + +Please look into [the examples directory](examples) for more. + +## Contribution + +Contribution is very welcome! If you didn't contribute before, just +filter for issues with "easy" label. Please note that your contributions +are assumed to be dual-licensed under Apache-2.0/MIT. diff --git a/specs/src/lib.rs b/specs/src/lib.rs index a69c3b200..f1fba7029 100644 --- a/specs/src/lib.rs +++ b/specs/src/lib.rs @@ -184,7 +184,7 @@ extern crate serde; #[macro_use] extern crate serde_derive; -pub use group::{ComponentGroup, DeconstructedGroup, SerializeGroup, Split}; +pub use group::{ComponentGroup, DeconstructedGroup, Split}; pub use join::{Join, JoinIter, JoinParIter, ParJoin}; pub use shred::{ Dispatcher, DispatcherBuilder, Fetch, FetchId, FetchIdMut, FetchMut, RunNow, RunningTime, System, SystemData}; @@ -199,7 +199,7 @@ pub use world::{Component, CreateIter, CreateIterAtomic, EntitiesRes, Entity, En Generation, LazyInsert, LazyInsertions, World}; #[cfg(feature="serialize")] -pub use world::{WorldSerializer, WorldDeserializer}; +pub use group::SerializeGroup; #[cfg(feature = "serialize")] pub use storage::{MergeError, PackedData}; @@ -207,6 +207,9 @@ pub use storage::{MergeError, PackedData}; #[cfg(feature = "common")] pub mod common; +#[cfg(feature="serialize")] +pub use world::{WorldSerializer, WorldDeserializer}; + /// A wrapper for a fetched `Entities` resource. /// Note that this is just `Fetch`, so /// you can easily use it in your system: diff --git a/specs_derive/README.md b/specs_derive/README.md index a23f16cbc..359c5b964 100644 --- a/specs_derive/README.md +++ b/specs_derive/README.md @@ -1,71 +1,107 @@ -# specs -[![Build Status](https://travis-ci.org/slide-rs/specs.svg)](https://travis-ci.org/slide-rs/specs) -[![Crates.io](https://img.shields.io/crates/v/specs.svg?maxAge=2592000)](https://crates.io/crates/specs) -[![Gitter](https://badges.gitter.im/slide-rs/specs.svg)](https://gitter.im/slide-rs/specs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +# Specs -Specs is an Entity-Component System written in Rust. It aims for parallel systems execution with high ergonomics and flexibility. The name can be interpret in a number of ways: -- "SPECS Parallel ECS" -- "Super Powerful ECS" -- "Special ECS" +> **S**pecs **P**arallel **ECS** +[![Build Status][bi]][bl] [![Crates.io][ci]][cl] [![Gitter][gi]][gl] ![MIT/Apache][li] [![Docs.rs][di]][dl] -#### Classification -According to [ECS Design Crossroads](https://github.com/amethyst/amethyst/wiki/ECS-Design-Crossroads), `specs` fulfills all the requirements, has _In-place modification_ updates, and _Generational ID_ entities. +[bi]: https://travis-ci.org/slide-rs/specs.svg?branch=master +[bl]: https://travis-ci.org/slide-rs/specs -#### Features -- Automatic execution of the systems in parallel. Follows Rust ownership rules, where each component storage behaves as a variable. Depends on the order, in which systems are started. -- Component storage is abstract behind the trait. One can use vectors, hashmaps, trees, or whatever else. -- New components can be registered at any point from user modules. They don't have to be POD. -- No virtual calls, low overhead. +[ci]: https://img.shields.io/crates/v/specs.svg +[cl]: https://crates.io/crates/specs/ -#### Why is it fast -- Do you know many other natively parallel ECS in Rust? -- Abstract storage means you can choose the most efficient one according to your needs. You can even roll in your own. -- No virtual calls during systems processing means you work with the data directly. +[li]: https://img.shields.io/badge/license-Apache%202.0-blue.svg -See [ecs_bench](https://github.com/lschmierer/ecs_bench) for single- and multi-threaded performance comparisons. +[di]: https://docs.rs/specs/badge.svg +[dl]: https://docs.rs/specs/ -#### Why is it cool -- Your system can be as simple as a closure working on some components, no redundant info or boilerplate is needed. At the same time, you can manually fiddle with entities and components, and it would still be safe and convenient. -- Your components can be anything (as long as they implement `Component`)! Neither `Copy` or even `Clone` bounds are needed. -- Your component storages can be anything. Consider crazy stuff like a BSP tree, or a database over the network. Some storages can safely allow sharing their components between entities, some can not - but it's up to you to choose. +[gi]: https://badges.gitter.im/slide-rs/specs.svg +[gl]: https://gitter.im/slide-rs/specs -## Examples +Specs is an Entity-Component System written in Rust. +Unlike most other ECS libraries out there, it provides -#### Entity creation -```rust -let mut planner = { - let mut w = specs::World::new(); - // All components types should be registered before working with them - w.register::(); - w.register::(); - // create_now() of World provides with an EntityBuilder to add components to an Entity - w.create_now().with(Position(0)).with(Speed(2)).build(); - w.create_now().with(Position(-1)).with(Speed(100)).build(); - w.create_now().with(Position(127)).build(); - // Planner is used to run systems on the specified world with as many - // threads as virtual cpus - specs::Planner::new(w) -}; -``` +* easy parallelism +* high flexibility + * contains 5 different storages for components, which can be extended by the user + * it's types are mostly not coupled, so you can easily write some part yourself and + still use Specs + * `System`s may read from and write to components and resources, can depend on each + other and you can use barriers to force several stages in system execution +* high performance for real-world applications -#### System run -In order to run a system, you can either use a convenience-function (`runXwYr`) or a custom one (see below in the section "Custom system" and the examples in the `/examples` directory). Convencience-functions are used to request a defined number of mutable and immutable components on an entity. X and Y stand for the number of parameters respectively. `run1w1r` will allow you to use one mutable and one immutable component requirement respectively, as you can see below. Run-functions always iterate over all entities of a world with the requested components. +## Example ```rust -planner.run1w1r(|p: &mut Position, s: &Speed| { - *p += *s; -}); -``` +// A component contains data +// which is associated with an entity. +#[derive(Debug)] +struct Vel(f32); +#[derive(Debug)] +struct Pos(f32); -#### Custom system -```rust -impl System for MySystem { - fn run(&mut self, arg: RunArg, context: u32) { - let mut numbers = arg.fetch(|w| w.write::()); - for n in (&numbers).join() { - *n += context; +impl Component for Vel { + type Storage = VecStorage; +} + +impl Component for Pos { + type Storage = VecStorage; +} + +struct SysA; + +impl<'a> System<'a> for SysA { + // These are the resources required for execution. + // You can also define a struct and `#[derive(SystemData)]`, + // see the `full` example. + type SystemData = (WriteStorage<'a, Pos>, ReadStorage<'a, Vel>); + + fn run(&mut self, data: Self::SystemData) { + // The `.join()` combines multiple components, + // so we only access those entities which have + // both of them. + + let (mut pos, vel) = data; + + for (pos, vel) in (&mut pos, &vel).join() { + pos.0 += vel.0; } } } + +fn main() { + // The `World` is our + // container for components + // and other resources. + let mut world = World::new(); + world.register::(); + world.register::(); + + // An entity may or may not contain some component. + + world.create_entity().with(Vel(2.0)).with(Pos(0.0)).build(); + world.create_entity().with(Vel(4.0)).with(Pos(1.6)).build(); + world.create_entity().with(Vel(1.5)).with(Pos(5.4)).build(); + + // This entity does not have `Vel`, so it won't be dispatched. + world.create_entity().with(Pos(2.0)).build(); + + // This builds a dispatcher. + // The third parameter of `add` specifies + // logical dependencies on other systems. + // Since we only have one, we don't depend on anything. + // See the `full` example for dependencies. + let mut dispatcher = DispatcherBuilder::new().add(SysA, "sys_a", &[]).build(); + + // This dispatches all the systems in parallel (but blocking). + dispatcher.dispatch(&mut world.res); +} ``` + +Please look into [the examples directory](examples) for more. + +## Contribution + +Contribution is very welcome! If you didn't contribute before, just +filter for issues with "easy" label. Please note that your contributions +are assumed to be dual-licensed under Apache-2.0/MIT. diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index b25d53ad8..c239f2fd6 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -31,6 +31,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { .collect::(); #[allow(unused_variables)] let ref comp_serialize_name = component_serialize.names(); + let ref comp_serialize_id = component_serialize.ids(); let ref comp_serialize_ty = component_serialize.types(); #[allow(unused_variables)] let comp_serialize_ty2 = comp_serialize_ty; @@ -89,7 +90,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn serialize_group(world: &_specs::World, serializer: S) -> Result { let mut map = serializer.serialize_map(None)?; #( - let storage = world.read::<#comp_serialize_ty>(); + let storage = world.read_with_id::<#comp_serialize_ty>(#comp_serialize_id); _serde::ser::SerializeMap::serialize_entry(&mut map, #comp_serialize_name, &storage)?; )* @@ -99,7 +100,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { #( - let storage = world.read::<#comp_serialize_ty>(); + let storage = world.read_with_id::<#comp_serialize_ty>(#comp_serialize_id); _serde::ser::SerializeMap::serialize_entry(map, #comp_serialize_name, &storage)?; )* #( #subgroup_ty::serialize_subgroup::(world, map)?; )* @@ -124,7 +125,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { match key { #( #comp_serialize_name => { - let mut storage = self.0.write::<#comp_serialize_ty>(); + let mut storage = self.0.write_with_id::<#comp_serialize_ty>(#comp_serialize_id); let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; let _ = storage.merge(self.1, packed); }, @@ -154,7 +155,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { match key { #( #comp_serialize_name => { - let mut storage = world.write::<#comp_serialize_ty>(); + let mut storage = world.write_with_id::<#comp_serialize_ty>(#comp_serialize_id); let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; let _ = storage.merge(entities, packed); Ok(Some(())) @@ -382,4 +383,10 @@ impl<'a> ItemList<'a> { .map(|item| item.field.ty.clone() ) .collect() } + + pub fn ids(&self) -> Vec { + self.0.iter() + .map(|item| item.parameter.id ) + .collect() + } } From 7f95c6c9145a36c1d416a6481a3136125df5e4a9 Mon Sep 17 00:00:00 2001 From: Aceeri Date: Sun, 18 Jun 2017 04:28:39 -0700 Subject: [PATCH 11/11] Extend component list --- .gitignore | 1 + .travis.yml | 6 + Cargo.toml | 7 +- {specs/benches => benches}/parallel.rs | 0 {specs/benches => benches}/world.rs | 0 {specs/examples => examples}/basic.rs | 0 {specs_derive/examples => examples}/derive.rs | 14 +- {specs/examples => examples}/full.rs | 0 {specs/examples => examples}/serialize.rs | 3 +- specs/.gitignore | 7 - specs/Cargo.toml | 49 ----- specs/README.md | 107 ----------- specs_derive/Cargo.toml | 3 +- specs_derive/README.md | 136 +++++++------- specs_derive/src/component_group.rs | 175 +++++++++--------- {specs/src => src}/group.rs | 5 + {specs/src => src}/join.rs | 0 {specs/src => src}/lib.rs | 1 - {specs/src => src}/storage/check.rs | 0 {specs/src => src}/storage/data.rs | 0 {specs/src => src}/storage/mod.rs | 0 {specs/src => src}/storage/ser.rs | 0 {specs/src => src}/storage/storages.rs | 0 {specs/src => src}/storage/tests.rs | 0 {specs/src => src}/world.rs | 2 - {specs/tests => tests}/tests.rs | 0 26 files changed, 173 insertions(+), 343 deletions(-) rename {specs/benches => benches}/parallel.rs (100%) rename {specs/benches => benches}/world.rs (100%) rename {specs/examples => examples}/basic.rs (100%) rename {specs_derive/examples => examples}/derive.rs (90%) rename {specs/examples => examples}/full.rs (100%) rename {specs/examples => examples}/serialize.rs (98%) delete mode 100644 specs/.gitignore delete mode 100644 specs/Cargo.toml delete mode 100644 specs/README.md rename {specs/src => src}/group.rs (96%) rename {specs/src => src}/join.rs (100%) rename {specs/src => src}/lib.rs (99%) rename {specs/src => src}/storage/check.rs (100%) rename {specs/src => src}/storage/data.rs (100%) rename {specs/src => src}/storage/mod.rs (100%) rename {specs/src => src}/storage/ser.rs (100%) rename {specs/src => src}/storage/storages.rs (100%) rename {specs/src => src}/storage/tests.rs (100%) rename {specs/src => src}/world.rs (99%) rename {specs/tests => tests}/tests.rs (100%) diff --git a/.gitignore b/.gitignore index d7ae0ff17..62d6d6dab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Generated by Cargo /target/ +/specs_derive/target/ Cargo.lock # Generated by mdbook diff --git a/.travis.yml b/.travis.yml index 654b5cac6..bdb4d2c9d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: rust rust: - nightly +- beta - stable branches: @@ -10,10 +11,15 @@ branches: - master script: +- cargo clean - cargo build --all --verbose +- cargo clean - cargo test --all --verbose +- cargo clean - cargo build --all --verbose --features serialize +- cargo clean - cargo test --all --verbose --features serialize +- cargo clean - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then cargo bench --all --verbose --no-run; fi diff --git a/Cargo.toml b/Cargo.toml index 95f127dd5..f1f857874 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,3 @@ -<<<<<<< HEAD [package] name = "specs" version = "0.9.2" @@ -50,9 +49,10 @@ common = ["futures"] serialize = ["serde", "serde_derive"] [dev-dependencies] -cgmath = { version = "0.14", features = ["eders"] } +cgmath = { version = "0.14", features = ["eders"] } rand = "0.3" serde_json = "1.0" +specs_derive = { path = "specs_derive", version = "0.1", features = ["serialize"] } [[example]] name = "basic" @@ -68,3 +68,6 @@ required-features = ["common"] name = "serialize" required-features = ["serialize"] +[[example]] +name = "derive" +required-features = ["serialize"] diff --git a/specs/benches/parallel.rs b/benches/parallel.rs similarity index 100% rename from specs/benches/parallel.rs rename to benches/parallel.rs diff --git a/specs/benches/world.rs b/benches/world.rs similarity index 100% rename from specs/benches/world.rs rename to benches/world.rs diff --git a/specs/examples/basic.rs b/examples/basic.rs similarity index 100% rename from specs/examples/basic.rs rename to examples/basic.rs diff --git a/specs_derive/examples/derive.rs b/examples/derive.rs similarity index 90% rename from specs_derive/examples/derive.rs rename to examples/derive.rs index 9ef37198f..60a16b5a3 100644 --- a/specs_derive/examples/derive.rs +++ b/examples/derive.rs @@ -6,18 +6,13 @@ extern crate specs; #[macro_use] extern crate specs_derive; -#[cfg(feature="serialize")] extern crate serde; -#[cfg(feature="serialize")] #[macro_use] extern crate serde_derive; -#[cfg(feature="serialize")] extern crate serde_json; -#[cfg(feature="serialize")] fn main() { - use specs::{Component, ComponentGroup, DeconstructedGroup, DispatcherBuilder, Entities, EntitiesRes, Join, SerializeGroup, System, ReadStorage, Split, VecStorage, WriteStorage, World, WorldDeserializer, WorldSerializer}; - use serde::{Deserialize, Serialize}; + use specs::{Component, ComponentGroup, DeconstructedGroup, DispatcherBuilder, Entities, Join, System, Split, VecStorage, WriteStorage, World, WorldDeserializer, WorldSerializer}; use serde::de::DeserializeSeed; #[derive(Debug, Serialize, Deserialize)] @@ -54,7 +49,6 @@ fn main() { #[allow(dead_code)] struct SomeGroup { #[group(serialize)] - #[group(id = "5")] field1: Comp1, #[group(serialize)] @@ -145,7 +139,7 @@ fn main() { let world_deserializer = WorldDeserializer::::new(&mut world, entity_list.as_slice()); let mut json_deserializer = serde_json::Deserializer::from_str(&serialized); - world_deserializer.deserialize(&mut json_deserializer); + let _ = world_deserializer.deserialize(&mut json_deserializer); } { @@ -188,7 +182,3 @@ fn main() { ); } -#[cfg(not(feature="serialize"))] -fn main() { - println!("Requires `serialize` flag to run"); -} diff --git a/specs/examples/full.rs b/examples/full.rs similarity index 100% rename from specs/examples/full.rs rename to examples/full.rs diff --git a/specs/examples/serialize.rs b/examples/serialize.rs similarity index 98% rename from specs/examples/serialize.rs rename to examples/serialize.rs index bfedff4fb..3feb2b2f3 100644 --- a/specs/examples/serialize.rs +++ b/examples/serialize.rs @@ -32,6 +32,7 @@ fn main() { } #[derive(ComponentGroup)] + #[allow(dead_code)] struct SerialGroup { #[group(serialize)] comp_serialize: CompSerialize, @@ -183,7 +184,7 @@ fn main() { let world_deserializer = WorldDeserializer::::new(&mut world, entity_list.as_slice()); let mut json_deserializer = serde_json::Deserializer::from_str(&serialized); - world_deserializer.deserialize(&mut json_deserializer); + let _ = world_deserializer.deserialize(&mut json_deserializer); } { diff --git a/specs/.gitignore b/specs/.gitignore deleted file mode 100644 index 99d938f8b..000000000 --- a/specs/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -# Generated by Cargo -/target/ -Cargo.lock - -# IDEs / Editor -*.iml -.idea diff --git a/specs/Cargo.toml b/specs/Cargo.toml deleted file mode 100644 index 2e851af08..000000000 --- a/specs/Cargo.toml +++ /dev/null @@ -1,49 +0,0 @@ -[package] -name = "specs" -version = "0.9.1" -description = """ -Specs is an Entity-Component System library written in Rust. -Unlike most other ECS libraries out there, it provides - -* easy parallelism -* high flexibility - * contains 5 different storages for components, which can be extended by the user - * it's types are mostly not coupled, so you can easily write some part yourself and - still use Specs - * `System`s may read from and write to components and resources, can depend on each - other and you can use barriers to force several stages in system execution -* high performance for real-world applications -""" -documentation = "https://docs.rs/specs/" -repository = "https://github.com/slide-rs/specs" -homepage = "https://slide-rs.github.io/specs-website/" -keywords = ["gamedev"] -categories = ["concurrency"] -license = "Apache-2.0" -authors = ["slide-rs hackers"] -exclude = ["bors.toml", ".travis.yml"] - -[badges] -travis-ci = { repository = "slide-rs/specs" } - -[dependencies] -atom = "0.3" -fnv = "1.0" -hibitset = "0.1.3" -mopa = "0.2" -shred = "0.4.2" -shred-derive = "0.3" -tuple_utils = "0.2" -rayon = "0.7.1" - -serde = { version = "1.0", optional = true } -serde_derive = { version = "1.0", optional = true } - -[features] -serialize = ["serde", "serde_derive"] - -[dev-dependencies] -cgmath = { version = "0.14", features = ["eders"] } -rand = "0.3" -serde_json = "1.0" -specs_derive = { path = "../specs_derive", version = "0.1", features = ["serialize"] } diff --git a/specs/README.md b/specs/README.md deleted file mode 100644 index 359c5b964..000000000 --- a/specs/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# Specs - -> **S**pecs **P**arallel **ECS** - -[![Build Status][bi]][bl] [![Crates.io][ci]][cl] [![Gitter][gi]][gl] ![MIT/Apache][li] [![Docs.rs][di]][dl] - -[bi]: https://travis-ci.org/slide-rs/specs.svg?branch=master -[bl]: https://travis-ci.org/slide-rs/specs - -[ci]: https://img.shields.io/crates/v/specs.svg -[cl]: https://crates.io/crates/specs/ - -[li]: https://img.shields.io/badge/license-Apache%202.0-blue.svg - -[di]: https://docs.rs/specs/badge.svg -[dl]: https://docs.rs/specs/ - -[gi]: https://badges.gitter.im/slide-rs/specs.svg -[gl]: https://gitter.im/slide-rs/specs - -Specs is an Entity-Component System written in Rust. -Unlike most other ECS libraries out there, it provides - -* easy parallelism -* high flexibility - * contains 5 different storages for components, which can be extended by the user - * it's types are mostly not coupled, so you can easily write some part yourself and - still use Specs - * `System`s may read from and write to components and resources, can depend on each - other and you can use barriers to force several stages in system execution -* high performance for real-world applications - -## Example - -```rust -// A component contains data -// which is associated with an entity. -#[derive(Debug)] -struct Vel(f32); -#[derive(Debug)] -struct Pos(f32); - -impl Component for Vel { - type Storage = VecStorage; -} - -impl Component for Pos { - type Storage = VecStorage; -} - -struct SysA; - -impl<'a> System<'a> for SysA { - // These are the resources required for execution. - // You can also define a struct and `#[derive(SystemData)]`, - // see the `full` example. - type SystemData = (WriteStorage<'a, Pos>, ReadStorage<'a, Vel>); - - fn run(&mut self, data: Self::SystemData) { - // The `.join()` combines multiple components, - // so we only access those entities which have - // both of them. - - let (mut pos, vel) = data; - - for (pos, vel) in (&mut pos, &vel).join() { - pos.0 += vel.0; - } - } -} - -fn main() { - // The `World` is our - // container for components - // and other resources. - let mut world = World::new(); - world.register::(); - world.register::(); - - // An entity may or may not contain some component. - - world.create_entity().with(Vel(2.0)).with(Pos(0.0)).build(); - world.create_entity().with(Vel(4.0)).with(Pos(1.6)).build(); - world.create_entity().with(Vel(1.5)).with(Pos(5.4)).build(); - - // This entity does not have `Vel`, so it won't be dispatched. - world.create_entity().with(Pos(2.0)).build(); - - // This builds a dispatcher. - // The third parameter of `add` specifies - // logical dependencies on other systems. - // Since we only have one, we don't depend on anything. - // See the `full` example for dependencies. - let mut dispatcher = DispatcherBuilder::new().add(SysA, "sys_a", &[]).build(); - - // This dispatches all the systems in parallel (but blocking). - dispatcher.dispatch(&mut world.res); -} -``` - -Please look into [the examples directory](examples) for more. - -## Contribution - -Contribution is very welcome! If you didn't contribute before, just -filter for issues with "easy" label. Please note that your contributions -are assumed to be dual-licensed under Apache-2.0/MIT. diff --git a/specs_derive/Cargo.toml b/specs_derive/Cargo.toml index 2de696191..30cd7d69d 100644 --- a/specs_derive/Cargo.toml +++ b/specs_derive/Cargo.toml @@ -7,7 +7,7 @@ authors = ["Aceeri "] proc-macro = true [dependencies] -specs = { path = "../specs", version = "0.9.1" } +specs = { path = "../", version = "0.9.2" } syn = "0.11.10" quote = "0.3.15" serde = { version = "1.0", optional = true } @@ -19,3 +19,4 @@ serde_json = "1.0" [features] default = [] serialize = ["serde", "specs/serialize"] + diff --git a/specs_derive/README.md b/specs_derive/README.md index 359c5b964..fdcde3d6d 100644 --- a/specs_derive/README.md +++ b/specs_derive/README.md @@ -1,6 +1,5 @@ -# Specs -> **S**pecs **P**arallel **ECS** +# Specs Procedural Derive Macros [![Build Status][bi]][bl] [![Crates.io][ci]][cl] [![Gitter][gi]][gl] ![MIT/Apache][li] [![Docs.rs][di]][dl] @@ -18,90 +17,83 @@ [gi]: https://badges.gitter.im/slide-rs/specs.svg [gl]: https://gitter.im/slide-rs/specs -Specs is an Entity-Component System written in Rust. -Unlike most other ECS libraries out there, it provides +## Component Grouping -* easy parallelism -* high flexibility - * contains 5 different storages for components, which can be extended by the user - * it's types are mostly not coupled, so you can easily write some part yourself and - still use Specs - * `System`s may read from and write to components and resources, can depend on each - other and you can use barriers to force several stages in system execution -* high performance for real-world applications +In a couple situations you are required to perform some task on a bunch of different components, +such as serialization or registering the component into the world. Tasks like these require either +dynamic dispatch through the use of trait objects or closures, but that can make you lose performance +and prevent some compiler optimizations. However, the alternative is a lot of boilerplate and isn't +very scalable if using third party code where they also require registering components similar to the +`World`. -## Example +In these situations it is useful to use a macro to reduce that boilerplate and make it less annoying +to add new components to the program. Component groups mark a bunch of different components that +you want to have some operation perform on all of them. -```rust -// A component contains data -// which is associated with an entity. -#[derive(Debug)] -struct Vel(f32); -#[derive(Debug)] -struct Pos(f32); - -impl Component for Vel { - type Storage = VecStorage; -} - -impl Component for Pos { - type Storage = VecStorage; -} - -struct SysA; +### Usage -impl<'a> System<'a> for SysA { - // These are the resources required for execution. - // You can also define a struct and `#[derive(SystemData)]`, - // see the `full` example. - type SystemData = (WriteStorage<'a, Pos>, ReadStorage<'a, Vel>); - fn run(&mut self, data: Self::SystemData) { - // The `.join()` combines multiple components, - // so we only access those entities which have - // both of them. +Component groups use a procedural derive macro along with using attributes with the tag `group`. +Fields in the component group `struct` are by default components, alternatively they can be marked +as a subgroup using the `subgroup` attribute. Subgroups in a component group will try to behave the +same as if the components were in the parent group. The field names are also used as unique identifiers +for components in things like serialization. - let (mut pos, vel) = data; +Note: When using the `call` macro to use the component groups, it is necessary to use another method +on subgroups for subgroups to behave correctly in the `call` macro. - for (pos, vel) in (&mut pos, &vel).join() { - pos.0 += vel.0; - } - } +```rust +#[derive(ComponentGroup)] +struct ExampleGroup { + // The group defaults to just a component. + // + // The field name "component1" will be used as an + // unique identifier. + component1: Component1, + + // Component grouping comes with built in support + // for serialization and deserialization with `serde` + // usage + #[group(serialize)] + component2: Component2, + + #[group(id = "5")] + component3: Component3, } -fn main() { - // The `World` is our - // container for components - // and other resources. - let mut world = World::new(); - world.register::(); - world.register::(); +#[derive(ComponentGroup)] +struct AnotherGroup { + component4: Component4, - // An entity may or may not contain some component. + // If you need a subgroup, then you need to + // designate the fields that are subgroups. + #[group(subgroup)] + example_group: ExampleGroup, +} +``` - world.create_entity().with(Vel(2.0)).with(Pos(0.0)).build(); - world.create_entity().with(Vel(4.0)).with(Pos(1.6)).build(); - world.create_entity().with(Vel(1.5)).with(Pos(5.4)).build(); +When operated on a method, this component group will look similar to something like: +```rust +fn method() { ... } +method::(); +method::(); +method::(); +method::(); +``` - // This entity does not have `Vel`, so it won't be dispatched. - world.create_entity().with(Pos(2.0)).build(); +### Attributes - // This builds a dispatcher. - // The third parameter of `add` specifies - // logical dependencies on other systems. - // Since we only have one, we don't depend on anything. - // See the `full` example for dependencies. - let mut dispatcher = DispatcherBuilder::new().add(SysA, "sys_a", &[]).build(); +`#[group(subgroup)]` +Marks the field as a subgroup. Will attempt to behave similar to if the components nested in the subgroup +are in the parent group. - // This dispatches all the systems in parallel (but blocking). - dispatcher.dispatch(&mut world.res); -} -``` +`#[group(serialize)]` +Marks the field as a serializable component or subgroup. All fields that are marked by this should implement +`Serialize` and `Deserialize`. The field name is used as the unique identifier for serializaion. -Please look into [the examples directory](examples) for more. +`#[group(id = "...")]` +Identifies a component id other than the default `0usize`. -## Contribution +### `call` Macro -Contribution is very welcome! If you didn't contribute before, just -filter for issues with "easy" label. Please note that your contributions -are assumed to be dual-licensed under Apache-2.0/MIT. +Component groups also provide capability for external extension using the `call` macro. diff --git a/specs_derive/src/component_group.rs b/specs_derive/src/component_group.rs index c239f2fd6..6024585d5 100644 --- a/specs_derive/src/component_group.rs +++ b/specs_derive/src/component_group.rs @@ -25,17 +25,6 @@ pub fn expand_group(input: &DeriveInput) -> Result { .collect::(); let ref comp_ty = component.types(); - // Serializable components - let ref component_serialize = component.iter() - .filter(|item| item.parameter.serialize) - .collect::(); - #[allow(unused_variables)] - let ref comp_serialize_name = component_serialize.names(); - let ref comp_serialize_id = component_serialize.ids(); - let ref comp_serialize_ty = component_serialize.types(); - #[allow(unused_variables)] - let comp_serialize_ty2 = comp_serialize_ty; - // Subgroup fields let ref subgroup = items.iter() .filter(|item| item.parameter.subgroup ) @@ -68,11 +57,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { fn components() -> Vec<&'static str> { #[allow(unused_mut)] let mut list = #name::local_components(); - #( - for component in #subgroup_ty::components() { - list.push(component); - } - )* + #( list.extend(#subgroup_ty::components()); )* list } fn subgroups() -> Vec<&'static str> { @@ -84,95 +69,107 @@ pub fn expand_group(input: &DeriveInput) -> Result { } }; - // Serialization methods #[cfg(feature="serialize")] - let serialize = quote! { - fn serialize_group(world: &_specs::World, serializer: S) -> Result { - let mut map = serializer.serialize_map(None)?; - #( - let storage = world.read_with_id::<#comp_serialize_ty>(#comp_serialize_id); - _serde::ser::SerializeMap::serialize_entry(&mut map, #comp_serialize_name, &storage)?; - )* - - #( #subgroup_ty::serialize_subgroup::(world, &mut map)?; )* - _serde::ser::SerializeMap::end(map) - } + let serialize = { + // Serializable components + let ref component_serialize = component.iter() + .filter(|item| item.parameter.serialize) + .collect::(); + let ref comp_serialize_name = component_serialize.names(); + let ref comp_serialize_id = component_serialize.ids(); + let ref comp_serialize_ty = component_serialize.types(); + let comp_serialize_ty2 = comp_serialize_ty; + + quote! { + fn serialize_group(world: &_specs::World, serializer: S) -> Result { + #[allow(unused_mut)] + let mut map = serializer.serialize_map(None)?; + #( + let storage = world.read_with_id::<#comp_serialize_ty>(#comp_serialize_id); + _serde::ser::SerializeMap::serialize_entry(&mut map, #comp_serialize_name, &storage)?; + )* - fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { - #( - let storage = world.read_with_id::<#comp_serialize_ty>(#comp_serialize_id); - _serde::ser::SerializeMap::serialize_entry(map, #comp_serialize_name, &storage)?; - )* - #( #subgroup_ty::serialize_subgroup::(world, map)?; )* - Ok(()) - } + #( #subgroup_ty::serialize_subgroup::(world, &mut map)?; )* + _serde::ser::SerializeMap::end(map) + } - fn deserialize_group<'de, D: _serde::Deserializer<'de>>(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { - use std::fmt; + fn serialize_subgroup(world: &_specs::World, map: &mut S::SerializeMap) -> Result<(), S::Error> { + #( + let storage = world.read_with_id::<#comp_serialize_ty>(#comp_serialize_id); + _serde::ser::SerializeMap::serialize_entry(map, #comp_serialize_name, &storage)?; + )* + #( #subgroup_ty::serialize_subgroup::(world, map)?; )* + Ok(()) + } - struct ComponentVisitor<'a>(&'a mut _specs::World, &'a [_specs::Entity]); - impl<'a, 'de> _serde::de::Visitor<'de> for ComponentVisitor<'a> { - type Value = (); - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "a map of component identifiers to packed data") - } + fn deserialize_group<'de, D: _serde::Deserializer<'de>>(world: &mut _specs::World, entities: &[_specs::Entity], deserializer: D) -> Result<(), D::Error> { + use std::fmt; - fn visit_map(self, mut map: M) -> Result<(), M::Error> - where M: _serde::de::MapAccess<'de> - { - #[allow(unused_variables)] - while let Some(key) = map.next_key::<&'de str>()? { - match key { - #( - #comp_serialize_name => { - let mut storage = self.0.write_with_id::<#comp_serialize_ty>(#comp_serialize_id); - let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; - let _ = storage.merge(self.1, packed); - }, - )* - uncaught_key @ _ => { + struct ComponentVisitor<'a>(&'a mut _specs::World, &'a [_specs::Entity]); + impl<'a, 'de> _serde::de::Visitor<'de> for ComponentVisitor<'a> { + type Value = (); + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "a map of component identifiers to packed data") + } + + fn visit_map(self, mut map: M) -> Result<(), M::Error> + where M: _serde::de::MapAccess<'de> + { + #[allow(unused_variables)] + while let Some(key) = map.next_key::<&'de str>()? { + match key { #( - if let Some(()) = <#subgroup_ty as _specs::SerializeGroup>::deserialize_subgroup(self.0, self.1, uncaught_key, &mut map)? { - continue; // subgroup deserialized the components - } + #comp_serialize_name => { + let mut storage = self.0.write_with_id::<#comp_serialize_ty>(#comp_serialize_id); + let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; + let _ = storage.merge(self.1, packed); + }, )* - continue; // not in the registered component list, ignore - }, + uncaught_key @ _ => { + #( + if let Some(()) = <#subgroup_ty as _specs::SerializeGroup>::deserialize_subgroup(self.0, self.1, uncaught_key, &mut map)? { + continue; // subgroup deserialized the components + } + )* + continue; // not in the registered component list, ignore + }, + } } - } - Ok(()) + Ok(()) + } } - } - Ok(deserializer.deserialize_map(ComponentVisitor(world, entities))?) - } + Ok(deserializer.deserialize_map(ComponentVisitor(world, entities))?) + } - fn deserialize_subgroup<'de, M>(world: &mut _specs::World, entities: &[_specs::Entity], key: &'de str, mut map: &mut M) -> Result, M::Error> - where M: _serde::de::MapAccess<'de> - { - #[allow(unused_variables)] - match key { - #( - #comp_serialize_name => { - let mut storage = world.write_with_id::<#comp_serialize_ty>(#comp_serialize_id); - let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; - let _ = storage.merge(entities, packed); - Ok(Some(())) - }, - )* - uncaught_key @ _ => { + fn deserialize_subgroup<'de, M>(world: &mut _specs::World, entities: &[_specs::Entity], key: &'de str, mut map: &mut M) -> Result, M::Error> + where M: _serde::de::MapAccess<'de> + { + #[allow(unused_variables)] + match key { #( - if let Some(()) = #subgroup_ty::deserialize_subgroup(world, entities, uncaught_key, map)? { - return Ok(Some(())); - } + #comp_serialize_name => { + let mut storage = world.write_with_id::<#comp_serialize_ty>(#comp_serialize_id); + let packed = map.next_value::<_specs::PackedData<#comp_serialize_ty2>>()?; + let _ = storage.merge(entities, packed); + Ok(Some(())) + }, )* - Ok(None) - }, + uncaught_key @ _ => { + #( + if let Some(()) = #subgroup_ty::deserialize_subgroup(world, entities, uncaught_key, map)? { + return Ok(Some(())); + } + )* + Ok(None) + }, + } } } }; + // Normal expand (no serialization) let expanded = quote! { #[automatically_derived] @@ -194,7 +191,7 @@ pub fn expand_group(input: &DeriveInput) -> Result { // Wrap the expanded code to prevent context conflicts. let wrap = quote! { - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + #[allow(non_upper_case_globals, unused_mut, unused_attributes, unused_qualifications)] #[macro_use] const #dummy_const: () = { extern crate specs as _specs; @@ -253,7 +250,7 @@ impl Parameter { params.id = id; } else { - println!("{} is not a valid id", id); + panic!("{} is not a valid id", id); } }, _ => panic!("Unknown group attribute: {:?}", meta_item), diff --git a/specs/src/group.rs b/src/group.rs similarity index 96% rename from specs/src/group.rs rename to src/group.rs index 69b31ff69..deeaaaf1a 100644 --- a/specs/src/group.rs +++ b/src/group.rs @@ -75,6 +75,9 @@ impl Split for () { #[macro_export] macro_rules! call { // Top level calls + + // Calls methods with local components. Should be used together with the `subgroup` call + // so that recursive groups work properly. ( component: $group:ty => fn $method:ident [ $( $before:ty ),* ] in [ $( $after:ty ),* ] @@ -87,6 +90,8 @@ macro_rules! call { ( $( $args ),* ) ); }; + + // Calls methods with the subgroups. ( subgroup: $group:ty => fn $method:ident [ $( $before:ty ),* ] in [ $( $after:ty ),* ] diff --git a/specs/src/join.rs b/src/join.rs similarity index 100% rename from specs/src/join.rs rename to src/join.rs diff --git a/specs/src/lib.rs b/src/lib.rs similarity index 99% rename from specs/src/lib.rs rename to src/lib.rs index f1fba7029..f1858a854 100644 --- a/specs/src/lib.rs +++ b/src/lib.rs @@ -225,7 +225,6 @@ pub type Entities<'a> = Fetch<'a, EntitiesRes>; /// An index is basically the id of an `Entity`. pub type Index = u32; -#[macro_export] mod group; mod join; mod storage; diff --git a/specs/src/storage/check.rs b/src/storage/check.rs similarity index 100% rename from specs/src/storage/check.rs rename to src/storage/check.rs diff --git a/specs/src/storage/data.rs b/src/storage/data.rs similarity index 100% rename from specs/src/storage/data.rs rename to src/storage/data.rs diff --git a/specs/src/storage/mod.rs b/src/storage/mod.rs similarity index 100% rename from specs/src/storage/mod.rs rename to src/storage/mod.rs diff --git a/specs/src/storage/ser.rs b/src/storage/ser.rs similarity index 100% rename from specs/src/storage/ser.rs rename to src/storage/ser.rs diff --git a/specs/src/storage/storages.rs b/src/storage/storages.rs similarity index 100% rename from specs/src/storage/storages.rs rename to src/storage/storages.rs diff --git a/specs/src/storage/tests.rs b/src/storage/tests.rs similarity index 100% rename from specs/src/storage/tests.rs rename to src/storage/tests.rs diff --git a/specs/src/world.rs b/src/world.rs similarity index 99% rename from specs/src/world.rs rename to src/world.rs index 709cf27e3..83f64efde 100644 --- a/specs/src/world.rs +++ b/src/world.rs @@ -10,8 +10,6 @@ use serde::{Serialize, Serializer, Deserializer}; #[cfg(feature="serialize")] use group::SerializeGroup; -use group::ComponentGroup; - use hibitset::{AtomicBitSet, BitSet, BitSetOr}; use mopa::Any; use shred::{Fetch, FetchMut, Resource, Resources}; diff --git a/specs/tests/tests.rs b/tests/tests.rs similarity index 100% rename from specs/tests/tests.rs rename to tests/tests.rs