diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c
index abb4efb..b54abf7 100644
--- a/native/Ymir.Box3D/ymir_box3d_soa.c
+++ b/native/Ymir.Box3D/ymir_box3d_soa.c
@@ -57,7 +57,7 @@ enum
YMIR_SOA_JOINT_REMOVED = 4 // a destroyed joint's lane: never accepted by add_joint
};
-#define YMIR_SOA_ABI_VERSION 5u
+#define YMIR_SOA_ABI_VERSION 6u
// A body to create. `size` by kind: sphere {radius}, capsule {radius, half_length} (segment along
// local Y), box and static box {half_x, half_y, half_z}. `parent` is the lane index of an earlier body
@@ -177,6 +177,9 @@ typedef struct ymir_box3d_soa_view
const float* last_substep_force;
const int32_t* contact_count;
const uint64_t* material_id;
+ // Per joint slot: counts the destroys of that slot. A grab's handle is (lane, generation); destroy_joint refuses
+ // a handle whose generation is not the slot's, so a stale release cannot destroy a later grab in a reused slot.
+ const uint32_t* joint_generation;
} ymir_box3d_soa_view;
// A begin or end of touch between two bodies: their lane indices and the shapes' stable ids.
@@ -266,6 +269,7 @@ typedef struct ymir_box3d_soa_world
float* lanes; // YMIR_SOA_BODY_FLOAT_LANES arrays of `capacity` floats, lane-major
b3JointId* joints;
uint32_t* joint_kind;
+ uint32_t* joint_generation;
uint64_t* joint_removed_at; // step_count when the slot was destroyed; reusable once a step has passed
int32_t* joint_body_a;
int32_t* joint_body_b;
@@ -412,6 +416,7 @@ static void ymir_soa_free(ymir_box3d_soa_world* world)
free(world->joints);
free(world->joint_kind);
free(world->joint_removed_at);
+ free(world->joint_generation);
free(world->joint_body_a);
free(world->joint_body_b);
free(world->joint_local_a);
@@ -461,6 +466,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create(
world->joints = (b3JointId*)calloc(m, sizeof(b3JointId));
world->joint_kind = (uint32_t*)calloc(m, sizeof(uint32_t));
world->joint_removed_at = (uint64_t*)calloc(m, sizeof(uint64_t));
+ world->joint_generation = (uint32_t*)calloc(m, sizeof(uint32_t));
world->joint_body_a = (int32_t*)calloc(m, sizeof(int32_t));
world->joint_body_b = (int32_t*)calloc(m, sizeof(int32_t));
world->joint_local_a = (b3Quat*)calloc(m, sizeof(b3Quat));
@@ -476,7 +482,8 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create(
world->bodies == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL ||
world->limb == NULL || world->size == NULL || world->lanes == NULL || world->joints == NULL || world->joint_kind == NULL ||
world->joint_body_a == NULL || world->joint_body_b == NULL || world->joint_local_a == NULL ||
- world->joint_local_b == NULL || world->joint_lanes == NULL || world->joint_removed_at == NULL)
+ world->joint_local_b == NULL || world->joint_lanes == NULL || world->joint_removed_at == NULL ||
+ world->joint_generation == NULL)
{
ymir_soa_free(world);
return YMIR_SOA_OUT_OF_MEMORY;
@@ -810,11 +817,14 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint(
return YMIR_SOA_OK;
}
-// Releases a motor joint (a grab). Only motor joints: general joint removal is another cut's. The lane becomes a
-// tombstone, kind REMOVED, bodies -1 and every lane 0, until a later step lets add_joint reuse it.
-YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_joint(ymir_box3d_soa_world* world, int32_t joint)
+// Releases a motor joint (a grab) named by its lane and the slot's generation read when it was added. Only motor
+// joints: general joint removal is another cut's. A generation that is not the slot's current one is refused, so
+// a stale handle never destroys a later joint in a reused slot. The lane becomes a tombstone, kind REMOVED,
+// bodies -1 and every lane 0, until a later step lets add_joint reuse it.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_joint(ymir_box3d_soa_world* world, int32_t joint, uint32_t generation)
{
- if (world == NULL || joint < 0 || joint >= world->joint_count || world->joint_kind[joint] != YMIR_SOA_JOINT_MOTOR)
+ if (world == NULL || joint < 0 || joint >= world->joint_count || world->joint_kind[joint] != YMIR_SOA_JOINT_MOTOR ||
+ world->joint_generation[joint] != generation)
{
return YMIR_SOA_INVALID_ARGUMENT;
}
@@ -824,6 +834,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_joint(ymir_box3d_soa_world*
world->joint_body_a[joint] = -1;
world->joint_body_b[joint] = -1;
world->joint_removed_at[joint] = world->step_count;
+ world->joint_generation[joint] += 1;
for (int lane = 0; lane < YMIR_SOA_JOINT_FLOAT_LANES; ++lane)
{
ymir_soa_joint_lane(world, lane)[joint] = 0.0f;
@@ -1161,6 +1172,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world
.last_substep_force = base + YMIR_SOA_LAST_SUBSTEP_FORCE_LANE * n,
.contact_count = world->contact_count,
.material_id = world->material_id,
+ .joint_generation = world->joint_generation,
};
return YMIR_SOA_OK;
}
diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs
index e9dad3f..18a9b06 100644
--- a/src/Ymir.Box3D/Box3DSoaWorld.cs
+++ b/src/Ymir.Box3D/Box3DSoaWorld.cs
@@ -67,6 +67,15 @@ internal struct Box3DSoaRayHitNative
public uint Reserved;
}
+///
+/// A joint's identity: its lane and the slot's generation when it was added. Converts to the lane for reading lanes;
+/// takes the whole handle and refuses one from an earlier occupant of the slot.
+///
+public readonly record struct Box3DSoaJointHandle(int Lane, uint Generation)
+{
+ public static implicit operator int(Box3DSoaJointHandle handle) => handle.Lane;
+}
+
/// The closest hit of a ray. false is a miss and every other field is then default.
public readonly record struct Box3DSoaRayHit(
bool Hit, int Lane, ulong StableId, (float X, float Y, float Z) Point, (float X, float Y, float Z) Normal, float Fraction);
@@ -126,6 +135,7 @@ internal unsafe struct Box3DSoaViewNative
public float* LastSubstepForce;
public int* ContactCount;
public ulong* MaterialId;
+ public uint* JointGeneration;
}
/// Native layout of ymir_box3d_soa_facts: counts, dropped counters, then three pointers.
@@ -271,7 +281,7 @@ internal static unsafe partial class Box3DSoaNative
[LibraryImport(Library)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
- internal static partial int ymir_box3d_soa_destroy_joint(nint world, int joint);
+ internal static partial int ymir_box3d_soa_destroy_joint(nint world, int joint, uint generation);
[LibraryImport(Library)]
[UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
@@ -368,6 +378,10 @@ public readonly unsafe struct Box3DSoaView
/// The material id the body was added with (0 by default).
public ReadOnlySpan MaterialId => Lane(_v.MaterialId, Count);
+ /// Per joint slot, the number of times it has been destroyed. A joint's handle is its lane and the generation read
+ /// when it was added; refuses a handle from an earlier occupant of the slot.
+ public ReadOnlySpan JointGeneration => Lane(_v.JointGeneration, JointCount);
+
/// Joints at the moment this view was taken: take it after the last AddJoint.
public int JointCount => _v.JointCount;
public ReadOnlySpan JointKind => Lane(_v.JointKind, JointCount);
@@ -403,7 +417,7 @@ public readonly unsafe struct Box3DSoaView
///
public sealed class Box3DSoaWorld : IDisposable
{
- private const uint ExpectedAbi = 5;
+ private const uint ExpectedAbi = 6;
private nint _handle;
///
@@ -414,8 +428,8 @@ public sealed class Box3DSoaWorld : IDisposable
int capacity, float gravityX = 0f, float gravityY = -10f, float gravityZ = 0f, int jointCapacity = 0,
int? factCapacity = null, float hitThreshold = 1f)
{
- if (Box3DSoaNative.ymir_box3d_soa_get_abi_version() != ExpectedAbi ||
- Box3DSoaNative.ymir_box3d_soa_get_view_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ RequireNativeAbi(Box3DSoaNative.ymir_box3d_soa_get_abi_version());
+ if (Box3DSoaNative.ymir_box3d_soa_get_view_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
Box3DSoaNative.ymir_box3d_soa_get_body_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
Box3DSoaNative.ymir_box3d_soa_get_joint_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
Box3DSoaNative.ymir_box3d_soa_get_facts_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
@@ -429,6 +443,15 @@ public sealed class Box3DSoaWorld : IDisposable
Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, out _handle));
}
+ /// Fails closed when the native library is not the ABI this build expects, in either direction.
+ internal static void RequireNativeAbi(uint nativeAbi)
+ {
+ if (nativeAbi != ExpectedAbi)
+ {
+ throw new InvalidOperationException($"The native Ymir Box3D SoA ABI is {nativeAbi}; this build expects {ExpectedAbi}.");
+ }
+ }
+
/// The live lanes. Count and step count are read from native memory each call.
public Box3DSoaView View
{
@@ -501,9 +524,9 @@ public sealed class Box3DSoaWorld : IDisposable
/// Joins two bodies at a world-space . The joint frame's z axis is
/// (the hinge axis of a revolute joint); the pose at creation is the joint's zero.
/// Limits are radians: the revolute angle, or the spherical twist with as swing.
- /// A weld takes no limits. Returns the joint's lane index. Body B is the child.
+ /// A weld takes no limits. Returns the joint's handle (lane and generation). Body B is the child.
///
- public int AddJoint(
+ public Box3DSoaJointHandle AddJoint(
Box3DSoaJointKind kind, int bodyA, int bodyB, (float X, float Y, float Z) anchor,
(float X, float Y, float Z) axis, bool limit = false, float lower = 0f, float upper = 0f, float coneAngle = 0f)
{
@@ -515,16 +538,18 @@ public sealed class Box3DSoaWorld : IDisposable
AxisX = axis.X, AxisY = axis.Y, AxisZ = axis.Z, Lower = lower, Upper = upper, ConeAngle = coneAngle,
};
Check(Box3DSoaNative.ymir_box3d_soa_add_joint(_handle, desc, out var index));
- return index;
+ return HandleOf(index);
}
///
/// A motor joint: position springs that pull body B's frame onto body A's. The frame sits at the world-space
/// at creation (axes aligned with the world), so the spring pulls B's anchor point onto A's.
/// Hertz 0 turns that spring off; MaxForce (N) and MaxTorque (N m) bound it. All are finite and
- /// not negative. Pair an anchor (body A) with the body to grab (body B). Returns the joint's lane index.
+ /// not negative. Pair an anchor (body A) with the body to grab (body B). Returns the joint's handle (lane and generation).
+ /// Create the anchor only when a joint will follow (check ): the joint validates its spring
+ /// fields, so a grab that fails there leaves the anchor behind. One long-lived anchor per cursor is the intended use.
///
- public int AddMotorJoint(
+ public Box3DSoaJointHandle AddMotorJoint(
int bodyA, int bodyB, (float X, float Y, float Z) anchor,
(float Hertz, float Damping, float MaxForce) linear, (float Hertz, float Damping, float MaxTorque) angular)
{
@@ -537,19 +562,26 @@ public sealed class Box3DSoaWorld : IDisposable
AngularHertz = angular.Hertz, AngularDamping = angular.Damping, MaxTorque = angular.MaxTorque,
};
Check(Box3DSoaNative.ymir_box3d_soa_add_joint(_handle, desc, out var index));
- return index;
+ return HandleOf(index);
}
///
/// Releases a motor joint (a grab); the anchor and the grabbed body stay. The joint's lane becomes a tombstone:
/// kind , bodies -1, every other lane 0. It is reused by a later AddJoint only
/// once a has completed, so lanes read this step stay valid. Throws for any other kind of joint
- /// (general removal is another cut's) or a lane that is not a live joint.
+ /// (general removal is another cut's), a lane that is not a live joint, or a handle whose generation is not the slot's:
+ /// a release made with a stale handle never destroys a later grab in a reused slot.
///
- public void DestroyJoint(int jointLane)
+ public void DestroyJoint(Box3DSoaJointHandle joint)
{
ObjectDisposedException.ThrowIf(_handle == 0, this);
- Check(Box3DSoaNative.ymir_box3d_soa_destroy_joint(_handle, jointLane));
+ Check(Box3DSoaNative.ymir_box3d_soa_destroy_joint(_handle, joint.Lane, joint.Generation));
+ }
+
+ private unsafe Box3DSoaJointHandle HandleOf(int lane)
+ {
+ Check(Box3DSoaNative.ymir_box3d_soa_get_view(_handle, out var v));
+ return new Box3DSoaJointHandle(lane, v.JointGeneration[lane]);
}
/// Joints AddJoint could create right now: unused capacity plus tombstones whose step has completed.
diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs
index a4134db..96b2313 100644
--- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs
+++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs
@@ -137,6 +137,40 @@ public sealed class Box3DSoaGrabTests
}
}
+ [Fact]
+ public void A_stale_release_cannot_destroy_a_later_grab_in_a_reused_slot()
+ {
+ using var world = new Box3DSoaWorld(capacity: 3, gravityY: 0f, jointCapacity: 1);
+ var sphere = world.AddSphere(1, (0f, 0f, 0f), Radius, Density);
+ var anchor = world.AddAnchor(2, (0f, 0f, 0f));
+ var first = world.AddMotorJoint(anchor, sphere, (0f, 0f, 0f), (5f, 0.7f, 1e6f), (0f, 0f, 0f));
+ world.Step(Dt);
+ world.DestroyJoint(first);
+ world.Step(Dt); // the slot may now be reused
+ var second = world.AddMotorJoint(anchor, sphere, (0f, 0f, 0f), (5f, 0.7f, 1e6f), (0f, 0f, 0f));
+ Assert.Equal(first.Lane, second.Lane);
+ Assert.NotEqual(first.Generation, second.Generation);
+ Assert.Equal(second.Generation, world.View.JointGeneration[second.Lane]);
+
+ Assert.Throws(() => world.DestroyJoint(first)); // the UI's second release click
+ var view = world.View;
+ Assert.Equal((uint)Box3DSoaJointKind.Motor, view.JointKind[second.Lane]);
+ for (var i = 0; i < 90; i++) { world.SetAnchorTarget(anchor, (1f, 0f, 0f), default, Dt); world.Step(Dt); }
+ Assert.Equal(1f, view.PositionX[sphere], 0.02f); // the second grab still holds
+
+ world.DestroyJoint(second);
+ Assert.Throws(() => world.DestroyJoint(second));
+ }
+
+ [Fact]
+ public void The_managed_side_refuses_a_native_library_of_another_abi_in_either_direction()
+ {
+ Assert.Equal(6u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
+ Box3DSoaWorld.RequireNativeAbi(6);
+ Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(5)); // an older native under this managed build
+ Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(7)); // a newer one
+ }
+
[Fact]
public void Only_a_live_motor_joint_can_be_destroyed()
{
@@ -149,8 +183,8 @@ public sealed class Box3DSoaGrabTests
var motor = world.AddMotorJoint(anchor, sphere, (1f, 5f, 0f), (5f, 0.7f, 100f), (0f, 0f, 0f));
Assert.Throws(() => world.DestroyJoint(hinge));
Assert.Throws(() => world.DestroyJoint(weld));
- Assert.Throws(() => world.DestroyJoint(-1));
- Assert.Throws(() => world.DestroyJoint(3));
+ Assert.Throws(() => world.DestroyJoint(new Box3DSoaJointHandle(-1, 0)));
+ Assert.Throws(() => world.DestroyJoint(new Box3DSoaJointHandle(3, 0)));
var view = world.View;
Assert.Equal((uint)Box3DSoaJointKind.Revolute, view.JointKind[hinge]);
world.DestroyJoint(motor);