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