Optimizations (#161)

- cache body sim indices and split out fat aabb
- deferred restitution
- the manifold point normal velocity is only computed for restitution or
hit events, otherwise it is zero
This commit is contained in:
Erin Catto 2026-09-20 15:54:52 -07:00 • committed by GitHub
commit 9e5a4cde86
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 3395 additions and 864 deletions

View file

@ -621,7 +621,7 @@ void Sample::DrawMetrics()
int count = m_profileWriteIndex - m_profileReadIndex;
// Unroll ring buffer into per-field histories.
constexpr int kRowCount = 22;
constexpr int kRowCount = 21;
float histories[kRowCount][m_profileCapacity];
float totals[kRowCount] = {};
for ( int i = 0; i < count; ++i )
@ -640,16 +640,15 @@ void Sample::DrawMetrics()
histories[9][i] = p.solveImpulses;
histories[10][i] = p.integratePositions;
histories[11][i] = p.relaxImpulses;
histories[12][i] = p.applyRestitution;
histories[13][i] = p.storeImpulses;
histories[14][i] = p.splitIslands;
histories[15][i] = p.transforms;
histories[16][i] = p.jointEvents;
histories[17][i] = p.hitEvents;
histories[18][i] = p.refit;
histories[19][i] = p.sleepIslands;
histories[20][i] = p.bullets;
histories[21][i] = p.sensors;
histories[12][i] = p.storeImpulses;
histories[13][i] = p.splitIslands;
histories[14][i] = p.transforms;
histories[15][i] = p.jointEvents;
histories[16][i] = p.hitEvents;
histories[17][i] = p.refit;
histories[18][i] = p.sleepIslands;
histories[19][i] = p.bullets;
histories[20][i] = p.sensors;
totals[0] += p.step;
totals[1] += p.pairs;
@ -663,16 +662,15 @@ void Sample::DrawMetrics()
totals[9] += p.solveImpulses;
totals[10] += p.integratePositions;
totals[11] += p.relaxImpulses;
totals[12] += p.applyRestitution;
totals[13] += p.storeImpulses;
totals[14] += p.splitIslands;
totals[15] += p.transforms;
totals[16] += p.jointEvents;
totals[17] += p.hitEvents;
totals[18] += p.refit;
totals[19] += p.sleepIslands;
totals[20] += p.bullets;
totals[21] += p.sensors;
totals[12] += p.storeImpulses;
totals[13] += p.splitIslands;
totals[14] += p.transforms;
totals[15] += p.jointEvents;
totals[16] += p.hitEvents;
totals[17] += p.refit;
totals[18] += p.sleepIslands;
totals[19] += p.bullets;
totals[20] += p.sensors;
}
// Smoothed over the last few frames so bars don't jitter visibly.
@ -728,13 +726,13 @@ void Sample::DrawMetrics()
const ImU32 colorDefault = IM_COL32( 220, 220, 220, 255 );
const RowDef rows[kRowCount] = {
{ "step", 0, colorStep }, { "pairs", 0, colorPairs }, { "collide", 0, colorCollide },
{ "solve", 0, colorSolve }, { "setup", 1, colorDefault }, { "constraints", 1, colorDefault },
{ "prepare", 2, colorDefault }, { "velocities", 2, colorDefault }, { "warm start", 2, colorDefault },
{ "bias", 2, colorDefault }, { "positions", 2, colorDefault }, { "relax", 2, colorDefault },
{ "restitution", 2, colorDefault }, { "store", 2, colorDefault }, { "split islands", 2, colorDefault },
{ "transforms", 1, colorDefault }, { "joint events", 1, colorDefault }, { "hit events", 1, colorDefault },
{ "refit BVH", 1, colorDefault }, { "sleep", 1, colorDefault }, { "bullets", 1, colorDefault },
{ "step", 0, colorStep }, { "pairs", 0, colorPairs }, { "collide", 0, colorCollide },
{ "solve", 0, colorSolve }, { "setup", 1, colorDefault }, { "constraints", 1, colorDefault },
{ "prepare", 2, colorDefault }, { "velocities", 2, colorDefault }, { "warm start", 2, colorDefault },
{ "bias", 2, colorDefault }, { "positions", 2, colorDefault }, { "relax", 2, colorDefault },
{ "store", 2, colorDefault }, { "split islands", 2, colorDefault },
{ "transforms", 1, colorDefault }, { "joint events", 1, colorDefault }, { "hit events", 1, colorDefault },
{ "refit BVH", 1, colorDefault }, { "sleep", 1, colorDefault }, { "bullets", 1, colorDefault },
{ "sensors", 0, colorSensors },
};
@ -955,7 +953,7 @@ void Sample::DrawMetrics()
ImGui::Text( "toi d/p/r = %d/%d/%d", s.distanceIterations, s.pushBackIterations, s.rootIterations );
ImGui::Text( "stack allocator size = %d K", s.stackUsed / 1024 );
ImGui::Text( "arena capacity = %d K", s.arenaCapacity / 1024 );
ImGui::Text( "total allocation = %d K", s.byteCount / 1024 );
ImGui::Text( "total allocation = %d K", (int)(s.byteCount / 1024) );
ImGui::Separator();
b3Capacity c = b3World_GetMaxCapacity( m_worldId );
@ -2175,3 +2173,24 @@ float CastClosestCallback( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float
rayContext->hit = true;
return fraction;
}
MechanicalEnergy MeasureEnergy( b3WorldId worldId, const b3BodyId* bodyIds, int count )
{
b3Vec3 gravity = b3World_GetGravity( worldId );
MechanicalEnergy energy = {};
for ( int i = 0; i < count; ++i )
{
b3MassData massData = b3Body_GetMassData( bodyIds[i] );
b3Vec3 v = b3Body_GetLinearVelocity( bodyIds[i] );
// The inertia tensor is in the body frame, so bring the angular velocity back to it
b3Vec3 w = b3InvRotateVector( b3Body_GetRotation( bodyIds[i] ), b3Body_GetAngularVelocity( bodyIds[i] ) );
energy.linear += 0.5f * massData.mass * b3Dot( v, v );
energy.angular += 0.5f * b3Dot( w, b3MulMV( massData.inertia, w ) );
energy.potential -= massData.mass * b3Dot( gravity, b3ToVec3( b3Body_GetWorldCenter( bodyIds[i] ) ) );
}
return energy;
}

View file

@ -294,3 +294,19 @@ struct CastClosestContext
float CastClosestCallback( b3ShapeId shapeId, b3Pos point, b3Vec3 normal, float fraction, uint64_t materialId, int triangleIndex,
int childIndex, void* context );
struct MechanicalEnergy
{
float Total() const
{
return linear + angular + potential;
}
float linear;
float angular;
float potential;
};
// Kinetic and gravitational potential energy summed over the bodies. Restitution samples
// use the total as the invariant that may only decrease.
MechanicalEnergy MeasureEnergy( b3WorldId worldId, const b3BodyId* bodyIds, int count );

View file

@ -8,6 +8,10 @@
#include "box3d/box3d.h"
#include <ctype.h>
#include <iterator>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
class Crash : public Sample
@ -132,65 +136,164 @@ public:
static int sampleMultiplePrismatic = RegisterSample( "Issues", "Multiple Prismatic", MultiplePrismatic::Create );
// bad hull SM_Waterfall_MED_Wide_01
static const b3Vec3 waterfallPoints[] = {
{ 0.100183107, -498.925385, -1275.39966 }, { 0.100183107, -498.925415, 0.125000000 },
{ 0.100183107, 486.343750, 0.125000000 }, { 0.100183107, 486.343719, -1275.39966 },
{ -395.117462, 486.343781, -1462.43750 }, { -395.117462, 486.343750, -96.7426758 },
{ -395.117462, -498.925415, -96.7424469 }, { -395.117462, -498.925446, -1462.52612 },
{ -186.979691, 486.294891, -1462.47949 }, { -298.250000, 486.294891, 0.125000000 },
{ -395.121216, 486.294891, -1462.52612 }, { -186.984360, -498.913361, -1462.48413 },
{ -298.250000, -498.913361, 0.125000000 },
};
static const b3Vec3 quadPoints[] = {
{ 100.000000, -142.292389, 130.826111 }, { 99.5354385, -71.3011093, 130.826111 },
{ 99.5930862, -80.1112213, -100.000000 }, { 100.000000, -142.292389, -100.000000 },
{ 99.5930862, -80.1112213, 130.826111 },
};
static const b3Vec3 thinBoxPoints[] = {
{ -11.3861933, -24.2451687, -12.0037909 }, { -11.3889809, -24.2466526, -11.9013014 },
{ -11.3804407, -24.3151531, -12.0046492 }, { -11.3832273, -24.3166409, -11.9021587 },
{ -14.4396200, -24.3636723, -12.1324549 }, { -14.4432650, -24.3655701, -12.0299988 },
{ -14.4356947, -24.4337788, -12.1336164 }, { -14.4393377, -24.4356804, -12.0311594 },
};
// Inline point sets are scaled from centimeters. A null point array is a file in data/hulls.
struct HullSource
{
const char* name;
const b3Vec3* points;
int count;
float scale;
};
static const HullSource hullSources[] = {
{ "waterfall", waterfallPoints, (int)std::size( waterfallPoints ), 0.01f },
{ "quad", quadPoints, (int)std::size( quadPoints ), 0.01f },
{ "thin box", thinBoxPoints, (int)std::size( thinBoxPoints ), 0.01f },
{ "axe.txt", nullptr, 0, 1.0f },
};
static constexpr int hullSourceCount = (int)std::size( hullSources );
// Reads x, y, z triples separated by commas or whitespace. A C source repro is
// also accepted: only the first initializer list is parsed, so counts and other
// numbers in the surrounding code are ignored.
static bool LoadHullPoints( const char* path, std::vector<b3Vec3>* points )
{
points->clear();
FILE* file = fopen( path, "rb" );
if ( file == nullptr )
{
fprintf( stderr, "Failed to open '%s'\n", path );
return false;
}
fseek( file, 0, SEEK_END );
long size = ftell( file );
fseek( file, 0, SEEK_SET );
if ( size < 0 )
{
fprintf( stderr, "Failed to read '%s'\n", path );
fclose( file );
return false;
}
std::vector<char> text( size + 1 );
size_t readCount = fread( text.data(), 1, size, file );
fclose( file );
text[readCount] = '\0';
char* begin = text.data();
char* end = begin + readCount;
for ( char* c = begin; *c != '\0'; ++c )
{
if ( *c != '{' )
{
continue;
}
char* prev = c - 1;
while ( prev >= begin && isspace( (unsigned char)*prev ) )
{
--prev;
}
if ( prev < begin || *prev != '=' )
{
continue;
}
begin = c + 1;
int depth = 1;
for ( end = begin; *end != '\0'; ++end )
{
if ( *end == '{' )
{
depth += 1;
}
else if ( *end == '}' && --depth == 0 )
{
break;
}
}
break;
}
*end = '\0';
std::vector<float> values;
char* cursor = begin;
while ( *cursor != '\0' )
{
char* stop;
float value = strtof( cursor, &stop );
if ( stop == cursor )
{
cursor += 1;
continue;
}
values.push_back( value );
cursor = stop;
}
if ( values.size() % 3 != 0 )
{
fprintf( stderr, "'%s' has %d values, not a multiple of 3\n", path, (int)values.size() );
}
int count = (int)values.size() / 3;
points->resize( count );
for ( int i = 0; i < count; ++i )
{
( *points )[i] = { values[3 * i], values[3 * i + 1], values[3 * i + 2] };
}
return count > 0;
}
class HullCrash : public Sample
{
public:
explicit HullCrash( SampleContext* context )
: Sample( context )
{
m_hull = nullptr;
m_sourceIndex = 3;
m_maxVertexCount = B3_MAX_HULL_VERTICES;
LoadPoints();
CreateHull();
if ( m_context->restart == false )
{
m_camera->SetView( 0.0f, 15.0f, 5.0f, b3Pos_zero );
FrameView();
}
m_hull = nullptr;
#if 0
// bad hull SM_Waterfall_MED_Wide_01
b3Vec3 points[] = {
{ 0.100183107, -498.925385, -1275.39966 }, { 0.100183107, -498.925415, 0.125000000 },
{ 0.100183107, 486.343750, 0.125000000 }, { 0.100183107, 486.343719, -1275.39966 },
{ -395.117462, 486.343781, -1462.43750 }, { -395.117462, 486.343750, -96.7426758 },
{ -395.117462, -498.925415, -96.7424469 }, { -395.117462, -498.925446, -1462.52612 },
{ -186.979691, 486.294891, -1462.47949 }, { -298.250000, 486.294891, 0.125000000 },
{ -395.121216, 486.294891, -1462.52612 }, { -186.984360, -498.913361, -1462.48413 },
{ -298.250000, -498.913361, 0.125000000 },
};
#elif 1
b3Vec3 points[] = {
{ 100.000000, -142.292389, 130.826111 }, { 99.5354385, -71.3011093, 130.826111 },
{ 99.5930862, -80.1112213, -100.000000 }, { 100.000000, -142.292389, -100.000000 },
{ 99.5930862, -80.1112213, 130.826111 },
};
#else
b3Vec3 points[] = {
{ -11.3861933, -24.2451687, -12.0037909 }, { -11.3889809, -24.2466526, -11.9013014 },
{ -11.3804407, -24.3151531, -12.0046492 }, { -11.3832273, -24.3166409, -11.9021587 },
{ -14.4396200, -24.3636723, -12.1324549 }, { -14.4432650, -24.3655701, -12.0299988 },
{ -14.4356947, -24.4337788, -12.1336164 }, { -14.4393377, -24.4356804, -12.0311594 },
};
#endif
static_assert( sizeof( points ) / sizeof( points[0] ) < m_capacity, "bad" );
m_count = sizeof( points ) / sizeof( points[0] );
for ( int i = 0; i < m_count; ++i )
{
m_points[i] = 0.01f * points[i];
}
// This shift shouldn't be necessary but I'm doing it so the hull
// appears on the screen.
// for ( int i = 0; i < m_count; ++i )
//{
// m_points[i] -= m_points[0];
// m_points[i] *= 0.01f;
//}
m_hull = b3CreateHull( m_points, m_count, m_count );
(void)m_hull;
}
~HullCrash() override
@ -201,6 +304,94 @@ public:
}
}
void LoadPoints()
{
const HullSource& source = hullSources[m_sourceIndex];
if ( source.points != nullptr )
{
m_points.assign( source.points, source.points + source.count );
}
else
{
char path[64];
snprintf( path, sizeof( path ), "data/hulls/%s", source.name );
LoadHullPoints( path, &m_points );
}
for ( b3Vec3& point : m_points )
{
point = source.scale * point;
}
// The reported failure used the point count as the limit
m_maxVertexCount = b3ClampInt( (int)m_points.size(), 4, B3_MAX_HULL_VERTICES );
}
void CreateHull()
{
if ( m_hull != nullptr )
{
b3DestroyHull( m_hull );
m_hull = nullptr;
}
int count = (int)m_points.size();
if ( count >= 4 )
{
m_hull = b3CreateHull( m_points.data(), count, m_maxVertexCount );
}
}
void FrameView()
{
if ( m_points.empty() )
{
return;
}
b3AABB bounds = b3MakeAABB( m_points.data(), (int)m_points.size(), 0.0f );
float radius = b3Length( b3AABB_Extents( bounds ) );
m_camera->SetView( 0.0f, 15.0f, b3MaxFloat( 3.0f * radius, 1.0f ), b3ToPos( b3AABB_Center( bounds ) ) );
}
bool DrawControls() override
{
DrawTextLine( "points = %d", (int)m_points.size() );
if ( m_hull != nullptr )
{
DrawTextLine( "hull: vertices = %d, edges = %d, faces = %d", m_hull->vertexCount, m_hull->edgeCount / 2,
m_hull->faceCount );
}
else
{
DrawTextLine( "hull creation failed" );
}
if ( ImGui::BeginCombo( "Source", hullSources[m_sourceIndex].name ) )
{
for ( int i = 0; i < hullSourceCount; ++i )
{
if ( ImGui::Selectable( hullSources[i].name, i == m_sourceIndex ) )
{
m_sourceIndex = i;
LoadPoints();
CreateHull();
FrameView();
}
}
ImGui::EndCombo();
}
if ( ImGui::SliderInt( "Max Vertices", &m_maxVertexCount, 4, B3_MAX_HULL_VERTICES ) )
{
CreateHull();
}
return true;
}
void Render() override
{
if ( m_hull != nullptr )
@ -209,9 +400,9 @@ public:
}
else
{
for ( int i = 0; i < m_count; ++i )
for ( const b3Vec3& point : m_points )
{
DrawPoint( b3ToPos( m_points[i] ), 5.0f, MakeColor( b3_colorWhite ) );
DrawPoint( b3ToPos( point ), 5.0f, MakeColor( b3_colorWhite ) );
}
}
@ -225,10 +416,10 @@ public:
return new HullCrash( sampleContext );
}
static constexpr int m_capacity = 64;
std::vector<b3Vec3> m_points;
b3HullData* m_hull;
b3Vec3 m_points[m_capacity];
int m_count;
int m_sourceIndex;
int m_maxVertexCount;
};
static int sampleHullCrash = RegisterSample( "Issues", "Hull Crash", HullCrash::Create );
@ -1146,6 +1337,7 @@ public:
static int sampleWheelStack = RegisterSample( "Issues", "GMod Wheel Stack", WheelStack::Create );
// There was a problem where this bouncing box could gain energy. This has been fixed by the deferred restitution update.
class RestitutionOvershoot : public Sample
{
public:
@ -1176,6 +1368,7 @@ public:
b3BodyDef boxDef = b3DefaultBodyDef();
boxDef.type = b3_dynamicBody;
boxDef.position = { 0.0f, m_dropHeight, 0.0f };
boxDef.safetyFactor = 0.1f;
m_boxBody = b3CreateBody( m_worldId, &boxDef );
b3ShapeDef boxShape = b3DefaultShapeDef();
@ -1186,6 +1379,9 @@ public:
m_maxBounceY = 0.0f;
m_bounced = false;
m_failed = false;
m_startEnergy = MeasureEnergy( m_worldId, &m_boxBody, 1 ).Total();
m_maxEnergy = m_startEnergy;
m_energyFailed = false;
}
void Step() override
@ -1221,9 +1417,29 @@ public:
b3Pos markerPoint = { 0.0f, m_dropHeight + m_boxHalf, 0.0f };
DrawPlane( b3Vec3_axisY, markerPoint, MakeColor( b3_colorYellow ) );
// Perfect restitution and no friction, so the total energy may only decrease. It is the honest
// invariant here: the height check cannot tell a bounce that gained potential energy from one
// that converted it into spin, and this drop does both.
MechanicalEnergy energy = MeasureEnergy( m_worldId, &m_boxBody, 1 );
float total = energy.Total();
if ( total > m_maxEnergy )
{
m_maxEnergy = total;
}
if ( m_bounced && total > m_startEnergy * ( 1.0f + m_energyTolerance ) )
{
m_energyFailed = true;
}
DrawTextLine( "drop height = %.2f m", m_dropHeight );
DrawTextLine( "current y = %.2f m", m_currentY );
DrawTextLine( "max bounce = %.2f m", m_maxBounceY );
DrawTextLine( "kinetic = %.0f J linear + %.0f J angular", energy.linear, energy.angular );
DrawTextLine( "potential = %.0f J", energy.potential );
DrawTextLine( "total = %.0f J (%.2f%% of start, peak %.2f%%)", total, 100.0f * total / m_startEnergy,
100.0f * m_maxEnergy / m_startEnergy );
if ( m_bounced == false )
{
@ -1237,6 +1453,15 @@ public:
{
DrawTextLine( "PASS: bounce stays at or below drop height" );
}
if ( m_energyFailed )
{
DrawTextLine( "FAIL: total energy increased" );
}
else if ( m_bounced )
{
DrawTextLine( "PASS: total energy did not increase" );
}
}
static Sample* Create( SampleContext* context )
@ -1244,11 +1469,16 @@ public:
return new RestitutionOvershoot( context );
}
static constexpr float m_energyTolerance = 0.001f;
b3BodyId m_boxBody = {};
float m_currentY = 0.0f;
float m_maxBounceY = 0.0f;
float m_startEnergy = 0.0f;
float m_maxEnergy = 0.0f;
bool m_bounced = false;
bool m_failed = false;
bool m_energyFailed = false;
};
static int sampleRestitutionOvershoot = RegisterSample( "Issues", "Restitution Overshoot", RestitutionOvershoot::Create );

View file

@ -1,6 +1,7 @@
// SPDX-FileCopyrightText: 2025 Erin Catto
// SPDX-License-Identifier: MIT
#include "gfx/debug_adapter.h"
#include "gfx/draw.h"
#include "human.h"
#include "imgui.h"
@ -336,6 +337,528 @@ public:
static int sampleRestitution = RegisterSample( "Shapes", "Restitution", Restitution::Create );
// Similar to the MeasureSupportedBounce unit test
class SphereStackRestitution : public Sample
{
public:
static constexpr float m_impactSpeed = 5.0f;
static constexpr int m_maxStackCount = 3;
explicit SphereStackRestitution( SampleContext* context )
: Sample( context )
{
if ( context->restart == false )
{
m_camera->SetView( 20.0f, 10.0f, 12.0f, { 0.0f, 2.5f, 0.0f } );
}
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { 0.0f, -1.0f, 0.0f };
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = 0.0f;
b3BoxHull box = b3MakeBoxHull( 40.0f, 1.0f, 40.0f );
b3ShapeId groundShapeId = b3CreateHullShape( groundId, &shapeDef, &box.base );
SetGroundShape( groundShapeId );
CreateScene();
}
b3BodyId CreateBall( float y, float velocityY, float restitution, bool hitEvents )
{
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { 0.0f, y, 0.0f };
bodyDef.linearVelocity = { 0.0f, velocityY, 0.0f };
bodyDef.enableSleep = false;
b3BodyId bodyId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = restitution;
shapeDef.enableHitEvents = hitEvents;
b3Sphere sphere = { b3Vec3_zero, 0.5f };
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
return bodyId;
}
void CreateScene()
{
for ( int i = 0; i < m_bodyCount; ++i )
{
b3DestroyBody( m_bodyIds[i] );
}
m_bodyCount = 0;
if ( m_gravity )
{
b3World_SetGravity( m_worldId, { 0.0f, -10.0f, 0.0f } );
}
else
{
b3World_SetGravity( m_worldId, b3Vec3_zero );
}
for ( int i = 0; i < m_stackCount; ++i )
{
m_bodyIds[m_bodyCount] = CreateBall( 0.5f + 1.0f * i, 0.0f, 0.0f, false );
m_bodyCount += 1;
}
// Start half a step of travel above contact so the impact lands mid step, matching the test
m_startHeight = 0.5f + 1.0f * m_stackCount + 0.5f * m_impactSpeed * ( 1.0f / 60.0f );
m_impactorId = CreateBall( m_startHeight, -m_impactSpeed, m_restitution, true );
m_bodyIds[m_bodyCount] = m_impactorId;
m_bodyCount += 1;
m_startEnergy = MeasureEnergy( m_worldId, m_bodyIds, m_bodyCount ).Total();
m_peakEnergy = m_startEnergy;
m_coefficient = 0.0f;
m_latched = false;
m_hit = false;
}
bool DrawControls() override
{
bool rebuild = false;
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
if ( ImGui::SliderFloat( "Restitution", &m_restitution, 0.0f, 1.0f, "%.2f" ) )
{
rebuild = true;
}
if ( ImGui::SliderInt( "Stack", &m_stackCount, 0, m_maxStackCount ) )
{
rebuild = true;
}
ImGui::PopItemWidth();
if ( ImGui::Checkbox( "Gravity", &m_gravity ) )
{
rebuild = true;
}
if ( ImGui::Button( "Reset" ) )
{
rebuild = true;
}
if ( rebuild )
{
CreateScene();
}
return true;
}
void Step() override
{
Sample::Step();
b3ContactEvents events = b3World_GetContactEvents( m_worldId );
if ( events.hitCount > 0 )
{
m_hit = true;
}
float vy = b3Body_GetLinearVelocity( m_impactorId ).y;
// The rebound only means something once the impact has happened and the impactor is leaving
if ( m_latched == false && m_hit && vy > 0.0f )
{
m_coefficient = vy / m_impactSpeed;
m_latched = true;
}
float supportSpeed = 0.0f;
for ( int i = 0; i < m_stackCount; ++i )
{
supportSpeed = b3MaxFloat( supportSpeed, b3Length( b3Body_GetLinearVelocity( m_bodyIds[i] ) ) );
}
DrawLine( { -2.0f, m_startHeight, 0.0f }, { 2.0f, m_startHeight, 0.0f }, MakeColor( b3_colorRed ) );
MechanicalEnergy energy = MeasureEnergy( m_worldId, m_bodyIds, m_bodyCount );
float total = energy.Total();
m_peakEnergy = b3MaxFloat( m_peakEnergy, total );
DrawTextLine( "impactor vy = %.3f m/s", vy );
DrawTextLine( "coefficient = %.4f live (target %.2f)", vy / m_impactSpeed, m_restitution );
if ( m_latched )
{
DrawTextLine( "coefficient = %.4f at first rebound", m_coefficient );
}
DrawTextLine( "support speed = %.4f m/s", supportSpeed );
float scale = m_startEnergy != 0.0f ? 100.0f / m_startEnergy : 0.0f;
DrawTextLine( "kinetic = %.3f J linear + %.3f J angular", energy.linear, energy.angular );
DrawTextLine( "potential = %.3f J", energy.potential );
DrawTextLine( "total = %.3f J (%.2f%% of start, peak %.2f%%)", total, scale * total, scale * m_peakEnergy );
}
static Sample* Create( SampleContext* context )
{
return new SphereStackRestitution( context );
}
b3BodyId m_bodyIds[m_maxStackCount + 1] = {};
b3BodyId m_impactorId = b3_nullBodyId;
int m_bodyCount = 0;
int m_stackCount = 2;
float m_restitution = 1.0f;
float m_startHeight = 0.0f;
float m_coefficient = 0.0f;
float m_startEnergy = 0.0f;
float m_peakEnergy = 0.0f;
bool m_gravity = false;
bool m_latched = false;
bool m_hit = false;
};
static int sampleSphereStackRestitution = RegisterSample( "Shapes", "Sphere Stack Restitution", SphereStackRestitution::Create );
// Similar to the MeasureFlatBounce and SpinTest unit tests
class BoxRestitution : public Sample
{
public:
static constexpr float m_impactSpeed = 5.0f;
explicit BoxRestitution( SampleContext* context )
: Sample( context )
{
if ( context->restart == false )
{
m_camera->SetView( 20.0f, 10.0f, 14.0f, { 0.0f, 3.0f, 0.0f } );
}
// Gravity would bias the measured coefficient
b3World_SetGravity( m_worldId, b3Vec3_zero );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { 0.0f, -1.0f, 0.0f };
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = 0.0f;
b3BoxHull box = b3MakeBoxHull( 40.0f, 1.0f, 40.0f );
b3ShapeId groundShapeId = b3CreateHullShape( groundId, &shapeDef, &box.base );
SetGroundShape( groundShapeId );
CreateScene();
}
void CreateScene()
{
if ( B3_IS_NON_NULL( m_boxId ) )
{
b3DestroyBody( m_boxId );
}
// Start half a step of travel above contact so the impact lands mid step, matching the test
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { 0.0f, 0.25f + 0.5f * m_impactSpeed * ( 1.0f / 60.0f ), 0.0f };
bodyDef.linearVelocity = { 0.0f, -m_impactSpeed, 0.0f };
bodyDef.angularVelocity = { 0.0f, 0.0f, m_spin };
bodyDef.enableSleep = false;
m_boxId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = m_restitution;
shapeDef.enableHitEvents = true;
b3BoxHull box = b3MakeBoxHull( 1.0f, 0.25f, 1.0f );
b3CreateHullShape( m_boxId, &shapeDef, &box.base );
m_startEnergy = MeasureEnergy( m_worldId, &m_boxId, 1 ).Total();
m_peakEnergy = m_startEnergy;
m_coefficient = 0.0f;
m_latched = false;
m_hit = false;
}
bool DrawControls() override
{
bool rebuild = false;
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
if ( ImGui::SliderFloat( "Restitution", &m_restitution, 0.0f, 1.0f, "%.2f" ) )
{
rebuild = true;
}
if ( ImGui::SliderFloat( "Spin", &m_spin, 0.0f, 2.0f, "%.2f" ) )
{
rebuild = true;
}
ImGui::PopItemWidth();
if ( ImGui::Button( "Reset" ) )
{
rebuild = true;
}
if ( rebuild )
{
CreateScene();
}
return true;
}
void Step() override
{
Sample::Step();
b3ContactEvents events = b3World_GetContactEvents( m_worldId );
if ( events.hitCount > 0 )
{
m_hit = true;
}
float vy = b3Body_GetLinearVelocity( m_boxId ).y;
b3Vec3 w = b3Body_GetAngularVelocity( m_boxId );
if ( m_latched == false && m_hit && vy > 0.0f )
{
m_coefficient = vy / m_impactSpeed;
m_latched = true;
}
Vec4 yellow = MakeColor( b3_colorYellow );
DrawPoint( b3Body_GetWorldPoint( m_boxId, { -1.0f, -0.25f, -1.0f } ), 8.0f, yellow );
DrawPoint( b3Body_GetWorldPoint( m_boxId, { 1.0f, -0.25f, -1.0f } ), 8.0f, yellow );
DrawPoint( b3Body_GetWorldPoint( m_boxId, { -1.0f, -0.25f, 1.0f } ), 8.0f, yellow );
DrawPoint( b3Body_GetWorldPoint( m_boxId, { 1.0f, -0.25f, 1.0f } ), 8.0f, yellow );
MechanicalEnergy energy = MeasureEnergy( m_worldId, &m_boxId, 1 );
float total = energy.Total();
m_peakEnergy = b3MaxFloat( m_peakEnergy, total );
DrawTextLine( "vy = %.3f m/s", vy );
DrawTextLine( "coefficient = %.4f live (target %.2f)", vy / m_impactSpeed, m_restitution );
if ( m_latched )
{
DrawTextLine( "coefficient = %.4f at first rebound", m_coefficient );
}
// The spin is about z, so any x or y component is residual from the sequential point solve
DrawTextLine( "spin in = %.2f, spin out = %.4f (ideal %.2f at e = 1)", m_spin, w.z, -m_spin );
DrawTextLine( "off axis spin = %.4f rad/s", sqrtf( w.x * w.x + w.y * w.y ) );
float scale = m_startEnergy != 0.0f ? 100.0f / m_startEnergy : 0.0f;
DrawTextLine( "kinetic = %.3f J linear + %.3f J angular", energy.linear, energy.angular );
DrawTextLine( "potential = %.3f J", energy.potential );
DrawTextLine( "total = %.3f J (%.2f%% of start, peak %.2f%%)", total, scale * total, scale * m_peakEnergy );
}
static Sample* Create( SampleContext* context )
{
return new BoxRestitution( context );
}
b3BodyId m_boxId = b3_nullBodyId;
float m_restitution = 0.9f;
float m_spin = 0.0f;
float m_coefficient = 0.0f;
float m_startEnergy = 0.0f;
float m_peakEnergy = 0.0f;
bool m_latched = false;
bool m_hit = false;
};
static int sampleBoxRestitution = RegisterSample( "Shapes", "Box Restitution", BoxRestitution::Create );
// Similar to the ImpulseTest unit test. The hit event marks the bounce and carries the approach speed,
// so the impulse the contact reports can be checked against reversing that speed at the coefficient.
// The total runs a little over because the contact also carries the weight for the part of the step
// it is active.
class BounceImpulse : public Sample
{
public:
explicit BounceImpulse( SampleContext* context )
: Sample( context )
{
if ( context->restart == false )
{
m_camera->SetView( 20.0f, 10.0f, 36.0f, { 0.0f, 8.0f, 0.0f } );
}
b3World_SetGravity( m_worldId, { 0.0f, -10.0f, 0.0f } );
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.position = { 0.0f, -1.0f, 0.0f };
b3BodyId groundId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = 0.0f;
b3BoxHull box = b3MakeBoxHull( 40.0f, 1.0f, 40.0f );
b3ShapeId groundShapeId = b3CreateHullShape( groundId, &shapeDef, &box.base );
SetGroundShape( groundShapeId );
CreateScene();
}
void CreateScene()
{
if ( B3_IS_NON_NULL( m_ballId ) )
{
b3DestroyBody( m_ballId );
}
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = b3_dynamicBody;
bodyDef.position = { 0.0f, 0.5f + m_dropHeight, 0.0f };
bodyDef.enableSleep = false;
m_ballId = b3CreateBody( m_worldId, &bodyDef );
b3ShapeDef shapeDef = b3DefaultShapeDef();
shapeDef.baseMaterial.friction = 0.0f;
shapeDef.baseMaterial.restitution = m_restitution;
shapeDef.enableHitEvents = true;
b3Sphere sphere = { b3Vec3_zero, 0.5f };
b3CreateSphereShape( m_ballId, &shapeDef, &sphere );
m_mass = b3Body_GetMass( m_ballId );
m_approachSpeed = 0.0f;
m_totalImpulse = 0.0f;
m_expectedImpulse = 0.0f;
m_contactSteps = 0;
m_hit = false;
m_bouncing = false;
}
bool DrawControls() override
{
bool rebuild = false;
ImGui::PushItemWidth( 6.0f * ImGui::GetFontSize() );
if ( ImGui::SliderFloat( "Restitution", &m_restitution, 0.0f, 1.0f, "%.2f" ) )
{
rebuild = true;
}
if ( ImGui::SliderFloat( "Height", &m_dropHeight, 0.5f, 50.0f, "%.1f" ) )
{
rebuild = true;
}
ImGui::PopItemWidth();
if ( ImGui::Button( "Reset" ) )
{
rebuild = true;
}
if ( rebuild )
{
CreateScene();
}
return true;
}
void Step() override
{
Sample::Step();
if ( m_didStep )
{
b3ContactEvents events = b3World_GetContactEvents( m_worldId );
if ( m_hit == false && events.hitCount > 0 )
{
m_hit = true;
m_bouncing = true;
m_approachSpeed = events.hitEvents[0].approachSpeed;
m_expectedImpulse = ( 1.0f + m_restitution ) * m_mass * m_approachSpeed;
}
// Keep summing until the contact lets go, a slow bounce can take a few steps to leave
if ( m_bouncing )
{
b3ContactData contactData[4];
int contactCount = b3Body_GetContactData( m_ballId, contactData, 4 );
for ( int c = 0; c < contactCount; ++c )
{
for ( int m = 0; m < contactData[c].manifoldCount; ++m )
{
const b3Manifold* manifold = contactData[c].manifolds + m;
for ( int p = 0; p < manifold->pointCount; ++p )
{
m_totalImpulse += manifold->points[p].totalNormalImpulse;
}
}
}
if ( contactCount > 0 )
{
m_contactSteps += 1;
}
else
{
m_bouncing = false;
}
}
}
float startHeight = 0.5f + m_dropHeight;
DrawLine( { -2.0f, startHeight, 0.0f }, { 2.0f, startHeight, 0.0f }, MakeColor( b3_colorRed ) );
DrawTextLine( "vy = %.3f m/s", b3Body_GetLinearVelocity( m_ballId ).y );
if ( m_hit )
{
DrawTextLine( "approach speed = %.3f m/s", m_approachSpeed );
DrawTextLine( "total impulse = %.2f N s over %d steps", m_totalImpulse, m_contactSteps );
DrawTextLine( "expected impulse = %.2f N s", m_expectedImpulse );
}
else
{
DrawTextLine( "waiting for the hit" );
}
}
static Sample* Create( SampleContext* context )
{
return new BounceImpulse( context );
}
b3BodyId m_ballId = b3_nullBodyId;
float m_restitution = 0.5f;
float m_dropHeight = 20.0f;
float m_mass = 0.0f;
float m_approachSpeed = 0.0f;
float m_totalImpulse = 0.0f;
float m_expectedImpulse = 0.0f;
int m_contactSteps = 0;
bool m_hit = false;
bool m_bouncing = false;
};
static int sampleBounceImpulse = RegisterSample( "Shapes", "Bounce Impulse", BounceImpulse::Create );
// This shows an optimization when creating many static shapes you can skip having them invoke collision, assuming
// dynamic bodies are added after the static bodies.
class StaticInvoke : public Sample