Skip to main content

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_derive::{Deref, DerefMut};
11use bevy_ecs::change_detection::MaybeLocation;
12use bevy_ecs::component::Mutable;
13use bevy_ecs::query::EcsAccessType;
14use bevy_ecs::relationship::RelationshipSourceCollection;
15use bevy_ecs::{
16    archetype::Archetype,
17    change_detection::Tick,
18    component::{ComponentId, Components},
19    entity::{EntityMapper, MapEntities},
20    prelude::*,
21    query::{FilteredAccess, IterQueryData, QueryData, ReadOnlyQueryData, WorldQuery},
22    storage::{Table, TableRow},
23    system::EntityCommands,
24    world::unsafe_world_cell::UnsafeWorldCell,
25};
26use bevy_reflect::Reflect;
27
28use crate::{Any, CastInto, Kind};
29
30/// Represents an [`Entity`] of [`Kind`] `T`.
31///
32/// `Instance<Any>` is functionally equivalent to an entity.
33///
34/// # Usage
35/// An `Instance<T>` can be used to access entities in a "kind-safe" manner to improve safety and readability.
36///
37/// This type is designed to behave exactly like an [`Entity`].
38///
39/// This means you may use it as a [`Query`] parameter, pass it to [`Commands`] to access [`InstanceCommands<T>`],
40/// or store it as a type-safe reference to an [`Entity`].
41///
42/// Note that an `Instance<T>` has `'static` lifetime and does not contain any [`Component`] data.
43/// It *only* contains type information.
44///
45/// # Example
46/// ```
47/// # use bevy::prelude::*;
48/// # use moonshine_kind::prelude::*;
49///
50/// #[derive(Component)]
51/// struct Apple;
52///
53/// #[derive(Component)]
54/// struct Orange;
55///
56/// struct Fruit;
57///
58/// impl Kind for Fruit {
59///     type Filter = Or<(With<Apple>, With<Orange>)>;
60/// }
61///
62/// #[derive(Resource, Deref, DerefMut)]
63/// struct FruitBasket(Vec<Instance<Fruit>>);
64///
65/// fn collect_fruits(mut basket: ResMut<FruitBasket>, fruits: Query<Instance<Fruit>>) {
66///     for fruit in fruits.iter() {
67///         println!("{fruit:?}");
68///         basket.push(fruit);
69///     }
70/// }
71///
72/// # bevy_ecs::system::assert_is_system(collect_fruits);
73/// ```
74#[derive(Reflect)]
75pub struct Instance<T: Kind>(Entity, #[reflect(ignore)] PhantomData<T>);
76
77impl<T: Kind> Instance<T> {
78    /// Same as [`Entity::PLACEHOLDER`], but for an [`Instance<T>`].
79    pub const PLACEHOLDER: Self = Self(Entity::PLACEHOLDER, PhantomData);
80
81    /// Creates a new instance of kind `T` from some [`Entity`].
82    ///
83    /// # Usage
84    /// This function is useful when you **know** an `Entity` is of a specific kind and you
85    /// need an `Instance<T>` with no way to validate it.
86    ///
87    /// See [`Instance::from_entity`] for a safer alternative.
88    ///
89    /// # Safety
90    /// Assumes `entity` is a valid instance of kind `T`.
91    ///
92    /// # Example
93    /// ```
94    /// # use bevy::prelude::*;
95    /// # use moonshine_kind::prelude::*;
96    ///
97    /// #[derive(Component)]
98    /// struct Apple;
99    ///
100    /// fn init_apple(entity: Entity, commands: &mut Commands) -> Instance<Apple> {
101    ///     commands.entity(entity).insert(Apple);
102    ///     // SAFE: `entity` will be a valid instance of `Apple`.
103    ///     unsafe { Instance::from_entity_unchecked(entity) }
104    /// }
105    /// ```
106    pub unsafe fn from_entity_unchecked(entity: Entity) -> Self {
107        Self(entity, PhantomData)
108    }
109
110    /// Returns the [`Entity`] of this instance.
111    pub fn entity(&self) -> Entity {
112        self.0
113    }
114
115    /// Converts this instance into an instance of another kind [`Kind`] `U`.
116    ///
117    /// # Usage
118    /// A kind `T` is safety convertible to another kind `U` if `T` implements [`CastInto<U>`].
119    pub fn cast_into<U: Kind>(self) -> Instance<U>
120    where
121        T: CastInto<U>,
122    {
123        unsafe { T::cast(self) }
124    }
125
126    /// Converts this instance into an instance of [`Kind`] [`Any`].
127    ///
128    /// # Usage
129    ///
130    /// Any [`Instance<T>`] can be safely cast into an [`Instance<Any>`] using this function.
131    pub fn cast_into_any(self) -> Instance<Any> {
132        // SAFE: All instances are of kind `Any`.
133        unsafe { self.cast_into_unchecked() }
134    }
135
136    /// Converts this instance into an instance of another kind [`Kind`] `U` without any validation.
137    ///
138    /// # Usage
139    /// This function is useful when you **know** an `Instance<T>` is convertible to a specific type and you
140    /// need an `Instance<U>` with no way to validate it.
141    ///
142    /// Always prefer to explicitly declare safe casts with the [`CastInto`] trait and use [`Instance::cast_into`].
143    ///
144    /// # Safety
145    /// Assumes this instance is also a valid `Instance<U>`.
146    pub unsafe fn cast_into_unchecked<U: Kind>(self) -> Instance<U> {
147        Instance::from_entity_unchecked(self.entity())
148    }
149
150    /// Returns a mutable reference to the internal [`Entity`] of this [`Instance`].
151    ///
152    /// # Safety
153    /// You are responsible to ensure the entity is still a valid instance of [`Kind`] `T`.
154    #[deprecated(note = "use `Instance::<T>::from_entity_unchecked` instead")]
155    pub unsafe fn as_entity_mut(&mut self) -> &mut Entity {
156        &mut self.0
157    }
158}
159
160impl<T: Component> Instance<T> {
161    /// Creates a new instance of kind `T` from some [`EntityRef`] if the entity has a [`Component`] of type `T`.
162    pub fn from_entity(entity: EntityRef) -> Option<Self> {
163        if entity.contains::<T>() {
164            // SAFE: `entity` must be of kind `T`.
165            Some(unsafe { Self::from_entity_unchecked(entity.id()) })
166        } else {
167            None
168        }
169    }
170}
171
172impl<T: Kind> Clone for Instance<T> {
173    fn clone(&self) -> Self {
174        *self
175    }
176}
177
178impl<T: Kind> Copy for Instance<T> {}
179
180impl<T: Kind> fmt::Debug for Instance<T> {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        write!(f, "{}({:?})", T::debug_name(), self.0)
183    }
184}
185
186impl<T: Kind> fmt::Display for Instance<T> {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        write!(
189            f,
190            "{}({}v{})",
191            T::debug_name(),
192            self.0.index(),
193            self.0.generation()
194        )
195    }
196}
197
198impl<T: Kind> Hash for Instance<T> {
199    fn hash<H: Hasher>(&self, state: &mut H) {
200        self.0.hash(state);
201    }
202}
203
204impl<T: Kind, U: Kind> PartialEq<Instance<U>> for Instance<T> {
205    fn eq(&self, other: &Instance<U>) -> bool {
206        self.0 == other.0
207    }
208}
209
210impl<T: Kind> PartialEq<Entity> for Instance<T> {
211    fn eq(&self, other: &Entity) -> bool {
212        self.0 == *other
213    }
214}
215
216impl<T: Kind> PartialEq<Instance<T>> for Entity {
217    fn eq(&self, other: &Instance<T>) -> bool {
218        other == self
219    }
220}
221
222impl<T: Kind> Eq for Instance<T> {}
223
224impl<T: Kind> PartialOrd for Instance<T> {
225    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
226        Some(self.cmp(other))
227    }
228}
229
230impl<T: Kind> Ord for Instance<T> {
231    fn cmp(&self, other: &Self) -> Ordering {
232        self.0.cmp(&other.0)
233    }
234}
235
236impl<T: Kind> Deref for Instance<T> {
237    type Target = Entity;
238
239    fn deref(&self) -> &Self::Target {
240        &self.0
241    }
242}
243
244impl<T: Kind> Borrow<Entity> for Instance<T> {
245    fn borrow(&self) -> &Entity {
246        &self.0
247    }
248}
249
250unsafe impl<T: Kind> WorldQuery for Instance<T> {
251    type Fetch<'a> = <T::Filter as WorldQuery>::Fetch<'a>;
252
253    type State = <T::Filter as WorldQuery>::State;
254
255    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
256        <T::Filter as WorldQuery>::shrink_fetch(fetch)
257    }
258
259    unsafe fn init_fetch<'w>(
260        world: UnsafeWorldCell<'w>,
261        state: &Self::State,
262        last_change_tick: Tick,
263        change_tick: Tick,
264    ) -> Self::Fetch<'w> {
265        <T::Filter as WorldQuery>::init_fetch(world, state, last_change_tick, change_tick)
266    }
267
268    const IS_DENSE: bool = <T::Filter as WorldQuery>::IS_DENSE;
269
270    unsafe fn set_archetype<'w>(
271        fetch: &mut Self::Fetch<'w>,
272        state: &Self::State,
273        archetype: &'w Archetype,
274        table: &'w Table,
275    ) {
276        <T::Filter as WorldQuery>::set_archetype(fetch, state, archetype, table)
277    }
278
279    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
280        <T::Filter as WorldQuery>::set_table(fetch, state, table)
281    }
282
283    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
284        <T::Filter as WorldQuery>::update_component_access(state, access)
285    }
286
287    fn get_state(components: &Components) -> Option<Self::State> {
288        <T::Filter as WorldQuery>::get_state(components)
289    }
290
291    fn init_state(world: &mut World) -> Self::State {
292        <T::Filter as WorldQuery>::init_state(world)
293    }
294
295    fn matches_component_set(
296        state: &Self::State,
297        set_contains_id: &impl Fn(ComponentId) -> bool,
298    ) -> bool {
299        <T::Filter as WorldQuery>::matches_component_set(state, set_contains_id)
300    }
301}
302
303unsafe impl<T: Kind> IterQueryData for Instance<T> {}
304
305unsafe impl<T: Kind> ReadOnlyQueryData for Instance<T> {}
306
307unsafe impl<T: Kind> QueryData for Instance<T> {
308    type ReadOnly = Self;
309
310    const IS_READ_ONLY: bool = <Entity as QueryData>::IS_READ_ONLY;
311
312    const IS_ARCHETYPAL: bool = <Entity as QueryData>::IS_ARCHETYPAL;
313
314    type Item<'w, 's> = Self;
315
316    fn shrink<'wlong: 'wshort, 'wshort, 's>(
317        item: Self::Item<'wlong, 's>,
318    ) -> Self::Item<'wshort, 's> {
319        item
320    }
321
322    unsafe fn fetch<'w, 's>(
323        _state: &'s Self::State,
324        _fetch: &mut Self::Fetch<'w>,
325        entity: Entity,
326        _table_row: TableRow,
327    ) -> Option<Self::Item<'w, 's>> {
328        Some(Instance::from_entity_unchecked(entity))
329    }
330
331    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
332        // Based on impl for `Entity`
333        std::iter::empty()
334    }
335}
336
337impl<T: Kind> MapEntities for Instance<T> {
338    fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
339        self.0 = entity_mapper.get_mapped(self.0);
340    }
341}
342
343impl<T: Kind> From<Instance<T>> for Entity {
344    fn from(instance: Instance<T>) -> Self {
345        instance.entity()
346    }
347}
348
349impl<T: Kind> RelationshipSourceCollection for Instance<T> {
350    type SourceIter<'a> = <Entity as RelationshipSourceCollection>::SourceIter<'a>;
351
352    fn new() -> Self {
353        Self::PLACEHOLDER
354    }
355
356    fn with_capacity(_capacity: usize) -> Self {
357        Self::new()
358    }
359
360    fn reserve(&mut self, additional: usize) {
361        self.0.reserve(additional);
362    }
363
364    fn add(&mut self, entity: Entity) -> bool {
365        self.0.add(entity)
366    }
367
368    fn remove(&mut self, entity: Entity) -> bool {
369        self.0.remove(entity)
370    }
371
372    fn iter(&self) -> Self::SourceIter<'_> {
373        self.0.iter()
374    }
375
376    fn len(&self) -> usize {
377        self.0.len()
378    }
379
380    fn clear(&mut self) {
381        self.0.clear();
382    }
383
384    fn shrink_to_fit(&mut self) {
385        self.0.shrink_to_fit();
386    }
387
388    fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
389        self.0.extend_from_iter(entities)
390    }
391}
392
393impl From<Entity> for Instance<Any> {
394    fn from(entity: Entity) -> Self {
395        Self(entity, PhantomData)
396    }
397}
398
399impl<T: Kind> ContainsEntity for Instance<T> {
400    fn entity(&self) -> Entity {
401        self.entity()
402    }
403}
404
405/// Similar to [`ContainsEntity`], but for [`Instance<T>`].
406pub trait ContainsInstance<T: Kind> {
407    /// Returns the associated [`Instance<T>`].
408    fn instance(&self) -> Instance<T>;
409
410    /// Returns the [`Entity`] of the associated [`Instance<T>`].
411    fn entity(&self) -> Entity {
412        self.instance().entity()
413    }
414}
415
416/// A [`QueryData`] item which represents a reference to an [`Instance<T>`] and its associated [`Component`].
417///
418/// This is analogous to a `(Instance<T>, &T)` query.
419///
420/// # Usage
421/// If a [`Kind`] is also a component, it is often convenient to access the instance and component data together.
422/// This type is designed to make these queries more ergonomic.
423///
424/// You may use this type as either a [`Query`] parameter, or access it from an [`EntityRef`].
425///
426/// # Example
427/// ```
428/// # use bevy::prelude::*;
429/// # use moonshine_kind::prelude::*;
430///
431/// #[derive(Component)]
432/// struct Apple {
433///     freshness: f32,
434/// }
435///
436/// impl Apple {
437///     fn is_fresh(&self) -> bool {
438///         self.freshness >= 0.5
439///     }
440/// }
441///
442/// // Query Access:
443/// fn fresh_apples(query: Query<InstanceRef<Apple>>) -> Vec<Instance<Apple>> {
444///     query.iter()
445///         .filter_map(|apple| apple.is_fresh().then_some(apple.instance()))
446///         .collect()
447/// }
448///
449/// // Entity Access:
450/// fn fresh_apples_world<'a>(world: &'a World) -> Vec<InstanceRef<'a, Apple>> {
451///    world.try_query::<EntityRef>()
452///         .unwrap()
453///         .iter(&world)
454///         .filter_map(|entity| InstanceRef::from_entity(entity))
455///         .collect()
456/// }
457///
458/// # bevy_ecs::system::assert_is_system(fresh_apples);
459/// ```
460pub struct InstanceRef<'a, T: Component>(Instance<T>, &'a T);
461
462unsafe impl<T: Component> WorldQuery for InstanceRef<'_, T> {
463    type Fetch<'w> = <(Instance<T>, &'static T) as WorldQuery>::Fetch<'w>;
464
465    type State = <(Instance<T>, &'static T) as WorldQuery>::State;
466
467    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
468        <(Instance<T>, &T) as WorldQuery>::shrink_fetch(fetch)
469    }
470
471    unsafe fn init_fetch<'w>(
472        world: UnsafeWorldCell<'w>,
473        state: &Self::State,
474        last_run: Tick,
475        this_run: Tick,
476    ) -> Self::Fetch<'w> {
477        <(Instance<T>, &T) as WorldQuery>::init_fetch(world, state, last_run, this_run)
478    }
479
480    const IS_DENSE: bool = <(Instance<T>, &T) as WorldQuery>::IS_DENSE;
481
482    unsafe fn set_archetype<'w>(
483        fetch: &mut Self::Fetch<'w>,
484        state: &Self::State,
485        archetype: &'w Archetype,
486        table: &'w Table,
487    ) {
488        <(Instance<T>, &T) as WorldQuery>::set_archetype(fetch, state, archetype, table)
489    }
490
491    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
492        <(Instance<T>, &T) as WorldQuery>::set_table(fetch, state, table)
493    }
494
495    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
496        <(Instance<T>, &T) as WorldQuery>::update_component_access(state, access)
497    }
498
499    fn init_state(world: &mut World) -> Self::State {
500        <(Instance<T>, &T) as WorldQuery>::init_state(world)
501    }
502
503    fn get_state(components: &Components) -> Option<Self::State> {
504        <(Instance<T>, &T) as WorldQuery>::get_state(components)
505    }
506
507    fn matches_component_set(
508        state: &Self::State,
509        set_contains_id: &impl Fn(ComponentId) -> bool,
510    ) -> bool {
511        <(Instance<T>, &T) as WorldQuery>::matches_component_set(state, set_contains_id)
512    }
513}
514
515unsafe impl<T: Component> QueryData for InstanceRef<'_, T> {
516    type ReadOnly = Self;
517
518    const IS_READ_ONLY: bool = true;
519
520    const IS_ARCHETYPAL: bool = <&'static T as QueryData>::IS_ARCHETYPAL;
521
522    type Item<'w, 's> = InstanceRef<'w, T>;
523
524    fn shrink<'wlong: 'wshort, 'wshort, 's>(
525        item: Self::Item<'wlong, 's>,
526    ) -> Self::Item<'wshort, 's> {
527        InstanceRef(item.0, item.1)
528    }
529
530    unsafe fn fetch<'w, 's>(
531        state: &'s Self::State,
532        fetch: &mut Self::Fetch<'w>,
533        entity: Entity,
534        table_row: TableRow,
535    ) -> Option<Self::Item<'w, 's>> {
536        <(Instance<T>, &T) as QueryData>::fetch(state, fetch, entity, table_row)
537            .map(|(instance, data)| InstanceRef(instance, data))
538    }
539
540    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
541        <(Instance<T>, &T) as QueryData>::iter_access(state)
542    }
543}
544
545unsafe impl<T: Component> IterQueryData for InstanceRef<'_, T> {}
546
547unsafe impl<T: Component> ReadOnlyQueryData for InstanceRef<'_, T> {}
548
549impl<'a, T: Component> InstanceRef<'a, T> {
550    /// Creates a new [`InstanceRef<T>`] from an [`EntityRef`] if it contains a given [`Component`] of type `T`.
551    pub fn from_entity(entity: EntityRef<'a>) -> Option<Self> {
552        Some(Self(
553            // SAFE: Kind is validated by `entity.get()` above.
554            unsafe { Instance::from_entity_unchecked(entity.id()) },
555            entity.get()?,
556        ))
557    }
558
559    /// Creates a new [`InstanceRef<T>`] from [`EntityRef`] without any validation.
560    ///
561    /// # Safety
562    /// Assumes `entity` is a valid instance of kind `T`.
563    pub unsafe fn from_entity_unchecked(entity: EntityRef<'a>) -> Self {
564        Self(
565            Instance::from_entity_unchecked(entity.id()),
566            entity.get().unwrap(),
567        )
568    }
569}
570
571impl<T: Component> Clone for InstanceRef<'_, T> {
572    fn clone(&self) -> Self {
573        *self
574    }
575}
576
577impl<T: Component> Copy for InstanceRef<'_, T> {}
578
579impl<T: Component> From<InstanceRef<'_, T>> for Instance<T> {
580    fn from(item: InstanceRef<T>) -> Self {
581        item.instance()
582    }
583}
584
585impl<T: Component> From<&InstanceRef<'_, T>> for Instance<T> {
586    fn from(item: &InstanceRef<T>) -> Self {
587        item.instance()
588    }
589}
590
591impl<T: Component> PartialEq for InstanceRef<'_, T> {
592    fn eq(&self, other: &Self) -> bool {
593        self.0 == other.0
594    }
595}
596
597impl<T: Component> PartialEq<Entity> for InstanceRef<'_, T> {
598    fn eq(&self, other: &Entity) -> bool {
599        self.0 == *other
600    }
601}
602
603impl<T: Component> PartialEq<InstanceRef<'_, T>> for Entity {
604    fn eq(&self, other: &InstanceRef<'_, T>) -> bool {
605        other == self
606    }
607}
608
609impl<T: Component, U: Component> PartialEq<Instance<U>> for InstanceRef<'_, T>
610where
611    U: CastInto<T>,
612{
613    fn eq(&self, other: &Instance<U>) -> bool {
614        *self.0 == *other
615    }
616}
617
618impl<T: Component, U: Component> PartialEq<InstanceRef<'_, U>> for Instance<T>
619where
620    U: CastInto<T>,
621{
622    fn eq(&self, other: &InstanceRef<'_, U>) -> bool {
623        *self == other.instance()
624    }
625}
626
627impl<T: Component> Eq for InstanceRef<'_, T> {}
628
629impl<T: Component> Deref for InstanceRef<'_, T> {
630    type Target = T;
631
632    fn deref(&self) -> &Self::Target {
633        self.1
634    }
635}
636
637impl<T: Component> AsRef<Instance<T>> for InstanceRef<'_, T> {
638    fn as_ref(&self) -> &Instance<T> {
639        &self.0
640    }
641}
642
643impl<T: Component> AsRef<T> for InstanceRef<'_, T> {
644    fn as_ref(&self) -> &T {
645        self.1
646    }
647}
648
649impl<T: Component> ContainsInstance<T> for InstanceRef<'_, T> {
650    fn instance(&self) -> Instance<T> {
651        self.0
652    }
653}
654
655/// A [`QueryData`] item which represents a mutable reference to an [`Instance<T>`] and its associated [`Component`].
656///
657/// This is analogous to a `(Instance<T>, &mut T)` query.
658///
659/// # Usage
660/// This type behaves similar like [`InstanceRef<T>`] but allows mutable access to its associated [`Component`].
661///
662/// The main difference is that you cannot create an [`InstanceMut<T>`] from an [`EntityMut`].
663/// See [`InstanceMut::from_entity`] for more details.
664///
665/// See [`InstanceRef<T>`] for more information and examples.
666pub struct InstanceMut<'a, T: Component>(Instance<T>, Mut<'a, T>);
667
668unsafe impl<T: Component> WorldQuery for InstanceMut<'_, T> {
669    type Fetch<'w> = <(Instance<T>, &'static mut T) as WorldQuery>::Fetch<'w>;
670
671    type State = <(Instance<T>, &'static mut T) as WorldQuery>::State;
672
673    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
674        <(Instance<T>, &mut T) as WorldQuery>::shrink_fetch(fetch)
675    }
676
677    unsafe fn init_fetch<'w>(
678        world: UnsafeWorldCell<'w>,
679        state: &Self::State,
680        last_run: Tick,
681        this_run: Tick,
682    ) -> Self::Fetch<'w> {
683        <(Instance<T>, &mut T) as WorldQuery>::init_fetch(world, state, last_run, this_run)
684    }
685
686    const IS_DENSE: bool = <(Instance<T>, &T) as WorldQuery>::IS_DENSE;
687
688    unsafe fn set_archetype<'w>(
689        fetch: &mut Self::Fetch<'w>,
690        state: &Self::State,
691        archetype: &'w Archetype,
692        table: &'w Table,
693    ) {
694        <(Instance<T>, &mut T) as WorldQuery>::set_archetype(fetch, state, archetype, table)
695    }
696
697    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
698        <(Instance<T>, &mut T) as WorldQuery>::set_table(fetch, state, table)
699    }
700
701    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
702        <(Instance<T>, &T) as WorldQuery>::update_component_access(state, access)
703    }
704
705    fn init_state(world: &mut World) -> Self::State {
706        <(Instance<T>, &T) as WorldQuery>::init_state(world)
707    }
708
709    fn get_state(components: &Components) -> Option<Self::State> {
710        <(Instance<T>, &T) as WorldQuery>::get_state(components)
711    }
712
713    fn matches_component_set(
714        state: &Self::State,
715        set_contains_id: &impl Fn(ComponentId) -> bool,
716    ) -> bool {
717        <(Instance<T>, &T) as WorldQuery>::matches_component_set(state, set_contains_id)
718    }
719}
720
721unsafe impl<'b, T: Component<Mutability = Mutable>> QueryData for InstanceMut<'b, T> {
722    type ReadOnly = InstanceRef<'b, T>;
723
724    const IS_READ_ONLY: bool = false;
725
726    const IS_ARCHETYPAL: bool = <&'static mut T as QueryData>::IS_ARCHETYPAL;
727
728    type Item<'w, 's> = InstanceMut<'w, T>;
729
730    fn shrink<'wlong: 'wshort, 'wshort, 's>(
731        item: Self::Item<'wlong, 's>,
732    ) -> Self::Item<'wshort, 's> {
733        InstanceMut(item.0, item.1)
734    }
735
736    unsafe fn fetch<'w, 's>(
737        state: &'s Self::State,
738        fetch: &mut Self::Fetch<'w>,
739        entity: Entity,
740        table_row: TableRow,
741    ) -> Option<Self::Item<'w, 's>> {
742        <(Instance<T>, &mut T) as QueryData>::fetch(state, fetch, entity, table_row)
743            .map(|(instance, data)| InstanceMut(instance, data))
744    }
745
746    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
747        <(Instance<T>, &mut T) as QueryData>::iter_access(state)
748    }
749}
750
751impl<'a, T: Component<Mutability = Mutable>> InstanceMut<'a, T> {
752    /// Creates a new [`InstanceMut<T>`] from an [`EntityWorldMut`] if it contains a given [`Component`] of type `T`.
753    pub fn from_entity(entity: EntityMut<'a>) -> Option<Self> {
754        let id = entity.id();
755        let data = entity.into_mut()?;
756        Some(Self(
757            // SAFE: Kind is validated by `entity.get_mut()` above.
758            unsafe { Instance::from_entity_unchecked(id) },
759            data,
760        ))
761    }
762
763    /// Creates a new [`InstanceMut<T>`] from an [`EntityMut`] without any validation.
764    ///
765    /// # Safety
766    /// Assumes `entity` is a valid instance of kind `T`.
767    pub unsafe fn from_entity_unchecked(entity: EntityMut<'a>) -> Self {
768        let id = entity.id();
769        let data = entity.into_mut().unwrap();
770        Self(Instance::from_entity_unchecked(id), data)
771    }
772}
773
774impl<T: Component> From<InstanceMut<'_, T>> for Instance<T> {
775    fn from(item: InstanceMut<T>) -> Self {
776        item.instance()
777    }
778}
779
780impl<T: Component> From<&InstanceMut<'_, T>> for Instance<T> {
781    fn from(item: &InstanceMut<T>) -> Self {
782        item.instance()
783    }
784}
785
786impl<T: Component> PartialEq for InstanceMut<'_, T> {
787    fn eq(&self, other: &Self) -> bool {
788        self.0 == other.0
789    }
790}
791
792impl<T: Component> PartialEq<Entity> for InstanceMut<'_, T> {
793    fn eq(&self, other: &Entity) -> bool {
794        self.0 == *other
795    }
796}
797
798impl<T: Component> PartialEq<InstanceMut<'_, T>> for Entity {
799    fn eq(&self, other: &InstanceMut<'_, T>) -> bool {
800        other == self
801    }
802}
803
804impl<T: Component, U: Component> PartialEq<Instance<U>> for InstanceMut<'_, T>
805where
806    U: CastInto<T>,
807{
808    fn eq(&self, other: &Instance<U>) -> bool {
809        *self.0 == *other
810    }
811}
812
813impl<T: Component, U: Component> PartialEq<InstanceMut<'_, U>> for Instance<T>
814where
815    U: CastInto<T>,
816{
817    fn eq(&self, other: &InstanceMut<'_, U>) -> bool {
818        *self == other.instance()
819    }
820}
821
822impl<T: Component> Eq for InstanceMut<'_, T> {}
823
824impl<T: Component> Deref for InstanceMut<'_, T> {
825    type Target = T;
826
827    fn deref(&self) -> &Self::Target {
828        self.1.as_ref()
829    }
830}
831
832impl<T: Component> DerefMut for InstanceMut<'_, T> {
833    fn deref_mut(&mut self) -> &mut Self::Target {
834        self.1.as_mut()
835    }
836}
837
838impl<T: Component> AsRef<Instance<T>> for InstanceMut<'_, T> {
839    fn as_ref(&self) -> &Instance<T> {
840        &self.0
841    }
842}
843
844impl<T: Component> AsRef<T> for InstanceMut<'_, T> {
845    fn as_ref(&self) -> &T {
846        self.1.as_ref()
847    }
848}
849
850impl<T: Component> AsMut<T> for InstanceMut<'_, T> {
851    fn as_mut(&mut self) -> &mut T {
852        self.1.as_mut()
853    }
854}
855
856impl<T: Component> DetectChanges for InstanceMut<'_, T> {
857    fn is_added(&self) -> bool {
858        self.1.is_added()
859    }
860
861    fn is_changed(&self) -> bool {
862        self.1.is_changed()
863    }
864
865    fn last_changed(&self) -> Tick {
866        self.1.last_changed()
867    }
868
869    fn added(&self) -> Tick {
870        self.1.added()
871    }
872
873    fn changed_by(&self) -> MaybeLocation {
874        self.1.changed_by()
875    }
876
877    fn is_added_after(&self, other: Tick) -> bool {
878        self.1.is_added_after(other)
879    }
880
881    fn is_changed_after(&self, other: Tick) -> bool {
882        self.1.is_changed_after(other)
883    }
884}
885
886impl<T: Component> DetectChangesMut for InstanceMut<'_, T> {
887    type Inner = T;
888
889    fn set_changed(&mut self) {
890        self.1.set_changed();
891    }
892
893    fn set_last_changed(&mut self, last_changed: Tick) {
894        self.1.set_last_changed(last_changed);
895    }
896
897    fn bypass_change_detection(&mut self) -> &mut Self::Inner {
898        self.1.bypass_change_detection()
899    }
900
901    fn set_added(&mut self) {
902        self.1.set_added();
903    }
904
905    fn set_last_added(&mut self, last_added: Tick) {
906        self.1.set_last_added(last_added);
907    }
908}
909
910impl<T: Component> ContainsInstance<T> for InstanceMut<'_, T> {
911    fn instance(&self) -> Instance<T> {
912        self.0
913    }
914}
915
916/// Extension trait to access [`InstanceCommands<T>`] from [`Commands`].
917///
918/// See [`InstanceCommands`] for more information.
919pub trait GetInstanceCommands<T: Kind> {
920    /// Returns the [`InstanceCommands<T>`] for an [`Instance<T>`].
921    fn instance(&mut self, instance: Instance<T>) -> InstanceCommands<'_, T>;
922}
923
924impl<T: Kind> GetInstanceCommands<T> for Commands<'_, '_> {
925    fn instance(&mut self, instance: Instance<T>) -> InstanceCommands<'_, T> {
926        InstanceCommands(self.entity(instance.entity()), PhantomData)
927    }
928}
929
930/// [`EntityCommands`] with kind semantics.
931///
932/// # Usage
933/// On its own, this type is not very useful. Instead, it is designed to be extended using traits.
934/// This allows you to design commands for a specific kind of an entity in a type-safe manner.
935///
936/// # Example
937/// ```
938/// # use bevy::prelude::*;
939/// # use moonshine_kind::prelude::*;
940///
941/// #[derive(Component)]
942/// struct Apple;
943///
944/// #[derive(Component)]
945/// struct Eat;
946///
947/// trait EatApple {
948///     fn eat(&mut self);
949/// }
950///
951/// impl EatApple for InstanceCommands<'_, Apple> {
952///     fn eat(&mut self) {
953///         info!("Crunch!");
954///         self.despawn();
955///     }
956/// }
957///
958/// fn eat_apples(apples: Query<Instance<Apple>, With<Eat>>, mut commands: Commands) {
959///     for apple in apples.iter() {
960///         commands.instance(apple).eat();
961///     }
962/// }
963///
964/// # bevy_ecs::system::assert_is_system(eat_apples);
965pub struct InstanceCommands<'a, T: Kind>(EntityCommands<'a>, PhantomData<T>);
966
967impl<'a, T: Kind> InstanceCommands<'a, T> {
968    /// Creates a new [`InstanceCommands<T>`] from [`EntityCommands`] without any validation.
969    ///
970    /// # Safety
971    /// Assumes `entity` is a valid instance of kind `T`.
972    pub unsafe fn from_entity_unchecked(entity: EntityCommands<'a>) -> Self {
973        Self(entity, PhantomData)
974    }
975
976    /// Creates a new [`InstanceCommands<T>`] from [`EntityRef`] if it contains a [`Component`] of type `T`.
977    pub fn from_entity(entity: EntityRef, commands: &'a mut Commands) -> Option<Self>
978    where
979        T: Component,
980    {
981        if entity.contains::<T>() {
982            Some(Self(commands.entity(entity.id()), PhantomData))
983        } else {
984            None
985        }
986    }
987
988    /// Returns the associated [`Instance<T>`].
989    pub fn instance(&self) -> Instance<T> {
990        // SAFE: `self.entity()` must be a valid instance of kind `T`.
991        unsafe { Instance::from_entity_unchecked(self.id()) }
992    }
993
994    /// Returns the associated [`EntityCommands`].
995    pub fn as_entity(&mut self) -> &mut EntityCommands<'a> {
996        &mut self.0
997    }
998
999    /// Equivalent to [`EntityCommands::insert`], but it returns `self` to maintain kind semantics.
1000    pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
1001        self.0.insert(bundle);
1002        self
1003    }
1004
1005    /// Equivalent to [`EntityCommands::insert`], but it returns `self` to maintain kind semantics.
1006    pub fn remove<U: Component>(&mut self) -> &mut Self {
1007        self.0.remove::<U>();
1008        self
1009    }
1010
1011    /// Equivalent to [`EntityCommands::try_insert`], but it returns `self` to maintain kind semantics.
1012    pub fn try_remove<U: Component>(&mut self) -> &mut Self {
1013        self.0.try_remove::<U>();
1014        self
1015    }
1016
1017    /// Returns an [`InstanceCommands`] with a smaller lifetime.
1018    ///
1019    /// This is useful if you have `&mut InstanceCommands` but you need `InstanceCommands`.
1020    pub fn reborrow(&mut self) -> InstanceCommands<'_, T> {
1021        InstanceCommands(self.0.reborrow(), PhantomData)
1022    }
1023
1024    /// Converts this [`InstanceCommands<T>`] into an [`InstanceCommands<U>`], given that `T` implements [`CastInto<U>`].
1025    pub fn cast_into<U: Kind>(self) -> InstanceCommands<'a, U>
1026    where
1027        T: CastInto<U>,
1028    {
1029        // SAFE: `CastInto<U>` is implemented for `T`.
1030        unsafe { InstanceCommands::from_entity_unchecked(self.0) }
1031    }
1032}
1033
1034impl<'a, T: Kind> From<InstanceCommands<'a, T>> for Instance<T> {
1035    fn from(commands: InstanceCommands<'a, T>) -> Self {
1036        commands.instance()
1037    }
1038}
1039
1040impl<'a, T: Kind> From<&InstanceCommands<'a, T>> for Instance<T> {
1041    fn from(commands: &InstanceCommands<'a, T>) -> Self {
1042        commands.instance()
1043    }
1044}
1045
1046impl<'a, T: Kind> Deref for InstanceCommands<'a, T> {
1047    type Target = EntityCommands<'a>;
1048
1049    fn deref(&self) -> &Self::Target {
1050        &self.0
1051    }
1052}
1053
1054impl<T: Kind> DerefMut for InstanceCommands<'_, T> {
1055    fn deref_mut(&mut self) -> &mut Self::Target {
1056        &mut self.0
1057    }
1058}
1059
1060impl<T: Kind> ContainsInstance<T> for InstanceCommands<'_, T> {
1061    fn instance(&self) -> Instance<T> {
1062        self.instance()
1063    }
1064}
1065
1066/// A macro which implements [`EntityEvent`] from an [`Instance<T>`].
1067///
1068/// This is useful when you have an [`EntityEvent`] which refers to its target by [`Instance<T>`].
1069///
1070/// ```
1071/// use bevy::prelude::*;
1072/// use bevy::ecs::event::EntityTrigger;
1073/// use moonshine_kind::prelude::*;
1074/// use moonshine_kind::impl_entity_event_from_instance;
1075///
1076/// #[derive(Component)]
1077/// struct Fruit;
1078///
1079/// #[derive(Event)]
1080/// #[event(trigger = EntityTrigger)]
1081/// struct Eat {
1082///     target: Instance<Fruit>
1083/// }
1084///
1085/// impl_entity_event_from_instance!(Eat { .target, .. });
1086///
1087/// let mut world = World::new();
1088/// let fruit = world.spawn_instance(Fruit).instance();
1089/// world.trigger_with(Eat { target: fruit }, EntityTrigger);
1090/// ```
1091#[macro_export]
1092macro_rules! impl_entity_event_from_instance {
1093    ($name:ident < $($gen:tt),+ $(,)? > $(where $($where:tt)+)? ) => {
1094        $crate::impl_entity_event_from_instance!($name<$($gen),+> { .instance, .. } $(where $($where)+)?);
1095    };
1096
1097    ($name:ident < $($gen:tt),+ $(,)? > { .$field:ident, .. } $(where $($where:tt)+)? ) => {
1098        impl<$($gen),+> EntityEvent for $name<$($gen),+>
1099        $(where $($where)+)? {
1100            fn event_target(&self) -> Entity {
1101                self.$field.entity()
1102            }
1103        }
1104    };
1105
1106    ($name:ident) => {
1107        $crate::impl_entity_event_from_instance!($name { .instance, .. });
1108    };
1109
1110    ($name:ident { .$field:ident, .. }) => {
1111        impl EntityEvent for $name {
1112            fn event_target(&self) -> Entity {
1113                self.$field.entity()
1114            }
1115        }
1116
1117    }
1118}
1119
1120#[test]
1121fn test_impl_entity_event_from_instance() {
1122    #![allow(unused)]
1123
1124    #[derive(Event)]
1125    struct Foo {
1126        instance: Instance<Any>,
1127    }
1128
1129    #[derive(Event)]
1130    struct Bar {
1131        inst: Instance<Any>,
1132    }
1133
1134    #[derive(Event)]
1135    struct Baz<T: Kind> {
1136        instance: Instance<T>,
1137    }
1138
1139    #[derive(Event)]
1140    struct Bat<T: Kind> {
1141        inst: Instance<T>,
1142    }
1143
1144    impl_entity_event_from_instance!(Foo);
1145    impl_entity_event_from_instance!(Bar { .inst, .. });
1146    impl_entity_event_from_instance!(Baz<T> where T: Kind);
1147    impl_entity_event_from_instance!(Bat<T> { .inst, .. } where T: Kind);
1148}
1149
1150// Experimental
1151#[doc(hidden)]
1152#[derive(Deref, DerefMut, Reflect)]
1153pub struct InstanceVec<T: Kind>(Vec<Instance<T>>);
1154
1155impl<T: Kind> Default for InstanceVec<T> {
1156    fn default() -> Self {
1157        Self(Vec::new())
1158    }
1159}
1160
1161impl<T: Kind> InstanceVec<T> {
1162    #[doc(hidden)]
1163    pub fn with_capacity(capacity: usize) -> Self {
1164        Self(Vec::with_capacity(capacity))
1165    }
1166}
1167
1168impl<T: Kind> MapEntities for InstanceVec<T> {
1169    fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
1170        let olds: Vec<_> = self.0.drain(..).collect();
1171        for old in olds {
1172            let new_entity = entity_mapper.get_mapped(old.entity());
1173            // SAFE: In Deserializer, we trust.
1174            let new = unsafe { Instance::from_entity_unchecked(new_entity) };
1175            self.0.push(new);
1176        }
1177    }
1178}
1179
1180impl<T: Kind> RelationshipSourceCollection for InstanceVec<T> {
1181    type SourceIter<'a>
1182        = std::iter::Map<std::slice::Iter<'a, Instance<T>>, fn(&Instance<T>) -> Entity>
1183    where
1184        Self: 'a;
1185
1186    fn new() -> Self {
1187        Self::default()
1188    }
1189
1190    fn with_capacity(capacity: usize) -> Self {
1191        Self::with_capacity(capacity)
1192    }
1193
1194    fn reserve(&mut self, additional: usize) {
1195        self.0.reserve(additional);
1196    }
1197
1198    fn add(&mut self, entity: Entity) -> bool {
1199        self.0
1200            .push(unsafe { Instance::from_entity_unchecked(entity) });
1201        true
1202    }
1203
1204    fn remove(&mut self, entity: Entity) -> bool {
1205        let Some(index) = self.0.iter().position(|i| *i == entity) else {
1206            return false;
1207        };
1208        self.0.swap_remove(index);
1209        true
1210    }
1211
1212    fn iter(&self) -> Self::SourceIter<'_> {
1213        self.0.iter().map(|i| i.entity())
1214    }
1215
1216    fn len(&self) -> usize {
1217        self.0.len()
1218    }
1219
1220    fn clear(&mut self) {
1221        self.0.clear()
1222    }
1223
1224    fn shrink_to_fit(&mut self) {
1225        self.0.shrink_to_fit()
1226    }
1227
1228    fn extend_from_iter(&mut self, entities: impl IntoIterator<Item = Entity>) {
1229        self.0.extend(
1230            entities
1231                .into_iter()
1232                .map(|entity| unsafe { Instance::from_entity_unchecked(entity) }),
1233        )
1234    }
1235}
1236
1237#[cfg(test)]
1238mod test_instance_vec {
1239    use super::*;
1240
1241    // In a world, where the relationship:
1242    //      Friends(Vec<Instance<Person>>) <-> FriendOf(Instance<Person>)
1243    // Cannot exist due to Bevy derive requirements and Rust trait implementation restrictions...
1244    // This is a workaround to sort of guarantee kind safety:
1245
1246    use bevy::prelude::*;
1247    use moonshine_util::expect::Expect; // <--- Required for this pattern to work.
1248
1249    use crate::prelude::*;
1250
1251    // Marker to "guarantee" kind safety across related components:
1252    #[derive(Component)]
1253    struct Person;
1254
1255    // A potato is not a person. It doesn't have friends. :(
1256    #[derive(Component)]
1257    struct Potato;
1258
1259    #[derive(Component, Deref)]
1260    #[require(Expect<Person>)] // <--- Only People can have Friends
1261    #[relationship_target(relationship = FriendOf)]
1262    struct Friends(
1263        // Wrapper around `Vec<Instance<Person>>` to implement `RelationshipSourceCollection`
1264        InstanceVec<Person>,
1265    );
1266
1267    #[derive(Component)]
1268    #[require(Expect<Person>)] // <--- Only People become Friends
1269    #[relationship(relationship_target = Friends)]
1270    struct FriendOf(
1271        // This entity can point to anything, but if it points to anything other
1272        // than a Person, it would cause a panic because both `Friends` and `FriendOf` expect `Person`.
1273        pub Entity,
1274    );
1275
1276    #[test]
1277    fn test_instance_vec_relationship() {
1278        let mut app = App::new();
1279        app.add_plugins(MinimalPlugins);
1280        let w = app.world_mut();
1281        let p0 = w.spawn_instance(Person).instance();
1282        let p1 = w.spawn_instance(Person).instance();
1283        w.entity_mut(*p1).insert(FriendOf(*p0));
1284
1285        let fs = w.get::<Friends>(*p0).expect("Person 0 must have Friends");
1286        let f: Instance<Person> = *fs.first().expect("Person 0 must have at least 1 friend");
1287        assert_eq!(f, p1, "Person 1 must be a friend of Person 0");
1288    }
1289
1290    #[test]
1291    #[should_panic]
1292    fn test_instance_vec_relationship_panic_1() {
1293        let mut app = App::new();
1294        app.add_plugins(MinimalPlugins);
1295        let w = app.world_mut();
1296        let potato = w.spawn_instance(Potato).instance();
1297        let person = w.spawn_instance(Person).instance();
1298
1299        // PANIC: Person cannot be friends with Potato. :(
1300        w.entity_mut(*person).insert(FriendOf(*potato));
1301    }
1302
1303    #[test]
1304    #[should_panic]
1305    fn test_instance_vec_relationship_panic_2() {
1306        let mut app = App::new();
1307        app.add_plugins(MinimalPlugins);
1308        let w = app.world_mut();
1309        let potato = w.spawn_instance(Potato).instance();
1310        let person = w.spawn_instance(Person).instance();
1311
1312        // PANIC: Potato cannot be friends with Person. :(
1313        w.entity_mut(*potato).insert(FriendOf(*person));
1314    }
1315}