# Objective Currently, a query iterator can be collected into a `Vec` and sorted, but this can be quite unwieldy, especially when many `Component`s are involved. The `itertools` crate helps somewhat, but the need to write a closure over all of `QueryData` can sometimes hurt ergonomics, anywhere from slightly to strongly. A key extraction function only partially helps, as `sort_by_key` does not allow returning non-`Copy` data. `sort_by` does not suffer from the `Copy` restriction, but now the user has to write out a `cmp` function over two `QueryData::Item`s when it could have just been handled by the `Ord` impl for the key. `sort` requires the entire `Iterator` Item to be `Ord`, which is rarely usable without manual helper functionality. If the user wants to hide away unused components with a `..` range, they need to track item tuple order across their function. Mutable `QueryData` can also introduce further complexity. Additionally, sometimes users solely include `Component`s /`Entity` to guarantee iteration order. For a user to write a function to abstract away repeated sorts over various `QueryData` types they use would require reaching for the `all_tuples!` macro, and continue tracking tuple order afterwards. Fixes https://github.com/bevyengine/bevy/issues/1470. ## Solution Custom sort methods on `QueryIter`, which take a query lens as a generic argument, like `transmute_lens` in `Query`. This allows users to choose what part of their queries they pass to their sort function calls, serving as a kind of "key extraction function" before the sort call. F.e. allowing users to implement `Ord` for a Component, then call `query.iter().sort::<OrdComponent>()` This works independent of mutability in `QueryData`, `QueryData` tuple order, or the underlying `iter/iter_mut` call. Non-`Copy` components could also be used this way, an internal `Arc<usize>` being an example. If `Ord` impls on components do not suffice, other sort methods can be used. Notably useful when combined with `EntityRef` or `EntityMut`. Another boon from using underlying `transmute` functionality, is that with the [allowed transmutes](http://dev-docs.bevyengine.org/bevy/ecs/prelude/struct.Query.html#allowed-transmutes), it is possible to sort a `Query` with `Entity` even if it wasn't included in the original `Query`. The additional generic parameter on the methods other than `sort` and `sort_unstable` currently cannot be removed due to Rust limitations, however their types can be inferred. The new methods do not conflict with the `itertools` sort methods, as those use the "sorted" prefix. This is implemented barely touching existing code. That change to existing code being that `QueryIter` now holds on to the reference to `UnsafeWorldCell` that is used to initialize it. A lens query is constructed with `Entity` attached at the end, sorted, and turned into an iterator. The iterator maps away the lens query, leaving only an iterator of `Entity`, which is used by `QuerySortedIter` to retrieve the actual items. `QuerySortedIter` resembles a combination of `QueryManyIter` and `QueryIter`, but it uses an entity list that is guaranteed to contain unique entities, and implements `ExactSizeIterator`, `DoubleEndedIterator`, `FusedIterator` regardless of mutability or filter kind (archetypal/non-archetypal). The sort methods are not allowed to be called after `next`, and will panic otherwise. This is checked using `QueryIterationCursor` state, which is unique on initialization. Empty queries are an exception to this, as they do not return any item in the first place. That is because tracking how many iterations have already passed would require regressing either normal query iteration a slight bit, or sorted iteration by a lot. Besides, that would not be the intended use of these methods. ## Testing To ensure that `next` being called before `sort` results in a panic, I added some tests. I also test that empty `QueryIter`s do not exhibit this restriction. The query sorts test checks for equivalence to the underlying sorts. This change requires that `Query<(Entity, Entity)>` remains legal, if that is not already guaranteed, which is also ensured by the aforementioned test. ## Next Steps Implement the set of sort methods for `QueryManyIter` as well. - This will mostly work the same, other than needing to return a new `QuerySortedManyIter` to account for iteration over lists of entities that are not guaranteed to be unique. This new query iterator will need a bit of internal restructuring to allow for double-ended mutable iteration, while not regressing read-only iteration. The implementations for each pair of - `sort`, `sort_unstable`, - `sort_by`, sort_unstable_by, - `sort_by_key,` `sort_by_cached_key` are the same aside from the panic message and the sort call, so they could be merged with an inner function. That would require the use of higher-ranked trait bounds on `WorldQuery::Item<'1>`, and is unclear to me whether it is currently doable. Iteration in QuerySortedIter might have space for improvement. When sorting by `Entity`, an `(Entity, Entity)` lens `QueryData` is constructed, is that worth remedying? When table sorts are implemented, a fast path could be introduced to these sort methods. ## Future Possibilities Implementing `Ord` for EntityLocation might be useful. Some papercuts in ergonomics can be improved by future Rust features: - The additional generic parameter aside from the query lens can be removed once this feature is stable: `Fn -> impl Trait` (`impl Trait` in `Fn` trait return position) - With type parameter defaults, the query lens generic can be defaulted to `QueryData::Item`, allowing the sort methods to look and behave like `slice::sort` when no query lens is specified. - With TAIT, the iterator generic on `QuerySortedIter` and thus the huge visible `impl Iterator` type in the sort function signatures can be removed. - With specialization, the bound on `L` could be relaxed to `QueryData` when the underlying iterator is mutable. ## Changelog Added `sort`, `sort_unstable`, `sort_by`, `sort_unstable_by`, `sort_by_key`, `sort_by_cached_key` to `QueryIter`. |
||
|---|---|---|
| .cargo | ||
| .github | ||
| assets | ||
| benches | ||
| crates | ||
| docs | ||
| docs-template | ||
| errors | ||
| examples | ||
| src | ||
| tests | ||
| tools | ||
| .gitattributes | ||
| .gitignore | ||
| Cargo.toml | ||
| CHANGELOG.md | ||
| clippy.toml | ||
| CODE_OF_CONDUCT.md | ||
| CONTRIBUTING.md | ||
| CREDITS.md | ||
| deny.toml | ||
| LICENSE-APACHE | ||
| LICENSE-MIT | ||
| README.md | ||
| rustfmt.toml | ||
| typos.toml | ||
What is Bevy?
Bevy is a refreshingly simple data-driven game engine built in Rust. It is free and open-source forever!
WARNING
Bevy is still in the early stages of development. Important features are missing. Documentation is sparse. A new version of Bevy containing breaking changes to the API is released approximately once every 3 months. We provide migration guides, but we can't guarantee migrations will always be easy. Use only if you are willing to work in this environment.
MSRV: Bevy relies heavily on improvements in the Rust language and compiler. As a result, the Minimum Supported Rust Version (MSRV) is generally close to "the latest stable release" of Rust.
Design Goals
- Capable: Offer a complete 2D and 3D feature set
- Simple: Easy for newbies to pick up, but infinitely flexible for power users
- Data Focused: Data-oriented architecture using the Entity Component System paradigm
- Modular: Use only what you need. Replace what you don't like
- Fast: App logic should run quickly, and when possible, in parallel
- Productive: Changes should compile quickly ... waiting isn't fun
About
- Features: A quick overview of Bevy's features.
- News: A development blog that covers our progress, plans and shiny new features.
Docs
- Quick Start Guide: Bevy's official Quick Start Guide. The best place to start learning Bevy.
- Bevy Rust API Docs: Bevy's Rust API docs, which are automatically generated from the doc comments in this repo.
- Official Examples: Bevy's dedicated, runnable examples, which are great for digging into specific concepts.
- Community-Made Learning Resources: More tutorials, documentation, and examples made by the Bevy community.
Community
Before contributing or participating in discussions with the community, you should familiarize yourself with our Code of Conduct.
- Discord: Bevy's official discord server.
- Reddit: Bevy's official subreddit.
- GitHub Discussions: The best place for questions about Bevy, answered right here!
- Bevy Assets: A collection of awesome Bevy projects, tools, plugins and learning materials.
Contributing
If you'd like to help build Bevy, check out the Contributor's Guide. For simple problems, feel free to open an issue or PR and tackle it yourself!
For more complex architecture decisions and experimental mad science, please open an RFC (Request For Comments) so we can brainstorm together effectively!
Getting Started
We recommend checking out the Quick Start Guide for a brief introduction.
Follow the Setup guide to ensure your development environment is set up correctly. Once set up, you can quickly try out the examples by cloning this repo and running the following commands:
# Switch to the correct version (latest release, default is main development branch)
git checkout latest
# Runs the "breakout" example
cargo run --example breakout
To draw a window with standard functionality enabled, use:
use bevy::prelude::*;
fn main(){
App::new()
.add_plugins(DefaultPlugins)
.run();
}
Fast Compiles
Bevy can be built just fine using default configuration on stable Rust. However for really fast iterative compiles, you should enable the "fast compiles" setup by following the instructions here.
Bevy Cargo Features
This list outlines the different cargo features supported by Bevy. These allow you to customize the Bevy feature set for your use-case.
Thanks
Bevy is the result of the hard work of many people. A huge thanks to all Bevy contributors, the many open source projects that have come before us, the Rust gamedev ecosystem, and the many libraries we build on.
A huge thanks to Bevy's generous sponsors. Bevy will always be free and open source, but it isn't free to make. Please consider sponsoring our work if you like what we're building.
This project is tested with BrowserStack.
License
Bevy is free, open source and permissively licensed! Except where noted (below and/or in individual files), all code in this repository is dual-licensed under either:
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
at your option. This means you can select the license you prefer! This dual-licensing approach is the de-facto standard in the Rust ecosystem and there are very good reasons to include both.
Some of the engine's code carries additional copyright notices and license terms due to their external origins.
These are generally BSD-like, but exact details vary by crate:
If the README of a crate contains a 'License' header (or similar), the additional copyright notices and license terms applicable to that crate will be listed.
The above licensing requirement still applies to contributions to those crates, and sections of those crates will carry those license terms.
The license field of each crate will also reflect this.
For example, bevy_mikktspace has code under the Zlib license (as well as a copyright notice when choosing the MIT license).
The assets included in this repository (for our examples) typically fall under different open licenses. These will not be included in your game (unless copied in by you), and they are not distributed in the published bevy crates. See CREDITS.md for the details of the licenses of those files.
Your contributions
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.