├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | Notable user-facing changes with each release version will be described in this file. 4 | 5 | ## [0.2.0]: 2022-11-19 6 | 7 | ## Changed 8 | - Bevy 0.9 compatibility 9 | 10 | ## [0.1.1]: 2022-08-21 11 | 12 | ### Added 13 | - Helper functions for directly serializing to a file: 14 | - `scene_file_from_query_components` 15 | - `scene_file_from_query_filter` 16 | - `SceneBuilder::export_to_file` 17 | - Helper functions for directly adding to the app's asset collection: 18 | - `add_scene_from_query_components` 19 | - `add_scene_from_query_filter` 20 | - `SceneBuilder::build_scene_and_add` 21 | 22 | ## [0.1.0]: 2022-08-19 23 | 24 | Initial Release 25 | 26 | [0.2.0]: https://github.com/IyesGames/iyes_scene_tools/tree/v0.2.0 27 | [0.1.1]: https://github.com/IyesGames/iyes_scene_tools/tree/v0.1.1 28 | [0.1.0]: https://github.com/IyesGames/iyes_scene_tools/tree/v0.1.0 29 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "iyes_scene_tools" 3 | version = "0.2.0" 4 | edition = "2021" 5 | description = "Extra helpers for working with Bevy Scenes" 6 | license = "MIT OR Apache-2.0" 7 | readme = "README.md" 8 | repository = "https://github.com/IyesGames/iyes_scene_tools" 9 | keywords = ["gamedev", "bevy"] 10 | categories = ["game-engines"] 11 | exclude = ["assets"] 12 | 13 | [dependencies] 14 | thiserror = "1.0.37" 15 | ron = "0.8.0" 16 | 17 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 18 | 19 | [dependencies.bevy] 20 | version = "0.10" 21 | default-features = false 22 | features = [ "bevy_scene", "bevy_asset" ] 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Dual-licensed under either 2 | 3 | * MIT License (docs/LICENSE-MIT or http://opensource.org/licenses/MIT) 4 | * Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) 5 | 6 | at your option. 7 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Helpers for working with Bevy Scenes 2 | 3 | Version compatibility table: 4 | 5 | |Bevy Version|Crate Version| 6 | |------------|-------------| 7 | |`0.10` |`main` | 8 | |`0.9` |`0.2` | 9 | |`0.8` |`0.1` | 10 | 11 | ## What is this about? 12 | 13 | For the uninitiated: Bevy Scenes are a way to store some predefined Bevy ECS 14 | data (arbitrary entities with components on them) and be able to instantiate 15 | them later, as many times as you want! 16 | 17 | You can use Scenes for many use cases: 18 | - Loading your game levels/maps (or parts of them) 19 | - Preconfigured game units/modules (some other engines call this "prefabs") 20 | - Saving game state 21 | - … 22 | 23 | Creating Bevy scenes, and working with the Bevy scene format, can be difficult 24 | unapproachable. While Bevy makes it easy to use existing scenes in your game 25 | (just spawn them with [`DynamicSceneBundle`]), creating/exporting such data is 26 | something opinionated and Bevy's APIs might not be flexible enough for some use 27 | cases. 28 | 29 | The goal of this crate is to provide alternative APIs for creating Bevy scene 30 | files. Your scenes can include whatever you want, by exporting a custom 31 | selection of things from any Bevy app! 32 | 33 | ## Scene Export 34 | 35 | You can create Bevy [`DynamicScene`]s that include whatever exact selection 36 | of entities and components you want! 37 | 38 | The selections can be done with a syntax similar to Bevy Queries. 39 | 40 | This create will then copy the relevant data, based on your selections, 41 | from your `World`, and create a scene from it! 42 | 43 | There are two "modes" for component selection: 44 | - "all components": when you just select entities, without specifying components. 45 | When generating the scene, each entity will be scanned to autodetect 46 | all [compatible](#warning) components and include them in the scene 47 | - "explicit component list": you specify exactly what components to include 48 | (they may be required or optional), and only those will be exported 49 | ([incompatible types will be skipped](#warning)) 50 | 51 | ```rust 52 | // quick: make a scene with all entities that match a given query filter 53 | // (all components will be included) 54 | let my_scene = scene_from_query_filter::<( 55 | With, 56 | Without, 57 | )>(&mut world); 58 | 59 | // quick: same thing, but only with specific components 60 | let my_scene = scene_from_query_components::< 61 | // the components to include 62 | // (require A and B, only select entities that have them) 63 | // (C is optional, include it if it is present) 64 | (&ComponentA, &ComponentB, Option<&ComponentC>), 65 | // additional filter, to select only specific entities 66 | (With, Without), 67 | >(&mut world); 68 | ``` 69 | 70 | If you want more flexibility, you can use [`SceneBuilder`], which lets you 71 | accumulate multiple selections incrementally, and then create a scene with 72 | everything you added. The component selection can be controlled with 73 | per-entity granularity. 74 | 75 | ```rust 76 | let mut builder = SceneBuilder::new(&mut world); 77 | 78 | // include entities using query filter: 79 | // all entities with `GameItem` 80 | // all of their components will be included 81 | builder.add_from_query_filter::>(); 82 | 83 | // only specific components for these entities 84 | builder.add_with_components::< 85 | // the components to select 86 | (&Transform, &Health, &BaseStats, Option<&SpecialAbility>), 87 | // query filter to select entities 88 | Or<(With, With)> 89 | >(); 90 | 91 | // also add some special entities 92 | builder.add_entity(e); 93 | builder.add_entities(&[magic1, magic2, magic3]); 94 | builder.add_components_to_entities::< 95 | &Transform 96 | >(special_entities.iter()); 97 | 98 | // we can ignore some components; 99 | // they will never be implicitly included, unless they were 100 | // explicitly selected for specific entities 101 | builder.ignore_components::<(&GlobalTransform, &ComputedVisibility)>(); 102 | 103 | // now that we have selected everything, make a scene from it! 104 | let my_scene = builder.build_scene(); 105 | ``` 106 | 107 | ### Exporting to scene asset files 108 | 109 | The above examples will create a [`DynamicScene`] instance. However, if you 110 | are simply interested in creating asset files, there are convenience methods 111 | for exporting directly to a Bevy Scene RON Asset file: 112 | 113 | ```rust 114 | // the standalone (simple) functions: 115 | 116 | // like `scene_from_query_components`, but takes a file path 117 | scene_file_from_query_components::(world, "my_scene.scn.ron") 118 | .expect("Scene file output failed"); 119 | 120 | // like `scene_from_query_filter`, but takes a file path 121 | scene_file_from_query_filter::(world, "my_scene2.scn.ron") 122 | .expect("Scene file output failed"); 123 | 124 | // for `SceneBuilder`: 125 | let mut builder = SceneBuilder::new(world); 126 | // ... add stuff ... 127 | // instead of `.build_scene()`: 128 | builder.export_to_file("fancy_scene.scn.ron") 129 | .expect("Scene file output failed"); 130 | ``` 131 | 132 | All of the above methods also return the [`DynamicScene`] in the `Ok` result, 133 | if the export was successful, in case you also want to do anything else with 134 | the generated scene. 135 | 136 | If you prefer not to use the convenience file export methods, you can output 137 | to a scene asset file manually like this: 138 | 139 | ```rust 140 | // create the scene, using any of the methods shown before 141 | let my_scene = /* ... */; 142 | // need the type registry 143 | let type_registry = world.resource::(); 144 | // output the contents as a String 145 | let data = my_scene.serialize_ron(type_registry) 146 | .expect("Scene serialization failed"); 147 | // create a scene file (ending in `.scn.ron`) 148 | std::fs::write("file.scn.ron", &data) 149 | .expect("Writing to file failed"); 150 | ``` 151 | 152 | ### Directly using a generated scene 153 | 154 | If you want to generate a scene and use it straight away, without 155 | exporting/loading asset files, here is how. 156 | 157 | To use the generated scene in your app, it needs to be added to the app's 158 | assets (the `Assets` resource), to get a handle. 159 | 160 | There are convenience methods to do this for you, which return 161 | `Handle` instead of the bare `DynamicScene`. 162 | 163 | ```rust 164 | // the standalone (simple) functions: 165 | 166 | // like `scene_from_query_components`, but adds it to the app for you 167 | let handle = add_scene_from_query_components::(world); 168 | 169 | // like `scene_from_query_filter`, but adds it to the app for you 170 | let handle = add_scene_from_query_filter::(world); 171 | 172 | // for `SceneBuilder`: 173 | let mut builder = SceneBuilder::new(world); 174 | // … add stuff … 175 | // instead of `.build_scene()`: 176 | let handle = builder.build_scene_and_add(); 177 | ``` 178 | 179 | If you want to do it manually without the helper functions: 180 | 181 | ```rust 182 | // get the `Assets` resource: 183 | // (if we are in an exclusive system) 184 | let mut assets = world.resource_mut::>(); 185 | // (in a regular system, you can use `ResMut>`) 186 | 187 | // add it 188 | let handle = assets.add(my_scene); 189 | ``` 190 | 191 | Later, you can spawn your scene from anywhere. 192 | 193 | From a regular system: 194 | 195 | ```rust 196 | commands.spawn_bundle(DynamicSceneBundle { 197 | scene: handle, 198 | ..default() 199 | }); 200 | ``` 201 | 202 | With direct World access: 203 | 204 | ```rust 205 | world.spawn().insert_bundle(DynamicSceneBundle { 206 | scene: handle, 207 | ..default() 208 | }); 209 | ``` 210 | 211 | ### Warning 212 | 213 | **Warning!** You *must* ensure that your component types: 214 | - impl `Reflect` 215 | - reflect `Component` 216 | - are registered in the type registry 217 | 218 | Otherwise, they will be silently ignored, and will be missing from your scene! 219 | 220 | If you are serializing your scenes to asset files, you probably also want 221 | `FromReflect`, or otherwise you will not be able to load your scenes later! 222 | 223 | ```rust 224 | #[derive(Component, Default, Reflect, FromReflect)] 225 | #[reflect(Component)] 226 | struct MyComponent; 227 | ``` 228 | 229 | (note: Bevy requires either a `FromWorld` or a `Default` impl, to derive `Reflect`) 230 | 231 | ```rust 232 | app.register_type::(); 233 | ``` 234 | 235 | This is required boilerplate, for all components that you want to use 236 | with scenes! Otherwise, things will silently not work. 237 | 238 | ## "Blueprints" Pattern 239 | 240 | This is a recommendation for how to make your workflow more flexible, and 241 | get the most usefulness out of Bevy scenes. 242 | 243 | --- 244 | 245 | There are many component types in Bevy that represent internal state 246 | computed at runtime, such as: `GlobalTransform`, `ComputedVisibility`, 247 | `Interaction`, etc…. 248 | 249 | Their values don't need to be persisted in scenes. You might want to omit 250 | them. This will also help your scenes be less bloated. 251 | 252 | You might also want to omit other components of your choice, if you prefer 253 | to set them up using code, or initialize them to defaults. 254 | 255 | ```rust 256 | let mut builder = SceneBuilder::new(world); 257 | 258 | // add our game entities 259 | builder.add_from_query_filter::>(); 260 | builder.add_from_query_filter::>(); 261 | builder.add_from_query_filter::>(); 262 | // … 263 | 264 | // for our UI Nodes, only persist hierarchy + `Style`, `UiColor`, `Text`, `Button` 265 | builder.add_with_components::< 266 | ( 267 | (Option<&Parent>, Option<&Children>), 268 | (&Style, &UiColor, Option<&Text>, Option<&Button>), 269 | ), 270 | With 271 | >(); 272 | 273 | // never include these components in any entity 274 | builder.ignore_components::< 275 | (&GlobalTransform, &Visibility, &ComputedVisibility, &CalculatedSize) 276 | >(); 277 | 278 | let my_scene = builder.build_scene(); 279 | ``` 280 | 281 | --- 282 | 283 | If you are creating such a "sparse" scene (we can call it "blueprint"), 284 | that only has some of the components and is missing others, you can write 285 | some code to populate the entities to "complete" their setup. 286 | 287 | This is easily done using a system with an `Added` query filter. This way, 288 | you detect when such entities are spawned into the world, and you can do 289 | any additional setup on them using code. 290 | 291 | ```rust 292 | // ensure everything with a transform has all the transform/visibility stuff 293 | fn setup_spatial( 294 | mut commands: Commands, 295 | // detect anything that was just added and needs setup 296 | q_new: Query< 297 | (Entity, &Transform), 298 | (Added, Without) 299 | >, 300 | ) { 301 | for (e, transform) in q_new.iter() { 302 | commands.entity(e).insert_bundle(SpatialBundle { 303 | // preserve the transform 304 | transform, 305 | ..Default::default() 306 | }); 307 | } 308 | } 309 | 310 | /// complete the setup of our UI 311 | /// (btw, this could be the starting point for the development 312 | /// of a nice automatic theming system ;) hehe) 313 | fn setup_ui( 314 | mut commands: Commands, 315 | // detect anything that was just added and needs setup 316 | q_new: Query< 317 | (Entity, &Style, Option<&UiColor>, Option<&Text>, Option<&Button>), 318 | (Added