blob: 7300ea1bd1db950884f8fb135091d17a7169d8ae [file] [log] [blame]
Jeff Brown8a90e6e2012-05-11 12:24:35 -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
Jeff Brown9eb7d862012-06-01 12:39:25 -070023// Log debug messages about the progress of the algorithm itself.
24#define DEBUG_STRATEGY 0
Jeff Brown8a90e6e2012-05-11 12:24:35 -070025
26#include <math.h>
27#include <limits.h>
28
29#include <androidfw/VelocityTracker.h>
30#include <utils/BitSet.h>
31#include <utils/String8.h>
32#include <utils/Timers.h>
33
Jeff Brown9eb7d862012-06-01 12:39:25 -070034#include <cutils/properties.h>
35
Jeff Brown8a90e6e2012-05-11 12:24:35 -070036namespace android {
37
Jeff Brown90729402012-05-14 18:46:18 -070038// Nanoseconds per milliseconds.
39static const nsecs_t NANOS_PER_MS = 1000000;
40
41// Threshold for determining that a pointer has stopped moving.
42// Some input devices do not send ACTION_MOVE events in the case where a pointer has
43// stopped. We need to detect this case so that we can accurately predict the
44// velocity after the pointer starts moving again.
45static const nsecs_t ASSUME_POINTER_STOPPED_TIME = 40 * NANOS_PER_MS;
46
47
Jeff Brown85bd0d62012-05-13 15:30:42 -070048static float vectorDot(const float* a, const float* b, uint32_t m) {
Jeff Brown8a90e6e2012-05-11 12:24:35 -070049 float r = 0;
50 while (m--) {
51 r += *(a++) * *(b++);
52 }
53 return r;
54}
55
Jeff Brown85bd0d62012-05-13 15:30:42 -070056static float vectorNorm(const float* a, uint32_t m) {
Jeff Brown8a90e6e2012-05-11 12:24:35 -070057 float r = 0;
58 while (m--) {
59 float t = *(a++);
60 r += t * t;
61 }
62 return sqrtf(r);
63}
64
Jeff Brown9eb7d862012-06-01 12:39:25 -070065#if DEBUG_STRATEGY || DEBUG_VELOCITY
Jeff Brown8a90e6e2012-05-11 12:24:35 -070066static String8 vectorToString(const float* a, uint32_t m) {
67 String8 str;
68 str.append("[");
69 while (m--) {
70 str.appendFormat(" %f", *(a++));
71 if (m) {
72 str.append(",");
73 }
74 }
75 str.append(" ]");
76 return str;
77}
78
79static String8 matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) {
80 String8 str;
81 str.append("[");
82 for (size_t i = 0; i < m; i++) {
83 if (i) {
84 str.append(",");
85 }
86 str.append(" [");
87 for (size_t j = 0; j < n; j++) {
88 if (j) {
89 str.append(",");
90 }
91 str.appendFormat(" %f", a[rowMajor ? i * n + j : j * m + i]);
92 }
93 str.append(" ]");
94 }
95 str.append(" ]");
96 return str;
97}
98#endif
99
Jeff Brown85bd0d62012-05-13 15:30:42 -0700100
101// --- VelocityTracker ---
102
Jeff Brown9eb7d862012-06-01 12:39:25 -0700103// The default velocity tracker strategy.
104// Although other strategies are available for testing and comparison purposes,
105// this is the strategy that applications will actually use. Be very careful
106// when adjusting the default strategy because it can dramatically affect
107// (often in a bad way) the user experience.
108const char* VelocityTracker::DEFAULT_STRATEGY = "lsq2";
109
110VelocityTracker::VelocityTracker(const char* strategy) :
111 mLastEventTime(0), mCurrentPointerIdBits(0), mActivePointerId(-1) {
112 char value[PROPERTY_VALUE_MAX];
113
114 // Allow the default strategy to be overridden using a system property for debugging.
115 if (!strategy) {
116 int length = property_get("debug.velocitytracker.strategy", value, NULL);
117 if (length > 0) {
118 strategy = value;
119 } else {
120 strategy = DEFAULT_STRATEGY;
121 }
122 }
123
124 // Configure the strategy.
125 if (!configureStrategy(strategy)) {
126 ALOGD("Unrecognized velocity tracker strategy name '%s'.", strategy);
127 if (!configureStrategy(DEFAULT_STRATEGY)) {
128 LOG_ALWAYS_FATAL("Could not create the default velocity tracker strategy '%s'!",
129 strategy);
130 }
131 }
Jeff Brown85bd0d62012-05-13 15:30:42 -0700132}
133
Jeff Brown85bd0d62012-05-13 15:30:42 -0700134VelocityTracker::~VelocityTracker() {
135 delete mStrategy;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700136}
137
Jeff Brown9eb7d862012-06-01 12:39:25 -0700138bool VelocityTracker::configureStrategy(const char* strategy) {
139 mStrategy = createStrategy(strategy);
140 return mStrategy != NULL;
141}
142
143VelocityTrackerStrategy* VelocityTracker::createStrategy(const char* strategy) {
144 if (!strcmp("lsq1", strategy)) {
145 // 1st order least squares. Quality: POOR.
146 // Frequently underfits the touch data especially when the finger accelerates
147 // or changes direction. Often underestimates velocity. The direction
148 // is overly influenced by historical touch points.
149 return new LeastSquaresVelocityTrackerStrategy(1);
150 }
151 if (!strcmp("lsq2", strategy)) {
152 // 2nd order least squares. Quality: VERY GOOD.
153 // Pretty much ideal, but can be confused by certain kinds of touch data,
154 // particularly if the panel has a tendency to generate delayed,
155 // duplicate or jittery touch coordinates when the finger is released.
156 return new LeastSquaresVelocityTrackerStrategy(2);
157 }
158 if (!strcmp("lsq3", strategy)) {
159 // 3rd order least squares. Quality: UNUSABLE.
160 // Frequently overfits the touch data yielding wildly divergent estimates
161 // of the velocity when the finger is released.
162 return new LeastSquaresVelocityTrackerStrategy(3);
163 }
Jeff Brown53dd12a2012-06-01 13:24:04 -0700164 if (!strcmp("int1", strategy)) {
165 // 1st order integrating filter. Quality: GOOD.
166 // Not as good as 'lsq2' because it cannot estimate acceleration but it is
167 // more tolerant of errors. Like 'lsq1', this strategy tends to underestimate
168 // the velocity of a fling but this strategy tends to respond to changes in
169 // direction more quickly and accurately.
170 return new IntegratingVelocityTrackerStrategy();
171 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700172 return NULL;
173}
174
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700175void VelocityTracker::clear() {
Jeff Brown85bd0d62012-05-13 15:30:42 -0700176 mCurrentPointerIdBits.clear();
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700177 mActivePointerId = -1;
Jeff Brown85bd0d62012-05-13 15:30:42 -0700178
179 mStrategy->clear();
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700180}
181
182void VelocityTracker::clearPointers(BitSet32 idBits) {
Jeff Brown85bd0d62012-05-13 15:30:42 -0700183 BitSet32 remainingIdBits(mCurrentPointerIdBits.value & ~idBits.value);
184 mCurrentPointerIdBits = remainingIdBits;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700185
186 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
187 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
188 }
Jeff Brown85bd0d62012-05-13 15:30:42 -0700189
190 mStrategy->clearPointers(idBits);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700191}
192
193void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700194 while (idBits.count() > MAX_POINTERS) {
195 idBits.clearLastMarkedBit();
196 }
197
Jeff Brown90729402012-05-14 18:46:18 -0700198 if ((mCurrentPointerIdBits.value & idBits.value)
199 && eventTime >= mLastEventTime + ASSUME_POINTER_STOPPED_TIME) {
200#if DEBUG_VELOCITY
201 ALOGD("VelocityTracker: stopped for %0.3f ms, clearing state.",
202 (eventTime - mLastEventTime) * 0.000001f);
203#endif
204 // We have not received any movements for too long. Assume that all pointers
205 // have stopped.
206 mStrategy->clear();
207 }
208 mLastEventTime = eventTime;
209
Jeff Brown85bd0d62012-05-13 15:30:42 -0700210 mCurrentPointerIdBits = idBits;
211 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
212 mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit();
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700213 }
214
Jeff Brown85bd0d62012-05-13 15:30:42 -0700215 mStrategy->addMovement(eventTime, idBits, positions);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700216
217#if DEBUG_VELOCITY
218 ALOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
219 eventTime, idBits.value, mActivePointerId);
220 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
221 uint32_t id = iterBits.firstMarkedBit();
222 uint32_t index = idBits.getIndexOfBit(id);
223 iterBits.clearBit(id);
224 Estimator estimator;
Jeff Brown85bd0d62012-05-13 15:30:42 -0700225 getEstimator(id, &estimator);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700226 ALOGD(" %d: position (%0.3f, %0.3f), "
227 "estimator (degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f)",
228 id, positions[index].x, positions[index].y,
229 int(estimator.degree),
Jeff Browndcab1902012-05-14 18:44:17 -0700230 vectorToString(estimator.xCoeff, estimator.degree + 1).string(),
231 vectorToString(estimator.yCoeff, estimator.degree + 1).string(),
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700232 estimator.confidence);
233 }
234#endif
235}
236
237void VelocityTracker::addMovement(const MotionEvent* event) {
238 int32_t actionMasked = event->getActionMasked();
239
240 switch (actionMasked) {
241 case AMOTION_EVENT_ACTION_DOWN:
242 case AMOTION_EVENT_ACTION_HOVER_ENTER:
243 // Clear all pointers on down before adding the new movement.
244 clear();
245 break;
246 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
247 // Start a new movement trace for a pointer that just went down.
248 // We do this on down instead of on up because the client may want to query the
249 // final velocity for a pointer that just went up.
250 BitSet32 downIdBits;
251 downIdBits.markBit(event->getPointerId(event->getActionIndex()));
252 clearPointers(downIdBits);
253 break;
254 }
255 case AMOTION_EVENT_ACTION_MOVE:
256 case AMOTION_EVENT_ACTION_HOVER_MOVE:
257 break;
258 default:
259 // Ignore all other actions because they do not convey any new information about
260 // pointer movement. We also want to preserve the last known velocity of the pointers.
261 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
262 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
263 // pointers that remained down but we will also receive an ACTION_MOVE with this
264 // information if any of them actually moved. Since we don't know how many pointers
265 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
266 // before adding the movement.
267 return;
268 }
269
270 size_t pointerCount = event->getPointerCount();
271 if (pointerCount > MAX_POINTERS) {
272 pointerCount = MAX_POINTERS;
273 }
274
275 BitSet32 idBits;
276 for (size_t i = 0; i < pointerCount; i++) {
277 idBits.markBit(event->getPointerId(i));
278 }
279
Jeff Browndcab1902012-05-14 18:44:17 -0700280 uint32_t pointerIndex[MAX_POINTERS];
281 for (size_t i = 0; i < pointerCount; i++) {
282 pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i));
283 }
284
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700285 nsecs_t eventTime;
286 Position positions[pointerCount];
287
288 size_t historySize = event->getHistorySize();
289 for (size_t h = 0; h < historySize; h++) {
290 eventTime = event->getHistoricalEventTime(h);
291 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browndcab1902012-05-14 18:44:17 -0700292 uint32_t index = pointerIndex[i];
293 positions[index].x = event->getHistoricalX(i, h);
294 positions[index].y = event->getHistoricalY(i, h);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700295 }
296 addMovement(eventTime, idBits, positions);
297 }
298
299 eventTime = event->getEventTime();
300 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browndcab1902012-05-14 18:44:17 -0700301 uint32_t index = pointerIndex[i];
302 positions[index].x = event->getX(i);
303 positions[index].y = event->getY(i);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700304 }
305 addMovement(eventTime, idBits, positions);
306}
307
Jeff Brown85bd0d62012-05-13 15:30:42 -0700308bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
309 Estimator estimator;
310 if (getEstimator(id, &estimator) && estimator.degree >= 1) {
311 *outVx = estimator.xCoeff[1];
312 *outVy = estimator.yCoeff[1];
313 return true;
314 }
315 *outVx = 0;
316 *outVy = 0;
317 return false;
318}
319
320bool VelocityTracker::getEstimator(uint32_t id, Estimator* outEstimator) const {
321 return mStrategy->getEstimator(id, outEstimator);
322}
323
324
325// --- LeastSquaresVelocityTrackerStrategy ---
326
Jeff Brown85bd0d62012-05-13 15:30:42 -0700327const nsecs_t LeastSquaresVelocityTrackerStrategy::HORIZON;
328const uint32_t LeastSquaresVelocityTrackerStrategy::HISTORY_SIZE;
329
Jeff Brown9eb7d862012-06-01 12:39:25 -0700330LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree) :
331 mDegree(degree) {
Jeff Brown85bd0d62012-05-13 15:30:42 -0700332 clear();
333}
334
335LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {
336}
337
338void LeastSquaresVelocityTrackerStrategy::clear() {
339 mIndex = 0;
340 mMovements[0].idBits.clear();
341}
342
343void LeastSquaresVelocityTrackerStrategy::clearPointers(BitSet32 idBits) {
344 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
345 mMovements[mIndex].idBits = remainingIdBits;
346}
347
348void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
349 const VelocityTracker::Position* positions) {
350 if (++mIndex == HISTORY_SIZE) {
351 mIndex = 0;
352 }
353
354 Movement& movement = mMovements[mIndex];
355 movement.eventTime = eventTime;
356 movement.idBits = idBits;
357 uint32_t count = idBits.count();
358 for (uint32_t i = 0; i < count; i++) {
359 movement.positions[i] = positions[i];
360 }
361}
362
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700363/**
364 * Solves a linear least squares problem to obtain a N degree polynomial that fits
365 * the specified input data as nearly as possible.
366 *
367 * Returns true if a solution is found, false otherwise.
368 *
369 * The input consists of two vectors of data points X and Y with indices 0..m-1.
Jeff Brown9eb7d862012-06-01 12:39:25 -0700370 * The output is a vector B with indices 0..n that describes a polynomial
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700371 * that fits the data, such the sum of abs(Y[i] - (B[0] + B[1] X[i] + B[2] X[i]^2 ... B[n] X[i]^n))
372 * for all i between 0 and m-1 is minimized.
373 *
374 * That is to say, the function that generated the input data can be approximated
375 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
376 *
377 * The coefficient of determination (R^2) is also returned to describe the goodness
378 * of fit of the model for the given data. It is a value between 0 and 1, where 1
379 * indicates perfect correspondence.
380 *
381 * This function first expands the X vector to a m by n matrix A such that
382 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n.
383 *
384 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
385 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
386 * part is all zeroes), we can simplify the decomposition into an m by n matrix
387 * Q1 and a n by n matrix R1 such that A = Q1 R1.
388 *
389 * Finally we solve the system of linear equations given by R1 B = (Qtranspose Y)
390 * to find B.
391 *
392 * For efficiency, we lay out A and Q column-wise in memory because we frequently
393 * operate on the column vectors. Conversely, we lay out R row-wise.
394 *
395 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
396 * http://en.wikipedia.org/wiki/Gram-Schmidt
397 */
398static bool solveLeastSquares(const float* x, const float* y, uint32_t m, uint32_t n,
399 float* outB, float* outDet) {
Jeff Brown9eb7d862012-06-01 12:39:25 -0700400#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700401 ALOGD("solveLeastSquares: m=%d, n=%d, x=%s, y=%s", int(m), int(n),
402 vectorToString(x, m).string(), vectorToString(y, m).string());
403#endif
404
405 // Expand the X vector to a matrix A.
406 float a[n][m]; // column-major order
407 for (uint32_t h = 0; h < m; h++) {
408 a[0][h] = 1;
409 for (uint32_t i = 1; i < n; i++) {
410 a[i][h] = a[i - 1][h] * x[h];
411 }
412 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700413#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700414 ALOGD(" - a=%s", matrixToString(&a[0][0], m, n, false /*rowMajor*/).string());
415#endif
416
417 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
418 float q[n][m]; // orthonormal basis, column-major order
419 float r[n][n]; // upper triangular matrix, row-major order
420 for (uint32_t j = 0; j < n; j++) {
421 for (uint32_t h = 0; h < m; h++) {
422 q[j][h] = a[j][h];
423 }
424 for (uint32_t i = 0; i < j; i++) {
425 float dot = vectorDot(&q[j][0], &q[i][0], m);
426 for (uint32_t h = 0; h < m; h++) {
427 q[j][h] -= dot * q[i][h];
428 }
429 }
430
431 float norm = vectorNorm(&q[j][0], m);
432 if (norm < 0.000001f) {
433 // vectors are linearly dependent or zero so no solution
Jeff Brown9eb7d862012-06-01 12:39:25 -0700434#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700435 ALOGD(" - no solution, norm=%f", norm);
436#endif
437 return false;
438 }
439
440 float invNorm = 1.0f / norm;
441 for (uint32_t h = 0; h < m; h++) {
442 q[j][h] *= invNorm;
443 }
444 for (uint32_t i = 0; i < n; i++) {
445 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
446 }
447 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700448#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700449 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).string());
450 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).string());
451
452 // calculate QR, if we factored A correctly then QR should equal A
453 float qr[n][m];
454 for (uint32_t h = 0; h < m; h++) {
455 for (uint32_t i = 0; i < n; i++) {
456 qr[i][h] = 0;
457 for (uint32_t j = 0; j < n; j++) {
458 qr[i][h] += q[j][h] * r[j][i];
459 }
460 }
461 }
462 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).string());
463#endif
464
465 // Solve R B = Qt Y to find B. This is easy because R is upper triangular.
466 // We just work from bottom-right to top-left calculating B's coefficients.
467 for (uint32_t i = n; i-- != 0; ) {
468 outB[i] = vectorDot(&q[i][0], y, m);
469 for (uint32_t j = n - 1; j > i; j--) {
470 outB[i] -= r[i][j] * outB[j];
471 }
472 outB[i] /= r[i][i];
473 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700474#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700475 ALOGD(" - b=%s", vectorToString(outB, n).string());
476#endif
477
478 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
479 // SSerr is the residual sum of squares (squared variance of the error),
480 // and SStot is the total sum of squares (squared variance of the data).
481 float ymean = 0;
482 for (uint32_t h = 0; h < m; h++) {
483 ymean += y[h];
484 }
485 ymean /= m;
486
487 float sserr = 0;
488 float sstot = 0;
489 for (uint32_t h = 0; h < m; h++) {
490 float err = y[h] - outB[0];
491 float term = 1;
492 for (uint32_t i = 1; i < n; i++) {
493 term *= x[h];
494 err -= term * outB[i];
495 }
496 sserr += err * err;
497 float var = y[h] - ymean;
498 sstot += var * var;
499 }
500 *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1;
Jeff Brown9eb7d862012-06-01 12:39:25 -0700501#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700502 ALOGD(" - sserr=%f", sserr);
503 ALOGD(" - sstot=%f", sstot);
504 ALOGD(" - det=%f", *outDet);
505#endif
506 return true;
507}
508
Jeff Brown85bd0d62012-05-13 15:30:42 -0700509bool LeastSquaresVelocityTrackerStrategy::getEstimator(uint32_t id,
510 VelocityTracker::Estimator* outEstimator) const {
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700511 outEstimator->clear();
512
513 // Iterate over movement samples in reverse time order and collect samples.
514 float x[HISTORY_SIZE];
515 float y[HISTORY_SIZE];
516 float time[HISTORY_SIZE];
517 uint32_t m = 0;
518 uint32_t index = mIndex;
519 const Movement& newestMovement = mMovements[mIndex];
520 do {
521 const Movement& movement = mMovements[index];
522 if (!movement.idBits.hasBit(id)) {
523 break;
524 }
525
526 nsecs_t age = newestMovement.eventTime - movement.eventTime;
Jeff Brown85bd0d62012-05-13 15:30:42 -0700527 if (age > HORIZON) {
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700528 break;
529 }
530
Jeff Brown85bd0d62012-05-13 15:30:42 -0700531 const VelocityTracker::Position& position = movement.getPosition(id);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700532 x[m] = position.x;
533 y[m] = position.y;
534 time[m] = -age * 0.000000001f;
535 index = (index == 0 ? HISTORY_SIZE : index) - 1;
536 } while (++m < HISTORY_SIZE);
537
538 if (m == 0) {
539 return false; // no data
540 }
541
542 // Calculate a least squares polynomial fit.
Jeff Brown9eb7d862012-06-01 12:39:25 -0700543 uint32_t degree = mDegree;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700544 if (degree > m - 1) {
545 degree = m - 1;
546 }
547 if (degree >= 1) {
548 float xdet, ydet;
549 uint32_t n = degree + 1;
550 if (solveLeastSquares(time, x, m, n, outEstimator->xCoeff, &xdet)
551 && solveLeastSquares(time, y, m, n, outEstimator->yCoeff, &ydet)) {
Jeff Brown90729402012-05-14 18:46:18 -0700552 outEstimator->time = newestMovement.eventTime;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700553 outEstimator->degree = degree;
554 outEstimator->confidence = xdet * ydet;
Jeff Brown9eb7d862012-06-01 12:39:25 -0700555#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700556 ALOGD("estimate: degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f",
557 int(outEstimator->degree),
558 vectorToString(outEstimator->xCoeff, n).string(),
559 vectorToString(outEstimator->yCoeff, n).string(),
560 outEstimator->confidence);
561#endif
562 return true;
563 }
564 }
565
566 // No velocity data available for this pointer, but we do have its current position.
567 outEstimator->xCoeff[0] = x[0];
568 outEstimator->yCoeff[0] = y[0];
Jeff Brown90729402012-05-14 18:46:18 -0700569 outEstimator->time = newestMovement.eventTime;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700570 outEstimator->degree = 0;
571 outEstimator->confidence = 1;
572 return true;
573}
574
Jeff Brown53dd12a2012-06-01 13:24:04 -0700575
576// --- IntegratingVelocityTrackerStrategy ---
577
578IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy() {
579}
580
581IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() {
582}
583
584void IntegratingVelocityTrackerStrategy::clear() {
585 mPointerIdBits.clear();
586}
587
588void IntegratingVelocityTrackerStrategy::clearPointers(BitSet32 idBits) {
589 mPointerIdBits.value &= ~idBits.value;
590}
591
592void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
593 const VelocityTracker::Position* positions) {
594 uint32_t index = 0;
595 for (BitSet32 iterIdBits(idBits); !iterIdBits.isEmpty();) {
596 uint32_t id = iterIdBits.clearFirstMarkedBit();
597 State& state = mPointerState[id];
598 const VelocityTracker::Position& position = positions[index++];
599 if (mPointerIdBits.hasBit(id)) {
600 updateState(state, eventTime, position.x, position.y);
601 } else {
602 initState(state, eventTime, position.x, position.y);
603 }
604 }
605
606 mPointerIdBits = idBits;
607}
608
609bool IntegratingVelocityTrackerStrategy::getEstimator(uint32_t id,
610 VelocityTracker::Estimator* outEstimator) const {
611 outEstimator->clear();
612
613 if (mPointerIdBits.hasBit(id)) {
614 const State& state = mPointerState[id];
615 populateEstimator(state, outEstimator);
616 return true;
617 }
618
619 return false;
620}
621
622void IntegratingVelocityTrackerStrategy::initState(State& state,
623 nsecs_t eventTime, float xpos, float ypos) {
624 state.updateTime = eventTime;
625 state.first = true;
626
627 state.xpos = xpos;
628 state.xvel = 0;
629 state.ypos = ypos;
630 state.yvel = 0;
631}
632
633void IntegratingVelocityTrackerStrategy::updateState(State& state,
634 nsecs_t eventTime, float xpos, float ypos) {
635 const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
636 const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
637
638 if (eventTime <= state.updateTime + MIN_TIME_DELTA) {
639 return;
640 }
641
642 float dt = (eventTime - state.updateTime) * 0.000000001f;
643 state.updateTime = eventTime;
644
645 float xvel = (xpos - state.xpos) / dt;
646 float yvel = (ypos - state.ypos) / dt;
647 if (state.first) {
648 state.xvel = xvel;
649 state.yvel = yvel;
650 state.first = false;
651 } else {
652 float alpha = dt / (FILTER_TIME_CONSTANT + dt);
653 state.xvel += (xvel - state.xvel) * alpha;
654 state.yvel += (yvel - state.yvel) * alpha;
655 }
656 state.xpos = xpos;
657 state.ypos = ypos;
658}
659
660void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state,
661 VelocityTracker::Estimator* outEstimator) {
662 outEstimator->time = state.updateTime;
663 outEstimator->degree = 1;
664 outEstimator->confidence = 1.0f;
665 outEstimator->xCoeff[0] = state.xpos;
666 outEstimator->xCoeff[1] = state.xvel;
667 outEstimator->yCoeff[0] = state.ypos;
668 outEstimator->yCoeff[1] = state.yvel;
669}
670
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700671} // namespace android