Use a Taylor approximation for velocity damping #633
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, linear and angular velocity damping are handled with a Padé approximation of exponential decay. This formulation is also used by engines such as Rapier and Box2D. Box2D has a brief derivation for the math.
This is run at every substep for entities with
LinearDampingandAngularDamping, during velocity integration.The Padé approximation is used to avoid calling
exp, which is comparatively expensive and also has non-deterministic precision, meaning that a slower software implementation would likely be required.An even faster option that avoids a division is the first-order Taylor approximation:
This PR changes velocity damping to use this Taylor approximation.
Accuracy
In my testing, the Taylor approximation produces results that are still extremely close to the exponential function when running at reasonable time steps. Here I am simulating 1,000 objects with damping coefficients ranging from 1 (top) to 0 (bottom) with an initial linear velocity towards the right.
Blue is the exponential function, red is the Palé approximation, and green is the Taylor approximation. Even with just 1 substep and a time step of 10 Hz, the results it settles at are very close:
With a more reasonable but still conservative setup of 4 substeps and a time step of 50 Hz, they are practically indistinguishable:
Based on these results, it seems like the Taylor approximation would provide good enough accuracy while being extremely cheap.
Aside: Caching
We can observe that the damping formula only requires the damping coefficient and delta time for the damping factor. When using a fixed time step (which is recommended for physics), these values typically remain constant. If we cached this factor, and only updated it when the damping coefficient or time step change, we could reduce damping to a single multiplication:
This is something that should be benchmarked and tested to see if the caching is worth storing the extra float.