Scoop API

scoop:scoop.surface:0.1.0

src/shared/animation/easing.scoop

Selected production source · src/shared/animation/easing.scoop

1package scoop.surface
3import scoop.math.abs
4import scoop.math.max
5import scoop.math.min
7/** A unit-time cubic Bézier curve. X controls are monotonic; Y controls may overshoot. */
8public class Easing private constructor(
9 private val x1: Double,
10 private val y1: Double,
11 private val x2: Double,
12 private val y2: Double
13) {
14 public fun transform(fraction: Double): Double {
15 requireAnimation(fraction.isFinite(), "non-finite easing fraction")
16 val x = min(1.0, max(0.0, fraction))
17 if (x1 == y1 && x2 == y2)
18 return x
19 return cubic(parameter(x), y1, y2)
20 }
21 internal fun slope(fraction: Double): Double {
22 if (x1 == y1 && x2 == y2)
23 return 1.0
24 val t = parameter(fraction)
25 val dx = derivative(t, x1, x2)
26 if (abs(dx) > 0.000000000001)
27 return derivative(t, y1, y2) / dx
28 val before = max(0.0, fraction - 0.000001)
29 val after = min(1.0, fraction + 0.000001)
30 return (transform(after) - transform(before)) / (after - before)
31 }
32 private fun parameter(x: Double): Double {
33 if (x <= 0.0)
34 return 0.0
35 if (x >= 1.0)
36 return 1.0
37 var low = 0.0
38 var high = 1.0
39 for (index in 0 ..< 48) {
40 val middle = (low + high) * 0.5
41 if (cubic(middle, x1, x2) < x)
42 low = middle
43 else
44 high = middle
45 }
46 return (low + high) * 0.5
47 }
48 public companion object {
49 public val Linear: Easing = Easing(0.0, 0.0, 1.0, 1.0)
50 public val EaseIn: Easing = Easing(0.42, 0.0, 1.0, 1.0)
51 public val EaseOut: Easing = Easing(0.0, 0.0, 0.58, 1.0)
52 public val EaseInOut: Easing = Easing(0.42, 0.0, 0.58, 1.0)
53 public fun cubicBezier(x1: Double, y1: Double, x2: Double, y2: Double): Easing {
54 requireAnimation(
55 x1.isFinite() &&
56 y1.isFinite() &&
57 x2.isFinite() &&
58 y2.isFinite() &&
59 x1 >=
60 0.0 &&
61 x1 <=
62 1.0 &&
63 x2 >=
64 0.0 &&
65 x2 <=
66 1.0,
67 "invalid cubic Bézier controls"
68 )
69 return Easing(x1, y1, x2, y2)
70 }
71 }
74private fun cubic(t: Double, a: Double, b: Double): Double {
75 val q = 1.0 - t
76 return (3.0 * q * q * t) * a + (3.0 * q * t * t) * b + t * t * t
79private fun derivative(t: Double, a: Double, b: Double): Double {
80 val q = 1.0 - t
81 return 3.0 * q * q * a + 6.0 * q * t * (b - a) + 3.0 * t * t * (1.0 - b)