Euphoria
tweenable.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "assert/assert.h"
4 
5 #include "core/easing.h"
7 
8 namespace eu::core
9 {
10  template <typename T>
11  struct Tweenable
12  {
13  using Self = Tweenable<T>;
14 
15  static constexpr float transition_ended = 2.0f;
16 
17  T from;
18  T to;
19  T value;
20 
21  float t = 1.0f;
22  float speed = 1.0f;
24 
25  explicit Tweenable(T v)
26  : from(v)
27  , to(v)
28  , value(v)
29  {
30  }
31 
33  {
35  return *this;
36  }
37 
38  Self& set(const T& new_value)
39  {
40  value = new_value;
42  return *this;
43  }
44 
45  void set(const T& new_value, easing::Function f, float time)
46  {
47  ASSERT(time >= 0.0f);
48 
49  from = value;
50  to = new_value;
52  t = 0.0f;
53  speed = 1.0f / time;
54  }
55 
56  void set(easing::Function f, const T& new_value, float time)
57  {
58  set(new_value, f, time);
59  }
60 
61  template<typename F>
62  void update(float dt, F transform_function)
63  {
64  if(t >= 1.0f)
65  {
66  return;
67  }
68 
69  t += dt * speed;
70 
71  if (is_active() == false)
72  {
73  value = to;
75  }
76  else
77  {
78  const auto f = easing::apply(easing_function, t);
79  value = transform_function(from, f, to);
80  }
81  }
82 
83  void update(float dt)
84  {
85  update(dt, default_interpolate<T>);
86  }
87 
88  [[nodiscard]] bool is_active() const
89  {
90  return t < 1.0f;
91  }
92  };
93 }
#define ASSERT(x)
Definition: assert.h:29
float apply(Function f, float t)
Definition: easing.cc:61
void set(easing::Function f, const T &new_value, float time)
Definition: tweenable.h:56
bool is_active() const
Definition: tweenable.h:88
void update(float dt)
Definition: tweenable.h:83
void update(float dt, F transform_function)
Definition: tweenable.h:62
void set(const T &new_value, easing::Function f, float time)
Definition: tweenable.h:45
easing::Function easing_function
Definition: tweenable.h:23
Self & set(const T &new_value)
Definition: tweenable.h:38
static constexpr float transition_ended
Definition: tweenable.h:15