diff --git a/libs/bt/include/psemek/bt/on_event.hpp b/libs/bt/include/psemek/bt/on_event.hpp new file mode 100644 index 00000000..f8703907 --- /dev/null +++ b/libs/bt/include/psemek/bt/on_event.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include + +#include + +namespace psemek::bt +{ + + template + struct on_event_node; + + template + struct on_event_node, EventFn> + : node> + { + using tree_type = tree; + using node_type = node; + using typename node_type::status; + + on_event_node(EventFn && event_fn, node_ptr child) + : event_fn_(std::move(event_fn)) + , child_(std::move(child)) + {} + + void start(Args ... args) override + { + child_->start(args...); + } + + status update(Time dt, Args ... args) override + { + if (cached_status_) + { + auto result = *cached_status_; + cached_status_ = std::nullopt; + return result; + } + + return child_->update(dt, args...); + } + + bool event(Event const & e, Args ... args) override + { + cached_status_ = event_fn_(e, args...); + if (cached_status_) + return true; + return child_->event(e, args...); + } + + + private: + EventFn event_fn_; + node_ptr child_; + std::optional cached_status_; + }; + + template + node_ptr on_event(EventFn && event_fn, node_ptr child) + { + return std::make_unique>(std::move(event_fn), std::move(child)); + } + +}