summaryrefslogtreecommitdiffstats
path: root/gfx/layers/apz/src/DesktopFlingPhysics.h
blob: e93cc07a2312400ecc8935b1f83c67ac781b3b82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_layers_DesktopFlingPhysics_h_
#define mozilla_layers_DesktopFlingPhysics_h_

#include "AsyncPanZoomController.h"
#include "Units.h"
#include "mozilla/Assertions.h"
#include "mozilla/StaticPrefs_apz.h"

namespace mozilla {
namespace layers {

class DesktopFlingPhysics {
 public:
  void Init(const ParentLayerPoint& aStartingVelocity,
            float aPLPPI /* unused */) {
    mVelocity = aStartingVelocity;
  }
  void Sample(const TimeDuration& aDelta, ParentLayerPoint* aOutVelocity,
              ParentLayerPoint* aOutOffset) {
    float friction = StaticPrefs::apz_fling_friction();
    float threshold = StaticPrefs::apz_fling_stopped_threshold();

    mVelocity = ParentLayerPoint(
        ApplyFrictionOrCancel(mVelocity.x, aDelta, friction, threshold),
        ApplyFrictionOrCancel(mVelocity.y, aDelta, friction, threshold));

    *aOutVelocity = mVelocity;
    *aOutOffset = mVelocity * aDelta.ToMilliseconds();
  }

 private:
  /**
   * Applies friction to the given velocity and returns the result, or
   * returns zero if the velocity is too low.
   * |aVelocity| is the incoming velocity.
   * |aDelta| is the amount of time that has passed since the last time
   * friction was applied.
   * |aFriction| is the amount of friction to apply.
   * |aThreshold| is the velocity below which the fling is cancelled.
   */
  static float ApplyFrictionOrCancel(float aVelocity,
                                     const TimeDuration& aDelta,
                                     float aFriction, float aThreshold) {
    if (fabsf(aVelocity) <= aThreshold) {
      // If the velocity is very low, just set it to 0 and stop the fling,
      // otherwise we'll just asymptotically approach 0 and the user won't
      // actually see any changes.
      return 0.0f;
    }

    aVelocity *= pow(1.0f - aFriction, float(aDelta.ToMilliseconds()));
    return aVelocity;
  }

  ParentLayerPoint mVelocity;
};

}  // namespace layers
}  // namespace mozilla

#endif  // mozilla_layers_DesktopFlingPhysics_h_