1 /*
2 * Copyright (c) 2021 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/animation/cubic_curve.h"
17
18 namespace OHOS::Ace {
19 namespace {
20
21 constexpr float FRACTION_PARAMETER_MAX = 1.0f;
22 constexpr float FRACTION_PARAMETER_MIN = 0.0f;
23
24 } // namespace
CubicCurve(float x0,float y0,float x1,float y1)25 CubicCurve::CubicCurve(float x0, float y0, float x1, float y1)
26 : x0_(x0), y0_(y0), x1_(x1), y1_(y1)
27 {}
28
MoveInternal(float time)29 float CubicCurve::MoveInternal(float time)
30 {
31 if (time < FRACTION_PARAMETER_MIN || time > FRACTION_PARAMETER_MAX) {
32 LOGE("CubicCurve MoveInternal: time is less than 0 or larger than 1, return 1");
33 return FRACTION_PARAMETER_MAX;
34 }
35 // let P0 = (0,0), P3 = (1,1)
36 float start = 0.0f;
37 float end = 1.0f;
38 while (true) {
39 float midpoint = (start + end) / 2;
40 float estimate = CalculateCubic(x0_, x1_, midpoint);
41
42 if (NearEqual(time, estimate, cubicErrorBound_)) {
43 return CalculateCubic(y0_, y1_, midpoint);
44 }
45
46 if (estimate < time) {
47 start = midpoint;
48 } else {
49 end = midpoint;
50 }
51 }
52 }
53
ToString()54 const std::string CubicCurve::ToString()
55 {
56 std::string curveString("cubic-bezier");
57 std::string comma(",");
58 curveString.append(std::string("(") + std::to_string(x0_) + comma + std::to_string(y0_)
59 + comma + std::to_string(x1_) + comma + std::to_string(y1_) + std::string(")"));
60 return curveString;
61 }
62
CalculateCubic(float a,float b,float m)63 float CubicCurve::CalculateCubic(float a, float b, float m)
64 {
65 return 3.0f * a * (1.0f - m) * (1.0f - m) * m + 3.0f * b * (1.0f - m) * m * m + m * m * m;
66 }
67
68 } // namespace OHOS::Ace
69