Files
lingua-engine/native/physics-native/lingua_physics.c
T
EmilandClaude Sonnet 5 792b626396 M4: engine.physics — Box3D, over a narrow, verified P/Invoke shim
native/physics-native/lingua_physics.c wraps Box3D at a specific pinned
commit (47d7f7c — Box3D has no 1.0 release yet, and its only tag, v0.1.0,
already diverges from this API, confirmed by diffing headers rather than
assuming). The wrapper is deliberately narrow: Box3D's own b3WorldDef/
b3BodyDef/b3ShapeDef are large structs with function pointers, and
b3BoxHull's own doc comment says it "has data hanging off the end and
cannot be directly copied" — none of that crosses the P/Invoke boundary.
Every exported Lingua_* function takes and returns only plain int32/float/
bool scalars, and handles are this shim's own array-index handles, not
Box3D's id structs. C# binds them with classic DllImport rather than the
newer LibraryImport specifically because LibraryImport's generated
marshalling needs AllowUnsafeBlocks even for an all-scalar signature like
every one of these — DllImport needs none, keeping this plugin inside the
kernel's "no unsafe in the v1 hot path" rule with no exception required.

engine.physics adds Rigidbody/BoxCollider/SphereCollider components and
PhysicsWorld, which diffs Query<Rigidbody>() against its own tracked set
every Stage.FixedUpdate (there's no destruction event to hook) to create
and destroy native bodies, steps Box3D once per invocation — Engine.Host's
accumulator decides how many times that runs per frame, not this plugin —
and writes each body's resulting transform back to GameObject.Transform.
IPhysicsService exposes ApplyLinearImpulse/Get/SetLinearVelocity for
gameplay code.

Verified twice: a standalone C smoke test against the native shim alone
(a box dropped from y=5 onto a static ground settles at y≈1.0, exactly
where the two half-heights sum to), and the full pipeline through Engine.
Host — a headless run with a real scene, --dump showing the same box
settling at y=0.9999 after physics, scene load, and Stage.FixedUpdate all
went through the real kernel. 5 new automated tests in Engine.Physics.
Tests cover the same settling behavior for both shapes, a missing-collider
warning that fires once and doesn't throw, cleanup after a GameObject is
destroyed mid-simulation, and that an applied impulse actually changes
velocity — all passed on the first run.

Physics-enabled GameObjects must be root-level for now: PhysicsWorld
writes Box3D's world-space transform straight into LocalPosition/
LocalRotation, correct only when local and world space are the same
thing. A parented rigidbody needs the same parent-WorldMatrix-inverse
handling GizmoMath.WorldToLocalPosition already does for the gizmo — real,
not-yet-done work, not silently wrong.

Full suite: 81 tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1qPfzq8TDCUMFMV3UwV5N
2026-09-02 17:05:39 +03:00

229 lines
6.1 KiB
C

// A deliberately narrow C shim between Box3D's real API and P/Invoke.
//
// Box3D's own API is not safe to bind directly from C#: b3WorldDef,
// b3BodyDef, and b3ShapeDef are large structs with function pointers and
// nested types passed by value, and b3BoxHull is a struct whose own doc
// comment says "has data hanging off the end and cannot be directly
// copied." Replicating any of that layout byte-for-byte in C# is exactly
// the kind of "compiles, passes a smoke test, breaks on someone else's
// machine" risk docs/kernel-contract.md's own risk table warns about for
// native interop specifically. So none of it crosses the P/Invoke
// boundary: every exported function here takes and returns only plain
// int32_t/float scalars, which marshal automatically with no `unsafe` on
// the C# side at all.
//
// Handles are plain array indices into fixed-capacity tables, not Box3D's
// own id structs — one less thing to get the marshaling of exactly right,
// and plenty of headroom for an indie-scale game (Box3D itself caps out at
// 128 worlds; nothing here needs more than one at a time yet).
#include <stdbool.h>
#include <stdint.h>
#include <box3d/box3d.h>
#if defined( _WIN32 )
#define LINGUA_API __declspec( dllexport )
#else
#define LINGUA_API __attribute__( ( visibility( "default" ) ) )
#endif
#define LINGUA_MAX_WORLDS 8
#define LINGUA_MAX_BODIES 8192
static b3WorldId g_worlds[LINGUA_MAX_WORLDS];
static bool g_worldUsed[LINGUA_MAX_WORLDS];
static b3BodyId g_bodies[LINGUA_MAX_BODIES];
static bool g_bodyUsed[LINGUA_MAX_BODIES];
static bool ValidWorld( int32_t handle )
{
return handle >= 0 && handle < LINGUA_MAX_WORLDS && g_worldUsed[handle];
}
static bool ValidBody( int32_t handle )
{
return handle >= 0 && handle < LINGUA_MAX_BODIES && g_bodyUsed[handle];
}
static int32_t AllocBodySlot( void )
{
for ( int32_t i = 0; i < LINGUA_MAX_BODIES; i++ )
{
if ( !g_bodyUsed[i] )
return i;
}
return -1;
}
LINGUA_API int32_t Lingua_CreateWorld( float gravityX, float gravityY, float gravityZ )
{
for ( int32_t i = 0; i < LINGUA_MAX_WORLDS; i++ )
{
if ( g_worldUsed[i] )
continue;
b3WorldDef def = b3DefaultWorldDef();
def.gravity = ( b3Vec3 ){ gravityX, gravityY, gravityZ };
g_worlds[i] = b3CreateWorld( &def );
g_worldUsed[i] = true;
return i;
}
return -1;
}
LINGUA_API void Lingua_DestroyWorld( int32_t worldHandle )
{
if ( !ValidWorld( worldHandle ) )
return;
b3DestroyWorld( g_worlds[worldHandle] );
g_worldUsed[worldHandle] = false;
}
LINGUA_API void Lingua_WorldStep( int32_t worldHandle, float timeStep, int32_t subStepCount )
{
if ( !ValidWorld( worldHandle ) )
return;
b3World_Step( g_worlds[worldHandle], timeStep, subStepCount );
}
static int32_t CreateBody(
int32_t worldHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
int32_t bodyType )
{
if ( !ValidWorld( worldHandle ) )
return -1;
int32_t slot = AllocBodySlot();
if ( slot < 0 )
return -1;
b3BodyDef bodyDef = b3DefaultBodyDef();
bodyDef.type = (b3BodyType)bodyType;
bodyDef.position = ( b3Vec3 ){ px, py, pz };
bodyDef.rotation = ( b3Quat ){ { qx, qy, qz }, qw };
g_bodies[slot] = b3CreateBody( g_worlds[worldHandle], &bodyDef );
g_bodyUsed[slot] = true;
return slot;
}
static void ShapeDef( float density, float friction, float restitution, b3ShapeDef* def )
{
*def = b3DefaultShapeDef();
def->density = density;
def->baseMaterial.friction = friction;
def->baseMaterial.restitution = restitution;
}
LINGUA_API int32_t Lingua_CreateBoxBody(
int32_t worldHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
float halfWidth, float halfHeight, float halfDepth,
int32_t bodyType, float density, float friction, float restitution )
{
int32_t handle = CreateBody( worldHandle, px, py, pz, qx, qy, qz, qw, bodyType );
if ( handle < 0 )
return -1;
b3ShapeDef shapeDef;
ShapeDef( density, friction, restitution, &shapeDef );
b3BoxHull hull = b3MakeBoxHull( halfWidth, halfHeight, halfDepth );
b3CreateHullShape( g_bodies[handle], &shapeDef, &hull.base );
return handle;
}
LINGUA_API int32_t Lingua_CreateSphereBody(
int32_t worldHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
float radius,
int32_t bodyType, float density, float friction, float restitution )
{
int32_t handle = CreateBody( worldHandle, px, py, pz, qx, qy, qz, qw, bodyType );
if ( handle < 0 )
return -1;
b3ShapeDef shapeDef;
ShapeDef( density, friction, restitution, &shapeDef );
b3Sphere sphere = { ( b3Vec3 ){ 0, 0, 0 }, radius };
b3CreateSphereShape( g_bodies[handle], &shapeDef, &sphere );
return handle;
}
LINGUA_API void Lingua_DestroyBody( int32_t bodyHandle )
{
if ( !ValidBody( bodyHandle ) )
return;
b3DestroyBody( g_bodies[bodyHandle] );
g_bodyUsed[bodyHandle] = false;
}
LINGUA_API void Lingua_GetBodyTransform(
int32_t bodyHandle,
float* outPx, float* outPy, float* outPz,
float* outQx, float* outQy, float* outQz, float* outQw )
{
if ( !ValidBody( bodyHandle ) )
return;
b3WorldTransform t = b3Body_GetTransform( g_bodies[bodyHandle] );
*outPx = t.p.x;
*outPy = t.p.y;
*outPz = t.p.z;
*outQx = t.q.v.x;
*outQy = t.q.v.y;
*outQz = t.q.v.z;
*outQw = t.q.s;
}
LINGUA_API void Lingua_SetBodyTransform(
int32_t bodyHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw )
{
if ( !ValidBody( bodyHandle ) )
return;
b3Body_SetTransform( g_bodies[bodyHandle], ( b3Pos ){ px, py, pz }, ( b3Quat ){ { qx, qy, qz }, qw } );
}
LINGUA_API void Lingua_ApplyLinearImpulse( int32_t bodyHandle, float ix, float iy, float iz, bool wake )
{
if ( !ValidBody( bodyHandle ) )
return;
b3Body_ApplyLinearImpulseToCenter( g_bodies[bodyHandle], ( b3Vec3 ){ ix, iy, iz }, wake );
}
LINGUA_API void Lingua_GetLinearVelocity( int32_t bodyHandle, float* outVx, float* outVy, float* outVz )
{
if ( !ValidBody( bodyHandle ) )
return;
b3Vec3 v = b3Body_GetLinearVelocity( g_bodies[bodyHandle] );
*outVx = v.x;
*outVy = v.y;
*outVz = v.z;
}
LINGUA_API void Lingua_SetLinearVelocity( int32_t bodyHandle, float vx, float vy, float vz )
{
if ( !ValidBody( bodyHandle ) )
return;
b3Body_SetLinearVelocity( g_bodies[bodyHandle], ( b3Vec3 ){ vx, vy, vz } );
}