From 92e446a4f682edc95a5cf93349173b7c54c74080 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 25 Nov 2026 04:38:37 +0100 Subject: [PATCH] Settle binding: Settle, Wet patch lanes, WetVolume per body, wet friction; tests and docs Co-Authored-By: Claude Sonnet 5.5 --- docs/soa-world.md | 24 +- native/Ymir.Box3D/ymir_particles.c | 13 +- src/Ymir.Box3D/Box3DSoaWorld.cs | 54 ++- .../Box3DSoaFluidTests.cs | 6 +- .../Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs | 320 ++++++++++++++++++ 5 files changed, 396 insertions(+), 21 deletions(-) create mode 100644 tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs diff --git a/docs/soa-world.md b/docs/soa-world.md index 8d661e7..148d529 100644 --- a/docs/soa-world.md +++ b/docs/soa-world.md @@ -8,11 +8,11 @@ Box3D decides every physical outcome; Ymir creates bodies, steps the world and e `ymir_box3d_session_*` (`ymir_box3d.c`) is the planar Aetheria session: gravity is zero, Y is locked, only yaw rotates (`motionLocks.linearY/angularX/angularZ`), and state leaves by `copy_bodies` into an array of structs. A body cannot fall or tumble there, and every read is a copy. The SoA world is a -separate native object (`ymir_box3d_soa.c`, ABI 13) so the Aetheria session's contract is untouched. +separate native object (`ymir_box3d_soa.c`, ABI 14) so the Aetheria session's contract is untouched. ## Contract -- Native (ABI 13): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) / +- Native (ABI 14): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) / create_particles / destroy_particles / create_distances / create_bends / attach / remove / set_material / free_slots / add_body / add_joint / step / get_view / get_facts / set_anchor_target / destroy_joint / free_joint_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). Capacities are fixed at creation, @@ -104,7 +104,7 @@ separate native object (`ymir_box3d_soa.c`, ABI 13) so the Aetheria session's co 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}` that is not all zero owns fixed + `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 @@ -112,7 +112,7 @@ separate native object (`ymir_box3d_soa.c`, ABI 13) so the Aetheria session's co 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`), particle, body, point, compliance, `force` (sensor). Tether lanes (derived): attachment, - particle, bound, parent tether, edge, other attachment. Material table: friction, XSPH viscosity and the caller's material id. Handles are + particle, bound, parent tether, edge, other attachment. Material table: friction, XSPH viscosity, wet friction and the caller's material id. Handles are (lane, generation). - 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; @@ -207,7 +207,21 @@ separate native object (`ymir_box3d_soa.c`, ABI 13) so the Aetheria session's co 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. + 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 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 only `settle`, `remove(WET)` and `destroy_particles` 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 read by nothing here: what wet friction does to a contact is the cut `ymir-fluid-wet-friction`. 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. 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 diff --git a/native/Ymir.Box3D/ymir_particles.c b/native/Ymir.Box3D/ymir_particles.c index 5208551..09b1c8a 100644 --- a/native/Ymir.Box3D/ymir_particles.c +++ b/native/Ymir.Box3D/ymir_particles.c @@ -2268,20 +2268,17 @@ int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h { 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->contacts[h[k].lane] || + 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)) { - for (int32_t j = 0; j < k; ++j) - { - p->contacts[h[j].lane] = 0; - } return YMIR_PARTICLES_INVALID_ARGUMENT; // a particle named twice would settle its volume twice } - p->contacts[h[k].lane] = 1; // scratch between steps: the step zeroes it again + p->done[h[k].lane] = 1; } int32_t saved_count = p->wet_count; int32_t logged = 0; @@ -2366,10 +2363,6 @@ int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h out[k] = (ymir_handle){into, p->wet_generation[into]}; } } - for (int32_t k = 0; k < n; ++k) - { - p->contacts[h[k].lane] = 0; - } if (status != YMIR_PARTICLES_OK) { for (int32_t u = logged - 1; u >= 0; --u) diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index e25aabe..13cc035 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -83,7 +83,9 @@ public enum Box3DSoaConstraintType : uint { Distance = 1, Bend = 2, - Attachment = 3 + Attachment = 3, + /// A wet patch: settled liquid on a body or a solid particle. + Wet = 4 } /// A constraint's identity: its type, lane and the slot's generation when it was made. @@ -546,6 +548,10 @@ internal static unsafe partial class Box3DSoaNative [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] internal static partial int ymir_box3d_soa_attach(nint world, in Box3DSoaAttachmentDesc desc, out Box3DSoaParticleHandle handle); + [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_remove(nint world, uint type, int n, Box3DSoaParticleHandle* handles); @@ -759,6 +765,28 @@ public readonly unsafe struct Box3DSoaView /// 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); + /// 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); @@ -1128,6 +1156,25 @@ public sealed class Box3DSoaWorld : IDisposable } } + /// + /// 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. 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 patch 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)); + var native = 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); + } + /// Removes one constraint. public void Remove(Box3DSoaConstraintHandle constraint) => Remove([constraint]); @@ -1135,10 +1182,10 @@ public sealed class Box3DSoaWorld : IDisposable /// Sets a material table entry: the friction particles of that material have against bodies, the caller's id for it and the /// XSPH viscosity coefficient (dimensionless, >= 0) fluid particles of it relax their velocities by. /// - public void SetMaterial(int index, float friction, ulong materialId = 0, float viscosity = 0f) + public void SetMaterial(int index, float friction, ulong materialId = 0, float viscosity = 0f, float wetFriction = 0f) { ObjectDisposedException.ThrowIf(_handle == 0, this); - Check(Box3DSoaNative.ymir_box3d_soa_set_material(_handle, index, new Box3DSoaMaterialDesc { Friction = friction, Viscosity = viscosity, MaterialId = materialId })); + Check(Box3DSoaNative.ymir_box3d_soa_set_material(_handle, index, new Box3DSoaMaterialDesc { Friction = friction, Viscosity = viscosity, WetFriction = wetFriction, MaterialId = materialId })); } /// Lanes a new particle could take right now (never used, or dead for a step). @@ -1146,6 +1193,7 @@ public sealed class Box3DSoaWorld : IDisposable public int FreeDistanceSlots => FreeSlots(Box3DSoaConstraintType.Distance); public int FreeBendSlots => FreeSlots(Box3DSoaConstraintType.Bend); public int FreeAttachmentSlots => FreeSlots(Box3DSoaConstraintType.Attachment); + public int FreeWetSlots => FreeSlots(Box3DSoaConstraintType.Wet); private int FreeSlots(Box3DSoaConstraintType type) { diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs index b5035be..949ffe0 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs @@ -6,7 +6,7 @@ namespace Ymir.Box3D.Soa.Tests; using Pos = (float X, float Y, float Z); /// Fluid as a phase bit of the one particle solver: docs/soa-world.md, particles section, Fluid. -public sealed class Box3DSoaFluidTests +public sealed partial class Box3DSoaFluidTests { private const float Dt = Box3DSoaParticleTests.Dt; private const int Sub = Box3DSoaParticleTests.Sub; @@ -35,8 +35,8 @@ public sealed class Box3DSoaFluidTests private const float R = 0.0125f; private const float FluidMass = 0.015625f; // (2 r)^3 of water: 15.6 mL - private static Box3DSoaWorld FluidWorld(int particles, int bodies = 8, float gravityY = -10f, int materials = 2) => - new(bodies, gravityY: gravityY, particles: new Box3DSoaParticleCapacities(particles, 16, 16, 16, 64, materials, particles)); + private static Box3DSoaWorld FluidWorld(int particles, int bodies = 8, float gravityY = -10f, int materials = 2, int wets = 0) => + new(bodies, gravityY: gravityY, particles: new Box3DSoaParticleCapacities(particles, 16, 16, 16, 64, materials, particles, wets)); /// A floor and four walls: an open well of interior half-width centred on the y axis. private static void Well(Box3DSoaWorld world, float half) diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs new file mode 100644 index 0000000..1a178f3 --- /dev/null +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaWetTests.cs @@ -0,0 +1,320 @@ +using System.Runtime.InteropServices; +using Ymir.Box3D; + +namespace Ymir.Box3D.Soa.Tests; + +using Pos = (float X, float Y, float Z); + +/// Settled liquid as data: docs/soa-world.md, Settle. The step writes no wet lane; settle, remove and destroy do. +public sealed partial class Box3DSoaFluidTests +{ + private const float DropVolume = (2f * R) * (2f * R) * (2f * R); // (2 r)^3, in float as the native computes it + + private static Box3DSoaParticleHandle Handle(Box3DSoaWorld world, int lane) => new(lane, world.View.ParticleGeneration[lane]); + + /// A floor (body lane 0, top at y 0) and a world with room for patches; the drops rest on it for 20 ticks so each reads its support. + private static Box3DSoaWorld WetFloor(int particles, int wets, Pos[] at, uint[]? material = null, float[]? radius = null, int materials = 2) + { + var world = FluidWorld(particles, gravityY: -9.81f, materials: materials, wets: wets); + world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f); + var desc = new Box3DSoaParticleDesc[at.Length]; + for (var i = 0; i < at.Length; i++) + { + var r = radius?[i] ?? R; + desc[i] = new Box3DSoaParticleDesc((at[i].X, r, at[i].Z), FluidMass * (r / R) * (r / R) * (r / R), r, FluidPhase, material?[i] ?? 0u, null, default); + } + world.CreateParticles(desc); + for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub); + return world; + } + + private static Box3DSoaParticleHandle[] Handles(Box3DSoaWorld world, int count) => + Enumerable.Range(0, count).Select(i => Handle(world, i)).ToArray(); + + private static byte[] WetBytes(Box3DSoaView v) + { + var o = new MemoryStream(); + void B(ReadOnlySpan lane) where T : unmanaged => o.Write(MemoryMarshal.AsBytes(lane)); + B(v.WetBody); B(v.WetParticle); B(v.WetX); B(v.WetY); B(v.WetZ); B(v.WetRadius); B(v.WetPatchVolume); B(v.WetMaterial); + B(v.WetLive); B(v.WetGeneration); B(v.WetRemovedAt); B(v.WetVolume); + return o.ToArray(); + } + + private static byte[] WorldBytes(Box3DSoaView v) + { + var o = new MemoryStream(); + void B(ReadOnlySpan lane) where T : unmanaged => o.Write(MemoryMarshal.AsBytes(lane)); + o.Write(WetBytes(v)); + B(v.ParticleLive); B(v.ParticleGeneration); B(v.ParticleX); B(v.ParticleY); B(v.ParticleZ); B(v.ParticleVx); B(v.ParticleVy); B(v.ParticleVz); + B(v.ParticleRemovedAt); B(v.SupportBody); B(v.SupportParticle); + B(v.TetherAttachment); B(v.TetherParticle); B(v.TetherParent); B(v.TetherEdge); B(v.TetherOther); B(v.TetherBound); B(v.ParticleComponent); + return o.ToArray(); + } + + private static int LivePatches(Box3DSoaView v) => v.WetLive.ToArray().Count(l => l != 0); + + // Relative error of the patch volumes' sum against n (2 r)^3, over three settle orders of the same 100 drops (ascending, descending, interleaved): shipped + // worst 1.909e-7 (a float sum, so the bound takes the worst across orders by lodur:ruling:ymir-column-mean-bound-order-noise), M1 (a merge forgets the volume + // already in the patch) 0.84 in each order: bound sqrt(1.909e-7 x 0.84) = 4.0e-4, separation 4.4e6. M2 (no merge) and M2b (merge across materials) conserve the sum and are + // claimed by Settle_merges_inside_a_patch. + private const double ConserveBound = 4.0e-4; + + [Fact] + public void Settle_conserves_volume() + { + var worst = 0.0; + foreach (var order in new[] { "ascending", "descending", "interleaved" }) + { + var at = new Pos[100]; + for (var k = 0; k < 10; k++) for (var i = 0; i < 10; i++) at[k * 10 + i] = (-0.14f + 2.5f * R * i, 0f, -0.14f + 2.5f * R * k); + using var world = WetFloor(128, 16, at); + var view = world.View; + Assert.All(Enumerable.Range(0, 100), i => Assert.True(view.SupportBody[i] >= 0, $"drop {i} reads no support")); + var tethers = Snapshot(view); + var drops = Handles(world, 100); + if (order == "descending") Array.Reverse(drops); + if (order == "interleaved") drops = drops.Where((_, i) => i % 2 == 0).Concat(drops.Where((_, i) => i % 2 == 1).Reverse()).ToArray(); + world.Settle(drops); + view = world.View; + SameTethers(tethers, Snapshot(view)); + Assert.All(Enumerable.Range(0, 100), i => Assert.Equal(0u, view.ParticleLive[i])); + var sum = 0.0; + for (var w = 0; w < view.WetCount; w++) if (view.WetLive[w] != 0) sum += view.WetPatchVolume[w]; + var error = Math.Abs(sum - 100.0 * DropVolume) / (100.0 * DropVolume); + Readings.Add($"WET conserve {order}: {LivePatches(view)} patches, relative error {error:E3}"); + worst = Math.Max(worst, error); + } + Assert.True(worst <= ConserveBound, $"relative error {worst:E3}"); + } + + // Centre of a merged patch against the volume-weighted mean of its two contact points, in metres: shipped worst 5.96e-8, M3 (an unweighted mean) 2.333e-2: + // bound sqrt(5.96e-8 x 2.333e-2) = 3.7e-5 m, separation 3.9e5. + private const double CentreBound = 3.7e-5; + + [Fact] + public void Settle_merges_inside_a_patch() + { + // A drop's patch is a disc of radius sqrt((2 r)^3 / (pi film)) = 70.5 mm. Two drops 30 mm apart: one patch. + using (var world = WetFloor(16, 4, [(-0.015f, 0f, 0f), (0.015f, 0f, 0f)])) + { + world.Settle(Handles(world, 2)); + Assert.Equal(1, LivePatches(world.View)); + Assert.Equal(2f * DropVolume, world.View.WetPatchVolume[0], 1e-9f); + } + // Two spots 200 mm apart: two. + using (var world = WetFloor(16, 4, [(-0.1f, 0f, 0f), (0.1f, 0f, 0f)])) + { + world.Settle(Handles(world, 2)); + Assert.Equal(2, LivePatches(world.View)); + } + // The same spot, two materials: two (liquids of different material do not mix). + using (var world = WetFloor(16, 4, [(-0.015f, 0f, 0f), (0.015f, 0f, 0f)], material: [0u, 1u])) + { + world.Settle(Handles(world, 2)); + var view = world.View; + Assert.Equal(2, LivePatches(view)); + Assert.Equal(0u, view.WetMaterial[0]); + Assert.Equal(1u, view.WetMaterial[1]); + } + // Unequal drops (volume 1 : 8) merge to the volume-weighted centre, in the body's frame (the floor body is at y -0.5: the contact point is 0.5 above its origin). + using (var world = WetFloor(16, 4, [(-0.03f, 0f, 0f), (0.03f, 0f, 0f)], radius: [R, 2f * R])) + { + var view = world.View; + var (x0, x1) = ((double)view.ParticleX[0], (double)view.ParticleX[1]); + var (v0, v1) = ((double)DropVolume, 8.0 * DropVolume); + var (z0, z1) = ((double)view.ParticleZ[0], (double)view.ParticleZ[1]); + world.Settle(Handles(world, 2)); + view = world.View; + Assert.Equal(1, LivePatches(view)); + var cx = (x0 * v0 + x1 * v1) / (v0 + v1); + var cz = (z0 * v0 + z1 * v1) / (v0 + v1); + var error = Math.Max(Math.Abs(view.WetX[0] - cx), Math.Max(Math.Abs(view.WetZ[0] - cz), Math.Abs(view.WetY[0] - 0.5))); + Readings.Add($"WET centre error {error:E3} m, weighted x {cx:F5}, unweighted {(x0 + x1) / 2:F5}"); + Assert.Equal(0, view.WetBody[0]); + Assert.Equal(-1, view.WetParticle[0]); + Assert.True(error <= CentreBound, $"centre error {error:E3} m"); + } + } + + [Fact] + public void Settle_refusals_change_nothing() + { + // One patch lane. A pedestal (body 1) beside the floor (body 0); a drop on each, a second on the floor, a solid particle, a drop in flight. + using var world = FluidWorld(16, gravityY: -9.81f, wets: 1); + world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f); + world.AddStaticBox(2, (0.5f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), friction: 0.3f); + var made = new Box3DSoaParticleHandle[4]; + world.CreateParticles([Fluid((-0.5f, R, 0f)), Fluid((-0.45f, R, 0f)), Fluid((0.5f, 0.2f + R, 0f)), Fluid((0.9f, 30f, 0f))], made); + var solid = new Box3DSoaParticleHandle[1]; + world.CreateParticles([new Box3DSoaParticleDesc((0.2f, 0.5f, 0f), 0.02f, R, 0u, 0, null, default)], solid); + for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub); + var (floorA, floorB, pedestal, flight) = (made[0], made[1], made[2], made[3]); + Assert.Equal(0, world.View.SupportBody[floorA.Lane]); + Assert.Equal(1, world.View.SupportBody[pedestal.Lane]); + world.Settle([floorA]); // the only lane is taken, on the floor + Assert.Equal(1, LivePatches(world.View)); + var gone = new Box3DSoaParticleHandle[1]; + world.CreateParticles([Fluid((0.9f, 30f, 0.5f))], gone); + world.DestroyParticles(gone); + var before = WorldBytes(world.View); + void Refused(params Box3DSoaParticleHandle[] batch) + { + Assert.Throws(() => world.Settle(batch)); + Assert.True(before.AsSpan().SequenceEqual(WorldBytes(world.View)), "a refused batch changed a lane"); + } + Refused(floorB, solid[0]); // a solid particle + Refused(floorB, flight); // no support + Refused(floorB, gone[0]); // a stale handle + Refused(floorB, floorB); // named twice + Refused(floorB, pedestal); // the floor drop would merge, the pedestal drop finds no lane and no patch on its support: FULL, all undone + world.Settle([floorB]); // and without the pedestal drop it merges + Assert.Equal(1, LivePatches(world.View)); + Assert.Equal(2f * DropVolume, world.View.WetPatchVolume[0], 1e-9f); + } + + [Fact] + public void Patches_follow_their_body() + { + // A patch on a free box keeps its point in the box's frame while the box is shoved along the floor. + { + using var world = FluidWorld(64, gravityY: -9.81f, wets: 4); + world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f); + var box = world.AddBox(2, (0f, 0.1f, 0f), (0.1f, 0.1f, 0.1f), 5000f, friction: 0.3f); + var drop = new Box3DSoaParticleHandle[1]; + world.CreateParticles([Fluid((0.03f, 0.2f + R, 0.02f))], drop); + for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub); + Assert.Equal(box, world.View.SupportBody[drop[0].Lane]); + world.Settle(drop); + var view = world.View; + var (x, y, z) = (view.WetX[0], view.WetY[0], view.WetZ[0]); + Assert.Equal(box, view.WetBody[0]); + var rest = view.PositionX[box]; + world.ApplyImpulse(box, (1500f, 0f, 0f), (view.PositionX[box], view.PositionY[box], view.PositionZ[box])); + for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, Sub); + view = world.View; + Assert.True(view.PositionX[box] - rest > 0.1f, "the box moved"); + Assert.Equal((x, y, z), (view.WetX[0], view.WetY[0], view.WetZ[0])); + Assert.Equal(box, view.WetBody[0]); + } + // A patch on a solid particle goes when that particle is destroyed; a patch on a body does not. + { + using var world = new Box3DSoaWorld(4, gravityY: -9.81f, particles: new Box3DSoaParticleCapacities(256, 160, 140, 16, 1024, 2, 16, 4)); + world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f)); + var sheet = Graph.Sheet(world, (0f, 0.6f, 0f), (0.04f, 0f, 0f), (0f, 0f, 0.04f), 8, 8, 0.02f, 0.02f, Box3DSoaPhase.Of(4, true, true)); + for (var j = 0; j < 8; j++) + for (var i = 0; i < 8; i += 7) + world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[j * 8 + i], point: (0.04f * i, 0.6f, 0.04f * j)); + var drops = new Box3DSoaParticleHandle[1]; + world.CreateParticles([Fluid((0.12f, 0.64f, 0.12f))], drops); + for (var tick = 0; tick < 20; tick++) world.Step(1f / 60f, Sub); + var under = world.View.SupportParticle[drops[0].Lane]; + Assert.True(under >= 0); + world.Settle(drops); + var view = world.View; + Assert.Equal(1, LivePatches(view)); + Assert.Equal(under, view.WetParticle[0]); + Assert.Equal(-1, view.WetBody[0]); + Assert.Equal((0f, 0f, 0f), (view.WetX[0], view.WetY[0], view.WetZ[0])); + world.DestroyParticles([sheet.Particles.Single(h => h.Lane == under)]); + view = world.View; + Assert.Equal(0, LivePatches(view)); + Assert.Equal(0f, view.WetPatchVolume[0]); + Assert.Equal(-1, view.WetParticle[0]); + Assert.Equal(1u, view.WetGeneration[0]); + } + } + + [Fact] + public void Wet_volume_reads_patches() + { + using var world = WetFloor(16, 4, [(-0.1f, 0f, 0f), (0.1f, 0f, 0f), (0.11f, 0f, 0.01f)]); + void Reads() + { + var v = world.View; + var sum = new float[v.Count]; + for (var w = 0; w < v.WetCount; w++) if (v.WetLive[w] != 0) sum[v.WetBody[w]] += v.WetPatchVolume[w]; + Assert.True(sum.AsSpan().SequenceEqual(v.WetVolume), "wet volume is not the patch sum"); + } + Assert.Equal(0f, world.View.WetVolume[0]); + var patches = new Box3DSoaConstraintHandle[3]; + world.Settle(Handles(world, 3), patches); + Reads(); + Assert.Equal(3f * DropVolume, world.View.WetVolume[0], 1e-9f); + Assert.Equal(patches[1].Lane, patches[2].Lane); + var before = WetBytes(world.View); + for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, Sub); // a step writes no wet lane and no wet volume + Assert.True(before.AsSpan().SequenceEqual(WetBytes(world.View)), "a step changed a wet lane"); + Assert.Equal(2, world.FreeWetSlots); // two of four lanes taken + world.Remove(patches[0]); + Reads(); + Assert.Equal(2f * DropVolume, world.View.WetVolume[0], 1e-9f); + Assert.Equal(2, world.FreeWetSlots); // a freed lane waits for a step to pass + world.Step(1f / 60f, Sub); + Assert.Equal(3, world.FreeWetSlots); + Assert.Throws(() => world.Remove(patches[0])); // a stale handle + } + + // ---- determinism ---------------------------------------------------------------------------------------- + + private static ulong HashWet(Box3DSoaView v) + { + var h = 1469598103934665603ul; + h = Fnv(h, WorldBytes(v)); + void F(ReadOnlySpan lane) => h = Fnv(h, MemoryMarshal.AsBytes(lane)); + F(v.PositionX); F(v.PositionY); F(v.PositionZ); + return h; + } + + private static ulong[] WetCheckpoints(bool nudge = false) + { + // A pool poured into a well that holds a free box; every 10 ticks every drop that reads a support settles. + using var world = FluidWorld(256, gravityY: -9.81f, wets: 32); + Well(world, 0.1f); + world.AddBox(6, (0f, 0.04f, 0f), (0.04f, 0.04f, 0.04f), 2000f, friction: 0.3f); + var desc = new Box3DSoaParticleDesc[100]; + for (var k = 0; k < 5; k++) for (var j = 0; j < 4; j++) for (var i = 0; i < 5; i++) + desc[(k * 4 + j) * 5 + i] = new Box3DSoaParticleDesc((-0.05f + 0.03f * i, 0.12f + 0.03f * j, -0.05f + 0.03f * k), FluidMass, R, FluidPhase, 0, null, default); + if (nudge) desc[40].X = BitConverter.UInt32BitsToSingle(BitConverter.SingleToUInt32Bits(desc[40].X) + 1); + world.CreateParticles(desc); + var hashes = new ulong[6]; + for (var c = 0; c < 6; c++) + { + for (var t = 0; t < 40; t++) + { + world.Step(1f / 60f, Sub); + if (t % 10 != 9) continue; + var v = world.View; + var supported = new List(); + for (var lane = 0; lane < v.ParticleCount; lane++) + if (v.ParticleLive[lane] != 0 && (v.SupportBody[lane] >= 0 || v.SupportParticle[lane] >= 0)) supported.Add(new Box3DSoaParticleHandle(lane, v.ParticleGeneration[lane])); + world.Settle(supported.ToArray()); + } + hashes[c] = HashWet(world.View); + } + Assert.True(LivePatches(world.View) > 0, "nothing settled"); + return hashes; + } + + // Recorded on this commit's build (gcc 13.2, -ffp-contract=off): the wet pour at ticks 40, 80, ... 240. + private static readonly ulong[] WetHashes = [1795683519249061853ul, 16977328850116599834ul, 12459064917284188353ul, 470571818171069221ul, 7502974747124893900ul, 8400504905509365280ul]; + + [Fact] + public void Wet_world_is_byte_deterministic() + { + var a = WetCheckpoints(); + var b = WetCheckpoints(); + Assert.True(a.AsSpan().SequenceEqual(b), "two runs diverged: " + string.Join(",", a) + " vs " + string.Join(",", b)); + Assert.True(a.Distinct().Count() > 1, "the scene moves"); + Assert.False(a.AsSpan().SequenceEqual(WetCheckpoints(nudge: true)), "a one-ulp input difference must diverge"); + Assert.True(WetHashes.AsSpan().SequenceEqual(a), string.Join(",", a.Select(g => g + "ul"))); + } + + [Fact] + public async Task Wet_world_is_the_same_bytes_on_any_thread_under_load() + { + var serial = WetCheckpoints(); + var results = Enumerable.Range(0, 8).Select(_ => Task.Factory.StartNew(() => WetCheckpoints(), TaskCreationOptions.LongRunning)).ToArray(); + await Task.WhenAll(results); + foreach (var r in results) Assert.True(Enumerable.SequenceEqual(serial, await r), "a concurrent run diverged from the serial one"); + } +}