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
use std::marker::PhantomData;

use crate::{
    core::messages::Frame,
    global::{CallbackReturn, EntityId, OkEmpty},
    internal::{component::ComponentsTuple, conversion::FromBindgen, wit},
    message::Listener,
    message::RuntimeMessage,
};

use ambient_shared_types::ComponentIndex;

/// Creates a new [GeneralQueryBuilder] that will find entities that have the specified `components`
/// and can be [built](GeneralQueryBuilder::build) to create a [GeneralQuery].
///
/// Building a query is somewhat expensive, but they are cheap to copy and evaluate, so it's
/// recommended that you build your queries once and reuse them elsewhere.
pub fn query<Components: ComponentsTuple + Copy + Clone + 'static>(
    components: Components,
) -> GeneralQueryBuilder<Components> {
    GeneralQuery::create(components)
}

/// Creates a new [ChangeQuery] that will find entities that have the specified `components`
/// that will call its bound function when components marked by [ChangeQuery::track_change]
/// change.
pub fn change_query<Components: ComponentsTuple + Copy + Clone + 'static>(
    components: Components,
) -> UntrackedChangeQuery<Components> {
    UntrackedChangeQuery::create(components)
}

/// Creates a new [EventQuery] that will find entities that have the specified `components`
/// that will call its bound function when an entity with those components are spawned / seen
/// for the first time by this query.
pub fn spawn_query<Components: ComponentsTuple + Copy + Clone + 'static>(
    components: Components,
) -> EventQuery<Components> {
    EventQuery::create(QueryEvent::Spawn, components)
}

/// Creates a new [EventQuery] that will find entities that have the specified `components`
/// that will call its bound function when an entity with those components are despawned / seen
/// for the last time by this query.
pub fn despawn_query<Components: ComponentsTuple + Copy + Clone + 'static>(
    components: Components,
) -> EventQuery<Components> {
    EventQuery::create(QueryEvent::Despawn, components)
}

/// When this [EventQuery] should return results.
pub enum QueryEvent {
    /// When this collection of components is spawned.
    Spawn,
    /// When this collection of components is despawned.
    Despawn,
}

#[derive(Clone, Copy, Debug)]
/// An ECS query used to find entities in the world.
pub struct GeneralQuery<Components: ComponentsTuple + Copy + Clone + 'static>(
    QueryImpl<Components>,
);
impl<Components: ComponentsTuple + Copy + Clone + 'static> GeneralQuery<Components> {
    /// Creates a new [GeneralQueryBuilder] that will find entities that have the specified `components`
    /// and can be [built](GeneralQueryBuilder::build) to create a [GeneralQuery].
    ///
    /// Building a query is somewhat expensive, but they are cheap to copy and evaluate, so it's
    /// recommended that you build your queries once and reuse them elsewhere.
    pub fn create(components: Components) -> GeneralQueryBuilder<Components> {
        GeneralQueryBuilder(QueryBuilderImpl::new(components.as_indices()))
    }

    /// Evaluate the query and return the results.
    pub fn evaluate(&self) -> Vec<(EntityId, Components::Data)> {
        self.0.evaluate()
    }

    /// Consume this query and call `callback` (`fn`) each frame with the result of the query.
    pub fn each_frame<R: CallbackReturn>(
        self,
        callback: impl FnMut(Vec<(EntityId, Components::Data)>) -> R + 'static,
    ) -> Listener {
        self.0.bind(callback)
    }
}
/// Build a [GeneralQuery] for the ECS. This is how you find entities in the game world.
pub struct GeneralQueryBuilder<Components: ComponentsTuple + Copy + Clone + 'static>(
    QueryBuilderImpl<Components>,
);
impl<Components: ComponentsTuple + Copy + Clone + 'static> GeneralQueryBuilder<Components> {
    /// The entities must include the components in `requires`.
    pub fn requires(mut self, requires: impl ComponentsTuple) -> Self {
        self.0.requires(requires);
        self
    }

    /// The entities must not include the components in `exclude`.
    pub fn excludes(mut self, excludes: impl ComponentsTuple) -> Self {
        self.0.excludes(excludes);
        self
    }

    /// Builds a [GeneralQuery].
    pub fn build(self) -> GeneralQuery<Components> {
        GeneralQuery(QueryImpl::new(
            self.0.build_impl(vec![], wit::component::QueryEvent::Frame),
        ))
    }

    /// Consume this query and call `callback` (`fn`) each frame with the result of the query.
    pub fn each_frame<R: CallbackReturn>(
        self,
        callback: impl FnMut(Vec<(EntityId, Components::Data)>) -> R + 'static,
    ) -> Listener {
        self.build().each_frame(callback)
    }
}

/// An ECS query that will call a callback when entities containing components
/// marked with [Self::track_change] have those components change. This type
/// represents a query that has not had any components marked for tracking yet.
///
/// Note that this cannot be built without calling [Self::track_change]
/// at least once.
pub struct UntrackedChangeQuery<Components: ComponentsTuple + Copy + Clone + 'static>(
    QueryBuilderImpl<Components>,
    Vec<ComponentIndex>,
);
impl<Components: ComponentsTuple + Copy + Clone + 'static> UntrackedChangeQuery<Components> {
    /// Creates a new query that will find entities that have the specified `components`.
    /// It will call its bound function when components marked by [Self::track_change] change.
    pub fn create(components: Components) -> Self {
        Self(QueryBuilderImpl::new(components.as_indices()), vec![])
    }

    /// The query will return results when these components change values.
    ///
    /// This converts this type to a [ChangeQuery], which can be used to bind a callback.
    pub fn track_change(self, changes: impl ComponentsTuple) -> ChangeQuery<Components> {
        let cqwt = ChangeQuery(self);
        cqwt.track_change(changes)
    }
}

/// A partially-built ECS query that calls a callback when entities containing components
/// marked with [Self::track_change] have those components change.
///
/// This cannot be constructed without first going through [UntrackedChangeQuery] or
/// [change_query].
pub struct ChangeQuery<Components: ComponentsTuple + Copy + Clone + 'static>(
    UntrackedChangeQuery<Components>,
);
impl<Components: ComponentsTuple + Copy + Clone + 'static> ChangeQuery<Components> {
    /// The entities must include the components in `requires`.
    pub fn requires(mut self, requires: impl ComponentsTuple) -> Self {
        self.0 .0.requires(requires);
        self
    }

    /// The entities must not include the components in `exclude`.
    pub fn excludes(mut self, excludes: impl ComponentsTuple) -> Self {
        self.0 .0.excludes(excludes);
        self
    }

    /// The query will return results when these components change values.
    ///
    /// Note that this does *not* implicitly [requires](Self::requires) the components; this allows you to track
    /// changes for entities that do not have all of the tracked components.
    pub fn track_change(mut self, changes: impl ComponentsTuple) -> Self {
        self.0 .1.extend_from_slice(&changes.as_indices());
        self
    }

    /// Each time the components marked by [Self::track_change] change,
    /// the `callback` (`fn`) is called with the result of the query.
    pub fn bind<R: CallbackReturn>(
        self,
        callback: impl FnMut(Vec<(EntityId, Components::Data)>) -> R + 'static,
    ) -> Listener {
        self.build().bind(callback)
    }

    fn build(self) -> QueryImpl<Components> {
        QueryImpl::new(
            self.0
                 .0
                .build_impl(self.0 .1, wit::component::QueryEvent::Frame),
        )
    }
}

/// An ECS query that calls a callback when its associated event occurs.
pub struct EventQuery<Components: ComponentsTuple + Copy + Clone + 'static>(
    QueryBuilderImpl<Components>,
    QueryEvent,
);
impl<Components: ComponentsTuple + Copy + Clone + 'static> EventQuery<Components> {
    /// Creates a new [EventQuery] that will find entities that have the specified `components`
    /// that will call its bound function when the `event` occurs.
    pub fn create(event: QueryEvent, components: Components) -> Self {
        Self(QueryBuilderImpl::new(components.as_indices()), event)
    }

    /// The entities must include the components in `requires`.
    pub fn requires(mut self, requires: impl ComponentsTuple) -> Self {
        self.0.requires(requires);
        self
    }

    /// The entities must not include the components in `excludes`.
    pub fn excludes(mut self, excludes: impl ComponentsTuple) -> Self {
        self.0.excludes(excludes);
        self
    }

    /// Each time the entity associated with `components` experiences the event,
    /// the `callback` (`fn`) is called with the result of the query.
    pub fn bind<R: CallbackReturn>(
        self,
        callback: impl FnMut(Vec<(EntityId, Components::Data)>) -> R + 'static,
    ) -> Listener {
        self.build().bind(callback)
    }

    fn build(self) -> QueryImpl<Components> {
        QueryImpl::new(self.0.build_impl(
            vec![],
            match self.1 {
                QueryEvent::Spawn => wit::component::QueryEvent::Spawn,
                QueryEvent::Despawn => wit::component::QueryEvent::Despawn,
            },
        ))
    }
}

#[derive(Clone, Copy, Debug)]
struct QueryImpl<Components: ComponentsTuple + Copy + Clone + 'static>(
    u64,
    PhantomData<Components>,
);
impl<Components: ComponentsTuple + Copy + Clone + 'static> QueryImpl<Components> {
    fn new(id: u64) -> Self {
        Self(id, PhantomData)
    }

    fn evaluate(&self) -> Vec<(EntityId, Components::Data)> {
        wit::component::query_eval(self.0)
            .into_iter()
            .map(|(id, components)| {
                (
                    id.from_bindgen(),
                    Components::from_component_types(components)
                        .expect("invalid type conversion on component query"),
                )
            })
            .collect()
    }

    fn bind<R: CallbackReturn>(
        self,
        mut callback: impl FnMut(Vec<(EntityId, Components::Data)>) -> R + 'static,
    ) -> Listener {
        Frame::subscribe(move |_| {
            let results = self.evaluate();
            if !results.is_empty() {
                callback(results).into_result()?;
            }
            OkEmpty
        })
    }
}

struct QueryBuilderImpl<Components: ComponentsTuple + Copy + Clone + 'static> {
    components: Vec<ComponentIndex>,
    include: Vec<ComponentIndex>,
    exclude: Vec<ComponentIndex>,
    _data: PhantomData<Components>,
}
impl<Components: ComponentsTuple + Copy + Clone + 'static> QueryBuilderImpl<Components> {
    fn new(components: Vec<ComponentIndex>) -> QueryBuilderImpl<Components> {
        Self {
            components,
            include: vec![],
            exclude: vec![],
            _data: PhantomData,
        }
    }
    pub fn requires(&mut self, include: impl ComponentsTuple) {
        self.include.extend_from_slice(&include.as_indices());
    }
    pub fn excludes(&mut self, exclude: impl ComponentsTuple) {
        self.exclude.extend_from_slice(&exclude.as_indices());
    }
    fn build_impl(self, changed: Vec<ComponentIndex>, event: wit::component::QueryEvent) -> u64 {
        wit::component::query(
            &wit::component::QueryBuild {
                components: self.components,
                includes: self.include,
                excludes: self.exclude,
                changed,
            },
            event,
        )
    }
}