mirror of
https://github.com/zhigang1992/react-native.git
synced 2026-05-12 11:40:33 +08:00
Add closed-form damped harmonic oscillator algorithm to Animated.spring
Summary: As I was working on mimicking iOS animations for my ongoing work with `react-navigation`, one task I had was to match the "push from right" animation that is common in UINavigationController. I was able to grab the exact animation values for this animation with some LLDB magic, and found that the screen is animated using a `CASpringAnimation` with the parameters: - stiffness: 1000 - damping: 500 - mass: 3 After spending a considerable amount of time attempting to replicate the spring created with these values by CASpringAnimation by specifying values for tension and friction in the current `Animated.spring` implementation, I was unable to come up with mathematically equivalent values that could replicate the spring _exactly_. After doing some research, I ended up disassembling the QuartzCore framework, reading the assembly, and determined that Apple's implementation of `CASpringAnimation` does not use an integrated, numerical animation model as we do in Animated.spring, but instead solved for the closed form of the equations that govern damped harmonic oscillation (the differential equations themselves are [here](https://en.wikipedia.org/wiki/Harmonic_oscillator#Damped_harmonic_oscillator), and a paper describing the math to arrive at the closed-form solution to the second-order ODE that describes the DHO is [here](http://planetmath.org/sites/default/files/texpdf/39745.pdf)). Though we can get the currently implemented RK4 integration close by tweaking some values, it is, the current model is at it's core, an approximation. It seemed that if I wanted to implement the `CASpringAnimation` behavior _exactly_, I needed to implement the analytical model (as is implemented in `CASpringAnimation`) in `Animated`. We add three new optional parameters to `Animated.spring` (to both the JS and native implementations): - `stiffness`, a value describing the spring's stiffness coefficient - `damping`, a value defining how the spring's motion should be damped due to the forces of friction (technically called the _viscous damping coefficient_). - `mass`, a value describing the mass of the object attached to the end of the simulated spring Just like if a developer were to specify `bounciness`/`speed` and `tension`/`friction` in the same config, specifying any of these new parameters while also specifying the aforementioned config values will cause an error to be thrown. ~Defaults for `Animated.spring` across all three implementations (JS/iOS/Android) stay the same, so this is intended to be *a non-breaking change*.~ ~If `stiffness`, `damping`, or `mass` are provided in the config, we switch to animating the spring with the new damped harmonic oscillator model (`DHO` as described in the code).~ We replace the old RK4 integration implementation with our new analytic implementation. Tension/friction nicely correspond directly to stiffness/damping with the mass of the spring locked at 1. This is intended to be *a non-breaking change*, but there may be very slight differences in people's springs (maybe not even noticeable to the naked eye), given the fact that this implementation is more accurate. The DHO animation algorithm will calculate the _position_ of the spring at time _t_ explicitly and in an analytical fashion, and use this calculation to update the animation's value. It will also analytically calculate the velocity at time _t_, so as to allow animated value tracking to continue to work as expected. Also, docs have been updated to cover the new configuration options (and also I added docs for Animated configuration options that were missing, such as `restDisplacementThreshold`, etc). Run tests. Run "Animated Gratuitous App" and "NativeAnimation" example in RNTester. Closes https://github.com/facebook/react-native/pull/15322 Differential Revision: D5794791 Pulled By: hramos fbshipit-source-id: 58ed9e134a097e321c85c417a142576f6a8952f8
This commit is contained in:
committed by
Facebook Github Bot
parent
4d54b48167
commit
26133beda9
@@ -25,6 +25,8 @@
|
||||
|
||||
@end
|
||||
|
||||
const NSTimeInterval MAX_DELTA_TIME = 0.064;
|
||||
|
||||
@implementation RCTSpringAnimation
|
||||
{
|
||||
CGFloat _toValue;
|
||||
@@ -32,8 +34,9 @@
|
||||
BOOL _overshootClamping;
|
||||
CGFloat _restDisplacementThreshold;
|
||||
CGFloat _restSpeedThreshold;
|
||||
CGFloat _tension;
|
||||
CGFloat _friction;
|
||||
CGFloat _stiffness;
|
||||
CGFloat _damping;
|
||||
CGFloat _mass;
|
||||
CGFloat _initialVelocity;
|
||||
NSTimeInterval _animationStartTime;
|
||||
NSTimeInterval _animationCurrentTime;
|
||||
@@ -44,6 +47,8 @@
|
||||
|
||||
NSInteger _iterations;
|
||||
NSInteger _currentLoop;
|
||||
|
||||
NSTimeInterval _t; // Current time (startTime + dt)
|
||||
}
|
||||
|
||||
- (instancetype)initWithId:(NSNumber *)animationId
|
||||
@@ -57,13 +62,16 @@
|
||||
_animationId = animationId;
|
||||
_toValue = [RCTConvert CGFloat:config[@"toValue"]];
|
||||
_fromValue = valueNode.value;
|
||||
_lastPosition = 0;
|
||||
_valueNode = valueNode;
|
||||
_overshootClamping = [RCTConvert BOOL:config[@"overshootClamping"]];
|
||||
_restDisplacementThreshold = [RCTConvert CGFloat:config[@"restDisplacementThreshold"]];
|
||||
_restSpeedThreshold = [RCTConvert CGFloat:config[@"restSpeedThreshold"]];
|
||||
_tension = [RCTConvert CGFloat:config[@"tension"]];
|
||||
_friction = [RCTConvert CGFloat:config[@"friction"]];
|
||||
_stiffness = [RCTConvert CGFloat:config[@"stiffness"]];
|
||||
_damping = [RCTConvert CGFloat:config[@"damping"]];
|
||||
_mass = [RCTConvert CGFloat:config[@"mass"]];
|
||||
_initialVelocity = [RCTConvert CGFloat:config[@"initialVelocity"]];
|
||||
|
||||
_callback = [callback copy];
|
||||
|
||||
_lastPosition = _fromValue;
|
||||
@@ -100,72 +108,68 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init)
|
||||
// Animation has not begun or animation has already finished.
|
||||
return;
|
||||
}
|
||||
|
||||
if (_animationStartTime == -1) {
|
||||
_animationStartTime = _animationCurrentTime = currentTime;
|
||||
|
||||
// calculate delta time
|
||||
NSTimeInterval deltaTime;
|
||||
if(_animationStartTime == -1) {
|
||||
_t = 0.0;
|
||||
_animationStartTime = currentTime;
|
||||
deltaTime = 0.0;
|
||||
} else {
|
||||
// Handle frame drops, and only advance dt by a max of MAX_DELTA_TIME
|
||||
deltaTime = MIN(MAX_DELTA_TIME, currentTime - _animationCurrentTime);
|
||||
_t = _t + deltaTime;
|
||||
}
|
||||
|
||||
// We are using a fixed time step and a maximum number of iterations.
|
||||
// The following post provides a lot of thoughts into how to build this
|
||||
// loop: http://gafferongames.com/game-physics/fix-your-timestep/
|
||||
CGFloat TIMESTEP_MSEC = 1;
|
||||
// Velocity is based on seconds instead of milliseconds
|
||||
CGFloat step = TIMESTEP_MSEC / 1000;
|
||||
|
||||
NSInteger numSteps = floorf((currentTime - _animationCurrentTime) / step);
|
||||
|
||||
// store the timestamp
|
||||
_animationCurrentTime = currentTime;
|
||||
if (numSteps == 0) {
|
||||
return;
|
||||
|
||||
CGFloat c = _damping;
|
||||
CGFloat m = _mass;
|
||||
CGFloat k = _stiffness;
|
||||
CGFloat v0 = -_initialVelocity;
|
||||
|
||||
CGFloat zeta = c / (2 * sqrtf(k * m));
|
||||
CGFloat omega0 = sqrtf(k / m);
|
||||
CGFloat omega1 = omega0 * sqrtf(1.0 - (zeta * zeta));
|
||||
CGFloat x0 = _toValue - _fromValue;
|
||||
|
||||
CGFloat position;
|
||||
CGFloat velocity;
|
||||
if (zeta < 1) {
|
||||
// Under damped
|
||||
CGFloat envelope = expf(-zeta * omega0 * _t);
|
||||
position =
|
||||
_toValue -
|
||||
envelope *
|
||||
((v0 + zeta * omega0 * x0) / omega1 * sinf(omega1 * _t) +
|
||||
x0 * cosf(omega1 * _t));
|
||||
// This looks crazy -- it's actually just the derivative of the
|
||||
// oscillation function
|
||||
velocity =
|
||||
zeta *
|
||||
omega0 *
|
||||
envelope *
|
||||
(sinf(omega1 * _t) * (v0 + zeta * omega0 * x0) / omega1 +
|
||||
x0 * cosf(omega1 * _t)) -
|
||||
envelope *
|
||||
(cosf(omega1 * _t) * (v0 + zeta * omega0 * x0) -
|
||||
omega1 * x0 * sinf(omega1 * _t));
|
||||
} else {
|
||||
CGFloat envelope = expf(-omega0 * _t);
|
||||
position = _toValue - envelope * (x0 + (v0 + omega0 * x0) * _t);
|
||||
velocity =
|
||||
envelope * (v0 * (_t * omega0 - 1) + _t * x0 * (omega0 * omega0));
|
||||
}
|
||||
|
||||
CGFloat position = _lastPosition;
|
||||
CGFloat velocity = _lastVelocity;
|
||||
|
||||
CGFloat tempPosition = _lastPosition;
|
||||
CGFloat tempVelocity = _lastVelocity;
|
||||
|
||||
for (NSInteger i = 0; i < numSteps; ++i) {
|
||||
// This is using RK4. A good blog post to understand how it works:
|
||||
// http://gafferongames.com/game-physics/integration-basics/
|
||||
CGFloat aVelocity = velocity;
|
||||
CGFloat aAcceleration = _tension * (_toValue - tempPosition) - _friction * tempVelocity;
|
||||
tempPosition = position + aVelocity * step / 2;
|
||||
tempVelocity = velocity + aAcceleration * step / 2;
|
||||
|
||||
CGFloat bVelocity = tempVelocity;
|
||||
CGFloat bAcceleration = _tension * (_toValue - tempPosition) - _friction * tempVelocity;
|
||||
tempPosition = position + bVelocity * step / 2;
|
||||
tempVelocity = velocity + bAcceleration * step / 2;
|
||||
|
||||
CGFloat cVelocity = tempVelocity;
|
||||
CGFloat cAcceleration = _tension * (_toValue - tempPosition) - _friction * tempVelocity;
|
||||
tempPosition = position + cVelocity * step / 2;
|
||||
tempVelocity = velocity + cAcceleration * step / 2;
|
||||
|
||||
CGFloat dVelocity = tempVelocity;
|
||||
CGFloat dAcceleration = _tension * (_toValue - tempPosition) - _friction * tempVelocity;
|
||||
tempPosition = position + cVelocity * step / 2;
|
||||
tempVelocity = velocity + cAcceleration * step / 2;
|
||||
|
||||
CGFloat dxdt = (aVelocity + 2 * (bVelocity + cVelocity) + dVelocity) / 6;
|
||||
CGFloat dvdt = (aAcceleration + 2 * (bAcceleration + cAcceleration) + dAcceleration) / 6;
|
||||
|
||||
position += dxdt * step;
|
||||
velocity += dvdt * step;
|
||||
}
|
||||
|
||||
|
||||
_lastPosition = position;
|
||||
_lastVelocity = velocity;
|
||||
|
||||
|
||||
[self onUpdate:position];
|
||||
|
||||
if (_animationHasFinished) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Conditions for stopping the spring animation
|
||||
BOOL isOvershooting = NO;
|
||||
if (_overshootClamping && _tension != 0) {
|
||||
if (_overshootClamping && _stiffness != 0) {
|
||||
if (_fromValue < _toValue) {
|
||||
isOvershooting = position > _toValue;
|
||||
} else {
|
||||
@@ -174,22 +178,24 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init)
|
||||
}
|
||||
BOOL isVelocity = ABS(velocity) <= _restSpeedThreshold;
|
||||
BOOL isDisplacement = YES;
|
||||
if (_tension != 0) {
|
||||
if (_stiffness != 0) {
|
||||
isDisplacement = ABS(_toValue - position) <= _restDisplacementThreshold;
|
||||
}
|
||||
|
||||
|
||||
if (isOvershooting || (isVelocity && isDisplacement)) {
|
||||
if (_tension != 0) {
|
||||
if (_stiffness != 0) {
|
||||
// Ensure that we end up with a round value
|
||||
if (_animationHasFinished) {
|
||||
return;
|
||||
}
|
||||
[self onUpdate:_toValue];
|
||||
}
|
||||
|
||||
|
||||
if (_iterations == -1 || _currentLoop < _iterations) {
|
||||
_lastPosition = _fromValue;
|
||||
_lastVelocity = _initialVelocity;
|
||||
// Set _animationStartTime to -1 to reset instance variables on the next animation step.
|
||||
_animationStartTime = -1;
|
||||
_currentLoop++;
|
||||
[self onUpdate:_fromValue];
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user