diff --git a/flecs.h b/flecs.h index d0cf66d7b..f9d7f3d3a 100644 --- a/flecs.h +++ b/flecs.h @@ -22165,6 +22165,12 @@ struct iter { return ecs_field_column_index(m_iter, index); } + /** Obtain term that triggered an observer + */ + int32_t term_index() const { + return m_iter->term_index + 1; // in iter_t, the term index is zero-based, so add 1. + } + /** Convert current iterator result to string. */ flecs::string str() const { diff --git a/include/flecs/addons/cpp/iter.hpp b/include/flecs/addons/cpp/iter.hpp index 3a6afde5f..1ad25c45f 100644 --- a/include/flecs/addons/cpp/iter.hpp +++ b/include/flecs/addons/cpp/iter.hpp @@ -220,6 +220,12 @@ struct iter { return ecs_field_column_index(m_iter, index); } + /** Obtain term that triggered an observer + */ + int32_t term_index() const { + return m_iter->term_index + 1; // in iter_t, the term index is zero-based, so add 1. + } + /** Convert current iterator result to string. */ flecs::string str() const { diff --git a/test/cpp_api/project.json b/test/cpp_api/project.json index 9bac0713c..a09c21a31 100644 --- a/test/cpp_api/project.json +++ b/test/cpp_api/project.json @@ -924,7 +924,8 @@ "on_add_with_pair_singleton", "add_in_yield_existing", "add_in_yield_existing_multi", - "name_from_root" + "name_from_root", + "term_index" ] }, { "id": "Filter", diff --git a/test/cpp_api/src/Observer.cpp b/test/cpp_api/src/Observer.cpp index 438dd99e1..16c3fbad8 100644 --- a/test/cpp_api/src/Observer.cpp +++ b/test/cpp_api/src/Observer.cpp @@ -816,3 +816,23 @@ void Observer_name_from_root(void) { flecs::entity ns = ecs.entity("::ns"); test_assert(ns == sys.parent()); } + +void Observer_term_index(void) { + flecs::world ecs; + + auto e1 = ecs.entity().add().add(); + + int32_t last_term = -1; + + ecs.observer() + .event(flecs::OnSet) + .each([&](flecs::iter& it, size_t row, const Position &p, const Velocity &v) { + last_term = it.term_index(); + }); + + e1.set({ 10, 20 }); + test_int(last_term, 1); + + e1.set({ 30, 40 }); + test_int(last_term, 2); +} \ No newline at end of file diff --git a/test/cpp_api/src/main.cpp b/test/cpp_api/src/main.cpp index 2fae2458e..1c21cefc1 100644 --- a/test/cpp_api/src/main.cpp +++ b/test/cpp_api/src/main.cpp @@ -891,6 +891,7 @@ void Observer_on_add_with_pair_singleton(void); void Observer_add_in_yield_existing(void); void Observer_add_in_yield_existing_multi(void); void Observer_name_from_root(void); +void Observer_term_index(void); // Testsuite 'Filter' void Filter_term_each_component(void); @@ -4825,6 +4826,10 @@ bake_test_case Observer_testcases[] = { { "name_from_root", Observer_name_from_root + }, + { + "term_index", + Observer_term_index } }; @@ -6763,7 +6768,7 @@ static bake_test_suite suites[] = { "Observer", NULL, NULL, - 32, + 33, Observer_testcases }, {