1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "core/gestures/velocity_tracker.h"
17
18 #include <chrono>
19
20 namespace OHOS::Ace {
21
UpdateTouchPoint(const TouchEvent & event,bool end)22 void VelocityTracker::UpdateTouchPoint(const TouchEvent& event, bool end)
23 {
24 isVelocityDone_ = false;
25 currentTrackPoint_ = event;
26 if (isFirstPoint_) {
27 firstTrackPoint_ = event;
28 isFirstPoint_ = false;
29 } else {
30 delta_ = event.GetOffset() - lastPosition_;
31 lastPosition_ = event.GetOffset();
32 }
33 std::chrono::duration<double> diffTime = event.time - lastTimePoint_;
34 lastTimePoint_ = event.time;
35 lastPosition_ = event.GetOffset();
36 // judge duration is 500ms.
37 static const double range = 0.5;
38 if (delta_.IsZero() && end && (diffTime.count() < range)) {
39 return;
40 }
41 // nanoseconds duration to seconds.
42 std::chrono::duration<double> duration = event.time - firstTrackPoint_.time;
43 auto seconds = duration.count();
44 xAxis_.UpdatePoint(seconds, event.x);
45 yAxis_.UpdatePoint(seconds, event.y);
46 }
47
UpdateVelocity()48 void VelocityTracker::UpdateVelocity()
49 {
50 if (isVelocityDone_) {
51 return;
52 }
53 // the least square method three params curve is 0 * x^3 + a2 * x^2 + a1 * x + a0
54 // the velocity is 2 * a2 * x + a1;
55 static const int32_t linearParam = 2;
56 std::vector<double> xAxis { 3, 0 };
57 auto xValue = xAxis_.GetXVals().back();
58 double xVelocity = 0.0;
59 if (xAxis_.GetLeastSquareParams(xAxis)) {
60 xVelocity = linearParam * xAxis[0] * xValue + xAxis[1];
61 }
62 std::vector<double> yAxis { 3, 0 };
63 auto yValue = yAxis_.GetXVals().back();
64 double yVelocity = 0.0;
65 if (yAxis_.GetLeastSquareParams(yAxis)) {
66 yVelocity = linearParam * yAxis[0] * yValue + yAxis[1];
67 }
68
69 velocity_.SetOffsetPerSecond({ xVelocity, yVelocity });
70 isVelocityDone_ = true;
71 }
72
73 } // namespace OHOS::Ace
74