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#[derive(Reflect)]
72pub struct Instance<T: Kind>(Entity, #[reflect(ignore)] PhantomData<T>);
73
74impl<T: Kind> Instance<T> {
75 pub const PLACEHOLDER: Self = Self(Entity::PLACEHOLDER, PhantomData);
77
78 pub unsafe fn from_entity_unchecked(entity: Entity) -> Self {
104 Self(entity, PhantomData)
105 }
106
107 pub fn entity(&self) -> Entity {
109 self.0
110 }
111
112 pub fn cast_into<U: Kind>(self) -> Instance<U>
117 where
118 T: CastInto<U>,
119 {
120 unsafe { T::cast(self) }
121 }
122
123 pub fn cast_into_any(self) -> Instance<Any> {
129 unsafe { self.cast_into_unchecked() }
131 }
132
133 pub unsafe fn cast_into_unchecked<U: Kind>(self) -> Instance<U> {
144 Instance::from_entity_unchecked(self.entity())
145 }
146
147 pub unsafe fn as_entity_mut(&mut self) -> &mut Entity {
152 &mut self.0
153 }
154}
155
156impl<T: Component> Instance<T> {
157 pub fn from_entity(entity: EntityRef) -> Option<Self> {
159 if entity.contains::<T>() {
160 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
392pub trait ContainsInstance<T: Kind> {
394 fn instance(&self) -> Instance<T>;
396
397 fn entity(&self) -> Entity {
399 self.instance().entity()
400 }
401}
402
403pub 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 pub fn from_entity(entity: EntityRef<'a>) -> Option<Self> {
530 Some(Self(
531 unsafe { Instance::from_entity_unchecked(entity.id()) },
533 entity.get()?,
534 ))
535 }
536
537 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
603pub 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 pub fn from_entity(entity: EntityMut<'a>) -> Option<Self> {
697 let id = entity.id();
698 let data = entity.into_mut()?;
699 Some(Self(
700 unsafe { Instance::from_entity_unchecked(id) },
702 data,
703 ))
704 }
705
706 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
821pub trait GetInstanceCommands<T: Kind> {
825 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
835pub struct InstanceCommands<'a, T: Kind>(EntityCommands<'a>, PhantomData<T>);
871
872impl<'a, T: Kind> InstanceCommands<'a, T> {
873 pub unsafe fn from_entity_unchecked(entity: EntityCommands<'a>) -> Self {
878 Self(entity, PhantomData)
879 }
880
881 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 pub fn instance(&self) -> Instance<T> {
895 unsafe { Instance::from_entity_unchecked(self.id()) }
897 }
898
899 pub fn as_entity(&mut self) -> &mut EntityCommands<'a> {
901 &mut self.0
902 }
903
904 pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
906 self.0.insert(bundle);
907 self
908 }
909
910 pub fn remove<U: Component>(&mut self) -> &mut Self {
912 self.0.remove::<U>();
913 self
914 }
915
916 pub fn try_remove<U: Component>(&mut self) -> &mut Self {
918 self.0.try_remove::<U>();
919 self
920 }
921
922 pub fn reborrow(&mut self) -> InstanceCommands<'_, T> {
926 InstanceCommands(self.0.reborrow(), PhantomData)
927 }
928
929 pub fn cast_into<U: Kind>(self) -> InstanceCommands<'a, U>
931 where
932 T: CastInto<U>,
933 {
934 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