blob: f79219f1518085deafe902cfef9dcc64d7b21247 [file] [log] [blame]
Yeabkal Wubshit6b662762023-05-22 23:07:31 -07001/*
2 * Copyright 2023 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// clang-format off
18#include "../Macros.h"
19// clang-format on
20
21#include "SlopController.h"
22
23namespace {
24int signOf(float value) {
25 if (value == 0) return 0;
26 if (value > 0) return 1;
27 return -1;
28}
29} // namespace
30
31namespace android {
32
33SlopController::SlopController(float slopThreshold, nsecs_t slopDurationNanos)
34 : mSlopThreshold(slopThreshold), mSlopDurationNanos(slopDurationNanos) {}
35
Yeabkal Wubshit6b662762023-05-22 23:07:31 -070036float SlopController::consumeEvent(nsecs_t eventTimeNanos, float value) {
37 if (mSlopDurationNanos == 0) {
38 return value;
39 }
40
41 if (shouldResetSlopTracking(eventTimeNanos, value)) {
42 mCumulativeValue = 0;
43 mHasSlopBeenMet = false;
44 }
45
46 mLastEventTimeNanos = eventTimeNanos;
47
48 if (mHasSlopBeenMet) {
49 // Since slop has already been met, we know that all of the current value would pass the
50 // slop threshold. So return that, without any further processing.
51 return value;
52 }
53
54 mCumulativeValue += value;
55
56 if (abs(mCumulativeValue) >= mSlopThreshold) {
57 mHasSlopBeenMet = true;
58 // Return the amount of value that exceeds the slop.
59 return signOf(value) * (abs(mCumulativeValue) - mSlopThreshold);
60 }
61
62 return 0;
63}
64
Yeabkal Wubshitf1ed7052023-06-16 10:01:53 -070065bool SlopController::shouldResetSlopTracking(nsecs_t eventTimeNanos, float value) const {
Yeabkal Wubshit6b662762023-05-22 23:07:31 -070066 const nsecs_t ageNanos = eventTimeNanos - mLastEventTimeNanos;
67 if (ageNanos >= mSlopDurationNanos) {
68 return true;
69 }
70 if (value == 0) {
71 return false;
72 }
73 if (signOf(mCumulativeValue) != signOf(value)) {
74 return true;
75 }
76 return false;
77}
78
79} // namespace android