├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bevy_mod_check_filter_macros ├── Cargo.toml ├── README.md └── src │ └── lib.rs ├── examples └── enum-derive.rs └── src ├── impls.rs └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_mod_check_filter" 3 | version = "0.3.0" 4 | edition = "2021" 5 | categories = ["game-engines"] 6 | description = "A module for improved ergonomics with Enabled-style marker components." 7 | keywords = ["bevy", "query", "filter", "component"] 8 | license = "MIT OR Apache-2.0" 9 | readme = "README.md" 10 | repository = "https://github.com/ItsDoot/bevy_mod_check_filter" 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [workspace] 15 | members = ["bevy_mod_check_filter_macros"] 16 | 17 | [dependencies] 18 | bevy_ecs = "0.8" 19 | bevy_ptr = "0.8" 20 | bevy_mod_check_filter_macros = { path = "./bevy_mod_check_filter_macros", version = "0.3.0" } 21 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bevy_mod_check_filter 2 | 3 | A query filter to allow `Enabled`-style marker components without losing the 4 | ergonomics of `ZST`-style marker component filtering! 5 | 6 | ## Example 7 | 8 | Without `bevy_mod_check_filter`: 9 | 10 | ```rust 11 | #[derive(Component)] 12 | struct Poisoned; 13 | 14 | #[derive(Component)] 15 | struct Name { name: &'static str } 16 | 17 | fn all_poisoned(entities: Query<&Name, With>) { 18 | // ... 19 | } 20 | ``` 21 | 22 | With `bevy_mod_check_filter`: 23 | 24 | ```rust 25 | #[derive(Component)] 26 | struct Poisoned(pub bool); 27 | 28 | impl std::ops::Deref for Poisoned { 29 | type Target = bool; 30 | 31 | fn deref(&self) -> &Self::Target { 32 | &self.0 33 | } 34 | } 35 | 36 | #[derive(Component)] 37 | struct Name { name: &'static str } 38 | 39 | fn all_poisoned(entities: Query<&Name, Check>>) { 40 | // ... 41 | } 42 | 43 | // OR with one of the provided type aliases: 44 | fn find_poisoned(entities: Query<&Name, IsTrue>) { 45 | // ... 46 | } 47 | ``` 48 | 49 | ## License 50 | 51 | All code in this repository is dual-licensed under either: 52 | 53 | - MIT License (LICENSE-MIT file or http://opensource.org/licenses/MIT) 54 | - Apache License, Version 2.0 (LICENSE-APACHE file or 55 | http://www.apache.org/licenses/LICENSE-2.0) 56 | -------------------------------------------------------------------------------- /bevy_mod_check_filter_macros/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_mod_check_filter_macros" 3 | version = "0.3.0" 4 | edition = "2021" 5 | categories = ["game-engines"] 6 | description = "A module for improved ergonomics with Enabled-style marker components." 7 | keywords = ["bevy", "query", "filter", "component"] 8 | license = "MIT OR Apache-2.0" 9 | readme = "README.md" 10 | repository = "https://github.com/ItsDoot/bevy_mod_check_filter" 11 | 12 | [lib] 13 | proc-macro = true 14 | 15 | [dependencies] 16 | syn = {version = "1.0", features = ["extra-traits"]} 17 | quote = "1.0" 18 | proc-macro2 = "1.0" 19 | -------------------------------------------------------------------------------- /bevy_mod_check_filter_macros/README.md: -------------------------------------------------------------------------------- 1 | # bevy_mod_check_filter_macros 2 | 3 | Macros for the [bevy_mod_check_filter](https://crates.io/bevy_mod_check_filter) 4 | crate. 5 | -------------------------------------------------------------------------------- /bevy_mod_check_filter_macros/src/lib.rs: -------------------------------------------------------------------------------- 1 | use proc_macro2::TokenStream; 2 | use quote::{quote, ToTokens}; 3 | use syn::{parse_macro_input, DeriveInput, Ident}; 4 | 5 | #[proc_macro_derive(IsVariant)] 6 | pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { 7 | // Parse the input tokens into a syntax tree 8 | let input = parse_macro_input!(input as DeriveInput); 9 | 10 | let enum_name = input.ident; 11 | let vis = input.vis.to_token_stream(); 12 | 13 | let expanded: TokenStream = if let syn::Data::Enum(e) = input.data { 14 | e.variants 15 | .into_iter() 16 | .map(|v| { 17 | let ident = v.ident; 18 | let name = Ident::new(&format!("Is{ident}"), ident.span()); 19 | let m = match v.fields { 20 | syn::Fields::Unit => quote! { #enum_name::#ident }, 21 | _ => quote! { #enum_name::#ident { .. } }, 22 | }; 23 | 24 | quote! { 25 | #vis struct #name; 26 | 27 | impl bevy_mod_check_filter::Predicate<#enum_name> for #name { 28 | fn test(test: &#enum_name) -> bool { 29 | match *test { 30 | #m => true, 31 | _ => false, 32 | } 33 | } 34 | } 35 | } 36 | }) 37 | .collect() 38 | } else { 39 | panic!("IsVariant derive only works on Enums"); 40 | }; 41 | 42 | // Hand the output tokens back to the compiler 43 | proc_macro::TokenStream::from(expanded) 44 | } 45 | -------------------------------------------------------------------------------- /examples/enum-derive.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | 3 | use bevy_ecs::prelude::*; 4 | use bevy_mod_check_filter::*; 5 | 6 | /// IsVariant will generate three predicates: `IsWalking`, `IsRunning`, and `IsFlying` 7 | #[derive(Component, IsVariant)] 8 | enum EnemyState { 9 | Walking, 10 | Running(bool, f32), 11 | Flying { max_height: f32 }, 12 | } 13 | 14 | /// works with the enum as a component 15 | fn walking_enemies(_entities: Query>) { 16 | // ... 17 | } 18 | 19 | pub fn main() {} 20 | -------------------------------------------------------------------------------- /src/impls.rs: -------------------------------------------------------------------------------- 1 | use std::{cell::UnsafeCell, marker::PhantomData}; 2 | 3 | use bevy_ecs::{ 4 | archetype::{Archetype, ArchetypeComponentId}, 5 | component::{Component, ComponentId, ComponentStorage, StorageType}, 6 | entity::Entity, 7 | query::{ 8 | Access, Fetch, FetchState, FilteredAccess, QueryItem, ReadOnlyWorldQuery, WorldQuery, 9 | WorldQueryGats, 10 | }, 11 | storage::{ComponentSparseSet, Table, Tables}, 12 | world::World, 13 | }; 14 | use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref}; 15 | 16 | use crate::{Check, Predicate}; 17 | 18 | // SAFETY: `ROQueryFetch` is the same as `QueryFetch` 19 | unsafe impl> WorldQuery for Check { 20 | type ReadOnly = Self; 21 | 22 | type State = CheckState; 23 | 24 | fn shrink<'wlong: 'wshort, 'wshort>(item: QueryItem<'wlong, Self>) -> QueryItem<'wshort, Self> { 25 | item 26 | } 27 | } 28 | 29 | impl<'w, T: Component, Pred: Predicate> WorldQueryGats<'w> for Check { 30 | type Fetch = CheckFetch<'w, T, Pred>; 31 | type _State = CheckState; 32 | } 33 | 34 | // SAFETY: read-only access 35 | unsafe impl> ReadOnlyWorldQuery for Check {} 36 | 37 | /// The [`FetchState`] of [`Equals`]. 38 | pub struct CheckState { 39 | component_id: ComponentId, 40 | marker: PhantomData, 41 | } 42 | 43 | impl FetchState for CheckState { 44 | fn init(world: &mut World) -> Self { 45 | Self { 46 | component_id: world.init_component::(), 47 | marker: PhantomData, 48 | } 49 | } 50 | 51 | fn matches_component_set(&self, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool { 52 | set_contains_id(self.component_id) 53 | } 54 | } 55 | 56 | /// The [`Fetch`] of [`Equals`]. 57 | pub struct CheckFetch<'w, T, Pred> { 58 | pred_marker: PhantomData, 59 | // T::Storage = TableStorage 60 | table_components: Option>>, 61 | entity_table_rows: Option>, 62 | // T::Storage = SparseStorage 63 | entities: Option>, 64 | sparse_set: Option<&'w ComponentSparseSet>, 65 | } 66 | 67 | impl Clone for CheckFetch<'_, T, Pred> { 68 | fn clone(&self) -> Self { 69 | Self { 70 | pred_marker: PhantomData, 71 | table_components: self.table_components, 72 | entity_table_rows: self.entity_table_rows, 73 | entities: self.entities, 74 | sparse_set: self.sparse_set, 75 | } 76 | } 77 | } 78 | 79 | // SAFETY: this reads the T component. archetype component access and component access are updated to reflect that 80 | unsafe impl<'w, T: Component, Pred: Predicate> Fetch<'w> for CheckFetch<'w, T, Pred> { 81 | type Item = bool; 82 | type State = CheckState; 83 | 84 | unsafe fn init( 85 | world: &'w World, 86 | state: &Self::State, 87 | _last_change_tick: u32, 88 | _change_tick: u32, 89 | ) -> Self { 90 | Self { 91 | pred_marker: PhantomData, 92 | table_components: None, 93 | entity_table_rows: None, 94 | entities: None, 95 | sparse_set: (T::Storage::STORAGE_TYPE == StorageType::SparseSet).then(|| { 96 | world 97 | .storages() 98 | .sparse_sets 99 | .get(state.component_id) 100 | .unwrap() 101 | }), 102 | } 103 | } 104 | 105 | const IS_DENSE: bool = { 106 | match T::Storage::STORAGE_TYPE { 107 | StorageType::Table => true, 108 | StorageType::SparseSet => false, 109 | } 110 | }; 111 | 112 | const IS_ARCHETYPAL: bool = true; 113 | 114 | unsafe fn set_archetype( 115 | &mut self, 116 | state: &Self::State, 117 | archetype: &'w Archetype, 118 | tables: &'w Tables, 119 | ) { 120 | match T::Storage::STORAGE_TYPE { 121 | StorageType::Table => { 122 | self.entity_table_rows = Some(archetype.entity_table_rows().into()); 123 | let column = tables[archetype.table_id()] 124 | .get_column(state.component_id) 125 | .unwrap(); 126 | self.table_components = Some(column.get_data_slice().into()); 127 | } 128 | StorageType::SparseSet => self.entities = Some(archetype.entities().into()), 129 | } 130 | } 131 | 132 | unsafe fn set_table(&mut self, state: &Self::State, table: &'w Table) { 133 | self.table_components = Some( 134 | table 135 | .get_column(state.component_id) 136 | .unwrap() 137 | .get_data_slice() 138 | .into(), 139 | ); 140 | } 141 | 142 | unsafe fn archetype_fetch(&mut self, archetype_index: usize) -> Self::Item { 143 | let item = match T::Storage::STORAGE_TYPE { 144 | StorageType::Table => { 145 | let (entity_table_rows, table_components) = self 146 | .entity_table_rows 147 | .zip(self.table_components) 148 | .unwrap_or_else(|| debug_checked_unreachable()); 149 | let table_row = *entity_table_rows.get(archetype_index); 150 | table_components.get(table_row).deref() 151 | } 152 | StorageType::SparseSet => { 153 | let (entities, sparse_set) = self 154 | .entities 155 | .zip(self.sparse_set) 156 | .unwrap_or_else(|| debug_checked_unreachable()); 157 | let entity = *entities.get(archetype_index); 158 | sparse_set 159 | .get(entity) 160 | .unwrap_or_else(|| debug_checked_unreachable()) 161 | .deref::() 162 | } 163 | }; 164 | Pred::test(item) 165 | } 166 | 167 | unsafe fn table_fetch(&mut self, table_row: usize) -> Self::Item { 168 | let components = self 169 | .table_components 170 | .unwrap_or_else(|| debug_checked_unreachable()); 171 | let item = components.get(table_row).deref(); 172 | Pred::test(item) 173 | } 174 | 175 | unsafe fn archetype_filter_fetch(&mut self, archetype_index: usize) -> bool { 176 | self.archetype_fetch(archetype_index) 177 | } 178 | 179 | unsafe fn table_filter_fetch(&mut self, table_row: usize) -> bool { 180 | self.table_fetch(table_row) 181 | } 182 | 183 | fn update_component_access(state: &Self::State, access: &mut FilteredAccess) { 184 | assert!( 185 | !access.access().has_write(state.component_id), 186 | "Equals<{}, _> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", 187 | std::any::type_name::(), 188 | ); 189 | access.add_read(state.component_id); 190 | } 191 | 192 | fn update_archetype_component_access( 193 | state: &Self::State, 194 | archetype: &Archetype, 195 | access: &mut Access, 196 | ) { 197 | if let Some(archetype_component_id) = 198 | archetype.get_archetype_component_id(state.component_id) 199 | { 200 | access.add_read(archetype_component_id); 201 | } 202 | } 203 | } 204 | 205 | unsafe fn debug_checked_unreachable() -> ! { 206 | #[cfg(debug_assertions)] 207 | unreachable!(); 208 | #[cfg(not(debug_assertions))] 209 | std::hint::unreachable_unchecked(); 210 | } 211 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! [Component]: bevy_ecs::component::Component 2 | //! [Query]: bevy_ecs::system::Query 3 | //! [Check]: crate::Check 4 | //! [Is]: crate::Is 5 | //! [IsTrue]: crate::IsTrue 6 | #![doc = include_str!("../README.md")] 7 | 8 | use std::{marker::PhantomData, ops::Deref}; 9 | 10 | use bevy_ecs::component::Component; 11 | 12 | pub use bevy_mod_check_filter_macros::IsVariant; 13 | 14 | mod impls; 15 | 16 | /// Filter that selects entities with a component `T`, if the given [`Predicate`] is satisfied. 17 | /// 18 | /// This can be used in a [`Query`](bevy_ecs::system::Query) if entities with the component `T` 19 | /// must satisfy an arbitrary condition. 20 | /// 21 | /// # Examples 22 | /// 23 | /// ``` 24 | /// # use bevy_ecs::component::Component; 25 | /// # use bevy_ecs::system::IntoSystem; 26 | /// # use bevy_ecs::system::Query; 27 | /// # use bevy_mod_check_filter::Check; 28 | /// # use bevy_mod_check_filter::Is; 29 | /// # use bevy_mod_check_filter::IsTrue; 30 | /// 31 | /// #[derive(Component)] 32 | /// struct Poisoned(bool); 33 | /// 34 | /// impl std::ops::Deref for Poisoned { 35 | /// type Target = bool; 36 | /// 37 | /// fn deref(&self) -> &Self::Target { 38 | /// &self.0 39 | /// } 40 | /// } 41 | /// 42 | /// # #[derive(Component)] 43 | /// # struct Name { name: &'static str }; 44 | /// 45 | /// fn find_all_poisoned(query: Query<&Name, Check>>) { 46 | /// for name in &query { 47 | /// println!("{} is poisoned!", name.name); 48 | /// } 49 | /// } 50 | /// # bevy_ecs::system::assert_is_system(find_all_poisoned); 51 | /// 52 | /// // With type alias: 53 | /// fn all_poisoned(query: Query<&Name, IsTrue>) { 54 | /// for name in &query { 55 | /// println!("{} is poisoned!", name.name); 56 | /// } 57 | /// } 58 | /// # bevy_ecs::system::assert_is_system(all_poisoned); 59 | /// ``` 60 | pub struct Check>(PhantomData, PhantomData); 61 | 62 | /// A trait for implementing versatile pre-filtering of [`Component`]s. 63 | pub trait Predicate { 64 | /// Checks if the given value is acceptable. 65 | fn test(test: &T) -> bool; 66 | } 67 | 68 | /// The negation of [`Check`]. 69 | /// 70 | /// See [`Check`] for an example of non-negation. 71 | pub type CheckNot = Check>; 72 | 73 | /// A [`Predicate`] that returns the negation of the given predicate. 74 | /// 75 | /// Use [`CheckNot`] when you need negation. 76 | pub struct Not>(PhantomData<(T, P)>); 77 | 78 | impl> Predicate for Not { 79 | fn test(test: &T) -> bool { 80 | !P::test(test) 81 | } 82 | } 83 | 84 | /// Query filter for checking if the component `T` is coercable as `true`. 85 | /// 86 | /// See [`Check`] for example usage. 87 | pub type IsTrue = Check>; 88 | 89 | /// Query filter for checking if the component `T` is coercable as `false`. 90 | /// 91 | /// See [`Check`] for example usage of its negation, [`IsTrue`]. 92 | pub type IsFalse = Check>; 93 | 94 | /// A [`Predicate`] that checks if the provided `T`, coerced into a `bool`, equals the given `VALUE`. 95 | /// 96 | /// This predicate is used as part of [`IsTrue`] and [`IsFalse`]. 97 | pub struct Is; 98 | 99 | impl Predicate for Is 100 | where 101 | T: Deref, 102 | { 103 | fn test(test: &T) -> bool { 104 | **test == VALUE 105 | } 106 | } 107 | --------------------------------------------------------------------------------