bevy_ecs/query/
mod.rs

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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//! Contains APIs for retrieving component data from the world.

mod access;
mod builder;
mod error;
mod fetch;
mod filter;
mod iter;
mod par_iter;
mod state;
mod world_query;

pub use access::*;
pub use bevy_ecs_macros::{QueryData, QueryFilter};
pub use builder::*;
pub use error::*;
pub use fetch::*;
pub use filter::*;
pub use iter::*;
pub use par_iter::*;
pub use state::*;
pub use world_query::*;

/// A debug checked version of [`Option::unwrap_unchecked`]. Will panic in
/// debug modes if unwrapping a `None` or `Err` value in debug mode, but is
/// equivalent to `Option::unwrap_unchecked` or `Result::unwrap_unchecked`
/// in release mode.
pub(crate) trait DebugCheckedUnwrap {
    type Item;
    /// # Panics
    /// Panics if the value is `None` or `Err`, only in debug mode.
    ///
    /// # Safety
    /// This must never be called on a `None` or `Err` value. This can
    /// only be called on `Some` or `Ok` values.
    unsafe fn debug_checked_unwrap(self) -> Self::Item;
}

// These two impls are explicitly split to ensure that the unreachable! macro
// does not cause inlining to fail when compiling in release mode.
#[cfg(debug_assertions)]
impl<T> DebugCheckedUnwrap for Option<T> {
    type Item = T;

    #[inline(always)]
    #[track_caller]
    unsafe fn debug_checked_unwrap(self) -> Self::Item {
        if let Some(inner) = self {
            inner
        } else {
            unreachable!()
        }
    }
}

// These two impls are explicitly split to ensure that the unreachable! macro
// does not cause inlining to fail when compiling in release mode.
#[cfg(debug_assertions)]
impl<T, U> DebugCheckedUnwrap for Result<T, U> {
    type Item = T;

    #[inline(always)]
    #[track_caller]
    unsafe fn debug_checked_unwrap(self) -> Self::Item {
        if let Ok(inner) = self {
            inner
        } else {
            unreachable!()
        }
    }
}

// These two impls are explicitly split to ensure that the unreachable! macro
// does not cause inlining to fail when compiling in release mode.
#[cfg(not(debug_assertions))]
impl<T, U> DebugCheckedUnwrap for Result<T, U> {
    type Item = T;

    #[inline(always)]
    #[track_caller]
    unsafe fn debug_checked_unwrap(self) -> Self::Item {
        if let Ok(inner) = self {
            inner
        } else {
            core::hint::unreachable_unchecked()
        }
    }
}

#[cfg(not(debug_assertions))]
impl<T> DebugCheckedUnwrap for Option<T> {
    type Item = T;

    #[inline(always)]
    unsafe fn debug_checked_unwrap(self) -> Self::Item {
        if let Some(inner) = self {
            inner
        } else {
            core::hint::unreachable_unchecked()
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        self as bevy_ecs,
        component::Component,
        prelude::{AnyOf, Changed, Entity, Or, QueryState, With, Without},
        query::{ArchetypeFilter, Has, QueryCombinationIter, ReadOnlyQueryData},
        schedule::{IntoSystemConfigs, Schedule},
        system::{IntoSystem, Query, System, SystemState},
        world::World,
    };
    use bevy_ecs_macros::{QueryData, QueryFilter};
    use core::{any::type_name, fmt::Debug, hash::Hash};
    use std::collections::HashSet;

    #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy, PartialOrd, Ord)]
    struct A(usize);
    #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy)]
    struct B(usize);
    #[derive(Component, Debug, Eq, PartialEq, Clone, Copy)]
    struct C(usize);
    #[derive(Component, Debug, Eq, PartialEq, Clone, Copy)]
    struct D(usize);

    #[derive(Component, Debug, Hash, Eq, PartialEq, Clone, Copy, PartialOrd, Ord)]
    #[component(storage = "SparseSet")]
    struct Sparse(usize);

    #[test]
    fn query() {
        let mut world = World::new();
        world.spawn((A(1), B(1)));
        world.spawn(A(2));
        let values = world.query::<&A>().iter(&world).collect::<HashSet<&A>>();
        assert!(values.contains(&A(1)));
        assert!(values.contains(&A(2)));

        for (_a, mut b) in world.query::<(&A, &mut B)>().iter_mut(&mut world) {
            b.0 = 3;
        }
        let values = world.query::<&B>().iter(&world).collect::<Vec<&B>>();
        assert_eq!(values, vec![&B(3)]);
    }

    #[test]
    fn query_filtered_exactsizeiterator_len() {
        fn choose(n: usize, k: usize) -> usize {
            if n == 0 || k == 0 || n < k {
                return 0;
            }
            let ks = 1..=k;
            let ns = (n - k + 1..=n).rev();
            ks.zip(ns).fold(1, |acc, (k, n)| acc * n / k)
        }
        fn assert_combination<D, F, const K: usize>(world: &mut World, expected_size: usize)
        where
            D: ReadOnlyQueryData,
            F: ArchetypeFilter,
        {
            let mut query = world.query_filtered::<D, F>();
            let query_type = type_name::<QueryCombinationIter<D, F, K>>();
            let iter = query.iter_combinations::<K>(world);
            assert_all_sizes_iterator_equal(iter, expected_size, 0, query_type);
            let iter = query.iter_combinations::<K>(world);
            assert_all_sizes_iterator_equal(iter, expected_size, 1, query_type);
            let iter = query.iter_combinations::<K>(world);
            assert_all_sizes_iterator_equal(iter, expected_size, 5, query_type);
        }
        fn assert_all_sizes_equal<D, F>(world: &mut World, expected_size: usize)
        where
            D: ReadOnlyQueryData,
            F: ArchetypeFilter,
        {
            let mut query = world.query_filtered::<D, F>();
            let query_type = type_name::<QueryState<D, F>>();
            assert_all_exact_sizes_iterator_equal(query.iter(world), expected_size, 0, query_type);
            assert_all_exact_sizes_iterator_equal(query.iter(world), expected_size, 1, query_type);
            assert_all_exact_sizes_iterator_equal(query.iter(world), expected_size, 5, query_type);

            let expected = expected_size;
            assert_combination::<D, F, 1>(world, choose(expected, 1));
            assert_combination::<D, F, 2>(world, choose(expected, 2));
            assert_combination::<D, F, 5>(world, choose(expected, 5));
            assert_combination::<D, F, 43>(world, choose(expected, 43));
            assert_combination::<D, F, 64>(world, choose(expected, 64));
        }
        fn assert_all_exact_sizes_iterator_equal(
            iterator: impl ExactSizeIterator,
            expected_size: usize,
            skip: usize,
            query_type: &'static str,
        ) {
            let len = iterator.len();
            println!("len:           {len}");
            assert_all_sizes_iterator_equal(iterator, expected_size, skip, query_type);
            assert_eq!(len, expected_size);
        }
        fn assert_all_sizes_iterator_equal(
            mut iterator: impl Iterator,
            expected_size: usize,
            skip: usize,
            query_type: &'static str,
        ) {
            let expected_size = expected_size.saturating_sub(skip);
            for _ in 0..skip {
                iterator.next();
            }
            let size_hint_0 = iterator.size_hint().0;
            let size_hint_1 = iterator.size_hint().1;
            // `count` tests that not only it is the expected value, but also
            // the value is accurate to what the query returns.
            let count = iterator.count();
            // This will show up when one of the asserts in this function fails
            println!(
                "query declared sizes: \n\
                for query:     {query_type} \n\
                expected:      {expected_size} \n\
                size_hint().0: {size_hint_0} \n\
                size_hint().1: {size_hint_1:?} \n\
                count():       {count}"
            );
            assert_eq!(size_hint_0, expected_size);
            assert_eq!(size_hint_1, Some(expected_size));
            assert_eq!(count, expected_size);
        }

        let mut world = World::new();
        world.spawn((A(1), B(1)));
        world.spawn(A(2));
        world.spawn(A(3));

        assert_all_sizes_equal::<&A, With<B>>(&mut world, 1);
        assert_all_sizes_equal::<&A, Without<B>>(&mut world, 2);

        let mut world = World::new();
        world.spawn((A(1), B(1), C(1)));
        world.spawn((A(2), B(2)));
        world.spawn((A(3), B(3)));
        world.spawn((A(4), C(4)));
        world.spawn((A(5), C(5)));
        world.spawn((A(6), C(6)));
        world.spawn(A(7));
        world.spawn(A(8));
        world.spawn(A(9));
        world.spawn(A(10));

        // With/Without for B and C
        assert_all_sizes_equal::<&A, With<B>>(&mut world, 3);
        assert_all_sizes_equal::<&A, With<C>>(&mut world, 4);
        assert_all_sizes_equal::<&A, Without<B>>(&mut world, 7);
        assert_all_sizes_equal::<&A, Without<C>>(&mut world, 6);

        // With/Without (And) combinations
        assert_all_sizes_equal::<&A, (With<B>, With<C>)>(&mut world, 1);
        assert_all_sizes_equal::<&A, (With<B>, Without<C>)>(&mut world, 2);
        assert_all_sizes_equal::<&A, (Without<B>, With<C>)>(&mut world, 3);
        assert_all_sizes_equal::<&A, (Without<B>, Without<C>)>(&mut world, 4);

        // With/Without Or<()> combinations
        assert_all_sizes_equal::<&A, Or<(With<B>, With<C>)>>(&mut world, 6);
        assert_all_sizes_equal::<&A, Or<(With<B>, Without<C>)>>(&mut world, 7);
        assert_all_sizes_equal::<&A, Or<(Without<B>, With<C>)>>(&mut world, 8);
        assert_all_sizes_equal::<&A, Or<(Without<B>, Without<C>)>>(&mut world, 9);
        assert_all_sizes_equal::<&A, (Or<(With<B>,)>, Or<(With<C>,)>)>(&mut world, 1);
        assert_all_sizes_equal::<&A, Or<(Or<(With<B>, With<C>)>, With<D>)>>(&mut world, 6);

        for i in 11..14 {
            world.spawn((A(i), D(i)));
        }

        assert_all_sizes_equal::<&A, Or<(Or<(With<B>, With<C>)>, With<D>)>>(&mut world, 9);
        assert_all_sizes_equal::<&A, Or<(Or<(With<B>, With<C>)>, Without<D>)>>(&mut world, 10);

        // a fair amount of entities
        for i in 14..20 {
            world.spawn((C(i), D(i)));
        }
        assert_all_sizes_equal::<Entity, (With<C>, With<D>)>(&mut world, 6);
    }

    // the order of the combinations is not guaranteed, but each unique combination is present
    fn check_combinations<T: Ord + Hash + Debug, const K: usize>(
        values: HashSet<[&T; K]>,
        expected: HashSet<[&T; K]>,
    ) {
        values.iter().for_each(|pair| {
            let mut sorted = *pair;
            sorted.sort();
            assert!(expected.contains(&sorted),
                    "the results of iter_combinations should contain this combination {:?}. Expected: {:?}, got: {:?}",
                    &sorted, &expected, &values);
        });
    }

    #[test]
    fn query_iter_combinations() {
        let mut world = World::new();

        world.spawn((A(1), B(1)));
        world.spawn(A(2));
        world.spawn(A(3));
        world.spawn(A(4));

        let values: HashSet<[&A; 2]> = world.query::<&A>().iter_combinations(&world).collect();
        check_combinations(
            values,
            HashSet::from([
                [&A(1), &A(2)],
                [&A(1), &A(3)],
                [&A(1), &A(4)],
                [&A(2), &A(3)],
                [&A(2), &A(4)],
                [&A(3), &A(4)],
            ]),
        );
        let mut a_query = world.query::<&A>();

        let values: HashSet<[&A; 3]> = a_query.iter_combinations(&world).collect();
        check_combinations(
            values,
            HashSet::from([
                [&A(1), &A(2), &A(3)],
                [&A(1), &A(2), &A(4)],
                [&A(1), &A(3), &A(4)],
                [&A(2), &A(3), &A(4)],
            ]),
        );

        let mut b_query = world.query::<&B>();
        assert_eq!(
            b_query.iter_combinations::<2>(&world).size_hint(),
            (0, Some(0))
        );
        let values: Vec<[&B; 2]> = b_query.iter_combinations(&world).collect();
        assert_eq!(values, Vec::<[&B; 2]>::new());
    }

    #[test]
    fn query_filtered_iter_combinations() {
        use bevy_ecs::query::{Added, Or, With, Without};

        let mut world = World::new();

        world.spawn((A(1), B(1)));
        world.spawn(A(2));
        world.spawn(A(3));
        world.spawn(A(4));

        let mut a_wout_b = world.query_filtered::<&A, Without<B>>();
        let values: HashSet<[&A; 2]> = a_wout_b.iter_combinations(&world).collect();
        check_combinations(
            values,
            HashSet::from([[&A(2), &A(3)], [&A(2), &A(4)], [&A(3), &A(4)]]),
        );

        let values: HashSet<[&A; 3]> = a_wout_b.iter_combinations(&world).collect();
        check_combinations(values, HashSet::from([[&A(2), &A(3), &A(4)]]));

        let mut query = world.query_filtered::<&A, Or<(With<A>, With<B>)>>();
        let values: HashSet<[&A; 2]> = query.iter_combinations(&world).collect();
        check_combinations(
            values,
            HashSet::from([
                [&A(1), &A(2)],
                [&A(1), &A(3)],
                [&A(1), &A(4)],
                [&A(2), &A(3)],
                [&A(2), &A(4)],
                [&A(3), &A(4)],
            ]),
        );

        let mut query = world.query_filtered::<&mut A, Without<B>>();
        let mut combinations = query.iter_combinations_mut(&mut world);
        while let Some([mut a, mut b, mut c]) = combinations.fetch_next() {
            a.0 += 10;
            b.0 += 100;
            c.0 += 1000;
        }

        let values: HashSet<[&A; 3]> = a_wout_b.iter_combinations(&world).collect();
        check_combinations(values, HashSet::from([[&A(12), &A(103), &A(1004)]]));

        // Check if Added<T>, Changed<T> works
        let mut world = World::new();

        world.spawn((A(1), B(1)));
        world.spawn((A(2), B(2)));
        world.spawn((A(3), B(3)));
        world.spawn((A(4), B(4)));

        let mut query_added = world.query_filtered::<&A, Added<A>>();

        world.clear_trackers();
        world.spawn(A(5));

        assert_eq!(query_added.iter_combinations::<2>(&world).count(), 0);

        world.clear_trackers();
        world.spawn(A(6));
        world.spawn(A(7));

        assert_eq!(query_added.iter_combinations::<2>(&world).count(), 1);

        world.clear_trackers();
        world.spawn(A(8));
        world.spawn(A(9));
        world.spawn(A(10));

        assert_eq!(query_added.iter_combinations::<2>(&world).count(), 3);
    }

    #[test]
    fn query_iter_combinations_sparse() {
        let mut world = World::new();

        world.spawn_batch((1..=4).map(Sparse));

        let values: HashSet<[&Sparse; 3]> =
            world.query::<&Sparse>().iter_combinations(&world).collect();
        check_combinations(
            values,
            HashSet::from([
                [&Sparse(1), &Sparse(2), &Sparse(3)],
                [&Sparse(1), &Sparse(2), &Sparse(4)],
                [&Sparse(1), &Sparse(3), &Sparse(4)],
                [&Sparse(2), &Sparse(3), &Sparse(4)],
            ]),
        );
    }

    #[test]
    fn multi_storage_query() {
        let mut world = World::new();

        world.spawn((Sparse(1), B(2)));
        world.spawn(Sparse(2));

        let values = world
            .query::<&Sparse>()
            .iter(&world)
            .collect::<HashSet<&Sparse>>();
        assert!(values.contains(&Sparse(1)));
        assert!(values.contains(&Sparse(2)));

        for (_a, mut b) in world.query::<(&Sparse, &mut B)>().iter_mut(&mut world) {
            b.0 = 3;
        }

        let values = world.query::<&B>().iter(&world).collect::<Vec<&B>>();
        assert_eq!(values, vec![&B(3)]);
    }

    #[test]
    fn any_query() {
        let mut world = World::new();

        world.spawn((A(1), B(2)));
        world.spawn(A(2));
        world.spawn(C(3));

        let values: Vec<(Option<&A>, Option<&B>)> =
            world.query::<AnyOf<(&A, &B)>>().iter(&world).collect();

        assert_eq!(
            values,
            vec![(Some(&A(1)), Some(&B(2))), (Some(&A(2)), None),]
        );
    }

    #[test]
    fn has_query() {
        let mut world = World::new();

        world.spawn((A(1), B(1)));
        world.spawn(A(2));
        world.spawn((A(3), B(1)));
        world.spawn(A(4));

        let values: HashSet<(&A, bool)> = world.query::<(&A, Has<B>)>().iter(&world).collect();

        assert!(values.contains(&(&A(1), true)));
        assert!(values.contains(&(&A(2), false)));
        assert!(values.contains(&(&A(3), true)));
        assert!(values.contains(&(&A(4), false)));
    }

    #[test]
    #[should_panic = "&mut bevy_ecs::query::tests::A conflicts with a previous access in this query."]
    fn self_conflicting_worldquery() {
        #[derive(QueryData)]
        #[query_data(mutable)]
        struct SelfConflicting {
            a: &'static mut A,
            b: &'static mut A,
        }

        let mut world = World::new();
        world.query::<SelfConflicting>();
    }

    #[test]
    fn derived_worldqueries() {
        let mut world = World::new();

        world.spawn((A(10), B(18), C(3), Sparse(4)));

        world.spawn((A(101), B(148), C(13)));
        world.spawn((A(51), B(46), Sparse(72)));
        world.spawn((A(398), C(6), Sparse(9)));
        world.spawn((B(11), C(28), Sparse(92)));

        world.spawn((C(18348), Sparse(101)));
        world.spawn((B(839), Sparse(5)));
        world.spawn((B(6721), C(122)));
        world.spawn((A(220), Sparse(63)));
        world.spawn((A(1092), C(382)));
        world.spawn((A(2058), B(3019)));

        world.spawn((B(38), C(8), Sparse(100)));
        world.spawn((A(111), C(52), Sparse(1)));
        world.spawn((A(599), B(39), Sparse(13)));
        world.spawn((A(55), B(66), C(77)));

        world.spawn_empty();

        {
            #[derive(QueryData)]
            struct CustomAB {
                a: &'static A,
                b: &'static B,
            }

            let custom_param_data = world
                .query::<CustomAB>()
                .iter(&world)
                .map(|item| (*item.a, *item.b))
                .collect::<Vec<_>>();
            let normal_data = world
                .query::<(&A, &B)>()
                .iter(&world)
                .map(|(a, b)| (*a, *b))
                .collect::<Vec<_>>();
            assert_eq!(custom_param_data, normal_data);
        }

        {
            #[derive(QueryData)]
            struct FancyParam {
                e: Entity,
                b: &'static B,
                opt: Option<&'static Sparse>,
            }

            let custom_param_data = world
                .query::<FancyParam>()
                .iter(&world)
                .map(|fancy| (fancy.e, *fancy.b, fancy.opt.copied()))
                .collect::<Vec<_>>();
            let normal_data = world
                .query::<(Entity, &B, Option<&Sparse>)>()
                .iter(&world)
                .map(|(e, b, opt)| (e, *b, opt.copied()))
                .collect::<Vec<_>>();
            assert_eq!(custom_param_data, normal_data);
        }

        {
            #[derive(QueryData)]
            struct MaybeBSparse {
                blah: Option<(&'static B, &'static Sparse)>,
            }
            #[derive(QueryData)]
            struct MatchEverything {
                abcs: AnyOf<(&'static A, &'static B, &'static C)>,
                opt_bsparse: MaybeBSparse,
            }

            let custom_param_data = world
                .query::<MatchEverything>()
                .iter(&world)
                .map(
                    |MatchEverythingItem {
                         abcs: (a, b, c),
                         opt_bsparse: MaybeBSparseItem { blah: bsparse },
                     }| {
                        (
                            (a.copied(), b.copied(), c.copied()),
                            bsparse.map(|(b, sparse)| (*b, *sparse)),
                        )
                    },
                )
                .collect::<Vec<_>>();
            let normal_data = world
                .query::<(AnyOf<(&A, &B, &C)>, Option<(&B, &Sparse)>)>()
                .iter(&world)
                .map(|((a, b, c), bsparse)| {
                    (
                        (a.copied(), b.copied(), c.copied()),
                        bsparse.map(|(b, sparse)| (*b, *sparse)),
                    )
                })
                .collect::<Vec<_>>();
            assert_eq!(custom_param_data, normal_data);
        }

        {
            #[derive(QueryFilter)]
            struct AOrBFilter {
                a: Or<(With<A>, With<B>)>,
            }
            #[derive(QueryFilter)]
            struct NoSparseThatsSlow {
                no: Without<Sparse>,
            }

            let custom_param_entities = world
                .query_filtered::<Entity, (AOrBFilter, NoSparseThatsSlow)>()
                .iter(&world)
                .collect::<Vec<_>>();
            let normal_entities = world
                .query_filtered::<Entity, (Or<(With<A>, With<B>)>, Without<Sparse>)>()
                .iter(&world)
                .collect::<Vec<_>>();
            assert_eq!(custom_param_entities, normal_entities);
        }

        {
            #[derive(QueryFilter)]
            struct CSparseFilter {
                tuple_structs_pls: With<C>,
                ugh: With<Sparse>,
            }

            let custom_param_entities = world
                .query_filtered::<Entity, CSparseFilter>()
                .iter(&world)
                .collect::<Vec<_>>();
            let normal_entities = world
                .query_filtered::<Entity, (With<C>, With<Sparse>)>()
                .iter(&world)
                .collect::<Vec<_>>();
            assert_eq!(custom_param_entities, normal_entities);
        }

        {
            #[derive(QueryFilter)]
            struct WithoutComps {
                _1: Without<A>,
                _2: Without<B>,
                _3: Without<C>,
            }

            let custom_param_entities = world
                .query_filtered::<Entity, WithoutComps>()
                .iter(&world)
                .collect::<Vec<_>>();
            let normal_entities = world
                .query_filtered::<Entity, (Without<A>, Without<B>, Without<C>)>()
                .iter(&world)
                .collect::<Vec<_>>();
            assert_eq!(custom_param_entities, normal_entities);
        }

        {
            #[derive(QueryData)]
            struct IterCombAB {
                a: &'static A,
                b: &'static B,
            }

            let custom_param_data = world
                .query::<IterCombAB>()
                .iter_combinations::<2>(&world)
                .map(|[item0, item1]| [(*item0.a, *item0.b), (*item1.a, *item1.b)])
                .collect::<Vec<_>>();
            let normal_data = world
                .query::<(&A, &B)>()
                .iter_combinations(&world)
                .map(|[(a0, b0), (a1, b1)]| [(*a0, *b0), (*a1, *b1)])
                .collect::<Vec<_>>();
            assert_eq!(custom_param_data, normal_data);
        }
    }

    #[test]
    fn many_entities() {
        let mut world = World::new();
        world.spawn((A(0), B(0)));
        world.spawn((A(0), B(0)));
        world.spawn(A(0));
        world.spawn(B(0));
        {
            fn system(has_a: Query<Entity, With<A>>, has_a_and_b: Query<(&A, &B)>) {
                assert_eq!(has_a_and_b.iter_many(&has_a).count(), 2);
            }
            let mut system = IntoSystem::into_system(system);
            system.initialize(&mut world);
            system.run((), &mut world);
        }
        {
            fn system(has_a: Query<Entity, With<A>>, mut b_query: Query<&mut B>) {
                let mut iter = b_query.iter_many_mut(&has_a);
                while let Some(mut b) = iter.fetch_next() {
                    b.0 = 1;
                }
            }
            let mut system = IntoSystem::into_system(system);
            system.initialize(&mut world);
            system.run((), &mut world);
        }
        {
            fn system(query: Query<(Option<&A>, &B)>) {
                for (maybe_a, b) in &query {
                    match maybe_a {
                        Some(_) => assert_eq!(b.0, 1),
                        None => assert_eq!(b.0, 0),
                    }
                }
            }
            let mut system = IntoSystem::into_system(system);
            system.initialize(&mut world);
            system.run((), &mut world);
        }
    }

    #[test]
    fn mut_to_immut_query_methods_have_immut_item() {
        #[derive(Component)]
        struct Foo;

        let mut world = World::new();
        let e = world.spawn(Foo).id();

        // state
        let mut q = world.query::<&mut Foo>();
        let _: Option<&Foo> = q.iter(&world).next();
        let _: Option<[&Foo; 2]> = q.iter_combinations::<2>(&world).next();
        let _: Option<&Foo> = q.iter_manual(&world).next();
        let _: Option<&Foo> = q.iter_many(&world, [e]).next();
        q.iter(&world).for_each(|_: &Foo| ());

        let _: Option<&Foo> = q.get(&world, e).ok();
        let _: Option<&Foo> = q.get_manual(&world, e).ok();
        let _: Option<[&Foo; 1]> = q.get_many(&world, [e]).ok();
        let _: Option<&Foo> = q.get_single(&world).ok();
        let _: &Foo = q.single(&world);

        // system param
        let mut q = SystemState::<Query<&mut Foo>>::new(&mut world);
        let q = q.get_mut(&mut world);
        let _: Option<&Foo> = q.iter().next();
        let _: Option<[&Foo; 2]> = q.iter_combinations::<2>().next();
        let _: Option<&Foo> = q.iter_many([e]).next();
        q.iter().for_each(|_: &Foo| ());

        let _: Option<&Foo> = q.get(e).ok();
        let _: Option<[&Foo; 1]> = q.get_many([e]).ok();
        let _: Option<&Foo> = q.get_single().ok();
        let _: [&Foo; 1] = q.many([e]);
        let _: &Foo = q.single();
    }

    // regression test for https://github.com/bevyengine/bevy/pull/8029
    #[test]
    fn par_iter_mut_change_detection() {
        let mut world = World::new();
        world.spawn((A(1), B(1)));

        fn propagate_system(mut query: Query<(&A, &mut B), Changed<A>>) {
            query.par_iter_mut().for_each(|(a, mut b)| {
                b.0 = a.0;
            });
        }

        fn modify_system(mut query: Query<&mut A>) {
            for mut a in &mut query {
                a.0 = 2;
            }
        }

        let mut schedule = Schedule::default();
        schedule.add_systems((propagate_system, modify_system).chain());
        schedule.run(&mut world);
        world.clear_trackers();
        schedule.run(&mut world);
        world.clear_trackers();

        let values = world.query::<&B>().iter(&world).collect::<Vec<&B>>();
        assert_eq!(values, vec![&B(2)]);
    }
}