FallbackLUTInterpolator.java revision 315c329544d7c593d1072b071cbb92d9afe74021
1/*
2 * Copyright (C) 2014 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
17package com.android.internal.view.animation;
18
19import android.animation.TimeInterpolator;
20import android.util.TimeUtils;
21import android.view.Choreographer;
22
23/**
24 * Interpolator that builds a lookup table to use. This is a fallback for
25 * building a native interpolator from a TimeInterpolator that is not marked
26 * with {@link HasNativeInterpolator}
27 */
28@HasNativeInterpolator
29public class FallbackLUTInterpolator implements NativeInterpolatorFactory {
30
31    private final float mLut[];
32
33    /**
34     * Used to cache the float[] LUT for use across multiple native
35     * interpolator creation
36     */
37    public FallbackLUTInterpolator(TimeInterpolator interpolator, int duration) {
38        mLut = createLUT(interpolator, duration);
39    }
40
41    private static float[] createLUT(TimeInterpolator interpolator, int duration) {
42        long frameIntervalNanos = Choreographer.getInstance().getFrameIntervalNanos();
43        int animIntervalMs = (int) (frameIntervalNanos / TimeUtils.NANOS_PER_MS);
44        int numAnimFrames = (int) Math.ceil(duration / animIntervalMs);
45        float values[] = new float[numAnimFrames];
46        float lastFrame = numAnimFrames - 1;
47        for (int i = 0; i < numAnimFrames; i++) {
48            float inValue = i / lastFrame;
49            values[i] = interpolator.getInterpolation(inValue);
50        }
51        return values;
52    }
53
54    @Override
55    public long createNativeInterpolator() {
56        return NativeInterpolatorFactoryHelper.createLutInterpolator(mLut);
57    }
58
59    /**
60     * Used to create a one-shot float[] LUT & native interpolator
61     */
62    public static long createNativeInterpolator(TimeInterpolator interpolator, int duration) {
63        float[] lut = createLUT(interpolator, duration);
64        return NativeInterpolatorFactoryHelper.createLutInterpolator(lut);
65    }
66}
67