Hi,
My name is Jarek, I'm a student of physics. At the moment I'm writing my masters thesis and I wanted to share a short study of energy conservation in Box2D that I did during my thesis research.
The task from the thesis requires to develop a simple 2D rigid body dynamics solver.
I tried to check if the Box2D iterative solver model is good enough for the thesis purpose.
Below I present the results of my investigations.
1) General description
While energy conservation was crucial in my work, the first goal was to make it possible to control and maintain numerical error for energy and avoid numerical dissipation.
I did test the fluctuation of energy in Box2D for two different floating point implementations: double and single/float precisions.
The test environment was meant to conserve energy.
In the following description MKS unit system (meters-kilograms-seconds) will be used.
All the tests were performed with fixed time step, which was set to 0.01.
All objects had the same density set to 1.0.
2) First test
2.1) Methodology
The test system consists of 100 small boxes (1x1 size each) contained in a 40x40 container box (static body).
Initial velocity of each small box was set to (0,-5).
Float-based (unmodified) Box2D v2.3.0 used.
No external forces were applied (no gravity).
The system was set to be frictionless
b2FixtureDef.friction = 1.0,
with elastic collisions
b2FixtureDef.restitution = 1.0,
b2Settings: b2_velocityThreshold = 0.0.
For the calculation of the Percent Difference of Kinetic Energy (dissipation) the following formula was used
KeErr = fabs(Ke - KeInit) / KeInit * 100.0 [%].
Between collisions (during collision-less motion) the total energy of the system was conserved, however, energy fluctuations occurred after each collision.
Due to this fact duration of each test was measured in total number of collisions.
The goal was to run a sequence of simulations duration of which would be equal to 10M collisions (the collision counter would be incremented by the number of contact points after every velocity constraint solver execution).
The test (for the system configuration above) was run for the float-based Box2D.
2.2) Results
Collision counter vs. dissipation:
Collision Count: 100K
KeErr: 16.23%
Collision Count: 150K
KeErr: 25.87%
Collision Count: 200K
KeErr: 34.27%
Collision Count: 300K
KeErr: 57.19%
Collision Count: 500K
KeErr: 102.50%
Collision Count: 1M
KeErr: 759.51%
Collision Count: 1.5M
KeErr: 31849.52%
After about 1.5M collisions the dissipation stabilizes at the level of 32K% (+/- 5K%)
2.3) Discussion
The occurrence of step energy error above MaxKeErr=0.001% (step energy error = dissipation jump in a single world-step, with dissipation delta above preconfigured MaxKeErr) happened every 550 collisions.
It also should be clarified that by 'world-step' in this text I will refer to a single b2Island::Step() execution, not b2World::Step() execution (the reason behind this is that adaptive velocity constraint iteration as well as step energy error control/measurement have been implemented in b2Island::Step() method)
3) Second test
3.1) Methodology
In the next step adaptive (dynamic) iteration count into velocity constraint solver loop was added, so that the velocity constraint solver could repeat its iterations until the step energy error below selected value of 0.001% was reached.
Maximum number of iterations was set to 100K. When the number of iterations exceeds this bound then the iteration procedure stops and the number of the step energy errors above 0.001% is incremented.
3.2) Results
Collision Count: 1M
KeErr: 492.47%
3.3) Discussion
Frequency of the step energy errors above 0.001% decreased to 1 every 780 collisions.
I had isolated the configuration at which energy error jump occurs and built a simple test case with just 2 small boxes closed in a fixed box container.
Here is start configuration of that system:
box0:
position: (-14, 20)
angle: PI/4
velocity: (0, 0)
angVelocity: 0
box1:
position: (5, 20)
angle: 0
velocity: (-20, 0)
angVelocity: 0
ground-container:
g0: (-20, 0)
g1: (20, 0)
g2: (20, 40)
g3: (-20, 40)
In this test case I investigated the situation when the dissipation changes rapidly and the results are as follows.
First box0 hits box1 and bounces back right, box0 stays still touching (slowly sliding over) left side of ground-container.
Then box0 hits the right side of the container and bounces to the left. Then box0 hits box1 for the second time and in this collision the solver gives the rapid change in the energy error.
The source of this behavior was located in the part of the code responsible for velocity threshold handling in b2ContactSolver.cpp in b2ContactSolver::InitializeVelocityConstraints() method:
// Setup a velocity bias for restitution.
vcp->velocityBias = 0.0f;
float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA));
if (vRel < -b2_velocityThreshold)
{
vcp->velocityBias = -vc->restitution * vRel;
}
The velocity threshold is a mechanism implemented to remove micro-collisions and make still objects visually stable.
The condition (vRel < -b2_velocityThreshold) states that any relative velocity (in the direction of the normal to the contact plane) smaller than that set in b2Settings::b2_velocityThreshold will be canceled, i.e., the collision will be treated as inelastic.
However, the condition also states that only non-separating velocity will be taken into account later by velocity constraint solver. Any positive (separating) relative velocity at the point of contact will be canceled just as it would be while the restitution of colliding objects is zero.
Now, lets analyse the following hypothetic scenario with 2 colliding objects.
Two of them are still separating, i.e., contact exists between the two objects and the relative velocity at the contact point is positive (this is exactly what occurs in box0-ground contact after first box1 collision; due to small angular velocity acquired after collision box0 slides frictionlessly over the ground).
If the two objects are hit by a third object (here: the second hit of box0 by box1), then the separation velocity of two objects will be taken into solver account as zero (because of the velocity threshold clamp condition). That will produce a small energy error, accumulating after every occurrence of this scenario.
Attribute b2Settings::b2_velocityThreshold for all tests was set to zero and the whole configuration was meant to be frictionless / elastic. For this reason the scenario presented above is a good candidate for explaining what occurs when energy is changing periodically and could reveal the background of the dissipation problem.
4) Third test
4.1) Methodology
In this test I changed the velocity threshold clamp condition replacing:
if (vRel < -b2_velocityThreshold)
by:
if (fabs(vRel) > b2_velocityThreshold)
It prevents the velocity threshold mechanism from canceling the relative velocity during separating-velocity collisions (with zero b2_velocityThreshold) while keeping the velocity threshold mechanism working for non-zero b2_velocityThreshold.
The test was performed under the following conditions:
Velocity threshold clamp modified condition as described above was applied.
Default (fixed) velocity constraint iteration count was used (Settings::velocityIterations = 8).
No dynamic (adaptive) velocity constraint iteration count was used.
The test used the same start configuration (100 boxes + ground-box container) as the first test.
The results of dissipation test were presented below.
4.2) Results
Collision Count: 100K
KeErr: 0.1372%
Collision Count: 1M
KeErr: 1.514%
Collision Count: 10M
KeErr: 15.64%
4.1) Discussion
One can observe that in comparison to the first test, after introducing above modification of velocity threshold condition, the dissipation decreased by approx 400 times at 1M collisions.
Also the dissipation is now linear relative to collision count.
5) Fourth test
5.1) Methodology
Then I applied the earlier code modification and turned on adaptive VC (velocity constraint) iteration count.
Below are results for 10M collisions test.
The maximum energy error to adapt the VC iteration count to (in single simulation step) was set to MaxKeErr=0.001%
The maximum number of VC iterations in single world-step to adapt to MaxKeErr was set to 100K iterations.
Velocity threshold clamp modified condition as described above was applied.
'HiIter' is maximum number of iterations achieved in a single world-step.
'AddIterExecs' is the number of world-steps in which additional (to default Settings::velocityIterations = 8) VC solver iterations were executed to achieve energy error below MaxKeErr in these world-steps.
5.2) Results
Collision Count: 10M
KeErr: 2.169%
HiIter: 27
AddIterExecs: 624
5.3) Discussion
It should be noticed that in this test 1 collision out of 10M was not resolved, i.e., it did not obtain error below prescribed bound of 0.001% set in MaxKeErr.
It was assumed that the reason behind not resolving this single collision with error below requested was that the value set in MaxKeErr was too small to converge to energy error below MaxKeErr for the solver using float precision.
6) Fifth test
6.1) Methodology
In order to correct the issue in the discussion above, Box2D was rewritten using double precision numbers instead of single precision numbers. The results of the test for 10M collisions of the new Box2D with the mentioned modifications (adaptive VC solver iteration and changed velocity threshold clamp condition) were presented below.
Maximum energy error was set to MaxKeErr=0.001%
Maximum number of VC iterations in single world step was set to 100K iterations.
6.2) Results
Collision Count: 10M
KeErr: 0.923%
HiIter: 30
AddIterExecs: 608
6.3) Discussion
All collisions were resolved obtaining step energy error below configured MaxKeErr=0.001%.
7) Sixth test
7.1) Methodology
Finally, below there are results for the test of the double-based Box2D for 10M collision with MaxKeErr=0.00001%.
Adaptive VC solver and changed velocity threshold clamp condition were applied.
7.2) Results
Collision Count: 10M
KeErr: 0.013942%
HiIter: 60
AddIterExecs: 4911
7.3) Discussion
It can be observed that the base step error MaxKeErr propagates accumulating into the final dissipation (KeErr) approx every 1000 collisions.
It is still left to investigate if the relation between MaxKeErr and KeErr is linear or not.
This relation can be used in a particular simulation to choose proper MaxKeErr at the beginning to obtain final numerical dissipation not greater than requested.
8) Conclusions
Applying discussed modification for velocity threshold clamp condition reduces the dissipation.
Application of adaptive velocity constraint iteration scheme (with the above modification) makes it possible to control maximum dissipation in single world-step.
Double-based Box2D implementation raises the issues:
- It has no effect on dissipation without adaptive velocity constraint iteration and presented velocity threshold fix.
- Both of the above modifications give higher resolution control of maximum dissipation in single world-step.
Finally it should be pointed out that these modifications should not improve neither simulation stability nor visual realism when applied in typical game-like environments. That is because the game environments usually include non-zero friction, inelastic collisions, gravity and different energy fluctuation sources. That results in dissipation (which is allowed and desired for the visual realism in games) far greater than observed / discussed in this study.
For these reasons the modifications discussed here could be useful in scientific simulations, e.g., Molecular Dynamics.
Kind regards,
Jarek
My name is Jarek, I'm a student of physics. At the moment I'm writing my masters thesis and I wanted to share a short study of energy conservation in Box2D that I did during my thesis research.
The task from the thesis requires to develop a simple 2D rigid body dynamics solver.
I tried to check if the Box2D iterative solver model is good enough for the thesis purpose.
Below I present the results of my investigations.
1) General description
While energy conservation was crucial in my work, the first goal was to make it possible to control and maintain numerical error for energy and avoid numerical dissipation.
I did test the fluctuation of energy in Box2D for two different floating point implementations: double and single/float precisions.
The test environment was meant to conserve energy.
In the following description MKS unit system (meters-kilograms-seconds) will be used.
All the tests were performed with fixed time step, which was set to 0.01.
All objects had the same density set to 1.0.
2) First test
2.1) Methodology
The test system consists of 100 small boxes (1x1 size each) contained in a 40x40 container box (static body).
Initial velocity of each small box was set to (0,-5).
Float-based (unmodified) Box2D v2.3.0 used.
No external forces were applied (no gravity).
The system was set to be frictionless
b2FixtureDef.friction = 1.0,
with elastic collisions
b2FixtureDef.restitution = 1.0,
b2Settings: b2_velocityThreshold = 0.0.
For the calculation of the Percent Difference of Kinetic Energy (dissipation) the following formula was used
KeErr = fabs(Ke - KeInit) / KeInit * 100.0 [%].
Between collisions (during collision-less motion) the total energy of the system was conserved, however, energy fluctuations occurred after each collision.
Due to this fact duration of each test was measured in total number of collisions.
The goal was to run a sequence of simulations duration of which would be equal to 10M collisions (the collision counter would be incremented by the number of contact points after every velocity constraint solver execution).
The test (for the system configuration above) was run for the float-based Box2D.
2.2) Results
Collision counter vs. dissipation:
Collision Count: 100K
KeErr: 16.23%
Collision Count: 150K
KeErr: 25.87%
Collision Count: 200K
KeErr: 34.27%
Collision Count: 300K
KeErr: 57.19%
Collision Count: 500K
KeErr: 102.50%
Collision Count: 1M
KeErr: 759.51%
Collision Count: 1.5M
KeErr: 31849.52%
After about 1.5M collisions the dissipation stabilizes at the level of 32K% (+/- 5K%)
2.3) Discussion
The occurrence of step energy error above MaxKeErr=0.001% (step energy error = dissipation jump in a single world-step, with dissipation delta above preconfigured MaxKeErr) happened every 550 collisions.
It also should be clarified that by 'world-step' in this text I will refer to a single b2Island::Step() execution, not b2World::Step() execution (the reason behind this is that adaptive velocity constraint iteration as well as step energy error control/measurement have been implemented in b2Island::Step() method)
3) Second test
3.1) Methodology
In the next step adaptive (dynamic) iteration count into velocity constraint solver loop was added, so that the velocity constraint solver could repeat its iterations until the step energy error below selected value of 0.001% was reached.
Maximum number of iterations was set to 100K. When the number of iterations exceeds this bound then the iteration procedure stops and the number of the step energy errors above 0.001% is incremented.
3.2) Results
Collision Count: 1M
KeErr: 492.47%
3.3) Discussion
Frequency of the step energy errors above 0.001% decreased to 1 every 780 collisions.
I had isolated the configuration at which energy error jump occurs and built a simple test case with just 2 small boxes closed in a fixed box container.
Here is start configuration of that system:
box0:
position: (-14, 20)
angle: PI/4
velocity: (0, 0)
angVelocity: 0
box1:
position: (5, 20)
angle: 0
velocity: (-20, 0)
angVelocity: 0
ground-container:
g0: (-20, 0)
g1: (20, 0)
g2: (20, 40)
g3: (-20, 40)
In this test case I investigated the situation when the dissipation changes rapidly and the results are as follows.
First box0 hits box1 and bounces back right, box0 stays still touching (slowly sliding over) left side of ground-container.
Then box0 hits the right side of the container and bounces to the left. Then box0 hits box1 for the second time and in this collision the solver gives the rapid change in the energy error.
The source of this behavior was located in the part of the code responsible for velocity threshold handling in b2ContactSolver.cpp in b2ContactSolver::InitializeVelocityConstraints() method:
// Setup a velocity bias for restitution.
vcp->velocityBias = 0.0f;
float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA));
if (vRel < -b2_velocityThreshold)
{
vcp->velocityBias = -vc->restitution * vRel;
}
The velocity threshold is a mechanism implemented to remove micro-collisions and make still objects visually stable.
The condition (vRel < -b2_velocityThreshold) states that any relative velocity (in the direction of the normal to the contact plane) smaller than that set in b2Settings::b2_velocityThreshold will be canceled, i.e., the collision will be treated as inelastic.
However, the condition also states that only non-separating velocity will be taken into account later by velocity constraint solver. Any positive (separating) relative velocity at the point of contact will be canceled just as it would be while the restitution of colliding objects is zero.
Now, lets analyse the following hypothetic scenario with 2 colliding objects.
Two of them are still separating, i.e., contact exists between the two objects and the relative velocity at the contact point is positive (this is exactly what occurs in box0-ground contact after first box1 collision; due to small angular velocity acquired after collision box0 slides frictionlessly over the ground).
If the two objects are hit by a third object (here: the second hit of box0 by box1), then the separation velocity of two objects will be taken into solver account as zero (because of the velocity threshold clamp condition). That will produce a small energy error, accumulating after every occurrence of this scenario.
Attribute b2Settings::b2_velocityThreshold for all tests was set to zero and the whole configuration was meant to be frictionless / elastic. For this reason the scenario presented above is a good candidate for explaining what occurs when energy is changing periodically and could reveal the background of the dissipation problem.
4) Third test
4.1) Methodology
In this test I changed the velocity threshold clamp condition replacing:
if (vRel < -b2_velocityThreshold)
by:
if (fabs(vRel) > b2_velocityThreshold)
It prevents the velocity threshold mechanism from canceling the relative velocity during separating-velocity collisions (with zero b2_velocityThreshold) while keeping the velocity threshold mechanism working for non-zero b2_velocityThreshold.
The test was performed under the following conditions:
Velocity threshold clamp modified condition as described above was applied.
Default (fixed) velocity constraint iteration count was used (Settings::velocityIterations = 8).
No dynamic (adaptive) velocity constraint iteration count was used.
The test used the same start configuration (100 boxes + ground-box container) as the first test.
The results of dissipation test were presented below.
4.2) Results
Collision Count: 100K
KeErr: 0.1372%
Collision Count: 1M
KeErr: 1.514%
Collision Count: 10M
KeErr: 15.64%
4.1) Discussion
One can observe that in comparison to the first test, after introducing above modification of velocity threshold condition, the dissipation decreased by approx 400 times at 1M collisions.
Also the dissipation is now linear relative to collision count.
5) Fourth test
5.1) Methodology
Then I applied the earlier code modification and turned on adaptive VC (velocity constraint) iteration count.
Below are results for 10M collisions test.
The maximum energy error to adapt the VC iteration count to (in single simulation step) was set to MaxKeErr=0.001%
The maximum number of VC iterations in single world-step to adapt to MaxKeErr was set to 100K iterations.
Velocity threshold clamp modified condition as described above was applied.
'HiIter' is maximum number of iterations achieved in a single world-step.
'AddIterExecs' is the number of world-steps in which additional (to default Settings::velocityIterations = 8) VC solver iterations were executed to achieve energy error below MaxKeErr in these world-steps.
5.2) Results
Collision Count: 10M
KeErr: 2.169%
HiIter: 27
AddIterExecs: 624
5.3) Discussion
It should be noticed that in this test 1 collision out of 10M was not resolved, i.e., it did not obtain error below prescribed bound of 0.001% set in MaxKeErr.
It was assumed that the reason behind not resolving this single collision with error below requested was that the value set in MaxKeErr was too small to converge to energy error below MaxKeErr for the solver using float precision.
6) Fifth test
6.1) Methodology
In order to correct the issue in the discussion above, Box2D was rewritten using double precision numbers instead of single precision numbers. The results of the test for 10M collisions of the new Box2D with the mentioned modifications (adaptive VC solver iteration and changed velocity threshold clamp condition) were presented below.
Maximum energy error was set to MaxKeErr=0.001%
Maximum number of VC iterations in single world step was set to 100K iterations.
6.2) Results
Collision Count: 10M
KeErr: 0.923%
HiIter: 30
AddIterExecs: 608
6.3) Discussion
All collisions were resolved obtaining step energy error below configured MaxKeErr=0.001%.
7) Sixth test
7.1) Methodology
Finally, below there are results for the test of the double-based Box2D for 10M collision with MaxKeErr=0.00001%.
Adaptive VC solver and changed velocity threshold clamp condition were applied.
7.2) Results
Collision Count: 10M
KeErr: 0.013942%
HiIter: 60
AddIterExecs: 4911
7.3) Discussion
It can be observed that the base step error MaxKeErr propagates accumulating into the final dissipation (KeErr) approx every 1000 collisions.
It is still left to investigate if the relation between MaxKeErr and KeErr is linear or not.
This relation can be used in a particular simulation to choose proper MaxKeErr at the beginning to obtain final numerical dissipation not greater than requested.
8) Conclusions
Applying discussed modification for velocity threshold clamp condition reduces the dissipation.
Application of adaptive velocity constraint iteration scheme (with the above modification) makes it possible to control maximum dissipation in single world-step.
Double-based Box2D implementation raises the issues:
- It has no effect on dissipation without adaptive velocity constraint iteration and presented velocity threshold fix.
- Both of the above modifications give higher resolution control of maximum dissipation in single world-step.
Finally it should be pointed out that these modifications should not improve neither simulation stability nor visual realism when applied in typical game-like environments. That is because the game environments usually include non-zero friction, inelastic collisions, gravity and different energy fluctuation sources. That results in dissipation (which is allowed and desired for the visual realism in games) far greater than observed / discussed in this study.
For these reasons the modifications discussed here could be useful in scientific simulations, e.g., Molecular Dynamics.
Kind regards,
Jarek