blob: 408b2401349603a53a87d4ef08360532e63be9e3 [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 }
164 return NULL;
165}
166
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700167void VelocityTracker::clear() {
Jeff Brown85bd0d62012-05-13 15:30:42 -0700168 mCurrentPointerIdBits.clear();
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700169 mActivePointerId = -1;
Jeff Brown85bd0d62012-05-13 15:30:42 -0700170
171 mStrategy->clear();
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700172}
173
174void VelocityTracker::clearPointers(BitSet32 idBits) {
Jeff Brown85bd0d62012-05-13 15:30:42 -0700175 BitSet32 remainingIdBits(mCurrentPointerIdBits.value & ~idBits.value);
176 mCurrentPointerIdBits = remainingIdBits;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700177
178 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
179 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
180 }
Jeff Brown85bd0d62012-05-13 15:30:42 -0700181
182 mStrategy->clearPointers(idBits);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700183}
184
185void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700186 while (idBits.count() > MAX_POINTERS) {
187 idBits.clearLastMarkedBit();
188 }
189
Jeff Brown90729402012-05-14 18:46:18 -0700190 if ((mCurrentPointerIdBits.value & idBits.value)
191 && eventTime >= mLastEventTime + ASSUME_POINTER_STOPPED_TIME) {
192#if DEBUG_VELOCITY
193 ALOGD("VelocityTracker: stopped for %0.3f ms, clearing state.",
194 (eventTime - mLastEventTime) * 0.000001f);
195#endif
196 // We have not received any movements for too long. Assume that all pointers
197 // have stopped.
198 mStrategy->clear();
199 }
200 mLastEventTime = eventTime;
201
Jeff Brown85bd0d62012-05-13 15:30:42 -0700202 mCurrentPointerIdBits = idBits;
203 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
204 mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit();
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700205 }
206
Jeff Brown85bd0d62012-05-13 15:30:42 -0700207 mStrategy->addMovement(eventTime, idBits, positions);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700208
209#if DEBUG_VELOCITY
210 ALOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
211 eventTime, idBits.value, mActivePointerId);
212 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
213 uint32_t id = iterBits.firstMarkedBit();
214 uint32_t index = idBits.getIndexOfBit(id);
215 iterBits.clearBit(id);
216 Estimator estimator;
Jeff Brown85bd0d62012-05-13 15:30:42 -0700217 getEstimator(id, &estimator);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700218 ALOGD(" %d: position (%0.3f, %0.3f), "
219 "estimator (degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f)",
220 id, positions[index].x, positions[index].y,
221 int(estimator.degree),
Jeff Browndcab1902012-05-14 18:44:17 -0700222 vectorToString(estimator.xCoeff, estimator.degree + 1).string(),
223 vectorToString(estimator.yCoeff, estimator.degree + 1).string(),
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700224 estimator.confidence);
225 }
226#endif
227}
228
229void VelocityTracker::addMovement(const MotionEvent* event) {
230 int32_t actionMasked = event->getActionMasked();
231
232 switch (actionMasked) {
233 case AMOTION_EVENT_ACTION_DOWN:
234 case AMOTION_EVENT_ACTION_HOVER_ENTER:
235 // Clear all pointers on down before adding the new movement.
236 clear();
237 break;
238 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
239 // Start a new movement trace for a pointer that just went down.
240 // We do this on down instead of on up because the client may want to query the
241 // final velocity for a pointer that just went up.
242 BitSet32 downIdBits;
243 downIdBits.markBit(event->getPointerId(event->getActionIndex()));
244 clearPointers(downIdBits);
245 break;
246 }
247 case AMOTION_EVENT_ACTION_MOVE:
248 case AMOTION_EVENT_ACTION_HOVER_MOVE:
249 break;
250 default:
251 // Ignore all other actions because they do not convey any new information about
252 // pointer movement. We also want to preserve the last known velocity of the pointers.
253 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
254 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
255 // pointers that remained down but we will also receive an ACTION_MOVE with this
256 // information if any of them actually moved. Since we don't know how many pointers
257 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
258 // before adding the movement.
259 return;
260 }
261
262 size_t pointerCount = event->getPointerCount();
263 if (pointerCount > MAX_POINTERS) {
264 pointerCount = MAX_POINTERS;
265 }
266
267 BitSet32 idBits;
268 for (size_t i = 0; i < pointerCount; i++) {
269 idBits.markBit(event->getPointerId(i));
270 }
271
Jeff Browndcab1902012-05-14 18:44:17 -0700272 uint32_t pointerIndex[MAX_POINTERS];
273 for (size_t i = 0; i < pointerCount; i++) {
274 pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i));
275 }
276
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700277 nsecs_t eventTime;
278 Position positions[pointerCount];
279
280 size_t historySize = event->getHistorySize();
281 for (size_t h = 0; h < historySize; h++) {
282 eventTime = event->getHistoricalEventTime(h);
283 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browndcab1902012-05-14 18:44:17 -0700284 uint32_t index = pointerIndex[i];
285 positions[index].x = event->getHistoricalX(i, h);
286 positions[index].y = event->getHistoricalY(i, h);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700287 }
288 addMovement(eventTime, idBits, positions);
289 }
290
291 eventTime = event->getEventTime();
292 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browndcab1902012-05-14 18:44:17 -0700293 uint32_t index = pointerIndex[i];
294 positions[index].x = event->getX(i);
295 positions[index].y = event->getY(i);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700296 }
297 addMovement(eventTime, idBits, positions);
298}
299
Jeff Brown85bd0d62012-05-13 15:30:42 -0700300bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
301 Estimator estimator;
302 if (getEstimator(id, &estimator) && estimator.degree >= 1) {
303 *outVx = estimator.xCoeff[1];
304 *outVy = estimator.yCoeff[1];
305 return true;
306 }
307 *outVx = 0;
308 *outVy = 0;
309 return false;
310}
311
312bool VelocityTracker::getEstimator(uint32_t id, Estimator* outEstimator) const {
313 return mStrategy->getEstimator(id, outEstimator);
314}
315
316
317// --- LeastSquaresVelocityTrackerStrategy ---
318
Jeff Brown85bd0d62012-05-13 15:30:42 -0700319const nsecs_t LeastSquaresVelocityTrackerStrategy::HORIZON;
320const uint32_t LeastSquaresVelocityTrackerStrategy::HISTORY_SIZE;
321
Jeff Brown9eb7d862012-06-01 12:39:25 -0700322LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(uint32_t degree) :
323 mDegree(degree) {
Jeff Brown85bd0d62012-05-13 15:30:42 -0700324 clear();
325}
326
327LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {
328}
329
330void LeastSquaresVelocityTrackerStrategy::clear() {
331 mIndex = 0;
332 mMovements[0].idBits.clear();
333}
334
335void LeastSquaresVelocityTrackerStrategy::clearPointers(BitSet32 idBits) {
336 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
337 mMovements[mIndex].idBits = remainingIdBits;
338}
339
340void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
341 const VelocityTracker::Position* positions) {
342 if (++mIndex == HISTORY_SIZE) {
343 mIndex = 0;
344 }
345
346 Movement& movement = mMovements[mIndex];
347 movement.eventTime = eventTime;
348 movement.idBits = idBits;
349 uint32_t count = idBits.count();
350 for (uint32_t i = 0; i < count; i++) {
351 movement.positions[i] = positions[i];
352 }
353}
354
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700355/**
356 * Solves a linear least squares problem to obtain a N degree polynomial that fits
357 * the specified input data as nearly as possible.
358 *
359 * Returns true if a solution is found, false otherwise.
360 *
361 * The input consists of two vectors of data points X and Y with indices 0..m-1.
Jeff Brown9eb7d862012-06-01 12:39:25 -0700362 * The output is a vector B with indices 0..n that describes a polynomial
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700363 * 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))
364 * for all i between 0 and m-1 is minimized.
365 *
366 * That is to say, the function that generated the input data can be approximated
367 * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
368 *
369 * The coefficient of determination (R^2) is also returned to describe the goodness
370 * of fit of the model for the given data. It is a value between 0 and 1, where 1
371 * indicates perfect correspondence.
372 *
373 * This function first expands the X vector to a m by n matrix A such that
374 * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n.
375 *
376 * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
377 * and an m by n upper triangular matrix R. Because R is upper triangular (lower
378 * part is all zeroes), we can simplify the decomposition into an m by n matrix
379 * Q1 and a n by n matrix R1 such that A = Q1 R1.
380 *
381 * Finally we solve the system of linear equations given by R1 B = (Qtranspose Y)
382 * to find B.
383 *
384 * For efficiency, we lay out A and Q column-wise in memory because we frequently
385 * operate on the column vectors. Conversely, we lay out R row-wise.
386 *
387 * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
388 * http://en.wikipedia.org/wiki/Gram-Schmidt
389 */
390static bool solveLeastSquares(const float* x, const float* y, uint32_t m, uint32_t n,
391 float* outB, float* outDet) {
Jeff Brown9eb7d862012-06-01 12:39:25 -0700392#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700393 ALOGD("solveLeastSquares: m=%d, n=%d, x=%s, y=%s", int(m), int(n),
394 vectorToString(x, m).string(), vectorToString(y, m).string());
395#endif
396
397 // Expand the X vector to a matrix A.
398 float a[n][m]; // column-major order
399 for (uint32_t h = 0; h < m; h++) {
400 a[0][h] = 1;
401 for (uint32_t i = 1; i < n; i++) {
402 a[i][h] = a[i - 1][h] * x[h];
403 }
404 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700405#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700406 ALOGD(" - a=%s", matrixToString(&a[0][0], m, n, false /*rowMajor*/).string());
407#endif
408
409 // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
410 float q[n][m]; // orthonormal basis, column-major order
411 float r[n][n]; // upper triangular matrix, row-major order
412 for (uint32_t j = 0; j < n; j++) {
413 for (uint32_t h = 0; h < m; h++) {
414 q[j][h] = a[j][h];
415 }
416 for (uint32_t i = 0; i < j; i++) {
417 float dot = vectorDot(&q[j][0], &q[i][0], m);
418 for (uint32_t h = 0; h < m; h++) {
419 q[j][h] -= dot * q[i][h];
420 }
421 }
422
423 float norm = vectorNorm(&q[j][0], m);
424 if (norm < 0.000001f) {
425 // vectors are linearly dependent or zero so no solution
Jeff Brown9eb7d862012-06-01 12:39:25 -0700426#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700427 ALOGD(" - no solution, norm=%f", norm);
428#endif
429 return false;
430 }
431
432 float invNorm = 1.0f / norm;
433 for (uint32_t h = 0; h < m; h++) {
434 q[j][h] *= invNorm;
435 }
436 for (uint32_t i = 0; i < n; i++) {
437 r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
438 }
439 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700440#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700441 ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).string());
442 ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).string());
443
444 // calculate QR, if we factored A correctly then QR should equal A
445 float qr[n][m];
446 for (uint32_t h = 0; h < m; h++) {
447 for (uint32_t i = 0; i < n; i++) {
448 qr[i][h] = 0;
449 for (uint32_t j = 0; j < n; j++) {
450 qr[i][h] += q[j][h] * r[j][i];
451 }
452 }
453 }
454 ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).string());
455#endif
456
457 // Solve R B = Qt Y to find B. This is easy because R is upper triangular.
458 // We just work from bottom-right to top-left calculating B's coefficients.
459 for (uint32_t i = n; i-- != 0; ) {
460 outB[i] = vectorDot(&q[i][0], y, m);
461 for (uint32_t j = n - 1; j > i; j--) {
462 outB[i] -= r[i][j] * outB[j];
463 }
464 outB[i] /= r[i][i];
465 }
Jeff Brown9eb7d862012-06-01 12:39:25 -0700466#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700467 ALOGD(" - b=%s", vectorToString(outB, n).string());
468#endif
469
470 // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
471 // SSerr is the residual sum of squares (squared variance of the error),
472 // and SStot is the total sum of squares (squared variance of the data).
473 float ymean = 0;
474 for (uint32_t h = 0; h < m; h++) {
475 ymean += y[h];
476 }
477 ymean /= m;
478
479 float sserr = 0;
480 float sstot = 0;
481 for (uint32_t h = 0; h < m; h++) {
482 float err = y[h] - outB[0];
483 float term = 1;
484 for (uint32_t i = 1; i < n; i++) {
485 term *= x[h];
486 err -= term * outB[i];
487 }
488 sserr += err * err;
489 float var = y[h] - ymean;
490 sstot += var * var;
491 }
492 *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1;
Jeff Brown9eb7d862012-06-01 12:39:25 -0700493#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700494 ALOGD(" - sserr=%f", sserr);
495 ALOGD(" - sstot=%f", sstot);
496 ALOGD(" - det=%f", *outDet);
497#endif
498 return true;
499}
500
Jeff Brown85bd0d62012-05-13 15:30:42 -0700501bool LeastSquaresVelocityTrackerStrategy::getEstimator(uint32_t id,
502 VelocityTracker::Estimator* outEstimator) const {
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700503 outEstimator->clear();
504
505 // Iterate over movement samples in reverse time order and collect samples.
506 float x[HISTORY_SIZE];
507 float y[HISTORY_SIZE];
508 float time[HISTORY_SIZE];
509 uint32_t m = 0;
510 uint32_t index = mIndex;
511 const Movement& newestMovement = mMovements[mIndex];
512 do {
513 const Movement& movement = mMovements[index];
514 if (!movement.idBits.hasBit(id)) {
515 break;
516 }
517
518 nsecs_t age = newestMovement.eventTime - movement.eventTime;
Jeff Brown85bd0d62012-05-13 15:30:42 -0700519 if (age > HORIZON) {
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700520 break;
521 }
522
Jeff Brown85bd0d62012-05-13 15:30:42 -0700523 const VelocityTracker::Position& position = movement.getPosition(id);
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700524 x[m] = position.x;
525 y[m] = position.y;
526 time[m] = -age * 0.000000001f;
527 index = (index == 0 ? HISTORY_SIZE : index) - 1;
528 } while (++m < HISTORY_SIZE);
529
530 if (m == 0) {
531 return false; // no data
532 }
533
534 // Calculate a least squares polynomial fit.
Jeff Brown9eb7d862012-06-01 12:39:25 -0700535 uint32_t degree = mDegree;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700536 if (degree > m - 1) {
537 degree = m - 1;
538 }
539 if (degree >= 1) {
540 float xdet, ydet;
541 uint32_t n = degree + 1;
542 if (solveLeastSquares(time, x, m, n, outEstimator->xCoeff, &xdet)
543 && solveLeastSquares(time, y, m, n, outEstimator->yCoeff, &ydet)) {
Jeff Brown90729402012-05-14 18:46:18 -0700544 outEstimator->time = newestMovement.eventTime;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700545 outEstimator->degree = degree;
546 outEstimator->confidence = xdet * ydet;
Jeff Brown9eb7d862012-06-01 12:39:25 -0700547#if DEBUG_STRATEGY
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700548 ALOGD("estimate: degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f",
549 int(outEstimator->degree),
550 vectorToString(outEstimator->xCoeff, n).string(),
551 vectorToString(outEstimator->yCoeff, n).string(),
552 outEstimator->confidence);
553#endif
554 return true;
555 }
556 }
557
558 // No velocity data available for this pointer, but we do have its current position.
559 outEstimator->xCoeff[0] = x[0];
560 outEstimator->yCoeff[0] = y[0];
Jeff Brown90729402012-05-14 18:46:18 -0700561 outEstimator->time = newestMovement.eventTime;
Jeff Brown8a90e6e2012-05-11 12:24:35 -0700562 outEstimator->degree = 0;
563 outEstimator->confidence = 1;
564 return true;
565}
566
567} // namespace android