diff --git a/.gitmodules b/.gitmodules
index 0773f0a..5ec6d4f 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,3 +1,3 @@
[submodule "extern/box3d"]
path = extern/box3d
- url = https://github.com/erincatto/box3d.git
+ url = https://eureka.gamecult.org/forge/GameCult/box3d.git
diff --git a/.voidbot/state/README.md b/.voidbot/state/README.md
deleted file mode 100644
index 30776d7..0000000
--- a/.voidbot/state/README.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# Ymir Persona State
-
-`ymir.cc` is Ymir's repo-local persistent Persona state.
-
-Do not hand-edit the `.cc` file. Use the repo-local tools:
-
-```powershell
-.\tools\persona-state-read.ps1
-.\tools\persona-remember.ps1 -Summary "..." -Claim "..." -Tension "..." -ActionImplication "..."
-```
-
-The tools call VoidBot's typed self-state service so the same document schema
-used by registered repo Faces owns mutation and reads.
-
-VoidBot automatic indexing requires Ymir to be registered as a repo Face
-identity in VoidBot. Until then, this file is local typed state and can still be
-read or mutated by the tools here.
diff --git a/.voidbot/state/ymir.cc b/.voidbot/state/ymir.cc
deleted file mode 100644
index b27533d..0000000
Binary files a/.voidbot/state/ymir.cc and /dev/null differ
diff --git a/.voidbot/voice/identity.json b/.voidbot/voice/identity.json
deleted file mode 100644
index 9dc8809..0000000
--- a/.voidbot/voice/identity.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "id": "ymir",
- "repoName": "Ymir",
- "repoPath": "E:/Projects/Ymir",
- "displayName": "Ymir",
- "description": "Ymir Face for the Ymir repo: the world-body physics substrate for GameCult. Ymir should speak with plain, heavy precision: body, field, contact, impulse, witness, cut. It cares about moving physics truth out of Unity and into a coherent CultMath/CultCache/CultMesh-owned substrate without letting adapters, renderers, or debug surfaces pretend to own the world.",
- "grants": [
- "discussion",
- "rumination",
- "repo_read",
- "repo_propose"
- ],
- "jurisdictions": [
- {
- "kind": "repo",
- "id": "Ymir",
- "repoName": "Ymir",
- "path": "E:/Projects/Ymir",
- "authority": "propose"
- }
- ],
- "faceStatePath": "E:/Projects/Ymir/.voidbot/state/ymir.cc"
-}
diff --git a/AGENTS.md b/AGENTS.md
index bbb8913..e2216c9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,55 +1,10 @@
# Ymir Agent Instructions
-Ymir owns authoritative physics sessions and their GameCult contracts. Box3D
-owns the physics algorithms inside those sessions. Treat Unity, products,
-renderers, editor tools, and dashboards as clients or adapters unless a
-document explicitly transfers authority.
-
-Before substantial implementation, state:
-
-- Objective: what physical invariant or cutover outcome the work serves.
-- Current mechanism: how bodies, fields, contacts, and commands flow now.
-- Invariants: what must remain true during direct load, step, query, adapter
- playback, and reload.
-- Intended change: which owner or data path becomes simpler.
-- Cut line: which old callback, cache, adapter, or compatibility path may be
- deleted or demoted.
+Ymir provides the 3D SoA rigid-body and PBD/SPH particle boundary (`Ymir.Box3D` and `native/Ymir.Box3D`) around pinned Box3D (`extern/box3d`), consumed by `Lodur` and `BadDaySimulator`. Box3D owns rigid integration, collision geometry, broadphase, joints, and contact solving.
Architecture constraints:
-- Do not reimplement Box3D integration, collision geometry, broadphase,
- queries, solver behavior, contact lifecycle, or numeric tolerances.
- Physics edge cases follow the pinned Box3D release. Executable parity tests
- witness selected released behaviors; they are not a second specification.
-- `Ymir.Core` owns typed contracts, stable-id projection, session commands,
- deterministic ordering, persistence reconstruction, and publication. The
- native Ymir wrapper owns Box3D ABI isolation. Daemon, Unity, and future Rust
- or CultMesh surfaces consume those boundaries without importing Box3D
- internals.
-- Use CultMath for GameCult-side numeric projections and force preparation. It
- must not become a second integration or collision engine. Do not copy
- Unity.Mathematics helpers into Ymir.
-- JSON is allowed at HTTP/CLI compatibility boundaries. It is not durable truth.
- Durable state should move toward CultCache `.cc` documents and CultMesh
- publication.
-- Keep adapters boring. A Unity adapter may submit commands, receive snapshots,
- and render them; it must not silently repair or override Ymir state.
-- During cutover, provider advertisements and operator state must describe the
- running implementation. Target Box3D/CultMesh capabilities are not live
- capabilities until their production paths exist.
-- Aetheria embeds Ymir. Eve clients connect directly to Aetheria's advertised
- CultMesh provider; standalone Ymir and rendezvous services are not in the
- Aetheria gameplay path.
-- Add tests at the layer where the invariant lives. State invariants belong in
- `Ymir.Core`; daemon route shape belongs in daemon smokes; Unity visual timing
- bugs need Unity-side probes.
-
-Persona and persistent memory:
-
-- Ymir's repo Face identity lives in `.voidbot/voice/identity.json`.
-- Ymir's Persona state path is `.voidbot/state/ymir.cc`.
-- Read state with `tools/persona-state-read.ps1`.
-- Write durable repo memories with `tools/persona-remember.ps1`; do not hand-edit
- `.cc` state.
-- Preserve lessons that steer future ownership, cutover, invariants, and
- failure modes. Do not commemorate every small patch.
+- Do not reimplement Box3D rigid integration, collision geometry, broadphase, queries, or solver behavior in managed code.
+- Keep `native/Ymir.Box3D` free of gameplay policy: Box3D and the particle solver decide physics; consumers (`Lodur`, `BadDaySimulator`) own gameplay policy, limb control, and teardown rules.
+- Read `docs/soa-world.md` before changing ABI 21 structs or lane layouts; update both native `ymir_box3d_soa.c` size/ABI checks and managed `Box3DSoaWorld.cs` structs together.
+- Add tests in `tests/Ymir.Box3D.Soa.Tests/` at the layer where the invariant lives, and run the suite on a build host matching the target platform (Linux builds/tests run on Yggdrasil).
diff --git a/Directory.Build.props b/Directory.Build.props
deleted file mode 100644
index c8a3c67..0000000
--- a/Directory.Build.props
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
- $(CULTLIB_ROOT)
- $(MSBuildThisFileDirectory)..\CultLib
-
- 42dce3611a81adc5c5fac54cadbaa5637d6022d3
- C:\Program Files\Git\cmd\git.exe
- git
-
-
diff --git a/Directory.Build.targets b/Directory.Build.targets
deleted file mode 100644
index 46d436a..0000000
--- a/Directory.Build.targets
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
- <_CultLibReference Include="@(ProjectReference)"
- Condition="$([System.String]::Copy('%(Filename)').StartsWith('GameCult.')) or '%(Filename)' == 'CultMath'" />
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/README.md b/README.md
index 0616a5d..64ef24f 100644
--- a/README.md
+++ b/README.md
@@ -1,161 +1,24 @@
# Ymir
-Ymir is the GameCult library and service boundary around a pinned Box3D
-release, being cut over into Aetheria's authoritative embedded physics
-substrate. The name means **Not Invented Here**. We are taking the hint.
+Ymir is GameCult's 3D physics boundary around a pinned Box3D release (`extern/box3d`), consumed directly by `Lodur` and `BadDaySimulator`.
-Box3D owns physics algorithms. Ymir owns the service boundary that makes those
-algorithms usable as durable, typed GameCult world truth. Unity, renderers, and
-game products consume Ymir state and contact facts; they do not become physics
-authorities.
+Box3D owns rigid-body integration, collision geometry, broadphase, joints, and contact solving. Ymir adds a C17 native SoA wrapper (`native/Ymir.Box3D`) with an embedded XPBD solid + SPH fluid particle solver (`ymir_particles.c`) and a managed `.NET 8` binding (`src/Ymir.Box3D`, package `GameCult.Ymir.Box3D`).
-The production runtime path is a retained Box3D session. The parity facade
-witnesses released behavior at the native boundary; Ymir adds stable ids,
-typed commands and facts, replay memory, and deterministic projection without
-installing a second solver.
+## Entry Points
-## Front Door
-
-- **Value:** a retained Box3D physics session with GameCult world truth around it: stable entity ids, explicit mutation receipts, typed contact facts (Begin/Hit/End), replay-backed checkpoints, and deterministic result ordering.
-- **Problem:** physics authority must not be split between Unity callbacks, gameplay geometry tests and a managed solver. Box3D decides physics, Ymir owns the service boundary, Aetheria supplies intent.
-- **Entry points:**
- - `src/Ymir.Core/YmirSession.cs`: the public in-process retained session (commands, receipts, stepping, queries, `CapturePersistence`). `YmirSimulator.cs` is the snapshot facade that wraps an isolated session.
- - `src/Ymir.Box3D/` and `native/Ymir.Box3D/`: the native session ABI and the Ymir-owned Box3D shim (`GameCult.Ymir.Box3D` package).
- - `tests/Ymir.Box3D.Parity/`: the executable parity contract against pinned Box3D v0.1.0 (`docs/box3d-parity.md`).
- - `docs/architecture.md`, `docs/retained-session-contract.md`, `docs/aetheria-cutover.md`.
- - Build and test: `git submodule update --init --recursive`, then `dotnet test Ymir.slnx` (needs CMake and a C17 compiler).
-- **Live:** retained sessions, replay-backed checkpoint reconstruction, parity for overlap and cast queries, tractor membership, contact-begin facts, restitution, torque lifetime, collision filtering and bullet CCD. Aetheria embeds one session per run and zone and stores persistence in a daemon-private CultCache. Package version `0.3.0`.
-- **Planned:** journal compaction, Linux and macOS package RIDs (built and smoked on their own workers), a committed release smoke for packaging, and the optional standalone daemon (`src/ymir-daemon` is a thin command host today and is never in Aetheria's gameplay path).
-
-## Target Ownership
-
-- Box3D owns rigid-body integration, collision geometry, broadphase, solver
- 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, public in-process retained sessions, explicit mutation
- receipts, typed contact facts, snapshot lowering, deterministic result
- ordering, versioned CultCache snapshots.
-- An optional Ymir daemon may own named session routing, durable command receipts,
- checkpoint reconstruction, CultMesh command/fact publication, and process
- supervision for worlds it hosts. It is not part of Aetheria's gameplay path.
-- Aetheria owns gameplay policy and supplies typed physical intent: bodies,
- fields, tractor targets, forces, projectiles, filters, and the gameplay
- consequences of Ymir contact facts.
-- CultMath remains available for GameCult-side numeric projections and force
- preparation. It is not a second collision or integration engine.
-- Unity and Eve lowerers render world state and submit commands. They never
- repair, override, or independently simulate authoritative physics.
-
-Box3D opaque handles are process-local derived state. They are never durable
-entity ids and never cross the public contract boundary.
-
-Ymir does not promise bit-identical continuation from an arbitrary mid-world
-snapshot. Replay starts from canonical creation order plus the complete command
-stream. Checkpoints may accelerate numeric state recovery within named
-tolerances, but authoritative contact lifecycle facts resume only after that
-canonical history has been replayed through the checkpoint tick.
-
-## Aetheria Deployment Boundary
-
-Aetheria embeds the Ymir library and native Box3D wrapper in its own daemon.
-The Aetheria daemon owns gameplay ticks, world policy, player sessions,
-commands, receipts, assets, and the Eve/CultMesh provider advertisement.
-Generic Eve clients connect directly to Aetheria; they do not connect through
-Ymir or a rendezvous service.
-
-A future standalone Ymir daemon may expose the same physics contract for
-tooling or other products. It is not an intermediary in Aetheria's gameplay
-path and must never become a competing copy of Aetheria world truth.
-
-## Current Cutover State
-
-Box3D v0.1.0 is pinned at commit
-`8441b4a06d6d09dcfb0b0f704df4d847d1437b92`. A Ymir-owned native shim and
-parity suite already witness released Box3D behavior for:
-
-- sphere overlap and shape casts
-- tractor capsule membership and rounded caps
-- numeric overlap and cast slop
-- planar sphere-world stepping
-- 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,
-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 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. Aetheria
-embeds one session per run and zone; its old 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. Replay-backed checkpoint reconstruction is
-implemented. `CapturePersistence` emits only the journal suffix not yet stored
-by its host plus a bounded resume descriptor; restore verifies contiguous
-chunks, the complete journal digest, the projected world, and active contact
-episodes before the session can emit facts. Aetheria stores those records in a
-daemon-private CultCache and uses its hard-flushed public frame as the commit
-marker. Journal compaction 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
-[retained-session contract](docs/retained-session-contract.md) records the
-current ownership cut shared by embedded and optional standalone hosts.
+- `src/Ymir.Box3D/Box3DSoaWorld.cs`: managed 3D SoA world (`Box3DSoaWorld`, `Box3DSoaView`, `Box3DSoaFacts`) exposing contiguous body, joint, particle, constraint, wet-patch, and sensor lanes read in place.
+- `native/Ymir.Box3D/ymir_box3d_soa.c` and `native/Ymir.Box3D/ymir_particles.c`: native SoA world (ABI 21) and PBD/SPH particle engine built into `ymir_box3d` (`ymir_box3d.dll` / `libymir_box3d.so` / `libymir_box3d.dylib`).
+- `tests/Ymir.Box3D.Soa.Tests/`: xUnit verification suite covering rigid dynamics, joints, grabs, contact facts, impulses, removals, particles, cloth/rope coupling, fluids, wet patches, and sensors.
+- `docs/soa-world.md`: SoA world contract, lane semantics, and measured bounds.
+- `docs/box3d-parity.md`: pinned Box3D fork provenance (`extern/box3d`) and observed upstream behavior.
## Build And Test
-Initialize the pinned dependency and run the solution:
+Initialize the pinned Box3D submodule and build/test with CMake + a C17 compiler:
```powershell
git submodule update --init --recursive
dotnet test Ymir.slnx
```
-The parity project builds the native shim from source and requires CMake plus a
-C17 compiler:
-
-```powershell
-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.
-
-The current package version is `0.3.0`. ABI v5 exposes the exact pinned native
-build identity plus 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,
-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.
-
-## Building against CultLib
-
-Builds are pinned to CultLib 2.0.0 (tag `cultlib-unity-v2.0.0`, revision `42dce3611a81adc5c5fac54cadbaa5637d6022d3`); the build fails if the CultLib checkout differs or is dirty. Create a pinned worktree and point the build at it:
-
-```powershell
-git -C worktree add --detach cultlib-unity-v2.0.0
-dotnet build -p:CultLibRoot= # or set CULTLIB_ROOT=
-```
-
-Without an override the sibling `..\CultLib` checkout is used and must itself be at that tag.
+Box3D is MIT licensed; its license is retained in `extern/box3d/LICENSE` and packed in `GameCult.Ymir.Box3D`.
diff --git a/Ymir.slnx b/Ymir.slnx
index a793caa..51ef251 100644
--- a/Ymir.slnx
+++ b/Ymir.slnx
@@ -1,12 +1,8 @@
-
-
-
-
+
-
diff --git a/docs/aetheria-cutover.md b/docs/aetheria-cutover.md
deleted file mode 100644
index 4d32e47..0000000
--- a/docs/aetheria-cutover.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# Aetheria Cutover Notes
-
-## First Slice
-
-Cut over projectile travel and impact discovery before trying to replace every
-Unity physics use.
-
-1. Spawn a Ymir body for each projectile and relevant target hull/contact shape.
-2. Step Ymir on the same fixed tick used by Aetheria gameplay.
-3. Render Unity projectile GameObjects from Ymir snapshots.
-4. Convert Ymir contacts into Aetheria hit/splash policy.
-5. Keep Unity colliders as visual/debug witnesses only during the transition.
-6. Delete or neuter collider callbacks once the Ymir path owns hit truth.
-
-## Negative Checks
-
-- A projectile with a Unity collider disabled still travels and hits through
- Ymir.
-- A Unity `OnCollisionEnter` callback cannot apply damage independently.
-- Replaying from the same canonical creation order and command stream under the
- accepted Box3D build produces the same ordered Ymir facts.
-- Restarting from a checkpoint matches named numeric state tolerances. It emits
- no authoritative gameplay contact facts until canonical history has replayed
- through the checkpoint tick and restored exact contact lifecycle identity.
-- Mid-flight visible projectile position matches the Ymir snapshot within a
- named tolerance.
-
-## Adapter Boundary
-
-Unity adapter code may:
-
-- submit spawn/despawn/field/body commands
-- receive snapshots and contacts
-- render GameObjects from snapshots
-- publish diagnostics
-
-Unity adapter code may not:
-
-- alter positions as a hidden repair loop
-- apply gameplay damage from Unity collisions
-- maintain a parallel physics cache that can override Ymir
-- treat scene hierarchy as the source of simulation truth
diff --git a/docs/architecture.md b/docs/architecture.md
deleted file mode 100644
index 07bf2e1..0000000
--- a/docs/architecture.md
+++ /dev/null
@@ -1,237 +0,0 @@
-# Ymir Architecture
-
-## Objective
-
-Expose Box3D as authoritative, typed, persistent GameCult physics without
-leaking an alpha native API into products, clients, or durable state.
-
-Ymir's target is a stable embedded wrapper around retained Box3D worlds, not an
-independent physics-engine research project. Box3D supplies the physics mind.
-Ymir supplies the memory, nerves, names, and session boundary. The same
-boundary may optionally be hosted as a standalone daemon.
-
-## 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,
-casts, and contact transitions are true.
-
-Ymir owns the enclosing session and contract:
-
-- pin and build the accepted Box3D release;
-- map stable GameCult ids to transient Box3D handles;
-- accept typed body, shape, filter, force, torque, field, query, and step
- commands;
-- project Box3D outputs into typed, deterministically ordered Ymir facts;
-- reconstruct sessions from CultCache checkpoints;
-- return typed state, contacts, queries, and receipts to an embedding product;
-- when running standalone, publish Ymir's own physics provider and operator
- surfaces through CultMesh;
-- supervise world lifetime, failure, replay, and observability.
-
-## Deployment Boundary
-
-For Aetheria, Ymir is an embedded library. Aetheria owns the outer daemon,
-gameplay session, fixed tick, product commands and receipts, asset catalog, and
-advertised Eve/CultMesh surface. Generic Eve clients connect directly to the
-Aetheria daemon. They never import Ymir internals and do not route gameplay
-through a standalone Ymir or discovery service.
-
-A standalone Ymir daemon is an optional hosting mode for physics tooling and
-other products. It hosts the same Ymir session primitive; it is not an
-Aetheria relay and cannot own a shadow copy of Aetheria's world.
-
-## 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 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 embedded retained-session library has replay-backed reconstruction,
-durable command receipts, incremental journal-suffix capture, and bounded
-resume descriptors. Aetheria stores these in a second daemon-private CultCache:
-immutable chunks are flushed first, immutable per-frame resumes second, and the
-public Aetheria frame last. The public frame is the only commit marker. Orphaned
-private records cannot advance gameplay truth, and restart fails closed once
-the persistence capability has been activated. Complete replay history is not
-product state and never rides in public client frames. The current CLI still
-has no named session registry or CultMesh command lowerings; its CultCache
-output remains a regenerated diagnostic projection.
-
-## Target Inputs
-
-- stable body and shape definitions
-- fixed time step and explicit substep count
-- transient forces, torques, impulses, and target transforms
-- collision filters and material definitions
-- overlap, ray, and shape-cast queries
-- product-owned selections such as which pickup ids a tractor may affect
-
-Aetheria chooses physical intent and gameplay eligibility. Box3D decides
-geometry membership and contact. Ymir carries the typed handoff.
-
-## Target Outputs
-
-- body transforms and linear/angular velocities
-- begin, end, and hit contact facts with stable Ymir ids
-- overlap and cast results sorted by distance and stable id
-- step receipts and replay/checkpoint provenance
-- provider-owned operator and debug projections
-
-Box3D callback order is not a public contract. Ymir may sort facts, but it may
-not alter their membership or invent missing contacts.
-
-## Derived State
-
-- Box3D world, body, shape, contact, and joint handles are transient session
- state derived from stable Ymir definitions.
-- CultCache checkpoints are reconstruction inputs and publication records; they
- are not a second live solver.
-- SoA body documents are transport and inspection projections over the live
- session.
-- Unity GameObjects and Electron objects are render state only.
-- Aetheria damage, loot, capacity, faction, and scoring consequences are
- derived from Ymir facts plus Aetheria policy.
-
-## Dimensional Compatibility
-
-The fossil Aetheria simulation uses a two-dimensional gameplay plane. During
-cutover, Ymir maps that plane into Box3D X/Z with translation on Y locked and
-rotation constrained to the plane normal. This is an explicit compatibility
-projection. It does not make Ymir a second 2D physics engine.
-
-Sphere friction and inertia are not identical to planar disk behavior. Any
-mechanic that depends on that difference must be witnessed against the fossil
-and then expressed through Box3D configuration, not repaired by a parallel
-solver.
-
-## Forbidden Writers
-
-- managed integration, impulse resolution, collision geometry, or broadphase
- code in Ymir;
-- persisted force or torque replayed as if it were continuing authority;
-- Aetheria rectangle, capsule, overlap, or contact tests deciding gameplay
- physics;
-- Unity collision callbacks deciding hits, destruction, or pickup collection;
-- renderer transforms pushing hidden corrections into the world;
-- transport endpoints or dashboards owning world state;
-- Box3D opaque ids stored as durable GameCult identity.
-
-## Target Shared Paths
-
-Direct player commands, agent commands, programmatic spawns, server ticks,
-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 creates, retains, and disposes the
-corresponding embedded Ymir session. 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
-transaction triggered exactly once by a Ymir/Box3D contact fact.
-
-## Native Boundary
-
-`extern/box3d` pins the accepted upstream source. `native/Ymir.Box3D` owns a
-small stable C ABI facade. Managed Ymir code binds only to that facade; it does
-not scatter hundreds of direct P/Invokes across the daemon.
-
-The native facade must remain boring:
-
-- caller-owned blittable buffers;
-- explicit version and precision facts;
-- no GameCult gameplay policy;
-- no JSON state boundary;
-- no public exposure of Box3D internal handles;
-- first-class RID packaging before production consumers depend on it.
-
-## Target Persistence Contract
-
-Canonical deterministic replay starts from the same initial definitions and
-creation order, then applies the complete command stream under the pinned
-Box3D build and accepted runtime configuration.
-
-A checkpoint restart is a different promise. Its schema must contain enough
-typed definitions and state to reconstruct an equivalent Box3D world: stable
-ids, 3D transforms, linear and angular velocity,
-body/shape/material/filter definitions, session tuning, and provenance. Box3D
-does not expose every internal solver cache, so arbitrary mid-world checkpoint
-restart is tested against named numeric state tolerances rather than claimed as
-bit-identical continuation. Contact membership, ordering, and exactly-once
-lifecycle identity are binary contracts, not tolerance checks. Authoritative
-contact facts resume only after canonical history has been replayed through the
-checkpoint tick; a checkpoint alone cannot emit gameplay contact facts.
-
-`gamecult.ymir.session_checkpoint.replay.v1` implements that promise. It stores
-the initial definitions, complete typed command journal, logical session
-generation, command digest, body-generation counter, world verification
-projection, active contact-episode verification records, and pinned runtime
-fingerprint. Restore replays into a new Box3D world with outward publication
-suppressed, then compares the reconstructed boundary exactly before returning a
-live session. The bounded binary codec rejects incompatible, corrupt, or
-trailing data and checksums the complete encoded payload. ABI v5 validates the
-exact pinned native build id, not merely Box3D's public version. Native Box3D
-identities never enter the checkpoint.
-
-`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.
-
-Transient forces and torques are commands, not durable body state. Derived
-mass and inertia are published only when useful for inspection. Old checkpoint
-versions must migrate explicitly or fail closed; they may not silently decode
-under a reassigned MessagePack layout.
-
-## Cut Line
-
-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;
-3. overlap and shape-cast lowering;
-4. continuous collision event timing and same-step Box3D cast witnesses;
-5. transient force and torque application;
-6. checkpoint reconstruction and replay (implemented; journal compaction and
- long-running storage remain operational work);
-7. Aetheria gravity, tractor, pickup, and payload smokes.
-
-There is no managed fallback after that cut. A native load or compatibility
-failure fails closed and reports the missing capability.
-
-## Required Verification
-
-- Box3D parity tests record released upstream law at the native boundary.
-- Ymir differential tests compare public projections with the same Box3D
- session facts.
-- Negative source checks prove custom solver and spatial-index authorities are
- absent after cutover.
-- Aetheria smokes prove gravity, tractor attraction, contact-gated pickup
- collection/rejection, physical payload hits, and restart continuation through
- the retained contract. Destruction loot remains Aetheria gameplay state
- gated by Ymir contact facts where collection occurs.
-- 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 e0a13d7..6f1ba84 100644
--- a/docs/box3d-parity.md
+++ b/docs/box3d-parity.md
@@ -1,76 +1,15 @@
-# Box3D Parity Harness
+# Pinned Box3D Fork Notes
## Authority
-Box3D v0.1.0 is Ymir's physics implementation and executable semantics oracle.
-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`.
+Box3D v0.1.0 is Ymir's rigid-body physics implementation (`extern/box3d` submodule), pinned at the GameCult fork commit `c790839` (`https://eureka.gamecult.org/forge/GameCult/box3d`, branch `gamecult/destroy-enlarged-proxy`).
-Box3D does not own GameCult entity ids, gameplay policy, persistence, or result
-ordering. Ymir projects Box3D facts into those contracts. Box3D owns
-shape overlap, shape cast, solver, broadphase, contact lifecycle, force and
-torque lifetime, and numeric tolerances.
+The fork is upstream `8441b4a06d6d09dcfb0b0f704df4d847d1437b92` plus:
+- `b3ManifoldPoint.stepNormalImpulse`: observed field recording the normal impulse each contact point applied over the whole step, with a static assert that `RELAX_ITERATIONS` is 1 so the sum is exact.
+- Substep callback (`b3World_SetSubStepCallback`, with `b3Body_GetSubStepState` and `b3Body_ApplySubStepImpulse`, valid only inside the callback) used by the particle phase (`ymir_particles.c`) after the biased solve and before positions integrate.
+- Contact friction hook (`ebe346a`, see `docs/soa-world.md`).
+- Broad-phase fix (`DestroyEnlargedProxyTest`): rebuilding when the move buffer is empty clears stale enlarged flags on tree ancestors after proxy destruction.
-## Body
+To rebase onto a newer Box3D, re-apply those commits, re-run `tests/Ymir.Box3D.Soa.Tests`, and compare pile state hashes against the upstream build.
-`native/Ymir.Box3D` statically links the pinned C17 library into one small
-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 5 uses caller-owned blittable buffers, explicit cdecl,
-fixed-width status/count values, compile-time C layout assertions, and a
-managed/native layout and pinned-build-identity 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.
-ABI v5 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:
-
-```powershell
-dotnet test tests\Ymir.Box3D.Parity\Ymir.Box3D.Parity.csproj
-```
-
-The build requires CMake and a C17 compiler. Box3D is MIT licensed; its license
-is retained in the pinned submodule.
-
-## Released v0.1.0 Law
-
-- Sphere overlap accepts separation strictly below the `0.0005 m` overlap
- slop. Exact tangency therefore overlaps.
-- Sphere shape casts use Box3D's `0.005 m` linear slop. The hit fraction is not
- the zero-tolerance analytic sphere intersection.
-- The low-level v0.1.0 sphere shape cast reports initially touching and
- initially overlapping shapes as hits. The harness records the released
- binary's behavior rather than relying on prose or recollection.
-- A two-point shape proxy plus radius is the tractor capsule. Membership
- includes rounded start and end caps and the same overlap slop.
-- Box3D query callback order is not a contract. Ymir sorts projected results by
- distance and stable entity id.
-- Contact begin facts are emitted after the world step.
-- 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
-
-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.
+Box3D is MIT licensed; its license is retained in `extern/box3d/LICENSE`.
diff --git a/docs/retained-session-contract.md b/docs/retained-session-contract.md
deleted file mode 100644
index 99bbbc9..0000000
--- a/docs/retained-session-contract.md
+++ /dev/null
@@ -1,203 +0,0 @@
-# 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 session 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 maps 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, 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.
-
-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
-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.
-
-## 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.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
- derived from Ymir facts.
-
-The replay checkpoint preserves the logical session generation, complete typed
-command journal, receipt ledger, body-generation counter, world projection, and
-active contact episodes. Restore creates a fresh native Box3D world and replays
-that journal through the checkpoint boundary before facts may leave the
-session. The world and episode records verify replay; they do not replace it or
-infer contact continuity from body proximity.
-
-`gamecult.ymir.session_checkpoint.replay.v1` is encoded by the bounded binary
-`YmirSessionCheckpointCodec`. The checkpoint carries the pinned Box3D/ABI/
-precision fingerprint and fails closed on incompatible provenance, corrupt or
-trailing data, journal divergence, world divergence, or contact-lineage
-divergence. A SHA-256 checksum binds session identity, provenance, journal,
-world verifier, and active episodes. ABI v5 independently validates the exact
-pinned native build id before opening a session. It contains no native Box3D
-handle or contact key.
-
-For incremental host persistence,
-`gamecult.ymir.session_journal_chunk.v1` carries a contiguous command-journal
-suffix and `gamecult.ymir.session_resume.v1` carries the bounded reconstruction
-boundary. `CapturePersistence(persistedJournalEntryCount)` never repeats an
-already acknowledged prefix. Restore orders chunks by their first entry,
-requires exact coverage from zero through the descriptor count, and then uses
-the same full replay and verifier path as a complete checkpoint. Both binary
-forms are independently checksummed.
-
-The cursor is an index within one session generation. Bounded persistence uses
-an explicit generation rollover, never an inferred acknowledgement side effect.
-`TryCreateCompactedPersistenceBaseline` may create a replacement session only
-when the current journal is empty or ends in an accepted Step and Box3D reports
-no active contact episodes. The replacement starts from the current body
-projection and time with a fresh session generation, revision zero, an empty
-receipt ledger, and an empty journal. The host atomically swaps ownership and
-then disposes the prior session.
-
-Active contacts, pending forces, or other unstepped mutations refuse rollover.
-Those sessions retain replay reconstruction until a later quiescent boundary.
-Ymir does not synthesize contact closure, serialize private Box3D handles, or
-pretend a body snapshot can preserve solver contact state. Old generation
-journals become audit history after the host commits the replacement boundary;
-they are not inputs to the new generation's restore.
-
-## 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, spawns, and checkpoint replay use the same
-explicit session operations. Restore establishes a fresh native world through
-those operations; it is not a parallel state 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. Revision-checked retained-session overlap and cast queries: done.
-4. One embedded retained world and physical-payload session per Aetheria run
- and zone: done.
-5. Incremental journal chunks and bounded resume descriptors: done. Aetheria
- stores them in a daemon-private CultCache; complete history does not ride in
- public product frames. Quiescent generation rollover provides the compaction
- primitive; host adoption and old-generation retention policy are separate.
-6. For optional standalone hosting, add a session registry, generation-bearing
- routed commands, idempotent Create, durable receipts, and CultMesh lowering.
-
-The isolated `YmirSimulator` remains a compatibility API. It is never the
-retained-world authority.
-
-Mutation-generated End evidence is currently retained in the native pending
-buffer and published by the next accepted Step. The host 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 reproduces command receipts, bodies, active contact
- identity, and subsequent Begin/End facts before authoritative publication.
diff --git a/docs/soa-world.md b/docs/soa-world.md
new file mode 100644
index 0000000..f45bfc5
--- /dev/null
+++ b/docs/soa-world.md
@@ -0,0 +1,356 @@
+# Headless SoA world
+
+A headless 3D Box3D world with a structure-of-arrays state view, for Lodur and Bad Day Simulator.
+Box3D decides every physical outcome; Ymir creates bodies, steps the world and exposes state (`ymir_box3d_soa.c`, ABI 21).
+
+## Contract
+
+- Native (ABI 21): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) /
+ create_particles / destroy_particles / create_distances / create_bends / create_sensors / take_wet(n, sensors, volumes, taken) / attach(n, desc*) / set_pinned(n, handles, pinned) / remove / set_material / free_slots /
+ add_body / add_static_heightfield / add_static_mesh / add_joint / step / get_view / get_facts / set_anchor_target / destroy_joint / set_joint_thresholds / remove_body / free_joint_slots / free_body_slots / apply_impulse / cast_ray_closest / destroy`. `add_body` takes one descriptor (sphere, capsule, box, static box, anchor; position,
+ rotation, velocity, size, density, friction, restitution, rolling resistance, material id, parent, limb). `add_static_heightfield` (kind 6) and `add_static_mesh` (kind 7) create static terrain/mesh bodies whose native `b3HeightFieldData` / `b3MeshData` allocations are owned per body slot and destroyed after `b3DestroyBody` / `b3DestroyWorld` on `remove_body` / `destroy` (particle proxies treat both as `YMIR_PROXY_NONE`). Capacities are fixed at creation,
+ so lane pointers never move.
+- Body lanes (`ymir_box3d_soa_view`): `stable_id`, `kind`, `parent` and `limb` (set at creation, not read by
+ Box3D: the limb tree for the consumer), `size_0`, `size_1`, `size_2` (read-only shape size set at creation,
+ never changed by `step`: sphere {radius}, capsule {radius, half_length} along local Y, box and static box
+ {half_x, half_y, half_z}; unused components 0; dynamic and static box shapes are centred on the body origin, whereas
+ `StaticHeightField` (kind 6, anchored at grid `(0, 0)`) and `StaticMesh` (kind 7, local vertex coordinates) leave `size_0..2 = 0`), position xyz, rotation quaternion xyzw, linear and angular
+ velocity xyz. One contiguous array per component, indexed by body.
+- Write lanes: per-body world `force` (at the centre of mass) and `torque`, xyz, mutable through the view.
+ `step` applies them to the dynamic bodies and clears them, so a lane holds one step's intent. A
+ non-finite value refuses the whole step before any body is touched.
+- Joints: `add_joint` takes two body indices (B is the child), a world anchor and axis, and a kind
+ (revolute, spherical, weld). The joint frame has its z axis on the axis (the hinge axis); the creation
+ pose is the joint's zero. Optional limits: revolute angle, spherical swing cone and twist. Joint lanes:
+ `joint_kind`, `joint_body_a/b`, `joint_angle` (Box3D's revolute angle or spherical twist), `joint_frame`
+ (world orientation of frame A, quaternion), `joint_origin` (world position of frame A's origin, the anchor), `joint_rotation` (frame B relative to frame A, quaternion,
+ w >= 0) and `joint_angular_velocity` (B minus A, in frame A). A consumer can compute a joint torque from
+ these and write it as equal and opposite torques on the two body lanes.
+- Joint stress: `joint_constraint_force_xyz` (N) and `joint_constraint_torque_xyz` (N m) are Box3D's constraint solution for the joint at the end of the last step
+ (`b3Joint_GetConstraintForce/Torque`, world frame; a hung mass at rest reads m g within 2%; a removed lane reads 0). The joint desc's `force_threshold` and
+ `torque_threshold` (+inf, the default, is never; NaN or a negative value is refused; `set_joint_thresholds(joint, generation, force, torque)` changes a live joint's)
+ make Box3D report the joint in a step where its load reaches one: an Overload fact `{joint_lane, joint_generation, force xyz, torque xyz}` (the load read after the step), at most once per
+ joint per step. The threshold is a sensor: Ymir never removes a joint on it, the caller decides with `destroy_joint`. Joint user data is lane + 1.
+- Contact lanes (read-only, rewritten by every `step`): `contact_impulse` (N s: the normal impulse the
+ body's touching contacts delivered to it over the whole step, the sum of Box3D's `stepNormalImpulse` over
+ its manifold points; 0 for a body touching nothing; exact, so a jointed limb's reading is what the contacts
+ really delivered, not a mass formula's guess. It is a sum of magnitudes over all the body's contacts, not the
+ net: a ball under a ball reads support plus load, 3 m g dt, not m g dt. At rest it equals the weight only on
+ average: heavy balls in a pile alternate between about 1.5 and 0.5 m g dt from step to step, so a consumer
+ must not threshold a single step; average over steps or use `contact_impulse / dt` as a load estimate over a
+ window), `contact_count`
+ (touching contacts), `mass` (kg, Box3D's `b3Body_GetMass` copied once at create; 0 for static, kinematic, anchor and removed lanes) and `material_id` (the body's `material_id`, also set as the shape's Box3D user
+ material). `stepNormalImpulse` is the GameCult Box3D fork's observed field (see `box3d-parity.md`); it is
+ the normal channel only, since Box3D exposes no tangent impulse. Sleep is off in SoA worlds, so manifolds
+ hold no stale values; if sleep is ever enabled, zero the lanes of sleeping bodies. The hit fact's `impulse`
+ (N s) is the same sum over the manifold of the hit's two shapes, read after the step.
+- Contact facts: every shape is created with contact and hit events on (Box3D's default is off). After each
+ `step`, `ymir_box3d_soa_get_facts` returns pointers and counts into buffers fixed at create (`fact_capacity`
+ per kind, no allocation in the step): Begin and End `{lane_a, lane_b, stable_id_a, stable_id_b}` and Hit
+ those plus `point` xyz, `normal` xyz (A to B), `approach_speed` (a touch faster than `hit_threshold` m/s)
+ and `material_a`, `material_b`; Touching (`touching`) lists each pair touching after the step once, `lane_a < lane_b`, from the same per-body contact read as `ContactCount` (`touching_dropped` past `fact_capacity`). Facts are in Box3D's event order and last one step: the next `step`
+ rewrites them. `*_dropped` counts the facts a step could not keep past `fact_capacity`. The lane in a fact
+ is the body's user data (lane + 1) and the stable id is the shape's user data. The facts report; they
+ decide nothing.
+- Overload and removal facts (buffers fixed at create like the rest): `overload` (above), `body_removed` `{lane, generation (the dead handle's), stable_id, wet_patches, wet_volume}`
+ and `joint_removed` `{lane, generation, body_a, body_b, with_body}` (1 when a removed body took the joint, 0 for `destroy_joint`). `remove_body` and `destroy_joint` write them
+ into pending arrays and the next `step` publishes them in removal order (a lane is removed at most once between steps, so they never overflow), with the End touch facts the
+ removal caused: a removed body's shape is no longer valid, so its End facts are attributed from the retired shape table `{shape, lane, stable_id}`, cleared once the step has
+ collected them. Every removal path (a grab release, a cut, a gib, a level unload) appears in these facts. A step refused for a non-finite write lane publishes nothing and keeps them.
+- Grab and poke input (immediate commands; Ymir decides nothing about grabbing, so a player grab, a scripted
+ hook and a cursor tool are all the same three calls):
+ - Anchor (body kind 4): a kinematic body with no shape. It never collides or is hit, its size lanes are 0 and
+ size, density, friction and material are ignored. `set_anchor_target(lane, position, rotation, time_step)`
+ gives it the velocity that reaches the pose after `time_step`, so passing the step's dt lands it on the pose
+ at the end of the next step, where `step` stops it: after every step an anchor's velocity is zeroed, so with no
+ new target it holds still at the last pose (a skipped frame flings nothing) and its velocity lanes read 0. It is
+ refused for a lane that is not an anchor, for non-finite or non-unit input and for a time step <= 0. The force and torque lanes never move an anchor. Its pose reads from the state lanes.
+ - Motor joint (kind 3): `add_joint` with the descriptor's `linear_hertz`, `linear_damping`, `max_force`,
+ `angular_hertz`, `angular_damping`, `max_torque` (finite, >= 0, ignored by the other kinds; zero hertz turns that
+ spring off; no velocity target). The frame is built from the world anchor and axis like every joint, so the
+ linear spring pulls body B's anchor point onto A's (A an anchor, B the body to grab). `max_force` and
+ `max_torque` bound the pull: with a max force below the weight the body hangs below the target. `joint_angle`
+ reads 0.
+ - Release: the cursor's anchor is long-lived (a client creates one per cursor and keeps it, or removes it with `remove_body`).
+ `destroy_joint(joint, generation)` releases a joint of any kind (a grab, a cut, a tear) through the one joint-ending path, `ymir_soa_retire_joint`,
+ the only `b3DestroyJoint`; the bodies stay. The joint's lane becomes a tombstone: `joint_kind` 4
+ (Removed), `joint_body_a/b` -1, every joint lane 0 (the constraint lanes included), generation + 1; no last state is kept, a caller that wants it reads before
+ removing. `joint_count` counts slots ever used, tombstones included.
+ `add_joint` reuses the lowest tombstone only after a step has completed since the destroy, so lanes read within a
+ step stay valid; until then the slot is not free. `free_joint_slots` (managed `FreeJointSlots`) is what
+ `add_joint` could create right now: check it, and `FreeBodySlots`, before adding an anchor for a grab, so a full
+ world leaves no orphan anchor. Repeated grab and release on one slot do not grow the world.
+ A joint's handle is its lane and the slot's generation (`joint_generation` lane, counts destroys of the slot;
+ managed `Box3DSoaJointHandle`, returned by `AddJoint` and `AddMotorJoint`, converts to the lane). `destroy_joint`
+ refuses a generation that is not the slot's, a removed lane and an out-of-range lane, so a second release click with an old handle never destroys a later
+ grab that reused the slot. Anchor creation must be followed by a joint that validates (its spring fields are
+ checked there), or the anchor is left behind: with one long-lived anchor per cursor that is accepted, and an atomic
+ `AddGrab` is a follow-up only if cursors become dynamic.
+ - Body removal: `remove_body(lane, generation)` (managed `RemoveBody(Box3DSoaBodyHandle)`) is the one body-ending path. A body's handle is its lane
+ and the lane's generation (`body_generation` lane; managed `Box3DSoaBodyHandle`, returned by every `Add*` body helper, converts to the lane, so lane arrays and `int`
+ parameters take it unchanged). It is refused whole, changing nothing, for a lane that is not a live body, a stale generation, and with status REFERENCED (6; managed: it
+ throws) while a live body attachment or liquid sensor names the body: the caller removes those first (an anchor is a body and gets no rule of its own: its attachments
+ and sensors count the same). Otherwise, in order: the body's wet patches are removed (`ymir_particles_release_body`, no Box3D call), every joint naming the body is
+ retired (ascending lane, so a removed anchor ends its grabs and their handles go stale), the body's shape is entered in the retired table, Box3D destroys the body and the lane
+ becomes a tombstone: `kind` 5 (Removed), every other lane 0 (stable id 0, parent -1, limb 0), generation + 1. Lane order never changes (no swap-remove; `count` is the
+ high-water mark of lanes ever used). `add_body` takes the lowest Removed lane whose step has completed, else appends, else FULL; a lane is never reused before the step
+ whose facts name it dead, and the removed stable id may be reused. `free_body_slots` (managed `FreeBodySlots`) counts them. `attach`, `create_sensors`, `add_joint` and a
+ new body's `parent` refuse a Removed lane; a live child's `parent` may still name one (the consumer owns its tree). `particle_support_body` is a last-step fact and may name a
+ removed lane until the next substep; a drop cannot settle on it (its proxy reads no shape). Box3D's own joint cascade in `b3DestroyBody` never runs: the joints are retired first.
+ - `apply_impulse(lane, impulse, point)`: a one-shot world impulse (N s) at a world point; off the centre of mass it
+ also spins the body. Dynamic bodies only (a static body or anchor is refused), non-finite input refused.
+ - `cast_ray_closest(origin, translation)` fills a `ymir_box3d_soa_ray_hit` {hit, lane, stable_id, point, normal,
+ fraction}: Box3D's closest hit along origin + t * translation, t in [0, 1], default filter; a miss is success with
+ `hit` 0 and every field 0; a non-finite or zero translation is refused. Anchors are never hit. A ray that starts
+ inside a shape skips that shape (Box3D's behaviour, it ignores initial overlap) and reports what lies beyond.
+ - Managed: `AddAnchor`, `SetAnchorTarget`, `AddMotorJoint`, `DestroyJoint`, `FreeJointSlots`, `FreeBodySlots`, `ApplyImpulse`, `CastRayClosest` (returns
+ `Box3DSoaRayHit`) on `Box3DSoaWorld`; refusals throw `InvalidOperationException`.
+- State lanes change only inside `step`. Between steps a caller may read any state lane in place.
+- Managed (`src/Ymir.Box3D/Box3DSoaWorld.cs`, public: `Box3DSoaWorld`, `Box3DSoaView`, `Box3DSoaFacts`, `Box3DSoaKind`, `Box3DSoaJointKind`; the native structs and the view constructor stay internal): `Box3DSoaView` exposes each lane as a span over
+ native memory (`ReadOnlySpan` for state, `Span` for write lanes). Spans are invalid after `Dispose`.
+ `Count` and `JointCount` are as of when the view was taken, so take it after the last add.
+ `Box3DSoaWorld.Facts` is a `ref struct` of `ReadOnlySpan`s (`Begin`, `End`, `Hit`) with the same dispose
+ guard; the constructor takes `factCapacity` (default 4 x capacity, 0 refused) and `hitThreshold` (default 1);
+ the `Add*` methods take an optional `materialId`.
+- Determinism: one Box3D worker, bodies stepped in insertion order, same inputs give identical lane
+ bytes on the same build. It is not claimed across platforms or CPUs.
+- Particles (`ymir_particles.c`, C17, calls no Box3D; `ymir_box3d_soa.c` stays the only Box3D caller and the only caller
+ of `ymir_particles_begin`, `_substep` and `_end`). The particle state is a constraint graph: particles are one lane set with a
+ phase word and every constraint type is a lane set of its own. There is no object above the lanes: a rope, a sheet, a gut or
+ flesh is whatever constraints a caller emitted, and exists only in that caller's builders. A world created with a
+ `ymir_particle_capacities{particles, distances, bends, attachments, tethers, materials, fluid, wets}` that is not all zero owns fixed
+ lanes that never move; created with none (`NULL` or all zero) it behaves byte-identically to ABI 8. Nothing writes a
+ particle's position or velocity but the step.
+ - Data model. Particle lanes: `x y z vx vy vz radius inv_mass rest_x rest_y rest_z phase material live generation removed_at
+ component`. The phase word: bits 0-19 are the group, bit 20 `SELF_COLLIDE`, bit 21 `SELF_FILTER`, bit 22 `FLUID`, bit 23 `NO_PARTICLE_CONTACT` (refused together with `FLUID`); any other bit is refused.
+ Distance lanes: two particles, rest length, compliance (m/N), `tension` (sensor). Bend lanes: two distances that share one
+ particle (and so the three particles a, b, c), rest and limit offsets, compliance. Attachment lanes: kind (body, static,
+ removed), flags (`TETHER`; `ONE_WAY`, Body only: the body side weighs nothing, so the attachment holds its particle to the body's point and never moves or loads the body, for flesh whose mass the bone already carries; `LIMB`, Body only: the particle is flesh of the body's limb tree, so contact skips every body whose limb-tree root, the `parent` lane followed to its end, is the attached body's), particle, body, point, compliance, `force` (sensor). Held lanes (derived, command time): per particle the list of bodies its live Body attachments name, which contact skips, and `limb_body`, the body of its lowest live `LIMB` attachment or -1. Limit: when a particle's `LIMB` attachments name bodies of two limb trees only the lowest one's tree is skipped; the other tree's bones collide, except the bodies the particle is attached to. Tether lanes (derived): attachment,
+ particle, bound, parent tether, edge, other attachment. Material table: friction, XSPH viscosity, wet friction and the caller's material id. Handles are
+ (lane, generation).
+ - Pinned, dormant, kinematic, anchor. `pinned` is a command-owned lane (`set_pinned`; `destroy_particles` frees it to 0). A pinned particle is dormant: no step walk visits it, its `x y z vx vy vz` are stale from the tick it was pinned until it wakes, and a reader draws it from its anchor, the point of its lowest live non-`TETHER` attachment (body or static) when it was pinned, held while it sleeps so no attachment another command adds can move it, where the view's `particle_pinned` lane says which and its `particle_anchor` lane names the attachment (readers read it, never re-derive it). A pinned particle that shares a live distance or bend with an unpinned one is kinematic: each substep its position is its anchor's point at the substep's start pose and its predicted position that point at the predicted pose, so the live neighbour is held against a moving border (its velocity is the anchor point's over the substep). Every step walk visits a list `rederive_active` derived at command time, the last step of every topology command and of `set_pinned`: `act` (live unpinned particles), `kin`, `act_dist` and `act_bend` (live constraints with an unpinned particle), `act_att` (attachments of unpinned particles), all in lane order, plus `anchor` and `w` (the inverse mass the step reads: 0 for pinned). With nothing pinned the lists are every live lane in lane order and `w` is `inv_mass`, bit for bit. A dormant particle is in no contact grid (flesh at rest meets no fluid and no body: it rides its bone, which is the body fluid and other bodies meet, so blood poured on dormant skin stops at the bone's capsule, within a skin radius of the skin's surface only while the capsule is that surface), writes no impulse, and a pinned fluid particle is refused. `set_pinned` refuses whole (INVALID_ARGUMENT) a stale or dead handle, a value other than 0 or 1, a fluid particle, and pinning a particle with no anchor; a wake sets position to the anchor's point at the bodies' poses now and velocity to that point's velocity. `remove(attachment)` refuses a pinned particle's anchor. No distance component holds both a pinned particle and a live `TETHER` attachment (a tether loads every lane of its component, and no walk moves a pinned one): `rederive_topology`, which every topology command and `set_pinned` end in, checks it once on the components it derives before writing any lane, and refuses whole whatever would break it (a tether attached into a component with pinned flesh, a distance joining such a component to a tethered one, a pin in a tethered component); the command backs its lanes out. Wake first. Any other attachment of a pinned particle is accepted in whatever lane it takes and leaves its anchor and pose as they were. A patch of settled liquid on a pinned particle is read at its anchor's point, so it rides the bone.
+ - Commands, each refused whole before anything changes: `create_particles(n, desc{position, velocity, rest, mass, radius,
+ phase, material})` takes the lowest free lanes; `destroy_particles(n, handles)` removes every constraint that touches them;
+ `create_distances(n, desc{a, b, rest (< 0 = rest-pose length), compliance})`; `create_bends(n, desc{e1, e2, compliance
+ (< 0 = soft pass off), max_angle (< 0 = no limit)})`, refused unless the two distances share exactly one particle and the
+ bend does something; `attach(n, desc{kind body|static, flags, particle, body, point, compliance}*)` (a batch like `create_distances`: every desc validated, the lowest free lanes by cursor, one derivation, backed out whole on a refusal: a batch equals N single attaches only when accepted, since N singles keep the attachments accepted before a refused one); `remove(type distance|bend|
+ attachment, n, handles)`; `set_material(index, desc{friction, viscosity (>= 0), material_id})`; `free_slots(lane set)`. A distance takes
+ the bends over it with it. Ymir never removes a constraint or releases an attachment on a load: tear, cut, gib and release
+ are the caller's say-so.
+ - Derivation. Every topology command ends in the one `rederive_topology()`, which is the only writer of the tether lanes and
+ the component lane. It builds the adjacency of the live distances, labels components by their lowest lane, and then islands
+ (Kim, Chentanez, Mueller 2012 sec. 3.4): a particle holding a live `TETHER` attachment is a tether particle, and an island is
+ a maximal set of tether particles joined by live distances, named by its lowest `TETHER` attachment. For each island, in lane
+ order, one Dijkstra (binary heap, ties by node then edge) over the distances' rest lengths runs from all its tether particles;
+ another island's tether particle is settled but not expanded. Each particle that is not a tether particle keeps the two
+ nearest islands by rest path (an equal path keeps the lower island) and gets one tether to the nearest point of each, bounded
+ by that geodesic path (not the Euclidean rest distance: 0.23% on a flat two-corner sheet, but a coiled rope could never uncoil under
+ it, and the graph has no surface to say when it holds), with the tether of the previous particle on the path and the edge used (parents come before children). Ranking
+ attachments instead of islands fails when a corner is held by adjacent pins (two corners of two pins stretch 11.6% at 5 s by
+ the two nearest attachments, 2.4% by islands); one island per particle (nearest only) stretched 16.4%, and Kim's typical four
+ islands buy 1.66% against 1.72% on a 20-pin sheet for twice the lanes, so the count is `YMIR_TETHER_ISLANDS` = 2. Float32
+ path sums can break the exact-arithmetic closure of the rankings at a tie (a particle keeps an island its parent dropped), so
+ a tether is written only when its parent particle is a source or holds a tether to the same island: a gated particle keeps
+ one tether. So N particles carry at most 2N tethers however many points are pinned: a 32 x 32 sheet pinned at 20 points had
+ 20650 tethers (3.5 ms per tick) and has 2008. Two `TETHER` attachments on different particles of one component, at least one
+ on a body, also get a pair tether: the rest path between their particles bounds the distance between their points (what lets
+ a heavy body be held at 0.1% stretch from a static point: the full excess moves the body, not only the light end particle).
+ Two static points never move, so their pair has no end to pull and is not derived. A pair tether sits behind a route of booking lanes (attachment -1, an edge
+ and a parent, no bound of their own) along that path, so the tension sensors read its load on the edges it crossed; pairs
+ cost O(A^2) lanes and a derivation runs one more Dijkstra per tether point that has a later partner. Hold a heavy body with
+ `TETHER` at both ends: with the tether on one end only a 70 kg body hung from a 48-particle rope sinks 0.25 m below its
+ attachment (speed 1.1 m/s at rest), with both it holds to 0.002% stretch. The tether count is known before anything is
+ written (the Dijkstras run once to count and once to write); a command that would need more than the tether capacity is undone
+ whole and refused (`create_distances` and `attach` are the commands that can).
+ - Lanes. Particle, distance, bend and attachment lanes are tombstones (live 0 or kind removed, generation + 1, every other lane 0
+ except `removed_at`) reused only once a step has passed, lowest lane first. Stale generations are refused. Counts are high-water
+ marks; a view's counts are read when the view is taken, so take it after the last command.
+ - Solve (inside the fork's substep callback, `h = dt / substeps`, one iteration of each pass per substep: the small step does
+ the converging). Order: predict particles and proxies, hash grid (the non-fluid lanes), pair contacts (Jacobi), the fluid pass (its own grid; fluid-solid contact), attachments, distances in
+ lane order, bends in lane order, tethers, body contacts last (with contacts first a box pushed into a rope reads 14% of a
+ radius inside). A bend works on the offset of its shared particle b from the centroid of a, b, c (Kelager 2010): a soft XPBD
+ pass toward the rest offset, then a hard unilateral pass at the offset `max_angle` allows (computed from the two rest
+ lengths), free inside it and rigid at it. It bends on any topology a caller builds, and the limit is a hard constraint at the
+ substep the solver runs: how stiff it reads at few substeps is the open question `bend-limit-stiffness`.
+ - Contact. Particles of different groups collide; of one group only when both set `SELF_COLLIDE`, and not (when either sets
+ `SELF_FILTER`) if their rest-pose distance is under 1.5 (ri + rj). A `NO_PARTICLE_CONTACT` particle meets bodies and fluid
+ only: it is left out of the solid grid, so no non-fluid particle touches it, while body contact and the fluid grid still
+ hold it. The solid grid is sized by its members (a cell's particles are walked in lane order whatever the bucket count, so
+ the sizing moves no byte); the fluid grid keeps the full table, which `fluid_density`'s sum order depends on. Each pair is found once, walking half the 27-cell
+ neighbourhood from each particle (its own cell for higher lanes, 13 cells forward), in two walks: the first counts each
+ particle's overlaps; the second moves both ends of a pair by one displacement, weighted `1 / max(n_i, n_j)`, so a pair's two
+ corrections carry equal and opposite momentum and contact conserves it (to float32 rounding of the positions: 0.01% in the
+ thrown scene, 0.6% at a 30:1 particle mass ratio and 6% at 100:1). No pair list is kept: its size is not bounded by the particle
+ count. Body contact: a particle against each shaped body in lane order, the correction
+ split by inverse mass at the contact point, Coulomb friction from the particle's material; every body a particle is attached to
+ is skipped.
+ - Fluid. Fluid is a phase bit, not an object: a particle with `FLUID` takes part in a number-density constraint with every
+ other fluid particle and with the solids it would touch by contact, and keeps contact (at `ri + rj`) with those solids; two
+ fluid particles do not contact, whatever their groups and `SELF_*` flags (all fluid shares one density field, Macklin et al.
+ 2014 sec. 7). Kernel per pair `h = 2 (ri + rj)` (4 r at equal radii), Poly6 `W = 315 / (64 pi h^9) (h^2 - r^2)^3` for the
+ density and Spiky `grad W = -45 / (pi h^6) (h - r)^2 r_hat` for the gradient (Macklin and Mueller 2013); no PhysX code is
+ adapted. The rest density `n0(h)` is the Poly6 sum over the simple-cubic lattice of spacing `h / 2` (a constant, computed at
+ create, times `h^-3`), so a particle has volume `(2 r)^3` and there is no rest-density field. The constraint is unilateral,
+ `C_i = max(n_i / n0 - 1, 0)`, so there is no artificial-pressure term and an under-dense fluid (a gas of far particles) is not
+ pulled together; `lambda_i = -C_i / (sum_k w_k |grad_k C_i|^2 + eps w_i)` (0 when that is 0; XPBD inverse-mass weighting, Macklin et al. 2016) with the gradients over `n0` in 1/m^2 and `eps = 1e-4` (a sweep of
+ 1e-6 to 1e-2 on the column test moved the max density between 1.344 and 1.377 and nothing else: the gradient sum is about 500).
+ Per substep, after contact, the fluid pass rebuilds the grid over every live lane at the kernel cell `4 r_fmax` (the same tables, in place; nothing after the
+ pass reads the contact grid) and copies position, inverse mass and phase into sorted order, so a bucket reads contiguously (`sorted[q]` is the lane of sorted index `q`).
+ `fluid_rings = ceil(2 (r_fmax + r_max) / 4 r_fmax)` (1 at equal radii: 27 cells). Pass A takes each fluid row in sorted order: the buckets of its cells, each bucket once (a
+ bucket two offsets hash to is skipped the second time, by a visit stamp; a particle of a cell outside the rings is out of reach, so the distance test needs no cell
+ compare), a branchless compaction of the candidates within `2 (r_i + r_max)` into a stack row buffer of 128 (hits past it add to `fluid_neighbour_overflow`), and over the
+ buffer `n_i` (self and the solids it would touch by contact counted, `s = 1` as Flex 7.1) and `lambda` (a solid's is 0), and the row's neighbour list: every kernel neighbour
+ in walk order, packed (CSR) into an arena of `fluid_capacity * 96` entries (about 33 neighbours at rest at 4 r reach, about 45 at the column's compression); each past the
+ arena adds 1 to `fluid_neighbour_overflow`, the ABI 12 view scalar (last step, summed over its substeps), so `n` and `lambda` stay exact until the row buffer overflows and
+ only the correction and XSPH lose the pairs past the arena. `fluid_capacity` (`ymir_particle_capacities.fluid`, `Box3DSoaParticleCapacities.Fluid`, 0 by default) is the most
+ live fluid particles: `create_particles` refuses a batch past it whole (`FULL`, no lane taken). Pass B reads the lists: each fluid row in index
+ order, each listed neighbour in list order, a fluid neighbour below the row skipped (its own row does the pair), a solid always done from the
+ fluid row; a pair moves by `d = (lambda_i + lambda_j) grad W / n0(h)`, end `i`
+ by `w_i d` and end `j` by `-w_j d`, applied after the pass (equal masses move as before; a static end takes nothing and the fluid its XPBD share, so the energy at 30 : 1 and 100 : 1 does not rise). A pair therefore
+ carries equal and opposite momentum at any mass ratio (a solid end is the reaction: `m_i dx_i = -m_j dx_j`), a zero-mass end
+ takes nothing, and the one pair formula serves fluid with fluid and with solids. Then the fluid-solid contact (the contact pass never sees a fluid lane: the contact grid holds
+ the other lanes only, at `2 r_max`): two passes over the fluid rows' lists, the first counting the overlaps of each listed solid at `ri + rj`, the second moving both ends as the contact
+ pass does, weight `1 / max(n_i, n_j)` over these pairs only, applied after (Jacobi); PhysX solves fluid-solid in its fluid pass the same way. The XSPH viscosity of Schechter and Bridson
+ runs after the velocity update over the same lists (fluid neighbours above the row), `dv = c (v_j - v_i) W / n0` with `c` the mean of the two
+ materials' `viscosity`, split by inverse mass the same way, and only when some material has a viscosity above 0 (one scan of the material lanes a substep). A pair that
+ entered reach since pass A is missed by XSPH (smoothing, not a constraint). Lists, copies and the fluid grid are per-substep scratch, carved once at create: 28 bytes a particle lane
+ (`nbr_start`, `nbr_count`, `sx sy sz sw sphase`; h1's per-lane lists were 388) and 384 a unit of fluid capacity. A world with no live fluid steps byte-identically to
+ one before fluid (no pass runs: `live_fluid` counts the live fluid particles, written by create and destroy only). Cost on the 16 x 16 sheet scene at 4 substeps, increment over the same scene without fluid (Release, three runs; the cost line in `Box3DSoaCouplingTests` now prints the median of nine interleaved with-and-without pairs and its interquartile range):
+ 512 fluid +0.76 to +0.84 ms a tick at viscosity 0 and +0.86 to +1.01 at 0.01; 2000 fluid +4.1 to +4.4 at both, against a target of 1.0 ms at 512 (h1: +3.0 to +3.4 and +13.1 to +13.9). The probe behind the design
+ (a standalone replica of the pass) read 7 ns a cell visit in the 125-cell walk: the cost was per cell, not arithmetic, so the cell is now the kernel reach and the copies and the branchless filter keep the 27 buckets cheap. Two counting sorts a substep run with fluid live.
+ sensor lane `particle_density` reads `n_i / n0` (1 at rest, 0 for a solid) in the last substep the particle ran.
+ Support lanes `particle_support_body` and `particle_support_particle` (ABI 13; `SupportBody`, `SupportParticle` in the binding) name what a fluid particle touched in the
+ last substep it ran. Both are cleared to -1 for each live fluid lane at the start of the substep, after prediction, and written by the substep's contacts: body contact
+ sets `support_body` to the lane of each shaped body whose surface comes within the particle's radius, bodies ascending, so the highest lane touched wins; the fluid-solid
+ contact pass sets `support_particle` to the first solid listed in the particle's row that touches it (pass 1 of the walk, the solid's lane). A fluid particle resting only
+ on fluid reads -1 on both, so the bottom of a deep pool is supported and the interior is not; a solid lane, a free lane and a lane after create or destroy read -1 too.
+ The lanes name contact, not rest: the caller judges speed. They are notification only, written by the step and read by no pass; a world with no settled liquid
+ steps byte-identically to ABI 12. `destroy_particles` writes -1 to a destroyed lane's support lanes and to the `support_particle` of every live drop that named a destroyed solid, so no read after a destroy
+ names a dead lane.
+ - Settle (ABI 14). Liquid at rest becomes data: `settle(n, handles)` (`Box3DSoaWorld.Settle`) turns each named fluid particle into volume in a wet patch and destroys the particle (through
+ `destroy_particles`, the ISOLATED derivation reused: fluid holds no constraint). A patch is a disc of settled liquid on one support: a body (`wet_body`, its point in the body's frame: the
+ particle's nearest surface point from the proxies, which the command refreshes first, so it follows the body) or a solid particle (`wet_particle`, point 0); the other support reads -1. Lanes
+ `wet_body wet_particle wet_x wet_y wet_z wet_radius wet_volume wet_material wet_live wet_generation wet_removed_at` (capacity `wets`, `YMIR_LANES_WET` = 4 for `remove` and `free_slots`, lanes
+ tombstoned and reused as the others). A drop's support is its last step's `support_body` (else `support_particle`); one with neither is refused. A drop's volume is `(2 r)^3`, its patch's radius
+ `sqrt(volume / (pi film))` with `YMIR_WET_FILM` = 1 mm (one constant; a film per liquid is not added). In handle order a drop joins the lowest live patch on the same support and material whose
+ disc holds its contact point (volumes add, the centre is the volume-weighted mean, the radius is recomputed); else it takes the lowest free lane; else it joins the nearest patch of the same support
+ and material; else (no patch on its support) it adds its volume to the nearest live patch of its material in the world, by world distance from the drop to the patch's centre (the patch's body pose applied; ties go to the lowest lane), and that centre stays; else (no live patch of its material at all) the batch is refused `FULL`, whole, and every lane is as it was (an undo log sized by `fluid_capacity`). A dead or non-fluid particle, a stale handle, a particle named twice
+ or one with no support is refused whole too. `wet_volume` per body (the view's `WetVolume`, `body_wet_volume` natively) is the sum of the live patches on the body in wet lane order, written by
+ `rederive_wet` alone, which `settle`, `take_wet`, `remove(WET)` and `destroy_particles` (when it kills patches on the solid particles it destroys) call; the step never writes a wet lane or the volume. `remove(WET)` kills patches and ends in `rederive_wet`,
+ never in `rederive_topology`; `destroy_particles` kills the patches on the solid particles it destroys. `settle` and `remove` return the patch handles to read. Material `wet_friction` (>= 0) is stored
+ and viewed (`MaterialWetFriction`), and lowers friction where the liquid lies (below). Which particles settle, and when, is the caller's policy
+ (speed, age, film depth: `lodur:follow_up:bds-blood-settle-policy`); Ymir holds the data and the command.
+ - Sensors (ABI 15). A liquid sensor is a sphere fixed in a body that reads the liquid volume inside it: `create_sensors(n, desc{body, point, radius})` (`Box3DSoaWorld.CreateSensors`; `point` in the body's frame, `radius` m,
+ capacity `sensors`, `YMIR_LANES_SENSOR` = 5 for `remove` and `free_slots`, lanes tombstoned and reused as the others) refuses the whole batch, changing nothing, for a body outside the world's body count, a radius that is not
+ finite and > 0, a non-finite point, or too few free lanes. Lanes `sensor_body sensor_x sensor_y sensor_z sensor_radius sensor_liquid_volume sensor_wet_volume sensor_live sensor_generation sensor_removed_at`; a free lane reads
+ live 0, body -1 and 0 elsewhere. At the end of every step `ymir_particles_end` writes `sensor_liquid_volume` (m^3): for each live sensor in lane order, the sum in lane order of `(2 r)^3` over the live fluid
+ particles whose centre lies within `radius` (distance squared <= radius squared) of the sensor's centre, the body's proxy position plus the proxy rotation applied to `point`, in the pose the last substep left the
+ proxy in; 0 when no fluid is live. A second lane, `sensor_wet_volume` (`SensorWetVolume`), is the pooled liquid: the sum of the volumes of the live wet patches whose centre lies within `radius` of that centre, on any body or
+ solid particle (a body's patch centre is in its body's frame: the sphere is taken into that frame, culled against the body's disc box and walked through the wet index by centre x, bodies ascending; a patch on a solid particle
+ sits at the particle's position and is summed after, in wet lane order, by a scan of the wet lanes, which have no index). Two numbers, not a sum, so a consumer weighs pooled and moving liquid apart
+ (`lodur:ruling:liquid-sensor-reads-pooled-liquid`). Both are end-of-step readings: a `settle`, `destroy_particles` or `remove` between steps shows at the next step, which is the contract. The pass runs before `ymir_particles_end`'s early return for no live particle, so a sensor never keeps a reading once the liquid is gone. The readings are sensors: the step
+ writes them and no pass reads them back, so a world with sensors steps byte for byte as one without, and a world with none steps as ABI 14. `remove(SENSOR)` ends in no topology derivation. Ymir names no organ
+ (a head's airway, a lung): the consumer places a sensor and maps the volume (`lodur:follow_up:lodur-airway-liquid`). Gives up: a sphere only, not a shape-exact volume, and no per-liquid split.
+ - Take (ABI 21). `take_wet(n, sensors, volumes, taken)` (`Box3DSoaWorld.TakeWet`) removes up to `volumes[k]` m^3 of pooled liquid from the wet patches sensor k reads, so liquid a body breathes in leaves the world.
+ It refuses the whole call, changing nothing (INVALID_ARGUMENT), for n < 0, a NULL array with n > 0, a stale or dead sensor, a sensor named twice, and a volume that is not finite or is < 0 (managed: an
+ `ArgumentException` for a handle that is not a sensor, unequal lengths, or a non-empty `taken` shorter than the sensors). Per sensor in call order: W is the pooled sum above, `f = W > 0 ? min(1, v / W) : 0`, and a second walk of
+ the same sphere test (`pooled_walk`, shared with the reading, so the take removes from exactly the patches the reading summed, patches on solid particles included) scales every visited patch's volume by `1 - f`
+ and its radius by `wet_disc_radius`; a patch at f = 1 is removed as `remove(WET)`. Proportional by design: the film on a face and the pool beneath it shrink together and no lane order decides whose liquid is taken. A later
+ sensor in the call sees an earlier one's take (one index serves the whole call: a killed lane keeps its centre until the call's one `rederive_wet`, which returns it to rest, and a walk skips a lane that is not live); `taken[k]` (m^3) is the summed volume that left the patches, in double and
+ rounded once, so float storage can leave it below the ask or 0; `rederive_wet` runs once at the end, and not at all when nothing changed. The proxies are refreshed first, as `settle` does. `sensor_wet_volume` is written by the step's end alone: the reading changes at the next step. Ymir names no organ (a lung, an airway):
+ the consumer decides when liquid is breathed. Live drops are not taken (the caller destroys whole drops).
+ - Wet friction. Settled liquid lowers friction where it lands, per contact, never per shape: `wet_mu(body, point, mu)` is `min(mu, wet_friction)` of the lowest live patch on that body whose
+ disc holds the point (the point in the body's frame, as `wet_x wet_y wet_z` are), and `mu` at once when the body's `wet_volume` is 0. It is the one patch test. A particle that touches a body
+ uses it at the nearest surface point for a solid particle (also `min` with `particle_wet_mu[i]`, the wet friction of the lowest live patch on that solid particle, +inf when dry, derived by
+ `rederive_wet`); a fluid particle keeps its material friction. Body-body contact goes through the GameCult Box3D fork's `b3World_SetContactFrictionCallback`: `b3UpdateConvexContact` calls the
+ hook right after the mix (`sqrt(frictionA frictionB)`) with the mean of the manifold points in each body's frame (one point per manifold), both bodies' user data (lane + 1) and the mixed value,
+ and the world's hook returns `wet_mu` on B of `wet_mu` on A of it: it only lowers. The read is race-free (patches change only between steps) and a world with no settled liquid steps byte for
+ byte as before. Box3D skips `contactFrictionFcn` for `b3_simMeshContact` (so wet friction does not apply to `StaticHeightField` or `StaticMesh` contacts). The fork runs the hook on a recycled contact too (Box3D skips a recycled contact's update, and with it the friction mix): it mixes again and calls the hook, only when a hook is installed, so friction follows a patch settled or removed under a body at rest. The lookup is culled: `rederive_wet` indexes the live body patches by body then centre x with each body's box and largest radius (`wet_order`, `wet_body_start`, `wet_body_count`, `wet_body_box`), so a point outside the body's box is a constant check and one inside binary-searches the x window; the lowest lane still decides. The fork's own tests: `test.exe WorldTest` (the unfiltered run stops at CompoundTest, which fails at the fork's base as well). No ABI change (14).
+ Fluid holds no constraint: `create_distances` and `attach` refuse a fluid particle, so `create_bends` (over distances) can
+ never name one; a thing that holds liquid is cloth around free fluid (a balloon), as in Flex sec. 8. Every `create_particles`
+ and every `destroy_particles` of particles that held no distance derives only the isolated lanes
+ (`rederive_topology` with the ISOLATED mode: `component[i] = i` for created lanes, 0 for destroyed, tethers untouched): emitting
+ and removing 64 fluid particles a tick on the 20-pin 32 x 32 sheet costs 0.3 ms a tick of commands where the full derivation
+ costs 4.2 ms.
+ - Coupling (unchanged): one proxy per body (pose, velocity, shape, real inverse mass and world inverse
+ inertia). Before each rigid substep's positions integrate, `b3Body_GetSubStepState` fills the proxies and `b3Body_ApplySubStepImpulse`
+ delivers each dynamic body's correction as an impulse; the `particle_impulse` lane is the tick's total. Bodies are never
+ teleported; no `b3Body_Apply*Impulse` or `SetTransform` runs from the particle path. The gate is the live particle count.
+ - Sensors. Every correction is `lambda / h^2` in newtons, one scale. Distance `tension` is read by momentum balance: the
+ constraint's own correction, the bends over it and the tether impulses routed leaves-first down each path tree each book their
+ position impulse along the edge, over `h^2`, mean over the substeps; it reads the weight below each edge within 1% from 1 to
+ 70 kg whichever way the load is routed. Attachment `force` is the sum of the corrections at the point, tether load included. Loop
+ caveat: a sensor reads the solver's corrections, and a load that circulates in a closed loop of the graph (a sheet pinned at
+ four corners) is read as the corrections it needs, not as a statically determined split.
+- Particle determinism: single thread; constraints Gauss-Seidel in lane order; the one Jacobi pass (pair contact) accumulates corrections and applies them after the walk (each pair once, from the
+ lower of its two cells, neighbours read in cell then index order from a stable counting-sort grid, a bucket shared
+ by two cells is told apart by the cells' coordinates, a pair weighted the same at both ends); the heap and the breadth-first
+ labelling break ties by lane; proxy impulses are summed per body in lane order, per substep; only `+ - * /`, `sqrtf` and `cosf`
+ (at command time); the file builds with `-ffp-contract=off` (`/fp:precise` on MSVC). Same bytes on the same build, serial or with
+ other worlds stepping on other threads. No threads in this cut.
+- Concurrency: see Threading below; world creation and destruction are serialized by Ymir's native lock.
+
+## Tests
+
+`tests/Ymir.Box3D.Soa.Tests`, run serially: gravity and rest read through one held view, address stability
+across steps, two runs byte-equal at six checkpoints (25 spheres colliding on a slab), a one-ulp input
+difference diverging, argument refusal, dispose; and for joints: hinge angle and the relative-rotation
+lanes agreeing, an off-axis hinge, a limit and a weld, a spherical joint leaving the swing plane, force and
+torque lanes (exact acceleration, cleared after the step, static bodies ignoring them, NaN refusing the
+step), capsule and box rest heights with parent and limb lanes, refusals, and bit-identical repeat runs of
+a torque-driven jointed body. `Box3DSoaGrabTests`: a strong grab reaching a target 1 m away within 1 s, a weak grab falling at least `g - F/m`, an anchor that does not collide and is not hit by a ray, force lanes not moving an anchor, an off-centre impulse (linear `J/m` and the spin's sign and size), the ray's nearest body with lane, stable id, point and fraction, refusals changing nothing, and bit-identical repeat runs with a moving anchor and an impulse. `Box3DSoaContactTests`: a drop gives one begin and one hit (speed within 5%
+of sqrt(2gh), point and normal), lifting gives one end, dropped counters resetting each step, materials on
+hits, facts lasting one step, overflow counted, per-step byte determinism of facts and contact lanes, and
+no allocation across 100 steps with fact reads. `Box3DSoaImpulseTests`: `contact_impulse` and the hit `impulse` equal the momentum change of the bodies the contact acted on, plus their weight, within 1e-4 of the peak at every step: a 5 kg ball and a 0.3 g BB at 100 m/s onto a jointed forearm (the BB reads 0.030 N s, the ball over 400 times more), the arm falling forearm-first onto a slab, a sphere dropped 1.4 m at 60 and 240 Hz, 1 and 4 sub-steps, restitution 0 and 0.5, two free bodies at restitution 0 and 0.5; a swung arm into a slab, a big sphere with 60 small ones converging (more contacts than graph colours, so the scalar overflow solver runs: the big lane is the sum of the small lanes, each equal to its own momentum change), and at rest `contact_impulse / dt` is the weight (0.1%, a lone sphere) while a body touching nothing reads 0.
+
+`Box3DSoaRemoveTests`: removing a body retires its joints and zeroes its lane (old handles stale, others untouched, facts one step), is refused while an attachment or a liquid sensor names it, each alone and for an anchor too (nothing changed; after the caller removes them it succeeds; attach, sensors, add_joint and a parent then refuse the lane), refuses a current-generation handle to a tombstone (destroy_joint and remove_body) and lets an add reuse stable id 0, skips a removed lane in the particle substeps and the write-lane check (its write lanes are still cleared), names every removed toucher over 200 single-removal steps in a two-lane world (the retired table is cleared each step), survives 12 seeds of random add/remove churn on a floor (run in Debug too: Box3D validates its broad-phase there), takes its wet patches with it (count and summed volume on the fact, another body's patches untouched), ends a grab when the anchor goes, ends a touch by name, leaves a drop unable to settle, keeps the other lanes' state, reuses a lane one step later with a new generation, repeats bit for bit with removals and thresholds over 300 steps and allocates nothing managed. `Box3DSoaJointTests`: the constraint lanes read m g, an overload is reported once its load reaches the threshold and the joint stays, thresholds are refused when NaN or negative. `Box3DSoaGrabTests`: every joint kind destroys through one path. `Box3DSoaParticleTests`: the ABI 8 scene's six checkpoint hashes with no particle capacity (pinned from 5104b17); a 48-particle rope (a builder in the tests: distances and soft bends) hanging from a tethered static point under 1% stretch for 4 s; a 70 kg sphere held by the same rope (from 1 s to 5 s speed under 0.001 m/s, stretch under 0.1%, the impulse per tick within 0.5% of m g dt); an anchor dragging a 5 kg box along the floor (`particle_impulse` reads it); a sphere, capsule, box and static box each pushed into a lying rope's end (no particle over 10% of its radius inside); a 16 x 16 sheet from the same two commands hung by two corners (after 5 s the corners carry the weight within 1% and no edge is past 5%), and by two corners of two pins each (after 8 s, same bounds: it still rings at 5 s); edge tension, the edge at 0, 10 and 46 and both attachment forces read the load at 1, 5, 20 and 70 kg; a cut (remove an edge of a hung 40-rope: the bends over it die, tethers 39 -> 19, the component splits, the head holds and the tail falls); overload (300 kg) removes nothing; destroying a mid-rope particle removes its constraints and releases a held body; a 24-particle cantilever at 32 substeps under a 30 and a 10 degree hard limit and a stiff and a floppy soft pass, and a limit-only bend bit-identical to no bend inside its cone; momentum of a rope, a sheet and a blob thrown into each other with no gravity within 5e-4 and energy never rising; phase rules (groups, `SELF_COLLIDE`, `SELF_FILTER`, a folded rope); an off-centre attachment spinning a free box by I^-1 (r x J) within 2%; lanes reused after a step lowest first, stale generations refused, a derivation that does not fit refused with no lane changed, bad input refused; a pile of four ropes and a sheet on two bodies byte-equal across two runs at six checkpoints (pinned), a one-ulp difference diverging, and eight concurrent worlds giving the serial bytes; no allocation across 100 steps and across a cut, a destroy and a create, and none for a 300-distance batch created and removed; gravity along each axis; a spinning box carrying its attachment point and two ends on one light box settling (the proxy's rotation); one group's `SELF_COLLIDE` needing both particles and `SELF_FILTER` either; a slack pair tether leaving its body alone; a refused `attach` leaving no lane and no tether; each particle on the nearest point of its two nearest islands (a 5-rope held at both ends, a star whose centre keeps the two nearer arms, a 9-rope with two touching points counting as one island) and no pair between two static points; every tether's parent present after each of 20 attaches on a 32 x 32 sheet (float ties at rank 2 gated); a particle held by two bodies touching neither. `Box3DSoaParticleSourceTests` reads the C source: no Box3D call in `ymir_particles.*`, no allocation outside create and free, no threads or atomics, no rope, sheet, cloth or chain identifier in the solver or the binding, the tether and component lanes written only by the derivation, every topology command ending in it, `begin` and `end` called once (in the step), `substep` once (in the callback), the callback the only user of the fork's two accessors, no topology change in the phases, and the retired names absent.
+
+`Box3DSoaCouplingTests` (also the batch file): a 256-attachment sheet attached one by one and as one batch ends with equal lanes, generations and state after 120 steps; a batch with one bad desc (a fluid particle, a removed body, `STATIC` with `ONE_WAY` or `LIMB`), more descs than free lanes, or a derivation past the tether capacity changes no lane; `ONE_WAY` leaves its box at speed 0 with a 0 impulse lane while the particle holds its point; spawn cost lines for 256 attachments and for one and four Fellas. A sphere thrown at 5 m/s with a 48 x 20 g rope from rest keeps x momentum within 0.1% and gains no energy, at 5 and 70 kg; thrown up it reaches the apex momentum allows; 5 kg snapping a taut rope at 6 m/s keeps at most 5% of its energy and 70 kg is still within a tick; a 45 degree pendulum for 12 s gains no energy and loses at most 1.25 times a heavy-particle control, and a hung body keeps its spin about the vertical; removing the body attachment or destroying the rope's particles frees a held 70 kg body in the step after, with no upward impulse; `particle_impulse` equals M dv minus M g dt every tick, hung and thrown; material friction 0.6 holds a rope on a 20 degree slope and friction 0 does not; no particle is farther from a tethered point than its rest path; an attached end stays on its body point; a world whose only body is static still steps the particles (a dropped rope falls g t^2 / 2 within 2%) and rests; and a cost line with 16 ropes x 48 and one 16 x 16 sheet at 4 substeps, one body and forty (printed, not asserted).
+
+`Box3DSoaTerrainTests`: a bowl `StaticHeightField` catching a dropped sphere (sliding into the bowl centre with zero tunneling) and box (resting flat at bowl height), a `StaticMesh` box-prism roof drop and horizontal wall drive without penetration, `CastRayClosest` returning accurate hit point, surface normal, lane, and stable id on both `StaticHeightField` and `StaticMesh`, 10 x 20 repeated add/step/remove/dispose churn cycles with live particles (verifying `BodiesRemoved` and `End` touch facts), and clean refusal without slot consumption on invalid grid/mesh inputs (all-degenerate collinear or repeated-index triangles, out-of-bounds `>= 50000f` / `> 1e5f` vertex coordinates, overflowing `min_height = -2e38f, max_height = +2e38f` or scaled extents `>= 1e5f`, and oversized `count_x * count_z > 64M`, `triangle_count > 16M`, or `vertex_count > 32M`).
+
+## Not done
+
+`Box3DSoaFluidTests`: the refusals (a distance or attachment naming fluid, a viscosity below 0 or not finite; a batch of fluid past the fluid capacity, refused whole); 64 fluid particles created and destroyed a tick on the 20-pin sheet leaving every tether lane byte-equal; an 8 x 8 x 16 column in a box well (max density, mean density, nothing outside); fluid thrown into a free sheet and rope at fluid : solid mass 64 : 20, 1 : 30, 30 : 1 and 100 : 1 (momentum drift, energy on every row); a 343-particle fluid block dropped 15 cm onto a floor of immovable solid particles at 4 substeps (penetration, nothing through the floor's interior bar the one particle over a lattice hole); probe scene 3, the 343-particle pour on a tilted sheet and a sloped rope at 4 substeps, printed as readings with the same block flagged solid as the control, asserting nothing; fluid pushing a free box with the impulse lane equal to its M dv; a 3 r lattice not clumping; XSPH damping a shear field; the kernel reaching a larger solid beyond two contact radii; the pour's six checkpoint hashes (two runs, a one-ulp nudge, eight concurrent worlds). Each bound states its readings and the mutant it separates from. `Fluid_cost_line` prints 512 and 2000 fluid particles on the sheet scene at viscosity 0 and 0.01. Overflow is asserted 0 in the column, the floor and the pour.
+
+Compound bodies
+and per-shape material, and motor joints with a velocity target (the motor joint here is a position spring only; Lodur drives limbs from torque lanes). A one-call cascading `remove_body` that also removes the attachments and sensors naming the body is not built: the caller removes them first.
+Consumers use `Ymir.Box3D` (`Box3DSoaWorld`) directly.
+Unity consumption is unrun; cross-platform bit-identity is unclaimed.
+
+Particles: a sheet pinned at few points sieves at 4 substeps (the pour stretches a corner-pinned 16 x 16 sheet 38% and a same-size particle passes it, a same-mass solid block worse; per-substep travel is about 1 cm against a 4 cm contact, so it is the sheet and the contact solver, not the fluid: a loose-cloth limit, ruling ymir-sheet-sieve-at-budget-substeps); a sheet attached along its length to a body holds (`Skin_on_a_bone_holds_under_pour_and_drop`: 30 skin particles on a capsule under a 343-particle pour or 64 dropped solids, 3 s at 4 substeps and 60 or 120 Hz, worst edge stretch 0.021, no load particle inside the bone, skin place held to float noise), so BDS skin needs no more substeps, no boundary density for rigid bodies (a Box3D body adds nothing to a fluid particle's density estimate, so fluid
+beside a wall or floor under-reads: a 8 x 8 x 16 column in a box well reads 0.88 mean at zero gravity), no cohesion, adhesion or
+vorticity, no settle of fluid to rest (the column keeps a velocity noise, 1.25 m/s at its worst at 3 s with the one pass a substep, 0.82 with viscosity 0.1), a column compresses under its own weight (max density 1.34 on 16 layers), no pinning command beyond zero mass and attachments, no
+sleep, no threads, no particle write lanes. A heavy body cannot be held up by contacts against a floor (the particles are squeezed
+between two solids a position solver cannot satisfy at a 50:1 mass ratio; the pushing tests drive the body into a rope end
+instead). A snap on a taut rope is inelastic by the solver's construction, and a swung weight loses a few percent more as a tied
+body than as a heavy particle; neither gains energy.
+A hard bend limit is one iteration per substep and is not rigid at the substep counts the tests run; whether to change the solver is
+the open question `bend-limit-stiffness`, and the solver is as it was. Measured on a 24-particle cantilever held at two particles, 600 ticks at 60 Hz, the
+largest deflection of one joint: a 10 degree limit allows 21.7 degrees at 4 substeps and 22.3 at 8, 13.6 at 32 under a 1 kg tip and
+32.0 at 32 under a 5 kg tip; a 30 degree limit allows 31.5 at 4, 33.8 at 8 and 29.9 at 32 under a 5 kg tip. A soft bend is no stiffer
+than a floppy one at 4 or 8 substeps (tip drop with no load, stiff 1e-7 against floppy 1e-4: 0.764 m against 0.779 at 4, 0.835
+against 0.822 at 8, 0.053 against 0.798 at 32 where it reads as pinned). Read a bend limit as a guide below about 32 substeps and
+not at all under a heavy tip. A 16 x 16 sheet hung by two corners rings for about 9 s before the corners carry its weight within 1%
+(by two corners of two pins each, about 6 s). Pair contact
+conserves momentum to float32 rounding of the positions, which grows with the particle mass ratio (0.6% at 30:1, 6% at 100:1);
+the momentum test's 5e-4 is that floor, not a contact property: translating the whole scene moves its drift between 0.56e-4 and
+4.0e-4 under either contact walk, and the per-particle-average mutant reads 5.6e-2.
+Determinism under MSVC's
+`/fp:precise` is unbuilt (no `cl` on the workstation).
+
+## Build and lifetime notes
+
+- Native library name: `ymir_box3d.dll` on Windows (MinGW needs `PREFIX ""`, set under `if(MINGW)`; MSVC emits it
+ natively), `libymir_box3d.so` on Linux, `libymir_box3d.dylib` on macOS. `Ymir.Box3D.csproj` copies from
+ `bin\$(Configuration)\` on every platform: `CMakeLists.txt` writes `bin/$/` and the csproj passes `-DCMAKE_BUILD_TYPE=$(Configuration)`, so single- and multi-config generators land in the same place.
+- Windows run: MinGW gcc with `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; `Ymir.Box3D.Soa.Tests` passes.
+ Linux run (Yggdrasil, default generator, gcc): the same tests pass and emit `bin/Debug/libymir_box3d.so`. macOS is unrun.
+- Threading: creating and destroying worlds is safe from any number of threads at once (a process-wide lock in `ymir_box3d_soa.c` serializes `b3CreateWorld`/`b3DestroyWorld`, which otherwise scan and rewrite Box3D's global world pool unsynchronized). Stepping distinct worlds concurrently is not known to race: Box3D's own docs promise no thread safety, and this rests on a reading of the pinned source and one light test. A single world
+ is still not thread-safe. `Box3DSoaConcurrentCreateTests` creates, steps and disposes worlds from eight threads.
+- At most 128 live worlds per process (Box3D's `B3_MAX_WORLDS`); creating more trips a Box3D assert, not a managed error.
+- `Box3DSoaWorld` is not thread-safe: `Dispose` must not race `Step` or a lane read. A `Box3DSoaView` refuses
+ to hand out a lane (ObjectDisposedException) once its world is disposed, and a `default` view refuses with
+ InvalidOperationException. The check guards obtaining a span, not a span already held: a span taken from a
+ view must not be used after the world is disposed. Known limit: an undisposed world leaks its
+ native memory; there is no finalizer or SafeHandle.
diff --git a/extern/box3d b/extern/box3d
index 8441b4a..c790839 160000
--- a/extern/box3d
+++ b/extern/box3d
@@ -1 +1 @@
-Subproject commit 8441b4a06d6d09dcfb0b0f704df4d847d1437b92
+Subproject commit c7908394eb3ec3aa0f54bf26a98a683c1950ac15
diff --git a/native/Ymir.Box3D/CMakeLists.txt b/native/Ymir.Box3D/CMakeLists.txt
index 29a706c..42e9639 100644
--- a/native/Ymir.Box3D/CMakeLists.txt
+++ b/native/Ymir.Box3D/CMakeLists.txt
@@ -11,7 +11,7 @@ set(BOX3D_VALIDATE ON CACHE BOOL "" FORCE)
add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../../extern/box3d" "${CMAKE_CURRENT_BINARY_DIR}/box3d")
-add_library(ymir_box3d SHARED ymir_box3d.c)
+add_library(ymir_box3d SHARED ymir_box3d_soa.c ymir_particles.c)
target_link_libraries(ymir_box3d PRIVATE box3d::box3d)
target_include_directories(ymir_box3d PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/box3d/include")
target_compile_features(ymir_box3d PRIVATE c_std_17)
@@ -21,6 +21,14 @@ endif()
set_target_properties(ymir_box3d PROPERTIES
C_VISIBILITY_PRESET hidden
- RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
- LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$"
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$"
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")
+if(MINGW)
+ # MinGW would emit libymir_box3d.dll; the managed side loads ymir_box3d.dll.
+ set_property(TARGET ymir_box3d PROPERTY PREFIX "")
+endif()
+
+# The particle solver's bytes must not depend on whether the compiler fuses a multiply and an add.
+set_source_files_properties(ymir_particles.c PROPERTIES COMPILE_OPTIONS
+ "$,/fp:precise,-ffp-contract=off>")
diff --git a/native/Ymir.Box3D/ymir_box3d.c b/native/Ymir.Box3D/ymir_box3d.c
deleted file mode 100644
index e42ff7c..0000000
--- a/native/Ymir.Box3D/ymir_box3d.c
+++ /dev/null
@@ -1,1773 +0,0 @@
-#include
-#include
-#include
-#include
-#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
-{
- int hit;
- float distance;
- float normal_x;
- float normal_y;
-} ymir_box3d_overlap_result;
-
-typedef struct ymir_box3d_cast_result
-{
- int hit;
- float fraction;
- float point_x;
- float point_y;
- float normal_x;
- float normal_y;
-} ymir_box3d_cast_result;
-
-typedef struct ymir_box3d_body_input
-{
- float position_x;
- float position_y;
- float velocity_x;
- float velocity_y;
- float radius;
- float mass;
- float restitution;
- int is_static;
-} ymir_box3d_body_input;
-
-typedef struct ymir_box3d_body_output
-{
- float position_x;
- float position_y;
- float velocity_x;
- float velocity_y;
- float angular_velocity;
-} ymir_box3d_body_output;
-
-typedef struct ymir_box3d_pair_step_result
-{
- ymir_box3d_body_output body_a;
- ymir_box3d_body_output body_b;
- int begin_contact_count;
- int end_contact_count;
- int hit_contact_count;
-} ymir_box3d_pair_step_result;
-
-typedef struct ymir_box3d_torque_result
-{
- float angular_velocity_after_applied_step;
- 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;
- uint64_t collision_category_bits;
- uint64_t collision_mask_bits;
- 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;
- 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
-{
- 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 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;
- 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;
- 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;
-
-typedef struct ymir_box3d_session
-{
- b3WorldId world_id;
- 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");
-_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");
-_Static_assert(sizeof(ymir_box3d_session_contact_event_output) == 64, "Unexpected Ymir Box3D contact event 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 && !(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)
-{
- 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 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;
- 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 = 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);
- 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;
- body_def.isBullet = input->is_bullet != 0;
- 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.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};
- 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,
- .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;
-}
-
-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) ||
- 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, 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)
- {
- 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->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;
-}
-
-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 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,
- 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();
- body_def.type = input->is_static != 0 ? b3_staticBody : b3_dynamicBody;
- body_def.position = ymir_vec(input->position_x, input->position_y);
- body_def.linearVelocity = ymir_vec(input->velocity_x, input->velocity_y);
- body_def.motionLocks.linearY = true;
- body_def.motionLocks.angularX = true;
- body_def.motionLocks.angularZ = true;
- body_def.enableSleep = false;
- b3BodyId body_id = b3CreateBody(world_id, &body_def);
-
- b3ShapeDef shape_def = b3DefaultShapeDef();
- if (input->is_static == 0)
- {
- float volume = 4.0f / 3.0f * B3_PI * input->radius * input->radius * input->radius;
- shape_def.density = input->mass / volume;
- }
- 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};
- b3CreateSphereShape(body_id, &shape_def, &sphere);
- return body_id;
-}
-
-static ymir_box3d_body_output ymir_read_body(b3BodyId body_id)
-{
- b3Pos position = b3Body_GetPosition(body_id);
- b3Vec3 velocity = b3Body_GetLinearVelocity(body_id);
- b3Vec3 angular_velocity = b3Body_GetAngularVelocity(body_id);
- return (ymir_box3d_body_output){
- .position_x = position.x,
- .position_y = position.z,
- .velocity_x = velocity.x,
- .velocity_y = velocity.z,
- .angular_velocity = angular_velocity.y,
- };
-}
-
-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;
- *minor = version.minor;
- *revision = version.revision;
- return b3IsDoublePrecision() ? 1 : 0;
-}
-
-YMIR_EXPORT ymir_box3d_overlap_result YMIR_CALL ymir_box3d_overlap_spheres(
- float query_x,
- float query_y,
- float query_radius,
- float body_x,
- float body_y,
- float body_radius)
-{
- b3Sphere body = {ymir_vec(body_x, body_y), body_radius};
- b3Vec3 query_point = ymir_vec(query_x, query_y);
- b3ShapeProxy query = {&query_point, 1, query_radius};
-
- b3DistanceInput input = {
- .proxyA = (b3ShapeProxy){&body.center, 1, body.radius},
- .proxyB = query,
- .transform = b3Transform_identity,
- .useRadii = true,
- };
- b3SimplexCache cache = {0};
- b3DistanceOutput distance = b3ShapeDistance(&input, &cache, NULL, 0);
-
- return (ymir_box3d_overlap_result){
- .hit = b3OverlapSphere(&body, b3Transform_identity, &query) ? 1 : 0,
- .distance = distance.distance,
- .normal_x = distance.normal.x,
- .normal_y = distance.normal.z,
- };
-}
-
-YMIR_EXPORT ymir_box3d_overlap_result YMIR_CALL ymir_box3d_overlap_capsule_sphere(
- float start_x,
- float start_y,
- float end_x,
- float end_y,
- float capsule_radius,
- float body_x,
- float body_y,
- float body_radius)
-{
- b3Sphere body = {ymir_vec(body_x, body_y), body_radius};
- b3Vec3 capsule_points[2] = {ymir_vec(start_x, start_y), ymir_vec(end_x, end_y)};
- b3ShapeProxy capsule = {capsule_points, 2, capsule_radius};
-
- b3DistanceInput input = {
- .proxyA = (b3ShapeProxy){&body.center, 1, body.radius},
- .proxyB = capsule,
- .transform = b3Transform_identity,
- .useRadii = true,
- };
- b3SimplexCache cache = {0};
- b3DistanceOutput distance = b3ShapeDistance(&input, &cache, NULL, 0);
-
- return (ymir_box3d_overlap_result){
- .hit = b3OverlapSphere(&body, b3Transform_identity, &capsule) ? 1 : 0,
- .distance = distance.distance,
- .normal_x = distance.normal.x,
- .normal_y = distance.normal.z,
- };
-}
-
-YMIR_EXPORT ymir_box3d_cast_result YMIR_CALL ymir_box3d_cast_sphere(
- float origin_x,
- float origin_y,
- float translation_x,
- float translation_y,
- float query_radius,
- float body_x,
- float body_y,
- float body_radius,
- int can_encroach)
-{
- b3Sphere body = {ymir_vec(body_x, body_y), body_radius};
- b3Vec3 query_point = ymir_vec(origin_x, origin_y);
- b3ShapeCastInput input = {
- .proxy = (b3ShapeProxy){&query_point, 1, query_radius},
- .translation = ymir_vec(translation_x, translation_y),
- .maxFraction = 1.0f,
- .canEncroach = can_encroach != 0,
- };
- b3CastOutput output = b3ShapeCastSphere(&body, &input);
-
- return (ymir_box3d_cast_result){
- .hit = output.hit ? 1 : 0,
- .fraction = output.fraction,
- .point_x = output.point.x,
- .point_y = output.point.z,
- .normal_x = output.normal.x,
- .normal_y = output.normal.z,
- };
-}
-
-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,
- int sub_step_count,
- float restitution_threshold,
- ymir_box3d_pair_step_result* result)
-{
- b3WorldDef world_def = b3DefaultWorldDef();
- world_def.gravity = b3Vec3_zero;
- world_def.enableSleep = false;
- world_def.restitutionThreshold = restitution_threshold;
- b3WorldId world_id = b3CreateWorld(&world_def);
-
- b3BodyId body_a = ymir_create_body(world_id, body_a_input);
- b3BodyId body_b = ymir_create_body(world_id, body_b_input);
- b3World_Step(world_id, time_step, sub_step_count);
-
- b3ContactEvents events = b3World_GetContactEvents(world_id);
- result->body_a = ymir_read_body(body_a);
- result->body_b = ymir_read_body(body_b);
- result->begin_contact_count = events.beginCount;
- result->end_contact_count = events.endCount;
- result->hit_contact_count = events.hitCount;
-
- b3DestroyWorld(world_id);
-}
-
-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;
- world_def.enableSleep = false;
- b3WorldId world_id = b3CreateWorld(&world_def);
-
- ymir_box3d_body_input input = {
- .radius = 1.0f,
- .mass = 1.0f,
- .is_static = 0,
- };
- b3BodyId body_id = ymir_create_body(world_id, &input);
- b3Body_ApplyTorque(body_id, (b3Vec3){0.0f, torque, 0.0f}, true);
- b3World_Step(world_id, time_step, sub_step_count);
- float after_applied_step = b3Body_GetAngularVelocity(body_id).y;
-
- b3World_Step(world_id, time_step, sub_step_count);
- float after_unforced_step = b3Body_GetAngularVelocity(body_id).y;
- b3DestroyWorld(world_id);
-
- return (ymir_box3d_torque_result){after_applied_step, after_unforced_step};
-}
-
-YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_get_abi_version(void)
-{
- return 5;
-}
-
-YMIR_EXPORT const char* YMIR_CALL ymir_box3d_get_build_id(void)
-{
- return "box3d-8441b4a06d6d09dcfb0b0f704df4d847d1437b92-abi5-f32";
-}
-
-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_event_output_size)
-{
- 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;
- }
-
- *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);
- *contact_event_output_size = (uint32_t)sizeof(ymir_box3d_session_contact_event_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->contact_events);
- free(session->pending_events);
- free(session->retired_shapes);
- free(session->drained_events);
- 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_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,
- uint32_t is_kinematic)
-{
- if (session == NULL || !ymir_is_finite(radius) || radius <= 0.0f || !ymir_is_finite(mass) ||
- (is_static == 0 && mass <= 0.0f) || (is_static != 0 && is_kinematic != 0) ||
- !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) || 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 : (is_kinematic != 0 ? b3_kinematicBody : 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;
- body->is_kinematic = is_kinematic != 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,
- 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;
- }
- }
-
- 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;
- if (body->is_static || body->is_kinematic)
- {
- 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;
-
- if (!body->participates_in_fields)
- {
- continue;
- }
-
- 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);
- session->drained_event_count = 0;
- 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;
- }
-
- 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;
-}
-
-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);
-}
-
-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/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c
new file mode 100644
index 0000000..dbd614d
--- /dev/null
+++ b/native/Ymir.Box3D/ymir_box3d_soa.c
@@ -0,0 +1,2424 @@
+// Headless 3D Box3D world with a structure-of-arrays state view. Box3D owns every physical
+// decision (integration, collision, contact, joints); this file creates bodies and joints, applies
+// the caller's force and torque lanes, steps the world and copies each body's and joint's state into
+// contiguous lanes once per step. A caller reads the state lanes and writes the force/torque lanes in
+// place through `ymir_box3d_soa_get_view`: the pointers are stable for the world's whole life
+// (capacities are fixed at creation) and the state lanes change only inside `ymir_box3d_soa_step`.
+//
+// See docs/soa-world.md.
+
+#include
+#include
+#include
+#include
+#include
+
+#include "ymir_particles.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+// Process-wide lock around Box3D world creation and destruction. b3CreateWorld and b3DestroyWorld scan
+// and rewrite the global world pool (b3_worlds) with no synchronization, so two threads creating worlds
+// at once can claim the same slot and corrupt it. Stepping and every other call touch only the caller's
+// own world and stay unlocked. A single world is still not thread-safe.
+#if defined(_WIN32)
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include
+static SRWLOCK ymir_world_pool_lock = SRWLOCK_INIT;
+#define YMIR_WORLD_POOL_LOCK() AcquireSRWLockExclusive(&ymir_world_pool_lock)
+#define YMIR_WORLD_POOL_UNLOCK() ReleaseSRWLockExclusive(&ymir_world_pool_lock)
+#else
+#include
+static pthread_mutex_t ymir_world_pool_lock = PTHREAD_MUTEX_INITIALIZER;
+#define YMIR_WORLD_POOL_LOCK() pthread_mutex_lock(&ymir_world_pool_lock)
+#define YMIR_WORLD_POOL_UNLOCK() pthread_mutex_unlock(&ymir_world_pool_lock)
+#endif
+
+static b3WorldId ymir_create_world_locked(const b3WorldDef* def)
+{
+ YMIR_WORLD_POOL_LOCK();
+ b3WorldId world_id = b3CreateWorld(def);
+ YMIR_WORLD_POOL_UNLOCK();
+ return world_id;
+}
+
+static void ymir_destroy_world_locked(b3WorldId world_id)
+{
+ YMIR_WORLD_POOL_LOCK();
+ b3DestroyWorld(world_id);
+ YMIR_WORLD_POOL_UNLOCK();
+}
+
+#if defined(_WIN32)
+#define YMIR_EXPORT __declspec(dllexport)
+#define YMIR_CALL __cdecl
+#else
+#define YMIR_EXPORT __attribute__((visibility("default")))
+#define YMIR_CALL
+#endif
+
+enum
+{
+ YMIR_SOA_OK = 0,
+ YMIR_SOA_INVALID_ARGUMENT = 1,
+ YMIR_SOA_DUPLICATE_ID = 2,
+ YMIR_SOA_FULL = 3,
+ YMIR_SOA_OUT_OF_MEMORY = 4,
+ YMIR_SOA_INTERNAL_ERROR = 5,
+ YMIR_SOA_REFERENCED = 6 // remove_body refused: a live attachment or sensor names the body (remove those first)
+};
+
+enum
+{
+ YMIR_SOA_KIND_SPHERE = 0,
+ YMIR_SOA_KIND_STATIC_BOX = 1,
+ YMIR_SOA_KIND_CAPSULE = 2,
+ YMIR_SOA_KIND_BOX = 3,
+ YMIR_SOA_KIND_ANCHOR = 4,
+ YMIR_SOA_KIND_REMOVED = 5, // a removed body's lane (remove_body): never accepted by add_body
+ YMIR_SOA_KIND_STATIC_HEIGHTFIELD = 6,
+ YMIR_SOA_KIND_STATIC_MESH = 7
+};
+
+enum
+{
+ YMIR_SOA_JOINT_REVOLUTE = 0,
+ YMIR_SOA_JOINT_SPHERICAL = 1,
+ YMIR_SOA_JOINT_WELD = 2,
+ YMIR_SOA_JOINT_MOTOR = 3,
+ YMIR_SOA_JOINT_REMOVED = 4 // a retired joint's lane (destroy_joint): never accepted by add_joint
+};
+
+#define YMIR_SOA_ABI_VERSION 21u
+
+// A body to create. `size` by kind: sphere {radius}, capsule {radius, half_length} (segment along
+// local Y), box and static box {half_x, half_y, half_z}. `parent` is the lane index of an earlier body
+// or -1; `limb` is the caller's label. Neither is used by Box3D: they are lanes for the consumer.
+// An anchor (kind 4) is a kinematic body with no shape: it is never hit and never collides, and size,
+// density, friction, restitution, rolling resistance and material are ignored. Its pose is set with
+// `ymir_box3d_soa_set_anchor_target`; the force and torque lanes never move it.
+typedef struct ymir_box3d_soa_body_desc
+{
+ uint64_t stable_id;
+ uint32_t kind;
+ int32_t parent;
+ int32_t limb;
+ uint32_t reserved;
+ float position[3];
+ float rotation[4]; // x y z w, unit
+ float velocity[3];
+ float size[3];
+ float density;
+ float friction;
+ float restitution;
+ float rolling_resistance; // Box3D's surface rolling resistance, >= 0; spheres and capsules roll without it
+ uint64_t material_id; // the caller's surface material id: set as the shape's user material, echoed on hit facts
+} ymir_box3d_soa_body_desc;
+
+// A joint between two bodies, given in world space at creation: the frame has its origin at `anchor`
+// and its z axis along `axis`; the creation pose is the joint's zero. Revolute turns about that z axis.
+// `enable_limit` applies `lower`/`upper` (revolute angle, spherical twist), and `cone_angle` (spherical
+// swing) when it is positive. Weld ignores limits.
+// A motor joint (kind 3) is a pair of position springs, no velocity target: the linear spring pulls body B's
+// frame origin onto body A's (so B's anchor point onto A's), the angular spring pulls B's frame orientation onto
+// A's. `*_hertz` 0 turns that spring off; `max_force` (N) and `max_torque` (N m) bound what it may apply, so a
+// weak grab hangs below its target. All six are finite and >= 0 and are ignored by the other kinds.
+// `ymir_box3d_soa_destroy_joint` releases a joint of any kind: its lane becomes a tombstone (kind REMOVED = 4, bodies -1,
+// every lane 0) that add_joint may reuse only once a step has completed since.
+// `force_threshold` (N) and `torque_threshold` (N m) make the joint report an Overload fact in a step where its load reaches
+// them; +inf (the usual value) is never, NaN or a negative value is refused. A threshold is a sensor: Ymir never removes a
+// joint on it.
+typedef struct ymir_box3d_soa_joint_desc
+{
+ uint32_t kind;
+ int32_t body_a;
+ int32_t body_b;
+ uint32_t enable_limit;
+ float anchor[3];
+ float axis[3];
+ float lower;
+ float upper;
+ float cone_angle;
+ float linear_hertz;
+ float linear_damping;
+ float max_force;
+ float angular_hertz;
+ float angular_damping;
+ float max_torque;
+ float force_threshold;
+ float torque_threshold;
+} ymir_box3d_soa_joint_desc;
+
+// Pointers first and in lane order, so the layout is the same on every 64-bit target. Lanes the caller
+// writes (force and torque per body) are mutable; every other lane is read-only to the caller.
+typedef struct ymir_box3d_soa_view
+{
+ uint32_t abi_version;
+ int32_t count;
+ int32_t capacity;
+ int32_t joint_count;
+ int32_t joint_capacity;
+ uint32_t reserved;
+ uint64_t step_count;
+ // Particle and constraint high-water counts and capacities (all 0 for a world created without capacities).
+ int32_t particle_count;
+ int32_t particle_capacity;
+ // Kernel neighbours past a fluid particle's list (96) in the last step, summed over substeps: 0 means the correction and XSPH saw every pair.
+ int32_t fluid_neighbour_overflow;
+ int32_t distance_count;
+ int32_t distance_capacity;
+ int32_t bend_count;
+ int32_t bend_capacity;
+ int32_t attachment_count;
+ int32_t attachment_capacity;
+ int32_t tether_count;
+ int32_t tether_capacity;
+ int32_t material_capacity;
+ int32_t wet_count; // wet patch lanes: the high-water mark
+ int32_t sensor_count; // liquid sensor lanes: the high-water mark
+ // bodies
+ const uint64_t* stable_id;
+ const uint32_t* kind;
+ const int32_t* parent;
+ const int32_t* limb;
+ // The body's shape size, read-only, same per-kind meaning as the body desc size: sphere {radius},
+ // capsule {radius, half_length}, box and static box {half_x, half_y, half_z}; unused components are 0.
+ const float* size_0;
+ const float* size_1;
+ const float* size_2;
+ const float* position_x;
+ const float* position_y;
+ const float* position_z;
+ const float* rotation_x;
+ const float* rotation_y;
+ const float* rotation_z;
+ const float* rotation_w;
+ const float* velocity_x;
+ const float* velocity_y;
+ const float* velocity_z;
+ const float* angular_velocity_x;
+ const float* angular_velocity_y;
+ const float* angular_velocity_z;
+ float* force_x;
+ float* force_y;
+ float* force_z;
+ float* torque_x;
+ float* torque_y;
+ float* torque_z;
+ // joints
+ const uint32_t* joint_kind;
+ const int32_t* joint_body_a;
+ const int32_t* joint_body_b;
+ const float* joint_angle;
+ const float* joint_frame_x;
+ const float* joint_frame_y;
+ const float* joint_frame_z;
+ const float* joint_frame_w;
+ const float* joint_rotation_x;
+ const float* joint_rotation_y;
+ const float* joint_rotation_z;
+ const float* joint_rotation_w;
+ const float* joint_angular_velocity_x;
+ const float* joint_angular_velocity_y;
+ const float* joint_angular_velocity_z;
+ // World position of the joint frame origin on body A (the joint anchor), refreshed every step like joint_frame.
+ const float* joint_origin_x;
+ const float* joint_origin_y;
+ const float* joint_origin_z;
+ // The load the joint carries, world frame, from Box3D's constraint solution at the end of the last step (N and N m); a free lane reads 0. Sensors: a joint hanging a mass m at rest reads m g.
+ const float* joint_constraint_force_x;
+ const float* joint_constraint_force_y;
+ const float* joint_constraint_force_z;
+ const float* joint_constraint_torque_x;
+ const float* joint_constraint_torque_y;
+ const float* joint_constraint_torque_z;
+ // Contact lanes, read-only, refreshed every step. contact_impulse is N s: the sum over the body's touching
+ // contact manifold points of stepNormalImpulse, the normal impulse the contacts delivered to the body over
+ // the whole step (0 for a body touching nothing). Exact, normal channel only: Box3D exposes no tangent
+ // impulse. A resting load is contact_impulse / dt.
+ // contact_count is the number of touching contacts. material_id is the body's desc material_id.
+ const float* contact_impulse;
+ const int32_t* contact_count;
+ const uint64_t* material_id;
+ // mass is kg from Box3D at create (b3Body_GetMass): 0 for static, kinematic and anchor bodies and for removed lanes.
+ const float* mass;
+ // Per body lane: counts the removals of that lane. remove_body refuses a handle whose generation is not the lane's, so a stale
+ // removal never takes a later body in a reused lane. A removed body's lane reads kind REMOVED and every other lane 0 (stable_id 0, parent -1).
+ const uint32_t* body_generation;
+ // Per joint slot: counts the destroys of that slot. A grab's handle is (lane, generation); destroy_joint refuses
+ // a handle whose generation is not the slot's, so a stale release cannot destroy a later grab in a reused slot.
+ const uint32_t* joint_generation;
+ // The impulse (N s, world) the particle phase delivered to the body over the last step, 0 for a body it did not
+ // touch. Notification only: Box3D already applied it.
+ const float* particle_impulse_x;
+ const float* particle_impulse_y;
+ const float* particle_impulse_z;
+ // Particle lanes (read-only; only `step` and the particle and constraint commands change them), indexed by lane
+ // up to the set's count (a high-water mark). A dead lane reads live 0 and every other lane 0 (the support lanes -1) except generation
+ // and removed_at. Handles are (lane, generation); a lane is reused once a step has passed since its removal.
+ const float* particle_x;
+ const float* particle_y;
+ const float* particle_z;
+ const float* particle_vx;
+ const float* particle_vy;
+ const float* particle_vz;
+ const float* particle_radius;
+ const float* particle_inv_mass;
+ const float* particle_rest_x;
+ const float* particle_rest_y;
+ const float* particle_rest_z;
+ const uint32_t* particle_phase;
+ const uint32_t* particle_material;
+ const uint32_t* particle_live;
+ const uint32_t* particle_generation;
+ const uint64_t* particle_removed_at;
+ // Derived by rederive_topology: the lowest lane of the particle's component of distance-connected particles.
+ const int32_t* particle_component;
+ // A fluid particle's number density over its rest density in the last substep it ran (1 is at rest), 0 for a solid: a sensor.
+ const float* particle_density;
+ // Distance lanes. tension (N) is the load the constraint carries, mean over the substeps: a sensor, Ymir never
+ // removes a constraint on it.
+ const int32_t* distance_a;
+ const int32_t* distance_b;
+ const float* distance_rest;
+ const float* distance_compliance;
+ const float* distance_tension;
+ const uint32_t* distance_live;
+ const uint32_t* distance_generation;
+ const uint64_t* distance_removed_at;
+ // Bend lanes: two distance lanes and the three particles (b shared); rest and limit are offsets of b from the
+ // centroid of a, b, c (limit < 0 = no hard limit; compliance < 0 = no soft pass).
+ const int32_t* bend_e1;
+ const int32_t* bend_e2;
+ const int32_t* bend_a;
+ const int32_t* bend_b;
+ const int32_t* bend_c;
+ const float* bend_rest;
+ const float* bend_limit;
+ const float* bend_compliance;
+ const uint32_t* bend_live;
+ const uint32_t* bend_generation;
+ const uint64_t* bend_removed_at;
+ // Attachment lanes. kind 0 body, 1 static, 2 removed (a tombstone). force (N) is what the attachment exerts
+ // on its particles, mean over the substeps, tether load included: a sensor.
+ const uint32_t* attachment_kind;
+ const uint32_t* attachment_flags;
+ const uint32_t* attachment_generation;
+ const int32_t* attachment_particle;
+ const int32_t* attachment_body;
+ const float* attachment_point_x;
+ const float* attachment_point_y;
+ const float* attachment_point_z;
+ const float* attachment_compliance;
+ const float* attachment_force_x;
+ const float* attachment_force_y;
+ const float* attachment_force_z;
+ const uint64_t* attachment_removed_at;
+ // Tether lanes, indexed up to tether_count: derived, never written by a command.
+ const int32_t* tether_att;
+ const int32_t* tether_particle;
+ const int32_t* tether_parent;
+ const int32_t* tether_edge;
+ const int32_t* tether_other;
+ const float* tether_bound;
+ // Material table, indexed up to material_capacity.
+ const float* material_friction;
+ const uint64_t* material_id_lane;
+ const float* material_viscosity;
+ // A fluid particle's support in the last substep it ran: the highest body lane it touched, and the first solid particle lane its
+ // row listed touching it; -1 for none, and -1 for a solid or free lane. Contact, not rest: the caller judges speed. Notification only.
+ const int32_t* particle_support_body;
+ const int32_t* particle_support_particle;
+ // Wet patches, indexed up to wet_count: settled liquid on a body (point in the body's frame) or a solid particle (point 0); one support is -1.
+ // Written by settle, remove and destroy only, never by the step. body_wet_volume is per body lane, derived from the live patches at command time.
+ const int32_t* wet_body;
+ const int32_t* wet_particle;
+ const float* wet_x;
+ const float* wet_y;
+ const float* wet_z;
+ const float* wet_radius;
+ const float* wet_patch_volume;
+ const uint32_t* wet_material;
+ const uint32_t* wet_live;
+ const uint32_t* wet_generation;
+ const uint64_t* wet_removed_at;
+ const float* body_wet_volume;
+ const float* material_wet_friction;
+ // Liquid sensors, indexed up to sensor_count: a sphere (point in the body's frame, radius m) fixed in body lane sensor_body; a free lane reads live 0, body -1 and 0 elsewhere.
+ // liquid_volume (m^3) is the sum of (2 r)^3 over the live fluid particles whose centre was inside it at the end of the last step, 0 with no liquid; wet_volume (m^3) is the sum of the
+ // volumes of the live wet patches whose centre was inside it then, on any body or solid particle. End-of-step values: a Settle, destroy or remove between steps shows at the next step.
+ // Sensors: the step writes them and nothing reads them back.
+ const int32_t* sensor_body;
+ const float* sensor_x;
+ const float* sensor_y;
+ const float* sensor_z;
+ const float* sensor_radius;
+ const float* sensor_liquid_volume;
+ const float* sensor_wet_volume;
+ const uint32_t* sensor_live;
+ const uint32_t* sensor_generation;
+ const uint64_t* sensor_removed_at;
+ // Particles: 1 for a pinned (dormant) particle, 0 else; notification only. A pinned particle's pos and vel are stale: draw it from its anchor attachment.
+ const uint32_t* particle_pinned;
+ // Particles: the attachment lane a pinned particle is drawn from (held from the command that pinned it), -1 for none; derived, read only.
+ const int32_t* particle_anchor;
+} ymir_box3d_soa_view;
+
+// A begin or end of touch between two bodies: their lane indices and the shapes' stable ids.
+typedef struct ymir_box3d_soa_touch_fact
+{
+ int32_t lane_a;
+ int32_t lane_b;
+ uint64_t stable_id_a;
+ uint64_t stable_id_b;
+} ymir_box3d_soa_touch_fact;
+
+// A hit: a touch approaching faster than the world's hit threshold. `normal` points from A to B.
+typedef struct ymir_box3d_soa_hit_fact
+{
+ int32_t lane_a;
+ int32_t lane_b;
+ uint64_t stable_id_a;
+ uint64_t stable_id_b;
+ float point[3];
+ float normal[3];
+ float approach_speed;
+ // The normal impulse (N s) the pair's contact delivered over the whole step: the sum of stepNormalImpulse
+ // over the manifold of the two shapes, read after the step. Exact, normal channel only.
+ float impulse;
+ uint64_t material_a;
+ uint64_t material_b;
+} ymir_box3d_soa_hit_fact;
+
+// A joint whose load reached its threshold in the step just taken, with the load Box3D reports for it after the step. The joint stays: Ymir never removes on a threshold.
+typedef struct ymir_box3d_soa_overload_fact
+{
+ int32_t joint_lane;
+ uint32_t joint_generation;
+ float force[3];
+ float torque[3];
+} ymir_box3d_soa_overload_fact;
+
+// A body removed by remove_body between steps, published by the next step. `generation` is the dead handle's; `wet_patches` and `wet_volume` (m^3) are what its removal took with it.
+typedef struct ymir_box3d_soa_body_removed_fact
+{
+ int32_t lane;
+ uint32_t generation;
+ uint64_t stable_id;
+ uint32_t wet_patches;
+ float wet_volume;
+} ymir_box3d_soa_body_removed_fact;
+
+// A joint retired by destroy_joint (with_body 0) or by remove_body of a body it named (with_body 1), published by the next step: the dead handle's lane and
+// generation and the two bodies it joined.
+typedef struct ymir_box3d_soa_joint_removed_fact
+{
+ int32_t lane;
+ uint32_t generation;
+ int32_t body_a;
+ int32_t body_b;
+ uint32_t with_body;
+} ymir_box3d_soa_joint_removed_fact;
+
+// A removed body's shape, kept until the step that reports its end-touch events has been collected: the shape id is dead, the table names it.
+typedef struct ymir_soa_retired_shape
+{
+ b3ShapeId shape;
+ int32_t lane;
+ uint64_t stable_id;
+} ymir_soa_retired_shape;
+
+// What Box3D reported for the step just taken, in Box3D's event order. The arrays are fixed for the
+// world's life and rewritten by every step: facts last one step. `dropped` counts facts past
+// `fact_capacity` that this step could not keep.
+typedef struct ymir_box3d_soa_facts
+{
+ uint32_t begin_count;
+ uint32_t end_count;
+ uint32_t hit_count;
+ uint32_t fact_capacity;
+ uint32_t begin_dropped;
+ uint32_t end_dropped;
+ uint32_t hit_dropped;
+ uint32_t reserved;
+ const ymir_box3d_soa_touch_fact* begin;
+ const ymir_box3d_soa_touch_fact* end;
+ const ymir_box3d_soa_hit_fact* hit;
+ const ymir_box3d_soa_overload_fact* overload; // at most joint_capacity: Box3D reports a joint at most once per step
+ uint32_t overload_count;
+ uint32_t reserved2;
+ // Removals made since the last step, in removal order, published by this step (at most one per lane, so these never overflow).
+ uint32_t body_removed_count;
+ uint32_t joint_removed_count;
+ const ymir_box3d_soa_body_removed_fact* body_removed;
+ const ymir_box3d_soa_joint_removed_fact* joint_removed;
+ // The step's touching pairs, each once, lane_a < lane_b, in lane then Box3D contact order: the same per-body contact read that fills
+ // the contact lanes. `touching_dropped` counts pairs past `fact_capacity`.
+ uint32_t touching_count;
+ uint32_t touching_dropped;
+ const ymir_box3d_soa_touch_fact* touching;
+} ymir_box3d_soa_facts;
+
+// The closest hit of a ray. `hit` is 0 for a miss and every other field is then 0. `lane` and `stable_id` name
+// the body and shape hit; `fraction` is of the ray's translation.
+typedef struct ymir_box3d_soa_ray_hit
+{
+ int32_t hit;
+ int32_t lane;
+ uint64_t stable_id;
+ float point[3];
+ float normal[3];
+ float fraction;
+ uint32_t reserved;
+} ymir_box3d_soa_ray_hit;
+
+#define YMIR_SOA_STATE_LANES 13
+#define YMIR_SOA_WRITE_LANES 6
+#define YMIR_SOA_CONTACT_IMPULSE_LANE (YMIR_SOA_STATE_LANES + YMIR_SOA_WRITE_LANES)
+#define YMIR_SOA_PARTICLE_IMPULSE_LANE (YMIR_SOA_CONTACT_IMPULSE_LANE + 1) // 3 lanes: x y z
+#define YMIR_SOA_BODY_FLOAT_LANES (YMIR_SOA_PARTICLE_IMPULSE_LANE + 3)
+#define YMIR_SOA_JOINT_FLOAT_LANES 21
+
+typedef struct ymir_box3d_soa_world
+{
+ b3WorldId world_id;
+ int32_t count;
+ int32_t capacity;
+ int32_t joint_count;
+ int32_t joint_capacity;
+ uint64_t step_count;
+ b3BodyId* bodies;
+ b3HeightFieldData** heightfields; // `capacity` entries: owned per slot for YMIR_SOA_KIND_STATIC_HEIGHTFIELD
+ b3MeshData** meshes; // `capacity` entries: owned per slot for YMIR_SOA_KIND_STATIC_MESH
+ uint64_t* stable_id;
+ uint32_t* kind;
+ int32_t* parent;
+ int32_t* limb;
+ int32_t* contact_count;
+ uint64_t* material_id;
+ float* mass;
+ uint32_t* body_generation;
+ uint64_t* body_removed_at; // step_count when the lane was removed; reusable once a step has passed
+ float* size; // 3 arrays of `capacity` floats, lane-major; written once in add_body
+ float* lanes; // YMIR_SOA_BODY_FLOAT_LANES arrays of `capacity` floats, lane-major
+ b3JointId* joints;
+ uint32_t* joint_kind;
+ uint32_t* joint_generation;
+ uint64_t* joint_removed_at; // step_count when the slot was destroyed; reusable once a step has passed
+ int32_t* joint_body_a;
+ int32_t* joint_body_b;
+ b3Quat* joint_local_a; // joint frame in body A, kept so the state is read without asking Box3D
+ b3Vec3* joint_local_origin_a; // the frame origin in body A, kept for the same reason
+ b3Quat* joint_local_b;
+ float* joint_lanes; // YMIR_SOA_JOINT_FLOAT_LANES arrays of `joint_capacity` floats, lane-major
+ uint32_t fact_capacity;
+ ymir_box3d_soa_facts facts; // counts and dropped counters live here; the arrays below back its pointers
+ ymir_box3d_soa_touch_fact* begin_facts;
+ ymir_box3d_soa_touch_fact* end_facts;
+ ymir_box3d_soa_touch_fact* touching_facts;
+ ymir_box3d_soa_hit_fact* hit_facts;
+ ymir_box3d_soa_overload_fact* overload_facts; // `joint_capacity` entries
+ ymir_box3d_soa_body_removed_fact* body_removed_facts; // `capacity` entries: what the last step published
+ ymir_box3d_soa_body_removed_fact* body_removed_pending; // removals since the last step
+ ymir_box3d_soa_joint_removed_fact* joint_removed_facts; // `joint_capacity` entries
+ ymir_box3d_soa_joint_removed_fact* joint_removed_pending;
+ ymir_soa_retired_shape* retired_shapes; // `capacity` entries
+ uint32_t body_removed_pending_count;
+ uint32_t joint_removed_pending_count;
+ uint32_t retired_count;
+ b3ContactData* contact_scratch; // `capacity` entries: a body has one shape, so at most capacity - 1 contacts
+ b3Vec3 gravity;
+ ymir_particles* particles; // NULL when created without particle capacity: the step then runs exactly as ABI 8
+} ymir_box3d_soa_world;
+
+static void ymir_soa_particle_substep(b3WorldId world_id, int sub_step, float h, void* context);
+
+static float* ymir_soa_lane(const ymir_box3d_soa_world* world, int lane)
+{
+ return world->lanes + (size_t)lane * (size_t)world->capacity;
+}
+
+static float* ymir_soa_joint_lane(const ymir_box3d_soa_world* world, int lane)
+{
+ return world->joint_lanes + (size_t)lane * (size_t)world->joint_capacity;
+}
+
+static int ymir_soa_finite(float v)
+{
+ return isfinite(v);
+}
+
+// A joint threshold: finite and >= 0, or +inf (never). Box3D asserts on inf, so +inf reaches it as FLT_MAX, its "never".
+static int ymir_soa_threshold_ok(float v)
+{
+ return !isnan(v) && v >= 0.0f;
+}
+
+static float ymir_soa_threshold(float v)
+{
+ return isinf(v) ? FLT_MAX : v;
+}
+
+static int ymir_soa_finite3(const float* v)
+{
+ return ymir_soa_finite(v[0]) && ymir_soa_finite(v[1]) && ymir_soa_finite(v[2]);
+}
+
+static int ymir_soa_is_anchor(uint32_t kind)
+{
+ return kind == YMIR_SOA_KIND_ANCHOR;
+}
+
+static int ymir_soa_is_dynamic(uint32_t kind)
+{
+ return kind == YMIR_SOA_KIND_SPHERE || kind == YMIR_SOA_KIND_CAPSULE || kind == YMIR_SOA_KIND_BOX;
+}
+
+static void ymir_soa_refresh(ymir_box3d_soa_world* world, int index)
+{
+ b3BodyId body = world->bodies[index];
+ b3Pos p = b3Body_GetPosition(body);
+ b3Quat q = b3Body_GetRotation(body);
+ b3Vec3 v = b3Body_GetLinearVelocity(body);
+ b3Vec3 w = b3Body_GetAngularVelocity(body);
+ const float values[YMIR_SOA_STATE_LANES] = {
+ p.x, p.y, p.z, q.v.x, q.v.y, q.v.z, q.s, v.x, v.y, v.z, w.x, w.y, w.z};
+ for (int lane = 0; lane < YMIR_SOA_STATE_LANES; ++lane)
+ {
+ ymir_soa_lane(world, lane)[index] = values[lane];
+ }
+}
+
+static b3Transform ymir_soa_body_transform(b3BodyId body)
+{
+ b3Pos p = b3Body_GetPosition(body);
+ b3Transform t = {{p.x, p.y, p.z}, b3Body_GetRotation(body)};
+ return t;
+}
+
+// Joint state from the bodies: the world orientation of frame A, frame B relative to frame A (as a
+// quaternion with w >= 0, the shorter arc) and the relative angular velocity in frame A. The angle
+// lane is Box3D's own: the revolute angle or the spherical twist angle, zero for a weld.
+static void ymir_soa_refresh_joint(ymir_box3d_soa_world* world, int j)
+{
+ int a = world->joint_body_a[j];
+ int b = world->joint_body_b[j];
+ b3Quat qa = b3MulQuat(b3Body_GetRotation(world->bodies[a]), world->joint_local_a[j]);
+ b3Vec3 origin = b3TransformPoint(ymir_soa_body_transform(world->bodies[a]), world->joint_local_origin_a[j]);
+ b3Quat qb = b3MulQuat(b3Body_GetRotation(world->bodies[b]), world->joint_local_b[j]);
+ b3Quat rel = b3InvMulQuat(qa, qb);
+ if (rel.s < 0.0f)
+ {
+ rel = b3NegateQuat(rel);
+ }
+ b3Vec3 w = b3InvRotateVector(
+ qa, b3Sub(b3Body_GetAngularVelocity(world->bodies[b]), b3Body_GetAngularVelocity(world->bodies[a])));
+ float angle = 0.0f;
+ if (world->joint_kind[j] == YMIR_SOA_JOINT_REVOLUTE)
+ {
+ angle = b3RevoluteJoint_GetAngle(world->joints[j]);
+ }
+ else if (world->joint_kind[j] == YMIR_SOA_JOINT_SPHERICAL)
+ {
+ angle = b3SphericalJoint_GetTwistAngle(world->joints[j]);
+ }
+ b3Vec3 force = b3Joint_GetConstraintForce(world->joints[j]);
+ b3Vec3 torque = b3Joint_GetConstraintTorque(world->joints[j]);
+ const float values[YMIR_SOA_JOINT_FLOAT_LANES] = {
+ angle, qa.v.x, qa.v.y, qa.v.z, qa.s, rel.v.x, rel.v.y, rel.v.z, rel.s, w.x, w.y, w.z, origin.x, origin.y, origin.z,
+ force.x, force.y, force.z, torque.x, torque.y, torque.z};
+ for (int lane = 0; lane < YMIR_SOA_JOINT_FLOAT_LANES; ++lane)
+ {
+ ymir_soa_joint_lane(world, lane)[j] = values[lane];
+ }
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_abi_version(void)
+{
+ return YMIR_SOA_ABI_VERSION;
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_view_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_view);
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_body_desc_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_body_desc);
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_joint_desc_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_joint_desc);
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_ray_hit_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_ray_hit);
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_touch_fact_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_touch_fact);
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_hit_fact_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_hit_fact);
+}
+
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_facts_size(void)
+{
+ return (uint32_t)sizeof(ymir_box3d_soa_facts);
+}
+
+static void ymir_soa_free(ymir_box3d_soa_world* world)
+{
+ if (world->heightfields != NULL)
+ {
+ for (int i = 0; i < world->capacity; ++i)
+ {
+ if (world->heightfields[i] != NULL)
+ {
+ b3DestroyHeightField(world->heightfields[i]);
+ }
+ }
+ free(world->heightfields);
+ }
+ if (world->meshes != NULL)
+ {
+ for (int i = 0; i < world->capacity; ++i)
+ {
+ if (world->meshes[i] != NULL)
+ {
+ b3DestroyMesh(world->meshes[i]);
+ }
+ }
+ free(world->meshes);
+ }
+ free(world->bodies);
+ free(world->stable_id);
+ free(world->kind);
+ free(world->parent);
+ free(world->limb);
+ free(world->contact_count);
+ free(world->material_id);
+ free(world->mass);
+ free(world->body_generation);
+ free(world->body_removed_at);
+ free(world->size);
+ free(world->lanes);
+ free(world->joints);
+ free(world->joint_kind);
+ free(world->joint_removed_at);
+ free(world->joint_generation);
+ free(world->joint_body_a);
+ free(world->joint_body_b);
+ free(world->joint_local_a);
+ free(world->joint_local_origin_a);
+ free(world->joint_local_b);
+ free(world->joint_lanes);
+ free(world->begin_facts);
+ free(world->end_facts);
+ free(world->touching_facts);
+ free(world->hit_facts);
+ free(world->overload_facts);
+ free(world->body_removed_facts);
+ free(world->body_removed_pending);
+ free(world->joint_removed_facts);
+ free(world->joint_removed_pending);
+ free(world->retired_shapes);
+ free(world->contact_scratch);
+ ymir_particles_free(world->particles);
+ free(world);
+}
+
+// Per-contact friction: a body carries lane + 1 as user data. Patches change only between steps, so the read is race-free; the hook only lowers.
+static float ymir_soa_contact_friction(void* user_a, void* user_b, b3Vec3 point_a, b3Vec3 point_b, float mixed, void* context)
+{
+ const ymir_particles* p = ((const ymir_box3d_soa_world*)context)->particles;
+ float f = ymir_particles_wet_mu(p, (int32_t)((uintptr_t)user_a) - 1, point_a.x, point_a.y, point_a.z, mixed);
+ return ymir_particles_wet_mu(p, (int32_t)((uintptr_t)user_b) - 1, point_b.x, point_b.y, point_b.z, f);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create(
+ int32_t capacity, int32_t joint_capacity, float gravity_x, float gravity_y, float gravity_z,
+ int32_t fact_capacity, float hit_threshold, const ymir_particle_capacities* particle_capacities,
+ ymir_box3d_soa_world** output)
+{
+ if (output == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ *output = NULL;
+ if (capacity <= 0 || joint_capacity < 0 || fact_capacity <= 0 || !ymir_soa_finite(gravity_x) ||
+ !ymir_soa_finite(gravity_y) || !ymir_soa_finite(gravity_z) || !ymir_soa_finite(hit_threshold) ||
+ hit_threshold < 0.0f || (particle_capacities != NULL && (particle_capacities->particles < 0 || particle_capacities->distances < 0 ||
+ particle_capacities->bends < 0 || particle_capacities->attachments < 0 || particle_capacities->tethers < 0 ||
+ particle_capacities->materials < 0 || particle_capacities->fluid < 0 || particle_capacities->sensors < 0)))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+
+ ymir_box3d_soa_world* world = (ymir_box3d_soa_world*)calloc(1, sizeof(ymir_box3d_soa_world));
+ if (world == NULL)
+ {
+ return YMIR_SOA_OUT_OF_MEMORY;
+ }
+ world->capacity = capacity;
+ world->joint_capacity = joint_capacity;
+ size_t n = (size_t)capacity;
+ size_t m = (size_t)joint_capacity > 0 ? (size_t)joint_capacity : 1; // calloc(0) may return NULL
+ world->bodies = (b3BodyId*)calloc(n, sizeof(b3BodyId));
+ world->heightfields = (b3HeightFieldData**)calloc(n, sizeof(b3HeightFieldData*));
+ world->meshes = (b3MeshData**)calloc(n, sizeof(b3MeshData*));
+ world->stable_id = (uint64_t*)calloc(n, sizeof(uint64_t));
+ world->kind = (uint32_t*)calloc(n, sizeof(uint32_t));
+ world->parent = (int32_t*)calloc(n, sizeof(int32_t));
+ world->limb = (int32_t*)calloc(n, sizeof(int32_t));
+ world->contact_count = (int32_t*)calloc(n, sizeof(int32_t));
+ world->material_id = (uint64_t*)calloc(n, sizeof(uint64_t));
+ world->mass = (float*)calloc(n, sizeof(float));
+ world->body_generation = (uint32_t*)calloc(n, sizeof(uint32_t));
+ world->body_removed_at = (uint64_t*)calloc(n, sizeof(uint64_t));
+ world->size = (float*)calloc(n * 3, sizeof(float));
+ world->lanes = (float*)calloc(n * YMIR_SOA_BODY_FLOAT_LANES, sizeof(float));
+ world->joints = (b3JointId*)calloc(m, sizeof(b3JointId));
+ world->joint_kind = (uint32_t*)calloc(m, sizeof(uint32_t));
+ world->joint_removed_at = (uint64_t*)calloc(m, sizeof(uint64_t));
+ world->joint_generation = (uint32_t*)calloc(m, sizeof(uint32_t));
+ world->joint_body_a = (int32_t*)calloc(m, sizeof(int32_t));
+ world->joint_body_b = (int32_t*)calloc(m, sizeof(int32_t));
+ world->joint_local_a = (b3Quat*)calloc(m, sizeof(b3Quat));
+ world->joint_local_origin_a = (b3Vec3*)calloc(m, sizeof(b3Vec3));
+ world->joint_local_b = (b3Quat*)calloc(m, sizeof(b3Quat));
+ world->joint_lanes = (float*)calloc(m * YMIR_SOA_JOINT_FLOAT_LANES, sizeof(float));
+ world->fact_capacity = (uint32_t)fact_capacity;
+ world->begin_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact));
+ world->end_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact));
+ world->touching_facts = (ymir_box3d_soa_touch_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_touch_fact));
+ world->hit_facts = (ymir_box3d_soa_hit_fact*)calloc((size_t)fact_capacity, sizeof(ymir_box3d_soa_hit_fact));
+ world->overload_facts = (ymir_box3d_soa_overload_fact*)calloc(m, sizeof(ymir_box3d_soa_overload_fact));
+ world->body_removed_facts = (ymir_box3d_soa_body_removed_fact*)calloc(n, sizeof(ymir_box3d_soa_body_removed_fact));
+ world->body_removed_pending = (ymir_box3d_soa_body_removed_fact*)calloc(n, sizeof(ymir_box3d_soa_body_removed_fact));
+ world->joint_removed_facts = (ymir_box3d_soa_joint_removed_fact*)calloc(m, sizeof(ymir_box3d_soa_joint_removed_fact));
+ world->joint_removed_pending = (ymir_box3d_soa_joint_removed_fact*)calloc(m, sizeof(ymir_box3d_soa_joint_removed_fact));
+ world->retired_shapes = (ymir_soa_retired_shape*)calloc(n, sizeof(ymir_soa_retired_shape));
+ world->contact_scratch = (b3ContactData*)calloc(n, sizeof(b3ContactData));
+ world->gravity = (b3Vec3){gravity_x, gravity_y, gravity_z};
+ if (particle_capacities != NULL && (particle_capacities->particles > 0 || particle_capacities->distances > 0 || particle_capacities->bends > 0 ||
+ particle_capacities->attachments > 0 || particle_capacities->tethers > 0 || particle_capacities->materials > 0 || particle_capacities->fluid > 0))
+ {
+ world->particles = ymir_particles_create(particle_capacities, capacity);
+ if (world->particles == NULL)
+ {
+ ymir_soa_free(world);
+ return YMIR_SOA_OUT_OF_MEMORY;
+ }
+ }
+ if (world->contact_count == NULL || world->material_id == NULL || world->mass == NULL || world->body_generation == NULL || world->body_removed_at == NULL || world->begin_facts == NULL ||
+ world->end_facts == NULL || world->touching_facts == NULL || world->hit_facts == NULL || world->overload_facts == NULL || world->contact_scratch == NULL ||
+ world->body_removed_facts == NULL || world->body_removed_pending == NULL || world->joint_removed_facts == NULL ||
+ world->joint_removed_pending == NULL || world->retired_shapes == NULL ||
+ world->bodies == NULL || world->heightfields == NULL || world->meshes == NULL || world->stable_id == NULL || world->kind == NULL || world->parent == NULL ||
+ world->limb == NULL || world->size == NULL || world->lanes == NULL || world->joints == NULL || world->joint_kind == NULL ||
+ world->joint_body_a == NULL || world->joint_body_b == NULL || world->joint_local_a == NULL || world->joint_local_origin_a == NULL ||
+ world->joint_local_b == NULL || world->joint_lanes == NULL || world->joint_removed_at == NULL ||
+ world->joint_generation == NULL)
+ {
+ ymir_soa_free(world);
+ return YMIR_SOA_OUT_OF_MEMORY;
+ }
+
+ b3WorldDef def = b3DefaultWorldDef();
+ def.gravity = (b3Vec3){gravity_x, gravity_y, gravity_z};
+ def.enableSleep = false;
+ def.hitEventThreshold = hit_threshold;
+ def.workerCount = 1; // one worker: the step order is fixed, which determinism rests on
+ world->world_id = ymir_create_world_locked(&def);
+ if (B3_IS_NULL(world->world_id))
+ {
+ ymir_soa_free(world);
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+ if (world->particles != NULL)
+ {
+ b3World_SetSubStepCallback(world->world_id, ymir_soa_particle_substep, world);
+ b3World_SetContactFrictionCallback(world->world_id, ymir_soa_contact_friction, world);
+ }
+
+ *output = world;
+ return YMIR_SOA_OK;
+}
+
+YMIR_EXPORT void YMIR_CALL ymir_box3d_soa_destroy(ymir_box3d_soa_world* world)
+{
+ if (world == NULL)
+ {
+ return;
+ }
+ if (B3_IS_NON_NULL(world->world_id) && b3World_IsValid(world->world_id))
+ {
+ ymir_destroy_world_locked(world->world_id);
+ }
+ ymir_soa_free(world);
+}
+
+// The lane a new body takes: the lowest removed lane whose removing step has completed, else the next fresh lane, else -1. A removed
+// lane is not reused within the step that removed it, so lanes a caller read that step stay meaningful.
+static int ymir_soa_body_slot(const ymir_box3d_soa_world* world)
+{
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (world->kind[i] == YMIR_SOA_KIND_REMOVED && world->step_count > world->body_removed_at[i])
+ {
+ return i;
+ }
+ }
+ return world->count < world->capacity ? world->count : -1;
+}
+
+// Bodies that add_body could create right now.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_body_slots(const ymir_box3d_soa_world* world)
+{
+ if (world == NULL)
+ {
+ return 0;
+ }
+ int32_t free_slots = world->capacity - world->count;
+ for (int i = 0; i < world->count; ++i)
+ {
+ free_slots += world->kind[i] == YMIR_SOA_KIND_REMOVED && world->step_count > world->body_removed_at[i];
+ }
+ return free_slots;
+}
+
+static int32_t ymir_soa_check_body(const ymir_box3d_soa_world* world, const ymir_box3d_soa_body_desc* d)
+{
+ if (d->kind > YMIR_SOA_KIND_ANCHOR || !ymir_soa_finite3(d->position) || !ymir_soa_finite3(d->velocity) ||
+ !ymir_soa_finite3(d->size) || !ymir_soa_finite(d->friction) || !ymir_soa_finite(d->restitution) ||
+ !ymir_soa_finite(d->density) || !ymir_soa_finite(d->rolling_resistance) || d->friction < 0.0f ||
+ d->restitution < 0.0f || d->rolling_resistance < 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ float q2 = 0.0f;
+ for (int i = 0; i < 4; ++i)
+ {
+ if (!ymir_soa_finite(d->rotation[i]))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ q2 += d->rotation[i] * d->rotation[i];
+ }
+ if (fabsf(q2 - 1.0f) > 1e-3f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ if (d->parent < -1 || d->parent >= world->count || (d->parent >= 0 && world->kind[d->parent] == YMIR_SOA_KIND_REMOVED))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ if (ymir_soa_is_dynamic(d->kind) && d->density <= 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ switch (d->kind)
+ {
+ case YMIR_SOA_KIND_ANCHOR:
+ break; // no shape: nothing to size
+ case YMIR_SOA_KIND_SPHERE:
+ if (d->size[0] <= 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ break;
+ case YMIR_SOA_KIND_CAPSULE:
+ if (d->size[0] <= 0.0f || d->size[1] <= 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ break;
+ default:
+ if (d->size[0] <= 0.0f || d->size[1] <= 0.0f || d->size[2] <= 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ break;
+ }
+ if (ymir_soa_body_slot(world) < 0)
+ {
+ return YMIR_SOA_FULL;
+ }
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (world->kind[i] != YMIR_SOA_KIND_REMOVED && world->stable_id[i] == d->stable_id)
+ {
+ return YMIR_SOA_DUPLICATE_ID;
+ }
+ }
+ return YMIR_SOA_OK;
+}
+
+static int32_t ymir_soa_check_static_slot(const ymir_box3d_soa_world* world, uint64_t stable_id)
+{
+ if (ymir_soa_body_slot(world) < 0)
+ {
+ return YMIR_SOA_FULL;
+ }
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (world->kind[i] != YMIR_SOA_KIND_REMOVED && world->stable_id[i] == stable_id)
+ {
+ return YMIR_SOA_DUPLICATE_ID;
+ }
+ }
+ return YMIR_SOA_OK;
+}
+
+static b3ShapeDef ymir_soa_static_shape_def(
+ uint64_t stable_id, float friction, float restitution, uint64_t material_id)
+{
+ b3ShapeDef shape_def = b3DefaultShapeDef();
+ shape_def.userData = (void*)(uintptr_t)stable_id;
+ shape_def.enableContactEvents = true; // off by default in Box3D
+ shape_def.enableHitEvents = true;
+ shape_def.baseMaterial.userMaterialId = material_id;
+ shape_def.baseMaterial.friction = friction;
+ shape_def.baseMaterial.restitution = restitution;
+ return shape_def;
+}
+
+static void ymir_soa_commit_static_slot(
+ ymir_box3d_soa_world* world, int slot, b3BodyId body, uint32_t kind, uint64_t stable_id, uint64_t material_id,
+ b3HeightFieldData* hf, b3MeshData* mesh, int32_t* index)
+{
+ if (slot == world->count)
+ {
+ world->count++;
+ }
+ world->bodies[slot] = body;
+ world->heightfields[slot] = hf;
+ world->meshes[slot] = mesh;
+ world->stable_id[slot] = stable_id;
+ world->kind[slot] = kind;
+ world->parent[slot] = -1;
+ world->limb[slot] = 0;
+ world->contact_count[slot] = 0;
+ world->material_id[slot] = material_id;
+ world->mass[slot] = 0.0f;
+ for (int k = 0; k < 3; k++)
+ {
+ world->size[(size_t)k * (size_t)world->capacity + (size_t)slot] = 0.0f;
+ }
+ ymir_soa_refresh(world, slot);
+ if (index != NULL)
+ {
+ *index = slot;
+ }
+}
+
+// Creates one body from a descriptor. Box3D owns mass: it follows from `density` and the shape.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_body(
+ ymir_box3d_soa_world* world, const ymir_box3d_soa_body_desc* d, int32_t* index)
+{
+ if (world == NULL || d == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ int32_t status = ymir_soa_check_body(world, d);
+ if (status != YMIR_SOA_OK)
+ {
+ return status;
+ }
+
+ int slot = ymir_soa_body_slot(world);
+ b3BodyDef body_def = b3DefaultBodyDef();
+ body_def.type = ymir_soa_is_anchor(d->kind) ? b3_kinematicBody
+ : ymir_soa_is_dynamic(d->kind) ? b3_dynamicBody
+ : b3_staticBody;
+ body_def.position = (b3Vec3){d->position[0], d->position[1], d->position[2]};
+ body_def.rotation = (b3Quat){{d->rotation[0], d->rotation[1], d->rotation[2]}, d->rotation[3]};
+ body_def.linearVelocity = (b3Vec3){d->velocity[0], d->velocity[1], d->velocity[2]};
+ body_def.enableSleep = false;
+ body_def.userData = (void*)((uintptr_t)slot + 1u); // lane + 1: a shape resolves to its lane
+ b3BodyId body = b3CreateBody(world->world_id, &body_def);
+ if (B3_IS_NULL(body))
+ {
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+ if (!ymir_soa_is_anchor(d->kind)) // an anchor has no shape
+ {
+ b3ShapeDef shape_def = b3DefaultShapeDef();
+ shape_def.userData = (void*)(uintptr_t)d->stable_id;
+ shape_def.enableContactEvents = true; // off by default in Box3D
+ shape_def.enableHitEvents = true;
+ shape_def.baseMaterial.userMaterialId = d->material_id;
+ if (ymir_soa_is_dynamic(d->kind))
+ {
+ shape_def.density = d->density;
+ }
+ shape_def.baseMaterial.friction = d->friction;
+ shape_def.baseMaterial.restitution = d->restitution;
+ shape_def.baseMaterial.rollingResistance = d->rolling_resistance;
+
+ b3ShapeId shape;
+ if (d->kind == YMIR_SOA_KIND_SPHERE)
+ {
+ b3Sphere sphere = {{0.0f, 0.0f, 0.0f}, d->size[0]};
+ shape = b3CreateSphereShape(body, &shape_def, &sphere);
+ }
+ else if (d->kind == YMIR_SOA_KIND_CAPSULE)
+ {
+ b3Capsule capsule = {{0.0f, -d->size[1], 0.0f}, {0.0f, d->size[1], 0.0f}, d->size[0]};
+ shape = b3CreateCapsuleShape(body, &shape_def, &capsule);
+ }
+ else
+ {
+ b3BoxHull box = b3MakeBoxHull(d->size[0], d->size[1], d->size[2]);
+ shape = b3CreateHullShape(body, &shape_def, &box.base);
+ }
+ if (B3_IS_NULL(shape))
+ {
+ b3DestroyBody(body);
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+ }
+
+ int i = slot;
+ if (i == world->count)
+ {
+ world->count++;
+ }
+ world->bodies[i] = body;
+ world->stable_id[i] = d->stable_id;
+ world->kind[i] = d->kind;
+ world->parent[i] = d->parent;
+ world->limb[i] = d->limb;
+ world->contact_count[i] = 0;
+ world->material_id[i] = ymir_soa_is_anchor(d->kind) ? 0 : d->material_id;
+ world->mass[i] = ymir_soa_is_dynamic(d->kind) ? b3Body_GetMass(body) : 0.0f; // the shapes exist above, so Box3D's mass is final
+ /* Publish only the components the kind uses; unused ones read 0 whatever the caller passed. */
+ int used = ymir_soa_is_anchor(d->kind) ? 0 : d->kind == YMIR_SOA_KIND_SPHERE ? 1 : d->kind == YMIR_SOA_KIND_CAPSULE ? 2 : 3;
+ for (int k = 0; k < 3; k++)
+ {
+ world->size[(size_t)k * (size_t)world->capacity + (size_t)i] = k < used ? d->size[k] : 0.0f;
+ }
+ ymir_soa_refresh(world, i);
+ if (index != NULL)
+ {
+ *index = i;
+ }
+ return YMIR_SOA_OK;
+}
+
+// Creates a static heightfield body at `origin` with CCW top-facing triangles (`clockwiseWinding = false`).
+// `ymir_box3d_soa_world` owns the `b3HeightFieldData*` for the slot's life and destroys it after the body on remove/destroy.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_static_heightfield(
+ ymir_box3d_soa_world* world, uint64_t stable_id, float origin_x, float origin_y, float origin_z,
+ const float* heights, int32_t count_x, int32_t count_z, float scale_x, float scale_y, float scale_z,
+ float min_height, float max_height, float friction, float restitution, uint64_t material_id, int32_t* index)
+{
+ if (world == NULL || heights == NULL || count_x < 2 || count_z < 2 ||
+ (int64_t)count_x * (int64_t)count_z > 64LL * 1024 * 1024 || !ymir_soa_finite(origin_x) ||
+ !ymir_soa_finite(origin_y) || !ymir_soa_finite(origin_z) || !ymir_soa_finite(scale_x) ||
+ !ymir_soa_finite(scale_y) || !ymir_soa_finite(scale_z) || scale_x <= 0.0f || scale_y <= 0.0f ||
+ scale_z <= 0.0f || !ymir_soa_finite(min_height) || !ymir_soa_finite(max_height) ||
+ min_height > max_height || !ymir_soa_finite(friction) || !ymir_soa_finite(restitution) ||
+ friction < 0.0f || restitution < 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ float height_range = max_height - min_height;
+ float extent_x = scale_x * (float)(count_x - 1);
+ float extent_z = scale_z * (float)(count_z - 1);
+ float scaled_min_y = scale_y * min_height;
+ float scaled_max_y = scale_y * max_height;
+ float scaled_range_y = scale_y * height_range;
+ if (!ymir_soa_finite(height_range) || !ymir_soa_finite(extent_x) || !ymir_soa_finite(extent_z) ||
+ !ymir_soa_finite(scaled_min_y) || !ymir_soa_finite(scaled_max_y) || !ymir_soa_finite(scaled_range_y) ||
+ fabsf(extent_x) >= 1e5f || fabsf(extent_z) >= 1e5f || fabsf(scaled_range_y) >= 1e5f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ int32_t height_count = count_x * count_z;
+ for (int32_t k = 0; k < height_count; ++k)
+ {
+ if (!ymir_soa_finite(heights[k]))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ }
+ int32_t status = ymir_soa_check_static_slot(world, stable_id);
+ if (status != YMIR_SOA_OK)
+ {
+ return status;
+ }
+
+ float* heights_copy = (float*)malloc((size_t)height_count * sizeof(float));
+ if (heights_copy == NULL)
+ {
+ return YMIR_SOA_OUT_OF_MEMORY;
+ }
+ memcpy(heights_copy, heights, (size_t)height_count * sizeof(float));
+
+ b3HeightFieldDef hf_def = {0};
+ hf_def.heights = heights_copy;
+ hf_def.materialIndices = NULL;
+ hf_def.scale = (b3Vec3){scale_x, scale_y, scale_z};
+ hf_def.countX = count_x;
+ hf_def.countZ = count_z;
+ hf_def.globalMinimumHeight = min_height;
+ hf_def.globalMaximumHeight = max_height;
+ hf_def.clockwiseWinding = false;
+ b3HeightFieldData* hf = b3CreateHeightField(&hf_def);
+ free(heights_copy);
+ if (hf == NULL)
+ {
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+
+ int slot = ymir_soa_body_slot(world);
+ b3BodyDef body_def = b3DefaultBodyDef();
+ body_def.type = b3_staticBody;
+ body_def.position = (b3Vec3){origin_x, origin_y, origin_z};
+ body_def.enableSleep = false;
+ body_def.userData = (void*)((uintptr_t)slot + 1u);
+ b3BodyId body = b3CreateBody(world->world_id, &body_def);
+ if (B3_IS_NULL(body))
+ {
+ b3DestroyHeightField(hf);
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+
+ b3ShapeDef shape_def = ymir_soa_static_shape_def(stable_id, friction, restitution, material_id);
+ b3ShapeId shape = b3CreateHeightFieldShape(body, &shape_def, hf);
+ if (B3_IS_NULL(shape))
+ {
+ b3DestroyBody(body);
+ b3DestroyHeightField(hf);
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+
+ ymir_soa_commit_static_slot(
+ world, slot, body, YMIR_SOA_KIND_STATIC_HEIGHTFIELD, stable_id, material_id, hf, NULL, index);
+ return YMIR_SOA_OK;
+}
+
+// Creates a static triangle mesh body at `origin` with CCW outward-facing triangles.
+// `ymir_box3d_soa_world` owns the `b3MeshData*` for the slot's life and destroys it after the body on remove/destroy.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_static_mesh(
+ ymir_box3d_soa_world* world, uint64_t stable_id, float origin_x, float origin_y, float origin_z,
+ const float* vertices_xyz, int32_t vertex_count, const int32_t* triangle_indices, int32_t triangle_count,
+ float friction, float restitution, uint64_t material_id, int32_t* index)
+{
+ if (world == NULL || vertices_xyz == NULL || triangle_indices == NULL || vertex_count < 3 || triangle_count <= 0 ||
+ vertex_count > 32 * 1024 * 1024 || triangle_count > 16 * 1024 * 1024 ||
+ !ymir_soa_finite(origin_x) || !ymir_soa_finite(origin_y) || !ymir_soa_finite(origin_z) ||
+ !ymir_soa_finite(friction) || !ymir_soa_finite(restitution) || friction < 0.0f || restitution < 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ int32_t float_count = vertex_count * 3;
+ for (int32_t k = 0; k < float_count; ++k)
+ {
+ float v = vertices_xyz[k];
+ if (!ymir_soa_finite(v) || fabsf(v) >= 50000.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ }
+ int32_t index_count = triangle_count * 3;
+ for (int32_t k = 0; k < index_count; ++k)
+ {
+ if (triangle_indices[k] < 0 || triangle_indices[k] >= vertex_count)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ }
+ int has_valid_triangle = 0;
+ for (int32_t t = 0; t < triangle_count; ++t)
+ {
+ int32_t i0 = triangle_indices[(size_t)t * 3 + 0];
+ int32_t i1 = triangle_indices[(size_t)t * 3 + 1];
+ int32_t i2 = triangle_indices[(size_t)t * 3 + 2];
+ if (i0 == i1 || i1 == i2 || i2 == i0)
+ {
+ continue;
+ }
+ const float* p0 = &vertices_xyz[(size_t)i0 * 3];
+ const float* p1 = &vertices_xyz[(size_t)i1 * 3];
+ const float* p2 = &vertices_xyz[(size_t)i2 * 3];
+ float e1x = p1[0] - p0[0];
+ float e1y = p1[1] - p0[1];
+ float e1z = p1[2] - p0[2];
+ float e2x = p2[0] - p0[0];
+ float e2y = p2[1] - p0[1];
+ float e2z = p2[2] - p0[2];
+ float cx = e1y * e2z - e1z * e2y;
+ float cy = e1z * e2x - e1x * e2z;
+ float cz = e1x * e2y - e1y * e2x;
+ float len_sq = cx * cx + cy * cy + cz * cz;
+ if (ymir_soa_finite(cx) && ymir_soa_finite(cy) && ymir_soa_finite(cz) &&
+ ymir_soa_finite(len_sq) && len_sq > 1e-10f)
+ {
+ has_valid_triangle = 1;
+ break;
+ }
+ }
+ if (!has_valid_triangle)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ int32_t status = ymir_soa_check_static_slot(world, stable_id);
+ if (status != YMIR_SOA_OK)
+ {
+ return status;
+ }
+
+ b3Vec3* verts = (b3Vec3*)malloc((size_t)vertex_count * sizeof(b3Vec3));
+ int32_t* indices = (int32_t*)malloc((size_t)index_count * sizeof(int32_t));
+ if (verts == NULL || indices == NULL)
+ {
+ free(verts);
+ free(indices);
+ return YMIR_SOA_OUT_OF_MEMORY;
+ }
+ for (int32_t k = 0; k < vertex_count; ++k)
+ {
+ verts[k] = (b3Vec3){vertices_xyz[(size_t)k * 3 + 0], vertices_xyz[(size_t)k * 3 + 1], vertices_xyz[(size_t)k * 3 + 2]};
+ }
+ memcpy(indices, triangle_indices, (size_t)index_count * sizeof(int32_t));
+
+ b3MeshDef mesh_def = {0};
+ mesh_def.vertices = verts;
+ mesh_def.indices = indices;
+ mesh_def.vertexCount = vertex_count;
+ mesh_def.triangleCount = triangle_count;
+ mesh_def.identifyEdges = true;
+ b3MeshData* mesh = b3CreateMesh(&mesh_def, NULL, 0);
+ free(verts);
+ free(indices);
+ if (mesh == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+
+ int slot = ymir_soa_body_slot(world);
+ b3BodyDef body_def = b3DefaultBodyDef();
+ body_def.type = b3_staticBody;
+ body_def.position = (b3Vec3){origin_x, origin_y, origin_z};
+ body_def.enableSleep = false;
+ body_def.userData = (void*)((uintptr_t)slot + 1u);
+ b3BodyId body = b3CreateBody(world->world_id, &body_def);
+ if (B3_IS_NULL(body))
+ {
+ b3DestroyMesh(mesh);
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+
+ b3ShapeDef shape_def = ymir_soa_static_shape_def(stable_id, friction, restitution, material_id);
+ b3ShapeId shape = b3CreateMeshShape(body, &shape_def, mesh, (b3Vec3){1.0f, 1.0f, 1.0f});
+ if (B3_IS_NULL(shape))
+ {
+ b3DestroyBody(body);
+ b3DestroyMesh(mesh);
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+
+ ymir_soa_commit_static_slot(
+ world, slot, body, YMIR_SOA_KIND_STATIC_MESH, stable_id, material_id, NULL, mesh, index);
+ return YMIR_SOA_OK;
+}
+
+// The lane a new joint takes: the lowest tombstone whose destroying step has completed, else the next fresh
+// slot, else -1. A destroyed lane is not reused within the step that destroyed it, so lanes a caller read
+// that step stay meaningful.
+static int ymir_soa_joint_slot(const ymir_box3d_soa_world* world)
+{
+ for (int j = 0; j < world->joint_count; ++j)
+ {
+ if (world->joint_kind[j] == YMIR_SOA_JOINT_REMOVED && world->step_count > world->joint_removed_at[j])
+ {
+ return j;
+ }
+ }
+ return world->joint_count < world->joint_capacity ? world->joint_count : -1;
+}
+
+// Joints that add_joint could create right now.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_joint_slots(const ymir_box3d_soa_world* world)
+{
+ if (world == NULL)
+ {
+ return 0;
+ }
+ int32_t free_slots = world->joint_capacity - world->joint_count;
+ for (int j = 0; j < world->joint_count; ++j)
+ {
+ free_slots += world->joint_kind[j] == YMIR_SOA_JOINT_REMOVED && world->step_count > world->joint_removed_at[j];
+ }
+ return free_slots;
+}
+
+// What every joint kind shares: the bodies, the thresholds and the lane + 1 user data a joint event resolves to its lane.
+static void ymir_soa_joint_base(const ymir_box3d_soa_world* world, b3JointDef* base, int slot, const ymir_box3d_soa_joint_desc* d)
+{
+ base->bodyIdA = world->bodies[d->body_a];
+ base->bodyIdB = world->bodies[d->body_b];
+ base->forceThreshold = ymir_soa_threshold(d->force_threshold);
+ base->torqueThreshold = ymir_soa_threshold(d->torque_threshold);
+ base->userData = (void*)((uintptr_t)slot + 1u);
+}
+
+// Creates a joint between two existing bodies. The joint frame is built in world space (origin at the
+// anchor, z along the axis) and expressed in each body's local frame, so the creation pose is zero.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_add_joint(
+ ymir_box3d_soa_world* world, const ymir_box3d_soa_joint_desc* d, int32_t* index)
+{
+ if (world == NULL || d == NULL || d->kind > YMIR_SOA_JOINT_MOTOR || d->body_a < 0 || d->body_a >= world->count ||
+ d->body_b < 0 || d->body_b >= world->count || d->body_a == d->body_b ||
+ world->kind[d->body_a] == YMIR_SOA_KIND_REMOVED || world->kind[d->body_b] == YMIR_SOA_KIND_REMOVED || !ymir_soa_finite3(d->anchor) ||
+ !ymir_soa_finite3(d->axis) || !ymir_soa_finite(d->lower) || !ymir_soa_finite(d->upper) ||
+ !ymir_soa_finite(d->cone_angle) || d->cone_angle < 0.0f || d->cone_angle > B3_PI ||
+ !ymir_soa_finite(d->linear_hertz) || !ymir_soa_finite(d->linear_damping) || !ymir_soa_finite(d->max_force) ||
+ !ymir_soa_finite(d->angular_hertz) || !ymir_soa_finite(d->angular_damping) || !ymir_soa_finite(d->max_torque) ||
+ d->linear_hertz < 0.0f || d->linear_damping < 0.0f || d->max_force < 0.0f || d->angular_hertz < 0.0f ||
+ d->angular_damping < 0.0f || d->max_torque < 0.0f || !ymir_soa_threshold_ok(d->force_threshold) ||
+ !ymir_soa_threshold_ok(d->torque_threshold))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ b3Vec3 axis = {d->axis[0], d->axis[1], d->axis[2]};
+ float length = sqrtf(b3Dot(axis, axis));
+ if (length < 1e-6f || (d->enable_limit != 0 && d->kind != YMIR_SOA_JOINT_WELD && d->lower > d->upper))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ int slot = ymir_soa_joint_slot(world);
+ if (slot < 0)
+ {
+ return YMIR_SOA_FULL;
+ }
+ axis = b3MulSV(1.0f / length, axis);
+
+ b3Transform frame = {{d->anchor[0], d->anchor[1], d->anchor[2]}, b3ComputeQuatBetweenUnitVectors((b3Vec3){0.0f, 0.0f, 1.0f}, axis)};
+ b3Transform local_a = b3InvMulTransforms(ymir_soa_body_transform(world->bodies[d->body_a]), frame);
+ b3Transform local_b = b3InvMulTransforms(ymir_soa_body_transform(world->bodies[d->body_b]), frame);
+
+ b3JointId joint;
+ if (d->kind == YMIR_SOA_JOINT_REVOLUTE)
+ {
+ b3RevoluteJointDef def = b3DefaultRevoluteJointDef();
+ def.base.localFrameA = local_a;
+ def.base.localFrameB = local_b;
+ ymir_soa_joint_base(world, &def.base, slot, d);
+ def.enableLimit = d->enable_limit != 0;
+ def.lowerAngle = d->lower;
+ def.upperAngle = d->upper;
+ joint = b3CreateRevoluteJoint(world->world_id, &def);
+ }
+ else if (d->kind == YMIR_SOA_JOINT_SPHERICAL)
+ {
+ b3SphericalJointDef def = b3DefaultSphericalJointDef();
+ def.base.localFrameA = local_a;
+ def.base.localFrameB = local_b;
+ ymir_soa_joint_base(world, &def.base, slot, d);
+ def.enableConeLimit = d->enable_limit != 0 && d->cone_angle > 0.0f;
+ def.coneAngle = d->cone_angle;
+ def.enableTwistLimit = d->enable_limit != 0;
+ def.lowerTwistAngle = d->lower;
+ def.upperTwistAngle = d->upper;
+ joint = b3CreateSphericalJoint(world->world_id, &def);
+ }
+ else if (d->kind == YMIR_SOA_JOINT_MOTOR)
+ {
+ b3MotorJointDef def = b3DefaultMotorJointDef();
+ def.base.localFrameA = local_a;
+ def.base.localFrameB = local_b;
+ ymir_soa_joint_base(world, &def.base, slot, d);
+ def.linearHertz = d->linear_hertz;
+ def.linearDampingRatio = d->linear_damping;
+ def.maxSpringForce = d->max_force;
+ def.angularHertz = d->angular_hertz;
+ def.angularDampingRatio = d->angular_damping;
+ def.maxSpringTorque = d->max_torque;
+ joint = b3CreateMotorJoint(world->world_id, &def);
+ }
+ else
+ {
+ b3WeldJointDef def = b3DefaultWeldJointDef();
+ def.base.localFrameA = local_a;
+ def.base.localFrameB = local_b;
+ ymir_soa_joint_base(world, &def.base, slot, d);
+ joint = b3CreateWeldJoint(world->world_id, &def);
+ }
+ if (B3_IS_NULL(joint))
+ {
+ return YMIR_SOA_INTERNAL_ERROR;
+ }
+
+ int j = slot;
+ if (j == world->joint_count)
+ {
+ world->joint_count++;
+ }
+ world->joints[j] = joint;
+ world->joint_kind[j] = d->kind;
+ world->joint_body_a[j] = d->body_a;
+ world->joint_body_b[j] = d->body_b;
+ world->joint_local_a[j] = local_a.q;
+ world->joint_local_origin_a[j] = local_a.p;
+ world->joint_local_b[j] = local_b.q;
+ ymir_soa_refresh_joint(world, j);
+ if (index != NULL)
+ {
+ *index = j;
+ }
+ return YMIR_SOA_OK;
+}
+
+// The one path that ends a joint: Box3D destroys it (waking its bodies), the lane becomes a tombstone (kind
+// REMOVED, bodies -1, every lane 0) and its generation moves on, so no handle names it again. add_joint may
+// reuse the lane only once a step has completed since. The removal is a JointRemoved fact, published by the next step.
+static void ymir_soa_retire_joint(ymir_box3d_soa_world* world, int32_t joint, uint32_t with_body)
+{
+ world->joint_removed_pending[world->joint_removed_pending_count++] = (ymir_box3d_soa_joint_removed_fact){
+ .lane = joint, .generation = world->joint_generation[joint], .body_a = world->joint_body_a[joint],
+ .body_b = world->joint_body_b[joint], .with_body = with_body};
+ b3DestroyJoint(world->joints[joint], true);
+ world->joints[joint] = (b3JointId){0};
+ world->joint_kind[joint] = YMIR_SOA_JOINT_REMOVED;
+ world->joint_body_a[joint] = -1;
+ world->joint_body_b[joint] = -1;
+ world->joint_removed_at[joint] = world->step_count;
+ world->joint_generation[joint] += 1;
+ for (int lane = 0; lane < YMIR_SOA_JOINT_FLOAT_LANES; ++lane)
+ {
+ ymir_soa_joint_lane(world, lane)[joint] = 0.0f;
+ }
+}
+
+// Releases a joint of any kind (a grab, a cut, a tear) named by its lane and the slot's generation read when it
+// was added. A generation that is not the slot's current one, or a removed lane, is refused, so a stale handle never
+// destroys a later joint in a reused slot.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_joint(ymir_box3d_soa_world* world, int32_t joint, uint32_t generation)
+{
+ if (world == NULL || joint < 0 || joint >= world->joint_count || world->joint_kind[joint] > YMIR_SOA_JOINT_MOTOR ||
+ world->joint_generation[joint] != generation)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ ymir_soa_retire_joint(world, joint, 0);
+ return YMIR_SOA_OK;
+}
+
+// Sets a live joint's thresholds (see the joint desc), named by lane and generation like destroy_joint. Refusals change nothing.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_set_joint_thresholds(
+ ymir_box3d_soa_world* world, int32_t joint, uint32_t generation, float force_threshold, float torque_threshold)
+{
+ if (world == NULL || joint < 0 || joint >= world->joint_count || world->joint_kind[joint] > YMIR_SOA_JOINT_MOTOR ||
+ world->joint_generation[joint] != generation || !ymir_soa_threshold_ok(force_threshold) ||
+ !ymir_soa_threshold_ok(torque_threshold))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ b3Joint_SetForceThreshold(world->joints[joint], ymir_soa_threshold(force_threshold));
+ b3Joint_SetTorqueThreshold(world->joints[joint], ymir_soa_threshold(torque_threshold));
+ return YMIR_SOA_OK;
+}
+
+// Removes a body named by its lane and the lane's generation read when it was added: the one body-ending path. Refused, nothing
+// changed, for a lane that is not a live body, a stale generation, or REFERENCED while a live attachment or sensor names the body.
+// Then: its wet patches go, every joint naming it is retired (ascending lane), Box3D destroys the body, and the lane becomes a
+// tombstone (kind REMOVED, every other lane 0, generation + 1) that add_body may reuse once a step has completed.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_remove_body(ymir_box3d_soa_world* world, int32_t lane, uint32_t generation)
+{
+ if (world == NULL || lane < 0 || lane >= world->count || world->kind[lane] == YMIR_SOA_KIND_REMOVED ||
+ world->body_generation[lane] != generation)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ uint32_t patches = 0;
+ float volume = 0.0f;
+ if (world->particles != NULL)
+ {
+ int32_t status = ymir_particles_release_body(world->particles, lane, world->step_count, &patches, &volume);
+ if (status != YMIR_PARTICLES_OK)
+ {
+ return status;
+ }
+ }
+ for (int j = 0; j < world->joint_count; ++j)
+ {
+ if (world->joint_kind[j] != YMIR_SOA_JOINT_REMOVED && (world->joint_body_a[j] == lane || world->joint_body_b[j] == lane))
+ {
+ ymir_soa_retire_joint(world, j, 1);
+ }
+ }
+ b3ShapeId shape;
+ if (!ymir_soa_is_anchor(world->kind[lane]) && b3Body_GetShapes(world->bodies[lane], &shape, 1) == 1)
+ {
+ assert(world->retired_count < (uint32_t)world->capacity); // Debug: one step's removals fit; the step clears the table
+ world->retired_shapes[world->retired_count++] = (ymir_soa_retired_shape){shape, lane, world->stable_id[lane]};
+ }
+ world->body_removed_pending[world->body_removed_pending_count++] = (ymir_box3d_soa_body_removed_fact){
+ .lane = lane, .generation = generation, .stable_id = world->stable_id[lane], .wet_patches = patches, .wet_volume = volume};
+ b3DestroyBody(world->bodies[lane]);
+ if (world->heightfields[lane] != NULL)
+ {
+ b3DestroyHeightField(world->heightfields[lane]);
+ world->heightfields[lane] = NULL;
+ }
+ if (world->meshes[lane] != NULL)
+ {
+ b3DestroyMesh(world->meshes[lane]);
+ world->meshes[lane] = NULL;
+ }
+ world->bodies[lane] = (b3BodyId){0};
+ world->kind[lane] = YMIR_SOA_KIND_REMOVED;
+ world->stable_id[lane] = 0;
+ world->parent[lane] = -1;
+ world->limb[lane] = 0;
+ world->contact_count[lane] = 0;
+ world->material_id[lane] = 0;
+ world->mass[lane] = 0.0f;
+ world->body_removed_at[lane] = world->step_count;
+ world->body_generation[lane] += 1;
+ for (int k = 0; k < 3; ++k)
+ {
+ world->size[(size_t)k * (size_t)world->capacity + (size_t)lane] = 0.0f;
+ }
+ for (int k = 0; k < YMIR_SOA_BODY_FLOAT_LANES; ++k)
+ {
+ ymir_soa_lane(world, k)[lane] = 0.0f;
+ }
+ return YMIR_SOA_OK;
+}
+
+// Applies the caller's force and torque lanes to the dynamic bodies, then clears them: a lane holds one
+// step's intent, so a stale force is never applied twice. A non-finite value refuses the whole step
+// before any body is touched.
+static int32_t ymir_soa_apply_write_lanes(ymir_box3d_soa_world* world)
+{
+ float* lane[YMIR_SOA_WRITE_LANES];
+ for (int k = 0; k < YMIR_SOA_WRITE_LANES; ++k)
+ {
+ lane[k] = ymir_soa_lane(world, YMIR_SOA_STATE_LANES + k);
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (world->kind[i] != YMIR_SOA_KIND_REMOVED && !ymir_soa_finite(lane[k][i]))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ }
+ }
+ for (int i = 0; i < world->count; ++i)
+ {
+ b3Vec3 force = {lane[0][i], lane[1][i], lane[2][i]};
+ b3Vec3 torque = {lane[3][i], lane[4][i], lane[5][i]};
+ if (ymir_soa_is_dynamic(world->kind[i]))
+ {
+ if (force.x != 0.0f || force.y != 0.0f || force.z != 0.0f)
+ {
+ b3Body_ApplyForceToCenter(world->bodies[i], force, true);
+ }
+ if (torque.x != 0.0f || torque.y != 0.0f || torque.z != 0.0f)
+ {
+ b3Body_ApplyTorque(world->bodies[i], torque, true);
+ }
+ }
+ for (int k = 0; k < YMIR_SOA_WRITE_LANES; ++k)
+ {
+ lane[k][i] = 0.0f;
+ }
+ }
+ return YMIR_SOA_OK;
+}
+
+// The lane of a shape's body, from the body user data set at add_body (lane + 1).
+static int32_t ymir_soa_shape_lane(b3ShapeId shape)
+{
+ return (int32_t)((uintptr_t)b3Body_GetUserData(b3Shape_GetBody(shape))) - 1;
+}
+
+// A shape's lane and stable id: from the live shape, or for a removed body's shape from the retired table.
+static void ymir_soa_resolve_shape(const ymir_box3d_soa_world* world, b3ShapeId shape, int32_t* lane, uint64_t* stable_id)
+{
+ if (b3Shape_IsValid(shape))
+ {
+ *lane = ymir_soa_shape_lane(shape);
+ *stable_id = (uint64_t)(uintptr_t)b3Shape_GetUserData(shape);
+ return;
+ }
+ for (uint32_t i = 0; i < world->retired_count; ++i)
+ {
+ if (B3_ID_EQUALS(world->retired_shapes[i].shape, shape))
+ {
+ *lane = world->retired_shapes[i].lane;
+ *stable_id = world->retired_shapes[i].stable_id;
+ return;
+ }
+ }
+ *lane = -1;
+ *stable_id = 0;
+}
+
+static void ymir_soa_touch_fact(
+ ymir_box3d_soa_world* world, ymir_box3d_soa_touch_fact* out, uint32_t* count, uint32_t* dropped, b3ShapeId a,
+ b3ShapeId b)
+{
+ if (*count >= world->fact_capacity)
+ {
+ *dropped += 1;
+ return;
+ }
+ ymir_box3d_soa_touch_fact fact;
+ ymir_soa_resolve_shape(world, a, &fact.lane_a, &fact.stable_id_a);
+ ymir_soa_resolve_shape(world, b, &fact.lane_b, &fact.stable_id_b);
+ out[(*count)++] = fact;
+}
+
+// The normal impulse (N s) a contact's manifold points delivered over the step.
+static float ymir_soa_manifold_impulse(const b3ContactData* data)
+{
+ float impulse = 0.0f;
+ for (int m = 0; m < data->manifoldCount; ++m)
+ {
+ const b3Manifold* manifold = data->manifolds + m;
+ for (int p = 0; p < manifold->pointCount; ++p)
+ {
+ impulse += manifold->points[p].stepNormalImpulse;
+ }
+ }
+ return impulse;
+}
+
+// A hit's impulse: the contact between its two shapes. A body has one shape, so a shape has at most
+// capacity - 1 contacts and the scratch holds them all.
+static float ymir_soa_pair_impulse(ymir_box3d_soa_world* world, const b3ContactHitEvent* e)
+{
+ int n = b3Shape_GetContactData(e->shapeIdA, world->contact_scratch, world->capacity);
+ for (int c = 0; c < n; ++c)
+ {
+ const b3ContactData* data = world->contact_scratch + c;
+ b3ShapeId other = B3_ID_EQUALS(data->shapeIdA, e->shapeIdA) ? data->shapeIdB : data->shapeIdA;
+ if (B3_ID_EQUALS(other, e->shapeIdB))
+ {
+ return ymir_soa_manifold_impulse(data);
+ }
+ }
+ return 0.0f;
+}
+
+// Rewrites the fact arrays from Box3D's contact events for the step just taken, in Box3D's event order.
+// Writes only into the buffers allocated at create: nothing is allocated here.
+static void ymir_soa_collect_facts(ymir_box3d_soa_world* world)
+{
+ ymir_box3d_soa_facts* f = &world->facts;
+ f->begin_count = f->end_count = f->hit_count = 0;
+ f->begin_dropped = f->end_dropped = f->hit_dropped = 0;
+ f->overload_count = 0;
+ f->body_removed_count = world->body_removed_pending_count;
+ f->joint_removed_count = world->joint_removed_pending_count;
+ memcpy(world->body_removed_facts, world->body_removed_pending, world->body_removed_pending_count * sizeof(*world->body_removed_pending));
+ memcpy(world->joint_removed_facts, world->joint_removed_pending, world->joint_removed_pending_count * sizeof(*world->joint_removed_pending));
+ world->body_removed_pending_count = 0;
+ world->joint_removed_pending_count = 0;
+ b3JointEvents joint_events = b3World_GetJointEvents(world->world_id);
+ for (int i = 0; i < joint_events.count; ++i)
+ {
+ int j = (int)((uintptr_t)joint_events.jointEvents[i].userData) - 1;
+ if (j < 0 || j >= world->joint_count || world->joint_kind[j] == YMIR_SOA_JOINT_REMOVED)
+ {
+ continue;
+ }
+ b3Vec3 force = b3Joint_GetConstraintForce(world->joints[j]);
+ b3Vec3 torque = b3Joint_GetConstraintTorque(world->joints[j]);
+ world->overload_facts[f->overload_count++] = (ymir_box3d_soa_overload_fact){
+ .joint_lane = j, .joint_generation = world->joint_generation[j],
+ .force = {force.x, force.y, force.z}, .torque = {torque.x, torque.y, torque.z}};
+ }
+ b3ContactEvents events = b3World_GetContactEvents(world->world_id);
+ for (int i = 0; i < events.beginCount; ++i)
+ {
+ const b3ContactBeginTouchEvent* e = events.beginEvents + i;
+ ymir_soa_touch_fact(world, world->begin_facts, &f->begin_count, &f->begin_dropped, e->shapeIdA, e->shapeIdB);
+ }
+ for (int i = 0; i < events.endCount; ++i)
+ {
+ const b3ContactEndTouchEvent* e = events.endEvents + i;
+ ymir_soa_touch_fact(world, world->end_facts, &f->end_count, &f->end_dropped, e->shapeIdA, e->shapeIdB);
+ }
+ for (int i = 0; i < events.hitCount; ++i)
+ {
+ const b3ContactHitEvent* e = events.hitEvents + i;
+ if (f->hit_count >= world->fact_capacity)
+ {
+ f->hit_dropped += 1;
+ continue;
+ }
+ world->hit_facts[f->hit_count++] = (ymir_box3d_soa_hit_fact){
+ .lane_a = ymir_soa_shape_lane(e->shapeIdA),
+ .lane_b = ymir_soa_shape_lane(e->shapeIdB),
+ .stable_id_a = (uint64_t)(uintptr_t)b3Shape_GetUserData(e->shapeIdA),
+ .stable_id_b = (uint64_t)(uintptr_t)b3Shape_GetUserData(e->shapeIdB),
+ .point = {(float)e->point.x, (float)e->point.y, (float)e->point.z},
+ .normal = {e->normal.x, e->normal.y, e->normal.z},
+ .approach_speed = e->approachSpeed,
+ .impulse = ymir_soa_pair_impulse(world, e),
+ .material_a = e->userMaterialIdA,
+ .material_b = e->userMaterialIdB,
+ };
+ }
+}
+
+// Per body: the touching contacts' count and the normal impulse they delivered over the whole step; the same read yields each
+// touching pair once, from its lower lane (a static body's lane lists its contacts too).
+static void ymir_soa_collect_contact_lanes(ymir_box3d_soa_world* world)
+{
+ float* lane = ymir_soa_lane(world, YMIR_SOA_CONTACT_IMPULSE_LANE);
+ ymir_box3d_soa_facts* f = &world->facts;
+ f->touching_count = 0;
+ f->touching_dropped = 0;
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (world->kind[i] == YMIR_SOA_KIND_REMOVED)
+ {
+ continue; // its lanes stay 0
+ }
+ int n = b3Body_GetContactData(world->bodies[i], world->contact_scratch, world->capacity);
+ float impulse = 0.0f;
+ for (int c = 0; c < n; ++c)
+ {
+ const b3ContactData* data = world->contact_scratch + c;
+ impulse += ymir_soa_manifold_impulse(data);
+ b3ShapeId mine = ymir_soa_shape_lane(data->shapeIdA) == i ? data->shapeIdA : data->shapeIdB;
+ b3ShapeId other = ymir_soa_shape_lane(data->shapeIdA) == i ? data->shapeIdB : data->shapeIdA;
+ int32_t other_lane = ymir_soa_shape_lane(other);
+ if (other_lane <= i)
+ {
+ continue;
+ }
+ if (f->touching_count >= world->fact_capacity)
+ {
+ f->touching_dropped += 1;
+ continue;
+ }
+ ymir_box3d_soa_touch_fact* t = world->touching_facts + f->touching_count++;
+ t->lane_a = i;
+ t->lane_b = other_lane;
+ t->stable_id_a = (uint64_t)(uintptr_t)b3Shape_GetUserData(mine);
+ t->stable_id_b = (uint64_t)(uintptr_t)b3Shape_GetUserData(other);
+ }
+ world->contact_count[i] = n;
+ lane[i] = impulse;
+ }
+}
+
+// The particle phase's view of the bodies, before Box3D's step: shape, size, and the real inverse mass and world
+// inverse inertia of each dynamic body (0 for static, kinematic and anchor bodies), with the step-start pose and
+// velocity (the substep callback refreshes pose and velocity every substep). Every shape is centred on the body
+// origin, so the origin is the centre of mass.
+static void ymir_soa_gather_proxies(ymir_box3d_soa_world* world)
+{
+ ymir_particles* pt = world->particles;
+ pt->body_count = world->count;
+ for (int i = 0; i < world->count; ++i)
+ {
+ ymir_particle_proxy* b = pt->proxies + i;
+ uint32_t kind = world->kind[i];
+ if (kind == YMIR_SOA_KIND_REMOVED)
+ {
+ memset(b, 0, sizeof(*b));
+ b->shape = YMIR_PROXY_NONE; // no shape: settle refuses it as a support, particles never touch it
+ continue;
+ }
+ b3BodyId body = world->bodies[i];
+ b3Pos p = b3Body_GetPosition(body);
+ b3Quat q = b3Body_GetRotation(body);
+ b3Vec3 v = b3Body_GetLinearVelocity(body);
+ b3Vec3 w = b3Body_GetAngularVelocity(body);
+ memset(b, 0, sizeof(*b));
+ b->shape = kind == YMIR_SOA_KIND_SPHERE ? YMIR_PROXY_SPHERE
+ : kind == YMIR_SOA_KIND_CAPSULE ? YMIR_PROXY_CAPSULE
+ : (kind == YMIR_SOA_KIND_STATIC_BOX || kind == YMIR_SOA_KIND_BOX) ? YMIR_PROXY_BOX
+ : YMIR_PROXY_NONE;
+ for (int k = 0; k < 3; ++k)
+ {
+ b->size[k] = world->size[(size_t)k * (size_t)world->capacity + (size_t)i];
+ }
+ int root = i;
+ for (int hops = 0; hops < world->count && world->parent[root] >= 0; ++hops)
+ {
+ root = world->parent[root]; // the limb tree's root: parents are earlier lanes, so the walk ends
+ }
+ b->root = root;
+ b->position[0] = p.x; b->position[1] = p.y; b->position[2] = p.z;
+ b->rotation[0] = q.v.x; b->rotation[1] = q.v.y; b->rotation[2] = q.v.z; b->rotation[3] = q.s;
+ b->velocity[0] = v.x; b->velocity[1] = v.y; b->velocity[2] = v.z;
+ b->angular_velocity[0] = w.x; b->angular_velocity[1] = w.y; b->angular_velocity[2] = w.z;
+ if (ymir_soa_is_dynamic(kind))
+ {
+ b3Matrix3 m = b3Body_GetWorldInverseRotationalInertia(body);
+ b->inv_mass = 1.0f / b3Body_GetMass(body);
+ b->inv_inertia[0] = m.cx.x; b->inv_inertia[1] = m.cy.x; b->inv_inertia[2] = m.cz.x;
+ b->inv_inertia[3] = m.cy.y; b->inv_inertia[4] = m.cz.y; b->inv_inertia[5] = m.cz.z;
+ }
+ }
+}
+
+// Box3D's substep callback: each proxy takes the body's pose at the substep's start and its velocity after the
+// biased solve; the particle substep corrects both sides; each dynamic body's correction goes back as an impulse
+// before Box3D integrates its position, so the body ends the substep where the constraint put it.
+static void ymir_soa_particle_substep(b3WorldId world_id, int sub_step, float h, void* context)
+{
+ (void)world_id;
+ (void)sub_step;
+ ymir_box3d_soa_world* world = (ymir_box3d_soa_world*)context;
+ ymir_particles* pt = world->particles;
+ if (pt->live_particles == 0)
+ {
+ return;
+ }
+ for (int i = 0; i < world->count; ++i)
+ {
+ ymir_particle_proxy* b = pt->proxies + i;
+ b3Pos c;
+ b3Quat q;
+ b3Vec3 v, w;
+ if (world->kind[i] == YMIR_SOA_KIND_REMOVED)
+ {
+ continue; // its proxy stays zero
+ }
+ if (!b3Body_GetSubStepState(world->bodies[i], &c, &q, &v, &w))
+ {
+ b->inv_mass = 0.0f;
+ }
+ b->position[0] = c.x; b->position[1] = c.y; b->position[2] = c.z;
+ b->rotation[0] = q.v.x; b->rotation[1] = q.v.y; b->rotation[2] = q.v.z; b->rotation[3] = q.s;
+ b->velocity[0] = v.x; b->velocity[1] = v.y; b->velocity[2] = v.z;
+ b->angular_velocity[0] = w.x; b->angular_velocity[1] = w.y; b->angular_velocity[2] = w.z;
+ }
+ ymir_particles_substep(pt, h, world->gravity.x, world->gravity.y, world->gravity.z);
+ for (int i = 0; i < world->count; ++i)
+ {
+ const ymir_particle_proxy* b = pt->proxies + i;
+ if (b->inv_mass == 0.0f)
+ {
+ continue;
+ }
+ b3Vec3 linear = {b->sub_impulse[0], b->sub_impulse[1], b->sub_impulse[2]};
+ b3Vec3 angular = {b->sub_angular[0], b->sub_angular[1], b->sub_angular[2]};
+ if (linear.x != 0.0f || linear.y != 0.0f || linear.z != 0.0f || angular.x != 0.0f || angular.y != 0.0f ||
+ angular.z != 0.0f)
+ {
+ b3Body_ApplySubStepImpulse(world->bodies[i], linear, angular);
+ }
+ }
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_step(ymir_box3d_soa_world* world, float time_step, int32_t sub_step_count)
+{
+ if (world == NULL || !ymir_soa_finite(time_step) || time_step <= 0.0f || sub_step_count <= 0)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ int32_t status = ymir_soa_apply_write_lanes(world);
+ if (status != YMIR_SOA_OK)
+ {
+ return status;
+ }
+ int particles_live = 0;
+ if (world->particles != NULL)
+ {
+ ymir_soa_gather_proxies(world);
+ particles_live = ymir_particles_begin(world->particles);
+ }
+ b3World_Step(world->world_id, time_step, sub_step_count); // the particle substeps run inside it
+ if (world->particles != NULL)
+ {
+ ymir_particles_end(world->particles, sub_step_count);
+ for (int i = 0; i < world->count; ++i)
+ {
+ const ymir_particle_proxy* b = world->particles->proxies + i;
+ for (int k = 0; k < 3; ++k)
+ {
+ ymir_soa_lane(world, YMIR_SOA_PARTICLE_IMPULSE_LANE + k)[i] = particles_live ? b->impulse[k] : 0.0f;
+ }
+ }
+ }
+ // An anchor moves only on a target: the one just applied has been reached, so it holds still until the
+ // next target. Otherwise its velocity would run it on past the pose (and fling what it holds).
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (ymir_soa_is_anchor(world->kind[i]))
+ {
+ b3Body_SetLinearVelocity(world->bodies[i], b3Vec3_zero);
+ b3Body_SetAngularVelocity(world->bodies[i], b3Vec3_zero);
+ }
+ }
+ ymir_soa_collect_facts(world);
+ world->retired_count = 0; // the end-touch events that named the removed shapes are collected
+ ymir_soa_collect_contact_lanes(world);
+ for (int i = 0; i < world->count; ++i)
+ {
+ if (world->kind[i] != YMIR_SOA_KIND_REMOVED)
+ {
+ ymir_soa_refresh(world, i);
+ }
+ }
+ for (int j = 0; j < world->joint_count; ++j)
+ {
+ if (world->joint_kind[j] != YMIR_SOA_JOINT_REMOVED)
+ {
+ ymir_soa_refresh_joint(world, j);
+ }
+ }
+ world->step_count += 1;
+ return YMIR_SOA_OK;
+}
+
+// Grab and poke input, each an immediate command on the caller's say-so. Ymir decides nothing about grabbing.
+
+// Sets an anchor's pose for the coming step: Box3D gives it the velocity that reaches the pose after
+// `time_step` seconds, so pass the step's own dt and the anchor arrives at the end of that step, where `step`
+// stops it (velocity 0) until the next target.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_set_anchor_target(
+ ymir_box3d_soa_world* world, int32_t lane, const float* position, const float* rotation, float time_step)
+{
+ if (world == NULL || position == NULL || rotation == NULL || lane < 0 || lane >= world->count ||
+ !ymir_soa_is_anchor(world->kind[lane]) || !ymir_soa_finite3(position) || !ymir_soa_finite(time_step) ||
+ time_step <= 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ float q2 = 0.0f;
+ for (int i = 0; i < 4; ++i)
+ {
+ if (!ymir_soa_finite(rotation[i]))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ q2 += rotation[i] * rotation[i];
+ }
+ if (fabsf(q2 - 1.0f) > 1e-3f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ b3WorldTransform target = {
+ {position[0], position[1], position[2]}, {{rotation[0], rotation[1], rotation[2]}, rotation[3]}};
+ b3Body_SetTargetTransform(world->bodies[lane], target, time_step, true);
+ return YMIR_SOA_OK;
+}
+
+// A one-shot world impulse (N s) applied at a world point, so it turns the body when the point is off the
+// centre of mass. Dynamic bodies only.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_apply_impulse(
+ ymir_box3d_soa_world* world, int32_t lane, const float* impulse, const float* point)
+{
+ if (world == NULL || impulse == NULL || point == NULL || lane < 0 || lane >= world->count ||
+ !ymir_soa_is_dynamic(world->kind[lane]) || !ymir_soa_finite3(impulse) || !ymir_soa_finite3(point))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ b3Body_ApplyLinearImpulse(
+ world->bodies[lane], (b3Vec3){impulse[0], impulse[1], impulse[2]}, (b3Pos){point[0], point[1], point[2]}, true);
+ return YMIR_SOA_OK;
+}
+
+// The closest shape along origin + t * translation, t in [0, 1], with Box3D's default filter. A miss is a
+// success with `hit` 0. Refuses a non-finite or zero-length translation.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_cast_ray_closest(
+ const ymir_box3d_soa_world* world, const float* origin, const float* translation, ymir_box3d_soa_ray_hit* out)
+{
+ if (world == NULL || origin == NULL || translation == NULL || out == NULL || !ymir_soa_finite3(origin) ||
+ !ymir_soa_finite3(translation) ||
+ translation[0] * translation[0] + translation[1] * translation[1] + translation[2] * translation[2] <= 0.0f)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ memset(out, 0, sizeof(*out));
+ b3RayResult r = b3World_CastRayClosest(
+ world->world_id, (b3Pos){origin[0], origin[1], origin[2]},
+ (b3Vec3){translation[0], translation[1], translation[2]}, b3DefaultQueryFilter());
+ if (!r.hit)
+ {
+ return YMIR_SOA_OK;
+ }
+ out->hit = 1;
+ out->lane = ymir_soa_shape_lane(r.shapeId);
+ out->stable_id = (uint64_t)(uintptr_t)b3Shape_GetUserData(r.shapeId);
+ out->point[0] = (float)r.point.x;
+ out->point[1] = (float)r.point.y;
+ out->point[2] = (float)r.point.z;
+ out->normal[0] = r.normal.x;
+ out->normal[1] = r.normal.y;
+ out->normal[2] = r.normal.z;
+ out->fraction = r.fraction;
+ return YMIR_SOA_OK;
+}
+
+// Particles and the constraints between them. Each command is the whole of its effect: Ymir never removes or
+// releases on a threshold, so tear, cut, gib and release are the caller's say-so. Every refusal changes nothing. A
+// world made without particle capacity refuses them all.
+
+// Sizes of the native descriptors, for the managed layout check: 0 particle, 1 distance, 2 bend, 3 attachment,
+// 4 material, 5 capacities, 6 handle, 7 sensor.
+YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_particle_desc_size(uint32_t which)
+{
+ switch (which)
+ {
+ case 0: return (uint32_t)sizeof(ymir_particle_desc);
+ case 1: return (uint32_t)sizeof(ymir_distance_desc);
+ case 2: return (uint32_t)sizeof(ymir_bend_desc);
+ case 3: return (uint32_t)sizeof(ymir_attachment_desc);
+ case 4: return (uint32_t)sizeof(ymir_material_desc);
+ case 5: return (uint32_t)sizeof(ymir_particle_capacities);
+ case 6: return (uint32_t)sizeof(ymir_handle);
+ case 7: return (uint32_t)sizeof(ymir_sensor_desc);
+ default: return 0;
+ }
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_particles(
+ ymir_box3d_soa_world* world, int32_t n, const ymir_particle_desc* d, ymir_handle* out)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ return ymir_particles_create_particles(world->particles, n, d, world->step_count, out);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_destroy_particles(ymir_box3d_soa_world* world, int32_t n, const ymir_handle* h)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ return ymir_particles_destroy_particles(world->particles, n, h, world->step_count);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_distances(
+ ymir_box3d_soa_world* world, int32_t n, const ymir_distance_desc* d, ymir_handle* out)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ return ymir_particles_create_distances(world->particles, n, d, world->step_count, out);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_bends(
+ ymir_box3d_soa_world* world, int32_t n, const ymir_bend_desc* d, ymir_handle* out)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ return ymir_particles_create_bends(world->particles, n, d, world->step_count, out);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_attach(
+ ymir_box3d_soa_world* world, int32_t n, const ymir_attachment_desc* d, ymir_handle* out)
+{
+ if (world == NULL || world->particles == NULL || n < 0 || (n > 0 && d == NULL))
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (d[k].kind == YMIR_ATTACH_BODY && d[k].body >= 0 && d[k].body < world->count &&
+ world->kind[d[k].body] == YMIR_SOA_KIND_REMOVED)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ }
+ return ymir_particles_attach(world->particles, n, d, world->count, world->step_count, out);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_remove(ymir_box3d_soa_world* world, uint32_t type, int32_t n, const ymir_handle* h)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ return ymir_particles_remove(world->particles, type, n, h, world->step_count);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_set_material(ymir_box3d_soa_world* world, int32_t index, const ymir_material_desc* d)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ return ymir_particles_set_material(world->particles, index, d);
+}
+
+// Settles fluid particles into wet patches (see ymir_particles_settle): the proxies are refreshed first, so the contact points are the bodies' poses now.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_settle(ymir_box3d_soa_world* world, int32_t n, const ymir_handle* h, ymir_handle* out)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ ymir_soa_gather_proxies(world);
+ return ymir_particles_settle(world->particles, n, h, world->step_count, out);
+}
+
+// Takes pooled liquid out of the wet patches liquid sensors read (see ymir_particles_take_wet): the proxies are refreshed first, so the spheres are where the bodies are now.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_take_wet(ymir_box3d_soa_world* world, int32_t n, const ymir_handle* sensors, const float* volumes, float* taken)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ ymir_soa_gather_proxies(world);
+ return ymir_particles_take_wet(world->particles, n, sensors, volumes, world->step_count, taken);
+}
+
+// Pins or wakes particles (see ymir_particles_set_pinned): the proxies are refreshed first, so a wake lands on the anchor's point at the bodies' poses now.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_set_pinned(ymir_box3d_soa_world* world, int32_t n, const ymir_handle* h, uint32_t pinned)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ ymir_soa_gather_proxies(world);
+ return ymir_particles_set_pinned(world->particles, n, h, pinned);
+}
+
+// Creates liquid sensors (see ymir_particles_create_sensors); a body must already exist.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create_sensors(ymir_box3d_soa_world* world, int32_t n, const ymir_sensor_desc* d, ymir_handle* out)
+{
+ if (world == NULL || world->particles == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; d != NULL && k < n; ++k)
+ {
+ if (d[k].body >= 0 && d[k].body < world->count && world->kind[d[k].body] == YMIR_SOA_KIND_REMOVED)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ }
+ return ymir_particles_create_sensors(world->particles, n, d, world->count, world->step_count, out);
+}
+
+// Lanes a new particle (0), distance (1), bend (2), attachment (3), wet patch (4) or sensor (5) could take right now.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_free_slots(const ymir_box3d_soa_world* world, uint32_t lane_set)
+{
+ return world == NULL || world->particles == NULL ? 0 : ymir_particles_free_slots(world->particles, lane_set, world->step_count);
+}
+
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world* world, ymir_box3d_soa_view* view)
+{
+ if (world == NULL || view == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ float* base = world->lanes;
+ size_t n = (size_t)world->capacity;
+ float* jb = world->joint_lanes;
+ size_t m = (size_t)world->joint_capacity;
+ const ymir_particles* pt = world->particles;
+ *view =(ymir_box3d_soa_view){
+ .abi_version = YMIR_SOA_ABI_VERSION,
+ .count = world->count,
+ .capacity = world->capacity,
+ .joint_count = world->joint_count,
+ .joint_capacity = world->joint_capacity,
+ .step_count = world->step_count,
+ .particle_count = pt != NULL ? pt->particle_count : 0,
+ .particle_capacity = pt != NULL ? pt->particle_capacity : 0,
+ .fluid_neighbour_overflow = pt != NULL ? pt->fluid_overflow : 0,
+ .distance_count = pt != NULL ? pt->distance_count : 0,
+ .distance_capacity = pt != NULL ? pt->distance_capacity : 0,
+ .bend_count = pt != NULL ? pt->bend_count : 0,
+ .bend_capacity = pt != NULL ? pt->bend_capacity : 0,
+ .attachment_count = pt != NULL ? pt->attachment_count : 0,
+ .attachment_capacity = pt != NULL ? pt->attachment_capacity : 0,
+ .tether_count = pt != NULL ? pt->tether_count : 0,
+ .tether_capacity = pt != NULL ? pt->tether_capacity : 0,
+ .material_capacity = pt != NULL ? pt->material_capacity : 0,
+ .wet_count = pt != NULL ? pt->wet_count : 0,
+ .sensor_count = pt != NULL ? pt->sensor_count : 0,
+ .stable_id = world->stable_id,
+ .kind = world->kind,
+ .parent = world->parent,
+ .limb = world->limb,
+ .size_0 = world->size + 0 * n,
+ .size_1 = world->size + 1 * n,
+ .size_2 = world->size + 2 * n,
+ .position_x = base + 0 * n,
+ .position_y = base + 1 * n,
+ .position_z = base + 2 * n,
+ .rotation_x = base + 3 * n,
+ .rotation_y = base + 4 * n,
+ .rotation_z = base + 5 * n,
+ .rotation_w = base + 6 * n,
+ .velocity_x = base + 7 * n,
+ .velocity_y = base + 8 * n,
+ .velocity_z = base + 9 * n,
+ .angular_velocity_x = base + 10 * n,
+ .angular_velocity_y = base + 11 * n,
+ .angular_velocity_z = base + 12 * n,
+ .force_x = base + 13 * n,
+ .force_y = base + 14 * n,
+ .force_z = base + 15 * n,
+ .torque_x = base + 16 * n,
+ .torque_y = base + 17 * n,
+ .torque_z = base + 18 * n,
+ .joint_kind = world->joint_kind,
+ .joint_body_a = world->joint_body_a,
+ .joint_body_b = world->joint_body_b,
+ .joint_angle = jb + 0 * m,
+ .joint_frame_x = jb + 1 * m,
+ .joint_frame_y = jb + 2 * m,
+ .joint_frame_z = jb + 3 * m,
+ .joint_frame_w = jb + 4 * m,
+ .joint_rotation_x = jb + 5 * m,
+ .joint_rotation_y = jb + 6 * m,
+ .joint_rotation_z = jb + 7 * m,
+ .joint_rotation_w = jb + 8 * m,
+ .joint_angular_velocity_x = jb + 9 * m,
+ .joint_angular_velocity_y = jb + 10 * m,
+ .joint_angular_velocity_z = jb + 11 * m,
+ .joint_origin_x = jb + 12 * m,
+ .joint_origin_y = jb + 13 * m,
+ .joint_origin_z = jb + 14 * m,
+ .joint_constraint_force_x = jb + 15 * m,
+ .joint_constraint_force_y = jb + 16 * m,
+ .joint_constraint_force_z = jb + 17 * m,
+ .joint_constraint_torque_x = jb + 18 * m,
+ .joint_constraint_torque_y = jb + 19 * m,
+ .joint_constraint_torque_z = jb + 20 * m,
+ .contact_impulse = base + YMIR_SOA_CONTACT_IMPULSE_LANE * n,
+ .contact_count = world->contact_count,
+ .material_id = world->material_id,
+ .mass = world->mass,
+ .body_generation = world->body_generation,
+ .joint_generation = world->joint_generation,
+ .particle_impulse_x = base + (YMIR_SOA_PARTICLE_IMPULSE_LANE + 0) * n,
+ .particle_impulse_y = base + (YMIR_SOA_PARTICLE_IMPULSE_LANE + 1) * n,
+ .particle_impulse_z = base + (YMIR_SOA_PARTICLE_IMPULSE_LANE + 2) * n,
+ };
+ if (pt != NULL)
+ {
+ view->particle_x = pt->pos_x;
+ view->particle_y = pt->pos_y;
+ view->particle_z = pt->pos_z;
+ view->particle_vx = pt->vel_x;
+ view->particle_vy = pt->vel_y;
+ view->particle_vz = pt->vel_z;
+ view->particle_radius = pt->radius;
+ view->particle_inv_mass = pt->inv_mass;
+ view->particle_rest_x = pt->rest_x;
+ view->particle_rest_y = pt->rest_y;
+ view->particle_rest_z = pt->rest_z;
+ view->particle_phase = pt->phase;
+ view->particle_material = pt->material;
+ view->particle_live = pt->particle_live;
+ view->particle_generation = pt->particle_generation;
+ view->particle_removed_at = pt->particle_removed_at;
+ view->particle_component = pt->component;
+ view->particle_density = pt->density;
+ view->distance_a = pt->dist_a;
+ view->distance_b = pt->dist_b;
+ view->distance_rest = pt->dist_rest;
+ view->distance_compliance = pt->dist_compliance;
+ view->distance_tension = pt->dist_tension;
+ view->distance_live = pt->dist_live;
+ view->distance_generation = pt->dist_generation;
+ view->distance_removed_at = pt->dist_removed_at;
+ view->bend_e1 = pt->bend_e1;
+ view->bend_e2 = pt->bend_e2;
+ view->bend_a = pt->bend_a;
+ view->bend_b = pt->bend_b;
+ view->bend_c = pt->bend_c;
+ view->bend_rest = pt->bend_rest;
+ view->bend_limit = pt->bend_limit;
+ view->bend_compliance = pt->bend_compliance;
+ view->bend_live = pt->bend_live;
+ view->bend_generation = pt->bend_generation;
+ view->bend_removed_at = pt->bend_removed_at;
+ view->attachment_kind = pt->att_kind;
+ view->attachment_flags = pt->att_flags;
+ view->attachment_generation = pt->att_generation;
+ view->attachment_particle = pt->att_particle;
+ view->attachment_body = pt->att_body;
+ view->attachment_point_x = pt->att_point_x;
+ view->attachment_point_y = pt->att_point_y;
+ view->attachment_point_z = pt->att_point_z;
+ view->attachment_compliance = pt->att_compliance;
+ view->attachment_force_x = pt->att_force_x;
+ view->attachment_force_y = pt->att_force_y;
+ view->attachment_force_z = pt->att_force_z;
+ view->attachment_removed_at = pt->att_removed_at;
+ view->tether_att = pt->tether_att;
+ view->tether_particle = pt->tether_particle;
+ view->tether_parent = pt->tether_parent;
+ view->tether_edge = pt->tether_edge;
+ view->tether_other = pt->tether_other;
+ view->tether_bound = pt->tether_bound;
+ view->material_friction = pt->mat_friction;
+ view->material_id_lane = pt->mat_id;
+ view->material_viscosity = pt->mat_viscosity;
+ view->particle_support_body = pt->support_body;
+ view->particle_support_particle = pt->support_particle;
+ view->wet_body = pt->wet_body;
+ view->wet_particle = pt->wet_particle;
+ view->wet_x = pt->wet_x;
+ view->wet_y = pt->wet_y;
+ view->wet_z = pt->wet_z;
+ view->wet_radius = pt->wet_radius;
+ view->wet_patch_volume = pt->wet_volume;
+ view->wet_material = pt->wet_material;
+ view->wet_live = pt->wet_live;
+ view->wet_generation = pt->wet_generation;
+ view->wet_removed_at = pt->wet_removed_at;
+ view->body_wet_volume = pt->wet_volume_body;
+ view->material_wet_friction = pt->mat_wet_friction;
+ view->sensor_body = pt->sensor_body;
+ view->sensor_x = pt->sensor_x;
+ view->sensor_y = pt->sensor_y;
+ view->sensor_z = pt->sensor_z;
+ view->sensor_radius = pt->sensor_radius;
+ view->sensor_liquid_volume = pt->sensor_liquid_volume;
+ view->sensor_wet_volume = pt->sensor_wet_volume;
+ view->sensor_live = pt->sensor_live;
+ view->sensor_generation = pt->sensor_generation;
+ view->sensor_removed_at = pt->sensor_removed_at;
+ view->particle_pinned = pt->pinned;
+ view->particle_anchor = pt->anchor;
+ }
+ return YMIR_SOA_OK;
+}
+
+// The facts of the last step: pointers into buffers fixed for the world's life, valid until the next step.
+YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_facts(const ymir_box3d_soa_world* world, ymir_box3d_soa_facts* facts)
+{
+ if (world == NULL || facts == NULL)
+ {
+ return YMIR_SOA_INVALID_ARGUMENT;
+ }
+ *facts = world->facts;
+ facts->fact_capacity = world->fact_capacity;
+ facts->begin = world->begin_facts;
+ facts->end = world->end_facts;
+ facts->touching = world->touching_facts;
+ facts->hit = world->hit_facts;
+ facts->overload = world->overload_facts;
+ facts->body_removed = world->body_removed_facts;
+ facts->joint_removed = world->joint_removed_facts;
+ return YMIR_SOA_OK;
+}
diff --git a/native/Ymir.Box3D/ymir_particles.c b/native/Ymir.Box3D/ymir_particles.c
new file mode 100644
index 0000000..f90de88
--- /dev/null
+++ b/native/Ymir.Box3D/ymir_particles.c
@@ -0,0 +1,3117 @@
+// Particles and the constraint graph between them: XPBD with small steps (Macklin 2016, 2019), bending by the
+// triangle-centroid form (Kelager 2010), long-range tethers derived from the graph (Kim 2012), contact by
+// pair-symmetric position projection (Macklin 2014), and two-way coupling to rigid bodies through proxies with
+// real mass (Mueller 2007, Detailed Rigid XPBD 2020). The file calls no Box3D and spawns nothing: one thread,
+// every sum in a fixed order. See ymir_particles.h.
+
+#include "ymir_particles.h"
+
+#include
+#include
+#include
+
+typedef struct v3
+{
+ float x, y, z;
+} v3;
+
+static v3 vadd(v3 a, v3 b) { return (v3){a.x + b.x, a.y + b.y, a.z + b.z}; }
+static v3 vsub(v3 a, v3 b) { return (v3){a.x - b.x, a.y - b.y, a.z - b.z}; }
+static v3 vmul(v3 a, float s) { return (v3){a.x * s, a.y * s, a.z * s}; }
+static float vdot(v3 a, v3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
+static v3 vcross(v3 a, v3 b) { return (v3){a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
+static float vlen(v3 a) { return sqrtf(vdot(a, a)); }
+static float vmin(float a, float b) { return a < b ? a : b; }
+static float vmax(float a, float b) { return a > b ? a : b; }
+static float vclamp(float a, float lo, float hi) { return a < lo ? lo : a > hi ? hi : a; }
+
+static v3 qrot(const float* q, v3 v)
+{
+ v3 u = {q[0], q[1], q[2]};
+ v3 t = vmul(vcross(u, v), 2.0f);
+ return vadd(vadd(v, vmul(t, q[3])), vcross(u, t));
+}
+
+static v3 qrot_inv(const float* q, v3 v)
+{
+ float c[4] = {-q[0], -q[1], -q[2], q[3]};
+ return qrot(c, v);
+}
+
+static v3 mat_mul(const float* m, v3 v) // symmetric xx xy xz yy yz zz
+{
+ return (v3){m[0] * v.x + m[1] * v.y + m[2] * v.z, m[1] * v.x + m[3] * v.y + m[4] * v.z, m[2] * v.x + m[4] * v.y + m[5] * v.z};
+}
+
+static int finite3(const float* v)
+{
+ return isfinite(v[0]) && isfinite(v[1]) && isfinite(v[2]);
+}
+
+static v3 P(const ymir_particles* p, const float* x, const float* y, const float* z, int i)
+{
+ (void)p;
+ return (v3){x[i], y[i], z[i]};
+}
+
+static void put(float* x, float* y, float* z, int i, v3 v)
+{
+ x[i] = v.x;
+ y[i] = v.y;
+ z[i] = v.z;
+}
+
+
+// A particle is held to the nearest point of each of its two nearest tether islands (Kim, Chentanez, Mueller 2012 sec. 3.4);
+// Kim's typical four were measured on the 20-pin 32x32 sheet: 1.66% worst edge against 1.72%, for twice the lanes.
+#define YMIR_TETHER_ISLANDS 2
+
+// Kernels (Mueller, Charypar, Gross 2003 as used by Macklin and Mueller 2013): Poly6 W(r, h) = 315 / (64 pi h^9) (h^2 - r^2)^3 for the
+// density, Spiky grad W = -45 / (pi h^6) (h - r)^2 r_hat for the gradient.
+#define YMIR_POLY6 (315.0f / (64.0f * 3.14159265358979f))
+#define YMIR_SPIKY (-45.0f / 3.14159265358979f)
+
+// Regularisation of the density constraint (Macklin and Mueller 2013 eq. 11), added to sum |grad C|^2 with the gradients over n0
+// in 1/m^2.
+#define YMIR_PBF_EPS 1.0e-4f
+
+// Neighbour-list entries a fluid lane adds to the arena (CSR, packed): about 33 kernel neighbours at rest (4 r reach), about 45 at the column's 1.34 compression.
+#define YMIR_FLUID_NEIGHBOURS 96
+
+// The thickness of a settled film in metres: a patch of volume V is a disc of radius sqrt(V / (pi film)). One constant for every liquid.
+#define YMIR_WET_FILM 1.0e-3f
+
+// Capacity of the stack buffer a fluid row gathers its candidates into before the pair arithmetic; hits past it count in fluid_overflow.
+#define YMIR_FLUID_CANDIDATES 128
+
+// ---- memory: one block, laid out once at create -------------------------------------------------------------
+
+static size_t layout(ymir_particles* p, unsigned char* base)
+{
+ size_t off = 0;
+ int64_t np = p->particle_capacity, nd = p->distance_capacity, nb = p->bend_capacity, na = p->attachment_capacity,
+ nt = p->tether_capacity, nm = p->material_capacity, nx = p->body_capacity, nw = p->wet_capacity, nf = p->fluid_capacity, ns = p->sensor_capacity;
+ int64_t heap = 2 * nd + na + 1; // every directed edge relaxes once, and every attachment seeds one
+ size_t table = (size_t)p->table_mask + 1;
+#define CARVE(field, type, count) \
+ do \
+ { \
+ off = (off + 15u) & ~(size_t)15u; \
+ if (base != NULL) \
+ p->field = (type*)(base + off); \
+ off += sizeof(type) * (size_t)(count); \
+ } while (0)
+ CARVE(proxies, ymir_particle_proxy, nx);
+ CARVE(pos_x, float, np); CARVE(pos_y, float, np); CARVE(pos_z, float, np);
+ CARVE(vel_x, float, np); CARVE(vel_y, float, np); CARVE(vel_z, float, np);
+ CARVE(radius, float, np); CARVE(inv_mass, float, np);
+ CARVE(rest_x, float, np); CARVE(rest_y, float, np); CARVE(rest_z, float, np);
+ CARVE(phase, uint32_t, np); CARVE(material, uint32_t, np); CARVE(particle_live, uint32_t, np);
+ CARVE(particle_generation, uint32_t, np); CARVE(particle_removed_at, uint64_t, np); CARVE(component, int32_t, np);
+ CARVE(pinned, uint32_t, np); CARVE(anchor, int32_t, np); CARVE(w, float, np); CARVE(act, int32_t, np); CARVE(kin, int32_t, np);
+ CARVE(act_att, int32_t, na); CARVE(act_dist, int32_t, nd); CARVE(act_bend, int32_t, nb);
+ CARVE(held_start, int32_t, np); CARVE(held_count, int32_t, np); CARVE(limb_body, int32_t, np); CARVE(held_body, int32_t, na);
+ CARVE(density, float, np); CARVE(support_body, int32_t, np); CARVE(support_particle, int32_t, np);
+ CARVE(nbr, int32_t, (int64_t)p->fluid_capacity * YMIR_FLUID_NEIGHBOURS); CARVE(nbr_start, int32_t, np); CARVE(nbr_count, int32_t, np);
+ CARVE(wet_body, int32_t, nw); CARVE(wet_particle, int32_t, nw); CARVE(wet_x, float, nw); CARVE(wet_y, float, nw); CARVE(wet_z, float, nw);
+ CARVE(wet_radius, float, nw); CARVE(wet_volume, float, nw); CARVE(wet_material, uint32_t, nw); CARVE(wet_live, uint32_t, nw);
+ CARVE(wet_generation, uint32_t, nw); CARVE(wet_removed_at, uint64_t, nw); CARVE(wet_volume_body, float, nx); CARVE(particle_wet_mu, float, np);
+ CARVE(wet_order, int32_t, nw); CARVE(wet_body_start, int32_t, nx); CARVE(wet_body_count, int32_t, nx); CARVE(wet_body_box, float, (int64_t)nx * 7);
+ CARVE(sensor_body, int32_t, ns); CARVE(sensor_x, float, ns); CARVE(sensor_y, float, ns); CARVE(sensor_z, float, ns); CARVE(sensor_radius, float, ns);
+ CARVE(sensor_liquid_volume, float, ns); CARVE(sensor_wet_volume, float, ns); CARVE(sensor_live, uint32_t, ns); CARVE(sensor_generation, uint32_t, ns); CARVE(sensor_removed_at, uint64_t, ns);
+ CARVE(wu_code, int32_t, nf); CARVE(wu_x, float, nf); CARVE(wu_y, float, nf); CARVE(wu_z, float, nf); CARVE(wu_volume, float, nf);
+ CARVE(dist_a, int32_t, nd); CARVE(dist_b, int32_t, nd); CARVE(dist_rest, float, nd); CARVE(dist_compliance, float, nd);
+ CARVE(dist_tension, float, nd); CARVE(dist_live, uint32_t, nd); CARVE(dist_generation, uint32_t, nd);
+ CARVE(dist_removed_at, uint64_t, nd);
+ CARVE(bend_e1, int32_t, nb); CARVE(bend_e2, int32_t, nb); CARVE(bend_a, int32_t, nb); CARVE(bend_b, int32_t, nb);
+ CARVE(bend_c, int32_t, nb); CARVE(bend_rest, float, nb); CARVE(bend_limit, float, nb); CARVE(bend_compliance, float, nb);
+ CARVE(bend_live, uint32_t, nb); CARVE(bend_generation, uint32_t, nb); CARVE(bend_removed_at, uint64_t, nb);
+ CARVE(att_kind, uint32_t, na); CARVE(att_flags, uint32_t, na); CARVE(att_generation, uint32_t, na);
+ CARVE(att_particle, int32_t, na); CARVE(att_body, int32_t, na);
+ CARVE(att_point_x, float, na); CARVE(att_point_y, float, na); CARVE(att_point_z, float, na);
+ CARVE(att_compliance, float, na);
+ CARVE(att_force_x, float, na); CARVE(att_force_y, float, na); CARVE(att_force_z, float, na);
+ CARVE(att_removed_at, uint64_t, na);
+ CARVE(tether_att, int32_t, nt); CARVE(tether_particle, int32_t, nt); CARVE(tether_parent, int32_t, nt);
+ CARVE(tether_edge, int32_t, nt); CARVE(tether_other, int32_t, nt); CARVE(tether_bound, float, nt);
+ CARVE(mat_friction, float, nm); CARVE(mat_viscosity, float, nm); CARVE(mat_wet_friction, float, nm); CARVE(mat_id, uint64_t, nm);
+ CARVE(pp_x, float, np); CARVE(pp_y, float, np); CARVE(pp_z, float, np);
+ CARVE(dp_x, float, np); CARVE(dp_y, float, np); CARVE(dp_z, float, np);
+ CARVE(dist_acc, float, nd); CARVE(lambda, float, np);
+ CARVE(tacc_x, float, nt); CARVE(tacc_y, float, nt); CARVE(tacc_z, float, nt);
+ CARVE(lane_list, int32_t, nd > na ? nd : na); CARVE(cell_x, int32_t, np); CARVE(cell_y, int32_t, np); CARVE(cell_z, int32_t, np);
+ CARVE(cell_start, int32_t, table + 1); CARVE(cell_fill, int32_t, table); CARVE(sorted, int32_t, np);
+ CARVE(contacts, int32_t, np);
+ CARVE(sx, float, np); CARVE(sy, float, np); CARVE(sz, float, np); CARVE(sw, float, np); CARVE(sphase, uint32_t, np);
+ CARVE(adj_start, int32_t, np + 1); CARVE(adj_edge, int32_t, 2 * nd);
+ CARVE(heap_key, float, heap); CARVE(heap_node, int32_t, heap); CARVE(heap_edge, int32_t, heap);
+ CARVE(path, float, np); CARVE(via, int32_t, np); CARVE(owner, int32_t, np); CARVE(tether_of, int32_t, np);
+ CARVE(queue, int32_t, np); CARVE(comp_size, int32_t, np); CARVE(done, uint8_t, np);
+ CARVE(isle, int32_t, np); CARVE(near_isle, int32_t, YMIR_TETHER_ISLANDS * np); CARVE(near_path, float, YMIR_TETHER_ISLANDS * np);
+#undef CARVE
+ return off + 16;
+}
+
+ymir_particles* ymir_particles_create(const ymir_particle_capacities* c, int32_t body_capacity)
+{
+ if (c == NULL || c->particles < 0 || c->distances < 0 || c->bends < 0 || c->attachments < 0 || c->tethers < 0 ||
+ c->materials < 0 || c->fluid < 0 || c->wets < 0 || c->sensors < 0 || body_capacity < 0)
+ {
+ return NULL;
+ }
+ ymir_particles* p = (ymir_particles*)calloc(1, sizeof(ymir_particles));
+ if (p == NULL)
+ {
+ return NULL;
+ }
+ p->particle_capacity = c->particles;
+ p->distance_capacity = c->distances;
+ p->bend_capacity = c->bends;
+ p->attachment_capacity = c->attachments;
+ p->tether_capacity = c->tethers;
+ p->material_capacity = c->materials;
+ p->body_capacity = body_capacity;
+ p->fluid_capacity = c->fluid;
+ p->wet_capacity = c->wets;
+ p->sensor_capacity = c->sensors;
+ uint32_t table = 16;
+ while (table < 2u * (uint32_t)c->particles)
+ {
+ table <<= 1;
+ }
+ p->table_mask = table - 1;
+ size_t bytes = layout(p, NULL);
+ p->arena = calloc(1, bytes);
+ if (p->arena == NULL)
+ {
+ free(p);
+ return NULL;
+ }
+ layout(p, (unsigned char*)p->arena);
+ for (int32_t w = 0; w < p->wet_capacity; ++w)
+ {
+ p->wet_body[w] = p->wet_particle[w] = -1; // a free patch lane holds -1 on both supports
+ }
+ for (int32_t s = 0; s < p->sensor_capacity; ++s)
+ {
+ p->sensor_body[s] = -1; // a free sensor lane holds -1 on its body
+ }
+ for (int32_t i = 0; i < p->particle_capacity; ++i)
+ {
+ p->particle_wet_mu[i] = INFINITY; // dry
+ }
+ // n0 for h = 1: the Poly6 kernel summed over the simple-cubic lattice of spacing 1/2 within reach (self included); at h it is k / h^3
+ float k = 0.0f;
+ for (int a = -2; a <= 2; ++a)
+ {
+ for (int b = -2; b <= 2; ++b)
+ {
+ for (int e = -2; e <= 2; ++e)
+ {
+ float t = 1.0f - 0.25f * (float)(a * a + b * b + e * e);
+ k += t > 0.0f ? t * t * t : 0.0f;
+ }
+ }
+ }
+ p->fluid_k = k * YMIR_POLY6;
+ return p;
+}
+
+void ymir_particles_free(ymir_particles* p)
+{
+ if (p != NULL)
+ {
+ free(p->arena);
+ free(p);
+ }
+}
+
+// ---- lanes ---------------------------------------------------------------------------------------------------
+
+static int lane_reusable(uint64_t step_count, uint64_t removed_at)
+{
+ return step_count > removed_at;
+}
+
+// The lowest free lane at or after `from`: a lane never used, or a dead one a step has passed since its removal.
+// -1 when there is none. `state` is the lane set's live (or kind) lane and `dead` the value a dead lane holds.
+static int32_t next_lane(const uint32_t* state, uint32_t dead, const uint64_t* removed_at, int32_t count, int32_t capacity,
+ int32_t from, uint64_t step_count)
+{
+ for (int32_t i = from; i < capacity; ++i)
+ {
+ if (i >= count || (state[i] == dead && lane_reusable(step_count, removed_at[i])))
+ {
+ return i;
+ }
+ }
+ return -1;
+}
+
+static int32_t free_count(const uint32_t* state, uint32_t dead, const uint64_t* removed_at, int32_t count, int32_t capacity,
+ uint64_t step_count)
+{
+ int32_t n = capacity - count;
+ for (int32_t i = 0; i < count; ++i)
+ {
+ n += state[i] == dead && lane_reusable(step_count, removed_at[i]);
+ }
+ return n;
+}
+
+int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count)
+{
+ if (p == NULL)
+ {
+ return 0;
+ }
+ switch (lane_set)
+ {
+ case YMIR_LANES_PARTICLE:
+ return free_count(p->particle_live, 0, p->particle_removed_at, p->particle_count, p->particle_capacity, step_count);
+ case YMIR_LANES_DISTANCE:
+ return free_count(p->dist_live, 0, p->dist_removed_at, p->distance_count, p->distance_capacity, step_count);
+ case YMIR_LANES_BEND:
+ return free_count(p->bend_live, 0, p->bend_removed_at, p->bend_count, p->bend_capacity, step_count);
+ case YMIR_LANES_ATTACHMENT:
+ return free_count(p->att_kind, YMIR_ATTACH_REMOVED, p->att_removed_at, p->attachment_count, p->attachment_capacity, step_count);
+ case YMIR_LANES_WET:
+ return free_count(p->wet_live, 0, p->wet_removed_at, p->wet_count, p->wet_capacity, step_count);
+ case YMIR_LANES_SENSOR:
+ return free_count(p->sensor_live, 0, p->sensor_removed_at, p->sensor_count, p->sensor_capacity, step_count);
+ default:
+ return 0;
+ }
+}
+
+static int particle_ok(const ymir_particles* p, int32_t lane, uint32_t generation)
+{
+ return lane >= 0 && lane < p->particle_count && p->particle_live[lane] && p->particle_generation[lane] == generation;
+}
+
+static int distance_ok(const ymir_particles* p, int32_t lane, uint32_t generation)
+{
+ return lane >= 0 && lane < p->distance_count && p->dist_live[lane] && p->dist_generation[lane] == generation;
+}
+
+static int bend_ok(const ymir_particles* p, int32_t lane, uint32_t generation)
+{
+ return lane >= 0 && lane < p->bend_count && p->bend_live[lane] && p->bend_generation[lane] == generation;
+}
+
+static int attachment_ok(const ymir_particles* p, int32_t lane, uint32_t generation)
+{
+ return lane >= 0 && lane < p->attachment_count && p->att_kind[lane] != YMIR_ATTACH_REMOVED && p->att_generation[lane] == generation;
+}
+
+// Tombstones: the lane keeps its generation (advanced) and removed_at; every other lane reads 0.
+static void kill_bend(ymir_particles* p, int32_t k, uint64_t step_count)
+{
+ p->bend_e1[k] = p->bend_e2[k] = p->bend_a[k] = p->bend_b[k] = p->bend_c[k] = 0;
+ p->bend_rest[k] = p->bend_limit[k] = p->bend_compliance[k] = 0.0f;
+ p->bend_live[k] = 0;
+ p->bend_generation[k] += 1;
+ p->bend_removed_at[k] = step_count;
+}
+
+// A distance takes the bends over it with it.
+static void kill_distance(ymir_particles* p, int32_t e, uint64_t step_count)
+{
+ for (int32_t k = 0; k < p->bend_count; ++k)
+ {
+ if (p->bend_live[k] && (p->bend_e1[k] == e || p->bend_e2[k] == e))
+ {
+ kill_bend(p, k, step_count);
+ }
+ }
+ p->dist_a[e] = p->dist_b[e] = 0;
+ p->dist_rest[e] = p->dist_compliance[e] = p->dist_tension[e] = 0.0f;
+ p->dist_live[e] = 0;
+ p->dist_generation[e] += 1;
+ p->dist_removed_at[e] = step_count;
+}
+
+static void kill_attachment(ymir_particles* p, int32_t a, uint64_t step_count)
+{
+ p->att_kind[a] = YMIR_ATTACH_REMOVED;
+ p->att_flags[a] = 0;
+ p->att_removed_at[a] = step_count;
+ p->att_generation[a] += 1;
+ p->att_particle[a] = -1;
+ p->att_body[a] = -1;
+ p->att_point_x[a] = p->att_point_y[a] = p->att_point_z[a] = 0.0f;
+ p->att_compliance[a] = 0.0f;
+ p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f;
+}
+
+static int wet_ok(const ymir_particles* p, int32_t lane, uint32_t generation)
+{
+ return lane >= 0 && lane < p->wet_count && p->wet_live[lane] && p->wet_generation[lane] == generation;
+}
+
+static int sensor_ok(const ymir_particles* p, int32_t lane, uint32_t generation)
+{
+ return lane >= 0 && lane < p->sensor_count && p->sensor_live[lane] && p->sensor_generation[lane] == generation;
+}
+
+static void kill_sensor(ymir_particles* p, int32_t s, uint64_t step_count)
+{
+ p->sensor_live[s] = 0;
+ p->sensor_body[s] = -1;
+ p->sensor_x[s] = p->sensor_y[s] = p->sensor_z[s] = 0.0f;
+ p->sensor_radius[s] = p->sensor_liquid_volume[s] = p->sensor_wet_volume[s] = 0.0f;
+ p->sensor_removed_at[s] = step_count;
+ p->sensor_generation[s] += 1;
+}
+
+static void wet_reset(ymir_particles* p, int32_t w)
+{
+ p->wet_live[w] = 0;
+ p->wet_body[w] = p->wet_particle[w] = -1;
+ p->wet_x[w] = p->wet_y[w] = p->wet_z[w] = 0.0f;
+ p->wet_radius[w] = p->wet_volume[w] = 0.0f;
+ p->wet_material[w] = 0;
+}
+
+static void kill_wet(ymir_particles* p, int32_t w, uint64_t step_count)
+{
+ // The lane keeps its centre until rederive_wet, so the index's order holds for the rest of the command.
+ float x = p->wet_x[w], y = p->wet_y[w], z = p->wet_z[w];
+ wet_reset(p, w);
+ p->wet_x[w] = x;
+ p->wet_y[w] = y;
+ p->wet_z[w] = z;
+ p->wet_removed_at[w] = step_count;
+ p->wet_generation[w] += 1;
+}
+
+// wet_volume_body[b] = the sum of the live patches on body b, in wet lane order; particle_wet_mu[i] = the wet friction of the lowest live
+// patch on solid particle i, +inf when dry. The one writer; settle, take_wet, remove(WET) and destroy call it. It returns killed lanes (live 0, centre kept) to rest.
+static void rederive_wet(ymir_particles* p)
+{
+ for (int32_t i = 0; i < p->particle_capacity; ++i)
+ {
+ p->particle_wet_mu[i] = INFINITY;
+ }
+ for (int32_t b = 0; b < p->body_capacity; ++b)
+ {
+ p->wet_volume_body[b] = 0.0f;
+ }
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (!p->wet_live[w])
+ {
+ wet_reset(p, w);
+ continue;
+ }
+ if (p->wet_body[w] >= 0 && p->wet_body[w] < p->body_capacity)
+ {
+ p->wet_volume_body[p->wet_body[w]] += p->wet_volume[w];
+ }
+ if (p->wet_particle[w] >= 0 && p->wet_particle[w] < p->particle_capacity &&
+ p->particle_wet_mu[p->wet_particle[w]] == INFINITY)
+ {
+ p->particle_wet_mu[p->wet_particle[w]] = p->mat_wet_friction[p->wet_material[w]];
+ }
+ }
+ // The lookup index: the live body patches grouped by body and sorted by centre x (then lane) in wet_order, with each body's slice, the box
+ // its discs lie in and its largest radius (wet_body_box: min xyz, max xyz, rmax). Insertion sort: it runs at command time over wet_count lanes.
+ int32_t n = 0;
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (p->wet_live[w] && p->wet_body[w] >= 0 && p->wet_body[w] < p->body_capacity)
+ {
+ int32_t k = n++;
+ while (k > 0 && (p->wet_body[p->wet_order[k - 1]] > p->wet_body[w] ||
+ (p->wet_body[p->wet_order[k - 1]] == p->wet_body[w] && p->wet_x[p->wet_order[k - 1]] > p->wet_x[w])))
+ {
+ p->wet_order[k] = p->wet_order[k - 1];
+ --k;
+ }
+ p->wet_order[k] = w;
+ }
+ }
+ for (int32_t b = 0; b < p->body_capacity; ++b)
+ {
+ p->wet_body_start[b] = p->wet_body_count[b] = 0;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t w = p->wet_order[k];
+ int32_t b = p->wet_body[w];
+ float* box = p->wet_body_box + 7 * (int64_t)b;
+ float c[3] = {p->wet_x[w], p->wet_y[w], p->wet_z[w]};
+ if (p->wet_body_count[b]++ == 0)
+ {
+ p->wet_body_start[b] = k;
+ for (int a = 0; a < 3; ++a)
+ {
+ box[a] = c[a] - p->wet_radius[w];
+ box[3 + a] = c[a] + p->wet_radius[w];
+ }
+ box[6] = p->wet_radius[w];
+ continue;
+ }
+ for (int a = 0; a < 3; ++a)
+ {
+ box[a] = vmin(box[a], c[a] - p->wet_radius[w]);
+ box[3 + a] = vmax(box[3 + a], c[a] + p->wet_radius[w]);
+ }
+ box[6] = vmax(box[6], p->wet_radius[w]);
+ }
+}
+
+// ---- derivation: components and tethers ----------------------------------------------------------------------
+
+static int heap_less(const ymir_particles* p, int32_t i, int32_t j)
+{
+ if (p->heap_key[i] != p->heap_key[j])
+ {
+ return p->heap_key[i] < p->heap_key[j];
+ }
+ if (p->heap_node[i] != p->heap_node[j])
+ {
+ return p->heap_node[i] < p->heap_node[j];
+ }
+ return p->heap_edge[i] < p->heap_edge[j];
+}
+
+static void heap_swap(ymir_particles* p, int32_t i, int32_t j)
+{
+ float k = p->heap_key[i]; p->heap_key[i] = p->heap_key[j]; p->heap_key[j] = k;
+ int32_t n = p->heap_node[i]; p->heap_node[i] = p->heap_node[j]; p->heap_node[j] = n;
+ int32_t e = p->heap_edge[i]; p->heap_edge[i] = p->heap_edge[j]; p->heap_edge[j] = e;
+}
+
+static void heap_push(ymir_particles* p, int32_t* size, float key, int32_t node, int32_t edge)
+{
+ int32_t i = (*size)++;
+ p->heap_key[i] = key;
+ p->heap_node[i] = node;
+ p->heap_edge[i] = edge;
+ while (i > 0 && heap_less(p, i, (i - 1) / 2))
+ {
+ heap_swap(p, i, (i - 1) / 2);
+ i = (i - 1) / 2;
+ }
+}
+
+// Moves the smallest entry to slot `size` (just past the shrunk heap), where the caller reads it.
+static void heap_pop(ymir_particles* p, int32_t* size)
+{
+ int32_t n = --(*size);
+ heap_swap(p, 0, n);
+ int32_t i = 0;
+ for (;;)
+ {
+ int32_t l = 2 * i + 1, r = l + 1, m = i;
+ if (l < n && heap_less(p, l, m))
+ {
+ m = l;
+ }
+ if (r < n && heap_less(p, r, m))
+ {
+ m = r;
+ }
+ if (m == i)
+ {
+ break;
+ }
+ heap_swap(p, i, m);
+ i = m;
+ }
+}
+
+
+static int is_tether(const ymir_particles* p, int32_t a)
+{
+ return p->att_kind[a] != YMIR_ATTACH_REMOVED && (p->att_flags[a] & YMIR_ATTACH_FLAG_TETHER);
+}
+
+// 1 when attachments a < b are both tethers on different particles of one component (`label` names components) and at
+// least one is on a body, so the rest path between their particles bounds the distance between their points. Two world
+// points never move: their pair has no end to pull (end_w is 0 at both).
+static int pairs_with(const ymir_particles* p, int32_t a, int32_t b, const int32_t* label)
+{
+ int32_t pa = p->att_particle[a], pb = p->att_particle[b];
+ return is_tether(p, b) && pa != pb && label[pa] == label[pb] &&
+ (p->att_kind[a] == YMIR_ATTACH_BODY || p->att_kind[b] == YMIR_ATTACH_BODY);
+}
+
+// Dijkstra (binary heap, ties by node then edge) over the live distances' rest lengths, from one attachment's particle
+// (`only` >= 0) or from every particle of the tether island named `island` (>= 0; `isle` labels them). Writes for each
+// settled particle its rest path `path`, the edge it was reached by `via` (-1 at a source), the attachment it is nearest
+// `owner` (the lowest TETHER attachment on a source particle), and its place in settle order `queue`: a parent settles
+// before its children. In island mode a tether particle of another island is settled but not expanded: the path through
+// it is implied by its own tethers and the pair tethers. Returns the settled count. Writes no lane.
+static int32_t settle(ymir_particles* p, int32_t only, int32_t island)
+{
+ int32_t size = 0, n = 0;
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ p->path[i] = 1.0e30f;
+ p->done[i] = 0;
+ p->via[i] = -1;
+ p->owner[i] = -1;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ int32_t s = p->att_particle[a];
+ if (only >= 0 ? a != only : !is_tether(p, a) || p->isle[s] != island)
+ {
+ continue;
+ }
+ if (p->path[s] != 0.0f)
+ {
+ p->path[s] = 0.0f;
+ p->owner[s] = a;
+ heap_push(p, &size, 0.0f, s, -1);
+ }
+ }
+ while (size > 0)
+ {
+ heap_pop(p, &size);
+ float key = p->heap_key[size];
+ int32_t u = p->heap_node[size];
+ if (p->done[u])
+ {
+ continue;
+ }
+ p->done[u] = 1;
+ p->queue[n++] = u;
+ if (only < 0 && p->isle[u] >= 0 && p->via[u] >= 0)
+ {
+ continue; // another island's tether particle: settled, not expanded
+ }
+ for (int32_t k = p->adj_start[u]; k < p->adj_start[u + 1]; ++k)
+ {
+ int32_t e = p->adj_edge[k], v = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e];
+ float nd = key + p->dist_rest[e];
+ if (!p->done[v] && nd < p->path[v])
+ {
+ p->path[v] = nd;
+ p->via[v] = e;
+ p->owner[v] = p->owner[u];
+ heap_push(p, &size, nd, v, e);
+ }
+ }
+ }
+ return n;
+}
+
+// The edge count of the settled path from a source to particle q, and the particle one edge nearer the source.
+static int32_t route_length(const ymir_particles* p, int32_t q)
+{
+ int32_t k = 0;
+ for (int32_t u = q; p->via[u] >= 0; ++k)
+ {
+ int32_t e = p->via[u];
+ u = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e];
+ }
+ return k;
+}
+
+// 1 when attachment a (a tether) has a later tether on another particle of its component: a pair to derive.
+static int has_pair(const ymir_particles* p, int32_t a, const int32_t* label)
+{
+ for (int32_t b = a + 1; b < p->attachment_count; ++b)
+ {
+ if (pairs_with(p, a, b, label))
+ {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+// The only writer of the active lists, the counts, anchor and w. Called at the end of rederive_topology (every topology command and
+// set_pinned): the step walks only these, so what a step visits is decided at command time and never tested per lane. A distance or bend
+// is active when one of its particles is unpinned; a pinned particle it reaches is kinematic (the step holds it on its anchor), and the
+// bend's three particles all count, since a bend reads b against the centroid of a and c.
+static void rederive_active(ymir_particles* p)
+{
+ int32_t np = p->particle_count;
+ for (int32_t i = 0; i < np; ++i)
+ {
+ // a pinned particle keeps the anchor it was pinned on (remove refuses it, destroy unpins), so no lane another command takes can move its pose
+ p->anchor[i] = p->pinned[i] ? p->anchor[i] : -1;
+ p->w[i] = p->particle_live[i] && !p->pinned[i] ? p->inv_mass[i] : 0.0f;
+ p->done[i] = 0; // scratch: marks the kinematic
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ int32_t i = p->att_particle[a];
+ if (p->att_kind[a] != YMIR_ATTACH_REMOVED && !(p->att_flags[a] & YMIR_ATTACH_FLAG_TETHER) && p->anchor[i] < 0)
+ {
+ p->anchor[i] = a;
+ }
+ }
+ int32_t n = 0;
+ for (int32_t i = 0; i < np; ++i)
+ {
+ if (p->particle_live[i] && !p->pinned[i])
+ {
+ p->act[n++] = i;
+ }
+ }
+ p->act_n = n;
+ n = 0;
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (p->att_kind[a] != YMIR_ATTACH_REMOVED && !p->pinned[p->att_particle[a]])
+ {
+ p->act_att[n++] = a;
+ }
+ }
+ p->act_att_n = n;
+ n = 0;
+ for (int32_t e = 0; e < p->distance_count; ++e)
+ {
+ int32_t i = p->dist_a[e], j = p->dist_b[e];
+ if (p->dist_live[e] && (!p->pinned[i] || !p->pinned[j]))
+ {
+ p->act_dist[n++] = e;
+ p->done[i] = p->done[j] = 1;
+ }
+ }
+ p->act_dist_n = n;
+ n = 0;
+ for (int32_t k = 0; k < p->bend_count; ++k)
+ {
+ int32_t a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k];
+ if (p->bend_live[k] && (!p->pinned[a] || !p->pinned[b] || !p->pinned[c]))
+ {
+ p->act_bend[n++] = k;
+ p->done[a] = p->done[b] = p->done[c] = 1;
+ }
+ }
+ p->act_bend_n = n;
+ n = 0;
+ for (int32_t i = 0; i < np; ++i)
+ {
+ if (p->particle_live[i] && p->pinned[i] && p->done[i])
+ {
+ p->kin[n++] = i;
+ }
+ }
+ p->kin_n = n;
+}
+
+// 1 when a distance component (`label` names them by a lane) holds both a live pinned particle and a live TETHER attachment.
+// A tether loads every lane of its component and no walk moves a pinned one, so no derivation admits it. done is scratch.
+static int pinned_meets_tether(ymir_particles* p, const int32_t* label)
+{
+ int32_t np = p->particle_count;
+ memset(p->done, 0, (size_t)np);
+ for (int32_t i = 0; i < np; ++i)
+ {
+ if (p->particle_live[i] && p->pinned[i])
+ {
+ p->done[label[i]] |= 1;
+ }
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (is_tether(p, a))
+ {
+ p->done[label[p->att_particle[a]]] |= 2;
+ }
+ }
+ for (int32_t i = 0; i < np; ++i)
+ {
+ if (p->done[i] == 3)
+ {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+// The only writer of the tether lanes and the component lane, and the one check that no component holds both pinned flesh
+// and a TETHER (pinned_meets_tether). Called at the end of every topology command and of set_pinned. The tether count and
+// the check are settled from the components before anything is written: a derivation that would not fit, or would admit a
+// pinned particle and a tether in one component, is refused (FULL, INVALID_ARGUMENT) with every lane as it was, and the
+// command backs its own lanes out.
+// ISOLATED is for a command that changed no distance and no attachment, only which lanes are live: the graph, so every
+// tether and every other lane's component, is as it was. It writes the component of the `n` lanes in `lanes` (each
+// just created, which is its own component, or just destroyed, which reads 0), their held list (empty) and limb body (-1),
+// and returns. A new particle is unpinned with no attachment and a destroyed one holds nothing, so it needs no check.
+// PINNED is for a command that changed only which lanes are pinned: the graph and every component are as they were, so it
+// checks on the component lane and derives the active lists.
+enum
+{
+ TOPO_FULL = 0,
+ TOPO_ISOLATED = 1,
+ TOPO_PINNED = 2
+};
+
+static int32_t rederive_topology(ymir_particles* p, int mode, const int32_t* lanes, int32_t n)
+{
+ if (mode == TOPO_PINNED)
+ {
+ if (pinned_meets_tether(p, p->component))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ rederive_active(p);
+ return YMIR_PARTICLES_OK;
+ }
+ if (mode == TOPO_ISOLATED)
+ {
+ for (int32_t k = 0; k < n; ++k)
+ {
+ p->component[lanes[k]] = p->particle_live[lanes[k]] ? lanes[k] : 0;
+ p->held_count[lanes[k]] = 0;
+ p->limb_body[lanes[k]] = -1;
+ }
+ rederive_active(p);
+ return YMIR_PARTICLES_OK;
+ }
+ int32_t np = p->particle_count;
+ memset(p->adj_start, 0, sizeof(int32_t) * ((size_t)np + 1));
+ for (int32_t e = 0; e < p->distance_count; ++e)
+ {
+ if (p->dist_live[e])
+ {
+ p->adj_start[p->dist_a[e] + 1]++;
+ p->adj_start[p->dist_b[e] + 1]++;
+ }
+ }
+ for (int32_t i = 0; i < np; ++i)
+ {
+ p->adj_start[i + 1] += p->adj_start[i];
+ p->comp_size[i] = p->adj_start[i]; // fill cursors
+ }
+ for (int32_t e = 0; e < p->distance_count; ++e)
+ {
+ if (p->dist_live[e])
+ {
+ p->adj_edge[p->comp_size[p->dist_a[e]]++] = e;
+ p->adj_edge[p->comp_size[p->dist_b[e]]++] = e;
+ }
+ }
+ // components by breadth-first labelling from the lowest lane, labels held in tether_of until the count is settled
+ for (int32_t i = 0; i < np; ++i)
+ {
+ p->tether_of[i] = -1;
+ }
+ for (int32_t i = 0; i < np; ++i)
+ {
+ if (!p->particle_live[i] || p->tether_of[i] >= 0)
+ {
+ continue;
+ }
+ int32_t head = 0, tail = 0;
+ p->tether_of[i] = i;
+ p->queue[tail++] = i;
+ while (head < tail)
+ {
+ int32_t u = p->queue[head++];
+ for (int32_t k = p->adj_start[u]; k < p->adj_start[u + 1]; ++k)
+ {
+ int32_t e = p->adj_edge[k], v = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e];
+ if (p->tether_of[v] < 0)
+ {
+ p->tether_of[v] = i;
+ p->queue[tail++] = v;
+ }
+ }
+ }
+ p->comp_size[i] = tail;
+ }
+ if (pinned_meets_tether(p, p->tether_of))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT; // a tether and pinned flesh in one component: wake it first
+ }
+ // Islands (Kim 2012 sec. 3.4): a particle holding a live TETHER attachment is a tether particle; an island is a maximal
+ // set of them joined by live distances, named by its lowest TETHER attachment. isle labels tether particles, -1 elsewhere
+ // (-2 while a tether particle awaits its island).
+ for (int32_t i = 0; i < np; ++i)
+ {
+ p->isle[i] = -1;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (is_tether(p, a))
+ {
+ p->isle[p->att_particle[a]] = -2;
+ }
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ int32_t s = p->att_particle[a];
+ if (!is_tether(p, a) || p->isle[s] != -2)
+ {
+ continue;
+ }
+ int32_t head = 0, tail = 0;
+ p->isle[s] = a;
+ p->queue[tail++] = s;
+ while (head < tail)
+ {
+ int32_t u = p->queue[head++];
+ for (int32_t k = p->adj_start[u]; k < p->adj_start[u + 1]; ++k)
+ {
+ int32_t e = p->adj_edge[k], v = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e];
+ if (p->isle[v] == -2)
+ {
+ p->isle[v] = a;
+ p->queue[tail++] = v;
+ }
+ }
+ }
+ }
+ // Each particle that is not a tether particle is held to the nearest point of each of its YMIR_TETHER_ISLANDS nearest
+ // islands: pass 1 keeps, per particle, the nearest islands by rest path (ties to the lower island); pass 2 writes them.
+ // Plus for each pair of tether attachments with a body among them one pair tether behind a route of booking lanes along
+ // their rest path. Counted before written.
+ int64_t need = 0;
+ for (int32_t i = 0; i < YMIR_TETHER_ISLANDS * np; ++i)
+ {
+ p->near_isle[i] = -1;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (!is_tether(p, a) || p->isle[p->att_particle[a]] != a)
+ {
+ continue;
+ }
+ int32_t n = settle(p, -1, a);
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t u = p->queue[k];
+ if (p->via[u] < 0 || p->isle[u] >= 0)
+ {
+ continue;
+ }
+ int32_t* isl = p->near_isle + YMIR_TETHER_ISLANDS * u;
+ float* dist = p->near_path + YMIR_TETHER_ISLANDS * u;
+ float d = p->path[u];
+ int32_t m = 0;
+ while (m < YMIR_TETHER_ISLANDS && isl[m] >= 0 && !(d < dist[m])) // an equal path keeps the earlier island
+ {
+ ++m;
+ }
+ if (m == YMIR_TETHER_ISLANDS)
+ {
+ continue;
+ }
+ for (int32_t j = YMIR_TETHER_ISLANDS - 1; j > m; --j)
+ {
+ isl[j] = isl[j - 1];
+ dist[j] = dist[j - 1];
+ }
+ isl[m] = a;
+ dist[m] = d;
+ }
+ }
+ for (int32_t i = 0; i < YMIR_TETHER_ISLANDS * np; ++i)
+ {
+ need += p->near_isle[i] >= 0;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (!is_tether(p, a) || !has_pair(p, a, p->tether_of))
+ {
+ continue;
+ }
+ settle(p, a, -1);
+ for (int32_t b = a + 1; b < p->attachment_count; ++b)
+ {
+ if (pairs_with(p, a, b, p->tether_of))
+ {
+ need += 1 + route_length(p, p->att_particle[b]);
+ }
+ }
+ }
+ if (need > p->tether_capacity)
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ for (int32_t i = 0; i < np; ++i)
+ {
+ p->component[i] = p->tether_of[i] >= 0 ? p->tether_of[i] : 0;
+ p->held_count[i] = 0;
+ p->limb_body[i] = -1;
+ }
+ // The held lists: held_start first holds each particle's slice end, then the attachments are walked from the highest
+ // lane down, each taking the slot below, so a slice ends up in ascending attachment lane order and starts at held_start.
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (p->att_kind[a] == YMIR_ATTACH_BODY)
+ {
+ p->held_count[p->att_particle[a]]++;
+ }
+ }
+ for (int32_t i = 0, end = 0; i < np; ++i)
+ {
+ end += p->held_count[i];
+ p->held_start[i] = end;
+ }
+ for (int32_t a = p->attachment_count - 1; a >= 0; --a)
+ {
+ if (p->att_kind[a] == YMIR_ATTACH_BODY)
+ {
+ int32_t i = p->att_particle[a];
+ p->held_body[--p->held_start[i]] = p->att_body[a];
+ if (p->att_flags[a] & YMIR_ATTACH_FLAG_LIMB)
+ {
+ p->limb_body[i] = p->att_body[a]; // descending: the lowest lane's body is the last written
+ }
+ }
+ }
+ int32_t nt = 0;
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (!is_tether(p, a) || p->isle[p->att_particle[a]] != a)
+ {
+ continue;
+ }
+ int32_t n = settle(p, -1, a);
+ for (int32_t i = 0; i < np; ++i)
+ {
+ p->tether_of[i] = -1;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t u = p->queue[k], e = p->via[u], held = 0;
+ if (e < 0 || p->isle[u] >= 0)
+ {
+ continue;
+ }
+ for (int32_t m = 0; m < YMIR_TETHER_ISLANDS; ++m)
+ {
+ held |= p->near_isle[YMIR_TETHER_ISLANDS * u + m] == a;
+ }
+ int32_t other = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e];
+ if (!held || (p->via[other] >= 0 && p->tether_of[other] < 0))
+ {
+ continue; // not one of u's nearest islands; or its parent is not held to this island (a float tie at rank 2)
+ }
+ int32_t t = nt++;
+ p->tether_att[t] = p->owner[u];
+ p->tether_particle[t] = u;
+ p->tether_bound[t] = p->path[u];
+ p->tether_edge[t] = e;
+ p->tether_other[t] = -1;
+ p->tether_parent[t] = p->tether_of[other];
+ p->tether_of[u] = t;
+ }
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (!is_tether(p, a) || !has_pair(p, a, p->component))
+ {
+ continue;
+ }
+ settle(p, a, -1);
+ for (int32_t b = a + 1; b < p->attachment_count; ++b)
+ {
+ if (!pairs_with(p, a, b, p->component))
+ {
+ continue;
+ }
+ int32_t q = p->att_particle[b], len = route_length(p, q), first = nt, u = q;
+ for (int32_t m = len - 1; m >= 0; --m) // the route, written from the source end: parents first
+ {
+ int32_t e = p->via[u], t = first + m;
+ p->tether_att[t] = -1;
+ p->tether_particle[t] = u;
+ p->tether_bound[t] = p->path[u];
+ p->tether_edge[t] = e;
+ p->tether_other[t] = -1;
+ p->tether_parent[t] = m == 0 ? -1 : t - 1;
+ u = p->dist_a[e] == u ? p->dist_b[e] : p->dist_a[e];
+ }
+ int32_t t = first + len;
+ p->tether_att[t] = a;
+ p->tether_particle[t] = q;
+ p->tether_bound[t] = p->path[q];
+ p->tether_edge[t] = -1;
+ p->tether_other[t] = b;
+ p->tether_parent[t] = t - 1;
+ nt = t + 1;
+ }
+ }
+ p->tether_count = nt;
+ rederive_active(p);
+ return YMIR_PARTICLES_OK;
+}
+
+// ---- commands ------------------------------------------------------------------------------------------------
+
+int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out)
+{
+ if (p == NULL || n < 0 || (n > 0 && d == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (!finite3(d[k].position) || !finite3(d[k].rest) || !finite3(d[k].velocity) || !isfinite(d[k].mass) || d[k].mass < 0.0f ||
+ (d[k].mass > 0.0f && !isfinite(1.0f / d[k].mass)) || !isfinite(d[k].radius) || d[k].radius <= 0.0f ||
+ (d[k].phase & ~(uint32_t)YMIR_PHASE_VALID) != 0 ||
+ ((d[k].phase & YMIR_PHASE_FLUID) && (d[k].phase & YMIR_PHASE_NO_PARTICLE_CONTACT)) ||
+ d[k].material >= (uint32_t)p->material_capacity)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ int32_t fluid = 0; // the fluid capacity sizes the neighbour arena: a batch past it is refused whole
+ for (int32_t k = 0; k < n; ++k)
+ {
+ fluid += (d[k].phase & YMIR_PHASE_FLUID) != 0;
+ }
+ if (p->live_fluid + fluid > p->fluid_capacity)
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ if (free_count(p->particle_live, 0, p->particle_removed_at, p->particle_count, p->particle_capacity, step_count) < n)
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ int32_t cursor = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t i = next_lane(p->particle_live, 0, p->particle_removed_at, p->particle_count, p->particle_capacity, cursor, step_count);
+ cursor = i + 1;
+ p->particle_count = i + 1 > p->particle_count ? i + 1 : p->particle_count;
+ p->pos_x[i] = d[k].position[0]; p->pos_y[i] = d[k].position[1]; p->pos_z[i] = d[k].position[2];
+ p->vel_x[i] = d[k].velocity[0]; p->vel_y[i] = d[k].velocity[1]; p->vel_z[i] = d[k].velocity[2];
+ p->rest_x[i] = d[k].rest[0]; p->rest_y[i] = d[k].rest[1]; p->rest_z[i] = d[k].rest[2];
+ p->radius[i] = d[k].radius;
+ p->inv_mass[i] = d[k].mass > 0.0f ? 1.0f / d[k].mass : 0.0f;
+ p->phase[i] = d[k].phase;
+ p->material[i] = d[k].material;
+ p->support_body[i] = p->support_particle[i] = -1;
+ p->particle_live[i] = 1;
+ p->live_particles++;
+ p->live_fluid += (d[k].phase & YMIR_PHASE_FLUID) != 0;
+ p->queue[k] = i;
+ if (out != NULL)
+ {
+ out[k] = (ymir_handle){i, p->particle_generation[i]};
+ }
+ }
+ return rederive_topology(p, TOPO_ISOLATED, p->queue, n); // a new particle holds no constraint
+}
+
+int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count)
+{
+ if (p == NULL || n < 0 || (n > 0 && h == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (!particle_ok(p, h[k].lane, h[k].generation))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ int held = 0; // whether a named particle holds a live distance: then the graph changes (an attachment alone makes no tether lane)
+ for (int32_t k = 0; k < n && !held; ++k)
+ {
+ int32_t i = h[k].lane;
+ for (int32_t e = 0; e < p->distance_count && !held; ++e)
+ {
+ held = p->dist_live[e] && (p->dist_a[e] == i || p->dist_b[e] == i);
+ }
+ }
+ int32_t killed = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t i = h[k].lane;
+ if (!p->particle_live[i])
+ {
+ continue; // named twice
+ }
+ p->queue[killed++] = i;
+ p->live_fluid -= (p->phase[i] & YMIR_PHASE_FLUID) != 0;
+ for (int32_t e = 0; e < p->distance_count; ++e)
+ {
+ if (p->dist_live[e] && (p->dist_a[e] == i || p->dist_b[e] == i))
+ {
+ kill_distance(p, e, step_count);
+ }
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (p->att_kind[a] != YMIR_ATTACH_REMOVED && p->att_particle[a] == i)
+ {
+ kill_attachment(p, a, step_count);
+ }
+ }
+ p->pos_x[i] = p->pos_y[i] = p->pos_z[i] = 0.0f;
+ p->vel_x[i] = p->vel_y[i] = p->vel_z[i] = 0.0f;
+ p->rest_x[i] = p->rest_y[i] = p->rest_z[i] = 0.0f;
+ p->radius[i] = p->inv_mass[i] = 0.0f;
+ p->phase[i] = p->material[i] = p->pinned[i] = 0;
+ p->density[i] = p->lambda[i] = 0.0f;
+ p->support_body[i] = p->support_particle[i] = -1;
+ p->particle_live[i] = 0;
+ p->particle_generation[i] += 1;
+ p->particle_removed_at[i] = step_count;
+ p->live_particles--;
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (p->particle_live[i] && p->support_particle[i] >= 0 && !p->particle_live[p->support_particle[i]])
+ {
+ p->support_particle[i] = -1; // a drop does not keep resting on a solid destroyed under it until the next step
+ }
+ }
+ int wet_killed = 0;
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (p->wet_live[w] && p->wet_particle[w] >= 0 && !p->particle_live[p->wet_particle[w]])
+ {
+ kill_wet(p, w, step_count); // the liquid on a destroyed solid goes with it; a particle patch is on no body, so wet_volume_body does not change
+ wet_killed = 1;
+ }
+ }
+ if (wet_killed)
+ {
+ rederive_wet(p); // the dry lane reads +inf again
+ }
+ return rederive_topology(p, held ? TOPO_FULL : TOPO_ISOLATED, p->queue, killed);
+}
+
+int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out)
+{
+ if (p == NULL || n < 0 || (n > 0 && d == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (!particle_ok(p, d[k].a.lane, d[k].a.generation) || !particle_ok(p, d[k].b.lane, d[k].b.generation) ||
+ d[k].a.lane == d[k].b.lane || !isfinite(d[k].rest) || !isfinite(d[k].compliance) || d[k].compliance < 0.0f ||
+ ((p->phase[d[k].a.lane] | p->phase[d[k].b.lane]) & YMIR_PHASE_FLUID) != 0) // fluid holds no constraint
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ if (free_count(p->dist_live, 0, p->dist_removed_at, p->distance_count, p->distance_capacity, step_count) < n)
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ int32_t old_count = p->distance_count, cursor = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t e = next_lane(p->dist_live, 0, p->dist_removed_at, p->distance_count, p->distance_capacity, cursor, step_count);
+ cursor = e + 1;
+ int32_t a = d[k].a.lane, b = d[k].b.lane;
+ p->lane_list[k] = e;
+ p->distance_count = e + 1 > p->distance_count ? e + 1 : p->distance_count;
+ p->dist_a[e] = a;
+ p->dist_b[e] = b;
+ p->dist_rest[e] = d[k].rest >= 0.0f
+ ? d[k].rest
+ : vlen(vsub((v3){p->rest_x[a], p->rest_y[a], p->rest_z[a]}, (v3){p->rest_x[b], p->rest_y[b], p->rest_z[b]}));
+ p->dist_compliance[e] = d[k].compliance;
+ p->dist_tension[e] = 0.0f;
+ p->dist_live[e] = 1;
+ }
+ int32_t status = rederive_topology(p, TOPO_FULL, NULL, 0);
+ if (status != YMIR_PARTICLES_OK)
+ {
+ for (int32_t k = 0; k < n; ++k) // back out: the lanes read as they did before the command
+ {
+ int32_t e = p->lane_list[k];
+ p->dist_a[e] = p->dist_b[e] = 0;
+ p->dist_rest[e] = p->dist_compliance[e] = 0.0f;
+ p->dist_live[e] = 0;
+ }
+ p->distance_count = old_count;
+ return status;
+ }
+ if (out != NULL)
+ {
+ for (int32_t k = 0; k < n; ++k)
+ {
+ out[k] = (ymir_handle){p->lane_list[k], p->dist_generation[p->lane_list[k]]};
+ }
+ }
+ return YMIR_PARTICLES_OK;
+}
+
+int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out)
+{
+ if (p == NULL || n < 0 || (n > 0 && d == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t e1 = d[k].e1.lane, e2 = d[k].e2.lane;
+ if (!distance_ok(p, e1, d[k].e1.generation) || !distance_ok(p, e2, d[k].e2.generation) || e1 == e2 ||
+ !isfinite(d[k].compliance) || !isfinite(d[k].max_angle) || d[k].max_angle > 3.14159265f ||
+ (d[k].compliance < 0.0f && d[k].max_angle < 0.0f) || !(p->dist_rest[e1] > 0.0f) || !(p->dist_rest[e2] > 0.0f))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT; // a bend that does nothing, or over links of no length, or not over two links
+ }
+ int32_t a1 = p->dist_a[e1], b1 = p->dist_b[e1], a2 = p->dist_a[e2], b2 = p->dist_b[e2];
+ int shared = (a1 == a2) + (a1 == b2) + (b1 == a2) + (b1 == b2);
+ if (shared != 1)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT; // the two distances must share exactly one particle
+ }
+ }
+ if (free_count(p->bend_live, 0, p->bend_removed_at, p->bend_count, p->bend_capacity, step_count) < n)
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ int32_t cursor = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t i = next_lane(p->bend_live, 0, p->bend_removed_at, p->bend_count, p->bend_capacity, cursor, step_count);
+ cursor = i + 1;
+ int32_t e1 = d[k].e1.lane, e2 = d[k].e2.lane;
+ int32_t a1 = p->dist_a[e1], b1 = p->dist_b[e1], a2 = p->dist_a[e2], b2 = p->dist_b[e2];
+ int32_t a, b, c;
+ if (b1 == a2) { a = a1; b = b1; c = b2; }
+ else if (a1 == a2) { a = b1; b = a1; c = b2; }
+ else if (b1 == b2) { a = a1; b = b1; c = a2; }
+ else { a = b1; b = a1; c = a2; }
+ p->bend_count = i + 1 > p->bend_count ? i + 1 : p->bend_count;
+ p->bend_e1[i] = e1; p->bend_e2[i] = e2;
+ p->bend_a[i] = a; p->bend_b[i] = b; p->bend_c[i] = c;
+ v3 ra = {p->rest_x[a], p->rest_y[a], p->rest_z[a]}, rb = {p->rest_x[b], p->rest_y[b], p->rest_z[b]},
+ rc = {p->rest_x[c], p->rest_y[c], p->rest_z[c]};
+ v3 centroid = vmul(vadd(vadd(ra, rb), rc), 1.0f / 3.0f);
+ p->bend_rest[i] = vlen(vsub(rb, centroid));
+ float l1 = p->dist_rest[e1], l2 = p->dist_rest[e2];
+ // |b - centroid| = |(a - b) + (c - b)| / 3, and at deflection phi from straight the links' sum has
+ // squared length l1^2 + l2^2 - 2 l1 l2 cos(phi): the offset at the limit.
+ p->bend_limit[i] = d[k].max_angle < 0.0f ? -1.0f : sqrtf(vmax(0.0f, l1 * l1 + l2 * l2 - 2.0f * l1 * l2 * cosf(d[k].max_angle))) / 3.0f;
+ p->bend_compliance[i] = d[k].compliance;
+ p->bend_live[i] = 1;
+ if (out != NULL)
+ {
+ out[k] = (ymir_handle){i, p->bend_generation[i]};
+ }
+ }
+ return rederive_topology(p, TOPO_FULL, NULL, 0);
+}
+
+int32_t ymir_particles_attach(ymir_particles* p, int32_t n, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out)
+{
+ if (p == NULL || n < 0 || (n > 0 && d == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if ((d[k].kind != YMIR_ATTACH_BODY && d[k].kind != YMIR_ATTACH_STATIC) ||
+ (d[k].flags & ~(uint32_t)(YMIR_ATTACH_FLAG_TETHER | YMIR_ATTACH_FLAG_LIMB | YMIR_ATTACH_FLAG_ONE_WAY)) != 0 ||
+ (d[k].kind == YMIR_ATTACH_STATIC && (d[k].flags & (YMIR_ATTACH_FLAG_LIMB | YMIR_ATTACH_FLAG_ONE_WAY)) != 0) ||
+ !particle_ok(p, d[k].particle.lane, d[k].particle.generation) || !finite3(d[k].point) || !isfinite(d[k].compliance) ||
+ d[k].compliance < 0.0f || (p->phase[d[k].particle.lane] & YMIR_PHASE_FLUID) != 0 || // fluid holds no constraint
+ (d[k].kind == YMIR_ATTACH_BODY && (d[k].body < 0 || d[k].body >= body_count)))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ if (free_count(p->att_kind, YMIR_ATTACH_REMOVED, p->att_removed_at, p->attachment_count, p->attachment_capacity, step_count) < n)
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ int32_t old_count = p->attachment_count, cursor = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t a = next_lane(p->att_kind, YMIR_ATTACH_REMOVED, p->att_removed_at, p->attachment_count, p->attachment_capacity, cursor, step_count);
+ cursor = a + 1;
+ p->lane_list[k] = a;
+ p->attachment_count = a + 1 > p->attachment_count ? a + 1 : p->attachment_count;
+ p->att_kind[a] = d[k].kind;
+ p->att_flags[a] = d[k].flags;
+ p->att_particle[a] = d[k].particle.lane;
+ p->att_body[a] = d[k].kind == YMIR_ATTACH_BODY ? d[k].body : -1;
+ p->att_point_x[a] = d[k].point[0];
+ p->att_point_y[a] = d[k].point[1];
+ p->att_point_z[a] = d[k].point[2];
+ p->att_compliance[a] = d[k].compliance;
+ p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f;
+ }
+ int32_t status = rederive_topology(p, TOPO_FULL, NULL, 0);
+ if (status != YMIR_PARTICLES_OK)
+ {
+ for (int32_t k = 0; k < n; ++k) // back out: the lanes read as they did before the command
+ {
+ int32_t a = p->lane_list[k];
+ p->att_kind[a] = a < old_count ? YMIR_ATTACH_REMOVED : 0;
+ p->att_flags[a] = 0;
+ p->att_particle[a] = a < old_count ? -1 : 0;
+ p->att_body[a] = a < old_count ? -1 : 0;
+ p->att_point_x[a] = p->att_point_y[a] = p->att_point_z[a] = 0.0f;
+ p->att_compliance[a] = 0.0f;
+ }
+ p->attachment_count = old_count;
+ return status;
+ }
+ if (out != NULL)
+ {
+ for (int32_t k = 0; k < n; ++k)
+ {
+ out[k] = (ymir_handle){p->lane_list[k], p->att_generation[p->lane_list[k]]};
+ }
+ }
+ return YMIR_PARTICLES_OK;
+}
+
+int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count)
+{
+ if (p == NULL || n < 0 || (n > 0 && h == NULL) ||
+ (type != YMIR_LANES_DISTANCE && type != YMIR_LANES_BEND && type != YMIR_LANES_ATTACHMENT && type != YMIR_LANES_WET &&
+ type != YMIR_LANES_SENSOR))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int ok = type == YMIR_LANES_DISTANCE ? distance_ok(p, h[k].lane, h[k].generation)
+ : type == YMIR_LANES_BEND ? bend_ok(p, h[k].lane, h[k].generation)
+ : type == YMIR_LANES_WET ? wet_ok(p, h[k].lane, h[k].generation)
+ : type == YMIR_LANES_SENSOR ? sensor_ok(p, h[k].lane, h[k].generation)
+ : attachment_ok(p, h[k].lane, h[k].generation);
+ if (!ok)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ for (int32_t k = 0; type == YMIR_LANES_ATTACHMENT && k < n; ++k)
+ {
+ int32_t i = p->att_particle[h[k].lane];
+ if (p->pinned[i] && p->anchor[i] == h[k].lane)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT; // a pinned particle is drawn from its anchor: wake it first
+ }
+ }
+ if (type == YMIR_LANES_SENSOR)
+ {
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (p->sensor_live[h[k].lane])
+ {
+ kill_sensor(p, h[k].lane, step_count);
+ }
+ }
+ return YMIR_PARTICLES_OK; // a sensor is in no graph: never rederive_topology
+ }
+ if (type == YMIR_LANES_WET)
+ {
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (p->wet_live[h[k].lane])
+ {
+ kill_wet(p, h[k].lane, step_count);
+ }
+ }
+ rederive_wet(p); // patches change no graph: never through rederive_topology
+ return YMIR_PARTICLES_OK;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t lane = h[k].lane;
+ if (type == YMIR_LANES_DISTANCE && p->dist_live[lane])
+ {
+ kill_distance(p, lane, step_count);
+ }
+ else if (type == YMIR_LANES_BEND && p->bend_live[lane])
+ {
+ kill_bend(p, lane, step_count);
+ }
+ else if (type == YMIR_LANES_ATTACHMENT && p->att_kind[lane] != YMIR_ATTACH_REMOVED)
+ {
+ kill_attachment(p, lane, step_count);
+ }
+ }
+ return rederive_topology(p, TOPO_FULL, NULL, 0);
+}
+
+int32_t ymir_particles_release_body(ymir_particles* p, int32_t body, uint64_t step_count, uint32_t* patches, float* volume)
+{
+ if (p == NULL || body < 0 || body >= p->body_capacity)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ if (p->att_kind[a] == YMIR_ATTACH_BODY && p->att_body[a] == body)
+ {
+ return YMIR_PARTICLES_REFERENCED;
+ }
+ }
+ for (int32_t s = 0; s < p->sensor_count; ++s)
+ {
+ if (p->sensor_live[s] && p->sensor_body[s] == body)
+ {
+ return YMIR_PARTICLES_REFERENCED;
+ }
+ }
+ uint32_t count = 0;
+ float total = 0.0f;
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (p->wet_live[w] && p->wet_body[w] == body)
+ {
+ count += 1;
+ total += p->wet_volume[w];
+ kill_wet(p, w, step_count);
+ }
+ }
+ if (count > 0)
+ {
+ rederive_wet(p);
+ }
+ if (patches != NULL)
+ {
+ *patches = count;
+ }
+ if (volume != NULL)
+ {
+ *volume = total;
+ }
+ return YMIR_PARTICLES_OK;
+}
+
+int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d)
+{
+ if (p == NULL || d == NULL || index < 0 || index >= p->material_capacity || !isfinite(d->friction) || d->friction < 0.0f ||
+ !isfinite(d->viscosity) || d->viscosity < 0.0f || !isfinite(d->wet_friction) || d->wet_friction < 0.0f)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ p->mat_friction[index] = d->friction;
+ p->mat_viscosity[index] = d->viscosity;
+ p->mat_wet_friction[index] = d->wet_friction;
+ p->mat_id[index] = d->material_id;
+ return YMIR_PARTICLES_OK;
+}
+
+// ---- the particle phase --------------------------------------------------------------------------------------
+
+typedef struct phase
+{
+ ymir_particles* p;
+ float h, inv_h;
+ float k; // force of a correction: lambda / h^2
+} phase;
+
+// Generalised inverse mass of a proxy along unit `n` at world point `at`.
+static float proxy_w(const ymir_particle_proxy* b, v3 at, v3 n)
+{
+ if (b->inv_mass == 0.0f)
+ {
+ return 0.0f;
+ }
+ v3 r = vsub(at, (v3){b->position[0], b->position[1], b->position[2]});
+ v3 rn = vcross(r, n);
+ return b->inv_mass + vdot(rn, mat_mul(b->inv_inertia, rn));
+}
+
+// Applies a position-level impulse `imp` (kg m) at `at` to a proxy: moves its predicted pose and books the
+// velocity-level impulse (imp / h) the caller applies to the body before Box3D integrates its position.
+static void proxy_push(const phase* f, ymir_particle_proxy* b, v3 at, v3 imp)
+{
+ if (b->inv_mass == 0.0f)
+ {
+ return;
+ }
+ v3 r = vsub(at, (v3){b->position[0], b->position[1], b->position[2]});
+ v3 torque = vcross(r, imp);
+ v3 dtheta = mat_mul(b->inv_inertia, torque);
+ b->position[0] += imp.x * b->inv_mass;
+ b->position[1] += imp.y * b->inv_mass;
+ b->position[2] += imp.z * b->inv_mass;
+ float* q = b->rotation;
+ float dq[4] = {
+ 0.5f * (dtheta.x * q[3] + dtheta.y * q[2] - dtheta.z * q[1]),
+ 0.5f * (dtheta.y * q[3] + dtheta.z * q[0] - dtheta.x * q[2]),
+ 0.5f * (dtheta.z * q[3] + dtheta.x * q[1] - dtheta.y * q[0]),
+ 0.5f * (-dtheta.x * q[0] - dtheta.y * q[1] - dtheta.z * q[2])};
+ float n2 = 0.0f;
+ for (int k = 0; k < 4; ++k)
+ {
+ q[k] += dq[k];
+ n2 += q[k] * q[k];
+ }
+ float inv = 1.0f / sqrtf(n2);
+ for (int k = 0; k < 4; ++k)
+ {
+ q[k] *= inv;
+ }
+ b->sub_impulse[0] += imp.x * f->inv_h;
+ b->sub_impulse[1] += imp.y * f->inv_h;
+ b->sub_impulse[2] += imp.z * f->inv_h;
+ b->sub_angular[0] += torque.x * f->inv_h;
+ b->sub_angular[1] += torque.y * f->inv_h;
+ b->sub_angular[2] += torque.z * f->inv_h;
+}
+
+// The world point an attachment holds, and the inverse mass of what it holds it to along `n`.
+static v3 end_point(const ymir_particles* p, int32_t a)
+{
+ if (p->att_kind[a] == YMIR_ATTACH_BODY)
+ {
+ const ymir_particle_proxy* b = p->proxies + p->att_body[a];
+ v3 local = {p->att_point_x[a], p->att_point_y[a], p->att_point_z[a]};
+ return vadd((v3){b->position[0], b->position[1], b->position[2]}, qrot(b->rotation, local));
+ }
+ return (v3){p->att_point_x[a], p->att_point_y[a], p->att_point_z[a]};
+}
+
+static float end_w(const ymir_particles* p, int32_t a, v3 at, v3 n)
+{
+ return p->att_kind[a] == YMIR_ATTACH_BODY && !(p->att_flags[a] & YMIR_ATTACH_FLAG_ONE_WAY) ? proxy_w(p->proxies + p->att_body[a], at, n) : 0.0f;
+}
+
+static void end_push(const phase* f, int32_t a, v3 at, v3 imp)
+{
+ ymir_particles* p = f->p;
+ if (p->att_kind[a] == YMIR_ATTACH_BODY && !(p->att_flags[a] & YMIR_ATTACH_FLAG_ONE_WAY))
+ {
+ proxy_push(f, p->proxies + p->att_body[a], at, imp);
+ }
+}
+
+// Adds a force (N) the attachment `a` exerts on its particles to its sensor lane.
+static void add_force(ymir_particles* p, int32_t a, v3 force)
+{
+ p->att_force_x[a] += force.x;
+ p->att_force_y[a] += force.y;
+ p->att_force_z[a] += force.z;
+}
+
+// ---- grid and particle-particle contact ----------------------------------------------------------------------
+
+static uint32_t cell_hash(int32_t a, int32_t b, int32_t c, uint32_t mask)
+{
+ return (((uint32_t)a * 73856093u) ^ ((uint32_t)b * 19349663u) ^ ((uint32_t)c * 83492791u)) & mask;
+}
+
+static int32_t cell_of(float v, float inv_cell)
+{
+ return (int32_t)vclamp(floorf(v * inv_cell), -1.0e6f, 1.0e6f);
+}
+
+// Counting sort into a hash grid of `mask` + 1 buckets and cell 1 / inv_cell: the live particles' predicted positions, fluid and
+// NO_PARTICLE_CONTACT lanes left out when `solids` is set. Within a bucket particles keep index order, so every neighbour walk is
+// the same on every run, whatever the bucket count.
+static void grid_sort(ymir_particles* p, float inv_cell, int solids, uint32_t mask)
+{
+ int32_t buckets = (int32_t)mask + 1;
+ memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1));
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ if (solids && (p->phase[i] & (YMIR_PHASE_FLUID | YMIR_PHASE_NO_PARTICLE_CONTACT)))
+ {
+ continue;
+ }
+ p->cell_x[i] = cell_of(p->pp_x[i], inv_cell);
+ p->cell_y[i] = cell_of(p->pp_y[i], inv_cell);
+ p->cell_z[i] = cell_of(p->pp_z[i], inv_cell);
+ p->cell_start[cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], mask) + 1]++;
+ }
+ for (int32_t c = 0; c < buckets; ++c)
+ {
+ p->cell_start[c + 1] += p->cell_start[c];
+ p->cell_fill[c] = 0;
+ }
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ if (!(solids && (p->phase[i] & (YMIR_PHASE_FLUID | YMIR_PHASE_NO_PARTICLE_CONTACT))))
+ {
+ uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], mask);
+ p->sorted[p->cell_start[c] + p->cell_fill[c]++] = i;
+ }
+ }
+}
+
+// The contact grid: the lanes that are neither fluid nor NO_PARTICLE_CONTACT, at a cell of 2 rmax, which holds every contact pair
+// (reach 2 rmax). Its bucket count follows its members, sized as create sizes table_mask and never above it. Fluid lanes meet the
+// others in fluid_density, on a grid of their own.
+static void build_grid(ymir_particles* p)
+{
+ float rmax = 0.0f;
+ int32_t members = 0;
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ if (!(p->phase[i] & (YMIR_PHASE_FLUID | YMIR_PHASE_NO_PARTICLE_CONTACT)))
+ {
+ rmax = vmax(rmax, p->radius[i]);
+ ++members;
+ }
+ }
+ uint32_t table = 16;
+ while (table < 2u * (uint32_t)members)
+ {
+ table <<= 1;
+ }
+ p->grid_mask = table - 1 < p->table_mask ? table - 1 : p->table_mask;
+ grid_sort(p, rmax > 0.0f ? 1.0f / (2.0f * rmax) : 0.0f, 1, p->grid_mask);
+}
+
+
+// Do particles i and j collide by contact? Symmetric in i and j, which momentum conservation needs. Two fluid particles
+// never do. Particles of different groups always do; of one group only when both set SELF_COLLIDE, and not, when either sets
+// SELF_FILTER, if they touched in the rest pose.
+static int collides(const ymir_particles* p, int32_t i, int32_t j)
+{
+ uint32_t a = p->phase[i], b = p->phase[j];
+ if (a & b & YMIR_PHASE_FLUID)
+ {
+ return 0; // two fluid particles meet in the density, not by contact
+ }
+ if ((a & YMIR_PHASE_GROUP_MASK) != (b & YMIR_PHASE_GROUP_MASK))
+ {
+ return 1;
+ }
+ if (!(a & b & YMIR_PHASE_SELF_COLLIDE))
+ {
+ return 0;
+ }
+ if ((a | b) & YMIR_PHASE_SELF_FILTER)
+ {
+ v3 d = vsub((v3){p->rest_x[i], p->rest_y[i], p->rest_z[i]}, (v3){p->rest_x[j], p->rest_y[j], p->rest_z[j]});
+ float reach = 1.5f * (p->radius[i] + p->radius[j]);
+ if (vdot(d, d) < reach * reach)
+ {
+ return 0;
+ }
+ }
+ return 1;
+}
+
+// The overlapping pair (i, j) found by the walk from i: the displacement from j to i, the contact distance, and the
+// inverse-mass sum. 1 when the pair collides, overlaps and has a particle that moves, else 0.
+static int touching(const ymir_particles* p, int32_t i, int32_t j, v3 xi, v3* d, float* r2, float* md, float* wsum)
+{
+ *d = vsub(xi, P(p, p->pp_x, p->pp_y, p->pp_z, j));
+ *md = p->radius[i] + p->radius[j];
+ *r2 = vdot(*d, *d);
+ *wsum = p->w[i] + p->w[j];
+ return *r2 < *md * *md && *r2 >= 1e-12f && *wsum != 0.0f && collides(p, i, j);
+}
+
+// The pairs of the live particles, each once: from every particle i, the partners j of its own cell with a higher index and
+// every partner of the 13 cells that follow its own in lexicographic offset order, cells read in that order and a cell's
+// particles in index order. `fn` sees each candidate pair (a bucket can hold other cells' particles; those are skipped here)
+// and decides if it counts. Inlined at each call, so the contact pass pays nothing for sharing the walk.
+#if defined(_MSC_VER)
+#define YMIR_INLINE static __forceinline
+#else
+#define YMIR_INLINE static inline __attribute__((always_inline))
+#endif
+
+typedef int (*pair_fn)(ymir_particles* p, void* ctx, int32_t i, int32_t j);
+
+YMIR_INLINE void walk_half(ymir_particles* p, pair_fn fn, void* ctx)
+{
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ if (p->phase[i] & (YMIR_PHASE_FLUID | YMIR_PHASE_NO_PARTICLE_CONTACT)) // the grid holds neither
+ {
+ continue;
+ }
+ for (int32_t cell = 0; cell < 14; ++cell) // 0 is the own cell; 1..13 are offsets 14..26 of the 27
+ {
+ int32_t o = cell == 0 ? 13 : 13 + cell, da = o / 9 - 1, db = o / 3 % 3 - 1, dc = o % 3 - 1;
+ int32_t ca = p->cell_x[i] + da, cb = p->cell_y[i] + db, cc = p->cell_z[i] + dc;
+ uint32_t bucket = cell_hash(ca, cb, cc, p->grid_mask);
+ for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q)
+ {
+ int32_t j = p->sorted[q];
+ if ((cell == 0 && j <= i) || p->cell_x[j] != ca || p->cell_y[j] != cb || p->cell_z[j] != cc)
+ {
+ continue; // the other end of a pair, or another cell sharing the bucket
+ }
+ fn(p, ctx, i, j);
+ }
+ }
+ }
+}
+
+// One pass of the contact walk: pass 0 counts every particle's overlaps, pass 1 moves both ends of each pair.
+static int contact_pair(ymir_particles* p, void* ctx, int32_t i, int32_t j) // 1 when the pair touches
+{
+ v3 d;
+ float r2, md, wsum;
+ if (!touching(p, i, j, P(p, p->pp_x, p->pp_y, p->pp_z, i), &d, &r2, &md, &wsum))
+ {
+ return 0;
+ }
+ if (*(int*)ctx == 0)
+ {
+ p->contacts[i]++;
+ p->contacts[j]++;
+ return 1;
+ }
+ float rr = sqrtf(r2), depth = (md - rr) / rr;
+ float weight = 1.0f / (float)(p->contacts[i] > p->contacts[j] ? p->contacts[i] : p->contacts[j]);
+ v3 di = vmul(d, weight * (p->w[i] / wsum) * depth);
+ v3 dj = vmul(d, weight * (p->w[j] / wsum) * depth);
+ p->dp_x[i] += di.x; p->dp_y[i] += di.y; p->dp_z[i] += di.z;
+ p->dp_x[j] -= dj.x; p->dp_y[j] -= dj.y; p->dp_z[j] -= dj.z;
+ return 1;
+}
+
+// Overlapping pairs push each other apart, split by inverse mass (Macklin 2014). Each pair is found once, by walking
+// half the 27-cell neighbourhood. Two walks: the first counts every particle's overlaps, the second moves both ends
+// of each pair by one displacement weighted 1 / max(n_i, n_j). The pair's two corrections then hold equal and
+// opposite momentum, so contact conserves it; a per-particle average would not. Pairs apply in walk order, so every
+// sum is the same on every run. No pair list is kept: its size is not bounded by the particle count.
+static void particle_contacts(ymir_particles* p)
+{
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ p->contacts[i] = 0;
+ p->dp_x[i] = p->dp_y[i] = p->dp_z[i] = 0.0f;
+ }
+ for (int pass = 0; pass < 2; ++pass)
+ {
+ walk_half(p, contact_pair, &pass);
+ }
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ p->pp_x[i] += p->dp_x[i];
+ p->pp_y[i] += p->dp_y[i];
+ p->pp_z[i] += p->dp_z[i];
+ }
+}
+
+// ---- fluid: number density (Macklin and Mueller 2013, unilateral as Macklin et al. 2014 sec. 7) and XSPH ---------------
+
+// The kernel reach of a pair: 4 r at equal radii. A kernel pair lies in the rings of cells fluid_grid sets.
+static float kernel_h(const ymir_particles* p, int32_t i, int32_t j)
+{
+ return 2.0f * (p->radius[i] + p->radius[j]);
+}
+
+static float n0_of(const ymir_particles* p, float h)
+{
+ return p->fluid_k / (h * h * h);
+}
+
+static float poly6(float r2, float h)
+{
+ float d = h * h - r2, h3 = h * h * h;
+ return d > 0.0f ? YMIR_POLY6 / (h3 * h3 * h3) * d * d * d : 0.0f;
+}
+
+// Gradient of W at displacement d (|d| = r) for reach h: Spiky, along d.
+static v3 spiky(v3 d, float r, float h)
+{
+ float h3 = h * h * h, t = h - r;
+ return vmul(d, YMIR_SPIKY / (h3 * h3) * t * t / r);
+}
+
+// Pass B: the pair's correction, (lambda_i + lambda_j) grad W / n0, with each end moving its own inverse mass times it (XPBD,
+// Macklin et al. 2016): equal and opposite momentum at any mass ratio, equal masses unchanged, a static end takes nothing.
+static void density_correct(ymir_particles* p, int32_t i, int32_t j)
+{
+ float wsum = p->w[i] + p->w[j];
+ if (wsum == 0.0f)
+ {
+ return;
+ }
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), P(p, p->pp_x, p->pp_y, p->pp_z, j));
+ float h = kernel_h(p, i, j), r2 = vdot(d, d), l = p->lambda[i] + p->lambda[j];
+ if (r2 >= h * h || r2 < 1e-12f || l == 0.0f)
+ {
+ return;
+ }
+ v3 corr = vmul(spiky(d, sqrtf(r2), h), l / n0_of(p, h));
+ v3 di = vmul(corr, p->w[i]), dj = vmul(corr, p->w[j]);
+ p->dp_x[i] += di.x; p->dp_y[i] += di.y; p->dp_z[i] += di.z;
+ p->dp_x[j] -= dj.x; p->dp_y[j] -= dj.y; p->dp_z[j] -= dj.z;
+}
+
+// The fluid grid: every live lane (a kernel pair can hold a solid) in the tables build_grid left, rebuilt at the kernel cell 4 rfmax.
+// A kernel pair reaches h = 2 (ri + rj), at most 2 (rfmax + rmax): fluid_rings cells hold it (1 at equal radii). Then the lanes'
+// predicted position, inverse mass and phase are copied into sorted order, so a bucket's candidates read contiguously; sorted[q] is
+// the lane of sorted index q. Nothing after the fluid pass reads this grid. Returns rmax over the live lanes.
+static float fluid_grid(ymir_particles* p)
+{
+ float rmax = 0.0f, rfmax = 0.0f;
+ for (int32_t k = 0; k < p->act_n; ++k)
+ {
+ int32_t i = p->act[k];
+ rmax = vmax(rmax, p->radius[i]);
+ rfmax = (p->phase[i] & YMIR_PHASE_FLUID) ? vmax(rfmax, p->radius[i]) : rfmax;
+ }
+ float inv_cell = 1.0f / (4.0f * rfmax);
+ p->fluid_rings = (int32_t)ceilf(2.0f * (rfmax + rmax) * inv_cell);
+ grid_sort(p, inv_cell, 0, p->table_mask);
+ for (int32_t q = 0; q < p->act_n; ++q) // the lanes grid_sort placed
+ {
+ int32_t j = p->sorted[q];
+ p->sx[q] = p->pp_x[j];
+ p->sy[q] = p->pp_y[j];
+ p->sz[q] = p->pp_z[j];
+ p->sw[q] = p->w[j];
+ p->sphase[q] = p->phase[j];
+ }
+ memset(p->cell_fill, 0, sizeof(int32_t) * ((size_t)p->table_mask + 1)); // the buckets' visit stamps, pass A
+ return rmax;
+}
+
+// Density constraint of every fluid particle, once per substep, after contact. Pass A gathers, fluid rows in sorted order: row i
+// takes the buckets of the (2 rings + 1)^3 cells around its own, each bucket once (a bucket two offsets hash to is skipped the
+// second time; a particle of a cell outside the rings is out of reach, so the distance test needs no cell compare), and
+// compacts without a branch the candidates within 2 (ri + rmax) into a row buffer. Over the buffer: n_i = sum W (self included; the
+// solids that touch i count too), C_i = max(n_i / n0 - 1, 0), lambda_i = -C_i / (sum_k w_k |grad_k C_i|^2 + eps w_i), 0 when that
+// is 0; a solid's lambda is 0. Pass A also writes i's neighbour list: every kernel neighbour in walk order until
+// YMIR_FLUID_NEIGHBOURS, each past that counted in fluid_overflow, as are candidates past the row buffer (n and lambda stay exact
+// until the buffer overflows; the correction and XSPH lose the pairs past the list). Pass B reads the lists: each fluid row i in index
+// order, each listed j in list order, a fluid j below i skipped (its row does the pair), a solid always done from i; corrections
+// apply after (Jacobi), so the sums are the same on every run. Then the fluid-solid contacts, on the same lists.
+static void fluid_density(ymir_particles* p)
+{
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ p->lambda[i] = 0.0f;
+ p->dp_x[i] = p->dp_y[i] = p->dp_z[i] = 0.0f;
+ }
+ float rmax = fluid_grid(p);
+ int32_t rings = p->fluid_rings, used = 0, arena = p->fluid_capacity * YMIR_FLUID_NEIGHBOURS;
+ for (int32_t qi = 0; qi < p->act_n; ++qi)
+ {
+ if (!(p->sphase[qi] & YMIR_PHASE_FLUID))
+ {
+ continue;
+ }
+ int32_t i = p->sorted[qi];
+ v3 xi = {p->sx[qi], p->sy[qi], p->sz[qi]}, gsum = {0.0f, 0.0f, 0.0f};
+ float h0 = 4.0f * p->radius[i], n0 = n0_of(p, h0), n = poly6(0.0f, h0), ssum = 0.0f, wi = p->w[i];
+ float reach = 2.0f * (p->radius[i] + rmax), reach2 = reach * reach;
+ int32_t buf[YMIR_FLUID_CANDIDATES], m = 0, hits = 0, stamp = qi + 1;
+ for (int32_t da = -rings; da <= rings; ++da)
+ for (int32_t db = -rings; db <= rings; ++db)
+ for (int32_t dc = -rings; dc <= rings; ++dc)
+ {
+ uint32_t bucket = cell_hash(p->cell_x[i] + da, p->cell_y[i] + db, p->cell_z[i] + dc, p->table_mask);
+ if (p->cell_fill[bucket] == stamp)
+ {
+ continue;
+ }
+ p->cell_fill[bucket] = stamp;
+ for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q)
+ {
+ float dx = xi.x - p->sx[q], dy = xi.y - p->sy[q], dz = xi.z - p->sz[q];
+ int32_t hit = (dx * dx + dy * dy + dz * dz < reach2) & (q != qi);
+ buf[m] = q;
+ m += hit & (m < YMIR_FLUID_CANDIDATES - 1);
+ hits += hit;
+ }
+ }
+ p->fluid_overflow += hits - m;
+ int32_t* list = p->nbr + used;
+ p->nbr_start[i] = used;
+ int32_t count = 0;
+ for (int32_t k = 0; k < m; ++k)
+ {
+ int32_t q = buf[k], j = p->sorted[q];
+ if (!(p->sphase[q] & YMIR_PHASE_FLUID) && !collides(p, i, j)) // fluid shares the density with fluid, and with the solids it would touch by contact
+ {
+ continue;
+ }
+ v3 d = vsub(xi, (v3){p->sx[q], p->sy[q], p->sz[q]});
+ float h = kernel_h(p, i, j), r2 = vdot(d, d);
+ if (r2 >= h * h)
+ {
+ continue;
+ }
+ if (used + count < arena)
+ {
+ list[count++] = j;
+ }
+ else
+ {
+ p->fluid_overflow++;
+ }
+ n += poly6(r2, h);
+ if (r2 >= 1e-12f)
+ {
+ v3 g = spiky(d, sqrtf(r2), h);
+ gsum = vadd(gsum, g);
+ ssum += p->sw[q] * vdot(g, g);
+ }
+ }
+ p->nbr_count[i] = count;
+ used += count;
+ float c = vmax(n / n0 - 1.0f, 0.0f);
+ p->density[i] = n / n0;
+ float den = (wi * vdot(gsum, gsum) + ssum) / (n0 * n0) + YMIR_PBF_EPS * wi;
+ p->lambda[i] = c == 0.0f || den == 0.0f ? 0.0f : -c / den;
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (!p->particle_live[i] || !(p->phase[i] & YMIR_PHASE_FLUID))
+ {
+ continue;
+ }
+ const int32_t* list = p->nbr + p->nbr_start[i];
+ for (int32_t k = 0; k < p->nbr_count[i]; ++k)
+ {
+ int32_t j = list[k];
+ if (j < i && (p->phase[j] & YMIR_PHASE_FLUID))
+ {
+ continue;
+ }
+ density_correct(p, i, j);
+ }
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (p->particle_live[i])
+ {
+ p->pp_x[i] += p->dp_x[i];
+ p->pp_y[i] += p->dp_y[i];
+ p->pp_z[i] += p->dp_z[i];
+ }
+ }
+ // Fluid-solid contact (the contact pass never sees a fluid lane): the listed solids of each fluid row that still overlap it,
+ // counted then moved as contact_pair does, weight 1 / max(n_i, n_j) over these pairs only; the moves apply after (Jacobi).
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ p->contacts[i] = 0;
+ p->dp_x[i] = p->dp_y[i] = p->dp_z[i] = 0.0f;
+ }
+ for (int pass = 0; pass < 2; ++pass)
+ {
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (!p->particle_live[i] || !(p->phase[i] & YMIR_PHASE_FLUID))
+ {
+ continue;
+ }
+ const int32_t* list = p->nbr + p->nbr_start[i];
+ for (int32_t k = 0; k < p->nbr_count[i]; ++k)
+ {
+ if (!(p->phase[list[k]] & YMIR_PHASE_FLUID) && contact_pair(p, &pass, i, list[k]) && pass == 1 && p->support_particle[i] < 0)
+ {
+ p->support_particle[i] = list[k]; // the first listed solid that touches: what the particle rests on
+ }
+ }
+ }
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (p->particle_live[i])
+ {
+ p->pp_x[i] += p->dp_x[i];
+ p->pp_y[i] += p->dp_y[i];
+ p->pp_z[i] += p->dp_z[i];
+ }
+ }
+}
+
+// XSPH (Schechter and Bridson 2012, as Macklin and Mueller 2013 sec. 5): a fluid pair's velocities relax toward each other,
+// dv = c (vj - vi) W / n0 with c the mean of the two materials', split by inverse mass like the density correction so the
+// pair keeps its momentum. Applied after the pass. Pairs come from the lists pass A wrote this substep (fluid j above i only), so a
+// pair that entered reach since is missed: smoothing, not a constraint.
+static void viscosity_pair(ymir_particles* p, int32_t i, int32_t j)
+{
+ float wsum = p->w[i] + p->w[j];
+ if (wsum == 0.0f)
+ {
+ return;
+ }
+ float c = 0.5f * (p->mat_viscosity[p->material[i]] + p->mat_viscosity[p->material[j]]);
+ v3 d = vsub(P(p, p->pos_x, p->pos_y, p->pos_z, i), P(p, p->pos_x, p->pos_y, p->pos_z, j));
+ float h = kernel_h(p, i, j), r2 = vdot(d, d);
+ if (c == 0.0f || r2 >= h * h)
+ {
+ return;
+ }
+ v3 dv = vmul(vsub(P(p, p->vel_x, p->vel_y, p->vel_z, j), P(p, p->vel_x, p->vel_y, p->vel_z, i)), c * poly6(r2, h) / n0_of(p, h));
+ v3 di = vmul(dv, 2.0f * p->w[i] / wsum), dj = vmul(dv, 2.0f * p->w[j] / wsum);
+ p->dp_x[i] += di.x; p->dp_y[i] += di.y; p->dp_z[i] += di.z;
+ p->dp_x[j] -= dj.x; p->dp_y[j] -= dj.y; p->dp_z[j] -= dj.z;
+}
+
+// Does any material have a viscosity? XSPH is a no-op when none does (a pair's coefficient is the mean of its two), so the walk is skipped.
+static int viscous_material(const ymir_particles* p)
+{
+ for (int32_t m = 0; m < p->material_capacity; ++m)
+ {
+ if (p->mat_viscosity[m] > 0.0f)
+ {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static void fluid_viscosity(ymir_particles* p)
+{
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ p->dp_x[i] = p->dp_y[i] = p->dp_z[i] = 0.0f;
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (!p->particle_live[i] || !(p->phase[i] & YMIR_PHASE_FLUID))
+ {
+ continue;
+ }
+ const int32_t* list = p->nbr + p->nbr_start[i];
+ for (int32_t k = 0; k < p->nbr_count[i]; ++k)
+ {
+ int32_t j = list[k];
+ if (j > i && (p->phase[j] & YMIR_PHASE_FLUID)) // a pair needs two fluid ends, and is done from the lower row
+ {
+ viscosity_pair(p, i, j);
+ }
+ }
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (p->particle_live[i])
+ {
+ p->vel_x[i] += p->dp_x[i];
+ p->vel_y[i] += p->dp_y[i];
+ p->vel_z[i] += p->dp_z[i];
+ }
+ }
+}
+
+// ---- particle-body contact -----------------------------------------------------------------------------------
+
+// Signed distance from `x` to the proxy's surface, the outward normal there and the nearest surface point.
+static float proxy_distance(const ymir_particle_proxy* b, v3 x, v3* normal, v3* surface)
+{
+ v3 c = {b->position[0], b->position[1], b->position[2]};
+ v3 n;
+ float d;
+ if (b->shape == YMIR_PROXY_BOX)
+ {
+ v3 l = qrot_inv(b->rotation, vsub(x, c));
+ v3 half = {b->size[0], b->size[1], b->size[2]};
+ v3 q = {fabsf(l.x) - half.x, fabsf(l.y) - half.y, fabsf(l.z) - half.z};
+ v3 nl;
+ if (q.x > 0.0f || q.y > 0.0f || q.z > 0.0f)
+ {
+ v3 out = {vmax(q.x, 0.0f), vmax(q.y, 0.0f), vmax(q.z, 0.0f)};
+ d = vlen(out);
+ nl = (v3){l.x < 0.0f ? -out.x : out.x, l.y < 0.0f ? -out.y : out.y, l.z < 0.0f ? -out.z : out.z};
+ nl = vmul(nl, 1.0f / d);
+ }
+ else
+ {
+ d = vmax(q.x, vmax(q.y, q.z)); // inside: the nearest face
+ nl = d == q.x ? (v3){l.x < 0.0f ? -1.0f : 1.0f, 0.0f, 0.0f}
+ : d == q.y ? (v3){0.0f, l.y < 0.0f ? -1.0f : 1.0f, 0.0f}
+ : (v3){0.0f, 0.0f, l.z < 0.0f ? -1.0f : 1.0f};
+ }
+ n = qrot(b->rotation, nl);
+ }
+ else
+ {
+ v3 centre = c;
+ if (b->shape == YMIR_PROXY_CAPSULE)
+ {
+ v3 axis = qrot(b->rotation, (v3){0.0f, 1.0f, 0.0f});
+ centre = vadd(c, vmul(axis, vclamp(vdot(vsub(x, c), axis), -b->size[1], b->size[1])));
+ }
+ v3 v = vsub(x, centre);
+ float l = vlen(v);
+ n = l > 1e-9f ? vmul(v, 1.0f / l) : (v3){0.0f, 1.0f, 0.0f};
+ d = l - b->size[0];
+ }
+ *normal = n;
+ *surface = vsub(x, vmul(n, d));
+ return d;
+}
+
+// The friction on body `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds the point, never above mu.
+// The one patch test, for particle-body contact here and body-body contact through the world's friction hook.
+float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu)
+{
+ if (p == NULL || body < 0 || body >= p->body_capacity || p->wet_body_count[body] == 0)
+ {
+ return mu;
+ }
+ const float* box = p->wet_body_box + 7 * (int64_t)body;
+ if (x < box[0] || x > box[3] || y < box[1] || y > box[4] || z < box[2] || z > box[5])
+ {
+ return mu; // outside every disc's box: a constant check
+ }
+ // The slice is sorted by centre x: only centres within the body's largest radius of x can hold the point. The lowest lane among them wins.
+ const int32_t* slice = p->wet_order + p->wet_body_start[body];
+ int32_t lo = 0, hi = p->wet_body_count[body];
+ while (lo < hi)
+ {
+ int32_t mid = (lo + hi) / 2;
+ if (p->wet_x[slice[mid]] < x - box[6])
+ {
+ lo = mid + 1;
+ }
+ else
+ {
+ hi = mid;
+ }
+ }
+ int32_t found = -1;
+ for (int32_t k = lo; k < p->wet_body_count[body] && p->wet_x[slice[k]] <= x + box[6]; ++k)
+ {
+ int32_t w = slice[k];
+ v3 d = {x - p->wet_x[w], y - p->wet_y[w], z - p->wet_z[w]};
+ if ((found < 0 || w < found) && vlen(d) <= p->wet_radius[w])
+ {
+ found = w;
+ }
+ }
+ return found < 0 ? mu : vmin(mu, p->mat_wet_friction[p->wet_material[found]]);
+}
+
+static float proxy_reach(const ymir_particle_proxy* b)
+{
+ if (b->shape == YMIR_PROXY_SPHERE)
+ {
+ return b->size[0];
+ }
+ if (b->shape == YMIR_PROXY_CAPSULE)
+ {
+ return b->size[0] + b->size[1];
+ }
+ return sqrtf(b->size[0] * b->size[0] + b->size[1] * b->size[1] + b->size[2] * b->size[2]);
+}
+
+// 1 when particle i is held to body k by an attachment: such a particle is the body's own point, so contact skips that body.
+// Reads the list rederive_topology wrote at the last command.
+static int held_by(const ymir_particles* p, int32_t i, int32_t k)
+{
+ for (int32_t s = p->held_start[i], e = s + p->held_count[i]; s < e; ++s)
+ {
+ if (p->held_body[s] == k)
+ {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+// Each particle against each shaped body in ascending lane order. The correction is split by inverse mass between
+// the particle and the body at the contact point; Coulomb friction removes the tangential slip up to mu times the
+// push. Every body the particle is attached to is skipped: the attachment already ties them. A LIMB attachment skips the
+// attached body's whole limb tree: flesh does not meet the bones of its own limb.
+static void body_contacts(phase* f)
+{
+ ymir_particles* p = f->p;
+ for (int32_t m = 0; m < p->act_n; ++m)
+ {
+ int32_t i = p->act[m];
+ if (p->w[i] == 0.0f)
+ {
+ continue;
+ }
+ int fluid = (p->phase[i] & YMIR_PHASE_FLUID) != 0;
+ float mu = p->mat_friction[p->material[i]];
+ float r = p->radius[i];
+ float wi = p->w[i];
+ for (int32_t k = 0; k < p->body_count; ++k)
+ {
+ ymir_particle_proxy* b = p->proxies + k;
+ if (b->shape == YMIR_PROXY_NONE)
+ {
+ continue;
+ }
+ v3 x = P(p, p->pp_x, p->pp_y, p->pp_z, i);
+ v3 c = {b->position[0], b->position[1], b->position[2]};
+ float reach = proxy_reach(b) + r;
+ v3 dc = vsub(x, c);
+ if (vdot(dc, dc) > reach * reach)
+ {
+ continue;
+ }
+ if ((p->limb_body[i] >= 0 && b->root == p->proxies[p->limb_body[i]].root) || held_by(p, i, k))
+ {
+ continue; // the particle is flesh of this body's limb tree, or attached to this body
+ }
+ v3 n, s;
+ float d = proxy_distance(b, x, &n, &s);
+ if (d >= r)
+ {
+ continue;
+ }
+ if (p->phase[i] & YMIR_PHASE_FLUID)
+ {
+ p->support_body[i] = k; // bodies ascend: the highest lane touched wins
+ }
+ float depth = r - d;
+ float wb = proxy_w(b, s, n);
+ float w = wi + wb;
+ x = vadd(x, vmul(n, depth * wi / w));
+ proxy_push(f, b, s, vmul(n, -depth / w));
+ float mu_k = mu;
+ if (!fluid)
+ {
+ // A solid on a wet body or wetted itself slips: the lowest wet friction there; a fluid particle keeps its own.
+ v3 l = qrot_inv(b->rotation, vsub(s, c));
+ mu_k = vmin(ymir_particles_wet_mu(p, k, l.x, l.y, l.z, mu), p->particle_wet_mu[i]);
+ }
+ if (mu_k > 0.0f)
+ {
+ // Slip of the particle against the body point over this substep, tangential part.
+ v3 rb = vsub(s, (v3){b->position[0], b->position[1], b->position[2]});
+ v3 vb = vadd((v3){b->velocity[0], b->velocity[1], b->velocity[2]},
+ vcross((v3){b->angular_velocity[0], b->angular_velocity[1], b->angular_velocity[2]}, rb));
+ v3 slip = vsub(vsub(x, P(p, p->pos_x, p->pos_y, p->pos_z, i)), vmul(vb, f->h)); // (x - x_prev) - v_body h
+ slip = vsub(slip, vmul(n, vdot(slip, n)));
+ float sl = vlen(slip);
+ if (sl > 1e-9f)
+ {
+ v3 t = vmul(slip, 1.0f / sl);
+ float move = vmin(sl, mu_k * depth);
+ float wt = wi + proxy_w(b, s, t);
+ x = vsub(x, vmul(t, move * wi / wt));
+ proxy_push(f, b, s, vmul(t, move / wt));
+ }
+ }
+ put(p->pp_x, p->pp_y, p->pp_z, i, x);
+ }
+ }
+}
+
+// ---- attachments, distances, bends, tethers ------------------------------------------------------------------
+
+// Books on edge `e` the load an impulse `imp` (kg m) delivered to the particle `far`, the side of the edge away
+// from `near`, puts on it: along the edge, positive when the edge is being stretched. Every impulse the
+// structure delivers has an equal and opposite one, so the sum past an edge is the load it carries however the
+// solver routed it.
+static void book(const phase* f, int32_t e, int32_t near_i, int32_t far_i, v3 imp)
+{
+ ymir_particles* p = f->p;
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, far_i), P(p, p->pp_x, p->pp_y, p->pp_z, near_i));
+ float len = vlen(d);
+ if (len > 1e-9f)
+ {
+ p->dist_acc[e] += -vdot(imp, d) / len * f->k;
+ }
+}
+
+// Pulls an attached particle onto the point it is attached to (rest length 0), by inverse mass.
+static void solve_attachments(phase* f)
+{
+ ymir_particles* p = f->p;
+ for (int32_t m = 0; m < p->act_att_n; ++m)
+ {
+ int32_t a = p->act_att[m], i = p->att_particle[a];
+ v3 at = end_point(p, a);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), at);
+ float len = vlen(d);
+ if (len < 1e-9f)
+ {
+ continue;
+ }
+ v3 n = vmul(d, 1.0f / len);
+ float den = p->w[i] + end_w(p, a, at, n) + p->att_compliance[a] / (f->h * f->h);
+ if (den == 0.0f)
+ {
+ continue;
+ }
+ float dl = -len / den;
+ put(p->pp_x, p->pp_y, p->pp_z, i, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, i), vmul(n, p->w[i] * dl)));
+ end_push(f, a, at, vmul(n, -dl));
+ add_force(p, a, vmul(n, dl * f->k));
+ }
+}
+
+// Each live distance in lane order (Gauss-Seidel), one iteration per substep: the small step does the converging.
+// Its lambda is its tension (positive when stretched).
+static void solve_distances(phase* f)
+{
+ ymir_particles* p = f->p;
+ for (int32_t m = 0; m < p->act_dist_n; ++m)
+ {
+ int32_t e = p->act_dist[m], i = p->dist_a[e], j = p->dist_b[e];
+ float wi = p->w[i], wj = p->w[j], alpha = p->dist_compliance[e] / (f->h * f->h);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), P(p, p->pp_x, p->pp_y, p->pp_z, i));
+ float len = vlen(d);
+ if (len < 1e-9f || wi + wj + alpha == 0.0f)
+ {
+ continue;
+ }
+ v3 n = vmul(d, 1.0f / len);
+ float dl = -(len - p->dist_rest[e]) / (wi + wj + alpha);
+ put(p->pp_x, p->pp_y, p->pp_z, i, vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), vmul(n, wi * dl)));
+ put(p->pp_x, p->pp_y, p->pp_z, j, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, j), vmul(n, wj * dl)));
+ p->dist_acc[e] += -dl * f->k;
+ }
+}
+
+// Each live bend in lane order, on the offset of the shared particle b from the centroid of a, b, c (Kelager
+// 2010): a soft pass (XPBD, compliance / h^2) toward the rest offset, then a hard unilateral pass at the offset the
+// maximum angle allows, free inside it and rigid at it. The three position impulses sum to zero; what crossed
+// each of the two distances is booked on it.
+static void solve_bends(phase* f)
+{
+ ymir_particles* p = f->p;
+ for (int32_t m = 0; m < p->act_bend_n; ++m)
+ {
+ int32_t k = p->act_bend[m], a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k];
+ float wa = p->w[a], wb = p->w[b], wc = p->w[c];
+ v3 ja = {0.0f, 0.0f, 0.0f}, jc = {0.0f, 0.0f, 0.0f};
+ for (int pass = 0; pass < 2; ++pass)
+ {
+ if ((pass == 0 && p->bend_compliance[k] < 0.0f) || (pass == 1 && p->bend_limit[k] < 0.0f))
+ {
+ continue;
+ }
+ float target = pass == 0 ? p->bend_rest[k] : p->bend_limit[k];
+ v3 centroid = vmul(vadd(vadd(P(p, p->pp_x, p->pp_y, p->pp_z, a), P(p, p->pp_x, p->pp_y, p->pp_z, b)),
+ P(p, p->pp_x, p->pp_y, p->pp_z, c)), 1.0f / 3.0f);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, b), centroid);
+ float len = vlen(d);
+ if (len < 1e-9f)
+ {
+ continue;
+ }
+ float violation = len - target;
+ if (pass == 1 && violation <= 0.0f)
+ {
+ continue;
+ }
+ float alpha = pass == 0 ? p->bend_compliance[k] / (f->h * f->h) : 0.0f;
+ float den = (wa + 4.0f * wb + wc) / 9.0f + alpha;
+ if (den == 0.0f)
+ {
+ continue;
+ }
+ v3 n = vmul(d, 1.0f / len);
+ float dl = -violation / den;
+ v3 ia = vmul(n, -dl / 3.0f), ib = vmul(n, 2.0f * dl / 3.0f), ic = vmul(n, -dl / 3.0f);
+ put(p->pp_x, p->pp_y, p->pp_z, a, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, a), vmul(ia, wa)));
+ put(p->pp_x, p->pp_y, p->pp_z, b, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, b), vmul(ib, wb)));
+ put(p->pp_x, p->pp_y, p->pp_z, c, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, c), vmul(ic, wc)));
+ ja = vadd(ja, ia);
+ jc = vadd(jc, ic);
+ }
+ book(f, p->bend_e1[k], a, b, vmul(ja, -1.0f)); // what crossed e1 toward b and c
+ book(f, p->bend_e2[k], b, c, jc);
+ }
+}
+
+// Long-range bounds derived from the graph, unilateral: a tether holds a particle within the rest path of an
+// attachment point, a pair tether holds two attachment points within the rest path between their particles. They
+// bear load past the distances, so each tether's impulse is routed leaves first up its path tree and booked on the
+// edges it crossed: the tension sensors read the load, not the path.
+static void solve_tethers(phase* f)
+{
+ ymir_particles* p = f->p;
+ for (int32_t t = 0; t < p->tether_count; ++t)
+ {
+ p->tacc_x[t] = p->tacc_y[t] = p->tacc_z[t] = 0.0f;
+ int32_t a = p->tether_att[t], b = p->tether_other[t];
+ if (a < 0)
+ {
+ continue; // a booking lane: it carries load up its route and bounds nothing
+ }
+ float bound = p->tether_bound[t];
+ if (b >= 0)
+ {
+ v3 pa = end_point(p, a), pb = end_point(p, b);
+ v3 d = vsub(pa, pb);
+ float len = vlen(d);
+ if (len <= bound)
+ {
+ continue;
+ }
+ v3 n = vmul(d, 1.0f / len);
+ float den = end_w(p, a, pa, n) + end_w(p, b, pb, n);
+ if (den == 0.0f)
+ {
+ continue;
+ }
+ float dl = -(len - bound) / den;
+ end_push(f, a, pa, vmul(n, dl));
+ end_push(f, b, pb, vmul(n, -dl));
+ add_force(p, a, vmul(n, -dl * f->k)); // each point pulls the particles away from the other
+ add_force(p, b, vmul(n, dl * f->k));
+ put(p->tacc_x, p->tacc_y, p->tacc_z, t, vmul(n, -dl)); // delivered to b's particle, toward a
+ continue;
+ }
+ int32_t j = p->tether_particle[t];
+ v3 at = end_point(p, a);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), at);
+ float len = vlen(d);
+ if (len <= bound)
+ {
+ continue;
+ }
+ v3 n = vmul(d, 1.0f / len);
+ float den = p->w[j] + end_w(p, a, at, n);
+ if (den == 0.0f)
+ {
+ continue;
+ }
+ float dl = -(len - bound) / den;
+ put(p->pp_x, p->pp_y, p->pp_z, j, vadd(P(p, p->pp_x, p->pp_y, p->pp_z, j), vmul(n, p->w[j] * dl)));
+ end_push(f, a, at, vmul(n, -dl));
+ add_force(p, a, vmul(n, dl * f->k)); // the force on the particles, toward the attachment
+ put(p->tacc_x, p->tacc_y, p->tacc_z, t, vmul(n, dl));
+ }
+ for (int32_t t = p->tether_count - 1; t >= 0; --t)
+ {
+ v3 load = P(p, p->tacc_x, p->tacc_y, p->tacc_z, t);
+ int32_t e = p->tether_edge[t];
+ if (e >= 0)
+ {
+ int32_t j = p->tether_particle[t], other = p->dist_a[e] == j ? p->dist_b[e] : p->dist_a[e];
+ book(f, e, other, j, load);
+ }
+ if (p->tether_parent[t] >= 0)
+ {
+ int32_t q = p->tether_parent[t];
+ put(p->tacc_x, p->tacc_y, p->tacc_z, q, vadd(P(p, p->tacc_x, p->tacc_y, p->tacc_z, q), load));
+ }
+ }
+}
+
+// ---- the step ------------------------------------------------------------------------------------------------
+
+int32_t ymir_particles_begin(ymir_particles* p)
+{
+ if (p == NULL || p->live_particles == 0)
+ {
+ return 0;
+ }
+ for (int32_t k = 0; k < p->body_count; ++k)
+ {
+ ymir_particle_proxy* b = p->proxies + k;
+ memset(b->impulse, 0, sizeof(b->impulse));
+ memset(b->angular_impulse, 0, sizeof(b->angular_impulse));
+ }
+ p->fluid_overflow = 0;
+ for (int32_t e = 0; e < p->distance_count; ++e)
+ {
+ p->dist_acc[e] = 0.0f;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ p->att_force_x[a] = p->att_force_y[a] = p->att_force_z[a] = 0.0f;
+ }
+ return 1;
+}
+
+// One substep of `h` against the proxies' poses at its start and velocities after the rigid solve: proxies are
+// predicted like particles, every constraint moves both sides by inverse mass, and each proxy's correction returns
+// as sub_impulse (its correction over h) for the caller to apply before the rigid positions integrate. Position,
+// velocity and momentum stay one state: XPBD's velocity update, done by the rigid integrator.
+void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz)
+{
+ if (p == NULL || p->live_particles == 0)
+ {
+ return;
+ }
+ phase f = {p, h, 1.0f / h, 1.0f / (h * h)};
+ v3 g = {gx, gy, gz};
+ for (int32_t m = 0; m < p->kin_n; ++m) // a kinematic particle is where its anchor is at this substep's start pose
+ {
+ int32_t i = p->kin[m];
+ put(p->pos_x, p->pos_y, p->pos_z, i, end_point(p, p->anchor[i]));
+ }
+ for (int32_t k = 0; k < p->body_count; ++k)
+ {
+ ymir_particle_proxy* b = p->proxies + k;
+ memset(b->sub_impulse, 0, sizeof(b->sub_impulse));
+ memset(b->sub_angular, 0, sizeof(b->sub_angular));
+ // predict the pose the rigid integrator reaches with this velocity
+ b->position[0] += h * b->velocity[0];
+ b->position[1] += h * b->velocity[1];
+ b->position[2] += h * b->velocity[2];
+ v3 w = vmul((v3){b->angular_velocity[0], b->angular_velocity[1], b->angular_velocity[2]}, h);
+ float* q = b->rotation;
+ float dq[4] = {
+ 0.5f * (w.x * q[3] + w.y * q[2] - w.z * q[1]),
+ 0.5f * (w.y * q[3] + w.z * q[0] - w.x * q[2]),
+ 0.5f * (w.z * q[3] + w.x * q[1] - w.y * q[0]),
+ 0.5f * (-w.x * q[0] - w.y * q[1] - w.z * q[2])};
+ float n2 = 0.0f;
+ for (int c = 0; c < 4; ++c)
+ {
+ q[c] += dq[c];
+ n2 += q[c] * q[c];
+ }
+ float inv = 1.0f / sqrtf(n2);
+ for (int c = 0; c < 4; ++c)
+ {
+ q[c] *= inv;
+ }
+ }
+ for (int32_t m = 0; m < p->kin_n; ++m) // ... and where it is at the predicted pose, which the constraints read
+ {
+ int32_t i = p->kin[m];
+ put(p->pp_x, p->pp_y, p->pp_z, i, end_point(p, p->anchor[i]));
+ }
+ for (int32_t m = 0; m < p->act_n; ++m)
+ {
+ int32_t i = p->act[m];
+ if (p->phase[i] & YMIR_PHASE_FLUID)
+ {
+ p->support_body[i] = p->support_particle[i] = -1; // this substep's contacts write them again
+ }
+ v3 x = P(p, p->pos_x, p->pos_y, p->pos_z, i);
+ if (p->w[i] > 0.0f)
+ {
+ v3 v = vadd(P(p, p->vel_x, p->vel_y, p->vel_z, i), vmul(g, h));
+ put(p->vel_x, p->vel_y, p->vel_z, i, v);
+ x = vadd(x, vmul(v, h));
+ }
+ put(p->pp_x, p->pp_y, p->pp_z, i, x);
+ }
+ build_grid(p);
+ particle_contacts(p);
+ if (p->live_fluid > 0)
+ {
+ fluid_density(p);
+ }
+ solve_attachments(&f);
+ solve_distances(&f);
+ solve_bends(&f);
+ solve_tethers(&f);
+ body_contacts(&f);
+ for (int32_t m = 0; m < p->act_n; ++m)
+ {
+ int32_t i = p->act[m];
+ v3 x = P(p, p->pos_x, p->pos_y, p->pos_z, i), y = P(p, p->pp_x, p->pp_y, p->pp_z, i);
+ if (p->w[i] > 0.0f)
+ {
+ put(p->vel_x, p->vel_y, p->vel_z, i, vmul(vsub(y, x), f.inv_h));
+ }
+ put(p->pos_x, p->pos_y, p->pos_z, i, y);
+ }
+ for (int32_t m = 0; m < p->kin_n; ++m) // the kinematic particle's velocity is the anchor's over the substep
+ {
+ int32_t i = p->kin[m];
+ put(p->vel_x, p->vel_y, p->vel_z, i, vmul(vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), P(p, p->pos_x, p->pos_y, p->pos_z, i)), f.inv_h));
+ put(p->pos_x, p->pos_y, p->pos_z, i, P(p, p->pp_x, p->pp_y, p->pp_z, i));
+ }
+ if (p->live_fluid > 0 && viscous_material(p))
+ {
+ fluid_viscosity(p);
+ }
+ for (int32_t k = 0; k < p->body_count; ++k)
+ {
+ ymir_particle_proxy* b = p->proxies + k;
+ for (int c = 0; c < 3; ++c)
+ {
+ b->impulse[c] += b->sub_impulse[c];
+ b->angular_impulse[c] += b->sub_angular[c];
+ }
+ }
+}
+
+static float wet_disc_radius(float volume);
+
+// A patch keeps the fraction keep of its volume: its radius follows, and it dies at a kept volume of 0.
+static double take_from_wet(ymir_particles* p, int32_t w, double keep, uint64_t step_count)
+{
+ float was = p->wet_volume[w];
+ float kept = (float)((double)was * keep);
+ if (!(kept > 0.0f))
+ {
+ kill_wet(p, w, step_count);
+ return was;
+ }
+ p->wet_volume[w] = kept;
+ p->wet_radius[w] = wet_disc_radius(kept);
+ return (double)was - (double)kept;
+}
+
+// The volume of the live wet patches whose centre lies within r of the world point c. A body's patches go through the wet cut's index: the sphere is taken into the
+// body's frame (where its patches' centres are), culled against the box of the body's discs, and only centres within r of its x are walked, in the index's order
+// (bodies ascending, then centre x). Patches on solid particles have no index and are summed after, in wet lane order, at their particle's position.
+// The one sphere test of the wet patches: the sensor's reading walks it with keep 1 (read only); take_wet walks it again with keep < 1, which also scales
+// every patch it visits by keep (recomputing its radius) and kills one whose kept volume is 0. Returns the volume inside before any change.
+// A killed lane keeps its centre until the command's rederive_wet, so the index's order holds across kills; the walk skips a lane that is not live.
+static float pooled_walk(ymir_particles* p, v3 c, float r, double keep, uint64_t step_count, double* removed)
+{
+ float total = 0.0f;
+ float r2 = r * r;
+ for (int32_t b = 0; b < p->body_count && b < p->body_capacity; ++b)
+ {
+ if (p->wet_body_count[b] == 0)
+ {
+ continue;
+ }
+ const ymir_particle_proxy* body = p->proxies + b;
+ v3 l = qrot_inv(body->rotation, vsub(c, (v3){body->position[0], body->position[1], body->position[2]}));
+ const float* box = p->wet_body_box + 7 * (int64_t)b;
+ if (l.x + r < box[0] || l.x - r > box[3] || l.y + r < box[1] || l.y - r > box[4] || l.z + r < box[2] || l.z - r > box[5])
+ {
+ continue;
+ }
+ const int32_t* slice = p->wet_order + p->wet_body_start[b];
+ int32_t lo = 0, hi = p->wet_body_count[b];
+ while (lo < hi)
+ {
+ int32_t mid = (lo + hi) / 2;
+ if (p->wet_x[slice[mid]] < l.x - r)
+ {
+ lo = mid + 1;
+ }
+ else
+ {
+ hi = mid;
+ }
+ }
+ for (int32_t k = lo; k < p->wet_body_count[b] && p->wet_x[slice[k]] <= l.x + r; ++k)
+ {
+ int32_t w = slice[k];
+ if (!p->wet_live[w])
+ {
+ continue;
+ }
+ v3 d = {l.x - p->wet_x[w], l.y - p->wet_y[w], l.z - p->wet_z[w]};
+ if (vdot(d, d) <= r2)
+ {
+ total += p->wet_volume[w];
+ if (keep < 1.0)
+ {
+ *removed += take_from_wet(p, w, keep, step_count);
+ }
+ }
+ }
+ }
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (p->wet_live[w] && p->wet_particle[w] >= 0 && p->wet_particle[w] < p->particle_count && p->particle_live[p->wet_particle[w]])
+ {
+ int32_t i = p->wet_particle[w];
+ // a pinned particle's pos is stale: it is where its anchor holds it now
+ v3 at = p->pinned[i] && p->anchor[i] >= 0 ? end_point(p, p->anchor[i]) : P(p, p->pos_x, p->pos_y, p->pos_z, i);
+ v3 d = vsub(at, c);
+ if (vdot(d, d) <= r2)
+ {
+ total += p->wet_volume[w];
+ if (keep < 1.0)
+ {
+ *removed += take_from_wet(p, w, keep, step_count);
+ }
+ }
+ }
+ }
+ return total;
+}
+
+// A sensor's centre in the world: its point on its body at the pose the last substep (or the caller's gather) left the proxy in.
+static v3 sensor_centre(const ymir_particles* p, int32_t s)
+{
+ const ymir_particle_proxy* b = p->proxies + p->sensor_body[s];
+ return vadd((v3){b->position[0], b->position[1], b->position[2]}, qrot(b->rotation, (v3){p->sensor_x[s], p->sensor_y[s], p->sensor_z[s]}));
+}
+
+// Each live sensor reads the liquid inside it: the sum, in lane order, of (2 r)^3 over the live fluid particles whose centre lies within its sphere, against the
+// pose the last substep left each proxy in. It runs whether or not any particle is live, so a sensor never keeps a reading once the liquid is gone.
+static void read_sensors(ymir_particles* p)
+{
+ for (int32_t s = 0; s < p->sensor_count; ++s)
+ {
+ if (!p->sensor_live[s])
+ {
+ continue;
+ }
+ float volume = 0.0f;
+ float pooled = 0.0f;
+ if (p->sensor_body[s] < p->body_count)
+ {
+ v3 c = sensor_centre(p, s);
+ float r2 = p->sensor_radius[s] * p->sensor_radius[s];
+ pooled = pooled_walk(p, c, p->sensor_radius[s], 1.0, 0, NULL);
+ for (int32_t i = 0; p->live_fluid > 0 && i < p->particle_count; ++i)
+ {
+ if (!p->particle_live[i] || !(p->phase[i] & YMIR_PHASE_FLUID))
+ {
+ continue;
+ }
+ v3 d = vsub(P(p, p->pos_x, p->pos_y, p->pos_z, i), c);
+ if (vdot(d, d) <= r2)
+ {
+ float side = 2.0f * p->radius[i];
+ volume += side * side * side;
+ }
+ }
+ }
+ p->sensor_liquid_volume[s] = volume;
+ p->sensor_wet_volume[s] = pooled;
+ }
+}
+
+void ymir_particles_end(ymir_particles* p, int32_t substeps)
+{
+ if (p == NULL)
+ {
+ return;
+ }
+ read_sensors(p);
+ if (p->live_particles == 0)
+ {
+ return;
+ }
+ float mean = 1.0f / (float)substeps;
+ for (int32_t e = 0; e < p->distance_count; ++e)
+ {
+ p->dist_tension[e] = p->dist_live[e] ? p->dist_acc[e] * mean : 0.0f;
+ }
+ for (int32_t a = 0; a < p->attachment_count; ++a)
+ {
+ p->att_force_x[a] *= mean;
+ p->att_force_y[a] *= mean;
+ p->att_force_z[a] *= mean;
+ }
+}
+
+// ---- pinned: the command-owned dormancy of a particle ------------------------------------------------------------
+
+int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handle* h, uint32_t pinned)
+{
+ if (p == NULL || n < 0 || (n > 0 && h == NULL) || pinned > 1)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t i = h[k].lane;
+ if (!particle_ok(p, i, h[k].generation) || (p->phase[i] & YMIR_PHASE_FLUID) || (pinned && p->anchor[i] < 0))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT; // a pinned particle is drawn from its anchor
+ }
+ }
+ int32_t newly = 0; // the lanes this pin took 0 -> 1, in queue, to back out if the derivation refuses
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t i = h[k].lane;
+ if (pinned)
+ {
+ if (!p->pinned[i])
+ {
+ p->pinned[i] = 1; // 0 -> 1 writes only the lane
+ p->queue[newly++] = i;
+ }
+ continue;
+ }
+ if (!p->pinned[i])
+ {
+ continue;
+ }
+ // wake: on the anchor's point, moving as that point moves, at the proxies' pose now
+ int32_t a = p->anchor[i];
+ v3 at = end_point(p, a), v = {0.0f, 0.0f, 0.0f};
+ if (p->att_kind[a] == YMIR_ATTACH_BODY)
+ {
+ const ymir_particle_proxy* b = p->proxies + p->att_body[a];
+ v = vadd((v3){b->velocity[0], b->velocity[1], b->velocity[2]},
+ vcross((v3){b->angular_velocity[0], b->angular_velocity[1], b->angular_velocity[2]},
+ vsub(at, (v3){b->position[0], b->position[1], b->position[2]})));
+ }
+ put(p->pos_x, p->pos_y, p->pos_z, i, at);
+ put(p->vel_x, p->vel_y, p->vel_z, i, v);
+ p->pinned[i] = 0;
+ }
+ // a wake only clears pinned lanes, so the derivation refuses only a pin, which wrote nothing but the lanes in queue
+ int32_t status = rederive_topology(p, TOPO_PINNED, NULL, 0);
+ for (int32_t k = 0; status != YMIR_PARTICLES_OK && k < newly; ++k)
+ {
+ p->pinned[p->queue[k]] = 0;
+ }
+ return status;
+}
+
+// ---- settle: liquid becomes data ----------------------------------------------------------------------------
+
+static float wet_disc_radius(float volume)
+{
+ return sqrtf(volume / (3.14159265358979f * YMIR_WET_FILM));
+}
+
+// The contact point of fluid particle i on its support, in the support's frame: the nearest surface point of the body, or 0 on a solid particle.
+// Returns 0 when the particle names no support the proxies can place.
+static int wet_support_point(const ymir_particles* p, int32_t i, int32_t* body, int32_t* particle, v3* point)
+{
+ *body = p->support_body[i];
+ *particle = p->support_particle[i];
+ *point = (v3){0.0f, 0.0f, 0.0f};
+ if (*body >= 0)
+ {
+ if (*body >= p->body_count || p->proxies[*body].shape == YMIR_PROXY_NONE)
+ {
+ return 0;
+ }
+ const ymir_particle_proxy* b = p->proxies + *body;
+ v3 n, s;
+ proxy_distance(b, P(p, p->pos_x, p->pos_y, p->pos_z, i), &n, &s);
+ *point = qrot_inv(b->rotation, vsub(s, (v3){b->position[0], b->position[1], b->position[2]}));
+ *particle = -1;
+ return 1;
+ }
+ return *particle >= 0 && *particle < p->particle_count && p->particle_live[*particle];
+}
+
+int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count, ymir_handle* out)
+{
+ if (p == NULL || n < 0 || (n > 0 && h == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ memset(p->done, 0, (size_t)p->particle_count); // scratch with no baseline: marks the particles named
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t body, particle;
+ v3 pt;
+ if (!particle_ok(p, h[k].lane, h[k].generation) || !(p->phase[h[k].lane] & YMIR_PHASE_FLUID) || p->done[h[k].lane] ||
+ !wet_support_point(p, h[k].lane, &body, &particle, &pt))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT; // a particle named twice would settle its volume twice
+ }
+ p->done[h[k].lane] = 1;
+ }
+ int32_t saved_count = p->wet_count;
+ int32_t logged = 0;
+ int32_t status = YMIR_PARTICLES_OK;
+ for (int32_t k = 0; k < n && status == YMIR_PARTICLES_OK; ++k)
+ {
+ int32_t i = h[k].lane;
+ int32_t body, particle;
+ v3 pt;
+ wet_support_point(p, i, &body, &particle, &pt);
+ uint32_t material = p->material[i];
+ float r2 = 2.0f * p->radius[i];
+ float volume = r2 * r2 * r2;
+ int32_t into = -1;
+ int32_t nearest = -1;
+ float nearest_d = 0.0f;
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (!p->wet_live[w] || p->wet_body[w] != body || p->wet_particle[w] != particle || p->wet_material[w] != material)
+ {
+ continue;
+ }
+ v3 c = {p->wet_x[w], p->wet_y[w], p->wet_z[w]};
+ float d = vlen(vsub(pt, c));
+ if (d <= p->wet_radius[w] && into < 0)
+ {
+ into = w; // the lowest patch whose disc holds the point
+ }
+ if (nearest < 0 || d < nearest_d)
+ {
+ nearest = w;
+ nearest_d = d;
+ }
+ }
+ int created = 0;
+ if (into < 0)
+ {
+ into = next_lane(p->wet_live, 0, p->wet_removed_at, p->wet_count, p->wet_capacity, 0, step_count);
+ created = into >= 0;
+ if (into < 0)
+ {
+ into = nearest; // no lane left: the nearest patch on this support takes it
+ }
+ }
+ int foreign = 0;
+ if (into < 0)
+ {
+ // No lane and no patch on this support: the pool of the nearest patch of this material, by world distance, grows by the drop's volume
+ // (its centre stays where it is: the drop's point is in another support's frame). Only when the material has no live patch at all is it FULL.
+ v3 at = P(p, p->pos_x, p->pos_y, p->pos_z, i);
+ float best = 0.0f;
+ for (int32_t w = 0; w < p->wet_count; ++w)
+ {
+ if (!p->wet_live[w] || p->wet_material[w] != material)
+ {
+ continue;
+ }
+ v3 c = {p->wet_x[w], p->wet_y[w], p->wet_z[w]};
+ v3 world;
+ if (p->wet_body[w] >= 0)
+ {
+ const ymir_particle_proxy* b = p->proxies + p->wet_body[w];
+ world = vadd((v3){b->position[0], b->position[1], b->position[2]}, qrot(b->rotation, c));
+ }
+ else
+ {
+ world = vadd(P(p, p->pos_x, p->pos_y, p->pos_z, p->wet_particle[w]), c);
+ }
+ float d = vlen(vsub(at, world));
+ if (into < 0 || d < best)
+ {
+ into = w;
+ best = d;
+ }
+ }
+ foreign = into >= 0;
+ }
+ if (into < 0)
+ {
+ status = YMIR_PARTICLES_FULL;
+ break;
+ }
+ p->wu_code[logged] = created ? -(into + 1) : into;
+ p->wu_x[logged] = p->wet_x[into];
+ p->wu_y[logged] = p->wet_y[into];
+ p->wu_z[logged] = p->wet_z[into];
+ p->wu_volume[logged] = p->wet_volume[into];
+ logged++;
+ if (created)
+ {
+ p->wet_live[into] = 1;
+ p->wet_body[into] = body;
+ p->wet_particle[into] = particle;
+ p->wet_material[into] = material;
+ p->wet_x[into] = pt.x;
+ p->wet_y[into] = pt.y;
+ p->wet_z[into] = pt.z;
+ p->wet_volume[into] = volume;
+ if (into >= p->wet_count)
+ {
+ p->wet_count = into + 1;
+ }
+ }
+ else if (foreign)
+ {
+ p->wet_volume[into] += volume;
+ }
+ else
+ {
+ float total = p->wet_volume[into] + volume;
+ p->wet_x[into] = (p->wet_x[into] * p->wet_volume[into] + pt.x * volume) / total; // centre: volume-weighted
+ p->wet_y[into] = (p->wet_y[into] * p->wet_volume[into] + pt.y * volume) / total;
+ p->wet_z[into] = (p->wet_z[into] * p->wet_volume[into] + pt.z * volume) / total;
+ p->wet_volume[into] = total;
+ }
+ p->wet_radius[into] = wet_disc_radius(p->wet_volume[into]);
+ if (out != NULL)
+ {
+ out[k] = (ymir_handle){into, p->wet_generation[into]};
+ }
+ }
+ if (status != YMIR_PARTICLES_OK)
+ {
+ for (int32_t u = logged - 1; u >= 0; --u)
+ {
+ if (p->wu_code[u] < 0)
+ {
+ wet_reset(p, -p->wu_code[u] - 1);
+ }
+ else
+ {
+ int32_t w = p->wu_code[u];
+ p->wet_x[w] = p->wu_x[u];
+ p->wet_y[w] = p->wu_y[u];
+ p->wet_z[w] = p->wu_z[u];
+ p->wet_volume[w] = p->wu_volume[u];
+ p->wet_radius[w] = wet_disc_radius(p->wu_volume[u]);
+ }
+ }
+ p->wet_count = saved_count;
+ return status;
+ }
+ rederive_wet(p);
+ return ymir_particles_destroy_particles(p, n, h, step_count);
+}
+
+int32_t ymir_particles_take_wet(ymir_particles* p, int32_t n, const ymir_handle* sensors, const float* volumes, uint64_t step_count, float* taken)
+{
+ if (p == NULL || n < 0 || (n > 0 && (sensors == NULL || volumes == NULL)))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (!sensor_ok(p, sensors[k].lane, sensors[k].generation) || !isfinite(volumes[k]) || volumes[k] < 0.0f)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t j = 0; j < k; ++j)
+ {
+ if (sensors[j].lane == sensors[k].lane)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ }
+ int changed = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t s = sensors[k].lane;
+ if (taken != NULL)
+ {
+ taken[k] = 0.0f;
+ }
+ if (p->sensor_body[s] >= p->body_count || volumes[k] == 0.0f)
+ {
+ continue;
+ }
+ v3 c = sensor_centre(p, s);
+ float r = p->sensor_radius[s];
+ float w = pooled_walk(p, c, r, 1.0, step_count, NULL);
+ double f = w > 0.0f ? fmin(1.0, (double)volumes[k] / (double)w) : 0.0;
+ if (!(f > 0.0))
+ {
+ continue;
+ }
+ double removed = 0.0;
+ pooled_walk(p, c, r, 1.0 - f, step_count, &removed);
+ changed = 1;
+ if (taken != NULL)
+ {
+ taken[k] = (float)removed;
+ }
+ }
+ if (changed)
+ {
+ rederive_wet(p);
+ }
+ return YMIR_PARTICLES_OK;
+}
+
+int32_t ymir_particles_create_sensors(ymir_particles* p, int32_t n, const ymir_sensor_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out)
+{
+ if (p == NULL || n < 0 || (n > 0 && d == NULL))
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ for (int32_t k = 0; k < n; ++k)
+ {
+ if (d[k].body < 0 || d[k].body >= body_count || !finite3(d[k].point) || !isfinite(d[k].radius) || d[k].radius <= 0.0f)
+ {
+ return YMIR_PARTICLES_INVALID_ARGUMENT;
+ }
+ }
+ if (n > free_count(p->sensor_live, 0, p->sensor_removed_at, p->sensor_count, p->sensor_capacity, step_count))
+ {
+ return YMIR_PARTICLES_FULL;
+ }
+ int32_t from = 0;
+ for (int32_t k = 0; k < n; ++k)
+ {
+ int32_t s = next_lane(p->sensor_live, 0, p->sensor_removed_at, p->sensor_count, p->sensor_capacity, from, step_count);
+ from = s + 1;
+ p->sensor_live[s] = 1;
+ p->sensor_body[s] = d[k].body;
+ p->sensor_x[s] = d[k].point[0];
+ p->sensor_y[s] = d[k].point[1];
+ p->sensor_z[s] = d[k].point[2];
+ p->sensor_radius[s] = d[k].radius;
+ p->sensor_liquid_volume[s] = p->sensor_wet_volume[s] = 0.0f; // the first step's end reads them
+ if (s >= p->sensor_count)
+ {
+ p->sensor_count = s + 1;
+ }
+ if (out != NULL)
+ {
+ out[k] = (ymir_handle){s, p->sensor_generation[s]};
+ }
+ }
+ return YMIR_PARTICLES_OK;
+}
diff --git a/native/Ymir.Box3D/ymir_particles.h b/native/Ymir.Box3D/ymir_particles.h
new file mode 100644
index 0000000..22267e0
--- /dev/null
+++ b/native/Ymir.Box3D/ymir_particles.h
@@ -0,0 +1,330 @@
+// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps
+// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body
+// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver moves those proxies by the
+// constraints it solves, and the impulse each body accumulated comes back in the proxy for soa.c to apply.
+// See docs/soa-world.md.
+//
+// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type
+// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a
+// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every
+// topology command ends in and which is their only writer.
+//
+// Determinism: single thread; constraints are Gauss-Seidel in lane order; the one Jacobi pass (particle-particle
+// contact) accumulates and applies after the walk (each pair once, from the lower of its two cells, neighbours read in cell then index order
+// from a stable counting-sort grid, a pair weighted the same at both ends); proxy impulses are summed per body
+// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise
+// on MSVC) so no fused multiply-add changes a byte.
+//
+// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019).
+// No code of PhysX 5.6.0 or any other solver is adapted here.
+
+#ifndef YMIR_PARTICLES_H
+#define YMIR_PARTICLES_H
+
+#include
+
+enum
+{
+ YMIR_PARTICLES_OK = 0,
+ YMIR_PARTICLES_INVALID_ARGUMENT = 1,
+ YMIR_PARTICLES_DUPLICATE_ID = 2,
+ YMIR_PARTICLES_FULL = 3,
+ YMIR_PARTICLES_OUT_OF_MEMORY = 4,
+ YMIR_PARTICLES_REFERENCED = 6 // a body that a live attachment or sensor names cannot be released
+};
+
+// Phase word: bits 0-19 are the group; the four flags below are the only other bits.
+enum
+{
+ YMIR_PHASE_GROUP_MASK = 0xFFFFFu,
+ YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it)
+ YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it)
+ YMIR_PHASE_FLUID = 1u << 22, // a fluid particle: number density, not contact, with other fluid; contact with solids. Group and
+ // the SELF_* flags are ignored between two fluid particles (all fluid shares one density field)
+ YMIR_PHASE_NO_PARTICLE_CONTACT = 1u << 23, // not in the solid contact grid: no contact with another particle that is not fluid;
+ // bodies stop it and fluid still meets it. Refused with FLUID
+ YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER | YMIR_PHASE_FLUID |
+ YMIR_PHASE_NO_PARTICLE_CONTACT
+};
+
+// Lane sets a command names (a type for remove, a set for free_slots).
+enum
+{
+ YMIR_LANES_PARTICLE = 0,
+ YMIR_LANES_DISTANCE = 1,
+ YMIR_LANES_BEND = 2,
+ YMIR_LANES_ATTACHMENT = 3,
+ YMIR_LANES_WET = 4, // a wet patch: settled liquid on a body or a solid particle
+ YMIR_LANES_SENSOR = 5 // a liquid sensor: a sphere fixed in a body that reads the liquid volume inside it
+};
+
+enum
+{
+ YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane)
+ YMIR_ATTACH_STATIC = 1, // particle to a world point
+ YMIR_ATTACH_REMOVED = 2
+};
+
+enum
+{
+ YMIR_ATTACH_FLAG_TETHER = 1u, // bounds each particle by the rest path to the nearest point of its two nearest islands of tether attachments
+ YMIR_ATTACH_FLAG_LIMB = 2u, // the particle is flesh of its body's limb tree: contact skips every body whose limb-tree root is the attached body's root; refused on a STATIC attachment
+ YMIR_ATTACH_FLAG_ONE_WAY = 4u // the body side weighs nothing: the attachment holds its particle to the body's point and never moves or loads the body (the bone's own mass already carries the flesh); refused on a STATIC attachment
+};
+
+enum
+{
+ YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it
+ YMIR_PROXY_SPHERE = 1,
+ YMIR_PROXY_CAPSULE = 2, // segment along local Y
+ YMIR_PROXY_BOX = 3
+};
+
+// A lane and the generation it had when the handle was made.
+typedef struct ymir_handle
+{
+ int32_t lane;
+ uint32_t generation;
+} ymir_handle;
+
+typedef struct ymir_particle_capacities
+{
+ int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets, sensors; // fluid: the most live particles with the FLUID phase; wets: the most wet patches; sensors: the most liquid sensors
+} ymir_particle_capacities;
+
+// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and
+// the self-collision filter read it); `material` indexes the material table.
+typedef struct ymir_particle_desc
+{
+ float position[3];
+ float rest[3];
+ float velocity[3];
+ float mass;
+ float radius;
+ uint32_t phase;
+ uint32_t material;
+} ymir_particle_desc;
+
+// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0.
+typedef struct ymir_distance_desc
+{
+ ymir_handle a, b;
+ float rest;
+ float compliance;
+} ymir_distance_desc;
+
+// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off;
+// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off.
+typedef struct ymir_bend_desc
+{
+ ymir_handle e1, e2;
+ float compliance;
+ float max_angle;
+} ymir_bend_desc;
+
+// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body)
+// or the world (static).
+typedef struct ymir_attachment_desc
+{
+ uint32_t kind;
+ uint32_t flags;
+ ymir_handle particle;
+ int32_t body;
+ float point[3];
+ float compliance; // m/N, >= 0
+ uint32_t reserved;
+} ymir_attachment_desc;
+
+// A liquid sensor to create: a sphere of `radius` m (> 0) centred on `point` in the frame of body lane `body`.
+typedef struct ymir_sensor_desc
+{
+ int32_t body;
+ float point[3];
+ float radius;
+} ymir_sensor_desc;
+
+typedef struct ymir_material_desc
+{
+ float friction; // >= 0
+ float viscosity; // >= 0, XSPH c (dimensionless): a fluid pair's velocities relax toward each other by c W / n0 per substep; mean of the pair's two
+ float wet_friction; // >= 0: what settled liquid of this material does to friction where it lands; stored for the friction cut, read by nothing here
+ uint32_t pad;
+ uint64_t material_id;
+} ymir_material_desc;
+
+// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse`
+// (N s, world, about the body position) are the totals the particle phase delivered, written by it.
+typedef struct ymir_particle_proxy
+{
+ uint32_t shape;
+ float size[3];
+ float position[3];
+ float rotation[4]; // x y z w
+ float velocity[3];
+ float angular_velocity[3];
+ float inv_mass; // 0 for static, kinematic and anchor bodies
+ float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz
+ float impulse[3]; // N s, world: the tick's total, the sum of every substep's
+ float angular_impulse[3];
+ float sub_impulse[3]; // N s: this substep's, applied by the caller before the body's positions integrate
+ float sub_angular[3];
+ int32_t root; // the lane of the body's limb-tree root (the body itself when it has no parent); filled by the caller each step
+} ymir_particle_proxy;
+
+typedef struct ymir_particles
+{
+ int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity;
+ int32_t body_capacity, fluid_capacity; // fluid_capacity: the most live fluid particles; it sizes the neighbour arena
+ int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks
+ int32_t tether_count; // derived: the live tethers
+ int32_t body_count; // bodies filled in `proxies` this step
+ int32_t live_particles;
+ int32_t act_n, kin_n, act_dist_n, act_bend_n, act_att_n; // derived (rederive_active): the lengths of act, kin, act_dist, act_bend and act_att
+ int32_t fluid_rings; // derived by fluid_density: rings of kernel cells (4 rfmax) that hold a kernel pair, 0 without fluid
+ int32_t fluid_overflow; // kernel neighbours past a fluid particle's list in the last step, summed over substeps: a sensor
+ int32_t wet_capacity, wet_count; // wet patches: the capacity and the high-water mark
+ int32_t sensor_capacity, sensor_count; // liquid sensors: the capacity and the high-water mark
+ int32_t live_fluid; // derived: the live particles with the FLUID phase bit; the create and destroy commands are its only writers
+ ymir_particle_proxy* proxies;
+
+ // particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at
+ float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass;
+ float *rest_x, *rest_y, *rest_z;
+ uint32_t *phase, *material, *particle_live, *particle_generation;
+ uint64_t* particle_removed_at;
+ uint32_t* pinned; // command-owned (set_pinned writes it; destroy_particles frees it to 0): a pinned particle is dormant, on no step walk, its pos and vel stale until wake; a reader draws it from its anchor
+ // Derived by rederive_active alone, at command time; a step never writes them. act: the live unpinned particles; kin: the pinned particles an active
+ // distance or bend reaches (the step sets their pos and pp from their anchor); act_dist and act_bend: the live constraints with an unpinned particle;
+ // act_att: the live attachments of unpinned particles. All in lane order, so with nothing pinned they are every live lane and w is inv_mass.
+ int32_t *act, *kin, *act_dist, *act_bend, *act_att;
+ int32_t* anchor; // derived: the lane of the particle's lowest live non-TETHER attachment (BODY or STATIC), -1 for none; a pinned particle keeps the one it was pinned on
+ float* w; // derived: the inverse mass the step reads: 0 for a pinned or free lane, else inv_mass
+ int32_t* component; // derived: the lowest lane of the particle's distance-connected component
+ int32_t *held_start, *held_count; // derived (rederive_topology): the slice of held_body that lists the bodies particle i is attached to (BODY attachments), contact skips them
+ int32_t* held_body; // derived, attachment capacity: the live BODY attachments' bodies grouped by particle, in attachment lane order
+ int32_t* limb_body; // derived: the body of the particle's lowest live LIMB attachment, -1 for none; contact skips every body in that body's limb tree
+ int32_t *nbr, *nbr_start, *nbr_count; // scratch: the fluid rows' kernel neighbours in walk order, packed (CSR) in an arena of fluid_capacity * YMIR_FLUID_NEIGHBOURS; row i holds nbr_count[i] from nbr_start[i], this substep's
+ int32_t *support_body, *support_particle; // sensor: what a fluid particle touched in the last substep, the highest body lane / the first solid lane its row listed touching it; -1 for none, and always -1 for a solid or free lane
+ float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0
+
+ // wet lanes: a patch of settled liquid on one support, a body (wet_body, its point in the body frame) or a solid particle (wet_particle, point 0);
+ // one of the two is -1, and a free lane holds -1 in both. Written by settle, take_wet, remove and destroy_particles only; the step never touches them.
+ int32_t *wet_body, *wet_particle;
+ float *wet_x, *wet_y, *wet_z, *wet_radius, *wet_volume; // wet_volume m^3; wet_radius = sqrt(volume / (pi YMIR_WET_FILM))
+ uint32_t *wet_material, *wet_live, *wet_generation;
+ uint64_t* wet_removed_at;
+ int32_t *wet_order, *wet_body_start, *wet_body_count; // derived lookup index (rederive_wet): live body patches by body then centre x; each body's slice
+ float* wet_body_box; // derived, 7 per body: min xyz and max xyz of its discs' boxes, then its largest radius
+ float* particle_wet_mu; // derived, per particle lane: the wet friction of the lowest live patch on that solid particle, +inf when dry (rederive_wet)
+ float* wet_volume_body; // derived, per body lane: the sum of the live patches on it in wet lane order (rederive_wet, at command time only)
+ int32_t* wu_code; // settle's undo log, one entry per distinct drop: a patch lane (merged: its old lanes below) or -(lane + 1) (created)
+ float *wu_x, *wu_y, *wu_z, *wu_volume;
+
+ // sensor lanes: a sphere fixed in a body; a free lane reads live 0, body -1 and 0 elsewhere except generation and removed_at. Written by create_sensors and
+ // remove; sensor_liquid_volume and sensor_wet_volume are written by end alone, at the step's end (m^3): the sum of (2 r)^3 over the live fluid particles whose centre is inside,
+ // and the sum of the volumes of the live wet patches whose centre is inside, on any body or solid particle
+ int32_t* sensor_body;
+ float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_volume, *sensor_wet_volume;
+ uint32_t *sensor_live, *sensor_generation;
+ uint64_t* sensor_removed_at;
+
+ // distance lanes
+ int32_t *dist_a, *dist_b;
+ float *dist_rest, *dist_compliance;
+ float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor
+ uint32_t *dist_live, *dist_generation;
+ uint64_t* dist_removed_at;
+
+ // bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared)
+ int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c;
+ float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off
+ uint32_t *bend_live, *bend_generation;
+ uint64_t* bend_removed_at;
+
+ // attachment lanes
+ uint32_t *att_kind, *att_flags, *att_generation;
+ int32_t *att_particle, *att_body;
+ float *att_point_x, *att_point_y, *att_point_z, *att_compliance;
+ float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor
+ uint64_t* att_removed_at;
+
+ // tether lanes: derived: grouped by island in lane order (an island: tether particles joined by live distances, named by its
+ // lowest tether attachment), settle order within; per island one for each particle that is not a tether particle and holds the island
+ // among its two nearest, to the attachment point it is nearest; then per attachment pair with a body among them a route of
+ // booking lanes (attachment -1, edge only) along their rest path and the pair tether; parents come first;
+ // other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point
+ int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other;
+ float* tether_bound;
+
+ // material table
+ float *mat_friction, *mat_viscosity, *mat_wet_friction;
+ uint64_t* mat_id;
+
+ // solver scratch, allocated once at create
+ float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z, *lambda;
+ float fluid_k; // n0(h) = fluid_k / h^3: the Poly6 sum over the simple-cubic lattice of spacing h / 2, a create-time constant
+ int32_t *lane_list, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts;
+ float *sx, *sy, *sz, *sw; // the fluid grid's lanes in sorted order (predicted position, inverse mass): scratch, only fluid_density reads them
+ uint32_t* sphase; // the sorted lanes' phase
+ int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *via, *owner, *tether_of, *queue, *comp_size, *isle, *near_isle;
+ float *heap_key, *path, *near_path;
+ uint8_t* done;
+ uint32_t table_mask;
+ uint32_t grid_mask; // scratch: the solid contact grid's bucket mask (build_grid writes it, walk_half reads it)
+ void* arena;
+} ymir_particles;
+
+// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure.
+ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, int32_t body_capacity);
+void ymir_particles_free(ymir_particles* p);
+
+// The friction on body lane `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds it, never above mu.
+float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu);
+
+// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest
+// lane first. Every refusal happens before anything changes; a command that would need more tethers than the
+// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command and set_pinned ends in
+// the one rederive_topology, which refuses whole (INVALID_ARGUMENT) a command that would leave one distance component holding both a pinned
+// particle and a live TETHER attachment (a tether loads every lane of its component, and no walk moves a pinned one): wake it first.
+int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count);
+int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out);
+// Attaches n particles in the lowest free lanes, by cursor, as a batch: every desc is validated, FULL when fewer than n lanes are free, one derivation, and a derivation that does not fit backs every lane out.
+int32_t ymir_particles_attach(ymir_particles* p, int32_t n, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
+int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count);
+// Pins (1) or wakes (0) the named particles. A pinned particle is dormant: on no step walk (a particle of a live distance or bend with an
+// unpinned particle is held on its anchor each substep instead), its pos and vel stale, drawn from its anchor. Refuses whole (INVALID_ARGUMENT,
+// nothing changed) a stale or dead handle, `pinned` not 0 or 1, a fluid particle, pinned 1 on a particle with no anchor, and what
+// rederive_topology refuses. The wake sets pos to the anchor's point at the proxies' pose now (the caller has filled
+// them) and vel to that point's velocity. Ends in rederive_topology. remove(ATTACHMENT) refuses a pinned particle's anchor.
+int32_t ymir_particles_set_pinned(ymir_particles* p, int32_t n, const ymir_handle* h, uint32_t pinned);
+// Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else
+// support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole
+// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no live patch of its material anywhere to merge into, before any
+// change. A drop that finds no lane and no patch on its support adds its volume to the nearest patch of its material in the world (the patch's centre stays). `out` (NULL or n handles) receives the patch each drop landed in.
+int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count, ymir_handle* out);
+// Takes pooled liquid out of the wet patches a liquid sensor reads. Refuses whole (INVALID_ARGUMENT, nothing changed) n < 0, a NULL array with n > 0, a stale or dead
+// sensor, a sensor named twice, and a volume that is not finite or is < 0. Then per sensor in call order: W is the pooled volume of the patches whose centres lie in the
+// sensor's sphere (the walk the reading sums, at the proxies' pose now), f = W > 0 ? min(1, volume / W) : 0, and every patch in the sphere keeps (1 - f) of its volume
+// (radius recomputed; a patch at f == 1 is removed as remove(WET)): proportional, so no lane order decides which patch gives. A later sensor sees an earlier one's take.
+// `taken` (NULL or n floats) receives per sensor the summed volume that left the patches (m^3): float rounding can leave it below the ask, or 0. Readings change at the next step's end; none is written here. One rederive_wet at the end when anything changed.
+int32_t ymir_particles_take_wet(ymir_particles* p, int32_t n, const ymir_handle* sensors, const float* volumes, uint64_t step_count, float* taken);
+// Creates liquid sensors in the lowest free lanes. Refuses whole (INVALID_ARGUMENT) a body outside [0, body_count), a radius that is not finite and > 0, or a
+// non-finite point; FULL when there are not n free lanes; nothing changes. A sensor only reads: its volume moves nothing.
+int32_t ymir_particles_create_sensors(ymir_particles* p, int32_t n, const ymir_sensor_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
+// Frees what the particle layer holds on body lane `body` so the body can be removed: REFERENCED, changing nothing, while a live body
+// attachment or a live sensor names it (the caller removes those first); otherwise every live wet patch on it is removed (one rederive_wet) and
+// `patches` and `volume` (either may be NULL) receive their count and summed volume (m^3). No rigid-body call.
+int32_t ymir_particles_release_body(ymir_particles* p, int32_t body, uint64_t step_count, uint32_t* patches, float* volume);
+int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d);
+int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count);
+
+// The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the
+// proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each
+// proxy's pose and velocity; it then applies each proxy's sub_impulse before positions integrate), end once.
+int32_t ymir_particles_begin(ymir_particles* p);
+void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz);
+void ymir_particles_end(ymir_particles* p, int32_t substeps);
+
+#endif
diff --git a/src/Ymir.Box3D/Box3DNative.cs b/src/Ymir.Box3D/Box3DNative.cs
deleted file mode 100644
index fa82bd2..0000000
--- a/src/Ymir.Box3D/Box3DNative.cs
+++ /dev/null
@@ -1,277 +0,0 @@
-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 nint ymir_box3d_get_build_id();
-
- [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,
- out uint contactEventOutputSize);
-
- [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_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,
- uint isKinematic);
-
- [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(
- 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);
-
- [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
-{
- 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,
- ulong CollisionCategoryBits,
- ulong CollisionMaskBits,
- float PositionX,
- float PositionZ,
- float VelocityX,
- float VelocityZ,
- float DirectionX,
- float DirectionZ,
- float AngularVelocity,
- float Torque,
- float Radius,
- float Mass,
- float Restitution,
- uint IsStatic,
- uint IsKinematic,
- uint IsBullet,
- uint ParticipatesInFields,
- int CollisionGroupIndex);
-
-[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 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,
- 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
deleted file mode 100644
index a2f480f..0000000
--- a/src/Ymir.Box3D/Box3DQueries.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-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/Box3DRuntime.cs b/src/Ymir.Box3D/Box3DRuntime.cs
deleted file mode 100644
index f1df20e..0000000
--- a/src/Ymir.Box3D/Box3DRuntime.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace Ymir.Box3D;
-
-public static class Box3DRuntime
-{
- public const string NativeBuildId =
- "box3d-8441b4a06d6d09dcfb0b0f704df4d847d1437b92-abi5-f32";
-
- public static string ValidatedBuildId
- {
- get
- {
- Box3DSession.EnsureCompatibleNativeLibrary();
- return NativeBuildId;
- }
- }
-}
diff --git a/src/Ymir.Box3D/Box3DSession.cs b/src/Ymir.Box3D/Box3DSession.cs
deleted file mode 100644
index 43bc1a3..0000000
--- a/src/Ymir.Box3D/Box3DSession.cs
+++ /dev/null
@@ -1,411 +0,0 @@
-using System.Runtime.InteropServices;
-
-namespace Ymir.Box3D;
-
-internal readonly record struct Box3DBody(
- ulong StableId,
- ulong CollisionCategoryBits,
- ulong CollisionMaskBits,
- float PositionX,
- float PositionZ,
- float VelocityX,
- float VelocityZ,
- float DirectionX,
- float DirectionZ,
- float AngularVelocity,
- float Torque,
- float Radius,
- float Mass,
- float Restitution,
- bool IsStatic,
- bool IsKinematic,
- bool IsBullet,
- bool ParticipatesInFields,
- int CollisionGroupIndex);
-
-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 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 = 5;
- 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.CollisionCategoryBits,
- body.CollisionMaskBits,
- 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,
- body.IsKinematic ? 1u : 0u,
- body.IsBullet ? 1u : 0u,
- body.ParticipatesInFields ? 1u : 0u,
- body.CollisionGroupIndex);
- }
-
- 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 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,
- bool isKinematic)
- {
- ThrowIfDisposed();
- ThrowIfMutationFailed(
- Box3DNative.ymir_box3d_session_configure(
- _handle, stableId, radius, mass, restitution, isStatic ? 1u : 0u, isKinematic ? 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();
- 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)
- {
- ThrowIfMutationFailed(
- 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();
- }
-
- 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)
- {
- 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}.");
- }
-
- var buildId = Marshal.PtrToStringAnsi(Box3DNative.ymir_box3d_get_build_id());
- if (!string.Equals(buildId, Box3DRuntime.NativeBuildId, StringComparison.Ordinal))
- {
- throw new InvalidOperationException(
- $"Ymir Box3D build mismatch. Managed expects '{Box3DRuntime.NativeBuildId}', native provides '{buildId ?? ""}'.");
- }
-
- ThrowIfFailed(
- Box3DNative.ymir_box3d_get_abi_layout(
- out var bodyInputSize,
- out var fieldInputSize,
- out var bodyOutputSize,
- 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)
- {
- 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 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.CollisionCategoryBits,
- body.CollisionMaskBits,
- 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,
- 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/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs
new file mode 100644
index 0000000..0a0f005
--- /dev/null
+++ b/src/Ymir.Box3D/Box3DSoaWorld.cs
@@ -0,0 +1,1625 @@
+using System.Buffers;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace Ymir.Box3D;
+
+public enum Box3DSoaKind : uint
+{
+ Sphere = 0,
+ StaticBox = 1,
+ Capsule = 2,
+ Box = 3,
+ /// A kinematic body with no shape: it never collides or is hit, and only moves it.
+ Anchor = 4,
+ /// The kind lane of a removed body (a tombstone, from RemoveBody): every other lane reads 0 and the parent -1.
+ Removed = 5,
+ /// A static heightfield terrain body whose native heightfield data is owned by the world until removed or disposed.
+ StaticHeightField = 6,
+ /// A static triangle mesh body whose native mesh data is owned by the world until removed or disposed.
+ StaticMesh = 7
+}
+
+public enum Box3DSoaJointKind : uint
+{
+ Revolute = 0,
+ Spherical = 1,
+ Weld = 2,
+ /// Position springs pulling body B's frame onto body A's, bounded by a maximum force and torque.
+ Motor = 3,
+ /// The kind lane of a retired joint (a tombstone, from DestroyJoint): bodies read -1 and every other lane 0.
+ Removed = 4
+}
+
+/// Native layout of ymir_box3d_soa_body_desc.
+[StructLayout(LayoutKind.Sequential)]
+internal struct Box3DSoaBodyDesc
+{
+ public ulong StableId;
+ public uint Kind;
+ public int Parent;
+ public int Limb;
+ public uint Reserved;
+ public float PositionX, PositionY, PositionZ;
+ public float RotationX, RotationY, RotationZ, RotationW;
+ public float VelocityX, VelocityY, VelocityZ;
+ public float Size0, Size1, Size2;
+ public float Density, Friction, Restitution, RollingResistance;
+ public ulong MaterialId;
+}
+
+/// Native layout of ymir_box3d_soa_joint_desc.
+[StructLayout(LayoutKind.Sequential)]
+internal struct Box3DSoaJointDesc
+{
+ public uint Kind;
+ public int BodyA;
+ public int BodyB;
+ public uint EnableLimit;
+ public float AnchorX, AnchorY, AnchorZ;
+ public float AxisX, AxisY, AxisZ;
+ public float Lower, Upper, ConeAngle;
+ public float LinearHertz, LinearDamping, MaxForce, AngularHertz, AngularDamping, MaxTorque;
+ public float ForceThreshold, TorqueThreshold;
+}
+
+/// Native layout of ymir_box3d_soa_ray_hit.
+[StructLayout(LayoutKind.Sequential)]
+internal struct Box3DSoaRayHitNative
+{
+ public int Hit;
+ public int Lane;
+ public ulong StableId;
+ public float PointX, PointY, PointZ;
+ public float NormalX, NormalY, NormalZ;
+ public float Fraction;
+ public uint Reserved;
+}
+
+///
+/// A particle's identity: its lane and the slot's generation when it was made. Native layout of ymir_handle.
+/// Converts to the lane for reading lanes; commands refuse a handle from an earlier occupant of the slot.
+///
+[StructLayout(LayoutKind.Sequential)]
+public readonly record struct Box3DSoaParticleHandle(int Lane, uint Generation)
+{
+ public static implicit operator int(Box3DSoaParticleHandle handle) => handle.Lane;
+}
+
+/// The constraint lane sets. Native numbering: a particle is set 0.
+public enum Box3DSoaConstraintType : uint
+{
+ Distance = 1,
+ Bend = 2,
+ Attachment = 3,
+ /// A wet patch: settled liquid on a body or a solid particle.
+ Wet = 4,
+ /// A liquid sensor: a sphere fixed in a body that reads the liquid volume inside it each step.
+ Sensor = 5
+}
+
+/// A constraint's identity: its type, lane and the slot's generation when it was made.
+public readonly record struct Box3DSoaConstraintHandle(Box3DSoaConstraintType Type, int Lane, uint Generation)
+{
+ public static implicit operator int(Box3DSoaConstraintHandle handle) => handle.Lane;
+}
+
+/// The phase word: bits 0-19 are the group; the flags are the only other bits.
+public static class Box3DSoaPhase
+{
+ public const uint GroupMask = 0xFFFFFu;
+ /// Particles of one group collide (both must set it).
+ public const uint SelfCollide = 1u << 20;
+ /// ...except pairs closer than 1.5 (ri + rj) in the rest pose (either may carry it).
+ public const uint SelfFilter = 1u << 21;
+ /// A fluid particle: number density, not contact, with other fluid; contact with solids. Fluid holds no distance, bend or attachment.
+ public const uint Fluid = 1u << 22;
+ /// Left out of the solid contact grid: no contact with another non-fluid particle. Bodies stop it and fluid still meets it. Refused with .
+ public const uint NoParticleContact = 1u << 23;
+
+ public static uint Of(uint group, bool selfCollide = false, bool selfFilter = false, bool fluid = false, bool noParticleContact = false) =>
+ (group & GroupMask) | (selfCollide ? SelfCollide : 0u) | (selfFilter ? SelfFilter : 0u) | (fluid ? Fluid : 0u) |
+ (noParticleContact ? NoParticleContact : 0u);
+}
+
+/// Capacities of the particle state; null or all zero is a world without particles (ABI 8 behaviour).
+[StructLayout(LayoutKind.Sequential)]
+public readonly record struct Box3DSoaParticleCapacities(int Particles, int Distances, int Bends, int Attachments, int Tethers, int Materials, int Fluid = 0, int Wets = 0, int Sensors = 0);
+
+/// Native layout of ymir_particle_desc: a particle to create. Mass kg (0 = immovable); rest is its place in the rest pose.
+[StructLayout(LayoutKind.Sequential)]
+public struct Box3DSoaParticleDesc
+{
+ public float X, Y, Z;
+ public float RestX, RestY, RestZ;
+ public float VelocityX, VelocityY, VelocityZ;
+ public float Mass, Radius;
+ public uint Phase, Material;
+
+ /// A particle at , its rest pose the same place unless says otherwise.
+ public Box3DSoaParticleDesc((float X, float Y, float Z) position, float mass, float radius, uint phase = 0, uint material = 0, (float X, float Y, float Z)? rest = null, (float X, float Y, float Z) velocity = default)
+ {
+ (X, Y, Z) = position;
+ (RestX, RestY, RestZ) = rest ?? position;
+ (VelocityX, VelocityY, VelocityZ) = velocity;
+ Mass = mass; Radius = radius; Phase = phase; Material = material;
+ }
+}
+
+/// Native layout of ymir_distance_desc. Rest < 0 takes the rest-pose length; compliance is m/N.
+[StructLayout(LayoutKind.Sequential)]
+public struct Box3DSoaDistanceDesc
+{
+ public Box3DSoaParticleHandle A, B;
+ public float Rest, Compliance;
+
+ public Box3DSoaDistanceDesc(Box3DSoaParticleHandle a, Box3DSoaParticleHandle b, float compliance = 0f, float rest = -1f)
+ {
+ A = a; B = b; Rest = rest; Compliance = compliance;
+ }
+}
+
+///
+/// Native layout of ymir_bend_desc: a bend over two distances that share one particle. A compliance < 0 switches
+/// the soft pass off, a max angle (radians from straight) < 0 the hard limit.
+///
+[StructLayout(LayoutKind.Sequential)]
+public struct Box3DSoaBendDesc
+{
+ public int E1;
+ public uint G1;
+ public int E2;
+ public uint G2;
+ public float Compliance, MaxAngle;
+
+ public Box3DSoaBendDesc(Box3DSoaConstraintHandle e1, Box3DSoaConstraintHandle e2, float compliance = 1e-4f, float maxAngle = -1f)
+ {
+ E1 = e1.Lane; G1 = e1.Generation; E2 = e2.Lane; G2 = e2.Generation; Compliance = compliance; MaxAngle = maxAngle;
+ }
+}
+
+///
+/// Native layout of ymir_attachment_desc; see
+/// for the fields.
+///
+[StructLayout(LayoutKind.Sequential)]
+public struct Box3DSoaAttachmentDesc
+{
+ public uint Kind;
+ public uint Flags;
+ public Box3DSoaParticleHandle Particle;
+ public int Body;
+ public float PointX, PointY, PointZ;
+ public float Compliance;
+ public uint Reserved;
+
+ public Box3DSoaAttachmentDesc(
+ Box3DSoaAttachKind kind, Box3DSoaParticleHandle particle, int target = -1, (float X, float Y, float Z) point = default,
+ float compliance = 0f, bool tether = false, bool limb = false, bool oneWay = false)
+ {
+ Kind = (uint)kind;
+ Flags = (tether ? 1u : 0u) | (limb ? 2u : 0u) | (oneWay ? 4u : 0u);
+ Particle = particle;
+ Body = target;
+ PointX = point.X; PointY = point.Y; PointZ = point.Z;
+ Compliance = compliance;
+ Reserved = 0;
+ }
+}
+
+/// Native layout of ymir_sensor_desc: a sphere of Radius m (> 0) centred on Point in the frame of body lane Body.
+[StructLayout(LayoutKind.Sequential)]
+internal struct Box3DSoaSensorDesc
+{
+ public int Body;
+ public float PointX, PointY, PointZ;
+ public float Radius;
+}
+
+/// Native layout of ymir_material_desc.
+[StructLayout(LayoutKind.Sequential)]
+internal struct Box3DSoaMaterialDesc
+{
+ public float Friction;
+ public float Viscosity;
+ public float WetFriction;
+ public uint Pad;
+ public ulong MaterialId;
+}
+
+public enum Box3DSoaAttachKind : uint
+{
+ /// The particle to a point fixed in a body: target is the body lane, point is in the body's frame.
+ Body = 0,
+ /// The particle to a world point (point); target is ignored.
+ Static = 1,
+ /// The kind lane of a removed attachment (a tombstone).
+ Removed = 2
+}
+
+///
+/// A joint's identity: its lane and the slot's generation when it was added. Converts to the lane for reading lanes;
+/// takes the whole handle and refuses one from an earlier occupant of the slot.
+///
+public readonly record struct Box3DSoaJointHandle(int Lane, uint Generation)
+{
+ public static implicit operator int(Box3DSoaJointHandle handle) => handle.Lane;
+}
+
+///
+/// A body's identity: its lane and the lane's generation when it was added. Converts to the lane for reading lanes and for every
+/// parameter that names a body; takes the whole handle and refuses one from an earlier occupant of the lane.
+///
+public readonly record struct Box3DSoaBodyHandle(int Lane, uint Generation)
+{
+ public static implicit operator int(Box3DSoaBodyHandle handle) => handle.Lane;
+}
+
+/// The closest hit of a ray. false is a miss and every other field is then default.
+public readonly record struct Box3DSoaRayHit(
+ bool Hit, int Lane, ulong StableId, (float X, float Y, float Z) Point, (float X, float Y, float Z) Normal, float Fraction);
+
+/// Native layout of ymir_box3d_soa_view: counts, then one pointer per lane.
+[StructLayout(LayoutKind.Sequential)]
+internal unsafe struct Box3DSoaViewNative
+{
+ public uint AbiVersion;
+ public int Count;
+ public int Capacity;
+ public int JointCount;
+ public int JointCapacity;
+ public uint Reserved;
+ public ulong StepCount;
+ public int ParticleCount;
+ public int ParticleCapacity;
+ public int FluidNeighbourOverflow;
+ public int DistanceCount;
+ public int DistanceCapacity;
+ public int BendCount;
+ public int BendCapacity;
+ public int AttachmentCount;
+ public int AttachmentCapacity;
+ public int TetherCount;
+ public int TetherCapacity;
+ public int MaterialCapacity;
+ public int WetCount;
+ public int SensorCount;
+ public ulong* StableId;
+ public uint* Kind;
+ public int* Parent;
+ public int* Limb;
+ public float* Size0;
+ public float* Size1;
+ public float* Size2;
+ public float* PositionX;
+ public float* PositionY;
+ public float* PositionZ;
+ public float* RotationX;
+ public float* RotationY;
+ public float* RotationZ;
+ public float* RotationW;
+ public float* VelocityX;
+ public float* VelocityY;
+ public float* VelocityZ;
+ public float* AngularVelocityX;
+ public float* AngularVelocityY;
+ public float* AngularVelocityZ;
+ public float* ForceX;
+ public float* ForceY;
+ public float* ForceZ;
+ public float* TorqueX;
+ public float* TorqueY;
+ public float* TorqueZ;
+ public uint* JointKind;
+ public int* JointBodyA;
+ public int* JointBodyB;
+ public float* JointAngle;
+ public float* JointFrameX;
+ public float* JointFrameY;
+ public float* JointFrameZ;
+ public float* JointFrameW;
+ public float* JointRotationX;
+ public float* JointRotationY;
+ public float* JointRotationZ;
+ public float* JointRotationW;
+ public float* JointAngularVelocityX;
+ public float* JointAngularVelocityY;
+ public float* JointAngularVelocityZ;
+ public float* JointOriginX;
+ public float* JointOriginY;
+ public float* JointOriginZ;
+ public float* JointConstraintForceX;
+ public float* JointConstraintForceY;
+ public float* JointConstraintForceZ;
+ public float* JointConstraintTorqueX;
+ public float* JointConstraintTorqueY;
+ public float* JointConstraintTorqueZ;
+ public float* ContactImpulse;
+ public int* ContactCount;
+ public ulong* MaterialId;
+ public float* Mass;
+ public uint* BodyGeneration;
+ public uint* JointGeneration;
+ public float* ParticleImpulseX;
+ public float* ParticleImpulseY;
+ public float* ParticleImpulseZ;
+ public float* ParticleX;
+ public float* ParticleY;
+ public float* ParticleZ;
+ public float* ParticleVx;
+ public float* ParticleVy;
+ public float* ParticleVz;
+ public float* ParticleRadius;
+ public float* ParticleInvMass;
+ public float* ParticleRestX;
+ public float* ParticleRestY;
+ public float* ParticleRestZ;
+ public uint* ParticlePhase;
+ public uint* ParticleMaterial;
+ public uint* ParticleLive;
+ public uint* ParticleGeneration;
+ public ulong* ParticleRemovedAt;
+ public int* ParticleComponent;
+ public float* ParticleDensity;
+ public int* DistanceA;
+ public int* DistanceB;
+ public float* DistanceRest;
+ public float* DistanceCompliance;
+ public float* DistanceTension;
+ public uint* DistanceLive;
+ public uint* DistanceGeneration;
+ public ulong* DistanceRemovedAt;
+ public int* BendE1;
+ public int* BendE2;
+ public int* BendA;
+ public int* BendB;
+ public int* BendC;
+ public float* BendRest;
+ public float* BendLimit;
+ public float* BendCompliance;
+ public uint* BendLive;
+ public uint* BendGeneration;
+ public ulong* BendRemovedAt;
+ public uint* AttachmentKind;
+ public uint* AttachmentFlags;
+ public uint* AttachmentGeneration;
+ public int* AttachmentParticle;
+ public int* AttachmentBody;
+ public float* AttachmentPointX;
+ public float* AttachmentPointY;
+ public float* AttachmentPointZ;
+ public float* AttachmentCompliance;
+ public float* AttachmentForceX;
+ public float* AttachmentForceY;
+ public float* AttachmentForceZ;
+ public ulong* AttachmentRemovedAt;
+ public int* TetherAtt;
+ public int* TetherParticle;
+ public int* TetherParent;
+ public int* TetherEdge;
+ public int* TetherOther;
+ public float* TetherBound;
+ public float* MaterialFriction;
+ public ulong* MaterialTableId;
+ public float* MaterialViscosity;
+ public int* SupportBody;
+ public int* SupportParticle;
+ public int* WetBody;
+ public int* WetParticle;
+ public float* WetX;
+ public float* WetY;
+ public float* WetZ;
+ public float* WetRadius;
+ public float* WetPatchVolume;
+ public uint* WetMaterial;
+ public uint* WetLive;
+ public uint* WetGeneration;
+ public ulong* WetRemovedAt;
+ public float* BodyWetVolume;
+ public float* MaterialWetFriction;
+ public int* SensorBody;
+ public float* SensorX;
+ public float* SensorY;
+ public float* SensorZ;
+ public float* SensorRadius;
+ public float* SensorLiquidVolume;
+ public float* SensorWetVolume;
+ public uint* SensorLive;
+ public uint* SensorGeneration;
+ public ulong* SensorRemovedAt;
+ public uint* ParticlePinned;
+ public int* ParticleAnchor;
+}
+
+/// Native layout of ymir_box3d_soa_facts: counts, dropped counters, then three pointers.
+[StructLayout(LayoutKind.Sequential)]
+internal unsafe struct Box3DSoaFactsNative
+{
+ public uint BeginCount;
+ public uint EndCount;
+ public uint HitCount;
+ public uint FactCapacity;
+ public uint BeginDropped;
+ public uint EndDropped;
+ public uint HitDropped;
+ public uint Reserved;
+ public Box3DSoaTouch* Begin;
+ public Box3DSoaTouch* End;
+ public Box3DSoaHit* Hit;
+ public Box3DSoaOverload* Overload;
+ public uint OverloadCount;
+ public uint Reserved2;
+ public uint BodyRemovedCount;
+ public uint JointRemovedCount;
+ public Box3DSoaBodyRemoved* BodyRemoved;
+ public Box3DSoaJointRemoved* JointRemoved;
+ public uint TouchingCount;
+ public uint TouchingDropped;
+ public Box3DSoaTouch* Touching;
+}
+
+/// A body removed by RemoveBody since the previous step, published by the next one. The lane and generation are the dead handle's;
+/// and (m^3) are the wet patches its removal took with it.
+[StructLayout(LayoutKind.Sequential)]
+public readonly struct Box3DSoaBodyRemoved
+{
+ public readonly int Lane;
+ public readonly uint Generation;
+ public readonly ulong StableId;
+ public readonly uint WetPatches;
+ public readonly float WetVolume;
+}
+
+/// A joint retired since the previous step, published by the next one: by DestroyJoint ( 0) or because RemoveBody
+/// removed a body it named (1). The lane and generation are the dead handle's; the bodies are the two it joined.
+[StructLayout(LayoutKind.Sequential)]
+public readonly struct Box3DSoaJointRemoved
+{
+ public readonly int Lane;
+ public readonly uint Generation;
+ public readonly int BodyA;
+ public readonly int BodyB;
+ public readonly uint WithBody;
+}
+
+/// A joint whose load reached its threshold in the step just taken, with the load (world frame; N and N m) Box3D reports for it after the step. The joint stays: Ymir never removes on a threshold.
+[StructLayout(LayoutKind.Sequential)]
+public readonly struct Box3DSoaOverload
+{
+ public readonly int JointLane;
+ public readonly uint JointGeneration;
+ public readonly float ForceX, ForceY, ForceZ;
+ public readonly float TorqueX, TorqueY, TorqueZ;
+}
+
+/// A begin or end of touch, or a pair touching after the step: the two bodies' lane indices and the two shapes' stable ids.
+[StructLayout(LayoutKind.Sequential)]
+public readonly struct Box3DSoaTouch
+{
+ public readonly int LaneA;
+ public readonly int LaneB;
+ public readonly ulong StableIdA;
+ public readonly ulong StableIdB;
+}
+
+/// A touch that approached faster than the world's hit threshold. Normal points from A to B.
+[StructLayout(LayoutKind.Sequential)]
+public readonly struct Box3DSoaHit
+{
+ public readonly int LaneA;
+ public readonly int LaneB;
+ public readonly ulong StableIdA;
+ public readonly ulong StableIdB;
+ public readonly float PointX, PointY, PointZ;
+ public readonly float NormalX, NormalY, NormalZ;
+ /// Metres per second, always positive.
+ public readonly float ApproachSpeed;
+ /// Normal impulse (N s) the pair's contact delivered over the whole step: the exact sum of Box3D's stepNormalImpulse over the manifold of the two shapes. Normal channel only.
+ public readonly float Impulse;
+ public readonly ulong MaterialA;
+ public readonly ulong MaterialB;
+}
+
+/// Facts past 's fact capacity that the last step could not keep.
+public readonly record struct Box3DSoaDropped(uint Begin, uint End, uint Hit, uint Touching);
+
+///
+/// What Box3D reported for the step just taken, in Box3D's event order: spans over native buffers that
+/// are fixed for the world's life and rewritten by every step, so they are valid until the next
+/// and invalid once the world is disposed.
+///
+public readonly unsafe ref struct Box3DSoaFacts
+{
+ private readonly Box3DSoaFactsNative _f;
+ private readonly Box3DSoaWorld _world;
+
+ internal Box3DSoaFacts(Box3DSoaFactsNative f, Box3DSoaWorld world)
+ {
+ _f = f;
+ _world = world;
+ }
+
+ private ReadOnlySpan Facts(T* p, uint n) where T : unmanaged
+ {
+ _world.ThrowIfDisposed();
+ return new(p, (int)n);
+ }
+
+ public ReadOnlySpan Begin => Facts(_f.Begin, _f.BeginCount);
+ public ReadOnlySpan End => Facts(_f.End, _f.EndCount);
+ /// Each pair of bodies touching after the step, once, LaneA < LaneB, in lane then Box3D contact order: the read that fills ContactCount.
+ public ReadOnlySpan Touching => Facts(_f.Touching, _f.TouchingCount);
+ public ReadOnlySpan Hit => Facts(_f.Hit, _f.HitCount);
+ /// Joints that reached a force or torque threshold in the last step (at most once each), in Box3D's joint order.
+ public ReadOnlySpan Overloads => Facts(_f.Overload, _f.OverloadCount);
+ /// Bodies removed since the previous step, in removal order. A touch such a body was in ends in by its old lane and stable id.
+ public ReadOnlySpan BodiesRemoved => Facts(_f.BodyRemoved, _f.BodyRemovedCount);
+ /// Joints retired since the previous step, in removal order: every DestroyJoint and every joint a RemoveBody took.
+ public ReadOnlySpan JointsRemoved => Facts(_f.JointRemoved, _f.JointRemovedCount);
+ public Box3DSoaDropped Dropped => new(_f.BeginDropped, _f.EndDropped, _f.HitDropped, _f.TouchingDropped);
+ public int Capacity => (int)_f.FactCapacity;
+}
+
+internal static unsafe partial class Box3DSoaNative
+{
+ private const string Library = "ymir_box3d";
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_abi_version();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_view_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_body_desc_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_joint_desc_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_facts_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_touch_fact_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_ray_hit_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_hit_fact_size();
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_create(int capacity, int jointCapacity, float gx, float gy, float gz, int factCapacity, float hitThreshold, Box3DSoaParticleCapacities* particles, out nint world);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial void ymir_box3d_soa_destroy(nint world);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_add_body(nint world, in Box3DSoaBodyDesc desc, out int index);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_add_static_heightfield(
+ nint world, ulong stableId, float originX, float originY, float originZ,
+ float* heights, int countX, int countZ, float scaleX, float scaleY, float scaleZ,
+ float minHeight, float maxHeight, float friction, float restitution, ulong materialId, out int index);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_add_static_mesh(
+ nint world, ulong stableId, float originX, float originY, float originZ,
+ float* verticesXyz, int vertexCount, int* triangleIndices, int triangleCount,
+ float friction, float restitution, ulong materialId, out int index);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_add_joint(nint world, in Box3DSoaJointDesc desc, out int index);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_step(nint world, float timeStep, int subStepCount);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_get_view(nint world, out Box3DSoaViewNative view);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_get_facts(nint world, out Box3DSoaFactsNative facts);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_destroy_joint(nint world, int joint, uint generation);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_remove_body(nint world, int lane, uint generation);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_free_body_slots(nint world);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_set_joint_thresholds(nint world, int joint, uint generation, float forceThreshold, float torqueThreshold);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_free_joint_slots(nint world);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_set_anchor_target(nint world, int lane, float* position, float* rotation, float timeStep);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_apply_impulse(nint world, int lane, float* impulse, float* point);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_cast_ray_closest(nint world, float* origin, float* translation, out Box3DSoaRayHitNative hit);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial uint ymir_box3d_soa_get_particle_desc_size(uint which);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_create_particles(nint world, int n, Box3DSoaParticleDesc* desc, Box3DSoaParticleHandle* output);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_destroy_particles(nint world, int n, Box3DSoaParticleHandle* handles);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_create_distances(nint world, int n, Box3DSoaDistanceDesc* desc, Box3DSoaParticleHandle* output);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_create_bends(nint world, int n, Box3DSoaBendDesc* desc, Box3DSoaParticleHandle* output);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_attach(nint world, int n, Box3DSoaAttachmentDesc* desc, Box3DSoaParticleHandle* output);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_set_pinned(nint world, int n, Box3DSoaParticleHandle* particles, uint pinned);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_create_sensors(nint world, int n, Box3DSoaSensorDesc* desc, Box3DSoaParticleHandle* output);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_settle(nint world, int n, Box3DSoaParticleHandle* handles, Box3DSoaParticleHandle* output);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_take_wet(nint world, int n, Box3DSoaParticleHandle* sensors, float* volumes, float* taken);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_remove(nint world, uint type, int n, Box3DSoaParticleHandle* handles);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_set_material(nint world, int index, in Box3DSoaMaterialDesc desc);
+
+ [LibraryImport(Library)]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ internal static partial int ymir_box3d_soa_free_slots(nint world, uint laneSet);
+}
+
+///
+/// The lanes of a : contiguous native arrays, one per component, indexed
+/// by body. Each accessor is a span over native memory, not a copy. The pointers are fixed for the
+/// world's life, the contents change only inside , and every span is
+/// invalid once the world is disposed.
+///
+public readonly unsafe struct Box3DSoaView
+{
+ private readonly Box3DSoaViewNative _v;
+ private readonly Box3DSoaWorld? _world;
+
+ private ReadOnlySpan Lane(T* p, int n) where T : unmanaged
+ {
+ (_world ?? throw new InvalidOperationException("This Box3DSoaView has no world; take it from Box3DSoaWorld.View.")).ThrowIfDisposed();
+ return new(p, n);
+ }
+
+ private Span Write(T* p, int n) where T : unmanaged
+ {
+ (_world ?? throw new InvalidOperationException("This Box3DSoaView has no world; take it from Box3DSoaWorld.View.")).ThrowIfDisposed();
+ return new(p, n);
+ }
+
+ internal Box3DSoaView(Box3DSoaViewNative v, Box3DSoaWorld world)
+ {
+ _v = v;
+ _world = world;
+ }
+
+ /// Bodies at the moment this view was taken: take it after the last Add. Only the lane contents are live.
+ public int Count => _v.Count;
+ public int Capacity => _v.Capacity;
+
+ public ReadOnlySpan StableId => Lane(_v.StableId, Count);
+ public ReadOnlySpan Kind => Lane(_v.Kind, Count);
+ /// Lane index of the body's parent in the limb tree, or -1 for a root. Set at creation, not used by Box3D.
+ public ReadOnlySpan Parent => Lane(_v.Parent, Count);
+ /// The caller's limb label for the body. Set at creation, not used by Box3D.
+ public ReadOnlySpan Limb => Lane(_v.Limb, Count);
+ /// The body's shape size, read-only, set at creation and never changed by Step. Size0 is the sphere or
+ /// capsule radius, or the box half-extent x; Size1 is the capsule half-length (along local Y) or the box half-extent y;
+ /// Size2 is the box half-extent z. Unused components are 0. Shapes are centred on the body origin.
+ public ReadOnlySpan Size0 => Lane(_v.Size0, Count);
+ public ReadOnlySpan Size1 => Lane(_v.Size1, Count);
+ public ReadOnlySpan Size2 => Lane(_v.Size2, Count);
+ public ReadOnlySpan PositionX => Lane(_v.PositionX, Count);
+ public ReadOnlySpan PositionY => Lane(_v.PositionY, Count);
+ public ReadOnlySpan PositionZ => Lane(_v.PositionZ, Count);
+ /// Unit quaternion, x y z w.
+ public ReadOnlySpan RotationX => Lane(_v.RotationX, Count);
+ public ReadOnlySpan RotationY => Lane(_v.RotationY, Count);
+ public ReadOnlySpan RotationZ => Lane(_v.RotationZ, Count);
+ public ReadOnlySpan RotationW => Lane(_v.RotationW, Count);
+ public ReadOnlySpan VelocityX => Lane(_v.VelocityX, Count);
+ public ReadOnlySpan VelocityY => Lane(_v.VelocityY, Count);
+ public ReadOnlySpan VelocityZ => Lane(_v.VelocityZ, Count);
+ public ReadOnlySpan AngularVelocityX => Lane(_v.AngularVelocityX, Count);
+ public ReadOnlySpan AngularVelocityY => Lane(_v.AngularVelocityY, Count);
+ public ReadOnlySpan AngularVelocityZ => Lane(_v.AngularVelocityZ, Count);
+
+ // Write lanes: the caller's per-body world force (N, at the centre of mass) and torque (N m), written
+ // in place before a step. Step applies them to the dynamic bodies and clears them, so a lane holds one
+ // step's intent. A non-finite value makes Step throw before any body is touched.
+ public Span ForceX => Write(_v.ForceX, Count);
+ public Span ForceY => Write(_v.ForceY, Count);
+ public Span ForceZ => Write(_v.ForceZ, Count);
+ public Span TorqueX => Write(_v.TorqueX, Count);
+ public Span TorqueY => Write(_v.TorqueY, Count);
+ public Span TorqueZ => Write(_v.TorqueZ, Count);
+
+ // Contact lanes, read-only, refreshed by every Step.
+ /// N s: the normal impulse the body's touching contact points delivered over the whole step, exact (the sum of Box3D's stepNormalImpulse). Normal channel only. A resting load is this over dt. 0 for a body touching nothing.
+ public ReadOnlySpan ContactImpulse => Lane(_v.ContactImpulse, Count);
+ /// Number of touching contacts.
+ public ReadOnlySpan ContactCount => Lane(_v.ContactCount, Count);
+ /// The material id the body was added with (0 by default).
+ public ReadOnlySpan MaterialId => Lane(_v.MaterialId, Count);
+ /// kg, from Box3D at create (density and shape); 0 for static, kinematic, anchor and removed lanes.
+ public ReadOnlySpan Mass => Lane(_v.Mass, Count);
+ /// Per body lane, the number of times it has been removed. A body's handle is its lane and the generation read when it was added;
+ /// refuses a handle from an earlier occupant of the lane. is the high-water mark of lanes
+ /// ever used: a lane with kind is free (reused once a step has completed).
+ public ReadOnlySpan BodyGeneration => Lane(_v.BodyGeneration, Count);
+
+ /// Per joint slot, the number of times it has been destroyed. A joint's handle is its lane and the generation read
+ /// when it was added; refuses a handle from an earlier occupant of the slot.
+ public ReadOnlySpan JointGeneration => Lane(_v.JointGeneration, JointCount);
+
+ /// Joints at the moment this view was taken: take it after the last AddJoint.
+ public int JointCount => _v.JointCount;
+ public ReadOnlySpan JointKind => Lane(_v.JointKind, JointCount);
+ /// Lane indices of the joint's two bodies; the second is the child.
+ public ReadOnlySpan JointBodyA => Lane(_v.JointBodyA, JointCount);
+ public ReadOnlySpan JointBodyB => Lane(_v.JointBodyB, JointCount);
+ /// Box3D's own angle: revolute angle or spherical twist angle (radians), zero for a weld.
+ public ReadOnlySpan JointAngle => Lane(_v.JointAngle, JointCount);
+ /// World orientation of the joint frame on body A (quaternion x y z w).
+ public ReadOnlySpan JointFrameX => Lane(_v.JointFrameX, JointCount);
+ public ReadOnlySpan JointFrameY => Lane(_v.JointFrameY, JointCount);
+ public ReadOnlySpan JointFrameZ => Lane(_v.JointFrameZ, JointCount);
+ public ReadOnlySpan JointFrameW => Lane(_v.JointFrameW, JointCount);
+ /// Joint frame B relative to frame A (quaternion x y z w, w >= 0); identity at the creation pose.
+ public ReadOnlySpan JointRotationX => Lane(_v.JointRotationX, JointCount);
+ public ReadOnlySpan JointRotationY => Lane(_v.JointRotationY, JointCount);
+ public ReadOnlySpan JointRotationZ => Lane(_v.JointRotationZ, JointCount);
+ public ReadOnlySpan JointRotationW => Lane(_v.JointRotationW, JointCount);
+ /// Body B's angular velocity minus body A's, expressed in frame A (rad/s).
+ public ReadOnlySpan JointAngularVelocityX => Lane(_v.JointAngularVelocityX, JointCount);
+ public ReadOnlySpan JointAngularVelocityY => Lane(_v.JointAngularVelocityY, JointCount);
+ public ReadOnlySpan JointAngularVelocityZ => Lane(_v.JointAngularVelocityZ, JointCount);
+ /// World position of the joint frame origin on body A (the joint anchor); at creation it is the anchor add_joint was given.
+ public ReadOnlySpan JointOriginX => Lane(_v.JointOriginX, JointCount);
+ public ReadOnlySpan JointOriginY => Lane(_v.JointOriginY, JointCount);
+ /// The load the joint carries, world frame, from Box3D's constraint solution at the end of the last step (N); a removed lane reads 0. A joint hanging a mass m at rest reads m g. A sensor: Ymir never removes a joint on it.
+ public ReadOnlySpan JointConstraintForceX => Lane(_v.JointConstraintForceX, JointCount);
+ public ReadOnlySpan JointConstraintForceY => Lane(_v.JointConstraintForceY, JointCount);
+ public ReadOnlySpan JointConstraintForceZ => Lane(_v.JointConstraintForceZ, JointCount);
+ /// The torque (N m) the joint carries, as the force lanes.
+ public ReadOnlySpan JointConstraintTorqueX => Lane(_v.JointConstraintTorqueX, JointCount);
+ public ReadOnlySpan JointConstraintTorqueY => Lane(_v.JointConstraintTorqueY, JointCount);
+ public ReadOnlySpan JointConstraintTorqueZ => Lane(_v.JointConstraintTorqueZ, JointCount);
+ public ReadOnlySpan JointOriginZ => Lane(_v.JointOriginZ, JointCount);
+
+ // Particle lanes: read-only, changed only by Step and by the particle and constraint commands. Lanes are indexed up to
+ // the set's count (a high-water mark). A dead lane reads live 0 and every other lane 0 except generation and removed_at;
+ // it is reused once a step has passed since its removal.
+ public int ParticleCount => _v.ParticleCount;
+ public int ParticleCapacity => _v.ParticleCapacity;
+ /// Kernel neighbours past a fluid particle's list of 96 in the last step, summed over substeps; 0 means the density correction and XSPH saw every pair.
+ public int FluidNeighbourOverflow => _v.FluidNeighbourOverflow;
+ public ReadOnlySpan ParticleX => Lane(_v.ParticleX, ParticleCount);
+ public ReadOnlySpan ParticleY => Lane(_v.ParticleY, ParticleCount);
+ public ReadOnlySpan ParticleZ => Lane(_v.ParticleZ, ParticleCount);
+ public ReadOnlySpan ParticleVx => Lane(_v.ParticleVx, ParticleCount);
+ public ReadOnlySpan ParticleVy => Lane(_v.ParticleVy, ParticleCount);
+ public ReadOnlySpan ParticleVz => Lane(_v.ParticleVz, ParticleCount);
+ public ReadOnlySpan ParticleRadius => Lane(_v.ParticleRadius, ParticleCount);
+ public ReadOnlySpan ParticleInvMass => Lane(_v.ParticleInvMass, ParticleCount);
+ public ReadOnlySpan ParticleRestX => Lane(_v.ParticleRestX, ParticleCount);
+ public ReadOnlySpan ParticleRestY => Lane(_v.ParticleRestY, ParticleCount);
+ public ReadOnlySpan ParticleRestZ => Lane(_v.ParticleRestZ, ParticleCount);
+ public ReadOnlySpan ParticlePhase => Lane(_v.ParticlePhase, ParticleCount);
+ public ReadOnlySpan ParticleMaterial => Lane(_v.ParticleMaterial, ParticleCount);
+ public ReadOnlySpan ParticleLive => Lane(_v.ParticleLive, ParticleCount);
+ public ReadOnlySpan ParticleGeneration => Lane(_v.ParticleGeneration, ParticleCount);
+ public ReadOnlySpan ParticleRemovedAt => Lane(_v.ParticleRemovedAt, ParticleCount);
+ /// Derived: the lowest lane of the particle's component of distance-connected particles.
+ public ReadOnlySpan ParticleComponent => Lane(_v.ParticleComponent, ParticleCount);
+ /// A fluid particle's number density over its rest density in the last substep it ran (1 is at rest), 0 for a solid: a sensor.
+ public ReadOnlySpan ParticleDensity => Lane(_v.ParticleDensity, ParticleCount);
+
+ public int DistanceCount => _v.DistanceCount;
+ public ReadOnlySpan DistanceA => Lane(_v.DistanceA, DistanceCount);
+ public ReadOnlySpan DistanceB => Lane(_v.DistanceB, DistanceCount);
+ public ReadOnlySpan DistanceRest => Lane(_v.DistanceRest, DistanceCount);
+ public ReadOnlySpan DistanceCompliance => Lane(_v.DistanceCompliance, DistanceCount);
+ /// N: the load the constraint carries (its own correction, the bends over it and the tether impulses routed through it), mean over the substeps. A sensor: Ymir never removes a constraint on it.
+ public ReadOnlySpan DistanceTension => Lane(_v.DistanceTension, DistanceCount);
+ public ReadOnlySpan DistanceLive => Lane(_v.DistanceLive, DistanceCount);
+ public ReadOnlySpan DistanceGeneration => Lane(_v.DistanceGeneration, DistanceCount);
+ public ReadOnlySpan DistanceRemovedAt => Lane(_v.DistanceRemovedAt, DistanceCount);
+
+ public int BendCount => _v.BendCount;
+ public ReadOnlySpan BendE1 => Lane(_v.BendE1, BendCount);
+ public ReadOnlySpan BendE2 => Lane(_v.BendE2, BendCount);
+ public ReadOnlySpan BendA => Lane(_v.BendA, BendCount);
+ public ReadOnlySpan BendB => Lane(_v.BendB, BendCount);
+ public ReadOnlySpan BendC => Lane(_v.BendC, BendCount);
+ /// Offsets of the shared particle from the centroid of the three, in metres: at rest and at the hard limit (negative: no limit).
+ public ReadOnlySpan BendRest => Lane(_v.BendRest, BendCount);
+ public ReadOnlySpan BendLimit => Lane(_v.BendLimit, BendCount);
+ public ReadOnlySpan BendCompliance => Lane(_v.BendCompliance, BendCount);
+ public ReadOnlySpan BendLive => Lane(_v.BendLive, BendCount);
+ public ReadOnlySpan BendGeneration => Lane(_v.BendGeneration, BendCount);
+ public ReadOnlySpan BendRemovedAt => Lane(_v.BendRemovedAt, BendCount);
+
+ public int AttachmentCount => _v.AttachmentCount;
+ public ReadOnlySpan AttachmentKind => Lane(_v.AttachmentKind, AttachmentCount);
+ public ReadOnlySpan AttachmentFlags => Lane(_v.AttachmentFlags, AttachmentCount);
+ public ReadOnlySpan AttachmentGeneration => Lane(_v.AttachmentGeneration, AttachmentCount);
+ public ReadOnlySpan AttachmentParticle => Lane(_v.AttachmentParticle, AttachmentCount);
+ /// The body lane () or -1.
+ public ReadOnlySpan AttachmentBody => Lane(_v.AttachmentBody, AttachmentCount);
+ public ReadOnlySpan AttachmentPointX => Lane(_v.AttachmentPointX, AttachmentCount);
+ public ReadOnlySpan AttachmentPointY => Lane(_v.AttachmentPointY, AttachmentCount);
+ public ReadOnlySpan AttachmentPointZ => Lane(_v.AttachmentPointZ, AttachmentCount);
+ public ReadOnlySpan AttachmentCompliance => Lane(_v.AttachmentCompliance, AttachmentCount);
+ /// N: what the attachment exerts on its particles, mean over the substeps, tether load included. A sensor.
+ public ReadOnlySpan AttachmentForceX => Lane(_v.AttachmentForceX, AttachmentCount);
+ public ReadOnlySpan AttachmentForceY => Lane(_v.AttachmentForceY, AttachmentCount);
+ public ReadOnlySpan AttachmentForceZ => Lane(_v.AttachmentForceZ, AttachmentCount);
+ public ReadOnlySpan AttachmentRemovedAt => Lane(_v.AttachmentRemovedAt, AttachmentCount);
+
+ /// Derived tethers, up to : written only by the topology commands, parents before children per attachment.
+ public int TetherCount => _v.TetherCount;
+ public int TetherCapacity => _v.TetherCapacity;
+ public ReadOnlySpan TetherAttachment => Lane(_v.TetherAtt, TetherCount);
+ public ReadOnlySpan TetherParticle => Lane(_v.TetherParticle, TetherCount);
+ public ReadOnlySpan TetherParent => Lane(_v.TetherParent, TetherCount);
+ public ReadOnlySpan TetherEdge => Lane(_v.TetherEdge, TetherCount);
+ /// The second attachment of a pair tether (a bound between two attachment points, edge -1), or -1.
+ public ReadOnlySpan TetherOther => Lane(_v.TetherOther, TetherCount);
+ public ReadOnlySpan TetherBound => Lane(_v.TetherBound, TetherCount);
+
+ public int MaterialCapacity => _v.MaterialCapacity;
+ public ReadOnlySpan MaterialFriction => Lane(_v.MaterialFriction, MaterialCapacity);
+ public ReadOnlySpan MaterialTableId => Lane(_v.MaterialTableId, MaterialCapacity);
+ /// The XSPH coefficient of each material (a fluid pair relaxes its velocities by the mean of the two).
+ public ReadOnlySpan MaterialViscosity => Lane(_v.MaterialViscosity, MaterialCapacity);
+ /// A fluid particle's support in the last substep it ran: the highest body lane it touched, else -1; -1 for a solid or free lane. Contact, not rest: the caller judges speed. Notification only.
+ public ReadOnlySpan SupportBody => Lane(_v.SupportBody, ParticleCount);
+ /// A fluid particle's support in the last substep it ran: the first solid particle lane its row listed touching it, else -1 (resting on fluid alone reads -1); -1 for a solid or free lane.
+ public ReadOnlySpan SupportParticle => Lane(_v.SupportParticle, ParticleCount);
+
+ /// Wet patch lanes (settled liquid, see ), indexed up to . A free lane reads live 0, -1 on both supports and 0 elsewhere.
+ public int WetCount => _v.WetCount;
+ /// The body lane a patch lies on, else -1; its point is in the body's frame.
+ public ReadOnlySpan WetBody => Lane(_v.WetBody, WetCount);
+ /// The solid particle lane a patch lies on, else -1 (its point is then 0).
+ public ReadOnlySpan WetParticle => Lane(_v.WetParticle, WetCount);
+ public ReadOnlySpan WetX => Lane(_v.WetX, WetCount);
+ public ReadOnlySpan WetY => Lane(_v.WetY, WetCount);
+ public ReadOnlySpan WetZ => Lane(_v.WetZ, WetCount);
+ /// m: sqrt(volume / (pi film)), film 1 mm.
+ public ReadOnlySpan WetRadius => Lane(_v.WetRadius, WetCount);
+ /// m^3 of liquid in each patch.
+ public ReadOnlySpan WetPatchVolume => Lane(_v.WetPatchVolume, WetCount);
+ public ReadOnlySpan WetMaterial => Lane(_v.WetMaterial, WetCount);
+ public ReadOnlySpan WetLive => Lane(_v.WetLive, WetCount);
+ public ReadOnlySpan WetGeneration => Lane(_v.WetGeneration, WetCount);
+ public ReadOnlySpan WetRemovedAt => Lane(_v.WetRemovedAt, WetCount);
+ /// m^3 of settled liquid on each body: the sum of its live patches, derived when a command changes them; the step never writes it.
+ public ReadOnlySpan WetVolume => Lane(_v.BodyWetVolume, Count);
+ /// The wet friction of each material (stored for the friction cut; nothing here reads it).
+ public ReadOnlySpan MaterialWetFriction => Lane(_v.MaterialWetFriction, MaterialCapacity);
+
+ /// Liquid sensor lanes (see ), indexed up to . A free lane reads live 0, body -1 and 0 elsewhere (generation and removed-at kept).
+ public int SensorCount => _v.SensorCount;
+ /// The body lane a sensor is fixed in; its point is in that body's frame.
+ public ReadOnlySpan SensorBody => Lane(_v.SensorBody, SensorCount);
+ public ReadOnlySpan SensorX => Lane(_v.SensorX, SensorCount);
+ public ReadOnlySpan SensorY => Lane(_v.SensorY, SensorCount);
+ public ReadOnlySpan SensorZ => Lane(_v.SensorZ, SensorCount);
+ /// m
+ public ReadOnlySpan SensorRadius => Lane(_v.SensorRadius, SensorCount);
+ /// m^3 of liquid inside each sensor at the end of the last step: the sum of (2 r)^3 over the live fluid particles whose centre was inside, 0 with none. A sensor: the step writes it and nothing reads it back.
+ public ReadOnlySpan SensorLiquidVolume => Lane(_v.SensorLiquidVolume, SensorCount);
+ /// m^3 of settled liquid at the end of the last step: the sum of the volumes of the live wet patches whose centre was inside each sensor, on any body or solid particle. A Settle, destroy or remove between steps shows at the next step.
+ public ReadOnlySpan SensorWetVolume => Lane(_v.SensorWetVolume, SensorCount);
+ public ReadOnlySpan SensorLive => Lane(_v.SensorLive, SensorCount);
+ public ReadOnlySpan SensorGeneration => Lane(_v.SensorGeneration, SensorCount);
+ public ReadOnlySpan SensorRemovedAt => Lane(_v.SensorRemovedAt, SensorCount);
+ /// 1 for a pinned (dormant) particle, else 0; notification only. A pinned particle's position and velocity lanes are stale: draw it from the attachment names, see .
+ public ReadOnlySpan ParticlePinned => Lane(_v.ParticlePinned, ParticleCount);
+ /// The attachment lane each pinned particle is drawn from: its lowest live non-tether attachment when it was pinned, held while it sleeps, so no attachment added later moves it; -1 for none. Derived, read only.
+ public ReadOnlySpan ParticleAnchor => Lane(_v.ParticleAnchor, ParticleCount);
+
+ /// N s, world: the impulse the particle phase delivered to each body over the last step (0 for a body it did not touch). Box3D has already applied it; this is notification only.
+ public ReadOnlySpan ParticleImpulseX => Lane(_v.ParticleImpulseX, Count);
+ public ReadOnlySpan ParticleImpulseY => Lane(_v.ParticleImpulseY, Count);
+ public ReadOnlySpan ParticleImpulseZ => Lane(_v.ParticleImpulseZ, Count);
+
+ /// Address of a lane, for tests and interop that need to prove nothing was copied.
+ public nint PositionYAddress => (nint)_v.PositionY;
+}
+
+///
+/// A headless 3D Box3D world: N bodies stepped deterministically (one worker, fixed order) with a
+/// structure-of-arrays state view read in place. Ymir writes no solver; Box3D decides everything.
+/// Not thread-safe: Dispose must not race Step or a lane read. Dispose frees the native world; an
+/// undisposed world leaks it (no finalizer by design in this cut).
+///
+public sealed class Box3DSoaWorld : IDisposable
+{
+ private const uint ExpectedAbi = 21;
+ private static int s_abiVerified;
+ private nint _handle;
+
+ /// The gravity (m/s^2) this world was created with; native has no setter, so this copy cannot disagree.
+ public (float X, float Y, float Z) Gravity { get; }
+
+ ///
+ /// bounds each kind of per-step contact fact (default 4 x capacity; 0 or less is refused);
+ /// is the approach speed in m/s above which a touch is a hit (Box3D's default, 1).
+ ///
+ public unsafe Box3DSoaWorld(
+ int capacity, float gravityX = 0f, float gravityY = -10f, float gravityZ = 0f, int jointCapacity = 0,
+ int? factCapacity = null, float hitThreshold = 1f, Box3DSoaParticleCapacities? particles = null)
+ {
+ EnsureNativeAbi();
+
+ var caps = particles.GetValueOrDefault();
+ Check(Box3DSoaNative.ymir_box3d_soa_create(capacity, jointCapacity, gravityX, gravityY, gravityZ, factCapacity ?? checked(capacity * 4), hitThreshold, particles.HasValue ? &caps : null, out _handle));
+ Gravity = (gravityX, gravityY, gravityZ);
+ }
+
+ private static void EnsureNativeAbi()
+ {
+ if (Volatile.Read(ref s_abiVerified) != 0)
+ {
+ return;
+ }
+ RequireNativeAbi(Box3DSoaNative.ymir_box3d_soa_get_abi_version());
+ static uint Size(uint which) => Box3DSoaNative.ymir_box3d_soa_get_particle_desc_size(which);
+ if (Box3DSoaNative.ymir_box3d_soa_get_view_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Box3DSoaNative.ymir_box3d_soa_get_body_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Box3DSoaNative.ymir_box3d_soa_get_joint_desc_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Box3DSoaNative.ymir_box3d_soa_get_facts_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Box3DSoaNative.ymir_box3d_soa_get_touch_fact_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Box3DSoaNative.ymir_box3d_soa_get_hit_fact_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Box3DSoaNative.ymir_box3d_soa_get_ray_hit_size() != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(0) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(1) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(2) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(3) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(4) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(5) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(6) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf() ||
+ Size(7) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf())
+ {
+ throw new InvalidOperationException("The native Ymir Box3D SoA ABI does not match this build.");
+ }
+ Volatile.Write(ref s_abiVerified, 1);
+ }
+
+ /// Fails closed when the native library is not the ABI this build expects, in either direction.
+ internal static void RequireNativeAbi(uint nativeAbi)
+ {
+ if (nativeAbi != ExpectedAbi)
+ {
+ throw new InvalidOperationException($"The native Ymir Box3D SoA ABI is {nativeAbi}; this build expects {ExpectedAbi}.");
+ }
+ }
+
+ /// The live lanes. Count and step count are read from native memory each call.
+ public Box3DSoaView View
+ {
+ get
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ Check(Box3DSoaNative.ymir_box3d_soa_get_view(_handle, out var v));
+ return new Box3DSoaView(v, this);
+ }
+ }
+
+ /// The contact facts of the last Step: empty before the first Step and rewritten by the next.
+ public Box3DSoaFacts Facts
+ {
+ get
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ Check(Box3DSoaNative.ymir_box3d_soa_get_facts(_handle, out var f));
+ return new Box3DSoaFacts(f, this);
+ }
+ }
+
+ /// Steps taken so far.
+ public ulong StepCount
+ {
+ get
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ Check(Box3DSoaNative.ymir_box3d_soa_get_view(_handle, out var v));
+ return v.StepCount;
+ }
+ }
+
+ /// Adds a dynamic sphere; returns its lane index.
+ public Box3DSoaBodyHandle AddSphere(
+ ulong stableId, (float X, float Y, float Z) position, float radius, float density,
+ (float X, float Y, float Z) velocity = default, float friction = 0.6f, float restitution = 0f,
+ int parent = -1, int limb = 0, float rollingResistance = 0f, ulong materialId = 0) =>
+ AddBody(Describe(Box3DSoaKind.Sphere, stableId, position, default, (radius, 0f, 0f), density,
+ velocity, friction, restitution, parent, limb, rollingResistance, materialId));
+
+ /// Adds a static axis-aligned box centred at .
+ public Box3DSoaBodyHandle AddStaticBox(
+ ulong stableId, (float X, float Y, float Z) position, (float X, float Y, float Z) halfExtents,
+ float friction = 0.6f, float restitution = 0f, ulong materialId = 0) =>
+ AddBody(Describe(Box3DSoaKind.StaticBox, stableId, position, default, halfExtents, 0f,
+ default, friction, restitution, -1, 0, 0f, materialId));
+
+ ///
+ /// Adds a static heightfield body at with columns along X
+ /// and rows along Z (heights[z * countX + x]), scaled by
+ /// with CCW top-facing triangles. The native world owns the compiled heightfield until removed or disposed.
+ ///
+ public unsafe Box3DSoaBodyHandle AddStaticHeightField(
+ ulong stableId, (float X, float Y, float Z) origin, ReadOnlySpan heights, int countX, int countZ,
+ (float X, float Y, float Z) scale, float minHeight, float maxHeight,
+ float friction = 0.6f, float restitution = 0f, ulong materialId = 0)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (countX >= 2 && countZ >= 2 && (long)heights.Length != (long)countX * countZ)
+ throw new ArgumentException("Heights length must equal countX * countZ.", nameof(heights));
+ fixed (float* h = heights)
+ {
+ Check(Box3DSoaNative.ymir_box3d_soa_add_static_heightfield(
+ _handle, stableId, origin.X, origin.Y, origin.Z,
+ countX >= 2 && countZ >= 2 ? h : null, countX, countZ,
+ scale.X, scale.Y, scale.Z, minHeight, maxHeight, friction, restitution, materialId, out var index));
+ return BodyHandleOf(index);
+ }
+ }
+
+ ///
+ /// Adds a static triangle mesh body at with CCW outward-facing triangles.
+ /// The native world owns the compiled mesh BVH until removed or disposed.
+ ///
+ public unsafe Box3DSoaBodyHandle AddStaticMesh(
+ ulong stableId, (float X, float Y, float Z) origin, ReadOnlySpan vertices,
+ ReadOnlySpan triangleIndices, float friction = 0.6f, float restitution = 0f, ulong materialId = 0)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (Unsafe.SizeOf() != sizeof(float) * 3)
+ throw new InvalidOperationException("Unexpected Vector3 layout.");
+ if (triangleIndices.Length % 3 != 0)
+ throw new ArgumentException("Triangle indices length must be a multiple of 3.", nameof(triangleIndices));
+ fixed (Vector3* v = vertices)
+ fixed (int* idx = triangleIndices)
+ {
+ Check(Box3DSoaNative.ymir_box3d_soa_add_static_mesh(
+ _handle, stableId, origin.X, origin.Y, origin.Z,
+ (float*)v, vertices.Length, idx, triangleIndices.Length / 3,
+ friction, restitution, materialId, out var index));
+ return BodyHandleOf(index);
+ }
+ }
+
+ ///
+ /// Adds a dynamic capsule: a segment of either side of the centre along
+ /// the body's local Y, swept by . is a unit quaternion
+ /// x y z w; the default (all zero) means identity.
+ ///
+ public Box3DSoaBodyHandle AddCapsule(
+ ulong stableId, (float X, float Y, float Z) position, float radius, float halfLength, float density,
+ (float X, float Y, float Z, float W) rotation = default, float friction = 0.6f, float restitution = 0f,
+ int parent = -1, int limb = 0, float rollingResistance = 0f, ulong materialId = 0) =>
+ AddBody(Describe(Box3DSoaKind.Capsule, stableId, position, rotation, (radius, halfLength, 0f), density,
+ default, friction, restitution, parent, limb, rollingResistance, materialId));
+
+ /// Adds a dynamic box with the given half extents; rotation as for .
+ public Box3DSoaBodyHandle AddBox(
+ ulong stableId, (float X, float Y, float Z) position, (float X, float Y, float Z) halfExtents, float density,
+ (float X, float Y, float Z, float W) rotation = default, float friction = 0.6f, float restitution = 0f,
+ int parent = -1, int limb = 0, ulong materialId = 0) =>
+ AddBody(Describe(Box3DSoaKind.Box, stableId, position, rotation, halfExtents, density,
+ default, friction, restitution, parent, limb, 0f, materialId));
+
+ ///
+ /// Joins two bodies at a world-space . The joint frame's z axis is
+ /// (the hinge axis of a revolute joint); the pose at creation is the joint's zero.
+ /// Limits are radians: the revolute angle, or the spherical twist with as swing.
+ /// A weld takes no limits. Returns the joint's handle (lane and generation). Body B is the child.
+ ///
+ public Box3DSoaJointHandle AddJoint(
+ Box3DSoaJointKind kind, int bodyA, int bodyB, (float X, float Y, float Z) anchor,
+ (float X, float Y, float Z) axis, bool limit = false, float lower = 0f, float upper = 0f, float coneAngle = 0f,
+ float forceThreshold = float.PositiveInfinity, float torqueThreshold = float.PositiveInfinity)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ var desc = new Box3DSoaJointDesc
+ {
+ Kind = (uint)kind, BodyA = bodyA, BodyB = bodyB, EnableLimit = limit ? 1u : 0u,
+ AnchorX = anchor.X, AnchorY = anchor.Y, AnchorZ = anchor.Z,
+ AxisX = axis.X, AxisY = axis.Y, AxisZ = axis.Z, Lower = lower, Upper = upper, ConeAngle = coneAngle,
+ ForceThreshold = forceThreshold, TorqueThreshold = torqueThreshold,
+ };
+ Check(Box3DSoaNative.ymir_box3d_soa_add_joint(_handle, desc, out var index));
+ return HandleOf(index);
+ }
+
+ ///
+ /// A motor joint: position springs that pull body B's frame onto body A's. The frame sits at the world-space
+ /// at creation (axes aligned with the world), so the spring pulls B's anchor point onto A's.
+ /// Hertz 0 turns that spring off; MaxForce (N) and MaxTorque (N m) bound it. All are finite and
+ /// not negative. Pair an anchor (body A) with the body to grab (body B). Returns the joint's handle (lane and generation).
+ /// Create the anchor only when a joint will follow (check ): the joint validates its spring
+ /// fields, so a grab that fails there leaves the anchor behind. One long-lived anchor per cursor is the intended use.
+ ///
+ public Box3DSoaJointHandle AddMotorJoint(
+ int bodyA, int bodyB, (float X, float Y, float Z) anchor,
+ (float Hertz, float Damping, float MaxForce) linear, (float Hertz, float Damping, float MaxTorque) angular,
+ float forceThreshold = float.PositiveInfinity, float torqueThreshold = float.PositiveInfinity)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ var desc = new Box3DSoaJointDesc
+ {
+ Kind = (uint)Box3DSoaJointKind.Motor, BodyA = bodyA, BodyB = bodyB,
+ AnchorX = anchor.X, AnchorY = anchor.Y, AnchorZ = anchor.Z, AxisZ = 1f,
+ LinearHertz = linear.Hertz, LinearDamping = linear.Damping, MaxForce = linear.MaxForce,
+ AngularHertz = angular.Hertz, AngularDamping = angular.Damping, MaxTorque = angular.MaxTorque,
+ ForceThreshold = forceThreshold, TorqueThreshold = torqueThreshold,
+ };
+ Check(Box3DSoaNative.ymir_box3d_soa_add_joint(_handle, desc, out var index));
+ return HandleOf(index);
+ }
+
+ ///
+ /// Releases a joint of any kind (a grab, a cut, a tear); the bodies stay. The joint's lane becomes a tombstone:
+ /// kind , bodies -1, every other lane 0. It is reused by a later AddJoint only
+ /// once a has completed, so lanes read this step stay valid. Throws for a lane that is not a live joint
+ /// or a handle whose generation is not the slot's: a release made with a stale handle never destroys a later joint in a reused slot.
+ /// The lanes keep no last state; read what you need before removing.
+ ///
+ public void DestroyJoint(Box3DSoaJointHandle joint)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ Check(Box3DSoaNative.ymir_box3d_soa_destroy_joint(_handle, joint.Lane, joint.Generation));
+ }
+
+ ///
+ /// Sets a live joint's thresholds: in a step where its force (N) or torque (N m) reaches one, the joint appears in
+ /// ; +inf is never. The joint is never removed on a threshold. Throws for NaN or a
+ /// negative value, a lane that is not a live joint, or a stale handle; a refusal changes nothing.
+ ///
+ public void SetJointThresholds(Box3DSoaJointHandle joint, float forceThreshold, float torqueThreshold)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ Check(Box3DSoaNative.ymir_box3d_soa_set_joint_thresholds(_handle, joint.Lane, joint.Generation, forceThreshold, torqueThreshold));
+ }
+
+ private unsafe Box3DSoaJointHandle HandleOf(int lane)
+ {
+ Check(Box3DSoaNative.ymir_box3d_soa_get_view(_handle, out var v));
+ return new Box3DSoaJointHandle(lane, v.JointGeneration[lane]);
+ }
+
+ /// Joints AddJoint could create right now: unused capacity plus tombstones whose step has completed.
+ /// Check it before adding an anchor for a grab, so a full world leaves no orphan anchor.
+ public int FreeJointSlots
+ {
+ get
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ return Box3DSoaNative.ymir_box3d_soa_free_joint_slots(_handle);
+ }
+ }
+
+ /// Bodies AddSphere and its siblings could create right now: unused capacity plus lanes removed in an earlier step.
+ public int FreeBodySlots
+ {
+ get
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ return Box3DSoaNative.ymir_box3d_soa_free_body_slots(_handle);
+ }
+ }
+
+ ///
+ /// Removes a body: its wet patches go, every joint naming it is retired (their handles go stale), and its lane becomes a tombstone
+ /// (kind , every other lane 0, generation + 1) that a later Add* reuses once a has completed.
+ /// A touch it was in ends by name in the next step's facts. Throws, changing nothing, for a lane that is not a live body, a stale handle, or
+ /// while a live attachment or liquid sensor names the body (remove those first). Removing an anchor ends its grabs the same way.
+ ///
+ public void RemoveBody(Box3DSoaBodyHandle body)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ Check(Box3DSoaNative.ymir_box3d_soa_remove_body(_handle, body.Lane, body.Generation));
+ }
+
+ /// Adds a kinematic anchor with no shape (rotation as for ); returns its lane index.
+ public Box3DSoaBodyHandle AddAnchor(ulong stableId, (float X, float Y, float Z) position, (float X, float Y, float Z, float W) rotation = default) =>
+ AddBody(Describe(Box3DSoaKind.Anchor, stableId, position, rotation, default, 0f, default, 0f, 0f, -1, 0));
+
+ ///
+ /// Sets an anchor's pose for the coming step. Box3D gives the anchor the velocity that reaches it after
+ /// , so pass the same dt as the next and the anchor arrives at its end,
+ /// where Step stops it: with no new target it holds still (its velocity lanes read 0).
+ /// Throws for a lane that is not an anchor, a non-finite or non-unit input, or a non-positive time step.
+ ///
+ public unsafe void SetAnchorTarget(
+ int lane, (float X, float Y, float Z) position, (float X, float Y, float Z, float W) rotation, float timeStep)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (rotation == default) rotation = (0f, 0f, 0f, 1f);
+ var p = stackalloc float[] { position.X, position.Y, position.Z };
+ var q = stackalloc float[] { rotation.X, rotation.Y, rotation.Z, rotation.W };
+ Check(Box3DSoaNative.ymir_box3d_soa_set_anchor_target(_handle, lane, p, q, timeStep));
+ }
+
+ ///
+ /// A one-shot world impulse (N s) at a world : it adds impulse / mass to the linear
+ /// velocity and turns the body by (point - centre of mass) x impulse. Dynamic bodies only; throws otherwise
+ /// or for non-finite input.
+ ///
+ public unsafe void ApplyImpulse(int lane, (float X, float Y, float Z) impulse, (float X, float Y, float Z) point)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ var j = stackalloc float[] { impulse.X, impulse.Y, impulse.Z };
+ var p = stackalloc float[] { point.X, point.Y, point.Z };
+ Check(Box3DSoaNative.ymir_box3d_soa_apply_impulse(_handle, lane, j, p));
+ }
+
+ ///
+ /// The closest shape along + t * , t in [0, 1], with Box3D's
+ /// default filter; anchors have no shape and are never hit. Throws for non-finite input or a zero translation.
+ ///
+ public unsafe Box3DSoaRayHit CastRayClosest((float X, float Y, float Z) origin, (float X, float Y, float Z) translation)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ var o = stackalloc float[] { origin.X, origin.Y, origin.Z };
+ var t = stackalloc float[] { translation.X, translation.Y, translation.Z };
+ Check(Box3DSoaNative.ymir_box3d_soa_cast_ray_closest(_handle, o, t, out var h));
+ return new Box3DSoaRayHit(h.Hit != 0, h.Lane, h.StableId, (h.PointX, h.PointY, h.PointZ), (h.NormalX, h.NormalY, h.NormalZ), h.Fraction);
+ }
+
+ ///
+ /// Creates particles in the lowest free lanes and writes their handles to (empty to discard them).
+ /// Throws for a full world, a bad phase or material index or non-finite input; nothing changes when it throws.
+ ///
+ public unsafe void CreateParticles(ReadOnlySpan particles, Span handles = default)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (!handles.IsEmpty && handles.Length < particles.Length) throw new ArgumentException("One handle per particle.", nameof(handles));
+ fixed (Box3DSoaParticleDesc* d = particles)
+ fixed (Box3DSoaParticleHandle* h = handles)
+ Check(Box3DSoaNative.ymir_box3d_soa_create_particles(_handle, particles.Length, d, handles.IsEmpty ? null : h));
+ }
+
+ ///
+ /// Destroys particles and, with them, every constraint that touches them. Their lanes are tombstones (live 0) reusable once a
+ /// has completed. A stale handle is refused.
+ ///
+ public unsafe void DestroyParticles(ReadOnlySpan particles)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ fixed (Box3DSoaParticleHandle* h = particles)
+ Check(Box3DSoaNative.ymir_box3d_soa_destroy_particles(_handle, particles.Length, h));
+ }
+
+ /// Creates distance constraints; may be empty. Throws, changing nothing, when the derived tethers would not fit the tether capacity or a distance component would hold both a pinned particle and a tether.
+ public unsafe void CreateDistances(ReadOnlySpan distances, Span handles = default)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (!handles.IsEmpty && handles.Length < distances.Length) throw new ArgumentException("One handle per distance.", nameof(handles));
+ Box3DSoaParticleHandle[]? rented = null;
+ Span native = distances.Length <= 256 ? stackalloc Box3DSoaParticleHandle[distances.Length] : (rented = ArrayPool.Shared.Rent(distances.Length)).AsSpan(0, distances.Length);
+ try
+ {
+ fixed (Box3DSoaDistanceDesc* d = distances)
+ fixed (Box3DSoaParticleHandle* h = native)
+ Check(Box3DSoaNative.ymir_box3d_soa_create_distances(_handle, distances.Length, d, h));
+ for (var i = 0; i < handles.Length && i < native.Length; i++)
+ handles[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Distance, native[i].Lane, native[i].Generation);
+ }
+ finally
+ {
+ if (rented is not null) ArrayPool.Shared.Return(rented);
+ }
+ }
+
+ /// Creates bends over pairs of distances that share one particle; a bend dies with either of its distances.
+ public unsafe void CreateBends(ReadOnlySpan bends, Span handles = default)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (!handles.IsEmpty && handles.Length < bends.Length) throw new ArgumentException("One handle per bend.", nameof(handles));
+ Box3DSoaParticleHandle[]? rented = null;
+ Span native = bends.Length <= 256 ? stackalloc Box3DSoaParticleHandle[bends.Length] : (rented = ArrayPool.Shared.Rent(bends.Length)).AsSpan(0, bends.Length);
+ try
+ {
+ fixed (Box3DSoaBendDesc* d = bends)
+ fixed (Box3DSoaParticleHandle* h = native)
+ Check(Box3DSoaNative.ymir_box3d_soa_create_bends(_handle, bends.Length, d, h));
+ for (var i = 0; i < handles.Length && i < native.Length; i++)
+ handles[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Bend, native[i].Lane, native[i].Generation);
+ }
+ finally
+ {
+ if (rented is not null) ArrayPool.Shared.Return(rented);
+ }
+ }
+
+ ///
+ /// Ties each particle of to a body point or a world point, as one command ending in one derivation:
+ /// lanes are taken lowest first in order, and a refusal (a bad desc, a removed body, no free lanes, tethers past capacity, a distance component
+ /// left holding both a pinned particle and a tether) throws with nothing changed. A pinned particle's anchor is held whatever lane an attachment takes. may be empty.
+ ///
+ public unsafe void Attach(ReadOnlySpan attachments, Span handles = default)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (!handles.IsEmpty && handles.Length < attachments.Length) throw new ArgumentException("One handle per attachment.", nameof(handles));
+ Box3DSoaParticleHandle[]? rented = null;
+ Span native = attachments.Length <= 256 ? stackalloc Box3DSoaParticleHandle[attachments.Length] : (rented = ArrayPool.Shared.Rent(attachments.Length)).AsSpan(0, attachments.Length);
+ try
+ {
+ fixed (Box3DSoaAttachmentDesc* d = attachments)
+ fixed (Box3DSoaParticleHandle* h = native)
+ Check(Box3DSoaNative.ymir_box3d_soa_attach(_handle, attachments.Length, d, h));
+ for (var i = 0; i < handles.Length && i < native.Length; i++)
+ handles[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Attachment, native[i].Lane, native[i].Generation);
+ }
+ finally
+ {
+ if (rented is not null) ArrayPool.Shared.Return(rented);
+ }
+ }
+
+ ///
+ /// Ties to a body point (kind Body: is the body lane, in
+ /// its frame) or a world point (Static). With the point also bounds every particle of the component by
+ /// the rest path. With (Body only) the particle is flesh of the body's limb tree: contact skips every body
+ /// that shares the attached body's limb-tree root, not just the attached body. With (Body only) the body
+ /// side weighs nothing: the particle is held to the body's point and the body is never moved or loaded by it.
+ /// is m/N, 0 for rigid. Attach where the particle already is.
+ ///
+ public Box3DSoaConstraintHandle Attach(
+ Box3DSoaAttachKind kind, Box3DSoaParticleHandle particle, int target = -1, (float X, float Y, float Z) point = default,
+ float compliance = 0f, bool tether = false, bool limb = false, bool oneWay = false)
+ {
+ var desc = new Box3DSoaAttachmentDesc(kind, particle, target, point, compliance, tether, limb, oneWay);
+ Span handle = stackalloc Box3DSoaConstraintHandle[1];
+ Attach(new ReadOnlySpan(in desc), handle);
+ return handle[0];
+ }
+
+ /// Removes constraints of one type (a distance takes the bends over it with it). A stale handle is refused.
+ public unsafe void Remove(ReadOnlySpan constraints)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (constraints.IsEmpty) return;
+ var type = constraints[0].Type;
+ Box3DSoaParticleHandle[]? rented = null;
+ Span native = constraints.Length <= 256 ? stackalloc Box3DSoaParticleHandle[constraints.Length] : (rented = ArrayPool.Shared.Rent(constraints.Length)).AsSpan(0, constraints.Length);
+ try
+ {
+ for (var i = 0; i < constraints.Length; i++)
+ {
+ if (constraints[i].Type != type) throw new ArgumentException("One type per call.", nameof(constraints));
+ native[i] = new Box3DSoaParticleHandle(constraints[i].Lane, constraints[i].Generation);
+ }
+ fixed (Box3DSoaParticleHandle* h = native)
+ Check(Box3DSoaNative.ymir_box3d_soa_remove(_handle, (uint)type, constraints.Length, h));
+ }
+ finally
+ {
+ if (rented is not null) ArrayPool.Shared.Return(rented);
+ }
+ }
+
+ ///
+ /// Pins ( true) or wakes the named particles. A pinned particle is dormant: no step walk visits it, its position and velocity
+ /// lanes are stale, and a reader draws it from its anchor ( says which, names the attachment). A pinned particle that shares a
+ /// live distance or bend with an unpinned one is held on its anchor each substep instead. A wake puts the particle on its anchor's point at the
+ /// bodies' poses now, moving as that point moves. Refuses the whole batch, changing nothing, for a stale or dead handle, a fluid particle, or pinning
+ /// a particle with no non-tether attachment or whose distance component holds a tether attachment (no command leaves a component holding both). Removing a pinned particle's anchor attachment is refused.
+ ///
+ public unsafe void SetPinned(ReadOnlySpan particles, bool pinned)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ fixed (Box3DSoaParticleHandle* h = particles)
+ Check(Box3DSoaNative.ymir_box3d_soa_set_pinned(_handle, particles.Length, h, pinned ? 1u : 0u));
+ }
+
+ ///
+ /// Settles fluid particles into wet patches and destroys them: each drop (volume (2 r)^3) joins the lowest patch on its support whose disc
+ /// holds its contact point, else takes the lowest free lane, else joins the nearest patch on that support, else adds its volume to the nearest patch of its material anywhere (that patch's centre stays). A drop's support is its
+ /// last step's , else . Refuses the whole batch, changing
+ /// nothing, for a dead or non-fluid particle, one without a support, a particle named twice, or no lane and no live patch of its material to join.
+ /// (or empty) receives the patch each drop landed in. Which particles settle is the caller's policy.
+ ///
+ public unsafe void Settle(ReadOnlySpan particles, Span patches = default)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (!patches.IsEmpty && patches.Length < particles.Length) throw new ArgumentException("One handle per particle.", nameof(patches));
+ Span native = particles.Length <= 16 ? stackalloc Box3DSoaParticleHandle[particles.Length] : new Box3DSoaParticleHandle[particles.Length];
+ fixed (Box3DSoaParticleHandle* h = particles)
+ fixed (Box3DSoaParticleHandle* o = native)
+ Check(Box3DSoaNative.ymir_box3d_soa_settle(_handle, particles.Length, h, patches.IsEmpty ? null : o));
+ for (var i = 0; i < patches.Length && i < native.Length; i++)
+ patches[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Wet, native[i].Lane, native[i].Generation);
+ }
+
+ ///
+ /// Takes up to [k] m^3 of pooled liquid from the wet patches sensor k reads (the patches whose centres lie in its sphere, at the bodies' poses now), every patch the
+ /// same fraction, so no lane order decides which gives; a patch taken to nothing is removed. Sensors apply in call order, a later one seeing an earlier one's take.
+ /// (or empty) receives the summed volume that left the patches per sensor (float rounding can leave it below the ask, or 0). Refuses the whole batch, changing nothing, for a stale or removed sensor, a sensor named twice,
+ /// or a volume that is not finite or is negative; throws for a handle that is not a sensor, unequal lengths, or a non-empty shorter than the sensors.
+ /// Readings change at the next step's end. Which liquid is breathed, and when, is the caller's policy.
+ ///
+ public unsafe void TakeWet(ReadOnlySpan sensors, ReadOnlySpan volumes, Span taken = default)
+ {
+ ObjectDisposedException.ThrowIf(_handle == 0, this);
+ if (sensors.Length != volumes.Length) throw new ArgumentException("One volume per sensor.", nameof(volumes));
+ if (!taken.IsEmpty && taken.Length < sensors.Length) throw new ArgumentException("One taken per sensor.", nameof(taken));
+ Span