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
This commit is contained in:
Emil
2026-09-02 17:05:39 +03:00
co-authored by Claude Sonnet 5
parent c2bcb9b9fe
commit 792b626396
20 changed files with 898 additions and 0 deletions
@@ -0,0 +1,7 @@
using System.Runtime.CompilerServices;
// PhysicsWorld is internal — nothing outside this plugin needs it, real
// physics behavior is tested against it directly rather than only through
// IPlugin/IPhysicsService's much narrower surface. Same pattern as
// Engine.Assets' PngReader.
[assembly: InternalsVisibleTo("Engine.Physics.Tests")]
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Generates the deps.json AssemblyDependencyResolver needs to find
this plugin's dependencies — see PluginLoadContext in Engine.Kernel,
and the same property on the other native-facing plugins. -->
<EnableDynamicLoading>true</EnableDynamicLoading>
</PropertyGroup>
<ItemGroup>
<!-- The compiled native shim (Box3D folded in) — see
native/physics-native/. Copied straight into this plugin's own
output directory (not a runtimes/<rid>/native/ NuGet-style path):
DllImport's default unmanaged-library probing already checks the
calling assembly's own directory, and PluginLoadContext.
LoadUnmanagedDll falls back to that default probing whenever its
AssemblyDependencyResolver doesn't recognize the name (returning
IntPtr.Zero, not failing outright) — confirmed empirically, see
PhysicsWorldTests. -->
<Content Include="native/liblingua_physics.so">
<Link>liblingua_physics.so</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\Engine.Kernel\Engine.Kernel.csproj" />
<ProjectReference Include="..\Engine.Physics.Contracts\Engine.Physics.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,72 @@
using System.Runtime.InteropServices;
namespace Engine.Physics;
/// <summary>
/// The entire P/Invoke surface, matching native/physics-native/
/// lingua_physics.c's exports one-to-one. Every parameter is a plain
/// int/float/bool — no struct crosses this boundary, on purpose, see that
/// file's own doc comment for why.
///
/// Classic DllImport, not the newer source-generated LibraryImport:
/// LibraryImport's generated marshalling code needs AllowUnsafeBlocks even
/// for an all-blittable signature like every one of these, and there's no
/// reason to open that door — DllImport marshals plain int/float/bool/out
/// float scalars with no unsafe code at all, which is what actually keeps
/// this plugin inside the kernel's "no unsafe in the v1 hot path" rule
/// (Directory.Build.props) instead of needing a narrow exception to it.
/// </summary>
internal static class Native
{
private const string Lib = "lingua_physics";
[DllImport(Lib)]
public static extern int Lingua_CreateWorld(float gravityX, float gravityY, float gravityZ);
[DllImport(Lib)]
public static extern void Lingua_DestroyWorld(int worldHandle);
[DllImport(Lib)]
public static extern void Lingua_WorldStep(int worldHandle, float timeStep, int subStepCount);
[DllImport(Lib)]
public static extern int Lingua_CreateBoxBody(
int worldHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
float halfWidth, float halfHeight, float halfDepth,
int bodyType, float density, float friction, float restitution);
[DllImport(Lib)]
public static extern int Lingua_CreateSphereBody(
int worldHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
float radius,
int bodyType, float density, float friction, float restitution);
[DllImport(Lib)]
public static extern void Lingua_DestroyBody(int bodyHandle);
[DllImport(Lib)]
public static extern void Lingua_GetBodyTransform(
int bodyHandle,
out float px, out float py, out float pz,
out float qx, out float qy, out float qz, out float qw);
[DllImport(Lib)]
public static extern void Lingua_SetBodyTransform(
int bodyHandle,
float px, float py, float pz,
float qx, float qy, float qz, float qw);
[DllImport(Lib)]
public static extern void Lingua_ApplyLinearImpulse(
int bodyHandle, float ix, float iy, float iz, [MarshalAs(UnmanagedType.U1)] bool wake);
[DllImport(Lib)]
public static extern void Lingua_GetLinearVelocity(int bodyHandle, out float vx, out float vy, out float vz);
[DllImport(Lib)]
public static extern void Lingua_SetLinearVelocity(int bodyHandle, float vx, float vy, float vz);
}
@@ -0,0 +1,54 @@
using System.Numerics;
using Engine.Kernel.Diagnostics;
using Engine.Kernel.Plugins;
using Engine.Kernel.Scheduling;
using Engine.Kernel.World;
using Engine.Physics.Contracts;
namespace Engine.Physics;
/// <summary>
/// M4's physics plugin: Box3D, over the shim in native/physics-native/ —
/// see that file's own doc comment for why nothing crosses the P/Invoke
/// boundary but plain scalars. One system, on Stage.FixedUpdate: sync new/
/// removed Rigidbodies, step once, write results back to Transform. Each
/// FixedUpdate invocation is exactly one physics step at ITime.
/// FixedDeltaTime — Engine.Host's accumulator (Time.ConsumeFixedSteps)
/// decides how many times that runs this frame, not this plugin.
/// </summary>
public sealed class PhysicsPlugin : IPlugin
{
private static readonly Vector3 Gravity = new(0f, -9.81f, 0f);
private PhysicsWorld? _world;
private ITime? _time;
public void Configure(IPluginContext ctx)
{
_time = ctx.Time;
_world = new PhysicsWorld(Gravity, ctx.Log);
ctx.Services.Provide<IPhysicsService>(new PhysicsService(_world));
ctx.Schedule.Add(Stage.FixedUpdate, Step)
.Reads<Rigidbody>()
.Reads<BoxCollider>()
.Reads<SphereCollider>();
ctx.Log.Info("physics world ready (Box3D)");
}
public void Shutdown(IPluginContext ctx)
{
ctx.Schedule.RemoveAllFrom("engine.physics");
ctx.Services.Revoke<IPhysicsService>();
_world?.Dispose();
_world = null;
_time = null;
}
private void Step(IWorld world)
{
_world!.Sync(world);
_world.Step(_time!.FixedDeltaTime);
}
}
@@ -0,0 +1,15 @@
using System.Numerics;
using Engine.Kernel.World;
using Engine.Physics.Contracts;
namespace Engine.Physics;
internal sealed class PhysicsService(PhysicsWorld world) : IPhysicsService
{
public void ApplyLinearImpulse(GameObject go, Vector3 impulse, bool wake = true) =>
world.ApplyLinearImpulse(go, impulse, wake);
public Vector3 GetLinearVelocity(GameObject go) => world.GetLinearVelocity(go);
public void SetLinearVelocity(GameObject go, Vector3 velocity) => world.SetLinearVelocity(go, velocity);
}
@@ -0,0 +1,130 @@
using System.Numerics;
using Engine.Kernel.Diagnostics;
using Engine.Kernel.World;
using Engine.Physics.Contracts;
namespace Engine.Physics;
/// <summary>
/// Owns the one native Box3D world this plugin creates, and the GameObject
/// &lt;-&gt; native body handle mapping. <see cref="Sync"/> creates bodies for
/// any GameObject that's grown a Rigidbody since last frame and destroys
/// bodies for any that lost one (component removed, or the GameObject
/// itself was destroyed) — there's no destruction event to hook, so this
/// diffs Query&lt;Rigidbody&gt;() against the tracked set every FixedUpdate
/// instead. <see cref="Step"/> advances the simulation once and writes
/// every tracked body's new transform back into its GameObject.
/// </summary>
internal sealed class PhysicsWorld : IDisposable
{
private readonly int _handle;
private readonly ILogger _log;
private readonly Dictionary<GameObject, int> _bodies = [];
private readonly HashSet<GameObject> _warnedMissingCollider = [];
public PhysicsWorld(Vector3 gravity, ILogger log)
{
_log = log;
_handle = Native.Lingua_CreateWorld(gravity.X, gravity.Y, gravity.Z);
}
public void Sync(IWorld world)
{
var live = new HashSet<GameObject>();
foreach (var go in world.Query<Rigidbody>())
{
live.Add(go);
if (!_bodies.ContainsKey(go))
TryCreateBody(go);
}
if (_bodies.Count == live.Count)
return;
foreach (var stale in _bodies.Keys.Where(go => !live.Contains(go)).ToList())
{
Native.Lingua_DestroyBody(_bodies[stale]);
_bodies.Remove(stale);
_warnedMissingCollider.Remove(stale);
}
}
public void Step(float timeStep, int subStepCount = 4)
{
Native.Lingua_WorldStep(_handle, timeStep, subStepCount);
foreach (var (go, handle) in _bodies)
{
Native.Lingua_GetBodyTransform(handle, out var px, out var py, out var pz, out var qx, out var qy, out var qz, out var qw);
var t = go.Transform;
t.LocalPosition = new Vector3(px, py, pz);
t.LocalRotation = new Quaternion(qx, qy, qz, qw);
go.Transform = t;
}
}
public void ApplyLinearImpulse(GameObject go, Vector3 impulse, bool wake)
{
if (_bodies.TryGetValue(go, out var handle))
Native.Lingua_ApplyLinearImpulse(handle, impulse.X, impulse.Y, impulse.Z, wake);
}
public Vector3 GetLinearVelocity(GameObject go)
{
if (!_bodies.TryGetValue(go, out var handle))
return Vector3.Zero;
Native.Lingua_GetLinearVelocity(handle, out var vx, out var vy, out var vz);
return new Vector3(vx, vy, vz);
}
public void SetLinearVelocity(GameObject go, Vector3 velocity)
{
if (_bodies.TryGetValue(go, out var handle))
Native.Lingua_SetLinearVelocity(handle, velocity.X, velocity.Y, velocity.Z);
}
private void TryCreateBody(GameObject go)
{
var rb = go.GetComponent<Rigidbody>()!;
var pos = go.Transform.LocalPosition;
var rot = go.Transform.LocalRotation;
var box = go.GetComponent<BoxCollider>();
var sphere = go.GetComponent<SphereCollider>();
int handle;
if (box is not null)
{
handle = Native.Lingua_CreateBoxBody(
_handle, pos.X, pos.Y, pos.Z, rot.X, rot.Y, rot.Z, rot.W,
box.HalfExtents.X, box.HalfExtents.Y, box.HalfExtents.Z,
(int)rb.Type, rb.Density, rb.Friction, rb.Restitution);
}
else if (sphere is not null)
{
handle = Native.Lingua_CreateSphereBody(
_handle, pos.X, pos.Y, pos.Z, rot.X, rot.Y, rot.Z, rot.W,
sphere.Radius, (int)rb.Type, rb.Density, rb.Friction, rb.Restitution);
}
else
{
if (_warnedMissingCollider.Add(go))
_log.Warn($"'{go.Name}' has a Rigidbody but no BoxCollider/SphereCollider — no physics body created.");
return;
}
_bodies[go] = handle;
}
public void Dispose()
{
foreach (var handle in _bodies.Values)
Native.Lingua_DestroyBody(handle);
_bodies.Clear();
Native.Lingua_DestroyWorld(_handle);
}
}
Binary file not shown.