Reduce ghosts (#212)
Full ghost collision handling for sphere, capsule, and hull versus a single mesh or heightfield. This requires mesh to be built with edge identification. Optimized mesh builder. Removed B3_MAX_MESH_CONTACT_TRIANGLES. You will still hit performance problems for dense meshes. Fixes #184
This commit is contained in:
parent
3362633204
commit
38f2ae1e19
61 changed files with 17756 additions and 1492 deletions
|
|
@ -5,8 +5,14 @@ set(BOX3D_SHARED_FILES
|
|||
benchmarks.h
|
||||
determinism.c
|
||||
determinism.h
|
||||
ghost_collisions.c
|
||||
ghost_collisions.h
|
||||
ghost_oracle.c
|
||||
ghost_oracle.h
|
||||
human.c
|
||||
human.h
|
||||
mesh_drop.c
|
||||
mesh_drop.h
|
||||
overflow_color.c
|
||||
overflow_color.h
|
||||
stability.c
|
||||
|
|
|
|||
867
shared/ghost_collisions.c
Normal file
867
shared/ghost_collisions.c
Normal file
|
|
@ -0,0 +1,867 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "ghost_collisions.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define GHOST_HALF_LENGTH 20.0f
|
||||
#define GHOST_HALF_WIDTH 3.0f
|
||||
#define GHOST_START_X -16.0f
|
||||
|
||||
// The rail deflects the body sideways and the floor is frictionless, so a narrow floor ends the run off
|
||||
// the side instead of at the far end
|
||||
#define GHOST_RAIL_HALF_LENGTH ( 0.5f * GHOST_HALF_LENGTH )
|
||||
#define GHOST_RAIL_HALF_WIDTH ( 2.0f * GHOST_HALF_WIDTH )
|
||||
|
||||
// A run takes about 144 steps, clear of 150 where the 900 step scan would flip between 5 and 6 runs
|
||||
#define GHOST_RAIL_START_X -5.3f
|
||||
|
||||
// A 34 degree chamfer like the s&box beams
|
||||
#define GHOST_CHAMFER_WIDTH 0.05f
|
||||
#define GHOST_CHAMFER_DROP ( GHOST_CHAMFER_WIDTH / 1.5f )
|
||||
|
||||
#define GHOST_RAIL_SKIRT 0.4f
|
||||
|
||||
typedef struct PeelPreset
|
||||
{
|
||||
int columnCount;
|
||||
float scaleX;
|
||||
float startZ;
|
||||
} PeelPreset;
|
||||
|
||||
static const PeelPreset s_peelPresets[GHOST_PEEL_PRESET_COUNT] = {
|
||||
{ 4, 0.1f, -55.0f },
|
||||
{ 4, 0.1f, -54.0f },
|
||||
{ 4, 0.01f, -55.0f },
|
||||
{ 16, 0.01f, -54.0f },
|
||||
};
|
||||
|
||||
const char* g_ghostSceneNames[e_ghostSceneCount] = {
|
||||
"Flat", "Concave", "Cliff", "Crest", "Bumps", "Internal", "Chamfer", "Rail",
|
||||
};
|
||||
|
||||
const char* g_ghostBodyNames[e_ghostBodyCount] = { "Box", "H Capsule", "V Capsule", "Sphere", "Cylinder" };
|
||||
|
||||
const char* g_ghostPeelPresetNames[GHOST_PEEL_PRESET_COUNT] = {
|
||||
"4.1:-55",
|
||||
"4.1:-54",
|
||||
"4.01:-55",
|
||||
"16.01:-54",
|
||||
};
|
||||
|
||||
GhostSettings GetDefaultGhostSettings( void )
|
||||
{
|
||||
GhostSettings settings = {
|
||||
.scene = e_ghostFlat,
|
||||
.body = e_ghostBox,
|
||||
.peelPreset = 0,
|
||||
.mirror = false,
|
||||
.heightField = false,
|
||||
.cellSize = 0.25f,
|
||||
.speed = 6.0f,
|
||||
.yaw = 0.0f,
|
||||
.friction = 0.0f,
|
||||
.fixedRotation = false,
|
||||
.speculative = true,
|
||||
};
|
||||
return settings;
|
||||
}
|
||||
|
||||
typedef struct MeshBuilder
|
||||
{
|
||||
b3Vec3* vertices;
|
||||
int vertexCount;
|
||||
int32_t* indices;
|
||||
int indexCount;
|
||||
} MeshBuilder;
|
||||
|
||||
// The profile runs in +x with the solid below it. The mirror flips x in the data and the mesh
|
||||
// scale flips it back, so the world geometry is the same either way.
|
||||
static void AddGrid( MeshBuilder* builder, const b3Vec2* points, int pointCount, float halfWidth, int zCount, bool alternate,
|
||||
bool mirror )
|
||||
{
|
||||
float sign = mirror ? -1.0f : 1.0f;
|
||||
int stride = zCount + 1;
|
||||
int base = builder->vertexCount;
|
||||
|
||||
builder->vertices = realloc( builder->vertices, ( builder->vertexCount + pointCount * stride ) * sizeof( b3Vec3 ) );
|
||||
for ( int i = 0; i < pointCount; ++i )
|
||||
{
|
||||
for ( int j = 0; j <= zCount; ++j )
|
||||
{
|
||||
float z = -halfWidth + 2.0f * halfWidth * (float)j / (float)zCount;
|
||||
builder->vertices[builder->vertexCount++] = (b3Vec3){ sign * points[i].x, points[i].y, z };
|
||||
}
|
||||
}
|
||||
|
||||
int triangleCount = 2 * ( pointCount - 1 ) * zCount;
|
||||
builder->indices = realloc( builder->indices, ( builder->indexCount + 3 * triangleCount ) * sizeof( int32_t ) );
|
||||
for ( int i = 0; i + 1 < pointCount; ++i )
|
||||
{
|
||||
for ( int j = 0; j < zCount; ++j )
|
||||
{
|
||||
int a = base + i * stride + j;
|
||||
int b = a + 1;
|
||||
int c = a + stride + 1;
|
||||
int d = a + stride;
|
||||
|
||||
int corners[6] = { a, b, c, c, d, a };
|
||||
|
||||
// Alternate the diagonal like cooked level geometry
|
||||
if ( alternate && ( ( i + j ) & 1 ) )
|
||||
{
|
||||
int flipped[6] = { a, b, d, b, c, d };
|
||||
memcpy( corners, flipped, sizeof( corners ) );
|
||||
}
|
||||
|
||||
for ( int k = 0; k < 6; k += 3 )
|
||||
{
|
||||
builder->indices[builder->indexCount++] = corners[k];
|
||||
builder->indices[builder->indexCount++] = mirror ? corners[k + 2] : corners[k + 1];
|
||||
builder->indices[builder->indexCount++] = mirror ? corners[k + 1] : corners[k + 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void AddStrip( MeshBuilder* builder, const b3Vec2* profile, int count, float cellSize, float zCell, bool mirror )
|
||||
{
|
||||
int pointCount = 1;
|
||||
for ( int k = 0; k + 1 < count; ++k )
|
||||
{
|
||||
b3Vec2 a = profile[k];
|
||||
b3Vec2 b = profile[k + 1];
|
||||
float length = sqrtf( ( b.x - a.x ) * ( b.x - a.x ) + ( b.y - a.y ) * ( b.y - a.y ) );
|
||||
pointCount += b3MaxInt( 1, (int)ceilf( length / cellSize - 0.01f ) );
|
||||
}
|
||||
|
||||
b3Vec2* points = malloc( pointCount * sizeof( b3Vec2 ) );
|
||||
int index = 0;
|
||||
points[index++] = profile[0];
|
||||
for ( int k = 0; k + 1 < count; ++k )
|
||||
{
|
||||
b3Vec2 a = profile[k];
|
||||
b3Vec2 b = profile[k + 1];
|
||||
float length = sqrtf( ( b.x - a.x ) * ( b.x - a.x ) + ( b.y - a.y ) * ( b.y - a.y ) );
|
||||
int n = b3MaxInt( 1, (int)ceilf( length / cellSize - 0.01f ) );
|
||||
for ( int s = 1; s <= n; ++s )
|
||||
{
|
||||
float t = (float)s / (float)n;
|
||||
points[index++] = (b3Vec2){ a.x + t * ( b.x - a.x ), a.y + t * ( b.y - a.y ) };
|
||||
}
|
||||
}
|
||||
|
||||
int zCount = b3MaxInt( 1, (int)ceilf( 2.0f * GHOST_HALF_WIDTH / zCell - 0.01f ) );
|
||||
AddGrid( builder, points, pointCount, GHOST_HALF_WIDTH, zCount, true, mirror );
|
||||
free( points );
|
||||
}
|
||||
|
||||
// The rail cross section is a profile in zy extruded along x. Each quad side is its edge direction along
|
||||
// the section crossed with x, which is the outward normal for a section traversed with air on the left.
|
||||
static void AddRail( MeshBuilder* builder, const b3Vec2* section, int count, float halfLength, float cellSize, bool mirror )
|
||||
{
|
||||
float sign = mirror ? -1.0f : 1.0f;
|
||||
int xCount = b3MaxInt( 1, (int)ceilf( 2.0f * halfLength / cellSize - 0.01f ) );
|
||||
int stride = xCount + 1;
|
||||
|
||||
int pointCount = 1;
|
||||
for ( int k = 0; k + 1 < count; ++k )
|
||||
{
|
||||
float dz = section[k + 1].x - section[k].x;
|
||||
float dy = section[k + 1].y - section[k].y;
|
||||
pointCount += b3MaxInt( 1, (int)ceilf( sqrtf( dz * dz + dy * dy ) / cellSize - 0.01f ) );
|
||||
}
|
||||
|
||||
builder->vertices = realloc( builder->vertices, pointCount * stride * sizeof( b3Vec3 ) );
|
||||
int index = 0;
|
||||
for ( int k = 0; k < count; ++k )
|
||||
{
|
||||
int n = 1;
|
||||
if ( k + 1 < count )
|
||||
{
|
||||
float dz = section[k + 1].x - section[k].x;
|
||||
float dy = section[k + 1].y - section[k].y;
|
||||
n = b3MaxInt( 1, (int)ceilf( sqrtf( dz * dz + dy * dy ) / cellSize - 0.01f ) );
|
||||
}
|
||||
|
||||
// The last point only closes the final segment
|
||||
int last = k + 1 < count ? n : 1;
|
||||
for ( int s = 0; s < last; ++s )
|
||||
{
|
||||
float t = k + 1 < count ? (float)s / (float)n : 0.0f;
|
||||
b3Vec2 a = section[k];
|
||||
b3Vec2 b = k + 1 < count ? section[k + 1] : a;
|
||||
float z = a.x + t * ( b.x - a.x );
|
||||
float y = a.y + t * ( b.y - a.y );
|
||||
for ( int j = 0; j <= xCount; ++j )
|
||||
{
|
||||
float x = -halfLength + 2.0f * halfLength * (float)j / (float)xCount;
|
||||
builder->vertices[index++] = (b3Vec3){ sign * x, y, z };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
builder->vertexCount = index;
|
||||
|
||||
int triangleCount = 2 * ( pointCount - 1 ) * xCount;
|
||||
builder->indices = realloc( builder->indices, 3 * triangleCount * sizeof( int32_t ) );
|
||||
builder->indexCount = 0;
|
||||
for ( int i = 0; i + 1 < pointCount; ++i )
|
||||
{
|
||||
for ( int j = 0; j < xCount; ++j )
|
||||
{
|
||||
int a = i * stride + j;
|
||||
int b = a + 1;
|
||||
int c = a + stride + 1;
|
||||
int d = a + stride;
|
||||
|
||||
int corners[6] = { a, d, c, c, b, a };
|
||||
if ( ( i + j ) & 1 )
|
||||
{
|
||||
int flipped[6] = { a, d, b, d, c, b };
|
||||
memcpy( corners, flipped, sizeof( corners ) );
|
||||
}
|
||||
|
||||
for ( int k = 0; k < 6; k += 3 )
|
||||
{
|
||||
builder->indices[builder->indexCount++] = corners[k];
|
||||
builder->indices[builder->indexCount++] = mirror ? corners[k + 2] : corners[k + 1];
|
||||
builder->indices[builder->indexCount++] = mirror ? corners[k + 1] : corners[k + 2];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static float EvaluateRail( float z, float cellZ )
|
||||
{
|
||||
if ( z < -0.5f * cellZ )
|
||||
{
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
return z < 0.5f * cellZ ? GHOST_RAIL_HEIGHT : -GHOST_RAIL_SKIRT;
|
||||
}
|
||||
|
||||
static void AddMesh( GhostCollisionsData* data, MeshBuilder* builder, bool frictionless )
|
||||
{
|
||||
b3MeshDef meshDef = { 0 };
|
||||
meshDef.vertices = builder->vertices;
|
||||
meshDef.indices = builder->indices;
|
||||
meshDef.vertexCount = builder->vertexCount;
|
||||
meshDef.triangleCount = builder->indexCount / 3;
|
||||
meshDef.weldVertices = true;
|
||||
meshDef.weldTolerance = 0.001f;
|
||||
meshDef.identifyEdges = true;
|
||||
|
||||
b3MeshData* mesh = b3CreateMesh( &meshDef, NULL, 0 );
|
||||
data->meshes[data->meshCount++] = mesh;
|
||||
|
||||
b3Vec3 scale = data->settings.mirror ? (b3Vec3){ -1.0f, 1.0f, 1.0f } : b3Vec3_one;
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
if ( frictionless )
|
||||
{
|
||||
shapeDef.baseMaterial.friction = 0.0f;
|
||||
}
|
||||
b3CreateMeshShape( data->groundId, &shapeDef, mesh, scale );
|
||||
|
||||
builder->vertexCount = 0;
|
||||
builder->indexCount = 0;
|
||||
}
|
||||
|
||||
// The bodies holding height field shapes must go first
|
||||
static void DestroyGhostGroundData( GhostCollisionsData* data )
|
||||
{
|
||||
for ( int i = 0; i < data->meshCount; ++i )
|
||||
{
|
||||
b3DestroyMesh( data->meshes[i] );
|
||||
data->meshes[i] = NULL;
|
||||
}
|
||||
data->meshCount = 0;
|
||||
|
||||
for ( int i = 0; i < data->heightFieldCount; ++i )
|
||||
{
|
||||
b3DestroyHeightField( data->heightFields[i] );
|
||||
data->heightFields[i] = NULL;
|
||||
}
|
||||
data->heightFieldCount = 0;
|
||||
}
|
||||
|
||||
static void PushProfile( GhostCollisionsData* data, float x, float y )
|
||||
{
|
||||
if ( data->profileCount < GHOST_MAX_PROFILE_POINTS )
|
||||
{
|
||||
data->profile[data->profileCount++] = (b3Vec2){ x, y };
|
||||
}
|
||||
}
|
||||
|
||||
// The profile is a function of x, a vertical step has two points at the same x
|
||||
static float EvaluateProfile( const GhostCollisionsData* data, float x )
|
||||
{
|
||||
const b3Vec2* profile = data->profile;
|
||||
int count = data->profileCount;
|
||||
for ( int k = 0; k + 1 < count; ++k )
|
||||
{
|
||||
if ( x <= profile[k + 1].x )
|
||||
{
|
||||
float dx = profile[k + 1].x - profile[k].x;
|
||||
float t = dx > 0.0f ? b3ClampFloat( ( x - profile[k].x ) / dx, 0.0f, 1.0f ) : 1.0f;
|
||||
return profile[k].y + t * ( profile[k + 1].y - profile[k].y );
|
||||
}
|
||||
}
|
||||
|
||||
return profile[count - 1].y;
|
||||
}
|
||||
|
||||
static int GetCellCount( float length, float cellSize )
|
||||
{
|
||||
return b3MaxInt( 1, (int)ceilf( length / cellSize - 0.01f ) );
|
||||
}
|
||||
|
||||
// Samples the profile on a grid spanning x0 to x1. The mirror samples in reverse and turns the body half
|
||||
// way around y, so the world geometry is the same either way. All tiles of a scene share one height range
|
||||
// so their quantized heights line up at a seam.
|
||||
static void AddHeightField( b3WorldId worldId, GhostCollisionsData* data, float x0, float x1, int cellCountX, float halfWidth,
|
||||
int cellCountZ, bool frictionless )
|
||||
{
|
||||
float minHeight = FLT_MAX;
|
||||
float maxHeight = -FLT_MAX;
|
||||
for ( int k = 0; k < data->profileCount; ++k )
|
||||
{
|
||||
minHeight = b3MinFloat( minHeight, data->profile[k].y );
|
||||
maxHeight = b3MaxFloat( maxHeight, data->profile[k].y );
|
||||
}
|
||||
|
||||
bool mirror = data->settings.mirror;
|
||||
int countX = cellCountX + 1;
|
||||
int countZ = cellCountZ + 1;
|
||||
float cellX = ( x1 - x0 ) / (float)cellCountX;
|
||||
float cellZ = 2.0f * halfWidth / (float)cellCountZ;
|
||||
|
||||
// The mirror turns the body half way around y, which also reverses z
|
||||
bool rail = data->settings.scene == e_ghostRail;
|
||||
float* heights = malloc( countX * countZ * sizeof( float ) );
|
||||
for ( int row = 0; row < countZ; ++row )
|
||||
{
|
||||
float z = mirror ? halfWidth - cellZ * (float)row : -halfWidth + cellZ * (float)row;
|
||||
for ( int column = 0; column < countX; ++column )
|
||||
{
|
||||
float x = mirror ? x1 - cellX * (float)column : x0 + cellX * (float)column;
|
||||
heights[row * countX + column] = rail ? EvaluateRail( z, cellZ ) : EvaluateProfile( data, x );
|
||||
}
|
||||
}
|
||||
|
||||
b3HeightFieldDef def = { 0 };
|
||||
def.heights = heights;
|
||||
def.scale = (b3Vec3){ cellX, 1.0f, cellZ };
|
||||
def.countX = countX;
|
||||
def.countZ = countZ;
|
||||
def.globalMinimumHeight = minHeight;
|
||||
def.globalMaximumHeight = maxHeight;
|
||||
b3HeightFieldData* heightField = b3CreateHeightField( &def );
|
||||
free( heights );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
if ( mirror )
|
||||
{
|
||||
bodyDef.position = (b3Pos){ x1, 0.0f, halfWidth };
|
||||
bodyDef.rotation = (b3Quat){ { 0.0f, 1.0f, 0.0f }, 0.0f };
|
||||
}
|
||||
else
|
||||
{
|
||||
bodyDef.position = (b3Pos){ x0, 0.0f, -halfWidth };
|
||||
}
|
||||
|
||||
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
if ( frictionless )
|
||||
{
|
||||
shapeDef.baseMaterial.friction = 0.0f;
|
||||
}
|
||||
b3CreateHeightFieldShape( bodyId, &shapeDef, heightField );
|
||||
|
||||
data->heightFields[data->heightFieldCount] = heightField;
|
||||
data->heightBodyIds[data->heightFieldCount] = bodyId;
|
||||
data->heightFieldCount += 1;
|
||||
}
|
||||
|
||||
void CreateGhostGround( b3WorldId worldId, GhostCollisionsData* data )
|
||||
{
|
||||
if ( B3_IS_NON_NULL( data->groundId ) )
|
||||
{
|
||||
b3DestroyBody( data->groundId );
|
||||
}
|
||||
|
||||
for ( int i = 0; i < data->heightFieldCount; ++i )
|
||||
{
|
||||
b3DestroyBody( data->heightBodyIds[i] );
|
||||
}
|
||||
|
||||
DestroyGhostGroundData( data );
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
data->groundId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
const GhostSettings* settings = &data->settings;
|
||||
bool rail = settings->scene == e_ghostRail;
|
||||
float h = rail ? GHOST_RAIL_HALF_LENGTH : GHOST_HALF_LENGTH;
|
||||
data->profileCount = 0;
|
||||
data->halfLength = h;
|
||||
data->halfWidth = rail ? GHOST_RAIL_HALF_WIDTH : GHOST_HALF_WIDTH;
|
||||
|
||||
switch ( settings->scene )
|
||||
{
|
||||
case e_ghostConcave:
|
||||
{
|
||||
float slope = 8.0f * B3_PI / 180.0f;
|
||||
PushProfile( data, -h, h * tanf( slope ) );
|
||||
PushProfile( data, 0.0f, 0.0f );
|
||||
PushProfile( data, h, 0.0f );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_ghostCliff:
|
||||
// A height field cannot hold a vertical wall, so there the drop takes one cell
|
||||
PushProfile( data, -h, 3.0f );
|
||||
PushProfile( data, 0.0f, 3.0f );
|
||||
PushProfile( data, settings->heightField ? settings->cellSize : 0.0f, 0.0f );
|
||||
PushProfile( data, h, 0.0f );
|
||||
break;
|
||||
|
||||
case e_ghostCrest:
|
||||
PushProfile( data, -h, 0.0f );
|
||||
PushProfile( data, -10.0f, 0.0f );
|
||||
PushProfile( data, 0.0f, 1.0f );
|
||||
PushProfile( data, 10.0f, 0.0f );
|
||||
PushProfile( data, h, 0.0f );
|
||||
break;
|
||||
|
||||
case e_ghostBumps:
|
||||
// Gentle folds of a few degrees, the range that only flat edge suppression misses
|
||||
for ( int i = 0; i <= 80; ++i )
|
||||
{
|
||||
float x = -h + 0.5f * (float)i;
|
||||
float y = x < -10.0f ? 0.0f : 0.05f * ( 1.0f - cosf( B3_PI * x ) );
|
||||
PushProfile( data, x, y );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_ghostInternal:
|
||||
// PEEL's curved mesh: 32 rows 4 m apart, each step up 1.25 times the last, sliding toward +x
|
||||
for ( int i = 31; i >= 0; --i )
|
||||
{
|
||||
PushProfile( data, 62.0f - 4.0f * (float)i, 1.0f + 0.1f * powf( 1.25f, (float)i ) );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_ghostChamfer:
|
||||
// Flat tops at y = 0 with a chamfered notch every meter. A body crossing a notch overhangs both
|
||||
// chamfers while its bottom rests on the convex top edges.
|
||||
PushProfile( data, -h, 0.0f );
|
||||
for ( int i = 0; i < 30; ++i )
|
||||
{
|
||||
float x = -8.0f + (float)i;
|
||||
PushProfile( data, x, 0.0f );
|
||||
PushProfile( data, x + GHOST_CHAMFER_WIDTH, -GHOST_CHAMFER_DROP );
|
||||
PushProfile( data, x + 2.0f * GHOST_CHAMFER_WIDTH, -GHOST_CHAMFER_DROP );
|
||||
PushProfile( data, x + 3.0f * GHOST_CHAMFER_WIDTH, 0.0f );
|
||||
}
|
||||
PushProfile( data, h, 0.0f );
|
||||
break;
|
||||
|
||||
case e_ghostRail:
|
||||
// Cross section in zy, from the floor up the inner wall, over the top and down the outer skirt
|
||||
PushProfile( data, -data->halfWidth, 0.0f );
|
||||
PushProfile( data, 0.0f, 0.0f );
|
||||
PushProfile( data, 0.0f, GHOST_RAIL_HEIGHT );
|
||||
PushProfile( data, GHOST_RAIL_THICKNESS, GHOST_RAIL_HEIGHT );
|
||||
PushProfile( data, GHOST_RAIL_THICKNESS, -GHOST_RAIL_SKIRT );
|
||||
break;
|
||||
|
||||
default:
|
||||
PushProfile( data, -h, 0.0f );
|
||||
PushProfile( data, h, 0.0f );
|
||||
break;
|
||||
}
|
||||
|
||||
MeshBuilder builder = { 0 };
|
||||
float cellSize = settings->cellSize;
|
||||
bool mirror = settings->mirror;
|
||||
float groundHalfWidth = data->halfWidth;
|
||||
int cellCountZ = GetCellCount( 2.0f * groundHalfWidth, cellSize );
|
||||
|
||||
if ( settings->heightField )
|
||||
{
|
||||
if ( settings->scene == e_ghostInternal )
|
||||
{
|
||||
// One grid line per profile row, as in the mesh
|
||||
PeelPreset preset = s_peelPresets[settings->peelPreset];
|
||||
int zCount = preset.columnCount - 1;
|
||||
data->halfWidth = 20.0f * preset.scaleX * (float)zCount;
|
||||
float x0 = data->profile[0].x;
|
||||
float x1 = data->profile[data->profileCount - 1].x;
|
||||
AddHeightField( worldId, data, x0, x1, data->profileCount - 1, data->halfWidth, zCount, true );
|
||||
|
||||
b3BoxHull box = b3MakeOffsetBoxHull( 140.0f, 1.0f, 30.0f, ( b3Vec3 ){ 65.0f, -1.0f, 0.0f } );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( data->groundId, &shapeDef, &box.base );
|
||||
}
|
||||
else if ( settings->scene == e_ghostChamfer )
|
||||
{
|
||||
// One cell per chamfer puts every notch vertex on the grid
|
||||
AddHeightField( worldId, data, -h, h, GetCellCount( 2.0f * h, GHOST_CHAMFER_WIDTH ), groundHalfWidth, cellCountZ,
|
||||
false );
|
||||
}
|
||||
else
|
||||
{
|
||||
AddHeightField( worldId, data, -h, h, GetCellCount( 2.0f * h, cellSize ), groundHalfWidth, cellCountZ, false );
|
||||
}
|
||||
}
|
||||
else if ( settings->scene == e_ghostRail )
|
||||
{
|
||||
AddRail( &builder, data->profile, data->profileCount, h, cellSize, mirror );
|
||||
AddMesh( data, &builder, false );
|
||||
}
|
||||
else if ( settings->scene == e_ghostInternal )
|
||||
{
|
||||
// The mesh has no friction and the ground plane under it does, as in PEEL
|
||||
PeelPreset preset = s_peelPresets[settings->peelPreset];
|
||||
int zCount = preset.columnCount - 1;
|
||||
float halfWidth = 20.0f * preset.scaleX * (float)zCount;
|
||||
AddGrid( &builder, data->profile, data->profileCount, halfWidth, zCount, false, mirror );
|
||||
data->halfWidth = halfWidth;
|
||||
AddMesh( data, &builder, true );
|
||||
|
||||
b3BoxHull box = b3MakeOffsetBoxHull( 140.0f, 1.0f, 30.0f, ( b3Vec3 ){ 65.0f, -1.0f, 0.0f } );
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
b3CreateHullShape( data->groundId, &shapeDef, &box.base );
|
||||
}
|
||||
else
|
||||
{
|
||||
AddStrip( &builder, data->profile, data->profileCount, cellSize, cellSize, mirror );
|
||||
AddMesh( data, &builder, false );
|
||||
}
|
||||
|
||||
free( builder.vertices );
|
||||
free( builder.indices );
|
||||
}
|
||||
|
||||
void LaunchGhostBody( b3WorldId worldId, GhostCollisionsData* data )
|
||||
{
|
||||
if ( B3_IS_NON_NULL( data->bodyId ) )
|
||||
{
|
||||
b3DestroyBody( data->bodyId );
|
||||
}
|
||||
|
||||
const GhostSettings* settings = &data->settings;
|
||||
|
||||
// PEEL drops its bodies from rest, sized in meters rather than tenths
|
||||
bool peel = settings->scene == e_ghostInternal;
|
||||
float boxHalf = peel ? 1.0f : 0.2f;
|
||||
float capsuleRadius = peel ? 1.0f : 0.2f;
|
||||
float capsuleHalf = peel ? 2.0f : 0.4f;
|
||||
float sphereRadius = peel ? 1.0f : 0.25f;
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
bodyDef.enableContactRecycling = false;
|
||||
b3Quat yaw = b3MakeQuatFromAxisAngle( b3Vec3_axisY, settings->yaw * B3_PI / 180.0f );
|
||||
|
||||
if ( peel )
|
||||
{
|
||||
bodyDef.position = (b3Pos){ s_peelPresets[settings->peelPreset].startZ, 80.0f, 0.0f };
|
||||
bodyDef.rotation = yaw;
|
||||
}
|
||||
else if ( settings->scene == e_ghostRail )
|
||||
{
|
||||
// Dropped across the rail top, pitched so a box face sweeps into the rail edge at an angle. The real
|
||||
// contact is edge on edge and perpendicular to the rail, a face normal there leans along the rail
|
||||
// and catches the body. Found in the Conveyor Circuit sample.
|
||||
b3Quat pitch = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, 60.0f * B3_PI / 180.0f );
|
||||
bodyDef.position = (b3Pos){ GHOST_RAIL_START_X, GHOST_RAIL_HEIGHT + 0.45f, -0.15f };
|
||||
bodyDef.rotation = b3MulQuat( pitch, yaw );
|
||||
bodyDef.linearVelocity = (b3Vec3){ settings->speed, 0.0f, 0.0f };
|
||||
}
|
||||
else
|
||||
{
|
||||
int segment = 0;
|
||||
for ( int k = 0; k + 1 < data->profileCount; ++k )
|
||||
{
|
||||
if ( data->profile[k].x <= GHOST_START_X && GHOST_START_X < data->profile[k + 1].x )
|
||||
{
|
||||
segment = k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
b3Vec2 a = data->profile[segment];
|
||||
b3Vec2 b = data->profile[segment + 1];
|
||||
float length = sqrtf( ( b.x - a.x ) * ( b.x - a.x ) + ( b.y - a.y ) * ( b.y - a.y ) );
|
||||
b3Vec2 d = { ( b.x - a.x ) / length, ( b.y - a.y ) / length };
|
||||
b3Vec2 n = { -d.y, d.x };
|
||||
float y = a.y + ( GHOST_START_X - a.x ) * d.y / d.x;
|
||||
|
||||
float lift = boxHalf;
|
||||
if ( settings->body == e_ghostSphere )
|
||||
{
|
||||
lift = sphereRadius;
|
||||
}
|
||||
else if ( settings->body == e_ghostVCapsule )
|
||||
{
|
||||
lift = capsuleHalf + capsuleRadius;
|
||||
}
|
||||
lift += 0.01f;
|
||||
|
||||
bodyDef.position = (b3Pos){ GHOST_START_X + lift * n.x, y + lift * n.y, 0.0f };
|
||||
b3Quat slope = b3MakeQuatFromAxisAngle( b3Vec3_axisZ, atan2f( d.y, d.x ) );
|
||||
bodyDef.rotation = b3MulQuat( slope, yaw );
|
||||
bodyDef.linearVelocity = (b3Vec3){ settings->speed * d.x, settings->speed * d.y, 0.0f };
|
||||
}
|
||||
|
||||
bodyDef.motionLocks.angularX = settings->fixedRotation;
|
||||
bodyDef.motionLocks.angularY = settings->fixedRotation;
|
||||
bodyDef.motionLocks.angularZ = settings->fixedRotation;
|
||||
bodyDef.enableSleep = false;
|
||||
bodyDef.name = "slider";
|
||||
data->bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.baseMaterial.friction = settings->friction;
|
||||
shapeDef.enableSpeculativeContact = settings->speculative;
|
||||
|
||||
switch ( settings->body )
|
||||
{
|
||||
case e_ghostBox:
|
||||
{
|
||||
b3BoxHull box = peel ? b3MakeBoxHull( 1.0f, 1.0f, 1.0f ) : b3MakeBoxHull( 0.4f, 0.2f, 0.4f );
|
||||
data->shapeId = b3CreateHullShape( data->bodyId, &shapeDef, &box.base );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_ghostHCapsule:
|
||||
{
|
||||
b3Capsule capsule = { { 0.0f, 0.0f, -capsuleHalf }, { 0.0f, 0.0f, capsuleHalf }, capsuleRadius };
|
||||
data->shapeId = b3CreateCapsuleShape( data->bodyId, &shapeDef, &capsule );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_ghostVCapsule:
|
||||
{
|
||||
b3Capsule capsule = { { 0.0f, -capsuleHalf, 0.0f }, { 0.0f, capsuleHalf, 0.0f }, capsuleRadius };
|
||||
data->shapeId = b3CreateCapsuleShape( data->bodyId, &shapeDef, &capsule );
|
||||
}
|
||||
break;
|
||||
|
||||
case e_ghostSphere:
|
||||
{
|
||||
b3Sphere sphere = { b3Vec3_zero, sphereRadius };
|
||||
data->shapeId = b3CreateSphereShape( data->bodyId, &shapeDef, &sphere );
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
data->shapeId = b3CreateHullShape( data->bodyId, &shapeDef, peel ? data->peelCylinder : data->cylinder );
|
||||
break;
|
||||
}
|
||||
|
||||
data->contactBounds = b3Shape_GetAABB( data->shapeId );
|
||||
data->runGhostCount = 0;
|
||||
data->runSteps = 0;
|
||||
}
|
||||
|
||||
GhostCollisionsData CreateGhostCollisions( b3WorldId worldId, GhostSettings settings )
|
||||
{
|
||||
GhostCollisionsData data = { 0 };
|
||||
data.settings = settings;
|
||||
data.cylinder = b3CreateCylinder( 0.4f, 0.4f, -0.2f, 16 );
|
||||
data.peelCylinder = b3CreateCylinder( 2.0f, 1.0f, -1.0f, 16 );
|
||||
data.groundId = b3_nullBodyId;
|
||||
data.bodyId = b3_nullBodyId;
|
||||
data.shapeId = b3_nullShapeId;
|
||||
|
||||
CreateGhostGround( worldId, &data );
|
||||
LaunchGhostBody( worldId, &data );
|
||||
return data;
|
||||
}
|
||||
|
||||
static float SegmentAngle( const GhostCollisionsData* data, int k )
|
||||
{
|
||||
b3Vec2 a = data->profile[k];
|
||||
b3Vec2 b = data->profile[k + 1];
|
||||
return atan2f( b.x - a.x, a.y - b.y );
|
||||
}
|
||||
|
||||
// The normal points from the ground to the body. A hull face can be the reference face, so any
|
||||
// normal within the span of face normals under the body is valid. At a side edge of the ground the
|
||||
// normal may also lean off that side, perpendicular to the edge.
|
||||
static bool IsGhost( const GhostCollisionsData* data, b3Vec3 normal, float xMin, float xMax, float zMin, float zMax )
|
||||
{
|
||||
float tolerance = 5.0f * B3_PI / 180.0f;
|
||||
float sinTolerance = sinf( tolerance );
|
||||
if ( b3AbsFloat( normal.z ) > sinTolerance )
|
||||
{
|
||||
// The manifold must reach the side it leans off
|
||||
float margin = 0.05f;
|
||||
bool atSide = normal.z < 0.0f ? zMin < -data->halfWidth + margin : zMax > data->halfWidth - margin;
|
||||
if ( atSide == false )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// A normal leaning off a side has a short projection, which leaves little room to lean along the edge
|
||||
float planarLength = sqrtf( normal.x * normal.x + normal.y * normal.y );
|
||||
if ( planarLength < sinTolerance )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
GhostBody body = data->settings.body;
|
||||
bool chamferHull = data->settings.scene == e_ghostChamfer && ( body == e_ghostBox || body == e_ghostCylinder );
|
||||
|
||||
float lower = B3_PI;
|
||||
float upper = -B3_PI;
|
||||
int segmentCount = data->profileCount - 1;
|
||||
for ( int k = 0; k < segmentCount; ++k )
|
||||
{
|
||||
float x0 = b3MinFloat( data->profile[k].x, data->profile[k + 1].x );
|
||||
float x1 = b3MaxFloat( data->profile[k].x, data->profile[k + 1].x );
|
||||
if ( x1 < xMin || xMax < x0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// A flat hull bottom resting on the top edges must keep its own normal, so for a hull only the tops
|
||||
// count. A round body's normal comes from the closest ground feature, which can be a top edge.
|
||||
if ( chamferHull && ( data->profile[k].y < 0.0f || data->profile[k + 1].y < 0.0f ) )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float angle = SegmentAngle( data, k );
|
||||
lower = b3MinFloat( lower, angle );
|
||||
upper = b3MaxFloat( upper, angle );
|
||||
}
|
||||
|
||||
float angle = atan2f( normal.y, normal.x );
|
||||
float deviation = b3MaxFloat( lower - angle, angle - upper );
|
||||
if ( deviation <= 0.0f )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Measure the lean outside the span in 3D so a steep side normal is not over counted
|
||||
return deviation > 0.5f * B3_PI || planarLength * sinf( deviation ) > sinTolerance;
|
||||
}
|
||||
|
||||
int UpdateGhostCollisions( b3WorldId worldId, GhostCollisionsData* data, GhostReport* reports, int capacity )
|
||||
{
|
||||
b3Pos center = b3Body_GetWorldCenter( data->bodyId );
|
||||
bool done = center.x > data->halfLength - 1.0f || center.y < -3.0f;
|
||||
if ( data->settings.scene == e_ghostInternal )
|
||||
{
|
||||
// Run out onto the ground plane, or give up on a body knocked off the side
|
||||
done = center.x > 100.0f || center.y < -3.0f || data->runSteps > 900;
|
||||
}
|
||||
|
||||
if ( done )
|
||||
{
|
||||
data->runCount += 1;
|
||||
LaunchGhostBody( worldId, data );
|
||||
center = b3Body_GetWorldCenter( data->bodyId );
|
||||
}
|
||||
|
||||
data->runSteps += 1;
|
||||
|
||||
b3AABB bounds = data->contactBounds;
|
||||
float xMin = (float)bounds.lowerBound.x - 0.1f;
|
||||
float xMax = (float)bounds.upperBound.x + 0.1f;
|
||||
data->contactBounds = b3Shape_GetAABB( data->shapeId );
|
||||
|
||||
int ghostCount = 0;
|
||||
b3ContactData contacts[8];
|
||||
int contactCount = b3Body_GetContactData( data->bodyId, contacts, 8 );
|
||||
for ( int i = 0; i < contactCount; ++i )
|
||||
{
|
||||
bool bodyIsA = B3_ID_EQUALS( contacts[i].shapeIdA, data->shapeId );
|
||||
b3ShapeId otherId = bodyIsA ? contacts[i].shapeIdB : contacts[i].shapeIdA;
|
||||
b3ShapeType otherType = b3Shape_GetType( otherId );
|
||||
if ( otherType != b3_meshShape && otherType != b3_heightShape )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for ( int j = 0; j < contacts[i].manifoldCount; ++j )
|
||||
{
|
||||
const b3Manifold* manifold = contacts[i].manifolds + j;
|
||||
|
||||
// Speculative points that never pushed are harmless
|
||||
float impulse = 0.0f;
|
||||
for ( int k = 0; k < manifold->pointCount; ++k )
|
||||
{
|
||||
impulse += manifold->points[k].totalNormalImpulse;
|
||||
}
|
||||
|
||||
if ( manifold->pointCount == 0 || impulse <= 0.0f )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float zMin = FLT_MAX;
|
||||
float zMax = -FLT_MAX;
|
||||
for ( int k = 0; k < manifold->pointCount; ++k )
|
||||
{
|
||||
b3Vec3 anchor = bodyIsA ? manifold->points[k].anchorA : manifold->points[k].anchorB;
|
||||
float z = (float)center.z + anchor.z;
|
||||
zMin = b3MinFloat( zMin, z );
|
||||
zMax = b3MaxFloat( zMax, z );
|
||||
}
|
||||
|
||||
b3Vec3 normal = bodyIsA ? b3Neg( manifold->normal ) : manifold->normal;
|
||||
if ( data->settings.scene == e_ghostRail )
|
||||
{
|
||||
// The rail is the same all along x, so no valid normal leans along it
|
||||
if ( b3AbsFloat( normal.x ) <= sinf( 5.0f * B3_PI / 180.0f ) )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if ( IsGhost( data, normal, xMin, xMax, zMin, zMax ) == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( ghostCount < capacity )
|
||||
{
|
||||
b3Vec3 anchor = bodyIsA ? manifold->points[0].anchorA : manifold->points[0].anchorB;
|
||||
reports[ghostCount] = (GhostReport){
|
||||
.point = b3OffsetPos( center, anchor ),
|
||||
.normal = normal,
|
||||
.separation = manifold->points[0].separation,
|
||||
.impulse = impulse,
|
||||
};
|
||||
}
|
||||
|
||||
ghostCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
data->runGhostCount += ghostCount;
|
||||
data->ghostCount += ghostCount;
|
||||
return ghostCount;
|
||||
}
|
||||
|
||||
void DestroyGhostCollisions( GhostCollisionsData* data )
|
||||
{
|
||||
DestroyGhostGroundData( data );
|
||||
b3DestroyHull( data->cylinder );
|
||||
b3DestroyHull( data->peelCylinder );
|
||||
data->cylinder = NULL;
|
||||
data->peelCylinder = NULL;
|
||||
}
|
||||
143
shared/ghost_collisions.h
Normal file
143
shared/ghost_collisions.h
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "box3d/id.h"
|
||||
#include "box3d/math_functions.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Ghost collision scenes, shared by the Mesh / Ghost Collisions sample and the headless ghost scan.
|
||||
// Each ground is a profile in the xy-plane extruded along z and finely tessellated, so a sliding
|
||||
// body crosses many internal edges. A manifold that pushes on the body is a ghost when its normal
|
||||
// points outside the span of face normals under the body. Those are the ones that block or launch
|
||||
// a body.
|
||||
|
||||
// A conveyor side rail along x, the floor is on the -z side
|
||||
#define GHOST_RAIL_HEIGHT 0.35f
|
||||
#define GHOST_RAIL_THICKNESS 0.08f
|
||||
|
||||
typedef enum GhostScene
|
||||
{
|
||||
e_ghostFlat,
|
||||
e_ghostConcave,
|
||||
e_ghostCliff,
|
||||
e_ghostCrest,
|
||||
e_ghostBumps,
|
||||
e_ghostInternal,
|
||||
e_ghostChamfer,
|
||||
e_ghostRail,
|
||||
e_ghostSceneCount
|
||||
} GhostScene;
|
||||
|
||||
typedef enum GhostBody
|
||||
{
|
||||
e_ghostBox,
|
||||
e_ghostHCapsule,
|
||||
e_ghostVCapsule,
|
||||
e_ghostSphere,
|
||||
e_ghostCylinder,
|
||||
e_ghostBodyCount
|
||||
} GhostBody;
|
||||
|
||||
// Mesh variants of the PEEL InternalEdges presets
|
||||
#define GHOST_PEEL_PRESET_COUNT 4
|
||||
|
||||
// Chamfer has the longest profile
|
||||
#define GHOST_MAX_PROFILE_POINTS 128
|
||||
|
||||
extern const char* g_ghostSceneNames[e_ghostSceneCount];
|
||||
extern const char* g_ghostBodyNames[e_ghostBodyCount];
|
||||
extern const char* g_ghostPeelPresetNames[GHOST_PEEL_PRESET_COUNT];
|
||||
|
||||
typedef struct GhostSettings
|
||||
{
|
||||
GhostScene scene;
|
||||
GhostBody body;
|
||||
int peelPreset;
|
||||
bool mirror;
|
||||
|
||||
// Build the ground from height fields instead of meshes. Each height field is its own shape.
|
||||
bool heightField;
|
||||
|
||||
float cellSize;
|
||||
float speed;
|
||||
|
||||
// Degrees
|
||||
float yaw;
|
||||
|
||||
float friction;
|
||||
bool fixedRotation;
|
||||
bool speculative;
|
||||
} GhostSettings;
|
||||
|
||||
GhostSettings GetDefaultGhostSettings( void );
|
||||
|
||||
typedef struct GhostReport
|
||||
{
|
||||
b3Pos point;
|
||||
b3Vec3 normal;
|
||||
float separation;
|
||||
float impulse;
|
||||
} GhostReport;
|
||||
|
||||
typedef struct GhostCollisionsData
|
||||
{
|
||||
GhostSettings settings;
|
||||
b3Vec2 profile[GHOST_MAX_PROFILE_POINTS];
|
||||
int profileCount;
|
||||
|
||||
// The ground spans x in [-halfLength, halfLength] and z in [-halfWidth, halfWidth]
|
||||
float halfLength;
|
||||
float halfWidth;
|
||||
b3MeshData* meshes[2];
|
||||
int meshCount;
|
||||
|
||||
// A height field shape has no local transform, so each one gets its own static body
|
||||
b3HeightFieldData* heightFields[2];
|
||||
b3BodyId heightBodyIds[2];
|
||||
int heightFieldCount;
|
||||
b3HullData* cylinder;
|
||||
b3HullData* peelCylinder;
|
||||
b3BodyId groundId;
|
||||
b3BodyId bodyId;
|
||||
b3ShapeId shapeId;
|
||||
|
||||
// Body bounds at the start of the step, where the contacts were computed. A fast body can cross a fold
|
||||
// within a step, so the bounds after the step can miss the face a contact came from.
|
||||
b3AABB contactBounds;
|
||||
|
||||
// Steps in the current run
|
||||
int runSteps;
|
||||
|
||||
// Completed runs, each ending when the body reaches the end or falls off
|
||||
int runCount;
|
||||
|
||||
int runGhostCount;
|
||||
int ghostCount;
|
||||
} GhostCollisionsData;
|
||||
|
||||
// Creates the ground and launches the body
|
||||
GhostCollisionsData CreateGhostCollisions( b3WorldId worldId, GhostSettings settings );
|
||||
|
||||
// Rebuild the ground after a scene, preset, mirror, height field or cell size change. Relaunch after this.
|
||||
void CreateGhostGround( b3WorldId worldId, GhostCollisionsData* data );
|
||||
|
||||
// Launch a new body from the start, after a body, speed, yaw, friction or rotation change
|
||||
void LaunchGhostBody( b3WorldId worldId, GhostCollisionsData* data );
|
||||
|
||||
// Call after each world step. Relaunches a body that finished its run, then counts the ghost
|
||||
// manifolds on the body. Returns the ghost count for this step and writes up to capacity reports.
|
||||
int UpdateGhostCollisions( b3WorldId worldId, GhostCollisionsData* data, GhostReport* reports, int capacity );
|
||||
|
||||
void DestroyGhostCollisions( GhostCollisionsData* data );
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
779
shared/ghost_oracle.c
Normal file
779
shared/ghost_oracle.c
Normal file
|
|
@ -0,0 +1,779 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "ghost_oracle.h"
|
||||
|
||||
#include "ghost_collisions.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
#include "box3d/constants.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <stddef.h>
|
||||
|
||||
const char* g_oracleSceneNames[e_oracleSceneCount] = {
|
||||
"flat", "fan", "crest", "valley", "ridge", "saddle ridge", "rail", "wave",
|
||||
};
|
||||
|
||||
// The wave scene is the largest, 169 vertices and 288 triangles
|
||||
#define ORACLE_MAX_VERTICES 256
|
||||
#define ORACLE_MAX_INDICES ( 3 * 512 )
|
||||
#define ORACLE_MAX_MANIFOLDS 128
|
||||
|
||||
typedef struct OracleBuilder
|
||||
{
|
||||
b3Vec3 vertices[ORACLE_MAX_VERTICES];
|
||||
int32_t indices[ORACLE_MAX_INDICES];
|
||||
int vertexCount;
|
||||
int indexCount;
|
||||
} OracleBuilder;
|
||||
|
||||
static int AddVertex( OracleBuilder* builder, b3Vec3 vertex )
|
||||
{
|
||||
B3_ASSERT( builder->vertexCount < ORACLE_MAX_VERTICES );
|
||||
if ( builder->vertexCount == ORACLE_MAX_VERTICES )
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
builder->vertices[builder->vertexCount] = vertex;
|
||||
return builder->vertexCount++;
|
||||
}
|
||||
|
||||
// Winds the triangle to face the given direction
|
||||
static void AddTriangle( OracleBuilder* builder, int a, int b, int c, b3Vec3 facing )
|
||||
{
|
||||
B3_ASSERT( builder->indexCount + 3 <= ORACLE_MAX_INDICES );
|
||||
if ( builder->indexCount + 3 > ORACLE_MAX_INDICES )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
b3Vec3 va = builder->vertices[a];
|
||||
b3Vec3 normal = b3Cross( b3Sub( builder->vertices[b], va ), b3Sub( builder->vertices[c], va ) );
|
||||
if ( b3Dot( normal, facing ) < 0.0f )
|
||||
{
|
||||
int temp = b;
|
||||
b = c;
|
||||
c = temp;
|
||||
}
|
||||
|
||||
builder->indices[builder->indexCount++] = a;
|
||||
builder->indices[builder->indexCount++] = b;
|
||||
builder->indices[builder->indexCount++] = c;
|
||||
}
|
||||
|
||||
typedef float OracleHeightFcn( float x, float z );
|
||||
|
||||
// Up facing grid with alternating diagonals
|
||||
static void BuildGrid( OracleBuilder* builder, int countX, int countZ, float cellSize, OracleHeightFcn* height )
|
||||
{
|
||||
float x0 = -0.5f * cellSize * countX;
|
||||
float z0 = -0.5f * cellSize * countZ;
|
||||
int base = builder->vertexCount;
|
||||
for ( int k = 0; k <= countZ; ++k )
|
||||
{
|
||||
for ( int i = 0; i <= countX; ++i )
|
||||
{
|
||||
float x = x0 + cellSize * i;
|
||||
float z = z0 + cellSize * k;
|
||||
AddVertex( builder, (b3Vec3){ x, height( x, z ), z } );
|
||||
}
|
||||
}
|
||||
|
||||
int stride = countX + 1;
|
||||
for ( int k = 0; k < countZ; ++k )
|
||||
{
|
||||
for ( int i = 0; i < countX; ++i )
|
||||
{
|
||||
int a = base + k * stride + i;
|
||||
int b = a + 1;
|
||||
int c = a + stride + 1;
|
||||
int d = a + stride;
|
||||
if ( ( i + k ) & 1 )
|
||||
{
|
||||
AddTriangle( builder, a, d, b, b3Vec3_axisY );
|
||||
AddTriangle( builder, b, d, c, b3Vec3_axisY );
|
||||
}
|
||||
else
|
||||
{
|
||||
AddTriangle( builder, a, d, c, b3Vec3_axisY );
|
||||
AddTriangle( builder, a, c, b, b3Vec3_axisY );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static float FlatHeight( float x, float z )
|
||||
{
|
||||
(void)x;
|
||||
(void)z;
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
static float CrestHeight( float x, float z )
|
||||
{
|
||||
(void)z;
|
||||
return -0.26795f * fabsf( x );
|
||||
}
|
||||
|
||||
static float ValleyHeight( float x, float z )
|
||||
{
|
||||
(void)z;
|
||||
return 0.26795f * fabsf( x );
|
||||
}
|
||||
|
||||
static float RidgeHeight( float x, float z )
|
||||
{
|
||||
(void)z;
|
||||
return -fabsf( x );
|
||||
}
|
||||
|
||||
// libm trig differs in the last bit between platforms, which would make each a different mesh
|
||||
static float WaveHeight( float x, float z )
|
||||
{
|
||||
float s1 = b3ComputeCosSin( 2.3f * x + 0.4f ).sine;
|
||||
float c1 = b3ComputeCosSin( 1.7f * z ).cosine;
|
||||
float s2 = b3ComputeCosSin( 4.1f * z - 1.3f * x ).sine;
|
||||
return 0.12f * s1 * c1 + 0.05f * s2;
|
||||
}
|
||||
|
||||
static void BuildFan( OracleBuilder* builder )
|
||||
{
|
||||
int center = AddVertex( builder, b3Vec3_zero );
|
||||
for ( int i = 0; i < 6; ++i )
|
||||
{
|
||||
b3CosSin cs = b3ComputeCosSin( ( i + 0.5f ) * B3_PI / 3.0f );
|
||||
AddVertex( builder, (b3Vec3){ 2.0f * cs.cosine, 0.0f, 2.0f * cs.sine } );
|
||||
}
|
||||
|
||||
for ( int i = 0; i < 6; ++i )
|
||||
{
|
||||
AddTriangle( builder, center, 1 + i, 1 + ( i + 1 ) % 6, b3Vec3_axisY );
|
||||
}
|
||||
}
|
||||
|
||||
// A ridge along x running into a rising wall, so the ridge end is a saddle vertex
|
||||
static void BuildSaddleRidge( OracleBuilder* builder )
|
||||
{
|
||||
float xs[3] = { -2.0f, 0.0f, 1.0f };
|
||||
float crests[3] = { -0.004f, 0.0f, 0.3f };
|
||||
float sides[3] = { -0.7f, -0.7f, -0.4f };
|
||||
for ( int i = 0; i < 3; ++i )
|
||||
{
|
||||
AddVertex( builder, (b3Vec3){ xs[i], sides[i], -1.0f } );
|
||||
AddVertex( builder, (b3Vec3){ xs[i], crests[i], 0.0f } );
|
||||
AddVertex( builder, (b3Vec3){ xs[i], sides[i], 1.0f } );
|
||||
}
|
||||
|
||||
for ( int i = 0; i < 2; ++i )
|
||||
{
|
||||
for ( int k = 0; k < 2; ++k )
|
||||
{
|
||||
int a = 3 * i + k;
|
||||
AddTriangle( builder, a, a + 1, a + 3, b3Vec3_axisY );
|
||||
AddTriangle( builder, a + 3, a + 1, a + 4, b3Vec3_axisY );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A wall facing -z meeting a narrow top at a convex edge, like a conveyor side rail
|
||||
static void BuildRail( OracleBuilder* builder )
|
||||
{
|
||||
float sectionZ[4] = { 0.0f, 0.0f, GHOST_RAIL_THICKNESS, GHOST_RAIL_THICKNESS };
|
||||
float sectionY[4] = { 0.0f, GHOST_RAIL_HEIGHT, GHOST_RAIL_HEIGHT, 0.0f };
|
||||
int columns = 5;
|
||||
for ( int row = 0; row < 4; ++row )
|
||||
{
|
||||
for ( int column = 0; column < columns; ++column )
|
||||
{
|
||||
AddVertex( builder, (b3Vec3){ -0.5f + 0.25f * column, sectionY[row], sectionZ[row] } );
|
||||
}
|
||||
}
|
||||
|
||||
b3Vec3 facings[3] = { { 0.0f, 0.0f, -1.0f }, b3Vec3_axisY, b3Vec3_axisZ };
|
||||
for ( int row = 0; row < 3; ++row )
|
||||
{
|
||||
for ( int column = 0; column < columns - 1; ++column )
|
||||
{
|
||||
int a = columns * row + column;
|
||||
int b = a + 1;
|
||||
int c = a + columns + 1;
|
||||
int d = a + columns;
|
||||
if ( ( row + column ) & 1 )
|
||||
{
|
||||
AddTriangle( builder, a, d, b, facings[row] );
|
||||
AddTriangle( builder, d, c, b, facings[row] );
|
||||
}
|
||||
else
|
||||
{
|
||||
AddTriangle( builder, a, d, c, facings[row] );
|
||||
AddTriangle( builder, c, b, a, facings[row] );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b3MeshData* CreateOracleMesh( OracleScene scene )
|
||||
{
|
||||
static OracleBuilder builder;
|
||||
builder.vertexCount = 0;
|
||||
builder.indexCount = 0;
|
||||
|
||||
switch ( scene )
|
||||
{
|
||||
case e_oracleFlat:
|
||||
BuildGrid( &builder, 6, 6, 0.5f, FlatHeight );
|
||||
break;
|
||||
case e_oracleFan:
|
||||
BuildFan( &builder );
|
||||
break;
|
||||
case e_oracleCrest:
|
||||
BuildGrid( &builder, 8, 4, 0.5f, CrestHeight );
|
||||
break;
|
||||
case e_oracleValley:
|
||||
BuildGrid( &builder, 8, 4, 0.5f, ValleyHeight );
|
||||
break;
|
||||
case e_oracleRidge:
|
||||
BuildGrid( &builder, 6, 4, 0.5f, RidgeHeight );
|
||||
break;
|
||||
case e_oracleSaddleRidge:
|
||||
BuildSaddleRidge( &builder );
|
||||
break;
|
||||
case e_oracleRail:
|
||||
BuildRail( &builder );
|
||||
break;
|
||||
case e_oracleWave:
|
||||
BuildGrid( &builder, 12, 12, 0.25f, WaveHeight );
|
||||
break;
|
||||
default:
|
||||
return NULL;
|
||||
}
|
||||
|
||||
b3MeshDef def = { 0 };
|
||||
def.vertices = builder.vertices;
|
||||
def.stride = sizeof( b3Vec3 );
|
||||
def.vertexCount = builder.vertexCount;
|
||||
def.indices = builder.indices;
|
||||
def.triangleCount = builder.indexCount / 3;
|
||||
def.weldVertices = true;
|
||||
def.weldTolerance = 0.001f;
|
||||
def.identifyEdges = true;
|
||||
return b3CreateMesh( &def, NULL, 0 );
|
||||
}
|
||||
|
||||
// Local state and 24 bits per draw, which the global 15 bit generator in utils.h does not give
|
||||
typedef struct OracleRandom
|
||||
{
|
||||
uint32_t state;
|
||||
} OracleRandom;
|
||||
|
||||
static float RandomUnit( OracleRandom* random )
|
||||
{
|
||||
uint32_t x = random->state;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
random->state = x;
|
||||
return (float)( x >> 8 ) / 16777216.0f;
|
||||
}
|
||||
|
||||
static float RandomRange( OracleRandom* random, float lower, float upper )
|
||||
{
|
||||
return lower + ( upper - lower ) * RandomUnit( random );
|
||||
}
|
||||
|
||||
static b3Vec3 RandomDirection( OracleRandom* random )
|
||||
{
|
||||
for ( int i = 0; i < 16; ++i )
|
||||
{
|
||||
b3Vec3 v = { RandomRange( random, -1.0f, 1.0f ), RandomRange( random, -1.0f, 1.0f ),
|
||||
RandomRange( random, -1.0f, 1.0f ) };
|
||||
float lengthSquared = b3LengthSquared( v );
|
||||
if ( 0.01f < lengthSquared && lengthSquared <= 1.0f )
|
||||
{
|
||||
return b3MulSV( 1.0f / sqrtf( lengthSquared ), v );
|
||||
}
|
||||
}
|
||||
|
||||
return b3Vec3_axisY;
|
||||
}
|
||||
|
||||
// Direction within the given angle of the axis
|
||||
static b3Vec3 RandomTilt( OracleRandom* random, b3Vec3 axis, float maxAngle )
|
||||
{
|
||||
b3Vec3 perp = b3Cross( axis, RandomDirection( random ) );
|
||||
float length = b3Length( perp );
|
||||
if ( length < 1.0e-4f )
|
||||
{
|
||||
return axis;
|
||||
}
|
||||
|
||||
perp = b3MulSV( 1.0f / length, perp );
|
||||
b3CosSin cs = b3ComputeCosSin( RandomRange( random, 0.0f, maxAngle ) );
|
||||
return b3Add( b3MulSV( cs.cosine, axis ), b3MulSV( cs.sine, perp ) );
|
||||
}
|
||||
|
||||
static bool CollectPair( b3Vec3 a, b3Vec3 b, b3Vec3 c, int triangleIndex, void* context )
|
||||
{
|
||||
OracleReference* reference = context;
|
||||
|
||||
// A truncated union would misjudge the pose
|
||||
B3_ASSERT( reference->pairCount < ORACLE_MAX_TRIANGLES );
|
||||
if ( reference->pairCount == ORACLE_MAX_TRIANGLES )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
OraclePair* pair = reference->pairs + reference->pairCount;
|
||||
*pair = (OraclePair){ 0 };
|
||||
pair->triangleIndex = triangleIndex;
|
||||
pair->vertices[0] = a;
|
||||
pair->vertices[1] = b;
|
||||
pair->vertices[2] = c;
|
||||
pair->faceNormal = b3Normalize( b3Cross( b3Sub( b, a ), b3Sub( c, a ) ) );
|
||||
pair->owned = true;
|
||||
pair->dominatedBy = -1;
|
||||
reference->pairCount += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
// From Real-time Collision Detection, p141
|
||||
static b3Vec3 ClosestPointOnTriangle( b3Vec3 p, b3Vec3 a, b3Vec3 b, b3Vec3 c )
|
||||
{
|
||||
b3Vec3 ab = b3Sub( b, a );
|
||||
b3Vec3 ac = b3Sub( c, a );
|
||||
b3Vec3 ap = b3Sub( p, a );
|
||||
float d1 = b3Dot( ab, ap );
|
||||
float d2 = b3Dot( ac, ap );
|
||||
if ( d1 <= 0.0f && d2 <= 0.0f )
|
||||
{
|
||||
return a;
|
||||
}
|
||||
|
||||
b3Vec3 bp = b3Sub( p, b );
|
||||
float d3 = b3Dot( ab, bp );
|
||||
float d4 = b3Dot( ac, bp );
|
||||
if ( d3 >= 0.0f && d4 <= d3 )
|
||||
{
|
||||
return b;
|
||||
}
|
||||
|
||||
float vc = d1 * d4 - d3 * d2;
|
||||
if ( vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f )
|
||||
{
|
||||
return b3MulAdd( a, d1 / ( d1 - d3 ), ab );
|
||||
}
|
||||
|
||||
b3Vec3 cp = b3Sub( p, c );
|
||||
float d5 = b3Dot( ab, cp );
|
||||
float d6 = b3Dot( ac, cp );
|
||||
if ( d6 >= 0.0f && d5 <= d6 )
|
||||
{
|
||||
return c;
|
||||
}
|
||||
|
||||
float vb = d5 * d2 - d1 * d6;
|
||||
if ( vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f )
|
||||
{
|
||||
return b3MulAdd( a, d2 / ( d2 - d6 ), ac );
|
||||
}
|
||||
|
||||
float va = d3 * d6 - d5 * d4;
|
||||
if ( va <= 0.0f && ( d4 - d3 ) >= 0.0f && ( d5 - d6 ) >= 0.0f )
|
||||
{
|
||||
float w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
|
||||
return b3MulAdd( b, w, b3Sub( c, b ) );
|
||||
}
|
||||
|
||||
float denom = 1.0f / ( va + vb + vc );
|
||||
float v = vb * denom;
|
||||
float w = vc * denom;
|
||||
return b3Add( a, b3Add( b3MulSV( v, ab ), b3MulSV( w, ac ) ) );
|
||||
}
|
||||
|
||||
// The closest pair of each nearby triangle and the union distance
|
||||
static float ComputePairs( OracleReference* reference, const b3MeshData* mesh, const b3HullData* hull, b3Transform transform )
|
||||
{
|
||||
reference->pairCount = 0;
|
||||
|
||||
b3AABB bounds = b3ComputeHullAABB( hull, transform );
|
||||
// Collided points can be well past the speculative distance and the proximal test looks around them
|
||||
float margin = 0.25f;
|
||||
bounds.lowerBound = b3Sub( bounds.lowerBound, (b3Vec3){ margin, margin, margin } );
|
||||
bounds.upperBound = b3Add( bounds.upperBound, (b3Vec3){ margin, margin, margin } );
|
||||
|
||||
b3Mesh meshShape = { .data = (b3MeshData*)mesh, .scale = b3Vec3_one };
|
||||
b3QueryMesh( &meshShape, bounds, CollectPair, reference );
|
||||
|
||||
float minDistance = FLT_MAX;
|
||||
for ( int i = 0; i < reference->pairCount; ++i )
|
||||
{
|
||||
OraclePair* pair = reference->pairs + i;
|
||||
b3DistanceInput input = { 0 };
|
||||
input.proxyA = (b3ShapeProxy){ pair->vertices, 3, 0.0f };
|
||||
input.proxyB = (b3ShapeProxy){ b3GetHullPoints( hull ), hull->vertexCount, 0.0f };
|
||||
input.transform = transform;
|
||||
input.useRadii = false;
|
||||
b3SimplexCache cache = { 0 };
|
||||
b3DistanceOutput output = b3ShapeDistance( &input, &cache, NULL, 0 );
|
||||
pair->meshPoint = output.pointA;
|
||||
pair->hullPoint = output.pointB;
|
||||
pair->normal = output.normal;
|
||||
pair->distance = output.distance;
|
||||
|
||||
if ( output.distance < minDistance )
|
||||
{
|
||||
minDistance = output.distance;
|
||||
reference->closestMeshPoint = output.pointA;
|
||||
reference->closestHullPoint = output.pointB;
|
||||
}
|
||||
}
|
||||
|
||||
reference->distance = minDistance;
|
||||
return minDistance;
|
||||
}
|
||||
|
||||
#define ORACLE_CONTAIN_TOLERANCE 1.0e-4f
|
||||
|
||||
static bool TriangleContains( const OraclePair* pair, b3Vec3 point )
|
||||
{
|
||||
b3Vec3 closest = ClosestPointOnTriangle( point, pair->vertices[0], pair->vertices[1], pair->vertices[2] );
|
||||
return b3DistanceSquared( closest, point ) < ORACLE_CONTAIN_TOLERANCE * ORACLE_CONTAIN_TOLERANCE;
|
||||
}
|
||||
|
||||
// A closest pair is a contact of the union unless a closer triangle also contains its mesh point
|
||||
static void ComputeOwnership( OracleReference* reference )
|
||||
{
|
||||
// Ties along shared features differ only by GJK round off
|
||||
float tieTolerance = 0.02f * B3_LINEAR_SLOP;
|
||||
|
||||
for ( int i = 0; i < reference->pairCount; ++i )
|
||||
{
|
||||
OraclePair* pair = reference->pairs + i;
|
||||
pair->owned = true;
|
||||
pair->dominatedBy = -1;
|
||||
for ( int j = 0; j < reference->pairCount; ++j )
|
||||
{
|
||||
const OraclePair* other = reference->pairs + j;
|
||||
if ( j == i || other->distance >= pair->distance - tieTolerance )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( TriangleContains( other, pair->meshPoint ) )
|
||||
{
|
||||
pair->owned = false;
|
||||
pair->dominatedBy = other->triangleIndex;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On success the reference holds the closest pairs of the returned pose
|
||||
static bool MakeOraclePose( OracleReference* reference, const b3MeshData* mesh, OracleScene scene, int index, b3BoxHull* box,
|
||||
b3Transform* transform )
|
||||
{
|
||||
OracleRandom random = { 0x9E3779B9u ^ ( 2654435761u * (uint32_t)( index + 1 ) ) ^ ( 40503u * (uint32_t)scene ) };
|
||||
for ( int i = 0; i < 4; ++i )
|
||||
{
|
||||
RandomUnit( &random );
|
||||
}
|
||||
|
||||
const b3Vec3* vertices = b3GetMeshVertices( mesh );
|
||||
const b3MeshTriangle* triangles = b3GetMeshTriangles( mesh );
|
||||
int triangleIndex = (int)( RandomUnit( &random ) * mesh->triangleCount );
|
||||
triangleIndex = triangleIndex < mesh->triangleCount ? triangleIndex : mesh->triangleCount - 1;
|
||||
b3Vec3 a = vertices[triangles[triangleIndex].index1];
|
||||
b3Vec3 b = vertices[triangles[triangleIndex].index2];
|
||||
b3Vec3 c = vertices[triangles[triangleIndex].index3];
|
||||
b3Vec3 faceNormal = b3Normalize( b3Cross( b3Sub( b, a ), b3Sub( c, a ) ) );
|
||||
|
||||
float u = RandomUnit( &random );
|
||||
float v = RandomUnit( &random );
|
||||
if ( u + v > 1.0f )
|
||||
{
|
||||
u = 1.0f - u;
|
||||
v = 1.0f - v;
|
||||
}
|
||||
|
||||
b3Vec3 target = b3Add( a, b3Add( b3MulSV( u, b3Sub( b, a ) ), b3MulSV( v, b3Sub( c, a ) ) ) );
|
||||
|
||||
float hx = RandomRange( &random, 0.05f, 0.4f );
|
||||
float hy = RandomRange( &random, 0.05f, 0.4f );
|
||||
float hz = RandomRange( &random, 0.05f, 0.4f );
|
||||
*box = b3MakeBoxHull( hx, hy, hz );
|
||||
|
||||
// Half the boxes rest nearly flat on the face, where parallel faces make ties
|
||||
b3Quat rotation;
|
||||
if ( RandomUnit( &random ) < 0.5f )
|
||||
{
|
||||
b3Vec3 up = RandomTilt( &random, faceNormal, 0.2f );
|
||||
b3Quat align = b3ComputeQuatBetweenUnitVectors( b3Vec3_axisY, up );
|
||||
b3Quat yaw = b3MakeQuatFromAxisAngle( b3Vec3_axisY, RandomRange( &random, -B3_PI, B3_PI ) );
|
||||
rotation = b3MulQuat( align, yaw );
|
||||
}
|
||||
else
|
||||
{
|
||||
b3Vec3 axis = RandomDirection( &random );
|
||||
rotation = b3MakeQuatFromAxisAngle( axis, RandomRange( &random, -B3_PI, B3_PI ) );
|
||||
}
|
||||
|
||||
b3Vec3 approach = RandomTilt( &random, faceNormal, 1.0f );
|
||||
|
||||
// Put the hull support point against the target
|
||||
const b3Vec3* hullPoints = b3GetHullPoints( &box->base );
|
||||
b3Vec3 localDirection = b3InvRotateVector( rotation, b3Neg( approach ) );
|
||||
b3Vec3 support = hullPoints[0];
|
||||
for ( int i = 1; i < box->base.vertexCount; ++i )
|
||||
{
|
||||
if ( b3Dot( hullPoints[i], localDirection ) > b3Dot( support, localDirection ) )
|
||||
{
|
||||
support = hullPoints[i];
|
||||
}
|
||||
}
|
||||
|
||||
float linearSlop = B3_LINEAR_SLOP;
|
||||
float gap = linearSlop * ( 0.2f + 3.4f * RandomUnit( &random ) * RandomUnit( &random ) );
|
||||
b3Transform pose = { b3Sub( target, b3RotateVector( rotation, support ) ), rotation };
|
||||
pose.p = b3MulAdd( pose.p, gap, approach );
|
||||
|
||||
for ( int iteration = 0; iteration < 20; ++iteration )
|
||||
{
|
||||
*transform = pose;
|
||||
|
||||
float distance = ComputePairs( reference, mesh, &box->base, pose );
|
||||
if ( reference->pairCount == 0 )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( distance <= 0.0f )
|
||||
{
|
||||
pose.p = b3MulAdd( pose.p, 2.0f * linearSlop, approach );
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( b3AbsFloat( distance - gap ) < 0.05f * linearSlop )
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
b3Vec3 direction = b3Normalize( b3Sub( reference->closestHullPoint, reference->closestMeshPoint ) );
|
||||
pose.p = b3MulAdd( pose.p, gap - distance, direction );
|
||||
}
|
||||
|
||||
*transform = pose;
|
||||
float distance = ComputePairs( reference, mesh, &box->base, pose );
|
||||
return reference->pairCount > 0 && ORACLE_MIN_DISTANCE <= distance && distance <= B3_SPECULATIVE_DISTANCE;
|
||||
}
|
||||
|
||||
// Smallest squared sine between the normal and the face normal of a triangle that contains the mesh
|
||||
// point and faces the normal. FLT_MAX if there is no such triangle.
|
||||
static float FacingSineSquared( const OracleReference* reference, b3Vec3 meshPoint, b3Vec3 normal )
|
||||
{
|
||||
float best = FLT_MAX;
|
||||
for ( int i = 0; i < reference->pairCount; ++i )
|
||||
{
|
||||
const OraclePair* pair = reference->pairs + i;
|
||||
if ( b3Dot( pair->faceNormal, normal ) <= 0.0f || TriangleContains( pair, meshPoint ) == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
best = b3MinFloat( best, b3LengthSquared( b3Cross( pair->faceNormal, normal ) ) );
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
// The mesh point is the closest union point to a point a little way out along the normal
|
||||
static bool IsProximalNormal( const OracleReference* reference, b3Vec3 meshPoint, b3Vec3 normal, float sinTolerance )
|
||||
{
|
||||
float probeDistance = 0.01f;
|
||||
b3Vec3 probe = b3MulAdd( meshPoint, probeDistance, normal );
|
||||
float bestDistanceSquared = FLT_MAX;
|
||||
b3Vec3 best = meshPoint;
|
||||
for ( int i = 0; i < reference->pairCount; ++i )
|
||||
{
|
||||
const OraclePair* pair = reference->pairs + i;
|
||||
b3Vec3 closest = ClosestPointOnTriangle( probe, pair->vertices[0], pair->vertices[1], pair->vertices[2] );
|
||||
float distanceSquared = b3DistanceSquared( closest, probe );
|
||||
if ( distanceSquared < bestDistanceSquared )
|
||||
{
|
||||
bestDistanceSquared = distanceSquared;
|
||||
best = closest;
|
||||
}
|
||||
}
|
||||
|
||||
float offset = sinTolerance * probeDistance;
|
||||
return b3DistanceSquared( best, meshPoint ) < offset * offset;
|
||||
}
|
||||
|
||||
// Collides the hull and judges every manifold against the reference
|
||||
static void JudgeCollision( OracleResult* result, const OracleReference* reference, const b3MeshData* mesh,
|
||||
const b3HullData* hull, b3Transform transform, bool handleGhosts )
|
||||
{
|
||||
result->pointCount = 0;
|
||||
result->ghostCount = 0;
|
||||
result->missed = false;
|
||||
|
||||
b3Manifold manifolds[ORACLE_MAX_MANIFOLDS];
|
||||
b3Mesh meshShape = { .data = (b3MeshData*)mesh, .scale = b3Vec3_one };
|
||||
int manifoldCount =
|
||||
b3CollideMeshAndHull( manifolds, ORACLE_MAX_MANIFOLDS, &meshShape, hull, transform, true, handleGhosts );
|
||||
B3_ASSERT( manifoldCount < ORACLE_MAX_MANIFOLDS );
|
||||
|
||||
// Clustering merges manifolds whose normals are within about 5 degrees
|
||||
float sinTolerance = 0.1f;
|
||||
float minSeparation = FLT_MAX;
|
||||
for ( int i = 0; i < manifoldCount; ++i )
|
||||
{
|
||||
const b3Manifold* manifold = manifolds + i;
|
||||
int firstPoint = result->pointCount;
|
||||
for ( int j = 0; j < manifold->pointCount; ++j )
|
||||
{
|
||||
B3_ASSERT( result->pointCount < ORACLE_MAX_POINTS );
|
||||
if ( result->pointCount == ORACLE_MAX_POINTS )
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
const b3ManifoldPoint* manifoldPoint = manifold->points + j;
|
||||
OraclePoint* point = result->points + result->pointCount;
|
||||
point->point = manifoldPoint->anchorA;
|
||||
point->meshPoint = manifoldPoint->anchorA;
|
||||
point->normal = manifold->normal;
|
||||
point->separation = manifoldPoint->separation + B3_MESH_REST_OFFSET;
|
||||
point->triangleIndex = manifoldPoint->triangleIndex;
|
||||
point->verdict = e_oracleGhost;
|
||||
result->pointCount += 1;
|
||||
|
||||
minSeparation = b3MinFloat( minSeparation, point->separation );
|
||||
|
||||
const OraclePair* pair = NULL;
|
||||
for ( int k = 0; k < reference->pairCount; ++k )
|
||||
{
|
||||
if ( reference->pairs[k].triangleIndex == point->triangleIndex )
|
||||
{
|
||||
pair = reference->pairs + k;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The reference bounds contain the collider bounds, so every collided triangle has a pair
|
||||
B3_ASSERT( pair != NULL );
|
||||
if ( pair == NULL )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
b3Vec3 meshPoint =
|
||||
ClosestPointOnTriangle( point->point, pair->vertices[0], pair->vertices[1], pair->vertices[2] );
|
||||
point->meshPoint = meshPoint;
|
||||
|
||||
// A proximal normal also has to be in front of a face here, or an inverted face normal would pass
|
||||
float sineSquared = FacingSineSquared( reference, meshPoint, point->normal );
|
||||
if ( sineSquared < sinTolerance * sinTolerance )
|
||||
{
|
||||
point->verdict = e_oracleFace;
|
||||
}
|
||||
else if ( sineSquared < FLT_MAX && IsProximalNormal( reference, meshPoint, point->normal, sinTolerance ) )
|
||||
{
|
||||
point->verdict = e_oracleFeature;
|
||||
}
|
||||
}
|
||||
|
||||
float deepest = FLT_MAX;
|
||||
for ( int j = firstPoint; j < result->pointCount; ++j )
|
||||
{
|
||||
deepest = b3MinFloat( deepest, result->points[j].separation );
|
||||
}
|
||||
|
||||
bool valid = false;
|
||||
for ( int j = firstPoint; j < result->pointCount; ++j )
|
||||
{
|
||||
const OraclePoint* point = result->points + j;
|
||||
if ( point->separation <= deepest + B3_LINEAR_SLOP && point->verdict != e_oracleGhost )
|
||||
{
|
||||
valid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for ( int j = firstPoint; j < result->pointCount && valid; ++j )
|
||||
{
|
||||
OraclePoint* point = result->points + j;
|
||||
point->verdict = point->verdict == e_oracleGhost ? e_oracleShared : point->verdict;
|
||||
}
|
||||
|
||||
if ( valid == false && result->pointCount > firstPoint )
|
||||
{
|
||||
result->ghostCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// The union closest pair has to be represented. SAT separation is a lower bound on distance.
|
||||
float linearSlop = B3_LINEAR_SLOP;
|
||||
float distance = reference->distance;
|
||||
if ( distance < B3_SPECULATIVE_DISTANCE - linearSlop && minSeparation > distance + linearSlop )
|
||||
{
|
||||
result->missed = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool EvaluateOraclePose( OraclePose* pose, const b3MeshData* mesh, OracleScene scene, int index )
|
||||
{
|
||||
if ( MakeOraclePose( &pose->reference, mesh, scene, index, &pose->box, &pose->transform ) == false )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
B3_ASSERT( pose->reference.distance >= ORACLE_MIN_DISTANCE );
|
||||
ComputeOwnership( &pose->reference );
|
||||
|
||||
const b3HullData* hull = &pose->box.base;
|
||||
JudgeCollision( &pose->raw, &pose->reference, mesh, hull, pose->transform, false );
|
||||
JudgeCollision( &pose->handled, &pose->reference, mesh, hull, pose->transform, true );
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IsOracleCullingMiss( const OraclePose* pose )
|
||||
{
|
||||
return pose->handled.missed && pose->raw.missed == false;
|
||||
}
|
||||
|
||||
OracleScan ScanGhostOracle( const b3MeshData* mesh, OracleScene scene, int poseCount )
|
||||
{
|
||||
static OraclePose pose;
|
||||
OracleScan scan = { 0 };
|
||||
scan.firstGhost = -1;
|
||||
scan.firstMissed = -1;
|
||||
|
||||
for ( int i = 0; i < poseCount; ++i )
|
||||
{
|
||||
if ( EvaluateOraclePose( &pose, mesh, scene, i ) == false )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
scan.validCount += 1;
|
||||
scan.rawGhostPoses += pose.raw.ghostCount > 0 ? 1 : 0;
|
||||
|
||||
if ( pose.handled.ghostCount > 0 )
|
||||
{
|
||||
scan.ghostPoses += 1;
|
||||
scan.firstGhost = scan.firstGhost < 0 ? i : scan.firstGhost;
|
||||
}
|
||||
|
||||
if ( IsOracleCullingMiss( &pose ) )
|
||||
{
|
||||
scan.missedPoses += 1;
|
||||
scan.firstMissed = scan.firstMissed < 0 ? i : scan.firstMissed;
|
||||
}
|
||||
}
|
||||
|
||||
return scan;
|
||||
}
|
||||
168
shared/ghost_oracle.h
Normal file
168
shared/ghost_oracle.h
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "box3d/math_functions.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Separated-pose oracle for mesh ghost handling. With the hull clear of the mesh the union of the
|
||||
// triangles is the reference surface, and none of the Voronoi logic under test is needed to judge a
|
||||
// contact against it.
|
||||
//
|
||||
// A normal is valid at a mesh location when the union has it there: the face normal of a triangle
|
||||
// containing the location, or a proximal normal, meaning the location is the closest union point to a
|
||||
// point a little way out along the normal. That second test gives the convex edge wedge and the vertex
|
||||
// cone exactly, and nothing at a concave crease beyond the two face normals. A manifold shares one normal
|
||||
// across its points, so it is a ghost when the normal is valid at none of its points within linear slop of
|
||||
// its deepest.
|
||||
//
|
||||
// The contacts the union itself has are the local minima of the distance between the hull and the
|
||||
// union. A triangle's closest pair (GJK) is one unless a triangle that also contains its mesh point is
|
||||
// closer to the hull. The distance to a triangle is convex over the triangle, so that test is exact. The
|
||||
// union closest pair must be represented by a collided point, otherwise the contact was missed.
|
||||
|
||||
typedef enum OracleScene
|
||||
{
|
||||
e_oracleFlat,
|
||||
e_oracleFan,
|
||||
e_oracleCrest,
|
||||
e_oracleValley,
|
||||
e_oracleRidge,
|
||||
e_oracleSaddleRidge,
|
||||
e_oracleRail,
|
||||
e_oracleWave,
|
||||
e_oracleSceneCount
|
||||
} OracleScene;
|
||||
|
||||
extern const char* g_oracleSceneNames[e_oracleSceneCount];
|
||||
|
||||
#define ORACLE_MAX_TRIANGLES 256
|
||||
#define ORACLE_MAX_POINTS 128
|
||||
|
||||
// Poses per scene in the unit test, and in the sample scan so the two report the same counts
|
||||
#define ORACLE_SCAN_POSES 500
|
||||
|
||||
typedef enum OracleVerdict
|
||||
{
|
||||
// Face normal of a triangle containing the point
|
||||
e_oracleFace,
|
||||
|
||||
// Proximal normal at an edge or vertex
|
||||
e_oracleFeature,
|
||||
|
||||
// Not valid here, but valid at a deep point of the same manifold
|
||||
e_oracleShared,
|
||||
|
||||
// Point of a manifold whose normal is valid at none of its deep points
|
||||
e_oracleGhost,
|
||||
} OracleVerdict;
|
||||
|
||||
typedef struct OraclePair
|
||||
{
|
||||
int triangleIndex;
|
||||
b3Vec3 vertices[3];
|
||||
b3Vec3 faceNormal;
|
||||
b3Vec3 meshPoint;
|
||||
b3Vec3 hullPoint;
|
||||
b3Vec3 normal;
|
||||
float distance;
|
||||
bool owned;
|
||||
|
||||
// Triangle index of a closer triangle containing the mesh point, or -1
|
||||
int dominatedBy;
|
||||
} OraclePair;
|
||||
|
||||
// The union of the triangles near the hull. Depends only on the pose, not on the collider.
|
||||
typedef struct OracleReference
|
||||
{
|
||||
// Distance between the hull and the mesh
|
||||
float distance;
|
||||
b3Vec3 closestMeshPoint;
|
||||
b3Vec3 closestHullPoint;
|
||||
|
||||
OraclePair pairs[ORACLE_MAX_TRIANGLES];
|
||||
int pairCount;
|
||||
} OracleReference;
|
||||
|
||||
typedef struct OraclePoint
|
||||
{
|
||||
b3Vec3 point;
|
||||
|
||||
// Closest point on the point's triangle
|
||||
b3Vec3 meshPoint;
|
||||
b3Vec3 normal;
|
||||
|
||||
// Geometric separation, without the mesh rest offset the collider subtracts
|
||||
float separation;
|
||||
int triangleIndex;
|
||||
OracleVerdict verdict;
|
||||
} OraclePoint;
|
||||
|
||||
// The collider output judged against the reference
|
||||
typedef struct OracleResult
|
||||
{
|
||||
OraclePoint points[ORACLE_MAX_POINTS];
|
||||
int pointCount;
|
||||
|
||||
// Ghost manifolds
|
||||
int ghostCount;
|
||||
|
||||
// The union closest pair has no collided point
|
||||
bool missed;
|
||||
} OracleResult;
|
||||
|
||||
typedef struct OraclePose
|
||||
{
|
||||
b3BoxHull box;
|
||||
b3Transform transform;
|
||||
OracleReference reference;
|
||||
|
||||
// Collided without and with ghost handling
|
||||
OracleResult raw;
|
||||
OracleResult handled;
|
||||
} OraclePose;
|
||||
|
||||
typedef struct OracleScan
|
||||
{
|
||||
// Separated poses
|
||||
int validCount;
|
||||
|
||||
// Poses with a ghost manifold, without and with ghost handling
|
||||
int rawGhostPoses;
|
||||
int ghostPoses;
|
||||
|
||||
// Poses where ghost handling lost the closest pair
|
||||
int missedPoses;
|
||||
|
||||
// Pose indices, -1 for none
|
||||
int firstGhost;
|
||||
int firstMissed;
|
||||
} OracleScan;
|
||||
|
||||
// The poses keep the hull separated by at least this much, where the closest direction is well defined
|
||||
#define ORACLE_MIN_DISTANCE ( 0.1f * B3_LINEAR_SLOP )
|
||||
|
||||
// Caller destroys with b3DestroyMesh
|
||||
b3MeshData* CreateOracleMesh( OracleScene scene );
|
||||
|
||||
// Deterministic random box and pose for the scene and index, separated from the mesh by
|
||||
// [ORACLE_MIN_DISTANCE, B3_SPECULATIVE_DISTANCE], collided and judged with and without ghost handling.
|
||||
// Returns false if no separated pose was found, in which case the reference and results mean nothing.
|
||||
bool EvaluateOraclePose( OraclePose* pose, const b3MeshData* mesh, OracleScene scene, int index );
|
||||
|
||||
// A miss counts against ghost handling only when the collider represents the closest pair without it
|
||||
bool IsOracleCullingMiss( const OraclePose* pose );
|
||||
|
||||
// Poses [0, poseCount) of the scene
|
||||
OracleScan ScanGhostOracle( const b3MeshData* mesh, OracleScene scene, int poseCount );
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
355
shared/mesh_drop.c
Normal file
355
shared/mesh_drop.c
Normal file
|
|
@ -0,0 +1,355 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "mesh_drop.h"
|
||||
|
||||
#include "box3d/box3d.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
|
||||
#define WAVE_CELL_WIDTH 1.0f
|
||||
#define WAVE_ROW_FREQUENCY 0.1f
|
||||
#define WAVE_COLUMN_FREQUENCY 0.2f
|
||||
#define DROP_SPACING 0.5f
|
||||
#define DROP_HEIGHT 5.0f
|
||||
#define BODY_RADIUS 0.05f
|
||||
#define CAPSULE_HALF_LENGTH 0.2f
|
||||
|
||||
const char* g_meshDropShapeNames[e_meshDropShapeCount] = { "box", "capsule", "cylinder", "sphere" };
|
||||
|
||||
const float g_meshDropDepthLevels[MESH_DROP_DEPTH_LEVEL_COUNT] = { 4.0f, 8.0f, 16.0f, 32.0f };
|
||||
|
||||
// Same XorShift32 and mapping as the samples, but with local state so worlds can run on many threads
|
||||
static float RandomFloatRange( uint32_t* state, float lo, float hi )
|
||||
{
|
||||
uint32_t x = *state;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
*state = x;
|
||||
|
||||
int i = (int)( x % 32768 );
|
||||
float r = (float)( i & 32767 ) / 32767.0f;
|
||||
return ( hi - lo ) * r + lo;
|
||||
}
|
||||
|
||||
static b3Vec3 RandomVec3Uniform( uint32_t* state, float lo, float hi )
|
||||
{
|
||||
b3Vec3 v;
|
||||
v.x = RandomFloatRange( state, lo, hi );
|
||||
v.y = RandomFloatRange( state, lo, hi );
|
||||
v.z = RandomFloatRange( state, lo, hi );
|
||||
return v;
|
||||
}
|
||||
|
||||
static uint32_t HashSeed( uint32_t x )
|
||||
{
|
||||
x ^= x >> 16;
|
||||
x *= 0x7feb352du;
|
||||
x ^= x >> 15;
|
||||
x *= 0x846ca68bu;
|
||||
x ^= x >> 16;
|
||||
return x != 0 ? x : 1;
|
||||
}
|
||||
|
||||
static b3BoxHull MakeDropBox( void )
|
||||
{
|
||||
// The soft contact solver cannot always resolve a smaller box at 4 sub-steps, and its size gets
|
||||
// close to the time of impact tolerances
|
||||
return b3MakeBoxHull( 0.02f, 0.2f, 0.04f );
|
||||
}
|
||||
|
||||
MeshDropSettings GetDefaultMeshDropSettings( void )
|
||||
{
|
||||
MeshDropSettings settings = {
|
||||
.shape = e_meshDropBox,
|
||||
.amplitude = 0.5f,
|
||||
.collide = false,
|
||||
.soloIndex = -1,
|
||||
};
|
||||
return settings;
|
||||
}
|
||||
|
||||
uint32_t GetMeshDropSeed( uint32_t baseSeed, int generation )
|
||||
{
|
||||
return HashSeed( HashSeed( baseSeed ) + (uint32_t)generation );
|
||||
}
|
||||
|
||||
int GetMeshDropStepLimit( MeshDropShape shape )
|
||||
{
|
||||
return shape == e_meshDropCapsule ? 3000 : 1000;
|
||||
}
|
||||
|
||||
float GetMeshDropTunnelHeight( void )
|
||||
{
|
||||
return -2.0f;
|
||||
}
|
||||
|
||||
b3MeshData* CreateMeshDropMesh( float amplitude )
|
||||
{
|
||||
return b3CreateWaveMesh( MESH_DROP_WAVE_COUNT, MESH_DROP_WAVE_COUNT, WAVE_CELL_WIDTH, amplitude, WAVE_ROW_FREQUENCY,
|
||||
WAVE_COLUMN_FREQUENCY );
|
||||
}
|
||||
|
||||
b3HullData* CreateMeshDropCylinder( void )
|
||||
{
|
||||
return b3CreateCylinder( 0.4f, BODY_RADIUS, 0.0f, 6 );
|
||||
}
|
||||
|
||||
b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh )
|
||||
{
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
b3BodyId groundId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
shapeDef.filter.categoryBits = 1;
|
||||
b3CreateMeshShape( groundId, &shapeDef, mesh, b3Vec3_one );
|
||||
|
||||
float extent = 0.5f * MESH_DROP_WAVE_COUNT * WAVE_CELL_WIDTH;
|
||||
float halfHeight = 1.0f;
|
||||
|
||||
b3Transform transforms[4] = {
|
||||
{ { 0.0f, halfHeight, -extent }, b3Quat_identity },
|
||||
{ { 0.0f, halfHeight, extent }, b3Quat_identity },
|
||||
{ { -extent, halfHeight, 0.0f }, b3Quat_identity },
|
||||
{ { extent, halfHeight, 0.0f }, b3Quat_identity },
|
||||
};
|
||||
|
||||
for ( int i = 0; i < 4; ++i )
|
||||
{
|
||||
float hx = i < 2 ? extent : 0.1f;
|
||||
float hz = i < 2 ? 0.1f : extent;
|
||||
b3BoxHull wallBox = b3MakeTransformedBoxHull( hx, halfHeight, hz, transforms[i] );
|
||||
b3CreateHullShape( groundId, &shapeDef, &wallBox.base );
|
||||
}
|
||||
|
||||
return groundId;
|
||||
}
|
||||
|
||||
void CreateMeshDropBodies( b3WorldId worldId, MeshDropSettings settings, uint32_t seed, const b3HullData* cylinder,
|
||||
b3BodyId* bodies )
|
||||
{
|
||||
b3BoxHull box = MakeDropBox();
|
||||
b3Capsule capsule = { { 0.0f, -CAPSULE_HALF_LENGTH, 0.0f }, { 0.0f, CAPSULE_HALF_LENGTH, 0.0f }, BODY_RADIUS };
|
||||
b3Sphere sphere = { b3Vec3_zero, BODY_RADIUS };
|
||||
|
||||
b3BodyDef bodyDef = b3DefaultBodyDef();
|
||||
bodyDef.type = b3_dynamicBody;
|
||||
|
||||
b3ShapeDef shapeDef = b3DefaultShapeDef();
|
||||
bool round = settings.shape == e_meshDropCapsule || settings.shape == e_meshDropSphere;
|
||||
shapeDef.baseMaterial.rollingResistance = round ? 0.4f : 0.1f;
|
||||
|
||||
if ( settings.collide == false )
|
||||
{
|
||||
shapeDef.filter.categoryBits = 2;
|
||||
shapeDef.filter.maskBits = 1;
|
||||
}
|
||||
|
||||
uint32_t state = seed;
|
||||
int index = 0;
|
||||
for ( int i = 0; i < MESH_DROP_GRID_COUNT; ++i )
|
||||
{
|
||||
for ( int j = 0; j < MESH_DROP_GRID_COUNT; ++j )
|
||||
{
|
||||
// Draw for every body so a solo body gets the same velocity it has in the full drop
|
||||
b3Vec3 linearVelocity = RandomVec3Uniform( &state, -1.0f, 1.0f );
|
||||
b3Vec3 angularVelocity = RandomVec3Uniform( &state, -5.0f, 5.0f );
|
||||
|
||||
if ( settings.soloIndex >= 0 && settings.soloIndex != index )
|
||||
{
|
||||
bodies[index] = b3_nullBodyId;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
bodyDef.position = (b3Pos){ DROP_SPACING * ( i - 0.5f * MESH_DROP_GRID_COUNT ), DROP_HEIGHT,
|
||||
DROP_SPACING * ( j - 0.5f * MESH_DROP_GRID_COUNT ) };
|
||||
bodyDef.linearVelocity = linearVelocity;
|
||||
bodyDef.angularVelocity = angularVelocity;
|
||||
bodyDef.userData = (void*)(intptr_t)( index + 1 );
|
||||
b3BodyId bodyId = b3CreateBody( worldId, &bodyDef );
|
||||
|
||||
switch ( settings.shape )
|
||||
{
|
||||
case e_meshDropBox:
|
||||
b3CreateHullShape( bodyId, &shapeDef, &box.base );
|
||||
break;
|
||||
case e_meshDropCapsule:
|
||||
b3CreateCapsuleShape( bodyId, &shapeDef, &capsule );
|
||||
break;
|
||||
case e_meshDropCylinder:
|
||||
b3CreateHullShape( bodyId, &shapeDef, cylinder );
|
||||
break;
|
||||
default:
|
||||
b3CreateSphereShape( bodyId, &shapeDef, &sphere );
|
||||
break;
|
||||
}
|
||||
|
||||
bodies[index] = bodyId;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int GetMeshDropBodyIndex( void* userData )
|
||||
{
|
||||
intptr_t value = (intptr_t)userData;
|
||||
return 1 <= value && value <= MESH_DROP_BODY_COUNT ? (int)value - 1 : -1;
|
||||
}
|
||||
|
||||
void ResetMeshDropDepth( MeshDropDepth* depth, MeshDropSettings settings, const b3HullData* cylinder )
|
||||
{
|
||||
// Same heights as b3CreateWaveMesh
|
||||
float omegaZ = 2.0f * B3_PI * WAVE_ROW_FREQUENCY * WAVE_CELL_WIDTH;
|
||||
float omegaX = 2.0f * B3_PI * WAVE_COLUMN_FREQUENCY * WAVE_CELL_WIDTH;
|
||||
int index = 0;
|
||||
for ( int ix = 0; ix <= MESH_DROP_WAVE_COUNT; ++ix )
|
||||
{
|
||||
float rowHeight = b3ComputeCosSin( omegaX * ix ).sine;
|
||||
for ( int iz = 0; iz <= MESH_DROP_WAVE_COUNT; ++iz )
|
||||
{
|
||||
float columnHeight = b3ComputeCosSin( omegaZ * iz ).sine;
|
||||
depth->heights[index++] = settings.amplitude * rowHeight * columnHeight;
|
||||
}
|
||||
}
|
||||
|
||||
depth->amplitude = fabsf( settings.amplitude );
|
||||
depth->probeCount = 0;
|
||||
depth->radius = 0.0f;
|
||||
|
||||
switch ( settings.shape )
|
||||
{
|
||||
case e_meshDropBox:
|
||||
case e_meshDropCylinder:
|
||||
{
|
||||
b3BoxHull box = MakeDropBox();
|
||||
const b3HullData* hull = settings.shape == e_meshDropBox ? &box.base : cylinder;
|
||||
const b3Vec3* points = b3GetHullPoints( hull );
|
||||
int count = hull->vertexCount < MESH_DROP_MAX_PROBES ? hull->vertexCount : MESH_DROP_MAX_PROBES;
|
||||
for ( int i = 0; i < count; ++i )
|
||||
{
|
||||
depth->probes[i] = points[i];
|
||||
}
|
||||
depth->probeCount = count;
|
||||
}
|
||||
break;
|
||||
|
||||
case e_meshDropCapsule:
|
||||
depth->probes[0] = (b3Vec3){ 0.0f, -CAPSULE_HALF_LENGTH, 0.0f };
|
||||
depth->probes[1] = (b3Vec3){ 0.0f, CAPSULE_HALF_LENGTH, 0.0f };
|
||||
depth->probeCount = 2;
|
||||
depth->radius = BODY_RADIUS;
|
||||
break;
|
||||
|
||||
default:
|
||||
depth->probes[0] = b3Vec3_zero;
|
||||
depth->probeCount = 1;
|
||||
depth->radius = BODY_RADIUS;
|
||||
break;
|
||||
}
|
||||
|
||||
float maxLength = 0.0f;
|
||||
for ( int i = 0; i < depth->probeCount; ++i )
|
||||
{
|
||||
maxLength = fmaxf( maxLength, b3Length( depth->probes[i] ) );
|
||||
}
|
||||
depth->boundingRadius = maxLength + depth->radius;
|
||||
|
||||
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
|
||||
{
|
||||
depth->bodyDepths[i] = -FLT_MAX;
|
||||
}
|
||||
|
||||
depth->maxDepth = -FLT_MAX;
|
||||
depth->maxIndex = -1;
|
||||
depth->maxStep = 0;
|
||||
depth->stepCount = 0;
|
||||
}
|
||||
|
||||
// Signed distance to the plane of the wave triangle under the point. Exact away from the folds, where
|
||||
// it reads a little deep on a crest and shallow in a valley.
|
||||
static float GetWaveDistance( const MeshDropDepth* depth, b3Vec3 p )
|
||||
{
|
||||
float origin = -0.5f * MESH_DROP_WAVE_COUNT * WAVE_CELL_WIDTH;
|
||||
float u = ( p.x - origin ) / WAVE_CELL_WIDTH;
|
||||
float v = ( p.z - origin ) / WAVE_CELL_WIDTH;
|
||||
int ix = b3ClampInt( (int)floorf( u ), 0, MESH_DROP_WAVE_COUNT - 1 );
|
||||
int iz = b3ClampInt( (int)floorf( v ), 0, MESH_DROP_WAVE_COUNT - 1 );
|
||||
|
||||
int stride = MESH_DROP_WAVE_COUNT + 1;
|
||||
float ha = depth->heights[ix * stride + iz];
|
||||
float hb = depth->heights[ix * stride + iz + 1];
|
||||
float hc = depth->heights[( ix + 1 ) * stride + iz + 1];
|
||||
float hd = depth->heights[( ix + 1 ) * stride + iz];
|
||||
|
||||
// The cell diagonal runs from a to c, matching b3CreateWaveMesh
|
||||
float w = WAVE_CELL_WIDTH;
|
||||
b3Vec3 a = { origin + ix * w, ha, origin + iz * w };
|
||||
b3Vec3 ac = { w, hc - ha, w };
|
||||
b3Vec3 side = v - iz >= u - ix ? (b3Vec3){ 0.0f, hb - ha, w } : (b3Vec3){ w, hd - ha, 0.0f };
|
||||
b3Vec3 normal = b3Normalize( b3Cross( side, ac ) );
|
||||
if ( normal.y < 0.0f )
|
||||
{
|
||||
normal = b3Neg( normal );
|
||||
}
|
||||
|
||||
return b3Dot( normal, b3Sub( p, a ) );
|
||||
}
|
||||
|
||||
void UpdateMeshDropDepth( b3WorldId worldId, MeshDropDepth* depth )
|
||||
{
|
||||
depth->stepCount += 1;
|
||||
|
||||
b3BodyEvents events = b3World_GetBodyEvents( worldId );
|
||||
for ( int i = 0; i < events.moveCount; ++i )
|
||||
{
|
||||
const b3BodyMoveEvent* event = events.moveEvents + i;
|
||||
int index = GetMeshDropBodyIndex( event->userData );
|
||||
if ( index < 0 )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
b3WorldTransform transform = event->transform;
|
||||
if ( (float)transform.p.y - depth->boundingRadius > depth->amplitude )
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float sink = -FLT_MAX;
|
||||
for ( int j = 0; j < depth->probeCount; ++j )
|
||||
{
|
||||
b3Pos point = b3TransformWorldPoint( transform, depth->probes[j] );
|
||||
b3Vec3 p = { (float)point.x, (float)point.y, (float)point.z };
|
||||
sink = fmaxf( sink, depth->radius - GetWaveDistance( depth, p ) );
|
||||
}
|
||||
|
||||
if ( sink > depth->bodyDepths[index] )
|
||||
{
|
||||
depth->bodyDepths[index] = sink;
|
||||
}
|
||||
|
||||
if ( sink > depth->maxDepth )
|
||||
{
|
||||
depth->maxDepth = sink;
|
||||
depth->maxIndex = index;
|
||||
depth->maxStep = depth->stepCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void GetMeshDropDepthCounts( const MeshDropDepth* depth, int counts[MESH_DROP_DEPTH_LEVEL_COUNT] )
|
||||
{
|
||||
for ( int level = 0; level < MESH_DROP_DEPTH_LEVEL_COUNT; ++level )
|
||||
{
|
||||
float threshold = g_meshDropDepthLevels[level] * B3_LINEAR_SLOP;
|
||||
int count = 0;
|
||||
for ( int i = 0; i < MESH_DROP_BODY_COUNT; ++i )
|
||||
{
|
||||
count += depth->bodyDepths[i] > threshold ? 1 : 0;
|
||||
}
|
||||
counts[level] = count;
|
||||
}
|
||||
}
|
||||
115
shared/mesh_drop.h
Normal file
115
shared/mesh_drop.h
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
// SPDX-FileCopyrightText: 2026 Erin Catto
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "box3d/collision.h"
|
||||
#include "box3d/id.h"
|
||||
#include "box3d/math_functions.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
// Mesh Drop scene, shared by the Continuous / Mesh Drop sample and the headless mesh soak. A generation
|
||||
// drops a grid of small bodies with random velocities on a wave mesh and steps until they sleep. A body
|
||||
// that falls out of the world tunneled. The depth tracker measures how far each body sinks into the
|
||||
// wave, which flags contact trouble far more often than tunnels do.
|
||||
|
||||
typedef enum MeshDropShape
|
||||
{
|
||||
e_meshDropBox,
|
||||
e_meshDropCapsule,
|
||||
e_meshDropCylinder,
|
||||
e_meshDropSphere,
|
||||
e_meshDropShapeCount
|
||||
} MeshDropShape;
|
||||
|
||||
#define MESH_DROP_GRID_COUNT 32
|
||||
#define MESH_DROP_BODY_COUNT ( MESH_DROP_GRID_COUNT * MESH_DROP_GRID_COUNT )
|
||||
#define MESH_DROP_DEPTH_LEVEL_COUNT 4
|
||||
|
||||
// Wave mesh cells along x and z
|
||||
#define MESH_DROP_WAVE_COUNT 40
|
||||
|
||||
// Enough for the cylinder hull
|
||||
#define MESH_DROP_MAX_PROBES 16
|
||||
|
||||
extern const char* g_meshDropShapeNames[e_meshDropShapeCount];
|
||||
|
||||
// Sink depth thresholds in linear slop
|
||||
extern const float g_meshDropDepthLevels[MESH_DROP_DEPTH_LEVEL_COUNT];
|
||||
|
||||
typedef struct MeshDropSettings
|
||||
{
|
||||
MeshDropShape shape;
|
||||
float amplitude;
|
||||
|
||||
// Let the bodies collide with each other. Off isolates mesh collision.
|
||||
bool collide;
|
||||
|
||||
// Create only this grid index, or -1 for all. Without body collision a body moves the same alone.
|
||||
int soloIndex;
|
||||
} MeshDropSettings;
|
||||
|
||||
MeshDropSettings GetDefaultMeshDropSettings( void );
|
||||
|
||||
// Hashes the base before adding the generation, so nearby base seeds share no generations
|
||||
uint32_t GetMeshDropSeed( uint32_t baseSeed, int generation );
|
||||
|
||||
// Steps a generation may take to fall asleep
|
||||
int GetMeshDropStepLimit( MeshDropShape shape );
|
||||
|
||||
// A body below this height tunneled
|
||||
float GetMeshDropTunnelHeight( void );
|
||||
|
||||
b3MeshData* CreateMeshDropMesh( float amplitude );
|
||||
b3HullData* CreateMeshDropCylinder( void );
|
||||
|
||||
// Creates a static body with the wave mesh and four walls
|
||||
b3BodyId CreateMeshDropGround( b3WorldId worldId, const b3MeshData* mesh );
|
||||
|
||||
// Creates the bodies of one generation in grid order. Bodies left out by the solo index are null. The
|
||||
// body user data encodes the grid index, see GetMeshDropBodyIndex.
|
||||
void CreateMeshDropBodies( b3WorldId worldId, MeshDropSettings settings, uint32_t seed, const b3HullData* cylinder,
|
||||
b3BodyId* bodies );
|
||||
|
||||
// Grid index from body user data, or -1 if the body is not part of the drop
|
||||
int GetMeshDropBodyIndex( void* userData );
|
||||
|
||||
typedef struct MeshDropDepth
|
||||
{
|
||||
// Wave heights at the mesh vertices
|
||||
float heights[( MESH_DROP_WAVE_COUNT + 1 ) * ( MESH_DROP_WAVE_COUNT + 1 )];
|
||||
|
||||
// Collision points in the body frame, rounded by the radius
|
||||
b3Vec3 probes[MESH_DROP_MAX_PROBES];
|
||||
int probeCount;
|
||||
float radius;
|
||||
float boundingRadius;
|
||||
float amplitude;
|
||||
|
||||
// Deepest sink of each body so far, positive when inside the wave
|
||||
float bodyDepths[MESH_DROP_BODY_COUNT];
|
||||
|
||||
float maxDepth;
|
||||
int maxIndex;
|
||||
int maxStep;
|
||||
int stepCount;
|
||||
} MeshDropDepth;
|
||||
|
||||
// Starts tracking a new generation
|
||||
void ResetMeshDropDepth( MeshDropDepth* depth, MeshDropSettings settings, const b3HullData* cylinder );
|
||||
|
||||
// Call after each world step
|
||||
void UpdateMeshDropDepth( b3WorldId worldId, MeshDropDepth* depth );
|
||||
|
||||
// Number of bodies that sank deeper than each depth level
|
||||
void GetMeshDropDepthCounts( const MeshDropDepth* depth, int counts[MESH_DROP_DEPTH_LEVEL_COUNT] );
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
Loading…
Reference in a new issue