| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1 | /* | 
|  | 2 | * Copyright (C) 2012 The Android Open Source Project | 
|  | 3 | * | 
|  | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); | 
|  | 5 | * you may not use this file except in compliance with the License. | 
|  | 6 | * You may obtain a copy of the License at | 
|  | 7 | * | 
|  | 8 | *      http://www.apache.org/licenses/LICENSE-2.0 | 
|  | 9 | * | 
|  | 10 | * Unless required by applicable law or agreed to in writing, software | 
|  | 11 | * distributed under the License is distributed on an "AS IS" BASIS, | 
|  | 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 
|  | 13 | * See the License for the specific language governing permissions and | 
|  | 14 | * limitations under the License. | 
|  | 15 | */ | 
|  | 16 |  | 
|  | 17 | #define LOG_TAG "VelocityTracker" | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 18 |  | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 19 | #include <array> | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 20 | #include <inttypes.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 21 | #include <limits.h> | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 22 | #include <math.h> | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 23 | #include <optional> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 24 |  | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 25 | #include <android-base/stringprintf.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 26 | #include <input/VelocityTracker.h> | 
|  | 27 | #include <utils/BitSet.h> | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 28 | #include <utils/Timers.h> | 
|  | 29 |  | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 30 | using std::literals::chrono_literals::operator""ms; | 
|  | 31 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 32 | namespace android { | 
|  | 33 |  | 
| Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 34 | /** | 
|  | 35 | * Log debug messages about velocity tracking. | 
|  | 36 | * Enable this via "adb shell setprop log.tag.VelocityTrackerVelocity DEBUG" (requires restart) | 
|  | 37 | */ | 
|  | 38 | const bool DEBUG_VELOCITY = | 
|  | 39 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Velocity", ANDROID_LOG_INFO); | 
|  | 40 |  | 
|  | 41 | /** | 
|  | 42 | * Log debug messages about the progress of the algorithm itself. | 
|  | 43 | * Enable this via "adb shell setprop log.tag.VelocityTrackerStrategy DEBUG" (requires restart) | 
|  | 44 | */ | 
|  | 45 | const bool DEBUG_STRATEGY = | 
|  | 46 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Strategy", ANDROID_LOG_INFO); | 
|  | 47 |  | 
|  | 48 | /** | 
|  | 49 | * Log debug messages about the 'impulse' strategy. | 
|  | 50 | * Enable this via "adb shell setprop log.tag.VelocityTrackerImpulse DEBUG" (requires restart) | 
|  | 51 | */ | 
|  | 52 | const bool DEBUG_IMPULSE = | 
|  | 53 | __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Impulse", ANDROID_LOG_INFO); | 
|  | 54 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 55 | // Nanoseconds per milliseconds. | 
|  | 56 | static const nsecs_t NANOS_PER_MS = 1000000; | 
|  | 57 |  | 
| Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 58 | // All axes supported for velocity tracking, mapped to their default strategies. | 
|  | 59 | // Although other strategies are available for testing and comparison purposes, | 
|  | 60 | // the default strategy is the one that applications will actually use.  Be very careful | 
|  | 61 | // when adjusting the default strategy because it can dramatically affect | 
|  | 62 | // (often in a bad way) the user experience. | 
|  | 63 | static const std::map<int32_t, VelocityTracker::Strategy> DEFAULT_STRATEGY_BY_AXIS = | 
|  | 64 | {{AMOTION_EVENT_AXIS_X, VelocityTracker::Strategy::LSQ2}, | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 65 | {AMOTION_EVENT_AXIS_Y, VelocityTracker::Strategy::LSQ2}, | 
|  | 66 | {AMOTION_EVENT_AXIS_SCROLL, VelocityTracker::Strategy::IMPULSE}}; | 
| Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 67 |  | 
|  | 68 | // Axes specifying location on a 2D plane (i.e. X and Y). | 
|  | 69 | static const std::set<int32_t> PLANAR_AXES = {AMOTION_EVENT_AXIS_X, AMOTION_EVENT_AXIS_Y}; | 
|  | 70 |  | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 71 | // Axes whose motion values are differential values (i.e. deltas). | 
|  | 72 | static const std::set<int32_t> DIFFERENTIAL_AXES = {AMOTION_EVENT_AXIS_SCROLL}; | 
|  | 73 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 74 | // Threshold for determining that a pointer has stopped moving. | 
|  | 75 | // Some input devices do not send ACTION_MOVE events in the case where a pointer has | 
|  | 76 | // stopped.  We need to detect this case so that we can accurately predict the | 
|  | 77 | // velocity after the pointer starts moving again. | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 78 | static const std::chrono::duration ASSUME_POINTER_STOPPED_TIME = 40ms; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 79 |  | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 80 | static std::string toString(std::chrono::nanoseconds t) { | 
|  | 81 | std::stringstream stream; | 
|  | 82 | stream.precision(1); | 
|  | 83 | stream << std::fixed << std::chrono::duration<float, std::milli>(t).count() << " ms"; | 
|  | 84 | return stream.str(); | 
|  | 85 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 86 |  | 
|  | 87 | static float vectorDot(const float* a, const float* b, uint32_t m) { | 
|  | 88 | float r = 0; | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 89 | for (size_t i = 0; i < m; i++) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 90 | r += *(a++) * *(b++); | 
|  | 91 | } | 
|  | 92 | return r; | 
|  | 93 | } | 
|  | 94 |  | 
|  | 95 | static float vectorNorm(const float* a, uint32_t m) { | 
|  | 96 | float r = 0; | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 97 | for (size_t i = 0; i < m; i++) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 98 | float t = *(a++); | 
|  | 99 | r += t * t; | 
|  | 100 | } | 
|  | 101 | return sqrtf(r); | 
|  | 102 | } | 
|  | 103 |  | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 104 | static std::string vectorToString(const float* a, uint32_t m) { | 
|  | 105 | std::string str; | 
|  | 106 | str += "["; | 
| Siarhei Vishniakou | 7b9d189 | 2017-07-05 18:58:41 -0700 | [diff] [blame] | 107 | for (size_t i = 0; i < m; i++) { | 
|  | 108 | if (i) { | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 109 | str += ","; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 110 | } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 111 | str += android::base::StringPrintf(" %f", *(a++)); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 112 | } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 113 | str += " ]"; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 114 | return str; | 
|  | 115 | } | 
|  | 116 |  | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 117 | static std::string vectorToString(const std::vector<float>& v) { | 
|  | 118 | return vectorToString(v.data(), v.size()); | 
|  | 119 | } | 
|  | 120 |  | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 121 | static std::string matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) { | 
|  | 122 | std::string str; | 
|  | 123 | str = "["; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 124 | for (size_t i = 0; i < m; i++) { | 
|  | 125 | if (i) { | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 126 | str += ","; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 127 | } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 128 | str += " ["; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 129 | for (size_t j = 0; j < n; j++) { | 
|  | 130 | if (j) { | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 131 | str += ","; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 132 | } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 133 | str += android::base::StringPrintf(" %f", a[rowMajor ? i * n + j : j * m + i]); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 134 | } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 135 | str += " ]"; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 136 | } | 
| Siarhei Vishniakou | ec2727e | 2017-07-06 10:22:03 -0700 | [diff] [blame] | 137 | str += " ]"; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 138 | return str; | 
|  | 139 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 140 |  | 
|  | 141 |  | 
|  | 142 | // --- VelocityTracker --- | 
|  | 143 |  | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 144 | VelocityTracker::VelocityTracker(const Strategy strategy) | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 145 | : mLastEventTime(0), | 
|  | 146 | mCurrentPointerIdBits(0), | 
|  | 147 | mActivePointerId(-1), | 
|  | 148 | mOverrideStrategy(strategy) {} | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 149 |  | 
|  | 150 | VelocityTracker::~VelocityTracker() { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 151 | } | 
|  | 152 |  | 
| Yeabkal Wubshit | eca273c | 2022-10-05 19:06:40 -0700 | [diff] [blame] | 153 | bool VelocityTracker::isAxisSupported(int32_t axis) { | 
|  | 154 | return DEFAULT_STRATEGY_BY_AXIS.find(axis) != DEFAULT_STRATEGY_BY_AXIS.end(); | 
|  | 155 | } | 
|  | 156 |  | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 157 | void VelocityTracker::configureStrategy(int32_t axis) { | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 158 | const bool isDifferentialAxis = DIFFERENTIAL_AXES.find(axis) != DIFFERENTIAL_AXES.end(); | 
|  | 159 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 160 | std::unique_ptr<VelocityTrackerStrategy> createdStrategy; | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 161 | if (mOverrideStrategy != VelocityTracker::Strategy::DEFAULT) { | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 162 | createdStrategy = createStrategy(mOverrideStrategy, isDifferentialAxis /* deltaValues */); | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 163 | } else { | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 164 | createdStrategy = createStrategy(DEFAULT_STRATEGY_BY_AXIS.at(axis), | 
|  | 165 | isDifferentialAxis /* deltaValues */); | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 166 | } | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 167 |  | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 168 | LOG_ALWAYS_FATAL_IF(createdStrategy == nullptr, | 
|  | 169 | "Could not create velocity tracker strategy for axis '%" PRId32 "'!", axis); | 
|  | 170 | mConfiguredStrategies[axis] = std::move(createdStrategy); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 171 | } | 
|  | 172 |  | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 173 | std::unique_ptr<VelocityTrackerStrategy> VelocityTracker::createStrategy( | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 174 | VelocityTracker::Strategy strategy, bool deltaValues) { | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 175 | switch (strategy) { | 
|  | 176 | case VelocityTracker::Strategy::IMPULSE: | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 177 | ALOGI_IF(DEBUG_STRATEGY, "Initializing impulse strategy"); | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 178 | return std::make_unique<ImpulseVelocityTrackerStrategy>(deltaValues); | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 179 |  | 
|  | 180 | case VelocityTracker::Strategy::LSQ1: | 
|  | 181 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(1); | 
|  | 182 |  | 
|  | 183 | case VelocityTracker::Strategy::LSQ2: | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 184 | ALOGI_IF(DEBUG_STRATEGY && !DEBUG_IMPULSE, "Initializing lsq2 strategy"); | 
| Chris Ye | f859148 | 2020-04-17 11:49:17 -0700 | [diff] [blame] | 185 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(2); | 
|  | 186 |  | 
|  | 187 | case VelocityTracker::Strategy::LSQ3: | 
|  | 188 | return std::make_unique<LeastSquaresVelocityTrackerStrategy>(3); | 
|  | 189 |  | 
|  | 190 | case VelocityTracker::Strategy::WLSQ2_DELTA: | 
|  | 191 | return std::make_unique< | 
|  | 192 | LeastSquaresVelocityTrackerStrategy>(2, | 
|  | 193 | LeastSquaresVelocityTrackerStrategy:: | 
|  | 194 | WEIGHTING_DELTA); | 
|  | 195 | case VelocityTracker::Strategy::WLSQ2_CENTRAL: | 
|  | 196 | return std::make_unique< | 
|  | 197 | LeastSquaresVelocityTrackerStrategy>(2, | 
|  | 198 | LeastSquaresVelocityTrackerStrategy:: | 
|  | 199 | WEIGHTING_CENTRAL); | 
|  | 200 | case VelocityTracker::Strategy::WLSQ2_RECENT: | 
|  | 201 | return std::make_unique< | 
|  | 202 | LeastSquaresVelocityTrackerStrategy>(2, | 
|  | 203 | LeastSquaresVelocityTrackerStrategy:: | 
|  | 204 | WEIGHTING_RECENT); | 
|  | 205 |  | 
|  | 206 | case VelocityTracker::Strategy::INT1: | 
|  | 207 | return std::make_unique<IntegratingVelocityTrackerStrategy>(1); | 
|  | 208 |  | 
|  | 209 | case VelocityTracker::Strategy::INT2: | 
|  | 210 | return std::make_unique<IntegratingVelocityTrackerStrategy>(2); | 
|  | 211 |  | 
|  | 212 | case VelocityTracker::Strategy::LEGACY: | 
|  | 213 | return std::make_unique<LegacyVelocityTrackerStrategy>(); | 
|  | 214 |  | 
|  | 215 | default: | 
|  | 216 | break; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 217 | } | 
| Yi Kong | 5bed83b | 2018-07-17 12:53:47 -0700 | [diff] [blame] | 218 | return nullptr; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 219 | } | 
|  | 220 |  | 
|  | 221 | void VelocityTracker::clear() { | 
|  | 222 | mCurrentPointerIdBits.clear(); | 
|  | 223 | mActivePointerId = -1; | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 224 | mConfiguredStrategies.clear(); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 225 | } | 
|  | 226 |  | 
|  | 227 | void VelocityTracker::clearPointers(BitSet32 idBits) { | 
|  | 228 | BitSet32 remainingIdBits(mCurrentPointerIdBits.value & ~idBits.value); | 
|  | 229 | mCurrentPointerIdBits = remainingIdBits; | 
|  | 230 |  | 
|  | 231 | if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) { | 
|  | 232 | mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1; | 
|  | 233 | } | 
|  | 234 |  | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 235 | for (const auto& [_, strategy] : mConfiguredStrategies) { | 
|  | 236 | strategy->clearPointers(idBits); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 237 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 238 | } | 
|  | 239 |  | 
| Siarhei Vishniakou | ae0f990 | 2020-09-14 19:23:31 -0500 | [diff] [blame] | 240 | void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 241 | const std::map<int32_t /*axis*/, std::vector<float>>& positions) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 242 | while (idBits.count() > MAX_POINTERS) { | 
|  | 243 | idBits.clearLastMarkedBit(); | 
|  | 244 | } | 
|  | 245 |  | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 246 | if ((mCurrentPointerIdBits.value & idBits.value) && | 
|  | 247 | std::chrono::nanoseconds(eventTime - mLastEventTime) > ASSUME_POINTER_STOPPED_TIME) { | 
|  | 248 | ALOGD_IF(DEBUG_VELOCITY, "VelocityTracker: stopped for %s, clearing state.", | 
|  | 249 | toString(std::chrono::nanoseconds(eventTime - mLastEventTime)).c_str()); | 
|  | 250 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 251 | // We have not received any movements for too long.  Assume that all pointers | 
|  | 252 | // have stopped. | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 253 | mConfiguredStrategies.clear(); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 254 | } | 
|  | 255 | mLastEventTime = eventTime; | 
|  | 256 |  | 
|  | 257 | mCurrentPointerIdBits = idBits; | 
|  | 258 | if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) { | 
|  | 259 | mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit(); | 
|  | 260 | } | 
|  | 261 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 262 | for (const auto& [axis, positionValues] : positions) { | 
|  | 263 | LOG_ALWAYS_FATAL_IF(idBits.count() != positionValues.size(), | 
|  | 264 | "Mismatching number of pointers, idBits=%" PRIu32 ", positions=%zu", | 
|  | 265 | idBits.count(), positionValues.size()); | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 266 | if (mConfiguredStrategies.find(axis) == mConfiguredStrategies.end()) { | 
|  | 267 | configureStrategy(axis); | 
|  | 268 | } | 
|  | 269 | mConfiguredStrategies[axis]->addMovement(eventTime, idBits, positionValues); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 270 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 271 |  | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 272 | if (DEBUG_VELOCITY) { | 
|  | 273 | ALOGD("VelocityTracker: addMovement eventTime=%" PRId64 | 
|  | 274 | ", idBits=0x%08x, activePointerId=%d", | 
|  | 275 | eventTime, idBits.value, mActivePointerId); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 276 | for (const auto& positionsEntry : positions) { | 
|  | 277 | for (BitSet32 iterBits(idBits); !iterBits.isEmpty();) { | 
|  | 278 | uint32_t id = iterBits.firstMarkedBit(); | 
|  | 279 | uint32_t index = idBits.getIndexOfBit(id); | 
|  | 280 | iterBits.clearBit(id); | 
|  | 281 | Estimator estimator; | 
|  | 282 | getEstimator(positionsEntry.first, id, &estimator); | 
|  | 283 | ALOGD("  %d: axis=%d, position=%0.3f, " | 
|  | 284 | "estimator (degree=%d, coeff=%s, confidence=%f)", | 
|  | 285 | id, positionsEntry.first, positionsEntry.second[index], int(estimator.degree), | 
|  | 286 | vectorToString(estimator.coeff, estimator.degree + 1).c_str(), | 
|  | 287 | estimator.confidence); | 
|  | 288 | } | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 289 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 290 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 291 | } | 
|  | 292 |  | 
|  | 293 | void VelocityTracker::addMovement(const MotionEvent* event) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 294 | // Stores data about which axes to process based on the incoming motion event. | 
|  | 295 | std::set<int32_t> axesToProcess; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 296 | int32_t actionMasked = event->getActionMasked(); | 
|  | 297 |  | 
|  | 298 | switch (actionMasked) { | 
|  | 299 | case AMOTION_EVENT_ACTION_DOWN: | 
|  | 300 | case AMOTION_EVENT_ACTION_HOVER_ENTER: | 
|  | 301 | // Clear all pointers on down before adding the new movement. | 
|  | 302 | clear(); | 
| Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 303 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 304 | break; | 
|  | 305 | case AMOTION_EVENT_ACTION_POINTER_DOWN: { | 
|  | 306 | // Start a new movement trace for a pointer that just went down. | 
|  | 307 | // We do this on down instead of on up because the client may want to query the | 
|  | 308 | // final velocity for a pointer that just went up. | 
|  | 309 | BitSet32 downIdBits; | 
|  | 310 | downIdBits.markBit(event->getPointerId(event->getActionIndex())); | 
|  | 311 | clearPointers(downIdBits); | 
| Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 312 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 313 | break; | 
|  | 314 | } | 
|  | 315 | case AMOTION_EVENT_ACTION_MOVE: | 
|  | 316 | case AMOTION_EVENT_ACTION_HOVER_MOVE: | 
| Yeabkal Wubshit | 67b3ab0 | 2022-09-16 00:18:17 -0700 | [diff] [blame] | 317 | axesToProcess.insert(PLANAR_AXES.begin(), PLANAR_AXES.end()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 318 | break; | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 319 | case AMOTION_EVENT_ACTION_POINTER_UP: | 
|  | 320 | case AMOTION_EVENT_ACTION_UP: { | 
|  | 321 | std::chrono::nanoseconds delaySinceLastEvent(event->getEventTime() - mLastEventTime); | 
|  | 322 | if (delaySinceLastEvent > ASSUME_POINTER_STOPPED_TIME) { | 
|  | 323 | ALOGD_IF(DEBUG_VELOCITY, | 
|  | 324 | "VelocityTracker: stopped for %s, clearing state upon pointer liftoff.", | 
|  | 325 | toString(delaySinceLastEvent).c_str()); | 
|  | 326 | // We have not received any movements for too long.  Assume that all pointers | 
|  | 327 | // have stopped. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 328 | for (int32_t axis : PLANAR_AXES) { | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 329 | mConfiguredStrategies.erase(axis); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 330 | } | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 331 | } | 
|  | 332 | // These actions because they do not convey any new information about | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 333 | // pointer movement.  We also want to preserve the last known velocity of the pointers. | 
|  | 334 | // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position | 
|  | 335 | // of the pointers that went up.  ACTION_POINTER_UP does include the new position of | 
|  | 336 | // pointers that remained down but we will also receive an ACTION_MOVE with this | 
|  | 337 | // information if any of them actually moved.  Since we don't know how many pointers | 
|  | 338 | // will be going up at once it makes sense to just wait for the following ACTION_MOVE | 
|  | 339 | // before adding the movement. | 
|  | 340 | return; | 
|  | 341 | } | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 342 | case AMOTION_EVENT_ACTION_SCROLL: | 
|  | 343 | axesToProcess.insert(AMOTION_EVENT_AXIS_SCROLL); | 
|  | 344 | break; | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 345 | default: | 
|  | 346 | // Ignore all other actions. | 
|  | 347 | return; | 
|  | 348 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 349 |  | 
|  | 350 | size_t pointerCount = event->getPointerCount(); | 
|  | 351 | if (pointerCount > MAX_POINTERS) { | 
|  | 352 | pointerCount = MAX_POINTERS; | 
|  | 353 | } | 
|  | 354 |  | 
|  | 355 | BitSet32 idBits; | 
|  | 356 | for (size_t i = 0; i < pointerCount; i++) { | 
|  | 357 | idBits.markBit(event->getPointerId(i)); | 
|  | 358 | } | 
|  | 359 |  | 
|  | 360 | uint32_t pointerIndex[MAX_POINTERS]; | 
|  | 361 | for (size_t i = 0; i < pointerCount; i++) { | 
|  | 362 | pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i)); | 
|  | 363 | } | 
|  | 364 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 365 | std::map<int32_t, std::vector<float>> positions; | 
|  | 366 | for (int32_t axis : axesToProcess) { | 
|  | 367 | positions[axis].resize(pointerCount); | 
|  | 368 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 369 |  | 
|  | 370 | size_t historySize = event->getHistorySize(); | 
| Siarhei Vishniakou | 69e4d0f | 2020-09-14 19:53:29 -0500 | [diff] [blame] | 371 | for (size_t h = 0; h <= historySize; h++) { | 
|  | 372 | nsecs_t eventTime = event->getHistoricalEventTime(h); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 373 | for (int32_t axis : axesToProcess) { | 
|  | 374 | for (size_t i = 0; i < pointerCount; i++) { | 
|  | 375 | positions[axis][pointerIndex[i]] = event->getHistoricalAxisValue(axis, i, h); | 
|  | 376 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 377 | } | 
|  | 378 | addMovement(eventTime, idBits, positions); | 
|  | 379 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 380 | } | 
|  | 381 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 382 | std::optional<float> VelocityTracker::getVelocity(int32_t axis, uint32_t id) const { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 383 | Estimator estimator; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 384 | bool validVelocity = getEstimator(axis, id, &estimator) && estimator.degree >= 1; | 
|  | 385 | if (validVelocity) { | 
|  | 386 | return estimator.coeff[1]; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 387 | } | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 388 | return {}; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 389 | } | 
|  | 390 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 391 | VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units, | 
|  | 392 | float maxVelocity) { | 
|  | 393 | ComputedVelocity computedVelocity; | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 394 | for (const auto& [axis, _] : mConfiguredStrategies) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 395 | BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits); | 
|  | 396 | while (!copyIdBits.isEmpty()) { | 
|  | 397 | uint32_t id = copyIdBits.clearFirstMarkedBit(); | 
|  | 398 | std::optional<float> velocity = getVelocity(axis, id); | 
|  | 399 | if (velocity) { | 
|  | 400 | float adjustedVelocity = | 
|  | 401 | std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity); | 
|  | 402 | computedVelocity.addVelocity(axis, id, adjustedVelocity); | 
|  | 403 | } | 
|  | 404 | } | 
|  | 405 | } | 
|  | 406 | return computedVelocity; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 407 | } | 
|  | 408 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 409 | bool VelocityTracker::getEstimator(int32_t axis, uint32_t id, Estimator* outEstimator) const { | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 410 | const auto& it = mConfiguredStrategies.find(axis); | 
|  | 411 | if (it == mConfiguredStrategies.end()) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 412 | return false; | 
|  | 413 | } | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 414 | return it->second->getEstimator(id, outEstimator); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 415 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 416 |  | 
|  | 417 | // --- LeastSquaresVelocityTrackerStrategy --- | 
|  | 418 |  | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 419 | LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree, | 
|  | 420 | Weighting weighting) | 
|  | 421 | : mDegree(degree), mWeighting(weighting), mIndex(0) {} | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 422 |  | 
|  | 423 | LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() { | 
|  | 424 | } | 
|  | 425 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 426 | void LeastSquaresVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
|  | 427 | BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); | 
|  | 428 | mMovements[mIndex].idBits = remainingIdBits; | 
|  | 429 | } | 
|  | 430 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 431 | void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
|  | 432 | const std::vector<float>& positions) { | 
| Siarhei Vishniakou | 346ac6a | 2019-04-10 09:58:05 -0700 | [diff] [blame] | 433 | if (mMovements[mIndex].eventTime != eventTime) { | 
|  | 434 | // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates | 
|  | 435 | // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include | 
|  | 436 | // the new pointer. If the eventtimes for both events are identical, just update the data | 
|  | 437 | // for this time. | 
|  | 438 | // We only compare against the last value, as it is likely that addMovement is called | 
|  | 439 | // in chronological order as events occur. | 
|  | 440 | mIndex++; | 
|  | 441 | } | 
|  | 442 | if (mIndex == HISTORY_SIZE) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 443 | mIndex = 0; | 
|  | 444 | } | 
|  | 445 |  | 
|  | 446 | Movement& movement = mMovements[mIndex]; | 
|  | 447 | movement.eventTime = eventTime; | 
|  | 448 | movement.idBits = idBits; | 
|  | 449 | uint32_t count = idBits.count(); | 
|  | 450 | for (uint32_t i = 0; i < count; i++) { | 
|  | 451 | movement.positions[i] = positions[i]; | 
|  | 452 | } | 
|  | 453 | } | 
|  | 454 |  | 
|  | 455 | /** | 
|  | 456 | * Solves a linear least squares problem to obtain a N degree polynomial that fits | 
|  | 457 | * the specified input data as nearly as possible. | 
|  | 458 | * | 
|  | 459 | * Returns true if a solution is found, false otherwise. | 
|  | 460 | * | 
|  | 461 | * The input consists of two vectors of data points X and Y with indices 0..m-1 | 
|  | 462 | * along with a weight vector W of the same size. | 
|  | 463 | * | 
|  | 464 | * The output is a vector B with indices 0..n that describes a polynomial | 
|  | 465 | * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i] | 
|  | 466 | * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized. | 
|  | 467 | * | 
|  | 468 | * Accordingly, the weight vector W should be initialized by the caller with the | 
|  | 469 | * reciprocal square root of the variance of the error in each input data point. | 
|  | 470 | * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]). | 
|  | 471 | * The weights express the relative importance of each data point.  If the weights are | 
|  | 472 | * all 1, then the data points are considered to be of equal importance when fitting | 
|  | 473 | * the polynomial.  It is a good idea to choose weights that diminish the importance | 
|  | 474 | * of data points that may have higher than usual error margins. | 
|  | 475 | * | 
|  | 476 | * Errors among data points are assumed to be independent.  W is represented here | 
|  | 477 | * as a vector although in the literature it is typically taken to be a diagonal matrix. | 
|  | 478 | * | 
|  | 479 | * That is to say, the function that generated the input data can be approximated | 
|  | 480 | * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n. | 
|  | 481 | * | 
|  | 482 | * The coefficient of determination (R^2) is also returned to describe the goodness | 
|  | 483 | * of fit of the model for the given data.  It is a value between 0 and 1, where 1 | 
|  | 484 | * indicates perfect correspondence. | 
|  | 485 | * | 
|  | 486 | * This function first expands the X vector to a m by n matrix A such that | 
|  | 487 | * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then | 
|  | 488 | * multiplies it by w[i]./ | 
|  | 489 | * | 
|  | 490 | * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q | 
|  | 491 | * and an m by n upper triangular matrix R.  Because R is upper triangular (lower | 
|  | 492 | * part is all zeroes), we can simplify the decomposition into an m by n matrix | 
|  | 493 | * Q1 and a n by n matrix R1 such that A = Q1 R1. | 
|  | 494 | * | 
|  | 495 | * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y) | 
|  | 496 | * to find B. | 
|  | 497 | * | 
|  | 498 | * For efficiency, we lay out A and Q column-wise in memory because we frequently | 
|  | 499 | * operate on the column vectors.  Conversely, we lay out R row-wise. | 
|  | 500 | * | 
|  | 501 | * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares | 
|  | 502 | * http://en.wikipedia.org/wiki/Gram-Schmidt | 
|  | 503 | */ | 
| Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 504 | static bool solveLeastSquares(const std::vector<float>& x, const std::vector<float>& y, | 
|  | 505 | const std::vector<float>& w, uint32_t n, float* outB, float* outDet) { | 
|  | 506 | const size_t m = x.size(); | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 507 |  | 
|  | 508 | ALOGD_IF(DEBUG_STRATEGY, "solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n), | 
|  | 509 | vectorToString(x).c_str(), vectorToString(y).c_str(), vectorToString(w).c_str()); | 
|  | 510 |  | 
| Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 511 | LOG_ALWAYS_FATAL_IF(m != y.size() || m != w.size(), "Mismatched vector sizes"); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 512 |  | 
|  | 513 | // Expand the X vector to a matrix A, pre-multiplied by the weights. | 
|  | 514 | float a[n][m]; // column-major order | 
|  | 515 | for (uint32_t h = 0; h < m; h++) { | 
|  | 516 | a[0][h] = w[h]; | 
|  | 517 | for (uint32_t i = 1; i < n; i++) { | 
|  | 518 | a[i][h] = a[i - 1][h] * x[h]; | 
|  | 519 | } | 
|  | 520 | } | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 521 |  | 
|  | 522 | ALOGD_IF(DEBUG_STRATEGY, "  - a=%s", | 
|  | 523 | matrixToString(&a[0][0], m, n, false /*rowMajor*/).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 524 |  | 
|  | 525 | // Apply the Gram-Schmidt process to A to obtain its QR decomposition. | 
|  | 526 | float q[n][m]; // orthonormal basis, column-major order | 
|  | 527 | float r[n][n]; // upper triangular matrix, row-major order | 
|  | 528 | for (uint32_t j = 0; j < n; j++) { | 
|  | 529 | for (uint32_t h = 0; h < m; h++) { | 
|  | 530 | q[j][h] = a[j][h]; | 
|  | 531 | } | 
|  | 532 | for (uint32_t i = 0; i < j; i++) { | 
|  | 533 | float dot = vectorDot(&q[j][0], &q[i][0], m); | 
|  | 534 | for (uint32_t h = 0; h < m; h++) { | 
|  | 535 | q[j][h] -= dot * q[i][h]; | 
|  | 536 | } | 
|  | 537 | } | 
|  | 538 |  | 
|  | 539 | float norm = vectorNorm(&q[j][0], m); | 
|  | 540 | if (norm < 0.000001f) { | 
|  | 541 | // vectors are linearly dependent or zero so no solution | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 542 | ALOGD_IF(DEBUG_STRATEGY, "  - no solution, norm=%f", norm); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 543 | return false; | 
|  | 544 | } | 
|  | 545 |  | 
|  | 546 | float invNorm = 1.0f / norm; | 
|  | 547 | for (uint32_t h = 0; h < m; h++) { | 
|  | 548 | q[j][h] *= invNorm; | 
|  | 549 | } | 
|  | 550 | for (uint32_t i = 0; i < n; i++) { | 
|  | 551 | r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m); | 
|  | 552 | } | 
|  | 553 | } | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 554 | if (DEBUG_STRATEGY) { | 
|  | 555 | ALOGD("  - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).c_str()); | 
|  | 556 | ALOGD("  - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 557 |  | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 558 | // calculate QR, if we factored A correctly then QR should equal A | 
|  | 559 | float qr[n][m]; | 
|  | 560 | for (uint32_t h = 0; h < m; h++) { | 
|  | 561 | for (uint32_t i = 0; i < n; i++) { | 
|  | 562 | qr[i][h] = 0; | 
|  | 563 | for (uint32_t j = 0; j < n; j++) { | 
|  | 564 | qr[i][h] += q[j][h] * r[j][i]; | 
|  | 565 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 566 | } | 
|  | 567 | } | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 568 | ALOGD("  - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 569 | } | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 570 |  | 
|  | 571 | // Solve R B = Qt W Y to find B.  This is easy because R is upper triangular. | 
|  | 572 | // We just work from bottom-right to top-left calculating B's coefficients. | 
|  | 573 | float wy[m]; | 
|  | 574 | for (uint32_t h = 0; h < m; h++) { | 
|  | 575 | wy[h] = y[h] * w[h]; | 
|  | 576 | } | 
| Dan Austin | 389ddba | 2015-09-22 14:32:03 -0700 | [diff] [blame] | 577 | for (uint32_t i = n; i != 0; ) { | 
|  | 578 | i--; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 579 | outB[i] = vectorDot(&q[i][0], wy, m); | 
|  | 580 | for (uint32_t j = n - 1; j > i; j--) { | 
|  | 581 | outB[i] -= r[i][j] * outB[j]; | 
|  | 582 | } | 
|  | 583 | outB[i] /= r[i][i]; | 
|  | 584 | } | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 585 |  | 
|  | 586 | ALOGD_IF(DEBUG_STRATEGY, "  - b=%s", vectorToString(outB, n).c_str()); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 587 |  | 
|  | 588 | // Calculate the coefficient of determination as 1 - (SSerr / SStot) where | 
|  | 589 | // SSerr is the residual sum of squares (variance of the error), | 
|  | 590 | // and SStot is the total sum of squares (variance of the data) where each | 
|  | 591 | // has been weighted. | 
|  | 592 | float ymean = 0; | 
|  | 593 | for (uint32_t h = 0; h < m; h++) { | 
|  | 594 | ymean += y[h]; | 
|  | 595 | } | 
|  | 596 | ymean /= m; | 
|  | 597 |  | 
|  | 598 | float sserr = 0; | 
|  | 599 | float sstot = 0; | 
|  | 600 | for (uint32_t h = 0; h < m; h++) { | 
|  | 601 | float err = y[h] - outB[0]; | 
|  | 602 | float term = 1; | 
|  | 603 | for (uint32_t i = 1; i < n; i++) { | 
|  | 604 | term *= x[h]; | 
|  | 605 | err -= term * outB[i]; | 
|  | 606 | } | 
|  | 607 | sserr += w[h] * w[h] * err * err; | 
|  | 608 | float var = y[h] - ymean; | 
|  | 609 | sstot += w[h] * w[h] * var * var; | 
|  | 610 | } | 
|  | 611 | *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1; | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 612 |  | 
|  | 613 | ALOGD_IF(DEBUG_STRATEGY, "  - sserr=%f", sserr); | 
|  | 614 | ALOGD_IF(DEBUG_STRATEGY, "  - sstot=%f", sstot); | 
|  | 615 | ALOGD_IF(DEBUG_STRATEGY, "  - det=%f", *outDet); | 
|  | 616 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 617 | return true; | 
|  | 618 | } | 
|  | 619 |  | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 620 | /* | 
|  | 621 | * Optimized unweighted second-order least squares fit. About 2x speed improvement compared to | 
|  | 622 | * the default implementation | 
|  | 623 | */ | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 624 | static std::optional<std::array<float, 3>> solveUnweightedLeastSquaresDeg2( | 
| Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 625 | const std::vector<float>& x, const std::vector<float>& y) { | 
|  | 626 | const size_t count = x.size(); | 
|  | 627 | LOG_ALWAYS_FATAL_IF(count != y.size(), "Mismatching array sizes"); | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 628 | // Solving y = a*x^2 + b*x + c | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 629 | float sxi = 0, sxiyi = 0, syi = 0, sxi2 = 0, sxi3 = 0, sxi2yi = 0, sxi4 = 0; | 
|  | 630 |  | 
|  | 631 | for (size_t i = 0; i < count; i++) { | 
|  | 632 | float xi = x[i]; | 
|  | 633 | float yi = y[i]; | 
|  | 634 | float xi2 = xi*xi; | 
|  | 635 | float xi3 = xi2*xi; | 
|  | 636 | float xi4 = xi3*xi; | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 637 | float xiyi = xi*yi; | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 638 | float xi2yi = xi2*yi; | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 639 |  | 
|  | 640 | sxi += xi; | 
|  | 641 | sxi2 += xi2; | 
|  | 642 | sxiyi += xiyi; | 
|  | 643 | sxi2yi += xi2yi; | 
|  | 644 | syi += yi; | 
|  | 645 | sxi3 += xi3; | 
|  | 646 | sxi4 += xi4; | 
|  | 647 | } | 
|  | 648 |  | 
|  | 649 | float Sxx = sxi2 - sxi*sxi / count; | 
|  | 650 | float Sxy = sxiyi - sxi*syi / count; | 
|  | 651 | float Sxx2 = sxi3 - sxi*sxi2 / count; | 
|  | 652 | float Sx2y = sxi2yi - sxi2*syi / count; | 
|  | 653 | float Sx2x2 = sxi4 - sxi2*sxi2 / count; | 
|  | 654 |  | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 655 | float denominator = Sxx*Sx2x2 - Sxx2*Sxx2; | 
|  | 656 | if (denominator == 0) { | 
|  | 657 | ALOGW("division by 0 when computing velocity, Sxx=%f, Sx2x2=%f, Sxx2=%f", Sxx, Sx2x2, Sxx2); | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 658 | return std::nullopt; | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 659 | } | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 660 | // Compute a | 
|  | 661 | float numerator = Sx2y*Sxx - Sxy*Sxx2; | 
|  | 662 | float a = numerator / denominator; | 
|  | 663 |  | 
|  | 664 | // Compute b | 
|  | 665 | numerator = Sxy*Sx2x2 - Sx2y*Sxx2; | 
|  | 666 | float b = numerator / denominator; | 
|  | 667 |  | 
|  | 668 | // Compute c | 
|  | 669 | float c = syi/count - b * sxi/count - a * sxi2/count; | 
|  | 670 |  | 
|  | 671 | return std::make_optional(std::array<float, 3>({c, b, a})); | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 672 | } | 
|  | 673 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 674 | bool LeastSquaresVelocityTrackerStrategy::getEstimator(uint32_t id, | 
|  | 675 | VelocityTracker::Estimator* outEstimator) const { | 
|  | 676 | outEstimator->clear(); | 
|  | 677 |  | 
|  | 678 | // Iterate over movement samples in reverse time order and collect samples. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 679 | std::vector<float> positions; | 
| Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 680 | std::vector<float> w; | 
|  | 681 | std::vector<float> time; | 
|  | 682 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 683 | uint32_t index = mIndex; | 
|  | 684 | const Movement& newestMovement = mMovements[mIndex]; | 
|  | 685 | do { | 
|  | 686 | const Movement& movement = mMovements[index]; | 
|  | 687 | if (!movement.idBits.hasBit(id)) { | 
|  | 688 | break; | 
|  | 689 | } | 
|  | 690 |  | 
|  | 691 | nsecs_t age = newestMovement.eventTime - movement.eventTime; | 
|  | 692 | if (age > HORIZON) { | 
|  | 693 | break; | 
|  | 694 | } | 
|  | 695 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 696 | positions.push_back(movement.getPosition(id)); | 
| Siarhei Vishniakou | 81e8b16 | 2020-09-14 22:10:11 -0500 | [diff] [blame] | 697 | w.push_back(chooseWeight(index)); | 
|  | 698 | time.push_back(-age * 0.000000001f); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 699 | index = (index == 0 ? HISTORY_SIZE : index) - 1; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 700 | } while (positions.size() < HISTORY_SIZE); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 701 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 702 | const size_t m = positions.size(); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 703 | if (m == 0) { | 
|  | 704 | return false; // no data | 
|  | 705 | } | 
|  | 706 |  | 
|  | 707 | // Calculate a least squares polynomial fit. | 
|  | 708 | uint32_t degree = mDegree; | 
|  | 709 | if (degree > m - 1) { | 
|  | 710 | degree = m - 1; | 
|  | 711 | } | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 712 |  | 
|  | 713 | if (degree == 2 && mWeighting == WEIGHTING_NONE) { | 
|  | 714 | // Optimize unweighted, quadratic polynomial fit | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 715 | std::optional<std::array<float, 3>> coeff = | 
|  | 716 | solveUnweightedLeastSquaresDeg2(time, positions); | 
|  | 717 | if (coeff) { | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 718 | outEstimator->time = newestMovement.eventTime; | 
|  | 719 | outEstimator->degree = 2; | 
|  | 720 | outEstimator->confidence = 1; | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 721 | for (size_t i = 0; i <= outEstimator->degree; i++) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 722 | outEstimator->coeff[i] = (*coeff)[i]; | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 723 | } | 
| Siarhei Vishniakou | 489d38e | 2017-06-16 17:16:25 +0100 | [diff] [blame] | 724 | return true; | 
|  | 725 | } | 
| Siarhei Vishniakou | e96bc7a | 2018-09-06 10:19:16 -0700 | [diff] [blame] | 726 | } else if (degree >= 1) { | 
|  | 727 | // General case for an Nth degree polynomial fit | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 728 | float det; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 729 | uint32_t n = degree + 1; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 730 | if (solveLeastSquares(time, positions, w, n, outEstimator->coeff, &det)) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 731 | outEstimator->time = newestMovement.eventTime; | 
|  | 732 | outEstimator->degree = degree; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 733 | outEstimator->confidence = det; | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 734 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 735 | ALOGD_IF(DEBUG_STRATEGY, "estimate: degree=%d, coeff=%s, confidence=%f", | 
|  | 736 | int(outEstimator->degree), vectorToString(outEstimator->coeff, n).c_str(), | 
|  | 737 | outEstimator->confidence); | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 738 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 739 | return true; | 
|  | 740 | } | 
|  | 741 | } | 
|  | 742 |  | 
|  | 743 | // No velocity data available for this pointer, but we do have its current position. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 744 | outEstimator->coeff[0] = positions[0]; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 745 | outEstimator->time = newestMovement.eventTime; | 
|  | 746 | outEstimator->degree = 0; | 
|  | 747 | outEstimator->confidence = 1; | 
|  | 748 | return true; | 
|  | 749 | } | 
|  | 750 |  | 
|  | 751 | float LeastSquaresVelocityTrackerStrategy::chooseWeight(uint32_t index) const { | 
|  | 752 | switch (mWeighting) { | 
|  | 753 | case WEIGHTING_DELTA: { | 
|  | 754 | // Weight points based on how much time elapsed between them and the next | 
|  | 755 | // point so that points that "cover" a shorter time span are weighed less. | 
|  | 756 | //   delta  0ms: 0.5 | 
|  | 757 | //   delta 10ms: 1.0 | 
|  | 758 | if (index == mIndex) { | 
|  | 759 | return 1.0f; | 
|  | 760 | } | 
|  | 761 | uint32_t nextIndex = (index + 1) % HISTORY_SIZE; | 
|  | 762 | float deltaMillis = (mMovements[nextIndex].eventTime- mMovements[index].eventTime) | 
|  | 763 | * 0.000001f; | 
|  | 764 | if (deltaMillis < 0) { | 
|  | 765 | return 0.5f; | 
|  | 766 | } | 
|  | 767 | if (deltaMillis < 10) { | 
|  | 768 | return 0.5f + deltaMillis * 0.05; | 
|  | 769 | } | 
|  | 770 | return 1.0f; | 
|  | 771 | } | 
|  | 772 |  | 
|  | 773 | case WEIGHTING_CENTRAL: { | 
|  | 774 | // Weight points based on their age, weighing very recent and very old points less. | 
|  | 775 | //   age  0ms: 0.5 | 
|  | 776 | //   age 10ms: 1.0 | 
|  | 777 | //   age 50ms: 1.0 | 
|  | 778 | //   age 60ms: 0.5 | 
|  | 779 | float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime) | 
|  | 780 | * 0.000001f; | 
|  | 781 | if (ageMillis < 0) { | 
|  | 782 | return 0.5f; | 
|  | 783 | } | 
|  | 784 | if (ageMillis < 10) { | 
|  | 785 | return 0.5f + ageMillis * 0.05; | 
|  | 786 | } | 
|  | 787 | if (ageMillis < 50) { | 
|  | 788 | return 1.0f; | 
|  | 789 | } | 
|  | 790 | if (ageMillis < 60) { | 
|  | 791 | return 0.5f + (60 - ageMillis) * 0.05; | 
|  | 792 | } | 
|  | 793 | return 0.5f; | 
|  | 794 | } | 
|  | 795 |  | 
|  | 796 | case WEIGHTING_RECENT: { | 
|  | 797 | // Weight points based on their age, weighing older points less. | 
|  | 798 | //   age   0ms: 1.0 | 
|  | 799 | //   age  50ms: 1.0 | 
|  | 800 | //   age 100ms: 0.5 | 
|  | 801 | float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime) | 
|  | 802 | * 0.000001f; | 
|  | 803 | if (ageMillis < 50) { | 
|  | 804 | return 1.0f; | 
|  | 805 | } | 
|  | 806 | if (ageMillis < 100) { | 
|  | 807 | return 0.5f + (100 - ageMillis) * 0.01f; | 
|  | 808 | } | 
|  | 809 | return 0.5f; | 
|  | 810 | } | 
|  | 811 |  | 
|  | 812 | case WEIGHTING_NONE: | 
|  | 813 | default: | 
|  | 814 | return 1.0f; | 
|  | 815 | } | 
|  | 816 | } | 
|  | 817 |  | 
|  | 818 |  | 
|  | 819 | // --- IntegratingVelocityTrackerStrategy --- | 
|  | 820 |  | 
|  | 821 | IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) : | 
|  | 822 | mDegree(degree) { | 
|  | 823 | } | 
|  | 824 |  | 
|  | 825 | IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() { | 
|  | 826 | } | 
|  | 827 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 828 | void IntegratingVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
|  | 829 | mPointerIdBits.value &= ~idBits.value; | 
|  | 830 | } | 
|  | 831 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 832 | void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
|  | 833 | const std::vector<float>& positions) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 834 | uint32_t index = 0; | 
|  | 835 | for (BitSet32 iterIdBits(idBits); !iterIdBits.isEmpty();) { | 
|  | 836 | uint32_t id = iterIdBits.clearFirstMarkedBit(); | 
|  | 837 | State& state = mPointerState[id]; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 838 | const float position = positions[index++]; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 839 | if (mPointerIdBits.hasBit(id)) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 840 | updateState(state, eventTime, position); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 841 | } else { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 842 | initState(state, eventTime, position); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 843 | } | 
|  | 844 | } | 
|  | 845 |  | 
|  | 846 | mPointerIdBits = idBits; | 
|  | 847 | } | 
|  | 848 |  | 
|  | 849 | bool IntegratingVelocityTrackerStrategy::getEstimator(uint32_t id, | 
|  | 850 | VelocityTracker::Estimator* outEstimator) const { | 
|  | 851 | outEstimator->clear(); | 
|  | 852 |  | 
|  | 853 | if (mPointerIdBits.hasBit(id)) { | 
|  | 854 | const State& state = mPointerState[id]; | 
|  | 855 | populateEstimator(state, outEstimator); | 
|  | 856 | return true; | 
|  | 857 | } | 
|  | 858 |  | 
|  | 859 | return false; | 
|  | 860 | } | 
|  | 861 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 862 | void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime, | 
|  | 863 | float pos) const { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 864 | state.updateTime = eventTime; | 
|  | 865 | state.degree = 0; | 
|  | 866 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 867 | state.pos = pos; | 
|  | 868 | state.accel = 0; | 
|  | 869 | state.vel = 0; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 870 | } | 
|  | 871 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 872 | void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime, | 
|  | 873 | float pos) const { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 874 | const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS; | 
|  | 875 | const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds | 
|  | 876 |  | 
|  | 877 | if (eventTime <= state.updateTime + MIN_TIME_DELTA) { | 
|  | 878 | return; | 
|  | 879 | } | 
|  | 880 |  | 
|  | 881 | float dt = (eventTime - state.updateTime) * 0.000000001f; | 
|  | 882 | state.updateTime = eventTime; | 
|  | 883 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 884 | float vel = (pos - state.pos) / dt; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 885 | if (state.degree == 0) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 886 | state.vel = vel; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 887 | state.degree = 1; | 
|  | 888 | } else { | 
|  | 889 | float alpha = dt / (FILTER_TIME_CONSTANT + dt); | 
|  | 890 | if (mDegree == 1) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 891 | state.vel += (vel - state.vel) * alpha; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 892 | } else { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 893 | float accel = (vel - state.vel) / dt; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 894 | if (state.degree == 1) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 895 | state.accel = accel; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 896 | state.degree = 2; | 
|  | 897 | } else { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 898 | state.accel += (accel - state.accel) * alpha; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 899 | } | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 900 | state.vel += (state.accel * dt) * alpha; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 901 | } | 
|  | 902 | } | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 903 | state.pos = pos; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 904 | } | 
|  | 905 |  | 
|  | 906 | void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state, | 
|  | 907 | VelocityTracker::Estimator* outEstimator) const { | 
|  | 908 | outEstimator->time = state.updateTime; | 
|  | 909 | outEstimator->confidence = 1.0f; | 
|  | 910 | outEstimator->degree = state.degree; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 911 | outEstimator->coeff[0] = state.pos; | 
|  | 912 | outEstimator->coeff[1] = state.vel; | 
|  | 913 | outEstimator->coeff[2] = state.accel / 2; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 914 | } | 
|  | 915 |  | 
|  | 916 |  | 
|  | 917 | // --- LegacyVelocityTrackerStrategy --- | 
|  | 918 |  | 
| Yeabkal Wubshit | 47ff708 | 2022-09-10 23:09:15 -0700 | [diff] [blame] | 919 | LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() : mIndex(0) {} | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 920 |  | 
|  | 921 | LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() { | 
|  | 922 | } | 
|  | 923 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 924 | void LegacyVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
|  | 925 | BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); | 
|  | 926 | mMovements[mIndex].idBits = remainingIdBits; | 
|  | 927 | } | 
|  | 928 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 929 | void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
|  | 930 | const std::vector<float>& positions) { | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 931 | if (++mIndex == HISTORY_SIZE) { | 
|  | 932 | mIndex = 0; | 
|  | 933 | } | 
|  | 934 |  | 
|  | 935 | Movement& movement = mMovements[mIndex]; | 
|  | 936 | movement.eventTime = eventTime; | 
|  | 937 | movement.idBits = idBits; | 
|  | 938 | uint32_t count = idBits.count(); | 
|  | 939 | for (uint32_t i = 0; i < count; i++) { | 
|  | 940 | movement.positions[i] = positions[i]; | 
|  | 941 | } | 
|  | 942 | } | 
|  | 943 |  | 
|  | 944 | bool LegacyVelocityTrackerStrategy::getEstimator(uint32_t id, | 
|  | 945 | VelocityTracker::Estimator* outEstimator) const { | 
|  | 946 | outEstimator->clear(); | 
|  | 947 |  | 
|  | 948 | const Movement& newestMovement = mMovements[mIndex]; | 
|  | 949 | if (!newestMovement.idBits.hasBit(id)) { | 
|  | 950 | return false; // no data | 
|  | 951 | } | 
|  | 952 |  | 
|  | 953 | // Find the oldest sample that contains the pointer and that is not older than HORIZON. | 
|  | 954 | nsecs_t minTime = newestMovement.eventTime - HORIZON; | 
|  | 955 | uint32_t oldestIndex = mIndex; | 
|  | 956 | uint32_t numTouches = 1; | 
|  | 957 | do { | 
|  | 958 | uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1; | 
|  | 959 | const Movement& nextOldestMovement = mMovements[nextOldestIndex]; | 
|  | 960 | if (!nextOldestMovement.idBits.hasBit(id) | 
|  | 961 | || nextOldestMovement.eventTime < minTime) { | 
|  | 962 | break; | 
|  | 963 | } | 
|  | 964 | oldestIndex = nextOldestIndex; | 
|  | 965 | } while (++numTouches < HISTORY_SIZE); | 
|  | 966 |  | 
|  | 967 | // Calculate an exponentially weighted moving average of the velocity estimate | 
|  | 968 | // at different points in time measured relative to the oldest sample. | 
|  | 969 | // This is essentially an IIR filter.  Newer samples are weighted more heavily | 
|  | 970 | // than older samples.  Samples at equal time points are weighted more or less | 
|  | 971 | // equally. | 
|  | 972 | // | 
|  | 973 | // One tricky problem is that the sample data may be poorly conditioned. | 
|  | 974 | // Sometimes samples arrive very close together in time which can cause us to | 
|  | 975 | // overestimate the velocity at that time point.  Most samples might be measured | 
|  | 976 | // 16ms apart but some consecutive samples could be only 0.5sm apart because | 
|  | 977 | // the hardware or driver reports them irregularly or in bursts. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 978 | float accumV = 0; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 979 | uint32_t index = oldestIndex; | 
|  | 980 | uint32_t samplesUsed = 0; | 
|  | 981 | const Movement& oldestMovement = mMovements[oldestIndex]; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 982 | float oldestPosition = oldestMovement.getPosition(id); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 983 | nsecs_t lastDuration = 0; | 
|  | 984 |  | 
|  | 985 | while (numTouches-- > 1) { | 
|  | 986 | if (++index == HISTORY_SIZE) { | 
|  | 987 | index = 0; | 
|  | 988 | } | 
|  | 989 | const Movement& movement = mMovements[index]; | 
|  | 990 | nsecs_t duration = movement.eventTime - oldestMovement.eventTime; | 
|  | 991 |  | 
|  | 992 | // If the duration between samples is small, we may significantly overestimate | 
|  | 993 | // the velocity.  Consequently, we impose a minimum duration constraint on the | 
|  | 994 | // samples that we include in the calculation. | 
|  | 995 | if (duration >= MIN_DURATION) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 996 | float position = movement.getPosition(id); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 997 | float scale = 1000000000.0f / duration; // one over time delta in seconds | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 998 | float v = (position - oldestPosition) * scale; | 
|  | 999 | accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1000 | lastDuration = duration; | 
|  | 1001 | samplesUsed += 1; | 
|  | 1002 | } | 
|  | 1003 | } | 
|  | 1004 |  | 
|  | 1005 | // Report velocity. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1006 | float newestPosition = newestMovement.getPosition(id); | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1007 | outEstimator->time = newestMovement.eventTime; | 
|  | 1008 | outEstimator->confidence = 1; | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1009 | outEstimator->coeff[0] = newestPosition; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1010 | if (samplesUsed) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1011 | outEstimator->coeff[1] = accumV; | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1012 | outEstimator->degree = 1; | 
|  | 1013 | } else { | 
|  | 1014 | outEstimator->degree = 0; | 
|  | 1015 | } | 
|  | 1016 | return true; | 
|  | 1017 | } | 
|  | 1018 |  | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1019 | // --- ImpulseVelocityTrackerStrategy --- | 
|  | 1020 |  | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1021 | ImpulseVelocityTrackerStrategy::ImpulseVelocityTrackerStrategy(bool deltaValues) | 
|  | 1022 | : mDeltaValues(deltaValues), mIndex(0) {} | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1023 |  | 
|  | 1024 | ImpulseVelocityTrackerStrategy::~ImpulseVelocityTrackerStrategy() { | 
|  | 1025 | } | 
|  | 1026 |  | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1027 | void ImpulseVelocityTrackerStrategy::clearPointers(BitSet32 idBits) { | 
|  | 1028 | BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value); | 
|  | 1029 | mMovements[mIndex].idBits = remainingIdBits; | 
|  | 1030 | } | 
|  | 1031 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1032 | void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits, | 
|  | 1033 | const std::vector<float>& positions) { | 
| Siarhei Vishniakou | 346ac6a | 2019-04-10 09:58:05 -0700 | [diff] [blame] | 1034 | if (mMovements[mIndex].eventTime != eventTime) { | 
|  | 1035 | // When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates | 
|  | 1036 | // of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include | 
|  | 1037 | // the new pointer. If the eventtimes for both events are identical, just update the data | 
|  | 1038 | // for this time. | 
|  | 1039 | // We only compare against the last value, as it is likely that addMovement is called | 
|  | 1040 | // in chronological order as events occur. | 
|  | 1041 | mIndex++; | 
|  | 1042 | } | 
|  | 1043 | if (mIndex == HISTORY_SIZE) { | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1044 | mIndex = 0; | 
|  | 1045 | } | 
|  | 1046 |  | 
|  | 1047 | Movement& movement = mMovements[mIndex]; | 
|  | 1048 | movement.eventTime = eventTime; | 
|  | 1049 | movement.idBits = idBits; | 
|  | 1050 | uint32_t count = idBits.count(); | 
|  | 1051 | for (uint32_t i = 0; i < count; i++) { | 
|  | 1052 | movement.positions[i] = positions[i]; | 
|  | 1053 | } | 
|  | 1054 | } | 
|  | 1055 |  | 
|  | 1056 | /** | 
|  | 1057 | * Calculate the total impulse provided to the screen and the resulting velocity. | 
|  | 1058 | * | 
|  | 1059 | * The touchscreen is modeled as a physical object. | 
|  | 1060 | * Initial condition is discussed below, but for now suppose that v(t=0) = 0 | 
|  | 1061 | * | 
|  | 1062 | * The kinetic energy of the object at the release is E=0.5*m*v^2 | 
|  | 1063 | * Then vfinal = sqrt(2E/m). The goal is to calculate E. | 
|  | 1064 | * | 
|  | 1065 | * The kinetic energy at the release is equal to the total work done on the object by the finger. | 
|  | 1066 | * The total work W is the sum of all dW along the path. | 
|  | 1067 | * | 
|  | 1068 | * dW = F*dx, where dx is the piece of path traveled. | 
|  | 1069 | * Force is change of momentum over time, F = dp/dt = m dv/dt. | 
|  | 1070 | * Then substituting: | 
|  | 1071 | * dW = m (dv/dt) * dx = m * v * dv | 
|  | 1072 | * | 
|  | 1073 | * Summing along the path, we get: | 
|  | 1074 | * W = sum(dW) = sum(m * v * dv) = m * sum(v * dv) | 
|  | 1075 | * Since the mass stays constant, the equation for final velocity is: | 
|  | 1076 | * vfinal = sqrt(2*sum(v * dv)) | 
|  | 1077 | * | 
|  | 1078 | * Here, | 
|  | 1079 | * dv : change of velocity = (v[i+1]-v[i]) | 
|  | 1080 | * dx : change of distance = (x[i+1]-x[i]) | 
|  | 1081 | * dt : change of time = (t[i+1]-t[i]) | 
|  | 1082 | * v : instantaneous velocity = dx/dt | 
|  | 1083 | * | 
|  | 1084 | * The final formula is: | 
|  | 1085 | * vfinal = sqrt(2) * sqrt(sum((v[i]-v[i-1])*|v[i]|)) for all i | 
|  | 1086 | * The absolute value is needed to properly account for the sign. If the velocity over a | 
|  | 1087 | * particular segment descreases, then this indicates braking, which means that negative | 
|  | 1088 | * work was done. So for two positive, but decreasing, velocities, this contribution would be | 
|  | 1089 | * negative and will cause a smaller final velocity. | 
|  | 1090 | * | 
|  | 1091 | * Initial condition | 
|  | 1092 | * There are two ways to deal with initial condition: | 
|  | 1093 | * 1) Assume that v(0) = 0, which would mean that the screen is initially at rest. | 
|  | 1094 | * This is not entirely accurate. We are only taking the past X ms of touch data, where X is | 
|  | 1095 | * currently equal to 100. However, a touch event that created a fling probably lasted for longer | 
|  | 1096 | * than that, which would mean that the user has already been interacting with the touchscreen | 
|  | 1097 | * and it has probably already been moving. | 
|  | 1098 | * 2) Assume that the touchscreen has already been moving at a certain velocity, calculate this | 
|  | 1099 | * initial velocity and the equivalent energy, and start with this initial energy. | 
|  | 1100 | * Consider an example where we have the following data, consisting of 3 points: | 
|  | 1101 | *                 time: t0, t1, t2 | 
|  | 1102 | *                 x   : x0, x1, x2 | 
|  | 1103 | *                 v   : 0 , v1, v2 | 
|  | 1104 | * Here is what will happen in each of these scenarios: | 
|  | 1105 | * 1) By directly applying the formula above with the v(0) = 0 boundary condition, we will get | 
|  | 1106 | * vfinal = sqrt(2*(|v1|*(v1-v0) + |v2|*(v2-v1))). This can be simplified since v0=0 | 
|  | 1107 | * vfinal = sqrt(2*(|v1|*v1 + |v2|*(v2-v1))) = sqrt(2*(v1^2 + |v2|*(v2 - v1))) | 
|  | 1108 | * since velocity is a real number | 
|  | 1109 | * 2) If we treat the screen as already moving, then it must already have an energy (per mass) | 
|  | 1110 | * equal to 1/2*v1^2. Then the initial energy should be 1/2*v1*2, and only the second segment | 
|  | 1111 | * will contribute to the total kinetic energy (since we can effectively consider that v0=v1). | 
|  | 1112 | * This will give the following expression for the final velocity: | 
|  | 1113 | * vfinal = sqrt(2*(1/2*v1^2 + |v2|*(v2-v1))) | 
|  | 1114 | * This analysis can be generalized to an arbitrary number of samples. | 
|  | 1115 | * | 
|  | 1116 | * | 
|  | 1117 | * Comparing the two equations above, we see that the only mathematical difference | 
|  | 1118 | * is the factor of 1/2 in front of the first velocity term. | 
|  | 1119 | * This boundary condition would allow for the "proper" calculation of the case when all of the | 
|  | 1120 | * samples are equally spaced in time and distance, which should suggest a constant velocity. | 
|  | 1121 | * | 
|  | 1122 | * Note that approach 2) is sensitive to the proper ordering of the data in time, since | 
|  | 1123 | * the boundary condition must be applied to the oldest sample to be accurate. | 
|  | 1124 | */ | 
| Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 1125 | static float kineticEnergyToVelocity(float work) { | 
|  | 1126 | static constexpr float sqrt2 = 1.41421356237; | 
|  | 1127 | return (work < 0 ? -1.0 : 1.0) * sqrtf(fabsf(work)) * sqrt2; | 
|  | 1128 | } | 
|  | 1129 |  | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1130 | static float calculateImpulseVelocity(const nsecs_t* t, const float* x, size_t count, | 
|  | 1131 | bool deltaValues) { | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1132 | // The input should be in reversed time order (most recent sample at index i=0) | 
|  | 1133 | // t[i] is in nanoseconds, but due to FP arithmetic, convert to seconds inside this function | 
| Siarhei Vishniakou | 6de8f5e | 2018-03-02 18:48:15 -0800 | [diff] [blame] | 1134 | static constexpr float SECONDS_PER_NANO = 1E-9; | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1135 |  | 
|  | 1136 | if (count < 2) { | 
|  | 1137 | return 0; // if 0 or 1 points, velocity is zero | 
|  | 1138 | } | 
|  | 1139 | if (t[1] > t[0]) { // Algorithm will still work, but not perfectly | 
|  | 1140 | ALOGE("Samples provided to calculateImpulseVelocity in the wrong order"); | 
|  | 1141 | } | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1142 |  | 
|  | 1143 | // If the data values are delta values, we do not have to calculate deltas here. | 
|  | 1144 | // We can use the delta values directly, along with the calculated time deltas. | 
|  | 1145 | // Since the data value input is in reversed time order: | 
|  | 1146 | //      [a] for non-delta inputs, instantenous velocity = (x[i] - x[i-1])/(t[i] - t[i-1]) | 
|  | 1147 | //      [b] for delta inputs, instantenous velocity = -x[i-1]/(t[i] - t[i - 1]) | 
|  | 1148 | // e.g., let the non-delta values are: V = [2, 3, 7], the equivalent deltas are D = [2, 1, 4]. | 
|  | 1149 | // Since the input is in reversed time order, the input values for this function would be | 
|  | 1150 | // V'=[7, 3, 2] and D'=[4, 1, 2] for the non-delta and delta values, respectively. | 
|  | 1151 | // | 
|  | 1152 | // The equivalent of {(V'[2] - V'[1]) = 2 - 3 = -1} would be {-D'[1] = -1} | 
|  | 1153 | // Similarly, the equivalent of {(V'[1] - V'[0]) = 3 - 7 = -4} would be {-D'[0] = -4} | 
|  | 1154 |  | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1155 | if (count == 2) { // if 2 points, basic linear calculation | 
|  | 1156 | if (t[1] == t[0]) { | 
|  | 1157 | ALOGE("Events have identical time stamps t=%" PRId64 ", setting velocity = 0", t[0]); | 
|  | 1158 | return 0; | 
|  | 1159 | } | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1160 | const float deltaX = deltaValues ? -x[0] : x[1] - x[0]; | 
|  | 1161 | return deltaX / (SECONDS_PER_NANO * (t[1] - t[0])); | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1162 | } | 
|  | 1163 | // Guaranteed to have at least 3 points here | 
|  | 1164 | float work = 0; | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1165 | for (size_t i = count - 1; i > 0 ; i--) { // start with the oldest sample and go forward in time | 
|  | 1166 | if (t[i] == t[i-1]) { | 
|  | 1167 | ALOGE("Events have identical time stamps t=%" PRId64 ", skipping sample", t[i]); | 
|  | 1168 | continue; | 
|  | 1169 | } | 
| Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 1170 | float vprev = kineticEnergyToVelocity(work); // v[i-1] | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1171 | const float deltaX = deltaValues ? -x[i-1] : x[i] - x[i-1]; | 
|  | 1172 | float vcurr = deltaX / (SECONDS_PER_NANO * (t[i] - t[i-1])); // v[i] | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1173 | work += (vcurr - vprev) * fabsf(vcurr); | 
|  | 1174 | if (i == count - 1) { | 
|  | 1175 | work *= 0.5; // initial condition, case 2) above | 
|  | 1176 | } | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1177 | } | 
| Siarhei Vishniakou | 97b5e18 | 2017-09-01 13:52:33 -0700 | [diff] [blame] | 1178 | return kineticEnergyToVelocity(work); | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1179 | } | 
|  | 1180 |  | 
|  | 1181 | bool ImpulseVelocityTrackerStrategy::getEstimator(uint32_t id, | 
|  | 1182 | VelocityTracker::Estimator* outEstimator) const { | 
|  | 1183 | outEstimator->clear(); | 
|  | 1184 |  | 
|  | 1185 | // Iterate over movement samples in reverse time order and collect samples. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1186 | float positions[HISTORY_SIZE]; | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1187 | nsecs_t time[HISTORY_SIZE]; | 
|  | 1188 | size_t m = 0; // number of points that will be used for fitting | 
|  | 1189 | size_t index = mIndex; | 
|  | 1190 | const Movement& newestMovement = mMovements[mIndex]; | 
|  | 1191 | do { | 
|  | 1192 | const Movement& movement = mMovements[index]; | 
|  | 1193 | if (!movement.idBits.hasBit(id)) { | 
|  | 1194 | break; | 
|  | 1195 | } | 
|  | 1196 |  | 
|  | 1197 | nsecs_t age = newestMovement.eventTime - movement.eventTime; | 
|  | 1198 | if (age > HORIZON) { | 
|  | 1199 | break; | 
|  | 1200 | } | 
|  | 1201 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1202 | positions[m] = movement.getPosition(id); | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1203 | time[m] = movement.eventTime; | 
|  | 1204 | index = (index == 0 ? HISTORY_SIZE : index) - 1; | 
|  | 1205 | } while (++m < HISTORY_SIZE); | 
|  | 1206 |  | 
|  | 1207 | if (m == 0) { | 
|  | 1208 | return false; // no data | 
|  | 1209 | } | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1210 | outEstimator->coeff[0] = 0; | 
| Yeabkal Wubshit | 0bb5e59 | 2022-09-14 01:22:28 -0700 | [diff] [blame] | 1211 | outEstimator->coeff[1] = calculateImpulseVelocity(time, positions, m, mDeltaValues); | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1212 | outEstimator->coeff[2] = 0; | 
|  | 1213 |  | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1214 | outEstimator->time = newestMovement.eventTime; | 
|  | 1215 | outEstimator->degree = 2; // similar results to 2nd degree fit | 
|  | 1216 | outEstimator->confidence = 1; | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 1217 |  | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1218 | ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", outEstimator->coeff[1]); | 
| Siarhei Vishniakou | 9f26fc3 | 2022-06-17 22:13:57 +0000 | [diff] [blame] | 1219 |  | 
| Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1220 | if (DEBUG_IMPULSE) { | 
|  | 1221 | // TODO(b/134179997): delete this block once the switch to 'impulse' is complete. | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1222 | // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons. | 
|  | 1223 | // X axis chosen arbitrarily for velocity comparisons. | 
| Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1224 | VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2); | 
|  | 1225 | BitSet32 idBits; | 
|  | 1226 | const uint32_t pointerId = 0; | 
|  | 1227 | idBits.markBit(pointerId); | 
|  | 1228 | for (ssize_t i = m - 1; i >= 0; i--) { | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1229 | lsq2.addMovement(time[i], idBits, {{AMOTION_EVENT_AXIS_X, {positions[i]}}}); | 
| Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1230 | } | 
| Yeabkal Wubshit | 384ab0f | 2022-09-09 16:39:18 +0000 | [diff] [blame] | 1231 | std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId); | 
|  | 1232 | if (v) { | 
|  | 1233 | ALOGD("lsq2 velocity: %.1f", *v); | 
| Siarhei Vishniakou | 276467b | 2022-03-17 09:43:28 -0700 | [diff] [blame] | 1234 | } else { | 
|  | 1235 | ALOGD("lsq2 velocity: could not compute velocity"); | 
|  | 1236 | } | 
| Siarhei Vishniakou | e37bcec | 2021-09-28 14:24:32 -0700 | [diff] [blame] | 1237 | } | 
| Siarhei Vishniakou | 00a4ea9 | 2017-06-08 21:43:20 +0100 | [diff] [blame] | 1238 | return true; | 
|  | 1239 | } | 
|  | 1240 |  | 
| Jeff Brown | 5912f95 | 2013-07-01 19:10:31 -0700 | [diff] [blame] | 1241 | } // namespace android |