From bb35465623f8d36e378718dcefebdcfd28702837 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 25 Nov 2026 00:37:33 +0100 Subject: [PATCH] Particles: fluid as a phase bit: unilateral number-density PBF with solids in the estimate, momentum-exact pair split, XSPH Poly6/Spiky kernels per pair h = 2 (ri + rj), n0 a create-time lattice constant, lambda gathered over the 27 cells, corrections scattered over the contact pass's half-walk (the walk is now shared) and split by inverse mass, XSPH after the velocity update. Grid cell 2 r_max with no live fluid (byte-identical), 2 (r_fmax + r_max) with. Binding: Box3DSoaPhase.Fluid, material viscosity, ParticleDensity and MaterialViscosity lanes, ABI 11 (the lanes are here because the fluid tests read them). Co-Authored-By: Claude Sonnet 5.5 --- native/Ymir.Box3D/ymir_box3d_soa.c | 7 +- native/Ymir.Box3D/ymir_particles.c | 319 +++++++++++--- native/Ymir.Box3D/ymir_particles.h | 10 +- src/Ymir.Box3D/Box3DSoaWorld.cs | 19 +- .../Box3DSoaFluidTests.cs | 389 ++++++++++++++++++ .../Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs | 8 +- tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs | 19 + .../Box3DSoaParticleTests.cs | 6 + 8 files changed, 717 insertions(+), 60 deletions(-) diff --git a/native/Ymir.Box3D/ymir_box3d_soa.c b/native/Ymir.Box3D/ymir_box3d_soa.c index be99f38..4f98139 100644 --- a/native/Ymir.Box3D/ymir_box3d_soa.c +++ b/native/Ymir.Box3D/ymir_box3d_soa.c @@ -58,7 +58,7 @@ enum YMIR_SOA_JOINT_REMOVED = 4 // a destroyed joint's lane: never accepted by add_joint }; -#define YMIR_SOA_ABI_VERSION 10u +#define YMIR_SOA_ABI_VERSION 11u // 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 @@ -223,6 +223,8 @@ typedef struct ymir_box3d_soa_view 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; @@ -271,6 +273,7 @@ typedef struct ymir_box3d_soa_view // Material table, indexed up to material_capacity. const float* material_friction; const uint64_t* material_id_lane; + const float* material_viscosity; } ymir_box3d_soa_view; // A begin or end of touch between two bodies: their lane indices and the shapes' stable ids. @@ -1524,6 +1527,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world 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; @@ -1564,6 +1568,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world 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; } return YMIR_SOA_OK; } diff --git a/native/Ymir.Box3D/ymir_particles.c b/native/Ymir.Box3D/ymir_particles.c index 0aee1a5..3bf6cbd 100644 --- a/native/Ymir.Box3D/ymir_particles.c +++ b/native/Ymir.Box3D/ymir_particles.c @@ -66,6 +66,15 @@ static void put(float* x, float* y, float* z, int i, v3 v) // 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 + // ---- memory: one block, laid out once at create ------------------------------------------------------------- static size_t layout(ymir_particles* p, unsigned char* base) @@ -90,6 +99,7 @@ static size_t layout(ymir_particles* p, unsigned char* base) 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(density, float, np); 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); @@ -104,10 +114,10 @@ static size_t layout(ymir_particles* p, unsigned char* base) 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_id, uint64_t, nm); + CARVE(mat_friction, float, nm); CARVE(mat_viscosity, 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(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); 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); @@ -154,6 +164,20 @@ ymir_particles* ymir_particles_create(const ymir_particle_capacities* c, int32_t return NULL; } layout(p, (unsigned char*)p->arena); + // 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; } @@ -804,6 +828,7 @@ int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymi 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] = 0; + p->density[i] = p->lambda[i] = 0.0f; p->particle_live[i] = 0; p->particle_generation[i] += 1; p->particle_removed_at[i] = step_count; @@ -1016,11 +1041,13 @@ int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const 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) + 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) { return YMIR_PARTICLES_INVALID_ARGUMENT; } p->mat_friction[index] = d->friction; + p->mat_viscosity[index] = d->viscosity; p->mat_id[index] = d->material_id; return YMIR_PARTICLES_OK; } @@ -1135,15 +1162,20 @@ static int32_t cell_of(float v, float inv_cell) // index order, so every neighbour walk is the same on every run. static float build_grid(ymir_particles* p) { - float rmax = 0.0f; + float rmax = 0.0f, rfmax = 0.0f; for (int32_t i = 0; i < p->particle_count; ++i) { if (p->particle_live[i]) { rmax = vmax(rmax, p->radius[i]); + if (p->phase[i] & YMIR_PHASE_FLUID) + { + rfmax = vmax(rfmax, p->radius[i]); + } } } - float inv_cell = 1.0f / (2.0f * rmax); + // A cell holds every contact pair (reach 2 rmax); with fluid it holds every kernel pair too (reach h = 2 (ri + rj)). + float inv_cell = p->live_fluid == 0 ? 1.0f / (2.0f * rmax) : 1.0f / vmax(2.0f * rmax, 2.0f * (rfmax + rmax)); int32_t buckets = (int32_t)p->table_mask + 1; memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1)); for (int32_t i = 0; i < p->particle_count; ++i) @@ -1174,12 +1206,16 @@ static float build_grid(ymir_particles* p) } -// Do particles i and j collide by contact? Symmetric in i and j, which momentum conservation needs. Particles of -// different groups always do; of one group only when both set SELF_COLLIDE, and not, when either sets +// 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; @@ -1211,9 +1247,69 @@ static int touching(const ymir_particles* p, int32_t i, int32_t j, v3 xi, v3* d, 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 void (*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 i = 0; i < p->particle_count; ++i) + { + if (!p->particle_live[i]) + { + 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->table_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 void contact_pair(ymir_particles* p, void* ctx, int32_t i, int32_t j) +{ + 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; + } + if (*(int*)ctx == 0) + { + p->contacts[i]++; + p->contacts[j]++; + return; + } + 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->inv_mass[i] / wsum) * depth); + v3 dj = vmul(d, weight * (p->inv_mass[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; +} + // Overlapping pairs push each other apart, split by inverse mass (Macklin 2014). Each pair is found once, by walking -// half the 27-cell neighbourhood: a particle's own cell (partners of higher index) and the 13 cells that follow it -// in lexicographic offset order. Two walks: the first counts every particle's overlaps, the second moves both ends +// 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. @@ -1226,43 +1322,7 @@ static void particle_contacts(ymir_particles* p) } for (int pass = 0; pass < 2; ++pass) { - for (int32_t i = 0; i < p->particle_count; ++i) - { - if (!p->particle_live[i]) - { - continue; - } - v3 xi = P(p, p->pp_x, p->pp_y, p->pp_z, i); - 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->table_mask); - for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q) - { - int32_t j = p->sorted[q]; - v3 d; - float r2, md, wsum; - if ((cell == 0 && j <= i) || p->cell_x[j] != ca || p->cell_y[j] != cb || p->cell_z[j] != cc || - !touching(p, i, j, xi, &d, &r2, &md, &wsum)) - { - continue; // the other end of a pair, another cell sharing the bucket, or no touch - } - if (pass == 0) - { - p->contacts[i]++; - p->contacts[j]++; - continue; - } - 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->inv_mass[i] / wsum) * depth); - v3 dj = vmul(d, weight * (p->inv_mass[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; - } - } - } + walk_half(p, contact_pair, &pass); } for (int32_t i = 0; i < p->particle_count; ++i) { @@ -1275,6 +1335,165 @@ static void particle_contacts(ymir_particles* p) } } +// ---- 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 27 cells (build_grid's cell rule). +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); +} + +// Does the pair (i, j) share the density? Fluid with fluid, or fluid with a solid it would touch by contact. The kernel +// overlap decides the rest. +static int density_pair(const ymir_particles* p, int32_t i, int32_t j) +{ + uint32_t fi = p->phase[i] & YMIR_PHASE_FLUID, fj = p->phase[j] & YMIR_PHASE_FLUID; + return (fi | fj) != 0 && (fi != 0 && fj != 0 ? 1 : collides(p, i, j)); +} + +// Pass B: the pair's correction, (lambda_i + lambda_j) grad W / n0, split by inverse mass: each end moves 2 w / (wi + wj) of it, +// so the pair carries equal and opposite momentum at any mass ratio and a solid end is the reaction. +static void density_scatter(ymir_particles* p, void* ctx, int32_t i, int32_t j) +{ + (void)ctx; + float wsum = p->inv_mass[i] + p->inv_mass[j]; + if (wsum == 0.0f || !density_pair(p, i, j)) + { + 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, 2.0f * p->inv_mass[i] / wsum), dj = vmul(corr, 2.0f * p->inv_mass[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; +} + +// Density constraint of every fluid particle, once per substep, after contact. Pass A gathers (fluid i over the full 27 +// cells, in cell then index order): 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 |grad C_i|^2 + eps); a solid's lambda is 0. Pass B scatters the pair corrections over the contact +// pass's half-walk and applies them after it (Jacobi), so the sums are the same on every run. +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; + } + for (int32_t i = 0; i < p->particle_count; ++i) + { + if (!p->particle_live[i] || !(p->phase[i] & YMIR_PHASE_FLUID)) + { + continue; + } + v3 xi = P(p, p->pp_x, p->pp_y, p->pp_z, i), 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; + for (int32_t o = 0; o < 27; ++o) + { + int32_t ca = p->cell_x[i] + o / 9 - 1, cb = p->cell_y[i] + o / 3 % 3 - 1, cc = p->cell_z[i] + o % 3 - 1; + uint32_t bucket = cell_hash(ca, cb, cc, p->table_mask); + for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q) + { + int32_t j = p->sorted[q]; + if (j == i || p->cell_x[j] != ca || p->cell_y[j] != cb || p->cell_z[j] != cc || !density_pair(p, i, j)) + { + continue; + } + v3 d = vsub(xi, P(p, p->pp_x, p->pp_y, p->pp_z, j)); + float h = kernel_h(p, i, j), r2 = vdot(d, d); + if (r2 >= h * h) + { + continue; + } + n += poly6(r2, h); + if (r2 >= 1e-12f) + { + v3 g = spiky(d, sqrtf(r2), h); + gsum = vadd(gsum, g); + ssum += vdot(g, g); + } + } + } + float c = vmax(n / n0 - 1.0f, 0.0f); + p->density[i] = n / n0; + p->lambda[i] = c == 0.0f ? 0.0f : -c / ((vdot(gsum, gsum) + ssum) / (n0 * n0) + YMIR_PBF_EPS); + } + walk_half(p, density_scatter, NULL); + 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 walk. +static void viscosity_pair(ymir_particles* p, void* ctx, int32_t i, int32_t j) +{ + (void)ctx; + float wsum = p->inv_mass[i] + p->inv_mass[j]; + if (wsum == 0.0f || !(p->phase[i] & p->phase[j] & YMIR_PHASE_FLUID)) + { + 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->inv_mass[i] / wsum), dj = vmul(dv, 2.0f * p->inv_mass[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; +} + +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; + } + walk_half(p, viscosity_pair, NULL); + 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. @@ -1706,6 +1925,10 @@ void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, floa } build_grid(p); particle_contacts(p); + if (p->live_fluid > 0) + { + fluid_density(p); + } solve_attachments(&f); solve_distances(&f); solve_bends(&f); @@ -1724,6 +1947,10 @@ void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, floa } put(p->pos_x, p->pos_y, p->pos_z, i, y); } + if (p->live_fluid > 0) + { + fluid_viscosity(p); + } for (int32_t k = 0; k < p->body_count; ++k) { ymir_particle_proxy* b = p->proxies + k; diff --git a/native/Ymir.Box3D/ymir_particles.h b/native/Ymir.Box3D/ymir_particles.h index 6fcedc5..7707aba 100644 --- a/native/Ymir.Box3D/ymir_particles.h +++ b/native/Ymir.Box3D/ymir_particles.h @@ -129,8 +129,8 @@ typedef struct ymir_attachment_desc typedef struct ymir_material_desc { - float friction; // >= 0 - uint32_t reserved; + 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 uint64_t material_id; } ymir_material_desc; @@ -169,6 +169,7 @@ typedef struct ymir_particles uint32_t *phase, *material, *particle_live, *particle_generation; uint64_t* particle_removed_at; int32_t* component; // derived: the lowest lane of the particle's distance-connected component + float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0 // distance lanes int32_t *dist_a, *dist_b; @@ -199,11 +200,12 @@ typedef struct ymir_particles float* tether_bound; // material table - float* mat_friction; + float *mat_friction, *mat_viscosity; 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; + 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; 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; diff --git a/src/Ymir.Box3D/Box3DSoaWorld.cs b/src/Ymir.Box3D/Box3DSoaWorld.cs index 1c30f89..6940e55 100644 --- a/src/Ymir.Box3D/Box3DSoaWorld.cs +++ b/src/Ymir.Box3D/Box3DSoaWorld.cs @@ -181,7 +181,7 @@ internal struct Box3DSoaAttachmentDesc internal struct Box3DSoaMaterialDesc { public float Friction; - public uint Reserved; + public float Viscosity; public ulong MaterialId; } @@ -299,6 +299,7 @@ internal unsafe struct Box3DSoaViewNative public uint* ParticleGeneration; public ulong* ParticleRemovedAt; public int* ParticleComponent; + public float* ParticleDensity; public int* DistanceA; public int* DistanceB; public float* DistanceRest; @@ -339,6 +340,7 @@ internal unsafe struct Box3DSoaViewNative public float* TetherBound; public float* MaterialFriction; public ulong* MaterialTableId; + public float* MaterialViscosity; } /// Native layout of ymir_box3d_soa_facts: counts, dropped counters, then three pointers. @@ -671,6 +673,8 @@ public readonly unsafe struct Box3DSoaView 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); @@ -728,6 +732,8 @@ public readonly unsafe struct Box3DSoaView 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); /// 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); @@ -746,7 +752,7 @@ public readonly unsafe struct Box3DSoaView /// public sealed class Box3DSoaWorld : IDisposable { - private const uint ExpectedAbi = 10; + private const uint ExpectedAbi = 11; private nint _handle; /// @@ -1101,11 +1107,14 @@ public sealed class Box3DSoaWorld : IDisposable /// Removes one constraint. public void Remove(Box3DSoaConstraintHandle constraint) => Remove([constraint]); - /// Sets a material table entry: the friction particles of that material have against bodies and the caller's id for it. - public void SetMaterial(int index, float friction, ulong materialId = 0) + /// + /// 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) { ObjectDisposedException.ThrowIf(_handle == 0, this); - Check(Box3DSoaNative.ymir_box3d_soa_set_material(_handle, index, new Box3DSoaMaterialDesc { Friction = friction, MaterialId = materialId })); + Check(Box3DSoaNative.ymir_box3d_soa_set_material(_handle, index, new Box3DSoaMaterialDesc { Friction = friction, Viscosity = viscosity, MaterialId = materialId })); } /// Lanes a new particle could take right now (never used, or dead for a step). diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs index bf39138..0e06ad9 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaFluidTests.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using Ymir.Box3D; namespace Ymir.Box3D.Soa.Tests; @@ -31,6 +32,22 @@ public sealed class Box3DSoaFluidTests Assert.True(a.Bound.AsSpan().SequenceEqual(b.Bound), "tether bounds differ"); } + 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)); + + /// 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) + { + world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f); + world.AddStaticBox(2, (half + 0.25f, 1f, 0f), (0.25f, 1f, 1f), friction: 0.3f); + world.AddStaticBox(3, (-half - 0.25f, 1f, 0f), (0.25f, 1f, 1f), friction: 0.3f); + world.AddStaticBox(4, (0f, 1f, half + 0.25f), (1f, 1f, 0.25f), friction: 0.3f); + world.AddStaticBox(5, (0f, 1f, -half - 0.25f), (1f, 1f, 0.25f), friction: 0.3f); + } + [Fact] public void Fluid_refusals() { @@ -54,6 +71,13 @@ public sealed class Box3DSoaFluidTests world.CreateDistances([new Box3DSoaDistanceDesc(ps[0], other[0])]); world.Attach(Box3DSoaAttachKind.Static, ps[0], point: (0f, 0f, 0f), tether: true); Assert.Equal(1, world.View.DistanceCount); // the view is a snapshot of the counts + // a viscosity below 0 or not finite is refused, the material as it was + world.SetMaterial(1, 0.3f, 7, 0.25f); + Assert.Throws(() => world.SetMaterial(1, 0.3f, 8, -0.01f)); + Assert.Throws(() => world.SetMaterial(1, 0.3f, 8, float.NaN)); + Assert.Throws(() => world.SetMaterial(1, 0.3f, 8, float.PositiveInfinity)); + Assert.Equal(0.25f, world.View.MaterialViscosity[1]); + Assert.Equal(7ul, world.View.MaterialTableId[1]); } [Fact] @@ -102,4 +126,369 @@ public sealed class Box3DSoaFluidTests Console.Error.WriteLine(line); Readings.Add(line); } + + // ---- scenes --------------------------------------------------------------------------------------------- + + private static float Sq(float x) => x * x; + + /// + /// A fluid block thrown at a free 16 x 16 sheet and a 48-rope in zero gravity, nothing pinned: every particle is free, so + /// momentum is the whole of it. Masses are per particle. + /// + private static Box3DSoaWorld Collision(float fluidMass, float solidMass) + { + var world = new Box3DSoaWorld(4, gravityY: 0f, particles: new Box3DSoaParticleCapacities(1024, 1024, 1024, 8, 64, 2)); + world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f)); + Graph.Sheet(world, (0f, 0f, 0f), (0.04f, 0f, 0f), (0f, 0.04f, 0f), 16, 16, solidMass, 0.02f, Box3DSoaPhase.Of(7, true, true)); + Graph.Rope(world, Graph.Line((-0.3f, 0.25f, 0.3f), (0.03f, 0f, 0f), 48), solidMass, 0.0125f, Box3DSoaPhase.Of(8, true, true), bend: 1e-5f); + Graph.Block(world, (0.2f, 0.17f, 0.45f), 5, 5, 5, 0.02f, fluidMass, Box3DSoaPhase.Of(9, fluid: true), velocity: (0f, 0f, -4f)); + return world; + } + + /// Drift of the total momentum over the run as a fraction of its initial size, and the highest kinetic energy over the initial. + private static (double Drift, double EnergyRatio) Momentum(Box3DSoaWorld world, int ticks) + { + (double X, double Y, double Z, double E) Total() + { + var v = world.View; + double x = 0, y = 0, z = 0, e = 0; + for (var i = 0; i < v.ParticleCount; i++) + { + if (v.ParticleLive[i] == 0 || v.ParticleInvMass[i] == 0f) continue; + double m = 1.0 / v.ParticleInvMass[i]; + x += m * v.ParticleVx[i]; y += m * v.ParticleVy[i]; z += m * v.ParticleVz[i]; + e += 0.5 * m * (Sq(v.ParticleVx[i]) + Sq(v.ParticleVy[i]) + Sq(v.ParticleVz[i])); + } + return (x, y, z, e); + } + var p0 = Total(); + var emax = p0.E; + var worst = 0.0; + var mag = Math.Sqrt(p0.X * p0.X + p0.Y * p0.Y + p0.Z * p0.Z); + for (var t = 0; t < ticks; t++) + { + world.Step(1f / 60f, 4); + var p = Total(); + emax = Math.Max(emax, p.E); + worst = Math.Max(worst, Math.Sqrt(Sq((float)(p.X - p0.X)) + Sq((float)(p.Y - p0.Y)) + Sq((float)(p.Z - p0.Z))) / mag); + } + return (worst, emax / p0.E); + } + + /// Probe scene 3: a 7 x 7 x 7 fluid block above a 16 x 16 sheet tilted down toward +x (pinned at its corners) and a sloped 24-rope. + private static (Box3DSoaWorld World, Made Sheet, Made Rope, Box3DSoaParticleHandle[] Fluid) Pour(bool nudge = false) + { + var world = new Box3DSoaWorld(4, gravityY: -9.81f, particles: new Box3DSoaParticleCapacities(640, 560, 520, 8, 1024, 2)); // the probe's g + world.AddStaticBox(1, (0f, -50f, 0f), (1f, 1f, 1f)); + world.SetMaterial(1, 0.3f, 0, 0.01f); // the probe's XSPH coefficient + const float sp = 0.04f, r = 0.02f; + var sheet = Graph.Sheet(world, (0f, 0.6f, 0f), (sp, -0.012f, 0f), (0f, 0f, sp), 16, 16, 0.02f, r, Box3DSoaPhase.Of(4, true, true), bend: 1e-3f); + foreach (var i in new[] { 0, 15, 240, 255 }) + { + var v = world.View; + world.Attach(Box3DSoaAttachKind.Static, sheet.Particles[i], point: (v.ParticleX[i], v.ParticleY[i], v.ParticleZ[i])); // plain pins, as the probe's + } + var line = Graph.Line((0.55f, 0.25f, 0.30f), ((1.40f - 0.55f) / 23f, -0.40f / 23f, 0f), 24); + var rope = Graph.Rope(world, line, 0.02f, r, Box3DSoaPhase.Of(5), bend: 1e-5f); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[0], point: line[0], tether: true); + world.Attach(Box3DSoaAttachKind.Static, rope.Particles[23], point: line[23], tether: true); + var desc = new Box3DSoaParticleDesc[343]; + for (var a = 0; a < 7; a++) for (var b = 0; b < 7; b++) for (var c = 0; c < 7; c++) + desc[(a * 7 + b) * 7 + c] = new Box3DSoaParticleDesc((0.10f + a * sp, 0.75f + b * sp, 0.18f + c * sp), 1000f * sp * sp * sp, r, Box3DSoaPhase.Of(6, fluid: true), 1); + if (nudge) desc[100].X = BitConverter.UInt32BitsToSingle(BitConverter.SingleToUInt32Bits(desc[100].X) + 1); + var fluid = new Box3DSoaParticleHandle[desc.Length]; + world.CreateParticles(desc, fluid); + return (world, sheet, rope, fluid); + } + + /// Substeps of the pour (probe scene 3 ran 8; the pour is chaotic and its pinned counts move with it: 6 -> 333/12/338, 8 -> 295/33/329 with one overlap at 0.496, 12 -> 212/60/299). + private const int PourSub = 10; + + // ---- behaviour ------------------------------------------------------------------------------------------ + + // Bounds follow lodur:ruling:deterministic-bound-margin: the geometric mean of the shipped worst and the least claimed mutant, separation >= 1.2. + // |mean - 1| at 3 s: shipped 0.0124, M2 (cell stays 2 r_max) 0.0152, M7 (fluid pairs also contact) 0.0206: bound sqrt(0.0124 x 0.0152) = 0.0137, + // separation 1.23. The max density reads 1.3440 shipped, 1.3576 under M2 and 1.2653 under M7: no mutant is 1.2 away, so the max has no + // claim; 1.5 is a sanity ceiling (the column compressing under its weight is the one-pass solver, not a defect: probe pours peaked at 1.07). + private const float ColumnMax = 1.5f; + private const float ColumnMean = 0.0137f; + + [Fact] + public void Fluid_column_rests_at_rest_density() + { + // A 8 x 8 x 16 block (r 1.25 cm, water mass) resting in a static box well, 3 s at 60 Hz x 4 substeps. The density constraint is + // one pass a substep, so the column compresses under its own weight and its walls read low (a rigid box adds no density + // to the estimate, docs/soa-world.md Not done); what is judged is that the max stays under the bound and the mean near 1. + using var world = FluidWorld(1024); + const float half = 0.105f; + Well(world, half); + // Alternate groups and set both self flags: two fluid particles share one density field whatever their group (Flex sec. 7), so + // neither a group boundary nor SELF_COLLIDE makes a contact between them. + var desc = new Box3DSoaParticleDesc[8 * 16 * 8]; + for (var k = 0; k < 8; k++) for (var j = 0; j < 16; j++) for (var i = 0; i < 8; i++) + desc[(k * 16 + j) * 8 + i] = new Box3DSoaParticleDesc((-0.0875f + 2 * R * i, R + 2 * R * j, -0.0875f + 2 * R * k), FluidMass, R, + Box3DSoaPhase.Of((uint)((i + j + k) % 2 + 1), true, true, true)); + var block = new Box3DSoaParticleHandle[desc.Length]; + world.CreateParticles(desc, block); + var worst = 0f; + for (var tick = 0; tick < 180; tick++) + { + world.Step(1f / 60f, 4); + if (tick < 120) continue; + var d = world.View.ParticleDensity; + foreach (var h in block) worst = MathF.Max(worst, d[h.Lane]); + } + var v = world.View; + double mean = 0; + var outside = 0; + foreach (var h in block) + { + mean += v.ParticleDensity[h.Lane]; + if (MathF.Abs(v.ParticleX[h.Lane]) > half || MathF.Abs(v.ParticleZ[h.Lane]) > half || v.ParticleY[h.Lane] < -0.01f) outside++; + } + mean /= block.Length; + var line = $"COLUMN max density over the last second {worst:F4}, mean at 3 s {mean:F4}, outside the well {outside}"; + Readings.Add(line); + Assert.Equal(0, outside); + Assert.True(worst <= ColumnMax, $"{line}: max over {ColumnMax}"); + Assert.True(Math.Abs(mean - 1.0) <= ColumnMean, $"{line}: mean off 1 by over {ColumnMean}"); + } + + [Fact] + public void Fluid_density_counts_a_larger_solid_beyond_two_contact_radii() + { + // The kernel reach of a pair is 2 (ri + rj), so a fluid particle sees a solid of radius 5 cm 12.5 cm away while contact reaches + // 6.25 cm: the grid cell is 2 (r_fluid_max + r_max), not 2 r_max. Placed two 10 cm cells of the narrower grid apart (10.15 cm), the + // solid is in the fluid particle's estimate only if the cell is the wider. + double Density(bool solid) + { + using var world = FluidWorld(8, gravityY: 0f); + world.CreateParticles([Fluid((0.099f, 0f, 0f))]); + if (solid) world.CreateParticles([new Box3DSoaParticleDesc((0.2005f, 0f, 0f), 1f, 0.05f, Box3DSoaPhase.Of(1))]); + world.Step(1f / 60f, 4); + return world.View.ParticleDensity[0]; + } + var alone = Density(false); + var near = Density(true); + var rise = near / alone - 1.0; + var line = $"KERNEL_REACH fluid density {alone:F6} alone, {near:F6} with a 5 cm solid 10.15 cm away: rise {rise:E3}"; + Readings.Add(line); + Assert.True(rise >= KernelReachBound, line); + } + + // Relative rise of the fluid particle's density: shipped 2.530e-3, M2 (cell stays 2 r_max) 0, which counts one unit (1e-6) by + // lodur:ruling:deterministic-bound-zero-reading: bound sqrt(2.530e-3 x 1e-6) = 5.0e-5, separation 50. + private const double KernelReachBound = 5.0e-5; + + // Drift as a fraction of the initial momentum, worst of the three mass ratios: shipped 3.50e-4 (fluid : solid 1 : 30; 1.5e-5 at the other two, + // the float32 floor as Contact_conserves_momentum's), least claimed mutant 1.165e-2 (M1, solid end of pass B not moved, at 30 : 1; M3, each + // end takes the whole correction, reads 0.139 at least): bound sqrt(3.50e-4 x 1.165e-2) = 2.0e-3, separation 33. + // Kinetic energy, equal-mass-class scene only: shipped 1.000000 (no rise at 1e-6), never above initial to the float floor 1e-5 as the contact test. + // At 30 : 1 the density pass does raise it (1.108, pure contact 1.0001): stored constraint violation released against light solids; reported, not claimed. + private const double MomentumBound = 2.0e-3; + private const double EnergyBound = 1e-5; + + [Theory] + [InlineData(0.064f, 0.02f)] // fluid water, solids as the pour + [InlineData(0.002f, 0.06f)] // fluid : solid 1 : 30 + [InlineData(0.06f, 0.002f)] // fluid : solid 30 : 1 + public void Fluid_solid_momentum_zero_g(float fluidMass, float solidMass) + { + // A fluid block thrown into a free sheet and a free rope in zero gravity for 2 s: every pair (fluid and fluid, fluid and solid, solid + // and solid) moves its two ends by equal and opposite momentum, so the total may not drift and the kinetic energy may not rise, + // at any mass ratio. The bound is the float32 floor of the scene, as Contact_conserves_momentum's. + using var world = Collision(fluidMass, solidMass); + var (drift, energy) = Momentum(world, 120); + var line = $"MOMENTUM_FLUID m_f {fluidMass} m_s {solidMass}: drift {drift:E3} of the initial momentum, kinetic energy max/initial {energy:F6}"; + Readings.Add(line); + Assert.True(drift <= MomentumBound, line); + if (fluidMass == 0.064f) Assert.True(energy <= 1 + EnergyBound, line); + } + + [Fact] + public void Fluid_pours_on_a_sheet_and_off_a_rope() + { + var (world, sheet, rope, fluid) = Pour(); + using (world) + { + var touchedSheet = new bool[fluid.Length]; + var touchedRope = new bool[fluid.Length]; + var deep = 0; var minRatio = 9f; + var solids = sheet.Particles.Select(h => (h.Lane, Sheet: true)).Concat(rope.Particles.Select(h => (h.Lane, Sheet: false))).ToArray(); + for (var tick = 0; tick < 240; tick++) + { + world.Step(1f / 60f, PourSub); + var v = world.View; + for (var k = 0; k < fluid.Length; k++) + { + var f = fluid[k].Lane; + foreach (var (s, onSheet) in solids) + { + var reach = v.ParticleRadius[f] + v.ParticleRadius[s]; + var d = Graph.Dist(v, f, s); + if (d < 1.25f * reach) { if (onSheet) touchedSheet[k] = true; else touchedRope[k] = true; } + if (d < 0.5f * reach) deep++; + minRatio = MathF.Min(minRatio, d / reach); + } + } + } + var view = world.View; + var below = fluid.Count(h => view.ParticleY[h.Lane] < -0.2f); + var line = $"POUR touched the sheet {touchedSheet.Count(b => b)} of {fluid.Length}, the rope {touchedRope.Count(b => b)}, below y = -0.2 m at 4 s {below}, within half a contact distance of a solid {deep} (closest {minRatio:F3} of a contact distance)"; + Readings.Add(line); + Assert.True(touchedSheet.Count(b => b) >= 250, line); + Assert.True(touchedRope.Count(b => b) >= 30, line); + Assert.True(below >= 300, line); + Assert.Equal(0, deep); + } + } + + [Fact] + public void Fluid_pushes_a_body() + { + // A fluid block thrown down on a free 1 kg box in zero gravity: the contact and gravity terms are 0, so the box's M dv in a tick is + // the impulse the particles gave it, which the lane reads. Fluid is booked on a body as any particle is. + using var world = FluidWorld(256, gravityY: 0f); + const float mass = 1f; + var box = world.AddBox(2, (0f, 0f, 0f), (0.1f, 0.1f, 0.1f), mass / (8f * 0.1f * 0.1f * 0.1f), friction: 0.3f); + Graph.Block(world, (-0.0375f, 0.13f, -0.0375f), 4, 4, 4, R, FluidMass, FluidPhase, velocity: (0f, -3f, 0f)); + var view = world.View; + var (vx, vy, vz) = (view.VelocityX[box], view.VelocityY[box], view.VelocityZ[box]); + float worst = 0f, peak = 0f; + for (var tick = 0; tick < 120; tick++) + { + world.Step(1f / 60f, 4); + var dx = mass * (view.VelocityX[box] - vx) - view.ParticleImpulseX[box]; + var dy = mass * (view.VelocityY[box] - vy) - view.ParticleImpulseY[box]; + var dz = mass * (view.VelocityZ[box] - vz) - view.ParticleImpulseZ[box]; + worst = MathF.Max(worst, MathF.Max(MathF.Abs(dx), MathF.Max(MathF.Abs(dy), MathF.Abs(dz)))); + peak = MathF.Max(peak, MathF.Abs(view.ParticleImpulseY[box])); + (vx, vy, vz) = (view.VelocityX[box], view.VelocityY[box], view.VelocityZ[box]); + } + var line = $"PUSH peak impulse {peak:F5} N s a tick, worst |M dv - lane| {worst:E3} N s ({worst / peak:P3} of the peak)"; + Readings.Add(line); + Assert.True(peak > 0.01f, line); + Assert.True(worst <= 0.005f * peak, line); + } + + // Drift of the mean nearest-neighbour distance in micrometres: shipped 0 (reads 0.000 at 1e-3, so half a unit, 5e-4), M4 (bilateral C) 1.529e7: + // bound sqrt(5e-4 x 1.529e7) = 87 micrometres by lodur:ruling:deterministic-bound-zero-reading, separation 1.8e5. + private const double ClumpBound = 87.0; + + [Fact] + public void Fluid_does_not_clump() + { + // Particles on a lattice at 3 r spacing are under-dense: a unilateral constraint (C = max(n / n0 - 1, 0)) leaves them where they + // are. A bilateral one pulls them together to rest density. + using var world = FluidWorld(512, gravityY: 0f); + world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f)); + var block = Graph.Block(world, (0f, 0f, 0f), 6, 6, 6, R, FluidMass, FluidPhase, pitch: 3f * R); + double Mean() + { + var v = world.View; + double sum = 0; + foreach (var a in block) + { + var nearest = float.MaxValue; + foreach (var b in block) if (a.Lane != b.Lane) nearest = MathF.Min(nearest, Graph.Dist(v, a.Lane, b.Lane)); + sum += nearest; + } + return sum / block.Length; + } + var before = Mean(); + for (var tick = 0; tick < 60; tick++) world.Step(1f / 60f, 4); + var after = Mean(); + var line = $"CLUMP mean nearest-neighbour distance {before * 1e3:F6} mm before, {after * 1e3:F6} mm after 1 s (pitch {3f * R * 1e3:F4} mm), drift {Math.Abs(after - before) * 1e6:F3} micrometres"; + Readings.Add(line); + Assert.True(Math.Abs(after - before) * 1e6 <= ClumpBound, line); + } + + // Variance ratio, viscosity 0.1 over 0: shipped 0.7799, M5 (XSPH skipped) 1.0000: bound sqrt(0.7799 x 1.0000) = 0.883, separation 1.28. + private const double ShearBound = 0.883; + + [Fact] + public void Fluid_viscosity_damps_shear() + { + // The same block with a shear velocity field (vx by layer) for 0.5 s in zero gravity: XSPH at 0.1 takes the velocity variance + // under the bound, at 0 it stays. + static double Variance(float viscosity) + { + using var world = FluidWorld(512, gravityY: 0f); + world.AddStaticBox(1, (0f, -100f, 0f), (1f, 1f, 1f)); + world.SetMaterial(0, 0.3f, 0, viscosity); + var desc = new Box3DSoaParticleDesc[216]; + for (var k = 0; k < 6; k++) for (var j = 0; j < 6; j++) for (var i = 0; i < 6; i++) + desc[(k * 6 + j) * 6 + i] = new Box3DSoaParticleDesc((2 * R * i, 2 * R * j, 2 * R * k), FluidMass, R, FluidPhase, 0, null, (0.5f * (j - 2.5f), 0f, 0f)); + var made = new Box3DSoaParticleHandle[216]; + world.CreateParticles(desc, made); + for (var tick = 0; tick < 30; tick++) world.Step(1f / 60f, 4); + var v = world.View; + double mean = 0, sq = 0; + foreach (var h in made) { mean += v.ParticleVx[h.Lane]; sq += Sq(v.ParticleVx[h.Lane]); } + mean /= made.Length; + return sq / made.Length - mean * mean; + } + var free = Variance(0f); + var damped = Variance(0.1f); + var line = $"SHEAR velocity variance after 0.5 s: viscosity 0 {free:F5}, viscosity 0.1 {damped:F5} (ratio {damped / free:F4})"; + Readings.Add(line); + Assert.True(damped <= ShearBound * free, line); + } + + // ---- determinism ---------------------------------------------------------------------------------------- + + private static ulong Fnv(ulong h, ReadOnlySpan bytes) + { + foreach (var b in bytes) { h ^= b; h *= 1099511628211ul; } + return h; + } + + private static ulong HashFluid(Box3DSoaView v) + { + var h = 1469598103934665603ul; + void F(ReadOnlySpan lane) => h = Fnv(h, MemoryMarshal.AsBytes(lane)); + F(v.ParticleX); F(v.ParticleY); F(v.ParticleZ); F(v.ParticleVx); F(v.ParticleVy); F(v.ParticleVz); F(v.ParticleDensity); + F(v.DistanceTension); F(v.AttachmentForceX); F(v.AttachmentForceY); F(v.AttachmentForceZ); + F(v.PositionX); F(v.PositionY); F(v.PositionZ); F(v.VelocityX); F(v.VelocityY); F(v.VelocityZ); + F(v.ParticleImpulseX); F(v.ParticleImpulseY); F(v.ParticleImpulseZ); + return h; + } + + private static ulong[] Checkpoints(bool nudge = false) + { + var (world, _, _, _) = Pour(nudge); + using (world) + { + var hashes = new ulong[6]; + for (var c = 0; c < 6; c++) + { + for (var t = 0; t < 40; t++) world.Step(1f / 60f, PourSub); + hashes[c] = HashFluid(world.View); + } + return hashes; + } + } + + // Recorded on this commit's build (gcc 13.2, -ffp-contract=off): the pour scene's particle, density and body lanes at ticks 40, 80, ... 240. + private static readonly ulong[] FluidHashes = [5483896317407431507ul, 5543394749619665441ul, 17137743801444348829ul, 2389985220451369037ul, 13124815529364315574ul, 13300095781041689986ul]; + + [Fact] + public void Fluid_world_is_byte_deterministic() + { + var a = Checkpoints(); + var b = Checkpoints(); + Assert.True(a.AsSpan().SequenceEqual(b), "two runs diverged: " + string.Join(",", a) + " vs " + string.Join(",", b)); + Assert.True(a.Distinct().Count() == 6, "the scene moves"); + Assert.False(a.AsSpan().SequenceEqual(Checkpoints(nudge: true)), "a one-ulp input difference must diverge"); + Assert.True(FluidHashes.AsSpan().SequenceEqual(a), string.Join(",", a.Select(g => g + "ul"))); + } + + [Fact] + public async Task Fluid_world_is_the_same_bytes_on_any_thread_under_load() + { + var serial = Checkpoints(); + var results = Enumerable.Range(0, 8).Select(_ => Task.Factory.StartNew(() => Checkpoints(), 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"); + } } diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs index 1fcdfc4..b6fd52e 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGrabTests.cs @@ -167,10 +167,10 @@ public sealed class Box3DSoaGrabTests [Fact] public void The_managed_side_refuses_a_native_library_of_another_abi_in_either_direction() { - Assert.Equal(10u, Box3DSoaNative.ymir_box3d_soa_get_abi_version()); - Box3DSoaWorld.RequireNativeAbi(10); - Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(9)); // an older native under this managed build - Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(11)); // a newer one + Assert.Equal(11u, Box3DSoaNative.ymir_box3d_soa_get_abi_version()); + Box3DSoaWorld.RequireNativeAbi(11); + Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(10)); // an older native under this managed build + Assert.Throws(() => Box3DSoaWorld.RequireNativeAbi(12)); // a newer one } [Fact] diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs index 4ee775d..6b40e51 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaGraph.cs @@ -72,6 +72,25 @@ internal static class Graph return new Made(p, e, bends); } + /// + /// An x x block of particles on a simple-cubic lattice at spacing + /// 2 (or ), the first particle's centre at , x fastest. No constraint: pass the fluid phase for a liquid. + /// + public static Box3DSoaParticleHandle[] Block( + Box3DSoaWorld world, Pos origin, int nx, int ny, int nz, float radius, float mass, uint phase, uint material = 0, Pos velocity = default, float pitch = 0f) + { + var desc = new Box3DSoaParticleDesc[nx * ny * nz]; + var s = pitch > 0f ? pitch : 2f * radius; + for (var k = 0; k < nz; k++) + for (var j = 0; j < ny; j++) + for (var i = 0; i < nx; i++) + desc[(k * ny + j) * nx + i] = new Box3DSoaParticleDesc( + (origin.X + s * i, origin.Y + s * j, origin.Z + s * k), mass, radius, phase, material, null, velocity); + var p = new Box3DSoaParticleHandle[desc.Length]; + world.CreateParticles(desc, p); + return p; + } + public static float Dist(Box3DSoaView v, int a, int b) => MathF.Sqrt(Sq(v.ParticleX[a] - v.ParticleX[b]) + Sq(v.ParticleY[a] - v.ParticleY[b]) + Sq(v.ParticleZ[a] - v.ParticleZ[b])); diff --git a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs index eabf319..9846529 100644 --- a/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs +++ b/tests/Ymir.Box3D.Soa.Tests/Box3DSoaParticleTests.cs @@ -1099,6 +1099,12 @@ public sealed class Box3DSoaParticleSourceTests Assert.True(Count(File.ReadAllText(f), retired) == 0, f); Assert.Equal(0, Count(c + h, @"PARTICLE_" + @"PARTICLE|find_range|mark_slots|stable_id_taken|rest_pos|add_struct")); Assert.Equal(0, Count(c, @"1\.0f / \(float\)contacts")); + // no fluid path runs in a world with no live fluid: both passes sit behind the counter + var substep = StripComments(Body(c, "void ymir_particles_substep(")); + Assert.Equal(1, Count(substep, @"if \(p->live_fluid > 0\)\s*\{\s*fluid_density\(p\);")); + Assert.Equal(1, Count(substep, @"if \(p->live_fluid > 0\)\s*\{\s*fluid_viscosity\(p\);")); + // fluid has one writer of live_fluid pair: the two commands + Assert.Equal(0, Count(StripComments(c.Replace(Body(c, "int32_t ymir_particles_create_particles("), "").Replace(Body(c, "int32_t ymir_particles_destroy_particles("), "")), @"live_fluid\s*(\+\+|--|[-+]?=[^=])")); } [Fact]