1use std::{
4 error::Error,
5 fmt,
6 ops::{Deref, DerefMut},
7};
8
9use bevy_ecs::{
10 entity_disabling::Disabled,
11 query::{
12 Allow, IterQueryData, QueryData, QueryFilter, QueryIter as BevyQueryIter,
13 QuerySingleError as BevyQuerySingleError, ROQueryItem, With, Without,
14 },
15 system::{Query as BevyQuery, Single as BevySingle, SystemParam},
16};
17
18use crate::identity::{LogicEntity, ManagedEntity, WorldGeneration, WorldIdentityState};
19
20type ManagedFilter<F> = (F, Allow<Disabled>, Without<Disabled>, With<ManagedEntity>);
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum QueryEntityError {
25 ForeignWorld {
27 entity: LogicEntity,
29 active: WorldGeneration,
31 },
32 DoesNotMatch {
34 entity: LogicEntity,
36 },
37}
38
39impl fmt::Display for QueryEntityError {
40 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41 match self {
42 Self::ForeignWorld { entity, active } => write!(
43 formatter,
44 "entity {entity:?} does not belong to active generation {active:?}"
45 ),
46 Self::DoesNotMatch { entity } => {
47 write!(formatter, "entity {entity:?} is absent or does not match")
48 }
49 }
50 }
51}
52
53impl Error for QueryEntityError {}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum QuerySingleError {
58 NoEntities,
60 MultipleEntities,
62}
63
64impl fmt::Display for QuerySingleError {
65 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 Self::NoEntities => formatter.write_str("no enabled managed entity matches the query"),
68 Self::MultipleEntities => {
69 formatter.write_str("more than one enabled managed entity matches the query")
70 }
71 }
72 }
73}
74
75impl Error for QuerySingleError {}
76
77#[derive(SystemParam)]
89pub struct Query<'w, 's, D: QueryData + 'static, F: QueryFilter + 'static = ()> {
90 inner: BevyQuery<'w, 's, D, ManagedFilter<F>>,
91 identities: BevyQuery<'w, 's, &'static ManagedEntity, ManagedFilter<()>>,
92 identity: bevy_ecs::prelude::Res<'w, WorldIdentityState>,
93}
94
95pub struct QueryIterator<'w, 's, D: QueryData, F: QueryFilter> {
100 inner: BevyQueryIter<'w, 's, D, ManagedFilter<F>>,
101}
102
103#[derive(SystemParam)]
116pub struct Single<'w, 's, D: IterQueryData + 'static, F: QueryFilter + 'static = ()> {
117 inner: BevySingle<'w, 's, D, ManagedFilter<F>>,
118}
119
120impl<'w, 's, D: IterQueryData + 'static, F: QueryFilter + 'static> Deref for Single<'w, 's, D, F> {
121 type Target = D::Item<'w, 's>;
122
123 fn deref(&self) -> &Self::Target {
124 self.inner.deref()
125 }
126}
127
128impl<'w, 's, D: IterQueryData + 'static, F: QueryFilter + 'static> DerefMut
129 for Single<'w, 's, D, F>
130{
131 fn deref_mut(&mut self) -> &mut Self::Target {
132 self.inner.deref_mut()
133 }
134}
135
136impl<'w, 's, D: IterQueryData + 'static, F: QueryFilter + 'static> Single<'w, 's, D, F> {
137 pub fn into_inner(self) -> D::Item<'w, 's> {
141 self.inner.into_inner()
142 }
143}
144
145impl<'w, 's, D: IterQueryData, F: QueryFilter> Iterator for QueryIterator<'w, 's, D, F> {
146 type Item = D::Item<'w, 's>;
147
148 fn next(&mut self) -> Option<Self::Item> {
149 self.inner.next()
150 }
151
152 fn size_hint(&self) -> (usize, Option<usize>) {
153 self.inner.size_hint()
154 }
155}
156
157impl<'s, D: QueryData + 'static, F: QueryFilter + 'static> Query<'_, 's, D, F> {
158 pub fn iter(&self) -> QueryIterator<'_, 's, D::ReadOnly, F> {
162 QueryIterator {
163 inner: self.inner.iter(),
164 }
165 }
166
167 pub fn iter_mut(&mut self) -> QueryIterator<'_, 's, D, F>
170 where
171 D: IterQueryData,
172 {
173 QueryIterator {
174 inner: self.inner.iter_mut(),
175 }
176 }
177
178 pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {
184 self.inner.single().map_err(map_single_error)
185 }
186
187 pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError>
193 where
194 D: IterQueryData,
195 {
196 self.inner.single_mut().map_err(map_single_error)
197 }
198
199 pub fn get(&self, entity: LogicEntity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {
202 self.validate(entity)?;
203 self.inner
204 .get(entity.entity())
205 .map_err(|_| QueryEntityError::DoesNotMatch { entity })
206 }
207
208 pub fn get_mut(&mut self, entity: LogicEntity) -> Result<D::Item<'_, 's>, QueryEntityError> {
211 self.validate(entity)?;
212 self.inner
213 .get_mut(entity.entity())
214 .map_err(|_| QueryEntityError::DoesNotMatch { entity })
215 }
216
217 fn validate(&self, entity: LogicEntity) -> Result<(), QueryEntityError> {
218 if !self.identity.owns(entity) {
219 return Err(QueryEntityError::ForeignWorld {
220 entity,
221 active: self.identity.generation(),
222 });
223 }
224 if !self
225 .identities
226 .get(entity.entity())
227 .is_ok_and(|managed| managed.handle(entity.entity()) == entity)
228 {
229 return Err(QueryEntityError::DoesNotMatch { entity });
230 }
231 Ok(())
232 }
233}
234
235fn map_single_error(error: BevyQuerySingleError) -> QuerySingleError {
236 match error {
237 BevyQuerySingleError::NoEntities(_) => QuerySingleError::NoEntities,
238 BevyQuerySingleError::MultipleEntities(_) => QuerySingleError::MultipleEntities,
239 }
240}
241
242impl<'w, 's, D, F> IntoIterator for &'w Query<'_, 's, D, F>
243where
244 D: QueryData + 'static,
245 F: QueryFilter + 'static,
246{
247 type Item = ROQueryItem<'w, 's, D>;
248 type IntoIter = QueryIterator<'w, 's, D::ReadOnly, F>;
249
250 fn into_iter(self) -> Self::IntoIter {
251 self.iter()
252 }
253}
254
255impl<'w, 's, D, F> IntoIterator for &'w mut Query<'_, 's, D, F>
256where
257 D: IterQueryData + 'static,
258 F: QueryFilter + 'static,
259{
260 type Item = D::Item<'w, 's>;
261 type IntoIter = QueryIterator<'w, 's, D, F>;
262
263 fn into_iter(self) -> Self::IntoIter {
264 self.iter_mut()
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use bevy_ecs::{
271 entity_disabling::Disabled,
272 prelude::{Component, Res, ResMut, Resource},
273 query::Allow,
274 world::World,
275 };
276
277 use crate::{
278 identity::{
279 ApplicationId, LogicEntity, LogicEntityRef, ManagedEntity, WorldGeneration,
280 WorldIdentityState,
281 },
282 system::{Stage, StageFactories, SystemRunFailure},
283 };
284
285 use super::*;
286
287 #[derive(Component)]
288 struct Marker(u8);
289
290 #[derive(Resource, Default)]
291 struct Observation(Option<Result<u8, QuerySingleError>>);
292
293 #[derive(Resource, Default)]
294 struct RequiredSingleObservation {
295 runs: usize,
296 value: Option<u8>,
297 entity: Option<LogicEntity>,
298 }
299
300 #[derive(Resource, Clone, Copy)]
301 struct PointLookupTarget(LogicEntity);
302
303 #[derive(Resource, Default)]
304 struct PointLookupObservation {
305 read: Option<Result<LogicEntity, QueryEntityError>>,
306 write: Option<Result<(), QueryEntityError>>,
307 }
308
309 fn observe_single(markers: Query<&Marker>, mut observation: ResMut<Observation>) {
310 observation.0 = Some(markers.single().map(|marker| marker.0));
311 }
312
313 fn increment_single(mut markers: Query<&mut Marker>) {
314 if let Ok(mut marker) = markers.single_mut() {
315 marker.0 += 1;
316 }
317 }
318
319 fn observe_required_single(
320 marker: Single<&Marker>,
321 mut observation: ResMut<RequiredSingleObservation>,
322 ) {
323 observation.runs += 1;
324 observation.value = Some(marker.0);
325 }
326
327 fn observe_required_single_tuple(
328 marker: Single<(LogicEntityRef, &Marker)>,
329 mut observation: ResMut<RequiredSingleObservation>,
330 ) {
331 let (entity, marker) = marker.into_inner();
332 observation.runs += 1;
333 observation.value = Some(marker.0);
334 observation.entity = Some(entity.handle());
335 }
336
337 fn increment_required_single(mut marker: Single<&mut Marker>) {
338 marker.0 += 1;
339 }
340
341 fn observe_point_lookup(
342 target: Res<PointLookupTarget>,
343 markers: Query<(LogicEntityRef, &Marker)>,
344 mut observation: ResMut<PointLookupObservation>,
345 ) {
346 observation.read = Some(
347 markers
348 .get(target.0)
349 .map(|(identity, _marker)| identity.handle()),
350 );
351 }
352
353 fn mutate_point_lookup(
354 target: Res<PointLookupTarget>,
355 mut markers: Query<&mut Marker>,
356 mut observation: ResMut<PointLookupObservation>,
357 ) {
358 observation.write = Some(markers.get_mut(target.0).map(|mut marker| marker.0 += 1));
359 }
360
361 fn managed_world(values: &[(u8, bool)]) -> World {
362 let application = ApplicationId::from_raw(1);
363 let generation = WorldGeneration::new(application, 1);
364 let mut world = World::new();
365 world.insert_resource(WorldIdentityState::new(application, generation));
366 world.insert_resource(Observation::default());
367 world.insert_resource(RequiredSingleObservation::default());
368 for (value, disabled) in values {
369 let raw = if *disabled {
370 world.spawn((Marker(*value), Disabled)).id()
371 } else {
372 world.spawn(Marker(*value)).id()
373 };
374 let entity = LogicEntity::new(application, generation, raw);
375 world.entity_mut(raw).insert(ManagedEntity::new(entity));
376 }
377 world
378 }
379
380 fn run_system_result<S, MarkerType>(
381 world: &mut World,
382 system: S,
383 ) -> Result<(), SystemRunFailure>
384 where
385 S: bevy_ecs::system::SystemParamFunction<MarkerType, In = (), Out = ()>
386 + Clone
387 + Send
388 + Sync
389 + 'static,
390 S::Param: crate::system::SupportedSystemParamTuple,
391 MarkerType: 'static,
392 {
393 let mut factories = StageFactories::default();
394 factories.add(system);
395 let mut stage = factories
396 .instantiate(world, Stage::FixedUpdate)
397 .expect("query test System should initialize");
398 stage.run(world)
399 }
400
401 fn run_system<S, MarkerType>(world: &mut World, system: S)
402 where
403 S: bevy_ecs::system::SystemParamFunction<MarkerType, In = (), Out = ()>
404 + Clone
405 + Send
406 + Sync
407 + 'static,
408 S::Param: crate::system::SupportedSystemParamTuple,
409 MarkerType: 'static,
410 {
411 run_system_result(world, system).expect("query test System should run");
412 }
413
414 #[test]
415 fn single_reports_zero_one_and_multiple_enabled_entities() {
416 for (values, expected) in [
417 (&[][..], Err(QuerySingleError::NoEntities)),
418 (&[(7, false)][..], Ok(7)),
419 (
420 &[(7, false), (9, false)][..],
421 Err(QuerySingleError::MultipleEntities),
422 ),
423 (&[(7, false), (9, true)][..], Ok(7)),
424 (&[(9, true)][..], Err(QuerySingleError::NoEntities)),
425 ] {
426 let mut world = managed_world(values);
427 run_system(&mut world, observe_single);
428 assert_eq!(world.resource::<Observation>().0, Some(expected));
429 }
430 }
431
432 #[test]
433 fn single_mut_changes_the_only_enabled_managed_entity() {
434 let mut world = managed_world(&[(4, false), (9, true)]);
435 run_system(&mut world, increment_single);
436
437 let values: Vec<_> = world
438 .query_filtered::<&Marker, Allow<Disabled>>()
439 .iter(&world)
440 .map(|value| value.0)
441 .collect();
442 assert!(values.contains(&5));
443 assert!(values.contains(&9));
444 }
445
446 #[test]
447 fn required_single_dereferences_the_only_enabled_managed_entity() {
448 let mut world = managed_world(&[(7, false), (9, true)]);
449 run_system(&mut world, observe_required_single);
450
451 let observation = world.resource::<RequiredSingleObservation>();
452 assert_eq!(observation.runs, 1);
453 assert_eq!(observation.value, Some(7));
454 }
455
456 #[test]
457 fn required_single_cardinality_failure_stops_before_the_system_body() {
458 for (values, expected_reason) in [
459 (&[][..], "No matching entities"),
460 (&[(7, false), (9, false)][..], "Multiple matching entities"),
461 (&[(7, true)][..], "No matching entities"),
462 ] {
463 let mut world = managed_world(values);
464 let error = run_system_result(&mut world, observe_required_single)
465 .expect_err("invalid cardinality should stop the managed System");
466
467 assert!(
468 error.reason().contains(expected_reason),
469 "unexpected parameter validation reason: {}",
470 error.reason()
471 );
472 assert!(
473 !error.reason().contains("ManagedEntity"),
474 "private managed filter leaked into diagnostics: {}",
475 error.reason()
476 );
477 assert_eq!(world.resource::<RequiredSingleObservation>().runs, 0);
478 }
479 }
480
481 #[test]
482 fn required_single_tuple_returns_the_managed_identity_without_an_extra_lookup() {
483 let mut world = managed_world(&[(11, false)]);
484 let (raw, managed, _) = world
485 .query::<(bevy_ecs::entity::Entity, &ManagedEntity, &Marker)>()
486 .single(&world)
487 .expect("test World should have one managed marker");
488 let expected = managed.handle(raw);
489
490 run_system(&mut world, observe_required_single_tuple);
491
492 let observation = world.resource::<RequiredSingleObservation>();
493 assert_eq!(observation.runs, 1);
494 assert_eq!(observation.value, Some(11));
495 assert_eq!(observation.entity, Some(expected));
496 }
497
498 #[test]
499 fn required_single_mutates_only_the_enabled_managed_entity() {
500 let mut world = managed_world(&[(4, false), (9, true)]);
501 run_system(&mut world, increment_required_single);
502
503 let values: Vec<_> = world
504 .query_filtered::<&Marker, Allow<Disabled>>()
505 .iter(&world)
506 .map(|value| value.0)
507 .collect();
508 assert!(values.contains(&5));
509 assert!(values.contains(&9));
510 }
511
512 #[test]
513 fn point_lookups_reject_a_row_with_mismatched_private_provenance() {
514 let mut world = managed_world(&[(7, false)]);
515 let (raw, managed) = world
516 .query::<(bevy_ecs::entity::Entity, &ManagedEntity)>()
517 .single(&world)
518 .expect("test World should have one managed marker");
519 let target = managed.handle(raw);
520 world.insert_resource(PointLookupTarget(target));
521 world.insert_resource(PointLookupObservation::default());
522 let corrupted = WorldGeneration::new(ApplicationId::from_raw(1), 99);
523 world
524 .entity_mut(raw)
525 .insert(ManagedEntity::for_generation(corrupted));
526
527 run_system(&mut world, observe_point_lookup);
528 run_system(&mut world, mutate_point_lookup);
529
530 let observation = world.resource::<PointLookupObservation>();
531 assert!(matches!(
532 observation.read,
533 Some(Err(QueryEntityError::DoesNotMatch { entity })) if entity == target
534 ));
535 assert!(matches!(
536 observation.write,
537 Some(Err(QueryEntityError::DoesNotMatch { entity })) if entity == target
538 ));
539 assert_eq!(world.get::<Marker>(raw).map(|marker| marker.0), Some(7));
540 }
541}