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

use crate::{
    archetype::Archetype,
    query::{merge_access, Access, IntoQuery, Query},
    system::ActionQueue,
    world::{QueryRef, World},
};

use super::{FnArg, FnArgCache, FnArgGet};

/// Cache for an argument that is stored between calls to function-system.
pub trait QueryArgGet<'a> {
    /// Argument specified in [`QueryRef`]
    type Arg: QueryArg<Cache = Self, Query = Self::Query>;

    /// Constructed query type.
    type Query: Query;

    /// Returns query for an argument.
    fn get(&'a mut self, world: &'a World) -> Self::Query;
}

/// Cache for an argument that is stored between calls to function-system.
pub trait QueryArgCache: for<'a> QueryArgGet<'a> + Send + Default + 'static {
    /// Returns true if the query skips component unconditionally.
    fn skips_archetype(&self, archetype: &Archetype) -> bool;

    /// Returns some access type performed by the query.
    fn access_component(&self, id: TypeId) -> Option<Access>;
}

/// Types that can be used as queries with [`QueryRef`] for function-systems.
pub trait QueryArg: IntoQuery {
    /// Cache for an argument that is stored between calls to function-system.
    type Cache: QueryArgCache;
}

/// Cache type used by corresponding [`QueryRef`].
#[derive(Default)]
pub struct QueryRefCache<Q, F> {
    query: Q,
    filter: F,
}

unsafe impl<'a, Q, F> FnArgGet<'a> for QueryRefCache<Q, F>
where
    Q: QueryArgCache,
    F: QueryArgCache,
{
    type Arg = QueryRef<'a, <Q as QueryArgGet<'a>>::Arg, <F as QueryArgGet<'a>>::Arg>;

    #[inline]
    unsafe fn get_unchecked(
        &'a mut self,
        world: NonNull<World>,
        _queue: &mut dyn ActionQueue,
    ) -> Self::Arg {
        let world = world.as_ref(); // # Safety: Declares read access.
        let query = self.query.get(world);
        let filter = self.filter.get(world);
        QueryRef::new(world, query, filter)
    }
}

impl<Q, F> FnArgCache for QueryRefCache<Q, F>
where
    Q: QueryArgCache,
    F: QueryArgCache,
{
    #[inline]
    fn is_local(&self) -> bool {
        false
    }

    #[inline]
    fn world_access(&self) -> Option<Access> {
        Some(Access::Read)
    }

    #[inline]
    fn skips_archetype(&self, archetype: &Archetype) -> bool {
        self.query.skips_archetype(archetype) || self.filter.skips_archetype(archetype)
    }

    #[inline]
    fn access_component(&self, id: TypeId) -> Option<Access> {
        merge_access(
            self.query.access_component(id),
            self.filter.access_component(id),
        )
    }

    #[inline]
    fn access_resource(&self, _id: TypeId) -> Option<Access> {
        None
    }
}

impl<'a, Q, F> FnArg for QueryRef<'a, Q, F>
where
    Q: QueryArg,
    F: QueryArg,
{
    type Cache = QueryRefCache<Q::Cache, F::Cache>;
}

macro_rules! for_tuple {
    () => {
        // This one is shorter because `Default` is not implemented for larger tuples.
        for_tuple!(for A B C D E F G H I J L M);
        // for_tuple!(for A);
    };

    (for) => {
        for_tuple!(impl);
    };

    (for $head:ident $($tail:ident)*) => {
        for_tuple!(for $($tail)*);
        for_tuple!(impl $head $($tail)*);
    };

    (impl) => {
        impl<'a> QueryArgGet<'a> for () {
            type Arg = ();
            type Query = ();

            #[inline]
            fn get(&mut self, _world: &World) {}
        }

        impl QueryArgCache for () {
            #[inline]
            fn skips_archetype(&self, _archetype: &Archetype) -> bool {
                false
            }
            #[inline]
            fn access_component(&self, _id: TypeId) -> Option<Access> {
                None
            }
        }

        impl QueryArg for () {
            type Cache = ();
        }
    };

    (impl $($a:ident)+) => {
        #[allow(non_snake_case)]
        #[allow(unused_parens)]
        impl<'a $(, $a)+> QueryArgGet<'a> for ($($a,)+)
        where
            $($a: QueryArgGet<'a>,)+
        {
            type Arg = ($($a::Arg,)+);
            type Query = ($($a::Query,)+);

            #[inline]
            fn get(&'a mut self, world: &'a World) -> Self::Query {
                let ($($a,)+) = self;
                ($($a::get($a, world),)+)
            }
        }

        #[allow(non_snake_case)]
        #[allow(unused_parens)]
        impl<$($a),+> QueryArgCache for ($($a,)+)
        where
            $($a: QueryArgCache,)+
        {
            #[inline]
            fn skips_archetype(&self, archetype: &Archetype) -> bool {
                let ($($a,)+) = self;
                $($a.skips_archetype(archetype))||+
            }

            #[inline]
            fn access_component(&self, _id: TypeId) -> Option<Access> {
                let ($($a,)+) = self;
                let mut access = None;
                $({
                    access = merge_access(access, $a.access_component(_id));
                })*
                access
            }
        }

        #[allow(non_snake_case)]
        #[allow(unused_parens)]
        impl<$($a),+> QueryArg for ($($a,)+)
        where
            $($a: QueryArg,)+
        {
            type Cache = ($($a::Cache,)+);
        }
    };
}

for_tuple!();