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