Skip to main content

examples/relationships/
relationships_basics.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Component)]
6pub struct Eats;
7
8fn main() {
9    let world = World::new();
10
11    // Entity used for Grows relationship
12    let grows = world.entity_named("Grows");
13
14    // Relationship objects
15    let apples = world.entity_named("Apples");
16    let pears = world.entity_named("Pears");
17
18    // Create an entity with 3 relationships. Relationships are like regular components,
19    // but combine two types/identifiers into an (relationship, object) pair.
20    let bob = world
21        .entity_named("Bob")
22        // Pairs can be constructed from a type and entity
23        .add((Eats, apples))
24        .add((Eats, pears))
25        // Pairs can also be constructed from two entity ids
26        .add((grows, pears));
27
28    // Has can be used with relationships as well
29    println!("Bob eats apples? {}", bob.has((Eats, apples)));
30
31    // Wildcards can be used to match relationships
32    println!(
33        "Bob grows food? {}, {}",
34        bob.has((grows, flecs::Wildcard::ID)),
35        //or you can do
36        bob.has((grows, id::<flecs::Wildcard>()))
37    );
38
39    println!();
40
41    // Print the type of the entity. Should output:
42    //   (Identifier,Name),(Eats,Apples),(Eats,Pears),(Grows,Pears)
43    println!("Bob's type: [{}]", bob.archetype());
44
45    println!();
46
47    // Relationships can be iterated for an entity. This iterates (Eats, *):
48    bob.each_target(Eats, |second| {
49        println!("Bob eats {}", second.name());
50    });
51
52    println!();
53
54    // Iterate by explicitly providing the pair. This iterates (*, Pears):
55    bob.each_pair(flecs::Wildcard::ID, pears, |id| {
56        println!("Bob {} pears", id.first_id().name());
57    });
58
59    println!();
60
61    // Get first target of relationship
62    println!("Bob eats {}", bob.target(Eats, 0).unwrap().name());
63
64    // Get second target of relationship
65    println!("Bob also eats {}", bob.target(Eats, 1).unwrap().name());
66
67    // Output:
68    //  Bob eats apples? true
69    //  Bob grows food? true, true
70
71    //  Bob's type: [(Identifier,Name), (Eats,Apples), (Eats,Pears), (Grows,Pears)]
72
73    //  Bob eats Apples
74    //  Bob eats Pears
75
76    //  Bob Eats pears
77    //  Bob Grows pears
78
79    //  Bob eats Apples
80    //  Bob also eats Pears
81}
82
83#[cfg(feature = "flecs_nightly_tests")]
84#[test]
85fn test() {
86    let output_capture = OutputCapture::capture().unwrap();
87    main();
88    output_capture.test("relationships_basics".to_string());
89}