### Build All Examples with Bake Source: https://github.com/sandermertens/flecs/blob/master/examples/README.md Use Bake to build all available examples in the repository. ```bash bake examples ``` -------------------------------- ### Run a Single Example with Bake (Release Config) Source: https://github.com/sandermertens/flecs/blob/master/examples/README.md Execute a specific example using Bake with the 'release' configuration enabled for optimizations. ```bash bake run examples/c/entities/basics --cfg release ``` -------------------------------- ### Run Flecs example Source: https://github.com/sandermertens/flecs/blob/master/examples/build/bazel/README.md Execute the provided example project using the Bazel CLI. ```bash bazel run //example ``` -------------------------------- ### Run a Single Example with Bake Source: https://github.com/sandermertens/flecs/blob/master/examples/README.md Use Bake to run a specific example. Specify the path to the example relative to the repository root. ```bash bake run examples/c/entities/basics ``` -------------------------------- ### Build C Examples with CMake Source: https://github.com/sandermertens/flecs/blob/master/examples/README.md Use these commands to build the C examples with CMake. Navigate to the 'examples/c' directory and create a build directory. ```bash cd examples/c mkdir cmake_build cd cmake_build cmake .. cmake --build . ``` -------------------------------- ### Run a Single C Example (Static) Source: https://github.com/sandermertens/flecs/blob/master/examples/README.md Execute a specific C example binary from the 'cmake_build' directory. Binaries linked with the static library have the '_static' postfix. ```bash ./entities_basics_static ``` -------------------------------- ### Build C++ Examples with CMake Source: https://github.com/sandermertens/flecs/blob/master/examples/README.md Use these commands to build the C++ examples with CMake. Navigate to the 'examples/cpp' directory and create a build directory. ```bash cd examples/cpp mkdir cmake_build cd cmake_build cmake .. cmake --build . ``` -------------------------------- ### Add, Set, Get, and Remove Components in C# Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Provides examples for component manipulation in C#. Covers adding, setting values, retrieving, and removing components using the C# API. ```cs Entity e = world.Entity(); // Add a component. This creates the component in the ECS storage, but does not // assign it with a value. e.Add(); // Set the value for the Position & Velocity components. A component will be // added if the entity doesn't have it yet. e.Set(new(10, 20)) .Set(new(1, 2)); // Get a component ref readonly Position p = ref e.Get(); // Remove component e.Remove(); ``` -------------------------------- ### Prefab Inheritance Setup (C++ v3 vs v4) Source: https://github.com/sandermertens/flecs/blob/master/docs/MigrationGuide.md Compares C++ prefab inheritance setup. v4 uses `world.component().add(flecs::OnInstantiate, flecs::Inherit)` to enable inheritance for components. ```cpp // v3 flecs::entity p = world.prefab("SpaceShip") .set(MaxSpeed{100}) .set_override(Damage{0}); flecs::entity i = world.entity().is_a(p); ``` ```cpp // v4 world.component().add(flecs::OnInstantiate, flecs::Inherit); flecs::entity p = world.prefab("SpaceShip") .set(MaxSpeed{100}) .set(Damage{0}); flecs::entity i = world.entity().is_a(p); ``` -------------------------------- ### Query Singleton Components Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Examples showing how to include singleton components in queries and systems. ```c ecs_add_id(world, ecs_id(Gravity), EcsSingleton); // Create query that matches Gravity as singleton ecs_query_t *q = ecs_query(world, { .terms = { // Regular component { .id = ecs_id(Velocity) }, // A singleton is a component matched on itself { .id = ecs_id(Gravity), .src.id = ecs_id(Gravity) } } }); // Create a system using the query DSL with a singleton: ECS_SYSTEM(world, ApplyGravity, EcsOnUpdate, Velocity, Gravity); ``` ```cpp world.query_builder() .build(); ``` ```cs world.QueryBuilder().Build(); ``` ```rust world .query::<(&Velocity, &Gravity)>() .build(); ``` ```clojure (vf/with-query w [_ Velocity pos [:src Position Position]] pos) ``` -------------------------------- ### C: Set and Get Singleton Component Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Demonstrates how to set and get a singleton component in C. Ensure the component is registered before use. ```c ECS_COMPONENT(world, TimeOfDay); // Set singleton ecs_singleton_set(world, TimeOfDay, { 0.5 }); // Get singleton const TimeOfDay *t = ecs_singleton_get(world, TimeOfDay); ``` -------------------------------- ### C99 System Example Source: https://github.com/sandermertens/flecs/blob/master/README.md Demonstrates defining components, systems, and entities in C99. ```c typedef struct { float x, y; } Position, Velocity; void Move(ecs_iter_t *it) { Position *p = ecs_field(it, Position, 0); Velocity *v = ecs_field(it, Velocity, 1); for (int i = 0; i < it->count; i++) { p[i].x += v[i].x; p[i].y += v[i].y; } } int main(int argc, char *argv[]) { ecs_world_t *ecs = ecs_init(); ECS_COMPONENT(ecs, Position); ECS_COMPONENT(ecs, Velocity); ECS_SYSTEM(ecs, Move, EcsOnUpdate, Position, Velocity); ecs_entity_t e = ecs_insert(ecs, ecs_value(Position, {10, 20}), ecs_value(Velocity, {1, 2})); while (ecs_progress(ecs, 0)) { } } ``` -------------------------------- ### C#: Set and Get Singleton Component Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Illustrates setting and getting a singleton component in C#. This is useful for global game resources. ```cs // Set singleton world.Set(new TimeOfDay(0.5)); // Get singleton ref readonly TimeOfDay t = ref world.Get(); ``` -------------------------------- ### Full template example with parameters Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsScriptTutorial.md This is a complete example of a template definition for a fence, including parameterized properties for dimensions and color, and its instantiation with specific values. ```js using flecs.components.* const PI = 3.1415926 plane { - Position3{} - Rotation3{PI / 2} - Rectangle{10000, 10000} - Rgb{0.9, 0.9, 0.9} } template Fence { const width = 20 const height = 10 const color : Rgb = {0.15, 0.1, 0.05} const pillar_width = 2 const pillar_box : Box = { $pillar_width, $height, $pillar_width } with $color, $pillar_box { left_pillar { - Position3{x: - $width/2, y: $height/2} } right_pillar { - Position3{x: $width/2, y: $height/2} } } const bar_sep = 4 const bar_height = 2 const bar_depth = $pillar_width/2 const bar_box : Box = { $width, $bar_height, $bar_depth } with $color, $bar_box { top_bar { - Position3{y: $height/2 + $bar_sep/2} } bottom_bar { - Position3{y: $height/2 - $bar_sep/2} } } } // Prefab Fence fence_a : Fence { - Position3{-10} } fence_b : Fence { - Position3{10} } ``` -------------------------------- ### Instantiate Prefabs in C and C++ Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsScriptTutorial.md Examples showing how to load a Flecs script file and instantiate entities based on a defined prefab. ```c // In C ecs_script_run_file(world, "fence.flecs"); ecs_entity_t fence = ecs_lookup(world, "Fence"); ecs_entity_t fence_a = ecs_new_w_pair(world, EcsIsA, fence); ecs_entity_t fence_b = ecs_new_w_pair(world, EcsIsA, fence); ecs_set(world, fence_a, EcsPosition3, {-10}); ecs_set(world, fence_b, EcsPosition3, {10}); ``` ```cpp // In C++ using namespace flecs::components::transform; ecs_script_run_file(world, "fence.flecs"); auto fence = world.lookup("Fence"); auto fence_a = world.entity().is_a(fence); auto fence_b = world.entity().is_a(fence); fence_a.set({-10}); fence_b.set({10}); ``` -------------------------------- ### C++ System Example Source: https://github.com/sandermertens/flecs/blob/master/README.md Demonstrates defining components, systems, and entities in C++ using the Flecs C++ API. ```cpp struct Position { float x, y; }; struct Velocity { float x, y; }; int main(int argc, char *argv[]) { flecs::world ecs; ecs.system() .each([](Position& p, const Velocity& v) { p.x += v.x; p.y += v.y; }); auto e = ecs.entity() .insert([](Position& p, Velocity& v) { p = {10, 20}; v = {1, 2}; }); while (ecs.progress()) { } } ``` -------------------------------- ### Flecs Query Language examples Source: https://github.com/sandermertens/flecs/blob/master/docs/Queries.md A collection of equality and inequality operator examples in the Flecs Query Language. ```js $this == Foo $this != Foo $this == "Foo" $this != "Fo" ``` -------------------------------- ### Implement and Register a Monitor Source: https://github.com/sandermertens/flecs/blob/master/docs/ObserversManual.md Examples of defining and using monitor observers across different supported languages. ```c void MyMonitor(ecs_iter_t *it) { if (it->event == EcsOnAdd) { for (int i = 0; i < it->count; i ++) { // Entity started matching query } } else if (it->event == EcsOnRemove) { for (int i = 0; i < it->count; i ++) { // Entity stopped matching query } } } // Monitor observer for Position, (ChildOf, *) ecs_observer(world, { .query.terms = { { ecs_id(Position) }, { ecs_pair(EcsChildOf, EcsWildcard) } }, .events = { EcsMonitor }, .callback = MyMonitor }); ecs_entity_t p_a = ecs_new(world); ecs_entity_t p_b = ecs_new(world); ecs_entity_t e = ecs_new(world); // Doesn't trigger the monitor, entity doesn't match ecs_set(world, e, Position, {10, 20}); // Entity now matches, triggers monitor with OnAdd event ecs_add(world, e, EcsChildOf, p_a); // Entity still matches the query, monitor doesn't trigger ecs_add(world, e, EcsChildOf, p_b); // Entity no longer matches, triggers monitor with OnRemove event ecs_remove(world, e, Position); ``` ```cpp // Monitor observer for Position, (ChildOf, *) world.observer() .with(flecs::ChildOf, flecs::Wildcard) .event(flecs::Monitor) .each([](flecs::iter& it, size_t i, Position& p) { if (it.event() == flecs::OnAdd) { // Entity started matching query } else if (it.event() == flecs::OnRemove) { // Entity stopped matching query } }); flecs::entity p_a = world.entity(); flecs::entity p_b = world.entity(); flecs::entity e = world.entity(); // Doesn't trigger the monitor, entity doesn't match e.set(Position{10, 20}); // Entity now matches, triggers monitor with OnAdd event e.child_of(p_a); // Entity still matches the query, monitor doesn't trigger e.child_of(p_b); // Entity no longer matches, triggers monitor with OnRemove event e.remove(); ``` ```cs // Monitor observer for Position, (ChildOf, *) world.Observer() .With(Ecs.ChildOf, Ecs.WildCard) .Event(Ecs.Monitor) .Each((Iter it, int i, ref Position p) => { if (it.Event() == Ecs.OnAdd) { // Entity started matching query } else if (it.Event() == Ecs.OnRemove) { // Entity stopped matching query } }); Entity p_a = world.Entity(); Entity p_b = world.Entity(); Entity e = world.Entity(); // Doesn't trigger the monitor, entity doesn't match e.Set(new Position(10, 20)); // Entity now matches, triggers monitor with OnAdd event e.ChildOf(p_a); // Entity still matches the query, monitor doesn't trigger e.ChildOf(p_b); // Entity no longer matches, triggers monitor with OnRemove event e.Remove(); ``` ```rust // Monitor observer for Position, (ChildOf, *) world .observer::() .with::(flecs::Wildcard) .each_iter(|it, i, (p, v)| { if it.event() == flecs::OnAdd::ID { // Entity started matching query } else if it.event() == flecs::OnRemove::ID { // Entity stopped matching query } }); let p_a = world.entity(); let p_b = world.entity(); let e = world.entity(); // Doesn't trigger the monitor, entity doesn't match e.set(Position { x: 10.0, y: 20.0 }); // Entity now matches, triggers monitor with OnAdd event e.child_of(p_a); // Entity still matches the query, monitor doesn't trigger e.child_of(p_b); // Entity no longer matches, triggers monitor with OnRemove event e.remove::(); ``` -------------------------------- ### Rust: OnAdd Observer Example Source: https://github.com/sandermertens/flecs/blob/master/docs/ObserversManual.md Provides a Rust example of an OnAdd observer, highlighting that it activates only on the first component addition to an entity. Re-adding the component does not trigger the observer. ```rust let e = world.entity(); // OnAdd observer fires e.add::(); // OnAdd observer doesn't fire, entity already has component e.add::(); ``` -------------------------------- ### Component Registration with Modules (C++) Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Organize component registration in C++ using modules. This example shows how to define and import a module for components. ```cpp struct movement { movement(flecs::world& world) { world.component(); world.component(); } }; flecs::world world; world.import(); ``` -------------------------------- ### Expression: Component Initialization Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsScript.md Examples of initializing component values using direct struct initialization or named members. ```cpp const x: Position: {10, 20} const x: Position: {x: 10, y: 20} ``` -------------------------------- ### Get Component Entity and Data (Rust) Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Provides a Rust example for getting a component's entity and accessing its metadata. ```Rust // Get the entity for the Position component let pos = world.component::(); // Component entities have the Component component pos.get::<&flecs::Component>(|comp_data| { println!( "size: {}, alignment: 2%", comp_data.size, comp_data.alignment ); }); ``` -------------------------------- ### Get Component Size (Rust) Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Provides a Rust example for fetching component size. It uses the entity system to get the component's metadata, including its size. ```rust let pos_e = world.entity_from::(); pos_e.get::<&flecs::Component>(|c| { println!("Component size: {}", c.size); }); ``` -------------------------------- ### Build Android with Ninja Source: https://github.com/sandermertens/flecs/blob/master/docs/BuildingFlecs.md After configuring the Android build with CMake, navigate to the 'build_android' directory and run 'ninja' to start the build process. ```bash ninja ``` -------------------------------- ### Query Entities with Components (HTTP) Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsRemoteApi.md Example of an HTTP GET request to query entities that have both 'Position' and 'Velocity' components. ```HTTP GET /query?expr=Position%2CVelocity ``` -------------------------------- ### Manage Singleton Components via Entity API Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md These examples demonstrate how to treat a component as a singleton by adding it to its own entity ID. ```c ecs_set(world, ecs_id(Gravity), Gravity, {9.81}); const Gravity *g = ecs_get(world, ecs_id(Gravity), Gravity); ``` ```cpp flecs::entity grav_e = world.entity(); grav_e.set({9.81}); const Gravity& g = grav_e.get(); ``` ```cs Entity gravE = world.Entity(); gravE.Set(new(10, 20)); ref readonly Gravity g = ref gravE.Get(); ``` ```rust let grav_e = world.entity_from::(); grav_e.set(Gravity { x: 10, y: 20 }); grav_e.get::<&Gravity>(|g| { println!("Gravity: {}, {}", g.x, g.y); }); ``` ```clojure (merge w {Position [(Position [30 40])]}) (get-in w [Position Position]) ``` -------------------------------- ### GET /commands/capture Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsRemoteApi.md Starts capturing deferred commands, allowing them to be retrieved per frame via `/commands/frame/`. ```APIDOC ## GET /commands/capture ### Description Start capturing deferred commands so they can be retrieved per frame via `GET /commands/frame/`. Captured frames are retained for approximately 60 seconds at 60 FPS. ### Method GET ### Endpoint /commands/capture ### Response #### Success Response (200) - Indicates that command capturing has started. ``` -------------------------------- ### Query Endpoint with Variables Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsRemoteApi.md This example shows how to perform a query that involves variables, such as using a variable for a pair relationship. It includes the HTTP GET request and equivalent JavaScript, C, and C++ calls. ```APIDOC ## GET /query ### Description Performs a query on the Flecs world, supporting variables in the query expression. This example uses a variable `p` for a pair relationship. ### Method GET ### Endpoint /query ### Query Parameters - **expr** (string) - Required - The query expression, potentially containing variables. ### Request Example ```http GET /query?expr=Position%2C(ChildOf%2C%24p) ``` ### Response #### Success Response (200) - **results** (array) - An array of query results. May include `vars` object detailing variable bindings and `fields` with `ids` for variable component IDs. ``` -------------------------------- ### Prefab Inheritance Setup (C v3 vs v4) Source: https://github.com/sandermertens/flecs/blob/master/docs/MigrationGuide.md Shows how to set up prefab inheritance in C. v4 requires explicitly adding the 'EcsOnInstantiate, EcsInherit' pair to components that should inherit. ```c // v3 ecs_entity_t p = ecs_new_prefab(world, "SpaceShip"); ecs_set(world, p, MaxSpeed, {100}); ecs_set(world, p, Damage, {0}); ecs_override(world, p, Damage); ecs_entity_t i = ecs_new_w_pair(world, EcsIsA, p); ``` ```c // v4 ecs_add_pair(world, ecs_id(MaxSpeed), EcsOnInstantiate, EcsInherit); ecs_entity_t p = ecs_entity(world, { .name = "SpaceShip", .add = ecs_ids(EcsPrefab) }); ecs_set(world, p, MaxSpeed, {100}); ecs_set(world, p, Damage, {0}); ecs_entity_t i = ecs_new_w_pair(world, EcsIsA, p); ``` -------------------------------- ### Retrieve Entity Data Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsRemoteApi.md This example shows how to retrieve basic entity data, including its parent, name, tags, and components. The HTTP GET request to `/entity/Sun/Earth` returns a JSON object representing the entity. ```APIDOC ## GET /entity/Sun/Earth ### Description Retrieves basic information about a specific entity, including its parent, name, tags, and components. ### Method GET ### Endpoint /entity/Sun/Earth ### Response #### Success Response (200) - **parent** (string) - The parent entity's name. - **name** (string) - The entity's name. - **tags** (array) - A list of tags associated with the entity. - **components** (object) - An object containing the entity's components and their values. ``` -------------------------------- ### Query Endpoint with Fields and Entity IDs Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsRemoteApi.md This example demonstrates how to perform a query and retrieve entity IDs while excluding detailed fields. It shows the HTTP GET request and equivalent JavaScript, C, and C++ calls. ```APIDOC ## GET /query ### Description Performs a query on the Flecs world and returns results. This specific example shows how to disable field serialization and enable entity ID serialization. ### Method GET ### Endpoint /query ### Query Parameters - **expr** (string) - Required - The query expression. - **fields** (boolean) - Optional - Whether to serialize fields. Defaults to true. - **entity_ids** (boolean) - Optional - Whether to serialize entity IDs. Defaults to false. ### Request Example ```http GET /query?expr=Position%2C%3FPosition(up)&fields=false&entity_ids=true ``` ### Response #### Success Response (200) - **results** (array) - An array of query results, potentially including entity names and IDs. ``` -------------------------------- ### Query Endpoint for Meta Information Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsRemoteApi.md This example demonstrates how to retrieve meta-information about a query, such as query details and field details, without returning the actual query results. It shows the HTTP GET request and equivalent JavaScript, C, and C++ calls. ```APIDOC ## GET /query ### Description Retrieves meta-information about a query, including query structure and field details, without serializing the actual query results. ### Method GET ### Endpoint /query ### Query Parameters - **expr** (string) - Required - The query expression. - **query_info** (boolean) - Optional - Whether to serialize query information. Defaults to false. - **field_info** (boolean) - Optional - Whether to serialize field information. Defaults to false. - **results** (boolean) - Optional - Whether to serialize query results. Defaults to true. ### Request Example ```http GET /query?expr=Position%2C%3FMass(up)?query_info=true&field_info=true&results=false ``` ### Response #### Success Response (200) - The response structure will contain details about the query and its fields, as specified by `query_info` and `field_info` parameters. ``` -------------------------------- ### Staging Behavior Example Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Demonstrates how ECS operations are enqueued during staging, which may cause immediate checks to return unexpected results. ```cpp if (!e.has()) { e.add(); return e.has(); } ``` -------------------------------- ### Enable Custom Build and System Addon Source: https://github.com/sandermertens/flecs/blob/master/docs/BuildingFlecs.md Use these defines to enable a custom build and specifically include the System addon. ```c #define FLECS_CUSTOM_BUILD // Don't build all addons #define FLECS_SYSTEM // Build FLECS_SYSTEM ``` -------------------------------- ### Group entities by region in Rust Source: https://github.com/sandermertens/flecs/blob/master/docs/Queries.md Reference to the group_by example implementation in the Rust examples folder. ```rust // see example in examples folder under query/group_by ``` -------------------------------- ### Define and Run C System with ecs_system_init Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Demonstrates defining a system in C using the ecs_system_init function and then running it. This provides more explicit control over system initialization. ```c // Option 2, use the ecs_system_init function/ecs_system macro ecs_entity_t move_sys = ecs_system(world, { .query.terms = { { ecs_id(Position) }, { ecs_id(Velocity) }, }, .callback = Move }); ecs_run(world, move_sys, delta_time, NULL); // Run system ``` -------------------------------- ### Flecs Query Language Examples Source: https://github.com/sandermertens/flecs/blob/master/docs/Queries.md Examples of using member value queries with the Flecs Query Language, including wildcards and variables. ```text Movement.direction($this, Left) ``` ```text Movement.value($this, *) ``` ```text Movement.value($this, $direction), $direction != Left ``` -------------------------------- ### Create and Lookup Entity by Name (C) Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Demonstrates creating an entity with a name and looking it up using the world. Also shows how to retrieve the entity's name. ```C ecs_entity_t e = ecs_entity(world, { .name = "MyEntity" }); if (e == ecs_lookup(world, "MyEntity")) { // true } printf("%s\n", ecs_get_name(world, e)); ``` -------------------------------- ### Create and Lookup Entity by Name (C++) Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Demonstrates creating an entity with a name and looking it up using the world. Also shows how to retrieve the entity's name. ```cpp flecs::entity e = world.entity("MyEntity"); if (e == world.lookup("MyEntity")) { // true } std::cout << e.name() << std::endl; ``` -------------------------------- ### Instantiate a simple prefab Source: https://github.com/sandermertens/flecs/blob/master/docs/PrefabsManual.md Demonstrates creating a prefab entity with a component and instantiating it using the EcsIsA relationship. ```c ECS_COMPONENT(ecs, Defense); // Create a SpaceShip prefab with a Defense component. ecs_entity_t SpaceShip = ecs_entity(ecs, { .name = "SpaceShip", .add = ecs_ids( EcsPrefab ) }); ecs_set(ecs, SpaceShip, Defense, {50}); // Create two prefab instances ecs_entity_t inst_1 = ecs_new_w_pair(world, EcsIsA, SpaceShip); ecs_entity_t inst_2 = ecs_new_w_pair(world, EcsIsA, SpaceShip); // Get instantiated component const Defense *d = ecs_get(world, inst_1, Defense); ``` ```cpp struct Defense { float value; }; // Create a SpaceShip prefab with a Defense component. flecs::entity SpaceShip = world.prefab("SpaceShip") .set(Defense{50}); // Create two prefab instances flecs::entity inst_1 = world.entity().is_a(SpaceShip); flecs::entity inst_2 = world.entity().is_a(SpaceShip); // Get instantiated component const Defense& d = inst_1.get(); ``` ```cs public record struct Defense(double Value); // Create a SpaceShip prefab with a Defense component. Entity spaceship = world.Entity("Spaceship") .Set(new Defense(50)); // Create two prefab instances Entity inst1 = world.Entity().IsA(spaceship); Entity inst2 = world.Entity().IsA(spaceship); // Get instantiated component ref readonly Defense attack = ref inst1.Get(); ``` ```rust #[derive(Component)] struct Defense { value: u32, } // Create a spaceship prefab with a Defense component. let spaceship = world.prefab_named("spaceship").set(Defense { value: 50 }); // Create two prefab instances let inst_1 = world.entity().is_a_id(spaceship); let inst_2 = world.entity().is_a_id(spaceship); // Get instantiated component inst_1.get::<&Defense>(|defense| { println!("Defense value: {}", defense.value); }); ``` -------------------------------- ### Create and Use Custom Pipeline (C) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Defines a custom pipeline that matches systems with the 'Foo' tag and configures the world to use it. Includes an example system and progress call. ```c ECS_TAG(world, Foo); // Create custom pipeline ecs_entity_t pipeline = ecs_pipeline_init(world, &(ecs_pipeline_desc_t){ .query.terms = { { .id = EcsSystem }, // mandatory { .id = Foo } } }); // Configure the world to use the custom pipeline ecs_set_pipeline(world, pipeline); // Create system ECS_SYSTEM(world, Move, Foo, Position, Velocity); // Runs the pipeline & system ecs_progress(world, 0); ``` -------------------------------- ### Create and Lookup Entity by Name (C#) Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Demonstrates creating an entity with a name and looking it up using the world. Also shows how to retrieve the entity's name. ```cs Entity e = world.Entity("MyEntity"); if (e == world.Lookup("MyEntity")) { // true } Console.WriteLine(e.Name()); ``` -------------------------------- ### Get Component Entity and Data (C) Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Demonstrates how to get the entity ID for a registered component in C and retrieve its metadata (size, alignment). ```C // Register component (see below) ECS_COMPONENT(world, Position); // The ecs_id() macro can be used in C to obtain the component id from a type ecs_entity_t pos = ecs_id(Position); // Component entities have the Component component const EcsComponent *comp_data = ecs_get(world, pos, EcsComponent); printf("{size: %d, alignment: %d}\n", comp_data->size, comp_data->alignment); ``` -------------------------------- ### Run System at Time Interval (C++) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a C++ system to run at a specific time interval using the `.interval()` method. This example sets the system to run at 1Hz. ```cpp world.system() .interval(1.0) // Run at 1Hz .each(...); ``` -------------------------------- ### Create Prefab Variants in C Source: https://github.com/sandermertens/flecs/blob/master/docs/PrefabsManual.md Demonstrates creating a base prefab, a variant that inherits from it, and then instantiating the variant. Overrides components on the variant to customize it. ```c ECS_COMPONENT(ecs, Health); ECS_COMPONENT(ecs, Defense); // Create prefab ecs_entity_t SpaceShip = ecs_entity(ecs, { .name = "SpaceShip", .add = ecs_ids( EcsPrefab ) }); ecs_set(ecs, SpaceShip, Defense, {50}); ecs_set(ecs, SpaceShip, Health, {100}); // Create prefab variant ecs_entity_t freighter = ecs_entity(ecs, { .name = "Freighter", .add = ecs_ids( EcsPrefab, ecs_isa(SpaceShip) ) }); // Override the Health component of the freighter ecs_set(ecs, freighter, Health, {150}); // Create prefab instance ecs_entity_t inst = ecs_new_w_pair(world, EcsIsA, Freighter); const Health *health = ecs_get(world, inst, Health); // 150 const Defense *defense = ecs_get(world, inst, Defense); // 50 ``` -------------------------------- ### Rust: Set and Get Singleton Component Source: https://github.com/sandermertens/flecs/blob/master/docs/EntitiesComponents.md Demonstrates how to set and get a singleton component in Rust. This API is designed for efficient global resource management. ```rust // Set singleton world.set(TimeOfDay { value: 0.5 }); // Get singleton world.get::<&TimeOfDay>(|time| println!("{}", time.value)); ``` -------------------------------- ### Create Prefab Hierarchy in C Source: https://github.com/sandermertens/flecs/blob/master/docs/PrefabsManual.md Shows how to create a prefab with a child entity, both as prefabs, and then instantiate the hierarchy. The child can be looked up after instantiation. ```c // Create a prefab hierarchy. ecs_entity_t SpaceShip = ecs_entity(ecs, { .name = "SpaceShip", .add = ecs_ids( EcsPrefab ) }); ecs_entity_t Cockpit = ecs_entity(ecs, { .name = "Cockpit", .parent = SpaceShip, // shortcut to add_pair(EcsChildOf) .add = ecs_ids( EcsPrefab ) }); // Instantiate the prefab hierarchy ecs_entity_t inst = ecs_new_w_pair(world, EcsIsA, SpaceShip); // Lookup instantiated child ecs_entity_t inst_cockpit = ecs_lookup_child(ecs, inst, "Cockpit"); ``` -------------------------------- ### Run System at Time Interval (C) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a system to run at a specific time interval using `ecs_set_interval`. This example sets the system to run at 1Hz. ```c // Using the ECS_SYSTEM macro ECS_SYSTEM(world, Move, EcsOnUpdate, Position, [in] Velocity); ecs_set_interval(world, ecs_id(Move), 1.0); // Run at 1Hz ``` ```c // Using the ecs_system_init function/ecs_system macro: ecs_system(world, { .entity = ecs_entity(world, { .name = "Move", .add = ecs_ids( ecs_dependson(EcsOnUpdate) ) }), .query.terms = { { ecs_id(Position) }, { ecs_id(Velocity), .inout = EcsIn } }, .callback = Move, .interval = 1.0 // Run at 1Hz }); ``` -------------------------------- ### C++ Inheritable Component and Query Source: https://github.com/sandermertens/flecs/blob/master/docs/Queries.md Demonstrates registering an inheritable component, setting up inheritance, and querying entities that inherit the component upwards. ```cpp // Register an inheritable component 'Mass' world.component().add(flecs::OnInstantiate, flecs::Inherit); flecs::entity base = world.entity() .add(); flecs::entity parent = world.entity() .add(flecs::IsA, base); // inherits Mass flecs::entity child = world.entity() .add(flecs::ChildOf, parent); // Matches 'child', because parent inherits Mass from prefab flecs::query<> q = world.query_builder() .with().up() // traverses ChildOf upwards .build(); ``` -------------------------------- ### Get Component Size (C#) Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Illustrates retrieving component size in C#. Similar to other languages, it involves getting the component entity and accessing its 'EcsComponent' data. ```csharp Entity posE = world.Entity(); ref readonly EcsComponent c = ref posE.Get(); Console.WriteLine($"Component size: {c.size}"); ``` -------------------------------- ### Get Component Size (C++) Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Shows how to get the size of a component using the C++ API. This involves obtaining the entity for the component and then retrieving its 'EcsComponent' information. ```cpp flecs::entity pos_e = world.entity(); const EcsComponent& c = pos_e.get(); std::cout << "Component size: " << c.size << std::endl; ``` -------------------------------- ### Run System at Rate (C) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a system to run every Nth frame using `ecs_set_rate`. This example sets the system to run every other frame. ```c // Using the ECS_SYSTEM macro ECS_SYSTEM(world, Move, EcsOnUpdate, Position, [in] Velocity); ecs_set_rate(world, ecs_id(Move), 2); // Run every other frame ``` ```c // Using the ecs_system_init function/ecs_system macro: ecs_system(world, { .entity = ecs_entity(world, { .name = "Move", .add = ecs_ids( ecs_dependson(EcsOnUpdate) ) }), .query.terms = { { ecs_id(Position) }, { ecs_id(Velocity), .inout = EcsIn } }, .callback = Move, .rate = 2.0 // Run every other frame }); ``` -------------------------------- ### Install Flecs Headers Source: https://github.com/sandermertens/flecs/blob/master/CMakeLists.txt Installs Flecs header files from the 'include' directory to the system's include directory. This makes the Flecs API available to other projects. ```cmake include(GNUInstallDirs) install(DIRECTORY "${PROJECT_SOURCE_DIR}/include/" DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp" PATTERN "*.inl") ``` -------------------------------- ### Run System at Rate (C#) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a C# system to run every Nth frame using the `.Rate()` method. This example sets the system to run every other frame. ```csharp world.System() .Rate(2) // Run every other frame .Each(...); ``` -------------------------------- ### Run System at Rate (C++) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a C++ system to run every Nth frame using the `.rate()` method. This example sets the system to run every other frame. ```cpp world.system() .rate(2) // Run every other frame .each(...); ``` -------------------------------- ### Get Component Size (Clojure) Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Demonstrates how to get component size in Clojure by directly interfacing with the C Flecs API. The result includes size and alignment information. ```clojure ;; We use the lower-level C Flecs API directly. (-> (vf.c/ecs-get-id w (vf/eid pos-e) (vf/eid w :vf/component)) (vp/as vf/EcsComponent)) ;; => #:vybe.flecs{EcsComponent {:size 8, :alignment 4}} ``` -------------------------------- ### Get Component Entity ID in Clojure Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Illustrates how to get the entity ID for a component in Clojure using `vf/ent`. It notes that Clojure-generated components have a prefixed name internally. ```clojure (def pos-e (vf/ent w Position)) ;; Components generated from Clojure have the name prefixed with `C_` in the Flecs internal name (vf/get-name pos-e) ;; => "C_Position" ``` -------------------------------- ### Add, Set, Get, and Remove Components in C Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Demonstrates the basic component operations in C. Components are added, set with values, retrieved, and removed from entities. ```c ECS_COMPONENT(world, Position); ECS_COMPONENT(world, Velocity); ecs_entity_t e = ecs_new(world); // Add a component. This creates the component in the ECS storage, but does not // assign it with a value. ecs_add(world, e, Velocity); // Set the value for the Position & Velocity components. A component will be // added if the entity doesn't have it yet. ecs_set(world, e, Position, {10, 20}); ecs_set(world, e, Velocity, {1, 2}); // Get a component const Position *p = ecs_get(world, e, Position); // Remove component ecs_remove(world, e, Position); ``` -------------------------------- ### Install CMake Configuration Files Source: https://github.com/sandermertens/flecs/blob/master/CMakeLists.txt Installs CMake configuration files for the Flecs package. This allows other CMake projects to find and use Flecs via `find_package(flecs)`. ```cmake install(EXPORT flecs-export DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/flecs NAMESPACE flecs:: FILE flecs-config.cmake) ``` -------------------------------- ### Install Flecs Libraries Source: https://github.com/sandermertens/flecs/blob/master/CMakeLists.txt Installs the built Flecs targets (shared and static libraries) to their respective runtime, library, and archive destinations. Also exports targets for package management. ```cmake install(TARGETS ${FLECS_TARGETS} EXPORT flecs-export RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) ``` -------------------------------- ### FlecsScript Initializer Examples Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsScript.md Demonstrates various ways to initialize composite and collection members in FlecsScript, including direct values, named members, nested structures, and arrays. ```cpp {} {10, 20} {x: 10, y: 20} {{10, 20}, {30, 40}} {start: {x: 10, y: 20}, stop: {x: 10, y: 20}} [10, 20, 30] [{10, 20}, {30, 40}, {50, 60}] {x += 10, y *= 2} ``` -------------------------------- ### CMake Build Configuration for Flecs C++ Examples Source: https://github.com/sandermertens/flecs/blob/master/examples/cpp/CMakeLists.txt This CMake script sets up the build environment for Flecs C++ examples. It defines the minimum required CMake version, sets the project name, locates the Flecs library, and includes necessary utility scripts for compilation options and warnings. It then iterates through a list of example targets to create buildable targets for each. ```cmake cmake_minimum_required(VERSION 3.5) cmake_policy(SET CMP0063 NEW) project(flecs_cpp_examples LANGUAGES CXX) set(FLECS_DIR ../..) set(CUR_DIR ${CMAKE_CURRENT_SOURCE_DIR}) add_subdirectory(${FLECS_DIR} ${CMAKE_CURRENT_BINARY_DIR}/flecs) include(../../cmake/target_default_compile_options.cmake) include(../../cmake/target_default_compile_warnings.cmake) include(../../cmake/target_default_compile_functions.cmake) list_targets(EXAMPLES) foreach (EXAMPLE ${EXAMPLES}) create_target_cxx(${EXAMPLE} "") create_target_cxx(${EXAMPLE} "static") endforeach () ``` -------------------------------- ### Rust Change Detection Example Source: https://github.com/sandermertens/flecs/blob/master/docs/Queries.md Illustrates Flecs change detection in Rust. This example shows how to build queries for detecting changes, checking if entities have been modified, and conditionally skipping updates. ```rust // Query used for change detection. let q_read = world.query::<&Position>() .detect_changes() .build(); // Query used to create changes let q_write = world.new_query::<&mut Position>(); // defaults to inout // Test if changes have occurred for anything matching the query. let changed = q_read.is_changed(); // Setting a component will update the changed state let e = world.entity().set(Position { x: 10.0, y: 20.0 }); q_write.run(|mut it| { while it.next() { if !changed { // If no changes are made to the iterated table, the skip function can be // called to prevent marking the matched components as dirty. it.skip(); } else { // Iterate as usual. It does not matter whether the code actually writes the // components or not: when a table is not skipped, components matched with // inout or out terms will be marked dirty by the iterator. } } }); q_read.run(|mut it| { while it.next() { if it.is_changed() { // Check if the current table has changed. The change state will be reset // after the table is iterated, so code can respond to changes in individual // tables. } } }); ``` -------------------------------- ### Run System at Time Interval (C#) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a C# system to run at a specific time interval using the `.Interval()` method. This example sets the system to run at 1Hz. ```csharp world.System() .Interval(1.0f) // Run at 1Hz .Each(...); ``` -------------------------------- ### Get Component Entity ID in C# Source: https://github.com/sandermertens/flecs/blob/master/docs/Quickstart.md Explains how to get the entity ID for a component in C# using `World.Entity()`. It also shows adding components to the component's entity. ```cs Entity posE = world.Entity(); Console.WriteLine($"Name: {posE.Name()}"); // outputs 'Name: Position' // It's possible to add components like you would for any entity posE.Add(); ``` -------------------------------- ### Run System at Time Interval (Rust) Source: https://github.com/sandermertens/flecs/blob/master/docs/Systems.md Configure a Rust system to run at a specific time interval using the `.interval()` method. This example sets the system to run at 1Hz. ```rust world.system::<&Position>() .interval(1.0) // Run at 1Hz .each(|p| { // ... }); ``` -------------------------------- ### Flecs Playground Script Example Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsScriptTutorial.md A comprehensive Flecs Script example used in the playground, demonstrating the use of templates, parameters, and components to build a scene including a plane, fences, and enclosing structures. ```flecs using flecs.components.* using flecs.meta using flecs.game const PI = 3.1415926 // The ground plane plane { - Position3{} - Rotation3{$PI/2} - Rectangle{10000, 10000} - Rgb{0.9, 0.9, 0.9} } template Fence { // Fence parameters prop width : f32 = 40 prop height : f32 = 20 const color : Rgb = {0.15, 0.1, 0.05} // Pillar parameters const pillar_width = 2 const pillar_spacing = 10 const pillar_count = $width / $pillar_spacing const p_grid_spacing = $width / ($pillar_count - 1) // Bar parameters const bar_spacing = 3 const bar_height = 2 const bar_depth = $pillar_width / 2 const bar_count = $height / $bar_spacing const b_grid_spacing = $height / $bar_count with Prefab, $color { Pillar : - Box { $pillar_width, $height, $pillar_width } Bar : - Box {$width, $bar_height, $bar_depth} } // Pillars pillars { - Position3{y: $height/2} - Grid{ x.count: $pillar_count, x.spacing: $p_grid_spacing prefab: Pillar } } // Bars bars { - Position3{y: $height/2} - Grid{ y.count: $bar_count, y.spacing: $b_grid_spacing prefab: Bar } } } // Prefab Fence template Enclosing { prop width: f32 = 40 prop height: f32 = 10 prop depth: f32 = 40 prop color: Rgb = {0.15, 0.1, 0.05} const width_half = $width / 2 const depth_half = $depth / 2 const PI = 3.1415926 left { - Position3{x: -$width_half} - Rotation3{y: $PI / 2} - Fence{width: $depth, height:$} } right { - Position3{x: $width_half} - Rotation3{y: $PI / 2} - Fence{width: $depth, height:$} } back { - Position3{z: -$depth_half} - Fence{width: $width, height:$} } front { - Position3{z: $depth_half} - Fence{width: $width, height:$} } } pasture : - Enclosing{ width: 100, depth: 100 height: 30 } camera { - Position3{52, 41, -82} - Rotation3{-0.45, -0.54} } ``` -------------------------------- ### Instantiate Fence Template Source: https://github.com/sandermertens/flecs/blob/master/docs/FlecsScriptTutorial.md This example shows how to instantiate the 'Fence' template. The parameters for width and height are implicitly taken from the context or default values if not specified. ```flecs fence_a { Enclosing{}} ```