Skip to main content

examples/reflection/
reflection_basics_bitmask.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Component)]
6struct Toppings {
7    value: u32,
8}
9
10impl Toppings {
11    const BACON: u32 = 0x1;
12    const LETTUCE: u32 = 0x2;
13    const TOMATO: u32 = 0x4;
14
15    fn new() -> Self {
16        Toppings { value: 0 }
17    }
18
19    fn add(&mut self, topping: u32) {
20        self.value |= topping;
21    }
22
23    fn remove(&mut self, topping: u32) {
24        self.value &= !topping;
25    }
26
27    fn has(&self, topping: u32) -> bool {
28        self.value & topping != 0
29    }
30}
31
32#[derive(Component)]
33struct Sandwich {
34    toppings: Toppings,
35}
36
37impl Sandwich {
38    fn new() -> Self {
39        Sandwich {
40            toppings: Toppings::new(),
41        }
42    }
43
44    fn add_topping(&mut self, topping: u32) {
45        self.toppings.add(topping);
46    }
47
48    fn remove_topping(&mut self, topping: u32) {
49        self.toppings.remove(topping);
50    }
51
52    fn has_topping(&self, topping: u32) -> bool {
53        self.toppings.has(topping)
54    }
55}
56
57fn main() {
58    let world = World::new();
59
60    world
61        .component::<Toppings>()
62        .bit("bacon", Toppings::BACON)
63        .bit("lettuce", Toppings::LETTUCE)
64        .bit("tomato", Toppings::TOMATO);
65
66    world
67        .component::<Sandwich>()
68        .member(Toppings::id(), "toppings");
69
70    // Create entity with Sandwich
71    let e = world.entity().set(Sandwich {
72        toppings: Toppings {
73            value: Toppings::BACON | Toppings::LETTUCE,
74        },
75    });
76
77    // Convert Sandwidth component to flecs expression string
78    e.get::<&Sandwich>(|val| {
79        println!("{}", world.to_expr(val));
80    });
81
82    // Output:
83    //  {toppings: lettuce|bacon}
84}
85
86#[cfg(feature = "flecs_nightly_tests")]
87#[test]
88fn test() {
89    let output_capture = OutputCapture::capture().unwrap();
90    main();
91    output_capture.test("reflection_bitmask".to_string());
92}