Skip to content

Instantly share code, notes, and snippets.

@ZeroErrors
Last active July 21, 2023 17:07
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/8121827b7d0cce2639a782523f693442 to your computer and use it in GitHub Desktop.
Save ZeroErrors/8121827b7d0cce2639a782523f693442 to your computer and use it in GitHub Desktop.
flecs - Query for relationship example
#include <iostream>
#include "flecs.h"
struct Position
{
int x, y, z;
};
struct Tag1 {};
struct Tag2 {};
int main(int argc, char* argv[])
{
{
flecs::world ecs(argc, argv);
std::cout << "Tag1" << std::endl;
// Tag1 is a regular tag, this means pairs with this tag will be stored per table.
// Each unique combination of (Tag1, *) makes a new table.
ecs.component<Tag1>();
ecs.system()
.with<Tag1>(flecs::Wildcard) // Query for anything with relation (Tag1, *)
.iter([](flecs::iter& it) {
auto ecs = it.world();
auto second = it.pair(1).second();
// All of these entities have (Tag1, second)
std::cout << "iter: " << second.name() << std::endl;
for (auto i : it) {
auto entity = it.entity(i);
std::cout << "- " << entity.name() << std::endl;
}
});
// Create entities for example
auto e1 = ecs.entity("e1")
.set<Position>({ 0, 1, 0 });
auto e2 = ecs.entity("e2")
.set<Position>({ 0, 0, 1 });
ecs.entity("t1-1")
.add<Tag1>(e1);
ecs.entity("t1-2")
.add<Tag1>(e2);
ecs.progress();
}
std::cout << std::endl;
{
flecs::world ecs(argc, argv);
std::cout << "Tag2" << std::endl;
// Tag2 is a Union tag, this means entities with different combinations of (Tag2, *) can share the same
// table. The table column will store the entity id for the second part of the relation.
ecs.component<Tag2>()
.add(flecs::Union);
ecs.system()
.with<Tag2>(flecs::Wildcard) // Query for anything with relation (Tag2, *)
.iter([](flecs::iter& it) {
auto ecs = it.world();
auto secondColumn = it.field<flecs::entity_t>(1);
std::cout << "iter" << std::endl;
for (auto i : it) {
auto entity = it.entity(i);
auto second = ecs.entity(secondColumn[i]);
// This entity has (Tag2, second)
std::cout << "- " << entity.name() << ", " << second.name() << std::endl;
}
});
// Create entities for example
auto e1 = ecs.entity("e1")
.set<Position>({ 0, 1, 0 });
auto e2 = ecs.entity("e2")
.set<Position>({ 0, 0, 1 });
ecs.entity("t2-1")
.add<Tag2>(e1);
ecs.entity("t2-2")
.add<Tag2>(e2);
ecs.progress();
}
return 0;
}
Tag1
iter: e1
- t1-1
iter: e2
- t1-2
Tag2
iter
- t2-1, e1
- t2-2, e2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment