moonshine_kind/
instance.rs

1use std::borrow::Borrow;
2use std::{
3    cmp::Ordering,
4    fmt,
5    hash::{Hash, Hasher},
6    marker::PhantomData,
7    ops::{Deref, DerefMut},
8};
9
10use bevy_ecs::change_detection::MaybeLocation;
11use bevy_ecs::component::Mutable;
12use bevy_ecs::relationship::RelationshipSourceCollection;
13use bevy_ecs::{
14    archetype::Archetype,
15    component::{ComponentId, Components, Tick},
16    entity::{EntityMapper, MapEntities},
17    prelude::*,
18    query::{FilteredAccess, QueryData, ReadOnlyQueryData, WorldQuery},
19    storage::{Table, TableRow},
20    system::EntityCommands,
21    world::unsafe_world_cell::UnsafeWorldCell,
22};
23use bevy_reflect::Reflect;
24
25use crate::{Any, CastInto, Kind};
26
27/// Represents an [`Entity`] of [`Kind`] `T`.
28///
29/// `Instance<Any>` is functionally equivalent to an entity.
30///
31/// # Usage
32/// An `Instance<T>` can be used to access entities in a "kind-safe" manner to improve safety and readability.
33///
34/// This type is designed to behave exactly like an [`Entity`].
35///
36/// This means you may use it as a [`Query`] parameter, pass it to [`Commands`] to access [`InstanceCommands<T>`],
37/// or store it as a type-safe reference to an [`Entity`].
38///
39/// Note that an `Instance<T>` has `'static` lifetime and does not contain any [`Component`] data.
40/// It *only* contains type information.
41///
42/// # Example
43/// ```
44/// # use bevy::prelude::*;
45/// # use moonshine_kind::prelude::*;
46///
47/// #[derive(Component)]
48/// struct Apple;
49///
50/// #[derive(Component)]
51/// struct Orange;
52///
53/// struct Fruit;
54///
55/// impl Kind for Fruit {
56///     type Filter = Or<(With<Apple>, With<Orange>)>;
57/// }
58///
59/// #[derive(Resource, Deref, DerefMut)]
60/// struct FruitBasket(Vec<Instance<Fruit>>);
61///
62/// fn collect_fruits(mut basket: ResMut<FruitBasket>, fruits: Query<Instance<Fruit>>) {
63///     for fruit in fruits.iter() {
64///         println!("{fruit:?}");
65///         basket.push(fruit);
66///     }
67/// }
68///
69/// # bevy_ecs::system::assert_is_system(collect_fruits);
70/// ```
71#[derive(Reflect)]
72pub struct Instance<T: Kind>(Entity, #[reflect(ignore)] PhantomData<T>);
73
74impl<T: Kind> Instance<T> {
75    /// Same as [`Entity::PLACEHOLDER`], but for an [`Instance<T>`].
76    pub const PLACEHOLDER: Self = Self(Entity::PLACEHOLDER, PhantomData);
77
78    /// Creates a new instance of kind `T` from some [`Entity`].
79    ///
80    /// # Usage
81    /// This function is useful when you **know** an `Entity` is of a specific kind and you
82    /// need an `Instance<T>` with no way to validate it.
83    ///
84    /// See [`Instance::from_entity`] for a safer alternative.
85    ///
86    /// # Safety
87    /// Assumes `entity` is a valid instance of kind `T`.
88    ///
89    /// # Example
90    /// ```
91    /// # use bevy::prelude::*;
92    /// # use moonshine_kind::prelude::*;
93    ///
94    /// #[derive(Component)]
95    /// struct Apple;
96    ///
97    /// fn init_apple(entity: Entity, commands: &mut Commands) -> Instance<Apple> {
98    ///     commands.entity(entity).insert(Apple);
99    ///     // SAFE: `entity` will be a valid instance of `Apple`.
100    ///     unsafe { Instance::from_entity_unchecked(entity) }
101    /// }
102    /// ```
103    pub unsafe fn from_entity_unchecked(entity: Entity) -> Self {
104        Self(entity, PhantomData)
105    }
106
107    /// Returns the [`Entity`] of this instance.
108    pub fn entity(&self) -> Entity {
109        self.0
110    }
111
112    /// Converts this instance into an instance of another kind [`Kind`] `U`.
113    ///
114    /// # Usage
115    /// A kind `T` is safety convertible to another kind `U` if `T` implements [`CastInto<U>`].
116    pub fn cast_into<U: Kind>(self) -> Instance<U>
117    where
118        T: CastInto<U>,
119    {
120        unsafe { T::cast(self) }
121    }
122
123    /// Converts this instance into an instance of [`Kind`] [`Any`].
124    ///
125    /// # Usage
126    ///
127    /// Any [`Instance<T>`] can be safely cast into an [`Instance<Any>`] using this function.
128    pub fn cast_into_any(self) -> Instance<Any> {
129        // SAFE: All instances are of kind `Any`.
130        unsafe { self.cast_into_unchecked() }
131    }
132
133    /// Converts this instance into an instance of another kind [`Kind`] `U` without any validation.
134    ///
135    /// # Usage
136    /// This function is useful when you **know** an `Instance<T>` is convertible to a specific type and you
137    /// need an `Instance<U>` with no way to validate it.
138    ///
139    /// Always prefer to explicitly declare safe casts with the [`CastInto`] trait and use [`Instance::cast_into`].
140    ///
141    /// # Safety
142    /// Assumes this instance is also a valid `Instance<U>`.
143    pub unsafe fn cast_into_unchecked<U: Kind>(self) -> Instance<U> {
144        Instance::from_entity_unchecked(self.entity())
145    }
146
147    /// Returns a mutable reference to the internal [`Entity`] of this [`Instance`].
148    ///
149    /// # Safety
150    /// You are responsible to ensure the entity is still a valid instance of [`Kind`] `T`.
151    pub unsafe fn as_entity_mut(&mut self) -> &mut Entity {
152        &mut self.0
153    }
154}
155
156impl<T: Component> Instance<T> {
157    /// Creates a new instance of kind `T` from some [`EntityRef`] if the entity has a [`Component`] of type `T`.
158    pub fn from_entity(entity: EntityRef) -> Option<Self> {
159        if entity.contains::<T>() {
160            // SAFE: `entity` must be of kind `T`.
161            Some(unsafe { Self::from_entity_unchecked(entity.id()) })
162        } else {
163            None
164        }
165    }
166}
167
168impl<T: Kind> Clone for Instance<T> {
169    fn clone(&self) -> Self {
170        *self
171    }
172}
173
174impl<T: Kind> Copy for Instance<T> {}
175
176impl<T: Kind> fmt::Debug for Instance<T> {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        write!(f, "{}({:?})", T::debug_name(), self.0)
179    }
180}
181
182impl<T: Kind> fmt::Display for Instance<T> {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        write!(
185            f,
186            "{}({}v{})",
187            T::debug_name(),
188            self.0.index(),
189            self.0.generation()
190        )
191    }
192}
193
194impl<T: Kind> Hash for Instance<T> {
195    fn hash<H: Hasher>(&self, state: &mut H) {
196        self.0.hash(state);
197    }
198}
199
200impl<T: Kind, U: Kind> PartialEq<Instance<U>> for Instance<T> {
201    fn eq(&self, other: &Instance<U>) -> bool {
202        self.0 == other.0
203    }
204}
205
206impl<T: Kind> PartialEq<Entity> for Instance<T> {
207    fn eq(&self, other: &Entity) -> bool {
208        self.0 == *other
209    }
210}
211
212impl<T: Kind> PartialEq<Instance<T>> for Entity {
213    fn eq(&self, other: &Instance<T>) -> bool {
214        other == self
215    }
216}
217
218impl<T: Kind> Eq for Instance<T> {}
219
220impl<T: Kind> PartialOrd for Instance<T> {
221    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
222        Some(self.cmp(other))
223    }
224}
225
226impl<T: Kind> Ord for Instance<T> {
227    fn cmp(&self, other: &Self) -> Ordering {
228        self.0.cmp(&other.0)
229    }
230}
231
232impl<T: Kind> Deref for Instance<T> {
233    type Target = Entity;
234
235    fn deref(&self) -> &Self::Target {
236        &self.0
237    }
238}
239
240impl<T: Kind> Borrow<Entity> for Instance<T> {
241    fn borrow(&self) -> &Entity {
242        &self.0
243    }
244}
245
246unsafe impl<T: Kind> WorldQuery for Instance<T> {
247    type Fetch<'a> = <T::Filter as WorldQuery>::Fetch<'a>;
248
249    type State = <T::Filter as WorldQuery>::State;
250
251    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
252        <T::Filter as WorldQuery>::shrink_fetch(fetch)
253    }
254
255    unsafe fn init_fetch<'w>(
256        world: UnsafeWorldCell<'w>,
257        state: &Self::State,
258        last_change_tick: Tick,
259        change_tick: Tick,
260    ) -> Self::Fetch<'w> {
261        <T::Filter as WorldQuery>::init_fetch(world, state, last_change_tick, change_tick)
262    }
263
264    const IS_DENSE: bool = <T::Filter as WorldQuery>::IS_DENSE;
265
266    unsafe fn set_archetype<'w>(
267        fetch: &mut Self::Fetch<'w>,
268        state: &Self::State,
269        archetype: &'w Archetype,
270        table: &'w Table,
271    ) {
272        <T::Filter as WorldQuery>::set_archetype(fetch, state, archetype, table)
273    }
274
275    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
276        <T::Filter as WorldQuery>::set_table(fetch, state, table)
277    }
278
279    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
280        <T::Filter as WorldQuery>::update_component_access(state, access)
281    }
282
283    fn get_state(components: &Components) -> Option<Self::State> {
284        <T::Filter as WorldQuery>::get_state(components)
285    }
286
287    fn init_state(world: &mut World) -> Self::State {
288        <T::Filter as WorldQuery>::init_state(world)
289    }
290
291    fn matches_component_set(
292        state: &Self::State,
293        set_contains_id: &impl Fn(ComponentId) -> bool,
294    ) -> bool {
295        <T::Filter as WorldQuery>::matches_component_set(state, set_contains_id)
296    }
297}
298
299unsafe impl<T: Kind> ReadOnlyQueryData for Instance<T> {}
300
301unsafe impl<T: Kind> QueryData for Instance<T> {
302    type ReadOnly = Self;
303
304    const IS_READ_ONLY: bool = true;
305
306    type Item<'w, 's> = Self;
307
308    fn shrink<'wlong: 'wshort, 'wshort, 's>(
309        item: Self::Item<'wlong, 's>,
310    ) -> Self::Item<'wshort, 's> {
311        item
312    }
313
314    unsafe fn fetch<'w, 's>(
315        _state: &'s Self::State,
316        _fetch: &mut Self::Fetch<'w>,
317        entity: Entity,
318        _table_row: TableRow,
319    ) -> Self::Item<'w, 's> {
320        Instance::from_entity_unchecked(entity)
321    }
322}
323
324impl<T: Kind> MapEntities for Instance<T> {
325    fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
326        self.0 = entity_mapper.get_mapped(self.0);
327    }
328}
329
330impl<T: Kind> From<Instance<T>> for Entity {
331    fn from(instance: Instance<T>) -> Self {
332        instance.entity()
333    }
334}
335
336impl<T: Kind> RelationshipSourceCollection for Instance<T> {
337    type SourceIter<'a> = <Entity as RelationshipSourceCollection>::SourceIter<'a>;
338
339    fn new() -> Self {
340        Self::PLACEHOLDER
341    }
342
343    fn with_capacity(_capacity: usize) -> Self {
344        Self::new()
345    }
346
347    fn reserve(&mut self, additional: usize) {
348        self.0.reserve(additional);
349    }
350
351    fn add(&mut self, entity: Entity) -> bool {
352        self.0.add(entity)
353    }
354
355    fn remove(&mut self, entity: Entity) -> bool {
356        self.0.remove(entity)
357    }
358
359    fn iter(&self) -> Self::SourceIter<'_> {
360        self.0.iter()
361    }
362
363    fn len(&self) -> usize {
364        self.0.len()
365    }
366
367    fn clear(&mut self) {
368        self.0.clear();
369    }
370
371    fn shrink_to_fit(&mut self) {
372        self.0.shrink_to_fit();
373    }
374
375    fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
376        self.0.extend_from_iter(entities)
377    }
378}
379
380impl From<Entity> for Instance<Any> {
381    fn from(entity: Entity) -> Self {
382        Self(entity, PhantomData)
383    }
384}
385
386impl<T: Kind> ContainsEntity for Instance<T> {
387    fn entity(&self) -> Entity {
388        self.entity()
389    }
390}
391
392/// Similar to [`ContainsEntity`], but for [`Instance<T>`].
393pub trait ContainsInstance<T: Kind> {
394    /// Returns the associated [`Instance<T>`].
395    fn instance(&self) -> Instance<T>;
396
397    /// Returns the [`Entity`] of the associated [`Instance<T>`].
398    fn entity(&self) -> Entity {
399        self.instance().entity()
400    }
401}
402
403/// A [`QueryData`] item which represents a reference to an [`Instance<T>`] and its associated [`Component`].
404///
405/// This is analogous to a `(Instance<T>, &T)` query.
406///
407/// # Usage
408/// If a [`Kind`] is also a component, it is often convenient to access the instance and component data together.
409/// This type is designed to make these queries more ergonomic.
410///
411/// You may use this type as either a [`Query`] parameter, or access it from an [`EntityRef`].
412///
413/// # Example
414/// ```
415/// # use bevy::prelude::*;
416/// # use moonshine_kind::prelude::*;
417///
418/// #[derive(Component)]
419/// struct Apple {
420///     freshness: f32,
421/// }
422///
423/// impl Apple {
424///     fn is_fresh(&self) -> bool {
425///         self.freshness >= 0.5
426///     }
427/// }
428///
429/// // Query Access:
430/// fn fresh_apples(query: Query<InstanceRef<Apple>>) -> Vec<Instance<Apple>> {
431///     query.iter()
432///         .filter_map(|apple| apple.is_fresh().then_some(apple.instance()))
433///         .collect()
434/// }
435///
436/// // Entity Access:
437/// fn fresh_apples_world<'a>(world: &'a World) -> Vec<InstanceRef<'a, Apple>> {
438///    world.iter_entities()
439///         .filter_map(|entity| InstanceRef::from_entity(entity))
440///         .collect()
441/// }
442///
443/// # bevy_ecs::system::assert_is_system(fresh_apples);
444/// ```
445pub struct InstanceRef<'a, T: Component>(Instance<T>, &'a T);
446
447unsafe impl<T: Component> WorldQuery for InstanceRef<'_, T> {
448    type Fetch<'w> = <(Instance<T>, &'static T) as WorldQuery>::Fetch<'w>;
449
450    type State = <(Instance<T>, &'static T) as WorldQuery>::State;
451
452    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
453        <(Instance<T>, &T) as WorldQuery>::shrink_fetch(fetch)
454    }
455
456    unsafe fn init_fetch<'w>(
457        world: UnsafeWorldCell<'w>,
458        state: &Self::State,
459        last_run: Tick,
460        this_run: Tick,
461    ) -> Self::Fetch<'w> {
462        <(Instance<T>, &T) as WorldQuery>::init_fetch(world, state, last_run, this_run)
463    }
464
465    const IS_DENSE: bool = <(Instance<T>, &T) as WorldQuery>::IS_DENSE;
466
467    unsafe fn set_archetype<'w>(
468        fetch: &mut Self::Fetch<'w>,
469        state: &Self::State,
470        archetype: &'w Archetype,
471        table: &'w Table,
472    ) {
473        <(Instance<T>, &T) as WorldQuery>::set_archetype(fetch, state, archetype, table)
474    }
475
476    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
477        <(Instance<T>, &T) as WorldQuery>::set_table(fetch, state, table)
478    }
479
480    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
481        <(Instance<T>, &T) as WorldQuery>::update_component_access(state, access)
482    }
483
484    fn init_state(world: &mut World) -> Self::State {
485        <(Instance<T>, &T) as WorldQuery>::init_state(world)
486    }
487
488    fn get_state(components: &Components) -> Option<Self::State> {
489        <(Instance<T>, &T) as WorldQuery>::get_state(components)
490    }
491
492    fn matches_component_set(
493        state: &Self::State,
494        set_contains_id: &impl Fn(ComponentId) -> bool,
495    ) -> bool {
496        <(Instance<T>, &T) as WorldQuery>::matches_component_set(state, set_contains_id)
497    }
498}
499
500unsafe impl<T: Component> QueryData for InstanceRef<'_, T> {
501    type ReadOnly = Self;
502
503    const IS_READ_ONLY: bool = true;
504
505    type Item<'w, 's> = InstanceRef<'w, T>;
506
507    fn shrink<'wlong: 'wshort, 'wshort, 's>(
508        item: Self::Item<'wlong, 's>,
509    ) -> Self::Item<'wshort, 's> {
510        InstanceRef(item.0, item.1)
511    }
512
513    unsafe fn fetch<'w, 's>(
514        state: &'s Self::State,
515        fetch: &mut Self::Fetch<'w>,
516        entity: Entity,
517        table_row: TableRow,
518    ) -> Self::Item<'w, 's> {
519        let (instance, data) =
520            <(Instance<T>, &T) as QueryData>::fetch(state, fetch, entity, table_row);
521        InstanceRef(instance, data)
522    }
523}
524
525unsafe impl<T: Component> ReadOnlyQueryData for InstanceRef<'_, T> {}
526
527impl<'a, T: Component> InstanceRef<'a, T> {
528    /// Creates a new [`InstanceRef<T>`] from an [`EntityRef`] if it contains a given [`Component`] of type `T`.
529    pub fn from_entity(entity: EntityRef<'a>) -> Option<Self> {
530        Some(Self(
531            // SAFE: Kind is validated by `entity.get()` above.
532            unsafe { Instance::from_entity_unchecked(entity.id()) },
533            entity.get()?,
534        ))
535    }
536
537    /// Creates a new [`InstanceRef<T>`] from [`EntityRef`] without any validation.
538    ///
539    /// # Safety
540    /// Assumes `entity` is a valid instance of kind `T`.
541    pub unsafe fn from_entity_unchecked(entity: EntityRef<'a>) -> Self {
542        Self(
543            Instance::from_entity_unchecked(entity.id()),
544            entity.get().unwrap(),
545        )
546    }
547}
548
549impl<T: Component> Clone for InstanceRef<'_, T> {
550    fn clone(&self) -> Self {
551        *self
552    }
553}
554
555impl<T: Component> Copy for InstanceRef<'_, T> {}
556
557impl<T: Component> From<InstanceRef<'_, T>> for Instance<T> {
558    fn from(item: InstanceRef<T>) -> Self {
559        item.instance()
560    }
561}
562
563impl<T: Component> From<&InstanceRef<'_, T>> for Instance<T> {
564    fn from(item: &InstanceRef<T>) -> Self {
565        item.instance()
566    }
567}
568
569impl<T: Component> PartialEq for InstanceRef<'_, T> {
570    fn eq(&self, other: &Self) -> bool {
571        self.0 == other.0
572    }
573}
574
575impl<T: Component> Eq for InstanceRef<'_, T> {}
576
577impl<T: Component> Deref for InstanceRef<'_, T> {
578    type Target = T;
579
580    fn deref(&self) -> &Self::Target {
581        self.1
582    }
583}
584
585impl<T: Component> AsRef<Instance<T>> for InstanceRef<'_, T> {
586    fn as_ref(&self) -> &Instance<T> {
587        &self.0
588    }
589}
590
591impl<T: Component> AsRef<T> for InstanceRef<'_, T> {
592    fn as_ref(&self) -> &T {
593        self.1
594    }
595}
596
597impl<T: Component> ContainsInstance<T> for InstanceRef<'_, T> {
598    fn instance(&self) -> Instance<T> {
599        self.0
600    }
601}
602
603/// A [`QueryData`] item which represents a mutable reference to an [`Instance<T>`] and its associated [`Component`].
604///
605/// This is analogous to a `(Instance<T>, &mut T)` query.
606///
607/// # Usage
608/// This type behaves similar like [`InstanceRef<T>`] but allows mutable access to its associated [`Component`].
609///
610/// The main difference is that you cannot create an [`InstanceMut<T>`] from an [`EntityMut`].
611/// See [`InstanceMut::from_entity`] for more details.
612///
613/// See [`InstanceRef<T>`] for more information and examples.
614pub struct InstanceMut<'a, T: Component>(Instance<T>, Mut<'a, T>);
615
616unsafe impl<T: Component> WorldQuery for InstanceMut<'_, T> {
617    type Fetch<'w> = <(Instance<T>, &'static mut T) as WorldQuery>::Fetch<'w>;
618
619    type State = <(Instance<T>, &'static mut T) as WorldQuery>::State;
620
621    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
622        <(Instance<T>, &mut T) as WorldQuery>::shrink_fetch(fetch)
623    }
624
625    unsafe fn init_fetch<'w>(
626        world: UnsafeWorldCell<'w>,
627        state: &Self::State,
628        last_run: Tick,
629        this_run: Tick,
630    ) -> Self::Fetch<'w> {
631        <(Instance<T>, &mut T) as WorldQuery>::init_fetch(world, state, last_run, this_run)
632    }
633
634    const IS_DENSE: bool = <(Instance<T>, &T) as WorldQuery>::IS_DENSE;
635
636    unsafe fn set_archetype<'w>(
637        fetch: &mut Self::Fetch<'w>,
638        state: &Self::State,
639        archetype: &'w Archetype,
640        table: &'w Table,
641    ) {
642        <(Instance<T>, &mut T) as WorldQuery>::set_archetype(fetch, state, archetype, table)
643    }
644
645    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
646        <(Instance<T>, &mut T) as WorldQuery>::set_table(fetch, state, table)
647    }
648
649    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
650        <(Instance<T>, &T) as WorldQuery>::update_component_access(state, access)
651    }
652
653    fn init_state(world: &mut World) -> Self::State {
654        <(Instance<T>, &T) as WorldQuery>::init_state(world)
655    }
656
657    fn get_state(components: &Components) -> Option<Self::State> {
658        <(Instance<T>, &T) as WorldQuery>::get_state(components)
659    }
660
661    fn matches_component_set(
662        state: &Self::State,
663        set_contains_id: &impl Fn(ComponentId) -> bool,
664    ) -> bool {
665        <(Instance<T>, &T) as WorldQuery>::matches_component_set(state, set_contains_id)
666    }
667}
668
669unsafe impl<'b, T: Component<Mutability = Mutable>> QueryData for InstanceMut<'b, T> {
670    type ReadOnly = InstanceRef<'b, T>;
671
672    const IS_READ_ONLY: bool = false;
673
674    type Item<'w, 's> = InstanceMut<'w, T>;
675
676    fn shrink<'wlong: 'wshort, 'wshort, 's>(
677        item: Self::Item<'wlong, 's>,
678    ) -> Self::Item<'wshort, 's> {
679        InstanceMut(item.0, item.1)
680    }
681
682    unsafe fn fetch<'w, 's>(
683        state: &'s Self::State,
684        fetch: &mut Self::Fetch<'w>,
685        entity: Entity,
686        table_row: TableRow,
687    ) -> Self::Item<'w, 's> {
688        let (instance, data) =
689            <(Instance<T>, &mut T) as QueryData>::fetch(state, fetch, entity, table_row);
690        InstanceMut(instance, data)
691    }
692}
693
694impl<'a, T: Component<Mutability = Mutable>> InstanceMut<'a, T> {
695    /// Creates a new [`InstanceMut<T>`] from an [`EntityWorldMut`] if it contains a given [`Component`] of type `T`.
696    pub fn from_entity(entity: EntityMut<'a>) -> Option<Self> {
697        let id = entity.id();
698        let data = entity.into_mut()?;
699        Some(Self(
700            // SAFE: Kind is validated by `entity.get_mut()` above.
701            unsafe { Instance::from_entity_unchecked(id) },
702            data,
703        ))
704    }
705
706    /// Creates a new [`InstanceMut<T>`] from an [`EntityMut`] without any validation.
707    ///
708    /// # Safety
709    /// Assumes `entity` is a valid instance of kind `T`.
710    pub unsafe fn from_entity_unchecked(entity: EntityMut<'a>) -> Self {
711        let id = entity.id();
712        let data = entity.into_mut().unwrap();
713        Self(Instance::from_entity_unchecked(id), data)
714    }
715}
716
717impl<T: Component> From<InstanceMut<'_, T>> for Instance<T> {
718    fn from(item: InstanceMut<T>) -> Self {
719        item.instance()
720    }
721}
722
723impl<T: Component> From<&InstanceMut<'_, T>> for Instance<T> {
724    fn from(item: &InstanceMut<T>) -> Self {
725        item.instance()
726    }
727}
728
729impl<T: Component> PartialEq for InstanceMut<'_, T> {
730    fn eq(&self, other: &Self) -> bool {
731        self.0 == other.0
732    }
733}
734
735impl<T: Component> Eq for InstanceMut<'_, T> {}
736
737impl<T: Component> Deref for InstanceMut<'_, T> {
738    type Target = T;
739
740    fn deref(&self) -> &Self::Target {
741        self.1.as_ref()
742    }
743}
744
745impl<T: Component> DerefMut for InstanceMut<'_, T> {
746    fn deref_mut(&mut self) -> &mut Self::Target {
747        self.1.as_mut()
748    }
749}
750
751impl<T: Component> AsRef<Instance<T>> for InstanceMut<'_, T> {
752    fn as_ref(&self) -> &Instance<T> {
753        &self.0
754    }
755}
756
757impl<T: Component> AsRef<T> for InstanceMut<'_, T> {
758    fn as_ref(&self) -> &T {
759        self.1.as_ref()
760    }
761}
762
763impl<T: Component> AsMut<T> for InstanceMut<'_, T> {
764    fn as_mut(&mut self) -> &mut T {
765        self.1.as_mut()
766    }
767}
768
769impl<T: Component> DetectChanges for InstanceMut<'_, T> {
770    fn is_added(&self) -> bool {
771        self.1.is_added()
772    }
773
774    fn is_changed(&self) -> bool {
775        self.1.is_changed()
776    }
777
778    fn last_changed(&self) -> Tick {
779        self.1.last_changed()
780    }
781
782    fn added(&self) -> Tick {
783        self.1.added()
784    }
785
786    fn changed_by(&self) -> MaybeLocation {
787        self.1.changed_by()
788    }
789}
790
791impl<T: Component> DetectChangesMut for InstanceMut<'_, T> {
792    type Inner = T;
793
794    fn set_changed(&mut self) {
795        self.1.set_changed();
796    }
797
798    fn set_last_changed(&mut self, last_changed: Tick) {
799        self.1.set_last_changed(last_changed);
800    }
801
802    fn bypass_change_detection(&mut self) -> &mut Self::Inner {
803        self.1.bypass_change_detection()
804    }
805
806    fn set_added(&mut self) {
807        self.1.set_added();
808    }
809
810    fn set_last_added(&mut self, last_added: Tick) {
811        self.1.set_last_added(last_added);
812    }
813}
814
815impl<T: Component> ContainsInstance<T> for InstanceMut<'_, T> {
816    fn instance(&self) -> Instance<T> {
817        self.0
818    }
819}
820
821/// Extension trait to access [`InstanceCommands<T>`] from [`Commands`].
822///
823/// See [`InstanceCommands`] for more information.
824pub trait GetInstanceCommands<T: Kind> {
825    /// Returns the [`InstanceCommands<T>`] for an [`Instance<T>`].
826    fn instance(&mut self, instance: Instance<T>) -> InstanceCommands<'_, T>;
827}
828
829impl<T: Kind> GetInstanceCommands<T> for Commands<'_, '_> {
830    fn instance(&mut self, instance: Instance<T>) -> InstanceCommands<'_, T> {
831        InstanceCommands(self.entity(instance.entity()), PhantomData)
832    }
833}
834
835/// [`EntityCommands`] with kind semantics.
836///
837/// # Usage
838/// On its own, this type is not very useful. Instead, it is designed to be extended using traits.
839/// This allows you to design commands for a specific kind of an entity in a type-safe manner.
840///
841/// # Example
842/// ```
843/// # use bevy::prelude::*;
844/// # use moonshine_kind::prelude::*;
845///
846/// #[derive(Component)]
847/// struct Apple;
848///
849/// #[derive(Component)]
850/// struct Eat;
851///
852/// trait EatApple {
853///     fn eat(&mut self);
854/// }
855///
856/// impl EatApple for InstanceCommands<'_, Apple> {
857///     fn eat(&mut self) {
858///         info!("Crunch!");
859///         self.despawn();
860///     }
861/// }
862///
863/// fn eat_apples(apples: Query<Instance<Apple>, With<Eat>>, mut commands: Commands) {
864///     for apple in apples.iter() {
865///         commands.instance(apple).eat();
866///     }
867/// }
868///
869/// # bevy_ecs::system::assert_is_system(eat_apples);
870pub struct InstanceCommands<'a, T: Kind>(EntityCommands<'a>, PhantomData<T>);
871
872impl<'a, T: Kind> InstanceCommands<'a, T> {
873    /// Creates a new [`InstanceCommands<T>`] from [`EntityCommands`] without any validation.
874    ///
875    /// # Safety
876    /// Assumes `entity` is a valid instance of kind `T`.
877    pub unsafe fn from_entity_unchecked(entity: EntityCommands<'a>) -> Self {
878        Self(entity, PhantomData)
879    }
880
881    /// Creates a new [`InstanceCommands<T>`] from [`EntityRef`] if it contains a [`Component`] of type `T`.
882    pub fn from_entity(entity: EntityRef, commands: &'a mut Commands) -> Option<Self>
883    where
884        T: Component,
885    {
886        if entity.contains::<T>() {
887            Some(Self(commands.entity(entity.id()), PhantomData))
888        } else {
889            None
890        }
891    }
892
893    /// Returns the associated [`Instance<T>`].
894    pub fn instance(&self) -> Instance<T> {
895        // SAFE: `self.entity()` must be a valid instance of kind `T`.
896        unsafe { Instance::from_entity_unchecked(self.id()) }
897    }
898
899    /// Returns the associated [`EntityCommands`].
900    pub fn as_entity(&mut self) -> &mut EntityCommands<'a> {
901        &mut self.0
902    }
903
904    /// Equivalent to [`EntityCommands::insert`], but it returns `self` to maintain kind semantics.
905    pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
906        self.0.insert(bundle);
907        self
908    }
909
910    /// Equivalent to [`EntityCommands::insert`], but it returns `self` to maintain kind semantics.
911    pub fn remove<U: Component>(&mut self) -> &mut Self {
912        self.0.remove::<U>();
913        self
914    }
915
916    /// Equivalent to [`EntityCommands::try_insert`], but it returns `self` to maintain kind semantics.
917    pub fn try_remove<U: Component>(&mut self) -> &mut Self {
918        self.0.try_remove::<U>();
919        self
920    }
921
922    /// Returns an [`InstanceCommands`] with a smaller lifetime.
923    ///
924    /// This is useful if you have `&mut InstanceCommands` but you need `InstanceCommands`.
925    pub fn reborrow(&mut self) -> InstanceCommands<'_, T> {
926        InstanceCommands(self.0.reborrow(), PhantomData)
927    }
928
929    /// Converts this [`InstanceCommands<T>`] into an [`InstanceCommands<U>`], given that `T` implements [`CastInto<U>`].
930    pub fn cast_into<U: Kind>(self) -> InstanceCommands<'a, U>
931    where
932        T: CastInto<U>,
933    {
934        // SAFE: `CastInto<U>` is implemented for `T`.
935        unsafe { InstanceCommands::from_entity_unchecked(self.0) }
936    }
937}
938
939impl<'a, T: Kind> From<InstanceCommands<'a, T>> for Instance<T> {
940    fn from(commands: InstanceCommands<'a, T>) -> Self {
941        commands.instance()
942    }
943}
944
945impl<'a, T: Kind> From<&InstanceCommands<'a, T>> for Instance<T> {
946    fn from(commands: &InstanceCommands<'a, T>) -> Self {
947        commands.instance()
948    }
949}
950
951impl<'a, T: Kind> Deref for InstanceCommands<'a, T> {
952    type Target = EntityCommands<'a>;
953
954    fn deref(&self) -> &Self::Target {
955        &self.0
956    }
957}
958
959impl<T: Kind> DerefMut for InstanceCommands<'_, T> {
960    fn deref_mut(&mut self) -> &mut Self::Target {
961        &mut self.0
962    }
963}
964
965impl<T: Kind> ContainsInstance<T> for InstanceCommands<'_, T> {
966    fn instance(&self) -> Instance<T> {
967        self.instance()
968    }
969}
970
971// /// Trait used to trigger an [`Instance<T>`] with an [`Event`].
972// pub trait TriggerInstance {
973//     /// Triggers an [`Event`] on the given [`Instance<T>`].
974//     ///
975//     /// You can use [`Trigger<E, T>`] to handle an event `E` on an [`Instance<T>`].
976//     fn trigger_instance<T: Component>(self, event: impl Event, instance: Instance<T>) -> Self;
977// }
978
979// impl TriggerInstance for &mut Commands<'_, '_> {
980//     fn trigger_instance<T: Component>(self, event: impl Event, instance: Instance<T>) -> Self {
981//         self.queue(move |world: &mut World| {
982//             world.trigger_instance(event, instance);
983//         });
984//         self
985//     }
986// }
987
988// impl TriggerInstance for &mut World {
989//     fn trigger_instance<T: Component>(self, event: impl Event, instance: Instance<T>) -> Self {
990//         let id = self.component_id::<T>().unwrap();
991//         self.trigger(event, (instance.entity(), id));
992//         self
993//     }
994// }
995
996// /// Trait used to access the a [`Trigger<E, T>::target`] as an [`Instance<T>`] if `T` is a [`Component`].
997// pub trait GetTriggerTargetInstance<T: Kind> {
998//     /// Returns the [`Instance<T>`] that was targeted by the [`Event`] that triggered this observer. It may
999//     /// be [`Instance::PLACEHOLDER`].
1000//     fn target_instance(&self) -> Instance<T>;
1001// }
1002
1003// impl<E: Event, T: Component> GetTriggerTargetInstance<T> for Trigger<'_, E, T> {
1004//     fn target_instance(&self) -> Instance<T> {
1005//         // SAFE: `Trigger` ensures target is an instance of kind `T`.
1006//         unsafe { Instance::from_entity_unchecked(self.target()) }
1007//     }
1008// }