1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
#![doc = include_str!("../README.md")]
use bevy_ecs::{prelude::*, query::QueryFilter};
pub mod prelude {
pub use crate::{kind, Kind, WithKind};
pub use crate::{GetInstanceCommands, InstanceCommands};
pub use crate::{Instance, InstanceMut, InstanceRef};
pub use crate::{KindBundle, SpawnInstance, SpawnInstanceWorld};
}
/// A type which represents the kind of an [`Entity`].
///
/// An entity is of kind `T` if it matches [`Query<Entity, <T as Kind>::Filter>`][`Query`].
///
/// By default, an entity with a [`Component`] of type `T` is also of kind `T`.
///
/// # Examples
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_kind::prelude::*;
///
/// #[derive(Component)]
/// struct Apple;
///
/// #[derive(Component)]
/// struct Orange;
///
/// struct Fruit;
///
/// impl Kind for Fruit {
/// type Filter = Or<(With<Apple>, With<Orange>)>;
/// }
///
/// fn fruits(query: Query<Instance<Fruit>>) {
/// for fruit in query.iter() {
/// println!("{fruit:?} is a fruit!");
/// }
/// }
///
/// # bevy_ecs::system::assert_is_system(fruits);
/// ```
pub trait Kind: 'static + Send + Sized + Sync {
type Filter: QueryFilter;
/// Returns the debug name of this kind.
///
/// By default, this is the short type name (without path) of this kind.
fn debug_name() -> String {
bevy_utils::get_short_name(std::any::type_name::<Self>())
}
}
impl<T: Component> Kind for T {
type Filter = With<T>;
}
/// Represents the kind of any [`Entity`].
///
/// See [`Instance<Any>`] for more information on usage.
pub struct Any;
impl Kind for Any {
type Filter = ();
}
mod instance;
pub use instance::*;
/// A trait which allows safe casting from one [`Kind`] to another.
///
/// # Usage
/// Prefer to use the [`kind`] macro to implement this trait.
pub trait CastInto<T: Kind>: Kind {
fn cast_into(instance: Instance<Self>) -> Instance<T>;
}
impl<T: Kind> CastInto<T> for T {
fn cast_into(instance: Instance<Self>) -> Instance<Self> {
instance
}
}
/// A macro to safely implement [`CastInto`] for a pair of related [`Kind`]s.
///
/// See [`CastInto`] for more information.
#[macro_export]
#[deprecated]
macro_rules! safe_cast {
($T:ty => $U:ty) => {
impl $crate::CastInto<$U> for $T {
fn cast_into(instance: $crate::Instance<Self>) -> $crate::Instance<$U> {
// SAFE: Because we said so!
unsafe { instance.cast_into_unchecked() }
}
}
};
}
/// A macro to safely implement [`CastInto`] for a pair of related [`Kind`]s.
///
/// See [`CastInto`] for more information.
///
/// # Usage
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_kind::prelude::*;
///
/// struct Fruit;
///
/// impl Kind for Fruit {
/// type Filter = With<Apple>;
/// }
///
/// #[derive(Component)]
/// struct Apple;
///
/// // We can guarantee all entities with an `Apple` component are of kind `Fruit`:
/// kind!(Apple is Fruit);
///
/// fn eat_apple(apple: Instance<Apple>) {
/// println!("Crunch!");
/// // SAFE: Because we said so.
/// eat_fruit(apple.cast_into());
/// }
///
/// fn eat_fruit(fruit: Instance<Fruit>) {
/// println!("Yum!");
/// }
/// ```
#[macro_export]
macro_rules! kind {
($T:ident is $U:ty) => {
impl $crate::CastInto<$U> for $T {
fn cast_into(instance: $crate::Instance<Self>) -> $crate::Instance<$U> {
// SAFE: Because we said so!
unsafe { instance.cast_into_unchecked() }
}
}
};
}
/// A short alias for using a [`Kind`] as a [`QueryFilter`].
///
/// # Example
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_kind::prelude::*;
///
/// #[derive(Component)]
/// struct Apple;
///
/// fn count_apples(query: Query<(), WithKind<Apple>>) -> usize {
/// query.iter().count()
/// }
///
/// # bevy_ecs::system::assert_is_system(count_apples);
/// ```
pub type WithKind<T> = <T as Kind>::Filter;
/// A [`Bundle`] which represents a [`Kind`].
///
/// # Usage
/// This trait is used to allow spawning an [`Instance<T>`] where `T` is [`<Self as KindBundle>::Kind`][`KindBundle::Kind`].
///
/// Any [`Component`] is automatically a kind bundle of its own kind.
///
/// See [`SpawnInstance`] for more information.
pub trait KindBundle: Bundle {
/// The [`Kind`] represented by this [`Bundle`].
type Kind: Kind;
}
impl<T: Component> KindBundle for T {
type Kind = T;
}
/// Extension trait to safely spawn an [`Instance<T>`] using [`Commands`] where `T` associated with a [`KindBundle`].
pub trait SpawnInstance {
/// Spawns a new [`Instance<T>`] using its associated [`KindBundle`].
///
/// # Example
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_kind::prelude::*;
///
/// #[derive(Component)]
/// struct Apple;
///
/// fn spawn_apple(mut commands: Commands) {
/// let apple: Instance<Apple> = commands.spawn_instance(Apple).instance();
/// println!("Spawned {apple:?}!");
/// }
///
/// # bevy_ecs::system::assert_is_system(spawn_apple);
fn spawn_instance<T: KindBundle>(&mut self, _: T) -> InstanceCommands<'_, T::Kind>;
}
impl SpawnInstance for Commands<'_, '_> {
fn spawn_instance<T: KindBundle>(&mut self, bundle: T) -> InstanceCommands<'_, T::Kind> {
let entity = self.spawn(bundle).id();
// SAFE: `entity` must be a valid instance of `T::Kind`.
unsafe { InstanceCommands::from_entity_unchecked(self.entity(entity)) }
}
}
/// Extension trait to safely spawn an [`Instance<T>`] using [`World`] where `T` associated with a [`KindBundle`].
pub trait SpawnInstanceWorld {
/// Spawns a new [`Instance<T>`] using its associated [`KindBundle`].
///
/// # Example
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_kind::prelude::*;
///
/// #[derive(Component)]
/// struct Apple;
///
/// fn spawn_apple(world: &mut World) {
/// let apple: Instance<Apple> = world.spawn_instance(Apple).instance();
/// println!("Spawned {apple:?}!");
/// }
fn spawn_instance<T: KindBundle>(&mut self, _: T) -> InstanceMutItem<'_, T::Kind>
where
T::Kind: Component;
}
impl SpawnInstanceWorld for World {
fn spawn_instance<T: KindBundle>(&mut self, bundle: T) -> InstanceMutItem<'_, T::Kind>
where
T::Kind: Component,
{
let entity = self.spawn(bundle).id();
// SAFE: `entity` must be a valid instance of kind `T`.
InstanceMutItem::from_entity(self, entity).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
use bevy_ecs::system::RunSystemOnce;
#[derive(Component)]
struct Foo;
#[derive(Component)]
struct Bar;
fn count<T: Kind>(query: Query<Instance<T>>) -> usize {
query.iter().count()
}
#[test]
fn kind_with() {
let mut world = World::new();
world.spawn(Foo);
assert_eq!(world.run_system_once(count::<Foo>), 1);
}
#[test]
fn kind_without() {
struct NotFoo;
impl Kind for NotFoo {
type Filter = Without<Foo>;
}
let mut world = World::new();
world.spawn(Foo);
assert_eq!(world.run_system_once(count::<NotFoo>), 0);
}
#[test]
fn kind_multi() {
let mut world = World::new();
world.spawn((Foo, Bar));
assert_eq!(world.run_system_once(count::<Foo>), 1);
assert_eq!(world.run_system_once(count::<Bar>), 1);
}
#[test]
fn kind_cast() {
kind!(Foo is Bar);
let any = Instance::<Any>::PLACEHOLDER;
let foo = Instance::<Foo>::PLACEHOLDER;
let bar = foo.cast_into::<Bar>();
assert!(foo.cast_into_any() == any);
assert!(bar.cast_into_any() == any);
// assert!(any.cast_into::<Foo>() == foo); // <-- Must not compile!
// assert!(bar.cast_into::<Foo>() == foo); // <-- Must not compile!
assert!(bar.entity() == foo.entity());
}
}