Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
spring_animation.mm
Go to the documentation of this file.
1//
2// Copyright (c) Meta Platforms, Inc. and affiliates.
3//
4// This source code is licensed under the MIT license found in the
5// LICENSE file in the root directory of this source tree.
6//
7// @flow
8// @format
9//
10
11#import "spring_animation.h"
12
13#include <Foundation/Foundation.h>
14
15@interface SpringAnimation ()
16
17@property(nonatomic, assign) double zeta;
18@property(nonatomic, assign) double omega0;
19@property(nonatomic, assign) double omega1;
20@property(nonatomic, assign) double v0;
21
22@end
23
24// Spring code adapted from React Native's Animation Library, see:
25// https://github.com/facebook/react-native/blob/main/Libraries/Animated/animations/SpringAnimation.js
26@implementation SpringAnimation
27- (instancetype)initWithStiffness:(double)stiffness
28 damping:(double)damping
29 mass:(double)mass
30 initialVelocity:(double)initialVelocity
31 fromValue:(double)fromValue
32 toValue:(double)toValue {
33 self = [super init];
34 if (self) {
35 _stiffness = stiffness;
36 _damping = damping;
37 _mass = mass;
38 _initialVelocity = initialVelocity;
39 _fromValue = fromValue;
40 _toValue = toValue;
41
42 _zeta = _damping / (2 * sqrt(_stiffness * _mass)); // Damping ratio.
43 _omega0 = sqrt(_stiffness / _mass); // Undamped angular frequency of the oscillator.
44 _omega1 = _omega0 * sqrt(1.0 - _zeta * _zeta); // Exponential decay.
45 _v0 = -_initialVelocity;
46 }
47 return self;
48}
49
50- (double)curveFunction:(double)t {
51 const double x0 = _toValue - _fromValue;
52
53 double y;
54 if (_zeta < 1) {
55 // Under damped.
56 const double envelope = exp(-_zeta * _omega0 * t);
57 y = _toValue - envelope * (((_v0 + _zeta * _omega0 * x0) / _omega1) * sin(_omega1 * t) +
58 x0 * cos(_omega1 * t));
59 } else {
60 // Critically damped.
61 const double envelope = exp(-_omega0 * t);
62 y = _toValue - envelope * (x0 + (_v0 + _omega0 * x0) * t);
63 }
64
65 return y;
66}
67@end
double y