examples/queries/
query_basics.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6pub struct Position {
7    pub x: f32,
8    pub y: f32,
9}
10
11#[derive(Debug, Component)]
12pub struct Velocity {
13    pub x: f32,
14    pub y: f32,
15}
16
17fn main() {
18    let world = World::new();
19
20    // Create a query for Position, Velocity. Queries are the fastest way to
21    // iterate entities as they cache results.
22    let query = world.new_query::<(&mut Position, &Velocity)>();
23
24    // Create a few test entities for a Position, Velocity query
25    world
26        .entity_named("e1")
27        .set(Position { x: 10.0, y: 20.0 })
28        .set(Velocity { x: 1.0, y: 2.0 });
29
30    world
31        .entity_named("e2")
32        .set(Position { x: 10.0, y: 20.0 })
33        .set(Velocity { x: 3.0, y: 4.0 });
34
35    // This entity will not match as it does not have Position, Velocity
36    world.entity_named("e3").set(Position { x: 10.0, y: 20.0 });
37
38    // The next lines show the different ways in which a query can be iterated.
39
40    // `The each_entity()` function iterates each entity individually and accepts an
41    // entity argument plus arguments for each query component:
42    query.each_entity(|e, (pos, vel)| {
43        pos.x += vel.x;
44        pos.y += vel.y;
45        println!("{}: [{:?}]", e.name(), pos);
46    });
47
48    // There's an equivalent function that does not include the entity argument
49    query.each(|(pos, vel)| {
50        pos.x += vel.x;
51        pos.y += vel.y;
52        println!("[{:?}]", pos);
53    });
54
55    // Iter is a bit more verbose, but allows for more control over how entities
56    // are iterated as it provides multiple entities in the same callback.
57    // There's also an `iter_only` function that only provides the iterator.
58    query.run_iter(|it, (pos, vel)| {
59        for i in it.iter() {
60            pos[i].x += vel[i].x;
61            pos[i].y += vel[i].y;
62            println!("[{:?}]", pos[i]);
63        }
64    });
65
66    // Output:
67    //  e1: [Position { x: 11.0, y: 22.0 }]
68    //  e2: [Position { x: 13.0, y: 24.0 }]
69    //  [Position { x: 12.0, y: 24.0 }]
70    //  [Position { x: 16.0, y: 28.0 }]
71    //  [Position { x: 13.0, y: 26.0 }]
72    //  [Position { x: 19.0, y: 32.0 }]
73}
74
75#[cfg(feature = "flecs_nightly_tests")]
76#[test]
77fn test() {
78    let output_capture = OutputCapture::capture().unwrap();
79    main();
80    output_capture.test("query_basics".to_string());
81}