1 /*
2  * Copyright (C) 2017 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 package com.android.launcher3.anim;
18 
19 import static com.android.launcher3.util.DefaultDisplay.getSingleFrameMs;
20 
21 import android.content.Context;
22 import android.graphics.Path;
23 import android.view.animation.AccelerateDecelerateInterpolator;
24 import android.view.animation.AccelerateInterpolator;
25 import android.view.animation.DecelerateInterpolator;
26 import android.view.animation.Interpolator;
27 import android.view.animation.LinearInterpolator;
28 import android.view.animation.OvershootInterpolator;
29 import android.view.animation.PathInterpolator;
30 
31 import com.android.launcher3.Utilities;
32 
33 
34 /**
35  * Common interpolators used in Launcher
36  */
37 public class Interpolators {
38 
39     public static final Interpolator LINEAR = new LinearInterpolator();
40 
41     public static final Interpolator ACCEL = new AccelerateInterpolator();
42     public static final Interpolator ACCEL_0_75 = new AccelerateInterpolator(0.75f);
43     public static final Interpolator ACCEL_1_5 = new AccelerateInterpolator(1.5f);
44     public static final Interpolator ACCEL_2 = new AccelerateInterpolator(2);
45 
46     public static final Interpolator DEACCEL = new DecelerateInterpolator();
47     public static final Interpolator DEACCEL_1_5 = new DecelerateInterpolator(1.5f);
48     public static final Interpolator DEACCEL_1_7 = new DecelerateInterpolator(1.7f);
49     public static final Interpolator DEACCEL_2 = new DecelerateInterpolator(2);
50     public static final Interpolator DEACCEL_2_5 = new DecelerateInterpolator(2.5f);
51     public static final Interpolator DEACCEL_3 = new DecelerateInterpolator(3f);
52     public static final Interpolator DEACCEL_5 = new DecelerateInterpolator(5f);
53 
54     public static final Interpolator ACCEL_DEACCEL = new AccelerateDecelerateInterpolator();
55 
56     public static final Interpolator FAST_OUT_SLOW_IN = new PathInterpolator(0.4f, 0f, 0.2f, 1f);
57 
58     public static final Interpolator AGGRESSIVE_EASE = new PathInterpolator(0.2f, 0f, 0f, 1f);
59     public static final Interpolator AGGRESSIVE_EASE_IN_OUT = new PathInterpolator(0.6f,0, 0.4f, 1);
60 
61     public static final Interpolator EXAGGERATED_EASE;
62 
63     public static final Interpolator INSTANT = t -> 1;
64     /**
65      * All values of t map to 0 until t == 1. This is primarily useful for setting view visibility,
66      * which should only happen at the very end of the animation (when it's already hidden).
67      */
68     public static final Interpolator FINAL_FRAME = t -> t < 1 ? 0 : 1;
69 
70     private static final int MIN_SETTLE_DURATION = 200;
71     private static final float OVERSHOOT_FACTOR = 0.9f;
72 
73     static {
74         Path exaggeratedEase = new Path();
75         exaggeratedEase.moveTo(0, 0);
76         exaggeratedEase.cubicTo(0.05f, 0f, 0.133333f, 0.08f, 0.166666f, 0.4f);
77         exaggeratedEase.cubicTo(0.225f, 0.94f, 0.5f, 1f, 1f, 1f);
78         EXAGGERATED_EASE = new PathInterpolator(exaggeratedEase);
79     }
80 
81     public static final Interpolator OVERSHOOT_1_2 = new OvershootInterpolator(1.2f);
82     public static final Interpolator OVERSHOOT_1_7 = new OvershootInterpolator(1.7f);
83 
84     public static final Interpolator TOUCH_RESPONSE_INTERPOLATOR =
85             new PathInterpolator(0.3f, 0f, 0.1f, 1f);
86 
87     /**
88      * Inversion of ZOOM_OUT, compounded with an ease-out.
89      */
90     public static final Interpolator ZOOM_IN = new Interpolator() {
91         @Override
92         public float getInterpolation(float v) {
93             return DEACCEL_3.getInterpolation(1 - ZOOM_OUT.getInterpolation(1 - v));
94         }
95     };
96 
97     public static final Interpolator ZOOM_OUT = new Interpolator() {
98 
99         private static final float FOCAL_LENGTH = 0.35f;
100 
101         @Override
102         public float getInterpolation(float v) {
103             return zInterpolate(v);
104         }
105 
106         /**
107          * This interpolator emulates the rate at which the perceived scale of an object changes
108          * as its distance from a camera increases. When this interpolator is applied to a scale
109          * animation on a view, it evokes the sense that the object is shrinking due to moving away
110          * from the camera.
111          */
112         private float zInterpolate(float input) {
113             return (1.0f - FOCAL_LENGTH / (FOCAL_LENGTH + input)) /
114                     (1.0f - FOCAL_LENGTH / (FOCAL_LENGTH + 1.0f));
115         }
116     };
117 
118     public static final Interpolator SCROLL = new Interpolator() {
119         @Override
120         public float getInterpolation(float t) {
121             t -= 1.0f;
122             return t*t*t*t*t + 1;
123         }
124     };
125 
126     public static final Interpolator SCROLL_CUBIC = new Interpolator() {
127         @Override
128         public float getInterpolation(float t) {
129             t -= 1.0f;
130             return t*t*t + 1;
131         }
132     };
133 
134     private static final float FAST_FLING_PX_MS = 10;
135 
136     public static Interpolator scrollInterpolatorForVelocity(float velocity) {
137         return Math.abs(velocity) > FAST_FLING_PX_MS ? SCROLL : SCROLL_CUBIC;
138     }
139 
140     /**
141      * Create an OvershootInterpolator with tension directly related to the velocity (in px/ms).
142      * @param velocity The start velocity of the animation we want to overshoot.
143      */
overshootInterpolatorForVelocity(float velocity)144     public static Interpolator overshootInterpolatorForVelocity(float velocity) {
145         return new OvershootInterpolator(Math.min(Math.abs(velocity), 3f));
146     }
147 
148     /**
149      * Runs the given interpolator such that the entire progress is set between the given bounds.
150      * That is, we set the interpolation to 0 until lowerBound and reach 1 by upperBound.
151      */
clampToProgress(Interpolator interpolator, float lowerBound, float upperBound)152     public static Interpolator clampToProgress(Interpolator interpolator, float lowerBound,
153             float upperBound) {
154         if (upperBound <= lowerBound) {
155             throw new IllegalArgumentException(String.format(
156                     "lowerBound (%f) must be less than upperBound (%f)", lowerBound, upperBound));
157         }
158         return t -> {
159             if (t < lowerBound) {
160                 return 0;
161             }
162             if (t > upperBound) {
163                 return 1;
164             }
165             return interpolator.getInterpolation((t - lowerBound) / (upperBound - lowerBound));
166         };
167     }
168 
169     /**
170      * Runs the given interpolator such that the interpolated value is mapped to the given range.
171      * This is useful, for example, if we only use this interpolator for part of the animation,
172      * such as to take over a user-controlled animation when they let go.
173      */
174     public static Interpolator mapToProgress(Interpolator interpolator, float lowerBound,
175             float upperBound) {
176         return t -> Utilities.mapRange(interpolator.getInterpolation(t), lowerBound, upperBound);
177     }
178 
179     /**
180      * Computes parameters necessary for an overshoot effect.
181      */
182     public static class OvershootParams {
183         public Interpolator interpolator;
184         public float start;
185         public float end;
186         public long duration;
187 
188         /**
189          * Given the input params, sets OvershootParams variables to be used by the caller.
190          * @param startProgress The progress from 0 to 1 that the overshoot starts from.
191          * @param overshootPastProgress The progress from 0 to 1 where we overshoot past (should
192          *        either be equal to startProgress or endProgress, depending on if we want to
193          *        overshoot immediately or only once we reach the end).
194          * @param endProgress The final progress from 0 to 1 that we will settle to.
195          * @param velocityPxPerMs The initial velocity that causes this overshoot.
196          * @param totalDistancePx The distance against which progress is calculated.
197          */
198         public OvershootParams(float startProgress, float overshootPastProgress,
199                 float endProgress, float velocityPxPerMs, int totalDistancePx, Context context) {
200             velocityPxPerMs = Math.abs(velocityPxPerMs);
201             start = startProgress;
202             int startPx = (int) (start * totalDistancePx);
203             // Overshoot by about half a frame.
204             float overshootBy = OVERSHOOT_FACTOR * velocityPxPerMs *
205                     getSingleFrameMs(context) / totalDistancePx / 2;
206             overshootBy = Utilities.boundToRange(overshootBy, 0.02f, 0.15f);
207             end = overshootPastProgress + overshootBy;
208             int endPx = (int) (end  * totalDistancePx);
209             int overshootDistance = endPx - startPx;
210             // Calculate deceleration necessary to reach overshoot distance.
211             // Formula: velocityFinal^2 = velocityInitial^2 + 2 * acceleration * distance
212             //          0 = v^2 + 2ad (velocityFinal == 0)
213             //          a = v^2 / -2d
214             float decelerationPxPerMs = velocityPxPerMs * velocityPxPerMs / (2 * overshootDistance);
215             // Calculate time necessary to reach peak of overshoot.
216             // Formula: acceleration = velocity / time
217             //          time = velocity / acceleration
218             duration = (long) (velocityPxPerMs / decelerationPxPerMs);
219 
220             // Now that we're at the top of the overshoot, need to settle back to endProgress.
221             float settleDistance = end - endProgress;
222             int settleDistancePx = (int) (settleDistance * totalDistancePx);
223             // Calculate time necessary for the settle.
224             // Formula: distance = velocityInitial * time + 1/2 * acceleration * time^2
225             //          d = 1/2at^2 (velocityInitial = 0, since we just stopped at the top)
226             //          t = sqrt(2d/a)
227             // Above formula assumes constant acceleration. Since we use ACCEL_DEACCEL, we actually
228             // have acceleration to halfway then deceleration the rest. So the formula becomes:
229             //          t = sqrt(d/a) * 2 (half the distance for accel, half for deaccel)
230             long settleDuration = (long) Math.sqrt(settleDistancePx / decelerationPxPerMs) * 4;
231 
232             settleDuration = Math.max(MIN_SETTLE_DURATION, settleDuration);
233             // How much of the animation to devote to playing the overshoot (the rest is for settle).
234             float overshootFraction = (float) duration / (duration + settleDuration);
235             duration += settleDuration;
236             // Finally, create the interpolator, composed of two interpolators: an overshoot, which
237             // reaches end > 1, and then a settle to endProgress.
238             Interpolator overshoot = Interpolators.clampToProgress(DEACCEL, 0, overshootFraction);
239             // The settle starts at 1, where 1 is the top of the overshoot, and maps to a fraction
240             // such that final progress is endProgress. For example, if we overshot to 1.1 but want
241             // to end at 1, we need to map to 1/1.1.
242             Interpolator settle = Interpolators.clampToProgress(Interpolators.mapToProgress(
243                     ACCEL_DEACCEL, 1, (endProgress - start) / (end - start)), overshootFraction, 1);
244             interpolator = t -> t <= overshootFraction
245                     ? overshoot.getInterpolation(t)
246                     : settle.getInterpolation(t);
247         }
248     }
249 }
250