HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
animator.hpp
1// Copyright Take Vos 2021.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "hires_utc_clock.hpp"
8#include "algorithm.hpp"
9#include <chrono>
10#include <cmath>
11#include "concepts.hpp"
12
13namespace tt {
14
17template<arithmetic T>
18class animator {
19public:
20 using value_type = T;
21
25 animator(hires_utc_clock::duration animation_duration) noexcept : _animation_duration(animation_duration) {}
26
31 void update(value_type new_value, hires_utc_clock::time_point current_time) noexcept
32 {
33 if (not initialized) {
34 initialized = true;
35 _old_value = new_value;
36 _new_value = new_value;
37 _start_time = current_time;
38
39 } else if (new_value != _new_value) {
40 _old_value = _new_value;
41 _new_value = new_value;
42 _start_time = current_time;
43 }
44 _current_time = current_time;
45 }
46
49 [[nodiscard]] bool is_animating() const noexcept
50 {
51 tt_axiom(initialized);
52 return progress() < 1.0f;
53 }
54
57 value_type current_value() const noexcept {
58 tt_axiom(initialized);
59 return std::lerp(_old_value, _new_value, progress());
60 }
61
62private:
63 value_type _old_value;
64 value_type _new_value;
66 hires_utc_clock::time_point _current_time;
67 hires_utc_clock::duration _animation_duration;
68 bool initialized = false;
69
70 float progress() const noexcept
71 {
72 ttlet dt = _current_time - _start_time;
73 ttlet p = static_cast<float>(dt / 1ms) / static_cast<float>(_animation_duration / 1ms);
74 return std::clamp(p, 0.0f, 1.0f);
75 }
76};
77
78} // namespace tt
A type that gets animated between two values.
Definition animator.hpp:18
void update(value_type new_value, hires_utc_clock::time_point current_time) noexcept
Update the value and time.
Definition animator.hpp:31
bool is_animating() const noexcept
Check if the animation is currently running.
Definition animator.hpp:49
animator(hires_utc_clock::duration animation_duration) noexcept
Constructor.
Definition animator.hpp:25
value_type current_value() const noexcept
The interpolated value between start and end value.
Definition animator.hpp:57