| 1 | /* |
| 2 | * Copyright (C) 2013 Canonical Ltd. |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation; version 3. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, |
| 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | * GNU General Public License for more details. |
| 12 | * |
| 13 | * You should have received a copy of the GNU General Public License |
| 14 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 15 | */ |
| 16 | |
| 17 | #ifndef DAMPER_P_H |
| 18 | #define DAMPER_P_H |
| 19 | |
| 20 | #include <QtCore/QPointF> |
| 21 | |
| 22 | /* |
| 23 | Decreases the oscillations of a value along an axis. |
| 24 | */ |
| 25 | template <class Type> class Damper { |
| 26 | public: |
| 27 | Damper() : m_value(0), m_maxDelta(0) { } |
| 28 | |
| 29 | // Maximum delta between the raw value and its dampened counterpart. |
| 30 | void setMaxDelta(Type maxDelta) { |
| 31 | if (maxDelta < 0) qFatal("Damper::maxDelta must be a positive number."); |
| 32 | m_maxDelta = maxDelta; |
| 33 | } |
| 34 | Type maxDelta() const { return m_maxDelta; } |
| 35 | |
| 36 | void reset(Type value) { |
| 37 | m_value = value; |
| 38 | } |
| 39 | |
| 40 | Type update(Type value) { |
| 41 | Type delta = value - m_value; |
| 42 | if (delta > 0 && delta > m_maxDelta) { |
| 43 | m_value += delta - m_maxDelta; |
| 44 | } else if (delta < 0 && delta < -m_maxDelta) { |
| 45 | m_value += delta + m_maxDelta; |
| 46 | } |
| 47 | |
| 48 | return m_value; |
| 49 | } |
| 50 | |
| 51 | Type value() const { return m_value; } |
| 52 | |
| 53 | private: |
| 54 | Type m_value; |
| 55 | Type m_maxDelta; |
| 56 | }; |
| 57 | |
| 58 | /* |
| 59 | A point that has its movement dampened. |
| 60 | */ |
| 61 | class DampedPointF { |
| 62 | public: |
| 63 | void setMaxDelta(qreal maxDelta) { |
| 64 | m_x.setMaxDelta(maxDelta); |
| 65 | m_y.setMaxDelta(maxDelta); |
| 66 | } |
| 67 | |
| 68 | qreal maxDelta() const { return m_x.maxDelta(); } |
| 69 | |
| 70 | void reset(const QPointF &point) { |
| 71 | m_x.reset(point.x()); |
| 72 | m_y.reset(point.y()); |
| 73 | } |
| 74 | |
| 75 | void update(const QPointF &point) { |
| 76 | m_x.update(point.x()); |
| 77 | m_y.update(point.y()); |
| 78 | } |
| 79 | |
| 80 | qreal x() const { return m_x.value(); } |
| 81 | qreal y() const { return m_y.value(); } |
| 82 | private: |
| 83 | Damper<qreal> m_x; |
| 84 | Damper<qreal> m_y; |
| 85 | }; |
| 86 | |
| 87 | QDebug operator<<(QDebug dbg, const DampedPointF &p); |
| 88 | |
| 89 | #endif // DAMPER_P_H |