Skip to content
Flecs v4.1
systems/run_to_each_callback

  • C++

    View on GitHub

    1#include <run_to_each_callback.h>
    2#include <iostream>
    3
    4// This example shows how a system that uses the run callback can forward to an
    5// each callback. This is often useful for installing generic behavior (like
    6// profiling, tracing) that wraps around the each callback.
    7
    8struct Position {
    9 double x, y;
    10};
    11
    12struct Velocity {
    13 double x, y;
    14};
    15
    16int main(int, char *[]) {
    17 flecs::world ecs;
    18
    19 flecs::system s = ecs.system<Position, const Velocity>()
    20 // Forward each result from the run callback to the each callback.
    21 .run([](flecs::iter& it) {
    22 std::cout << "Move begin\n";
    23
    24 // Walk over the iterator, forward to the system callback
    25 while (it.next()) {
    26 it.each();
    27 }
    28
    29 std::cout << "Move end\n";
    30 },
    31 [](flecs::entity e, Position& p, const Velocity& v) {
    32 p.x += v.x;
    33 p.y += v.y;
    34 std::cout << e.name() << ": {" << p.x << ", " << p.y << "}\n";
    35 });
    36
    37 // Create a few test entities for a Position, Velocity query
    38 ecs.entity("e1")
    39 .set<Position>({10, 20})
    40 .set<Velocity>({1, 2});
    41
    42 ecs.entity("e2")
    43 .set<Position>({10, 20})
    44 .set<Velocity>({3, 4});
    45
    46 // This entity will not match as it does not have Position, Velocity
    47 ecs.entity("e3")
    48 .set<Position>({10, 20});
    49
    50 // Run the system
    51 s.run();
    52
    53 // Output
    54 // Move begin
    55 // e1: {11, 22}
    56 // e2: {13, 24}
    57 // Move end
    58}
    flecs::system system(flecs::entity e) const
    Upcast an entity to a system.
    Definition impl.hpp:181
    flecs::entity entity(Args &&... args) const
    Create an entity.
    Definition impl.hpp:195
    flecs::string_view name() const
    Return the entity name.
    Entity.
    Definition entity.hpp:30
    Class for iterating over query results.
    Definition iter.hpp:68
    void each()
    Forward to each().
    Definition iter.hpp:481
    bool next()
    Progress iterator.
    Definition iter.hpp:465
    System.
    Definition impl.hpp:78
    system & run(Func &&func)
    Replace the system's run callback.
    Definition impl.hpp:108
    The world.
    Definition world.hpp:129