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:
Adam Miskiewicz
2017-09-20 23:36:11 -07:00
committed by Facebook Github Bot
parent 4d54b48167
commit 26133beda9
11 changed files with 488 additions and 310 deletions

View File

@@ -24,14 +24,14 @@ import com.facebook.react.bridge.ReadableMap;
private boolean mSpringStarted;
// configuration
private double mSpringFriction;
private double mSpringTension;
private double mSpringStiffness;
private double mSpringDamping;
private double mSpringMass;
private double mInitialVelocity;
private boolean mOvershootClampingEnabled;
// all physics simulation objects are final and reused in each processing pass
private final PhysicsState mCurrentState = new PhysicsState();
private final PhysicsState mPreviousState = new PhysicsState();
private final PhysicsState mTempState = new PhysicsState();
private double mStartValue;
private double mEndValue;
// thresholds for determining when the spring is at rest
@@ -44,9 +44,11 @@ import com.facebook.react.bridge.ReadableMap;
private double mOriginalValue;
SpringAnimation(ReadableMap config) {
mSpringFriction = config.getDouble("friction");
mSpringTension = config.getDouble("tension");
mCurrentState.velocity = config.getDouble("initialVelocity");
mSpringStiffness = config.getDouble("stiffness");
mSpringDamping = config.getDouble("damping");
mSpringMass = config.getDouble("mass");
mInitialVelocity = config.getDouble("initialVelocity");
mCurrentState.velocity = mInitialVelocity;
mEndValue = config.getDouble("toValue");
mRestSpeedThreshold = config.getDouble("restSpeedThreshold");
mDisplacementFromRestThreshold = config.getDouble("restDisplacementThreshold");
@@ -65,6 +67,7 @@ import com.facebook.react.bridge.ReadableMap;
}
mStartValue = mCurrentState.position = mAnimatedValue.mValue;
mLastTime = frameTimeMillis;
mTimeAccumulator = 0.0;
mSpringStarted = true;
}
advance((frameTimeMillis - mLastTime) / 1000.0);
@@ -97,7 +100,7 @@ import com.facebook.react.bridge.ReadableMap;
private boolean isAtRest() {
return Math.abs(mCurrentState.velocity) <= mRestSpeedThreshold &&
(getDisplacementDistanceForState(mCurrentState) <= mDisplacementFromRestThreshold ||
mSpringTension == 0);
mSpringStiffness == 0);
}
/**
@@ -105,31 +108,12 @@ import com.facebook.react.bridge.ReadableMap;
* @return true if the spring is overshooting its target
*/
private boolean isOvershooting() {
return mSpringTension > 0 &&
return mSpringStiffness > 0 &&
((mStartValue < mEndValue && mCurrentState.position > mEndValue) ||
(mStartValue > mEndValue && mCurrentState.position < mEndValue));
}
/**
* linear interpolation between the previous and current physics state based on the amount of
* timestep remaining after processing the rendering delta time in timestep sized chunks.
* @param alpha from 0 to 1, where 0 is the previous state, 1 is the current state
*/
private void interpolate(double alpha) {
mCurrentState.position = mCurrentState.position * alpha + mPreviousState.position *(1-alpha);
mCurrentState.velocity = mCurrentState.velocity * alpha + mPreviousState.velocity *(1-alpha);
}
/**
* advance the physics simulation in SOLVER_TIMESTEP_SEC sized chunks to fulfill the required
* realTimeDelta.
* The math is inlined inside the loop since it made a huge performance impact when there are
* several springs being advanced.
* @param time clock time
* @param realDeltaTime clock drift
*/
private void advance(double realDeltaTime) {
if (isAtRest()) {
return;
}
@@ -143,87 +127,55 @@ import com.facebook.react.bridge.ReadableMap;
mTimeAccumulator += adjustedDeltaTime;
double tension = mSpringTension;
double friction = mSpringFriction;
double c = mSpringDamping;
double m = mSpringMass;
double k = mSpringStiffness;
double v0 = -mInitialVelocity;
double position = mCurrentState.position;
double velocity = mCurrentState.velocity;
double tempPosition = mTempState.position;
double tempVelocity = mTempState.velocity;
double zeta = c / (2 * Math.sqrt(k * m ));
double omega0 = Math.sqrt(k / m);
double omega1 = omega0 * Math.sqrt(1.0 - (zeta * zeta));
double x0 = mEndValue - mStartValue;
double aVelocity, aAcceleration;
double bVelocity, bAcceleration;
double cVelocity, cAcceleration;
double dVelocity, dAcceleration;
double dxdt, dvdt;
// iterate over the true time
while (mTimeAccumulator >= SOLVER_TIMESTEP_SEC) {
/* begin debug
iterations++;
end debug */
mTimeAccumulator -= SOLVER_TIMESTEP_SEC;
if (mTimeAccumulator < SOLVER_TIMESTEP_SEC) {
// This will be the last iteration. Remember the previous state in case we need to
// interpolate
mPreviousState.position = position;
mPreviousState.velocity = velocity;
}
// Perform an RK4 integration to provide better detection of the acceleration curve via
// sampling of Euler integrations at 4 intervals feeding each derivative into the calculation
// of the next and taking a weighted sum of the 4 derivatives as the final output.
// This math was inlined since it made for big performance improvements when advancing several
// springs in one pass of the BaseSpringSystem.
// The initial derivative is based on the current velocity and the calculated acceleration
aVelocity = velocity;
aAcceleration = (tension * (mEndValue - tempPosition)) - friction * velocity;
// Calculate the next derivatives starting with the last derivative and integrating over the
// timestep
tempPosition = position + aVelocity * SOLVER_TIMESTEP_SEC * 0.5;
tempVelocity = velocity + aAcceleration * SOLVER_TIMESTEP_SEC * 0.5;
bVelocity = tempVelocity;
bAcceleration = (tension * (mEndValue - tempPosition)) - friction * tempVelocity;
tempPosition = position + bVelocity * SOLVER_TIMESTEP_SEC * 0.5;
tempVelocity = velocity + bAcceleration * SOLVER_TIMESTEP_SEC * 0.5;
cVelocity = tempVelocity;
cAcceleration = (tension * (mEndValue - tempPosition)) - friction * tempVelocity;
tempPosition = position + cVelocity * SOLVER_TIMESTEP_SEC;
tempVelocity = velocity + cAcceleration * SOLVER_TIMESTEP_SEC;
dVelocity = tempVelocity;
dAcceleration = (tension * (mEndValue - tempPosition)) - friction * tempVelocity;
// Take the weighted sum of the 4 derivatives as the final output.
dxdt = 1.0/6.0 * (aVelocity + 2.0 * (bVelocity + cVelocity) + dVelocity);
dvdt = 1.0/6.0 * (aAcceleration + 2.0 * (bAcceleration + cAcceleration) + dAcceleration);
position += dxdt * SOLVER_TIMESTEP_SEC;
velocity += dvdt * SOLVER_TIMESTEP_SEC;
double velocity;
double position;
double t = mTimeAccumulator;
if (zeta < 1) {
// Under damped
double envelope = Math.exp(-zeta * omega0 * t);
position =
mEndValue -
envelope *
((v0 + zeta * omega0 * x0) / omega1 * Math.sin(omega1 * t) +
x0 * Math.cos(omega1 * t));
// This looks crazy -- it's actually just the derivative of the
// oscillation function
velocity =
zeta *
omega0 *
envelope *
(Math.sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 +
x0 * Math.cos(omega1 * t)) -
envelope *
(Math.cos(omega1 * t) * (v0 + zeta * omega0 * x0) -
omega1 * x0 * Math.sin(omega1 * t));
} else {
// Critically damped spring
double envelope = Math.exp(-omega0 * t);
position = mEndValue - envelope * (x0 + (v0 + omega0 * x0) * t);
velocity =
envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0));
}
mTempState.position = tempPosition;
mTempState.velocity = tempVelocity;
mCurrentState.position = position;
mCurrentState.velocity = velocity;
if (mTimeAccumulator > 0) {
interpolate(mTimeAccumulator / SOLVER_TIMESTEP_SEC);
}
// End the spring immediately if it is overshooting and overshoot clamping is enabled.
// Also make sure that if the spring was considered within a resting threshold that it's now
// snapped to its end value.
if (isAtRest() || (mOvershootClampingEnabled && isOvershooting())) {
// Don't call setCurrentValue because that forces a call to onSpringUpdate
if (tension > 0) {
if (mSpringStiffness > 0) {
mStartValue = mEndValue;
mCurrentState.position = mEndValue;
} else {