Cogs.Core
Interpolator.h
1#pragma once
2
3#include "EasingFn.h"
4#include "Interpolation.hpp"
5
6#include "../Platform/Timer.h"
7
8#include <glm/vec3.hpp>
9#include <glm/ext/quaternion_float.hpp>
10#include <glm/ext/quaternion_common.hpp>
11#include <glm/gtx/norm.hpp>
12
13namespace Cogs {
14 template<typename T> inline bool tooCloseFn(const T& s, const T& d) {
15 return glm::distance2(s, d) < 0.000001;
16 }
17
18 template<> inline bool tooCloseFn<glm::quat>(const glm::quat& s, const glm::quat& d) {
19 return std::abs(glm::dot(s, d)) > 0.9999;
20 }
21
22 template<typename T> inline T interpolateFn(const T& s, const T& d, float t) {
23 return Interpolation::linear(s, d, t);
24 }
25
26 template<> inline glm::quat interpolateFn<glm::quat>(const glm::quat& s, const glm::quat& d, float t) {
27 return glm::slerp(s, d, t);
28 }
29
30 template<typename T> class Interpolator {
31 public:
32 Interpolator(T& destination) : mDestination(destination), mTarget(destination) {
33 }
34
35 Interpolator(T& destination, const T& target, EasingFn::Ptr fn, float duration) : Interpolator(destination) {
36 setTarget(target, fn, duration);
37 }
38
39 void setTarget(const T& target, EasingFn::Ptr fn, float duration) {
40 if (fn && (duration > 0.0f) && !tooCloseFn(mDestination, target)) {
41 mStart = mDestination;
42 mTarget = target;
43 mTimer.start();
44 mFunction = fn;
45 mDuration = duration;
46 }
47 else {
48 mDestination = target;
49 mTarget = target;
50 mFunction = nullptr;
51 }
52 }
53
54 void snapToTarget() {
55 if (mFunction) {
56 mDestination = mTarget;
57 mFunction = nullptr;
58 }
59 }
60
61 bool process() {
62 if (mFunction) {
63 float t = static_cast<float>(mTimer.elapsedSeconds()) / mDuration;
64
65 if (t < 1.0f) {
66 mDestination = interpolateFn(mStart, mTarget, mFunction(t));
67 }
68 else {
69 mDestination = mTarget;
70 mFunction = nullptr;
71 }
72 return true;
73 }
74 return false;
75 }
76
77 void cancel() { mFunction = nullptr; }
78 bool isProcessing() const { return mFunction; }
79
80 float getTime() { return isProcessing() ? static_cast<float>(mTimer.elapsedSeconds()) : 1.0f; }
81 T getTarget() const { return mTarget; }
82 T getValue() const { return mDestination; }
83
84 private:
85 T& mDestination;
86 T mStart;
87 T mTarget;
88 Timer mTimer;
89 EasingFn::Ptr mFunction = nullptr;
90 float mDuration = 0.0f;
91 };
92}
93
High-resolution performance timer.
Definition: Timer.h:46
Contains all Cogs related functionality.
Definition: FieldSetter.h:23