velocity_tracker.dart 15.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5

6 7
import 'package:flutter/foundation.dart';

8
import 'events.dart';
9 10
import 'lsq_solver.dart';

11
export 'dart:ui' show Offset, PointerDeviceKind;
12

13
/// A velocity in two dimensions.
14
@immutable
15
class Velocity {
16 17 18
  /// Creates a velocity.
  ///
  /// The [pixelsPerSecond] argument must not be null.
19
  const Velocity({
20
    required this.pixelsPerSecond,
21
  });
22 23

  /// A velocity that isn't moving at all.
24
  static const Velocity zero = Velocity(pixelsPerSecond: Offset.zero);
25 26 27 28

  /// The number of pixels per second of velocity in the x and y directions.
  final Offset pixelsPerSecond;

29
  /// Return the negation of a velocity.
30
  Velocity operator -() => Velocity(pixelsPerSecond: -pixelsPerSecond);
31 32

  /// Return the difference of two velocities.
33
  Velocity operator -(Velocity other) {
34
    return Velocity(pixelsPerSecond: pixelsPerSecond - other.pixelsPerSecond);
35
  }
36 37

  /// Return the sum of two velocities.
38
  Velocity operator +(Velocity other) {
39
    return Velocity(pixelsPerSecond: pixelsPerSecond + other.pixelsPerSecond);
40 41
  }

42 43 44 45 46 47 48 49 50 51 52
  /// Return a velocity whose magnitude has been clamped to [minValue]
  /// and [maxValue].
  ///
  /// If the magnitude of this Velocity is less than minValue then return a new
  /// Velocity with the same direction and with magnitude [minValue]. Similarly,
  /// if the magnitude of this Velocity is greater than maxValue then return a
  /// new Velocity with the same direction and magnitude [maxValue].
  ///
  /// If the magnitude of this Velocity is within the specified bounds then
  /// just return this.
  Velocity clampMagnitude(double minValue, double maxValue) {
53 54
    assert(minValue >= 0.0);
    assert(maxValue >= 0.0 && maxValue >= minValue);
55
    final double valueSquared = pixelsPerSecond.distanceSquared;
56
    if (valueSquared > maxValue * maxValue) {
57
      return Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * maxValue);
58 59
    }
    if (valueSquared < minValue * minValue) {
60
      return Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * minValue);
61
    }
62 63 64
    return this;
  }

65
  @override
66
  bool operator ==(Object other) {
67 68
    return other is Velocity
        && other.pixelsPerSecond == pixelsPerSecond;
69 70
  }

71
  @override
72 73
  int get hashCode => pixelsPerSecond.hashCode;

74
  @override
75 76 77
  String toString() => 'Velocity(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)})';
}

78 79 80
/// A two dimensional velocity estimate.
///
/// VelocityEstimates are computed by [VelocityTracker.getVelocityEstimate]. An
81
/// estimate's [confidence] measures how well the velocity tracker's position
82 83 84 85 86 87
/// data fit a straight line, [duration] is the time that elapsed between the
/// first and last position sample used to compute the velocity, and [offset]
/// is similarly the difference between the first and last positions.
///
/// See also:
///
88 89
///  * [VelocityTracker], which computes [VelocityEstimate]s.
///  * [Velocity], which encapsulates (just) a velocity vector and provides some
90 91 92
///    useful velocity operations.
class VelocityEstimate {
  /// Creates a dimensional velocity estimate.
93 94
  ///
  /// [pixelsPerSecond], [confidence], [duration], and [offset] must not be null.
95
  const VelocityEstimate({
96 97 98 99
    required this.pixelsPerSecond,
    required this.confidence,
    required this.duration,
    required this.offset,
100
  });
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

  /// The number of pixels per second of velocity in the x and y directions.
  final Offset pixelsPerSecond;

  /// A value between 0.0 and 1.0 that indicates how well [VelocityTracker]
  /// was able to fit a straight line to its position data.
  ///
  /// The value of this property is 1.0 for a perfect fit, 0.0 for a poor fit.
  final double confidence;

  /// The time that elapsed between the first and last position sample used
  /// to compute [pixelsPerSecond].
  final Duration duration;

  /// The difference between the first and last position sample used
  /// to compute [pixelsPerSecond].
  final Offset offset;

  @override
120
  String toString() => 'VelocityEstimate(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)}; offset: $offset, duration: $duration, confidence: ${confidence.toStringAsFixed(1)})';
121 122 123
}

class _PointAtTime {
124
  const _PointAtTime(this.point, this.time);
125 126

  final Duration time;
127
  final Offset point;
128 129 130 131 132

  @override
  String toString() => '_PointAtTime($point at $time)';
}

133
/// Computes a pointer's velocity based on data from [PointerMoveEvent]s.
134
///
135
/// The input data is provided by calling [addPosition]. Adding data is cheap.
136
///
137 138 139
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. This will
/// compute the velocity based on the data added so far. Only call these when
/// you need to use the velocity, as they are comparatively expensive.
140
///
141 142
/// The quality of the velocity estimation will be better if more data points
/// have been received.
143
class VelocityTracker {
144 145 146

  /// Create a new velocity tracker for a pointer [kind].
  VelocityTracker.withKind(this.kind);
147

148 149 150 151
  static const int _assumePointerMoveStoppedMilliseconds = 40;
  static const int _historySize = 20;
  static const int _horizonMilliseconds = 100;
  static const int _minSampleSize = 3;
152

153 154 155
  /// The kind of pointer this tracker is for.
  final PointerDeviceKind kind;

156
  // Circular buffer; current sample at _index.
157
  final List<_PointAtTime?> _samples = List<_PointAtTime?>.filled(_historySize, null);
158
  int _index = 0;
159

Adam Barth's avatar
Adam Barth committed
160
  /// Adds a position as the given time to the tracker.
161
  void addPosition(Duration time, Offset position) {
162
    _index += 1;
163
    if (_index == _historySize) {
164
      _index = 0;
165
    }
166
    _samples[_index] = _PointAtTime(position, time);
167 168
  }

Adam Barth's avatar
Adam Barth committed
169 170
  /// Returns an estimate of the velocity of the object being tracked by the
  /// tracker given the current information available to the tracker.
171 172 173 174
  ///
  /// Information is added using [addPosition].
  ///
  /// Returns null if there is no data on which to base an estimate.
175
  VelocityEstimate? getVelocityEstimate() {
176 177 178 179 180 181 182
    final List<double> x = <double>[];
    final List<double> y = <double>[];
    final List<double> w = <double>[];
    final List<double> time = <double>[];
    int sampleCount = 0;
    int index = _index;

183
    final _PointAtTime? newestSample = _samples[index];
184
    if (newestSample == null) {
185
      return null;
186
    }
187 188 189 190 191 192 193

    _PointAtTime previousSample = newestSample;
    _PointAtTime oldestSample = newestSample;

    // Starting with the most recent PointAtTime sample, iterate backwards while
    // the samples represent continuous motion.
    do {
194
      final _PointAtTime? sample = _samples[index];
195
      if (sample == null) {
196
        break;
197
      }
198

199 200
      final double age = (newestSample.time - sample.time).inMicroseconds.toDouble() / 1000;
      final double delta = (sample.time - previousSample.time).inMicroseconds.abs().toDouble() / 1000;
201
      previousSample = sample;
202
      if (age > _horizonMilliseconds || delta > _assumePointerMoveStoppedMilliseconds) {
203
        break;
204
      }
205 206

      oldestSample = sample;
207 208 209
      final Offset position = sample.point;
      x.add(position.dx);
      y.add(position.dy);
210 211
      w.add(1.0);
      time.add(-age);
212
      index = (index == 0 ? _historySize : index) - 1;
213

214
      sampleCount += 1;
215
    } while (sampleCount < _historySize);
216

217
    if (sampleCount >= _minSampleSize) {
218
      final LeastSquaresSolver xSolver = LeastSquaresSolver(time, x, w);
219
      final PolynomialFit? xFit = xSolver.solve(2);
220
      if (xFit != null) {
221
        final LeastSquaresSolver ySolver = LeastSquaresSolver(time, y, w);
222
        final PolynomialFit? yFit = ySolver.solve(2);
223
        if (yFit != null) {
224 225
          return VelocityEstimate( // convert from pixels/ms to pixels/s
            pixelsPerSecond: Offset(xFit.coefficients[1] * 1000, yFit.coefficients[1] * 1000),
226 227 228 229 230 231 232 233 234 235
            confidence: xFit.confidence * yFit.confidence,
            duration: newestSample.time - oldestSample.time,
            offset: newestSample.point - oldestSample.point,
          );
        }
      }
    }

    // We're unable to make a velocity estimate but we did have at least one
    // valid pointer position.
236
    return VelocityEstimate(
237 238 239 240 241
      pixelsPerSecond: Offset.zero,
      confidence: 1.0,
      duration: newestSample.time - oldestSample.time,
      offset: newestSample.point - oldestSample.point,
    );
242 243
  }

244 245 246 247 248
  /// Computes the velocity of the pointer at the time of the last
  /// provided data point.
  ///
  /// This can be expensive. Only call this when you need the velocity.
  ///
249 250
  /// Returns [Velocity.zero] if there is no data from which to compute an
  /// estimate or if the estimated velocity is zero.
251
  Velocity getVelocity() {
252
    final VelocityEstimate? estimate = getVelocityEstimate();
253
    if (estimate == null || estimate.pixelsPerSecond == Offset.zero) {
254
      return Velocity.zero;
255
    }
256
    return Velocity(pixelsPerSecond: estimate.pixelsPerSecond);
257 258
  }
}
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

/// A [VelocityTracker] subclass that provides a close approximation of iOS
/// scroll view's velocity estimation strategy.
///
/// The estimated velocity reported by this class is a close approximation of
/// the velocity an iOS scroll view would report with the same
/// [PointerMoveEvent]s, when the touch that initiates a fling is released.
///
/// This class differs from the [VelocityTracker] class in that it uses weighted
/// average of the latest few velocity samples of the tracked pointer, instead
/// of doing a linear regression on a relatively large amount of data points, to
/// estimate the velocity of the tracked pointer. Adding data points and
/// estimating the velocity are both cheap.
///
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. The
274
/// estimated velocity is typically used as the initial flinging velocity of a
275 276 277 278 279 280 281
/// `Scrollable`, when its drag gesture ends.
///
/// See also:
///
/// * [scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619385-scrollviewwillenddragging),
///   the iOS method that reports the fling velocity when the touch is released.
class IOSScrollViewFlingVelocityTracker extends VelocityTracker {
282
  /// Create a new IOSScrollViewFlingVelocityTracker.
283
  IOSScrollViewFlingVelocityTracker(super.kind) : super.withKind();
284

285 286 287 288 289 290
  /// The velocity estimation uses at most 4 `_PointAtTime` samples. The extra
  /// samples are there to make the `VelocityEstimate.offset` sufficiently large
  /// to be recognized as a fling. See
  /// `VerticalDragGestureRecognizer.isFlingGesture`.
  static const int _sampleSize = 20;

291
  final List<_PointAtTime?> _touchSamples = List<_PointAtTime?>.filled(_sampleSize, null);
292 293 294 295 296

  @override
  void addPosition(Duration time, Offset position) {
    assert(() {
      final _PointAtTime? previousPoint = _touchSamples[_index];
297
      if (previousPoint == null || previousPoint.time <= time) {
298
        return true;
299
      }
300
      throw FlutterError(
301
        'The position being added ($position) has a smaller timestamp ($time) '
302
        'than its predecessor: $previousPoint.',
303 304 305 306 307 308 309 310
      );
    }());
    _index = (_index + 1) % _sampleSize;
    _touchSamples[_index] = _PointAtTime(position, time);
  }

  // Computes the velocity using 2 adjacent points in history. When index = 0,
  // it uses the latest point recorded and the point recorded immediately before
311
  // it. The smaller index is, the earlier in history the points used are.
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  Offset _previousVelocityAt(int index) {
    final int endIndex = (_index + index) % _sampleSize;
    final int startIndex = (_index + index - 1) % _sampleSize;
    final _PointAtTime? end = _touchSamples[endIndex];
    final _PointAtTime? start = _touchSamples[startIndex];

    if (end == null || start == null) {
      return Offset.zero;
    }

    final int dt = (end.time - start.time).inMicroseconds;
    assert(dt >= 0);

    return dt > 0
      // Convert dt to milliseconds to preserve floating point precision.
      ? (end.point - start.point) * 1000 / (dt.toDouble() / 1000)
      : Offset.zero;
  }

  @override
  VelocityEstimate getVelocityEstimate() {
333
    // The velocity estimated using this expression is an approximation of the
334 335 336 337 338 339 340 341 342 343 344 345 346 347
    // scroll velocity of an iOS scroll view at the moment the user touch was
    // released, not the final velocity of the iOS pan gesture recognizer
    // installed on the scroll view would report. Typically in an iOS scroll
    // view the velocity values are different between the two, because the
    // scroll view usually slows down when the touch is released.
    final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.6
                                   + _previousVelocityAt(-1) * 0.35
                                   + _previousVelocityAt(0) * 0.05;

    final _PointAtTime? newestSample = _touchSamples[_index];
    _PointAtTime? oldestNonNullSample;

    for (int i = 1; i <= _sampleSize; i += 1) {
      oldestNonNullSample = _touchSamples[(_index + i) % _sampleSize];
348
      if (oldestNonNullSample != null) {
349
        break;
350
      }
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    }

    if (oldestNonNullSample == null || newestSample == null) {
      assert(false, 'There must be at least 1 point in _touchSamples: $_touchSamples');
      return const VelocityEstimate(
        pixelsPerSecond: Offset.zero,
        confidence: 0.0,
        duration: Duration.zero,
        offset: Offset.zero,
      );
    } else {
      return VelocityEstimate(
        pixelsPerSecond: estimatedVelocity,
        confidence: 1.0,
        duration: newestSample.time - oldestNonNullSample.time,
        offset: newestSample.point - oldestNonNullSample.point,
      );
    }
  }
}
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

/// A [VelocityTracker] subclass that provides a close approximation of macOS
/// scroll view's velocity estimation strategy.
///
/// The estimated velocity reported by this class is a close approximation of
/// the velocity a macOS scroll view would report with the same
/// [PointerMoveEvent]s, when the touch that initiates a fling is released.
///
/// This class differs from the [VelocityTracker] class in that it uses weighted
/// average of the latest few velocity samples of the tracked pointer, instead
/// of doing a linear regression on a relatively large amount of data points, to
/// estimate the velocity of the tracked pointer. Adding data points and
/// estimating the velocity are both cheap.
///
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. The
/// estimated velocity is typically used as the initial flinging velocity of a
/// `Scrollable`, when its drag gesture ends.
class MacOSScrollViewFlingVelocityTracker extends IOSScrollViewFlingVelocityTracker {
  /// Create a new MacOSScrollViewFlingVelocityTracker.
  MacOSScrollViewFlingVelocityTracker(super.kind);

  @override
  VelocityEstimate getVelocityEstimate() {
    // The velocity estimated using this expression is an approximation of the
    // scroll velocity of a macOS scroll view at the moment the user touch was
    // released.
    final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.15
                                   + _previousVelocityAt(-1) * 0.65
                                   + _previousVelocityAt(0) * 0.2;

    final _PointAtTime? newestSample = _touchSamples[_index];
    _PointAtTime? oldestNonNullSample;

    for (int i = 1; i <= IOSScrollViewFlingVelocityTracker._sampleSize; i += 1) {
      oldestNonNullSample = _touchSamples[(_index + i) % IOSScrollViewFlingVelocityTracker._sampleSize];
      if (oldestNonNullSample != null) {
        break;
      }
    }

    if (oldestNonNullSample == null || newestSample == null) {
      assert(false, 'There must be at least 1 point in _touchSamples: $_touchSamples');
      return const VelocityEstimate(
        pixelsPerSecond: Offset.zero,
        confidence: 0.0,
        duration: Duration.zero,
        offset: Offset.zero,
      );
    } else {
      return VelocityEstimate(
        pixelsPerSecond: estimatedVelocity,
        confidence: 1.0,
        duration: newestSample.time - oldestNonNullSample.time,
        offset: newestSample.point - oldestNonNullSample.point,
      );
    }
  }
}