From 721eee0656ea285cc8cbde5dd6f8489220b46d3e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 20:33:05 +0100 Subject: [PATCH 1/7] Replace managed physics with Box3D runtime boundary --- .gitignore | 2 +- README.md | 49 +- Ymir.slnx | 1 + docs/architecture.md | 58 +- docs/box3d-parity.md | 26 +- native/Ymir.Box3D/ymir_box3d.c | 867 +++++++++++++++++- src/Ymir.Box3D/Box3DNative.cs | 183 ++++ src/Ymir.Box3D/Box3DQueries.cs | 65 ++ src/Ymir.Box3D/Box3DSession.cs | 240 +++++ src/Ymir.Box3D/Properties/AssemblyInfo.cs | 3 + src/Ymir.Box3D/README.md | 13 + src/Ymir.Box3D/Ymir.Box3D.csproj | 58 ++ src/Ymir.Core/PhysicsModel.cs | 33 +- src/Ymir.Core/Properties/AssemblyInfo.cs | 3 + src/Ymir.Core/Ymir.Core.csproj | 3 +- src/Ymir.Core/YmirQueries.cs | 116 +++ .../YmirServicePublicationDocument.cs | 25 +- src/Ymir.Core/YmirSimulator.cs | 140 +-- src/Ymir.Core/YmirSoAWorld.cs | 67 +- src/Ymir.Core/YmirWorldSession.cs | 200 ++++ src/Ymir.Core/YmirWorldStateDocument.cs | 82 +- src/ymir-daemon/Program.cs | 2 +- tests/Ymir.Box3D.Parity/Box3DOracle.cs | 7 + .../Ymir.Box3D.Parity.csproj | 2 +- .../Ymir.Tests/YmirServicePublicationTests.cs | 7 +- tests/Ymir.Tests/YmirSimulatorTests.cs | 115 ++- 26 files changed, 2167 insertions(+), 200 deletions(-) create mode 100644 src/Ymir.Box3D/Box3DNative.cs create mode 100644 src/Ymir.Box3D/Box3DQueries.cs create mode 100644 src/Ymir.Box3D/Box3DSession.cs create mode 100644 src/Ymir.Box3D/Properties/AssemblyInfo.cs create mode 100644 src/Ymir.Box3D/README.md create mode 100644 src/Ymir.Box3D/Ymir.Box3D.csproj create mode 100644 src/Ymir.Core/Properties/AssemblyInfo.cs create mode 100644 src/Ymir.Core/YmirQueries.cs create mode 100644 src/Ymir.Core/YmirWorldSession.cs diff --git a/.gitignore b/.gitignore index 07d6ce7..c3dbd8a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,4 @@ obj/ *.user TestResults/ BenchmarkDotNet.Artifacts/ -artifacts/box3d-native/ +artifacts/ diff --git a/README.md b/README.md index d7c1434..9afa0d5 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Ymir -Ymir is the GameCult Box3D wrapper and authoritative physics daemon for -Aetheria and future world-bearing projects. The name means **Not Invented -Here**. We are taking the hint. +Ymir is the GameCult Box3D wrapper and physics-daemon boundary for Aetheria and +future world-bearing projects. The name means **Not Invented Here**. We are +taking the hint. Box3D owns physics algorithms. Ymir owns the service boundary that makes those algorithms usable as durable, typed GameCult world truth. Unity, renderers, and @@ -15,10 +15,13 @@ authorities. behavior, continuous collision, overlap and cast semantics, contact lifecycle, force and torque lifetime, tolerances, and deterministic step behavior for identical recorded inputs. -- Ymir owns the pinned Box3D version, stable GameCult entity ids, native ABI - isolation, long-lived world sessions, typed commands and facts, - deterministic result ordering, checkpoint reconstruction, CultCache state, - CultMesh publication, and daemon lifecycle. +- Ymir currently owns the pinned Box3D version, stable GameCult entity ids, + native ABI isolation, snapshot lowering, deterministic result ordering, + versioned CultCache snapshots, and a diagnostic Eve publication. +- The Ymir daemon will own long-lived world sessions, typed commands and + receipts, contact lifecycle facts, checkpoint reconstruction, CultMesh + publication, and process supervision. Those are the cutover contract, not a + claim that the current CLI already exposes them. - Aetheria owns gameplay policy and supplies typed physical intent: bodies, fields, tractor targets, forces, projectiles, filters, and the gameplay consequences of Ymir contact facts. @@ -44,11 +47,19 @@ parity suite already witness released Box3D behavior for: - restitution mixing - transient torque lifetime -The legacy managed Ymir solver remains temporarily live while retained Box3D -world sessions, end-contact lifecycle, continuous collision, replay, and -checkpoint reconstruction are connected. It is compatibility scaffolding, not -the target architecture. It will be deleted, along with Ymir's custom geometry -and spatial indexes, once the Box3D-backed path proves the public contract. +The production `Ymir.Box3D` boundary owns the native session ABI. The legacy +snapshot `YmirSimulator.Step` contract now creates an isolated Box3D session, +projects the result, and disposes it. It contains no managed integrator, +collision loop, or impulse solver. + +That snapshot facade deliberately does not pretend to own long-lived world +identity. The retained native session exists behind an internal managed port; +there is not yet a public session registry or command contract. Aetheria will +name one Ymir session per run and zone when that contract is exposed. Its old +process-wide simulator objects are not session identifiers. Planar heading, +angular velocity, and transient torque already pass through Box3D. Typed +begin/end/hit lifecycle facts, checkpoint reconstruction, and non-Windows RID +artifacts remain cutover work. See [the architecture map](docs/architecture.md) and [the executable parity contract](docs/box3d-parity.md). @@ -71,9 +82,17 @@ dotnet test tests\Ymir.Box3D.Parity\Ymir.Box3D.Parity.csproj Box3D is MIT licensed. Its license is retained in `extern/box3d`. +`GameCult.Ymir.Box3D` packages the managed boundary, Box3D license, and native +facade under `runtimes//native`. A local Windows x64 package has loaded in +an isolated empty consumer without CMake or the submodule. A committed release +smoke is still required before that is a repeatable packaging guarantee. Linux +and macOS packages must be produced and smoked on their own release workers +before those RIDs are advertised. + ## Cutover Rule A Ymir cutover is complete only when all runtime stepping, collision queries, -and contact facts come from a retained Box3D world through one Ymir session -primitive. Manual Unity callbacks, Aetheria geometry tests, and the managed -Ymir solver must be structurally unable to decide the result. +and contact facts come from Box3D through an explicitly owned Ymir session. +Manual Unity callbacks and Aetheria geometry tests must be structurally unable +to decide the result. Snapshot compatibility calls may use isolated sessions; +they are not allowed to infer or share retained-world identity. diff --git a/Ymir.slnx b/Ymir.slnx index 53b0fac..63de4d7 100644 --- a/Ymir.slnx +++ b/Ymir.slnx @@ -1,6 +1,7 @@ + diff --git a/docs/architecture.md b/docs/architecture.md index a4e021b..ce93991 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,7 +9,7 @@ Ymir is a wrapper and daemon, not an independent physics-engine research project. Box3D supplies the physics mind. Ymir supplies the memory, nerves, names, and service boundary. -## Owner +## Target Owner A long-lived Box3D `b3World` owns the physical decision: given the current world plus commands for a fixed step, what transforms, velocities, overlaps, @@ -27,7 +27,23 @@ Ymir owns the enclosing session and contract: CultMesh; - supervise world lifetime, failure, replay, and observability. -## Inputs +## Current Body + +The runtime solver cut is complete: Box3D is the only integrator, collision +engine, broadphase, query-geometry implementation, and contact source in the +committed Ymir path. The public `YmirSimulator.Step` compatibility API creates +an isolated internal session for one complete snapshot, projects its output, +and disposes it. Public circle overlap and cast APIs invoke Box3D geometry over +caller-supplied bodies. + +The retained native session and its managed wrapper are internal. The current +CLI has no named session registry, public mutation commands, command receipts, +retained-world queries, or begin/end/hit lifecycle contract. Its CultCache and +Eve output is a regenerated diagnostic projection. The sections marked as +target contract describe the cut still to build; they are not advertisements +of current daemon capability. + +## Target Inputs - stable body and shape definitions - fixed time step and explicit substep count @@ -39,7 +55,7 @@ Ymir owns the enclosing session and contract: Aetheria chooses physical intent and gameplay eligibility. Box3D decides geometry membership and contact. Ymir carries the typed handoff. -## Outputs +## Target Outputs - body transforms and linear/angular velocities - begin, end, and hit contact facts with stable Ymir ids @@ -87,12 +103,21 @@ solver. - transport endpoints or dashboards owning world state; - Box3D opaque ids stored as durable GameCult identity. -## Shared Paths +## Target Shared Paths Direct player commands, agent commands, programmatic spawns, server ticks, -imports, reconnects, replay, and checkpoint recovery all enter one Ymir world -session primitive. DTO compatibility methods may lower into that primitive; -they may not run an alternate step. +imports, reconnects, replay, and checkpoint recovery will enter the same Ymir +session primitive for their named world. Today, DTO compatibility methods +lower into an isolated Box3D session; they may not run an alternate step or +infer retained identity from a body list. + +Session identity must be explicit. A process-wide simulator object, zone index, +or repeated stable body id is not enough to join two calls to the same world. +Aetheria owns run and zone lifetime and will create, retain, and dispose the +corresponding Ymir session after the public port exists. Current projectile +sweep and stationary mine proximity integration can use Ymir's static +Box3D-backed circle-cast and overlap queries, but those calls do not join a +retained world or own contact lifecycle. Radial gravity and tractor attraction are typed force-generation inputs. They are applied to Box3D before stepping. Pickup collection remains an Aetheria @@ -115,6 +140,13 @@ The native facade must remain boring: ## Persistence +`gamecult.ymir.world_state.v1` appends planar direction and angular velocity to +the v0 layout. The v0 reader is an explicit migration path; keys are not +reassigned. Torque is transient command state and is intentionally absent. +Version 1 is a compatibility world snapshot, not a complete retained-session +checkpoint: it does not preserve full shape, material, filter, session tuning, +provenance, or warm contact state. + The canonical checkpoint schema must contain enough typed definitions and state to reconstruct the accepted Box3D world: stable ids, 3D transforms, linear and angular velocity, body/shape/material/filter definitions, session @@ -127,8 +159,10 @@ under a reassigned MessagePack layout. ## Cut Line -The managed Ymir solver, `YmirQueryPrimitives`, and `YmirSpatialIndex` are -deleted when retained Box3D sessions prove: +The managed integrator and circle impulse solver have been deleted from the +runtime path. Any uncommitted `YmirQueryPrimitives` or `YmirSpatialIndex` work +is obsolete and must not be annexed. The retained-session cut continues until +Box3D-backed sessions prove: 1. fixed-step body state projection; 2. begin/end/hit contact lifecycle; @@ -148,7 +182,9 @@ failure fails closed and reports the missing capability. session facts. - Negative source checks prove custom solver and spatial-index authorities are absent after cutover. -- Aetheria smokes prove gravity, contact-gated destruction loot, tractor - attraction, pickup collection, and fast payload hits. +- Aetheria smokes must prove gravity, contact-gated destruction loot, tractor + attraction, pickup collection, and fast payload hits through the retained + contract. Current gravity, pickup-contact, cast, and overlap witnesses cover + only the snapshot/query compatibility path. - Released-client witnesses prove generic Eve clients only observe Ymir and Aetheria provider contracts, never native implementation details. diff --git a/docs/box3d-parity.md b/docs/box3d-parity.md index d9e7790..e03f84f 100644 --- a/docs/box3d-parity.md +++ b/docs/box3d-parity.md @@ -3,7 +3,8 @@ ## Authority Box3D v0.1.0 is Ymir's physics implementation and executable semantics oracle. -The production session cutover is still under construction. The exact upstream source is pinned as the +The production native session ABI and snapshot lowering are live; explicit +retained-world ownership is still being connected. The exact upstream source is pinned as the `extern/box3d` submodule at commit `8441b4a06d6d09dcfb0b0f704df4d847d1437b92`. @@ -15,11 +16,17 @@ torque lifetime, and numeric tolerances. ## Body `native/Ymir.Box3D` statically links the pinned C17 library into one small -shared-library facade. The facade exports only blittable sphere overlap, -sphere cast, capsule-versus-sphere membership, planar pair stepping, torque -lifetime, and version operations. This keeps Box3D's alpha C ABI out of Ymir's +shared-library facade. The facade exports retained sphere-world sessions plus +the overlap, cast, pair-step, torque-lifetime, version, and ABI-layout +operations used by the harness. This keeps Box3D's alpha C ABI out of Ymir's public managed contracts. +Production ABI version 2 uses caller-owned blittable buffers, explicit cdecl, +fixed-width status/count values, compile-time C layout assertions, and a +managed/native layout sentinel before opening a session. Planar direction maps +to Box3D rotation about Y; angular velocity and transient torque remain Box3D +state and commands rather than managed integration. + `tests/Ymir.Box3D.Parity` builds that facade through CMake and invokes it with source-generated .NET interop. Run it with: @@ -50,9 +57,8 @@ is retained in the pinned submodule. ## Cut Line -The current managed collision formulas are transitional. They may exist only -while differential tests prove compatibility. The remaining parity slice -covers retained world sessions, end-contact lifecycle, continuous collision, -and replay. Once those facts are projected through a stable Ymir native port, -the managed solver, query geometry, and spatial indexes are deleted rather -than retained as fallback authority. +The managed integrator and circle collision solver are no longer runtime +authorities. The remaining parity slice covers explicit retained-world +ownership, end-contact lifecycle, continuous collision, and replay. Custom +query geometry and spatial indexes are not fallback authorities; Box3D owns +those edge cases. diff --git a/native/Ymir.Box3D/ymir_box3d.c b/native/Ymir.Box3D/ymir_box3d.c index 0756e3c..0126aa8 100644 --- a/native/Ymir.Box3D/ymir_box3d.c +++ b/native/Ymir.Box3D/ymir_box3d.c @@ -5,10 +5,17 @@ #include #include +#include +#include +#include +#include + #if defined(_WIN32) #define YMIR_EXPORT __declspec(dllexport) +#define YMIR_CALL __cdecl #else #define YMIR_EXPORT __attribute__((visibility("default"))) +#define YMIR_CALL #endif typedef struct ymir_box3d_overlap_result @@ -65,11 +72,561 @@ typedef struct ymir_box3d_torque_result float angular_velocity_after_unforced_step; } ymir_box3d_torque_result; +typedef enum ymir_box3d_status +{ + YMIR_BOX3D_OK = 0, + YMIR_BOX3D_INVALID_ARGUMENT = 1, + YMIR_BOX3D_DUPLICATE_ID = 2, + YMIR_BOX3D_BUFFER_TOO_SMALL = 3, + YMIR_BOX3D_OUT_OF_MEMORY = 4, + YMIR_BOX3D_INTERNAL_ERROR = 5, +} ymir_box3d_status; + +typedef struct ymir_box3d_session_body_input +{ + uint64_t stable_id; + float position_x; + float position_y; + float velocity_x; + float velocity_y; + float direction_x; + float direction_y; + float angular_velocity; + float torque; + float radius; + float mass; + float restitution; + uint32_t is_static; +} ymir_box3d_session_body_input; + +typedef struct ymir_box3d_radial_field_input +{ + float position_x; + float position_y; + float strength; + float radius; +} ymir_box3d_radial_field_input; + +typedef struct ymir_box3d_session_body_output +{ + uint64_t stable_id; + float position_x; + float position_y; + float velocity_x; + float velocity_y; + float direction_x; + float direction_y; + float angular_velocity; +} ymir_box3d_session_body_output; + +typedef struct ymir_box3d_session_contact_output +{ + uint64_t stable_id_a; + uint64_t stable_id_b; + float point_x; + float point_y; + float normal_x; + float normal_y; + float penetration; + float relative_speed; +} ymir_box3d_session_contact_output; + +typedef struct ymir_box3d_session_body +{ + uint64_t stable_id; + b3BodyId body_id; + b3ShapeId shape_id; + float last_position_x; + float last_position_y; + float last_velocity_x; + float last_velocity_y; + float last_direction_x; + float last_direction_y; + float last_angular_velocity; + float pending_torque; + float radius; + float mass; + float restitution; + uint32_t is_static; + int seen; +} ymir_box3d_session_body; + +typedef struct ymir_box3d_session +{ + b3WorldId world_id; + ymir_box3d_session_body* bodies; + int body_count; + int body_capacity; +} ymir_box3d_session; + +_Static_assert(sizeof(ymir_box3d_status) == sizeof(int32_t), "Ymir Box3D status ABI must be 32-bit"); +_Static_assert(sizeof(ymir_box3d_session_body_input) == 56, "Unexpected Ymir Box3D body input layout"); +_Static_assert(sizeof(ymir_box3d_radial_field_input) == 16, "Unexpected Ymir Box3D field layout"); +_Static_assert(sizeof(ymir_box3d_session_body_output) == 40, "Unexpected Ymir Box3D body output layout"); +_Static_assert(sizeof(ymir_box3d_session_contact_output) == 40, "Unexpected Ymir Box3D contact layout"); + static b3Vec3 ymir_vec(float x, float y) { return (b3Vec3){x, 0.0f, y}; } +static int ymir_is_finite(float value) +{ + return isfinite(value) != 0; +} + +static int ymir_session_body_input_is_valid(const ymir_box3d_session_body_input* input) +{ + float direction_length_squared = input != NULL + ? input->direction_x * input->direction_x + input->direction_y * input->direction_y + : 0.0f; + return input != NULL && input->stable_id != 0 && input->stable_id <= (uint64_t)UINTPTR_MAX && + ymir_is_finite(input->position_x) && ymir_is_finite(input->position_y) && + ymir_is_finite(input->velocity_x) && ymir_is_finite(input->velocity_y) && + ymir_is_finite(input->direction_x) && ymir_is_finite(input->direction_y) && + direction_length_squared > 1.0e-8f && ymir_is_finite(input->angular_velocity) && + ymir_is_finite(input->torque) && + ymir_is_finite(input->radius) && input->radius > 0.0f && ymir_is_finite(input->mass) && + (input->is_static != 0 || input->mass > 0.0f) && ymir_is_finite(input->restitution) && + input->restitution >= 0.0f; +} + +static b3Quat ymir_session_rotation(float direction_x, float direction_y) +{ + float angle = atan2f(direction_x, direction_y); + return b3MakeQuatFromAxisAngle((b3Vec3){0.0f, 1.0f, 0.0f}, angle); +} + +static b3Vec3 ymir_session_direction(b3BodyId body_id) +{ + return b3RotateVector(b3Body_GetRotation(body_id), (b3Vec3){0.0f, 0.0f, 1.0f}); +} + +static int ymir_session_find_body(const ymir_box3d_session* session, uint64_t stable_id) +{ + for (int i = 0; i < session->body_count; ++i) + { + if (session->bodies[i].stable_id == stable_id) + { + return i; + } + } + + return -1; +} + +static ymir_box3d_status ymir_session_reserve_bodies(ymir_box3d_session* session, int capacity) +{ + if (capacity <= session->body_capacity) + { + return YMIR_BOX3D_OK; + } + + int new_capacity = session->body_capacity > 0 ? session->body_capacity : 16; + while (new_capacity < capacity) + { + if (new_capacity > INT32_MAX / 2) + { + new_capacity = capacity; + break; + } + new_capacity *= 2; + } + + ymir_box3d_session_body* bodies = + (ymir_box3d_session_body*)realloc(session->bodies, (size_t)new_capacity * sizeof(ymir_box3d_session_body)); + if (bodies == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + + session->bodies = bodies; + session->body_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + +static float ymir_session_density(float mass, float radius) +{ + float volume = 4.0f / 3.0f * B3_PI * radius * radius * radius; + return mass / volume; +} + +static ymir_box3d_status ymir_session_create_body( + ymir_box3d_session* session, + const ymir_box3d_session_body_input* input, + ymir_box3d_session_body* output) +{ + b3BodyDef body_def = b3DefaultBodyDef(); + body_def.type = input->is_static != 0 ? b3_staticBody : b3_dynamicBody; + body_def.position = ymir_vec(input->position_x, input->position_y); + body_def.rotation = ymir_session_rotation(input->direction_x, input->direction_y); + body_def.linearVelocity = ymir_vec(input->velocity_x, input->velocity_y); + body_def.angularVelocity = (b3Vec3){0.0f, input->angular_velocity, 0.0f}; + body_def.motionLocks.linearY = true; + body_def.motionLocks.angularX = true; + body_def.motionLocks.angularZ = true; + body_def.enableSleep = false; + b3BodyId body_id = b3CreateBody(session->world_id, &body_def); + if (B3_IS_NULL(body_id)) + { + return YMIR_BOX3D_INTERNAL_ERROR; + } + + b3ShapeDef shape_def = b3DefaultShapeDef(); + shape_def.userData = (void*)(uintptr_t)input->stable_id; + shape_def.density = input->is_static != 0 ? 0.0f : ymir_session_density(input->mass, input->radius); + shape_def.baseMaterial.friction = 0.0f; + shape_def.baseMaterial.restitution = input->restitution; + shape_def.enableContactEvents = true; + shape_def.enableHitEvents = true; + b3Sphere sphere = {{0.0f, 0.0f, 0.0f}, input->radius}; + b3ShapeId shape_id = b3CreateSphereShape(body_id, &shape_def, &sphere); + if (B3_IS_NULL(shape_id)) + { + b3DestroyBody(body_id); + return YMIR_BOX3D_INTERNAL_ERROR; + } + + *output = (ymir_box3d_session_body){ + .stable_id = input->stable_id, + .body_id = body_id, + .shape_id = shape_id, + .last_position_x = input->position_x, + .last_position_y = input->position_y, + .last_velocity_x = input->velocity_x, + .last_velocity_y = input->velocity_y, + .last_direction_x = input->direction_x, + .last_direction_y = input->direction_y, + .last_angular_velocity = input->angular_velocity, + .pending_torque = input->torque, + .radius = input->radius, + .mass = input->mass, + .restitution = input->restitution, + .is_static = input->is_static != 0, + .seen = 1, + }; + return YMIR_BOX3D_OK; +} + +static void ymir_session_update_body( + ymir_box3d_session_body* body, + const ymir_box3d_session_body_input* input) +{ + int type_changed = body->is_static != (input->is_static != 0); + int radius_changed = body->radius != input->radius; + int mass_changed = body->mass != input->mass; + + if (type_changed) + { + b3Body_SetType(body->body_id, input->is_static != 0 ? b3_staticBody : b3_dynamicBody); + } + + if (radius_changed) + { + b3Sphere sphere = {{0.0f, 0.0f, 0.0f}, input->radius}; + b3Shape_SetSphere(body->shape_id, &sphere); + } + + if (type_changed || radius_changed || mass_changed) + { + float density = input->is_static != 0 ? 0.0f : ymir_session_density(input->mass, input->radius); + b3Shape_SetDensity(body->shape_id, density, false); + b3Body_ApplyMassFromShapes(body->body_id); + } + + if (body->restitution != input->restitution) + { + b3Shape_SetRestitution(body->shape_id, input->restitution); + } + + if (body->last_position_x != input->position_x || body->last_position_y != input->position_y || + body->last_direction_x != input->direction_x || body->last_direction_y != input->direction_y) + { + b3Body_SetTransform( + body->body_id, + ymir_vec(input->position_x, input->position_y), + ymir_session_rotation(input->direction_x, input->direction_y)); + } + + if (type_changed || body->last_velocity_x != input->velocity_x || body->last_velocity_y != input->velocity_y) + { + b3Body_SetLinearVelocity(body->body_id, ymir_vec(input->velocity_x, input->velocity_y)); + } + + if (type_changed || body->last_angular_velocity != input->angular_velocity) + { + b3Body_SetAngularVelocity(body->body_id, (b3Vec3){0.0f, input->angular_velocity, 0.0f}); + } + + body->last_position_x = input->position_x; + body->last_position_y = input->position_y; + body->last_velocity_x = input->velocity_x; + body->last_velocity_y = input->velocity_y; + body->last_direction_x = input->direction_x; + body->last_direction_y = input->direction_y; + body->last_angular_velocity = input->angular_velocity; + body->pending_torque = input->torque; + body->radius = input->radius; + body->mass = input->mass; + body->restitution = input->restitution; + body->is_static = input->is_static != 0; + body->seen = 1; +} + +static uint64_t ymir_session_shape_stable_id(b3ShapeId shape_id) +{ + return (uint64_t)(uintptr_t)b3Shape_GetUserData(shape_id); +} + +typedef struct ymir_box3d_stable_pair +{ + uint64_t first; + uint64_t second; +} ymir_box3d_stable_pair; + +typedef struct ymir_box3d_stable_pair_set +{ + ymir_box3d_stable_pair* pairs; + int count; + int capacity; +} ymir_box3d_stable_pair_set; + +static ymir_box3d_status ymir_session_add_stable_pair( + ymir_box3d_stable_pair_set* set, + uint64_t stable_id_a, + uint64_t stable_id_b, + int* added) +{ + uint64_t first = stable_id_a < stable_id_b ? stable_id_a : stable_id_b; + uint64_t second = stable_id_a < stable_id_b ? stable_id_b : stable_id_a; + for (int i = 0; i < set->count; ++i) + { + if (set->pairs[i].first == first && set->pairs[i].second == second) + { + *added = 0; + return YMIR_BOX3D_OK; + } + } + + if (set->count == set->capacity) + { + int new_capacity = set->capacity > 0 ? set->capacity * 2 : 16; + ymir_box3d_stable_pair* pairs = + (ymir_box3d_stable_pair*)realloc(set->pairs, (size_t)new_capacity * sizeof(ymir_box3d_stable_pair)); + if (pairs == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + set->pairs = pairs; + set->capacity = new_capacity; + } + + set->pairs[set->count++] = (ymir_box3d_stable_pair){first, second}; + *added = 1; + return YMIR_BOX3D_OK; +} + +static int ymir_session_contact_from_manifolds( + const b3ContactData* contact, + ymir_box3d_session_contact_output* result) +{ + const b3Manifold* selected_manifold = NULL; + const b3ManifoldPoint* selected_point = NULL; + for (int manifold_index = 0; manifold_index < contact->manifoldCount; ++manifold_index) + { + const b3Manifold* manifold = contact->manifolds + manifold_index; + for (int point_index = 0; point_index < manifold->pointCount; ++point_index) + { + const b3ManifoldPoint* point = manifold->points + point_index; + if (selected_point == NULL || point->separation < selected_point->separation) + { + selected_manifold = manifold; + selected_point = point; + } + } + } + + if (selected_point == NULL) + { + return 0; + } + + uint64_t stable_id_a = ymir_session_shape_stable_id(contact->shapeIdA); + uint64_t stable_id_b = ymir_session_shape_stable_id(contact->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0 || stable_id_a == stable_id_b) + { + return 0; + } + + b3BodyId body_a = b3Shape_GetBody(contact->shapeIdA); + b3BodyId body_b = b3Shape_GetBody(contact->shapeIdB); + b3Pos center_a = b3Body_GetWorldCenterOfMass(body_a); + b3Pos center_b = b3Body_GetWorldCenterOfMass(body_b); + b3Pos point_a = { + center_a.x + selected_point->anchorA.x, + center_a.y + selected_point->anchorA.y, + center_a.z + selected_point->anchorA.z, + }; + b3Pos point_b = { + center_b.x + selected_point->anchorB.x, + center_b.y + selected_point->anchorB.y, + center_b.z + selected_point->anchorB.z, + }; + *result = (ymir_box3d_session_contact_output){ + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + .point_x = 0.5f * (point_a.x + point_b.x), + .point_y = 0.5f * (point_a.z + point_b.z), + .normal_x = selected_manifold->normal.x, + .normal_y = selected_manifold->normal.z, + .penetration = selected_point->separation < 0.0f ? -selected_point->separation : 0.0f, + .relative_speed = selected_point->normalVelocity, + }; + return 1; +} + +static ymir_box3d_status ymir_session_emit_contact( + ymir_box3d_stable_pair_set* seen, + const ymir_box3d_session_contact_output* contact, + ymir_box3d_session_contact_output* output, + int capacity, + int* total) +{ + int added = 0; + ymir_box3d_status status = + ymir_session_add_stable_pair(seen, contact->stable_id_a, contact->stable_id_b, &added); + if (status != YMIR_BOX3D_OK || !added) + { + return status; + } + + if (output != NULL) + { + if (*total >= capacity) + { + return YMIR_BOX3D_BUFFER_TOO_SMALL; + } + output[*total] = *contact; + } + *total += 1; + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_visit_contacts( + const ymir_box3d_session* session, + ymir_box3d_session_contact_output* output, + int capacity, + int* count) +{ + int total = 0; + ymir_box3d_stable_pair_set seen = {0}; + for (int body_index = 0; body_index < session->body_count; ++body_index) + { + b3ShapeId source_shape = session->bodies[body_index].shape_id; + int contact_capacity = b3Shape_GetContactCapacity(source_shape); + if (contact_capacity <= 0) + { + continue; + } + + b3ContactData* contacts = (b3ContactData*)malloc((size_t)contact_capacity * sizeof(b3ContactData)); + if (contacts == NULL) + { + free(seen.pairs); + return YMIR_BOX3D_OUT_OF_MEMORY; + } + + int contact_count = b3Shape_GetContactData(source_shape, contacts, contact_capacity); + for (int contact_index = 0; contact_index < contact_count; ++contact_index) + { + const b3ContactData* contact = contacts + contact_index; + uint64_t stable_id_a = ymir_session_shape_stable_id(contact->shapeIdA); + uint64_t stable_id_b = ymir_session_shape_stable_id(contact->shapeIdB); + uint64_t source_stable_id = session->bodies[body_index].stable_id; + uint64_t first_stable_id = stable_id_a < stable_id_b ? stable_id_a : stable_id_b; + if (stable_id_a == 0 || stable_id_b == 0 || source_stable_id != first_stable_id) + { + continue; + } + + ymir_box3d_session_contact_output candidate; + if (ymir_session_contact_from_manifolds(contact, &candidate)) + { + ymir_box3d_status status = + ymir_session_emit_contact(&seen, &candidate, output, capacity, &total); + if (status != YMIR_BOX3D_OK) + { + free(contacts); + free(seen.pairs); + return status; + } + } + } + free(contacts); + } + + b3ContactEvents events = b3World_GetContactEvents(session->world_id); + for (int event_index = 0; event_index < events.hitCount; ++event_index) + { + const b3ContactHitEvent* event = events.hitEvents + event_index; + if (!b3Shape_IsValid(event->shapeIdA) || !b3Shape_IsValid(event->shapeIdB)) + { + continue; + } + + uint64_t stable_id_a = ymir_session_shape_stable_id(event->shapeIdA); + uint64_t stable_id_b = ymir_session_shape_stable_id(event->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0 || stable_id_a == stable_id_b) + { + continue; + } + + ymir_box3d_session_contact_output candidate = { + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + .point_x = event->point.x, + .point_y = event->point.z, + .normal_x = event->normal.x, + .normal_y = event->normal.z, + .penetration = 0.0f, + .relative_speed = -event->approachSpeed, + }; + ymir_box3d_status status = ymir_session_emit_contact(&seen, &candidate, output, capacity, &total); + if (status != YMIR_BOX3D_OK) + { + free(seen.pairs); + return status; + } + } + + for (int event_index = 0; event_index < events.beginCount; ++event_index) + { + const b3ContactBeginTouchEvent* event = events.beginEvents + event_index; + if (!b3Contact_IsValid(event->contactId)) + { + continue; + } + + b3ContactData contact = b3Contact_GetData(event->contactId); + ymir_box3d_session_contact_output candidate; + if (!ymir_session_contact_from_manifolds(&contact, &candidate)) + { + continue; + } + + ymir_box3d_status status = ymir_session_emit_contact(&seen, &candidate, output, capacity, &total); + if (status != YMIR_BOX3D_OK) + { + free(seen.pairs); + return status; + } + } + + free(seen.pairs); + *count = total; + return YMIR_BOX3D_OK; +} + static b3BodyId ymir_create_body(b3WorldId world_id, const ymir_box3d_body_input* input) { b3BodyDef body_def = b3DefaultBodyDef(); @@ -111,7 +668,7 @@ static ymir_box3d_body_output ymir_read_body(b3BodyId body_id) }; } -YMIR_EXPORT int ymir_box3d_get_version(int* major, int* minor, int* revision) +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_version(int32_t* major, int32_t* minor, int32_t* revision) { b3Version version = b3GetVersion(); *major = version.major; @@ -120,7 +677,7 @@ YMIR_EXPORT int ymir_box3d_get_version(int* major, int* minor, int* revision) return b3IsDoublePrecision() ? 1 : 0; } -YMIR_EXPORT ymir_box3d_overlap_result ymir_box3d_overlap_spheres( +YMIR_EXPORT ymir_box3d_overlap_result YMIR_CALL ymir_box3d_overlap_spheres( float query_x, float query_y, float query_radius, @@ -149,7 +706,7 @@ YMIR_EXPORT ymir_box3d_overlap_result ymir_box3d_overlap_spheres( }; } -YMIR_EXPORT ymir_box3d_overlap_result ymir_box3d_overlap_capsule_sphere( +YMIR_EXPORT ymir_box3d_overlap_result YMIR_CALL ymir_box3d_overlap_capsule_sphere( float start_x, float start_y, float end_x, @@ -180,7 +737,7 @@ YMIR_EXPORT ymir_box3d_overlap_result ymir_box3d_overlap_capsule_sphere( }; } -YMIR_EXPORT ymir_box3d_cast_result ymir_box3d_cast_sphere( +YMIR_EXPORT ymir_box3d_cast_result YMIR_CALL ymir_box3d_cast_sphere( float origin_x, float origin_y, float translation_x, @@ -211,7 +768,7 @@ YMIR_EXPORT ymir_box3d_cast_result ymir_box3d_cast_sphere( }; } -YMIR_EXPORT void ymir_box3d_step_pair( +YMIR_EXPORT void YMIR_CALL ymir_box3d_step_pair( const ymir_box3d_body_input* body_a_input, const ymir_box3d_body_input* body_b_input, float time_step, @@ -239,7 +796,7 @@ YMIR_EXPORT void ymir_box3d_step_pair( b3DestroyWorld(world_id); } -YMIR_EXPORT ymir_box3d_torque_result ymir_box3d_torque_lifetime(float torque, float time_step, int sub_step_count) +YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float torque, float time_step, int32_t sub_step_count) { b3WorldDef world_def = b3DefaultWorldDef(); world_def.gravity = b3Vec3_zero; @@ -262,3 +819,301 @@ YMIR_EXPORT ymir_box3d_torque_result ymir_box3d_torque_lifetime(float torque, fl return (ymir_box3d_torque_result){after_applied_step, after_unforced_step}; } + +YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_get_abi_version(void) +{ + return 2; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_abi_layout( + uint32_t* body_input_size, + uint32_t* field_input_size, + uint32_t* body_output_size, + uint32_t* contact_output_size) +{ + if (body_input_size == NULL || field_input_size == NULL || body_output_size == NULL || contact_output_size == NULL) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + + *body_input_size = (uint32_t)sizeof(ymir_box3d_session_body_input); + *field_input_size = (uint32_t)sizeof(ymir_box3d_radial_field_input); + *body_output_size = (uint32_t)sizeof(ymir_box3d_session_body_output); + *contact_output_size = (uint32_t)sizeof(ymir_box3d_session_contact_output); + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_create(ymir_box3d_session** output) +{ + if (output == NULL) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + *output = NULL; + + ymir_box3d_session* session = (ymir_box3d_session*)calloc(1, sizeof(ymir_box3d_session)); + if (session == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + + b3WorldDef world_def = b3DefaultWorldDef(); + world_def.gravity = b3Vec3_zero; + world_def.enableSleep = false; + world_def.workerCount = 1; + session->world_id = b3CreateWorld(&world_def); + if (B3_IS_NULL(session->world_id)) + { + free(session); + return YMIR_BOX3D_INTERNAL_ERROR; + } + + *output = session; + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT void YMIR_CALL ymir_box3d_session_destroy(ymir_box3d_session* session) +{ + if (session == NULL) + { + return; + } + + if (B3_IS_NON_NULL(session->world_id) && b3World_IsValid(session->world_id)) + { + b3DestroyWorld(session->world_id); + } + free(session->bodies); + free(session); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_sync_bodies( + ymir_box3d_session* session, + const ymir_box3d_session_body_input* bodies, + int32_t body_count) +{ + if (session == NULL || body_count < 0 || (body_count > 0 && bodies == NULL)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + + for (int i = 0; i < body_count; ++i) + { + if (!ymir_session_body_input_is_valid(bodies + i)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + for (int j = 0; j < i; ++j) + { + if (bodies[i].stable_id == bodies[j].stable_id) + { + return YMIR_BOX3D_DUPLICATE_ID; + } + } + } + + ymir_box3d_status status = ymir_session_reserve_bodies(session, session->body_count + body_count); + if (status != YMIR_BOX3D_OK) + { + return status; + } + + for (int i = 0; i < session->body_count; ++i) + { + session->bodies[i].seen = 0; + } + + for (int i = 0; i < body_count; ++i) + { + int body_index = ymir_session_find_body(session, bodies[i].stable_id); + if (body_index >= 0) + { + ymir_session_update_body(session->bodies + body_index, bodies + i); + continue; + } + + ymir_box3d_session_body body; + status = ymir_session_create_body(session, bodies + i, &body); + if (status != YMIR_BOX3D_OK) + { + return status; + } + session->bodies[session->body_count++] = body; + } + + for (int i = session->body_count - 1; i >= 0; --i) + { + if (session->bodies[i].seen) + { + continue; + } + + b3DestroyBody(session->bodies[i].body_id); + session->bodies[i] = session->bodies[session->body_count - 1]; + session->body_count -= 1; + } + + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( + ymir_box3d_session* session, + float time_step, + int32_t sub_step_count, + const ymir_box3d_radial_field_input* fields, + int32_t field_count) +{ + if (session == NULL || !ymir_is_finite(time_step) || time_step <= 0.0f || sub_step_count <= 0 || + field_count < 0 || (field_count > 0 && fields == NULL)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + + for (int field_index = 0; field_index < field_count; ++field_index) + { + const ymir_box3d_radial_field_input* field = fields + field_index; + if (!ymir_is_finite(field->position_x) || !ymir_is_finite(field->position_y) || + !ymir_is_finite(field->strength) || !ymir_is_finite(field->radius)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + } + + for (int body_index = 0; body_index < session->body_count; ++body_index) + { + ymir_box3d_session_body* body = session->bodies + body_index; + if (body->is_static) + { + body->pending_torque = 0.0f; + continue; + } + + if (body->pending_torque != 0.0f) + { + b3Body_ApplyTorque(body->body_id, (b3Vec3){0.0f, body->pending_torque, 0.0f}, true); + } + body->pending_torque = 0.0f; + + b3Pos position = b3Body_GetPosition(body->body_id); + float acceleration_x = 0.0f; + float acceleration_y = 0.0f; + for (int field_index = 0; field_index < field_count; ++field_index) + { + const ymir_box3d_radial_field_input* field = fields + field_index; + if (field->radius <= 0.0f || field->strength == 0.0f) + { + continue; + } + + float delta_x = field->position_x - position.x; + float delta_y = field->position_y - position.z; + float distance_squared = delta_x * delta_x + delta_y * delta_y; + if (distance_squared <= 0.0f) + { + continue; + } + + float distance = sqrtf(distance_squared); + if (distance > field->radius) + { + continue; + } + + float falloff = 1.0f - distance / field->radius; + float magnitude = field->strength * falloff / distance; + acceleration_x += delta_x * magnitude; + acceleration_y += delta_y * magnitude; + } + + if (acceleration_x != 0.0f || acceleration_y != 0.0f) + { + float mass = b3Body_GetMass(body->body_id); + b3Body_ApplyForceToCenter(body->body_id, ymir_vec(mass * acceleration_x, mass * acceleration_y), true); + } + } + + b3World_Step(session->world_id, time_step, sub_step_count); + for (int i = 0; i < session->body_count; ++i) + { + b3Pos position = b3Body_GetPosition(session->bodies[i].body_id); + b3Vec3 velocity = b3Body_GetLinearVelocity(session->bodies[i].body_id); + b3Vec3 direction = ymir_session_direction(session->bodies[i].body_id); + b3Vec3 angular_velocity = b3Body_GetAngularVelocity(session->bodies[i].body_id); + session->bodies[i].last_position_x = position.x; + session->bodies[i].last_position_y = position.z; + session->bodies[i].last_velocity_x = velocity.x; + session->bodies[i].last_velocity_y = velocity.z; + session->bodies[i].last_direction_x = direction.x; + session->bodies[i].last_direction_y = direction.z; + session->bodies[i].last_angular_velocity = angular_velocity.y; + } + + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_get_body_count(const ymir_box3d_session* session) +{ + return session != NULL ? session->body_count : -YMIR_BOX3D_INVALID_ARGUMENT; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_copy_bodies( + const ymir_box3d_session* session, + ymir_box3d_session_body_output* output, + int32_t capacity, + int32_t* written) +{ + if (session == NULL || written == NULL || capacity < 0 || (capacity > 0 && output == NULL)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + *written = session->body_count; + if (capacity < session->body_count) + { + return YMIR_BOX3D_BUFFER_TOO_SMALL; + } + + for (int i = 0; i < session->body_count; ++i) + { + b3Pos position = b3Body_GetPosition(session->bodies[i].body_id); + b3Vec3 velocity = b3Body_GetLinearVelocity(session->bodies[i].body_id); + b3Vec3 direction = ymir_session_direction(session->bodies[i].body_id); + b3Vec3 angular_velocity = b3Body_GetAngularVelocity(session->bodies[i].body_id); + output[i] = (ymir_box3d_session_body_output){ + .stable_id = session->bodies[i].stable_id, + .position_x = position.x, + .position_y = position.z, + .velocity_x = velocity.x, + .velocity_y = velocity.z, + .direction_x = direction.x, + .direction_y = direction.z, + .angular_velocity = angular_velocity.y, + }; + } + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_get_contact_count(const ymir_box3d_session* session) +{ + if (session == NULL) + { + return -YMIR_BOX3D_INVALID_ARGUMENT; + } + + int count = 0; + ymir_box3d_status status = ymir_session_visit_contacts(session, NULL, 0, &count); + return status == YMIR_BOX3D_OK ? count : -(int)status; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_copy_contacts( + const ymir_box3d_session* session, + ymir_box3d_session_contact_output* output, + int32_t capacity, + int32_t* written) +{ + if (session == NULL || written == NULL || capacity < 0 || (capacity > 0 && output == NULL)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + *written = 0; + return ymir_session_visit_contacts(session, output, capacity, written); +} diff --git a/src/Ymir.Box3D/Box3DNative.cs b/src/Ymir.Box3D/Box3DNative.cs new file mode 100644 index 0000000..86b3615 --- /dev/null +++ b/src/Ymir.Box3D/Box3DNative.cs @@ -0,0 +1,183 @@ +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using Microsoft.Win32.SafeHandles; + +namespace Ymir.Box3D; + +internal enum Box3DStatus +{ + Ok = 0, + InvalidArgument = 1, + DuplicateId = 2, + BufferTooSmall = 3, + OutOfMemory = 4, + InternalError = 5 +} + +internal static partial class Box3DNative +{ + internal const string LibraryName = "ymir_box3d"; + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial uint ymir_box3d_get_abi_version(); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_get_abi_layout( + out uint bodyInputSize, + out uint fieldInputSize, + out uint bodyOutputSize, + out uint contactOutputSize); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_get_version(out int major, out int minor, out int revision); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DCastOutput ymir_box3d_cast_sphere( + float originX, + float originZ, + float translationX, + float translationZ, + float queryRadius, + float bodyX, + float bodyZ, + float bodyRadius, + int canEncroach); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DOverlapOutput ymir_box3d_overlap_spheres( + float queryX, + float queryZ, + float queryRadius, + float bodyX, + float bodyZ, + float bodyRadius); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_create(out nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial void ymir_box3d_session_destroy(nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_sync_bodies( + Box3DSessionHandle session, + Box3DBodyInput* bodies, + int bodyCount); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_step( + Box3DSessionHandle session, + float deltaTime, + int substepCount, + Box3DRadialField* fields, + int fieldCount); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_body_count(Box3DSessionHandle session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_copy_bodies( + Box3DSessionHandle session, + Box3DBodyOutput* output, + int capacity, + out int written); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_contact_count(Box3DSessionHandle session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_copy_contacts( + Box3DSessionHandle session, + Box3DContactOutput* output, + int capacity, + out int written); +} + +internal sealed class Box3DSessionHandle : SafeHandleZeroOrMinusOneIsInvalid +{ + private Box3DSessionHandle() : base(true) + { + } + + internal Box3DSessionHandle(nint value) : base(true) => SetHandle(value); + + protected override bool ReleaseHandle() + { + Box3DNative.ymir_box3d_session_destroy(handle); + return true; + } +} + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DBodyInput( + ulong StableId, + float PositionX, + float PositionZ, + float VelocityX, + float VelocityZ, + float DirectionX, + float DirectionZ, + float AngularVelocity, + float Torque, + float Radius, + float Mass, + float Restitution, + uint IsStatic); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DRadialField( + float PositionX, + float PositionZ, + float Strength, + float Radius); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DBodyOutput( + ulong StableId, + float PositionX, + float PositionZ, + float VelocityX, + float VelocityZ, + float DirectionX, + float DirectionZ, + float AngularVelocity); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DContactOutput( + ulong StableIdA, + ulong StableIdB, + float PointX, + float PointZ, + float NormalX, + float NormalZ, + float Penetration, + float RelativeSpeed); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DCastOutput( + int Hit, + float Fraction, + float PointX, + float PointZ, + float NormalX, + float NormalZ); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DOverlapOutput( + int Hit, + float Distance, + float NormalX, + float NormalZ); diff --git a/src/Ymir.Box3D/Box3DQueries.cs b/src/Ymir.Box3D/Box3DQueries.cs new file mode 100644 index 0000000..a2f480f --- /dev/null +++ b/src/Ymir.Box3D/Box3DQueries.cs @@ -0,0 +1,65 @@ +namespace Ymir.Box3D; + +internal readonly record struct Box3DSphereCastHit( + float Fraction, + float PointX, + float PointZ, + float NormalX, + float NormalZ); + +internal readonly record struct Box3DSphereOverlapHit(float Distance, float NormalX, float NormalZ); + +internal static class Box3DQueries +{ + internal static Box3DSphereOverlapHit? OverlapSpheres( + float queryX, + float queryZ, + float queryRadius, + float bodyX, + float bodyZ, + float bodyRadius) + { + Box3DSession.EnsureCompatibleNativeLibrary(); + var output = Box3DNative.ymir_box3d_overlap_spheres( + queryX, + queryZ, + queryRadius, + bodyX, + bodyZ, + bodyRadius); + return output.Hit == 0 + ? null + : new Box3DSphereOverlapHit(output.Distance, output.NormalX, output.NormalZ); + } + + internal static Box3DSphereCastHit? CastSphere( + float originX, + float originZ, + float translationX, + float translationZ, + float queryRadius, + float bodyX, + float bodyZ, + float bodyRadius) + { + Box3DSession.EnsureCompatibleNativeLibrary(); + var output = Box3DNative.ymir_box3d_cast_sphere( + originX, + originZ, + translationX, + translationZ, + queryRadius, + bodyX, + bodyZ, + bodyRadius, + canEncroach: 0); + return output.Hit == 0 + ? null + : new Box3DSphereCastHit( + output.Fraction, + output.PointX, + output.PointZ, + output.NormalX, + output.NormalZ); + } +} diff --git a/src/Ymir.Box3D/Box3DSession.cs b/src/Ymir.Box3D/Box3DSession.cs new file mode 100644 index 0000000..dc409a9 --- /dev/null +++ b/src/Ymir.Box3D/Box3DSession.cs @@ -0,0 +1,240 @@ +using System.Runtime.InteropServices; + +namespace Ymir.Box3D; + +internal readonly record struct Box3DBody( + ulong StableId, + float PositionX, + float PositionZ, + float VelocityX, + float VelocityZ, + float DirectionX, + float DirectionZ, + float AngularVelocity, + float Torque, + float Radius, + float Mass, + float Restitution, + bool IsStatic); + +internal readonly record struct Box3DField(float PositionX, float PositionZ, float Strength, float Radius); + +internal readonly record struct Box3DBodyState( + ulong StableId, + float PositionX, + float PositionZ, + float VelocityX, + float VelocityZ, + float DirectionX, + float DirectionZ, + float AngularVelocity); + +internal readonly record struct Box3DContact( + ulong StableIdA, + ulong StableIdB, + float PointX, + float PointZ, + float NormalX, + float NormalZ, + float Penetration, + float RelativeSpeed); + +internal sealed class Box3DSession : IDisposable +{ + internal const uint AbiVersion = 2; + internal const int DefaultSubstepCount = 4; + + private readonly Box3DSessionHandle _handle; + private bool _disposed; + + internal Box3DSession() + { + EnsureCompatibleNativeLibrary(); + ThrowIfFailed(Box3DNative.ymir_box3d_session_create(out var value), "create session"); + if (value == 0) + { + throw new InvalidOperationException("Box3D returned a null Ymir session."); + } + + _handle = new Box3DSessionHandle(value); + } + + internal unsafe void SyncBodies(ReadOnlySpan bodies) + { + ThrowIfDisposed(); + var native = new Box3DBodyInput[bodies.Length]; + for (var i = 0; i < bodies.Length; i++) + { + var body = bodies[i]; + native[i] = new Box3DBodyInput( + body.StableId, + body.PositionX, + body.PositionZ, + body.VelocityX, + body.VelocityZ, + body.DirectionX, + body.DirectionZ, + body.AngularVelocity, + body.Torque, + body.Radius, + body.Mass, + body.Restitution, + body.IsStatic ? 1u : 0u); + } + + fixed (Box3DBodyInput* pointer = native) + { + var status = Box3DNative.ymir_box3d_session_sync_bodies(_handle, pointer, native.Length); + if (status is Box3DStatus.OutOfMemory or Box3DStatus.InternalError) + { + Dispose(); + } + ThrowIfFailed(status, "synchronize bodies"); + } + } + + internal unsafe void Step(float deltaTime, ReadOnlySpan fields, int substepCount = DefaultSubstepCount) + { + ThrowIfDisposed(); + if (!float.IsFinite(deltaTime) || deltaTime <= 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(deltaTime), "Delta time must be finite and positive."); + } + + if (substepCount <= 0) + { + throw new ArgumentOutOfRangeException(nameof(substepCount), "Substep count must be positive."); + } + + var native = new Box3DRadialField[fields.Length]; + for (var i = 0; i < fields.Length; i++) + { + native[i] = new Box3DRadialField(fields[i].PositionX, fields[i].PositionZ, fields[i].Strength, fields[i].Radius); + } + + fixed (Box3DRadialField* pointer = native) + { + ThrowIfFailed( + Box3DNative.ymir_box3d_session_step(_handle, deltaTime, substepCount, pointer, native.Length), + "step session"); + } + } + + internal unsafe Box3DBodyState[] CopyBodies() + { + ThrowIfDisposed(); + var count = Box3DNative.ymir_box3d_session_get_body_count(_handle); + if (count < 0) + { + throw new InvalidOperationException("Box3D returned an invalid body count."); + } + + var native = new Box3DBodyOutput[count]; + fixed (Box3DBodyOutput* pointer = native) + { + ThrowIfFailed(Box3DNative.ymir_box3d_session_copy_bodies(_handle, pointer, count, out var written), "copy bodies"); + if (written != count) + { + throw new InvalidOperationException($"Box3D body snapshot changed during copy: expected {count}, received {written}."); + } + } + + return native.Select(body => new Box3DBodyState( + body.StableId, + body.PositionX, + body.PositionZ, + body.VelocityX, + body.VelocityZ, + body.DirectionX, + body.DirectionZ, + body.AngularVelocity)).ToArray(); + } + + internal unsafe Box3DContact[] CopyContacts() + { + ThrowIfDisposed(); + var count = Box3DNative.ymir_box3d_session_get_contact_count(_handle); + if (count < 0) + { + throw new InvalidOperationException("Box3D returned an invalid contact count."); + } + + var native = new Box3DContactOutput[count]; + fixed (Box3DContactOutput* pointer = native) + { + ThrowIfFailed(Box3DNative.ymir_box3d_session_copy_contacts(_handle, pointer, count, out var written), "copy contacts"); + if (written != count) + { + throw new InvalidOperationException($"Box3D contact snapshot changed during copy: expected {count}, received {written}."); + } + } + + return native.Select(contact => new Box3DContact( + contact.StableIdA, + contact.StableIdB, + contact.PointX, + contact.PointZ, + contact.NormalX, + contact.NormalZ, + contact.Penetration, + contact.RelativeSpeed)).ToArray(); + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _handle.Dispose(); + _disposed = true; + } + + internal static void EnsureCompatibleNativeLibrary() + { + var abi = Box3DNative.ymir_box3d_get_abi_version(); + if (abi != AbiVersion) + { + throw new InvalidOperationException($"Ymir Box3D ABI mismatch. Managed expects {AbiVersion}, native provides {abi}."); + } + + ThrowIfFailed( + Box3DNative.ymir_box3d_get_abi_layout( + out var bodyInputSize, + out var fieldInputSize, + out var bodyOutputSize, + out var contactOutputSize), + "read native ABI layout"); + EnsureSize(bodyInputSize); + EnsureSize(fieldInputSize); + EnsureSize(bodyOutputSize); + EnsureSize(contactOutputSize); + + Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision); + if (major != 0 || minor != 1 || revision != 0) + { + throw new InvalidOperationException($"Ymir requires Box3D 0.1.0, but loaded {major}.{minor}.{revision}."); + } + } + + private static void EnsureSize(uint nativeSize) where T : struct + { + var managedSize = checked((uint)Marshal.SizeOf()); + if (managedSize != nativeSize) + { + throw new InvalidOperationException( + $"Ymir Box3D ABI layout mismatch for {typeof(T).Name}. Managed expects {managedSize} bytes, native provides {nativeSize}."); + } + } + + private static void ThrowIfFailed(Box3DStatus status, string operation) + { + if (status != Box3DStatus.Ok) + { + throw new InvalidOperationException($"Ymir could not {operation}: native Box3D status {status}."); + } + } + + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); +} diff --git a/src/Ymir.Box3D/Properties/AssemblyInfo.cs b/src/Ymir.Box3D/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..65a30aa --- /dev/null +++ b/src/Ymir.Box3D/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Ymir.Core")] diff --git a/src/Ymir.Box3D/README.md b/src/Ymir.Box3D/README.md new file mode 100644 index 0000000..3e797c4 --- /dev/null +++ b/src/Ymir.Box3D/README.md @@ -0,0 +1,13 @@ +# GameCult.Ymir.Box3D + +This is Ymir's private managed/native boundary for pinned Box3D v0.1.0. It is +installed transitively by Ymir; products and clients should reference Ymir's +typed session contracts instead of this package. + +The package includes the compiled native facade under `runtimes//native`. +Package consumers do not need CMake, a C compiler, or the Box3D submodule. +Missing or ABI-incompatible native assets fail closed when Ymir opens a physics +session. + +Source builds of Ymir use CMake to compile the pinned submodule. Box3D is MIT +licensed; its license is included in the package. diff --git a/src/Ymir.Box3D/Ymir.Box3D.csproj b/src/Ymir.Box3D/Ymir.Box3D.csproj new file mode 100644 index 0000000..8664858 --- /dev/null +++ b/src/Ymir.Box3D/Ymir.Box3D.csproj @@ -0,0 +1,58 @@ + + + + net8.0 + enable + enable + true + Ymir.Box3D + Ymir.Box3D + Native ABI boundary between Ymir sessions and pinned Box3D. + GameCult.Ymir.Box3D + 0.1.0 + GameCult + true + README.md + $(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D + $(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\production\$(Configuration) + C:\Program Files\CMake\bin\cmake.exe + cmake + + + + + + + + + + + + + + + + diff --git a/src/Ymir.Core/PhysicsModel.cs b/src/Ymir.Core/PhysicsModel.cs index 00ecd1b..188215c 100644 --- a/src/Ymir.Core/PhysicsModel.cs +++ b/src/Ymir.Core/PhysicsModel.cs @@ -18,7 +18,10 @@ public sealed record PhysicsBody( float Radius, float Mass, bool IsStatic = false, - float Restitution = 0.2f); + float Restitution = 0.2f, + Vec2? Direction = null, + float AngularVelocity = 0.0f, + float Torque = 0.0f); public sealed record RadialField( string Id, @@ -46,3 +49,31 @@ public sealed record ContactEvent( public sealed record SimulationStepResult( YmirWorld World, IReadOnlyList Contacts); + +public sealed record CircleCastQueryRequest( + Vec2 Origin, + Vec2 Direction, + float Distance, + float Radius, + IReadOnlyList Bodies); + +public sealed record CircleCastHit( + string BodyId, + Vec2 Point, + Vec2 Normal, + float Distance); + +public sealed record CircleCastQueryResult(IReadOnlyList Hits); + +public sealed record CircleOverlapQueryRequest( + Vec2 Center, + float Radius, + IReadOnlyList Bodies); + +public sealed record CircleOverlapHit( + string BodyId, + Vec2 Point, + Vec2 Normal, + float Distance); + +public sealed record CircleOverlapQueryResult(IReadOnlyList Hits); diff --git a/src/Ymir.Core/Properties/AssemblyInfo.cs b/src/Ymir.Core/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..53b0ddf --- /dev/null +++ b/src/Ymir.Core/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Ymir.Tests")] diff --git a/src/Ymir.Core/Ymir.Core.csproj b/src/Ymir.Core/Ymir.Core.csproj index 241aa28..00ea67f 100644 --- a/src/Ymir.Core/Ymir.Core.csproj +++ b/src/Ymir.Core/Ymir.Core.csproj @@ -6,6 +6,7 @@ + @@ -18,7 +19,7 @@ enable Ymir.Core Ymir.Core - GameCult physics/world substrate engine built on CultMath. + GameCult physics session daemon and contracts backed by pinned Box3D. GameCult diff --git a/src/Ymir.Core/YmirQueries.cs b/src/Ymir.Core/YmirQueries.cs new file mode 100644 index 0000000..19cf5a1 --- /dev/null +++ b/src/Ymir.Core/YmirQueries.cs @@ -0,0 +1,116 @@ +using Ymir.Box3D; + +namespace Ymir.Core; + +public static class YmirQueries +{ + public static CircleOverlapQueryResult OverlapCircle(CircleOverlapQueryRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(request), "Overlap radius must be finite and positive."); + } + if (!float.IsFinite(request.Center.X) || !float.IsFinite(request.Center.Y)) + { + throw new ArgumentOutOfRangeException(nameof(request), "Overlap center must be finite."); + } + + var hits = new List(); + foreach (var body in request.Bodies) + { + ValidateQueryBody(body, request); + var hit = Box3DQueries.OverlapSpheres( + request.Center.X, + request.Center.Y, + request.Radius, + body.Position.X, + body.Position.Y, + body.Radius); + if (hit is not { } value) + { + continue; + } + + hits.Add(new CircleOverlapHit( + body.Id, + request.Center, + new Vec2(value.NormalX, value.NormalZ), + value.Distance)); + } + + return new CircleOverlapQueryResult(hits + .OrderBy(hit => hit.Distance) + .ThenBy(hit => hit.BodyId, StringComparer.Ordinal) + .ToArray()); + } + + public static CircleCastQueryResult CastCircle(CircleCastQueryRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (!float.IsFinite(request.Distance) || request.Distance < 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(request), "Cast distance must be finite and non-negative."); + } + if (!float.IsFinite(request.Radius) || request.Radius <= 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(request), "Cast radius must be finite and positive."); + } + if (!float.IsFinite(request.Origin.X) || !float.IsFinite(request.Origin.Y)) + { + throw new ArgumentOutOfRangeException(nameof(request), "Cast origin must be finite."); + } + + var directionLengthSquared = request.Direction.X * request.Direction.X + request.Direction.Y * request.Direction.Y; + if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f) + { + throw new ArgumentOutOfRangeException(nameof(request), "Cast direction must be finite and non-zero."); + } + + var inverseLength = 1.0f / MathF.Sqrt(directionLengthSquared); + var translationX = request.Direction.X * inverseLength * request.Distance; + var translationY = request.Direction.Y * inverseLength * request.Distance; + var hits = new List(); + foreach (var body in request.Bodies) + { + ValidateQueryBody(body, request); + + var hit = Box3DQueries.CastSphere( + request.Origin.X, + request.Origin.Y, + translationX, + translationY, + request.Radius, + body.Position.X, + body.Position.Y, + body.Radius); + if (hit is not { } value) + { + continue; + } + + hits.Add(new CircleCastHit( + body.Id, + new Vec2(value.PointX, value.PointZ), + new Vec2(value.NormalX, value.NormalZ), + value.Fraction * request.Distance)); + } + + return new CircleCastQueryResult(hits + .OrderBy(hit => hit.Distance) + .ThenBy(hit => hit.BodyId, StringComparer.Ordinal) + .ToArray()); + } + + private static void ValidateQueryBody(PhysicsBody body, object request) + { + if (string.IsNullOrWhiteSpace(body.Id) || + !float.IsFinite(body.Position.X) || + !float.IsFinite(body.Position.Y) || + !float.IsFinite(body.Radius) || + body.Radius <= 0.0f) + { + throw new ArgumentException("Query bodies require stable ids and finite positive radii.", nameof(request)); + } + } +} diff --git a/src/Ymir.Core/YmirServicePublicationDocument.cs b/src/Ymir.Core/YmirServicePublicationDocument.cs index 0573799..4b492ea 100644 --- a/src/Ymir.Core/YmirServicePublicationDocument.cs +++ b/src/Ymir.Core/YmirServicePublicationDocument.cs @@ -17,7 +17,7 @@ public sealed class YmirProviderAdvertisementDocument public string Title { get; set; } = "Ymir Physics"; [Key(2)] - public string Description { get; set; } = "GameCult authoritative Box3D session wrapper and physics daemon."; + public string Description { get; set; } = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface."; [Key(3)] public string[] Owns { get; set; } = []; @@ -44,7 +44,7 @@ public sealed class YmirOperatorStateDocument public string Status { get; set; } = "mvp"; [Key(2)] - public string StateOwner { get; set; } = "Ymir world sessions and typed GameCult projections"; + public string StateOwner { get; set; } = "Isolated Box3D snapshot steps and typed diagnostic projections"; [Key(3)] public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)"; @@ -53,7 +53,7 @@ public sealed class YmirOperatorStateDocument public string BatchKernel { get; set; } = ""; [Key(5)] - public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v0 legacy checkpoint during Box3D cutover"; + public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration"; [Key(6)] public string UpdatedAtUtc { get; set; } = ""; @@ -81,18 +81,21 @@ public static class YmirServicePublication { ProviderId = "ymir.physics", Title = "Ymir Physics", - Description = "GameCult authoritative Box3D session wrapper and physics daemon.", + Description = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface.", Owns = [ - "authoritative physics session lifecycle", - "stable GameCult id to Box3D handle projection", - "typed physics commands and facts", + "Box3D-only isolated snapshot stepping", + "stable GameCult id to transient Box3D handle projection", + "Box3D-backed circle overlap and cast queries over submitted bodies", "deterministic result ordering", - "CultCache checkpoint reconstruction", - "CultMesh and Eve service publication" + "CultCache world snapshot v1 with explicit v0 read migration", + "diagnostic Eve publication" ], DoesNotOwn = [ + "public retained session lifecycle yet", + "typed command receipts or begin/end/hit lifecycle facts yet", + "complete checkpoint reconstruction yet", "physics algorithm invention", "Box3D solver and collision semantics", "Unity scene truth", @@ -108,10 +111,10 @@ public static class YmirServicePublication { ProviderId = "ymir.physics", Status = "mvp", - StateOwner = "Ymir world sessions and typed GameCult projections", + StateOwner = "Isolated Box3D snapshot steps and typed diagnostic projections", NumericSubstrate = "Box3D v0.1.0 (C17)", BatchKernel = "Box3D native solver; Ymir does not own physics algorithms", - Persistence = "CultCache gamecult.ymir.world_state.v0 legacy checkpoint during Box3D cutover", + Persistence = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration", UpdatedAtUtc = FormatUtc(now) }; diff --git a/src/Ymir.Core/YmirSimulator.cs b/src/Ymir.Core/YmirSimulator.cs index df4c6a4..d22c4de 100644 --- a/src/Ymir.Core/YmirSimulator.cs +++ b/src/Ymir.Core/YmirSimulator.cs @@ -1,144 +1,20 @@ -using CultMath; -using static CultMath.math; - namespace Ymir.Core; +/// +/// Compatibility façade for the snapshot-in/snapshot-out Ymir contract. +/// Calls are isolated by design; retained world ownership is not inferred from snapshots. +/// public sealed class YmirSimulator { - private const float MinimumMass = 0.0001f; - private const float MinimumDistance = 0.0001f; - public SimulationStepResult Step(SimulationStepRequest request) { - var result = Step(new SoASimulationStepRequest( - request.DeltaTime, - YmirSoAWorld.FromWorld(request.World))); - - return new SimulationStepResult(result.World.ToWorld(), result.Contacts); + using var session = new YmirWorldSession(); + return session.Step(request); } public SoASimulationStepResult Step(SoASimulationStepRequest request) { - if (request.DeltaTime <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be positive."); - } - - var world = request.World.Clone(); - world.Validate(); - - var accelerationX = new float[world.BodyCount]; - var accelerationY = new float[world.BodyCount]; - for (var i = 0; i < world.FieldCount; i++) - { - BatchMath.AddRadialFalloffAcceleration2D( - world.PositionX, - world.PositionY, - world.FieldPositionX[i], - world.FieldPositionY[i], - world.FieldStrength[i], - world.FieldRadius[i], - accelerationX, - accelerationY); - } - - BatchMath.IntegrateSemiImplicitEuler2D( - request.DeltaTime, - world.DynamicMask, - world.PositionX, - world.PositionY, - world.VelocityX, - world.VelocityY, - accelerationX, - accelerationY); - - var contacts = new List(); - ResolveCircleContacts(world, contacts); - - world.Time += request.DeltaTime; - return new SoASimulationStepResult( - world, - contacts); - } - - private static void ResolveCircleContacts(YmirSoAWorld world, List contacts) - { - for (var i = 0; i < world.BodyCount; i++) - { - for (var j = i + 1; j < world.BodyCount; j++) - { - var delta = world.PositionAt(j) - world.PositionAt(i); - var distance = length(delta); - var combinedRadius = world.Radius[i] + world.Radius[j]; - var penetration = combinedRadius - distance; - - if (penetration <= 0.0f) - { - continue; - } - - var normal = distance <= MinimumDistance ? float2(1.0f, 0.0f) : delta / distance; - var point = world.PositionAt(i) + normal * (world.Radius[i] - penetration * 0.5f); - var relativeVelocity = world.VelocityAt(j) - world.VelocityAt(i); - var relativeSpeed = dot(relativeVelocity, normal); - - contacts.Add(new ContactEvent( - world.BodyIds[i], - world.BodyIds[j], - Vec2.FromCultMath(point), - Vec2.FromCultMath(normal), - penetration, - relativeSpeed)); - - ResolveImpulse(world, i, j, normal, penetration, relativeSpeed); - } - } - } - - private static void ResolveImpulse( - YmirSoAWorld world, - int left, - int right, - float2 normal, - float penetration, - float relativeSpeed) - { - var leftInvMass = world.DynamicMask[left] <= 0.0f ? 0.0f : 1.0f / max(world.Mass[left], MinimumMass); - var rightInvMass = world.DynamicMask[right] <= 0.0f ? 0.0f : 1.0f / max(world.Mass[right], MinimumMass); - var invMassSum = leftInvMass + rightInvMass; - if (invMassSum <= 0.0f) - { - return; - } - - var correction = normal * (penetration / invMassSum); - if (leftInvMass > 0.0f) - { - world.SetPosition(left, world.PositionAt(left) - correction * leftInvMass); - } - - if (rightInvMass > 0.0f) - { - world.SetPosition(right, world.PositionAt(right) + correction * rightInvMass); - } - - if (relativeSpeed >= 0.0f) - { - return; - } - - var restitution = min(world.Restitution[left], world.Restitution[right]); - var impulseMagnitude = -(1.0f + restitution) * relativeSpeed / invMassSum; - var impulse = normal * impulseMagnitude; - - if (leftInvMass > 0.0f) - { - world.SetVelocity(left, world.VelocityAt(left) - impulse * leftInvMass); - } - - if (rightInvMass > 0.0f) - { - world.SetVelocity(right, world.VelocityAt(right) + impulse * rightInvMass); - } + using var session = new YmirWorldSession(); + return session.Step(request); } } diff --git a/src/Ymir.Core/YmirSoAWorld.cs b/src/Ymir.Core/YmirSoAWorld.cs index c312dc9..4117af7 100644 --- a/src/Ymir.Core/YmirSoAWorld.cs +++ b/src/Ymir.Core/YmirSoAWorld.cs @@ -10,6 +10,10 @@ public sealed class YmirSoAWorld public float[] PositionY { get; set; } = []; public float[] VelocityX { get; set; } = []; public float[] VelocityY { get; set; } = []; + public float[] DirectionX { get; set; } = []; + public float[] DirectionY { get; set; } = []; + public float[] AngularVelocity { get; set; } = []; + public float[] Torque { get; set; } = []; public float[] Radius { get; set; } = []; public float[] Mass { get; set; } = []; public float[] DynamicMask { get; set; } = []; @@ -37,6 +41,10 @@ public sealed class YmirSoAWorld PositionY = bodies.Select(body => body.Position.Y).ToArray(), VelocityX = bodies.Select(body => body.Velocity.X).ToArray(), VelocityY = bodies.Select(body => body.Velocity.Y).ToArray(), + DirectionX = bodies.Select(body => DirectionOrDefault(body.Direction).X).ToArray(), + DirectionY = bodies.Select(body => DirectionOrDefault(body.Direction).Y).ToArray(), + AngularVelocity = bodies.Select(body => body.AngularVelocity).ToArray(), + Torque = bodies.Select(body => body.Torque).ToArray(), Radius = bodies.Select(body => body.Radius).ToArray(), Mass = bodies.Select(body => body.Mass).ToArray(), DynamicMask = bodies.Select(body => body.IsStatic ? 0.0f : 1.0f).ToArray(), @@ -59,7 +67,10 @@ public sealed class YmirSoAWorld Radius[i], Mass[i], DynamicMask[i] <= 0.0f, - Restitution[i])) + Restitution[i], + new Vec2(DirectionX[i], DirectionY[i]), + AngularVelocity[i], + Torque[i])) .ToArray(), Enumerable.Range(0, FieldCount) .Select(i => new RadialField( @@ -77,6 +88,10 @@ public sealed class YmirSoAWorld PositionY = (float[])PositionY.Clone(), VelocityX = (float[])VelocityX.Clone(), VelocityY = (float[])VelocityY.Clone(), + DirectionX = (float[])DirectionX.Clone(), + DirectionY = (float[])DirectionY.Clone(), + AngularVelocity = (float[])AngularVelocity.Clone(), + Torque = (float[])Torque.Clone(), Radius = (float[])Radius.Clone(), Mass = (float[])Mass.Clone(), DynamicMask = (float[])DynamicMask.Clone(), @@ -109,6 +124,17 @@ public sealed class YmirSoAWorld { throw new ArgumentOutOfRangeException(nameof(Mass), "Dynamic body mass must be positive."); } + + var directionLengthSquared = DirectionX[i] * DirectionX[i] + DirectionY[i] * DirectionY[i]; + if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f) + { + throw new ArgumentOutOfRangeException(nameof(DirectionX), "Body direction must be finite and non-zero."); + } + + if (!float.IsFinite(AngularVelocity[i]) || !float.IsFinite(Torque[i])) + { + throw new ArgumentOutOfRangeException(nameof(AngularVelocity), "Body angular state must be finite."); + } } } @@ -131,12 +157,17 @@ public sealed class YmirSoAWorld private void ValidateBodyLengths() { var expected = BodyIds.Length; + FillMissingAngularState(expected); foreach (var length in new[] { PositionX.Length, PositionY.Length, VelocityX.Length, VelocityY.Length, + DirectionX.Length, + DirectionY.Length, + AngularVelocity.Length, + Torque.Length, Radius.Length, Mass.Length, DynamicMask.Length, @@ -150,6 +181,40 @@ public sealed class YmirSoAWorld } } + private void FillMissingAngularState(int expected) + { + if (DirectionX.Length == 0 && expected > 0) + { + DirectionX = new float[expected]; + } + + if (DirectionY.Length == 0 && expected > 0) + { + DirectionY = Enumerable.Repeat(1.0f, expected).ToArray(); + } + + if (AngularVelocity.Length == 0 && expected > 0) + { + AngularVelocity = new float[expected]; + } + + if (Torque.Length == 0 && expected > 0) + { + Torque = new float[expected]; + } + } + + private static Vec2 DirectionOrDefault(Vec2? direction) + { + if (direction is not { } value || + value.X * value.X + value.Y * value.Y <= 1.0e-8f) + { + return new Vec2(0.0f, 1.0f); + } + + return value; + } + private void ValidateFieldLengths() { var expected = FieldIds.Length; diff --git a/src/Ymir.Core/YmirWorldSession.cs b/src/Ymir.Core/YmirWorldSession.cs new file mode 100644 index 0000000..fa033ac --- /dev/null +++ b/src/Ymir.Core/YmirWorldSession.cs @@ -0,0 +1,200 @@ +using Ymir.Box3D; + +namespace Ymir.Core; + +/// +/// Owns one retained Box3D world and its stable GameCult identity projection. +/// Callers own the session lifetime; body snapshots do not imply session identity. +/// +internal sealed class YmirWorldSession : IDisposable +{ + private readonly object _gate = new(); + private readonly Box3DSession _session = new(); + private readonly Dictionary _keysById = new(StringComparer.Ordinal); + private readonly Dictionary _idsByKey = new(); + private ulong _nextKey = 1; + private bool _disposed; + + public SimulationStepResult Step(SimulationStepRequest request) + { + ArgumentNullException.ThrowIfNull(request); + var result = Step(new SoASimulationStepRequest( + request.DeltaTime, + YmirSoAWorld.FromWorld(request.World))); + + return new SimulationStepResult(result.World.ToWorld(), result.Contacts); + } + + public SoASimulationStepResult Step(SoASimulationStepRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (!float.IsFinite(request.DeltaTime) || request.DeltaTime <= 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(request), "DeltaTime must be finite and positive."); + } + + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var world = request.World.Clone(); + world.Validate(); + ValidateStableIds(world.BodyIds); + + var indicesByKey = new Dictionary(world.BodyCount); + foreach (var id in world.BodyIds.OrderBy(id => id, StringComparer.Ordinal)) + { + GetOrCreateKey(id); + } + + var bodies = new Box3DBody[world.BodyCount]; + for (var i = 0; i < world.BodyCount; i++) + { + var key = GetOrCreateKey(world.BodyIds[i]); + indicesByKey.Add(key, i); + bodies[i] = new Box3DBody( + key, + world.PositionX[i], + world.PositionY[i], + world.VelocityX[i], + world.VelocityY[i], + world.DirectionX[i], + world.DirectionY[i], + world.AngularVelocity[i], + world.Torque[i], + world.Radius[i], + world.Mass[i], + world.Restitution[i], + world.DynamicMask[i] <= 0.0f); + } + + Array.Sort(bodies, static (left, right) => left.StableId.CompareTo(right.StableId)); + + var fields = Enumerable.Range(0, world.FieldCount) + .OrderBy(index => world.FieldIds[index], StringComparer.Ordinal) + .Select(index => new Box3DField( + world.FieldPositionX[index], + world.FieldPositionY[index], + world.FieldStrength[index], + world.FieldRadius[index])) + .ToArray(); + + _session.SyncBodies(bodies); + _session.Step(request.DeltaTime, fields); + + foreach (var body in _session.CopyBodies()) + { + if (!indicesByKey.TryGetValue(body.StableId, out var index)) + { + throw new InvalidOperationException($"Box3D returned unknown stable body key {body.StableId}."); + } + + world.PositionX[index] = body.PositionX; + world.PositionY[index] = body.PositionZ; + world.VelocityX[index] = body.VelocityX; + world.VelocityY[index] = body.VelocityZ; + world.DirectionX[index] = body.DirectionX; + world.DirectionY[index] = body.DirectionZ; + world.AngularVelocity[index] = body.AngularVelocity; + world.Torque[index] = 0.0f; + } + + var contacts = _session.CopyContacts() + .Select(ProjectContact) + .OrderBy(contact => contact.BodyA, StringComparer.Ordinal) + .ThenBy(contact => contact.BodyB, StringComparer.Ordinal) + .ThenBy(contact => contact.Point.X) + .ThenBy(contact => contact.Point.Y) + .ToArray(); + + PruneInactiveIds(world.BodyIds); + + world.Time += request.DeltaTime; + return new SoASimulationStepResult(world, contacts); + } + } + + public void Dispose() + { + lock (_gate) + { + if (_disposed) + { + return; + } + + _session.Dispose(); + _disposed = true; + } + } + + private ulong GetOrCreateKey(string id) + { + if (_keysById.TryGetValue(id, out var existing)) + { + return existing; + } + + if (_nextKey == 0) + { + throw new InvalidOperationException("Ymir exhausted its stable native body key space."); + } + + var key = _nextKey++; + _keysById.Add(id, key); + _idsByKey.Add(key, id); + return key; + } + + private ContactEvent ProjectContact(Box3DContact contact) + { + var bodyA = ResolveId(contact.StableIdA); + var bodyB = ResolveId(contact.StableIdB); + var normal = new Vec2(contact.NormalX, contact.NormalZ); + if (StringComparer.Ordinal.Compare(bodyA, bodyB) > 0) + { + (bodyA, bodyB) = (bodyB, bodyA); + normal = new Vec2(-normal.X, -normal.Y); + } + + return new ContactEvent( + bodyA, + bodyB, + new Vec2(contact.PointX, contact.PointZ), + normal, + contact.Penetration, + contact.RelativeSpeed); + } + + private string ResolveId(ulong key) + { + if (!_idsByKey.TryGetValue(key, out var id)) + { + throw new InvalidOperationException($"Box3D returned unknown stable body key {key}."); + } + + return id; + } + + private void PruneInactiveIds(IReadOnlyList activeIds) + { + var active = activeIds.ToHashSet(StringComparer.Ordinal); + foreach (var id in _keysById.Keys.Where(id => !active.Contains(id)).ToArray()) + { + var key = _keysById[id]; + _keysById.Remove(id); + _idsByKey.Remove(key); + } + } + + private static void ValidateStableIds(IReadOnlyList bodyIds) + { + var unique = new HashSet(StringComparer.Ordinal); + foreach (var id in bodyIds) + { + if (!unique.Add(id)) + { + throw new ArgumentException($"Ymir body id '{id}' occurs more than once.", nameof(bodyIds)); + } + } + } +} diff --git a/src/Ymir.Core/YmirWorldStateDocument.cs b/src/Ymir.Core/YmirWorldStateDocument.cs index 4a34c06..3b9b2cf 100644 --- a/src/Ymir.Core/YmirWorldStateDocument.cs +++ b/src/Ymir.Core/YmirWorldStateDocument.cs @@ -6,7 +6,7 @@ namespace Ymir.Core; [CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v0")] [MessagePackObject] -public sealed class YmirWorldStateDocument +public sealed class YmirWorldStateDocumentV0 { [Key(0)] [CultName] @@ -57,7 +57,7 @@ public sealed class YmirWorldStateDocument [Key(15)] public float[] FieldRadius { get; set; } = []; - public static YmirWorldStateDocument FromSoA(string worldId, YmirSoAWorld world) => new() + public static YmirWorldStateDocumentV0 FromSoA(string worldId, YmirSoAWorld world) => new() { WorldId = worldId, Time = world.Time, @@ -97,6 +97,76 @@ public sealed class YmirWorldStateDocument }; } +[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v1")] +[MessagePackObject] +public sealed class YmirWorldStateDocumentV1 +{ + [Key(0), CultName] public string WorldId { get; set; } = "default"; + [Key(1)] public float Time { get; set; } + [Key(2)] public string[] BodyIds { get; set; } = []; + [Key(3)] public float[] PositionX { get; set; } = []; + [Key(4)] public float[] PositionY { get; set; } = []; + [Key(5)] public float[] VelocityX { get; set; } = []; + [Key(6)] public float[] VelocityY { get; set; } = []; + [Key(7)] public float[] Radius { get; set; } = []; + [Key(8)] public float[] Mass { get; set; } = []; + [Key(9)] public float[] DynamicMask { get; set; } = []; + [Key(10)] public float[] Restitution { get; set; } = []; + [Key(11)] public string[] FieldIds { get; set; } = []; + [Key(12)] public float[] FieldPositionX { get; set; } = []; + [Key(13)] public float[] FieldPositionY { get; set; } = []; + [Key(14)] public float[] FieldStrength { get; set; } = []; + [Key(15)] public float[] FieldRadius { get; set; } = []; + [Key(16)] public float[] DirectionX { get; set; } = []; + [Key(17)] public float[] DirectionY { get; set; } = []; + [Key(18)] public float[] AngularVelocity { get; set; } = []; + + public static YmirWorldStateDocumentV1 FromSoA(string worldId, YmirSoAWorld world) => new() + { + WorldId = worldId, + Time = world.Time, + BodyIds = (string[])world.BodyIds.Clone(), + PositionX = (float[])world.PositionX.Clone(), + PositionY = (float[])world.PositionY.Clone(), + VelocityX = (float[])world.VelocityX.Clone(), + VelocityY = (float[])world.VelocityY.Clone(), + Radius = (float[])world.Radius.Clone(), + Mass = (float[])world.Mass.Clone(), + DynamicMask = (float[])world.DynamicMask.Clone(), + Restitution = (float[])world.Restitution.Clone(), + FieldIds = (string[])world.FieldIds.Clone(), + FieldPositionX = (float[])world.FieldPositionX.Clone(), + FieldPositionY = (float[])world.FieldPositionY.Clone(), + FieldStrength = (float[])world.FieldStrength.Clone(), + FieldRadius = (float[])world.FieldRadius.Clone(), + DirectionX = (float[])world.DirectionX.Clone(), + DirectionY = (float[])world.DirectionY.Clone(), + AngularVelocity = (float[])world.AngularVelocity.Clone() + }; + + public YmirSoAWorld ToSoA() => new() + { + Time = Time, + BodyIds = (string[])BodyIds.Clone(), + PositionX = (float[])PositionX.Clone(), + PositionY = (float[])PositionY.Clone(), + VelocityX = (float[])VelocityX.Clone(), + VelocityY = (float[])VelocityY.Clone(), + Radius = (float[])Radius.Clone(), + Mass = (float[])Mass.Clone(), + DynamicMask = (float[])DynamicMask.Clone(), + Restitution = (float[])Restitution.Clone(), + FieldIds = (string[])FieldIds.Clone(), + FieldPositionX = (float[])FieldPositionX.Clone(), + FieldPositionY = (float[])FieldPositionY.Clone(), + FieldStrength = (float[])FieldStrength.Clone(), + FieldRadius = (float[])FieldRadius.Clone(), + DirectionX = (float[])DirectionX.Clone(), + DirectionY = (float[])DirectionY.Clone(), + AngularVelocity = (float[])AngularVelocity.Clone() + }; +} + public static class YmirCultCacheStore { public static async Task SaveWorldAsync(string path, string worldId, YmirSoAWorld world) @@ -113,8 +183,8 @@ public static class YmirCultCacheStore using (cache) { await cache.UpsertAsync( - YmirWorldStateDocument.FromSoA(worldId, world), - new CultRecordHandle(new CultRecordKey($"ymir:world:{worldId}"))) + YmirWorldStateDocumentV1.FromSoA(worldId, world), + new CultRecordHandle(new CultRecordKey($"ymir:world:{worldId}"))) .ConfigureAwait(false); await cache.FlushAsync().ConfigureAwait(false); } @@ -125,6 +195,8 @@ public static class YmirCultCacheStore using var cache = await CultCacheMessagePack.OpenAsync( path, new CultCacheOpenOptions { UseDirectoryStore = true }).ConfigureAwait(false); - return cache.Get(new CultRecordKey($"ymir:world:{worldId}"))?.ToSoA(); + var key = new CultRecordKey($"ymir:world:{worldId}"); + return cache.Get(key)?.ToSoA() + ?? cache.Get(key)?.ToSoA(); } } diff --git a/src/ymir-daemon/Program.cs b/src/ymir-daemon/Program.cs index 88b4b49..54f1089 100644 --- a/src/ymir-daemon/Program.cs +++ b/src/ymir-daemon/Program.cs @@ -82,7 +82,7 @@ internal static class Program ok = true, path, record = "ymir:world:sample", - schema = "gamecult.ymir.world_state.v0", + schema = "gamecult.ymir.world_state.v1", bodyCount = result.World.BodyCount, fieldCount = result.World.FieldCount }); diff --git a/tests/Ymir.Box3D.Parity/Box3DOracle.cs b/tests/Ymir.Box3D.Parity/Box3DOracle.cs index 5e501b0..beb1d58 100644 --- a/tests/Ymir.Box3D.Parity/Box3DOracle.cs +++ b/tests/Ymir.Box3D.Parity/Box3DOracle.cs @@ -1,4 +1,5 @@ using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; namespace Ymir.Box3D.Parity; @@ -7,9 +8,11 @@ internal static partial class Box3DOracle private const string LibraryName = "ymir_box3d"; [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial int ymir_box3d_get_version(out int major, out int minor, out int revision); [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial Box3DOverlapResult ymir_box3d_overlap_spheres( float queryX, float queryY, @@ -19,6 +22,7 @@ internal static partial class Box3DOracle float bodyRadius); [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial Box3DOverlapResult ymir_box3d_overlap_capsule_sphere( float startX, float startY, @@ -30,6 +34,7 @@ internal static partial class Box3DOracle float bodyRadius); [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial Box3DCastResult ymir_box3d_cast_sphere( float originX, float originY, @@ -42,6 +47,7 @@ internal static partial class Box3DOracle int canEncroach); [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial void ymir_box3d_step_pair( in Box3DBodyInput bodyA, in Box3DBodyInput bodyB, @@ -51,6 +57,7 @@ internal static partial class Box3DOracle out Box3DPairStepResult result); [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial Box3DTorqueResult ymir_box3d_torque_lifetime(float torque, float timeStep, int subStepCount); } diff --git a/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj b/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj index 79466d8..0987218 100644 --- a/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj +++ b/tests/Ymir.Box3D.Parity/Ymir.Box3D.Parity.csproj @@ -7,7 +7,7 @@ true false $(MSBuildThisFileDirectory)..\..\native\Ymir.Box3D - $(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\$(Configuration) + $(MSBuildThisFileDirectory)..\..\artifacts\box3d-native\parity\$(Configuration) C:\Program Files\CMake\bin\cmake.exe cmake diff --git a/tests/Ymir.Tests/YmirServicePublicationTests.cs b/tests/Ymir.Tests/YmirServicePublicationTests.cs index a6a4d93..d06be58 100644 --- a/tests/Ymir.Tests/YmirServicePublicationTests.cs +++ b/tests/Ymir.Tests/YmirServicePublicationTests.cs @@ -16,11 +16,14 @@ public sealed class YmirServicePublicationTests var diagnostics = YmirServicePublication.OperatorState(now); Assert.Contains("Box3D", advertisement.Description, StringComparison.Ordinal); - Assert.Contains("authoritative physics session lifecycle", advertisement.Owns); + Assert.Contains("Box3D-only isolated snapshot stepping", advertisement.Owns); + Assert.Contains("public retained session lifecycle yet", advertisement.DoesNotOwn); + Assert.Empty(advertisement.CommandLowerings); Assert.Contains("Box3D solver and collision semantics", advertisement.DoesNotOwn); Assert.Equal("Box3D v0.1.0 (C17)", diagnostics.NumericSubstrate); Assert.Contains("does not own physics algorithms", diagnostics.BatchKernel, StringComparison.Ordinal); - Assert.Contains("world_state.v0", diagnostics.Persistence, StringComparison.Ordinal); + Assert.Contains("world_state.v1", diagnostics.Persistence, StringComparison.Ordinal); + Assert.Contains("v0 read migration", diagnostics.Persistence, StringComparison.Ordinal); } [Fact] diff --git a/tests/Ymir.Tests/YmirSimulatorTests.cs b/tests/Ymir.Tests/YmirSimulatorTests.cs index cfb01fe..8eb4f05 100644 --- a/tests/Ymir.Tests/YmirSimulatorTests.cs +++ b/tests/Ymir.Tests/YmirSimulatorTests.cs @@ -1,4 +1,6 @@ using Ymir.Core; +using GameCult.Caching; +using GameCult.Caching.MessagePack; namespace Ymir.Tests; @@ -76,7 +78,78 @@ public sealed class YmirSimulatorTests } [Fact] - public void SoAStepUsesBufferAsSimulationAuthority() + public void ExplicitWorldSessionRetainsBox3DStateAcrossSteps() + { + using var session = new YmirWorldSession(); + var first = session.Step(new SimulationStepRequest( + 0.1f, + new YmirWorld( + 0.0f, + [new PhysicsBody("ship", Vec2.Zero, new Vec2(10.0f, 0.0f), 0.5f, 1.0f)], + []))); + + var second = session.Step(new SimulationStepRequest(0.1f, first.World)); + + Assert.Equal(2.0f, second.World.Bodies[0].Position.X, precision: 5); + Assert.Equal(0.2f, second.World.Time, precision: 5); + } + + [Fact] + public void Box3DOwnsPlanarOrientationAndConsumesTorqueOnce() + { + using var session = new YmirWorldSession(); + var first = session.Step(new SimulationStepRequest( + 0.1f, + new YmirWorld( + 0.0f, + [new PhysicsBody( + "ship", + Vec2.Zero, + Vec2.Zero, + 0.5f, + 1.0f, + Direction: new Vec2(0.0f, 1.0f), + Torque: 1.0f)], + []))); + + var firstBody = first.World.Bodies[0]; + Assert.NotNull(firstBody.Direction); + Assert.NotEqual(0.0f, firstBody.AngularVelocity); + Assert.Equal(0.0f, firstBody.Torque); + + var second = session.Step(new SimulationStepRequest(0.1f, first.World)); + Assert.Equal(firstBody.AngularVelocity, second.World.Bodies[0].AngularVelocity, precision: 4); + Assert.NotEqual(firstBody.Direction, second.World.Bodies[0].Direction); + } + + [Fact] + public void CircleCastUsesPinnedBox3DEdgeSemantics() + { + var result = YmirQueries.CastCircle(new CircleCastQueryRequest( + Vec2.Zero, + new Vec2(1.0f, 0.0f), + 10.0f, + 1.0f, + [new PhysicsBody("target", new Vec2(30.0f, 0.0f), Vec2.Zero, 20.0f, 1.0f, IsStatic: true)])); + + var hit = Assert.Single(result.Hits); + Assert.Equal("target", hit.BodyId); + Assert.InRange(hit.Distance, 8.99f, 9.01f); + } + + [Fact] + public void CircleOverlapUsesPinnedBox3DTangentSemantics() + { + var result = YmirQueries.OverlapCircle(new CircleOverlapQueryRequest( + Vec2.Zero, + 1.0f, + [new PhysicsBody("target", new Vec2(2.0f, 0.0f), Vec2.Zero, 1.0f, 1.0f, IsStatic: true)])); + + Assert.Equal("target", Assert.Single(result.Hits).BodyId); + } + + [Fact] + public void SoAStepProjectsBox3DStateIntoContractBuffers() { var simulator = new YmirSimulator(); var world = new YmirSoAWorld @@ -114,7 +187,7 @@ public sealed class YmirSimulatorTests { var world = YmirSoAWorld.FromWorld(new YmirWorld( 2.0f, - new[] { new PhysicsBody("ship", new Vec2(1.0f, 2.0f), new Vec2(3.0f, 4.0f), 0.5f, 1.0f) }, + new[] { new PhysicsBody("ship", new Vec2(1.0f, 2.0f), new Vec2(3.0f, 4.0f), 0.5f, 1.0f, Direction: new Vec2(1.0f, 0.0f), AngularVelocity: 2.0f) }, new[] { new RadialField("well", new Vec2(5.0f, 6.0f), 7.0f, 8.0f) })); await YmirCultCacheStore.SaveWorldAsync(path, "test", world); @@ -124,6 +197,8 @@ public sealed class YmirSimulatorTests Assert.Equal(["ship"], loaded!.BodyIds); Assert.Equal(1.0f, loaded.PositionX[0], precision: 5); Assert.Equal(7.0f, loaded.FieldStrength[0], precision: 5); + Assert.Equal(1.0f, loaded.DirectionX[0], precision: 5); + Assert.Equal(2.0f, loaded.AngularVelocity[0], precision: 5); } finally { @@ -139,6 +214,42 @@ public sealed class YmirSimulatorTests } } + [Fact] + public async Task CultCacheStoreReadsV0WithDefaultAngularState() + { + var path = Path.Combine(Path.GetTempPath(), $"ymir-v0-tests-{Guid.NewGuid():N}.cc"); + var recordsPath = $"{path}.records"; + try + { + var world = YmirSoAWorld.FromWorld(new YmirWorld( + 2.0f, + [new PhysicsBody("ship", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f)], + [])); + using (var cache = await CultCacheMessagePack.OpenAsync( + path, + new CultCacheOpenOptions { UseDirectoryStore = true, FlushOnDispose = true, StoreFlushOnDispose = true })) + { + await cache.UpsertAsync( + YmirWorldStateDocumentV0.FromSoA("test", world), + new CultRecordHandle(new CultRecordKey("ymir:world:test"))); + await cache.FlushAsync(); + } + + var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test"); + + Assert.NotNull(loaded); + loaded!.Validate(); + Assert.Equal(0.0f, loaded.DirectionX[0]); + Assert.Equal(1.0f, loaded.DirectionY[0]); + Assert.Equal(0.0f, loaded.AngularVelocity[0]); + } + finally + { + if (File.Exists(path)) File.Delete(path); + if (Directory.Exists(recordsPath)) Directory.Delete(recordsPath, recursive: true); + } + } + private static SimulationStepResult Step(params PhysicsBody[] bodies) { var simulator = new YmirSimulator(); From d0ddd7b7a30805b2678cc1ce96a64420f4dc6064 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 20:33:48 +0100 Subject: [PATCH 2/7] Remember the Box3D authority cut --- .voidbot/state/ymir.cc | Bin 2881 -> 4274 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.voidbot/state/ymir.cc b/.voidbot/state/ymir.cc index b340c88e18b067c6755c145c6c7e867481de9d38..0f043dd540a0b1b72de7097fc21dadab9b8ad76f 100644 GIT binary patch delta 1517 zcmZ`(J#QRE7?vGN!Kr{ELWoE&6+*hb^Z7m~LI`Q{|)50CnL zHwS~8gWYa_wET1P$G6rW?k%5hUSEEF#jU>?_nSBGZr!-CU4HY6ml+r03wB;xvvKA# z>%tMc;``r^wtl)Y`tC`=g?06zdhuahXqT`WGRx64=}(8FWGJWoWI9!oWN*56EL18} zH6Aa&-TGwl@f~MXB?DmTOMFSj&Pj33GZEO6t4z=ZQ<>FXOHaX4sf}Sp2ljMu>ygZb zE?#c@)%+uk0~wRIIg>VlXHG=m4oREmI#TaY>a0*@COmiOUbSFXCo{GM2UmAU7=^PY z2pLFJ0V;K<0Y&A1S$12lc5YS^gGe#cVBCGC{e!~}eJ%?Aw8{f%#n5o9;avyH0$kHZ z`=BLI7xpV|#CPa^Yc8aDBT6_Na6S@>l9YhIrs3v5u1iOFSXOBcl>Ix0BrE4ICa;N4 zOY7mBh6}LpH5&QACCr;Opgw@Bq(x&~k_vf(qf$Ew8TTr7n*B%QI0zlh24Hj#d7uTb zBbw`s$SKB?$C)6a14+l2*()lbb1x3;MXt6l zTs*qA2vp;@00{)QGE|CEq&i3RUHYub^W;2`e;HC6nK^6pgQj6ESj3Sww delta 270 zcmdm_cu;J^1||VBT|@H_10yRFODjVIJyXlc2bg9Fq6(TB7)(CMBsO^;AKT=1<{S)J zW3a3gi>xg3|JJp|$r-7+iD9Wl#hLkej4O*X@{3ABQj2mYZVq8t%{;k)SAB9H6Winy z>^zDqic9i~Qd1mDb{H8Lndus!TWbz9SZ4Aw-i_#18X7?zl#3w)(jzuGh`$nD#t7nx OPyFkI(Cjfbivj>>&`ucu From 82ddfc98a677938e3c89cd223e90c7fe3b194c9f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 21:17:41 +0100 Subject: [PATCH 3/7] Add retained Box3D session contract --- README.md | 32 +- docs/architecture.md | 19 +- docs/box3d-parity.md | 12 +- docs/retained-session-contract.md | 159 +++ native/Ymir.Box3D/ymir_box3d.c | 589 ++++++++++- src/Ymir.Box3D/Box3DNative.cs | 85 +- src/Ymir.Box3D/Box3DSession.cs | 151 ++- src/Ymir.Box3D/Ymir.Box3D.csproj | 2 +- src/Ymir.Core/RetainedSessionModel.cs | 120 +++ .../YmirServicePublicationDocument.cs | 13 +- src/Ymir.Core/YmirSession.cs | 992 ++++++++++++++++++ tests/Ymir.Box3D.Parity/Box3DOracle.cs | 73 ++ tests/Ymir.Box3D.Parity/Box3DParityTests.cs | 47 + .../Ymir.Tests/YmirServicePublicationTests.cs | 4 +- tests/Ymir.Tests/YmirSessionTests.cs | 215 ++++ 15 files changed, 2473 insertions(+), 40 deletions(-) create mode 100644 docs/retained-session-contract.md create mode 100644 src/Ymir.Core/RetainedSessionModel.cs create mode 100644 src/Ymir.Core/YmirSession.cs create mode 100644 tests/Ymir.Tests/YmirSessionTests.cs diff --git a/README.md b/README.md index 9afa0d5..138a991 100644 --- a/README.md +++ b/README.md @@ -16,12 +16,13 @@ authorities. lifecycle, force and torque lifetime, tolerances, and deterministic step behavior for identical recorded inputs. - Ymir currently owns the pinned Box3D version, stable GameCult entity ids, - native ABI isolation, snapshot lowering, deterministic result ordering, - versioned CultCache snapshots, and a diagnostic Eve publication. -- The Ymir daemon will own long-lived world sessions, typed commands and - receipts, contact lifecycle facts, checkpoint reconstruction, CultMesh - publication, and process supervision. Those are the cutover contract, not a - claim that the current CLI already exposes them. + native ABI isolation, public in-process retained sessions, explicit mutation + receipts, typed contact facts, snapshot lowering, deterministic result + ordering, versioned CultCache snapshots, and a diagnostic Eve publication. +- The Ymir daemon will own named session routing, durable command receipts, + checkpoint reconstruction, CultMesh command/fact publication, and process + supervision. Those are the daemon cutover contract, not a claim that the + current CLI already exposes them. - Aetheria owns gameplay policy and supplies typed physical intent: bodies, fields, tractor targets, forces, projectiles, filters, and the gameplay consequences of Ymir contact facts. @@ -53,16 +54,19 @@ projects the result, and disposes it. It contains no managed integrator, collision loop, or impulse solver. That snapshot facade deliberately does not pretend to own long-lived world -identity. The retained native session exists behind an internal managed port; -there is not yet a public session registry or command contract. Aetheria will -name one Ymir session per run and zone when that contract is exposed. Its old -process-wide simulator objects are not session identifiers. Planar heading, -angular velocity, and transient torque already pass through Box3D. Typed -begin/end/hit lifecycle facts, checkpoint reconstruction, and non-Windows RID -artifacts remain cutover work. +identity. The public in-process `YmirSession` now exposes explicit body +mutations, force and torque commands, revisioned receipts, retained stepping, +and typed Begin/Hit/End facts. It never treats omission as removal. The daemon +still lacks a named session registry and CultMesh command lowering. Aetheria +will name one session per run and zone through that daemon contract; its old +process-wide simulator objects are not session identifiers. Retained-world +queries, checkpoint reconstruction, and non-Windows RID artifacts remain +cutover work. See [the architecture map](docs/architecture.md) and -[the executable parity contract](docs/box3d-parity.md). +[the executable parity contract](docs/box3d-parity.md). The +[retained-session contract](docs/retained-session-contract.md) records the +current ownership cut and the public daemon boundary being built. ## Build And Test diff --git a/docs/architecture.md b/docs/architecture.md index ce93991..4f8a989 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,12 +36,17 @@ an isolated internal session for one complete snapshot, projects its output, and disposes it. Public circle overlap and cast APIs invoke Box3D geometry over caller-supplied bodies. -The retained native session and its managed wrapper are internal. The current -CLI has no named session registry, public mutation commands, command receipts, -retained-world queries, or begin/end/hit lifecycle contract. Its CultCache and -Eve output is a regenerated diagnostic projection. The sections marked as -target contract describe the cut still to build; they are not advertisements -of current daemon capability. +The retained native session now has a public in-process `YmirSession` port with +explicit spawn, remove, teleport, velocity, configuration, force, torque, +step, and disposal operations. It emits revisioned receipts and typed +Begin/Hit/End facts with stable Ymir identities. Ordinary retained steps do not +accept complete body snapshots. + +The current CLI still has no named session registry, CultMesh command +lowerings, retained-world queries, durable receipt ledger, or reconstruction +checkpoint. Its CultCache and Eve output is a regenerated diagnostic +projection. The sections marked as target contract describe that daemon cut; +they are not advertisements of current CLI capability. ## Target Inputs @@ -114,7 +119,7 @@ infer retained identity from a body list. Session identity must be explicit. A process-wide simulator object, zone index, or repeated stable body id is not enough to join two calls to the same world. Aetheria owns run and zone lifetime and will create, retain, and dispose the -corresponding Ymir session after the public port exists. Current projectile +corresponding Ymir session after daemon registry integration. Current projectile sweep and stationary mine proximity integration can use Ymir's static Box3D-backed circle-cast and overlap queries, but those calls do not join a retained world or own contact lifecycle. diff --git a/docs/box3d-parity.md b/docs/box3d-parity.md index e03f84f..1cb7f92 100644 --- a/docs/box3d-parity.md +++ b/docs/box3d-parity.md @@ -21,11 +21,15 @@ the overlap, cast, pair-step, torque-lifetime, version, and ABI-layout operations used by the harness. This keeps Box3D's alpha C ABI out of Ymir's public managed contracts. -Production ABI version 2 uses caller-owned blittable buffers, explicit cdecl, +Production ABI version 3 uses caller-owned blittable buffers, explicit cdecl, fixed-width status/count values, compile-time C layout assertions, and a -managed/native layout sentinel before opening a session. Planar direction maps -to Box3D rotation about Y; angular velocity and transient torque remain Box3D -state and commands rather than managed integration. +managed/native layout sentinel before opening a session. It adds explicit +retained body mutations, one-shot force and torque operations, and a +session-owned Begin/Hit/End event buffer. The private buffer retains Box3D's +stored contact key only long enough to correlate its separate event arrays; +public Ymir facts never expose native contact identity. Planar direction maps to Box3D +rotation about Y; angular velocity and transient torque remain Box3D state and +commands rather than managed integration. `tests/Ymir.Box3D.Parity` builds that facade through CMake and invokes it with source-generated .NET interop. Run it with: diff --git a/docs/retained-session-contract.md b/docs/retained-session-contract.md new file mode 100644 index 0000000..a5920dd --- /dev/null +++ b/docs/retained-session-contract.md @@ -0,0 +1,159 @@ +# Retained Session Contract + +## Objective + +One named Ymir session owns one retained Box3D world. A product may restore the +world once, issue explicit mutations, step it, query it, and consume typed +Box3D contact facts. A body snapshot is output and checkpoint material; it is +not an implicit command language. + +## Current Mechanism + +`YmirSimulator` is an isolated snapshot compatibility API. It creates a native +session, synchronizes a complete body list, steps once, projects the result, +and disposes the session. Its private compatibility helper uses that complete +list, so omission can delete a body and stale input can teleport or overwrite +solver velocity inside the isolated call. Its legacy contact output merges +current manifolds, begin events, and hit events into one pair-deduplicated list +and omits End. + +The public `YmirSession` does not use that mechanism for ordinary retained +steps. The compatibility path is not the retained daemon contract. + +## Owner + +- One public Ymir session serializes commands for one named world. +- Its native Box3D `b3World` exclusively owns integration, collision, + broadphase, queries, solver state, and contact lifecycle. +- Ymir owns stable GameCult ids, body generations, session revision, step + sequence, deterministic projection, fact identity, and command receipts. +- The product owns session lifetime and gameplay policy. Aetheria will map one + `(RunId, ZoneIndex)` lifetime to one Ymir session. + +## Target Inputs + +The retained port accepts narrow operations with explicit meaning: + +- spawn a body, rejecting an existing id; +- remove a body, rejecting an unknown id; +- teleport a body; +- set linear and angular velocity; +- configure body shape, mass, type, and restitution; +- apply one-shot force or torque; +- step with a fixed delta, substep count, and typed fields; +- dispose the session. + +The current public slice implements those mutation and step operations. +Retained-world overlap and cast queries at a named revision are the next +library cut; the static compatibility queries do not satisfy that contract. + +Restore/import is the only path allowed to accept a complete world snapshot. +There is no `Upsert`, generic patch bag, or omission-based removal. + +## Outputs + +Each accepted mutation produces a receipt that names the session generation, +command id, before revision, and after revision. A step additionally returns: + +- authoritative Box3D body state; +- the new step index; +- typed `Begin`, `Hit`, and `End` facts; +- stable fact ids and contact-episode ids; +- the accepted step configuration through its typed command. + +The current library validates the native Box3D version and ABI before session +creation but does not repeat those facts in every Step result. + +Facts canonicalize bodies by stable id and flip normals when canonicalization +swaps endpoints. Their public order is body pair, contact episode, kind, then +within-kind ordinal. This is stable publication order, not invented substep +chronology. + +## Derived State + +- Box3D handles are process-local and never cross the contract. +- DTO and SoA body arrays are projections. +- `gamecult.ymir.world_state.v1` is an inspection/migration snapshot, not a + retained-session checkpoint. +- Receipt and contact-episode ledgers are session metadata, not physics law. +- Aetheria cargo, damage, loot, feedback, and scoring remain gameplay state + derived from Ymir facts. + +The current in-process receipt ledger is not the durable daemon ledger. It is +kept for the lifetime of the session and is intentionally not advertised as a +reconnect or checkpoint guarantee. + +## Forbidden Writers + +- recurring complete-body synchronization after restore; +- snapshot omission as body removal; +- transform or velocity setters hidden inside ordinary Step; +- managed contact lifecycle inference that replaces Box3D events; +- random fact ids or ids derived from manifold floats; +- Box3D callback order exposed as a public ordering guarantee; +- Unity callbacks, renderer state, or gameplay proximity checks deciding + contact truth. + +## Shared Paths + +Direct commands, agent commands, and spawns use the same explicit in-process +session operations. Imports, reconnects, and replay must lower through those +operations after the daemon registry and reconstruction contract exist. +Restore will establish initial state; it will not remain a parallel writer. +Retained queries will observe a named revision without mutating it. Snapshot +reads cannot be fed back without an explicit restore, teleport, velocity, or +configuration operation. + +## Contact Identity + +A contact episode is identified by the canonical pair of body id plus body +generation and a monotonically assigned episode number. Begin and End share +that identity. A later re-contact creates a new episode. Fact identity derives +from session generation, step index, contact episode, kind, and deterministic +ordinal. Box3D contact and shape handles are never durable identity. + +Body removal must close any active episode exactly once. Because Box3D End +events may reference destroyed shapes, the native boundary retains stable ids +until the event buffer has been drained. + +Box3D publishes Begin, Hit, and End in separate arrays rather than one causal +sequence. The private ABI carries Box3D's stored transient contact key so Ymir +can correlate those arrays before assigning public episode identity. That key +is derived process state: it never appears in a public fact or checkpoint. + +## Cut Line + +1. Typed native mutation operations and step-owned lifecycle buffers: done. +2. Public managed retained session with no ordinary full synchronization: + done. +3. Add retained-world queries and revision checks. +4. Add the daemon session registry, generation-bearing routed commands, + idempotent Create, bounded live dedupe backed by durable receipts, and + CultMesh command lowering. +5. Move Aetheria to one session per run and zone, then delete its process-wide + simulator identity, manual tractor geometry, per-projectile mini-worlds, + and tuple contact dedup. + +The isolated `YmirSimulator` remains a compatibility API. It is never the +daemon authority. + +Mutation-generated End evidence is currently retained in the native pending +buffer and published by the next accepted Step. The daemon transaction cut +must make mutation plus Step one publication boundary, or return mutation facts +directly, before Ymir promises that removal followed by disposal publishes an +End fact. + +## Verification + +- A spawned body advances across steps without being resubmitted. +- Omission from unrelated commands cannot remove or reset a body. +- Force and torque affect exactly one accepted step. +- stale revisions and conflicting command ids cannot mutate the world. +- persistent touching emits one Begin, separation emits one End, and re-contact + creates a new episode. +- duplicate fact delivery cannot commit Aetheria cargo twice. +- different insertion orders produce the same semantic fact order. +- queries observe the requested retained revision and cannot inject bodies. +- disposed or stale session generations fail closed. +- restored continuation must reproduce bodies and fact identity before Ymir + advertises retained-session checkpoint support. diff --git a/native/Ymir.Box3D/ymir_box3d.c b/native/Ymir.Box3D/ymir_box3d.c index 0126aa8..9120c2c 100644 --- a/native/Ymir.Box3D/ymir_box3d.c +++ b/native/Ymir.Box3D/ymir_box3d.c @@ -131,6 +131,40 @@ typedef struct ymir_box3d_session_contact_output float relative_speed; } ymir_box3d_session_contact_output; +typedef enum ymir_box3d_contact_kind +{ + YMIR_BOX3D_CONTACT_BEGIN = 1, + YMIR_BOX3D_CONTACT_HIT = 2, + YMIR_BOX3D_CONTACT_END = 3, +} ymir_box3d_contact_kind; + +typedef struct ymir_box3d_session_contact_event_output +{ + int32_t kind; + uint32_t has_details; + uint32_t contact_id[3]; + uint64_t stable_id_a; + uint64_t stable_id_b; + float point_x; + float point_y; + float normal_x; + float normal_y; + float penetration; + float relative_speed; +} ymir_box3d_session_contact_event_output; + +typedef struct ymir_box3d_retired_shape +{ + uint64_t shape_id; + uint64_t stable_id; +} ymir_box3d_retired_shape; + +typedef struct ymir_box3d_drained_event +{ + int32_t kind; + uint32_t contact_id[3]; +} ymir_box3d_drained_event; + typedef struct ymir_box3d_session_body { uint64_t stable_id; @@ -157,6 +191,18 @@ typedef struct ymir_box3d_session ymir_box3d_session_body* bodies; int body_count; int body_capacity; + ymir_box3d_session_contact_event_output* contact_events; + int contact_event_count; + int contact_event_capacity; + ymir_box3d_session_contact_event_output* pending_events; + int pending_event_count; + int pending_event_capacity; + ymir_box3d_retired_shape* retired_shapes; + int retired_shape_count; + int retired_shape_capacity; + ymir_box3d_drained_event* drained_events; + int drained_event_count; + int drained_event_capacity; } ymir_box3d_session; _Static_assert(sizeof(ymir_box3d_status) == sizeof(int32_t), "Ymir Box3D status ABI must be 32-bit"); @@ -164,6 +210,7 @@ _Static_assert(sizeof(ymir_box3d_session_body_input) == 56, "Unexpected Ymir Box _Static_assert(sizeof(ymir_box3d_radial_field_input) == 16, "Unexpected Ymir Box3D field layout"); _Static_assert(sizeof(ymir_box3d_session_body_output) == 40, "Unexpected Ymir Box3D body output layout"); _Static_assert(sizeof(ymir_box3d_session_contact_output) == 40, "Unexpected Ymir Box3D contact layout"); +_Static_assert(sizeof(ymir_box3d_session_contact_event_output) == 64, "Unexpected Ymir Box3D contact event layout"); static b3Vec3 ymir_vec(float x, float y) { @@ -245,6 +292,76 @@ static ymir_box3d_status ymir_session_reserve_bodies(ymir_box3d_session* session return YMIR_BOX3D_OK; } +static ymir_box3d_status ymir_session_reserve_contact_events( + ymir_box3d_session_contact_event_output** events, + int* current_capacity, + int capacity) +{ + if (capacity <= *current_capacity) + { + return YMIR_BOX3D_OK; + } + + int new_capacity = *current_capacity > 0 ? *current_capacity : 16; + while (new_capacity < capacity) + { + new_capacity *= 2; + } + ymir_box3d_session_contact_event_output* resized = (ymir_box3d_session_contact_event_output*)realloc( + *events, (size_t)new_capacity * sizeof(ymir_box3d_session_contact_event_output)); + if (resized == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + *events = resized; + *current_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_reserve_retired_shapes(ymir_box3d_session* session, int capacity) +{ + if (capacity <= session->retired_shape_capacity) + { + return YMIR_BOX3D_OK; + } + int new_capacity = session->retired_shape_capacity > 0 ? session->retired_shape_capacity * 2 : 16; + while (new_capacity < capacity) + { + new_capacity *= 2; + } + ymir_box3d_retired_shape* resized = (ymir_box3d_retired_shape*)realloc( + session->retired_shapes, (size_t)new_capacity * sizeof(ymir_box3d_retired_shape)); + if (resized == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + session->retired_shapes = resized; + session->retired_shape_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_reserve_drained_events(ymir_box3d_session* session, int capacity) +{ + if (capacity <= session->drained_event_capacity) + { + return YMIR_BOX3D_OK; + } + int new_capacity = session->drained_event_capacity > 0 ? session->drained_event_capacity * 2 : 16; + while (new_capacity < capacity) + { + new_capacity *= 2; + } + ymir_box3d_drained_event* resized = (ymir_box3d_drained_event*)realloc( + session->drained_events, (size_t)new_capacity * sizeof(ymir_box3d_drained_event)); + if (resized == NULL) + { + return YMIR_BOX3D_OUT_OF_MEMORY; + } + session->drained_events = resized; + session->drained_event_capacity = new_capacity; + return YMIR_BOX3D_OK; +} + static float ymir_session_density(float mass, float radius) { float volume = 4.0f / 3.0f * B3_PI * radius * radius * radius; @@ -485,6 +602,217 @@ static int ymir_session_contact_from_manifolds( return 1; } +static uint64_t ymir_session_resolve_event_shape( + const ymir_box3d_session* session, + b3ShapeId shape_id) +{ + if (b3Shape_IsValid(shape_id)) + { + return ymir_session_shape_stable_id(shape_id); + } + + uint64_t stored_shape_id = b3StoreShapeId(shape_id); + for (int i = 0; i < session->retired_shape_count; ++i) + { + if (session->retired_shapes[i].shape_id == stored_shape_id) + { + return session->retired_shapes[i].stable_id; + } + } + return 0; +} + +static int ymir_session_event_was_drained( + const ymir_box3d_session* session, + int32_t kind, + b3ContactId contact_id) +{ + uint32_t stored[3]; + b3StoreContactId(contact_id, stored); + for (int i = 0; i < session->drained_event_count; ++i) + { + const ymir_box3d_drained_event* event = session->drained_events + i; + if (event->kind == kind && event->contact_id[0] == stored[0] && + event->contact_id[1] == stored[1] && event->contact_id[2] == stored[2]) + { + return 1; + } + } + return 0; +} + +static ymir_box3d_status ymir_session_mark_event_drained( + ymir_box3d_session* session, + int32_t kind, + b3ContactId contact_id) +{ + ymir_box3d_status status = ymir_session_reserve_drained_events(session, session->drained_event_count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + ymir_box3d_drained_event* stored = session->drained_events + session->drained_event_count++; + stored->kind = kind; + b3StoreContactId(contact_id, stored->contact_id); + return YMIR_BOX3D_OK; +} + +static ymir_box3d_status ymir_session_append_typed_event( + ymir_box3d_session* session, + int pending, + const ymir_box3d_session_contact_event_output* event) +{ + ymir_box3d_session_contact_event_output** events = pending ? &session->pending_events : &session->contact_events; + int* count = pending ? &session->pending_event_count : &session->contact_event_count; + int* capacity = pending ? &session->pending_event_capacity : &session->contact_event_capacity; + ymir_box3d_status status = ymir_session_reserve_contact_events(events, capacity, *count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + (*events)[(*count)++] = *event; + return YMIR_BOX3D_OK; +} + +enum +{ + YMIR_DRAIN_BEGIN = 1, + YMIR_DRAIN_HIT = 2, + YMIR_DRAIN_END = 4, +}; + +static ymir_box3d_status ymir_session_drain_contact_events( + ymir_box3d_session* session, + int event_mask, + int pending) +{ + b3ContactEvents events = b3World_GetContactEvents(session->world_id); + if ((event_mask & YMIR_DRAIN_BEGIN) != 0) + { + for (int i = 0; i < events.beginCount; ++i) + { + const b3ContactBeginTouchEvent* source = events.beginEvents + i; + if (ymir_session_event_was_drained(session, YMIR_BOX3D_CONTACT_BEGIN, source->contactId)) + { + continue; + } + uint64_t stable_id_a = ymir_session_resolve_event_shape(session, source->shapeIdA); + uint64_t stable_id_b = ymir_session_resolve_event_shape(session, source->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0) + { + continue; + } + + ymir_box3d_session_contact_event_output event = { + .kind = YMIR_BOX3D_CONTACT_BEGIN, + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + }; + b3StoreContactId(source->contactId, event.contact_id); + if (b3Contact_IsValid(source->contactId)) + { + b3ContactData data = b3Contact_GetData(source->contactId); + ymir_box3d_session_contact_output details; + if (ymir_session_contact_from_manifolds(&data, &details)) + { + event.has_details = 1; + event.point_x = details.point_x; + event.point_y = details.point_y; + event.normal_x = details.normal_x; + event.normal_y = details.normal_y; + event.penetration = details.penetration; + event.relative_speed = details.relative_speed; + } + } + ymir_box3d_status status = ymir_session_append_typed_event(session, pending, &event); + if (status != YMIR_BOX3D_OK) + { + return status; + } + status = ymir_session_mark_event_drained(session, YMIR_BOX3D_CONTACT_BEGIN, source->contactId); + if (status != YMIR_BOX3D_OK) + { + return status; + } + } + } + + if ((event_mask & YMIR_DRAIN_HIT) != 0) + { + for (int i = 0; i < events.hitCount; ++i) + { + const b3ContactHitEvent* source = events.hitEvents + i; + if (ymir_session_event_was_drained(session, YMIR_BOX3D_CONTACT_HIT, source->contactId)) + { + continue; + } + uint64_t stable_id_a = ymir_session_resolve_event_shape(session, source->shapeIdA); + uint64_t stable_id_b = ymir_session_resolve_event_shape(session, source->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0) + { + continue; + } + ymir_box3d_session_contact_event_output event = { + .kind = YMIR_BOX3D_CONTACT_HIT, + .has_details = 1, + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + .point_x = source->point.x, + .point_y = source->point.z, + .normal_x = source->normal.x, + .normal_y = source->normal.z, + .relative_speed = -source->approachSpeed, + }; + b3StoreContactId(source->contactId, event.contact_id); + ymir_box3d_status status = ymir_session_append_typed_event(session, pending, &event); + if (status != YMIR_BOX3D_OK) + { + return status; + } + status = ymir_session_mark_event_drained(session, YMIR_BOX3D_CONTACT_HIT, source->contactId); + if (status != YMIR_BOX3D_OK) + { + return status; + } + } + } + + if ((event_mask & YMIR_DRAIN_END) != 0) + { + for (int i = 0; i < events.endCount; ++i) + { + const b3ContactEndTouchEvent* source = events.endEvents + i; + if (ymir_session_event_was_drained(session, YMIR_BOX3D_CONTACT_END, source->contactId)) + { + continue; + } + uint64_t stable_id_a = ymir_session_resolve_event_shape(session, source->shapeIdA); + uint64_t stable_id_b = ymir_session_resolve_event_shape(session, source->shapeIdB); + if (stable_id_a == 0 || stable_id_b == 0) + { + continue; + } + ymir_box3d_session_contact_event_output event = { + .kind = YMIR_BOX3D_CONTACT_END, + .stable_id_a = stable_id_a, + .stable_id_b = stable_id_b, + }; + b3StoreContactId(source->contactId, event.contact_id); + ymir_box3d_status status = ymir_session_append_typed_event(session, pending, &event); + if (status != YMIR_BOX3D_OK) + { + return status; + } + status = ymir_session_mark_event_drained(session, YMIR_BOX3D_CONTACT_END, source->contactId); + if (status != YMIR_BOX3D_OK) + { + return status; + } + } + } + return YMIR_BOX3D_OK; +} + static ymir_box3d_status ymir_session_emit_contact( ymir_box3d_stable_pair_set* seen, const ymir_box3d_session_contact_output* contact, @@ -822,16 +1150,18 @@ YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_get_abi_version(void) { - return 2; + return 3; } YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_abi_layout( uint32_t* body_input_size, uint32_t* field_input_size, uint32_t* body_output_size, - uint32_t* contact_output_size) + uint32_t* contact_output_size, + uint32_t* contact_event_output_size) { - if (body_input_size == NULL || field_input_size == NULL || body_output_size == NULL || contact_output_size == NULL) + if (body_input_size == NULL || field_input_size == NULL || body_output_size == NULL || + contact_output_size == NULL || contact_event_output_size == NULL) { return YMIR_BOX3D_INVALID_ARGUMENT; } @@ -840,6 +1170,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_abi_layout( *field_input_size = (uint32_t)sizeof(ymir_box3d_radial_field_input); *body_output_size = (uint32_t)sizeof(ymir_box3d_session_body_output); *contact_output_size = (uint32_t)sizeof(ymir_box3d_session_contact_output); + *contact_event_output_size = (uint32_t)sizeof(ymir_box3d_session_contact_event_output); return YMIR_BOX3D_OK; } @@ -884,6 +1215,10 @@ YMIR_EXPORT void YMIR_CALL ymir_box3d_session_destroy(ymir_box3d_session* sessio b3DestroyWorld(session->world_id); } free(session->bodies); + free(session->contact_events); + free(session->pending_events); + free(session->retired_shapes); + free(session->drained_events); free(session); } @@ -956,6 +1291,198 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_sync_bodies( return YMIR_BOX3D_OK; } +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_spawn( + ymir_box3d_session* session, + const ymir_box3d_session_body_input* body_input) +{ + if (session == NULL || !ymir_session_body_input_is_valid(body_input)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + if (ymir_session_find_body(session, body_input->stable_id) >= 0) + { + return YMIR_BOX3D_DUPLICATE_ID; + } + ymir_box3d_status status = ymir_session_reserve_bodies(session, session->body_count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + ymir_box3d_session_body body; + status = ymir_session_create_body(session, body_input, &body); + if (status == YMIR_BOX3D_OK) + { + session->bodies[session->body_count++] = body; + } + return status; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_remove(ymir_box3d_session* session, uint64_t stable_id) +{ + if (session == NULL || stable_id == 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_status status = ymir_session_reserve_retired_shapes(session, session->retired_shape_count + 1); + if (status != YMIR_BOX3D_OK) + { + return status; + } + session->retired_shapes[session->retired_shape_count++] = (ymir_box3d_retired_shape){ + .shape_id = b3StoreShapeId(session->bodies[index].shape_id), + .stable_id = stable_id, + }; + b3DestroyBody(session->bodies[index].body_id); + session->bodies[index] = session->bodies[session->body_count - 1]; + session->body_count -= 1; + return ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_teleport( + ymir_box3d_session* session, + uint64_t stable_id, + float position_x, + float position_y, + float direction_x, + float direction_y) +{ + float direction_length_squared = direction_x * direction_x + direction_y * direction_y; + if (session == NULL || !ymir_is_finite(position_x) || !ymir_is_finite(position_y) || + !ymir_is_finite(direction_x) || !ymir_is_finite(direction_y) || direction_length_squared <= 1.0e-8f) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_session_body* body = session->bodies + index; + b3Body_SetTransform(body->body_id, ymir_vec(position_x, position_y), ymir_session_rotation(direction_x, direction_y)); + body->last_position_x = position_x; + body->last_position_y = position_y; + body->last_direction_x = direction_x; + body->last_direction_y = direction_y; + return ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_set_velocity( + ymir_box3d_session* session, + uint64_t stable_id, + float velocity_x, + float velocity_y, + float angular_velocity) +{ + if (session == NULL || !ymir_is_finite(velocity_x) || !ymir_is_finite(velocity_y) || + !ymir_is_finite(angular_velocity)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_session_body* body = session->bodies + index; + b3Body_SetLinearVelocity(body->body_id, ymir_vec(velocity_x, velocity_y)); + b3Body_SetAngularVelocity(body->body_id, (b3Vec3){0.0f, angular_velocity, 0.0f}); + body->last_velocity_x = velocity_x; + body->last_velocity_y = velocity_y; + body->last_angular_velocity = angular_velocity; + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_configure( + ymir_box3d_session* session, + uint64_t stable_id, + float radius, + float mass, + float restitution, + uint32_t is_static) +{ + if (session == NULL || !ymir_is_finite(radius) || radius <= 0.0f || !ymir_is_finite(mass) || + (is_static == 0 && mass <= 0.0f) || !ymir_is_finite(restitution) || restitution < 0.0f) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + ymir_box3d_session_body* body = session->bodies + index; + int type_changed = body->is_static != (is_static != 0); + int radius_changed = body->radius != radius; + int mass_changed = body->mass != mass; + if (type_changed) + { + b3Body_SetType(body->body_id, is_static != 0 ? b3_staticBody : b3_dynamicBody); + } + if (radius_changed) + { + b3Sphere sphere = {{0.0f, 0.0f, 0.0f}, radius}; + b3Shape_SetSphere(body->shape_id, &sphere); + } + if (type_changed || radius_changed || mass_changed) + { + float density = is_static != 0 ? 0.0f : ymir_session_density(mass, radius); + b3Shape_SetDensity(body->shape_id, density, false); + b3Body_ApplyMassFromShapes(body->body_id); + } + if (body->restitution != restitution) + { + b3Shape_SetRestitution(body->shape_id, restitution); + } + body->radius = radius; + body->mass = mass; + body->restitution = restitution; + body->is_static = is_static != 0; + ymir_box3d_status status = ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); + return status; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_apply_force( + ymir_box3d_session* session, + uint64_t stable_id, + float force_x, + float force_y) +{ + if (session == NULL || !ymir_is_finite(force_x) || !ymir_is_finite(force_y)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + b3Body_ApplyForceToCenter(session->bodies[index].body_id, ymir_vec(force_x, force_y), true); + return YMIR_BOX3D_OK; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_apply_torque( + ymir_box3d_session* session, + uint64_t stable_id, + float torque) +{ + if (session == NULL || !ymir_is_finite(torque)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + int index = ymir_session_find_body(session, stable_id); + if (index < 0) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + b3Body_ApplyTorque(session->bodies[index].body_id, (b3Vec3){0.0f, torque, 0.0f}, true); + return YMIR_BOX3D_OK; +} + YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( ymir_box3d_session* session, float time_step, @@ -979,6 +1506,23 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( } } + session->contact_event_count = 0; + ymir_box3d_status event_status = ymir_session_reserve_contact_events( + &session->contact_events, &session->contact_event_capacity, session->pending_event_count); + if (event_status != YMIR_BOX3D_OK) + { + return event_status; + } + if (session->pending_event_count > 0) + { + memcpy( + session->contact_events, + session->pending_events, + (size_t)session->pending_event_count * sizeof(ymir_box3d_session_contact_event_output)); + session->contact_event_count = session->pending_event_count; + session->pending_event_count = 0; + } + for (int body_index = 0; body_index < session->body_count; ++body_index) { ymir_box3d_session_body* body = session->bodies + body_index; @@ -1033,6 +1577,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( } b3World_Step(session->world_id, time_step, sub_step_count); + session->drained_event_count = 0; for (int i = 0; i < session->body_count; ++i) { b3Pos position = b3Body_GetPosition(session->bodies[i].body_id); @@ -1048,6 +1593,14 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( session->bodies[i].last_angular_velocity = angular_velocity.y; } + event_status = ymir_session_drain_contact_events( + session, YMIR_DRAIN_BEGIN | YMIR_DRAIN_HIT | YMIR_DRAIN_END, 0); + session->retired_shape_count = 0; + if (event_status != YMIR_BOX3D_OK) + { + return event_status; + } + return YMIR_BOX3D_OK; } @@ -1117,3 +1670,33 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_copy_contacts( *written = 0; return ymir_session_visit_contacts(session, output, capacity, written); } + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_get_contact_event_count(const ymir_box3d_session* session) +{ + return session != NULL ? session->contact_event_count : -YMIR_BOX3D_INVALID_ARGUMENT; +} + +YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_copy_contact_events( + const ymir_box3d_session* session, + ymir_box3d_session_contact_event_output* output, + int32_t capacity, + int32_t* written) +{ + if (session == NULL || written == NULL || capacity < 0 || (capacity > 0 && output == NULL)) + { + return YMIR_BOX3D_INVALID_ARGUMENT; + } + *written = session->contact_event_count; + if (capacity < session->contact_event_count) + { + return YMIR_BOX3D_BUFFER_TOO_SMALL; + } + if (session->contact_event_count > 0) + { + memcpy( + output, + session->contact_events, + (size_t)session->contact_event_count * sizeof(ymir_box3d_session_contact_event_output)); + } + return YMIR_BOX3D_OK; +} diff --git a/src/Ymir.Box3D/Box3DNative.cs b/src/Ymir.Box3D/Box3DNative.cs index 86b3615..f250b7b 100644 --- a/src/Ymir.Box3D/Box3DNative.cs +++ b/src/Ymir.Box3D/Box3DNative.cs @@ -28,7 +28,8 @@ internal static partial class Box3DNative out uint bodyInputSize, out uint fieldInputSize, out uint bodyOutputSize, - out uint contactOutputSize); + out uint contactOutputSize, + out uint contactEventOutputSize); [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] @@ -72,6 +73,60 @@ internal static partial class Box3DNative Box3DBodyInput* bodies, int bodyCount); + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_spawn( + Box3DSessionHandle session, + Box3DBodyInput* body); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_remove(Box3DSessionHandle session, ulong stableId); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_teleport( + Box3DSessionHandle session, + ulong stableId, + float positionX, + float positionZ, + float directionX, + float directionZ); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_set_velocity( + Box3DSessionHandle session, + ulong stableId, + float velocityX, + float velocityZ, + float angularVelocity); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_configure( + Box3DSessionHandle session, + ulong stableId, + float radius, + float mass, + float restitution, + uint isStatic); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_apply_force( + Box3DSessionHandle session, + ulong stableId, + float forceX, + float forceZ); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial Box3DStatus ymir_box3d_session_apply_torque( + Box3DSessionHandle session, + ulong stableId, + float torque); + [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static unsafe partial Box3DStatus ymir_box3d_session_step( @@ -104,6 +159,18 @@ internal static partial class Box3DNative Box3DContactOutput* output, int capacity, out int written); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_contact_event_count(Box3DSessionHandle session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial Box3DStatus ymir_box3d_session_copy_contact_events( + Box3DSessionHandle session, + Box3DContactEventOutput* output, + int capacity, + out int written); } internal sealed class Box3DSessionHandle : SafeHandleZeroOrMinusOneIsInvalid @@ -166,6 +233,22 @@ internal readonly record struct Box3DContactOutput( float Penetration, float RelativeSpeed); +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DContactEventOutput( + int Kind, + uint HasDetails, + uint ContactId0, + uint ContactId1, + uint ContactId2, + ulong StableIdA, + ulong StableIdB, + float PointX, + float PointZ, + float NormalX, + float NormalZ, + float Penetration, + float RelativeSpeed); + [StructLayout(LayoutKind.Sequential)] internal readonly record struct Box3DCastOutput( int Hit, diff --git a/src/Ymir.Box3D/Box3DSession.cs b/src/Ymir.Box3D/Box3DSession.cs index dc409a9..b6a9035 100644 --- a/src/Ymir.Box3D/Box3DSession.cs +++ b/src/Ymir.Box3D/Box3DSession.cs @@ -39,9 +39,31 @@ internal readonly record struct Box3DContact( float Penetration, float RelativeSpeed); +internal enum Box3DContactKind +{ + Begin = 1, + Hit = 2, + End = 3 +} + +internal readonly record struct Box3DContactKey(uint Part0, uint Part1, uint Part2); + +internal readonly record struct Box3DContactFact( + Box3DContactKind Kind, + Box3DContactKey ContactKey, + ulong StableIdA, + ulong StableIdB, + bool HasDetails, + float PointX, + float PointZ, + float NormalX, + float NormalZ, + float Penetration, + float RelativeSpeed); + internal sealed class Box3DSession : IDisposable { - internal const uint AbiVersion = 2; + internal const uint AbiVersion = 3; internal const int DefaultSubstepCount = 4; private readonly Box3DSessionHandle _handle; @@ -93,6 +115,67 @@ internal sealed class Box3DSession : IDisposable } } + internal unsafe void Spawn(Box3DBody body) + { + ThrowIfDisposed(); + var native = ToNative(body); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_spawn(_handle, &native), "spawn body"); + } + + internal void Remove(ulong stableId) + { + ThrowIfDisposed(); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_remove(_handle, stableId), "remove body"); + } + + internal void Teleport( + ulong stableId, + float positionX, + float positionZ, + float directionX, + float directionZ) + { + ThrowIfDisposed(); + ThrowIfMutationFailed( + Box3DNative.ymir_box3d_session_teleport( + _handle, stableId, positionX, positionZ, directionX, directionZ), + "teleport body"); + } + + internal void SetVelocity(ulong stableId, float linearX, float linearZ, float angular) + { + ThrowIfDisposed(); + ThrowIfMutationFailed( + Box3DNative.ymir_box3d_session_set_velocity(_handle, stableId, linearX, linearZ, angular), + "set body velocity"); + } + + internal void Configure( + ulong stableId, + float radius, + float mass, + float restitution, + bool isStatic) + { + ThrowIfDisposed(); + ThrowIfMutationFailed( + Box3DNative.ymir_box3d_session_configure( + _handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u), + "configure body"); + } + + internal void ApplyForce(ulong stableId, float x, float z) + { + ThrowIfDisposed(); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_apply_force(_handle, stableId, x, z), "apply body force"); + } + + internal void ApplyTorque(ulong stableId, float value) + { + ThrowIfDisposed(); + ThrowIfMutationFailed(Box3DNative.ymir_box3d_session_apply_torque(_handle, stableId, value), "apply body torque"); + } + internal unsafe void Step(float deltaTime, ReadOnlySpan fields, int substepCount = DefaultSubstepCount) { ThrowIfDisposed(); @@ -114,7 +197,7 @@ internal sealed class Box3DSession : IDisposable fixed (Box3DRadialField* pointer = native) { - ThrowIfFailed( + ThrowIfMutationFailed( Box3DNative.ymir_box3d_session_step(_handle, deltaTime, substepCount, pointer, native.Length), "step session"); } @@ -180,6 +263,42 @@ internal sealed class Box3DSession : IDisposable contact.RelativeSpeed)).ToArray(); } + internal unsafe Box3DContactFact[] CopyContactEvents() + { + ThrowIfDisposed(); + var count = Box3DNative.ymir_box3d_session_get_contact_event_count(_handle); + if (count < 0) + { + throw new InvalidOperationException("Box3D returned an invalid contact event count."); + } + + var native = new Box3DContactEventOutput[count]; + fixed (Box3DContactEventOutput* pointer = native) + { + ThrowIfFailed( + Box3DNative.ymir_box3d_session_copy_contact_events(_handle, pointer, count, out var written), + "copy contact events"); + if (written != count) + { + throw new InvalidOperationException( + $"Box3D contact event snapshot changed during copy: expected {count}, received {written}."); + } + } + + return native.Select(contact => new Box3DContactFact( + (Box3DContactKind)contact.Kind, + new Box3DContactKey(contact.ContactId0, contact.ContactId1, contact.ContactId2), + contact.StableIdA, + contact.StableIdB, + contact.HasDetails != 0, + contact.PointX, + contact.PointZ, + contact.NormalX, + contact.NormalZ, + contact.Penetration, + contact.RelativeSpeed)).ToArray(); + } + public void Dispose() { if (_disposed) @@ -204,12 +323,14 @@ internal sealed class Box3DSession : IDisposable out var bodyInputSize, out var fieldInputSize, out var bodyOutputSize, - out var contactOutputSize), + out var contactOutputSize, + out var contactEventOutputSize), "read native ABI layout"); EnsureSize(bodyInputSize); EnsureSize(fieldInputSize); EnsureSize(bodyOutputSize); EnsureSize(contactOutputSize); + EnsureSize(contactEventOutputSize); Box3DNative.ymir_box3d_get_version(out var major, out var minor, out var revision); if (major != 0 || minor != 1 || revision != 0) @@ -236,5 +357,29 @@ internal sealed class Box3DSession : IDisposable } } + private void ThrowIfMutationFailed(Box3DStatus status, string operation) + { + if (status is Box3DStatus.OutOfMemory or Box3DStatus.InternalError) + { + Dispose(); + } + ThrowIfFailed(status, operation); + } + + private static Box3DBodyInput ToNative(Box3DBody body) => new( + body.StableId, + body.PositionX, + body.PositionZ, + body.VelocityX, + body.VelocityZ, + body.DirectionX, + body.DirectionZ, + body.AngularVelocity, + body.Torque, + body.Radius, + body.Mass, + body.Restitution, + body.IsStatic ? 1u : 0u); + private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); } diff --git a/src/Ymir.Box3D/Ymir.Box3D.csproj b/src/Ymir.Box3D/Ymir.Box3D.csproj index 8664858..8d5c0f2 100644 --- a/src/Ymir.Box3D/Ymir.Box3D.csproj +++ b/src/Ymir.Box3D/Ymir.Box3D.csproj @@ -9,7 +9,7 @@ Ymir.Box3D Native ABI boundary between Ymir sessions and pinned Box3D. GameCult.Ymir.Box3D - 0.1.0 + 0.2.0 GameCult true README.md diff --git a/src/Ymir.Core/RetainedSessionModel.cs b/src/Ymir.Core/RetainedSessionModel.cs new file mode 100644 index 0000000..a30ea72 --- /dev/null +++ b/src/Ymir.Core/RetainedSessionModel.cs @@ -0,0 +1,120 @@ +namespace Ymir.Core; + +public sealed record YmirSessionCreateRequest( + string SessionId, + IReadOnlyList InitialBodies, + float InitialTime = 0.0f); + +public sealed record YmirCommandHeader(string CommandId, long ExpectedRevision); + +public sealed record YmirSpawnBodyCommand(YmirCommandHeader Header, PhysicsBody Body); + +public sealed record YmirRemoveBodyCommand(YmirCommandHeader Header, string BodyId); + +public sealed record YmirTeleportBodyCommand( + YmirCommandHeader Header, + string BodyId, + Vec2 Position, + Vec2 Direction); + +public sealed record YmirSetBodyVelocityCommand( + YmirCommandHeader Header, + string BodyId, + Vec2 LinearVelocity, + float AngularVelocity); + +public sealed record YmirConfigureBodyCommand( + YmirCommandHeader Header, + string BodyId, + float Radius, + float Mass, + bool IsStatic, + float Restitution); + +public sealed record YmirApplyForceCommand( + YmirCommandHeader Header, + string BodyId, + Vec2 Force); + +public sealed record YmirApplyTorqueCommand( + YmirCommandHeader Header, + string BodyId, + float Torque); + +public sealed record YmirStepSessionCommand( + YmirCommandHeader Header, + float DeltaTime, + IReadOnlyList Fields, + int SubstepCount = 4); + +public sealed record YmirDisposeSessionCommand(YmirCommandHeader Header); + +public enum YmirCommandOutcome +{ + Accepted, + Rejected +} + +public enum YmirCommandError +{ + None, + StaleRevision, + CommandIdConflict, + DuplicateBody, + UnknownBody, + StaticBody, + InvalidCommand, + SessionDisposed, + SessionFaulted +} + +public sealed record YmirCommandReceipt( + string ReceiptId, + string SessionId, + string SessionGeneration, + string CommandId, + string CommandKind, + YmirCommandOutcome Outcome, + YmirCommandError Error, + long BeforeRevision, + long AfterRevision, + long ObservedStepIndex, + IReadOnlyList ProducedFactIds); + +public enum YmirContactFactKind +{ + Begin, + Hit, + End +} + +public sealed record YmirContactFact( + string FactId, + string ContactId, + YmirContactFactKind Kind, + string SessionId, + string SessionGeneration, + long StepIndex, + string BodyA, + long BodyAGeneration, + string BodyB, + long BodyBGeneration, + Vec2? Point, + Vec2? Normal, + float? Penetration, + float? RelativeSpeed); + +public sealed record YmirSessionStepResult( + YmirCommandReceipt Receipt, + YmirWorld World, + long Revision, + long StepIndex, + IReadOnlyList ContactFacts); + +public sealed record YmirSessionInfo( + string SessionId, + string SessionGeneration, + long Revision, + long StepIndex, + bool IsDisposed, + bool IsFaulted); diff --git a/src/Ymir.Core/YmirServicePublicationDocument.cs b/src/Ymir.Core/YmirServicePublicationDocument.cs index 4b492ea..615692b 100644 --- a/src/Ymir.Core/YmirServicePublicationDocument.cs +++ b/src/Ymir.Core/YmirServicePublicationDocument.cs @@ -17,7 +17,7 @@ public sealed class YmirProviderAdvertisementDocument public string Title { get; set; } = "Ymir Physics"; [Key(2)] - public string Description { get; set; } = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface."; + public string Description { get; set; } = "GameCult Box3D retained-session library and physics-daemon cutover surface."; [Key(3)] public string[] Owns { get; set; } = []; @@ -44,7 +44,7 @@ public sealed class YmirOperatorStateDocument public string Status { get; set; } = "mvp"; [Key(2)] - public string StateOwner { get; set; } = "Isolated Box3D snapshot steps and typed diagnostic projections"; + public string StateOwner { get; set; } = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections"; [Key(3)] public string NumericSubstrate { get; set; } = "Box3D v0.1.0 (C17)"; @@ -81,10 +81,12 @@ public static class YmirServicePublication { ProviderId = "ymir.physics", Title = "Ymir Physics", - Description = "GameCult Box3D snapshot wrapper and physics-daemon cutover surface.", + Description = "GameCult Box3D retained-session library and physics-daemon cutover surface.", Owns = [ "Box3D-only isolated snapshot stepping", + "public in-process retained sessions with explicit mutation receipts", + "typed Begin, Hit, and End contact facts for retained steps", "stable GameCult id to transient Box3D handle projection", "Box3D-backed circle overlap and cast queries over submitted bodies", "deterministic result ordering", @@ -93,8 +95,7 @@ public static class YmirServicePublication ], DoesNotOwn = [ - "public retained session lifecycle yet", - "typed command receipts or begin/end/hit lifecycle facts yet", + "daemon-owned named session registry or CultMesh command lowering yet", "complete checkpoint reconstruction yet", "physics algorithm invention", "Box3D solver and collision semantics", @@ -111,7 +112,7 @@ public static class YmirServicePublication { ProviderId = "ymir.physics", Status = "mvp", - StateOwner = "Isolated Box3D snapshot steps and typed diagnostic projections", + StateOwner = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections", NumericSubstrate = "Box3D v0.1.0 (C17)", BatchKernel = "Box3D native solver; Ymir does not own physics algorithms", Persistence = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration", diff --git a/src/Ymir.Core/YmirSession.cs b/src/Ymir.Core/YmirSession.cs new file mode 100644 index 0000000..e963e6c --- /dev/null +++ b/src/Ymir.Core/YmirSession.cs @@ -0,0 +1,992 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using Ymir.Box3D; + +namespace Ymir.Core; + +/// +/// Owns one retained Box3D world. Ordinary operations are explicit commands; +/// complete snapshots are accepted only while the session is created. +/// +public sealed class YmirSession : IDisposable +{ + private readonly object _gate = new(); + private readonly Box3DSession _native = new(); + private readonly Dictionary _activeKeysById = new(StringComparer.Ordinal); + private readonly Dictionary _idsByKey = new(); + private readonly Dictionary _generationsByKey = new(); + private readonly Dictionary _bodies = new(StringComparer.Ordinal); + private readonly Dictionary _episodesByNativeContact = new(); + private readonly Dictionary _ledger = new(StringComparer.Ordinal); + private readonly string _sessionId; + private readonly string _sessionGeneration; + private ulong _nextNativeKey = 1; + private long _nextBodyGeneration = 1; + private long _revision; + private long _stepIndex; + private float _time; + private RadialField[] _fields = []; + private bool _disposed; + private bool _faulted; + + private YmirSession(YmirSessionCreateRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (string.IsNullOrWhiteSpace(request.SessionId)) + { + throw new ArgumentException("Session id is required.", nameof(request)); + } + if (!float.IsFinite(request.InitialTime) || request.InitialTime < 0.0f) + { + throw new ArgumentOutOfRangeException(nameof(request), "Initial time must be finite and non-negative."); + } + + _sessionId = request.SessionId; + _sessionGeneration = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); + _time = request.InitialTime; + + var initial = request.InitialBodies ?? throw new ArgumentNullException(nameof(request.InitialBodies)); + ValidateUniqueBodyIds(initial); + try + { + foreach (var body in initial.OrderBy(body => body.Id, StringComparer.Ordinal)) + { + ValidateBody(body, allowTorque: false); + SpawnCore(body); + } + } + catch + { + _native.Dispose(); + _disposed = true; + throw; + } + } + + public static YmirSession Create(YmirSessionCreateRequest request) => new(request); + + public YmirSessionInfo Info + { + get + { + lock (_gate) + { + return new YmirSessionInfo( + _sessionId, _sessionGeneration, _revision, _stepIndex, _disposed, _faulted); + } + } + } + + public YmirCommandReceipt Spawn(YmirSpawnBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.spawn", writer => WriteBody(writer, command.Body)); + if (Preflight(command.Header, fingerprint, "body.spawn") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.spawn", fingerprint); + } + if (!TryValidateBody(command.Body, allowTorque: false)) + { + return RejectAndStore(command.Header, fingerprint, "body.spawn", YmirCommandError.InvalidCommand); + } + if (_activeKeysById.ContainsKey(command.Body.Id)) + { + return RejectAndStore(command.Header, fingerprint, "body.spawn", YmirCommandError.DuplicateBody); + } + + SpawnCore(command.Body); + return AcceptAndStore(command.Header, fingerprint, "body.spawn"); + } + } + + public YmirCommandReceipt Remove(YmirRemoveBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.remove", writer => WriteString(writer, command.BodyId)); + if (Preflight(command.Header, fingerprint, "body.remove") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.remove", fingerprint); + } + if (string.IsNullOrWhiteSpace(command.BodyId) || + !_activeKeysById.TryGetValue(command.BodyId, out var key)) + { + return RejectAndStore(command.Header, fingerprint, "body.remove", YmirCommandError.UnknownBody); + } + + RunNative(() => + { + _native.Remove(key); + _activeKeysById.Remove(command.BodyId); + _bodies.Remove(command.BodyId); + }); + return AcceptAndStore(command.Header, fingerprint, "body.remove"); + } + } + + public YmirCommandReceipt Teleport(YmirTeleportBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.teleport", writer => + { + WriteString(writer, command.BodyId); + Write(writer, command.Position); + Write(writer, command.Direction); + }); + if (Preflight(command.Header, fingerprint, "body.teleport") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.teleport", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.teleport", YmirCommandError.UnknownBody); + } + if (!Finite(command.Position) || !ValidDirection(command.Direction)) + { + return RejectAndStore(command.Header, fingerprint, "body.teleport", YmirCommandError.InvalidCommand); + } + + var direction = Normalize(command.Direction); + RunNative(() => + { + _native.Teleport(key, command.Position.X, command.Position.Y, direction.X, direction.Y); + _bodies[command.BodyId] = body with { Position = command.Position, Direction = direction }; + UpdateBodyProjection(_native.CopyBodies()); + }); + return AcceptAndStore(command.Header, fingerprint, "body.teleport"); + } + } + + public YmirCommandReceipt SetVelocity(YmirSetBodyVelocityCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.set_velocity", writer => + { + WriteString(writer, command.BodyId); + Write(writer, command.LinearVelocity); + writer.Write(command.AngularVelocity); + }); + if (Preflight(command.Header, fingerprint, "body.set_velocity") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.set_velocity", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.UnknownBody); + } + if (body.IsStatic) + { + return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.StaticBody); + } + if (!Finite(command.LinearVelocity) || !float.IsFinite(command.AngularVelocity)) + { + return RejectAndStore(command.Header, fingerprint, "body.set_velocity", YmirCommandError.InvalidCommand); + } + + RunNative(() => + { + _native.SetVelocity(key, command.LinearVelocity.X, command.LinearVelocity.Y, command.AngularVelocity); + _bodies[command.BodyId] = body with + { + Velocity = command.LinearVelocity, + AngularVelocity = command.AngularVelocity + }; + UpdateBodyProjection(_native.CopyBodies()); + }); + return AcceptAndStore(command.Header, fingerprint, "body.set_velocity"); + } + } + + public YmirCommandReceipt Configure(YmirConfigureBodyCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.configure", writer => + { + WriteString(writer, command.BodyId); + writer.Write(command.Radius); + writer.Write(command.Mass); + writer.Write(command.IsStatic); + writer.Write(command.Restitution); + }); + if (Preflight(command.Header, fingerprint, "body.configure") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.configure", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.UnknownBody); + } + if (!float.IsFinite(command.Radius) || command.Radius <= 0.0f || + !float.IsFinite(command.Mass) || (!command.IsStatic && command.Mass <= 0.0f) || + !float.IsFinite(command.Restitution) || command.Restitution < 0.0f) + { + return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.InvalidCommand); + } + + RunNative(() => + { + _native.Configure(key, command.Radius, command.Mass, command.Restitution, command.IsStatic); + _bodies[command.BodyId] = body with + { + Radius = command.Radius, + Mass = command.Mass, + IsStatic = command.IsStatic, + Restitution = command.Restitution + }; + UpdateBodyProjection(_native.CopyBodies()); + }); + return AcceptAndStore(command.Header, fingerprint, "body.configure"); + } + } + + public YmirCommandReceipt ApplyForce(YmirApplyForceCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.apply_force", writer => + { + WriteString(writer, command.BodyId); + Write(writer, command.Force); + }); + if (Preflight(command.Header, fingerprint, "body.apply_force") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.apply_force", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.UnknownBody); + } + if (body.IsStatic) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.StaticBody); + } + if (!Finite(command.Force)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.InvalidCommand); + } + + RunNative(() => _native.ApplyForce(key, command.Force.X, command.Force.Y)); + return AcceptAndStore(command.Header, fingerprint, "body.apply_force"); + } + } + + public YmirCommandReceipt ApplyTorque(YmirApplyTorqueCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "body.apply_torque", writer => + { + WriteString(writer, command.BodyId); + writer.Write(command.Torque); + }); + if (Preflight(command.Header, fingerprint, "body.apply_torque") is { } previous) + { + return ReceiptFrom(previous, command.Header, "body.apply_torque", fingerprint); + } + if (!TryBody(command.BodyId, out var key, out var body)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.UnknownBody); + } + if (body.IsStatic) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.StaticBody); + } + if (!float.IsFinite(command.Torque)) + { + return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.InvalidCommand); + } + + RunNative(() => _native.ApplyTorque(key, command.Torque)); + return AcceptAndStore(command.Header, fingerprint, "body.apply_torque"); + } + } + + public YmirSessionStepResult Step(YmirStepSessionCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var submittedFields = command.Fields; + var fieldsValid = submittedFields != null && FieldsAreValid(submittedFields); + var orderedFields = fieldsValid + ? submittedFields!.OrderBy(field => field.Id, StringComparer.Ordinal).ToArray() + : []; + var fingerprint = Fingerprint(command.Header, "session.step", writer => + { + writer.Write(command.DeltaTime); + writer.Write(command.SubstepCount); + if (submittedFields == null) + { + writer.Write(-1); + return; + } + var fields = fieldsValid ? orderedFields : submittedFields; + writer.Write(fields.Count); + foreach (var field in fields) + { + WriteField(writer, field); + } + }); + if (Preflight(command.Header, fingerprint, "session.step") is { } previous) + { + if (previous.Result is YmirSessionStepResult replay) + { + return replay; + } + var rejected = ReceiptFrom(previous, command.Header, "session.step", fingerprint); + return new YmirSessionStepResult(rejected, SnapshotCore(), _revision, _stepIndex, []); + } + if (!float.IsFinite(command.DeltaTime) || command.DeltaTime <= 0.0f || + command.SubstepCount <= 0 || !fieldsValid) + { + var rejected = RejectAndStore(command.Header, fingerprint, "session.step", YmirCommandError.InvalidCommand); + return new YmirSessionStepResult(rejected, SnapshotCore(), _revision, _stepIndex, []); + } + + var nativeFields = orderedFields + .Select(field => new Box3DField(field.Position.X, field.Position.Y, field.Strength, field.Radius)) + .ToArray(); + YmirContactFact[] facts; + try + { + _native.Step(command.DeltaTime, nativeFields, command.SubstepCount); + UpdateBodyProjection(_native.CopyBodies()); + _time += command.DeltaTime; + _fields = orderedFields; + _stepIndex += 1; + _revision += 1; + facts = ProjectFacts(_native.CopyContactEvents()).ToArray(); + PruneRetiredIdentity(); + } + catch + { + Poison(); + throw; + } + try + { + var receipt = AcceptedReceipt(command.Header, "session.step", _revision - 1, _revision, + facts.Select(fact => fact.FactId).ToArray()); + var result = new YmirSessionStepResult(receipt, SnapshotCore(), _revision, _stepIndex, facts); + _ledger.Add(command.Header.CommandId, new LedgerEntry(fingerprint, result)); + return result; + } + catch + { + Poison(); + throw; + } + } + } + + public YmirWorld Snapshot() + { + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + return SnapshotCore(); + } + } + + public YmirCommandReceipt Dispose(YmirDisposeSessionCommand command) + { + ArgumentNullException.ThrowIfNull(command); + lock (_gate) + { + var fingerprint = Fingerprint(command.Header, "session.dispose", _ => { }); + if (Preflight(command.Header, fingerprint, "session.dispose") is { } previous) + { + return ReceiptFrom(previous, command.Header, "session.dispose", fingerprint); + } + + var before = _revision; + _native.Dispose(); + _disposed = true; + _revision += 1; + var receipt = AcceptedReceipt(command.Header, "session.dispose", before, _revision, []); + _ledger.Add(command.Header.CommandId, new LedgerEntry(fingerprint, receipt)); + return receipt; + } + } + + public void Dispose() + { + lock (_gate) + { + if (_disposed) + { + return; + } + _native.Dispose(); + _disposed = true; + } + } + + private void SpawnCore(PhysicsBody body) + { + var key = NextKey(); + var generation = _nextBodyGeneration++; + var canonicalBody = body with { Torque = 0.0f, Direction = DirectionOrDefault(body.Direction) }; + RunNative(() => + { + _native.Spawn(ToNative(key, canonicalBody)); + _activeKeysById.Add(canonicalBody.Id, key); + _idsByKey.Add(key, canonicalBody.Id); + _generationsByKey.Add(key, generation); + _bodies.Add(canonicalBody.Id, canonicalBody); + }); + } + + private IReadOnlyList ProjectFacts(IReadOnlyList nativeFacts) + { + var projected = new List(nativeFacts.Count); + var ephemeralEpisodes = new Dictionary(); + var newEpisodeOrdinals = new Dictionary(); + var factOrdinals = new Dictionary<( + ContactPair Pair, + long StartStep, + long EpisodeOrdinal, + YmirContactFactKind Kind), int>(); + foreach (var native in nativeFacts) + { + var canonical = CanonicalizeContact(native); + var pair = new ContactPair( + canonical.BodyA, + canonical.BodyAGeneration, + canonical.BodyB, + canonical.BodyBGeneration); + ActiveEpisode episode; + if (native.Kind == Box3DContactKind.Begin) + { + if (!_episodesByNativeContact.TryGetValue(native.ContactKey, out episode!)) + { + episode = NewEpisode(pair, newEpisodeOrdinals); + _episodesByNativeContact[native.ContactKey] = episode; + } + } + else if (!_episodesByNativeContact.TryGetValue(native.ContactKey, out episode!) && + !ephemeralEpisodes.TryGetValue(native.ContactKey, out episode!)) + { + episode = NewEpisode(pair, newEpisodeOrdinals); + ephemeralEpisodes.Add(native.ContactKey, episode); + } + + var kind = native.Kind switch + { + Box3DContactKind.Begin => YmirContactFactKind.Begin, + Box3DContactKind.Hit => YmirContactFactKind.Hit, + Box3DContactKind.End => YmirContactFactKind.End, + _ => throw new InvalidOperationException($"Unknown Box3D contact fact kind {native.Kind}.") + }; + var ordinalKey = (pair, episode.StartStepIndex, episode.Ordinal, kind); + var ordinal = factOrdinals.GetValueOrDefault(ordinalKey); + factOrdinals[ordinalKey] = ordinal + 1; + var pairId = PairId(pair); + var contactId = $"{_sessionGeneration}:contact:{pairId}:{episode.StartStepIndex}:{episode.Ordinal}"; + var factId = $"{_sessionGeneration}:step:{_stepIndex}:contact:{pairId}:{episode.StartStepIndex}:{episode.Ordinal}:{kind.ToString().ToLowerInvariant()}:{ordinal}"; + var hasDetails = native.HasDetails; + var fact = new YmirContactFact( + factId, + contactId, + kind, + _sessionId, + _sessionGeneration, + _stepIndex, + canonical.BodyA, + canonical.BodyAGeneration, + canonical.BodyB, + canonical.BodyBGeneration, + hasDetails ? canonical.Point : null, + hasDetails ? canonical.Normal : null, + hasDetails ? native.Penetration : null, + hasDetails ? native.RelativeSpeed : null); + projected.Add(new ProjectedFact(fact, episode.StartStepIndex, episode.Ordinal, ordinal)); + + if (native.Kind == Box3DContactKind.End) + { + _episodesByNativeContact.Remove(native.ContactKey); + ephemeralEpisodes.Remove(native.ContactKey); + } + } + + return projected + .OrderBy(item => item.Fact.BodyA, StringComparer.Ordinal) + .ThenBy(item => item.Fact.BodyAGeneration) + .ThenBy(item => item.Fact.BodyB, StringComparer.Ordinal) + .ThenBy(item => item.Fact.BodyBGeneration) + .ThenBy(item => item.EpisodeStartStep) + .ThenBy(item => item.EpisodeOrdinal) + .ThenBy(item => FactKindOrder(item.Fact.Kind)) + .ThenBy(item => item.Ordinal) + .Select(item => item.Fact) + .ToArray(); + } + + private CanonicalContact CanonicalizeContact(Box3DContactFact fact) + { + var idA = ResolveId(fact.StableIdA); + var idB = ResolveId(fact.StableIdB); + var generationA = _generationsByKey[fact.StableIdA]; + var generationB = _generationsByKey[fact.StableIdB]; + var swap = StringComparer.Ordinal.Compare(idA, idB) > 0 || + (StringComparer.Ordinal.Equals(idA, idB) && generationA > generationB); + return swap + ? new CanonicalContact( + idB, generationB, idA, generationA, + new Vec2(fact.PointX, fact.PointZ), + new Vec2(-fact.NormalX, -fact.NormalZ)) + : new CanonicalContact( + idA, generationA, idB, generationB, + new Vec2(fact.PointX, fact.PointZ), + new Vec2(fact.NormalX, fact.NormalZ)); + } + + private void UpdateBodyProjection(IReadOnlyList states) + { + foreach (var state in states) + { + var id = ResolveId(state.StableId); + if (!_bodies.TryGetValue(id, out var body) || _activeKeysById.GetValueOrDefault(id) != state.StableId) + { + throw new InvalidOperationException($"Box3D returned inactive body key {state.StableId}."); + } + _bodies[id] = body with + { + Position = new Vec2(state.PositionX, state.PositionZ), + Velocity = new Vec2(state.VelocityX, state.VelocityZ), + Direction = new Vec2(state.DirectionX, state.DirectionZ), + AngularVelocity = state.AngularVelocity, + Torque = 0.0f + }; + } + } + + private LedgerEntry? Preflight(YmirCommandHeader header, string fingerprint, string kind) + { + ValidateHeader(header); + if (_ledger.TryGetValue(header.CommandId, out var existing)) + { + return existing.Fingerprint == fingerprint + ? existing + : new LedgerEntry(fingerprint, ConflictReceipt(header, kind, fingerprint)); + } + if (_faulted) + { + var rejected = RejectedReceipt(header, kind, YmirCommandError.SessionFaulted); + var entry = new LedgerEntry(fingerprint, rejected); + _ledger.Add(header.CommandId, entry); + return entry; + } + if (_disposed) + { + var rejected = RejectedReceipt(header, kind, YmirCommandError.SessionDisposed); + var entry = new LedgerEntry(fingerprint, rejected); + _ledger.Add(header.CommandId, entry); + return entry; + } + if (header.ExpectedRevision != _revision) + { + var rejected = RejectedReceipt(header, kind, YmirCommandError.StaleRevision); + var entry = new LedgerEntry(fingerprint, rejected); + _ledger.Add(header.CommandId, entry); + return entry; + } + return null; + } + + private YmirCommandReceipt ReceiptFrom( + LedgerEntry entry, + YmirCommandHeader header, + string kind, + string fingerprint) + { + if (entry.Fingerprint != fingerprint) + { + return RejectedReceipt(header, kind, YmirCommandError.CommandIdConflict); + } + return entry.Result switch + { + YmirCommandReceipt receipt => receipt, + YmirSessionStepResult step => step.Receipt, + _ => throw new InvalidOperationException("Unknown Ymir receipt ledger entry.") + }; + } + + private YmirCommandReceipt AcceptAndStore(YmirCommandHeader header, string fingerprint, string kind) + { + try + { + var before = _revision; + _revision += 1; + var receipt = AcceptedReceipt(header, kind, before, _revision, []); + _ledger.Add(header.CommandId, new LedgerEntry(fingerprint, receipt)); + return receipt; + } + catch + { + Poison(); + throw; + } + } + + private YmirCommandReceipt RejectAndStore( + YmirCommandHeader header, + string fingerprint, + string kind, + YmirCommandError error) + { + var receipt = RejectedReceipt(header, kind, error); + _ledger.Add(header.CommandId, new LedgerEntry(fingerprint, receipt)); + return receipt; + } + + private YmirCommandReceipt AcceptedReceipt( + YmirCommandHeader header, + string kind, + long before, + long after, + IReadOnlyList facts) => + new( + $"{_sessionGeneration}:receipt:{header.CommandId}", + _sessionId, + _sessionGeneration, + header.CommandId, + kind, + YmirCommandOutcome.Accepted, + YmirCommandError.None, + before, + after, + _stepIndex, + facts); + + private YmirCommandReceipt RejectedReceipt( + YmirCommandHeader header, + string kind, + YmirCommandError error) => + new( + $"{_sessionGeneration}:receipt:{header.CommandId}", + _sessionId, + _sessionGeneration, + header.CommandId, + kind, + YmirCommandOutcome.Rejected, + error, + _revision, + _revision, + _stepIndex, + []); + + private YmirCommandReceipt ConflictReceipt( + YmirCommandHeader header, + string kind, + string fingerprint) + { + var conflictId = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint))) + .ToLowerInvariant(); + return new YmirCommandReceipt( + $"{_sessionGeneration}:receipt-conflict:{header.CommandId}:{conflictId}", + _sessionId, + _sessionGeneration, + header.CommandId, + kind, + YmirCommandOutcome.Rejected, + YmirCommandError.CommandIdConflict, + _revision, + _revision, + _stepIndex, + []); + } + + private YmirWorld SnapshotCore() => new( + _time, + _bodies.Values.OrderBy(body => body.Id, StringComparer.Ordinal).ToArray(), + _fields.ToArray()); + + private bool TryBody(string? id, out ulong key, out PhysicsBody body) + { + if (!string.IsNullOrWhiteSpace(id) && + _activeKeysById.TryGetValue(id, out key) && + _bodies.TryGetValue(id, out body!)) + { + return true; + } + key = 0; + body = null!; + return false; + } + + private string ResolveId(ulong key) => _idsByKey.TryGetValue(key, out var id) + ? id + : throw new InvalidOperationException($"Box3D returned unknown stable body key {key}."); + + private ActiveEpisode NewEpisode(ContactPair pair, IDictionary ordinals) + { + var ordinal = (ordinals.TryGetValue(pair, out var previous) ? previous : 0) + 1; + ordinals[pair] = ordinal; + return new ActiveEpisode(_stepIndex, ordinal, pair); + } + + private void PruneRetiredIdentity() + { + var activeKeys = _activeKeysById.Values.ToHashSet(); + foreach (var key in _idsByKey.Keys.Where(key => !activeKeys.Contains(key)).ToArray()) + { + var id = _idsByKey[key]; + var generation = _generationsByKey[key]; + if (_episodesByNativeContact.Values.Any(active => + (active.Pair.BodyA == id && active.Pair.BodyAGeneration == generation) || + (active.Pair.BodyB == id && active.Pair.BodyBGeneration == generation))) + { + throw new InvalidOperationException( + $"Box3D did not close every contact episode for removed body '{id}' generation {generation}."); + } + _idsByKey.Remove(key); + _generationsByKey.Remove(key); + } + } + + private void RunNative(Action operation) + { + try + { + operation(); + } + catch + { + Poison(); + throw; + } + } + + private void Poison() + { + _native.Dispose(); + _disposed = true; + _faulted = true; + } + + private ulong NextKey() + { + if (_nextNativeKey == 0) + { + throw new InvalidOperationException("Ymir exhausted its native body key space."); + } + return _nextNativeKey++; + } + + private static Box3DBody ToNative(ulong key, PhysicsBody body) + { + var direction = DirectionOrDefault(body.Direction); + return new Box3DBody( + key, + body.Position.X, + body.Position.Y, + body.Velocity.X, + body.Velocity.Y, + direction.X, + direction.Y, + body.AngularVelocity, + 0.0f, + body.Radius, + body.Mass, + body.Restitution, + body.IsStatic); + } + + private static Vec2 DirectionOrDefault(Vec2? direction) => + direction is { } value && ValidDirection(value) ? Normalize(value) : new Vec2(0.0f, 1.0f); + + private static Vec2 Normalize(Vec2 value) + { + var inverseLength = 1.0f / MathF.Sqrt(value.X * value.X + value.Y * value.Y); + return new Vec2(value.X * inverseLength, value.Y * inverseLength); + } + + private static void ValidateHeader(YmirCommandHeader header) + { + ArgumentNullException.ThrowIfNull(header); + if (string.IsNullOrWhiteSpace(header.CommandId)) + { + throw new ArgumentException("Command id is required.", nameof(header)); + } + if (header.ExpectedRevision < 0) + { + throw new ArgumentOutOfRangeException(nameof(header), "Expected revision must be non-negative."); + } + } + + private static void ValidateUniqueBodyIds(IReadOnlyList bodies) + { + var ids = new HashSet(StringComparer.Ordinal); + foreach (var body in bodies) + { + if (!ids.Add(body.Id)) + { + throw new ArgumentException($"Ymir body id '{body.Id}' occurs more than once.", nameof(bodies)); + } + } + } + + private static bool TryValidateBody(PhysicsBody body, bool allowTorque) + { + try + { + ValidateBody(body, allowTorque); + return true; + } + catch (ArgumentException) + { + return false; + } + } + + private static void ValidateBody(PhysicsBody body, bool allowTorque) + { + ArgumentNullException.ThrowIfNull(body); + if (string.IsNullOrWhiteSpace(body.Id) || !Finite(body.Position) || !Finite(body.Velocity) || + !float.IsFinite(body.Radius) || body.Radius <= 0.0f || + !float.IsFinite(body.Mass) || (!body.IsStatic && body.Mass <= 0.0f) || + !float.IsFinite(body.Restitution) || body.Restitution < 0.0f || + (body.Direction is { } direction && !ValidDirection(direction)) || + !float.IsFinite(body.AngularVelocity) || !float.IsFinite(body.Torque) || + (!allowTorque && body.Torque != 0.0f)) + { + throw new ArgumentException("Body definition is not valid for a retained Ymir session.", nameof(body)); + } + } + + private static bool FieldsAreValid(IReadOnlyList fields) + { + var ids = new HashSet(StringComparer.Ordinal); + return fields.All(field => field != null && + !string.IsNullOrWhiteSpace(field.Id) && ids.Add(field.Id) && Finite(field.Position) && + float.IsFinite(field.Strength) && float.IsFinite(field.Radius) && field.Radius >= 0.0f); + } + + private static bool Finite(Vec2 value) => float.IsFinite(value.X) && float.IsFinite(value.Y); + + private static bool ValidDirection(Vec2 value) => + Finite(value) && value.X * value.X + value.Y * value.Y > 1.0e-8f; + + private static string Fingerprint( + YmirCommandHeader header, + string kind, + Action writePayload) + { + using var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(1); + WriteString(writer, kind); + writer.Write(header.ExpectedRevision); + writePayload(writer); + } + return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, checked((int)stream.Length)))) + .ToLowerInvariant(); + } + + private static void WriteBody(BinaryWriter writer, PhysicsBody? body) + { + writer.Write(body != null); + if (body == null) + { + return; + } + WriteString(writer, body.Id); + Write(writer, body.Position); + Write(writer, body.Velocity); + writer.Write(body.Radius); + writer.Write(body.Mass); + writer.Write(body.IsStatic); + writer.Write(body.Restitution); + writer.Write(body.Direction.HasValue); + if (body.Direction is { } direction) + { + Write(writer, direction); + } + writer.Write(body.AngularVelocity); + writer.Write(body.Torque); + } + + private static void WriteField(BinaryWriter writer, RadialField? field) + { + writer.Write(field != null); + if (field == null) + { + return; + } + WriteString(writer, field.Id); + Write(writer, field.Position); + writer.Write(field.Strength); + writer.Write(field.Radius); + } + + private static void Write(BinaryWriter writer, Vec2 value) + { + writer.Write(value.X); + writer.Write(value.Y); + } + + private static void WriteString(BinaryWriter writer, string? value) + { + writer.Write(value != null); + if (value != null) + { + writer.Write(value); + } + } + + private static string PairId(ContactPair pair) + { + var source = $"{pair.BodyA.Length}:{pair.BodyA}:{pair.BodyAGeneration}:{pair.BodyB.Length}:{pair.BodyB}:{pair.BodyBGeneration}"; + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source))).ToLowerInvariant(); + } + + private static int FactKindOrder(Box3DContactKind kind) => kind switch + { + Box3DContactKind.Begin => 0, + Box3DContactKind.Hit => 1, + Box3DContactKind.End => 2, + _ => 3 + }; + + private static int FactKindOrder(YmirContactFactKind kind) => kind switch + { + YmirContactFactKind.Begin => 0, + YmirContactFactKind.Hit => 1, + YmirContactFactKind.End => 2, + _ => 3 + }; + + private sealed record LedgerEntry(string Fingerprint, object Result); + + private sealed record ContactPair(string BodyA, long BodyAGeneration, string BodyB, long BodyBGeneration); + + private sealed record ActiveEpisode(long StartStepIndex, long Ordinal, ContactPair Pair); + + private sealed record ProjectedFact( + YmirContactFact Fact, + long EpisodeStartStep, + long EpisodeOrdinal, + int Ordinal); + + private sealed record CanonicalContact( + string BodyA, + long BodyAGeneration, + string BodyB, + long BodyBGeneration, + Vec2 Point, + Vec2 Normal); +} diff --git a/tests/Ymir.Box3D.Parity/Box3DOracle.cs b/tests/Ymir.Box3D.Parity/Box3DOracle.cs index beb1d58..43a98be 100644 --- a/tests/Ymir.Box3D.Parity/Box3DOracle.cs +++ b/tests/Ymir.Box3D.Parity/Box3DOracle.cs @@ -59,6 +59,47 @@ internal static partial class Box3DOracle [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial Box3DTorqueResult ymir_box3d_torque_lifetime(float torque, float timeStep, int subStepCount); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial uint ymir_box3d_get_abi_version(); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_create(out nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial void ymir_box3d_session_destroy(nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_spawn(nint session, Box3DSessionBodyInput* body); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_remove(nint session, ulong stableId); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_step( + nint session, + float deltaTime, + int substepCount, + void* fields, + int fieldCount); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_contact_event_count(nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_copy_contact_events( + nint session, + Box3DSessionContactEvent* events, + int capacity, + out int written); } [StructLayout(LayoutKind.Sequential)] @@ -109,3 +150,35 @@ internal readonly record struct Box3DPairStepResult( internal readonly record struct Box3DTorqueResult( float AngularVelocityAfterAppliedStep, float AngularVelocityAfterUnforcedStep); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DSessionBodyInput( + ulong StableId, + float PositionX, + float PositionY, + float VelocityX, + float VelocityY, + float DirectionX, + float DirectionY, + float AngularVelocity, + float Torque, + float Radius, + float Mass, + float Restitution, + uint IsStatic); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DSessionContactEvent( + int Kind, + uint HasDetails, + uint ContactId0, + uint ContactId1, + uint ContactId2, + ulong StableIdA, + ulong StableIdB, + float PointX, + float PointY, + float NormalX, + float NormalY, + float Penetration, + float RelativeSpeed); diff --git a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs index 828c501..7d68ca3 100644 --- a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs +++ b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs @@ -120,4 +120,51 @@ public sealed class Box3DParityTests result.AngularVelocityAfterUnforcedStep, precision: 5); } + + [Fact] + public unsafe void RetainedSessionCommandsPreserveTypedContactLifecycle() + { + Assert.Equal(3u, Box3DOracle.ymir_box3d_get_abi_version()); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session)); + try + { + var bodyA = new Box3DSessionBodyInput( + 1, -0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0); + var bodyB = new Box3DSessionBodyInput( + 2, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyB)); + Assert.Equal(2, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA)); + Assert.Equal(1, Box3DOracle.ymir_box3d_session_remove(session, 999)); + + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0)); + var beginEvents = CopyEvents(session); + var begin = Assert.Single(beginEvents, value => value.Kind == 1); + Assert.Equal(new HashSet { 1, 2 }, new HashSet { begin.StableIdA, begin.StableIdB }); + Assert.Equal(1u, begin.HasDetails); + + Assert.Equal(0, Box3DOracle.ymir_box3d_session_remove(session, 2)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0)); + var end = Assert.Single(CopyEvents(session), value => value.Kind == 3); + Assert.Equal(new HashSet { 1, 2 }, new HashSet { end.StableIdA, end.StableIdB }); + Assert.Equal(0u, end.HasDetails); + } + finally + { + Box3DOracle.ymir_box3d_session_destroy(session); + } + } + + private static unsafe Box3DSessionContactEvent[] CopyEvents(nint session) + { + var count = Box3DOracle.ymir_box3d_session_get_contact_event_count(session); + Assert.True(count >= 0); + var events = new Box3DSessionContactEvent[count]; + fixed (Box3DSessionContactEvent* pointer = events) + { + Assert.Equal(0, Box3DOracle.ymir_box3d_session_copy_contact_events(session, pointer, count, out var written)); + Assert.Equal(count, written); + } + return events; + } } diff --git a/tests/Ymir.Tests/YmirServicePublicationTests.cs b/tests/Ymir.Tests/YmirServicePublicationTests.cs index d06be58..3668aed 100644 --- a/tests/Ymir.Tests/YmirServicePublicationTests.cs +++ b/tests/Ymir.Tests/YmirServicePublicationTests.cs @@ -17,7 +17,9 @@ public sealed class YmirServicePublicationTests Assert.Contains("Box3D", advertisement.Description, StringComparison.Ordinal); Assert.Contains("Box3D-only isolated snapshot stepping", advertisement.Owns); - Assert.Contains("public retained session lifecycle yet", advertisement.DoesNotOwn); + Assert.Contains("public in-process retained sessions with explicit mutation receipts", advertisement.Owns); + Assert.Contains("typed Begin, Hit, and End contact facts for retained steps", advertisement.Owns); + Assert.Contains("daemon-owned named session registry or CultMesh command lowering yet", advertisement.DoesNotOwn); Assert.Empty(advertisement.CommandLowerings); Assert.Contains("Box3D solver and collision semantics", advertisement.DoesNotOwn); Assert.Equal("Box3D v0.1.0 (C17)", diagnostics.NumericSubstrate); diff --git a/tests/Ymir.Tests/YmirSessionTests.cs b/tests/Ymir.Tests/YmirSessionTests.cs new file mode 100644 index 0000000..662a250 --- /dev/null +++ b/tests/Ymir.Tests/YmirSessionTests.cs @@ -0,0 +1,215 @@ +using Ymir.Core; + +namespace Ymir.Tests; + +public sealed class YmirSessionTests +{ + [Fact] + public void RetainedBodyAdvancesWithoutSnapshotResubmission() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "retained-motion", + [Body("ship", positionX: 0.0f, velocityX: 2.0f)])); + + var first = session.Step(Step("step-1", 0, 0.25f)); + var second = session.Step(Step("step-2", 1, 0.25f)); + + Assert.Equal(YmirCommandOutcome.Accepted, first.Receipt.Outcome); + Assert.Equal(1, first.Revision); + Assert.Equal(2, second.Revision); + Assert.Equal(2, second.StepIndex); + Assert.True(second.World.Bodies.Single().Position.X > first.World.Bodies.Single().Position.X); + Assert.Equal(2.0f, second.World.Bodies.Single().Velocity.X, 4); + } + + [Fact] + public void ForceReceiptIsIdempotentAndForceIsConsumedByOneStep() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest("force-once", [Body("ship")])); + var command = new YmirApplyForceCommand(Header("force", 0), "ship", new Vec2(10.0f, 0.0f)); + + var accepted = session.ApplyForce(command); + var replay = session.ApplyForce(command); + var conflict = session.ApplyForce(command with { Force = new Vec2(20.0f, 0.0f) }); + var revisionConflict = session.ApplyForce(command with { Header = Header("force", 1) }); + var forced = session.Step(Step("step-forced", 1, 0.1f)); + var unforced = session.Step(Step("step-unforced", 2, 0.1f)); + + Assert.Same(accepted, replay); + Assert.Equal(1, accepted.AfterRevision); + Assert.Equal(2, session.Info.StepIndex); + Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Error); + Assert.Equal(YmirCommandOutcome.Rejected, conflict.Outcome); + Assert.NotEqual(accepted.ReceiptId, conflict.ReceiptId); + Assert.Equal(YmirCommandError.CommandIdConflict, revisionConflict.Error); + Assert.Equal(forced.World.Bodies.Single().Velocity.X, unforced.World.Bodies.Single().Velocity.X, 4); + } + + [Fact] + public void OmissionCannotRemoveBodyAndRemoveIsExplicit() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "explicit-remove", + [Body("a"), Body("b", positionX: 10.0f)])); + + var velocity = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("set-a", 0), "a", new Vec2(1.0f, 0.0f), 0.0f)); + var stepped = session.Step(Step("step", 1, 0.1f)); + var removed = session.Remove(new YmirRemoveBodyCommand(Header("remove-b", 2), "b")); + + Assert.Equal(YmirCommandOutcome.Accepted, velocity.Outcome); + Assert.Equal(2, stepped.World.Bodies.Count); + Assert.Equal(YmirCommandOutcome.Accepted, removed.Outcome); + Assert.Equal(["a"], session.Snapshot().Bodies.Select(body => body.Id).ToArray()); + } + + [Fact] + public void ContactEpisodeEmitsBeginThenEndThenNewBegin() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "contact-lifecycle", + [ + Body("a", positionX: 0.0f, isStatic: true), + Body("b", positionX: 1.5f) + ])); + + var began = session.Step(Step("begin", 0, 0.01f)); + var persistent = session.Step(Step("persistent", 1, 0.01f)); + session.Teleport(new YmirTeleportBodyCommand( + Header("separate", 2), "b", new Vec2(10.0f, 0.0f), new Vec2(0.0f, 1.0f))); + var ended = session.Step(Step("end", 3, 0.01f)); + session.Teleport(new YmirTeleportBodyCommand( + Header("return", 4), "b", new Vec2(1.5f, 0.0f), new Vec2(0.0f, 1.0f))); + var beganAgain = session.Step(Step("begin-again", 5, 0.01f)); + + var firstBegin = Assert.Single(began.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + Assert.DoesNotContain(persistent.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + var end = Assert.Single(ended.ContactFacts, fact => fact.Kind == YmirContactFactKind.End); + var secondBegin = Assert.Single(beganAgain.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + Assert.Equal(firstBegin.ContactId, end.ContactId); + Assert.NotEqual(firstBegin.ContactId, secondBegin.ContactId); + Assert.Equal("a", firstBegin.BodyA); + Assert.Equal("b", firstBegin.BodyB); + } + + [Fact] + public void RemoveAndRecreateChangesBodyGeneration() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "body-generation", + [Body("wall", isStatic: true), Body("pickup", positionX: 1.5f)])); + var first = session.Step(Step("begin-1", 0, 0.01f)); + var firstFact = Assert.Single(first.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + session.Remove(new YmirRemoveBodyCommand(Header("remove", 1), "pickup")); + var removed = session.Step(Step("removed", 2, 0.01f)); + session.Spawn(new YmirSpawnBodyCommand(Header("spawn", 3), Body("pickup", positionX: 1.5f))); + var second = session.Step(Step("begin-2", 4, 0.01f)); + var secondFact = Assert.Single(second.ContactFacts, fact => + fact.Kind == YmirContactFactKind.Begin && + (fact.BodyA == "pickup" || fact.BodyB == "pickup")); + + var firstGeneration = BodyGeneration(firstFact, "pickup"); + Assert.Contains(removed.ContactFacts, fact => + fact.Kind == YmirContactFactKind.End && fact.ContactId == firstFact.ContactId); + Assert.True(BodyGeneration(secondFact, "pickup") > firstGeneration); + Assert.NotEqual(firstFact.ContactId, secondFact.ContactId); + } + + [Fact] + public void SnapshotImmediatelyReflectsCanonicalNativeMutationState() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "canonical-snapshot", + [Body("ship") with { Direction = new Vec2(0.0f, 2.0f) }])); + + Assert.Equal(new Vec2(0.0f, 1.0f), session.Snapshot().Bodies.Single().Direction); + session.Teleport(new YmirTeleportBodyCommand( + Header("teleport", 0), "ship", new Vec2(3.0f, 4.0f), new Vec2(2.0f, 0.0f))); + var teleported = session.Snapshot().Bodies.Single(); + Assert.Equal(1.0f, teleported.Direction!.Value.X, 5); + Assert.Equal(0.0f, teleported.Direction.Value.Y, 5); + Assert.Equal(new Vec2(3.0f, 4.0f), teleported.Position); + + session.Configure(new YmirConfigureBodyCommand( + Header("static", 1), "ship", 2.0f, 1.0f, true, 0.5f)); + var configured = session.Snapshot().Bodies.Single(); + Assert.True(configured.IsStatic); + Assert.Equal(2.0f, configured.Radius); + Assert.Equal(0.5f, configured.Restitution); + } + + [Fact] + public void StaleAndDisposedCommandsFailClosedWithoutMutation() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest("stale", [Body("ship")])); + var accepted = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("accepted", 0), "ship", new Vec2(1.0f, 0.0f), 0.0f)); + var stale = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("stale", 0), "ship", new Vec2(100.0f, 0.0f), 0.0f)); + var disposed = session.Dispose(new YmirDisposeSessionCommand(Header("dispose", 1))); + var afterDispose = session.Remove(new YmirRemoveBodyCommand(Header("late", 2), "ship")); + + Assert.Equal(YmirCommandOutcome.Accepted, accepted.Outcome); + Assert.Equal(YmirCommandError.StaleRevision, stale.Error); + Assert.Equal(YmirCommandOutcome.Accepted, disposed.Outcome); + Assert.Equal(YmirCommandError.SessionDisposed, afterDispose.Error); + Assert.Equal(2, afterDispose.BeforeRevision); + Assert.Equal(afterDispose.BeforeRevision, afterDispose.AfterRevision); + } + + [Fact] + public void TypedFingerprintRejectsDelimiterCollisionsAndNullPayloads() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest("fingerprints", [])); + var accepted = session.Spawn(new YmirSpawnBodyCommand( + Header("spawn", 0), Body("body|with|delimiters"))); + var conflict = session.Spawn(new YmirSpawnBodyCommand( + Header("spawn", 0), Body("body") with { Position = new Vec2(1.0f, 2.0f) })); + var nullBody = session.Spawn(new YmirSpawnBodyCommand(Header("null-body", 1), null!)); + var nullFields = session.Step(new YmirStepSessionCommand(Header("null-fields", 1), 0.1f, null!)); + + Assert.Equal(YmirCommandOutcome.Accepted, accepted.Outcome); + Assert.Equal(YmirCommandError.CommandIdConflict, conflict.Error); + Assert.Equal(YmirCommandError.InvalidCommand, nullBody.Error); + Assert.Equal(YmirCommandError.InvalidCommand, nullFields.Receipt.Error); + Assert.Equal(1, session.Info.Revision); + } + + [Fact] + public void StaticBodyVelocityCommandIsRejectedWithoutARevisionLie() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "static-velocity", [Body("wall", isStatic: true)])); + + var receipt = session.SetVelocity(new YmirSetBodyVelocityCommand( + Header("move-wall", 0), "wall", new Vec2(10.0f, 0.0f), 2.0f)); + + Assert.Equal(YmirCommandOutcome.Rejected, receipt.Outcome); + Assert.Equal(YmirCommandError.StaticBody, receipt.Error); + Assert.Equal(0, session.Info.Revision); + Assert.Equal(Vec2.Zero, session.Snapshot().Bodies.Single().Velocity); + } + + private static YmirCommandHeader Header(string id, long revision) => new(id, revision); + + private static long BodyGeneration(YmirContactFact fact, string bodyId) => + fact.BodyA == bodyId ? fact.BodyAGeneration : fact.BodyBGeneration; + + private static YmirStepSessionCommand Step(string id, long revision, float deltaTime) => + new(Header(id, revision), deltaTime, []); + + private static PhysicsBody Body( + string id, + float positionX = 0.0f, + float velocityX = 0.0f, + bool isStatic = false) => + new( + id, + new Vec2(positionX, 0.0f), + new Vec2(velocityX, 0.0f), + 1.0f, + 1.0f, + isStatic, + 0.0f, + new Vec2(0.0f, 1.0f)); +} From dedbc4e429c26a4847dcea5d2e6f566e796c9cb7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 21:18:15 +0100 Subject: [PATCH 4/7] Remember retained Box3D authority boundary --- .voidbot/state/ymir.cc | Bin 4274 -> 4011 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.voidbot/state/ymir.cc b/.voidbot/state/ymir.cc index 0f043dd540a0b1b72de7097fc21dadab9b8ad76f..5bfa22067d9838d16672c009ab476d11fc23e233 100644 GIT binary patch delta 1021 zcmYjQJ#Q015EUjuNW`Q-q(C4B2^!=};uuFxA_~HnXcHRJt@pkMDfFee|t1zq+!~>};&GmsUHS z;#ckc46xo}V6pgl^-}Tn;{I%*{ByCmF?XwWnNHT{Hs?mIZ481mrm$rWTTj5F_hhsO zZH8cm8WbHM*g@_|dKem~QvX>hLD`=R_g-b>fINf&!gG<~>K(Sgt@^kRta zY)Fy{%#4Pvi8>t#mv4fNT}2Yyl*$>2=n?SHa*+a;52)nET(cNNC}}pJ%teX2hkPg^))!b^rv`bMBWiAyi!HyQz z4@>|b&|1=c-kGs|-0Y1Kfk{Y{S)S1)MIi^HRlf8kpe~7@{(i|ukxr~Ll6~fXM>@EQ znXim)KsN@M7^K(x=xRc@Vwgb$@x>|iP4f{Lvk|Gpb?>+|1@4@S$DeElTQfuBPcNcPZis_~PSyaqavCt#x)k z1=08Kif8rvcaNqyoO*vORb(IB2A|%Aguk-F)*CYqYpqj!s4boYt(7Lfw424>`uAC| eJ$aXI7F@5u?S(fpU~{zs|1F%<&sesa?cM*O8fq#4 delta 1294 zcmY*ZyKWOf6cr&2!lXe$h=;he$gv3ti2|Y^M4$*EQP4m)p1tv2n4Q_o%;GEsE}>u1 zA|Zh&Xm|*Eet;etM9oidW^E^?v#(~)J+GM$7d~J7_;sPPvUzQF_1fx{-pbYW=KI3y z`N3xM=ES+?#nHXF;ra?roodc3o?kdte%V~SzBs;d-@B~RQJkfRg?O@VL>U_%s>p$S zWup{KWnKr-fuf^QtmTZh-2UqJJ8hH{zmEK9|B>K8&J>(s5*vBwRRZpkcE(6(e-6A; zS(&TAUD~V0?Ca$ryMm*yyQFM}voD*tEMn{ag_JKY%706Q(#J!QJN zwbP|Ls^D9di6j|A!>+IoT_}s}3$YTSXrPYWV{XNF=_w9?A*2PX%8M57S7gn7djG(>RKG;WPs9w_|; zN40nj8G99b;c%TiM>1;peam*)#VsljqI|n)8bu73qXTAz4wuA+WGTOlIl!G_)raTKDl~N#XRK<(L~M;TU{V>#kD~<6dY>R1)OL#GV~hCf z$my+0pgIY#ybr(%_}*1$#DU+q9{p$N49&Emk*HBFWtU=I!mKumq&hVz1u`Rsat(Mm z7Taf=^>c(baepLm7KXBvserQzERUQAn`t#B#Y}3!7;dKzP><-RH(BSbpOg-Fut(dj zRqQ!L=lLMT$&FqMSZhq`AF}h*-e+h|U76-|kOnGAth}k4>UeYV@a Date: Tue, 14 Jul 2026 22:01:19 +0100 Subject: [PATCH 5/7] Expose Box3D collision profiles through Ymir --- README.md | 7 ++ docs/architecture.md | 11 +-- docs/box3d-parity.md | 10 ++- docs/retained-session-contract.md | 8 +- native/Ymir.Box3D/ymir_box3d.c | 88 +++++++++++++++--- src/Ymir.Box3D/Box3DNative.cs | 11 ++- src/Ymir.Box3D/Box3DSession.cs | 31 +++++-- src/Ymir.Box3D/Ymir.Box3D.csproj | 2 +- src/Ymir.Core/PhysicsModel.cs | 8 +- src/Ymir.Core/RetainedSessionModel.cs | 3 +- .../YmirServicePublicationDocument.cs | 6 +- src/Ymir.Core/YmirSession.cs | 31 ++++++- src/Ymir.Core/YmirSoAWorld.cs | 58 +++++++++++- src/Ymir.Core/YmirWorldSession.cs | 8 +- src/Ymir.Core/YmirWorldStateDocument.cs | 77 +++++++++++++++- src/ymir-daemon/Program.cs | 2 +- tests/Ymir.Box3D.Parity/Box3DOracle.cs | 31 ++++++- tests/Ymir.Box3D.Parity/Box3DParityTests.cs | 89 +++++++++++++++++-- .../Ymir.Tests/YmirServicePublicationTests.cs | 2 +- tests/Ymir.Tests/YmirSessionTests.cs | 68 ++++++++++++++ tests/Ymir.Tests/YmirSimulatorTests.cs | 40 +++++++++ 21 files changed, 540 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 138a991..7452b06 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ parity suite already witness released Box3D behavior for: - contact-begin facts - restitution mixing - transient torque lifetime +- category/mask/group collision filtering +- bullet CCD against kinematic bodies, including Box3D's next-step contact-event timing The production `Ymir.Box3D` boundary owns the native session ABI. The legacy snapshot `YmirSimulator.Step` contract now creates an isolated Box3D session, @@ -93,6 +95,11 @@ smoke is still required before that is a repeatable packaging guarantee. Linux and macOS packages must be produced and smoked on their own release workers before those RIDs are advertised. +The current package version is `0.3.0`. ABI v4 exposes Box3D body type, +bullet, field-participation, and collision-filter configuration without +exposing Box3D handles. These are Ymir contract fields, but their behavior is +Box3D behavior. + ## Cutover Rule A Ymir cutover is complete only when all runtime stepping, collision queries, diff --git a/docs/architecture.md b/docs/architecture.md index 4f8a989..c377e64 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -145,10 +145,11 @@ The native facade must remain boring: ## Persistence -`gamecult.ymir.world_state.v1` appends planar direction and angular velocity to -the v0 layout. The v0 reader is an explicit migration path; keys are not -reassigned. Torque is transient command state and is intentionally absent. -Version 1 is a compatibility world snapshot, not a complete retained-session +`gamecult.ymir.world_state.v2` appends Box3D body type, bullet, +field-participation, and collision filter arrays to the v1 layout. The v1 and +v0 readers are explicit migration paths; keys are not reassigned. Torque is +transient command state and is intentionally absent. Version 2 is a +compatibility world snapshot, not a complete retained-session checkpoint: it does not preserve full shape, material, filter, session tuning, provenance, or warm contact state. @@ -172,7 +173,7 @@ Box3D-backed sessions prove: 1. fixed-step body state projection; 2. begin/end/hit contact lifecycle; 3. overlap and shape-cast lowering; -4. continuous collision and projectile witnesses; +4. continuous collision event timing and same-step Box3D cast witnesses; 5. transient force and torque application; 6. checkpoint reconstruction and replay; 7. Aetheria gravity, tractor, pickup, and payload smokes. diff --git a/docs/box3d-parity.md b/docs/box3d-parity.md index 1cb7f92..cae67ca 100644 --- a/docs/box3d-parity.md +++ b/docs/box3d-parity.md @@ -21,7 +21,7 @@ the overlap, cast, pair-step, torque-lifetime, version, and ABI-layout operations used by the harness. This keeps Box3D's alpha C ABI out of Ymir's public managed contracts. -Production ABI version 3 uses caller-owned blittable buffers, explicit cdecl, +Production ABI version 4 uses caller-owned blittable buffers, explicit cdecl, fixed-width status/count values, compile-time C layout assertions, and a managed/native layout sentinel before opening a session. It adds explicit retained body mutations, one-shot force and torque operations, and a @@ -30,6 +30,8 @@ stored contact key only long enough to correlate its separate event arrays; public Ymir facts never expose native contact identity. Planar direction maps to Box3D rotation about Y; angular velocity and transient torque remain Box3D state and commands rather than managed integration. +ABI v4 additionally carries Box3D static/kinematic/dynamic selection, bullet +CCD, category/mask/group filtering, and per-body radial-field participation. `tests/Ymir.Box3D.Parity` builds that facade through CMake and invokes it with source-generated .NET interop. Run it with: @@ -58,6 +60,12 @@ is retained in the pinned submodule. - Restitution uses the maximum of the two shape materials. - Applied torque is transient and cleared by each world step; a continuous torque must be submitted again for the next step. +- A negative Box3D group index suppresses collision within that group before + category/mask evaluation. Category and mask bits then decide eligible pairs. +- Bullet CCD against a kinematic target prevents traversal during the fast + step, but Box3D v0.1.0 emits the typed contact event on the following step. + Same-step gameplay triggering therefore requires an explicit Box3D shape + cast; Ymir must not invent an earlier Begin event. ## Cut Line diff --git a/docs/retained-session-contract.md b/docs/retained-session-contract.md index a5920dd..cc770bb 100644 --- a/docs/retained-session-contract.md +++ b/docs/retained-session-contract.md @@ -38,7 +38,7 @@ The retained port accepts narrow operations with explicit meaning: - remove a body, rejecting an unknown id; - teleport a body; - set linear and angular velocity; -- configure body shape, mass, type, and restitution; +- configure body shape, mass, static/kinematic/dynamic type, and restitution; - apply one-shot force or torque; - step with a fixed delta, substep count, and typed fields; - dispose the session. @@ -46,6 +46,10 @@ The retained port accepts narrow operations with explicit meaning: The current public slice implements those mutation and step operations. Retained-world overlap and cast queries at a named revision are the next library cut; the static compatibility queries do not satisfy that contract. +Bullet, collision-filter, and field-participation profiles are currently +spawn/restore definitions. Retained `Configure` changes radius, mass, +static/kinematic/dynamic type, and restitution only. Changing the profile +requires explicit remove-and-spawn until a typed profile command exists. Restore/import is the only path allowed to accept a complete world snapshot. There is no `Upsert`, generic patch bag, or omission-based removal. @@ -73,7 +77,7 @@ chronology. - Box3D handles are process-local and never cross the contract. - DTO and SoA body arrays are projections. -- `gamecult.ymir.world_state.v1` is an inspection/migration snapshot, not a +- `gamecult.ymir.world_state.v2` is an inspection/migration snapshot, not a retained-session checkpoint. - Receipt and contact-episode ledgers are session metadata, not physics law. - Aetheria cargo, damage, loot, feedback, and scoring remain gameplay state diff --git a/native/Ymir.Box3D/ymir_box3d.c b/native/Ymir.Box3D/ymir_box3d.c index 9120c2c..6d3d0f8 100644 --- a/native/Ymir.Box3D/ymir_box3d.c +++ b/native/Ymir.Box3D/ymir_box3d.c @@ -85,6 +85,8 @@ typedef enum ymir_box3d_status typedef struct ymir_box3d_session_body_input { uint64_t stable_id; + uint64_t collision_category_bits; + uint64_t collision_mask_bits; float position_x; float position_y; float velocity_x; @@ -97,6 +99,10 @@ typedef struct ymir_box3d_session_body_input float mass; float restitution; uint32_t is_static; + uint32_t is_kinematic; + uint32_t is_bullet; + uint32_t participates_in_fields; + int32_t collision_group_index; } ymir_box3d_session_body_input; typedef struct ymir_box3d_radial_field_input @@ -182,6 +188,12 @@ typedef struct ymir_box3d_session_body float mass; float restitution; uint32_t is_static; + uint32_t is_kinematic; + uint32_t is_bullet; + uint32_t participates_in_fields; + uint64_t collision_category_bits; + uint64_t collision_mask_bits; + int32_t collision_group_index; int seen; } ymir_box3d_session_body; @@ -206,7 +218,7 @@ typedef struct ymir_box3d_session } ymir_box3d_session; _Static_assert(sizeof(ymir_box3d_status) == sizeof(int32_t), "Ymir Box3D status ABI must be 32-bit"); -_Static_assert(sizeof(ymir_box3d_session_body_input) == 56, "Unexpected Ymir Box3D body input layout"); +_Static_assert(sizeof(ymir_box3d_session_body_input) == 88, "Unexpected Ymir Box3D body input layout"); _Static_assert(sizeof(ymir_box3d_radial_field_input) == 16, "Unexpected Ymir Box3D field layout"); _Static_assert(sizeof(ymir_box3d_session_body_output) == 40, "Unexpected Ymir Box3D body output layout"); _Static_assert(sizeof(ymir_box3d_session_contact_output) == 40, "Unexpected Ymir Box3D contact layout"); @@ -235,7 +247,17 @@ static int ymir_session_body_input_is_valid(const ymir_box3d_session_body_input* ymir_is_finite(input->torque) && ymir_is_finite(input->radius) && input->radius > 0.0f && ymir_is_finite(input->mass) && (input->is_static != 0 || input->mass > 0.0f) && ymir_is_finite(input->restitution) && - input->restitution >= 0.0f; + input->restitution >= 0.0f && !(input->is_static != 0 && input->is_kinematic != 0) && + input->collision_category_bits != 0; +} + +static b3BodyType ymir_session_body_type(const ymir_box3d_session_body_input* input) +{ + if (input->is_static != 0) + { + return b3_staticBody; + } + return input->is_kinematic != 0 ? b3_kinematicBody : b3_dynamicBody; } static b3Quat ymir_session_rotation(float direction_x, float direction_y) @@ -374,7 +396,7 @@ static ymir_box3d_status ymir_session_create_body( ymir_box3d_session_body* output) { b3BodyDef body_def = b3DefaultBodyDef(); - body_def.type = input->is_static != 0 ? b3_staticBody : b3_dynamicBody; + body_def.type = ymir_session_body_type(input); body_def.position = ymir_vec(input->position_x, input->position_y); body_def.rotation = ymir_session_rotation(input->direction_x, input->direction_y); body_def.linearVelocity = ymir_vec(input->velocity_x, input->velocity_y); @@ -383,6 +405,7 @@ static ymir_box3d_status ymir_session_create_body( body_def.motionLocks.angularX = true; body_def.motionLocks.angularZ = true; body_def.enableSleep = false; + body_def.isBullet = input->is_bullet != 0; b3BodyId body_id = b3CreateBody(session->world_id, &body_def); if (B3_IS_NULL(body_id)) { @@ -394,6 +417,9 @@ static ymir_box3d_status ymir_session_create_body( shape_def.density = input->is_static != 0 ? 0.0f : ymir_session_density(input->mass, input->radius); shape_def.baseMaterial.friction = 0.0f; shape_def.baseMaterial.restitution = input->restitution; + shape_def.filter.categoryBits = input->collision_category_bits; + shape_def.filter.maskBits = input->collision_mask_bits; + shape_def.filter.groupIndex = input->collision_group_index; shape_def.enableContactEvents = true; shape_def.enableHitEvents = true; b3Sphere sphere = {{0.0f, 0.0f, 0.0f}, input->radius}; @@ -420,6 +446,12 @@ static ymir_box3d_status ymir_session_create_body( .mass = input->mass, .restitution = input->restitution, .is_static = input->is_static != 0, + .is_kinematic = input->is_kinematic != 0, + .is_bullet = input->is_bullet != 0, + .participates_in_fields = input->participates_in_fields != 0, + .collision_category_bits = input->collision_category_bits, + .collision_mask_bits = input->collision_mask_bits, + .collision_group_index = input->collision_group_index, .seen = 1, }; return YMIR_BOX3D_OK; @@ -429,13 +461,31 @@ static void ymir_session_update_body( ymir_box3d_session_body* body, const ymir_box3d_session_body_input* input) { - int type_changed = body->is_static != (input->is_static != 0); + int type_changed = body->is_static != (input->is_static != 0) || + body->is_kinematic != (input->is_kinematic != 0); int radius_changed = body->radius != input->radius; int mass_changed = body->mass != input->mass; if (type_changed) { - b3Body_SetType(body->body_id, input->is_static != 0 ? b3_staticBody : b3_dynamicBody); + b3Body_SetType(body->body_id, ymir_session_body_type(input)); + } + + if (body->is_bullet != (input->is_bullet != 0)) + { + b3Body_SetBullet(body->body_id, input->is_bullet != 0); + } + + if (body->collision_category_bits != input->collision_category_bits || + body->collision_mask_bits != input->collision_mask_bits || + body->collision_group_index != input->collision_group_index) + { + b3Filter filter = { + .categoryBits = input->collision_category_bits, + .maskBits = input->collision_mask_bits, + .groupIndex = input->collision_group_index, + }; + b3Shape_SetFilter(body->shape_id, filter, true); } if (radius_changed) @@ -487,6 +537,12 @@ static void ymir_session_update_body( body->mass = input->mass; body->restitution = input->restitution; body->is_static = input->is_static != 0; + body->is_kinematic = input->is_kinematic != 0; + body->is_bullet = input->is_bullet != 0; + body->participates_in_fields = input->participates_in_fields != 0; + body->collision_category_bits = input->collision_category_bits; + body->collision_mask_bits = input->collision_mask_bits; + body->collision_group_index = input->collision_group_index; body->seen = 1; } @@ -1150,7 +1206,7 @@ YMIR_EXPORT ymir_box3d_torque_result YMIR_CALL ymir_box3d_torque_lifetime(float YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_get_abi_version(void) { - return 3; + return 4; } YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_get_abi_layout( @@ -1403,10 +1459,12 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_configure( float radius, float mass, float restitution, - uint32_t is_static) + uint32_t is_static, + uint32_t is_kinematic) { if (session == NULL || !ymir_is_finite(radius) || radius <= 0.0f || !ymir_is_finite(mass) || - (is_static == 0 && mass <= 0.0f) || !ymir_is_finite(restitution) || restitution < 0.0f) + (is_static == 0 && mass <= 0.0f) || (is_static != 0 && is_kinematic != 0) || + !ymir_is_finite(restitution) || restitution < 0.0f) { return YMIR_BOX3D_INVALID_ARGUMENT; } @@ -1416,12 +1474,14 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_configure( return YMIR_BOX3D_INVALID_ARGUMENT; } ymir_box3d_session_body* body = session->bodies + index; - int type_changed = body->is_static != (is_static != 0); + int type_changed = body->is_static != (is_static != 0) || body->is_kinematic != (is_kinematic != 0); int radius_changed = body->radius != radius; int mass_changed = body->mass != mass; if (type_changed) { - b3Body_SetType(body->body_id, is_static != 0 ? b3_staticBody : b3_dynamicBody); + b3Body_SetType( + body->body_id, + is_static != 0 ? b3_staticBody : (is_kinematic != 0 ? b3_kinematicBody : b3_dynamicBody)); } if (radius_changed) { @@ -1442,6 +1502,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_configure( body->mass = mass; body->restitution = restitution; body->is_static = is_static != 0; + body->is_kinematic = is_kinematic != 0; ymir_box3d_status status = ymir_session_drain_contact_events(session, YMIR_DRAIN_END, 1); return status; } @@ -1526,7 +1587,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( for (int body_index = 0; body_index < session->body_count; ++body_index) { ymir_box3d_session_body* body = session->bodies + body_index; - if (body->is_static) + if (body->is_static || body->is_kinematic) { body->pending_torque = 0.0f; continue; @@ -1538,6 +1599,11 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_session_step( } body->pending_torque = 0.0f; + if (!body->participates_in_fields) + { + continue; + } + b3Pos position = b3Body_GetPosition(body->body_id); float acceleration_x = 0.0f; float acceleration_y = 0.0f; diff --git a/src/Ymir.Box3D/Box3DNative.cs b/src/Ymir.Box3D/Box3DNative.cs index f250b7b..fb7ff83 100644 --- a/src/Ymir.Box3D/Box3DNative.cs +++ b/src/Ymir.Box3D/Box3DNative.cs @@ -110,7 +110,8 @@ internal static partial class Box3DNative float radius, float mass, float restitution, - uint isStatic); + uint isStatic, + uint isKinematic); [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] @@ -191,6 +192,8 @@ internal sealed class Box3DSessionHandle : SafeHandleZeroOrMinusOneIsInvalid [StructLayout(LayoutKind.Sequential)] internal readonly record struct Box3DBodyInput( ulong StableId, + ulong CollisionCategoryBits, + ulong CollisionMaskBits, float PositionX, float PositionZ, float VelocityX, @@ -202,7 +205,11 @@ internal readonly record struct Box3DBodyInput( float Radius, float Mass, float Restitution, - uint IsStatic); + uint IsStatic, + uint IsKinematic, + uint IsBullet, + uint ParticipatesInFields, + int CollisionGroupIndex); [StructLayout(LayoutKind.Sequential)] internal readonly record struct Box3DRadialField( diff --git a/src/Ymir.Box3D/Box3DSession.cs b/src/Ymir.Box3D/Box3DSession.cs index b6a9035..a395470 100644 --- a/src/Ymir.Box3D/Box3DSession.cs +++ b/src/Ymir.Box3D/Box3DSession.cs @@ -4,6 +4,8 @@ namespace Ymir.Box3D; internal readonly record struct Box3DBody( ulong StableId, + ulong CollisionCategoryBits, + ulong CollisionMaskBits, float PositionX, float PositionZ, float VelocityX, @@ -15,7 +17,11 @@ internal readonly record struct Box3DBody( float Radius, float Mass, float Restitution, - bool IsStatic); + bool IsStatic, + bool IsKinematic, + bool IsBullet, + bool ParticipatesInFields, + int CollisionGroupIndex); internal readonly record struct Box3DField(float PositionX, float PositionZ, float Strength, float Radius); @@ -63,7 +69,7 @@ internal readonly record struct Box3DContactFact( internal sealed class Box3DSession : IDisposable { - internal const uint AbiVersion = 3; + internal const uint AbiVersion = 4; internal const int DefaultSubstepCount = 4; private readonly Box3DSessionHandle _handle; @@ -90,6 +96,8 @@ internal sealed class Box3DSession : IDisposable var body = bodies[i]; native[i] = new Box3DBodyInput( body.StableId, + body.CollisionCategoryBits, + body.CollisionMaskBits, body.PositionX, body.PositionZ, body.VelocityX, @@ -101,7 +109,11 @@ internal sealed class Box3DSession : IDisposable body.Radius, body.Mass, body.Restitution, - body.IsStatic ? 1u : 0u); + body.IsStatic ? 1u : 0u, + body.IsKinematic ? 1u : 0u, + body.IsBullet ? 1u : 0u, + body.ParticipatesInFields ? 1u : 0u, + body.CollisionGroupIndex); } fixed (Box3DBodyInput* pointer = native) @@ -155,12 +167,13 @@ internal sealed class Box3DSession : IDisposable float radius, float mass, float restitution, - bool isStatic) + bool isStatic, + bool isKinematic) { ThrowIfDisposed(); ThrowIfMutationFailed( Box3DNative.ymir_box3d_session_configure( - _handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u), + _handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u, isKinematic ? 1u : 0u), "configure body"); } @@ -368,6 +381,8 @@ internal sealed class Box3DSession : IDisposable private static Box3DBodyInput ToNative(Box3DBody body) => new( body.StableId, + body.CollisionCategoryBits, + body.CollisionMaskBits, body.PositionX, body.PositionZ, body.VelocityX, @@ -379,7 +394,11 @@ internal sealed class Box3DSession : IDisposable body.Radius, body.Mass, body.Restitution, - body.IsStatic ? 1u : 0u); + body.IsStatic ? 1u : 0u, + body.IsKinematic ? 1u : 0u, + body.IsBullet ? 1u : 0u, + body.ParticipatesInFields ? 1u : 0u, + body.CollisionGroupIndex); private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); } diff --git a/src/Ymir.Box3D/Ymir.Box3D.csproj b/src/Ymir.Box3D/Ymir.Box3D.csproj index 8d5c0f2..58b2df9 100644 --- a/src/Ymir.Box3D/Ymir.Box3D.csproj +++ b/src/Ymir.Box3D/Ymir.Box3D.csproj @@ -9,7 +9,7 @@ Ymir.Box3D Native ABI boundary between Ymir sessions and pinned Box3D. GameCult.Ymir.Box3D - 0.2.0 + 0.3.0 GameCult true README.md diff --git a/src/Ymir.Core/PhysicsModel.cs b/src/Ymir.Core/PhysicsModel.cs index 188215c..9ed51cc 100644 --- a/src/Ymir.Core/PhysicsModel.cs +++ b/src/Ymir.Core/PhysicsModel.cs @@ -21,7 +21,13 @@ public sealed record PhysicsBody( float Restitution = 0.2f, Vec2? Direction = null, float AngularVelocity = 0.0f, - float Torque = 0.0f); + float Torque = 0.0f, + bool IsKinematic = false, + bool IsBullet = false, + bool ParticipatesInFields = true, + ulong CollisionCategoryBits = 1UL, + ulong CollisionMaskBits = ulong.MaxValue, + int CollisionGroupIndex = 0); public sealed record RadialField( string Id, diff --git a/src/Ymir.Core/RetainedSessionModel.cs b/src/Ymir.Core/RetainedSessionModel.cs index a30ea72..7f51f20 100644 --- a/src/Ymir.Core/RetainedSessionModel.cs +++ b/src/Ymir.Core/RetainedSessionModel.cs @@ -29,7 +29,8 @@ public sealed record YmirConfigureBodyCommand( float Radius, float Mass, bool IsStatic, - float Restitution); + float Restitution, + bool IsKinematic = false); public sealed record YmirApplyForceCommand( YmirCommandHeader Header, diff --git a/src/Ymir.Core/YmirServicePublicationDocument.cs b/src/Ymir.Core/YmirServicePublicationDocument.cs index 615692b..4770757 100644 --- a/src/Ymir.Core/YmirServicePublicationDocument.cs +++ b/src/Ymir.Core/YmirServicePublicationDocument.cs @@ -53,7 +53,7 @@ public sealed class YmirOperatorStateDocument public string BatchKernel { get; set; } = ""; [Key(5)] - public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration"; + public string Persistence { get; set; } = "CultCache gamecult.ymir.world_state.v2; explicit v1/v0 read migration"; [Key(6)] public string UpdatedAtUtc { get; set; } = ""; @@ -90,7 +90,7 @@ public static class YmirServicePublication "stable GameCult id to transient Box3D handle projection", "Box3D-backed circle overlap and cast queries over submitted bodies", "deterministic result ordering", - "CultCache world snapshot v1 with explicit v0 read migration", + "CultCache world snapshot v2 with explicit v1/v0 read migration", "diagnostic Eve publication" ], DoesNotOwn = @@ -115,7 +115,7 @@ public static class YmirServicePublication StateOwner = "In-process retained Box3D sessions, isolated snapshot steps, and diagnostic projections", NumericSubstrate = "Box3D v0.1.0 (C17)", BatchKernel = "Box3D native solver; Ymir does not own physics algorithms", - Persistence = "CultCache gamecult.ymir.world_state.v1; explicit v0 read migration", + Persistence = "CultCache gamecult.ymir.world_state.v2; explicit v1/v0 read migration", UpdatedAtUtc = FormatUtc(now) }; diff --git a/src/Ymir.Core/YmirSession.cs b/src/Ymir.Core/YmirSession.cs index e963e6c..71f5dd3 100644 --- a/src/Ymir.Core/YmirSession.cs +++ b/src/Ymir.Core/YmirSession.cs @@ -217,6 +217,7 @@ public sealed class YmirSession : IDisposable writer.Write(command.Mass); writer.Write(command.IsStatic); writer.Write(command.Restitution); + writer.Write(command.IsKinematic); }); if (Preflight(command.Header, fingerprint, "body.configure") is { } previous) { @@ -228,6 +229,7 @@ public sealed class YmirSession : IDisposable } if (!float.IsFinite(command.Radius) || command.Radius <= 0.0f || !float.IsFinite(command.Mass) || (!command.IsStatic && command.Mass <= 0.0f) || + (command.IsStatic && command.IsKinematic) || !float.IsFinite(command.Restitution) || command.Restitution < 0.0f) { return RejectAndStore(command.Header, fingerprint, "body.configure", YmirCommandError.InvalidCommand); @@ -235,12 +237,19 @@ public sealed class YmirSession : IDisposable RunNative(() => { - _native.Configure(key, command.Radius, command.Mass, command.Restitution, command.IsStatic); + _native.Configure( + key, + command.Radius, + command.Mass, + command.Restitution, + command.IsStatic, + command.IsKinematic); _bodies[command.BodyId] = body with { Radius = command.Radius, Mass = command.Mass, IsStatic = command.IsStatic, + IsKinematic = command.IsKinematic, Restitution = command.Restitution }; UpdateBodyProjection(_native.CopyBodies()); @@ -267,7 +276,7 @@ public sealed class YmirSession : IDisposable { return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.UnknownBody); } - if (body.IsStatic) + if (body.IsStatic || body.IsKinematic) { return RejectAndStore(command.Header, fingerprint, "body.apply_force", YmirCommandError.StaticBody); } @@ -299,7 +308,7 @@ public sealed class YmirSession : IDisposable { return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.UnknownBody); } - if (body.IsStatic) + if (body.IsStatic || body.IsKinematic) { return RejectAndStore(command.Header, fingerprint, "body.apply_torque", YmirCommandError.StaticBody); } @@ -791,6 +800,8 @@ public sealed class YmirSession : IDisposable var direction = DirectionOrDefault(body.Direction); return new Box3DBody( key, + body.CollisionCategoryBits, + body.CollisionMaskBits, body.Position.X, body.Position.Y, body.Velocity.X, @@ -802,7 +813,11 @@ public sealed class YmirSession : IDisposable body.Radius, body.Mass, body.Restitution, - body.IsStatic); + body.IsStatic, + body.IsKinematic, + body.IsBullet, + body.ParticipatesInFields, + body.CollisionGroupIndex); } private static Vec2 DirectionOrDefault(Vec2? direction) => @@ -858,7 +873,9 @@ public sealed class YmirSession : IDisposable if (string.IsNullOrWhiteSpace(body.Id) || !Finite(body.Position) || !Finite(body.Velocity) || !float.IsFinite(body.Radius) || body.Radius <= 0.0f || !float.IsFinite(body.Mass) || (!body.IsStatic && body.Mass <= 0.0f) || + (body.IsStatic && body.IsKinematic) || !float.IsFinite(body.Restitution) || body.Restitution < 0.0f || + body.CollisionCategoryBits == 0 || (body.Direction is { } direction && !ValidDirection(direction)) || !float.IsFinite(body.AngularVelocity) || !float.IsFinite(body.Torque) || (!allowTorque && body.Torque != 0.0f)) @@ -918,6 +935,12 @@ public sealed class YmirSession : IDisposable } writer.Write(body.AngularVelocity); writer.Write(body.Torque); + writer.Write(body.IsKinematic); + writer.Write(body.IsBullet); + writer.Write(body.ParticipatesInFields); + writer.Write(body.CollisionCategoryBits); + writer.Write(body.CollisionMaskBits); + writer.Write(body.CollisionGroupIndex); } private static void WriteField(BinaryWriter writer, RadialField? field) diff --git a/src/Ymir.Core/YmirSoAWorld.cs b/src/Ymir.Core/YmirSoAWorld.cs index 4117af7..3985ca1 100644 --- a/src/Ymir.Core/YmirSoAWorld.cs +++ b/src/Ymir.Core/YmirSoAWorld.cs @@ -18,6 +18,12 @@ public sealed class YmirSoAWorld public float[] Mass { get; set; } = []; public float[] DynamicMask { get; set; } = []; public float[] Restitution { get; set; } = []; + public float[] KinematicMask { get; set; } = []; + public float[] BulletMask { get; set; } = []; + public float[] FieldParticipationMask { get; set; } = []; + public ulong[] CollisionCategoryBits { get; set; } = []; + public ulong[] CollisionMaskBits { get; set; } = []; + public int[] CollisionGroupIndex { get; set; } = []; public string[] FieldIds { get; set; } = []; public float[] FieldPositionX { get; set; } = []; public float[] FieldPositionY { get; set; } = []; @@ -49,6 +55,12 @@ public sealed class YmirSoAWorld Mass = bodies.Select(body => body.Mass).ToArray(), DynamicMask = bodies.Select(body => body.IsStatic ? 0.0f : 1.0f).ToArray(), Restitution = bodies.Select(body => body.Restitution).ToArray(), + KinematicMask = bodies.Select(body => body.IsKinematic ? 1.0f : 0.0f).ToArray(), + BulletMask = bodies.Select(body => body.IsBullet ? 1.0f : 0.0f).ToArray(), + FieldParticipationMask = bodies.Select(body => body.ParticipatesInFields ? 1.0f : 0.0f).ToArray(), + CollisionCategoryBits = bodies.Select(body => body.CollisionCategoryBits).ToArray(), + CollisionMaskBits = bodies.Select(body => body.CollisionMaskBits).ToArray(), + CollisionGroupIndex = bodies.Select(body => body.CollisionGroupIndex).ToArray(), FieldIds = fields.Select(field => field.Id).ToArray(), FieldPositionX = fields.Select(field => field.Position.X).ToArray(), FieldPositionY = fields.Select(field => field.Position.Y).ToArray(), @@ -70,7 +82,13 @@ public sealed class YmirSoAWorld Restitution[i], new Vec2(DirectionX[i], DirectionY[i]), AngularVelocity[i], - Torque[i])) + Torque[i], + KinematicMask[i] > 0.0f, + BulletMask[i] > 0.0f, + FieldParticipationMask[i] > 0.0f, + CollisionCategoryBits[i], + CollisionMaskBits[i], + CollisionGroupIndex[i])) .ToArray(), Enumerable.Range(0, FieldCount) .Select(i => new RadialField( @@ -96,6 +114,12 @@ public sealed class YmirSoAWorld Mass = (float[])Mass.Clone(), DynamicMask = (float[])DynamicMask.Clone(), Restitution = (float[])Restitution.Clone(), + KinematicMask = (float[])KinematicMask.Clone(), + BulletMask = (float[])BulletMask.Clone(), + FieldParticipationMask = (float[])FieldParticipationMask.Clone(), + CollisionCategoryBits = (ulong[])CollisionCategoryBits.Clone(), + CollisionMaskBits = (ulong[])CollisionMaskBits.Clone(), + CollisionGroupIndex = (int[])CollisionGroupIndex.Clone(), FieldIds = (string[])FieldIds.Clone(), FieldPositionX = (float[])FieldPositionX.Clone(), FieldPositionY = (float[])FieldPositionY.Clone(), @@ -125,6 +149,16 @@ public sealed class YmirSoAWorld throw new ArgumentOutOfRangeException(nameof(Mass), "Dynamic body mass must be positive."); } + if (DynamicMask[i] <= 0.0f && KinematicMask[i] > 0.0f) + { + throw new ArgumentException("A body cannot be both static and kinematic."); + } + + if (CollisionCategoryBits[i] == 0) + { + throw new ArgumentOutOfRangeException(nameof(CollisionCategoryBits), "Collision category bits must be non-zero."); + } + var directionLengthSquared = DirectionX[i] * DirectionX[i] + DirectionY[i] * DirectionY[i]; if (!float.IsFinite(directionLengthSquared) || directionLengthSquared <= 1.0e-8f) { @@ -158,6 +192,7 @@ public sealed class YmirSoAWorld { var expected = BodyIds.Length; FillMissingAngularState(expected); + FillMissingCollisionState(expected); foreach (var length in new[] { PositionX.Length, @@ -171,7 +206,13 @@ public sealed class YmirSoAWorld Radius.Length, Mass.Length, DynamicMask.Length, - Restitution.Length + Restitution.Length, + KinematicMask.Length, + BulletMask.Length, + FieldParticipationMask.Length, + CollisionCategoryBits.Length, + CollisionMaskBits.Length, + CollisionGroupIndex.Length }) { if (length != expected) @@ -181,6 +222,19 @@ public sealed class YmirSoAWorld } } + private void FillMissingCollisionState(int expected) + { + if (KinematicMask.Length == 0 && expected > 0) KinematicMask = new float[expected]; + if (BulletMask.Length == 0 && expected > 0) BulletMask = new float[expected]; + if (FieldParticipationMask.Length == 0 && expected > 0) + FieldParticipationMask = Enumerable.Repeat(1.0f, expected).ToArray(); + if (CollisionCategoryBits.Length == 0 && expected > 0) + CollisionCategoryBits = Enumerable.Repeat(1UL, expected).ToArray(); + if (CollisionMaskBits.Length == 0 && expected > 0) + CollisionMaskBits = Enumerable.Repeat(ulong.MaxValue, expected).ToArray(); + if (CollisionGroupIndex.Length == 0 && expected > 0) CollisionGroupIndex = new int[expected]; + } + private void FillMissingAngularState(int expected) { if (DirectionX.Length == 0 && expected > 0) diff --git a/src/Ymir.Core/YmirWorldSession.cs b/src/Ymir.Core/YmirWorldSession.cs index fa033ac..ad8f01f 100644 --- a/src/Ymir.Core/YmirWorldSession.cs +++ b/src/Ymir.Core/YmirWorldSession.cs @@ -53,6 +53,8 @@ internal sealed class YmirWorldSession : IDisposable indicesByKey.Add(key, i); bodies[i] = new Box3DBody( key, + world.CollisionCategoryBits[i], + world.CollisionMaskBits[i], world.PositionX[i], world.PositionY[i], world.VelocityX[i], @@ -64,7 +66,11 @@ internal sealed class YmirWorldSession : IDisposable world.Radius[i], world.Mass[i], world.Restitution[i], - world.DynamicMask[i] <= 0.0f); + world.DynamicMask[i] <= 0.0f, + world.KinematicMask[i] > 0.0f, + world.BulletMask[i] > 0.0f, + world.FieldParticipationMask[i] > 0.0f, + world.CollisionGroupIndex[i]); } Array.Sort(bodies, static (left, right) => left.StableId.CompareTo(right.StableId)); diff --git a/src/Ymir.Core/YmirWorldStateDocument.cs b/src/Ymir.Core/YmirWorldStateDocument.cs index 3b9b2cf..8878029 100644 --- a/src/Ymir.Core/YmirWorldStateDocument.cs +++ b/src/Ymir.Core/YmirWorldStateDocument.cs @@ -167,6 +167,76 @@ public sealed class YmirWorldStateDocumentV1 }; } +[CultDocument("gamecult.ymir.world_state", "gamecult.ymir.world_state.v2")] +[MessagePackObject] +public sealed class YmirWorldStateDocumentV2 +{ + [Key(0), CultName] public string WorldId { get; set; } = "default"; + [Key(1)] public float Time { get; set; } + [Key(2)] public string[] BodyIds { get; set; } = []; + [Key(3)] public float[] PositionX { get; set; } = []; + [Key(4)] public float[] PositionY { get; set; } = []; + [Key(5)] public float[] VelocityX { get; set; } = []; + [Key(6)] public float[] VelocityY { get; set; } = []; + [Key(7)] public float[] Radius { get; set; } = []; + [Key(8)] public float[] Mass { get; set; } = []; + [Key(9)] public float[] DynamicMask { get; set; } = []; + [Key(10)] public float[] Restitution { get; set; } = []; + [Key(11)] public string[] FieldIds { get; set; } = []; + [Key(12)] public float[] FieldPositionX { get; set; } = []; + [Key(13)] public float[] FieldPositionY { get; set; } = []; + [Key(14)] public float[] FieldStrength { get; set; } = []; + [Key(15)] public float[] FieldRadius { get; set; } = []; + [Key(16)] public float[] DirectionX { get; set; } = []; + [Key(17)] public float[] DirectionY { get; set; } = []; + [Key(18)] public float[] AngularVelocity { get; set; } = []; + [Key(19)] public float[] KinematicMask { get; set; } = []; + [Key(20)] public float[] BulletMask { get; set; } = []; + [Key(21)] public float[] FieldParticipationMask { get; set; } = []; + [Key(22)] public ulong[] CollisionCategoryBits { get; set; } = []; + [Key(23)] public ulong[] CollisionMaskBits { get; set; } = []; + [Key(24)] public int[] CollisionGroupIndex { get; set; } = []; + + public static YmirWorldStateDocumentV2 FromSoA(string worldId, YmirSoAWorld world) => new() + { + WorldId = worldId, Time = world.Time, + BodyIds = (string[])world.BodyIds.Clone(), + PositionX = (float[])world.PositionX.Clone(), PositionY = (float[])world.PositionY.Clone(), + VelocityX = (float[])world.VelocityX.Clone(), VelocityY = (float[])world.VelocityY.Clone(), + Radius = (float[])world.Radius.Clone(), Mass = (float[])world.Mass.Clone(), + DynamicMask = (float[])world.DynamicMask.Clone(), Restitution = (float[])world.Restitution.Clone(), + FieldIds = (string[])world.FieldIds.Clone(), + FieldPositionX = (float[])world.FieldPositionX.Clone(), FieldPositionY = (float[])world.FieldPositionY.Clone(), + FieldStrength = (float[])world.FieldStrength.Clone(), FieldRadius = (float[])world.FieldRadius.Clone(), + DirectionX = (float[])world.DirectionX.Clone(), DirectionY = (float[])world.DirectionY.Clone(), + AngularVelocity = (float[])world.AngularVelocity.Clone(), + KinematicMask = (float[])world.KinematicMask.Clone(), BulletMask = (float[])world.BulletMask.Clone(), + FieldParticipationMask = (float[])world.FieldParticipationMask.Clone(), + CollisionCategoryBits = (ulong[])world.CollisionCategoryBits.Clone(), + CollisionMaskBits = (ulong[])world.CollisionMaskBits.Clone(), + CollisionGroupIndex = (int[])world.CollisionGroupIndex.Clone() + }; + + public YmirSoAWorld ToSoA() => new() + { + Time = Time, BodyIds = (string[])BodyIds.Clone(), + PositionX = (float[])PositionX.Clone(), PositionY = (float[])PositionY.Clone(), + VelocityX = (float[])VelocityX.Clone(), VelocityY = (float[])VelocityY.Clone(), + Radius = (float[])Radius.Clone(), Mass = (float[])Mass.Clone(), + DynamicMask = (float[])DynamicMask.Clone(), Restitution = (float[])Restitution.Clone(), + FieldIds = (string[])FieldIds.Clone(), + FieldPositionX = (float[])FieldPositionX.Clone(), FieldPositionY = (float[])FieldPositionY.Clone(), + FieldStrength = (float[])FieldStrength.Clone(), FieldRadius = (float[])FieldRadius.Clone(), + DirectionX = (float[])DirectionX.Clone(), DirectionY = (float[])DirectionY.Clone(), + AngularVelocity = (float[])AngularVelocity.Clone(), + KinematicMask = (float[])KinematicMask.Clone(), BulletMask = (float[])BulletMask.Clone(), + FieldParticipationMask = (float[])FieldParticipationMask.Clone(), + CollisionCategoryBits = (ulong[])CollisionCategoryBits.Clone(), + CollisionMaskBits = (ulong[])CollisionMaskBits.Clone(), + CollisionGroupIndex = (int[])CollisionGroupIndex.Clone() + }; +} + public static class YmirCultCacheStore { public static async Task SaveWorldAsync(string path, string worldId, YmirSoAWorld world) @@ -183,8 +253,8 @@ public static class YmirCultCacheStore using (cache) { await cache.UpsertAsync( - YmirWorldStateDocumentV1.FromSoA(worldId, world), - new CultRecordHandle(new CultRecordKey($"ymir:world:{worldId}"))) + YmirWorldStateDocumentV2.FromSoA(worldId, world), + new CultRecordHandle(new CultRecordKey($"ymir:world:{worldId}"))) .ConfigureAwait(false); await cache.FlushAsync().ConfigureAwait(false); } @@ -196,7 +266,8 @@ public static class YmirCultCacheStore path, new CultCacheOpenOptions { UseDirectoryStore = true }).ConfigureAwait(false); var key = new CultRecordKey($"ymir:world:{worldId}"); - return cache.Get(key)?.ToSoA() + return cache.Get(key)?.ToSoA() + ?? cache.Get(key)?.ToSoA() ?? cache.Get(key)?.ToSoA(); } } diff --git a/src/ymir-daemon/Program.cs b/src/ymir-daemon/Program.cs index 54f1089..96c9e6e 100644 --- a/src/ymir-daemon/Program.cs +++ b/src/ymir-daemon/Program.cs @@ -82,7 +82,7 @@ internal static class Program ok = true, path, record = "ymir:world:sample", - schema = "gamecult.ymir.world_state.v1", + schema = "gamecult.ymir.world_state.v2", bodyCount = result.World.BodyCount, fieldCount = result.World.FieldCount }); diff --git a/tests/Ymir.Box3D.Parity/Box3DOracle.cs b/tests/Ymir.Box3D.Parity/Box3DOracle.cs index 43a98be..4d42ca9 100644 --- a/tests/Ymir.Box3D.Parity/Box3DOracle.cs +++ b/tests/Ymir.Box3D.Parity/Box3DOracle.cs @@ -93,6 +93,18 @@ internal static partial class Box3DOracle [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static partial int ymir_box3d_session_get_contact_event_count(nint session); + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static partial int ymir_box3d_session_get_body_count(nint session); + + [LibraryImport(LibraryName)] + [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] + internal static unsafe partial int ymir_box3d_session_copy_bodies( + nint session, + Box3DSessionBodyOutput* bodies, + int capacity, + out int written); + [LibraryImport(LibraryName)] [UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])] internal static unsafe partial int ymir_box3d_session_copy_contact_events( @@ -154,6 +166,8 @@ internal readonly record struct Box3DTorqueResult( [StructLayout(LayoutKind.Sequential)] internal readonly record struct Box3DSessionBodyInput( ulong StableId, + ulong CollisionCategoryBits, + ulong CollisionMaskBits, float PositionX, float PositionY, float VelocityX, @@ -165,7 +179,11 @@ internal readonly record struct Box3DSessionBodyInput( float Radius, float Mass, float Restitution, - uint IsStatic); + uint IsStatic, + uint IsKinematic, + uint IsBullet, + uint ParticipatesInFields, + int CollisionGroupIndex); [StructLayout(LayoutKind.Sequential)] internal readonly record struct Box3DSessionContactEvent( @@ -182,3 +200,14 @@ internal readonly record struct Box3DSessionContactEvent( float NormalY, float Penetration, float RelativeSpeed); + +[StructLayout(LayoutKind.Sequential)] +internal readonly record struct Box3DSessionBodyOutput( + ulong StableId, + float PositionX, + float PositionY, + float VelocityX, + float VelocityY, + float DirectionX, + float DirectionY, + float AngularVelocity); diff --git a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs index 7d68ca3..6dd9475 100644 --- a/tests/Ymir.Box3D.Parity/Box3DParityTests.cs +++ b/tests/Ymir.Box3D.Parity/Box3DParityTests.cs @@ -124,14 +124,12 @@ public sealed class Box3DParityTests [Fact] public unsafe void RetainedSessionCommandsPreserveTypedContactLifecycle() { - Assert.Equal(3u, Box3DOracle.ymir_box3d_get_abi_version()); + Assert.Equal(4u, Box3DOracle.ymir_box3d_get_abi_version()); Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session)); try { - var bodyA = new Box3DSessionBodyInput( - 1, -0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0); - var bodyB = new Box3DSessionBodyInput( - 2, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0); + var bodyA = SessionBody(1, -0.9f); + var bodyB = SessionBody(2, 0.9f); Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA)); Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bodyB)); Assert.Equal(2, Box3DOracle.ymir_box3d_session_spawn(session, &bodyA)); @@ -155,6 +153,74 @@ public sealed class Box3DParityTests } } + [Fact] + public unsafe void NegativeGroupAndCategoryMasksAreBox3DCollisionAuthority() + { + Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session)); + try + { + var source = SessionBody(1, 0.0f, category: 1, mask: 2, group: -7); + var ownPayload = SessionBody(2, 0.0f, category: 2, mask: 1, group: -7); + var otherPayload = SessionBody(3, 0.0f, category: 2, mask: 1, group: -8); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &source)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &ownPayload)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &otherPayload)); + + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0)); + var pairs = CopyEvents(session) + .Where(value => value.Kind == 1) + .Select(value => new HashSet { value.StableIdA, value.StableIdB }) + .ToArray(); + + Assert.Single(pairs); + Assert.Equal(new HashSet { 1, 3 }, pairs[0]); + } + finally + { + Box3DOracle.ymir_box3d_session_destroy(session); + } + } + + [Fact] + public unsafe void BulletUsesBox3DContinuousCollisionAgainstKinematicTarget() + { + Assert.Equal(0, Box3DOracle.ymir_box3d_session_create(out var session)); + try + { + var bullet = SessionBody(1, -10.0f, velocityX: 100.0f, isBullet: true); + var target = SessionBody(2, 0.0f, isKinematic: true); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &bullet)); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_spawn(session, &target)); + + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 0.2f, 4, null, 0)); + Assert.Empty(CopyEvents(session)); + var ccdBodies = CopyBodies(session); + Assert.True(ccdBodies.Single(value => value.StableId == 1).PositionX < 0.0f); + Assert.Equal(0.0f, ccdBodies.Single(value => value.StableId == 2).PositionX, precision: 5); + Assert.Equal(0, Box3DOracle.ymir_box3d_session_step(session, 1.0f / 60.0f, 4, null, 0)); + Assert.Contains(CopyEvents(session), value => + (value.Kind == 1 || value.Kind == 2) && + new HashSet { value.StableIdA, value.StableIdB }.SetEquals([1UL, 2UL])); + } + finally + { + Box3DOracle.ymir_box3d_session_destroy(session); + } + } + + private static Box3DSessionBodyInput SessionBody( + ulong id, + float positionX, + float velocityX = 0.0f, + ulong category = 1, + ulong mask = ulong.MaxValue, + int group = 0, + bool isKinematic = false, + bool isBullet = false) => new( + id, category, mask, positionX, 0.0f, velocityX, 0.0f, 0.0f, 1.0f, + 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0, + isKinematic ? 1u : 0u, isBullet ? 1u : 0u, 1u, group); + private static unsafe Box3DSessionContactEvent[] CopyEvents(nint session) { var count = Box3DOracle.ymir_box3d_session_get_contact_event_count(session); @@ -167,4 +233,17 @@ public sealed class Box3DParityTests } return events; } + + private static unsafe Box3DSessionBodyOutput[] CopyBodies(nint session) + { + var count = Box3DOracle.ymir_box3d_session_get_body_count(session); + Assert.True(count >= 0); + var bodies = new Box3DSessionBodyOutput[count]; + fixed (Box3DSessionBodyOutput* pointer = bodies) + { + Assert.Equal(0, Box3DOracle.ymir_box3d_session_copy_bodies(session, pointer, count, out var written)); + Assert.Equal(count, written); + } + return bodies; + } } diff --git a/tests/Ymir.Tests/YmirServicePublicationTests.cs b/tests/Ymir.Tests/YmirServicePublicationTests.cs index 3668aed..b3aee04 100644 --- a/tests/Ymir.Tests/YmirServicePublicationTests.cs +++ b/tests/Ymir.Tests/YmirServicePublicationTests.cs @@ -24,7 +24,7 @@ public sealed class YmirServicePublicationTests Assert.Contains("Box3D solver and collision semantics", advertisement.DoesNotOwn); Assert.Equal("Box3D v0.1.0 (C17)", diagnostics.NumericSubstrate); Assert.Contains("does not own physics algorithms", diagnostics.BatchKernel, StringComparison.Ordinal); - Assert.Contains("world_state.v1", diagnostics.Persistence, StringComparison.Ordinal); + Assert.Contains("world_state.v2", diagnostics.Persistence, StringComparison.Ordinal); Assert.Contains("v0 read migration", diagnostics.Persistence, StringComparison.Ordinal); } diff --git a/tests/Ymir.Tests/YmirSessionTests.cs b/tests/Ymir.Tests/YmirSessionTests.cs index 662a250..ce7ad41 100644 --- a/tests/Ymir.Tests/YmirSessionTests.cs +++ b/tests/Ymir.Tests/YmirSessionTests.cs @@ -190,6 +190,74 @@ public sealed class YmirSessionTests Assert.Equal(Vec2.Zero, session.Snapshot().Bodies.Single().Velocity); } + [Fact] + public void CollisionProfilesExcludeOwnGroupAndPayloadPeers() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "collision-profile", + [ + Body("source") with + { + CollisionCategoryBits = 1, + CollisionMaskBits = 2, + CollisionGroupIndex = -7 + }, + Body("own-payload") with + { + CollisionCategoryBits = 2, + CollisionMaskBits = 1, + CollisionGroupIndex = -7 + }, + Body("other-payload") with + { + CollisionCategoryBits = 2, + CollisionMaskBits = 1, + CollisionGroupIndex = -8 + } + ])); + + var result = session.Step(Step("profile-step", 0, 1.0f / 60.0f)); + var begin = Assert.Single(result.ContactFacts, fact => fact.Kind == YmirContactFactKind.Begin); + + Assert.Equal(new HashSet { "source", "other-payload" }, new HashSet { begin.BodyA, begin.BodyB }); + } + + [Fact] + public void BodyCanOptOutOfRadialFields() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "field-profile", + [Body("affected", positionX: 1.0f), Body("ignored", positionX: -5.0f) with { ParticipatesInFields = false }])); + + var result = session.Step(new YmirStepSessionCommand( + Header("field-step", 0), + 0.1f, + [new RadialField("gravity", Vec2.Zero, 10.0f, 10.0f)])); + + Assert.NotEqual(0.0f, result.World.Bodies.Single(body => body.Id == "affected").Velocity.X); + Assert.Equal(0.0f, result.World.Bodies.Single(body => body.Id == "ignored").Velocity.X, 5); + } + + [Fact] + public void KinematicTargetDoesNotAcceptBulletImpulse() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "bullet-kinematic", + [ + Body("bullet", positionX: -10.0f, velocityX: 100.0f) with { IsBullet = true }, + Body("target") with { IsKinematic = true } + ])); + + var ccdStep = session.Step(Step("ccd", 0, 0.2f)); + var eventStep = session.Step(Step("event", 1, 1.0f / 60.0f)); + + Assert.Empty(ccdStep.ContactFacts); + Assert.Contains(eventStep.ContactFacts, fact => fact.Kind is YmirContactFactKind.Begin or YmirContactFactKind.Hit); + var target = eventStep.World.Bodies.Single(body => body.Id == "target"); + Assert.Equal(Vec2.Zero, target.Velocity); + Assert.Equal(Vec2.Zero, target.Position); + } + private static YmirCommandHeader Header(string id, long revision) => new(id, revision); private static long BodyGeneration(YmirContactFact fact, string bodyId) => diff --git a/tests/Ymir.Tests/YmirSimulatorTests.cs b/tests/Ymir.Tests/YmirSimulatorTests.cs index 8eb4f05..19e2f1a 100644 --- a/tests/Ymir.Tests/YmirSimulatorTests.cs +++ b/tests/Ymir.Tests/YmirSimulatorTests.cs @@ -250,6 +250,46 @@ public sealed class YmirSimulatorTests } } + [Fact] + public async Task CultCacheV2PreservesBox3DBodyProfile() + { + var path = Path.Combine(Path.GetTempPath(), $"ymir-v2-tests-{Guid.NewGuid():N}.cc"); + var recordsPath = $"{path}.records"; + try + { + var world = YmirSoAWorld.FromWorld(new YmirWorld( + 3.0f, + [new PhysicsBody("payload", Vec2.Zero, Vec2.Zero, 0.5f, 1.0f) with + { + IsKinematic = true, + IsBullet = true, + ParticipatesInFields = false, + CollisionCategoryBits = 4, + CollisionMaskBits = 2, + CollisionGroupIndex = -11 + }], + [])); + + await YmirCultCacheStore.SaveWorldAsync(path, "test", world); + var loaded = await YmirCultCacheStore.LoadWorldAsync(path, "test"); + + Assert.NotNull(loaded); + loaded!.Validate(); + var body = Assert.Single(loaded.ToWorld().Bodies); + Assert.True(body.IsKinematic); + Assert.True(body.IsBullet); + Assert.False(body.ParticipatesInFields); + Assert.Equal(4UL, body.CollisionCategoryBits); + Assert.Equal(2UL, body.CollisionMaskBits); + Assert.Equal(-11, body.CollisionGroupIndex); + } + finally + { + if (File.Exists(path)) File.Delete(path); + if (Directory.Exists(recordsPath)) Directory.Delete(recordsPath, recursive: true); + } + } + private static SimulationStepResult Step(params PhysicsBody[] bodies) { var simulator = new YmirSimulator(); From 014c95c4540bdd4ba5960de80c8280d12ad83a13 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 22:01:38 +0100 Subject: [PATCH 6/7] Remember Box3D collision profile boundary --- .voidbot/state/ymir.cc | Bin 4011 -> 4241 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.voidbot/state/ymir.cc b/.voidbot/state/ymir.cc index 5bfa22067d9838d16672c009ab476d11fc23e233..b27533d530c9055e2a1d7ded8e2738629a385568 100644 GIT binary patch delta 1083 zcmZWo&1(}u6o(qD(pc0(1*!N%yyepbr0vCiT#5(J?QOC<*&RANGtSH=jh7sYH)X+V zDOeS}D2n3IKcil}+do2ovx#Xy$YE#l=Ka3j`*8Qwy^miPmfGvB_WHxMM(1Ix__1(2 zckUD?*H(+8OLp$=5o%V7+m$;DSDzMZmD=a)SN1B!pT!#muf*e{y-Zlz+}foZSx=66crW~@aT-Y`va|CE=%CeTH(FCb+TPwFWBGt9 z@5oy=KqDrJB}^#i=|Cu+0X`znY{F5~%RQOACxuHP$EUm$0AgBs7I`XLkybPg|Mj($ zdMH#v&U3Rtj%B(P+H$W3C)*JNvy24kCO)sD@Xd%`7Kp*ibbscV1gw*TWD?a9G<|C}v0G zv=lR44g!RPF~$HzWG0u0bE7n1lLtnE%`_nZ5@Sb7dt$jywH43NJy&Q!&;*U(K)^Oy zIT*tF948OYQ5IA-`@u^DpMnqR(0?f445D(}4)9!QRks{fVt@!H;WR#lvsSwq%o}4= zg8uJYxxg$Tywoc2ZJ0Y4o*ddUy{Y~;{D=f_43WxVz%1*Z#+xf z>*D9)gO$@B7Abx^8T9vT8bl$g^@}xawTqMLt&4LftoCa0tNLy3u8Z}4F?XJ<_LJrD T#a%bNTPe<$zf@;zy50T15vPLZ delta 793 zcmYjP&ubGw6oxd&ijAdGdJx6u!CPFD#?YpoG~%J4IaHALP?^k5vO{)fmYKKNMi0S% zpdbU@LyHOK>Z$jDY zP`T+|tQ;>|f3xW>*RR$h>3a31`x7Pe=LfkoU}aur45e1UN=&tpID=eIMFJzEbGZL_ z07h_a5(}tdU*CmcIT{ILVaWJ|V8a>o%M2efOyM3wo`#C4Bpmk{PX$!kWC3W_+-1cG2j(eM6=Wx0T<;7G1MqqF}86MlUp1$iPBim?d+ zxOW#e=D#15SQ70bomt7PcWweU)g@uYF-b^524oXOkjlaj&}YeUFOIa01tAu}E}dXW zLOy_zln4c%vO?G<_@D}!B`uQgd$`Ohcup#eF2^a1NeQQr;~8ZThcurCL_BQ){o)5= z%4mlY8p2_3fAGku)f0D8J9lYo_jYf$-HN;0ox}IY#@4xw#tru)TK^*I2X!}S+@v*K yb#G}$kD_R$(`wVcUU9z~-qr-(H(9`u0}n|E_)YeZAA}9{vMS>Kv8; From d854d9376f129bebd7823bcdaeee1e2b4aee6569 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 14 Jul 2026 22:04:22 +0100 Subject: [PATCH 7/7] Add revisioned retained Box3D queries --- README.md | 7 +- docs/architecture.md | 11 ++-- docs/retained-session-contract.md | 10 +-- src/Ymir.Core/RetainedSessionModel.cs | 44 +++++++++++++ src/Ymir.Core/YmirSession.cs | 95 +++++++++++++++++++++++++++ tests/Ymir.Tests/YmirSessionTests.cs | 44 +++++++++++++ 6 files changed, 199 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 7452b06..5a7caaa 100644 --- a/README.md +++ b/README.md @@ -61,9 +61,10 @@ mutations, force and torque commands, revisioned receipts, retained stepping, and typed Begin/Hit/End facts. It never treats omission as removal. The daemon still lacks a named session registry and CultMesh command lowering. Aetheria will name one session per run and zone through that daemon contract; its old -process-wide simulator objects are not session identifiers. Retained-world -queries, checkpoint reconstruction, and non-Windows RID artifacts remain -cutover work. +process-wide simulator objects are not session identifiers. Revision-checked +retained-session circle overlap and cast queries observe the current stable-id +body projection without mutating it. Checkpoint reconstruction and non-Windows +RID artifacts remain cutover work. See [the architecture map](docs/architecture.md) and [the executable parity contract](docs/box3d-parity.md). The diff --git a/docs/architecture.md b/docs/architecture.md index c377e64..08a0184 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -43,7 +43,7 @@ Begin/Hit/End facts with stable Ymir identities. Ordinary retained steps do not accept complete body snapshots. The current CLI still has no named session registry, CultMesh command -lowerings, retained-world queries, durable receipt ledger, or reconstruction +lowerings, durable receipt ledger, or reconstruction checkpoint. Its CultCache and Eve output is a regenerated diagnostic projection. The sections marked as target contract describe that daemon cut; they are not advertisements of current CLI capability. @@ -119,10 +119,11 @@ infer retained identity from a body list. Session identity must be explicit. A process-wide simulator object, zone index, or repeated stable body id is not enough to join two calls to the same world. Aetheria owns run and zone lifetime and will create, retain, and dispose the -corresponding Ymir session after daemon registry integration. Current projectile -sweep and stationary mine proximity integration can use Ymir's static -Box3D-backed circle-cast and overlap queries, but those calls do not join a -retained world or own contact lifecycle. +corresponding Ymir session after daemon registry integration. Projectile sweep +and stationary mine proximity integration can use Ymir's revision-checked +retained-session circle-cast and overlap queries. They observe the current +stable-id body projection; they do not invent a contact episode or mutate the +Box3D world. Radial gravity and tractor attraction are typed force-generation inputs. They are applied to Box3D before stepping. Pickup collection remains an Aetheria diff --git a/docs/retained-session-contract.md b/docs/retained-session-contract.md index cc770bb..c5b3897 100644 --- a/docs/retained-session-contract.md +++ b/docs/retained-session-contract.md @@ -43,9 +43,11 @@ The retained port accepts narrow operations with explicit meaning: - step with a fixed delta, substep count, and typed fields; - dispose the session. -The current public slice implements those mutation and step operations. -Retained-world overlap and cast queries at a named revision are the next -library cut; the static compatibility queries do not satisfy that contract. +The current public slice implements those mutation and step operations plus +revision-checked circle overlap and cast queries. A query observes the current +retained body projection under the session lock and accepts an explicit set of +stable candidate body ids. The candidate set is product-owned eligibility; +Box3D still owns the overlap/cast geometry and numeric result. Bullet, collision-filter, and field-participation profiles are currently spawn/restore definitions. Retained `Configure` changes radius, mass, static/kinematic/dynamic type, and restitution only. Changing the profile @@ -130,7 +132,7 @@ is derived process state: it never appears in a public fact or checkpoint. 1. Typed native mutation operations and step-owned lifecycle buffers: done. 2. Public managed retained session with no ordinary full synchronization: done. -3. Add retained-world queries and revision checks. +3. Revision-checked retained-session overlap and cast queries: done. 4. Add the daemon session registry, generation-bearing routed commands, idempotent Create, bounded live dedupe backed by durable receipts, and CultMesh command lowering. diff --git a/src/Ymir.Core/RetainedSessionModel.cs b/src/Ymir.Core/RetainedSessionModel.cs index 7f51f20..fb7999a 100644 --- a/src/Ymir.Core/RetainedSessionModel.cs +++ b/src/Ymir.Core/RetainedSessionModel.cs @@ -112,6 +112,50 @@ public sealed record YmirSessionStepResult( long StepIndex, IReadOnlyList ContactFacts); +public sealed record YmirSessionCircleCastQuery( + string QueryId, + long ExpectedRevision, + Vec2 Origin, + Vec2 Direction, + float Distance, + float Radius, + IReadOnlyList CandidateBodyIds); + +public sealed record YmirSessionCircleOverlapQuery( + string QueryId, + long ExpectedRevision, + Vec2 Center, + float Radius, + IReadOnlyList CandidateBodyIds); + +public enum YmirQueryError +{ + None, + StaleRevision, + UnknownBody, + InvalidQuery, + SessionDisposed, + SessionFaulted +} + +public sealed record YmirSessionCircleCastResult( + string QueryId, + string SessionId, + string SessionGeneration, + long ObservedRevision, + long ObservedStepIndex, + YmirQueryError Error, + IReadOnlyList Hits); + +public sealed record YmirSessionCircleOverlapResult( + string QueryId, + string SessionId, + string SessionGeneration, + long ObservedRevision, + long ObservedStepIndex, + YmirQueryError Error, + IReadOnlyList Hits); + public sealed record YmirSessionInfo( string SessionId, string SessionGeneration, diff --git a/src/Ymir.Core/YmirSession.cs b/src/Ymir.Core/YmirSession.cs index 71f5dd3..23a5976 100644 --- a/src/Ymir.Core/YmirSession.cs +++ b/src/Ymir.Core/YmirSession.cs @@ -409,6 +409,59 @@ public sealed class YmirSession : IDisposable } } + public YmirSessionCircleCastResult CastCircle(YmirSessionCircleCastQuery query) + { + ArgumentNullException.ThrowIfNull(query); + lock (_gate) + { + var error = QueryPreflight(query.QueryId, query.ExpectedRevision, query.CandidateBodyIds, out var bodies); + if (error != YmirQueryError.None) + { + return new YmirSessionCircleCastResult( + query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, error, []); + } + + try + { + var result = YmirQueries.CastCircle(new CircleCastQueryRequest( + query.Origin, query.Direction, query.Distance, query.Radius, bodies)); + return new YmirSessionCircleCastResult( + query.QueryId, _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.None, result.Hits); + } + catch (ArgumentException) + { + return new YmirSessionCircleCastResult( + query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.InvalidQuery, []); + } + } + } + + public YmirSessionCircleOverlapResult OverlapCircle(YmirSessionCircleOverlapQuery query) + { + ArgumentNullException.ThrowIfNull(query); + lock (_gate) + { + var error = QueryPreflight(query.QueryId, query.ExpectedRevision, query.CandidateBodyIds, out var bodies); + if (error != YmirQueryError.None) + { + return new YmirSessionCircleOverlapResult( + query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, error, []); + } + + try + { + var result = YmirQueries.OverlapCircle(new CircleOverlapQueryRequest(query.Center, query.Radius, bodies)); + return new YmirSessionCircleOverlapResult( + query.QueryId, _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.None, result.Hits); + } + catch (ArgumentException) + { + return new YmirSessionCircleOverlapResult( + query.QueryId ?? "", _sessionId, _sessionGeneration, _revision, _stepIndex, YmirQueryError.InvalidQuery, []); + } + } + } + public YmirCommandReceipt Dispose(YmirDisposeSessionCommand command) { ArgumentNullException.ThrowIfNull(command); @@ -458,6 +511,48 @@ public sealed class YmirSession : IDisposable }); } + private YmirQueryError QueryPreflight( + string? queryId, + long expectedRevision, + IReadOnlyList? candidateBodyIds, + out PhysicsBody[] bodies) + { + bodies = []; + if (_faulted) + { + return YmirQueryError.SessionFaulted; + } + if (_disposed) + { + return YmirQueryError.SessionDisposed; + } + if (string.IsNullOrWhiteSpace(queryId) || expectedRevision < 0 || candidateBodyIds == null) + { + return YmirQueryError.InvalidQuery; + } + if (expectedRevision != _revision) + { + return YmirQueryError.StaleRevision; + } + + var seen = new HashSet(StringComparer.Ordinal); + var selected = new List(candidateBodyIds.Count); + foreach (var bodyId in candidateBodyIds) + { + if (string.IsNullOrWhiteSpace(bodyId) || !seen.Add(bodyId)) + { + return YmirQueryError.InvalidQuery; + } + if (!_bodies.TryGetValue(bodyId, out var body)) + { + return YmirQueryError.UnknownBody; + } + selected.Add(body); + } + bodies = selected.ToArray(); + return YmirQueryError.None; + } + private IReadOnlyList ProjectFacts(IReadOnlyList nativeFacts) { var projected = new List(nativeFacts.Count); diff --git a/tests/Ymir.Tests/YmirSessionTests.cs b/tests/Ymir.Tests/YmirSessionTests.cs index ce7ad41..4160a92 100644 --- a/tests/Ymir.Tests/YmirSessionTests.cs +++ b/tests/Ymir.Tests/YmirSessionTests.cs @@ -258,6 +258,50 @@ public sealed class YmirSessionTests Assert.Equal(Vec2.Zero, target.Position); } + [Fact] + public void RetainedCastObservesNamedRevisionAndExplicitCandidates() + { + using var session = YmirSession.Create(new YmirSessionCreateRequest( + "retained-cast", + [Body("source", positionX: -2.0f), Body("target", positionX: 2.0f), Body("ignored", positionX: 0.0f)])); + + var result = session.CastCircle(new YmirSessionCircleCastQuery( + "payload-sweep", + 0, + new Vec2(-5.0f, 0.0f), + new Vec2(1.0f, 0.0f), + 10.0f, + 0.25f, + ["target"])); + + Assert.Equal(YmirQueryError.None, result.Error); + Assert.Equal(0, result.ObservedRevision); + Assert.Equal(0, result.ObservedStepIndex); + Assert.Equal("target", Assert.Single(result.Hits).BodyId); + Assert.Equal(0, session.Info.Revision); + } + + [Fact] + public void RetainedQueriesFailClosedForStaleUnknownAndDisposedSessions() + { + var session = YmirSession.Create(new YmirSessionCreateRequest("query-failures", [Body("target")])); + + var stale = session.OverlapCircle(new YmirSessionCircleOverlapQuery( + "stale", 1, Vec2.Zero, 1.0f, ["target"])); + var unknown = session.OverlapCircle(new YmirSessionCircleOverlapQuery( + "unknown", 0, Vec2.Zero, 1.0f, ["missing"])); + session.Dispose(); + var disposed = session.OverlapCircle(new YmirSessionCircleOverlapQuery( + "disposed", 0, Vec2.Zero, 1.0f, ["target"])); + + Assert.Equal(YmirQueryError.StaleRevision, stale.Error); + Assert.Equal(YmirQueryError.UnknownBody, unknown.Error); + Assert.Equal(YmirQueryError.SessionDisposed, disposed.Error); + Assert.Empty(stale.Hits); + Assert.Empty(unknown.Hits); + Assert.Empty(disposed.Hits); + } + private static YmirCommandHeader Header(string id, long revision) => new(id, revision); private static long BodyGeneration(YmirContactFact fact, string bodyId) =>