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