my_ecs/ecs/sys/
select.rs

1use crate::{
2    ds::{
3        ATypeId, Borrowed, FlatIter, FlatIterMut, Getter, GetterMut, ManagedConstPtr, NonNullExt,
4        ParFlatIter, ParFlatIterMut, RawGetter, SendSyncPtr,
5    },
6    ecs::ent::{
7        component::{Component, ComponentKey, Components},
8        entity::{ContainEntity, Entity, EntityIndex, EntityName, EntityTag},
9        storage::EntityContainerRef,
10    },
11    util::{
12        macros::{
13            impl_into_iterator_for_parallel, impl_parallel_iterator, impl_unindexed_producer,
14        },
15        TakeRecur,
16    },
17};
18use rayon::iter::{plumbing::Producer, IntoParallelIterator};
19use std::{
20    any, fmt, iter,
21    marker::PhantomData,
22    ops::{Deref, DerefMut},
23    ptr::NonNull,
24    sync::Arc,
25};
26
27pub(crate) trait StoreSelectInfo: StoreFilterInfo {
28    fn contains(&self, key: &SelectKey) -> bool;
29    fn get(&self, key: &SelectKey) -> Option<&Arc<SelectInfo>>;
30    fn insert(&mut self, key: SelectKey, info: Arc<SelectInfo>);
31}
32
33pub(crate) trait StoreFilterInfo {
34    fn contains(&self, key: &FilterKey) -> bool;
35    fn get(&self, key: &FilterKey) -> Option<&Arc<FilterInfo>>;
36    fn insert(&mut self, key: FilterKey, info: Arc<FilterInfo>);
37}
38
39/// A trait for selecting a certain [`Target`](Select::Target) from entities
40/// that meet [`All`](Filter::All), [`Any`](Filter::Any), and
41/// [`None`](Filter::None) conditions.
42///
43/// # Example
44///
45/// ```ignore
46/// # use my_ecs::prelude::*;
47///
48/// #[derive(Component)] struct Ca;
49/// #[derive(Component)] struct Cb;
50/// #[derive(Component)] struct Cc;
51/// #[derive(Component)] struct Cd;
52///
53/// struct Sa;
54/// impl Select for Sa {
55///     type Target = Ca;
56///     type Filter = Fa;
57/// }
58/// struct Fa;
59/// impl Filter for Fa {
60///     type All = Cb;
61///     type Any = (Cc, Cd);
62///     type None = ();
63/// }
64///
65/// // Or simply
66/// filter!(Sb, Target = Ca, All = Cb, Any = (Cc, Cd));
67/// ```
68#[allow(private_interfaces, private_bounds)]
69pub trait Select: 'static {
70    type Target: Component;
71    type Filter: Filter;
72
73    #[doc(hidden)]
74    fn key() -> SelectKey {
75        SelectKey::of::<Self>()
76    }
77
78    #[doc(hidden)]
79    fn get_info_from<S>(stor: &mut S) -> &Arc<SelectInfo>
80    where
81        S: StoreSelectInfo + StoreFilterInfo + ?Sized,
82    {
83        let key = Self::key();
84
85        if !StoreSelectInfo::contains(stor, &key) {
86            let sinfo = Arc::new(Self::info_from(stor));
87            StoreSelectInfo::insert(stor, key, sinfo);
88        }
89
90        // Safety: Inserted right before.
91        unsafe { StoreSelectInfo::get(stor, &key).unwrap_unchecked() }
92    }
93
94    #[doc(hidden)]
95    fn info_from<S>(stor: &mut S) -> SelectInfo
96    where
97        S: StoreFilterInfo + ?Sized,
98    {
99        let target = ComponentKey::of::<Self::Target>();
100        let finfo = Arc::clone(Self::Filter::get_info_from(stor));
101        let name = any::type_name::<Self>();
102        SelectInfo::new(target, finfo, name)
103    }
104}
105
106/// A trait for selecting certain entities that meet [`All`](Filter::All),
107/// [`Any`](Filter::Any), and [`None`](Filter::None) conditions.
108///
109/// # Example
110///
111/// ```ignore
112/// # use my_ecs::prelude::*;
113///
114/// #[derive(Component)] struct Ca;
115/// #[derive(Component)] struct Cb;
116/// #[derive(Component)] struct Cc;
117/// #[derive(Component)] struct Cd;
118///
119/// /// Filtering using All, Any, and None.
120/// struct Fa;
121/// impl Filter for Fa {
122///     type All = Ca;
123///     type Any = (Cb, Cc);
124///     type None = Cd;
125///     type Exact = ();
126/// }
127///
128/// // Or simply
129/// filter!(Fb, All = Ca, Any = (Cb, Cc));
130///
131/// /// Filtering using Exact.
132/// struct Fb;
133/// impl Filter for Fc {
134///     type All = ();
135///     type Any = ();
136///     type None = ();
137///     type Exact = (Ca, Cb);
138/// }
139///
140/// // Or simply
141/// filter!(Fd, Exact = (Ca, Cb));
142/// ```
143#[allow(private_interfaces, private_bounds)]
144pub trait Filter: 'static {
145    /// A [`Component`] group to select entities that contains all components in
146    /// this group. It's something like *AND* condition. But if `All` is empty,
147    /// then any entities won't be rejected.
148    type All: Components;
149
150    /// A [`Component`] group to select entities that contains any components in
151    /// this group. It's something like *OR* condition. But if `Any` is empty,
152    /// then any entities won't be rejected.
153    type Any: Components;
154
155    /// A [`Component`] group to select entities that don't contain any
156    /// components in this group. It's something like *NOR* condition. Buf if
157    /// `None` is empty, then any entities won't be rejected.
158    type None: Components;
159
160    /// A [`Component`] group to select a specific entity that consists of
161    /// components in this group exactly.
162    type Exact: Components;
163
164    #[doc(hidden)]
165    fn key() -> FilterKey {
166        FilterKey::of::<Self>()
167    }
168
169    #[doc(hidden)]
170    fn all_any_none() -> [Box<[ComponentKey]>; 3] {
171        let all: Box<[ComponentKey]> = Self::All::keys().as_ref().into();
172        let any: Box<[ComponentKey]> = Self::Any::keys().as_ref().into();
173        let none: Box<[ComponentKey]> = Self::None::keys().as_ref().into();
174        [all, any, none]
175    }
176
177    #[doc(hidden)]
178    fn get_info_from<S>(stor: &mut S) -> &Arc<FilterInfo>
179    where
180        S: StoreFilterInfo + ?Sized,
181    {
182        let key = Self::key();
183
184        if !stor.contains(&key) {
185            let sinfo = Arc::new(Self::info());
186            stor.insert(key, sinfo);
187        }
188
189        // Safety: Inserted right before.
190        unsafe { stor.get(&key).unwrap_unchecked() }
191    }
192
193    #[doc(hidden)]
194    fn info() -> FilterInfo {
195        let [all, any, none] = Self::all_any_none();
196        let exact = Self::Exact::keys().as_ref().into();
197        let name = any::type_name::<Self>();
198        FilterInfo::new(all, any, none, exact, name)
199    }
200}
201
202/// An [`Entity`] is an exact [`Filter`].
203impl<T: Entity> Filter for T {
204    type All = ();
205    type Any = ();
206    type None = ();
207    type Exact = T;
208}
209
210/// Unique identifier for a type implementing [`Select`].
211pub(crate) type SelectKey = ATypeId<SelectKey_>;
212pub(crate) struct SelectKey_;
213
214/// Unique identifier for a type implementing [`Filter`].
215pub(crate) type FilterKey = ATypeId<FilterKey_>;
216pub(crate) struct FilterKey_;
217
218#[derive(Clone)]
219pub(crate) struct SelectInfo {
220    target: ComponentKey,
221    finfo: Arc<FilterInfo>,
222    name: &'static str,
223}
224
225impl fmt::Debug for SelectInfo {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        f.debug_struct("SelectInfo")
228            .field("name", &self.name())
229            .field("target", &self.target())
230            .field("finfo", &self.filter_info())
231            .finish()
232    }
233}
234
235impl SelectInfo {
236    const fn new(target: ComponentKey, finfo: Arc<FilterInfo>, name: &'static str) -> Self {
237        Self {
238            target,
239            finfo,
240            name,
241        }
242    }
243
244    pub(crate) const fn target(&self) -> &ComponentKey {
245        &self.target
246    }
247
248    pub(crate) const fn filter_info(&self) -> &Arc<FilterInfo> {
249        &self.finfo
250    }
251
252    pub(crate) const fn name(&self) -> &'static str {
253        self.name
254    }
255
256    pub(crate) fn filter<F>(&self, contains: F, num_columns: usize) -> bool
257    where
258        F: Fn(&ComponentKey) -> bool,
259    {
260        contains(self.target()) && self.finfo.filter(contains, num_columns)
261    }
262
263    /// Determines that the given selector is disjoint with this selector.
264    ///
265    /// Disjoint filters mean that two filters don't overlap at all.
266    /// Table below shows the disjoint conditions.
267    /// - Two have different targets.
268    /// - Two are disjoint filters.
269    pub(crate) fn is_disjoint(&self, rhs: &Self) -> bool {
270        (self.target != rhs.target) || self.finfo.is_disjoint(&rhs.finfo)
271    }
272
273    pub(crate) fn is_disjoint2(&self, rhs: &FilterInfo) -> bool {
274        self.finfo.is_disjoint(rhs)
275    }
276}
277
278#[derive(Clone)]
279pub(crate) struct FilterInfo {
280    all: Box<[ComponentKey]>,
281    any: Box<[ComponentKey]>,
282    none: Box<[ComponentKey]>,
283    exact: Box<[ComponentKey]>,
284    name: &'static str,
285}
286
287impl fmt::Debug for FilterInfo {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.debug_struct("FilterInfo")
290            .field("name", &self.name())
291            .field("all", &self.all())
292            .field("any", &self.any())
293            .field("none", &self.none())
294            .field("exact", &self.exact())
295            .finish()
296    }
297}
298
299impl FilterInfo {
300    const fn new(
301        all: Box<[ComponentKey]>,
302        any: Box<[ComponentKey]>,
303        none: Box<[ComponentKey]>,
304        exact: Box<[ComponentKey]>,
305        name: &'static str,
306    ) -> Self {
307        Self {
308            all,
309            any,
310            none,
311            exact,
312            name,
313        }
314    }
315
316    pub(crate) const fn all(&self) -> &[ComponentKey] {
317        &self.all
318    }
319
320    pub(crate) const fn any(&self) -> &[ComponentKey] {
321        &self.any
322    }
323
324    pub(crate) const fn none(&self) -> &[ComponentKey] {
325        &self.none
326    }
327
328    pub(crate) const fn exact(&self) -> &[ComponentKey] {
329        &self.exact
330    }
331
332    pub(crate) const fn name(&self) -> &'static str {
333        self.name
334    }
335
336    pub(crate) fn filter<F>(&self, contains: F, num_columns: usize) -> bool
337    where
338        F: Fn(&ComponentKey) -> bool,
339    {
340        // empty iter.all() -> returns true.
341        // empty iter.any() -> returns false.
342
343        if !self.exact.is_empty() {
344            self.exact.len() == num_columns && self.exact.iter().all(&contains)
345        } else {
346            self.all.iter().all(&contains)
347                && !self.none.iter().any(&contains)
348                && if self.any.is_empty() {
349                    true
350                } else {
351                    self.any.iter().any(contains)
352                }
353        }
354    }
355
356    /// Determines that the given filter is disjoint with this filter.
357    ///
358    /// Disjoint filters mean that two filters don't overlap at all.
359    /// Disjoint conditions are as follows.
360    pub(crate) fn is_disjoint(&self, rhs: &Self) -> bool {
361        let is_self_general = self.exact.is_empty();
362        let is_rhs_general = rhs.exact.is_empty();
363        match (is_self_general, is_rhs_general) {
364            // Exact and Exact
365            (false, false) => self.is_disjoint_exact_exact(rhs),
366            // Exact and General
367            (false, true) => rhs.is_disjoint_general_exact(self),
368            // General and Exact
369            (true, false) => self.is_disjoint_general_exact(rhs),
370            // General and General
371            (true, true) => self.is_disjoint_general_general(rhs),
372        }
373    }
374
375    /// # General vs. General disjoint conditions
376    /// - X's All intersects Y's None or vice versa.
377    /// - X's Any is a subset of Y's None or vice versa.
378    ///
379    /// | Filter | All    | None      | Any    |
380    /// | :---:  | :---:  | :---:     | :---:  |
381    /// | FA     | A, B   | C, D      | E, F   |
382    /// | FB     | ...    | A, ...    | ...    | 1. A.All intersects B.None
383    /// | FB     | ...    | B, ...    | ...    | 1. A.All intersects B.None
384    /// | FB     | C, ... | ...       | ...    | 2. A.None intersects B.All
385    /// | FB     | D, ... | ...       | ...    | 2. A.None intersects B.All
386    /// | FB     | ...    | ...       | C      | 3. B.Any is a subset of A.None
387    /// | FB     | ...    | ...       | D      | 3. B.Any is a subset of A.None
388    /// | FB     | ...    | ...       | C, D   | 3. B.Any is a subset of A.None
389    /// | FB     | ...    | E, F, ... | ...    | 4. A.Any is a subset of B.None
390    fn is_disjoint_general_general(&self, rhs: &Self) -> bool {
391        let (a_all, a_any, a_none) = (&self.all, &self.any, &self.none);
392        let (b_all, b_any, b_none) = (&rhs.all, &rhs.any, &rhs.none);
393
394        // 1. FA::All intersects FB::None
395        if a_all.iter().any(|a| b_none.contains(a)) {
396            return true;
397        }
398
399        // 2. FA::None intersects FA::All
400        if a_none.iter().any(|a| b_all.contains(a)) {
401            return true;
402        }
403
404        // 3. FB::Any is a subset of FA::None
405        if !b_any.is_empty() && b_any.iter().all(|b| a_none.contains(b)) {
406            return true;
407        }
408
409        // 4. FA::Any is a subset of FB::None
410        if !a_any.is_empty() && a_any.iter().all(|a| b_none.contains(a)) {
411            return true;
412        }
413
414        false
415    }
416
417    /// # Exact vs. filter disjoint conditions
418    ///
419    /// - Not the same one
420    fn is_disjoint_exact_exact(&self, rhs: &Self) -> bool {
421        if self.exact.len() != rhs.exact.len() {
422            return false;
423        }
424
425        self.exact.iter().any(|l| !rhs.exact.contains(l))
426    }
427
428    /// # General vs. filter disjoint conditions
429    ///
430    /// | Filter | All   | None  | Any   | Exact           |
431    /// | :---:  | :---: | :---: | :---: | :--:            |
432    /// | FA     | A, B  | C, D  | E, F  |                 |
433    /// | FB     |       |       |       | not A, ...      | // Case 1
434    /// | FB     |       |       |       | not B, ...      | // Case 1
435    /// | FB     |       |       |       | C, ...          | // Case 2
436    /// | FB     |       |       |       | D, ...          | // Case 2
437    /// | FB     |       |       |       | ... except E, F | // Case 3
438    fn is_disjoint_general_exact(&self, rhs: &Self) -> bool {
439        let (a_all, a_any, a_none) = (&self.all, &self.any, &self.none);
440        let b_exact = &rhs.exact;
441
442        // Case 1. `B` includes one not belonging `A.All`.
443        if b_exact.iter().any(|b| !a_all.contains(b)) {
444            return true;
445        }
446
447        // Case 2. `B` includes one of `A.None`.
448        if b_exact.iter().any(|b| a_none.contains(b)) {
449            return true;
450        }
451
452        // Case 3. `B` doesn't include any of `A.Any`.
453        if a_any.iter().all(|a| !b_exact.contains(a)) {
454            return true;
455        }
456
457        false
458    }
459}
460
461/// Shared references to [`Select::Target`] component arrays from multiple
462/// entities. You can get an iterator traversing over each component array via
463/// [`iter`](Self::iter). A component array belongs to a specific entity.
464#[derive(Debug)]
465pub struct Selected<'cont, Comp: 'cont> {
466    /// A struct holding borrowed component arrays and their entity tags.
467    raw: &'cont mut SelectedRaw,
468
469    /// Holds component type.
470    _marker: PhantomData<Comp>,
471}
472
473impl<'cont, Comp: 'cont> Selected<'cont, Comp> {
474    /// Creates [`Selected`] from a mutable reference to a [`SelectedRaw`].
475    /// [`SelectedRaw`] is not a container, but it's borrowing container's data,
476    /// and holding them inside [`Borrowed`]s. So we can think lifetime to the
477    /// '&mut [`SelectedRaw`]' is as if container's.
478    pub(crate) fn new(raw: &'cont mut SelectedRaw) -> Self {
479        Self {
480            raw,
481            _marker: PhantomData,
482        }
483    }
484
485    pub fn iter(&self) -> SelectedIter<'cont, Comp> {
486        SelectedIter::new(self)
487    }
488
489    pub fn par_iter(&self) -> ParSelectedIter<'cont, Comp> {
490        ParSelectedIter(self.iter())
491    }
492
493    pub(crate) fn as_raw(&self) -> &SelectedRaw {
494        self.raw
495    }
496}
497
498/// Mutable references to [`Select::Target`] component arrays from multiple
499/// entities.  You can get an iterator traversing over each component array via
500/// [`iter`](Self::iter) or [`iter_mut`](Self::iter_mut). A component array
501/// belongs to a specific entity.
502//
503// `Selected` has mutable reference to a `SelectedRaw` in it.
504// So we can make use of it and expose mutable methods to clients here.
505#[derive(Debug)]
506#[repr(transparent)]
507pub struct SelectedMut<'cont, Comp>(Selected<'cont, Comp>);
508
509impl<'cont, Comp: 'cont> SelectedMut<'cont, Comp> {
510    pub(crate) fn new(filtered: &'cont mut SelectedRaw) -> Self {
511        Self(Selected::new(filtered))
512    }
513
514    pub fn iter(&self) -> SelectedIter<'cont, Comp> {
515        self.0.iter()
516    }
517
518    pub fn iter_mut(&mut self) -> SelectedIterMut<'cont, Comp> {
519        SelectedIterMut(self.iter())
520    }
521
522    pub fn par_iter(&self) -> ParSelectedIter<'cont, Comp> {
523        self.0.par_iter()
524    }
525
526    pub fn par_iter_mut(&mut self) -> ParSelectedIterMut<'cont, Comp> {
527        ParSelectedIterMut(self.iter_mut())
528    }
529}
530
531#[derive(Debug)]
532pub struct FilteredMut<'stor, T: 'stor> {
533    raw: &'stor mut FilteredRaw,
534    _marker: PhantomData<T>,
535}
536
537impl<'stor, T: 'stor> FilteredMut<'stor, T> {
538    pub(crate) fn new(raw: &'stor mut FilteredRaw) -> Self {
539        Self {
540            raw,
541            _marker: PhantomData,
542        }
543    }
544
545    pub fn iter_mut(&mut self) -> FilteredIterMut<'stor, T> {
546        FilteredIterMut::new(self)
547    }
548
549    pub(crate) fn as_raw(&self) -> &FilteredRaw {
550        self.raw
551    }
552}
553
554impl<'stor, T: Entity + 'stor> TakeRecur for FilteredMut<'stor, T> {
555    type Inner = EntityContainerRef<'stor, T>;
556
557    fn take_recur(mut self) -> Self::Inner {
558        if let Some(cont) = self.iter_mut().next() {
559            cont
560        } else {
561            panic!("have you registered `{}`?", any::type_name::<T>());
562        }
563    }
564}
565
566/// Selected component arrays by a [`Select`].
567///
568// This struct contains borrowed `Select::Target` arrays. But, this struct
569// doesn't bring lifetime constraint into inside the struct, although it
570// borrows component arrays. Instead, borrowed data are encapsulated by
571// `Borrowed`, which is a run-time borrow checker. In other words, component
572// arrays must be borrowed and released everytime.
573//
574// This struct is intended to be used as a cache without lifetime.
575// Cache is a data storage which lives as long as system data.
576// But system data will live indefinitely,
577// so removing lifetime helps to keep things simple.
578#[derive(Debug)]
579pub(crate) struct SelectedRaw {
580    /// [EntityTag] searched by the filter.
581    //
582    // Each system owns `SelectedRaw`, so `etags` and `col_idxs` will be
583    // duplicated between systems.
584    etags: Vec<Arc<EntityTag>>,
585
586    /// Column(Component) index searched by the filter.
587    //
588    // Each system owns `SelectedRaw`, so `etags` and `col_idxs` will be
589    // duplicated between systems.
590    col_idxs: Vec<usize>,
591
592    /// Temporary buffer for the query result.
593    /// Content will be replaced for every query, but we can reuse the capacity.
594    /// Notice that this doesn't actually own [Borrowed] because this is just a temporary buffer.
595    /// Real user, system, owns it and will drop it after using it.
596    //
597    // See `request::BufferCleaner` for more details.
598    query_res: Vec<Borrowed<RawGetter>>,
599}
600
601impl SelectedRaw {
602    pub(crate) const fn new(etags: Vec<Arc<EntityTag>>, col_idxs: Vec<usize>) -> Self {
603        Self {
604            etags,
605            col_idxs,
606            query_res: Vec::new(),
607        }
608    }
609
610    pub(crate) fn take(
611        &mut self,
612    ) -> (
613        &Vec<Arc<EntityTag>>,
614        &Vec<usize>,
615        &mut Vec<Borrowed<RawGetter>>,
616    ) {
617        (&self.etags, &self.col_idxs, &mut self.query_res)
618    }
619
620    // `etags` and `col_idxs` always have the same length.
621    pub(crate) fn add(&mut self, etag: Arc<EntityTag>, ci: usize) {
622        self.etags.push(etag);
623        self.col_idxs.push(ci);
624    }
625
626    // `etags` and `col_idxs` always have the same length.
627    pub(crate) fn remove(&mut self, ei: EntityIndex, ci: usize) -> Option<Arc<EntityTag>> {
628        let ei_iter = self.etags.iter().map(|etag| etag.index());
629        let ei_ci_iter = ei_iter.zip(&self.col_idxs);
630
631        if let Some((i, _)) = ei_ci_iter
632            .enumerate()
633            .find(|(_, (item_ei, item_ci))| *item_ei == ei && **item_ci == ci)
634        {
635            let old = self.etags.swap_remove(i);
636            self.col_idxs.swap_remove(i);
637            Some(old)
638        } else {
639            None
640        }
641    }
642
643    /// Retrieve an iterator that traverses over entity and column index pair.
644    pub(crate) fn iter_index_pair<'a>(
645        etags: &'a [Arc<EntityTag>],
646        col_idxs: &'a [usize],
647    ) -> impl Iterator<Item = (EntityIndex, usize)> + 'a {
648        // Self::add() guarantees that etags and col_idxs have the same length.
649        etags
650            .iter()
651            .map(|etag| etag.index())
652            .zip(col_idxs.iter().cloned())
653    }
654
655    pub(crate) fn clear(&mut self) {
656        self.query_res.clear();
657    }
658
659    pub(crate) const fn query_res(&self) -> &Vec<Borrowed<RawGetter>> {
660        &self.query_res
661    }
662
663    const fn entity_tags(&self) -> &Vec<Arc<EntityTag>> {
664        &self.etags
665    }
666}
667
668#[derive(Debug)]
669pub(crate) struct FilteredRaw {
670    etags: Vec<Arc<EntityTag>>,
671    query_res: Vec<Borrowed<NonNull<dyn ContainEntity>>>,
672}
673
674impl FilteredRaw {
675    pub(crate) const fn new(etags: Vec<Arc<EntityTag>>) -> Self {
676        Self {
677            etags,
678            query_res: Vec::new(),
679        }
680    }
681
682    #[allow(clippy::type_complexity)]
683    pub(crate) fn take(
684        &mut self,
685    ) -> (
686        &Vec<Arc<EntityTag>>,
687        &mut Vec<Borrowed<NonNull<dyn ContainEntity>>>,
688    ) {
689        (&self.etags, &mut self.query_res)
690    }
691
692    pub(crate) fn add(&mut self, etag: Arc<EntityTag>) {
693        self.etags.push(etag);
694    }
695
696    pub(crate) fn remove(&mut self, ei: &EntityIndex) -> Option<Arc<EntityTag>> {
697        if let Some((i, _)) = self
698            .etags
699            .iter()
700            .enumerate()
701            .find(|(_, x)| &x.index() == ei)
702        {
703            let old = self.etags.swap_remove(i);
704            Some(old)
705        } else {
706            None
707        }
708    }
709
710    pub(crate) fn clear(&mut self) {
711        self.query_res.clear();
712    }
713
714    pub(crate) const fn query_res(&self) -> &Vec<Borrowed<NonNull<dyn ContainEntity>>> {
715        &self.query_res
716    }
717
718    const fn entity_tags(&self) -> &Vec<Arc<EntityTag>> {
719        &self.etags
720    }
721}
722
723#[derive(Debug, Clone)]
724pub struct SelectedIter<'cont, Comp: 'cont> {
725    getter_cur: SendSyncPtr<Borrowed<RawGetter>>,
726
727    getter_end: SendSyncPtr<Borrowed<RawGetter>>,
728
729    etag_cur: SendSyncPtr<Arc<EntityTag>>,
730
731    etag_end: SendSyncPtr<Arc<EntityTag>>,
732
733    _marker: PhantomData<&'cont Comp>,
734}
735
736impl<'cont, Comp: 'cont> SelectedIter<'cont, Comp> {
737    // Borrows `Selected`.
738    fn new(raw: &Selected<'cont, Comp>) -> Self {
739        // Safety: `Selected` guarantees we're good to access those vecs.
740        unsafe {
741            let getter_range = raw.as_raw().query_res().as_ptr_range();
742            let getter_cur = NonNull::new_unchecked(getter_range.start.cast_mut());
743            let getter_end = NonNull::new_unchecked(getter_range.end.cast_mut());
744
745            let etag_range = raw.as_raw().entity_tags().as_ptr_range();
746            let etag_cur = NonNull::new_unchecked(etag_range.start.cast_mut());
747            let etag_end = NonNull::new_unchecked(etag_range.end.cast_mut());
748
749            Self {
750                getter_cur: SendSyncPtr::new(getter_cur),
751                getter_end: SendSyncPtr::new(getter_end),
752                etag_cur: SendSyncPtr::new(etag_cur),
753                etag_end: SendSyncPtr::new(etag_end),
754                _marker: PhantomData,
755            }
756        }
757    }
758
759    #[inline]
760    pub const fn len(&self) -> usize {
761        let cur = self.getter_cur.as_ptr();
762        let end = self.getter_end.as_ptr();
763        unsafe { end.offset_from(cur) as usize }
764    }
765
766    #[inline]
767    pub const fn is_empty(&self) -> bool {
768        self.len() == 0
769    }
770
771    #[inline]
772    fn split_at(self, index: usize) -> (Self, Self) {
773        let l_getter_cur = self.getter_cur;
774        let l_getter_end = unsafe { self.getter_cur.add(index) };
775        let r_getter_cur = l_getter_end;
776        let r_getter_end = self.getter_end;
777
778        let l_etag_cur = self.etag_cur;
779        let l_etag_end = unsafe { self.etag_cur.add(index) };
780        let r_etag_cur = l_etag_end;
781        let r_etag_end = self.etag_end;
782
783        let l = SelectedIter {
784            getter_cur: l_getter_cur,
785            getter_end: l_getter_end,
786            etag_cur: l_etag_cur,
787            etag_end: l_etag_end,
788            _marker: PhantomData,
789        };
790        let r = SelectedIter {
791            getter_cur: r_getter_cur,
792            getter_end: r_getter_end,
793            etag_cur: r_etag_cur,
794            etag_end: r_etag_end,
795            _marker: PhantomData,
796        };
797        (l, r)
798    }
799
800    unsafe fn create_item(
801        getter: SendSyncPtr<Borrowed<RawGetter>>,
802        etag: SendSyncPtr<Arc<EntityTag>>,
803    ) -> TaggedGetter<'cont, Comp> {
804        let getter = unsafe {
805            let raw = **getter.as_ref();
806            Getter::from_raw(raw)
807        };
808
809        let etag = unsafe {
810            let etag = Arc::as_ptr(etag.as_ref()).cast_mut();
811            let etag = NonNullExt::new(etag).unwrap_unchecked();
812            ManagedConstPtr::new(etag)
813        };
814
815        TaggedGetter { getter, etag }
816    }
817}
818
819impl<'cont, Comp: 'cont> Iterator for SelectedIter<'cont, Comp> {
820    type Item = TaggedGetter<'cont, Comp>;
821
822    fn next(&mut self) -> Option<Self::Item> {
823        if self.getter_cur < self.getter_end {
824            let getter = self.getter_cur;
825            let etag = self.etag_cur;
826            unsafe {
827                self.getter_cur = self.getter_cur.add(1);
828                self.etag_cur = self.etag_cur.add(1);
829                Some(Self::create_item(getter, etag))
830            }
831        } else {
832            None
833        }
834    }
835
836    fn size_hint(&self) -> (usize, Option<usize>) {
837        let len = Self::len(self);
838        (len, Some(len))
839    }
840}
841
842impl<'cont, Comp: 'cont> iter::FusedIterator for SelectedIter<'cont, Comp> {}
843
844impl<'cont, Comp: 'cont> ExactSizeIterator for SelectedIter<'cont, Comp> {
845    fn len(&self) -> usize {
846        Self::len(self)
847    }
848}
849
850impl<'cont, Comp: 'cont> DoubleEndedIterator for SelectedIter<'cont, Comp> {
851    fn next_back(&mut self) -> Option<Self::Item> {
852        if self.getter_cur < self.getter_end {
853            unsafe {
854                self.getter_end = self.getter_cur.sub(1);
855                self.etag_end = self.etag_cur.sub(1);
856                Some(Self::create_item(self.getter_end, self.etag_end))
857            }
858        } else {
859            None
860        }
861    }
862}
863
864/// Parallel [`SelectedIter`].
865//
866// `Iterator` and `ParallelIterator` have the same signature methods,
867// So clients have to write fully-qualified syntax to specify methods.
868// This new type helps clients avoid it.
869#[derive(Debug, Clone)]
870#[repr(transparent)]
871pub struct ParSelectedIter<'cont, Comp>(pub SelectedIter<'cont, Comp>);
872
873impl<'cont, Comp: 'cont> ParSelectedIter<'cont, Comp> {
874    #[inline]
875    pub const fn into_seq(self) -> SelectedIter<'cont, Comp> {
876        self.0
877    }
878
879    #[inline]
880    pub const fn len(&self) -> usize {
881        self.0.len()
882    }
883
884    #[inline]
885    pub const fn is_empty(&self) -> bool {
886        self.0.is_empty()
887    }
888}
889
890impl<'cont, Comp: Send + Sync + 'cont> Producer for ParSelectedIter<'cont, Comp> {
891    type Item = TaggedGetter<'cont, Comp>;
892    type IntoIter = SelectedIter<'cont, Comp>;
893
894    #[inline]
895    fn into_iter(self) -> Self::IntoIter {
896        self.into_seq()
897    }
898
899    #[inline]
900    fn split_at(self, index: usize) -> (Self, Self) {
901        let (l, r) = SelectedIter::split_at(self.0, index);
902        (ParSelectedIter(l), ParSelectedIter(r))
903    }
904}
905
906impl_into_iterator_for_parallel!(
907    "lifetimes" = 'cont; "bounds" = Comp: {'cont};
908    "for" = ParSelectedIter; "to" = SelectedIter<'cont, Comp>;
909    "item" = TaggedGetter<'cont, Comp>;
910);
911impl_parallel_iterator!(
912    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
913    "for" = ParSelectedIter; "item" = TaggedGetter<'cont, Comp>;
914);
915impl_unindexed_producer!(
916    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
917    "for" = ParSelectedIter; "item" = TaggedGetter<'cont, Comp>;
918);
919
920// Mutable iterator is not cloneable.
921#[derive(Debug)]
922#[repr(transparent)]
923pub struct SelectedIterMut<'cont, Comp>(pub SelectedIter<'cont, Comp>);
924
925impl<'cont, Comp: 'cont> SelectedIterMut<'cont, Comp> {
926    #[inline]
927    pub const fn into_seq(self) -> SelectedIter<'cont, Comp> {
928        self.0
929    }
930
931    #[inline]
932    pub const fn len(&self) -> usize {
933        self.0.len()
934    }
935
936    #[inline]
937    pub const fn is_empty(&self) -> bool {
938        self.0.is_empty()
939    }
940
941    #[inline]
942    fn split_at(self, index: usize) -> (Self, Self) {
943        let (l, r) = SelectedIter::split_at(self.0, index);
944        (Self(l), Self(r))
945    }
946}
947
948impl<'cont, Comp> Iterator for SelectedIterMut<'cont, Comp> {
949    type Item = TaggedGetterMut<'cont, Comp>;
950
951    #[inline]
952    fn next(&mut self) -> Option<Self::Item> {
953        self.0.next().map(|TaggedGetter { getter, etag }| {
954            TaggedGetterMut {
955                // Safety: `GetterMut` is made from `Getter`,
956                // which proves it's `RawGetter` and type are valid.
957                getter: unsafe { GetterMut::from_raw(getter.into_raw()) },
958                etag,
959            }
960        })
961    }
962
963    fn size_hint(&self) -> (usize, Option<usize>) {
964        self.0.size_hint()
965    }
966}
967
968impl<'cont, Comp: 'cont> iter::FusedIterator for SelectedIterMut<'cont, Comp> {}
969
970impl<'cont, Comp: 'cont> ExactSizeIterator for SelectedIterMut<'cont, Comp> {
971    fn len(&self) -> usize {
972        Self::len(self)
973    }
974}
975
976impl<'cont, Comp: 'cont> DoubleEndedIterator for SelectedIterMut<'cont, Comp> {
977    #[inline]
978    fn next_back(&mut self) -> Option<Self::Item> {
979        self.0.next_back().map(|TaggedGetter { getter, etag }| {
980            TaggedGetterMut {
981                // Safety: `GetterMut` is made from `Getter`,
982                // which proves it's `RawGetter` and type are valid.
983                getter: unsafe { GetterMut::from_raw(getter.into_raw()) },
984                etag,
985            }
986        })
987    }
988}
989
990/// Parallel [`SelectedIterMut`].
991//
992// `Iterator` and `ParallelIterator` have the same signature methods,
993// So clients have to write fully-qualified syntax to specify methods.
994// This new type helps clients avoid it.
995#[derive(Debug)]
996#[repr(transparent)]
997pub struct ParSelectedIterMut<'cont, Comp>(pub SelectedIterMut<'cont, Comp>);
998
999impl<'cont, Comp: 'cont> ParSelectedIterMut<'cont, Comp> {
1000    #[inline]
1001    pub const fn into_seq(self) -> SelectedIterMut<'cont, Comp> {
1002        self.0
1003    }
1004
1005    #[inline]
1006    pub const fn len(&self) -> usize {
1007        self.0.len()
1008    }
1009
1010    #[inline]
1011    pub const fn is_empty(&self) -> bool {
1012        self.0.is_empty()
1013    }
1014}
1015
1016impl<'cont, Comp: Send + Sync> Producer for ParSelectedIterMut<'cont, Comp> {
1017    type Item = TaggedGetterMut<'cont, Comp>;
1018    type IntoIter = SelectedIterMut<'cont, Comp>;
1019
1020    #[inline]
1021    fn into_iter(self) -> Self::IntoIter {
1022        self.into_seq()
1023    }
1024
1025    #[inline]
1026    fn split_at(self, index: usize) -> (Self, Self) {
1027        let (l, r) = SelectedIterMut::split_at(self.0, index);
1028        (ParSelectedIterMut(l), ParSelectedIterMut(r))
1029    }
1030}
1031
1032impl_into_iterator_for_parallel!(
1033    "lifetimes" = 'cont; "bounds" = Comp: {'cont};
1034    "for" = ParSelectedIterMut; "to" = SelectedIterMut<'cont, Comp>;
1035    "item" = TaggedGetterMut<'cont, Comp>;
1036);
1037impl_parallel_iterator!(
1038    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
1039    "for" = ParSelectedIterMut; "item" = TaggedGetterMut<'cont, Comp>;
1040);
1041impl_unindexed_producer!(
1042    "lifetimes" = 'cont; "bounds" = Comp: {Send + Sync + 'cont};
1043    "for" = ParSelectedIterMut; "item" = TaggedGetterMut<'cont, Comp>;
1044);
1045
1046#[derive(Debug)]
1047pub struct FilteredIterMut<'stor, T: 'stor> {
1048    cont_cur: NonNull<Borrowed<NonNull<dyn ContainEntity>>>,
1049    cont_end: NonNull<Borrowed<NonNull<dyn ContainEntity>>>,
1050    etag_cur: NonNull<Arc<EntityTag>>,
1051    etag_end: NonNull<Arc<EntityTag>>,
1052    _marker: PhantomData<&'stor mut T>,
1053}
1054
1055impl<'stor, T: 'stor> FilteredIterMut<'stor, T> {
1056    fn new(raw: &mut FilteredMut<'stor, T>) -> Self {
1057        // Safety: `FilteredMut` guarantees we're good to access those vecs.
1058        unsafe {
1059            let cont_range = raw.as_raw().query_res().as_ptr_range();
1060            let cont_cur = NonNull::new_unchecked(cont_range.start.cast_mut());
1061            let cont_end = NonNull::new_unchecked(cont_range.end.cast_mut());
1062
1063            let etag_range = raw.as_raw().entity_tags().as_ptr_range();
1064            let etag_cur = NonNull::new_unchecked(etag_range.start.cast_mut());
1065            let etag_end = NonNull::new_unchecked(etag_range.end.cast_mut());
1066
1067            Self {
1068                cont_cur,
1069                cont_end,
1070                etag_cur,
1071                etag_end,
1072                _marker: PhantomData,
1073            }
1074        }
1075    }
1076
1077    #[inline]
1078    pub const fn len(&self) -> usize {
1079        let cur = self.cont_cur.as_ptr();
1080        let end = self.cont_end.as_ptr();
1081        unsafe { end.offset_from(cur) as usize }
1082    }
1083
1084    #[inline]
1085    pub const fn is_empty(&self) -> bool {
1086        self.len() == 0
1087    }
1088
1089    unsafe fn create_item(
1090        mut cont: NonNull<Borrowed<NonNull<dyn ContainEntity>>>,
1091        etag: NonNull<Arc<EntityTag>>,
1092    ) -> EntityContainerRef<'stor, T> {
1093        let etag = unsafe { etag.as_ref() };
1094        let etag = &**etag;
1095        let cont = unsafe { cont.as_mut().as_mut() };
1096        EntityContainerRef::new(etag, cont)
1097    }
1098}
1099
1100impl<'stor, T: 'stor> Iterator for FilteredIterMut<'stor, T> {
1101    type Item = EntityContainerRef<'stor, T>;
1102
1103    fn next(&mut self) -> Option<Self::Item> {
1104        if self.cont_cur < self.cont_end {
1105            let getter = self.cont_cur;
1106            let etag = self.etag_cur;
1107            unsafe {
1108                self.cont_cur = self.cont_cur.add(1);
1109                self.etag_cur = self.etag_cur.add(1);
1110                Some(Self::create_item(getter, etag))
1111            }
1112        } else {
1113            None
1114        }
1115    }
1116}
1117
1118impl<'stor, T: 'stor> iter::FusedIterator for FilteredIterMut<'stor, T> {}
1119
1120impl<'stor, T: 'stor> ExactSizeIterator for FilteredIterMut<'stor, T> {
1121    fn len(&self) -> usize {
1122        Self::len(self)
1123    }
1124}
1125
1126impl<'stor, T: 'stor> DoubleEndedIterator for FilteredIterMut<'stor, T> {
1127    fn next_back(&mut self) -> Option<Self::Item> {
1128        if self.cont_cur < self.cont_end {
1129            unsafe {
1130                self.cont_end = self.cont_cur.sub(1);
1131                self.etag_end = self.etag_cur.sub(1);
1132                Some(Self::create_item(self.cont_end, self.etag_end))
1133            }
1134        } else {
1135            None
1136        }
1137    }
1138}
1139
1140/// Component getter with entity tag.
1141///
1142/// * Component getter  
1143///   A component getter corresponds to a component array.
1144///   You can get each component inside component array via getter.
1145///   See [`Getter`] for more details.
1146///
1147/// * Entity tag  
1148///   Many entities may contain the same component type.
1149///   So, it's needed to know what entity this component belongs to.
1150///   Entity tag has entity identification such as entity name.
1151#[derive(Debug, Clone)]
1152pub struct TaggedGetter<'cont, Comp: 'cont> {
1153    getter: Getter<'cont, Comp>,
1154    etag: ManagedConstPtr<EntityTag>,
1155}
1156
1157impl<Comp> TaggedGetter<'_, Comp> {
1158    pub fn entity_index(&self) -> EntityIndex {
1159        self.etag.index()
1160    }
1161
1162    pub fn entity_name(&self) -> Option<&EntityName> {
1163        self.etag.get_name()
1164    }
1165
1166    pub fn component_names(&self) -> &[&'static str] {
1167        self.etag.get_component_names()
1168    }
1169}
1170
1171impl<'cont, Comp> Deref for TaggedGetter<'cont, Comp> {
1172    type Target = Getter<'cont, Comp>;
1173
1174    fn deref(&self) -> &Self::Target {
1175        &self.getter
1176    }
1177}
1178
1179impl<'cont, Comp> IntoIterator for TaggedGetter<'cont, Comp> {
1180    type Item = &'cont Comp;
1181    type IntoIter = FlatIter<'cont, Comp>;
1182
1183    fn into_iter(self) -> Self::IntoIter {
1184        self.getter.into_iter()
1185    }
1186}
1187
1188impl<'cont, Comp: Send + Sync> IntoParallelIterator for TaggedGetter<'cont, Comp> {
1189    type Iter = ParFlatIter<'cont, Comp>;
1190    type Item = &'cont Comp;
1191
1192    fn into_par_iter(self) -> Self::Iter {
1193        self.getter.into_par_iter()
1194    }
1195}
1196
1197/// Component getter with entity tag.
1198///
1199/// * Component getter  
1200///   A component getter corresponds to a component array.
1201///   You can get each component inside component array via getter.
1202///   See [`GetterMut`] for more details.
1203///
1204/// * Entity tag  
1205///   Many entities may contain the same component type.
1206///   So, it's needed to know what entity this component belongs to.
1207///   Entity tag has entity identification such as entity name.
1208#[derive(Debug)]
1209pub struct TaggedGetterMut<'cont, Comp: 'cont> {
1210    getter: GetterMut<'cont, Comp>,
1211    etag: ManagedConstPtr<EntityTag>,
1212}
1213
1214impl<Comp> TaggedGetterMut<'_, Comp> {
1215    pub fn entity_index(&self) -> EntityIndex {
1216        self.etag.index()
1217    }
1218
1219    pub fn entity_name(&self) -> Option<&EntityName> {
1220        self.etag.get_name()
1221    }
1222
1223    pub fn component_names(&self) -> &[&'static str] {
1224        self.etag.get_component_names()
1225    }
1226}
1227
1228impl<'cont, Comp> Deref for TaggedGetterMut<'cont, Comp> {
1229    type Target = GetterMut<'cont, Comp>;
1230
1231    fn deref(&self) -> &Self::Target {
1232        &self.getter
1233    }
1234}
1235
1236impl<Comp> DerefMut for TaggedGetterMut<'_, Comp> {
1237    fn deref_mut(&mut self) -> &mut Self::Target {
1238        &mut self.getter
1239    }
1240}
1241
1242impl<'cont, Comp> IntoIterator for TaggedGetterMut<'cont, Comp> {
1243    type Item = &'cont mut Comp;
1244    type IntoIter = FlatIterMut<'cont, Comp>;
1245
1246    fn into_iter(self) -> Self::IntoIter {
1247        self.getter.into_iter()
1248    }
1249}
1250
1251impl<'cont, Comp: Send + Sync> IntoParallelIterator for TaggedGetterMut<'cont, Comp> {
1252    type Iter = ParFlatIterMut<'cont, Comp>;
1253    type Item = &'cont mut Comp;
1254
1255    fn into_par_iter(self) -> Self::Iter {
1256        self.getter.into_par_iter()
1257    }
1258}
1259
1260#[cfg(test)]
1261mod tests {
1262    #[test]
1263    #[rustfmt::skip]
1264    fn test_my_ecs_macros_filter() {
1265        use crate as my_ecs;
1266        use crate::prelude::*;
1267        use crate::ecs::{
1268            sys::select::Select,
1269            ent::component::ComponentKey,
1270        };
1271
1272        #[derive(Component)] struct Ca;
1273        #[derive(Component)] struct Cb;
1274        #[derive(Component)] struct Cc;
1275        #[derive(Component)] struct Cd;
1276        #[derive(Component)] struct Ce;
1277        #[derive(Component)] struct Cf;
1278
1279        // Target only.
1280        filter!(F0, Target = Ca);
1281        let [all, any, none] = F0::all_any_none();
1282        assert_eq!(<F0 as Select>::Target::key(), Ca::key());
1283        assert!(all.is_empty());
1284        assert!(any.is_empty());
1285        assert!(none.is_empty());
1286
1287        // All only.
1288        filter!(F1, All = Ca);
1289        let [all, any, none] = F1::all_any_none();
1290        validate_slice(&all, &[Ca::key()]);
1291        assert!(any.is_empty());
1292        assert!(none.is_empty());
1293
1294        // Any only.
1295        filter!(F2, Any = Ca);
1296        let [all, any, none] = F2::all_any_none();
1297        assert!(all.is_empty());
1298        validate_slice(&any, &[Ca::key()]);
1299        assert!(none.is_empty());
1300
1301        // None only.
1302        filter!(F3, None = Ca);
1303        let [all, any, none] = F3::all_any_none();
1304        assert!(all.is_empty());
1305        assert!(any.is_empty());
1306        validate_slice(&none, &[Ca::key()]);
1307
1308        // All + Any + None.
1309        filter!(F4, All = (Ca, Cb), Any = (Cc, Cd), None = (Ce, Cf));
1310        let [all, any, none] = F4::all_any_none();
1311        validate_slice(&all, &[Ca::key(), Cb::key()]);
1312        validate_slice(&any, &[Cc::key(), Cd::key()]);
1313        validate_slice(&none, &[Ce::key(), Cf::key()]);
1314
1315        // Target + All + Any + None.
1316        filter!(F5, Target = Ca, All = Cb, Any = Cc, None = Cd);
1317        let [all, any, none] = F5::all_any_none();
1318        assert_eq!(<F5 as Select>::Target::key(), Ca::key());
1319        validate_slice(&all, &[Cb::key()]);
1320        validate_slice(&any, &[Cc::key()]);
1321        validate_slice(&none, &[Cd::key()]);
1322
1323        fn validate_slice(a: &[ComponentKey], b: &[ComponentKey]) {
1324            assert_eq!(a.len(), b.len());
1325            for (va, vb) in a.iter().zip(b) {
1326                assert_eq!(va, vb);
1327            }
1328        }
1329    }
1330}