AI Toolkit
Loading...
Searching...
No Matches
utility.hpp
1#pragma once
2
114#include <memory>
115#include <vector>
116#include <limits>
117
118#include <type_traits>
119#include <concepts>
120
121namespace aitoolkit::utility {
127 template <typename T>
128 class action {
129 public:
130 virtual ~action() = default;
131
135 virtual float score(const T& blackboard) const = 0;
136
140 virtual void apply(T& blackboard) const = 0;
141 };
142
147 template <typename T>
148 using action_ptr = std::unique_ptr<action<T>>;
149
150 template <typename A, typename T>
151 concept action_trait = std::derived_from<A, action<T>>;
152
157 template <typename T, action_trait<T> ...Actions>
158 std::vector<action_ptr<T>> action_list(Actions&&... actions) {
159 auto actions_list = std::vector<action_ptr<T>>{};
160 actions_list.reserve(sizeof...(Actions));
161 (actions_list.push_back(std::make_unique<Actions>(std::move(actions))), ...);
162 return actions_list;
163 }
164
170 template <typename T>
171 class evaluator {
172 public:
176 evaluator(std::vector<action_ptr<T>> actions) : m_actions(std::move(actions)) {}
177
181 void run(T& blackboard) const {
182 if (m_actions.empty()) {
183 return;
184 }
185
186 auto best_score = std::numeric_limits<float>::min();
187 auto best_action = m_actions.front().get();
188
189 for (auto& action : m_actions) {
190 auto score = action->score(blackboard);
191 if (score > best_score) {
192 best_score = score;
193 best_action = action.get();
194 }
195 }
196
197 best_action->apply(blackboard);
198 }
199
200 private:
201 std::vector<action_ptr<T>> m_actions;
202 };
203}
Base abstract class for all actions.
Definition utility.hpp:128
virtual float score(const T &blackboard) const =0
Return the score of the action.
virtual void apply(T &blackboard) const =0
Apply the action to the blackboard.
Evaluate a set of actions and apply the best one.
Definition utility.hpp:171
evaluator(std::vector< action_ptr< T > > actions)
Construct an evaluator from a list of actions.
Definition utility.hpp:176
void run(T &blackboard) const
Find the best action and apply it to the blackboard.
Definition utility.hpp:181
Definition utility.hpp:151
std::unique_ptr< action< T > > action_ptr
Heap allocated pointer to an action.
Definition utility.hpp:148
std::vector< action_ptr< T > > action_list(Actions &&... actions)
Helper function to create a list of actions.
Definition utility.hpp:158