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
use core::{any::TypeId, marker::PhantomData, ptr::NonNull};

use crate::{
    archetype::Archetype,
    entity::EntityId,
    epoch::EpochId,
    query::{Access, Fetch, ImmutableQuery, IntoQuery, Query, QueryFetch},
    relation::{Relation, TargetComponent},
};

/// Fetch for the `FilterRelatedBy<R>` query.
pub struct FetchFilterRelatedBy<'a, R: Relation> {
    origin: EntityId,
    ptr: NonNull<TargetComponent<R>>,
    marker: PhantomData<&'a TargetComponent<R>>,
}

unsafe impl<'a, R> Fetch<'a> for FetchFilterRelatedBy<'a, R>
where
    R: Relation,
{
    type Item = ();

    #[inline]
    fn dangling() -> Self {
        FetchFilterRelatedBy {
            origin: EntityId::dangling(),
            ptr: NonNull::dangling(),
            marker: PhantomData,
        }
    }

    #[inline]
    unsafe fn skip_chunk(&mut self, _: usize) -> bool {
        false
    }

    #[inline]
    unsafe fn visit_chunk(&mut self, _: usize) {}

    #[inline]
    unsafe fn skip_item(&mut self, idx: usize) -> bool {
        let target_component = &*self.ptr.as_ptr().add(idx);
        target_component.origins.contains(&self.origin)
    }

    #[inline]
    unsafe fn get_item(&mut self, _: usize) -> () {}
}

/// Filters targets of relation with specified origin.
pub struct FilterRelatedBy<R> {
    origin: EntityId,
    phantom: PhantomData<R>,
}

impl_debug!(FilterRelatedBy<R> { origin });

impl<R> FilterRelatedBy<R> {
    /// Returns relation filter bound to one specific origin.
    pub const fn new(origin: EntityId) -> Self {
        FilterRelatedBy {
            origin,
            phantom: PhantomData,
        }
    }
}

impl<'a, R> QueryFetch<'a> for FilterRelatedBy<R>
where
    R: Relation,
{
    type Item = ();
    type Fetch = FetchFilterRelatedBy<'a, R>;
}

impl<R> IntoQuery for FilterRelatedBy<R>
where
    R: Relation,
{
    type Query = Self;
}

unsafe impl<R> Query for FilterRelatedBy<R>
where
    R: Relation,
{
    #[inline]
    fn access(&self, ty: TypeId) -> Option<Access> {
        if ty == TypeId::of::<TargetComponent<R>>() {
            Some(Access::Read)
        } else {
            None
        }
    }

    #[inline]
    fn skip_archetype(&self, archetype: &Archetype) -> bool {
        !archetype.has_component(TypeId::of::<TargetComponent<R>>())
    }

    #[inline]
    unsafe fn access_archetype(&self, _archetype: &Archetype, f: &dyn Fn(TypeId, Access)) {
        f(TypeId::of::<TargetComponent<R>>(), Access::Read)
    }

    #[inline]
    unsafe fn fetch<'a>(
        &mut self,
        archetype: &'a Archetype,
        _epoch: EpochId,
    ) -> FetchFilterRelatedBy<'a, R> {
        let component = archetype
            .component(TypeId::of::<TargetComponent<R>>())
            .unwrap_unchecked();
        debug_assert_eq!(component.id(), TypeId::of::<TargetComponent<R>>());

        let data = component.data();

        FetchFilterRelatedBy {
            origin: self.origin,
            ptr: data.ptr.cast(),
            marker: PhantomData,
        }
    }
}

unsafe impl<R> ImmutableQuery for FilterRelatedBy<R> where R: Relation {}

/// Returns a filter to filter targets of relation with specified origin.
pub fn related_by<R: Relation>(origin: EntityId) -> FilterRelatedBy<R> {
    FilterRelatedBy {
        origin,
        phantom: PhantomData,
    }
}