Skip to content

Instantly share code, notes, and snippets.

@ZeroErrors
Created September 4, 2023 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZeroErrors/39c8d2a5653a00b8726cd8f2c748ea58 to your computer and use it in GitHub Desktop.
Save ZeroErrors/39c8d2a5653a00b8726cd8f2c748ea58 to your computer and use it in GitHub Desktop.
flecs - Iterate Relation Component C++ Example
#include "flecs.h"
#include <iostream>
struct Position {
float x;
float y;
};
struct Start {};
struct End {};
int main(int argc, char* argv[])
{
flecs::world ecs{argc, argv};
ecs.component<Position>();
// Constrcut example entities
ecs.entity("L1")
.set<Position, Start>({ 0.f, 0.f })
.set<Position, End>({ 1.f, 1.f });
auto first = ecs.entity("first");
auto second = ecs.entity("second");
ecs.entity("L2")
.set<Position>(first, { 0.f, 0.f })
.set<Position>(second, { 1.f, 1.f });
// Filter for entities
std::cout << std::endl << "Filter Each Entity" << std::endl;
ecs.filter_builder<>()
.with<Position>(flecs::Any) // Find any entity with a (Position, ?) pair
.each([](flecs::entity e) {
std::cout << e.name() << std::endl;
flecs::entity target;
for (int index = 0; target = e.target<Position>(index); index++)
{
auto value = e.get<Position>(target);
std::cout << target.name() << " = { x:" << value->x << ", y:" << value->y << " }" << std::endl;
}
std::cout << std::endl;
});
std::cout << "Filter Each Relation" << std::endl;
ecs.filter_builder<>()
.with<Position>(flecs::Wildcard) // Find all instances with a (Position, ?) pair
.build()
.iter([](flecs::iter& it) {
auto column = it.field<Position>(1);
for (auto i : it) {
auto& value = column[i];
std::cout << it.entity(i).name() << ", " << it.pair(1).second().name() << " = { x:" << value.x << ", y:" << value.y << " }" << std::endl;
}
});
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment