Liquid sensors: spheres fixed in bodies read the liquid volume inside them each step (ABI 15)

create_sensors, remove(SENSOR), free_slots(SENSOR) and sensor lanes; ymir_particles_end writes sensor_liquid_volume before its no-live-particle return. A sensor moves nothing; a world with none steps byte for byte as ABI 14.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-25 07:41:18 +01:00
commit 881a209e9a
8 changed files with 514 additions and 23 deletions

View file

@ -8,12 +8,12 @@ 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 14) so the Aetheria session's contract is untouched.
separate native object (`ymir_box3d_soa.c`, ABI 15) so the Aetheria session's contract is untouched.
## Contract
- 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 /
- Native (ABI 15): `ymir_box3d_soa_create(capacity, joint_capacity, gravity, fact_capacity, hit_threshold, particle_capacities*) /
create_particles / destroy_particles / create_distances / create_bends / create_sensors / 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,
so lane pointers never move.
@ -222,6 +222,14 @@ separate native object (`ymir_box3d_soa.c`, ABI 14) so the Aetheria session's co
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_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. 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 reading is a sensor: the step
writes it and no pass reads it 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.
- 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

View file

@ -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 14u
#define YMIR_SOA_ABI_VERSION 15u
// 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
@ -139,6 +139,7 @@ typedef struct ymir_box3d_soa_view
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;
@ -295,6 +296,18 @@ typedef struct ymir_box3d_soa_view
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: a sensor, the
// step writes it and nothing reads it 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 uint32_t* sensor_live;
const uint32_t* sensor_generation;
const uint64_t* sensor_removed_at;
} ymir_box3d_soa_view;
// A begin or end of touch between two bodies: their lane indices and the shapes' stable ids.
@ -577,7 +590,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_create(
!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->materials < 0 || particle_capacities->fluid < 0 || particle_capacities->sensors < 0)))
{
return YMIR_SOA_INVALID_ARGUMENT;
}
@ -1368,7 +1381,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_cast_ray_closest(
// 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.
// 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)
@ -1380,6 +1393,7 @@ YMIR_EXPORT uint32_t YMIR_CALL ymir_box3d_soa_get_particle_desc_size(uint32_t wh
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;
}
}
@ -1462,7 +1476,17 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_settle(ymir_box3d_soa_world* world,
return ymir_particles_settle(world->particles, n, h, world->step_count, out);
}
// Lanes a new particle (0), distance (1), bend (2), attachment (3) or wet patch (4) could take right now.
// 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;
}
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);
@ -1499,6 +1523,7 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world
.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,
@ -1627,6 +1652,15 @@ YMIR_EXPORT int32_t YMIR_CALL ymir_box3d_soa_get_view(const ymir_box3d_soa_world
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_live = pt->sensor_live;
view->sensor_generation = pt->sensor_generation;
view->sensor_removed_at = pt->sensor_removed_at;
}
return YMIR_SOA_OK;
}

View file

@ -90,7 +90,7 @@ 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;
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) \
@ -114,6 +114,8 @@ static size_t layout(ymir_particles* p, unsigned char* base)
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_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);
@ -150,7 +152,7 @@ static size_t layout(ymir_particles* p, unsigned char* base)
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 || body_capacity < 0)
c->materials < 0 || c->fluid < 0 || c->wets < 0 || c->sensors < 0 || body_capacity < 0)
{
return NULL;
}
@ -168,6 +170,7 @@ ymir_particles* ymir_particles_create(const ymir_particle_capacities* c, int32_t
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)
{
@ -186,6 +189,10 @@ ymir_particles* ymir_particles_create(const ymir_particle_capacities* c, int32_t
{
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
@ -267,6 +274,8 @@ int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, ui
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;
}
@ -337,6 +346,21 @@ 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] = 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;
@ -1153,7 +1177,8 @@ int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d,
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_DISTANCE && type != YMIR_LANES_BEND && type != YMIR_LANES_ATTACHMENT && type != YMIR_LANES_WET &&
type != YMIR_LANES_SENSOR))
{
return YMIR_PARTICLES_INVALID_ARGUMENT;
}
@ -1162,12 +1187,24 @@ int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const
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;
}
}
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)
@ -2322,9 +2359,48 @@ void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, floa
}
}
// 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;
if (p->live_fluid > 0 && p->sensor_body[s] < p->body_count)
{
const ymir_particle_proxy* b = p->proxies + p->sensor_body[s];
v3 c = 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]}));
float r2 = p->sensor_radius[s] * p->sensor_radius[s];
for (int32_t i = 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;
}
}
void ymir_particles_end(ymir_particles* p, int32_t substeps)
{
if (p == NULL || p->live_particles == 0)
if (p == NULL)
{
return;
}
read_sensors(p);
if (p->live_particles == 0)
{
return;
}
@ -2496,3 +2572,44 @@ int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h
rederive_wet(p);
return ymir_particles_destroy_particles(p, n, h, step_count);
}
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] = 0.0f; // the first step's end reads it
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;
}

View file

@ -50,7 +50,8 @@ enum
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_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
@ -82,7 +83,7 @@ typedef struct ymir_handle
typedef struct ymir_particle_capacities
{
int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets; // fluid: the most live particles with the FLUID phase; wets: the most wet patches
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
@ -128,6 +129,14 @@ typedef struct ymir_attachment_desc
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
@ -166,6 +175,7 @@ typedef struct ymir_particles
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;
@ -192,6 +202,13 @@ typedef struct ymir_particles
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 is written by end alone (m^3: the sum of (2 r)^3 over the live fluid particles whose centre is inside, at the step's end)
int32_t* sensor_body;
float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_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;
@ -258,6 +275,9 @@ int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const
// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no patch to merge into, before any
// change. `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);
// 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);
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);

View file

@ -85,7 +85,9 @@ public enum Box3DSoaConstraintType : uint
Bend = 2,
Attachment = 3,
/// <summary>A wet patch: settled liquid on a body or a solid particle.</summary>
Wet = 4
Wet = 4,
/// <summary>A liquid sensor: a sphere fixed in a body that reads the liquid volume inside it each step.</summary>
Sensor = 5
}
/// <summary>A constraint's identity: its type, lane and the slot's generation when it was made.</summary>
@ -111,7 +113,7 @@ public static class Box3DSoaPhase
/// <summary>Capacities of the particle state; <c>null</c> or all zero is a world without particles (ABI 8 behaviour).</summary>
[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);
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);
/// <summary>Native layout of <c>ymir_particle_desc</c>: a particle to create. Mass kg (0 = immovable); rest is its place in the rest pose.</summary>
[StructLayout(LayoutKind.Sequential)]
@ -178,6 +180,15 @@ internal struct Box3DSoaAttachmentDesc
public uint Reserved;
}
/// <summary>Native layout of <c>ymir_sensor_desc</c>: a sphere of <c>Radius</c> m (&gt; 0) centred on <c>Point</c> in the frame of body lane <c>Body</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
internal struct Box3DSoaSensorDesc
{
public int Body;
public float PointX, PointY, PointZ;
public float Radius;
}
/// <summary>Native layout of <c>ymir_material_desc</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
internal struct Box3DSoaMaterialDesc
@ -236,6 +247,7 @@ internal unsafe struct Box3DSoaViewNative
public int TetherCapacity;
public int MaterialCapacity;
public int WetCount;
public int SensorCount;
public ulong* StableId;
public uint* Kind;
public int* Parent;
@ -361,6 +373,15 @@ internal unsafe struct Box3DSoaViewNative
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 uint* SensorLive;
public uint* SensorGeneration;
public ulong* SensorRemovedAt;
}
/// <summary>Native layout of <c>ymir_box3d_soa_facts</c>: counts, dropped counters, then three pointers.</summary>
@ -548,6 +569,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_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);
@ -787,6 +812,21 @@ public readonly unsafe struct Box3DSoaView
/// <summary>The wet friction of each material (stored for the friction cut; nothing here reads it).</summary>
public ReadOnlySpan<float> MaterialWetFriction => Lane(_v.MaterialWetFriction, MaterialCapacity);
/// <summary>Liquid sensor lanes (see <see cref="Box3DSoaWorld.CreateSensors"/>), indexed up to <see cref="SensorCount"/>. A free lane reads live 0, body -1 and 0 elsewhere (generation and removed-at kept).</summary>
public int SensorCount => _v.SensorCount;
/// <summary>The body lane a sensor is fixed in; its point is in that body's frame.</summary>
public ReadOnlySpan<int> SensorBody => Lane(_v.SensorBody, SensorCount);
public ReadOnlySpan<float> SensorX => Lane(_v.SensorX, SensorCount);
public ReadOnlySpan<float> SensorY => Lane(_v.SensorY, SensorCount);
public ReadOnlySpan<float> SensorZ => Lane(_v.SensorZ, SensorCount);
/// <summary>m</summary>
public ReadOnlySpan<float> SensorRadius => Lane(_v.SensorRadius, SensorCount);
/// <summary>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.</summary>
public ReadOnlySpan<float> SensorLiquidVolume => Lane(_v.SensorLiquidVolume, SensorCount);
public ReadOnlySpan<uint> SensorLive => Lane(_v.SensorLive, SensorCount);
public ReadOnlySpan<uint> SensorGeneration => Lane(_v.SensorGeneration, SensorCount);
public ReadOnlySpan<ulong> SensorRemovedAt => Lane(_v.SensorRemovedAt, SensorCount);
/// <summary>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.</summary>
public ReadOnlySpan<float> ParticleImpulseX => Lane(_v.ParticleImpulseX, Count);
public ReadOnlySpan<float> ParticleImpulseY => Lane(_v.ParticleImpulseY, Count);
@ -804,7 +844,7 @@ public readonly unsafe struct Box3DSoaView
/// </summary>
public sealed class Box3DSoaWorld : IDisposable
{
private const uint ExpectedAbi = 14;
private const uint ExpectedAbi = 15;
private nint _handle;
/// <summary>
@ -830,7 +870,8 @@ public sealed class Box3DSoaWorld : IDisposable
Size(3) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaAttachmentDesc>() ||
Size(4) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaMaterialDesc>() ||
Size(5) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaParticleCapacities>() ||
Size(6) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaParticleHandle>())
Size(6) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaParticleHandle>() ||
Size(7) != (uint)System.Runtime.CompilerServices.Unsafe.SizeOf<Box3DSoaSensorDesc>())
{
throw new InvalidOperationException("The native Ymir Box3D SoA ABI does not match this build.");
}
@ -1175,6 +1216,26 @@ public sealed class Box3DSoaWorld : IDisposable
patches[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Wet, native[i].Lane, native[i].Generation);
}
/// <summary>
/// Creates liquid sensors in the lowest free lanes: each is a sphere of <c>radius</c> m (&gt; 0) centred on <c>point</c> in the frame of body lane <c>body</c>,
/// and reads <see cref="Box3DSoaView.SensorLiquidVolume"/> at the end of every step. Refuses the whole batch, changing nothing, for a body that does not exist,
/// a radius that is not finite and positive, a non-finite point, or too few free lanes. Remove one with <see cref="Remove(Box3DSoaConstraintHandle)"/>.
/// </summary>
public unsafe void CreateSensors(ReadOnlySpan<(int Body, (float X, float Y, float Z) Point, float Radius)> sensors, Span<Box3DSoaConstraintHandle> handles = default)
{
ObjectDisposedException.ThrowIf(_handle == 0, this);
if (!handles.IsEmpty && handles.Length < sensors.Length) throw new ArgumentException("One handle per sensor.", nameof(handles));
var desc = new Box3DSoaSensorDesc[sensors.Length];
for (var i = 0; i < desc.Length; i++)
desc[i] = new Box3DSoaSensorDesc { Body = sensors[i].Body, PointX = sensors[i].Point.X, PointY = sensors[i].Point.Y, PointZ = sensors[i].Point.Z, Radius = sensors[i].Radius };
var native = new Box3DSoaParticleHandle[sensors.Length];
fixed (Box3DSoaSensorDesc* d = desc)
fixed (Box3DSoaParticleHandle* o = native)
Check(Box3DSoaNative.ymir_box3d_soa_create_sensors(_handle, desc.Length, d, handles.IsEmpty ? null : o));
for (var i = 0; i < handles.Length && i < native.Length; i++)
handles[i] = new Box3DSoaConstraintHandle(Box3DSoaConstraintType.Sensor, native[i].Lane, native[i].Generation);
}
/// <summary>Removes one constraint.</summary>
public void Remove(Box3DSoaConstraintHandle constraint) => Remove([constraint]);
@ -1194,6 +1255,7 @@ public sealed class Box3DSoaWorld : IDisposable
public int FreeBendSlots => FreeSlots(Box3DSoaConstraintType.Bend);
public int FreeAttachmentSlots => FreeSlots(Box3DSoaConstraintType.Attachment);
public int FreeWetSlots => FreeSlots(Box3DSoaConstraintType.Wet);
public int FreeSensorSlots => FreeSlots(Box3DSoaConstraintType.Sensor);
private int FreeSlots(Box3DSoaConstraintType type)
{

View file

@ -35,8 +35,8 @@ public sealed partial 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, int wets = 0) =>
new(bodies, gravityY: gravityY, particles: new Box3DSoaParticleCapacities(particles, 16, 16, 16, 64, materials, particles, wets));
private static Box3DSoaWorld FluidWorld(int particles, int bodies = 8, float gravityY = -10f, int materials = 2, int wets = 0, int sensors = 0) =>
new(bodies, gravityY: gravityY, particles: new Box3DSoaParticleCapacities(particles, 16, 16, 16, 64, materials, particles, wets, sensors));
/// <summary>A floor and four walls: an open well of interior half-width <paramref name="half"/> centred on the y axis.</summary>
private static void Well(Box3DSoaWorld world, float half)

View file

@ -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(14u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
Box3DSoaWorld.RequireNativeAbi(14);
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(13)); // an older native under this managed build
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(15)); // a newer one
Assert.Equal(15u, Box3DSoaNative.ymir_box3d_soa_get_abi_version());
Box3DSoaWorld.RequireNativeAbi(15);
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(14)); // an older native under this managed build
Assert.Throws<InvalidOperationException>(() => Box3DSoaWorld.RequireNativeAbi(16)); // a newer one
}
[Fact]

View file

@ -0,0 +1,250 @@
using Ymir.Box3D;
namespace Ymir.Box3D.Soa.Tests;
using Pos = (float X, float Y, float Z);
/// <summary>Liquid sensors: docs/soa-world.md, Sensors. A sphere fixed in a body reads the liquid volume inside it at the end of every step; nothing reads it back.</summary>
public sealed partial class Box3DSoaFluidTests
{
/// <summary>The volume the sensor must read: (2 r)^3 summed in lane order over the live fluid lanes whose centre is within <paramref name="radius"/> of <paramref name="centre"/>, the count, and the closest any centre comes to the sphere's surface.</summary>
private static (float Volume, int Count, double Margin) Inside(Box3DSoaView v, Pos centre, float radius)
{
var volume = 0f;
var count = 0;
var margin = double.MaxValue;
for (var i = 0; i < v.ParticleCount; i++)
{
if (v.ParticleLive[i] == 0 || (v.ParticlePhase[i] & Box3DSoaPhase.Fluid) == 0) continue;
double dx = v.ParticleX[i] - centre.X, dy = v.ParticleY[i] - centre.Y, dz = v.ParticleZ[i] - centre.Z;
var d = Math.Sqrt(dx * dx + dy * dy + dz * dz);
margin = Math.Min(margin, Math.Abs(d - radius));
if (d <= radius)
{
var side = 2f * v.ParticleRadius[i];
volume += side * side * side;
count++;
}
}
return (volume, count, margin);
}
/// <summary>A well of half-width 0.15 (floor is body lane 0, top at y 0, frame origin at y -0.5) with a 6 x 6 x 6 block of water in it.</summary>
private static Box3DSoaWorld Pool(int sensors, int bodies = 8)
{
var world = FluidWorld(256, bodies, gravityY: -9.81f, sensors: sensors);
Well(world, 0.15f);
Graph.Block(world, (-0.0625f, 0.0125f, -0.0625f), 6, 6, 6, R, FluidMass, FluidPhase);
return world;
}
private static void Run(Box3DSoaWorld world, int ticks)
{
for (var t = 0; t < ticks; t++) world.Step(Dt, Sub);
}
[Fact]
public void Sensor_reads_the_liquid_inside()
{
using var world = Pool(sensors: 4);
var handles = new Box3DSoaConstraintHandle[3];
// The floor's frame origin is (0, -0.5, 0): a body-frame y of 0.5 + h is world height h over the floor.
world.CreateSensors([(0, (0f, 0.54f, 0f), 0.06f), (0, (0f, 1.5f, 0f), 0.1f), (0, (0f, 0.55f, 0f), 1f)], handles);
Run(world, 90);
var v = world.View;
var part = Inside(v, (0f, 0.04f, 0f), 0.06f);
var above = Inside(v, (0f, 1f, 0f), 0.1f);
var all = Inside(v, (0f, 0.05f, 0f), 1f);
Assert.True(part.Count > 0 && part.Count < all.Count, $"the scene must split the pool: {part.Count} of {all.Count}");
Assert.True(part.Margin > 1e-4 && all.Margin > 1e-4, $"a centre within 0.1 mm of a sensor's surface: {part.Margin} {all.Margin}");
Assert.Equal(216, all.Count);
Assert.Equal(part.Volume, v.SensorLiquidVolume[handles[0]]);
Assert.Equal(0f, above.Volume);
Assert.Equal(0f, v.SensorLiquidVolume[handles[1]]);
Assert.Equal(all.Volume, v.SensorLiquidVolume[handles[2]]);
Assert.Equal(3, v.SensorCount);
Readings.Add($"SENSOR pool 216 drops: partial sensor {part.Count} drops = {part.Volume:E4} m^3, all {all.Count} = {all.Volume:E4} m^3, margin {part.Margin:E2} m");
}
[Fact]
public void Sensor_on_a_dunked_and_lifted_body_reads_up_then_0()
{
using var world = Pool(sensors: 2);
var anchor = world.AddAnchor(9, (0f, 0.6f, 0f));
var handle = new Box3DSoaConstraintHandle[1];
world.CreateSensors([(anchor, (0.02f, 0f, 0f), 0.05f)], handle);
Run(world, 60);
var v = world.View;
Assert.Equal(0f, v.SensorLiquidVolume[handle[0]]);
var peak = 0f;
var reads = new List<float>();
for (var t = 0; t < 40; t++)
{
var y = t < 20 ? 0.6f - 0.03f * (t + 1) : 0.03f * (t - 19); // down to y 0, then back up to 0.6
world.SetAnchorTarget(anchor, (0f, y, 0f), default, Dt);
world.Step(Dt, Sub);
v = world.View;
var want = Inside(v, (v.PositionX[anchor] + 0.02f, v.PositionY[anchor], v.PositionZ[anchor]), 0.05f);
Assert.True(want.Margin > 1e-4, $"tick {t}: a centre within 0.1 mm of the surface ({want.Margin})");
Assert.Equal(want.Volume, v.SensorLiquidVolume[handle[0]]);
reads.Add(v.SensorLiquidVolume[handle[0]]);
peak = MathF.Max(peak, reads[^1]);
}
Assert.True(peak >= 3f * DropVolume, $"dunked: peak {peak}");
Assert.True(reads.Take(3).All(r => r == 0f), "above the surface it reads 0 on the way down");
Assert.Equal(0f, reads[^1]);
Readings.Add($"SENSOR dunk and lift: peak {peak:E4} m^3 ({peak / DropVolume:F1} drops), first {reads[0]}, last {reads[^1]}");
}
[Fact]
public void Sensor_follows_its_body_frame_and_the_pose_the_step_ends_in()
{
// Zero gravity, drops 0.5 m apart so none moves. The anchor is turned a quarter about z, so its body-frame point (0.3, 0, 0) lies at world (x, y + 0.3, z) over it,
// and it runs 0.5 m a tick along x: at the end of tick s it is over the drop at x 0.5 s. Decoys sit where an unrotated frame (or the pose a substep earlier) would look.
using var world = FluidWorld(32, 4, gravityY: 0f, sensors: 2);
var descs = new List<Box3DSoaParticleDesc>();
for (var k = 0; k < 8; k++)
{
descs.Add(Fluid((0.5f * k, 0.3f, 0f), FluidMass, R));
descs.Add(Fluid((0.5f * k + 0.3f, 0f, 0f), FluidMass, R));
}
world.CreateParticles(descs.ToArray());
var q = (0f, 0f, 0.70710678f, 0.70710678f);
var anchor = world.AddAnchor(9, (0f, 0f, 0f), q);
var handle = new Box3DSoaConstraintHandle[1];
world.CreateSensors([(anchor, (0.3f, 0f, 0f), 0.2f)], handle);
var reads = new float[10];
for (var s = 1; s <= 9; s++)
{
world.SetAnchorTarget(anchor, (0.5f * s, 0f, 0f), q, Dt);
world.Step(Dt, Sub);
reads[s] = world.View.SensorLiquidVolume[handle[0]];
}
for (var s = 1; s <= 7; s++) Assert.Equal(DropVolume, reads[s]);
Assert.Equal(0f, reads[8]);
Assert.Equal(0f, reads[9]);
}
[Fact]
public void Sensor_reads_0_once_every_drop_is_gone()
{
// The step's end returns early with no live particle; the sensor pass must run before that, or the sensor keeps its last reading.
foreach (var how in new[] { "destroyed", "destroyed with a solid left", "settled" })
{
using var world = FluidWorld(64, gravityY: -9.81f, wets: 8, sensors: 2);
world.AddStaticBox(1, (0f, -0.5f, 0f), (2f, 0.5f, 2f), friction: 0.3f);
var drops = Graph.Block(world, (0f, 0.0125f, 0f), 3, 1, 3, R, FluidMass, FluidPhase);
if (how == "destroyed with a solid left") world.CreateParticles([new Box3DSoaParticleDesc((1f, 1f, 1f), 1f, R)]);
var handle = new Box3DSoaConstraintHandle[1];
world.CreateSensors([(0, (0f, 0.5f, 0f), 0.5f)], handle);
Run(world, 20);
var nine = 0f;
for (var k = 0; k < 9; k++) nine += DropVolume; // the lane-order float sum the native pass makes
Assert.Equal(nine, world.View.SensorLiquidVolume[handle[0]]);
if (how == "settled") world.Settle(drops);
else world.DestroyParticles(drops);
world.Step(Dt, Sub);
Assert.Equal(0f, world.View.SensorLiquidVolume[handle[0]]);
Assert.Equal(how == "destroyed with a solid left" ? 1 : 0, world.View.ParticleLive.ToArray().Count(l => l != 0));
}
}
private static byte[] SensorBytes(Box3DSoaView v)
{
var o = new MemoryStream();
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
B(v.SensorBody); B(v.SensorX); B(v.SensorY); B(v.SensorZ); B(v.SensorRadius); B(v.SensorLiquidVolume); B(v.SensorLive); B(v.SensorGeneration); B(v.SensorRemovedAt);
o.Write(BitConverter.GetBytes(v.SensorCount));
return o.ToArray();
}
[Fact]
public void Sensor_refusals_and_reuse()
{
using var world = FluidWorld(16, 3, gravityY: 0f, sensors: 3);
world.AddStaticBox(1, (0f, 0f, 0f), (1f, 1f, 1f));
world.AddAnchor(2, (0f, 3f, 0f));
var before = SensorBytes(world.View);
var bad = new (int Body, Pos Point, float Radius)[]
{
(-1, (0f, 0f, 0f), 0.1f), (2, (0f, 0f, 0f), 0.1f), (0, (0f, 0f, 0f), 0f), (0, (0f, 0f, 0f), -0.1f), (0, (0f, 0f, 0f), float.NaN),
(0, (0f, 0f, 0f), float.PositiveInfinity), (0, (float.NaN, 0f, 0f), 0.1f), (0, (0f, float.PositiveInfinity, 0f), 0.1f),
};
foreach (var b in bad)
{
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(0, (0f, 0f, 0f), 0.1f), b]));
Assert.True(before.AsSpan().SequenceEqual(SensorBytes(world.View)), "a refused batch changed a lane");
Assert.Equal(3, world.FreeSensorSlots);
}
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(0, default, 0.1f), (0, default, 0.1f), (0, default, 0.1f), (0, default, 0.1f)]));
Assert.True(before.AsSpan().SequenceEqual(SensorBytes(world.View)), "a batch past the capacity changed a lane");
var h = new Box3DSoaConstraintHandle[3];
world.CreateSensors([(0, (0.1f, 0.2f, 0.3f), 0.4f), (1, (0f, 0f, 0f), 0.5f), (0, (1f, 1f, 1f), 0.6f)], h);
Assert.Equal([0, 1, 2], h.Select(x => x.Lane));
Assert.All(h, x => Assert.Equal(Box3DSoaConstraintType.Sensor, x.Type));
var view = world.View;
Assert.Equal(0, world.FreeSensorSlots);
Assert.Equal([0, 1, 0], view.SensorBody.ToArray());
Assert.Equal(0.2f, view.SensorY[0]);
Assert.Equal(0.5f, view.SensorRadius[1]);
// Remove: a tombstone reading 0, its lane back after a step, the lowest first, the old handle refused.
world.Remove([h[0], h[2]]);
view = world.View;
Assert.Equal([0u, 1u, 0u], view.SensorLive.ToArray());
Assert.Equal([-1, 1, -1], view.SensorBody.ToArray());
Assert.Equal(0f, view.SensorRadius[0]);
Assert.Equal(0, world.FreeSensorSlots);
Assert.Throws<InvalidOperationException>(() => world.Remove(h[0]));
Assert.Throws<InvalidOperationException>(() => world.CreateSensors([(0, default, 0.1f)]));
world.Step(Dt, Sub);
Assert.Equal(2, world.FreeSensorSlots);
var again = new Box3DSoaConstraintHandle[2];
world.CreateSensors([(1, (0f, 0f, 0f), 0.7f), (0, (0f, 0f, 0f), 0.8f)], again);
Assert.Equal([0, 2], again.Select(x => x.Lane));
Assert.Equal([1u, 1u], again.Select(x => x.Generation));
Assert.Throws<InvalidOperationException>(() => world.Remove(h[0])); // the old occupant's handle
}
[Fact]
public void Sensors_move_nothing()
{
// The same pool with and without four sensors steps to the same bytes in every other lane.
static byte[] Bytes(bool sensors)
{
using var world = Pool(sensors ? 4 : 0);
if (sensors) world.CreateSensors([(0, (0f, 0.54f, 0f), 0.06f), (0, (0.06f, 0.55f, 0f), 0.07f), (0, (0f, 0.6f, 0f), 0.2f), (0, (0f, 1.5f, 0f), 0.1f)]);
Run(world, 120);
var v = world.View;
var o = new MemoryStream();
void B<T>(ReadOnlySpan<T> lane) where T : unmanaged => o.Write(System.Runtime.InteropServices.MemoryMarshal.AsBytes(lane));
B(v.ParticleX); B(v.ParticleY); B(v.ParticleZ); B(v.ParticleVx); B(v.ParticleVy); B(v.ParticleVz); B(v.ParticleDensity); B(v.SupportBody); B(v.SupportParticle);
B(v.PositionX); B(v.PositionY); B(v.PositionZ); B(v.ParticleImpulseX); B(v.ParticleImpulseY); B(v.ParticleImpulseZ); B(v.ParticleLive); B(v.ParticleGeneration);
return o.ToArray();
}
Assert.True(Bytes(true).AsSpan().SequenceEqual(Bytes(false)), "a sensor moved something");
}
[Fact]
public void Remove_sensor_never_reaches_the_topology_derivation_and_Ymir_names_no_organ()
{
var source = NativeSource("ymir_particles.c").Replace("\r\n", "\n");
var at = source.IndexOf("if (type == YMIR_LANES_SENSOR)", StringComparison.Ordinal);
Assert.True(at > 0);
var branch = source.Substring(at, source.IndexOf("return YMIR_PARTICLES_OK;", at, StringComparison.Ordinal) - at);
branch = System.Text.RegularExpressions.Regex.Replace(branch, "//[^\n]*", "");
Assert.DoesNotContain("rederive_", branch);
Assert.DoesNotContain("TOPO_", branch);
// Ymir exposes a volume; what a head or a lung does with it is the caller's.
var organ = new System.Text.RegularExpressions.Regex("airway|lung|throat", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
for (var d = new DirectoryInfo(AppContext.BaseDirectory); d is not null; d = d.Parent)
{
var native = Path.Combine(d.FullName, "native", "Ymir.Box3D");
var src = Path.Combine(d.FullName, "src", "Ymir.Box3D");
if (!Directory.Exists(native) || !Directory.Exists(src)) continue;
foreach (var file in Directory.EnumerateFiles(native, "*.c").Concat(Directory.EnumerateFiles(native, "*.h")).Concat(Directory.EnumerateFiles(src, "*.cs")))
Assert.False(organ.IsMatch(File.ReadAllText(file)), file + " names an organ");
return;
}
throw new DirectoryNotFoundException("repo root");
}
}