From b7252f8746619ed15e0a5b36d3bd1b7e389e0edf Mon Sep 17 00:00:00 2001 From: lisyarus Date: Mon, 13 Feb 2023 18:03:56 +0300 Subject: [PATCH] Add a simple animation manager to util --- .../include/psemek/util/animation_manager.hpp | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 libs/util/include/psemek/util/animation_manager.hpp diff --git a/libs/util/include/psemek/util/animation_manager.hpp b/libs/util/include/psemek/util/animation_manager.hpp new file mode 100644 index 00000000..16edfd85 --- /dev/null +++ b/libs/util/include/psemek/util/animation_manager.hpp @@ -0,0 +1,80 @@ +#pragma once + +#include +#include +#include + +namespace psemek::util +{ + + template + struct animation_manager + { + struct animation + { + Time time; + Time duration; + Data data; + + Time position() const + { + return std::max(Time{0}, std::min(Time{1}, time / duration)); + } + + Time remaining() const + { + return duration - time; + } + + bool finished() const + { + return remaining() <= Time{0}; + } + }; + + void add(Time duration, Data data) + { + animations_.push_back(animation{Time{0}, duration, data}); + std::push_heap(animations_.begin(), animations_.end(), compare{}); + } + + void update(Time dt) + { + for (auto & animation : animations_) + animation.time += dt; + + while (!animations_.empty() && animations_.front().finished()) + { + std::pop_heap(animations_.begin(), animations_.end(), compare{}); + animations_.pop_back(); + } + } + + animation const * begin() const + { + return animations_.data(); + } + + animation const * end() const + { + return animations_.data() + animations_.size(); + } + + std::size_t size() const + { + return animations_.size(); + } + + private: + std::vector animations_; + + struct compare + { + bool operator() (animation const & a1, animation const & a2) + { + return a1.remaining() > a2.remaining(); + } + }; + }; + +}