1 |
/* |
2 |
* Copyright (c) 2017 Christian Schoenebeck |
3 |
* |
4 |
* http://www.linuxsampler.org |
5 |
* |
6 |
* This file is part of LinuxSampler and released under the same terms. |
7 |
* See README file for details. |
8 |
*/ |
9 |
|
10 |
#ifndef LS_FADE_H |
11 |
#define LS_FADE_H |
12 |
|
13 |
#include "EaseInEaseOut.h" |
14 |
|
15 |
namespace LinuxSampler { |
16 |
|
17 |
#define DEFAULT_FADE_CURVE FADE_CURVE_EASE_IN_EASE_OUT |
18 |
|
19 |
enum fade_curve_t { |
20 |
FADE_CURVE_LINEAR, |
21 |
FADE_CURVE_EASE_IN_EASE_OUT, |
22 |
}; |
23 |
|
24 |
/** @brief Fades a value with a selected curve. |
25 |
* |
26 |
* Implements a smoothed transition from one value to another value in a |
27 |
* requested amount of time, either with an ease-in and ease-out algorithm |
28 |
* (default), or linear. |
29 |
*/ |
30 |
class Fade : public EaseInEaseOut { |
31 |
public: |
32 |
Fade() : EaseInEaseOut() { |
33 |
curveType = DEFAULT_FADE_CURVE; |
34 |
} |
35 |
|
36 |
/** |
37 |
* Select another curve type for this Fade and immediately prepare this |
38 |
* Fade for operation with the new curve type. |
39 |
*/ |
40 |
void setCurve(fade_curve_t curve, float sampleRate) { |
41 |
curveType = curve; |
42 |
fadeTo(endValue, duration, sampleRate); |
43 |
} |
44 |
|
45 |
/** |
46 |
* Only set the new curve type. It is your responsibility to prepare this |
47 |
* Fade for subsequent operation, i.e. by calling fadeTo() afterwards, |
48 |
* otherwise the result of render() calls will be undefined. |
49 |
*/ |
50 |
void setCurveOnly(fade_curve_t curve) { |
51 |
curveType = curve; |
52 |
} |
53 |
|
54 |
/** |
55 |
* Fade the current value in @duration seconds to the new value reflected |
56 |
* by @a endValue, assuming the given @a sampleRate. |
57 |
*/ |
58 |
void fadeTo(float endValue, float duration, float sampleRate) { |
59 |
if (curveType == FADE_CURVE_EASE_IN_EASE_OUT) |
60 |
return EaseInEaseOut::fadeTo(endValue, duration, sampleRate); |
61 |
else { |
62 |
if (duration <= 0.f) { |
63 |
setCurrentValue(endValue); |
64 |
return; |
65 |
} |
66 |
this->endValue = endValue; |
67 |
steps = duration * sampleRate; |
68 |
c = (endValue - value) / float(steps); |
69 |
} |
70 |
} |
71 |
|
72 |
/** |
73 |
* Fade the current value in the currently set default duration to the new |
74 |
* value reflected by @a endValue, assuming the given @a sampleRate. |
75 |
*/ |
76 |
void fadeTo(float endValue, float sampleRate) { |
77 |
fadeTo(endValue, duration, sampleRate); |
78 |
} |
79 |
|
80 |
/** |
81 |
* Proceed transition by exactly one sample point and return the current |
82 |
* smoothed value at this stage. |
83 |
*/ |
84 |
inline float render() { |
85 |
if (curveType == FADE_CURVE_EASE_IN_EASE_OUT) |
86 |
return EaseInEaseOut::render(); |
87 |
if (!steps) return endValue; |
88 |
--steps; |
89 |
value += c; |
90 |
return value; |
91 |
} |
92 |
|
93 |
private: |
94 |
fade_curve_t curveType; |
95 |
}; |
96 |
|
97 |
} // namespace LinuxSampler |
98 |
|
99 |
#endif // LS_FADE_H |